ceulen 0.5.1 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (367) hide show
  1. package/CHANGELOG.md +365 -12
  2. package/README.md +87 -91
  3. package/extensions/lib/advisor-marker.ts +33 -0
  4. package/extensions/lib/panel.ts +25 -2
  5. package/extensions/lib/rate.ts +24 -0
  6. package/extensions/lib/registry.test.ts +67 -0
  7. package/extensions/lib/registry.ts +104 -8
  8. package/extensions/lib/tools.ts +47 -0
  9. package/extensions/lib/usage-store.ts +33 -0
  10. package/extensions/modules/advisor/commands/advisor.ts +244 -0
  11. package/extensions/modules/advisor/configPanel.ts +194 -0
  12. package/extensions/modules/advisor/index.ts +235 -0
  13. package/extensions/modules/advisor/lib/config.ts +248 -0
  14. package/extensions/modules/advisor/lib/emission-guard.ts +153 -0
  15. package/extensions/modules/advisor/lib/isolated-model.ts +160 -0
  16. package/extensions/modules/advisor/lib/model-picker.ts +47 -0
  17. package/extensions/modules/advisor/lib/watcher.ts +288 -0
  18. package/extensions/modules/advisor/test/compliance.test.ts +125 -0
  19. package/extensions/modules/advisor/test/config.test.ts +202 -0
  20. package/extensions/modules/advisor/test/configPanel.test.ts +223 -0
  21. package/extensions/modules/advisor/test/emission-guard.test.ts +201 -0
  22. package/extensions/modules/advisor/test/isolated-model.test.ts +311 -0
  23. package/extensions/modules/advisor/test/model-picker.test.ts +32 -0
  24. package/extensions/modules/advisor/test/module.test.ts +649 -0
  25. package/extensions/modules/advisor/test/watcher.test.ts +478 -0
  26. package/extensions/modules/classifier/configPanel.ts +104 -0
  27. package/extensions/modules/classifier/index.ts +297 -0
  28. package/extensions/modules/classifier/lib/settings.ts +95 -0
  29. package/extensions/modules/classifier/test/classifier.test.ts +475 -0
  30. package/extensions/modules/composer/index.ts +152 -3
  31. package/extensions/modules/composer/lib/footer.ts +119 -0
  32. package/extensions/modules/composer/lib/shapes.ts +265 -26
  33. package/extensions/modules/composer/test/editor.test.ts +1 -1
  34. package/extensions/modules/composer/test/footer.test.ts +96 -0
  35. package/extensions/modules/composer/test/module.test.ts +113 -11
  36. package/extensions/modules/composer/test/screen.test.ts +29 -1
  37. package/extensions/modules/composer/test/shapes.test.ts +224 -8
  38. package/extensions/modules/config/defaultTools.ts +96 -0
  39. package/extensions/modules/config/index.ts +147 -7
  40. package/extensions/modules/config/piSettings.ts +254 -69
  41. package/extensions/modules/config/test/defaultTools.test.ts +122 -0
  42. package/extensions/modules/config/test/menu.test.ts +64 -0
  43. package/extensions/modules/config/test/panel.test.ts +38 -23
  44. package/extensions/modules/config/test/piSettings.test.ts +130 -3
  45. package/extensions/modules/config/test/renderTools.test.ts +71 -0
  46. package/extensions/modules/config/test/tools.test.ts +146 -0
  47. package/extensions/modules/fff/index.ts +2094 -0
  48. package/extensions/modules/fff/lib/query.ts +129 -0
  49. package/extensions/modules/fff/test/index.test.ts +607 -0
  50. package/extensions/modules/fff/test/query.test.ts +71 -0
  51. package/extensions/modules/munin/configPanel.ts +108 -0
  52. package/extensions/modules/munin/index.ts +641 -0
  53. package/extensions/modules/munin/lib/helpers.ts +471 -0
  54. package/extensions/modules/munin/lib/retry.ts +20 -0
  55. package/extensions/modules/munin/lib/sdk.ts +218 -0
  56. package/extensions/modules/munin/test/config.test.ts +168 -0
  57. package/extensions/modules/munin/test/configPanel.test.ts +186 -0
  58. package/extensions/modules/munin/test/extension.test.ts +224 -0
  59. package/extensions/modules/munin/test/helpers.test.ts +523 -0
  60. package/extensions/modules/munin/test/retry.test.ts +145 -0
  61. package/extensions/modules/munin/test/stale-protocol.test.ts +554 -0
  62. package/extensions/modules/plan/configPanel.ts +152 -0
  63. package/extensions/modules/plan/index.ts +917 -0
  64. package/extensions/modules/plan/lib/plan-tools.ts +72 -0
  65. package/extensions/modules/plan/lib/prompt.ts +65 -0
  66. package/extensions/modules/plan/lib/settings.ts +166 -0
  67. package/extensions/modules/plan/lib/shell-gate.ts +200 -0
  68. package/extensions/modules/plan/test/configPanel.test.ts +96 -0
  69. package/extensions/modules/plan/test/harness.ts +133 -0
  70. package/extensions/modules/plan/test/module.test.ts +305 -0
  71. package/extensions/modules/plan/test/settings.test.ts +114 -0
  72. package/extensions/modules/plan/test/shell-gate.test.ts +103 -0
  73. package/extensions/modules/ponytail/index.ts +23 -73
  74. package/extensions/modules/ponytail/lib/config.ts +1 -6
  75. package/extensions/modules/ponytail/test/extension.test.ts +1 -85
  76. package/extensions/modules/repair/configPanel.ts +96 -0
  77. package/extensions/modules/repair/index.ts +414 -0
  78. package/extensions/modules/repair/lib/auto-bg.ts +333 -0
  79. package/extensions/modules/repair/lib/edit-repair.ts +155 -0
  80. package/extensions/modules/repair/lib/editor.ts +251 -0
  81. package/extensions/modules/repair/lib/guards.ts +34 -0
  82. package/extensions/modules/repair/lib/input-repair.ts +324 -0
  83. package/extensions/modules/repair/lib/patch.ts +481 -0
  84. package/extensions/modules/repair/lib/settings.ts +114 -0
  85. package/extensions/modules/repair/test/auto-bg.test.ts +405 -0
  86. package/extensions/modules/repair/test/edit-repair.test.ts +224 -0
  87. package/extensions/modules/repair/test/editor.test.ts +141 -0
  88. package/extensions/modules/repair/test/guards.test.ts +64 -0
  89. package/extensions/modules/repair/test/input-repair.test.ts +231 -0
  90. package/extensions/modules/repair/test/patch.test.ts +563 -0
  91. package/extensions/modules/repair/test/settings.test.ts +167 -0
  92. package/extensions/modules/repair/test/wrapper.test.ts +210 -0
  93. package/extensions/modules/router/commands/commands.ts +4 -0
  94. package/extensions/modules/router/configPanel.ts +24 -10
  95. package/extensions/modules/router/lib/client.ts +63 -0
  96. package/extensions/modules/router/lib/provider.ts +34 -13
  97. package/extensions/modules/router/lib/systemone.ts +152 -0
  98. package/extensions/modules/router/test/unit.test.ts +260 -0
  99. package/extensions/modules/rtk/findFallback.js +68 -0
  100. package/extensions/modules/rtk/index.ts +248 -0
  101. package/extensions/modules/rtk/safe-rewrite.js +74 -0
  102. package/extensions/modules/rtk/test/findFallback.test.js +66 -0
  103. package/extensions/modules/rtk/test/index.test.js +131 -0
  104. package/extensions/modules/rtk/test/safe-rewrite.test.js +96 -0
  105. package/extensions/modules/rtk/version-gate.js +34 -0
  106. package/extensions/modules/rules/index.ts +120 -0
  107. package/extensions/modules/rules/lib/rules.ts +348 -0
  108. package/extensions/modules/rules/test/lib.test.ts +263 -0
  109. package/extensions/modules/rules/test/module.test.ts +222 -0
  110. package/extensions/modules/serena/index.ts +629 -0
  111. package/extensions/modules/serena/lib/detect.ts +73 -0
  112. package/extensions/modules/serena/lib/env.ts +76 -0
  113. package/extensions/modules/serena/lib/guidance.ts +26 -0
  114. package/extensions/modules/serena/lib/normalize.ts +27 -0
  115. package/extensions/modules/serena/lib/symbol-key.ts +20 -0
  116. package/extensions/modules/serena/lib/truncate.ts +20 -0
  117. package/extensions/modules/serena/test/env.test.ts +122 -0
  118. package/extensions/modules/serena/test/index.test.ts +347 -0
  119. package/extensions/modules/serena/test/worker.test.ts +562 -0
  120. package/extensions/modules/serena/worker.ts +858 -0
  121. package/extensions/modules/steering/configPanel.ts +122 -0
  122. package/extensions/modules/steering/index.ts +616 -0
  123. package/extensions/modules/steering/lib/anchor.ts +175 -0
  124. package/extensions/modules/steering/lib/errors.ts +253 -0
  125. package/extensions/modules/steering/lib/family.ts +33 -0
  126. package/extensions/modules/steering/lib/guidance.ts +172 -0
  127. package/extensions/modules/steering/lib/history.ts +170 -0
  128. package/extensions/modules/steering/lib/settings.ts +127 -0
  129. package/extensions/modules/steering/test/anchor-regressions.test.ts +93 -0
  130. package/extensions/modules/steering/test/anchor-wiring.test.ts +99 -0
  131. package/extensions/modules/steering/test/anchor.test.ts +160 -0
  132. package/extensions/modules/steering/test/cache-stats.test.ts +43 -0
  133. package/extensions/modules/steering/test/errors.test.ts +309 -0
  134. package/extensions/modules/steering/test/family.test.ts +43 -0
  135. package/extensions/modules/steering/test/guidance.test.ts +357 -0
  136. package/extensions/modules/steering/test/harness.ts +93 -0
  137. package/extensions/modules/steering/test/history.test.ts +118 -0
  138. package/extensions/modules/steering/test/settings.test.ts +182 -0
  139. package/extensions/modules/steering/test/status.test.ts +71 -0
  140. package/extensions/modules/steering/test/toolCall.test.ts +99 -0
  141. package/extensions/modules/subagent/agents/planner.md +14 -0
  142. package/extensions/modules/subagent/agents/reviewer.md +42 -0
  143. package/extensions/modules/subagent/agents/scout.md +47 -0
  144. package/extensions/modules/subagent/agents/tester.md +12 -0
  145. package/extensions/modules/subagent/agents/worker.md +18 -0
  146. package/extensions/modules/subagent/configPanel.ts +219 -0
  147. package/extensions/modules/subagent/index.ts +2464 -0
  148. package/extensions/modules/subagent/lib/agents.ts +408 -0
  149. package/extensions/modules/subagent/lib/background.ts +383 -0
  150. package/extensions/modules/subagent/lib/herdr.ts +1019 -0
  151. package/extensions/modules/subagent/lib/history.ts +126 -0
  152. package/extensions/modules/subagent/lib/model.ts +156 -0
  153. package/extensions/modules/subagent/lib/render.ts +335 -0
  154. package/extensions/modules/subagent/lib/result.ts +110 -0
  155. package/extensions/modules/subagent/lib/roles.ts +296 -0
  156. package/extensions/modules/subagent/lib/routing.ts +228 -0
  157. package/extensions/modules/subagent/lib/runner.ts +559 -0
  158. package/extensions/modules/subagent/lib/schema.ts +21 -0
  159. package/extensions/modules/subagent/lib/security.ts +763 -0
  160. package/extensions/modules/subagent/lib/settings.ts +159 -0
  161. package/extensions/modules/subagent/lib/thread-viewer.ts +319 -0
  162. package/extensions/modules/subagent/lib/threads.ts +135 -0
  163. package/extensions/modules/subagent/lib/types.ts +18 -0
  164. package/extensions/modules/subagent/lib/widget.ts +475 -0
  165. package/extensions/modules/subagent/test/configPanel.test.ts +132 -0
  166. package/extensions/modules/subagent/test/herdr-advisor.test.ts +40 -0
  167. package/extensions/modules/subagent/test/routing.test.ts +524 -0
  168. package/extensions/modules/subagent/test/widget.test.ts +208 -0
  169. package/extensions/modules/todo/index.ts +478 -0
  170. package/extensions/modules/todo/test/todo.test.ts +252 -0
  171. package/extensions/modules/usage/index.ts +70 -16
  172. package/extensions/modules/usage/test/genrate.test.ts +70 -0
  173. package/extensions/modules/usage/test/parsers.test.ts +13 -0
  174. package/extensions/modules/usage/test/session-accumulators.test.ts +85 -0
  175. package/extensions/modules/ux/UPSTREAM +24 -0
  176. package/extensions/modules/ux/index.ts +393 -0
  177. package/extensions/modules/ux/lib/audit.ts +562 -0
  178. package/extensions/modules/ux/lib/config.ts +136 -0
  179. package/extensions/modules/ux/lib/instructions.ts +77 -0
  180. package/extensions/modules/ux/test/audit.test.ts +756 -0
  181. package/extensions/modules/ux/test/extension.test.ts +394 -0
  182. package/extensions/modules/ux/test/instructions.test.ts +19 -0
  183. package/extensions/modules/web/configPanel.ts +218 -0
  184. package/extensions/modules/web/index.ts +978 -0
  185. package/extensions/modules/web/lib/agy.ts +209 -0
  186. package/extensions/modules/web/lib/brave.ts +42 -0
  187. package/extensions/modules/web/lib/cdp.ts +686 -0
  188. package/extensions/modules/web/lib/chatapi.ts +101 -0
  189. package/extensions/modules/web/lib/chatgpt.ts +796 -0
  190. package/extensions/modules/web/lib/chrome.ts +328 -0
  191. package/extensions/modules/web/lib/config.ts +136 -0
  192. package/extensions/modules/web/lib/content.ts +99 -0
  193. package/extensions/modules/web/lib/crawl4ai.ts +172 -0
  194. package/extensions/modules/web/lib/extract.ts +235 -0
  195. package/extensions/modules/web/lib/firecrawl.ts +56 -0
  196. package/extensions/modules/web/lib/format.ts +197 -0
  197. package/extensions/modules/web/lib/gemini-auth.ts +286 -0
  198. package/extensions/modules/web/lib/gemini-dr.ts +338 -0
  199. package/extensions/modules/web/lib/gemini.ts +551 -0
  200. package/extensions/modules/web/lib/imageapi.ts +559 -0
  201. package/extensions/modules/web/lib/retry.ts +71 -0
  202. package/extensions/modules/web/lib/search.ts +237 -0
  203. package/extensions/modules/web/lib/searxng.ts +69 -0
  204. package/extensions/modules/web/lib/settings.ts +157 -0
  205. package/extensions/modules/web/scripts/cdp-smoke.ts +77 -0
  206. package/extensions/modules/web/scripts/gemini-smoke.ts +107 -0
  207. package/extensions/modules/web/test/agy.test.ts +383 -0
  208. package/extensions/modules/web/test/cdp.test.ts +717 -0
  209. package/extensions/modules/web/test/chat.test.ts +171 -0
  210. package/extensions/modules/web/test/chatgpt.test.ts +633 -0
  211. package/extensions/modules/web/test/chrome.test.ts +282 -0
  212. package/extensions/modules/web/test/config.test.ts +218 -0
  213. package/extensions/modules/web/test/configPanel.test.ts +198 -0
  214. package/extensions/modules/web/test/crawl.test.ts +134 -0
  215. package/extensions/modules/web/test/crawl4ai.test.ts +105 -0
  216. package/extensions/modules/web/test/extension.test.ts +118 -0
  217. package/extensions/modules/web/test/extract.test.ts +436 -0
  218. package/extensions/modules/web/test/fixtures/dr-confirm.bin +12 -0
  219. package/extensions/modules/web/test/fixtures/dr-plan.bin +20 -0
  220. package/extensions/modules/web/test/fixtures/interaction.html +31 -0
  221. package/extensions/modules/web/test/format.test.ts +230 -0
  222. package/extensions/modules/web/test/gemini-auth.test.ts +465 -0
  223. package/extensions/modules/web/test/gemini-dr.test.ts +249 -0
  224. package/extensions/modules/web/test/gemini.test.ts +472 -0
  225. package/extensions/modules/web/test/hook.test.ts +101 -0
  226. package/extensions/modules/web/test/image.test.ts +1089 -0
  227. package/extensions/modules/web/test/retry.test.ts +119 -0
  228. package/extensions/modules/web/test/screenshot.test.ts +109 -0
  229. package/extensions/modules/web/test/search.test.ts +210 -0
  230. package/extensions/modules/web/test/settings.test.ts +165 -0
  231. package/extensions/modules/web/test/skill.test.ts +72 -0
  232. package/extensions/modules/web/types.d.ts +3 -0
  233. package/extensions/modules/web/vendor/package.json +1 -0
  234. package/extensions/modules/web/vendor/readability/LICENSE.md +13 -0
  235. package/extensions/modules/web/vendor/readability/Readability-readerable.js +123 -0
  236. package/extensions/modules/web/vendor/readability/Readability.js +2787 -0
  237. package/extensions/modules/web/vendor/readability/index.d.ts +64 -0
  238. package/extensions/modules/web/vendor/readability/index.js +9 -0
  239. package/extensions/modules/web/vendor/turndown/LICENSE +21 -0
  240. package/extensions/modules/web/vendor/turndown/turndown.cjs.js +784 -0
  241. package/extensions/modules/web/vendor/turndown-plugin-gfm/LICENSE +21 -0
  242. package/extensions/modules/web/vendor/turndown-plugin-gfm/turndown-plugin-gfm.cjs.js +163 -0
  243. package/extensions/modules/zai/configPanel.ts +154 -0
  244. package/extensions/modules/zai/index.ts +186 -0
  245. package/extensions/modules/zai/lib/anthropic.ts +159 -0
  246. package/extensions/modules/zai/lib/settings.ts +198 -0
  247. package/extensions/modules/zai/lib/signing.ts +721 -0
  248. package/extensions/modules/zai/lib/throttle.ts +198 -0
  249. package/extensions/modules/zai/test/anthropic.test.ts +132 -0
  250. package/extensions/modules/zai/test/configPanel.test.ts +230 -0
  251. package/extensions/modules/zai/test/extension.test.ts +249 -0
  252. package/extensions/modules/zai/test/settings.test.ts +183 -0
  253. package/extensions/modules/zai/test/signing-wiring.test.ts +108 -0
  254. package/extensions/modules/zai/test/signing.test.ts +364 -0
  255. package/extensions/modules/zai/test/throttle.test.ts +329 -0
  256. package/package.json +19 -4
  257. package/scripts/validate-themes.mjs +75 -0
  258. package/skills/munin/SKILL.md +117 -0
  259. package/skills/ux-capture/SKILL.md +202 -0
  260. package/skills/ux-design/SKILL.md +279 -0
  261. package/skills/ux-presets/SKILL.md +484 -0
  262. package/skills/ux-routing/SKILL.md +46 -0
  263. package/skills/web/SKILL.md +153 -0
  264. package/themes/alabaster.json +93 -0
  265. package/themes/amethyst.json +96 -0
  266. package/themes/anthracite.json +93 -0
  267. package/themes/basalt.json +91 -0
  268. package/themes/birch.json +95 -0
  269. package/themes/catppuccin-mocha.json +91 -0
  270. package/themes/dark-abyss.json +91 -0
  271. package/themes/dark-arctic.json +104 -0
  272. package/themes/dark-aurora.json +95 -0
  273. package/themes/dark-catppuccin.json +107 -0
  274. package/themes/dark-cavern.json +91 -0
  275. package/themes/dark-celestial.json +106 -0
  276. package/themes/dark-copper.json +95 -0
  277. package/themes/dark-cosmos.json +90 -0
  278. package/themes/dark-cyberpunk.json +102 -0
  279. package/themes/dark-dracula.json +98 -0
  280. package/themes/dark-eclipse.json +91 -0
  281. package/themes/dark-ember.json +95 -0
  282. package/themes/dark-equinox.json +90 -0
  283. package/themes/dark-forest.json +96 -0
  284. package/themes/dark-github.json +105 -0
  285. package/themes/dark-gruvbox.json +112 -0
  286. package/themes/dark-lavender.json +95 -0
  287. package/themes/dark-lunar.json +89 -0
  288. package/themes/dark-midnight.json +95 -0
  289. package/themes/dark-monochrome.json +94 -0
  290. package/themes/dark-monokai.json +98 -0
  291. package/themes/dark-nebula.json +90 -0
  292. package/themes/dark-neon-noir.json +100 -0
  293. package/themes/dark-nord.json +98 -0
  294. package/themes/dark-ocean.json +101 -0
  295. package/themes/dark-one.json +100 -0
  296. package/themes/dark-poimandres.json +115 -0
  297. package/themes/dark-rainforest.json +91 -0
  298. package/themes/dark-reef.json +91 -0
  299. package/themes/dark-retro.json +92 -0
  300. package/themes/dark-rose-pine.json +96 -0
  301. package/themes/dark-sakura.json +95 -0
  302. package/themes/dark-slate.json +95 -0
  303. package/themes/dark-solarized.json +97 -0
  304. package/themes/dark-solstice.json +90 -0
  305. package/themes/dark-starfall.json +91 -0
  306. package/themes/dark-sunset.json +99 -0
  307. package/themes/dark-swamp.json +90 -0
  308. package/themes/dark-synthwave.json +103 -0
  309. package/themes/dark-taiga.json +91 -0
  310. package/themes/dark-terminal.json +95 -0
  311. package/themes/dark-tokyo-night.json +101 -0
  312. package/themes/dark-tundra.json +91 -0
  313. package/themes/dark-twilight.json +91 -0
  314. package/themes/dark-volcanic.json +91 -0
  315. package/themes/dark.json +80 -0
  316. package/themes/graphite.json +92 -0
  317. package/themes/light-arctic.json +107 -0
  318. package/themes/light-aurora-day.json +91 -0
  319. package/themes/light-canyon.json +91 -0
  320. package/themes/light-catppuccin.json +106 -0
  321. package/themes/light-cirrus.json +90 -0
  322. package/themes/light-coral.json +95 -0
  323. package/themes/light-cyberpunk.json +96 -0
  324. package/themes/light-dawn.json +90 -0
  325. package/themes/light-dunes.json +91 -0
  326. package/themes/light-eucalyptus.json +95 -0
  327. package/themes/light-forest.json +100 -0
  328. package/themes/light-frost.json +95 -0
  329. package/themes/light-github.json +115 -0
  330. package/themes/light-glacier.json +91 -0
  331. package/themes/light-gruvbox.json +108 -0
  332. package/themes/light-haze.json +90 -0
  333. package/themes/light-honeycomb.json +95 -0
  334. package/themes/light-lagoon.json +91 -0
  335. package/themes/light-lavender.json +95 -0
  336. package/themes/light-meadow.json +91 -0
  337. package/themes/light-mint.json +95 -0
  338. package/themes/light-monochrome.json +101 -0
  339. package/themes/light-ocean.json +99 -0
  340. package/themes/light-one.json +99 -0
  341. package/themes/light-opal.json +91 -0
  342. package/themes/light-orchard.json +91 -0
  343. package/themes/light-paper.json +95 -0
  344. package/themes/light-poimandres.json +115 -0
  345. package/themes/light-prism.json +90 -0
  346. package/themes/light-retro.json +98 -0
  347. package/themes/light-sand.json +95 -0
  348. package/themes/light-savanna.json +91 -0
  349. package/themes/light-solarized.json +102 -0
  350. package/themes/light-soleil.json +90 -0
  351. package/themes/light-sunset.json +99 -0
  352. package/themes/light-synthwave.json +98 -0
  353. package/themes/light-tokyo-night.json +111 -0
  354. package/themes/light-wetland.json +91 -0
  355. package/themes/light-zenith.json +89 -0
  356. package/themes/light.json +80 -0
  357. package/themes/limestone.json +94 -0
  358. package/themes/mahogany.json +97 -0
  359. package/themes/marble.json +93 -0
  360. package/themes/mirage.json +79 -0
  361. package/themes/obsidian.json +91 -0
  362. package/themes/onyx.json +91 -0
  363. package/themes/pearl.json +93 -0
  364. package/themes/porcelain.json +91 -0
  365. package/themes/quartz.json +96 -0
  366. package/themes/sandstone.json +95 -0
  367. package/themes/titanium.json +90 -0
@@ -0,0 +1,481 @@
1
+ // ponytail: vendored from @bacnh85/pi-model-tools 0.9.5 — lib/apply-patch.ts
2
+ // Local change: `nearestBlock` is imported from ./edit-repair.js (upstream
3
+ // lib/edit-repair.ts) — same file, ceulen extension.
4
+ /**
5
+ * apply-patch.ts — Codex-style V4D patch parser + applier for the `apply_patch`
6
+ * tool. The model emits only `@@` context + `-`/`+` change lines (a small diff),
7
+ * which is far easier for weaker models to reproduce verbatim than a large
8
+ * str_replace oldText block.
9
+ *
10
+ * Format (mirrors OpenAI Codex `apply_patch`):
11
+ * *** Begin Patch
12
+ * *** Add File: path/to/new.txt
13
+ * +content line 1
14
+ * +content line 2
15
+ * *** Delete File: path/to/old.txt
16
+ * *** Update File: path/to/existing.ts
17
+ * @@ context line (unchanged, for anchoring)
18
+ * -removed line
19
+ * +added line
20
+ * unchanged context line (leading space preserved)
21
+ * *** Update File: a.ts → b.ts (rename)
22
+ * *** End Patch
23
+ *
24
+ * Divergence from Codex: context+removed blocks must match UNIQUELY (Codex
25
+ * takes the first match). Silent wrong-location edits are worse than a clear
26
+ * error, and this matches pi's own `edit` philosophy.
27
+ *
28
+ * Leniency: if the @@ anchor text repeats as the immediately-following context
29
+ * or removed line (common when models treat `@@` as a git-diff-style locator
30
+ * header), the duplicate is collapsed automatically.
31
+ */
32
+
33
+ import { readFile, writeFile, unlink } from "node:fs/promises";
34
+ import { isAbsolute, resolve } from "node:path";
35
+ import { generateUnifiedPatch, withFileMutationQueue } from "@earendil-works/pi-coding-agent";
36
+ import { nearestBlock } from "./edit-repair.js";
37
+
38
+ export type FileOpKind = "add" | "delete" | "update";
39
+
40
+ export interface Hunk {
41
+ /** Ordered lines: context (with leading space stripped) + removed + added. */
42
+ context: string[];
43
+ removed: string[];
44
+ added: string[];
45
+ }
46
+
47
+ export interface FileOp {
48
+ kind: FileOpKind;
49
+ path: string;
50
+ /** For update-with-rename: the new path. */
51
+ movePath?: string;
52
+ hunks: Hunk[];
53
+ }
54
+
55
+ export interface ParsedPatch {
56
+ ops: FileOp[];
57
+ }
58
+
59
+ export class PatchParseError extends Error {}
60
+
61
+ // ── Parser ──
62
+
63
+ function stripLeadingSpace(line: string): string {
64
+ // In an update hunk, every payload line begins with a marker: ' ', '-', '+'.
65
+ // A literal leading space is the "context" marker and is part of the content.
66
+ return line.length > 0 ? line.slice(1) : "";
67
+ }
68
+
69
+ export function parsePatch(patch: string): ParsedPatch {
70
+ const lines = patch.split("\n");
71
+ const ops: FileOp[] = [];
72
+ let i = 0;
73
+
74
+ // Optional *** Begin Patch header.
75
+ if (i < lines.length && lines[i].trim() === "*** Begin Patch") i++;
76
+
77
+ let current: FileOp | null = null;
78
+ let inPayload = false;
79
+ const finalize = () => { if (current) { ops.push(current); current = null; } };
80
+
81
+ for (; i < lines.length; i++) {
82
+ const line = lines[i];
83
+ const trimmed = line.trim();
84
+
85
+ if (trimmed === "*** End Patch") { finalize(); break; }
86
+ if (trimmed === "*** Begin Patch") continue;
87
+
88
+ if (trimmed.startsWith("*** ")) {
89
+ finalize();
90
+ current = parseFileHeader(trimmed);
91
+ inPayload = false;
92
+ continue;
93
+ }
94
+
95
+ if (!current) {
96
+ if (trimmed.length === 0) continue; // tolerate blank lines between ops
97
+ throw new PatchParseError(`Unexpected patch line outside a file section: ${JSON.stringify(line)}`);
98
+ }
99
+
100
+ // `@@ <text>` introduces a new hunk; the text after `@@ ` is the anchor
101
+ // context line. A bare `@@` just flushes/separates hunks.
102
+ if (line.startsWith("@@")) {
103
+ if (current.kind === "add") throw new PatchParseError("'@@' is invalid in an *** Add File section");
104
+ inPayload = false;
105
+ current.hunks.push({ context: [], removed: [], added: [] });
106
+ const anchor = line.slice(2);
107
+ if (anchor.startsWith(" ")) {
108
+ current.hunks[current.hunks.length - 1].context.push(anchor.slice(1));
109
+ } else if (anchor.length > 0) {
110
+ // tolerate `@@text` with no space
111
+ current.hunks[current.hunks.length - 1].context.push(anchor);
112
+ }
113
+ continue;
114
+ }
115
+
116
+ // Payload lines only valid inside update/add.
117
+ if (current.kind === "delete") {
118
+ throw new PatchParseError(`*** Delete File sections must not contain payload lines: ${JSON.stringify(line)}`);
119
+ }
120
+
121
+ if (line.startsWith("+")) {
122
+ // Add-File payload ('+' lines) and Update added-lines share this path;
123
+ // content is the text after the '+' marker.
124
+ inPayload = true;
125
+ current.hunks.push({ context: [], removed: [], added: [stripLeadingSpace(line)] });
126
+ continue;
127
+ }
128
+ if (line.startsWith("-")) {
129
+ if (current.kind === "add") throw new PatchParseError(`'-' lines are invalid in an *** Add File section`);
130
+ inPayload = true;
131
+ current.hunks.push({ context: [], removed: [], added: [] });
132
+ current.hunks[current.hunks.length - 1].removed.push(stripLeadingSpace(line));
133
+ continue;
134
+ }
135
+ // A bare blank line (no marker) in an Add section is a literal empty
136
+ // content line; in an Update payload it's an added empty line (models
137
+ // frequently omit the '+' prefix on blank lines inside a +block, esp.
138
+ // fenced code blocks). Treating it as context would split the added block
139
+ // into two hunks and leave a matchBlock of [""] → "context not found".
140
+ if (line === "") {
141
+ if (current.kind === "add" || inPayload) {
142
+ current.hunks.push({ context: [], removed: [], added: [""] });
143
+ }
144
+ // else: stray blank between anchor and payload → ignore (lenient).
145
+ continue;
146
+ }
147
+ // Any other line in an Update section is context. Models frequently omit
148
+ // the leading-space context marker, so be lenient: treat the line verbatim.
149
+ // (In an Add section, only '+' lines are valid — anything else is an error.)
150
+ if (current.kind === "add") {
151
+ throw new PatchParseError(`Invalid Add File payload line (expected '+'): ${JSON.stringify(line)}`);
152
+ }
153
+ if (line.startsWith(" ")) {
154
+ current.hunks.push({ context: [], removed: [], added: [] });
155
+ current.hunks[current.hunks.length - 1].context.push(stripLeadingSpace(line));
156
+ } else {
157
+ current.hunks.push({ context: [], removed: [], added: [] });
158
+ current.hunks[current.hunks.length - 1].context.push(line);
159
+ }
160
+ continue;
161
+ }
162
+
163
+ finalize();
164
+ if (ops.length === 0) throw new PatchParseError("Patch contains no file operations.");
165
+ return { ops };
166
+ }
167
+
168
+ function parseFileHeader(header: string): FileOp {
169
+ // *** Add File: path / *** Delete File: path / *** Update File: path [→ newPath]
170
+ const addMatch = header.match(/^\*\*\* Add File:\s*(.+)$/);
171
+ if (addMatch) return { kind: "add", path: addMatch[1].trim(), hunks: [] };
172
+ const delMatch = header.match(/^\*\*\* Delete File:\s*(.+)$/);
173
+ if (delMatch) return { kind: "delete", path: delMatch[1].trim(), hunks: [] };
174
+ const updMatch = header.match(/^\*\*\* Update File:\s*(.+?)(?:\s*(?:->|→)\s*(.+))?$/);
175
+ if (updMatch) {
176
+ return { kind: "update", path: updMatch[1].trim(), movePath: updMatch[2]?.trim(), hunks: [] };
177
+ }
178
+ throw new PatchParseError(`Unrecognized file header: ${JSON.stringify(header)}`);
179
+ }
180
+
181
+ // ── Hunk assembly: collapse the marker-stream into ordered hunk groups ──
182
+
183
+ interface AssembledHunk {
184
+ /** Lines before the first `-`/`+`: pure context (anchor). */
185
+ context: string[];
186
+ /** Removed + added payload, in emission order. */
187
+ removed: string[];
188
+ added: string[];
189
+ }
190
+
191
+ /** Merge adjacent context/removed/added markers into coherent hunks. */
192
+ function assembleHunks(raw: Hunk[]): AssembledHunk[] {
193
+ const out: AssembledHunk[] = [];
194
+ let cur: AssembledHunk = { context: [], removed: [], added: [] };
195
+ let started = false;
196
+ // Once any payload hunk has been committed in this section, unstarted
197
+ // accumulated context is the previous hunk's TRAILING context; before that,
198
+ // it is leading context that no payload has claimed yet.
199
+ let sawPayload = false;
200
+ const flush = () => {
201
+ if (started) out.push(cur);
202
+ cur = { context: [], removed: [], added: [] };
203
+ started = false;
204
+ };
205
+ for (const h of raw) {
206
+ // A bare `@@` (empty raw hunk) starts a new hunk. Without this, consecutive
207
+ // context-free hunks (`@@ / -A +A' / @@ / -B +B'`) fuse into one hunk whose
208
+ // match block spans non-adjacent file lines → "Hunk context not found".
209
+ // Commit a pending payload hunk; drop the previous hunk's trailing context
210
+ // so it cannot glue onto the next hunk's — but keep leading context that no
211
+ // payload has claimed yet (e.g. `@@ anchor` / `@@` / payload), which was
212
+ // matchable before 0.8.1 and stays matchable.
213
+ if (!h.context.length && !h.removed.length && !h.added.length) {
214
+ if (started) flush();
215
+ else if (sawPayload) cur = { context: [], removed: [], added: [] };
216
+ continue;
217
+ }
218
+ if (h.context.length) {
219
+ if (started && (cur.removed.length || cur.added.length)) flush();
220
+ cur.context.push(...h.context);
221
+ }
222
+ if (h.removed.length || h.added.length) {
223
+ started = true;
224
+ sawPayload = true;
225
+ cur.removed.push(...h.removed);
226
+ cur.added.push(...h.added);
227
+ }
228
+ }
229
+ if (started) out.push(cur);
230
+ return out;
231
+ }
232
+
233
+ // ── seekSequence: Codex's progressive fuzzy matcher (4 passes) ──
234
+
235
+ function normalizeAscii(s: string): string {
236
+ return s.trim()
237
+ .replace(/[\u2010-\u2015\u2212]/g, "-")
238
+ .replace(/[\u2018\u2019\u201A\u201B]/g, "'")
239
+ .replace(/[\u201C\u201D\u201E\u201F]/g, '"')
240
+ .replace(/[\u00A0\u2002-\u200A\u202F\u205F\u3000]/g, " ");
241
+ }
242
+
243
+ function eqExact(a: string, b: string) { return a === b; }
244
+ function eqRstrip(a: string, b: string) { return a.trimEnd() === b.trimEnd(); }
245
+ function eqTrim(a: string, b: string) { return a.trim() === b.trim(); }
246
+ function eqUnicode(a: string, b: string) { return normalizeAscii(a) === normalizeAscii(b); }
247
+
248
+ /**
249
+ * Loose equality matching seekSequence's 4-pass progression. Used for dedup
250
+ * so the collapse is consistent with the matcher's own fuzzy boundaries.
251
+ */
252
+ function linesLooselyEqual(a: string, b: string): boolean {
253
+ return a === b
254
+ || a.trimEnd() === b.trimEnd()
255
+ || a.trim() === b.trim()
256
+ || normalizeAscii(a) === normalizeAscii(b);
257
+ }
258
+
259
+ /**
260
+ * Count matches of `pattern` lines within `lines`, trying progressively
261
+ * lenient equality. Returns count and first start index under the strictest
262
+ * pass that yields any match.
263
+ */
264
+ export function seekSequence(lines: string[], pattern: string[]): { count: number; firstIndex: number; exact: boolean; indices: number[] } {
265
+ if (pattern.length === 0) return { count: 0, firstIndex: -1, exact: true, indices: [] };
266
+ if (pattern.length > lines.length) return { count: 0, firstIndex: -1, exact: true, indices: [] };
267
+ for (const eq of [eqExact, eqRstrip, eqTrim, eqUnicode]) {
268
+ let count = 0;
269
+ let firstIndex = -1;
270
+ const indices: number[] = [];
271
+ for (let i = 0; i <= lines.length - pattern.length; i++) {
272
+ let ok = true;
273
+ for (let j = 0; j < pattern.length; j++) {
274
+ if (!eq(lines[i + j], pattern[j])) { ok = false; break; }
275
+ }
276
+ if (ok) {
277
+ count++;
278
+ indices.push(i);
279
+ if (firstIndex === -1) firstIndex = i;
280
+ }
281
+ }
282
+ if (count > 0) return { count, firstIndex, exact: eq === eqExact, indices };
283
+ }
284
+ return { count: 0, firstIndex: -1, exact: true, indices: [] };
285
+ }
286
+
287
+ // ── Applier ──
288
+
289
+ function stripBom(s: string): string { return s.startsWith("\uFEFF") ? s.slice(1) : s; }
290
+ function normalizeLF(s: string): string { return s.replace(/\r\n/g, "\n").replace(/\r/g, "\n"); }
291
+ function detectLineEnding(content: string): "\r\n" | "\n" {
292
+ const crlf = content.indexOf("\r\n");
293
+ const lf = content.indexOf("\n");
294
+ if (lf === -1) return "\n";
295
+ if (crlf === -1) return "\n";
296
+ return crlf < lf ? "\r\n" : "\n";
297
+ }
298
+ function restoreLineEndings(text: string, ending: "\r\n" | "\n"): string {
299
+ return ending === "\r\n" ? text.replace(/\n/g, "\r\n") : text;
300
+ }
301
+
302
+ /** Resolve a patch path the same way pi's built-in tools do: relative paths
303
+ * resolve under cwd, absolute paths are honored anywhere. (pi's resolveToCwd
304
+ * does NOT restrict absolute paths to cwd; matching that behavior keeps
305
+ * apply_patch compatible with edits the model references by absolute path.) */
306
+ function resolvePathLikePi(p: string, cwd: string): string {
307
+ const expanded = p.startsWith("~") ? (process.env.HOME ?? "") + p.slice(1) : p;
308
+ return isAbsolute(expanded) ? expanded : resolve(cwd, expanded);
309
+ }
310
+
311
+ export interface AppliedFile {
312
+ path: string;
313
+ /** For updates: the before/after content for diffing. */
314
+ before?: string;
315
+ after?: string;
316
+ kind: FileOpKind;
317
+ }
318
+
319
+ export interface ApplyResult {
320
+ files: AppliedFile[];
321
+ /** false if any hunk matched only via fuzzy (non-exact) pass. */
322
+ exact: boolean;
323
+ /** Unified diff string across all updated files. */
324
+ diff: string;
325
+ }
326
+
327
+ /**
328
+ * Apply a parsed patch's ops to the filesystem under cwd. Requires unique
329
+ * context+removed matches for every update hunk. Returns per-file before/after
330
+ * and a combined unified diff.
331
+ */
332
+ export async function applyPatchToFiles(parsed: ParsedPatch, cwd: string): Promise<ApplyResult> {
333
+ let exact = true;
334
+ const files: AppliedFile[] = [];
335
+ const diffParts: string[] = [];
336
+ const applied: string[] = [];
337
+
338
+ for (const op of parsed.ops) {
339
+ const abs = resolvePathLikePi(op.path, cwd);
340
+ try {
341
+ if (op.kind === "delete") {
342
+ const before = await withFileMutationQueue(abs, async () => {
343
+ const raw = await readOptional(abs);
344
+ if (raw === undefined) throw new Error(`Cannot delete (not found): ${op.path}`);
345
+ await unlink(abs);
346
+ return raw;
347
+ });
348
+ files.push({ path: op.path, before, after: "", kind: "delete" });
349
+ applied.push(op.path);
350
+ continue;
351
+ }
352
+
353
+ if (op.kind === "add") {
354
+ const content = op.hunks.map((h) => h.added.join("\n")).join("\n");
355
+ await withFileMutationQueue(abs, async () => {
356
+ if ((await readOptional(abs)) !== undefined) throw new Error(`Cannot add (already exists): ${op.path}`);
357
+ await writeFile(abs, content, "utf-8");
358
+ });
359
+ files.push({ path: op.path, before: "", after: content, kind: "add" });
360
+ applied.push(op.path);
361
+ continue;
362
+ }
363
+
364
+ // update
365
+ const destAbs = op.movePath ? resolvePathLikePi(op.movePath, cwd) : abs;
366
+ const { before, after } = await withFileMutationQueue(destAbs, async () => {
367
+ const raw = await readOptional(abs);
368
+ if (raw === undefined) throw new Error(`Cannot update (not found): ${op.path}`);
369
+ const bom = raw.startsWith("\uFEFF") ? "\uFEFF" : "";
370
+ const ending = detectLineEnding(stripBom(raw));
371
+ const beforeContent = normalizeLF(stripBom(raw));
372
+ const hunks = assembleHunks(op.hunks);
373
+
374
+ let work = beforeContent.split("\n");
375
+ const newHunks: { start: number; removedLen: number; added: string[] }[] = [];
376
+
377
+ for (const h of hunks) {
378
+ // ponytail: collapse a redundant @@ anchor the model restated as
379
+ // the first payload line (context or removed). Models treat `@@` like
380
+ // a git-diff locator header and repeat it as context/removed, which
381
+ // would otherwise require the line to appear twice consecutively in
382
+ // the file. Real Codex makes @@ a pure cursor-advance locator; we keep
383
+ // it in the match block so unique-match disambiguation still works
384
+ // (@@ fn / -dup), but drop the duplicate. Upgrade to full cursor
385
+ // semantics if unique-match is ever relaxed.
386
+ let matchBlock = [...h.context, ...h.removed];
387
+ if (matchBlock.length >= 2 && linesLooselyEqual(matchBlock[0], matchBlock[1])) {
388
+ matchBlock = matchBlock.slice(1);
389
+ }
390
+ // Pure additions with no anchor (e.g. *** Update File with only
391
+ // +lines, no @@): land at EOF instead of an opaque "context not found".
392
+ let firstIndex: number;
393
+ let hExact = true;
394
+ if (matchBlock.length === 0) {
395
+ // If the file ends with "\n", split() leaves a trailing "" element;
396
+ // insert before it so we don't add a spurious blank line.
397
+ firstIndex = work.length > 0 && work[work.length - 1] === "" ? work.length - 1 : work.length;
398
+ } else {
399
+ let sought = seekSequence(work, matchBlock);
400
+ if (sought.count === 0 && h.context.length > 0 && h.removed.length > 0) {
401
+ // Models trained on git diffs use `@@ text` as a section LABEL —
402
+ // often a paraphrase, not a verbatim file line — so the block
403
+ // fails on the anchor even when the removed payload matches
404
+ // uniquely. Demote the anchor to a hint: drop context and trust
405
+ // the removed lines alone, but only when they match exactly once
406
+ // (keeps the unique-match safety guarantee).
407
+ const payloadOnly = seekSequence(work, h.removed);
408
+ if (payloadOnly.count === 1) {
409
+ sought = payloadOnly;
410
+ matchBlock = h.removed;
411
+ hExact = false;
412
+ exact = false;
413
+ }
414
+ }
415
+ hExact = hExact && sought.exact;
416
+ if (!hExact) exact = false;
417
+ const anchor = matchBlock.join("\n");
418
+ if (sought.count === 0) {
419
+ throw new Error(`Hunk context not found in ${op.path}. Anchor:\n${anchor}\n${nearestBlock(beforeContent, anchor)}`);
420
+ }
421
+ if (sought.count > 1) {
422
+ const locs = sought.indices.slice(0, 3).map((idx) => idx + 1).join(", ");
423
+ throw new Error(`Hunk context is ambiguous (${sought.count} matches) in ${op.path}. Anchor:\n${anchor}\nFound at lines: ${locs}. Add more surrounding context lines to make it unique.`);
424
+ }
425
+ firstIndex = sought.firstIndex;
426
+ }
427
+ const removedStart = firstIndex + (matchBlock.length - h.removed.length);
428
+ newHunks.push({ start: removedStart, removedLen: h.removed.length, added: h.added });
429
+ }
430
+
431
+ // Guard against overlapping hunks (e.g. two hunks whose labels both
432
+ // failed and whose payloads demoted to the same span): reverse-order
433
+ // application would silently discard one hunk's added lines. Sorted
434
+ // desc, so an overlap means the earlier hunk's span reaches into the
435
+ // later one's start. Pure insertions (removedLen 0) at the same point
436
+ // are fine — both land, order among them is deterministic enough.
437
+ const ordered = [...newHunks].sort((a, b) => b.start - a.start);
438
+ for (let k = 1; k < ordered.length; k++) {
439
+ if (ordered[k].start + ordered[k].removedLen > ordered[k - 1].start) {
440
+ throw new Error(`Hunks overlap in ${op.path} (two hunks matched the same lines). Use distinct context per hunk, or split into separate apply_patch calls.`);
441
+ }
442
+ }
443
+ for (const h of ordered) {
444
+ work = [...work.slice(0, h.start), ...h.added, ...work.slice(h.start + h.removedLen)];
445
+ }
446
+
447
+ const afterContent = work.join("\n");
448
+ if (op.movePath && op.movePath !== op.path) {
449
+ if ((await readOptional(destAbs)) !== undefined) throw new Error(`Cannot rename onto existing file: ${op.movePath}`);
450
+ const outContent = bom + restoreLineEndings(afterContent, ending);
451
+ await unlink(abs);
452
+ await writeFile(destAbs, outContent, "utf-8");
453
+ } else {
454
+ const outContent = bom + restoreLineEndings(afterContent, ending);
455
+ await writeFile(abs, outContent, "utf-8");
456
+ }
457
+ return { before: beforeContent, after: afterContent };
458
+ });
459
+
460
+ files.push({ path: op.movePath ?? op.path, before, after, kind: "update" });
461
+ diffParts.push(generateUnifiedPatch(op.movePath ?? op.path, before, after));
462
+ applied.push(op.movePath ?? op.path);
463
+ } catch (err) {
464
+ // Report any files already applied before this op failed, so the model
465
+ // doesn't blindly re-apply the whole patch (and hit mismatches).
466
+ const appliedNote = applied.length > 0 ? ` (already applied: ${applied.join(", ")})` : "";
467
+ throw new Error(`${err instanceof Error ? err.message : String(err)}${appliedNote}`);
468
+ }
469
+ }
470
+
471
+ return { files, exact, diff: diffParts.join("\n").trimEnd() };
472
+ }
473
+
474
+ async function readOptional(abs: string): Promise<string | undefined> {
475
+ try {
476
+ const buf = await readFile(abs);
477
+ return buf.toString("utf-8");
478
+ } catch {
479
+ return undefined;
480
+ }
481
+ }
@@ -0,0 +1,114 @@
1
+ // repair module settings — the `repair` section of settings.json.
2
+ //
3
+ // Precedence (one file per layer, field-wise): defaults → global agent-dir
4
+ // settings.json → TRUSTED project `.pi/settings.json`. Read per tool call by
5
+ // index.ts, so a /config save applies to the next turn without /reload —
6
+ // exactly like subagent's read-per-execute() contract. The two bash keys
7
+ // (autoBg / autoBgSecs) are the exception: the wrapped bash description and
8
+ // the auto-background mechanics bind ONCE at module load, so those rows take
9
+ // effect on the next session.
10
+
11
+ import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
12
+ import os from "node:os";
13
+ import path from "node:path";
14
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
15
+
16
+ export interface RepairSettings {
17
+ /** Schema-driven argument repair (invalid/truncated JSON, param aliases). */
18
+ arguments: boolean;
19
+ /** Edit mismatch repair: trim-tolerant retry + nearest-region + escalation. */
20
+ editRetry: boolean;
21
+ /** Destructive-bash + read-on-guessed-path guards. */
22
+ guards: boolean;
23
+ /** Auto-background long foreground bash calls. */
24
+ autoBg: boolean;
25
+ /** Foreground threshold (seconds) before auto-backgrounding. */
26
+ autoBgSecs: number;
27
+ }
28
+
29
+ export const DEFAULT_REPAIR_SETTINGS: RepairSettings = {
30
+ arguments: true,
31
+ editRetry: true,
32
+ guards: true,
33
+ autoBg: false,
34
+ autoBgSecs: 120,
35
+ };
36
+
37
+ function agentDir(): string {
38
+ return process.env.PI_CODING_AGENT_DIR || path.join(os.homedir(), ".pi", "agent");
39
+ }
40
+
41
+ function readJson(file: string): Record<string, unknown> | null {
42
+ try {
43
+ if (!existsSync(file)) return null;
44
+ return JSON.parse(readFileSync(file, "utf8")) as Record<string, unknown>;
45
+ } catch {
46
+ return null; // unreadable/corrupt → this layer is simply absent
47
+ }
48
+ }
49
+
50
+ function section(json: Record<string, unknown> | null, key: string): Record<string, unknown> {
51
+ const raw = json?.[key];
52
+ return raw && typeof raw === "object" && !Array.isArray(raw) ? (raw as Record<string, unknown>) : {};
53
+ }
54
+
55
+ /** Merge one settings layer's `repair` keys over out (field-wise override). */
56
+ function mergeLayer(out: RepairSettings, json: Record<string, unknown> | null): void {
57
+ const s = section(json, "repair");
58
+ for (const key of ["arguments", "editRetry", "guards", "autoBg"] as const) {
59
+ if (typeof s[key] === "boolean") out[key] = s[key];
60
+ }
61
+ if (typeof s.autoBgSecs === "number" && Number.isFinite(s.autoBgSecs)) {
62
+ // Clamp to ≥1: "0.5" would floor to 0 → a 0 ms timer = instant-background
63
+ // everything (upstream's env reader clamped for the same reason).
64
+ out.autoBgSecs = Math.max(1, Math.floor(s.autoBgSecs));
65
+ }
66
+ }
67
+
68
+ /** The agent-dir settings.json (the file /config saves into). */
69
+ export function settingsPath(): string {
70
+ return path.join(agentDir(), "settings.json");
71
+ }
72
+
73
+ /** Effective repair settings: global agent-dir file ⊕ trusted project overlay. */
74
+ export function readRepairSettings(ctx?: ExtensionContext): RepairSettings {
75
+ const out: RepairSettings = { ...DEFAULT_REPAIR_SETTINGS };
76
+ mergeLayer(out, readJson(settingsPath()));
77
+ try {
78
+ if (ctx?.isProjectTrusted?.()) {
79
+ mergeLayer(out, readJson(path.join(ctx.cwd, ".pi", "settings.json")));
80
+ }
81
+ } catch { /* untrusted or ctx without cwd — global only */ }
82
+ return out;
83
+ }
84
+
85
+ /** True when a trusted project file carries a `repair` section (it then wins
86
+ * over any global save) — disclosed by the /config save and /repair status. */
87
+ export function projectShadow(cwd: string, trusted: boolean): boolean {
88
+ if (!trusted) return false;
89
+ return Object.keys(section(readJson(path.join(cwd, ".pi", "settings.json")), "repair")).length > 0;
90
+ }
91
+
92
+ /** Write the given keys back to the GLOBAL settings.json `repair` section.
93
+ * Atomic (tmp + rename); creates the file when missing. Returns the path. */
94
+ export function writeRepairSection(patch: Partial<RepairSettings>): string {
95
+ const file = settingsPath();
96
+ let settings: Record<string, unknown> = {};
97
+ if (existsSync(file)) {
98
+ try {
99
+ settings = JSON.parse(readFileSync(file, "utf8")) as Record<string, unknown>;
100
+ } catch {
101
+ throw new Error(`${file} is not valid JSON — fix or remove it before saving.`);
102
+ }
103
+ }
104
+ const repair = section(settings, "repair");
105
+ for (const [key, value] of Object.entries(patch)) {
106
+ if (value !== undefined) repair[key] = value;
107
+ }
108
+ settings.repair = repair;
109
+ mkdirSync(path.dirname(file), { recursive: true });
110
+ const tmp = file + ".tmp";
111
+ writeFileSync(tmp, JSON.stringify(settings, null, 2) + "\n");
112
+ renameSync(tmp, file);
113
+ return file;
114
+ }