@bastani/atomic 0.9.9-alpha.1 → 0.9.9-alpha.3

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 (576) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/dist/builtin/cursor/CHANGELOG.md +12 -0
  3. package/dist/builtin/cursor/package.json +3 -3
  4. package/dist/builtin/intercom/CHANGELOG.md +14 -0
  5. package/dist/builtin/intercom/README.md +10 -3
  6. package/dist/builtin/intercom/broker/client.ts +2 -0
  7. package/dist/builtin/intercom/broker/send-handler.ts +22 -20
  8. package/dist/builtin/intercom/foreground-detach-handoff.ts +3 -1
  9. package/dist/builtin/intercom/inbound-idle-queue.ts +82 -0
  10. package/dist/builtin/intercom/index-heavy.ts +47 -37
  11. package/dist/builtin/intercom/intercom-tool.ts +6 -4
  12. package/dist/builtin/intercom/intercom-utils.ts +30 -0
  13. package/dist/builtin/intercom/lifecycle.ts +8 -5
  14. package/dist/builtin/intercom/package.json +3 -3
  15. package/dist/builtin/intercom/reply-tracker.ts +19 -19
  16. package/dist/builtin/intercom/session-target.ts +68 -0
  17. package/dist/builtin/intercom/skills/intercom/SKILL.md +7 -4
  18. package/dist/builtin/intercom/source-ownership.ts +34 -0
  19. package/dist/builtin/intercom/subagent-relay.ts +45 -20
  20. package/dist/builtin/intercom/terminal-ordering-barrier.ts +111 -0
  21. package/dist/builtin/intercom/types.ts +5 -0
  22. package/dist/builtin/mcp/CHANGELOG.md +13 -0
  23. package/dist/builtin/mcp/package.json +4 -4
  24. package/dist/builtin/subagents/CHANGELOG.md +13 -0
  25. package/dist/builtin/subagents/package.json +5 -5
  26. package/dist/builtin/subagents/src/runs/background/notify.ts +53 -9
  27. package/dist/builtin/subagents/src/shared/types-config.ts +1 -0
  28. package/dist/builtin/web-access/CHANGELOG.md +13 -0
  29. package/dist/builtin/web-access/package.json +3 -3
  30. package/dist/builtin/web-access/web-search-tool.ts +1 -2
  31. package/dist/builtin/workflows/CHANGELOG.md +13 -0
  32. package/dist/builtin/workflows/package.json +3 -3
  33. package/dist/builtin/workflows/src/extension/workflow-tool.ts +18 -2
  34. package/dist/builtin/workflows/src/shared/serializable.ts +1 -1
  35. package/dist/bun/cli.d.ts.map +1 -1
  36. package/dist/bun/internal-intercom-broker.d.ts.map +1 -1
  37. package/dist/bun/register-bedrock.d.ts.map +1 -1
  38. package/dist/bun/restore-sandbox-env.d.ts.map +1 -1
  39. package/dist/bun/split-loader.d.ts.map +1 -1
  40. package/dist/cli/args.d.ts.map +1 -1
  41. package/dist/cli/config-selector.d.ts.map +1 -1
  42. package/dist/cli/file-processor.d.ts.map +1 -1
  43. package/dist/cli/initial-message.d.ts.map +1 -1
  44. package/dist/cli/list-models.d.ts.map +1 -1
  45. package/dist/cli/project-trust.d.ts.map +1 -1
  46. package/dist/cli/session-picker.d.ts.map +1 -1
  47. package/dist/cli/startup-ui.d.ts.map +1 -1
  48. package/dist/cli.d.ts.map +1 -1
  49. package/dist/config-self-update.d.ts.map +1 -1
  50. package/dist/config.d.ts.map +1 -1
  51. package/dist/core/agent-session-accessors.d.ts.map +1 -1
  52. package/dist/core/agent-session-auto-compaction.d.ts.map +1 -1
  53. package/dist/core/agent-session-bash.d.ts.map +1 -1
  54. package/dist/core/agent-session-compaction.d.ts.map +1 -1
  55. package/dist/core/agent-session-events.d.ts.map +1 -1
  56. package/dist/core/agent-session-export.d.ts.map +1 -1
  57. package/dist/core/agent-session-extension-bindings.d.ts.map +1 -1
  58. package/dist/core/agent-session-extension-bindings.js +9 -0
  59. package/dist/core/agent-session-extension-bindings.js.map +1 -1
  60. package/dist/core/agent-session-message-queue.d.ts +4 -1
  61. package/dist/core/agent-session-message-queue.d.ts.map +1 -1
  62. package/dist/core/agent-session-message-queue.js +35 -0
  63. package/dist/core/agent-session-message-queue.js.map +1 -1
  64. package/dist/core/agent-session-methods.d.ts +2 -1
  65. package/dist/core/agent-session-methods.d.ts.map +1 -1
  66. package/dist/core/agent-session-methods.js.map +1 -1
  67. package/dist/core/agent-session-models.d.ts.map +1 -1
  68. package/dist/core/agent-session-prompt.d.ts.map +1 -1
  69. package/dist/core/agent-session-retry.d.ts.map +1 -1
  70. package/dist/core/agent-session-runtime.d.ts.map +1 -1
  71. package/dist/core/agent-session-services.d.ts.map +1 -1
  72. package/dist/core/agent-session-skill-block.d.ts.map +1 -1
  73. package/dist/core/agent-session-state.d.ts.map +1 -1
  74. package/dist/core/agent-session-tool-hooks.d.ts.map +1 -1
  75. package/dist/core/agent-session-tool-registry.d.ts.map +1 -1
  76. package/dist/core/agent-session-tree.d.ts.map +1 -1
  77. package/dist/core/agent-session-types.d.ts.map +1 -1
  78. package/dist/core/agent-session.d.ts.map +1 -1
  79. package/dist/core/anthropic-thinking-guard.d.ts.map +1 -1
  80. package/dist/core/async/format.d.ts.map +1 -1
  81. package/dist/core/async/job-manager.d.ts.map +1 -1
  82. package/dist/core/async/session-manager.d.ts.map +1 -1
  83. package/dist/core/async/types.d.ts.map +1 -1
  84. package/dist/core/atomic-guide-command.d.ts.map +1 -1
  85. package/dist/core/auth-guidance.d.ts.map +1 -1
  86. package/dist/core/auth-storage-backends.d.ts.map +1 -1
  87. package/dist/core/auth-storage.d.ts +4 -0
  88. package/dist/core/auth-storage.d.ts.map +1 -1
  89. package/dist/core/bash-executor.d.ts.map +1 -1
  90. package/dist/core/builtin-packages.d.ts.map +1 -1
  91. package/dist/core/codex-fast-mode.d.ts.map +1 -1
  92. package/dist/core/compaction/branch-summarization.d.ts.map +1 -1
  93. package/dist/core/compaction/compaction-boundary.d.ts.map +1 -1
  94. package/dist/core/compaction/compaction-parameters.d.ts.map +1 -1
  95. package/dist/core/compaction/compaction-runner.d.ts.map +1 -1
  96. package/dist/core/compaction/compaction-types.d.ts.map +1 -1
  97. package/dist/core/compaction/compaction.d.ts.map +1 -1
  98. package/dist/core/compaction/deleted-ranges.d.ts.map +1 -1
  99. package/dist/core/compaction/index.d.ts.map +1 -1
  100. package/dist/core/compaction/range-planner.d.ts.map +1 -1
  101. package/dist/core/compaction/transcript-serialization.d.ts.map +1 -1
  102. package/dist/core/compaction/utils.d.ts.map +1 -1
  103. package/dist/core/context-window.d.ts.map +1 -1
  104. package/dist/core/copilot-anthropic-sse-repair.d.ts.map +1 -1
  105. package/dist/core/copilot-errors.d.ts.map +1 -1
  106. package/dist/core/copilot-gemini-payload-sanitizer.d.ts.map +1 -1
  107. package/dist/core/copilot-gemini-reasoning.d.ts.map +1 -1
  108. package/dist/core/copilot-gemini-tool-arguments.d.ts.map +1 -1
  109. package/dist/core/copilot-hosts.d.ts.map +1 -1
  110. package/dist/core/copilot-model-catalog.d.ts.map +1 -1
  111. package/dist/core/copilot-model-static-fallbacks.d.ts.map +1 -1
  112. package/dist/core/copilot-model-synthesis.d.ts.map +1 -1
  113. package/dist/core/defaults.d.ts.map +1 -1
  114. package/dist/core/diagnostics.d.ts.map +1 -1
  115. package/dist/core/event-bus.d.ts.map +1 -1
  116. package/dist/core/exec.d.ts.map +1 -1
  117. package/dist/core/experimental.d.ts.map +1 -1
  118. package/dist/core/export-html/ansi-to-html.d.ts.map +1 -1
  119. package/dist/core/export-html/index.d.ts.map +1 -1
  120. package/dist/core/export-html/template-script.d.ts.map +1 -1
  121. package/dist/core/export-html/tool-renderer.d.ts.map +1 -1
  122. package/dist/core/extensions/agent-events.d.ts.map +1 -1
  123. package/dist/core/extensions/api-types.d.ts +3 -1
  124. package/dist/core/extensions/api-types.d.ts.map +1 -1
  125. package/dist/core/extensions/api-types.js.map +1 -1
  126. package/dist/core/extensions/command-types.d.ts.map +1 -1
  127. package/dist/core/extensions/context-types.d.ts.map +1 -1
  128. package/dist/core/extensions/event-results.d.ts.map +1 -1
  129. package/dist/core/extensions/event-types.d.ts.map +1 -1
  130. package/dist/core/extensions/index.d.ts +1 -1
  131. package/dist/core/extensions/index.d.ts.map +1 -1
  132. package/dist/core/extensions/index.js.map +1 -1
  133. package/dist/core/extensions/loader-api.d.ts.map +1 -1
  134. package/dist/core/extensions/loader-api.js +4 -0
  135. package/dist/core/extensions/loader-api.js.map +1 -1
  136. package/dist/core/extensions/loader-core.d.ts.map +1 -1
  137. package/dist/core/extensions/loader-discovery.d.ts.map +1 -1
  138. package/dist/core/extensions/loader-resources.d.ts.map +1 -1
  139. package/dist/core/extensions/loader-runtime.d.ts.map +1 -1
  140. package/dist/core/extensions/loader-runtime.js +1 -0
  141. package/dist/core/extensions/loader-runtime.js.map +1 -1
  142. package/dist/core/extensions/loader-virtual-modules.d.ts.map +1 -1
  143. package/dist/core/extensions/loader.d.ts.map +1 -1
  144. package/dist/core/extensions/message-types.d.ts +3 -0
  145. package/dist/core/extensions/message-types.d.ts.map +1 -1
  146. package/dist/core/extensions/message-types.js.map +1 -1
  147. package/dist/core/extensions/provider-types.d.ts.map +1 -1
  148. package/dist/core/extensions/reactive-widget.d.ts.map +1 -1
  149. package/dist/core/extensions/runner-context.d.ts.map +1 -1
  150. package/dist/core/extensions/runner-events.d.ts.map +1 -1
  151. package/dist/core/extensions/runner-handlers.d.ts.map +1 -1
  152. package/dist/core/extensions/runner-project-trust.d.ts.map +1 -1
  153. package/dist/core/extensions/runner-registries.d.ts.map +1 -1
  154. package/dist/core/extensions/runner-shortcuts.d.ts.map +1 -1
  155. package/dist/core/extensions/runner-ui.d.ts.map +1 -1
  156. package/dist/core/extensions/runner.d.ts.map +1 -1
  157. package/dist/core/extensions/runner.js +1 -0
  158. package/dist/core/extensions/runner.js.map +1 -1
  159. package/dist/core/extensions/runtime-types.d.ts +3 -1
  160. package/dist/core/extensions/runtime-types.d.ts.map +1 -1
  161. package/dist/core/extensions/runtime-types.js.map +1 -1
  162. package/dist/core/extensions/session-events.d.ts.map +1 -1
  163. package/dist/core/extensions/tool-events.d.ts.map +1 -1
  164. package/dist/core/extensions/tool-types.d.ts.map +1 -1
  165. package/dist/core/extensions/types.d.ts.map +1 -1
  166. package/dist/core/extensions/ui-types.d.ts.map +1 -1
  167. package/dist/core/extensions/wrapper.d.ts.map +1 -1
  168. package/dist/core/flattened-tool-arguments.d.ts.map +1 -1
  169. package/dist/core/footer-data-provider.d.ts.map +1 -1
  170. package/dist/core/http-dispatcher.d.ts.map +1 -1
  171. package/dist/core/index.d.ts.map +1 -1
  172. package/dist/core/keybindings.d.ts.map +1 -1
  173. package/dist/core/messages.d.ts.map +1 -1
  174. package/dist/core/model-registry-auth.d.ts.map +1 -1
  175. package/dist/core/model-registry-builtins.d.ts.map +1 -1
  176. package/dist/core/model-registry-builtins.js.map +1 -1
  177. package/dist/core/model-registry-custom-loader.d.ts.map +1 -1
  178. package/dist/core/model-registry-custom-loader.js.map +1 -1
  179. package/dist/core/model-registry-dynamic.d.ts.map +1 -1
  180. package/dist/core/model-registry-loader.d.ts.map +1 -1
  181. package/dist/core/model-registry-schemas.d.ts +65 -13
  182. package/dist/core/model-registry-schemas.d.ts.map +1 -1
  183. package/dist/core/model-registry-schemas.js +5 -1
  184. package/dist/core/model-registry-schemas.js.map +1 -1
  185. package/dist/core/model-registry-types.d.ts.map +1 -1
  186. package/dist/core/model-registry.d.ts.map +1 -1
  187. package/dist/core/model-resolver-cli.d.ts.map +1 -1
  188. package/dist/core/model-resolver-defaults.d.ts.map +1 -1
  189. package/dist/core/model-resolver-initial.d.ts.map +1 -1
  190. package/dist/core/model-resolver-patterns.d.ts.map +1 -1
  191. package/dist/core/model-resolver-scope.d.ts.map +1 -1
  192. package/dist/core/model-resolver-types.d.ts.map +1 -1
  193. package/dist/core/model-resolver.d.ts.map +1 -1
  194. package/dist/core/openai-responses-payload-sanitizer.d.ts.map +1 -1
  195. package/dist/core/output-guard.d.ts.map +1 -1
  196. package/dist/core/package-manager-auto-resources.d.ts.map +1 -1
  197. package/dist/core/package-manager-command.d.ts.map +1 -1
  198. package/dist/core/package-manager-constants.d.ts.map +1 -1
  199. package/dist/core/package-manager-env.d.ts.map +1 -1
  200. package/dist/core/package-manager-git.d.ts.map +1 -1
  201. package/dist/core/package-manager-manifest.d.ts.map +1 -1
  202. package/dist/core/package-manager-npm.d.ts.map +1 -1
  203. package/dist/core/package-manager-operations.d.ts.map +1 -1
  204. package/dist/core/package-manager-paths.d.ts.map +1 -1
  205. package/dist/core/package-manager-progress.d.ts.map +1 -1
  206. package/dist/core/package-manager-resolver.d.ts.map +1 -1
  207. package/dist/core/package-manager-resource-accumulator.d.ts.map +1 -1
  208. package/dist/core/package-manager-resource-collector.d.ts.map +1 -1
  209. package/dist/core/package-manager-resource-files.d.ts.map +1 -1
  210. package/dist/core/package-manager-resource-patterns.d.ts.map +1 -1
  211. package/dist/core/package-manager-settings.d.ts.map +1 -1
  212. package/dist/core/package-manager-source.d.ts.map +1 -1
  213. package/dist/core/package-manager-types.d.ts.map +1 -1
  214. package/dist/core/package-manager.d.ts.map +1 -1
  215. package/dist/core/project-trust.d.ts.map +1 -1
  216. package/dist/core/prompt-templates-async.d.ts.map +1 -1
  217. package/dist/core/prompt-templates.d.ts.map +1 -1
  218. package/dist/core/provider-attribution.d.ts.map +1 -1
  219. package/dist/core/provider-context-usage.d.ts.map +1 -1
  220. package/dist/core/provider-display-names.d.ts.map +1 -1
  221. package/dist/core/resolve-config-value.d.ts.map +1 -1
  222. package/dist/core/resource-loader-assets.d.ts.map +1 -1
  223. package/dist/core/resource-loader-context-files.d.ts.map +1 -1
  224. package/dist/core/resource-loader-core.d.ts.map +1 -1
  225. package/dist/core/resource-loader-discovery.d.ts.map +1 -1
  226. package/dist/core/resource-loader-extensions.d.ts.map +1 -1
  227. package/dist/core/resource-loader-helpers.d.ts.map +1 -1
  228. package/dist/core/resource-loader-internals.d.ts.map +1 -1
  229. package/dist/core/resource-loader-package-resources.d.ts.map +1 -1
  230. package/dist/core/resource-loader-paths.d.ts.map +1 -1
  231. package/dist/core/resource-loader-reload.d.ts.map +1 -1
  232. package/dist/core/resource-loader-source-info.d.ts.map +1 -1
  233. package/dist/core/resource-loader-types.d.ts.map +1 -1
  234. package/dist/core/resource-loader.d.ts.map +1 -1
  235. package/dist/core/sdk-exports.d.ts.map +1 -1
  236. package/dist/core/sdk-types.d.ts.map +1 -1
  237. package/dist/core/sdk.d.ts.map +1 -1
  238. package/dist/core/session-cwd.d.ts.map +1 -1
  239. package/dist/core/session-entry-normalization.d.ts.map +1 -1
  240. package/dist/core/session-manager-archive.d.ts.map +1 -1
  241. package/dist/core/session-manager-classification.d.ts.map +1 -1
  242. package/dist/core/session-manager-core.d.ts.map +1 -1
  243. package/dist/core/session-manager-entries.d.ts.map +1 -1
  244. package/dist/core/session-manager-history.d.ts.map +1 -1
  245. package/dist/core/session-manager-list.d.ts.map +1 -1
  246. package/dist/core/session-manager-migrations.d.ts.map +1 -1
  247. package/dist/core/session-manager-paths.d.ts.map +1 -1
  248. package/dist/core/session-manager-storage.d.ts.map +1 -1
  249. package/dist/core/session-manager-types.d.ts.map +1 -1
  250. package/dist/core/session-manager-validation.d.ts.map +1 -1
  251. package/dist/core/session-manager.d.ts.map +1 -1
  252. package/dist/core/settings-manager-basic-accessors.d.ts.map +1 -1
  253. package/dist/core/settings-manager-core.d.ts.map +1 -1
  254. package/dist/core/settings-manager-internals.d.ts.map +1 -1
  255. package/dist/core/settings-manager-resource-accessors.d.ts.map +1 -1
  256. package/dist/core/settings-manager-ui-accessors.d.ts.map +1 -1
  257. package/dist/core/settings-manager.d.ts.map +1 -1
  258. package/dist/core/settings-merge.d.ts.map +1 -1
  259. package/dist/core/settings-storage.d.ts.map +1 -1
  260. package/dist/core/settings-types.d.ts.map +1 -1
  261. package/dist/core/skills-async.d.ts.map +1 -1
  262. package/dist/core/skills.d.ts.map +1 -1
  263. package/dist/core/slash-commands.d.ts.map +1 -1
  264. package/dist/core/source-info.d.ts.map +1 -1
  265. package/dist/core/system-prompt.d.ts.map +1 -1
  266. package/dist/core/telemetry.d.ts.map +1 -1
  267. package/dist/core/thinking-blocks.d.ts.map +1 -1
  268. package/dist/core/timings.d.ts.map +1 -1
  269. package/dist/core/tools/artifact-protocol.d.ts.map +1 -1
  270. package/dist/core/tools/artifacts.d.ts.map +1 -1
  271. package/dist/core/tools/ask-user-question/ask-user-question.d.ts.map +1 -1
  272. package/dist/core/tools/ask-user-question/config.d.ts.map +1 -1
  273. package/dist/core/tools/ask-user-question/index.d.ts.map +1 -1
  274. package/dist/core/tools/ask-user-question/state/build-questionnaire.d.ts.map +1 -1
  275. package/dist/core/tools/ask-user-question/state/inline-input.d.ts.map +1 -1
  276. package/dist/core/tools/ask-user-question/state/key-router.d.ts.map +1 -1
  277. package/dist/core/tools/ask-user-question/state/questionnaire-session.d.ts.map +1 -1
  278. package/dist/core/tools/ask-user-question/state/row-intent.d.ts.map +1 -1
  279. package/dist/core/tools/ask-user-question/state/selectors/contract.d.ts.map +1 -1
  280. package/dist/core/tools/ask-user-question/state/selectors/derivations.d.ts.map +1 -1
  281. package/dist/core/tools/ask-user-question/state/selectors/focus.d.ts.map +1 -1
  282. package/dist/core/tools/ask-user-question/state/selectors/projections.d.ts.map +1 -1
  283. package/dist/core/tools/ask-user-question/state/state-reducer.d.ts.map +1 -1
  284. package/dist/core/tools/ask-user-question/state/state.d.ts.map +1 -1
  285. package/dist/core/tools/ask-user-question/tool/format-answer.d.ts.map +1 -1
  286. package/dist/core/tools/ask-user-question/tool/response-envelope.d.ts.map +1 -1
  287. package/dist/core/tools/ask-user-question/tool/types.d.ts.map +1 -1
  288. package/dist/core/tools/ask-user-question/tool/validate-questionnaire.d.ts.map +1 -1
  289. package/dist/core/tools/ask-user-question/view/body-residual-spacer.d.ts.map +1 -1
  290. package/dist/core/tools/ask-user-question/view/component-binding.d.ts.map +1 -1
  291. package/dist/core/tools/ask-user-question/view/components/chat-row-view.d.ts.map +1 -1
  292. package/dist/core/tools/ask-user-question/view/components/multi-select-view.d.ts.map +1 -1
  293. package/dist/core/tools/ask-user-question/view/components/option-list-view.d.ts.map +1 -1
  294. package/dist/core/tools/ask-user-question/view/components/preview/markdown-content-cache.d.ts.map +1 -1
  295. package/dist/core/tools/ask-user-question/view/components/preview/preview-block-renderer.d.ts.map +1 -1
  296. package/dist/core/tools/ask-user-question/view/components/preview/preview-box-renderer.d.ts.map +1 -1
  297. package/dist/core/tools/ask-user-question/view/components/preview/preview-layout-decider.d.ts.map +1 -1
  298. package/dist/core/tools/ask-user-question/view/components/preview/preview-pane.d.ts.map +1 -1
  299. package/dist/core/tools/ask-user-question/view/components/submit-picker.d.ts.map +1 -1
  300. package/dist/core/tools/ask-user-question/view/components/tab-bar.d.ts.map +1 -1
  301. package/dist/core/tools/ask-user-question/view/components/wrapping-select.d.ts.map +1 -1
  302. package/dist/core/tools/ask-user-question/view/dialog-builder.d.ts.map +1 -1
  303. package/dist/core/tools/ask-user-question/view/props-adapter.d.ts.map +1 -1
  304. package/dist/core/tools/ask-user-question/view/stateful-view.d.ts.map +1 -1
  305. package/dist/core/tools/ask-user-question/view/tab-components.d.ts.map +1 -1
  306. package/dist/core/tools/ask-user-question/view/tab-content-strategy.d.ts.map +1 -1
  307. package/dist/core/tools/bash-async-execution.d.ts.map +1 -1
  308. package/dist/core/tools/bash-async-jobs.d.ts.map +1 -1
  309. package/dist/core/tools/bash-async-output.d.ts.map +1 -1
  310. package/dist/core/tools/bash-interceptor.d.ts.map +1 -1
  311. package/dist/core/tools/bash-leading-cd.d.ts.map +1 -1
  312. package/dist/core/tools/bash-pty-native.d.ts.map +1 -1
  313. package/dist/core/tools/bash.d.ts.map +1 -1
  314. package/dist/core/tools/block-resolver.d.ts.map +1 -1
  315. package/dist/core/tools/conflict-registry.d.ts.map +1 -1
  316. package/dist/core/tools/directory-tree.d.ts.map +1 -1
  317. package/dist/core/tools/edit-diff-preserve.d.ts.map +1 -1
  318. package/dist/core/tools/edit-diff.d.ts.map +1 -1
  319. package/dist/core/tools/edit.d.ts.map +1 -1
  320. package/dist/core/tools/fetch-url.d.ts.map +1 -1
  321. package/dist/core/tools/file-mutation-queue.d.ts.map +1 -1
  322. package/dist/core/tools/find.d.ts.map +1 -1
  323. package/dist/core/tools/glob-path-utils.d.ts.map +1 -1
  324. package/dist/core/tools/grep.d.ts.map +1 -1
  325. package/dist/core/tools/hashline-engine/apply.d.ts.map +1 -1
  326. package/dist/core/tools/hashline-engine/block.d.ts.map +1 -1
  327. package/dist/core/tools/hashline-engine/diff-preview.d.ts.map +1 -1
  328. package/dist/core/tools/hashline-engine/format.d.ts.map +1 -1
  329. package/dist/core/tools/hashline-engine/fs.d.ts.map +1 -1
  330. package/dist/core/tools/hashline-engine/index.d.ts.map +1 -1
  331. package/dist/core/tools/hashline-engine/input.d.ts.map +1 -1
  332. package/dist/core/tools/hashline-engine/messages.d.ts.map +1 -1
  333. package/dist/core/tools/hashline-engine/mismatch.d.ts.map +1 -1
  334. package/dist/core/tools/hashline-engine/normalize.d.ts.map +1 -1
  335. package/dist/core/tools/hashline-engine/parser.d.ts.map +1 -1
  336. package/dist/core/tools/hashline-engine/patcher.d.ts.map +1 -1
  337. package/dist/core/tools/hashline-engine/prefixes.d.ts.map +1 -1
  338. package/dist/core/tools/hashline-engine/recovery.d.ts.map +1 -1
  339. package/dist/core/tools/hashline-engine/snapshots.d.ts.map +1 -1
  340. package/dist/core/tools/hashline-engine/stream.d.ts.map +1 -1
  341. package/dist/core/tools/hashline-engine/tokenizer.d.ts.map +1 -1
  342. package/dist/core/tools/hashline-engine/types.d.ts.map +1 -1
  343. package/dist/core/tools/hashline.d.ts.map +1 -1
  344. package/dist/core/tools/index.d.ts.map +1 -1
  345. package/dist/core/tools/ls.d.ts.map +1 -1
  346. package/dist/core/tools/notebook.d.ts.map +1 -1
  347. package/dist/core/tools/output-accumulator.d.ts.map +1 -1
  348. package/dist/core/tools/oversized-tool-result.d.ts.map +1 -1
  349. package/dist/core/tools/path-utils.d.ts.map +1 -1
  350. package/dist/core/tools/read-document-extract.d.ts.map +1 -1
  351. package/dist/core/tools/read-selectors.d.ts.map +1 -1
  352. package/dist/core/tools/read-url.d.ts.map +1 -1
  353. package/dist/core/tools/read.d.ts.map +1 -1
  354. package/dist/core/tools/render-utils.d.ts.map +1 -1
  355. package/dist/core/tools/resource-selectors.d.ts.map +1 -1
  356. package/dist/core/tools/search-details.d.ts.map +1 -1
  357. package/dist/core/tools/search-line-ranges.d.ts.map +1 -1
  358. package/dist/core/tools/search-native.d.ts.map +1 -1
  359. package/dist/core/tools/search.d.ts.map +1 -1
  360. package/dist/core/tools/structured-output.d.ts.map +1 -1
  361. package/dist/core/tools/todos-execute.d.ts.map +1 -1
  362. package/dist/core/tools/todos-locks.d.ts.map +1 -1
  363. package/dist/core/tools/todos-model.d.ts.map +1 -1
  364. package/dist/core/tools/todos-mutations.d.ts.map +1 -1
  365. package/dist/core/tools/todos-paths.d.ts.map +1 -1
  366. package/dist/core/tools/todos-render.d.ts.map +1 -1
  367. package/dist/core/tools/todos-storage.d.ts.map +1 -1
  368. package/dist/core/tools/todos-types.d.ts.map +1 -1
  369. package/dist/core/tools/todos-types.js +1 -1
  370. package/dist/core/tools/todos-types.js.map +1 -1
  371. package/dist/core/tools/todos.d.ts.map +1 -1
  372. package/dist/core/tools/tool-definition-wrapper.d.ts.map +1 -1
  373. package/dist/core/tools/tool-definition-wrapper.js +6 -2
  374. package/dist/core/tools/tool-definition-wrapper.js.map +1 -1
  375. package/dist/core/tools/tool-limits.d.ts.map +1 -1
  376. package/dist/core/tools/truncate.d.ts.map +1 -1
  377. package/dist/core/tools/url-ip-guards.d.ts.map +1 -1
  378. package/dist/core/tools/write.d.ts.map +1 -1
  379. package/dist/core/trust-manager.d.ts.map +1 -1
  380. package/dist/core/typebox-compat.d.ts +12 -0
  381. package/dist/core/typebox-compat.d.ts.map +1 -0
  382. package/dist/core/typebox-compat.js +10 -0
  383. package/dist/core/typebox-compat.js.map +1 -0
  384. package/dist/index-extensions.d.ts.map +1 -1
  385. package/dist/index.d.ts +1 -0
  386. package/dist/index.d.ts.map +1 -1
  387. package/dist/index.js +1 -0
  388. package/dist/index.js.map +1 -1
  389. package/dist/main-app-mode.d.ts.map +1 -1
  390. package/dist/main-deferred-startup.d.ts.map +1 -1
  391. package/dist/main-early-input.d.ts.map +1 -1
  392. package/dist/main-session-options.d.ts.map +1 -1
  393. package/dist/main-session.d.ts.map +1 -1
  394. package/dist/main-stdio.d.ts.map +1 -1
  395. package/dist/main.d.ts.map +1 -1
  396. package/dist/migrations-config-values.d.ts.map +1 -1
  397. package/dist/migrations.d.ts.map +1 -1
  398. package/dist/modes/index.d.ts.map +1 -1
  399. package/dist/modes/interactive/chat-input-actions.d.ts.map +1 -1
  400. package/dist/modes/interactive/components/armin.d.ts.map +1 -1
  401. package/dist/modes/interactive/components/assistant-message.d.ts.map +1 -1
  402. package/dist/modes/interactive/components/atomic-banner.d.ts.map +1 -1
  403. package/dist/modes/interactive/components/bash-execution.d.ts.map +1 -1
  404. package/dist/modes/interactive/components/bordered-loader.d.ts.map +1 -1
  405. package/dist/modes/interactive/components/branch-summary-message.d.ts.map +1 -1
  406. package/dist/modes/interactive/components/chat-message-renderer.d.ts.map +1 -1
  407. package/dist/modes/interactive/components/chat-session-host-actions.d.ts.map +1 -1
  408. package/dist/modes/interactive/components/chat-session-host-editor.d.ts.map +1 -1
  409. package/dist/modes/interactive/components/chat-session-host-events.d.ts.map +1 -1
  410. package/dist/modes/interactive/components/chat-session-host-rendering.d.ts.map +1 -1
  411. package/dist/modes/interactive/components/chat-session-host-runtime.d.ts.map +1 -1
  412. package/dist/modes/interactive/components/chat-session-host-state.d.ts.map +1 -1
  413. package/dist/modes/interactive/components/chat-session-host-terminal-cleanup.d.ts.map +1 -1
  414. package/dist/modes/interactive/components/chat-session-host-types.d.ts.map +1 -1
  415. package/dist/modes/interactive/components/chat-session-host-utils.d.ts.map +1 -1
  416. package/dist/modes/interactive/components/chat-session-host.d.ts.map +1 -1
  417. package/dist/modes/interactive/components/chat-transcript.d.ts.map +1 -1
  418. package/dist/modes/interactive/components/compaction-boundary-message.d.ts.map +1 -1
  419. package/dist/modes/interactive/components/config-selector-list.d.ts.map +1 -1
  420. package/dist/modes/interactive/components/config-selector.d.ts.map +1 -1
  421. package/dist/modes/interactive/components/context-window-selector.d.ts.map +1 -1
  422. package/dist/modes/interactive/components/countdown-timer.d.ts.map +1 -1
  423. package/dist/modes/interactive/components/custom-editor.d.ts.map +1 -1
  424. package/dist/modes/interactive/components/custom-message.d.ts.map +1 -1
  425. package/dist/modes/interactive/components/daxnuts.d.ts.map +1 -1
  426. package/dist/modes/interactive/components/diff.d.ts.map +1 -1
  427. package/dist/modes/interactive/components/dynamic-border.d.ts.map +1 -1
  428. package/dist/modes/interactive/components/earendil-announcement.d.ts.map +1 -1
  429. package/dist/modes/interactive/components/extension-editor.d.ts.map +1 -1
  430. package/dist/modes/interactive/components/extension-input.d.ts.map +1 -1
  431. package/dist/modes/interactive/components/extension-selector.d.ts.map +1 -1
  432. package/dist/modes/interactive/components/fast-mode-selector.d.ts.map +1 -1
  433. package/dist/modes/interactive/components/footer.d.ts.map +1 -1
  434. package/dist/modes/interactive/components/index.d.ts.map +1 -1
  435. package/dist/modes/interactive/components/keybinding-hints.d.ts.map +1 -1
  436. package/dist/modes/interactive/components/login-dialog.d.ts.map +1 -1
  437. package/dist/modes/interactive/components/model-selector.d.ts.map +1 -1
  438. package/dist/modes/interactive/components/oauth-selector.d.ts.map +1 -1
  439. package/dist/modes/interactive/components/scoped-models-selector.d.ts.map +1 -1
  440. package/dist/modes/interactive/components/session-selector-delete.d.ts.map +1 -1
  441. package/dist/modes/interactive/components/session-selector-header.d.ts.map +1 -1
  442. package/dist/modes/interactive/components/session-selector-list.d.ts.map +1 -1
  443. package/dist/modes/interactive/components/session-selector-search.d.ts.map +1 -1
  444. package/dist/modes/interactive/components/session-selector-tree.d.ts.map +1 -1
  445. package/dist/modes/interactive/components/session-selector-types.d.ts.map +1 -1
  446. package/dist/modes/interactive/components/session-selector-utils.d.ts.map +1 -1
  447. package/dist/modes/interactive/components/session-selector.d.ts.map +1 -1
  448. package/dist/modes/interactive/components/settings-selector-handlers.d.ts.map +1 -1
  449. package/dist/modes/interactive/components/settings-selector-items.d.ts.map +1 -1
  450. package/dist/modes/interactive/components/settings-selector-options.d.ts.map +1 -1
  451. package/dist/modes/interactive/components/settings-selector-submenus.d.ts.map +1 -1
  452. package/dist/modes/interactive/components/settings-selector-types.d.ts.map +1 -1
  453. package/dist/modes/interactive/components/settings-selector.d.ts.map +1 -1
  454. package/dist/modes/interactive/components/show-images-selector.d.ts.map +1 -1
  455. package/dist/modes/interactive/components/skill-invocation-message.d.ts.map +1 -1
  456. package/dist/modes/interactive/components/theme-selector.d.ts.map +1 -1
  457. package/dist/modes/interactive/components/thinking-selector.d.ts.map +1 -1
  458. package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
  459. package/dist/modes/interactive/components/tree-selector-component.d.ts.map +1 -1
  460. package/dist/modes/interactive/components/tree-selector-content.d.ts.map +1 -1
  461. package/dist/modes/interactive/components/tree-selector-help.d.ts.map +1 -1
  462. package/dist/modes/interactive/components/tree-selector-label-input.d.ts.map +1 -1
  463. package/dist/modes/interactive/components/tree-selector-list.d.ts.map +1 -1
  464. package/dist/modes/interactive/components/tree-selector-model.d.ts.map +1 -1
  465. package/dist/modes/interactive/components/tree-selector-types.d.ts.map +1 -1
  466. package/dist/modes/interactive/components/tree-selector-viewport.d.ts.map +1 -1
  467. package/dist/modes/interactive/components/tree-selector.d.ts.map +1 -1
  468. package/dist/modes/interactive/components/trust-selector.d.ts.map +1 -1
  469. package/dist/modes/interactive/components/user-message-selector.d.ts.map +1 -1
  470. package/dist/modes/interactive/components/user-message.d.ts.map +1 -1
  471. package/dist/modes/interactive/components/visual-truncate.d.ts.map +1 -1
  472. package/dist/modes/interactive/components/working-status.d.ts.map +1 -1
  473. package/dist/modes/interactive/interactive-agent-events.d.ts.map +1 -1
  474. package/dist/modes/interactive/interactive-auth-login.d.ts.map +1 -1
  475. package/dist/modes/interactive/interactive-auth-routing.d.ts.map +1 -1
  476. package/dist/modes/interactive/interactive-autocomplete.d.ts.map +1 -1
  477. package/dist/modes/interactive/interactive-bash-compact.d.ts.map +1 -1
  478. package/dist/modes/interactive/interactive-child-ordering.d.ts.map +1 -1
  479. package/dist/modes/interactive/interactive-deferred-startup.d.ts.map +1 -1
  480. package/dist/modes/interactive/interactive-editor-actions.d.ts.map +1 -1
  481. package/dist/modes/interactive/interactive-extension-context.d.ts.map +1 -1
  482. package/dist/modes/interactive/interactive-extension-custom-ui.d.ts.map +1 -1
  483. package/dist/modes/interactive/interactive-extension-dialogs.d.ts.map +1 -1
  484. package/dist/modes/interactive/interactive-extension-runtime.d.ts.map +1 -1
  485. package/dist/modes/interactive/interactive-extension-widgets.d.ts.map +1 -1
  486. package/dist/modes/interactive/interactive-hotkeys-debug.d.ts.map +1 -1
  487. package/dist/modes/interactive/interactive-input-handling.d.ts.map +1 -1
  488. package/dist/modes/interactive/interactive-mode-base.d.ts.map +1 -1
  489. package/dist/modes/interactive/interactive-mode-deps.d.ts.map +1 -1
  490. package/dist/modes/interactive/interactive-mode-helpers.d.ts.map +1 -1
  491. package/dist/modes/interactive/interactive-mode-surface.d.ts.map +1 -1
  492. package/dist/modes/interactive/interactive-mode-types.d.ts.map +1 -1
  493. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  494. package/dist/modes/interactive/interactive-model-routing.d.ts.map +1 -1
  495. package/dist/modes/interactive/interactive-onboarding.d.ts.map +1 -1
  496. package/dist/modes/interactive/interactive-process-lifecycle.d.ts.map +1 -1
  497. package/dist/modes/interactive/interactive-queueing.d.ts.map +1 -1
  498. package/dist/modes/interactive/interactive-render-chat.d.ts.map +1 -1
  499. package/dist/modes/interactive/interactive-resource-disclosure.d.ts.map +1 -1
  500. package/dist/modes/interactive/interactive-resource-paths.d.ts.map +1 -1
  501. package/dist/modes/interactive/interactive-resource-rendering.d.ts.map +1 -1
  502. package/dist/modes/interactive/interactive-selectors.d.ts.map +1 -1
  503. package/dist/modes/interactive/interactive-session-routing.d.ts.map +1 -1
  504. package/dist/modes/interactive/interactive-session-runtime.d.ts.map +1 -1
  505. package/dist/modes/interactive/interactive-slash-commands.d.ts.map +1 -1
  506. package/dist/modes/interactive/interactive-startup.d.ts.map +1 -1
  507. package/dist/modes/interactive/model-search.d.ts.map +1 -1
  508. package/dist/modes/interactive/theme/color-utils.d.ts.map +1 -1
  509. package/dist/modes/interactive/theme/export-colors.d.ts.map +1 -1
  510. package/dist/modes/interactive/theme/global-theme.d.ts.map +1 -1
  511. package/dist/modes/interactive/theme/terminal-detection.d.ts.map +1 -1
  512. package/dist/modes/interactive/theme/theme-class.d.ts.map +1 -1
  513. package/dist/modes/interactive/theme/theme-controller.d.ts.map +1 -1
  514. package/dist/modes/interactive/theme/theme-loading.d.ts.map +1 -1
  515. package/dist/modes/interactive/theme/theme-parse.d.ts.map +1 -1
  516. package/dist/modes/interactive/theme/theme-schema.d.ts.map +1 -1
  517. package/dist/modes/interactive/theme/theme.d.ts.map +1 -1
  518. package/dist/modes/interactive/theme/tui-theme.d.ts.map +1 -1
  519. package/dist/modes/interactive/whimsical-messages.d.ts.map +1 -1
  520. package/dist/modes/print-mode.d.ts.map +1 -1
  521. package/dist/modes/rpc/jsonl.d.ts.map +1 -1
  522. package/dist/modes/rpc/rpc-client.d.ts.map +1 -1
  523. package/dist/modes/rpc/rpc-command-handler.d.ts.map +1 -1
  524. package/dist/modes/rpc/rpc-extension-ui.d.ts.map +1 -1
  525. package/dist/modes/rpc/rpc-input.d.ts.map +1 -1
  526. package/dist/modes/rpc/rpc-mode.d.ts.map +1 -1
  527. package/dist/modes/rpc/rpc-responses.d.ts.map +1 -1
  528. package/dist/modes/rpc/rpc-session-binding.d.ts.map +1 -1
  529. package/dist/modes/rpc/rpc-types.d.ts.map +1 -1
  530. package/dist/package-manager-cli-parser.d.ts.map +1 -1
  531. package/dist/package-manager-cli.d.ts.map +1 -1
  532. package/dist/rpc-entry.d.ts.map +1 -1
  533. package/dist/utils/ansi.d.ts.map +1 -1
  534. package/dist/utils/changelog.d.ts.map +1 -1
  535. package/dist/utils/child-process.d.ts.map +1 -1
  536. package/dist/utils/clipboard-image.d.ts.map +1 -1
  537. package/dist/utils/clipboard-native.d.ts.map +1 -1
  538. package/dist/utils/clipboard.d.ts.map +1 -1
  539. package/dist/utils/deprecation.d.ts.map +1 -1
  540. package/dist/utils/event-loop.d.ts.map +1 -1
  541. package/dist/utils/exif-orientation.d.ts.map +1 -1
  542. package/dist/utils/frontmatter.d.ts.map +1 -1
  543. package/dist/utils/fs-watch.d.ts.map +1 -1
  544. package/dist/utils/git-env.d.ts.map +1 -1
  545. package/dist/utils/git.d.ts.map +1 -1
  546. package/dist/utils/html.d.ts.map +1 -1
  547. package/dist/utils/image-convert.d.ts.map +1 -1
  548. package/dist/utils/image-process.d.ts.map +1 -1
  549. package/dist/utils/image-resize-core.d.ts.map +1 -1
  550. package/dist/utils/image-resize-worker.d.ts.map +1 -1
  551. package/dist/utils/image-resize.d.ts.map +1 -1
  552. package/dist/utils/json.d.ts.map +1 -1
  553. package/dist/utils/markit.d.ts.map +1 -1
  554. package/dist/utils/mime.d.ts.map +1 -1
  555. package/dist/utils/module-require.d.ts.map +1 -1
  556. package/dist/utils/open-browser.d.ts.map +1 -1
  557. package/dist/utils/paths.d.ts.map +1 -1
  558. package/dist/utils/photon.d.ts.map +1 -1
  559. package/dist/utils/pi-user-agent.d.ts.map +1 -1
  560. package/dist/utils/shell.d.ts.map +1 -1
  561. package/dist/utils/sleep.d.ts.map +1 -1
  562. package/dist/utils/split-launcher.d.ts.map +1 -1
  563. package/dist/utils/syntax-highlight.d.ts.map +1 -1
  564. package/dist/utils/tools-manager.d.ts.map +1 -1
  565. package/dist/utils/version-check.d.ts.map +1 -1
  566. package/dist/utils/windows-self-update.d.ts.map +1 -1
  567. package/docs/custom-provider.md +7 -1
  568. package/docs/extensions.md +19 -4
  569. package/docs/subagents.md +2 -0
  570. package/docs/workflows.md +2 -2
  571. package/examples/extensions/README.md +3 -1
  572. package/examples/extensions/subagent/schemas.ts +1 -1
  573. package/examples/extensions/tic-tac-toe.ts +1 -2
  574. package/examples/extensions/todo.ts +1 -2
  575. package/npm-shrinkwrap.json +214 -98
  576. package/package.json +12 -12
@@ -1 +1 @@
1
- {"version":3,"file":"apply.d.ts","sourceRoot":"","sources":["../../../../src/core/tools/hashline-engine/apply.ts"],"names":[],"mappings":"AAaA,OAAO,KAAK,EAAU,WAAW,EAAU,IAAI,EAAE,MAAM,YAAY,CAAC;AAsHpE,iFAAiF;AACjF,eAAO,MAAM,oBAAoB,QAAyB,CAAC;AAklB3D;;;;;GAKG;AACH,wBAAgB,UAAU,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,SAAS,IAAI,EAAE,GAAG,WAAW,CAqG5E","sourcesContent":["// @generated vendored verbatim from oh-my-pi packages/hashline @ 15b5c1397fc -- DO NOT EDIT.\n// Parity source for the Atomic hashline edit engine (issue #1483); adapted only for Atomic's Node runtime (relative imports, Bun->Node host calls, erasable constructor syntax).\n/**\n * Apply a parsed list of {@link Edit}s to a text body and return the\n * post-edit lines plus any diagnostic warnings. Pure function: no FS, no\n * mutation of the input.\n *\n * Replacement groups are first normalized by {@link repairReplacementBoundaries},\n * which absorbs common model mistakes where a payload restates unchanged range\n * boundaries or duplicates/drops structural closers.\n */\nimport { afterInsertLandingShiftWarning, blockInsertLandingShiftWarning, UNRESOLVED_BLOCK_INTERNAL } from \"./messages.js\";\nimport { cloneCursor } from \"./tokenizer.js\";\nimport type { Anchor, ApplyResult, Cursor, Edit } from \"./types.js\";\n\ntype LineOrigin = \"original\" | \"insert\" | \"replacement\";\n\ntype InsertEdit = Extract<Edit, { kind: \"insert\" }>;\ntype DeleteEdit = Extract<Edit, { kind: \"delete\" }>;\ntype AppliedEdit = InsertEdit | DeleteEdit;\n\ninterface IndexedEdit {\n\tedit: AppliedEdit;\n\tidx: number;\n}\n\nfunction isReplacementInsert(edit: Edit): edit is InsertEdit & { mode: \"replacement\" } {\n\treturn edit.kind === \"insert\" && edit.mode === \"replacement\";\n}\n\nfunction getCursorAnchors(cursor: Cursor): Anchor[] {\n\treturn cursor.kind === \"before_anchor\" || cursor.kind === \"after_anchor\" ? [cursor.anchor] : [];\n}\n\nfunction getEditAnchors(edit: AppliedEdit): Anchor[] {\n\tif (edit.kind === \"delete\") return [edit.anchor];\n\treturn getCursorAnchors(edit.cursor);\n}\n\nfunction trailingPhantomLine(fileLines: readonly string[]): number {\n\t// `split(\"\\n\")` on a newline-terminated file yields a trailing \"\" sentinel.\n\t// It is addressable for inserts (append-past-end), but it is not real\n\t// content. Deleting it only strips the file's final newline, so ignore delete\n\t// edits that land there; inclusive ranges ending at EOF then do the intended\n\t// thing and delete through the last concrete line.\n\treturn fileLines.length > 1 && fileLines[fileLines.length - 1] === \"\" ? fileLines.length : 0;\n}\n\nfunction dropTrailingPhantomDeletes(edits: AppliedEdit[], fileLines: readonly string[]): AppliedEdit[] {\n\tconst phantomLine = trailingPhantomLine(fileLines);\n\tif (phantomLine === 0) return edits;\n\treturn edits.filter(edit => edit.kind !== \"delete\" || edit.anchor.line !== phantomLine);\n}\n\n/**\n * Verify every anchored edit points at an existing line. File-version binding is\n * checked once per section via the header hash before this function runs.\n */\nfunction validateLineBounds(edits: readonly AppliedEdit[], fileLines: readonly string[]): void {\n\tfor (const edit of edits) {\n\t\tfor (const anchor of getEditAnchors(edit)) {\n\t\t\tif (anchor.line < 1 || anchor.line > fileLines.length) {\n\t\t\t\tthrow new Error(`Line ${anchor.line} does not exist (file has ${fileLines.length} lines)`);\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunction cloneAppliedEdit(edit: AppliedEdit, index: number): AppliedEdit {\n\tif (edit.kind === \"delete\") return { ...edit, anchor: { ...edit.anchor }, index };\n\treturn { ...edit, cursor: cloneCursor(edit.cursor), index };\n}\n\nfunction insertAtStart(fileLines: string[], lineOrigins: LineOrigin[], lines: string[]): void {\n\tif (lines.length === 0) return;\n\tconst origins = lines.map((): LineOrigin => \"insert\");\n\tif (fileLines.length === 1 && fileLines[0] === \"\") {\n\t\tfileLines.splice(0, 1, ...lines);\n\t\tlineOrigins.splice(0, 1, ...origins);\n\t\treturn;\n\t}\n\tfileLines.splice(0, 0, ...lines);\n\tlineOrigins.splice(0, 0, ...origins);\n}\n\nfunction insertAtEnd(fileLines: string[], lineOrigins: LineOrigin[], lines: string[]): number | undefined {\n\tif (lines.length === 0) return undefined;\n\tconst origins = lines.map((): LineOrigin => \"insert\");\n\tif (fileLines.length === 1 && fileLines[0] === \"\") {\n\t\tfileLines.splice(0, 1, ...lines);\n\t\tlineOrigins.splice(0, 1, ...origins);\n\t\treturn 1;\n\t}\n\tconst hasTrailingNewline = fileLines.length > 0 && fileLines[fileLines.length - 1] === \"\";\n\tconst insertIndex = hasTrailingNewline ? fileLines.length - 1 : fileLines.length;\n\tfileLines.splice(insertIndex, 0, ...lines);\n\tlineOrigins.splice(insertIndex, 0, ...origins);\n\treturn insertIndex + 1;\n}\n\nfunction bucketAnchorEditsByLine(edits: IndexedEdit[]): Map<number, IndexedEdit[]> {\n\tconst byLine = new Map<number, IndexedEdit[]>();\n\tfor (const entry of edits) {\n\t\tconst line =\n\t\t\tentry.edit.kind === \"delete\"\n\t\t\t\t? entry.edit.anchor.line\n\t\t\t\t: entry.edit.cursor.kind === \"before_anchor\" || entry.edit.cursor.kind === \"after_anchor\"\n\t\t\t\t\t? entry.edit.cursor.anchor.line\n\t\t\t\t\t: 0;\n\t\tconst bucket = byLine.get(line);\n\t\tif (bucket) bucket.push(entry);\n\t\telse byLine.set(line, [entry]);\n\t}\n\treturn byLine;\n}\n\n// ═══════════════════════════════════════════════════════════════════════════\n// Replacement-boundary repair\n//\n// Models routinely miscount a replacement range's edges. Sometimes the payload\n// re-states unchanged lines that still live on both sides of the range\n// (duplicating a function header and final statement); sometimes it only\n// re-states or omits a structural closer, which leaves delimiter balance broken.\n//\n// A balance-neutral boundary-echo repair fires only when both the leading and\n// trailing payload edges are exact copies of the surviving lines outside the\n// range. One-sided content echoes are left alone unless delimiter-balance repair\n// proves they are duplicated structural boundaries. This preserves intended\n// duplicate statements while absorbing the common \"body includes the unchanged\n// wrapper\" mistake.\n\n/** A line that is nothing but closing delimiters: `}`, `)`, `];`, `})`, `},`. */\nexport const STRUCTURAL_CLOSER_RE = /^\\s*[)\\]}]+[;,]?\\s*$/;\n\ninterface DelimiterBalance {\n\tparen: number;\n\tbracket: number;\n\tbrace: number;\n}\n\n/**\n * Net `()` / `[]` / `{}` delta across `lines`, skipping delimiters inside line\n * comments (`//`), block comments, and string/template literals. Block-comment\n * and backtick-template state carry across lines; `\"` / `'` reset at EOL since\n * they cannot span lines. Deliberately language-light: constructs it cannot\n * classify (e.g. regex literals) are counted naively, which can only suppress a\n * repair (the safe direction), never force one.\n */\nfunction computeDelimiterBalance(lines: readonly string[]): DelimiterBalance {\n\tconst balance: DelimiterBalance = { paren: 0, bracket: 0, brace: 0 };\n\tlet inBlockComment = false;\n\tlet quote = \"\";\n\tfor (const line of lines) {\n\t\tfor (let i = 0; i < line.length; i++) {\n\t\t\tconst ch = line[i];\n\t\t\tif (inBlockComment) {\n\t\t\t\tif (ch === \"*\" && line[i + 1] === \"/\") {\n\t\t\t\t\tinBlockComment = false;\n\t\t\t\t\ti++;\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (quote) {\n\t\t\t\tif (ch === \"\\\\\") i++;\n\t\t\t\telse if (ch === quote) quote = \"\";\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (ch === '\"' || ch === \"'\" || ch === \"`\") {\n\t\t\t\tquote = ch;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (ch === \"/\" && line[i + 1] === \"/\") break;\n\t\t\tif (ch === \"/\" && line[i + 1] === \"*\") {\n\t\t\t\tinBlockComment = true;\n\t\t\t\ti++;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tswitch (ch) {\n\t\t\t\tcase \"(\":\n\t\t\t\t\tbalance.paren++;\n\t\t\t\t\tbreak;\n\t\t\t\tcase \")\":\n\t\t\t\t\tbalance.paren--;\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"[\":\n\t\t\t\t\tbalance.bracket++;\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"]\":\n\t\t\t\t\tbalance.bracket--;\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"{\":\n\t\t\t\t\tbalance.brace++;\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"}\":\n\t\t\t\t\tbalance.brace--;\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\t// `\"` / `'` cannot span lines; only backtick templates and block comments do.\n\t\tif (quote === '\"' || quote === \"'\") quote = \"\";\n\t}\n\treturn balance;\n}\n\nfunction balanceDelta(a: DelimiterBalance, b: DelimiterBalance): DelimiterBalance {\n\treturn { paren: a.paren - b.paren, bracket: a.bracket - b.bracket, brace: a.brace - b.brace };\n}\n\nfunction balanceNegate(a: DelimiterBalance): DelimiterBalance {\n\treturn { paren: -a.paren, bracket: -a.bracket, brace: -a.brace };\n}\n\nfunction balanceEqual(a: DelimiterBalance, b: DelimiterBalance): boolean {\n\treturn a.paren === b.paren && a.bracket === b.bracket && a.brace === b.brace;\n}\n\nfunction balanceIsZero(a: DelimiterBalance): boolean {\n\treturn a.paren === 0 && a.bracket === 0 && a.brace === 0;\n}\n\ninterface ReplacementGroup {\n\t/** Positions in the edit array of the payload inserts, in payload order. */\n\tinsertIndices: number[];\n\t/** Positions in the edit array of the range deletes, ascending by line. */\n\tdeleteIndices: number[];\n\tpayload: string[];\n\t/** First deleted line (1-indexed). */\n\tstartLine: number;\n\t/** Last deleted line (1-indexed). */\n\tendLine: number;\n}\n\n/**\n * Detect a replacement group starting at `start`: a run of `before_anchor`\n * replacement inserts sharing one source op line, immediately followed by the\n * contiguous range deletes for that same op. Mirrors how the parser lowers an\n * `replace N..M:` hunk with a body.\n */\nfunction findReplacementGroup(edits: readonly AppliedEdit[], start: number): ReplacementGroup | undefined {\n\tconst first = edits[start];\n\tif (first?.kind !== \"insert\" || first.mode !== \"replacement\" || first.cursor.kind !== \"before_anchor\") {\n\t\treturn undefined;\n\t}\n\tconst { lineNum } = first;\n\tconst anchorLine = first.cursor.anchor.line;\n\tconst insertIndices: number[] = [];\n\tconst payload: string[] = [];\n\tlet i = start;\n\tfor (; i < edits.length; i++) {\n\t\tconst edit = edits[i];\n\t\tif (edit.kind !== \"insert\" || edit.mode !== \"replacement\" || edit.lineNum !== lineNum) break;\n\t\tif (edit.cursor.kind !== \"before_anchor\" || edit.cursor.anchor.line !== anchorLine) break;\n\t\tinsertIndices.push(i);\n\t\tpayload.push(edit.text);\n\t}\n\tconst deleteIndices: number[] = [];\n\tlet expectedLine = anchorLine;\n\tfor (; i < edits.length; i++) {\n\t\tconst edit = edits[i];\n\t\tif (edit.kind !== \"delete\" || edit.lineNum !== lineNum || edit.anchor.line !== expectedLine) break;\n\t\tdeleteIndices.push(i);\n\t\texpectedLine++;\n\t}\n\tif (deleteIndices.length === 0) return undefined;\n\treturn {\n\t\tinsertIndices,\n\t\tdeleteIndices,\n\t\tpayload,\n\t\tstartLine: anchorLine,\n\t\tendLine: anchorLine + deleteIndices.length - 1,\n\t};\n}\n\n/**\n * Largest `k` such that the payload's last `k` lines exactly equal the `k`\n * surviving file lines just below the range AND dropping them zeroes `delta`.\n * Requires a non-zero `delta`: a zero-balance candidate can never account for\n * the imbalance, so intentional duplicates of ordinary statements stay intact,\n * while duplicated structural lines (closers like `});`, openers like `foo(`)\n * are dropped when they exactly explain the imbalance.\n */\nfunction findDuplicateSuffix(group: ReplacementGroup, fileLines: readonly string[], delta: DelimiterBalance): number {\n\tif (balanceIsZero(delta)) return 0;\n\tconst { payload, endLine } = group;\n\tconst maxK = Math.min(payload.length, fileLines.length - endLine);\n\tfor (let k = maxK; k >= 1; k--) {\n\t\tlet matches = true;\n\t\tfor (let t = 0; t < k; t++) {\n\t\t\tif (payload[payload.length - k + t] !== fileLines[endLine + t]) {\n\t\t\t\tmatches = false;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (!matches) continue;\n\t\tif (balanceEqual(computeDelimiterBalance(payload.slice(payload.length - k)), delta)) return k;\n\t}\n\treturn 0;\n}\n\n/**\n * Largest `j` such that the payload's first `j` lines exactly equal the `j`\n * surviving file lines just above the range AND dropping them zeroes `delta`.\n * Requires a non-zero `delta`; see {@link findDuplicateSuffix}.\n */\nfunction findDuplicatePrefix(group: ReplacementGroup, fileLines: readonly string[], delta: DelimiterBalance): number {\n\tif (balanceIsZero(delta)) return 0;\n\tconst { payload, startLine } = group;\n\tconst maxJ = Math.min(payload.length, startLine - 1);\n\tfor (let j = maxJ; j >= 1; j--) {\n\t\tlet matches = true;\n\t\tfor (let t = 0; t < j; t++) {\n\t\t\tif (payload[t] !== fileLines[startLine - 1 - j + t]) {\n\t\t\t\tmatches = false;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (!matches) continue;\n\t\tif (balanceEqual(computeDelimiterBalance(payload.slice(0, j)), delta)) return j;\n\t}\n\treturn 0;\n}\n\n/**\n * Smallest `m` such that the range's last `m` deleted lines are all pure\n * structural closers and sparing them (keeping instead of deleting) zeroes\n * `delta`. The mirror mistake: a range that swallows a closing delimiter the\n * payload never restates.\n */\nfunction findDroppedSuffixClosers(\n\tgroup: ReplacementGroup,\n\tfileLines: readonly string[],\n\tdelta: DelimiterBalance,\n): number {\n\tconst wanted = balanceNegate(delta);\n\tconst maxM = group.deleteIndices.length;\n\tfor (let m = 1; m <= maxM; m++) {\n\t\tif (!STRUCTURAL_CLOSER_RE.test(fileLines[group.endLine - m] ?? \"\")) break;\n\t\tif (balanceEqual(computeDelimiterBalance(fileLines.slice(group.endLine - m, group.endLine)), wanted)) return m;\n\t}\n\treturn 0;\n}\n\ninterface BoundaryEcho {\n\tleading: number;\n\ttrailing: number;\n}\n\nfunction hasNonWhitespace(text: string): boolean {\n\tfor (let i = 0; i < text.length; i++) {\n\t\tconst code = text.charCodeAt(i);\n\t\tif (code !== 9 && code !== 10 && code !== 11 && code !== 12 && code !== 13 && code !== 32) return true;\n\t}\n\treturn false;\n}\n\nfunction countDuplicateLeadingBoundaryLines(group: ReplacementGroup, fileLines: readonly string[]): number {\n\tconst { payload, startLine } = group;\n\tconst max = Math.min(payload.length, startLine - 1);\n\tfor (let count = max; count >= 1; count--) {\n\t\tlet matches = true;\n\t\tlet hasContent = false;\n\t\tfor (let offset = 0; offset < count; offset++) {\n\t\t\tconst line = payload[offset];\n\t\t\tif (line !== fileLines[startLine - 1 - count + offset]) {\n\t\t\t\tmatches = false;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\thasContent ||= hasNonWhitespace(line);\n\t\t}\n\t\tif (matches && hasContent) return count;\n\t}\n\treturn 0;\n}\n\nfunction countDuplicateTrailingBoundaryLines(group: ReplacementGroup, fileLines: readonly string[]): number {\n\tconst { payload, endLine } = group;\n\tconst max = Math.min(payload.length, fileLines.length - endLine);\n\tfor (let count = max; count >= 1; count--) {\n\t\tlet matches = true;\n\t\tlet hasContent = false;\n\t\tfor (let offset = 0; offset < count; offset++) {\n\t\t\tconst line = payload[payload.length - count + offset];\n\t\t\tif (line !== fileLines[endLine + offset]) {\n\t\t\t\tmatches = false;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\thasContent ||= hasNonWhitespace(line);\n\t\t}\n\t\tif (matches && hasContent) return count;\n\t}\n\treturn 0;\n}\n\nfunction findBoundaryEcho(group: ReplacementGroup, fileLines: readonly string[]): BoundaryEcho | undefined {\n\tconst leadingMax = countDuplicateLeadingBoundaryLines(group, fileLines);\n\tif (leadingMax === 0) return undefined;\n\tconst trailingMax = countDuplicateTrailingBoundaryLines(group, fileLines);\n\tif (trailingMax === 0) return undefined;\n\t// Bail when every payload line could be claimed by a boundary echo: any\n\t// repair would strip explicit replacement content with no signal that the\n\t// payload was a mistake rather than an intentional duplication.\n\tif (leadingMax + trailingMax >= group.payload.length) return undefined;\n\t// Balance-neutrality guard (see header comment): the dropped echo lines must\n\t// either be delimiter-neutral on their own or exactly cancel the payload/range\n\t// balance delta. In brace-heavy code where bare closer lines repeat, an\n\t// \"echo\" that shifts delimiter balance is structural content the payload\n\t// placed intentionally — stripping it would corrupt the result.\n\tconst leadingBalance = computeDelimiterBalance(group.payload.slice(0, leadingMax));\n\tconst trailingBalance = computeDelimiterBalance(group.payload.slice(group.payload.length - trailingMax));\n\tconst droppedBalance = balanceDelta(leadingBalance, balanceNegate(trailingBalance));\n\tif (!balanceIsZero(droppedBalance)) {\n\t\tconst delta = balanceDelta(\n\t\t\tcomputeDelimiterBalance(group.payload),\n\t\t\tcomputeDelimiterBalance(fileLines.slice(group.startLine - 1, group.endLine)),\n\t\t);\n\t\tif (!balanceEqual(droppedBalance, delta)) return undefined;\n\t}\n\treturn { leading: leadingMax, trailing: trailingMax };\n}\n\nfunction describeBoundaryEchoRepair(group: ReplacementGroup, echo: BoundaryEcho): string {\n\treturn (\n\t\t`Auto-repaired a replacement boundary echo at line ${group.startLine}: ` +\n\t\t`dropped ${echo.leading} leading and ${echo.trailing} trailing payload line(s) already present outside the range. ` +\n\t\t`Issue the payload as the final desired content for the selected range only — never restate unchanged lines bordering the range.`\n\t);\n}\n\nfunction describeBoundaryRepair(group: ReplacementGroup, action: string): string {\n\treturn (\n\t\t`Auto-repaired a delimiter-balance mismatch in the replacement at line ${group.startLine}: ${action}. ` +\n\t\t`Issue the payload as the final desired content only — never restate or omit a closing bracket bordering the range.`\n\t);\n}\n\n/**\n * Normalize replacement groups so common off-by-one boundaries do not duplicate\n * unchanged surrounding lines or structural closers. Returns the repaired edit\n * list plus one warning per repaired group.\n */\nfunction repairReplacementBoundaries(\n\tedits: readonly AppliedEdit[],\n\tfileLines: readonly string[],\n): {\n\tedits: AppliedEdit[];\n\twarnings: string[];\n} {\n\tconst out: AppliedEdit[] = [];\n\tconst warnings: string[] = [];\n\tlet i = 0;\n\twhile (i < edits.length) {\n\t\tconst group = findReplacementGroup(edits, i);\n\t\tif (!group) {\n\t\t\tout.push(edits[i]);\n\t\t\ti++;\n\t\t\tcontinue;\n\t\t}\n\t\tconst inserts = group.insertIndices.map(idx => edits[idx]);\n\t\tconst deletes = group.deleteIndices.map(idx => edits[idx]);\n\t\ti = group.deleteIndices[group.deleteIndices.length - 1] + 1;\n\n\t\tconst boundaryEcho = findBoundaryEcho(group, fileLines);\n\t\tif (boundaryEcho) {\n\t\t\twarnings.push(describeBoundaryEchoRepair(group, boundaryEcho));\n\t\t\tout.push(...inserts.slice(boundaryEcho.leading, inserts.length - boundaryEcho.trailing), ...deletes);\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst delta = balanceDelta(\n\t\t\tcomputeDelimiterBalance(group.payload),\n\t\t\tcomputeDelimiterBalance(fileLines.slice(group.startLine - 1, group.endLine)),\n\t\t);\n\t\tif (balanceIsZero(delta)) {\n\t\t\tout.push(...inserts, ...deletes);\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst dupSuffix = findDuplicateSuffix(group, fileLines, delta);\n\t\tif (dupSuffix > 0) {\n\t\t\twarnings.push(\n\t\t\t\tdescribeBoundaryRepair(\n\t\t\t\t\tgroup,\n\t\t\t\t\t`dropped ${dupSuffix} duplicated trailing payload line(s) already present below the range`,\n\t\t\t\t),\n\t\t\t);\n\t\t\tout.push(...inserts.slice(0, inserts.length - dupSuffix), ...deletes);\n\t\t\tcontinue;\n\t\t}\n\t\tconst dupPrefix = findDuplicatePrefix(group, fileLines, delta);\n\t\tif (dupPrefix > 0) {\n\t\t\twarnings.push(\n\t\t\t\tdescribeBoundaryRepair(\n\t\t\t\t\tgroup,\n\t\t\t\t\t`dropped ${dupPrefix} duplicated leading payload line(s) already present above the range`,\n\t\t\t\t),\n\t\t\t);\n\t\t\tout.push(...inserts.slice(dupPrefix), ...deletes);\n\t\t\tcontinue;\n\t\t}\n\t\tconst droppedClosers = findDroppedSuffixClosers(group, fileLines, delta);\n\t\tif (droppedClosers > 0) {\n\t\t\twarnings.push(\n\t\t\t\tdescribeBoundaryRepair(\n\t\t\t\t\tgroup,\n\t\t\t\t\t`kept ${droppedClosers} structural closing line(s) the range deleted without restating`,\n\t\t\t\t),\n\t\t\t);\n\t\t\tout.push(...inserts, ...deletes.slice(0, deletes.length - droppedClosers));\n\t\t\tcontinue;\n\t\t}\n\t\tout.push(...inserts, ...deletes);\n\t}\n\treturn { edits: out, warnings };\n}\n\n// ═══════════════════════════════════════════════════════════════════════════\n// After-insert landing correction\n//\n// The body rows of an `insert after N:` hunk carry an implicit depth claim:\n// their leading indentation says how deep the author expects the new lines\n// to sit. Two corrections share that claim, in opposite directions:\n//\n// Outward (any after-insert): when the depth is shallower than line N itself,\n// the hunk is inserting a sibling of some enclosing construct while anchored\n// inside it — the common shape is anchoring on the last statement of a block\n// and writing the body at the parent's depth. Sliding the landing point\n// forward across the structural closer lines that follow (and nothing else —\n// content lines are never crossed) places the body at the depth its\n// indentation names.\n//\n// Inward (block-lowered inserts only): `insert after block N:` anchors on the\n// resolved block's closing line, but a body indented deeper than that closer\n// claims a depth inside the block — the common misreading of the op as\n// \"append at the end of block N's body\". Sliding the landing point backward\n// across the block's trailing closer lines places the body inside, at its\n// claimed depth. Scoped to block-lowered inserts because there the author\n// named the opener and never saw the closer; a plain `insert after M:` on a\n// closer line stays literal (the escape hatch for genuinely-after content\n// such as method-chain continuations).\n//\n// Both shifts are deliberately conservative: they fire only when the body\n// and anchor indentation are comparable (one is a prefix of the other),\n// cross only pure closing-delimiter lines, stop as soon as depth matches the\n// body's claim, and are abandoned when any other edit in the patch targets a\n// crossed line. Every shift is reported as a warning so the author can\n// re-issue when the original landing was intended.\n\n/** Leading run of tabs and spaces. */\nfunction leadingIndent(line: string): string {\n\tlet end = 0;\n\twhile (end < line.length) {\n\t\tconst code = line.charCodeAt(end);\n\t\tif (code !== 9 && code !== 32) break;\n\t\tend++;\n\t}\n\treturn line.slice(0, end);\n}\n\n/** `deeper` strictly extends `shallower` (same indent style, more depth). */\nfunction isIndentDeeper(deeper: string, shallower: string): boolean {\n\treturn deeper.length > shallower.length && deeper.startsWith(shallower);\n}\n\ninterface AfterInsertGroup {\n\t/** Anchor line shared by every insert row of the hunk. */\n\tanchor: number;\n\t/** Indices into the edit list, in patch order. */\n\tmembers: number[];\n\t/** First line of the resolved block when lowered from `insert after block N:`. */\n\tblockStart?: number;\n}\n\n/**\n * Depth of an after-insert hunk's body: the shallowest indentation across its\n * non-blank rows. Returns `undefined` when no depth claim can be made — an\n * all-blank or all-closer body, or rows whose indentation styles are not\n * mutually comparable (tabs vs spaces).\n */\nfunction bodyTargetIndent(rows: readonly string[]): string | undefined {\n\tconst nonBlank = rows.filter(hasNonWhitespace);\n\tif (nonBlank.length === 0) return undefined;\n\t// A body of pure closers re-balances delimiters; it claims no depth.\n\tif (nonBlank.every(row => STRUCTURAL_CLOSER_RE.test(row))) return undefined;\n\tlet target = leadingIndent(nonBlank[0] ?? \"\");\n\tfor (const row of nonBlank) {\n\t\tconst indent = leadingIndent(row);\n\t\tif (indent.startsWith(target)) continue;\n\t\tif (target.startsWith(indent)) target = indent;\n\t\telse return undefined;\n\t}\n\treturn target;\n}\n\n/**\n * Resolve where an after-insert hunk anchored on `group.anchor` should land\n * given its body depth `target`: the last structural closer line in the run\n * directly below the anchor whose indentation still covers `target`. Returns\n * `undefined` when the landing stays put.\n */\nfunction resolveShiftedLanding(\n\tgroup: AfterInsertGroup,\n\ttarget: string,\n\tfileLines: readonly string[],\n\ttargetedLines: ReadonlySet<number>,\n): { line: number; crossed: number } | undefined {\n\tconst anchorText = fileLines[group.anchor - 1];\n\tif (anchorText === undefined || !hasNonWhitespace(anchorText)) return undefined;\n\tif (!isIndentDeeper(leadingIndent(anchorText), target)) return undefined;\n\n\tlet landing = group.anchor;\n\tlet crossed = 0;\n\tfor (let line = group.anchor + 1; line <= fileLines.length; line++) {\n\t\tconst text = fileLines[line - 1] ?? \"\";\n\t\tif (!hasNonWhitespace(text)) continue; // look past blanks, never land on them\n\t\tif (!STRUCTURAL_CLOSER_RE.test(text)) break; // content is never crossed\n\t\tconst indent = leadingIndent(text);\n\t\tif (!indent.startsWith(target)) break; // shallower than the body — crossing would over-escape\n\t\tif (targetedLines.has(line)) return undefined; // another hunk owns this closer\n\t\tlanding = line;\n\t\tcrossed++;\n\t\tif (indent.length === target.length) break; // depth returned to the body's level\n\t}\n\treturn landing === group.anchor ? undefined : { line: landing, crossed };\n}\n\n/**\n * Resolve where a block-lowered after-insert anchored on the block's closing\n * line should land given a body depth `target` deeper than that closer: just\n * above the block's trailing run of closer lines, bounded below by\n * `blockStart` (an empty block lands the body right after its opener).\n * Returns `undefined` when the landing stays put.\n */\nfunction resolveInwardLanding(\n\tgroup: AfterInsertGroup,\n\ttarget: string,\n\tblockStart: number,\n\tfileLines: readonly string[],\n\ttargetedLines: ReadonlySet<number>,\n): number | undefined {\n\tconst anchorText = fileLines[group.anchor - 1];\n\tif (anchorText === undefined || !hasNonWhitespace(anchorText)) return undefined;\n\t// Fires only when the block ends in a pure closer the body out-indents.\n\t// Blocks ending in content (indentation-only languages) already land the\n\t// body inside the block — nothing to correct.\n\tif (!STRUCTURAL_CLOSER_RE.test(anchorText)) return undefined;\n\tif (!isIndentDeeper(target, leadingIndent(anchorText))) return undefined;\n\n\tlet landing = group.anchor;\n\tfor (let line = group.anchor; line > blockStart; line--) {\n\t\tconst text = fileLines[line - 1] ?? \"\";\n\t\tif (!hasNonWhitespace(text)) {\n\t\t\tlanding = line - 1; // look past trailing blanks, never land after one\n\t\t\tcontinue;\n\t\t}\n\t\tif (!STRUCTURAL_CLOSER_RE.test(text)) break; // content reached — land right after it\n\t\tconst indent = leadingIndent(text);\n\t\tif (!isIndentDeeper(target, indent)) break; // closer at the body's depth — land after it\n\t\t// Another hunk owns this closer (the group's own rows put the anchor\n\t\t// itself in `targetedLines`; that one is ours to cross).\n\t\tif (line !== group.anchor && targetedLines.has(line)) return undefined;\n\t\tlanding = line - 1;\n\t}\n\treturn landing === group.anchor ? undefined : landing;\n}\n\n/**\n * Slide mis-anchored after-insert hunks to the depth their body indentation\n * claims: outward past the structural closer lines that follow the anchor\n * when the body is shallower, or — for `insert after block N:` lowerings —\n * inward across the block's trailing closers when the body is deeper than\n * the block's closing line. Returns the corrected edit list plus one warning\n * per shifted hunk.\n */\nfunction repairAfterInsertLandings(\n\tedits: readonly AppliedEdit[],\n\tfileLines: readonly string[],\n): { edits: readonly AppliedEdit[]; warnings: string[] } {\n\t// Group plain (non-replacement) after-anchor inserts per authored hunk:\n\t// rows of one hunk share the anchor line and the patch header line.\n\tconst groups = new Map<string, AfterInsertGroup>();\n\tedits.forEach((edit, idx) => {\n\t\tif (edit.kind !== \"insert\" || edit.mode === \"replacement\") return;\n\t\tif (edit.cursor.kind !== \"after_anchor\") return;\n\t\tconst key = `${edit.cursor.anchor.line}:${edit.lineNum}`;\n\t\tconst group = groups.get(key);\n\t\tif (group === undefined)\n\t\t\tgroups.set(key, { anchor: edit.cursor.anchor.line, members: [idx], blockStart: edit.blockStart });\n\t\telse group.members.push(idx);\n\t});\n\tif (groups.size === 0) return { edits, warnings: [] };\n\n\t// Lines explicitly targeted by any edit; a shift never crosses them.\n\tconst targetedLines = new Set<number>();\n\tfor (const edit of edits) {\n\t\tif (edit.kind === \"delete\") targetedLines.add(edit.anchor.line);\n\t\telse if (edit.cursor.kind === \"before_anchor\" || edit.cursor.kind === \"after_anchor\")\n\t\t\ttargetedLines.add(edit.cursor.anchor.line);\n\t}\n\n\tlet out: AppliedEdit[] | undefined;\n\tconst warnings: string[] = [];\n\tconst retarget = (group: AfterInsertGroup, line: number): void => {\n\t\tout ??= [...edits];\n\t\tfor (const idx of group.members) {\n\t\t\tconst edit = out[idx] as InsertEdit;\n\t\t\tout[idx] = { ...edit, cursor: { kind: \"after_anchor\", anchor: { line } } };\n\t\t}\n\t};\n\tfor (const group of groups.values()) {\n\t\tconst target = bodyTargetIndent(group.members.map(idx => (edits[idx] as InsertEdit).text));\n\t\tif (target === undefined) continue;\n\t\tconst outward = resolveShiftedLanding(group, target, fileLines, targetedLines);\n\t\tif (outward !== undefined) {\n\t\t\tretarget(group, outward.line);\n\t\t\twarnings.push(afterInsertLandingShiftWarning(group.anchor, outward.line, outward.crossed));\n\t\t\tcontinue;\n\t\t}\n\t\tif (group.blockStart === undefined) continue;\n\t\tconst inward = resolveInwardLanding(group, target, group.blockStart, fileLines, targetedLines);\n\t\tif (inward === undefined) continue;\n\t\tretarget(group, inward);\n\t\twarnings.push(blockInsertLandingShiftWarning(group.blockStart, group.anchor, inward));\n\t}\n\treturn { edits: out ?? edits, warnings };\n}\n\n/**\n * Apply a parsed list of edits to a text body. Pure function — no I/O.\n *\n * Returns the post-edit text and the first changed line number (1-indexed).\n * Throws if an anchor is out of bounds.\n */\nexport function applyEdits(text: string, edits: readonly Edit[]): ApplyResult {\n\tif (edits.length === 0) return { text, firstChangedLine: undefined };\n\n\t// Block edits are deferred until `resolveBlockEdits` expands them into\n\t// concrete inserts + deletes. Reaching the applier with one still present\n\t// is an internal wiring bug, not authored-input error.\n\tfor (const edit of edits) {\n\t\tif (edit.kind === \"block\") throw new Error(UNRESOLVED_BLOCK_INTERNAL);\n\t}\n\tconst appliedEdits = edits as readonly AppliedEdit[];\n\n\tconst fileLines = text.split(\"\\n\");\n\tconst lineOrigins: LineOrigin[] = fileLines.map(() => \"original\");\n\n\tlet firstChangedLine: number | undefined;\n\tconst trackFirstChanged = (line: number) => {\n\t\tif (firstChangedLine === undefined || line < firstChangedLine) firstChangedLine = line;\n\t};\n\n\tconst targetEdits = dropTrailingPhantomDeletes(\n\t\tappliedEdits.map((edit, index) => cloneAppliedEdit(edit, index)),\n\t\tfileLines,\n\t);\n\tvalidateLineBounds(targetEdits, fileLines);\n\tconst { edits: repaired, warnings: boundaryWarnings } = repairReplacementBoundaries(targetEdits, fileLines);\n\tconst { edits: landed, warnings: landingWarnings } = repairAfterInsertLandings(repaired, fileLines);\n\tconst warnings = [...boundaryWarnings, ...landingWarnings];\n\n\t// Partition edits into bof, eof, and anchor-targeted buckets.\n\tconst bofLines: string[] = [];\n\tconst eofLines: string[] = [];\n\tconst anchorEdits: IndexedEdit[] = [];\n\tlanded.forEach((edit, idx) => {\n\t\tif (edit.kind === \"insert\" && edit.cursor.kind === \"bof\") {\n\t\t\tbofLines.push(edit.text);\n\t\t} else if (edit.kind === \"insert\" && edit.cursor.kind === \"eof\") {\n\t\t\teofLines.push(edit.text);\n\t\t} else {\n\t\t\tanchorEdits.push({ edit, idx });\n\t\t}\n\t});\n\n\t// Apply per-line buckets bottom-up so earlier indices stay valid.\n\tconst byLine = bucketAnchorEditsByLine(anchorEdits);\n\tfor (const line of [...byLine.keys()].sort((a, b) => b - a)) {\n\t\tconst bucket = byLine.get(line);\n\t\tif (!bucket) continue;\n\t\tbucket.sort((a, b) => a.idx - b.idx);\n\n\t\tconst idx = line - 1;\n\t\tconst currentLine = fileLines[idx] ?? \"\";\n\t\tconst beforeInsertLines: string[] = [];\n\t\tconst afterInsertLines: string[] = [];\n\t\tconst replacementLines: string[] = [];\n\t\tlet deleteLine = false;\n\n\t\tfor (const { edit } of bucket) {\n\t\t\tif (isReplacementInsert(edit)) {\n\t\t\t\treplacementLines.push(edit.text);\n\t\t\t} else if (edit.kind === \"insert\" && edit.cursor.kind === \"after_anchor\") {\n\t\t\t\tafterInsertLines.push(edit.text);\n\t\t\t} else if (edit.kind === \"insert\") {\n\t\t\t\tbeforeInsertLines.push(edit.text);\n\t\t\t} else if (edit.kind === \"delete\") {\n\t\t\t\tdeleteLine = true;\n\t\t\t}\n\t\t}\n\t\tif (\n\t\t\tbeforeInsertLines.length === 0 &&\n\t\t\treplacementLines.length === 0 &&\n\t\t\tafterInsertLines.length === 0 &&\n\t\t\t!deleteLine\n\t\t)\n\t\t\tcontinue;\n\n\t\tconst replacement = deleteLine\n\t\t\t? [...beforeInsertLines, ...replacementLines, ...afterInsertLines]\n\t\t\t: [...beforeInsertLines, ...replacementLines, currentLine, ...afterInsertLines];\n\t\tconst origins: LineOrigin[] = [];\n\t\tfor (let i = 0; i < beforeInsertLines.length; i++) origins.push(\"insert\");\n\t\tfor (let i = 0; i < replacementLines.length; i++) origins.push(deleteLine ? \"replacement\" : \"insert\");\n\t\tif (!deleteLine) origins.push(lineOrigins[idx] ?? \"original\");\n\t\tfor (let i = 0; i < afterInsertLines.length; i++) origins.push(\"insert\");\n\n\t\tfileLines.splice(idx, 1, ...replacement);\n\t\tlineOrigins.splice(idx, 1, ...origins);\n\t\ttrackFirstChanged(line);\n\t}\n\n\tif (bofLines.length > 0) {\n\t\tinsertAtStart(fileLines, lineOrigins, bofLines);\n\t\ttrackFirstChanged(1);\n\t}\n\tconst eofChangedLine = insertAtEnd(fileLines, lineOrigins, eofLines);\n\tif (eofChangedLine !== undefined) trackFirstChanged(eofChangedLine);\n\n\treturn {\n\t\ttext: fileLines.join(\"\\n\"),\n\t\tfirstChangedLine,\n\t\t...(warnings.length > 0 ? { warnings } : {}),\n\t};\n}\n"]}
1
+ {"version":3,"file":"apply.d.ts","sourceRoot":"","sources":["../../../../src/core/tools/hashline-engine/apply.ts"],"names":[],"mappings":"AAaA,OAAO,KAAK,EAAU,WAAW,EAAU,IAAI,EAAE,MAAM,YAAY,CAAC;AAsHpE,iFAAiF;AACjF,eAAO,MAAM,oBAAoB,QAAyB,CAAC;AAklB3D;;;;;GAKG;AACH,wBAAgB,UAAU,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,SAAS,IAAI,EAAE,GAAG,WAAW,CAqG5E"}
@@ -1 +1 @@
1
- {"version":3,"file":"block.d.ts","sourceRoot":"","sources":["../../../../src/core/tools/hashline-engine/block.ts"],"names":[],"mappings":"AAuBA,OAAO,KAAK,EAAE,eAAe,EAAE,aAAa,EAAU,IAAI,EAAE,MAAM,YAAY,CAAC;AAE/E,MAAM,WAAW,wBAAwB;IACxC;;;;;;;;OAQG;IACH,YAAY,CAAC,EAAE,OAAO,GAAG,MAAM,CAAC;IAChC;;;;;OAKG;IACH,UAAU,CAAC,EAAE,CAAC,UAAU,EAAE,eAAe,KAAK,IAAI,CAAC;IACnD;;;;OAIG;IACH,SAAS,CAAC,EAAE,CAAC,OAAO,EAAE,MAAM,KAAK,IAAI,CAAC;CACtC;AAED,wEAAwE;AACxE,wBAAgB,YAAY,CAAC,KAAK,EAAE,SAAS,IAAI,EAAE,GAAG,OAAO,CAE5D;AAED;;;;;;;;;GASG;AACH,wBAAgB,iBAAiB,CAChC,KAAK,EAAE,SAAS,IAAI,EAAE,EACtB,IAAI,EAAE,MAAM,EACZ,IAAI,EAAE,MAAM,EACZ,QAAQ,EAAE,aAAa,GAAG,SAAS,EACnC,OAAO,GAAE,wBAA6B,GACpC,SAAS,IAAI,EAAE,CAuFjB","sourcesContent":["// @generated vendored verbatim from oh-my-pi packages/hashline @ 15b5c1397fc -- DO NOT EDIT.\n// Parity source for the Atomic hashline edit engine (issue #1483); adapted only for Atomic's Node runtime (relative imports, Bun->Node host calls, erasable constructor syntax).\n/**\n * Expand deferred block edits (`replace block N:` / `delete block N` /\n * `insert after block N:`) into concrete inserts + deletes.\n *\n * The hashline parser cannot expand a block edit on its own — the line span is\n * unknown until file text + path (→ language) are available. This transform\n * runs at every apply/preview boundary that has text: it calls the injected\n * {@link BlockResolver} to resolve each block's `[start, end]` span, then emits\n * the exact same edits the concrete form produces in the parser: `replace\n * start..end:` inserts + deletes for a replace, a pure range delete for a\n * delete, and plain `after_anchor` inserts at `end` for an insert-after. After\n * it runs, no `block` edits remain, so {@link applyEdits} (and recovery) only\n * ever see resolved edits.\n */\nimport { STRUCTURAL_CLOSER_RE } from \"./apply.js\";\nimport {\n\tBLOCK_RESOLVER_UNAVAILABLE,\n\tblockUnresolvedMessage,\n\tinsertAfterBlockCloserLoweredWarning,\n\tinsertAfterBlockUnresolvedLoweredWarning,\n} from \"./messages.js\";\nimport type { BlockResolution, BlockResolver, Cursor, Edit } from \"./types.js\";\n\nexport interface ResolveBlockEditsOptions {\n\t/**\n\t * How to handle a replace/delete block edit that cannot be resolved\n\t * (missing resolver or a `null` span). `\"throw\"` (default) raises a\n\t * `blockUnresolvedMessage` error — used by the authoritative apply + final\n\t * preview paths. `\"drop\"` silently skips the edit — used by the streaming\n\t * preview, where a half-written file or transient parse error must not\n\t * throw. Unresolvable `insert after block N:` edits never reach this: they\n\t * are lowered to plain `insert after N:` with a warning.\n\t */\n\tonUnresolved?: \"throw\" | \"drop\";\n\t/**\n\t * Invoked once per successfully resolved block edit, in patch order, with\n\t * the anchor line and the concrete span it resolved to. Lets the host echo\n\t * the resolution back to the caller. Never fired for dropped/unresolvable\n\t * edits.\n\t */\n\tonResolved?: (resolution: BlockResolution) => void;\n\t/**\n\t * Invoked once per diagnostic produced while resolving — currently the\n\t * `insert after block N:` lowerings (closer anchor or unresolvable block).\n\t * Hosts should surface these on the apply result's `warnings`.\n\t */\n\tonWarning?: (message: string) => void;\n}\n\n/** True when at least one edit is an unresolved deferred block edit. */\nexport function hasBlockEdit(edits: readonly Edit[]): boolean {\n\treturn edits.some(edit => edit.kind === \"block\");\n}\n\n/**\n * Resolve every deferred block edit in `edits` against `text` (parsed as the\n * language inferred from `path`). Non-block edits pass through untouched.\n * Returns a fresh edit list with no `block` variants. The fast path returns the\n * input unchanged when there is nothing to resolve.\n *\n * Synthesized inserts/deletes carry sequential `index` values for readability\n * only — {@link applyEdits} re-derives every edit's index from array order, so\n * the passthrough edits keeping their original indices is harmless.\n */\nexport function resolveBlockEdits(\n\tedits: readonly Edit[],\n\ttext: string,\n\tpath: string,\n\tresolver: BlockResolver | undefined,\n\toptions: ResolveBlockEditsOptions = {},\n): readonly Edit[] {\n\tif (!hasBlockEdit(edits)) return edits;\n\tconst onUnresolved = options.onUnresolved ?? \"throw\";\n\tconst resolved: Edit[] = [];\n\tlet synthIndex = 0;\n\tfor (const edit of edits) {\n\t\tif (edit.kind !== \"block\") {\n\t\t\tresolved.push(edit);\n\t\t\tcontinue;\n\t\t}\n\t\tconst op = edit.mode === \"insert_after\" ? \"insert_after\" : edit.payloads.length === 0 ? \"delete\" : \"replace\";\n\t\tconst span = resolver ? resolver({ path, text, line: edit.anchor.line }) : null;\n\t\tif (span === null) {\n\t\t\t// `insert after block N:` never fails the patch — lower it to plain\n\t\t\t// `insert after N:` with a warning instead. Two flavors:\n\t\t\t// - anchored on a pure closing-delimiter line: no block begins\n\t\t\t// there, but line N IS the end of one, and \"after the end of the\n\t\t\t// block\" is exactly the plain form — warn with the opener rule.\n\t\t\t// - otherwise (unsupported language, blank line, unparsable block,\n\t\t\t// or no resolver wired): \"after the block at N\" degrades to\n\t\t\t// \"after line N\" — warn to verify the landing line.\n\t\t\tif (op === \"insert_after\") {\n\t\t\t\tconst anchorText = text.split(\"\\n\")[edit.anchor.line - 1];\n\t\t\t\tconst isCloser = anchorText !== undefined && STRUCTURAL_CLOSER_RE.test(anchorText);\n\t\t\t\toptions.onWarning?.(\n\t\t\t\t\tisCloser\n\t\t\t\t\t\t? insertAfterBlockCloserLoweredWarning(edit.anchor.line)\n\t\t\t\t\t\t: insertAfterBlockUnresolvedLoweredWarning(edit.anchor.line),\n\t\t\t\t);\n\t\t\t\tfor (const payload of edit.payloads) {\n\t\t\t\t\tconst cursor: Cursor = { kind: \"after_anchor\", anchor: { line: edit.anchor.line } };\n\t\t\t\t\tresolved.push({ kind: \"insert\", cursor, text: payload, lineNum: edit.lineNum, index: synthIndex++ });\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (onUnresolved === \"drop\") continue;\n\t\t\tthrow new Error(\n\t\t\t\t`line ${edit.lineNum}: ${\n\t\t\t\t\tresolver ? blockUnresolvedMessage(edit.anchor.line, op, text.split(\"\\n\")) : BLOCK_RESOLVER_UNAVAILABLE\n\t\t\t\t}`,\n\t\t\t);\n\t\t}\n\t\toptions.onResolved?.({\n\t\t\tanchorLine: edit.anchor.line,\n\t\t\tstart: span.start,\n\t\t\tend: span.end,\n\t\t\top,\n\t\t});\n\t\tif (op === \"insert_after\") {\n\t\t\t// Mirror the parser's `insert after N:` lowering: one `after_anchor`\n\t\t\t// insert per payload row, anchored on the block's last line. The\n\t\t\t// `blockStart` tag lets the applier's landing correction slide a\n\t\t\t// body that claims a depth inside the block back across the block's\n\t\t\t// trailing closer lines.\n\t\t\tfor (const payload of edit.payloads) {\n\t\t\t\tconst cursor: Cursor = { kind: \"after_anchor\", anchor: { line: span.end } };\n\t\t\t\tresolved.push({\n\t\t\t\t\tkind: \"insert\",\n\t\t\t\t\tcursor,\n\t\t\t\t\ttext: payload,\n\t\t\t\t\tlineNum: edit.lineNum,\n\t\t\t\t\tindex: synthIndex++,\n\t\t\t\t\tblockStart: span.start,\n\t\t\t\t});\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\t// Mirror the parser's `replace start..end:` expansion exactly: one\n\t\t// `before_anchor` replacement insert per payload row at `span.start`,\n\t\t// then one delete per line across `[span.start, span.end]`. An empty\n\t\t// `payloads` (from `delete block N`) emits no inserts — a pure deletion.\n\t\tfor (const payload of edit.payloads) {\n\t\t\tconst cursor: Cursor = { kind: \"before_anchor\", anchor: { line: span.start } };\n\t\t\tresolved.push({\n\t\t\t\tkind: \"insert\",\n\t\t\t\tcursor,\n\t\t\t\ttext: payload,\n\t\t\t\tlineNum: edit.lineNum,\n\t\t\t\tindex: synthIndex++,\n\t\t\t\tmode: \"replacement\",\n\t\t\t});\n\t\t}\n\t\tfor (let line = span.start; line <= span.end; line++) {\n\t\t\tresolved.push({ kind: \"delete\", anchor: { line }, lineNum: edit.lineNum, index: synthIndex++ });\n\t\t}\n\t}\n\treturn resolved;\n}\n"]}
1
+ {"version":3,"file":"block.d.ts","sourceRoot":"","sources":["../../../../src/core/tools/hashline-engine/block.ts"],"names":[],"mappings":"AAuBA,OAAO,KAAK,EAAE,eAAe,EAAE,aAAa,EAAU,IAAI,EAAE,MAAM,YAAY,CAAC;AAE/E,MAAM,WAAW,wBAAwB;IACxC;;;;;;;;OAQG;IACH,YAAY,CAAC,EAAE,OAAO,GAAG,MAAM,CAAC;IAChC;;;;;OAKG;IACH,UAAU,CAAC,EAAE,CAAC,UAAU,EAAE,eAAe,KAAK,IAAI,CAAC;IACnD;;;;OAIG;IACH,SAAS,CAAC,EAAE,CAAC,OAAO,EAAE,MAAM,KAAK,IAAI,CAAC;CACtC;AAED,wEAAwE;AACxE,wBAAgB,YAAY,CAAC,KAAK,EAAE,SAAS,IAAI,EAAE,GAAG,OAAO,CAE5D;AAED;;;;;;;;;GASG;AACH,wBAAgB,iBAAiB,CAChC,KAAK,EAAE,SAAS,IAAI,EAAE,EACtB,IAAI,EAAE,MAAM,EACZ,IAAI,EAAE,MAAM,EACZ,QAAQ,EAAE,aAAa,GAAG,SAAS,EACnC,OAAO,GAAE,wBAA6B,GACpC,SAAS,IAAI,EAAE,CAuFjB"}
@@ -1 +1 @@
1
- {"version":3,"file":"diff-preview.d.ts","sourceRoot":"","sources":["../../../../src/core/tools/hashline-engine/diff-preview.ts"],"names":[],"mappings":"AAEA;;;;;;;;;;;GAWG;AACH,OAAO,KAAK,EAAE,kBAAkB,EAAE,kBAAkB,EAAE,MAAM,YAAY,CAAC;AA+DzE,wBAAgB,uBAAuB,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,GAAE,kBAAuB,GAAG,kBAAkB,CAgD1G","sourcesContent":["// @generated vendored verbatim from oh-my-pi packages/hashline @ 15b5c1397fc -- DO NOT EDIT.\n// Parity source for the Atomic hashline edit engine (issue #1483); adapted only for Atomic's Node runtime (relative imports, Bun->Node host calls, erasable constructor syntax).\n/**\n * Re-number a unified diff that uses the `+<lineNum>|content` /\n * `-<lineNum>|content` / ` <lineNum>|content` line format into a compact\n * current-file preview. Removed lines are counted for stats and post-edit\n * offset tracking, but omitted from the preview. Added and context lines are\n * anchored to their post-edit positions so a follow-up edit can reuse visible\n * concrete lines directly. Long contiguous added runs are summarized with a\n * `…` marker instead of echoing every inserted line.\n *\n * This is intentionally decoupled from the diff producer: anything that\n * emits the `<sign><lineNum>|<content>` shape works.\n */\nimport type { CompactDiffOptions, CompactDiffPreview } from \"./types.js\";\n\nconst DEFAULT_ADDED_RUN_CONTEXT_LINES = 2;\n\nconst PREVIEW_ELISION_MARKER = \"…\";\n/** Blank row separating non-contiguous regions of a numbered diff. */\nconst PREVIEW_GAP_ROW = \"\";\nconst RAW_ELISION_MARKERS = new Set([\"...\", PREVIEW_ELISION_MARKER, `+${PREVIEW_ELISION_MARKER}`]);\n\nfunction isPreviewSeparator(line: string | undefined): boolean {\n\treturn line === PREVIEW_ELISION_MARKER || line === PREVIEW_GAP_ROW;\n}\n\nfunction appendPreviewLine(output: string[], line: string): void {\n\tconst normalized = RAW_ELISION_MARKERS.has(line) ? PREVIEW_ELISION_MARKER : line;\n\t// Separators (elision markers, blank gap rows) never stack: omitted\n\t// removed lines between two separators would otherwise leave them\n\t// adjacent. A leading separator is dropped outright.\n\tif (isPreviewSeparator(normalized) && (output.length === 0 || isPreviewSeparator(output[output.length - 1]))) {\n\t\treturn;\n\t}\n\toutput.push(normalized);\n}\n\ninterface ParsedDiffLine {\n\tkind: \"+\" | \"-\" | \" \";\n\tlineNumber: number;\n\tcontent: string;\n}\n\nfunction normalizeAddedRunContext(value: number | undefined): number {\n\tif (value === undefined || !Number.isFinite(value)) return DEFAULT_ADDED_RUN_CONTEXT_LINES;\n\treturn Math.max(1, Math.trunc(value));\n}\n\nfunction parseNumberedDiffLine(line: string): ParsedDiffLine | undefined {\n\tconst kind = line[0];\n\tif (kind !== \"+\" && kind !== \"-\" && kind !== \" \") return undefined;\n\n\tconst body = line.slice(1);\n\tconst sep = body.indexOf(\"|\");\n\tif (sep === -1) return undefined;\n\n\tconst lineNumber = Number.parseInt(body.slice(0, sep), 10);\n\tif (!Number.isFinite(lineNumber)) return undefined;\n\n\treturn { kind, lineNumber, content: body.slice(sep + 1) };\n}\n\nfunction appendAddedRun(output: string[], run: string[], edgeLines: number): void {\n\tif (run.length === 0) return;\n\n\tconst collapseThreshold = edgeLines * 2 + 1;\n\tif (run.length <= collapseThreshold) {\n\t\tfor (const text of run) appendPreviewLine(output, text);\n\t\treturn;\n\t}\n\n\tfor (let i = 0; i < edgeLines; i++) appendPreviewLine(output, run[i]);\n\tappendPreviewLine(output, PREVIEW_ELISION_MARKER);\n\tfor (let i = run.length - edgeLines; i < run.length; i++) appendPreviewLine(output, run[i]);\n}\n\nexport function buildCompactDiffPreview(diff: string, options: CompactDiffOptions = {}): CompactDiffPreview {\n\tconst lines = diff.length === 0 ? [] : diff.split(\"\\n\");\n\tconst addedRunContext = normalizeAddedRunContext(options.maxAddedRunContext ?? options.maxUnchangedRun);\n\tlet addedLines = 0;\n\tlet removedLines = 0;\n\tconst formatted: string[] = [];\n\tconst addedRun: string[] = [];\n\n\tconst flushAddedRun = (): void => {\n\t\tappendAddedRun(formatted, addedRun, addedRunContext);\n\t\taddedRun.length = 0;\n\t};\n\n\t// External diff producers number `+` lines with the post-edit line number,\n\t// `-` lines with the pre-edit line number, and context lines with the\n\t// pre-edit line number. To emit fresh line numbers usable for follow-up\n\t// edits, convert context-line numbers to post-edit positions by tracking\n\t// the running offset (added so far - removed so far) as we walk the diff.\n\tfor (const line of lines) {\n\t\tconst parsed = parseNumberedDiffLine(line);\n\t\tif (!parsed) {\n\t\t\tflushAddedRun();\n\t\t\tappendPreviewLine(formatted, line);\n\t\t\tcontinue;\n\t\t}\n\n\t\tswitch (parsed.kind) {\n\t\t\tcase \"+\": {\n\t\t\t\taddedLines++;\n\t\t\t\taddedRun.push(`${parsed.lineNumber}:${parsed.content}`);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"-\":\n\t\t\t\tflushAddedRun();\n\t\t\t\tremovedLines++;\n\t\t\t\tbreak;\n\t\t\tdefault: {\n\t\t\t\tflushAddedRun();\n\t\t\t\tconst newLineNumber = parsed.lineNumber + addedLines - removedLines;\n\t\t\t\tappendPreviewLine(formatted, `${newLineNumber}:${parsed.content}`);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\tflushAddedRun();\n\twhile (formatted.length > 0 && isPreviewSeparator(formatted[formatted.length - 1])) formatted.pop();\n\n\treturn { preview: formatted.join(\"\\n\"), addedLines, removedLines };\n}\n"]}
1
+ {"version":3,"file":"diff-preview.d.ts","sourceRoot":"","sources":["../../../../src/core/tools/hashline-engine/diff-preview.ts"],"names":[],"mappings":"AAEA;;;;;;;;;;;GAWG;AACH,OAAO,KAAK,EAAE,kBAAkB,EAAE,kBAAkB,EAAE,MAAM,YAAY,CAAC;AA+DzE,wBAAgB,uBAAuB,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,GAAE,kBAAuB,GAAG,kBAAkB,CAgD1G"}
@@ -1 +1 @@
1
- {"version":3,"file":"format.d.ts","sourceRoot":"","sources":["../../../../src/core/tools/hashline-engine/format.ts"],"names":[],"mappings":"AAEA;;;;GAIG;AAEH,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,YAAY,CAAC;AAEzC,qDAAqD;AACrD,eAAO,MAAM,cAAc,MAAM,CAAC;AAClC,eAAO,MAAM,cAAc,MAAM,CAAC;AAElC,2CAA2C;AAC3C,eAAO,MAAM,kBAAkB,MAAM,CAAC;AAEtC,yDAAyD;AACzD,eAAO,MAAM,kBAAkB,YAAY,CAAC;AAC5C,2FAA2F;AAC3F,eAAO,MAAM,gBAAgB,UAAU,CAAC;AACxC,sDAAsD;AACtD,eAAO,MAAM,iBAAiB,WAAW,CAAC;AAC1C,oDAAoD;AACpD,eAAO,MAAM,iBAAiB,WAAW,CAAC;AAC1C,oEAAoE;AACpE,eAAO,MAAM,gBAAgB,WAAW,CAAC;AACzC,mEAAmE;AACnE,eAAO,MAAM,eAAe,UAAU,CAAC;AACvC,sEAAsE;AACtE,eAAO,MAAM,cAAc,SAAS,CAAC;AACrC,oEAAoE;AACpE,eAAO,MAAM,cAAc,SAAS,CAAC;AACrC,0DAA0D;AAC1D,eAAO,MAAM,eAAe,MAAM,CAAC;AAEnC,0EAA0E;AAC1E,eAAO,MAAM,gBAAgB,MAAM,CAAC;AAEpC,mEAAmE;AACnE,eAAO,MAAM,YAAY,OAAO,CAAC;AAEjC,mFAAmF;AACnF,eAAO,MAAM,gBAAgB,MAAM,CAAC;AAMpC,+EAA+E;AAC/E,eAAO,MAAM,cAAc,cAAc,CAAC;AAE1C,oDAAoD;AACpD,eAAO,MAAM,sBAAsB,gBAAwB,CAAC;AAE5D,iDAAiD;AACjD,wBAAgB,mBAAmB,CAAC,KAAK,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,GAAG,MAAM,CAEtE;AAED,8CAA8C;AAC9C,wBAAgB,kBAAkB,CAAC,KAAK,EAAE,MAAM,EAAE,GAAG,SAAQ,GAAG,MAAM,CAErE;AAED,6DAA6D;AAC7D,wBAAgB,kBAAkB,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,CAWzD;AAED,mEAAmE;AACnE,eAAO,MAAM,mBAAmB,IAAI,CAAC;AACrC,6FAA6F;AAC7F,eAAO,MAAM,mBAAmB,gBAAqC,CAAC;AACtE,yDAAyD;AACzD,eAAO,MAAM,2BAA2B,kBAA6B,CAAC;AACtE,yFAAyF;AACzF,eAAO,MAAM,uBAAuB,QAAgC,CAAC;AACrE;;;GAGG;AACH,eAAO,MAAM,qBAAqB,YAAI,MAAM,EAAE,MAAM,EAAE,MAAM,CAAU,CAAC;AAuEvE,wBAAgB,eAAe,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAIpD;AAED;;;GAGG;AACH,wBAAgB,sBAAsB,CAAC,UAAU,SAAK,GAAG,MAAM,CAG9D;AAED,yEAAyE;AACzE,wBAAgB,oBAAoB,CAAC,QAAQ,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,MAAM,CAE/E;AAED,qDAAqD;AACrD,wBAAgB,kBAAkB,CAAC,UAAU,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,MAAM,CAE3E;AAED,4EAA4E;AAC5E,wBAAgB,mBAAmB,CAAC,IAAI,EAAE,MAAM,EAAE,SAAS,SAAI,GAAG,MAAM,CAGvE","sourcesContent":["// @generated vendored verbatim from oh-my-pi packages/hashline @ 15b5c1397fc -- DO NOT EDIT.\n// Parity source for the Atomic hashline edit engine (issue #1483); adapted only for Atomic's Node runtime (relative imports, Bun->Node host calls, erasable constructor syntax).\n/**\n * Hashline format primitives: sigils, separators, regex fragments, and\n * display helpers. These are the single source of truth for the parser, the\n * tokenizer, the prompt, and the formal grammar.\n */\n\nimport type { Cursor } from \"./types.js\";\n\n/** File-section header delimiters: `[path#hash]`. */\nexport const HL_FILE_PREFIX = \"[\";\nexport const HL_FILE_SUFFIX = \"]\";\n\n/** Payload sigil for literal body rows. */\nexport const HL_PAYLOAD_REPLACE = \"+\";\n\n/** Hunk-header keyword for concrete line replacement. */\nexport const HL_REPLACE_KEYWORD = \"replace\";\n/** Hunk-header sub-keyword: `replace block N:` resolves N to a tree-sitter block range. */\nexport const HL_BLOCK_KEYWORD = \"block\";\n/** Hunk-header keyword for concrete line deletion. */\nexport const HL_DELETE_KEYWORD = \"delete\";\n/** Hunk-header keyword for insertion operations. */\nexport const HL_INSERT_KEYWORD = \"insert\";\n/** Insert position keyword for inserting before a concrete line. */\nexport const HL_INSERT_BEFORE = \"before\";\n/** Insert position keyword for inserting after a concrete line. */\nexport const HL_INSERT_AFTER = \"after\";\n/** Insert position keyword for inserting at the start of the file. */\nexport const HL_INSERT_HEAD = \"head\";\n/** Insert position keyword for inserting at the end of the file. */\nexport const HL_INSERT_TAIL = \"tail\";\n/** Hunk-header terminator for body-bearing operations. */\nexport const HL_HEADER_COLON = \":\";\n\n/** Separator between a hashline file path and its opaque snapshot tag. */\nexport const HL_FILE_HASH_SEP = \"#\";\n\n/** Separator between two line numbers in a range, e.g. `5..10`. */\nexport const HL_RANGE_SEP = \"..\";\n\n/** Separator between a line number and displayed line content in hashline mode. */\nexport const HL_LINE_BODY_SEP = \":\";\n\nfunction regexEscape(str: string): string {\n\treturn str.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n\n/** Bare positive line-number Lid (no decorations, no captures, no anchors). */\nexport const HL_LINE_RE_RAW = `[1-9]\\\\d*`;\n\n/** Capture-group form of {@link HL_LINE_RE_RAW}. */\nexport const HL_LINE_CAPTURE_RE_RAW = `(${HL_LINE_RE_RAW})`;\n\n/** Format a concrete replacement hunk header. */\nexport function formatReplaceHeader(start: number, end: number): string {\n\treturn `${HL_REPLACE_KEYWORD} ${start}${HL_RANGE_SEP}${end}${HL_HEADER_COLON}`;\n}\n\n/** Format a concrete deletion hunk header. */\nexport function formatDeleteHeader(start: number, end = start): string {\n\treturn start === end ? `${HL_DELETE_KEYWORD} ${start}` : `${HL_DELETE_KEYWORD} ${start}${HL_RANGE_SEP}${end}`;\n}\n\n/** Format an insertion hunk header for a cursor position. */\nexport function formatInsertHeader(cursor: Cursor): string {\n\tswitch (cursor.kind) {\n\t\tcase \"before_anchor\":\n\t\t\treturn `${HL_INSERT_KEYWORD} ${HL_INSERT_BEFORE} ${cursor.anchor.line}${HL_HEADER_COLON}`;\n\t\tcase \"after_anchor\":\n\t\t\treturn `${HL_INSERT_KEYWORD} ${HL_INSERT_AFTER} ${cursor.anchor.line}${HL_HEADER_COLON}`;\n\t\tcase \"bof\":\n\t\t\treturn `${HL_INSERT_KEYWORD} ${HL_INSERT_HEAD}${HL_HEADER_COLON}`;\n\t\tcase \"eof\":\n\t\t\treturn `${HL_INSERT_KEYWORD} ${HL_INSERT_TAIL}${HL_HEADER_COLON}`;\n\t}\n}\n\n/** Number of hex characters in a content-derived file-hash tag. */\nexport const HL_FILE_HASH_LENGTH = 4;\n/** Canonical uppercase hexadecimal content-hash tag carried by a hashline section header. */\nexport const HL_FILE_HASH_RE_RAW = `[0-9A-F]{${HL_FILE_HASH_LENGTH}}`;\n/** Capture-group form of {@link HL_FILE_HASH_RE_RAW}. */\nexport const HL_FILE_HASH_CAPTURE_RE_RAW = `(${HL_FILE_HASH_RE_RAW})`;\n/** Regex-escaped form of {@link HL_LINE_BODY_SEP}, safe for embedding inside a regex. */\nexport const HL_LINE_BODY_SEP_RE_RAW = regexEscape(HL_LINE_BODY_SEP);\n/**\n * Representative file-hash tags for use in user-facing error messages and\n * prompt examples.\n */\nexport const HL_FILE_HASH_EXAMPLES = [\"1A2B\", \"3C4D\", \"9F3E\"] as const;\n/**\n * Normalize text before hashing: trim trailing `[ \\t\\r]` from every line (and\n * the final line) in a single pass so CRLF endings and display-trimmed lines\n * do not invalidate a tag.\n */\nfunction normalizeFileHashText(text: string): string {\n\treturn text.replace(/[ \\t\\r]+(?=\\n|$)/g, \"\");\n}\n/**\n * Compute the content-derived hash tag carried by a hashline section header.\n * The tag is a 4-hex fingerprint of the whole file's normalized text: any read\n * of byte-identical content mints the same tag, and a follow-up edit anchored\n * at any line validates whenever the live file still hashes to it.\n */\n// xxHash32 (canonical, seed 0) to match upstream Bun.hash.xxHash32 so section tags\n// are byte-identical to oh-my-pi for identical content. Pure-JS for Node runtime.\nconst XXH_PRIME32_1 = 0x9e3779b1;\nconst XXH_PRIME32_2 = 0x85ebca77;\nconst XXH_PRIME32_3 = 0xc2b2ae3d;\nconst XXH_PRIME32_4 = 0x27d4eb2f;\nconst XXH_PRIME32_5 = 0x165667b1;\nfunction xxhRotl(value: number, bits: number): number {\n\treturn (value << bits) | (value >>> (32 - bits));\n}\nfunction xxhRound(acc: number, input: number): number {\n\tacc = (acc + Math.imul(input, XXH_PRIME32_2)) | 0;\n\tacc = xxhRotl(acc, 13);\n\treturn Math.imul(acc, XXH_PRIME32_1) | 0;\n}\nfunction xxHash32(bytes: Uint8Array): number {\n\tconst len = bytes.length;\n\tlet index = 0;\n\tlet h32: number;\n\tconst readU32 = (offset: number): number =>\n\t\t(bytes[offset]! | (bytes[offset + 1]! << 8) | (bytes[offset + 2]! << 16) | (bytes[offset + 3]! << 24)) >>> 0;\n\tif (len >= 16) {\n\t\tlet v1 = (XXH_PRIME32_1 + XXH_PRIME32_2) | 0;\n\t\tlet v2 = XXH_PRIME32_2 | 0;\n\t\tlet v3 = 0;\n\t\tlet v4 = -XXH_PRIME32_1 | 0;\n\t\tconst limit = len - 16;\n\t\twhile (index <= limit) {\n\t\t\tv1 = xxhRound(v1, readU32(index)); index += 4;\n\t\t\tv2 = xxhRound(v2, readU32(index)); index += 4;\n\t\t\tv3 = xxhRound(v3, readU32(index)); index += 4;\n\t\t\tv4 = xxhRound(v4, readU32(index)); index += 4;\n\t\t}\n\t\th32 = (xxhRotl(v1, 1) + xxhRotl(v2, 7) + xxhRotl(v3, 12) + xxhRotl(v4, 18)) | 0;\n\t} else {\n\t\th32 = XXH_PRIME32_5 | 0;\n\t}\n\th32 = (h32 + len) | 0;\n\twhile (index + 4 <= len) {\n\t\th32 = (h32 + Math.imul(readU32(index), XXH_PRIME32_3)) | 0;\n\t\th32 = Math.imul(xxhRotl(h32, 17), XXH_PRIME32_4) | 0;\n\t\tindex += 4;\n\t}\n\twhile (index < len) {\n\t\th32 = (h32 + Math.imul(bytes[index]!, XXH_PRIME32_5)) | 0;\n\t\th32 = Math.imul(xxhRotl(h32, 11), XXH_PRIME32_1) | 0;\n\t\tindex += 1;\n\t}\n\th32 ^= h32 >>> 15;\n\th32 = Math.imul(h32, XXH_PRIME32_2);\n\th32 ^= h32 >>> 13;\n\th32 = Math.imul(h32, XXH_PRIME32_3);\n\th32 ^= h32 >>> 16;\n\treturn h32 >>> 0;\n}\nconst xxhEncoder = new TextEncoder();\nexport function computeFileHash(text: string): string {\n\tconst normalized = normalizeFileHashText(text);\n\tconst low16 = xxHash32(xxhEncoder.encode(normalized)) & 0xffff;\n\treturn low16.toString(16).padStart(HL_FILE_HASH_LENGTH, \"0\").toUpperCase();\n}\n\n/**\n * Format a comma-separated list of example anchors with an optional line-number\n * prefix, quoted for inclusion in error messages: `\"160\", \"42\", \"7\"`.\n */\nexport function describeAnchorExamples(linePrefix = \"\"): string {\n\tconst examples = linePrefix ? [linePrefix, `${linePrefix.slice(0, -1) || \"4\"}2`, \"7\"] : [\"160\", \"42\", \"7\"];\n\treturn examples.map(e => `\"${e}\"`).join(\", \");\n}\n\n/** Format a hashline section header for a file path and snapshot tag. */\nexport function formatHashlineHeader(filePath: string, fileHash: string): string {\n\treturn `${HL_FILE_PREFIX}${filePath}${HL_FILE_HASH_SEP}${fileHash}${HL_FILE_SUFFIX}`;\n}\n\n/** Formats a single numbered line as `LINE:TEXT`. */\nexport function formatNumberedLine(lineNumber: number, line: string): string {\n\treturn `${lineNumber}${HL_LINE_BODY_SEP}${line}`;\n}\n\n/** Format file text with hashline-mode line-number prefixes for display. */\nexport function formatNumberedLines(text: string, startLine = 1): string {\n\tconst lines = text.split(\"\\n\");\n\treturn lines.map((line, i) => formatNumberedLine(startLine + i, line)).join(\"\\n\");\n}\n"]}
1
+ {"version":3,"file":"format.d.ts","sourceRoot":"","sources":["../../../../src/core/tools/hashline-engine/format.ts"],"names":[],"mappings":"AAEA;;;;GAIG;AAEH,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,YAAY,CAAC;AAEzC,qDAAqD;AACrD,eAAO,MAAM,cAAc,MAAM,CAAC;AAClC,eAAO,MAAM,cAAc,MAAM,CAAC;AAElC,2CAA2C;AAC3C,eAAO,MAAM,kBAAkB,MAAM,CAAC;AAEtC,yDAAyD;AACzD,eAAO,MAAM,kBAAkB,YAAY,CAAC;AAC5C,2FAA2F;AAC3F,eAAO,MAAM,gBAAgB,UAAU,CAAC;AACxC,sDAAsD;AACtD,eAAO,MAAM,iBAAiB,WAAW,CAAC;AAC1C,oDAAoD;AACpD,eAAO,MAAM,iBAAiB,WAAW,CAAC;AAC1C,oEAAoE;AACpE,eAAO,MAAM,gBAAgB,WAAW,CAAC;AACzC,mEAAmE;AACnE,eAAO,MAAM,eAAe,UAAU,CAAC;AACvC,sEAAsE;AACtE,eAAO,MAAM,cAAc,SAAS,CAAC;AACrC,oEAAoE;AACpE,eAAO,MAAM,cAAc,SAAS,CAAC;AACrC,0DAA0D;AAC1D,eAAO,MAAM,eAAe,MAAM,CAAC;AAEnC,0EAA0E;AAC1E,eAAO,MAAM,gBAAgB,MAAM,CAAC;AAEpC,mEAAmE;AACnE,eAAO,MAAM,YAAY,OAAO,CAAC;AAEjC,mFAAmF;AACnF,eAAO,MAAM,gBAAgB,MAAM,CAAC;AAMpC,+EAA+E;AAC/E,eAAO,MAAM,cAAc,cAAc,CAAC;AAE1C,oDAAoD;AACpD,eAAO,MAAM,sBAAsB,gBAAwB,CAAC;AAE5D,iDAAiD;AACjD,wBAAgB,mBAAmB,CAAC,KAAK,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,GAAG,MAAM,CAEtE;AAED,8CAA8C;AAC9C,wBAAgB,kBAAkB,CAAC,KAAK,EAAE,MAAM,EAAE,GAAG,SAAQ,GAAG,MAAM,CAErE;AAED,6DAA6D;AAC7D,wBAAgB,kBAAkB,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,CAWzD;AAED,mEAAmE;AACnE,eAAO,MAAM,mBAAmB,IAAI,CAAC;AACrC,6FAA6F;AAC7F,eAAO,MAAM,mBAAmB,gBAAqC,CAAC;AACtE,yDAAyD;AACzD,eAAO,MAAM,2BAA2B,kBAA6B,CAAC;AACtE,yFAAyF;AACzF,eAAO,MAAM,uBAAuB,QAAgC,CAAC;AACrE;;;GAGG;AACH,eAAO,MAAM,qBAAqB,YAAI,MAAM,EAAE,MAAM,EAAE,MAAM,CAAU,CAAC;AAuEvE,wBAAgB,eAAe,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAIpD;AAED;;;GAGG;AACH,wBAAgB,sBAAsB,CAAC,UAAU,SAAK,GAAG,MAAM,CAG9D;AAED,yEAAyE;AACzE,wBAAgB,oBAAoB,CAAC,QAAQ,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,MAAM,CAE/E;AAED,qDAAqD;AACrD,wBAAgB,kBAAkB,CAAC,UAAU,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,MAAM,CAE3E;AAED,4EAA4E;AAC5E,wBAAgB,mBAAmB,CAAC,IAAI,EAAE,MAAM,EAAE,SAAS,SAAI,GAAG,MAAM,CAGvE"}
@@ -1 +1 @@
1
- {"version":3,"file":"fs.d.ts","sourceRoot":"","sources":["../../../../src/core/tools/hashline-engine/fs.ts"],"names":[],"mappings":"AAgBA;;;;GAIG;AACH,MAAM,WAAW,WAAW;IAC3B,yFAAyF;IACzF,IAAI,EAAE,MAAM,CAAC;CACb;AAED;;;;GAIG;AACH,qBAAa,aAAc,SAAQ,KAAK;IACvC,QAAQ,CAAC,IAAI,YAAY;IAEzB,YAAY,IAAI,EAAE,MAAM,EAAE,KAAK,CAAC,EAAE,OAAO,EAIxC;CACD;AAED,+EAA+E;AAC/E,wBAAgB,UAAU,CAAC,KAAK,EAAE,OAAO,GAAG,OAAO,CAIlD;AAED;;;;;;;;;;GAUG;AACH,8BAAsB,UAAU;IAC/B,gEAAgE;IAChE,QAAQ,CAAC,QAAQ,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC;IAEjD,kFAAkF;IAC5E,cAAc,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAAG;IAErD,mFAAmF;IACnF,QAAQ,CAAC,SAAS,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,WAAW,CAAC,CAAC;IAExE,6FAA6F;IACvF,MAAM,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,CAQ3C;IAED;;;;;OAKG;IACH,aAAa,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAElC;CACD;AAED;;;GAGG;AACH,qBAAa,kBAAmB,SAAQ,UAAU;;IAGjD,YAAY,OAAO,CAAC,EAAE,QAAQ,CAAC,SAAS,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,EAKxD;IAEK,QAAQ,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAI5C;IAEK,SAAS,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,WAAW,CAAC,CAGnE;IAEK,MAAM,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,CAE3C;IAED,mEAAmE;IACnE,GAAG,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,IAAI,CAEvC;IAED,gEAAgE;IAChE,GAAG,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAEpC;IAED,sEAAsE;IACtE,MAAM,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAE5B;IAED,wBAAwB;IACxB,KAAK,IAAI,IAAI,CAEZ;IAED,uCAAuC;IACvC,OAAO,IAAI,gBAAgB,CAAC,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAE5C;CACD;AAED;;;;GAIG;AACH,qBAAa,cAAe,SAAQ,UAAU;IACvC,QAAQ,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAG5C;IAEK,SAAS,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,WAAW,CAAC,CAGnE;IAED,aAAa,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAElC;IAEK,MAAM,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,CAE3C;CACD","sourcesContent":["// @generated vendored verbatim from oh-my-pi packages/hashline @ 15b5c1397fc -- DO NOT EDIT.\n// Parity source for the Atomic hashline edit engine (issue #1483); adapted only for Atomic's Node runtime (relative imports, Bun->Node host calls, erasable constructor syntax).\nimport { existsSync } from \"node:fs\";\nimport { readFile, writeFile } from \"node:fs/promises\";\n/**\n * Storage seam for the hashline patcher. {@link Filesystem} is intentionally\n * minimal — `readText`, `writeText`, `exists` — so any backing store can be\n * adapted: disk, memory, S3, an LSP text-document protocol, a Git tree, a\n * VFS, etc.\n *\n * The patcher does its own BOM stripping and LF normalization between\n * {@link Filesystem.readText} and {@link Filesystem.writeText}; the FS deals\n * only in raw text strings.\n */\nimport * as pathModule from \"node:path\";\n\n/**\n * Result returned by {@link Filesystem.writeText}. The patcher echoes back\n * `text` so adapters that transform on serialization (e.g. notebooks) can\n * report what actually landed on disk.\n */\nexport interface WriteResult {\n\t/** Final text that was persisted. May differ from the input if the FS transformed it. */\n\ttext: string;\n}\n\n/**\n * ENOENT-like error thrown by {@link Filesystem.readText} when a path is\n * missing. Carrying a `code` property keeps the contract compatible with\n * `node:fs` callers that already check `err.code === \"ENOENT\"`.\n */\nexport class NotFoundError extends Error {\n\treadonly code = \"ENOENT\";\n\n\tconstructor(path: string, cause?: unknown) {\n\t\tsuper(`File not found: ${path}`);\n\t\tthis.name = \"NotFoundError\";\n\t\tif (cause !== undefined) (this as Error & { cause?: unknown }).cause = cause;\n\t}\n}\n\n/** Type guard for {@link NotFoundError} and structurally-compatible errors. */\nexport function isNotFound(error: unknown): boolean {\n\tif (error instanceof NotFoundError) return true;\n\tif (error instanceof Error && (error as Error & { code?: string }).code === \"ENOENT\") return true;\n\treturn false;\n}\n\n/**\n * Abstract storage backend the {@link Patcher} reads from and writes to.\n * Subclass for new backends; the package ships {@link InMemoryFilesystem} and\n * {@link NodeFilesystem} for the most common cases.\n *\n * Implementations work with raw text — the patcher handles BOM stripping and\n * line-ending normalization itself. `readText` MUST throw {@link\n * NotFoundError} (or any error for which {@link isNotFound} returns true)\n * when the path doesn't exist; that's how the patcher detects a create-vs-\n * update.\n */\nexport abstract class Filesystem {\n\t/** Read the file's full text content. Throw on missing file. */\n\tabstract readText(path: string): Promise<string>;\n\n\t/** Validate that `path` is writable before a prepared batch starts committing. */\n\tasync preflightWrite(_path: string): Promise<void> {}\n\n\t/** Persist `content` at `path`. Returns the actual final text that was written. */\n\tabstract writeText(path: string, content: string): Promise<WriteResult>;\n\n\t/** Return true when the path exists and can be read. Default: probe via {@link readText}. */\n\tasync exists(path: string): Promise<boolean> {\n\t\ttry {\n\t\t\tawait this.readText(path);\n\t\t\treturn true;\n\t\t} catch (error) {\n\t\t\tif (isNotFound(error)) return false;\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\t/**\n\t * Canonical path used as a key by external caches (e.g. snapshot\n\t * stores). The default is identity; override to return an absolute or\n\t * otherwise canonicalised path so producers and consumers of cached\n\t * snapshots agree on the key without each having to redo the resolution.\n\t */\n\tcanonicalPath(path: string): string {\n\t\treturn path;\n\t}\n}\n\n/**\n * In-memory {@link Filesystem}. Useful for tests, sandboxes, dry-runs, and as\n * a building block for stacked adapters (e.g. an LRU layer on top).\n */\nexport class InMemoryFilesystem extends Filesystem {\n\t#files = new Map<string, string>();\n\n\tconstructor(initial?: Iterable<readonly [string, string]>) {\n\t\tsuper();\n\t\tif (initial) {\n\t\t\tfor (const [path, content] of initial) this.#files.set(path, content);\n\t\t}\n\t}\n\n\tasync readText(path: string): Promise<string> {\n\t\tconst text = this.#files.get(path);\n\t\tif (text === undefined) throw new NotFoundError(path);\n\t\treturn text;\n\t}\n\n\tasync writeText(path: string, content: string): Promise<WriteResult> {\n\t\tthis.#files.set(path, content);\n\t\treturn { text: content };\n\t}\n\n\tasync exists(path: string): Promise<boolean> {\n\t\treturn this.#files.has(path);\n\t}\n\n\t/** Synchronous helper for setting up fixtures without awaiting. */\n\tset(path: string, content: string): void {\n\t\tthis.#files.set(path, content);\n\t}\n\n\t/** Synchronous helper for inspecting state without awaiting. */\n\tget(path: string): string | undefined {\n\t\treturn this.#files.get(path);\n\t}\n\n\t/** Remove a single entry. Returns true when something was removed. */\n\tdelete(path: string): boolean {\n\t\treturn this.#files.delete(path);\n\t}\n\n\t/** Wipe all entries. */\n\tclear(): void {\n\t\tthis.#files.clear();\n\t}\n\n\t/** Iterate `[path, content]` pairs. */\n\tentries(): IterableIterator<[string, string]> {\n\t\treturn this.#files.entries();\n\t}\n}\n\n/**\n * Disk-backed {@link Filesystem} using Bun's file APIs. The default for CLI\n * use. Paths are accepted as-is; callers responsible for any cwd or\n * jail/sandbox resolution should wrap this with their own subclass.\n */\nexport class NodeFilesystem extends Filesystem {\n\tasync readText(path: string): Promise<string> {\n\t\tif (!existsSync(path)) throw new NotFoundError(path);\n\t\treturn readFile(path, \"utf8\");\n\t}\n\n\tasync writeText(path: string, content: string): Promise<WriteResult> {\n\t\tawait writeFile(path, content, \"utf8\");\n\t\treturn { text: content };\n\t}\n\n\tcanonicalPath(path: string): string {\n\t\treturn pathModule.resolve(path);\n\t}\n\n\tasync exists(path: string): Promise<boolean> {\n\t\treturn existsSync(path);\n\t}\n}\n"]}
1
+ {"version":3,"file":"fs.d.ts","sourceRoot":"","sources":["../../../../src/core/tools/hashline-engine/fs.ts"],"names":[],"mappings":"AAgBA;;;;GAIG;AACH,MAAM,WAAW,WAAW;IAC3B,yFAAyF;IACzF,IAAI,EAAE,MAAM,CAAC;CACb;AAED;;;;GAIG;AACH,qBAAa,aAAc,SAAQ,KAAK;IACvC,QAAQ,CAAC,IAAI,YAAY;IAEzB,YAAY,IAAI,EAAE,MAAM,EAAE,KAAK,CAAC,EAAE,OAAO,EAIxC;CACD;AAED,+EAA+E;AAC/E,wBAAgB,UAAU,CAAC,KAAK,EAAE,OAAO,GAAG,OAAO,CAIlD;AAED;;;;;;;;;;GAUG;AACH,8BAAsB,UAAU;IAC/B,gEAAgE;IAChE,QAAQ,CAAC,QAAQ,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC;IAEjD,kFAAkF;IAC5E,cAAc,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAAG;IAErD,mFAAmF;IACnF,QAAQ,CAAC,SAAS,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,WAAW,CAAC,CAAC;IAExE,6FAA6F;IACvF,MAAM,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,CAQ3C;IAED;;;;;OAKG;IACH,aAAa,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAElC;CACD;AAED;;;GAGG;AACH,qBAAa,kBAAmB,SAAQ,UAAU;;IAGjD,YAAY,OAAO,CAAC,EAAE,QAAQ,CAAC,SAAS,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,EAKxD;IAEK,QAAQ,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAI5C;IAEK,SAAS,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,WAAW,CAAC,CAGnE;IAEK,MAAM,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,CAE3C;IAED,mEAAmE;IACnE,GAAG,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,IAAI,CAEvC;IAED,gEAAgE;IAChE,GAAG,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAEpC;IAED,sEAAsE;IACtE,MAAM,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAE5B;IAED,wBAAwB;IACxB,KAAK,IAAI,IAAI,CAEZ;IAED,uCAAuC;IACvC,OAAO,IAAI,gBAAgB,CAAC,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAE5C;CACD;AAED;;;;GAIG;AACH,qBAAa,cAAe,SAAQ,UAAU;IACvC,QAAQ,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAG5C;IAEK,SAAS,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,WAAW,CAAC,CAGnE;IAED,aAAa,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAElC;IAEK,MAAM,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,CAE3C;CACD"}
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../src/core/tools/hashline-engine/index.ts"],"names":[],"mappings":"AAEA,cAAc,YAAY,CAAC;AAC3B,cAAc,YAAY,CAAC;AAC3B,cAAc,mBAAmB,CAAC;AAClC,cAAc,aAAa,CAAC;AAC5B,cAAc,SAAS,CAAC;AACxB,cAAc,YAAY,CAAC;AAC3B,cAAc,eAAe,CAAC;AAC9B,cAAc,eAAe,CAAC;AAC9B,cAAc,gBAAgB,CAAC;AAC/B,cAAc,aAAa,CAAC;AAC5B,cAAc,cAAc,CAAC;AAC7B,cAAc,eAAe,CAAC;AAC9B,cAAc,eAAe,CAAC;AAC9B,cAAc,gBAAgB,CAAC;AAC/B,cAAc,aAAa,CAAC;AAC5B,cAAc,gBAAgB,CAAC;AAC/B,cAAc,YAAY,CAAC","sourcesContent":["// @generated vendored verbatim from oh-my-pi packages/hashline @ 15b5c1397fc -- DO NOT EDIT.\n// Parity source for the Atomic hashline edit engine (issue #1483); adapted only for Atomic's Node runtime (relative imports, Bun->Node host calls, erasable constructor syntax).\nexport * from \"./apply.js\";\nexport * from \"./block.js\";\nexport * from \"./diff-preview.js\";\nexport * from \"./format.js\";\nexport * from \"./fs.js\";\nexport * from \"./input.js\";\nexport * from \"./messages.js\";\nexport * from \"./mismatch.js\";\nexport * from \"./normalize.js\";\nexport * from \"./parser.js\";\nexport * from \"./patcher.js\";\nexport * from \"./prefixes.js\";\nexport * from \"./recovery.js\";\nexport * from \"./snapshots.js\";\nexport * from \"./stream.js\";\nexport * from \"./tokenizer.js\";\nexport * from \"./types.js\";\n"]}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../src/core/tools/hashline-engine/index.ts"],"names":[],"mappings":"AAEA,cAAc,YAAY,CAAC;AAC3B,cAAc,YAAY,CAAC;AAC3B,cAAc,mBAAmB,CAAC;AAClC,cAAc,aAAa,CAAC;AAC5B,cAAc,SAAS,CAAC;AACxB,cAAc,YAAY,CAAC;AAC3B,cAAc,eAAe,CAAC;AAC9B,cAAc,eAAe,CAAC;AAC9B,cAAc,gBAAgB,CAAC;AAC/B,cAAc,aAAa,CAAC;AAC5B,cAAc,cAAc,CAAC;AAC7B,cAAc,eAAe,CAAC;AAC9B,cAAc,eAAe,CAAC;AAC9B,cAAc,gBAAgB,CAAC;AAC/B,cAAc,aAAa,CAAC;AAC5B,cAAc,gBAAgB,CAAC;AAC/B,cAAc,YAAY,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"input.d.ts","sourceRoot":"","sources":["../../../../src/core/tools/hashline-engine/input.ts"],"names":[],"mappings":"AAiBA,OAAO,KAAK,EAAE,WAAW,EAAE,aAAa,EAAE,IAAI,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AA+EjF,UAAU,UAAU;IACnB,IAAI,EAAE,MAAM,CAAC;IACb,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,IAAI,EAAE,MAAM,CAAC;CACb;AA+CD;;;;GAIG;AACH,wBAAgB,sCAAsC,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAK7E;AAyED;;;;;GAKG;AACH,qBAAa,YAAY;;IACxB,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,QAAQ,EAAE,MAAM,GAAG,SAAS,CAAC;IACtC,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IAGtB,YAAY,GAAG,EAAE,UAAU,EAI1B;IAED;;;;OAIG;IACH,KAAK,IAAI;QAAE,KAAK,EAAE,IAAI,EAAE,CAAC;QAAC,QAAQ,EAAE,SAAS,MAAM,EAAE,CAAA;KAAE,CAGtD;IAED,qCAAqC;IACrC,IAAI,KAAK,IAAI,SAAS,IAAI,EAAE,CAE3B;IAED,uDAAuD;IACvD,IAAI,QAAQ,IAAI,SAAS,MAAM,EAAE,CAEhC;IAED;;;;OAIG;IACH,IAAI,mBAAmB,IAAI,OAAO,CAOjC;IAED,+EAA+E;IAC/E,kBAAkB,IAAI,SAAS,MAAM,EAAE,CAgBtC;IAED;;;;;;;;;OASG;IACH,OAAO,CAAC,IAAI,EAAE,MAAM,EAAE,aAAa,CAAC,EAAE,aAAa,GAAG,WAAW,CAchE;IAED;;;;;;;;;;OAUG;IACH,cAAc,CAAC,IAAI,EAAE,MAAM,EAAE,aAAa,CAAC,EAAE,aAAa,GAAG,WAAW,CAYvE;CACD;AAED;;;;;;GAMG;AACH,qBAAa,KAAK;IACjB,QAAQ,CAAC,QAAQ,EAAE,SAAS,YAAY,EAAE,CAAC;IAE3C,OAAO,eAEN;IAED;;;;;;;;;;;OAWG;IACH,MAAM,CAAC,KAAK,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,GAAE,YAAiB,GAAG,KAAK,CAG7D;IAED;;;;OAIG;IACH,MAAM,CAAC,WAAW,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,GAAE,YAAiB,GAAG,YAAY,CAK1E;CACD","sourcesContent":["// @generated vendored verbatim from oh-my-pi packages/hashline @ 15b5c1397fc -- DO NOT EDIT.\n// Parity source for the Atomic hashline edit engine (issue #1483); adapted only for Atomic's Node runtime (relative imports, Bun->Node host calls, erasable constructor syntax).\n/**\n * Top-level patch parser. Splits an authored hashline input into a list of\n * {@link PatchSection}s, each rooted at a `[PATH#HASH]` header, then exposes\n * a {@link Patch} class that gives lazy access to the parsed edits per\n * section.\n *\n * The splitter is purely lexical — it doesn't know whether a section's path\n * actually exists. That's the patcher's job.\n */\nimport * as path from \"node:path\";\nimport { applyEdits } from \"./apply.js\";\nimport { resolveBlockEdits } from \"./block.js\";\nimport { HL_FILE_HASH_EXAMPLES, HL_FILE_HASH_LENGTH, HL_FILE_HASH_SEP, HL_FILE_PREFIX, HL_FILE_SUFFIX } from \"./format.js\";\nimport { parsePatch, parsePatchStreaming } from \"./parser.js\";\nimport { Tokenizer } from \"./tokenizer.js\";\nimport type { ApplyResult, BlockResolver, Edit, SplitOptions } from \"./types.js\";\n\n// Pure classification — single shared tokenizer is safe.\nconst TOKENIZER = new Tokenizer();\n\nfunction unquoteHashlinePath(pathText: string): string {\n\tif (pathText.length < 2) return pathText;\n\tconst first = pathText[0];\n\tconst last = pathText[pathText.length - 1];\n\tif ((first === '\"' || first === \"'\") && first === last) return pathText.slice(1, -1);\n\treturn pathText;\n}\n\n/**\n * Strip apply_patch-style noise that models reflexively prepend to the\n * path. Examples observed in benchmark traces:\n *\n * `Update File:foo.ts`, `Update:foo.ts`, `UpdateFile:foo.ts`,\n * `Update/File:foo.ts`, `Update-file:foo.ts`, `Update(File):foo.ts`,\n * `Update<File:foo.ts`, `Add File:foo.ts`, `Delete File:foo.ts`,\n * `Move to:foo.ts`, `***foo.ts`, `***Update File:foo.ts`.\n *\n * We strip a leading `***` (the model duplicating the header sigil) and a\n * leading `(Update|Add|Delete|Move)[<separator>]*(File|to)?[<separator>]*:`\n * keyword block, case-insensitive. The remaining text is the real path.\n */\nconst APPLY_PATCH_PATH_NOISE_RE =\n\t/^\\*{0,3}\\s*(?:(?:update|add|delete|move)[^A-Za-z0-9]*(?:file|to)?[^A-Za-z0-9]*:)?\\s*\\*{0,3}\\s*/i;\n\nfunction stripApplyPatchPathNoise(pathText: string): string {\n\treturn pathText.replace(APPLY_PATCH_PATH_NOISE_RE, \"\");\n}\n\n/**\n * Best-effort recovery for bracketed header lines the strict tokenizer\n * rejects. Strips apply_patch keyword noise (`Update File:`, `Update:`,\n * etc.) and an extra leading `***` (some models emit a hybrid\n * `[***foo.ts#HASH]` shape), then expects `PATH(#HASH)?`.\n * Returns `null` when no clean path can be salvaged.\n */\nfunction tryParseRecoveryHeader(line: string, cwd?: string): RawSection | null {\n\tif (!line.startsWith(HL_FILE_PREFIX) || !line.endsWith(HL_FILE_SUFFIX)) return null;\n\tconst body = stripApplyPatchPathNoise(line.slice(HL_FILE_PREFIX.length, line.length - HL_FILE_SUFFIX.length).trim());\n\tif (body.length === 0) return null;\n\n\t// Trailing `#XXXX` is the tag; everything before it is the path. The\n\t// path may contain whitespace (Windows OneDrive folders, Program Files,\n\t// etc.), so we anchor the tag at end-of-body rather than scanning\n\t// forward and stopping at the first space.\n\tconst trailing = new RegExp(`#([0-9A-Fa-f]{${HL_FILE_HASH_LENGTH}})\\\\s*$`).exec(body);\n\tlet pathText: string;\n\tlet fileHash: string | undefined;\n\tif (trailing !== null) {\n\t\tpathText = body.slice(0, trailing.index);\n\t\tfileHash = trailing[1].toUpperCase();\n\t} else {\n\t\tpathText = body.replace(/\\s+$/, \"\");\n\t}\n\n\t// Same rule as the strict tokenizer: the hashline header grammar uses\n\t// `#` as the path/tag separator and does not allow `#` inside\n\t// filenames. Anything `#` left in the path body — short tags, non-hex\n\t// tags, over-long tags, stale-tag copy-paste, line-suffixed tags —\n\t// means the header is malformed, not a path with an embedded hash.\n\tif (pathText.includes(\"#\")) return null;\n\n\tconst path = normalizeHashlinePath(pathText, cwd);\n\tif (path.length === 0) return null;\n\treturn fileHash !== undefined ? { path, fileHash, diff: \"\" } : { path, diff: \"\" };\n}\n\nfunction normalizeHashlinePath(rawPath: string, cwd?: string): string {\n\tconst unquoted = stripApplyPatchPathNoise(unquoteHashlinePath(rawPath.trim()));\n\tif (!cwd || !path.isAbsolute(unquoted)) return unquoted;\n\tconst relative = path.relative(path.resolve(cwd), path.resolve(unquoted));\n\tconst isWithinCwd = relative === \"\" || (!relative.startsWith(\"..\") && !path.isAbsolute(relative));\n\treturn isWithinCwd ? relative || \".\" : unquoted;\n}\n\ninterface RawSection {\n\tpath: string;\n\tfileHash?: string;\n\tdiff: string;\n}\n\n/**\n * Parse a `[PATH]` or `[PATH#hash]` header line. Returns `null` for lines that do\n * not start with `[`. Throws the strict \"Input header must be …\" error\n * when a bracketed line fails the strict shape (so malformed paths\n * surface immediately instead of being silently re-classified as payload).\n */\nfunction parseHashlineHeaderLine(line: string, cwd?: string): RawSection | null {\n\tconst trimmed = line.trimEnd();\n\tif (!trimmed.startsWith(HL_FILE_PREFIX)) return null;\n\n\tconst token = TOKENIZER.tokenize(trimmed);\n\tif (token.kind !== \"header\") {\n\t\t// Recovery: try to extract a path from the raw line after stripping\n\t\t// apply_patch noise. This handles `[*** Update File:foo.ts#CB5A]` and\n\t\t// the half-dozen variants models actually emit.\n\t\tconst recovered = tryParseRecoveryHeader(trimmed, cwd);\n\t\tif (recovered !== null) return recovered;\n\t\tthrow new Error(\n\t\t\t`Input header must be ${HL_FILE_PREFIX}PATH${HL_FILE_SUFFIX} or ${HL_FILE_PREFIX}PATH${HL_FILE_HASH_SEP}TAG${HL_FILE_SUFFIX} with a ${HL_FILE_HASH_LENGTH}-hex content-hash tag; got ${JSON.stringify(trimmed)}.`,\n\t\t);\n\t}\n\n\tconst parsedPath = normalizeHashlinePath(token.path, cwd);\n\tif (parsedPath.length === 0) {\n\t\tthrow new Error(`Input header \"${HL_FILE_PREFIX}${HL_FILE_SUFFIX}\" is empty; provide a file path.`);\n\t}\n\treturn token.fileHash !== undefined\n\t\t? { path: parsedPath, fileHash: token.fileHash, diff: \"\" }\n\t\t: { path: parsedPath, diff: \"\" };\n}\n\nfunction stripLeadingBlankLines(input: string): string {\n\tconst stripped = input.startsWith(\"\\uFEFF\") ? input.slice(1) : input;\n\tconst lines = stripped.split(\"\\n\");\n\twhile (lines.length > 0) {\n\t\tconst head = lines[0].replace(/\\r$/, \"\");\n\t\tif (head.trim().length === 0 || TOKENIZER.tokenize(head).kind === \"envelope-begin\") {\n\t\t\tlines.shift();\n\t\t\tcontinue;\n\t\t}\n\t\tbreak;\n\t}\n\treturn lines.join(\"\\n\");\n}\n\n/**\n * Returns true when the input contains at least one line that the tokenizer\n * recognizes as a hashline op. Used by streaming previews to decide whether\n * the partial input is worth treating as a hashline patch yet.\n */\nexport function containsRecognizableHashlineOperations(input: string): boolean {\n\tfor (const line of input.split(/\\r?\\n/)) {\n\t\tif (TOKENIZER.isOp(line)) return true;\n\t}\n\treturn false;\n}\n\nfunction normalizeFallbackInput(input: string, options: SplitOptions): string {\n\tconst stripped = input.startsWith(\"\\uFEFF\") ? input.slice(1) : input;\n\tconst hasExplicitHeader = stripped\n\t\t.split(/\\r?\\n/)\n\t\t.some(rawLine => parseHashlineHeaderLine(rawLine, options.cwd) !== null);\n\tif (hasExplicitHeader) return input;\n\n\tif (!options.path || !containsRecognizableHashlineOperations(input)) return input;\n\tconst fallbackPath = normalizeHashlinePath(options.path, options.cwd);\n\tif (fallbackPath.length === 0) return input;\n\treturn `${HL_FILE_PREFIX}${fallbackPath}${HL_FILE_SUFFIX}\\n${input}`;\n}\n\nfunction splitRawSections(input: string, options: SplitOptions = {}): RawSection[] {\n\tconst stripped = stripLeadingBlankLines(normalizeFallbackInput(input, options));\n\tconst lines = stripped.split(/\\r?\\n/);\n\tconst firstLine = lines[0] ?? \"\";\n\n\tif (parseHashlineHeaderLine(firstLine, options.cwd) === null) {\n\t\t// Catch unified-diff hunk-header contamination on the first line so\n\t\t// the model sees a focused error.\n\t\tconst firstTrimmed = firstLine.trimEnd();\n\t\tif (/^@@\\s+[-+]?\\d+,\\d+\\s+[-+]?\\d+,\\d+\\s+@@/.test(firstTrimmed)) {\n\t\t\tthrow new Error(\n\t\t\t\t\"unified-diff hunk header (`@@ -N,M +N,M @@`) is not valid in hashline. \" +\n\t\t\t\t\t`File sections start with \\`${HL_FILE_PREFIX}path${HL_FILE_HASH_SEP}HASH${HL_FILE_SUFFIX}\\`; use \\`replace\\`, \\`delete\\`, or \\`insert\\` ops.`,\n\t\t\t);\n\t\t}\n\t\tconst preview = JSON.stringify(firstLine.slice(0, 120));\n\t\tthrow new Error(\n\t\t\t`input must begin with \"${HL_FILE_PREFIX}PATH${HL_FILE_HASH_SEP}HASH${HL_FILE_SUFFIX}\" on the first non-blank line for anchored edits; got: ${preview}. ` +\n\t\t\t\t`Example: \"${HL_FILE_PREFIX}src/foo.ts${HL_FILE_HASH_SEP}${HL_FILE_HASH_EXAMPLES[0]}${HL_FILE_SUFFIX}\" then edit ops.`,\n\t\t);\n\t}\n\n\tconst sections: RawSection[] = [];\n\tlet current: RawSection | undefined;\n\tlet currentLines: string[] = [];\n\n\tconst flush = () => {\n\t\tif (!current) return;\n\t\tconst hasOps = currentLines.some(line => line.trim().length > 0);\n\t\tif (hasOps) sections.push({ ...current, diff: currentLines.join(\"\\n\") });\n\t\tcurrentLines = [];\n\t};\n\n\tfor (const line of lines) {\n\t\tconst trimmed = line.trimEnd();\n\t\tconst token = TOKENIZER.tokenize(line);\n\t\tif (token.kind === \"envelope-end\" || token.kind === \"abort\") break;\n\t\tif (token.kind === \"envelope-begin\") continue;\n\n\t\t// Route every bracket-prefixed line through parseHashlineHeaderLine so\n\t\t// malformed headers still raise the strict \"Input header must be …\"\n\t\t// diagnostic (the tokenizer alone would silently classify them as\n\t\t// payload).\n\t\tif (trimmed.startsWith(HL_FILE_PREFIX)) {\n\t\t\tconst header = parseHashlineHeaderLine(line, options.cwd);\n\t\t\tif (header !== null) {\n\t\t\t\tflush();\n\t\t\t\tcurrent = header;\n\t\t\t\tcurrentLines = [];\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\t\tcurrentLines.push(line);\n\t}\n\tflush();\n\treturn sections;\n}\n\n/**\n * Snapshot of one section in a parsed {@link Patch}: a target file plus the\n * lazily-parsed list of edits that should land on it. Constructed by\n * {@link Patch.parse}; consumers usually iterate `patch.sections` rather\n * than build these directly.\n */\nexport class PatchSection {\n\treadonly path: string;\n\treadonly fileHash: string | undefined;\n\treadonly diff: string;\n\t#parsed: { edits: Edit[]; warnings: string[] } | undefined;\n\n\tconstructor(raw: RawSection) {\n\t\tthis.path = raw.path;\n\t\tthis.fileHash = raw.fileHash;\n\t\tthis.diff = raw.diff;\n\t}\n\n\t/**\n\t * Parse this section's diff body. Cached: subsequent calls return the\n\t * same `{ edits, warnings }` object so callers can safely call this from\n\t * multiple paths (preflight, apply, diff-preview).\n\t */\n\tparse(): { edits: Edit[]; warnings: readonly string[] } {\n\t\tthis.#parsed ??= parsePatch(this.diff);\n\t\treturn this.#parsed;\n\t}\n\n\t/** Parsed edits for this section. */\n\tget edits(): readonly Edit[] {\n\t\treturn this.parse().edits;\n\t}\n\n\t/** Warnings emitted during parsing of this section. */\n\tget warnings(): readonly string[] {\n\t\treturn this.parse().warnings;\n\t}\n\n\t/**\n\t * True when at least one edit anchors to concrete file content. Pure\n\t * `insert head:` / `insert tail:` literal inserts do not count: those are\n\t * safe to apply to files that don't yet exist.\n\t */\n\tget hasAnchorScopedEdit(): boolean {\n\t\treturn this.edits.some(edit => {\n\t\t\tif (edit.kind === \"delete\") return true;\n\t\t\t// A `replace block N:` edit is anchored to concrete content on line N.\n\t\t\tif (edit.kind === \"block\") return true;\n\t\t\treturn edit.cursor.kind === \"before_anchor\" || edit.cursor.kind === \"after_anchor\";\n\t\t});\n\t}\n\n\t/** Anchor lines touched by this section, sorted ascending and deduplicated. */\n\tcollectAnchorLines(): readonly number[] {\n\t\tconst lines = new Set<number>();\n\t\tfor (const edit of this.edits) {\n\t\t\tif (edit.kind === \"delete\") {\n\t\t\t\tlines.add(edit.anchor.line);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (edit.kind === \"block\") {\n\t\t\t\tlines.add(edit.anchor.line);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (edit.cursor.kind === \"before_anchor\" || edit.cursor.kind === \"after_anchor\") {\n\t\t\t\tlines.add(edit.cursor.anchor.line);\n\t\t\t}\n\t\t}\n\t\treturn [...lines].sort((a, b) => a - b);\n\t}\n\n\t/**\n\t * Apply this section's edits to `text` and return the post-edit result.\n\t * Pure: does no I/O, does not validate the section snapshot tag. The\n\t * {@link Patcher} owns tag validation and recovery; reach for this\n\t * method directly when you've already validated the file content and\n\t * just want the result.\n\t *\n\t * `blockResolver` resolves any `replace block N:` edits against `text`; an\n\t * unresolvable block throws (this is the final, authoritative preview path).\n\t */\n\tapplyTo(text: string, blockResolver?: BlockResolver): ApplyResult {\n\t\tconst { edits, warnings } = this.parse();\n\t\tconst resolveWarnings: string[] = [];\n\t\tconst resolved = resolveBlockEdits(edits, text, this.path, blockResolver, {\n\t\t\tonUnresolved: \"throw\",\n\t\t\tonWarning: warning => resolveWarnings.push(warning),\n\t\t});\n\t\tconst result = applyEdits(text, resolved);\n\t\t// Preserve parse warnings so consumers don't need to call `parse()`\n\t\t// separately.\n\t\tconst merged = [...warnings, ...resolveWarnings, ...(result.warnings ?? [])];\n\t\treturn merged.length > 0\n\t\t\t? { ...result, warnings: merged }\n\t\t\t: { text: result.text, firstChangedLine: result.firstChangedLine };\n\t}\n\n\t/**\n\t * Streaming-tolerant counterpart to {@link applyTo}. Uses\n\t * {@link parsePatchStreaming} so a trailing in-flight op (no payload yet,\n\t * or a per-token parse error mid-stream) does not throw or emit a phantom\n\t * empty-payload edit. Intended for incremental diff previews; the writer\n\t * path should always use {@link applyTo}.\n\t *\n\t * `blockResolver` resolves any `replace block N:` edits against `text`; an\n\t * unresolvable block is silently dropped so a half-written file does not\n\t * throw mid-stream.\n\t */\n\tapplyPartialTo(text: string, blockResolver?: BlockResolver): ApplyResult {\n\t\tconst { edits, warnings } = parsePatchStreaming(this.diff);\n\t\tconst resolveWarnings: string[] = [];\n\t\tconst resolved = resolveBlockEdits(edits, text, this.path, blockResolver, {\n\t\t\tonUnresolved: \"drop\",\n\t\t\tonWarning: warning => resolveWarnings.push(warning),\n\t\t});\n\t\tconst result = applyEdits(text, resolved);\n\t\tconst merged = [...warnings, ...resolveWarnings, ...(result.warnings ?? [])];\n\t\treturn merged.length > 0\n\t\t\t? { ...result, warnings: merged }\n\t\t\t: { text: result.text, firstChangedLine: result.firstChangedLine };\n\t}\n}\n\n/**\n * A parsed hashline patch — zero or more {@link PatchSection}s, each rooted\n * at a `[PATH#HASH]` header. Construct via {@link Patch.parse}.\n *\n * `Patch` is pure data: parsing is line-anchored and does not look at the\n * filesystem. To apply a patch, hand it to {@link Patcher.apply}.\n */\nexport class Patch {\n\treadonly sections: readonly PatchSection[];\n\n\tprivate constructor(sections: PatchSection[]) {\n\t\tthis.sections = sections;\n\t}\n\n\t/**\n\t * Parse `input` into a {@link Patch}. `options.cwd` resolves absolute\n\t * paths inside headers to cwd-relative form; `options.path` provides a\n\t * fallback when the input lacks a header but contains hashline ops\n\t * (useful for streaming previews).\n\t *\n\t * Consecutive sections targeting the same path are merged into a single\n\t * section with concatenated diff bodies. Anchors authored against the\n\t * same file snapshot must be applied as one batch; otherwise the first\n\t * sub-edit shifts line numbers out from under the second's anchors and\n\t * validation fails.\n\t */\n\tstatic parse(input: string, options: SplitOptions = {}): Patch {\n\t\tconst raw = mergeSamePathSections(splitRawSections(input, options));\n\t\treturn new Patch(raw.map(section => new PatchSection(section)));\n\t}\n\n\t/**\n\t * Parse `input` and return only the first section. Throws if the input\n\t * has zero sections. Convenience for the single-section case where the\n\t * caller already knows the patch is one hunk.\n\t */\n\tstatic parseSingle(input: string, options: SplitOptions = {}): PatchSection {\n\t\tconst patch = Patch.parse(input, options);\n\t\tconst first = patch.sections[0];\n\t\tif (!first) throw new Error(\"Patch input did not produce any sections.\");\n\t\treturn first;\n\t}\n}\n\n/**\n * Collapse consecutive or interleaved sections targeting the same path into a\n * single section with concatenated diffs. Anchors authored against the same\n * file snapshot must be applied as one batch; otherwise the first sub-edit\n * shifts line numbers out from under the second's anchors and validation\n * fails. Path order is preserved by first occurrence.\n */\nfunction mergeSamePathSections(sections: RawSection[]): RawSection[] {\n\tconst byPath = new Map<string, { fileHash?: string; diffs: string[] }>();\n\tfor (const section of sections) {\n\t\tconst existing = byPath.get(section.path);\n\t\tif (existing) {\n\t\t\tif (\n\t\t\t\texisting.fileHash !== undefined &&\n\t\t\t\tsection.fileHash !== undefined &&\n\t\t\t\texisting.fileHash !== section.fileHash\n\t\t\t) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Conflicting hashline snapshot tags for ${section.path}: #${existing.fileHash} and #${section.fileHash}. Re-read the file and retry with one current header.`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (existing.fileHash === undefined && section.fileHash !== undefined) existing.fileHash = section.fileHash;\n\t\t\texisting.diffs.push(section.diff);\n\t\t\tcontinue;\n\t\t}\n\t\tbyPath.set(section.path, {\n\t\t\t...(section.fileHash !== undefined ? { fileHash: section.fileHash } : {}),\n\t\t\tdiffs: [section.diff],\n\t\t});\n\t}\n\treturn Array.from(byPath, ([sectionPath, entry]) => ({\n\t\tpath: sectionPath,\n\t\t...(entry.fileHash !== undefined ? { fileHash: entry.fileHash } : {}),\n\t\tdiff: entry.diffs.join(\"\\n\"),\n\t}));\n}\n"]}
1
+ {"version":3,"file":"input.d.ts","sourceRoot":"","sources":["../../../../src/core/tools/hashline-engine/input.ts"],"names":[],"mappings":"AAiBA,OAAO,KAAK,EAAE,WAAW,EAAE,aAAa,EAAE,IAAI,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AA+EjF,UAAU,UAAU;IACnB,IAAI,EAAE,MAAM,CAAC;IACb,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,IAAI,EAAE,MAAM,CAAC;CACb;AA+CD;;;;GAIG;AACH,wBAAgB,sCAAsC,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAK7E;AAyED;;;;;GAKG;AACH,qBAAa,YAAY;;IACxB,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,QAAQ,EAAE,MAAM,GAAG,SAAS,CAAC;IACtC,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IAGtB,YAAY,GAAG,EAAE,UAAU,EAI1B;IAED;;;;OAIG;IACH,KAAK,IAAI;QAAE,KAAK,EAAE,IAAI,EAAE,CAAC;QAAC,QAAQ,EAAE,SAAS,MAAM,EAAE,CAAA;KAAE,CAGtD;IAED,qCAAqC;IACrC,IAAI,KAAK,IAAI,SAAS,IAAI,EAAE,CAE3B;IAED,uDAAuD;IACvD,IAAI,QAAQ,IAAI,SAAS,MAAM,EAAE,CAEhC;IAED;;;;OAIG;IACH,IAAI,mBAAmB,IAAI,OAAO,CAOjC;IAED,+EAA+E;IAC/E,kBAAkB,IAAI,SAAS,MAAM,EAAE,CAgBtC;IAED;;;;;;;;;OASG;IACH,OAAO,CAAC,IAAI,EAAE,MAAM,EAAE,aAAa,CAAC,EAAE,aAAa,GAAG,WAAW,CAchE;IAED;;;;;;;;;;OAUG;IACH,cAAc,CAAC,IAAI,EAAE,MAAM,EAAE,aAAa,CAAC,EAAE,aAAa,GAAG,WAAW,CAYvE;CACD;AAED;;;;;;GAMG;AACH,qBAAa,KAAK;IACjB,QAAQ,CAAC,QAAQ,EAAE,SAAS,YAAY,EAAE,CAAC;IAE3C,OAAO,eAEN;IAED;;;;;;;;;;;OAWG;IACH,MAAM,CAAC,KAAK,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,GAAE,YAAiB,GAAG,KAAK,CAG7D;IAED;;;;OAIG;IACH,MAAM,CAAC,WAAW,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,GAAE,YAAiB,GAAG,YAAY,CAK1E;CACD"}
@@ -1 +1 @@
1
- {"version":3,"file":"messages.d.ts","sourceRoot":"","sources":["../../../../src/core/tools/hashline-engine/messages.ts"],"names":[],"mappings":"AAEA,oFAAoF;AAIpF,6DAA6D;AAC7D,eAAO,MAAM,gBAAgB,IAAI,CAAC;AAElC;;;;GAIG;AACH,wBAAgB,qBAAqB,CAAC,WAAW,EAAE,SAAS,MAAM,EAAE,EAAE,SAAS,EAAE,SAAS,MAAM,EAAE,GAAG,MAAM,EAAE,CAkB5G;AAED,+DAA+D;AAC/D,eAAO,MAAM,kBAAkB,oBAAoB,CAAC;AAEpD,8DAA8D;AAC9D,eAAO,MAAM,gBAAgB,kBAAkB,CAAC;AAEhD;;;GAGG;AACH,eAAO,MAAM,YAAY,cAAc,CAAC;AAExC,oEAAoE;AACpE,eAAO,MAAM,8BAA8B,qJACmG,CAAC;AAE/I,mEAAmE;AACnE,eAAO,MAAM,sCAAsC,0JACgG,CAAC;AAEpJ,yDAAyD;AACzD,eAAO,MAAM,4BAA4B,sFAC2C,CAAC;AAErF,iDAAiD;AACjD,eAAO,MAAM,kBAAkB,uHACiF,CAAC;AAEjH,iCAAiC;AACjC,eAAO,MAAM,aAAa,6FAA6F,CAAC;AAExH,4CAA4C;AAC5C,eAAO,MAAM,WAAW,qGAC2E,CAAC;AAEpG;;;;;;;GAOG;AACH,wBAAgB,sBAAsB,CACrC,IAAI,EAAE,MAAM,EACZ,EAAE,GAAE,SAAS,GAAG,QAAoB,EACpC,SAAS,CAAC,EAAE,SAAS,MAAM,EAAE,GAC3B,MAAM,CAWR;AAED,4GAA4G;AAC5G,eAAO,MAAM,0BAA0B,0IACiG,CAAC;AAEzI;;;;GAIG;AACH,wBAAgB,oCAAoC,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAEzE;AAED;;;;GAIG;AACH,wBAAgB,wCAAwC,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAE7E;AAED;;;GAGG;AACH,eAAO,MAAM,yBAAyB,yGACiE,CAAC;AAExG,uCAAuC;AACvC,eAAO,MAAM,oBAAoB,oFAAoF,CAAC;AAEtH,iDAAiD;AACjD,eAAO,MAAM,0BAA0B,0FACiD,CAAC;AAEzF,gCAAgC;AAChC,eAAO,MAAM,YAAY,kDAAkD,CAAC;AAE5E;;;;GAIG;AACH,wBAAgB,8BAA8B,CAAC,UAAU,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,MAAM,CAE/G;AAED;;;;GAIG;AACH,wBAAgB,8BAA8B,CAAC,UAAU,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM,GAAG,MAAM,CAElH;AAED,+DAA+D;AAC/D,eAAO,MAAM,yBAAyB,qHAC6E,CAAC;AAEpH,6DAA6D;AAC7D,eAAO,MAAM,8BAA8B,4HAC+E,CAAC;AAE3H;;;;;GAKG;AACH,eAAO,MAAM,+BAA+B,wLAC0I,CAAC;AAEvL;;;;GAIG;AACH,eAAO,MAAM,sBAAsB,sMAC4J,CAAC;AAEhM;;;GAGG;AACH,wBAAgB,yBAAyB,CAAC,WAAW,EAAE,MAAM,GAAG,MAAM,CAErE","sourcesContent":["// @generated vendored verbatim from oh-my-pi packages/hashline @ 15b5c1397fc -- DO NOT EDIT.\n// Parity source for the Atomic hashline edit engine (issue #1483); adapted only for Atomic's Node runtime (relative imports, Bun->Node host calls, erasable constructor syntax).\n/** Centralized error/warning text for the hashline parser, applier, and patcher. */\n\nimport { formatNumberedLine, HL_FILE_HASH_SEP, HL_FILE_PREFIX, HL_FILE_SUFFIX } from \"./format.js\";\n\n/** Lines of context shown either side of a hash mismatch. */\nexport const MISMATCH_CONTEXT = 2;\n\n/**\n * Numbered `LINE:TEXT` rows around `anchorLines` (±{@link MISMATCH_CONTEXT}),\n * `*`-marking anchors, `...` between non-adjacent runs. Out-of-range anchors\n * contribute no rows.\n */\nexport function formatAnchoredContext(anchorLines: readonly number[], fileLines: readonly string[]): string[] {\n\tconst displayLines = new Set<number>();\n\tfor (const line of anchorLines) {\n\t\tif (line < 1 || line > fileLines.length) continue;\n\t\tconst lo = Math.max(1, line - MISMATCH_CONTEXT);\n\t\tconst hi = Math.min(fileLines.length, line + MISMATCH_CONTEXT);\n\t\tfor (let lineNum = lo; lineNum <= hi; lineNum++) displayLines.add(lineNum);\n\t}\n\tconst anchorSet = new Set(anchorLines);\n\tconst rows: string[] = [];\n\tlet previous = -1;\n\tfor (const lineNum of [...displayLines].sort((a, b) => a - b)) {\n\t\tif (previous !== -1 && lineNum > previous + 1) rows.push(\"...\");\n\t\tprevious = lineNum;\n\t\tconst marker = anchorSet.has(lineNum) ? \"*\" : \" \";\n\t\trows.push(`${marker}${formatNumberedLine(lineNum, fileLines[lineNum - 1] ?? \"\")}`);\n\t}\n\treturn rows;\n}\n\n/** Optional patch envelope start marker; silently consumed. */\nexport const BEGIN_PATCH_MARKER = \"*** Begin Patch\";\n\n/** Optional patch envelope end marker; terminates parsing. */\nexport const END_PATCH_MARKER = \"*** End Patch\";\n\n/**\n * Truncation sentinel emitted by an agent loop mid-call. Ends parsing like\n * {@link END_PATCH_MARKER}, without a warning.\n */\nexport const ABORT_MARKER = \"*** Abort\";\n\n/** Two consecutive hunks targeted the exact same concrete range. */\nexport const REPLACE_PAIR_COALESCED_WARNING =\n\t\"Two hunks targeted the same range; kept only the second. One `replace N..M:` hunk per range — the body is the final content, never old+new.\";\n\n/** Bare bodyless hunk followed by an overlapping concrete hunk. */\nexport const REPLACE_PAIR_COALESCED_OVERLAP_WARNING =\n\t\"Dropped a bare hunk overlapped by the concrete hunk after it. One `replace N..M:` hunk per range — the body is the final content, never old+new.\";\n\n/** Bare body rows auto-converted to literal `+` rows. */\nexport const BARE_BODY_AUTO_PIPED_WARNING =\n\t\"Auto-prefixed bare body row(s) with `+`. Body rows must be `+TEXT` literal lines.\";\n\n/** Unified-diff-style `-` row in a hunk body. */\nexport const MINUS_ROW_REJECTED =\n\t\"`-` rows are not valid; the range already names the lines being changed. For a literal `-` line, write `+-…`.\";\n\n/** Replace hunk with no body. */\nexport const EMPTY_REPLACE = \"`replace N..M:` needs at least one `+TEXT` body row. To delete lines, use `delete N..M`.\";\n\n/** `replace block N:` hunk with no body. */\nexport const EMPTY_BLOCK =\n\t\"`replace block N:` needs at least one `+TEXT` body row. To delete a block, use `delete block N`.\";\n\n/**\n * Block-anchored replace/delete could not resolve to a syntactic block\n * (unsupported language, blank/out-of-range line, no node beginning on N, or\n * parse error). Appends a {@link formatAnchoredContext} preview when\n * `fileLines` is given. `insert after block N:` never reaches this — it is\n * lowered to plain `insert after N:` instead (see\n * {@link insertAfterBlockUnresolvedLoweredWarning}).\n */\nexport function blockUnresolvedMessage(\n\tline: number,\n\top: \"replace\" | \"delete\" = \"replace\",\n\tfileLines?: readonly string[],\n): string {\n\tconst phrase = op === \"delete\" ? `delete block ${line}` : `replace block ${line}:`;\n\tconst fallback = op === \"delete\" ? `delete ${line}..M` : `replace ${line}..M:`;\n\tlet message =\n\t\t`\\`${phrase}\\` could not resolve a syntactic block beginning on line ${line} ` +\n\t\t`(unsupported language, blank/closer line, or parse error). Use \\`${fallback}\\` with explicit lines.`;\n\tif (fileLines) {\n\t\tconst context = formatAnchoredContext([line], fileLines);\n\t\tif (context.length > 0) message += `\\n\\n${context.join(\"\\n\")}`;\n\t}\n\treturn message;\n}\n\n/** Block-anchored edit reached a path with no {@link BlockResolver} wired in — a host-configuration bug. */\nexport const BLOCK_RESOLVER_UNAVAILABLE =\n\t\"`replace block`/`delete block`/`insert after block` are not available here (no block resolver configured). Use a concrete line range.\";\n\n/**\n * `insert after block N:` anchored on a closing-delimiter line, lowered to\n * plain `insert after N:` — the closer ends a block, and inserting after it\n * is exactly what the plain form does.\n */\nexport function insertAfterBlockCloserLoweredWarning(line: number): string {\n\treturn `\\`insert after block ${line}:\\` anchors on a closing delimiter, so it was applied as plain \\`insert after ${line}:\\`. Anchor on the line that OPENS the construct.`;\n}\n\n/**\n * `insert after block N:` anchor unresolvable (unsupported language, blank\n * line, parse error, or no resolver), lowered to plain `insert after N:` —\n * applying with a warning beats failing the patch.\n */\nexport function insertAfterBlockUnresolvedLoweredWarning(line: number): string {\n\treturn `\\`insert after block ${line}:\\` could not resolve a syntactic block on line ${line}, so it was applied as plain \\`insert after ${line}:\\`. Verify the landing line; anchor on a line that OPENS a construct.`;\n}\n\n/**\n * Internal invariant: `applyEdits` received an unresolved `replace block N:`\n * edit; `resolveBlockEdits` must run first. Wiring bug, not authored input.\n */\nexport const UNRESOLVED_BLOCK_INTERNAL =\n\t\"internal error: unresolved `replace block` edit reached the applier (resolveBlockEdits was not run).\";\n\n/** Delete hunk received a body row. */\nexport const DELETE_TAKES_NO_BODY = \"`delete N..M` does not take body rows. Remove the body, or use `replace N..M:`.\";\n\n/** `delete block N` hunk received a body row. */\nexport const DELETE_BLOCK_TAKES_NO_BODY =\n\t\"`delete block N` does not take body rows. Remove the body, or use `replace block N:`.\";\n\n/** Insert hunk with no body. */\nexport const EMPTY_INSERT = \"`insert` needs at least one `+TEXT` body row.\";\n\n/**\n * `insert after` body indented shallower than the anchor: the landing slid\n * forward past trailing closer lines — the common \"anchored on the last line\n * I read instead of after the block\" mistake.\n */\nexport function afterInsertLandingShiftWarning(anchorLine: number, landingLine: number, crossed: number): string {\n\treturn `insert after ${anchorLine}: body indented shallower than the anchor, so the landing moved past ${crossed} closing line${crossed === 1 ? \"\" : \"s\"} to after line ${landingLine}. For the deeper position inside the block, re-issue with the body indented to match.`;\n}\n\n/**\n * `insert after block N:` body indented deeper than the block's closer: the\n * landing was pulled inside the block — a deeper body almost always means\n * \"append inside the block's body\".\n */\nexport function blockInsertLandingShiftWarning(blockStart: number, closerLine: number, landingLine: number): string {\n\treturn `insert after block ${blockStart}: body indented deeper than closing line ${closerLine}, so it was placed inside the block, after line ${landingLine}. \\`insert after block\\` lands AFTER the block at sibling depth — if inside was intended, use plain \\`insert after ${closerLine}:\\`.`;\n}\n\n/** `Recovery`: an external write matched a cached snapshot. */\nexport const RECOVERY_EXTERNAL_WARNING =\n\t\"Recovered from a stale file hash using a previous read snapshot (file changed externally between read and edit).\";\n\n/** `Recovery`: a prior in-session edit advanced the hash. */\nexport const RECOVERY_SESSION_CHAIN_WARNING =\n\t\"Recovered from a stale file hash using an earlier in-session snapshot (a prior edit in this session advanced the hash).\";\n\n/**\n * `Recovery`: session-chain replay fast-path. Less certain than\n * {@link RECOVERY_SESSION_CHAIN_WARNING} — the 3-way merge refused, the\n * anchor-content gate passed, but a coincidental insert+delete earlier in\n * the chain could still misplace an anchor — hence the verify hedge.\n */\nexport const RECOVERY_SESSION_REPLAY_WARNING =\n\t\"Recovered by replaying your edits onto the current file content (a prior in-session edit changed the lines you re-targeted with a stale hash). Verify the diff matches your intent.\";\n\n/**\n * `insert head:`/`insert tail:` applied despite a stale snapshot tag.\n * Head/tail position is content-independent, so drift is non-fatal: apply\n * onto live content and warn instead of hard-failing.\n */\nexport const HEADTAIL_DRIFT_WARNING =\n\t\"Applied the `insert head:`/`insert tail:` edit despite a stale snapshot tag (file changed since your read) — head/tail position is content-independent. Re-read if the drift was unexpected.\";\n\n/**\n * Section omitted the mandatory snapshot tag. Shared by the apply\n * ({@link Patcher.prepare}) and preview/diff paths so both stay in lockstep.\n */\nexport function missingSnapshotTagMessage(sectionPath: string): string {\n\treturn `Missing hashline snapshot tag for ${sectionPath}; use \\`${HL_FILE_PREFIX}${sectionPath}${HL_FILE_HASH_SEP}tag${HL_FILE_SUFFIX}\\` from your latest read/search output. To create a new file, use the write tool.`;\n}\n"]}
1
+ {"version":3,"file":"messages.d.ts","sourceRoot":"","sources":["../../../../src/core/tools/hashline-engine/messages.ts"],"names":[],"mappings":"AAEA,oFAAoF;AAIpF,6DAA6D;AAC7D,eAAO,MAAM,gBAAgB,IAAI,CAAC;AAElC;;;;GAIG;AACH,wBAAgB,qBAAqB,CAAC,WAAW,EAAE,SAAS,MAAM,EAAE,EAAE,SAAS,EAAE,SAAS,MAAM,EAAE,GAAG,MAAM,EAAE,CAkB5G;AAED,+DAA+D;AAC/D,eAAO,MAAM,kBAAkB,oBAAoB,CAAC;AAEpD,8DAA8D;AAC9D,eAAO,MAAM,gBAAgB,kBAAkB,CAAC;AAEhD;;;GAGG;AACH,eAAO,MAAM,YAAY,cAAc,CAAC;AAExC,oEAAoE;AACpE,eAAO,MAAM,8BAA8B,qJACmG,CAAC;AAE/I,mEAAmE;AACnE,eAAO,MAAM,sCAAsC,0JACgG,CAAC;AAEpJ,yDAAyD;AACzD,eAAO,MAAM,4BAA4B,sFAC2C,CAAC;AAErF,iDAAiD;AACjD,eAAO,MAAM,kBAAkB,uHACiF,CAAC;AAEjH,iCAAiC;AACjC,eAAO,MAAM,aAAa,6FAA6F,CAAC;AAExH,4CAA4C;AAC5C,eAAO,MAAM,WAAW,qGAC2E,CAAC;AAEpG;;;;;;;GAOG;AACH,wBAAgB,sBAAsB,CACrC,IAAI,EAAE,MAAM,EACZ,EAAE,GAAE,SAAS,GAAG,QAAoB,EACpC,SAAS,CAAC,EAAE,SAAS,MAAM,EAAE,GAC3B,MAAM,CAWR;AAED,4GAA4G;AAC5G,eAAO,MAAM,0BAA0B,0IACiG,CAAC;AAEzI;;;;GAIG;AACH,wBAAgB,oCAAoC,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAEzE;AAED;;;;GAIG;AACH,wBAAgB,wCAAwC,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAE7E;AAED;;;GAGG;AACH,eAAO,MAAM,yBAAyB,yGACiE,CAAC;AAExG,uCAAuC;AACvC,eAAO,MAAM,oBAAoB,oFAAoF,CAAC;AAEtH,iDAAiD;AACjD,eAAO,MAAM,0BAA0B,0FACiD,CAAC;AAEzF,gCAAgC;AAChC,eAAO,MAAM,YAAY,kDAAkD,CAAC;AAE5E;;;;GAIG;AACH,wBAAgB,8BAA8B,CAAC,UAAU,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,MAAM,CAE/G;AAED;;;;GAIG;AACH,wBAAgB,8BAA8B,CAAC,UAAU,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM,GAAG,MAAM,CAElH;AAED,+DAA+D;AAC/D,eAAO,MAAM,yBAAyB,qHAC6E,CAAC;AAEpH,6DAA6D;AAC7D,eAAO,MAAM,8BAA8B,4HAC+E,CAAC;AAE3H;;;;;GAKG;AACH,eAAO,MAAM,+BAA+B,wLAC0I,CAAC;AAEvL;;;;GAIG;AACH,eAAO,MAAM,sBAAsB,sMAC4J,CAAC;AAEhM;;;GAGG;AACH,wBAAgB,yBAAyB,CAAC,WAAW,EAAE,MAAM,GAAG,MAAM,CAErE"}
@@ -1 +1 @@
1
- {"version":3,"file":"mismatch.d.ts","sourceRoot":"","sources":["../../../../src/core/tools/hashline-engine/mismatch.ts"],"names":[],"mappings":"AAcA,qFAAqF;AACrF,wBAAgB,2BAA2B,CAAC,GAAG,CAAC,EAAE,MAAM,GAAG,MAAM,CAMhE;AAED,8EAA8E;AAC9E,wBAAgB,QAAQ,CAAC,GAAG,EAAE,MAAM,GAAG;IAAE,IAAI,EAAE,MAAM,CAAA;CAAE,CAQtD;AAED,MAAM,WAAW,eAAe;IAC/B,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,gBAAgB,EAAE,MAAM,CAAC;IACzB,cAAc,EAAE,MAAM,CAAC;IACvB,SAAS,EAAE,MAAM,EAAE,CAAC;IACpB,WAAW,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IAChC;;;;;;OAMG;IACH,cAAc,CAAC,EAAE,OAAO,CAAC;CACzB;AAED;;;;;GAKG;AACH,qBAAa,aAAc,SAAQ,KAAK;IACvC,QAAQ,CAAC,IAAI,EAAE,MAAM,GAAG,SAAS,CAAC;IAClC,QAAQ,CAAC,gBAAgB,EAAE,MAAM,CAAC;IAClC,QAAQ,CAAC,cAAc,EAAE,MAAM,CAAC;IAChC,QAAQ,CAAC,SAAS,EAAE,MAAM,EAAE,CAAC;IAC7B,QAAQ,CAAC,WAAW,EAAE,SAAS,MAAM,EAAE,CAAC;IACxC,QAAQ,CAAC,cAAc,EAAE,OAAO,CAAC;IAEjC,YAAY,OAAO,EAAE,eAAe,EASnC;IAED,IAAI,cAAc,IAAI,MAAM,CAS3B;IAED,MAAM,CAAC,eAAe,CAAC,OAAO,EAAE,eAAe,GAAG,MAAM,EAAE,CAazD;IAED,MAAM,CAAC,oBAAoB,CAAC,OAAO,EAAE,eAAe,GAAG,MAAM,CAE5D;IAED,MAAM,CAAC,aAAa,CAAC,OAAO,EAAE,eAAe,GAAG,MAAM,CAMrD;CACD;AAED,0EAA0E;AAC1E,wBAAgB,eAAe,CAAC,GAAG,EAAE;IAAE,IAAI,EAAE,MAAM,CAAA;CAAE,EAAE,SAAS,EAAE,MAAM,EAAE,GAAG,IAAI,CAIhF","sourcesContent":["// @generated vendored verbatim from oh-my-pi packages/hashline @ 15b5c1397fc -- DO NOT EDIT.\n// Parity source for the Atomic hashline edit engine (issue #1483); adapted only for Atomic's Node runtime (relative imports, Bun->Node host calls, erasable constructor syntax).\n/**\n * Error type raised when a section's snapshot tag does not match the live file\n * content and recovery is unavailable / has failed.\n *\n * Carries enough context to render a useful diagnostic: the anchored lines\n * plus a couple of lines of surrounding context. The {@link MismatchError}\n * formats this into a message at construction time.\n */\nimport { HL_FILE_HASH_EXAMPLES, HL_FILE_HASH_SEP, HL_FILE_PREFIX, HL_FILE_SUFFIX } from \"./format.js\";\nimport { formatAnchoredContext } from \"./messages.js\";\n\nconst LINE_REF_RE = /^\\s*[>+\\-*]*\\s*(\\d+)(?::.*)?\\s*$/;\n/** Format the required-shape diagnostic shown when a line reference is malformed. */\nexport function formatFullAnchorRequirement(raw?: string): string {\n\tconst received = raw === undefined ? \"\" : ` Received ${JSON.stringify(raw)}.`;\n\treturn (\n\t\t`a bare line number from read/search output plus the section header content-hash tag ` +\n\t\t`(for example ${HL_FILE_PREFIX}src/foo.ts${HL_FILE_HASH_SEP}${HL_FILE_HASH_EXAMPLES[0]}${HL_FILE_SUFFIX} and line \"160\")${received}`\n\t);\n}\n\n/** Parse a decorated bare line-number anchor like `42`, `*42:foo`, ` > 7`. */\nexport function parseTag(ref: string): { line: number } {\n\tconst match = ref.match(LINE_REF_RE);\n\tif (!match) {\n\t\tthrow new Error(`Invalid line reference. Expected ${formatFullAnchorRequirement(ref)}.`);\n\t}\n\tconst line = Number.parseInt(match[1], 10);\n\tif (line < 1) throw new Error(`Line number must be >= 1, got ${line} in \"${ref}\".`);\n\treturn { line };\n}\n\nexport interface MismatchDetails {\n\tpath?: string;\n\texpectedFileHash: string;\n\tactualFileHash: string;\n\tfileLines: string[];\n\tanchorLines?: readonly number[];\n\t/**\n\t * `true` when the section's expected hash resolved to a recorded snapshot\n\t * (file content drifted since that snapshot), `false` when no snapshot\n\t * was ever recorded for the hash (likely fabricated or carried over from\n\t * a prior session). Drives a more actionable rejection message; defaults\n\t * to `true` for backward compatibility with direct callers.\n\t */\n\thashRecognized?: boolean;\n}\n\n/**\n * Raised when a hashline section's snapshot tag doesn't match the live file's\n * content (and recovery, if configured, declined the merge). Carries the\n * file lines plus anchored lines so renderers can produce a richer\n * diagnostic via {@link MismatchError.displayMessage}.\n */\nexport class MismatchError extends Error {\n\treadonly path: string | undefined;\n\treadonly expectedFileHash: string;\n\treadonly actualFileHash: string;\n\treadonly fileLines: string[];\n\treadonly anchorLines: readonly number[];\n\treadonly hashRecognized: boolean;\n\n\tconstructor(details: MismatchDetails) {\n\t\tsuper(MismatchError.formatMessage(details));\n\t\tthis.name = \"MismatchError\";\n\t\tthis.path = details.path;\n\t\tthis.expectedFileHash = details.expectedFileHash;\n\t\tthis.actualFileHash = details.actualFileHash;\n\t\tthis.fileLines = details.fileLines;\n\t\tthis.anchorLines = details.anchorLines ?? [];\n\t\tthis.hashRecognized = details.hashRecognized ?? true;\n\t}\n\n\tget displayMessage(): string {\n\t\treturn MismatchError.formatDisplayMessage({\n\t\t\tpath: this.path,\n\t\t\texpectedFileHash: this.expectedFileHash,\n\t\t\tactualFileHash: this.actualFileHash,\n\t\t\tfileLines: this.fileLines,\n\t\t\tanchorLines: this.anchorLines,\n\t\t\thashRecognized: this.hashRecognized,\n\t\t});\n\t}\n\n\tstatic rejectionHeader(details: MismatchDetails): string[] {\n\t\tconst pathText = details.path ? ` for ${details.path}` : \"\";\n\t\tconst hashRecognized = details.hashRecognized ?? true;\n\t\tif (!hashRecognized) {\n\t\t\treturn [\n\t\t\t\t`Edit rejected${pathText}: hash ${HL_FILE_HASH_SEP}${details.expectedFileHash} is not from this session.`,\n\t\t\t\t`The current file hashes to ${HL_FILE_HASH_SEP}${details.actualFileHash}. Re-read the file with \\`read\\` to copy a current ${HL_FILE_PREFIX}path${HL_FILE_HASH_SEP}tag${HL_FILE_SUFFIX} header — never invent the tag and never reuse one from a prior session.`,\n\t\t\t];\n\t\t}\n\t\treturn [\n\t\t\t`Edit rejected${pathText}: file changed between read and edit.`,\n\t\t\t`Section is bound to ${HL_FILE_HASH_SEP}${details.expectedFileHash}, but the current file hashes to ${HL_FILE_HASH_SEP}${details.actualFileHash}. If a prior edit in this session modified this file, copy the ${HL_FILE_PREFIX}path${HL_FILE_HASH_SEP}newhash${HL_FILE_SUFFIX} header from that edit's response; otherwise re-read the file with \\`read\\` to refresh the tag before retrying.`,\n\t\t];\n\t}\n\n\tstatic formatDisplayMessage(details: MismatchDetails): string {\n\t\treturn MismatchError.formatMessage(details);\n\t}\n\n\tstatic formatMessage(details: MismatchDetails): string {\n\t\tconst lines = MismatchError.rejectionHeader(details);\n\t\tconst context = formatAnchoredContext(details.anchorLines ?? [], details.fileLines);\n\t\tif (context.length === 0) return lines.join(\"\\n\");\n\t\tlines.push(\"\", ...context);\n\t\treturn lines.join(\"\\n\");\n\t}\n}\n\n/** Throws when the line reference is out of bounds for the given file. */\nexport function validateLineRef(ref: { line: number }, fileLines: string[]): void {\n\tif (ref.line < 1 || ref.line > fileLines.length) {\n\t\tthrow new Error(`Line ${ref.line} does not exist (file has ${fileLines.length} lines)`);\n\t}\n}\n"]}
1
+ {"version":3,"file":"mismatch.d.ts","sourceRoot":"","sources":["../../../../src/core/tools/hashline-engine/mismatch.ts"],"names":[],"mappings":"AAcA,qFAAqF;AACrF,wBAAgB,2BAA2B,CAAC,GAAG,CAAC,EAAE,MAAM,GAAG,MAAM,CAMhE;AAED,8EAA8E;AAC9E,wBAAgB,QAAQ,CAAC,GAAG,EAAE,MAAM,GAAG;IAAE,IAAI,EAAE,MAAM,CAAA;CAAE,CAQtD;AAED,MAAM,WAAW,eAAe;IAC/B,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,gBAAgB,EAAE,MAAM,CAAC;IACzB,cAAc,EAAE,MAAM,CAAC;IACvB,SAAS,EAAE,MAAM,EAAE,CAAC;IACpB,WAAW,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IAChC;;;;;;OAMG;IACH,cAAc,CAAC,EAAE,OAAO,CAAC;CACzB;AAED;;;;;GAKG;AACH,qBAAa,aAAc,SAAQ,KAAK;IACvC,QAAQ,CAAC,IAAI,EAAE,MAAM,GAAG,SAAS,CAAC;IAClC,QAAQ,CAAC,gBAAgB,EAAE,MAAM,CAAC;IAClC,QAAQ,CAAC,cAAc,EAAE,MAAM,CAAC;IAChC,QAAQ,CAAC,SAAS,EAAE,MAAM,EAAE,CAAC;IAC7B,QAAQ,CAAC,WAAW,EAAE,SAAS,MAAM,EAAE,CAAC;IACxC,QAAQ,CAAC,cAAc,EAAE,OAAO,CAAC;IAEjC,YAAY,OAAO,EAAE,eAAe,EASnC;IAED,IAAI,cAAc,IAAI,MAAM,CAS3B;IAED,MAAM,CAAC,eAAe,CAAC,OAAO,EAAE,eAAe,GAAG,MAAM,EAAE,CAazD;IAED,MAAM,CAAC,oBAAoB,CAAC,OAAO,EAAE,eAAe,GAAG,MAAM,CAE5D;IAED,MAAM,CAAC,aAAa,CAAC,OAAO,EAAE,eAAe,GAAG,MAAM,CAMrD;CACD;AAED,0EAA0E;AAC1E,wBAAgB,eAAe,CAAC,GAAG,EAAE;IAAE,IAAI,EAAE,MAAM,CAAA;CAAE,EAAE,SAAS,EAAE,MAAM,EAAE,GAAG,IAAI,CAIhF"}
@@ -1 +1 @@
1
- {"version":3,"file":"normalize.d.ts","sourceRoot":"","sources":["../../../../src/core/tools/hashline-engine/normalize.ts"],"names":[],"mappings":"AAEA;;;;GAIG;AAEH,MAAM,MAAM,UAAU,GAAG,MAAM,GAAG,IAAI,GAAG,IAAI,CAAC;AAE9C,+FAA+F;AAC/F,wBAAgB,gBAAgB,CAAC,OAAO,EAAE,MAAM,GAAG,UAAU,CAO5D;AAED,yCAAyC;AACzC,wBAAgB,aAAa,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAElD;AAED,wDAAwD;AACxD,wBAAgB,kBAAkB,CAAC,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,UAAU,GAAG,MAAM,CAG3E;AAED,MAAM,WAAW,SAAS;IACzB,yEAAyE;IACzE,GAAG,EAAE,MAAM,CAAC;IACZ,yCAAyC;IACzC,IAAI,EAAE,MAAM,CAAC;CACb;AAED,kFAAkF;AAClF,wBAAgB,QAAQ,CAAC,OAAO,EAAE,MAAM,GAAG,SAAS,CAEnD","sourcesContent":["// @generated vendored from oh-my-pi packages/hashline @ 15b5c1397fc with Atomic parity adaptations -- DO NOT EDIT.\n// Parity source for the Atomic hashline edit engine (issue #1483); adapted for Atomic's Node runtime plus CR-only line-ending round trips.\n/**\n * Minimal text-shape normalization: line-ending detection / round-trip and\n * BOM stripping. The patcher uses these to canonicalize text to LF before\n * applying edits and to restore the original shape on write-back.\n */\n\nexport type LineEnding = \"\\r\\n\" | \"\\n\" | \"\\r\";\n\n/** Detect the first line ending style in `content`. Defaults to LF when neither is present. */\nexport function detectLineEnding(content: string): LineEnding {\n\tfor (let i = 0; i < content.length; i++) {\n\t\tconst ch = content[i];\n\t\tif (ch === \"\\n\") return \"\\n\";\n\t\tif (ch === \"\\r\") return content[i + 1] === \"\\n\" ? \"\\r\\n\" : \"\\r\";\n\t}\n\treturn \"\\n\";\n}\n\n/** Normalize every line ending to LF. */\nexport function normalizeToLF(text: string): string {\n\treturn text.replace(/\\r\\n?/g, \"\\n\");\n}\n\n/** Re-encode LF text with the requested line ending. */\nexport function restoreLineEndings(text: string, ending: LineEnding): string {\n\tif (ending === \"\\r\\n\") return text.replace(/\\n/g, \"\\r\\n\");\n\treturn ending === \"\\r\" ? text.replace(/\\n/g, \"\\r\") : text;\n}\n\nexport interface BomResult {\n\t/** Either the empty string or the BOM sequence (currently UTF-8 BOM). */\n\tbom: string;\n\t/** Text with any leading BOM removed. */\n\ttext: string;\n}\n\n/** Strip a UTF-8 BOM if present and return both the BOM and the trailing text. */\nexport function stripBom(content: string): BomResult {\n\treturn content.startsWith(\"\\uFEFF\") ? { bom: \"\\uFEFF\", text: content.slice(1) } : { bom: \"\", text: content };\n}\n"]}
1
+ {"version":3,"file":"normalize.d.ts","sourceRoot":"","sources":["../../../../src/core/tools/hashline-engine/normalize.ts"],"names":[],"mappings":"AAEA;;;;GAIG;AAEH,MAAM,MAAM,UAAU,GAAG,MAAM,GAAG,IAAI,GAAG,IAAI,CAAC;AAE9C,+FAA+F;AAC/F,wBAAgB,gBAAgB,CAAC,OAAO,EAAE,MAAM,GAAG,UAAU,CAO5D;AAED,yCAAyC;AACzC,wBAAgB,aAAa,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAElD;AAED,wDAAwD;AACxD,wBAAgB,kBAAkB,CAAC,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,UAAU,GAAG,MAAM,CAG3E;AAED,MAAM,WAAW,SAAS;IACzB,yEAAyE;IACzE,GAAG,EAAE,MAAM,CAAC;IACZ,yCAAyC;IACzC,IAAI,EAAE,MAAM,CAAC;CACb;AAED,kFAAkF;AAClF,wBAAgB,QAAQ,CAAC,OAAO,EAAE,MAAM,GAAG,SAAS,CAEnD"}
@@ -1 +1 @@
1
- {"version":3,"file":"parser.d.ts","sourceRoot":"","sources":["../../../../src/core/tools/hashline-engine/parser.ts"],"names":[],"mappings":"AAiBA,OAAO,EAAmD,KAAK,KAAK,EAAa,MAAM,gBAAgB,CAAC;AACxG,OAAO,KAAK,EAAkB,IAAI,EAAE,MAAM,YAAY,CAAC;AAyFvD,qBAAa,QAAQ;;IAkBpB,IAAI,CAAC,KAAK,EAAE,KAAK,GAAG,IAAI,CA0CvB;IAED,GAAG,IAAI;QAAE,KAAK,EAAE,IAAI,EAAE,CAAC;QAAC,QAAQ,EAAE,MAAM,EAAE,CAAA;KAAE,CAK3C;IAED,YAAY,IAAI;QAAE,KAAK,EAAE,IAAI,EAAE,CAAC;QAAC,QAAQ,EAAE,MAAM,EAAE,CAAA;KAAE,CAQpD;IAED,KAAK,IAAI,IAAI,CAOZ;CAqMD;AAOD,wBAAgB,UAAU,CAAC,IAAI,EAAE,MAAM,GAAG;IAAE,KAAK,EAAE,IAAI,EAAE,CAAC;IAAC,QAAQ,EAAE,MAAM,EAAE,CAAA;CAAE,CAK9E;AAED,wBAAgB,mBAAmB,CAAC,IAAI,EAAE,MAAM,GAAG;IAAE,KAAK,EAAE,IAAI,EAAE,CAAC;IAAC,QAAQ,EAAE,MAAM,EAAE,CAAA;CAAE,CAMvF","sourcesContent":["// @generated vendored verbatim from oh-my-pi packages/hashline @ 15b5c1397fc -- DO NOT EDIT.\n// Parity source for the Atomic hashline edit engine (issue #1483); adapted only for Atomic's Node runtime (relative imports, Bun->Node host calls, erasable constructor syntax).\n/**\n * Token-driven state machine that turns a stream of {@link Token}s into a\n * flat list of {@link Edit}s. Sits between the {@link Tokenizer} and the\n * applier.\n */\nimport { HL_PAYLOAD_REPLACE } from \"./format.js\";\nimport {\n\tBARE_BODY_AUTO_PIPED_WARNING,\n\tDELETE_BLOCK_TAKES_NO_BODY,\n\tDELETE_TAKES_NO_BODY,\n\tEMPTY_BLOCK,\n\tEMPTY_INSERT,\n\tMINUS_ROW_REJECTED,\n} from \"./messages.js\";\nimport { stripOneLeadingHashlinePrefix } from \"./prefixes.js\";\nimport { type BlockTarget, cloneCursor, type ParsedRange, type Token, Tokenizer } from \"./tokenizer.js\";\nimport type { Anchor, Cursor, Edit } from \"./types.js\";\n\nfunction validateRangeOrder(range: ParsedRange, lineNum: number): void {\n\tif (range.end.line < range.start.line) {\n\t\tthrow new Error(`line ${lineNum}: range ${range.start.line}..${range.end.line} ends before it starts.`);\n\t}\n}\n\nfunction expandRange(range: ParsedRange): Anchor[] {\n\tconst anchors: Anchor[] = [];\n\tfor (let line = range.start.line; line <= range.end.line; line++) anchors.push({ line });\n\treturn anchors;\n}\n\nfunction isSkippableCommentLine(line: string): boolean {\n\treturn line.trimStart().startsWith(\"#\");\n}\n\n/**\n * Stripped remainder of a bare `N: <value>` row that is a lone quoted or\n * numeric literal (optionally comma-terminated) — the shape of a numeric-keyed\n * dict/YAML body rather than read-output paste.\n */\nconst BARE_LITERAL_VALUE_RE = /^\\s*(?:\"[^\"]*\"|'[^']*'|[-+]?\\d+(?:\\.\\d+)?)\\s*,?\\s*$/;\n\nfunction detectApplyPatchContamination(text: string, _hasPending: boolean): string | null {\n\tconst trimmed = text.trimStart();\n\tif (trimmed.length === 0) return null;\n\tif (\n\t\ttrimmed.startsWith(\"*** Update File:\") ||\n\t\ttrimmed.startsWith(\"*** Add File:\") ||\n\t\ttrimmed.startsWith(\"*** Delete File:\") ||\n\t\ttrimmed.startsWith(\"*** Move to:\")\n\t) {\n\t\tconst preview = trimmed.length > 48 ? `${trimmed.slice(0, 48)}…` : trimmed;\n\t\treturn (\n\t\t\t`apply_patch sentinel ${JSON.stringify(preview)} is not valid in hashline. ` +\n\t\t\t\"File sections start with `[path#HASH]` (no `Update File:` / `Add File:` keyword). \" +\n\t\t\t\"Use `replace N..M:`, `delete N..M`, or `insert before|after|head|tail:` ops.\"\n\t\t);\n\t}\n\tif (/^@@\\s+[-+]?\\d+,\\d+\\s+[-+]?\\d+,\\d+\\s+@@/.test(trimmed)) {\n\t\treturn (\n\t\t\t\"unified-diff hunk header (`@@ -N,M +N,M @@`) is not valid in hashline. \" +\n\t\t\t\"Use `replace N..M:`, `delete N..M`, or `insert before|after|head|tail:` ops.\"\n\t\t);\n\t}\n\tif (trimmed.startsWith(\"@@\")) {\n\t\tconst preview = trimmed.length > 48 ? `${trimmed.slice(0, 48)}…` : trimmed;\n\t\treturn (\n\t\t\t`\\`@@\\`-bracketed hunk header ${JSON.stringify(preview)} is not valid in hashline. ` +\n\t\t\t\"Drop the `@@ ... @@` brackets and write a verb header such as `replace N..M:`.\"\n\t\t);\n\t}\n\tif (/^delete\\s+[1-9]\\d*(?:\\s*(?:\\.\\.|-|…|\\s)\\s*[1-9]\\d*)?\\s*:/.test(trimmed)) {\n\t\treturn \"`delete N..M` has no colon and no body. Remove the colon and body rows.\";\n\t}\n\tif (/^[1-9]\\d*\\s*$/.test(trimmed)) {\n\t\treturn `hunk headers need a verb. Use \\`replace ${trimmed}..${trimmed}:\\` to replace, or \\`delete ${trimmed}\\` to delete.`;\n\t}\n\tconst bareRange = /^([1-9]\\d*)\\s*[-. …]+\\s*([1-9]\\d*)\\s*:?$/.exec(trimmed);\n\tif (bareRange !== null) {\n\t\treturn (\n\t\t\t`bare range hunk header ${JSON.stringify(trimmed)} is not valid. ` +\n\t\t\t`Hunk headers need a verb: write \\`replace ${bareRange[1]}..${bareRange[2]}:\\` or \\`delete ${bareRange[1]}..${bareRange[2]}\\`.`\n\t\t);\n\t}\n\treturn null;\n}\n\ninterface PendingComment {\n\tlineNum: number;\n\ttext: string;\n}\n\ntype PayloadRow = { kind: \"literal\"; text: string; lineNum: number; bare?: boolean };\n\ninterface Pending {\n\ttarget: BlockTarget;\n\tlineNum: number;\n\tpayloads: PayloadRow[];\n\t/**\n\t * Blank rows seen after the body started. Interior blanks are committed to\n\t * the payload when the next non-blank row arrives; trailing blanks before\n\t * the next header/op are layout separators and are discarded on flush.\n\t */\n\tdeferredBlanks: PayloadRow[];\n}\n\nexport class Executor {\n\t#edits: Edit[] = [];\n\t#warnings: string[] = [];\n\t#editIndex = 0;\n\t#pending: Pending | undefined;\n\t#terminated = false;\n\t#skippableComments: PendingComment[] = [];\n\n\t#discardPendingSkippableComments(): void {\n\t\tthis.#skippableComments = [];\n\t}\n\n\t#consumePendingSkippableComments(): void {\n\t\tif (this.#skippableComments.length === 0) return;\n\t\tfor (const comment of this.#skippableComments) this.#handleRaw(comment.text, comment.lineNum);\n\t\tthis.#skippableComments = [];\n\t}\n\n\tfeed(token: Token): void {\n\t\tif (this.#terminated) return;\n\t\tswitch (token.kind) {\n\t\t\tcase \"envelope-begin\":\n\t\t\t\tthis.#consumePendingSkippableComments();\n\t\t\t\treturn;\n\t\t\tcase \"envelope-end\":\n\t\t\t\tthis.#consumePendingSkippableComments();\n\t\t\t\tthis.#terminated = true;\n\t\t\t\treturn;\n\t\t\tcase \"abort\":\n\t\t\t\tthis.#terminated = true;\n\t\t\t\treturn;\n\t\t\tcase \"header\":\n\t\t\t\tthis.#consumePendingSkippableComments();\n\t\t\t\tthis.#flushPending();\n\t\t\t\treturn;\n\t\t\tcase \"blank\":\n\t\t\t\tthis.#consumePendingSkippableComments();\n\t\t\t\tthis.#handleBlank(\"\", token.lineNum);\n\t\t\t\treturn;\n\t\t\tcase \"payload-literal\":\n\t\t\t\tthis.#consumePendingSkippableComments();\n\t\t\t\tthis.#handleLiteralPayload(token.text, token.lineNum);\n\t\t\t\treturn;\n\t\t\tcase \"raw\":\n\t\t\t\tif (this.#pending === undefined && isSkippableCommentLine(token.text)) {\n\t\t\t\t\tthis.#skippableComments.push({ text: token.text, lineNum: token.lineNum });\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tthis.#consumePendingSkippableComments();\n\t\t\t\tthis.#handleRaw(token.text, token.lineNum);\n\t\t\t\treturn;\n\t\t\tcase \"op-block\":\n\t\t\t\tthis.#discardPendingSkippableComments();\n\t\t\t\tif (token.target.kind === \"replace\" || token.target.kind === \"delete\") {\n\t\t\t\t\tvalidateRangeOrder(token.target.range, token.lineNum);\n\t\t\t\t}\n\t\t\t\tthis.#flushPending();\n\t\t\t\tthis.#pending = { target: token.target, lineNum: token.lineNum, payloads: [], deferredBlanks: [] };\n\t\t\t\treturn;\n\t\t}\n\t}\n\n\tend(): { edits: Edit[]; warnings: string[] } {\n\t\tthis.#consumePendingSkippableComments();\n\t\tthis.#flushPending();\n\t\tthis.#validateNoOverlappingDeletes();\n\t\treturn { edits: this.#edits, warnings: this.#warnings };\n\t}\n\n\tendStreaming(): { edits: Edit[]; warnings: string[] } {\n\t\tthis.#consumePendingSkippableComments();\n\t\tif (this.#pending && this.#pending.payloads.length > 0) this.#flushPending();\n\t\telse if (this.#pending?.target.kind === \"delete\" || this.#pending?.target.kind === \"delete_block\")\n\t\t\tthis.#flushPending();\n\t\telse this.#pending = undefined;\n\t\tthis.#validateNoOverlappingDeletes();\n\t\treturn { edits: this.#edits, warnings: this.#warnings };\n\t}\n\n\treset(): void {\n\t\tthis.#edits = [];\n\t\tthis.#warnings = [];\n\t\tthis.#editIndex = 0;\n\t\tthis.#pending = undefined;\n\t\tthis.#skippableComments = [];\n\t\tthis.#terminated = false;\n\t}\n\n\t#validateNoOverlappingDeletes(): void {\n\t\tconst sourceLinesByAnchor = new Map<number, number[]>();\n\t\tfor (const edit of this.#edits) {\n\t\t\tif (edit.kind !== \"delete\") continue;\n\t\t\tlet sourceLines = sourceLinesByAnchor.get(edit.anchor.line);\n\t\t\tif (sourceLines === undefined) {\n\t\t\t\tsourceLines = [];\n\t\t\t\tsourceLinesByAnchor.set(edit.anchor.line, sourceLines);\n\t\t\t}\n\t\t\tif (!sourceLines.includes(edit.lineNum)) sourceLines.push(edit.lineNum);\n\t\t}\n\t\tfor (const [anchorLine, sourceLines] of sourceLinesByAnchor) {\n\t\t\tif (sourceLines.length < 2) continue;\n\t\t\tconst [firstBlock, secondBlock] = [...sourceLines].sort((a, b) => a - b);\n\t\t\tthrow new Error(\n\t\t\t\t`line ${secondBlock}: anchor line ${anchorLine} is already targeted by another hunk on line ${firstBlock}. ` +\n\t\t\t\t\t\"Issue ONE hunk per range; payload is only the final desired content, never a before/after pair.\",\n\t\t\t);\n\t\t}\n\t}\n\n\t#handleLiteralPayload(text: string, lineNum: number): void {\n\t\tconst pending = this.#pending;\n\t\tif (!pending) {\n\t\t\tthrow new Error(\n\t\t\t\t`line ${lineNum}: payload line has no preceding hunk header. ` +\n\t\t\t\t\t`Got ${JSON.stringify(`${HL_PAYLOAD_REPLACE}${text}`)}.`,\n\t\t\t);\n\t\t}\n\t\tif (pending.target.kind === \"delete\") throw new Error(`line ${lineNum}: ${DELETE_TAKES_NO_BODY}`);\n\t\tif (pending.target.kind === \"delete_block\") throw new Error(`line ${lineNum}: ${DELETE_BLOCK_TAKES_NO_BODY}`);\n\t\tthis.#commitDeferredBlanks(pending);\n\t\tpending.payloads.push({ kind: \"literal\", text, lineNum });\n\t}\n\n\t#handleRaw(text: string, lineNum: number): void {\n\t\tconst contamination = detectApplyPatchContamination(text, this.#pending !== undefined);\n\t\tif (contamination !== null) throw new Error(`line ${lineNum}: ${contamination}`);\n\t\tif (this.#pending) {\n\t\t\tif (text.trim().length === 0) {\n\t\t\t\tthis.#handleBlank(text, lineNum);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (this.#pending.target.kind === \"delete\") throw new Error(`line ${lineNum}: ${DELETE_TAKES_NO_BODY}`);\n\t\t\tif (this.#pending.target.kind === \"delete_block\")\n\t\t\t\tthrow new Error(`line ${lineNum}: ${DELETE_BLOCK_TAKES_NO_BODY}`);\n\t\t\tif (text.trimStart().charCodeAt(0) === 45 /* - */) throw new Error(`line ${lineNum}: ${MINUS_ROW_REJECTED}`);\n\t\t\tif (!this.#warnings.includes(BARE_BODY_AUTO_PIPED_WARNING)) this.#warnings.push(BARE_BODY_AUTO_PIPED_WARNING);\n\t\t\tthis.#commitDeferredBlanks(this.#pending);\n\t\t\t// Defer read-output line-number stripping to #flushPending: a bare\n\t\t\t// \"N:text\" row is only a copy-paste artifact from snapshot output\n\t\t\t// when *every* bare row in the hunk carries that prefix. Stripping a\n\t\t\t// row in isolation would corrupt a genuine body that merely starts\n\t\t\t// with \"digits:\" (YAML ports \"42:hello\", timestamps \"12:30\") when it\n\t\t\t// sits next to an unprefixed sibling. Rows with an explicit \"+\" go\n\t\t\t// through #handleLiteralPayload and are never bare, never stripped.\n\t\t\tthis.#pending.payloads.push({ kind: \"literal\", text, lineNum, bare: true });\n\t\t\treturn;\n\t\t}\n\t\tif (text.trim().length === 0) return;\n\t\tthrow new Error(\n\t\t\t`line ${lineNum}: payload line has no preceding hunk header. ` +\n\t\t\t\t`Use \\`replace N..M:\\`, \\`delete N..M\\`, or \\`insert before|after|head|tail:\\` above the body. Got ${JSON.stringify(text)}.`,\n\t\t);\n\t}\n\n\t/**\n\t * A blank row inside a hunk body is ambiguous: interior blanks are body\n\t * content (a bare-pasted body legitimately contains empty lines), while\n\t * blanks before the body starts or trailing into the next op are layout.\n\t * Defer them; {@link #commitDeferredBlanks} folds them in only when a later\n\t * non-blank row proves they were interior.\n\t */\n\t#handleBlank(text: string, lineNum: number): void {\n\t\tconst pending = this.#pending;\n\t\tif (!pending) return;\n\t\tif (pending.target.kind === \"delete\" || pending.target.kind === \"delete_block\") return;\n\t\tif (pending.payloads.length === 0) return;\n\t\tpending.deferredBlanks.push({ kind: \"literal\", text, lineNum, bare: true });\n\t}\n\n\t#commitDeferredBlanks(pending: Pending): void {\n\t\tif (pending.deferredBlanks.length === 0) return;\n\t\tif (!this.#warnings.includes(BARE_BODY_AUTO_PIPED_WARNING)) this.#warnings.push(BARE_BODY_AUTO_PIPED_WARNING);\n\t\tpending.payloads.push(...pending.deferredBlanks);\n\t\tpending.deferredBlanks = [];\n\t}\n\n\t/**\n\t * Strip a single read-output line-number prefix (`N:`) from every bare body\n\t * row, but only when *all* bare rows carry one. A uniform set of prefixes is\n\t * the signature of content pasted straight from `read`/`search` output; a\n\t * mixed set means the `N:` is genuine payload content and must stay. Rows\n\t * authored with an explicit `+` are not bare and are never touched.\n\t */\n\t#stripBarePrefixesIfUniform(payloads: PayloadRow[]): void {\n\t\tlet sawBare = false;\n\t\tlet allLiteralValues = true;\n\t\tfor (const row of payloads) {\n\t\t\tif (!row.bare || row.text.trim().length === 0) continue;\n\t\t\tsawBare = true;\n\t\t\tconst stripped = stripOneLeadingHashlinePrefix(row.text);\n\t\t\tif (stripped === row.text) return;\n\t\t\tallLiteralValues &&= BARE_LITERAL_VALUE_RE.test(stripped);\n\t\t}\n\t\tif (!sawBare) return;\n\t\t// A body where every stripped remainder is a lone quoted/numeric literal\n\t\t// (optionally comma-terminated) is the shape of a numeric-keyed dict or\n\t\t// YAML mapping (`1: \"one\",`), not read-output paste; stripping the \"N:\"\n\t\t// keys would mangle every line. Leave such bodies untouched.\n\t\tif (allLiteralValues) return;\n\t\tfor (const row of payloads) {\n\t\t\tif (row.bare && row.text.trim().length > 0) row.text = stripOneLeadingHashlinePrefix(row.text);\n\t\t}\n\t}\n\n\t#pushInsert(cursor: Cursor, text: string, lineNum: number, mode?: \"replacement\"): void {\n\t\tthis.#edits.push({\n\t\t\tkind: \"insert\",\n\t\t\tcursor: cloneCursor(cursor),\n\t\t\ttext,\n\t\t\tlineNum,\n\t\t\tindex: this.#editIndex++,\n\t\t\t...(mode === undefined ? {} : { mode }),\n\t\t});\n\t}\n\n\t#pushDelete(anchor: Anchor, lineNum: number): void {\n\t\tthis.#edits.push({ kind: \"delete\", anchor: { ...anchor }, lineNum, index: this.#editIndex++ });\n\t}\n\n\t#pushBlock(anchor: Anchor, payloads: readonly PayloadRow[], lineNum: number, mode?: \"insert_after\"): void {\n\t\tthis.#edits.push({\n\t\t\tkind: \"block\",\n\t\t\tanchor: { ...anchor },\n\t\t\tpayloads: payloads.map(payload => payload.text),\n\t\t\t...(mode === undefined ? {} : { mode }),\n\t\t\tlineNum,\n\t\t\tindex: this.#editIndex++,\n\t\t});\n\t}\n\n\t#emitPayloadRows(cursor: Cursor, payloads: readonly PayloadRow[], lineNum: number, mode?: \"replacement\"): void {\n\t\tfor (const payload of payloads) this.#pushInsert(cursor, payload.text, lineNum, mode);\n\t}\n\n\t#flushPending(): void {\n\t\tconst pending = this.#pending;\n\t\tif (!pending) return;\n\t\tconst { target, lineNum, payloads } = pending;\n\t\tthis.#stripBarePrefixesIfUniform(payloads);\n\t\tthis.#pending = undefined;\n\t\tif (target.kind === \"delete\") {\n\t\t\tfor (const anchor of expandRange(target.range)) this.#pushDelete(anchor, lineNum);\n\t\t\treturn;\n\t\t}\n\t\tif (target.kind === \"delete_block\") {\n\t\t\t// A block edit with no payloads resolves to a pure block deletion.\n\t\t\tthis.#pushBlock(target.anchor, [], lineNum);\n\t\t\treturn;\n\t\t}\n\t\tif (target.kind === \"block\") {\n\t\t\tif (payloads.length === 0) throw new Error(`line ${lineNum}: ${EMPTY_BLOCK}`);\n\t\t\tthis.#pushBlock(target.anchor, payloads, lineNum);\n\t\t\treturn;\n\t\t}\n\t\tif (target.kind === \"insert_after_block\") {\n\t\t\tif (payloads.length === 0) throw new Error(`line ${lineNum}: ${EMPTY_INSERT}`);\n\t\t\tthis.#pushBlock(target.anchor, payloads, lineNum, \"insert_after\");\n\t\t\treturn;\n\t\t}\n\t\tif (payloads.length === 0) {\n\t\t\tif (target.kind === \"replace\") {\n\t\t\t\tfor (const anchor of expandRange(target.range)) this.#pushDelete(anchor, lineNum);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthrow new Error(`line ${lineNum}: ${EMPTY_INSERT}`);\n\t\t}\n\t\tif (target.kind === \"replace\") {\n\t\t\tconst cursor: Cursor = { kind: \"before_anchor\", anchor: { ...target.range.start } };\n\t\t\tthis.#emitPayloadRows(cursor, payloads, lineNum, \"replacement\");\n\t\t\tfor (const anchor of expandRange(target.range)) this.#pushDelete(anchor, lineNum);\n\t\t\treturn;\n\t\t}\n\t\tif (target.kind === \"insert_before\") {\n\t\t\tthis.#emitPayloadRows({ kind: \"before_anchor\", anchor: { ...target.anchor } }, payloads, lineNum);\n\t\t\treturn;\n\t\t}\n\t\tif (target.kind === \"insert_after\") {\n\t\t\tthis.#emitPayloadRows({ kind: \"after_anchor\", anchor: { ...target.anchor } }, payloads, lineNum);\n\t\t\treturn;\n\t\t}\n\t\tconst cursor: Cursor = target.kind === \"bof\" ? { kind: \"bof\" } : { kind: \"eof\" };\n\t\tthis.#emitPayloadRows(cursor, payloads, lineNum);\n\t}\n}\n\nfunction drain(executor: Executor, tokenizer: Tokenizer): { edits: Edit[]; warnings: string[] } {\n\tfor (const token of tokenizer.end()) executor.feed(token);\n\treturn executor.end();\n}\n\nexport function parsePatch(diff: string): { edits: Edit[]; warnings: string[] } {\n\tconst tokenizer = new Tokenizer();\n\tconst executor = new Executor();\n\tfor (const token of tokenizer.feed(diff)) executor.feed(token);\n\treturn drain(executor, tokenizer);\n}\n\nexport function parsePatchStreaming(diff: string): { edits: Edit[]; warnings: string[] } {\n\tconst tokenizer = new Tokenizer();\n\tconst executor = new Executor();\n\tfor (const token of tokenizer.feed(diff)) executor.feed(token);\n\tfor (const token of tokenizer.end()) executor.feed(token);\n\treturn executor.endStreaming();\n}\n"]}
1
+ {"version":3,"file":"parser.d.ts","sourceRoot":"","sources":["../../../../src/core/tools/hashline-engine/parser.ts"],"names":[],"mappings":"AAiBA,OAAO,EAAmD,KAAK,KAAK,EAAa,MAAM,gBAAgB,CAAC;AACxG,OAAO,KAAK,EAAkB,IAAI,EAAE,MAAM,YAAY,CAAC;AAyFvD,qBAAa,QAAQ;;IAkBpB,IAAI,CAAC,KAAK,EAAE,KAAK,GAAG,IAAI,CA0CvB;IAED,GAAG,IAAI;QAAE,KAAK,EAAE,IAAI,EAAE,CAAC;QAAC,QAAQ,EAAE,MAAM,EAAE,CAAA;KAAE,CAK3C;IAED,YAAY,IAAI;QAAE,KAAK,EAAE,IAAI,EAAE,CAAC;QAAC,QAAQ,EAAE,MAAM,EAAE,CAAA;KAAE,CAQpD;IAED,KAAK,IAAI,IAAI,CAOZ;CAqMD;AAOD,wBAAgB,UAAU,CAAC,IAAI,EAAE,MAAM,GAAG;IAAE,KAAK,EAAE,IAAI,EAAE,CAAC;IAAC,QAAQ,EAAE,MAAM,EAAE,CAAA;CAAE,CAK9E;AAED,wBAAgB,mBAAmB,CAAC,IAAI,EAAE,MAAM,GAAG;IAAE,KAAK,EAAE,IAAI,EAAE,CAAC;IAAC,QAAQ,EAAE,MAAM,EAAE,CAAA;CAAE,CAMvF"}
@@ -1 +1 @@
1
- {"version":3,"file":"patcher.d.ts","sourceRoot":"","sources":["../../../../src/core/tools/hashline-engine/patcher.ts"],"names":[],"mappings":"AA8BA,OAAO,KAAK,EAAE,UAAU,EAAe,MAAM,SAAS,CAAC;AAEvD,OAAO,KAAK,EAAE,KAAK,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AAGtD,OAAO,EAAoB,KAAK,UAAU,EAA+C,MAAM,gBAAgB,CAAC;AAChH,OAAO,EAAE,QAAQ,EAAuB,MAAM,eAAe,CAAC;AAC9D,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,gBAAgB,CAAC;AACpD,OAAO,KAAK,EAAE,WAAW,EAAE,eAAe,EAAE,aAAa,EAAQ,MAAM,YAAY,CAAC;AAEpF,MAAM,WAAW,cAAc;IAC9B,qDAAqD;IACrD,EAAE,EAAE,UAAU,CAAC;IACf,+EAA+E;IAC/E,SAAS,EAAE,aAAa,CAAC;IACzB;;;;OAIG;IACH,aAAa,CAAC,EAAE,aAAa,CAAC;CAC9B;AAED,qFAAqF;AACrF,MAAM,WAAW,kBAAkB;IAClC,sEAAsE;IACtE,IAAI,EAAE,MAAM,CAAC;IACb,sEAAsE;IACtE,aAAa,EAAE,MAAM,CAAC;IACtB,qFAAqF;IACrF,EAAE,EAAE,QAAQ,GAAG,QAAQ,GAAG,MAAM,CAAC;IACjC,mDAAmD;IACnD,MAAM,EAAE,MAAM,CAAC;IACf,kFAAkF;IAClF,KAAK,EAAE,MAAM,CAAC;IACd,+EAA+E;IAC/E,SAAS,EAAE,MAAM,CAAC;IAClB,mGAAmG;IACnG,OAAO,EAAE,MAAM,CAAC;IAChB,yEAAyE;IACzE,QAAQ,EAAE,MAAM,CAAC;IACjB,uEAAuE;IACvE,MAAM,EAAE,MAAM,CAAC;IACf,yEAAyE;IACzE,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,4EAA4E;IAC5E,QAAQ,EAAE,MAAM,EAAE,CAAC;IACnB;;;;OAIG;IACH,gBAAgB,CAAC,EAAE,eAAe,EAAE,CAAC;CACrC;AAED,MAAM,WAAW,kBAAkB;IAClC,QAAQ,EAAE,kBAAkB,EAAE,CAAC;CAC/B;AAED;;;;GAIG;AACH,qBAAa,eAAe;IAC3B,QAAQ,CAAC,OAAO,EAAE,YAAY,CAAC;IAC/B,QAAQ,CAAC,aAAa,EAAE,MAAM,CAAC;IAC/B,QAAQ,CAAC,MAAM,EAAE,OAAO,CAAC;IACzB,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;IAC5B,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC;IACrB,QAAQ,CAAC,UAAU,EAAE,UAAU,CAAC;IAChC,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;IAC5B,QAAQ,CAAC,WAAW,EAAE,WAAW,CAAC;IAClC,QAAQ,CAAC,aAAa,EAAE,SAAS,MAAM,EAAE,CAAC;IAC1C,gBAAgB;IAChB,YACC,OAAO,EAAE,YAAY,EACrB,aAAa,EAAE,MAAM,EACrB,MAAM,EAAE,OAAO,EACf,UAAU,EAAE,MAAM,EAClB,GAAG,EAAE,MAAM,EACX,UAAU,EAAE,UAAU,EACtB,UAAU,EAAE,MAAM,EAClB,WAAW,EAAE,WAAW,EACxB,aAAa,EAAE,SAAS,MAAM,EAAE,EAWhC;IAED,mEAAmE;IACnE,IAAI,MAAM,IAAI,OAAO,CAEpB;CACD;AA6CD;;;;;GAKG;AACH,qBAAa,OAAO;;IACnB,QAAQ,CAAC,EAAE,EAAE,UAAU,CAAC;IACxB,QAAQ,CAAC,SAAS,EAAE,aAAa,CAAC;IAClC,QAAQ,CAAC,QAAQ,EAAE,QAAQ,CAAC;IAC5B,QAAQ,CAAC,aAAa,EAAE,aAAa,GAAG,SAAS,CAAC;IAElD,YAAY,OAAO,EAAE,cAAc,EAQlC;IAED;;;;;;;OAOG;IACG,KAAK,CAAC,KAAK,EAAE,KAAK,GAAG,OAAO,CAAC,kBAAkB,CAAC,CAsCrD;IAED;;;OAGG;IACG,SAAS,CAAC,KAAK,EAAE,KAAK,GAAG,OAAO,CAAC,IAAI,CAAC,CAS3C;IAED;;;;;;;;OAQG;IACG,OAAO,CAAC,OAAO,EAAE,YAAY,GAAG,OAAO,CAAC,eAAe,CAAC,CAkC7D;IAED;;;;;OAKG;IACG,MAAM,CAAC,QAAQ,EAAE,eAAe,GAAG,OAAO,CAAC,kBAAkB,CAAC,CAwCnE;CA2GD","sourcesContent":["// @generated vendored verbatim from oh-my-pi packages/hashline @ 15b5c1397fc -- DO NOT EDIT.\n// Parity source for the Atomic hashline edit engine (issue #1483); adapted only for Atomic's Node runtime (relative imports, Bun->Node host calls, erasable constructor syntax).\n/**\n * High-level patch orchestrator. Reads each section's target file via the\n * configured {@link Filesystem}, strips BOM and normalizes line endings,\n * validates the section snapshot tag (with {@link Recovery}), applies the\n * result back through the same {@link Filesystem}.\n *\n * Two layers:\n * - {@link Patcher.apply} — high-level, preflight-atomic. It validates and\n * applies every section in memory before any write hits disk, then commits\n * in order. It is not write-transactional: a mid-batch filesystem failure\n * can leave earlier sections already written, and the thrown error reports\n * which sections landed.\n * - {@link Patcher.prepare} / {@link Patcher.commit} — granular primitives\n * for callers that need per-section control (e.g. batched LSP flush,\n * custom interleaving). `prepare` performs all the read-side work,\n * validates the section snapshot tag (with recovery), and applies the\n * edits in memory. `commit` writes the prepared result and records a\n * fresh snapshot.\n *\n * Because `prepare` already runs the full apply, a multi-section batch fails\n * before any write when parsing, stale-tag validation, or in-memory apply fails.\n *\n * The patcher itself is stateless across calls; reuse one instance per\n * filesystem configuration.\n */\nimport { applyEdits } from \"./apply.js\";\nimport { hasBlockEdit, resolveBlockEdits } from \"./block.js\";\nimport { computeFileHash, formatHashlineHeader } from \"./format.js\";\nimport type { Filesystem, WriteResult } from \"./fs.js\";\nimport { isNotFound } from \"./fs.js\";\nimport type { Patch, PatchSection } from \"./input.js\";\nimport { HEADTAIL_DRIFT_WARNING, missingSnapshotTagMessage } from \"./messages.js\";\nimport { MismatchError } from \"./mismatch.js\";\nimport { detectLineEnding, type LineEnding, normalizeToLF, restoreLineEndings, stripBom } from \"./normalize.js\";\nimport { Recovery, type RecoveryResult } from \"./recovery.js\";\nimport type { SnapshotStore } from \"./snapshots.js\";\nimport type { ApplyResult, BlockResolution, BlockResolver, Edit } from \"./types.js\";\n\nexport interface PatcherOptions {\n\t/** Storage backend used for all reads and writes. */\n\tfs: Filesystem;\n\t/** Snapshot store that minted and resolves hashline section tags. Required. */\n\tsnapshots: SnapshotStore;\n\t/**\n\t * Resolves `replace block N:` anchors to concrete line spans via tree-sitter.\n\t * Optional: when omitted, any `replace block N:` edit throws on apply (the\n\t * host did not wire a resolver). Plain line-range ops never need it.\n\t */\n\tblockResolver?: BlockResolver;\n}\n\n/** Per-section result returned by {@link Patcher.apply} / {@link Patcher.commit}. */\nexport interface PatchSectionResult {\n\t/** Section path (as authored, after cwd-resolution at parse time). */\n\tpath: string;\n\t/** Filesystem-canonical key for this section (e.g. absolute path). */\n\tcanonicalPath: string;\n\t/** `\"noop\"` when the apply produced no change; otherwise `\"create\"` / `\"update\"`. */\n\top: \"create\" | \"update\" | \"noop\";\n\t/** Pre-edit text (LF-normalized, BOM-stripped). */\n\tbefore: string;\n\t/** Post-edit text (LF-normalized, BOM-stripped). For `\"noop\"` equals `before`. */\n\tafter: string;\n\t/** Same text as `after` but with the original BOM and line ending restored. */\n\tpersisted: string;\n\t/** Final text that the {@link Filesystem} actually wrote (may differ if the FS transformed it). */\n\twritten: string;\n\t/** 4-hex content-hash tag for `after`. Use to anchor follow-up edits. */\n\tfileHash: string;\n\t/** Hashline section header (`[path#tag]`) of the post-edit content. */\n\theader: string;\n\t/** 1-indexed first changed line in `after`, or `undefined` for noops. */\n\tfirstChangedLine?: number;\n\t/** Warnings collected by the parser, applier, and (optionally) recovery. */\n\twarnings: string[];\n\t/**\n\t * Resolved spans for any `replace block`/`delete block` ops, present when the\n\t * apply matched the tagged content. Undefined for patches with no block ops\n\t * (and for resolutions routed through drift recovery, where numbers shift).\n\t */\n\tblockResolutions?: BlockResolution[];\n}\n\nexport interface PatcherApplyResult {\n\tsections: PatchSectionResult[];\n}\n\n/**\n * Opaque token returned by {@link Patcher.prepare}. Carries the section, the\n * raw file content read off disk, and the in-memory apply result.\n * {@link Patcher.commit} just writes the {@link PreparedSection.applyResult}.\n */\nexport class PreparedSection {\n\treadonly section: PatchSection;\n\treadonly canonicalPath: string;\n\treadonly exists: boolean;\n\treadonly rawContent: string;\n\treadonly bom: string;\n\treadonly lineEnding: LineEnding;\n\treadonly normalized: string;\n\treadonly applyResult: ApplyResult;\n\treadonly parseWarnings: readonly string[];\n\t/** @internal */\n\tconstructor(\n\t\tsection: PatchSection,\n\t\tcanonicalPath: string,\n\t\texists: boolean,\n\t\trawContent: string,\n\t\tbom: string,\n\t\tlineEnding: LineEnding,\n\t\tnormalized: string,\n\t\tapplyResult: ApplyResult,\n\t\tparseWarnings: readonly string[],\n\t) {\n\t\tthis.section = section;\n\t\tthis.canonicalPath = canonicalPath;\n\t\tthis.exists = exists;\n\t\tthis.rawContent = rawContent;\n\t\tthis.bom = bom;\n\t\tthis.lineEnding = lineEnding;\n\t\tthis.normalized = normalized;\n\t\tthis.applyResult = applyResult;\n\t\tthis.parseWarnings = parseWarnings;\n\t}\n\n\t/** Convenience: returns true when the apply produced no change. */\n\tget isNoop(): boolean {\n\t\treturn this.applyResult.text === this.normalized;\n\t}\n}\n\nfunction hasAnchorScopedEdit(edits: readonly Edit[]): boolean {\n\treturn edits.some(edit => {\n\t\tif (edit.kind === \"delete\") return true;\n\t\t// A `replace block N:` edit anchors to concrete content on line N.\n\t\tif (edit.kind === \"block\") return true;\n\t\treturn edit.cursor.kind === \"before_anchor\" || edit.cursor.kind === \"after_anchor\";\n\t});\n}\n\nfunction assertSectionHashPresent(sectionPath: string, fileHash: string | undefined): void {\n\tif (fileHash !== undefined) return;\n\tthrow new Error(missingSnapshotTagMessage(sectionPath));\n}\n\nfunction recoveryToApplyResult(result: RecoveryResult): ApplyResult {\n\treturn {\n\t\ttext: result.text,\n\t\tfirstChangedLine: result.firstChangedLine,\n\t\twarnings: result.warnings,\n\t};\n}\nfunction mergeWarnings(...sources: ReadonlyArray<readonly string[] | undefined>): string[] {\n\tconst out: string[] = [];\n\tfor (const source of sources) {\n\t\tif (!source) continue;\n\t\tfor (const warning of source) out.push(warning);\n\t}\n\treturn out;\n}\n\nfunction assertUniqueCanonicalPaths(prepared: readonly PreparedSection[]): void {\n\tconst seen = new Map<string, string>();\n\tfor (const entry of prepared) {\n\t\tconst previous = seen.get(entry.canonicalPath);\n\t\tif (previous !== undefined) {\n\t\t\tthrow new Error(\n\t\t\t\t`Multiple hashline sections resolve to the same file (${previous} and ${entry.section.path}). Merge their ops under one header before applying.`,\n\t\t\t);\n\t\t}\n\t\tseen.set(entry.canonicalPath, entry.section.path);\n\t}\n}\n\n/**\n * High-level patcher. Wires a {@link Filesystem} and a required\n * {@link SnapshotStore} together with the parsing + applying core.\n *\n * Construct once per FS configuration; reuse across patches.\n */\nexport class Patcher {\n\treadonly fs: Filesystem;\n\treadonly snapshots: SnapshotStore;\n\treadonly recovery: Recovery;\n\treadonly blockResolver: BlockResolver | undefined;\n\n\tconstructor(options: PatcherOptions) {\n\t\tif (!options.snapshots) {\n\t\t\tthrow new Error(\"Hashline Patcher requires a SnapshotStore; section tags are opaque store pointers.\");\n\t\t}\n\t\tthis.fs = options.fs;\n\t\tthis.snapshots = options.snapshots;\n\t\tthis.recovery = new Recovery(options.snapshots);\n\t\tthis.blockResolver = options.blockResolver;\n\t}\n\n\t/**\n\t * Apply every section in `patch`. `prepare` runs the full apply for each\n\t * section in memory before any write hits the filesystem, so a\n\t * multi-section batch fails before writing on parse/validation/apply errors.\n\t * Write commits are sequential rather than transactional; if a write fails,\n\t * earlier sections may already be on disk and are listed in the thrown error.\n\t * Returns one {@link PatchSectionResult} per section in the original patch order.\n\t */\n\tasync apply(patch: Patch): Promise<PatcherApplyResult> {\n\t\t// Single-section fast path.\n\t\tif (patch.sections.length === 1) {\n\t\t\tconst prepared = await this.prepare(patch.sections[0]);\n\t\t\treturn { sections: [await this.commit(prepared)] };\n\t\t}\n\n\t\t// Prepare every section first so any failure (stale hash, missing\n\t\t// file, parse error, in-memory no-op) surfaces before any write.\n\t\tconst prepared: PreparedSection[] = [];\n\t\tfor (const section of patch.sections) prepared.push(await this.prepare(section));\n\t\tassertUniqueCanonicalPaths(prepared);\n\t\tfor (const entry of prepared) {\n\t\t\tif (entry.isNoop) {\n\t\t\t\tthrow new Error(`Edits to ${entry.section.path} resulted in no changes being made.`);\n\t\t\t}\n\t\t}\n\n\t\tconst results: PatchSectionResult[] = [];\n\t\tfor (let index = 0; index < prepared.length; index++) {\n\t\t\ttry {\n\t\t\t\tresults.push(await this.commit(prepared[index]));\n\t\t\t} catch (error) {\n\t\t\t\t// A mid-batch write failure leaves earlier sections on disk with no\n\t\t\t\t// rollback; report exactly which sections landed so the caller can\n\t\t\t\t// re-issue only the missing ones instead of double-applying.\n\t\t\t\tconst written = prepared.slice(0, index).map(entry => entry.section.path);\n\t\t\t\tconst notWritten = prepared.slice(index + 1).map(entry => entry.section.path);\n\t\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Failed to write ${prepared[index].section.path}: ${message}` +\n\t\t\t\t\t\t(written.length > 0 ? ` Sections already written: ${written.join(\", \")}.` : \"\") +\n\t\t\t\t\t\t(notWritten.length > 0 ? ` Sections not written: ${notWritten.join(\", \")}.` : \"\"),\n\t\t\t\t\t{ cause: error },\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\treturn { sections: results };\n\t}\n\n\t/**\n\t * Run the preflight pass only: read, parse, validate, apply-in-memory.\n\t * No writes hit the filesystem. Use for CI checks and dry runs.\n\t */\n\tasync preflight(patch: Patch): Promise<void> {\n\t\tconst prepared: PreparedSection[] = [];\n\t\tfor (const section of patch.sections) prepared.push(await this.prepare(section));\n\t\tassertUniqueCanonicalPaths(prepared);\n\t\tfor (const entry of prepared) {\n\t\t\tif (entry.isNoop) {\n\t\t\t\tthrow new Error(`Edits to ${entry.section.path} resulted in no changes being made.`);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Read a section's target file, parse the section, validate the snapshot\n\t * tag (with recovery), and apply the edits in memory. Returns a\n\t * {@link PreparedSection} which can be fed to {@link commit} to land\n\t * the result on the filesystem.\n\t *\n\t * Throws on parse error, missing-file-for-anchored-edit, or unrecovered\n\t * tag mismatch ({@link MismatchError}).\n\t */\n\tasync prepare(section: PatchSection): Promise<PreparedSection> {\n\t\tconst { edits, warnings: parseWarnings } = section.parse();\n\t\tassertSectionHashPresent(section.path, section.fileHash);\n\n\t\tconst canonicalPath = this.fs.canonicalPath(section.path);\n\t\tawait this.fs.preflightWrite(section.path);\n\t\tconst { exists, rawContent } = await this.#tryRead(section.path);\n\t\tif (!exists) {\n\t\t\tthrow new Error(`File not found: ${section.path}. Use the write tool to create new files.`);\n\t\t}\n\n\t\tconst { bom, text } = stripBom(rawContent);\n\t\tconst lineEnding = detectLineEnding(text);\n\t\tconst normalized = normalizeToLF(text);\n\n\t\tconst applyResult = this.#applyWithRecovery({\n\t\t\tsection,\n\t\t\tcanonicalPath,\n\t\t\texists,\n\t\t\tnormalized,\n\t\t\tedits,\n\t\t});\n\n\t\treturn new PreparedSection(\n\t\t\tsection,\n\t\t\tcanonicalPath,\n\t\t\texists,\n\t\t\trawContent,\n\t\t\tbom,\n\t\t\tlineEnding,\n\t\t\tnormalized,\n\t\t\tapplyResult,\n\t\t\tparseWarnings,\n\t\t);\n\t}\n\n\t/**\n\t * Commit a previously {@link prepare}d section to the filesystem.\n\t * Restores line endings and BOM, writes via the {@link Filesystem}, and\n\t * records a fresh snapshot in the {@link SnapshotStore} keyed by the\n\t * filesystem-canonical path.\n\t */\n\tasync commit(prepared: PreparedSection): Promise<PatchSectionResult> {\n\t\tconst { section, normalized, bom, lineEnding, parseWarnings, exists, applyResult, canonicalPath } = prepared;\n\t\tconst after = applyResult.text;\n\t\tconst warnings = mergeWarnings(parseWarnings, applyResult.warnings);\n\n\t\tif (after === normalized) {\n\t\t\tconst hash = this.#recordFullSnapshot(canonicalPath, normalized);\n\t\t\treturn {\n\t\t\t\tpath: section.path,\n\t\t\t\tcanonicalPath,\n\t\t\t\top: \"noop\",\n\t\t\t\tbefore: normalized,\n\t\t\t\tafter: normalized,\n\t\t\t\tpersisted: prepared.rawContent,\n\t\t\t\twritten: prepared.rawContent,\n\t\t\t\tfileHash: hash,\n\t\t\t\theader: formatHashlineHeader(section.path, hash),\n\t\t\t\twarnings,\n\t\t\t};\n\t\t}\n\n\t\tconst persisted = bom + restoreLineEndings(after, lineEnding);\n\t\tconst write: WriteResult = await this.fs.writeText(section.path, persisted);\n\t\tconst fileHash = this.#recordFullSnapshot(canonicalPath, after);\n\t\tconst op = exists ? \"update\" : \"create\";\n\n\t\treturn {\n\t\t\tpath: section.path,\n\t\t\tcanonicalPath,\n\t\t\top,\n\t\t\tbefore: normalized,\n\t\t\tafter,\n\t\t\tpersisted,\n\t\t\twritten: write.text,\n\t\t\tfileHash,\n\t\t\theader: formatHashlineHeader(section.path, fileHash),\n\t\t\tfirstChangedLine: applyResult.firstChangedLine,\n\t\t\tblockResolutions: applyResult.blockResolutions,\n\t\t\twarnings,\n\t\t};\n\t}\n\n\tasync #tryRead(path: string): Promise<{ exists: boolean; rawContent: string }> {\n\t\ttry {\n\t\t\tconst content = await this.fs.readText(path);\n\t\t\treturn { exists: true, rawContent: content };\n\t\t} catch (error) {\n\t\t\tif (isNotFound(error)) return { exists: false, rawContent: \"\" };\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\t#recordFullSnapshot(canonicalPath: string, normalized: string): string {\n\t\treturn this.snapshots.record(canonicalPath, normalized);\n\t}\n\t#mismatchError(\n\t\tsection: PatchSection,\n\t\tcanonicalPath: string,\n\t\tnormalized: string,\n\t\texpected: string,\n\t\thashRecognized: boolean,\n\t): MismatchError {\n\t\tconst actualFileHash = this.#recordFullSnapshot(canonicalPath, normalized);\n\t\treturn new MismatchError({\n\t\t\tpath: section.path,\n\t\t\texpectedFileHash: expected,\n\t\t\tactualFileHash,\n\t\t\tfileLines: normalized.split(\"\\n\"),\n\t\t\tanchorLines: section.collectAnchorLines(),\n\t\t\thashRecognized,\n\t\t});\n\t}\n\n\t#applyWithRecovery(args: {\n\t\tsection: PatchSection;\n\t\tcanonicalPath: string;\n\t\texists: boolean;\n\t\tnormalized: string;\n\t\tedits: readonly Edit[];\n\t}): ApplyResult {\n\t\tconst { section, canonicalPath, exists, normalized, edits } = args;\n\t\tconst expected = exists ? section.fileHash : undefined;\n\t\tconst expectedSnapshot = expected === undefined ? null : this.snapshots.byHash(canonicalPath, expected);\n\t\tconst liveHashMatches = expected !== undefined && computeFileHash(normalized) === expected;\n\t\tconst liveSnapshot = expected === undefined ? null : this.snapshots.byHashAndText(canonicalPath, expected, normalized);\n\t\tconst liveMatches = liveHashMatches && liveSnapshot !== null;\n\t\tif (liveHashMatches && !liveMatches) {\n\t\t\tthrow this.#mismatchError(section, canonicalPath, normalized, expected, expectedSnapshot !== null);\n\t\t}\n\n\t\t// Resolve `replace block N:` edits to concrete ranges before recovery\n\t\t// runs. Block anchors are expressed against the snapshot the section tag\n\t\t// names, so resolve against that exact text:\n\t\t// - live content matches the tag (or there is no tag) → resolve against\n\t\t// the live, normalized content;\n\t\t// - the file drifted → resolve against the tagged snapshot's text so the\n\t\t// resulting ranges flow through the 3-way-merge recovery below.\n\t\t// When a block edit needs the tagged snapshot but it is unavailable, the\n\t\t// range cannot be placed safely — reject with a MismatchError (re-read).\n\t\tconst blockResolutions: BlockResolution[] = [];\n\t\tconst resolveWarnings: string[] = [];\n\t\tlet resolved: readonly Edit[] = edits;\n\t\tif (hasBlockEdit(edits)) {\n\t\t\tconst baseText =\n\t\t\t\texpected === undefined || liveMatches ? normalized : expectedSnapshot?.text;\n\t\t\tif (baseText === undefined) {\n\t\t\t\tthrow this.#mismatchError(section, canonicalPath, normalized, expected ?? \"\", false);\n\t\t\t}\n\t\t\tresolved = resolveBlockEdits(edits, baseText, section.path, this.blockResolver, {\n\t\t\t\tonUnresolved: \"throw\",\n\t\t\t\tonResolved: resolution => blockResolutions.push(resolution),\n\t\t\t\tonWarning: warning => resolveWarnings.push(warning),\n\t\t\t});\n\t\t}\n\t\tconst withResolveWarnings = (result: ApplyResult): ApplyResult =>\n\t\t\tresolveWarnings.length === 0\n\t\t\t\t? result\n\t\t\t\t: { ...result, warnings: [...resolveWarnings, ...(result.warnings ?? [])] };\n\n\t\t// No tag, or the tag still names the live content: an edit anchored at any\n\t\t// line is safe to apply, and the resolved block spans line up with what\n\t\t// the caller read, so echo them back. (A drifted file falls through to\n\t\t// recovery below, where line numbers shift, so resolutions are dropped.)\n\t\tif (expected === undefined || liveMatches) {\n\t\t\tconst result = applyEdits(normalized, resolved);\n\t\t\treturn withResolveWarnings(blockResolutions.length > 0 ? { ...result, blockResolutions } : result);\n\t\t}\n\t\t// Head/tail-only inserts are position-stable: \"start\"/\"end\" cannot move\n\t\t// with content drift, so a stale tag is non-fatal. Apply onto the live\n\t\t// content and warn instead of hard-failing — unlike an anchored\n\t\t// mismatch, which cannot be safely relocated and must reject.\n\t\tif (!hasAnchorScopedEdit(resolved)) {\n\t\t\tconst result = applyEdits(normalized, resolved);\n\t\t\treturn withResolveWarnings({ ...result, warnings: [HEADTAIL_DRIFT_WARNING, ...(result.warnings ?? [])] });\n\t\t}\n\t\t// File drifted: try to replay the edit against the version the tag\n\t\t// names and 3-way-merge it onto the live content.\n\t\tconst recovered = this.recovery.tryRecover({\n\t\t\tpath: canonicalPath,\n\t\t\tcurrentText: normalized,\n\t\t\tfileHash: expected,\n\t\t\tedits: resolved,\n\t\t});\n\t\tif (recovered) return withResolveWarnings(recoveryToApplyResult(recovered));\n\t\tconst hashRecognized = expectedSnapshot !== null;\n\t\tthrow this.#mismatchError(section, canonicalPath, normalized, expected, hashRecognized);\n\t}\n}\n"]}
1
+ {"version":3,"file":"patcher.d.ts","sourceRoot":"","sources":["../../../../src/core/tools/hashline-engine/patcher.ts"],"names":[],"mappings":"AA8BA,OAAO,KAAK,EAAE,UAAU,EAAe,MAAM,SAAS,CAAC;AAEvD,OAAO,KAAK,EAAE,KAAK,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AAGtD,OAAO,EAAoB,KAAK,UAAU,EAA+C,MAAM,gBAAgB,CAAC;AAChH,OAAO,EAAE,QAAQ,EAAuB,MAAM,eAAe,CAAC;AAC9D,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,gBAAgB,CAAC;AACpD,OAAO,KAAK,EAAE,WAAW,EAAE,eAAe,EAAE,aAAa,EAAQ,MAAM,YAAY,CAAC;AAEpF,MAAM,WAAW,cAAc;IAC9B,qDAAqD;IACrD,EAAE,EAAE,UAAU,CAAC;IACf,+EAA+E;IAC/E,SAAS,EAAE,aAAa,CAAC;IACzB;;;;OAIG;IACH,aAAa,CAAC,EAAE,aAAa,CAAC;CAC9B;AAED,qFAAqF;AACrF,MAAM,WAAW,kBAAkB;IAClC,sEAAsE;IACtE,IAAI,EAAE,MAAM,CAAC;IACb,sEAAsE;IACtE,aAAa,EAAE,MAAM,CAAC;IACtB,qFAAqF;IACrF,EAAE,EAAE,QAAQ,GAAG,QAAQ,GAAG,MAAM,CAAC;IACjC,mDAAmD;IACnD,MAAM,EAAE,MAAM,CAAC;IACf,kFAAkF;IAClF,KAAK,EAAE,MAAM,CAAC;IACd,+EAA+E;IAC/E,SAAS,EAAE,MAAM,CAAC;IAClB,mGAAmG;IACnG,OAAO,EAAE,MAAM,CAAC;IAChB,yEAAyE;IACzE,QAAQ,EAAE,MAAM,CAAC;IACjB,uEAAuE;IACvE,MAAM,EAAE,MAAM,CAAC;IACf,yEAAyE;IACzE,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,4EAA4E;IAC5E,QAAQ,EAAE,MAAM,EAAE,CAAC;IACnB;;;;OAIG;IACH,gBAAgB,CAAC,EAAE,eAAe,EAAE,CAAC;CACrC;AAED,MAAM,WAAW,kBAAkB;IAClC,QAAQ,EAAE,kBAAkB,EAAE,CAAC;CAC/B;AAED;;;;GAIG;AACH,qBAAa,eAAe;IAC3B,QAAQ,CAAC,OAAO,EAAE,YAAY,CAAC;IAC/B,QAAQ,CAAC,aAAa,EAAE,MAAM,CAAC;IAC/B,QAAQ,CAAC,MAAM,EAAE,OAAO,CAAC;IACzB,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;IAC5B,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC;IACrB,QAAQ,CAAC,UAAU,EAAE,UAAU,CAAC;IAChC,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;IAC5B,QAAQ,CAAC,WAAW,EAAE,WAAW,CAAC;IAClC,QAAQ,CAAC,aAAa,EAAE,SAAS,MAAM,EAAE,CAAC;IAC1C,gBAAgB;IAChB,YACC,OAAO,EAAE,YAAY,EACrB,aAAa,EAAE,MAAM,EACrB,MAAM,EAAE,OAAO,EACf,UAAU,EAAE,MAAM,EAClB,GAAG,EAAE,MAAM,EACX,UAAU,EAAE,UAAU,EACtB,UAAU,EAAE,MAAM,EAClB,WAAW,EAAE,WAAW,EACxB,aAAa,EAAE,SAAS,MAAM,EAAE,EAWhC;IAED,mEAAmE;IACnE,IAAI,MAAM,IAAI,OAAO,CAEpB;CACD;AA6CD;;;;;GAKG;AACH,qBAAa,OAAO;;IACnB,QAAQ,CAAC,EAAE,EAAE,UAAU,CAAC;IACxB,QAAQ,CAAC,SAAS,EAAE,aAAa,CAAC;IAClC,QAAQ,CAAC,QAAQ,EAAE,QAAQ,CAAC;IAC5B,QAAQ,CAAC,aAAa,EAAE,aAAa,GAAG,SAAS,CAAC;IAElD,YAAY,OAAO,EAAE,cAAc,EAQlC;IAED;;;;;;;OAOG;IACG,KAAK,CAAC,KAAK,EAAE,KAAK,GAAG,OAAO,CAAC,kBAAkB,CAAC,CAsCrD;IAED;;;OAGG;IACG,SAAS,CAAC,KAAK,EAAE,KAAK,GAAG,OAAO,CAAC,IAAI,CAAC,CAS3C;IAED;;;;;;;;OAQG;IACG,OAAO,CAAC,OAAO,EAAE,YAAY,GAAG,OAAO,CAAC,eAAe,CAAC,CAkC7D;IAED;;;;;OAKG;IACG,MAAM,CAAC,QAAQ,EAAE,eAAe,GAAG,OAAO,CAAC,kBAAkB,CAAC,CAwCnE;CA2GD"}
@@ -1 +1 @@
1
- {"version":3,"file":"prefixes.d.ts","sourceRoot":"","sources":["../../../../src/core/tools/hashline-engine/prefixes.ts"],"names":[],"mappings":"AAEA;;;;;;;;;;;;;;GAcG;AAmBH;;;;;;GAMG;AACH,wBAAgB,6BAA6B,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAElE;AAwCD;;;;;;;GAOG;AACH,wBAAgB,oBAAoB,CAAC,KAAK,EAAE,MAAM,EAAE,GAAG,MAAM,EAAE,CAwB9D;AAED;;;GAGG;AACH,wBAAgB,qBAAqB,CAAC,KAAK,EAAE,MAAM,EAAE,GAAG,MAAM,EAAE,CAQ/D;AAED;;;GAGG;AACH,wBAAgB,iBAAiB,CAAC,IAAI,EAAE,MAAM,EAAE,GAAG,MAAM,GAAG,IAAI,GAAG,SAAS,GAAG,MAAM,EAAE,CAOtF","sourcesContent":["// @generated vendored verbatim from oh-my-pi packages/hashline @ 15b5c1397fc -- DO NOT EDIT.\n// Parity source for the Atomic hashline edit engine (issue #1483); adapted only for Atomic's Node runtime (relative imports, Bun->Node host calls, erasable constructor syntax).\n/**\n * When a hashline payload is authored against `read`/`search` output, each\n * line is prefixed with either a hashline-mode line number (`123:`) or, for\n * diff-style echoes, a leading `+`. These helpers detect that and recover\n * the raw text. Two strip modes are exposed:\n *\n * - {@link stripNewLinePrefixes} — opportunistic: strips when the input\n * clearly carries hashline or diff prefixes, leaves it alone otherwise.\n * - {@link stripHashlinePrefixes} — strict: only strips when every non-empty\n * content line is hashline-prefixed.\n *\n * These run *before* the tokenizer; they exist because hashline mode is the\n * common case for echoed file content, and erroneously echoed prefixes will\n * otherwise turn every content line into a (malformed) op.\n */\n\nimport { HL_FILE_HASH_LENGTH } from \"./format.js\";\n\nconst HL_PREFIX_RE = /^\\s*(?:>>>|>>)?\\s*(?:[+*-]\\s*)?\\d+:/;\nconst HL_PREFIX_PLUS_RE = /^\\s*(?:>>>|>>)?\\s*\\+\\s*\\d+:/;\nconst HL_HEADER_RE = new RegExp(`^\\\\s*\\\\[[^#\\\\r\\\\n]+#[0-9a-fA-F]{${HL_FILE_HASH_LENGTH}}\\\\]\\\\s*$`);\nconst DIFF_PLUS_RE = /^[+](?![+])/;\nconst READ_TRUNCATION_NOTICE_RE = /^\\[(?:Showing lines \\d+-\\d+ of \\d+|\\d+ more lines? in (?:file|\\S+))\\b.*\\bUse :L?\\d+/;\n\nfunction stripLeadingHashlinePrefixes(line: string): string {\n\tlet result = line;\n\tlet previous: string;\n\tdo {\n\t\tprevious = result;\n\t\tresult = result.replace(HL_PREFIX_RE, \"\");\n\t} while (result !== previous);\n\treturn result;\n}\n/**\n * Single-pass variant of {@link stripLeadingHashlinePrefixes} that strips at\n * most one leading hashline prefix (`N:`, `>>>N:`, `+N:` etc.) and does NOT\n * loop. Use this when the input carries at most one snapshot prefix (e.g. a\n * bare body row paste from `read` output) — recursive stripping would corrupt\n * content whose own text starts with `digits:`.\n */\nexport function stripOneLeadingHashlinePrefix(line: string): string {\n\treturn line.replace(HL_PREFIX_RE, \"\");\n}\n\ninterface LinePrefixStats {\n\tnonEmpty: number;\n\theaderCount: number;\n\thashPrefixCount: number;\n\tdiffPlusHashPrefixCount: number;\n\tdiffPlusCount: number;\n\ttruncationNoticeCount: number;\n}\n\nfunction collectLinePrefixStats(lines: string[]): LinePrefixStats {\n\tconst stats: LinePrefixStats = {\n\t\tnonEmpty: 0,\n\t\theaderCount: 0,\n\t\thashPrefixCount: 0,\n\t\tdiffPlusHashPrefixCount: 0,\n\t\tdiffPlusCount: 0,\n\t\ttruncationNoticeCount: 0,\n\t};\n\n\tfor (const line of lines) {\n\t\tif (line.length === 0) continue;\n\t\tif (READ_TRUNCATION_NOTICE_RE.test(line)) {\n\t\t\tstats.truncationNoticeCount++;\n\t\t\tcontinue;\n\t\t}\n\t\tif (HL_HEADER_RE.test(line)) {\n\t\t\tstats.nonEmpty++;\n\t\t\tstats.headerCount++;\n\t\t\tcontinue;\n\t\t}\n\t\tstats.nonEmpty++;\n\t\tif (HL_PREFIX_RE.test(line)) stats.hashPrefixCount++;\n\t\tif (HL_PREFIX_PLUS_RE.test(line)) stats.diffPlusHashPrefixCount++;\n\t\tif (DIFF_PLUS_RE.test(line)) stats.diffPlusCount++;\n\t}\n\treturn stats;\n}\n\n/**\n * Strip whichever prefix scheme the lines appear to be carrying:\n * - hashline line-number prefixes (`123:`) when every content line has one\n * - leading `+` (diff style) when at least half the lines have one\n * - mixed `+<n>:` form when present\n *\n * Returns the lines untouched if no scheme is recognized.\n */\nexport function stripNewLinePrefixes(lines: string[]): string[] {\n\tconst stats = collectLinePrefixStats(lines);\n\tif (stats.nonEmpty === 0) return lines;\n\n\tconst contentLineCount = stats.nonEmpty - stats.headerCount;\n\tconst stripHash = contentLineCount > 0 && stats.hashPrefixCount === contentLineCount;\n\tconst stripPlus =\n\t\t!stripHash &&\n\t\tstats.diffPlusHashPrefixCount === 0 &&\n\t\tstats.diffPlusCount > 0 &&\n\t\tstats.diffPlusCount >= stats.nonEmpty * 0.5;\n\n\tif (!stripHash && !stripPlus && stats.diffPlusHashPrefixCount === 0) return lines;\n\n\treturn lines\n\t\t.filter(line => !READ_TRUNCATION_NOTICE_RE.test(line) && !(stripHash && HL_HEADER_RE.test(line)))\n\t\t.map(line => {\n\t\t\tif (stripHash) return stripLeadingHashlinePrefixes(line);\n\t\t\tif (stripPlus) return line.replace(DIFF_PLUS_RE, \"\");\n\t\t\tif (stats.diffPlusHashPrefixCount > 0 && HL_PREFIX_PLUS_RE.test(line)) {\n\t\t\t\treturn line.replace(HL_PREFIX_RE, \"\");\n\t\t\t}\n\t\t\treturn line;\n\t\t});\n}\n\n/**\n * Strict variant: strip hashline prefixes only when every content line is\n * hashline-prefixed. Returns the lines unchanged otherwise.\n */\nexport function stripHashlinePrefixes(lines: string[]): string[] {\n\tconst stats = collectLinePrefixStats(lines);\n\tif (stats.nonEmpty === 0) return lines;\n\tconst contentLineCount = stats.nonEmpty - stats.headerCount;\n\tif (contentLineCount === 0 || stats.hashPrefixCount !== contentLineCount) return lines;\n\treturn lines\n\t\t.filter(line => !READ_TRUNCATION_NOTICE_RE.test(line) && !HL_HEADER_RE.test(line))\n\t\t.map(line => stripLeadingHashlinePrefixes(line));\n}\n\n/**\n * Normalize line payloads by stripping read/search line prefixes. `null` /\n * `undefined` yield `[]`; a single multiline string is split on `\\n`.\n */\nexport function hashlineParseText(edit: string[] | string | null | undefined): string[] {\n\tif (edit == null) return [];\n\tif (typeof edit === \"string\") {\n\t\tconst trimmed = edit.endsWith(\"\\n\") ? edit.slice(0, -1) : edit;\n\t\tedit = trimmed.replaceAll(\"\\r\", \"\").split(\"\\n\");\n\t}\n\treturn stripNewLinePrefixes(edit);\n}\n"]}
1
+ {"version":3,"file":"prefixes.d.ts","sourceRoot":"","sources":["../../../../src/core/tools/hashline-engine/prefixes.ts"],"names":[],"mappings":"AAEA;;;;;;;;;;;;;;GAcG;AAmBH;;;;;;GAMG;AACH,wBAAgB,6BAA6B,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAElE;AAwCD;;;;;;;GAOG;AACH,wBAAgB,oBAAoB,CAAC,KAAK,EAAE,MAAM,EAAE,GAAG,MAAM,EAAE,CAwB9D;AAED;;;GAGG;AACH,wBAAgB,qBAAqB,CAAC,KAAK,EAAE,MAAM,EAAE,GAAG,MAAM,EAAE,CAQ/D;AAED;;;GAGG;AACH,wBAAgB,iBAAiB,CAAC,IAAI,EAAE,MAAM,EAAE,GAAG,MAAM,GAAG,IAAI,GAAG,SAAS,GAAG,MAAM,EAAE,CAOtF"}
@@ -1 +1 @@
1
- {"version":3,"file":"recovery.d.ts","sourceRoot":"","sources":["../../../../src/core/tools/hashline-engine/recovery.ts"],"names":[],"mappings":"AAeA,OAAO,KAAK,EAAY,aAAa,EAAE,MAAM,gBAAgB,CAAC;AAC9D,OAAO,KAAK,EAAuB,IAAI,EAAE,MAAM,YAAY,CAAC;AAO5D,MAAM,WAAW,YAAY;IAC5B,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,EAAE,MAAM,CAAC;IACpB,QAAQ,EAAE,MAAM,CAAC;IACjB,KAAK,EAAE,SAAS,IAAI,EAAE,CAAC;CACvB;AAED,MAAM,WAAW,cAAc;IAC9B,0BAA0B;IAC1B,IAAI,EAAE,MAAM,CAAC;IACb,yFAAyF;IACzF,gBAAgB,EAAE,MAAM,GAAG,SAAS,CAAC;IACrC,qFAAqF;IACrF,QAAQ,EAAE,MAAM,EAAE,CAAC;CACnB;AAkHD;;;;;;;;;;;;;;GAcG;AACH,qBAAa,QAAQ;IACpB,QAAQ,CAAC,KAAK,EAAE,aAAa,CAAC;IAC9B,YAAY,KAAK,EAAE,aAAa,EAAyB;IACzD;;;OAGG;IACH,UAAU,CAAC,IAAI,EAAE,YAAY,GAAG,cAAc,GAAG,IAAI,CAcpD;CACD","sourcesContent":["// @generated vendored verbatim from oh-my-pi packages/hashline @ 15b5c1397fc -- DO NOT EDIT.\n// Parity source for the Atomic hashline edit engine (issue #1483); adapted only for Atomic's Node runtime (relative imports, Bun->Node host calls, erasable constructor syntax).\n/**\n * Recover from a stale section snapshot tag by replaying the would-be edit\n * against a cached pre-edit snapshot of the file and 3-way-merging the\n * result onto the current on-disk content.\n *\n * The patcher consults this when a section tag resolves to a snapshot that no\n * longer matches the live file content. The recovery class is stateless apart\n * from the {@link SnapshotStore} it queries; the snapshot store is the seam\n * lets you plug in your own caching strategy.\n */\nimport * as Diff from \"diff\";\nimport { applyEdits } from \"./apply.js\";\nimport { RECOVERY_EXTERNAL_WARNING, RECOVERY_SESSION_CHAIN_WARNING, RECOVERY_SESSION_REPLAY_WARNING } from \"./messages.js\";\nimport type { Snapshot, SnapshotStore } from \"./snapshots.js\";\nimport type { Anchor, ApplyResult, Edit } from \"./types.js\";\n\n// Section tags are line-precise; never let Diff.applyPatch slide a hunk\n// onto a duplicate closer 100+ lines away. If snapshot replay does not\n// align exactly, refuse and let the caller re-read.\nconst RECOVERY_FUZZ_FACTOR = 0;\n\nexport interface RecoveryArgs {\n\tpath: string;\n\tcurrentText: string;\n\tfileHash: string;\n\tedits: readonly Edit[];\n}\n\nexport interface RecoveryResult {\n\t/** Post-recovery text. */\n\ttext: string;\n\t/** First changed line (1-indexed) relative to the live `currentText`, or `undefined`. */\n\tfirstChangedLine: number | undefined;\n\t/** Warnings collected during recovery, including the user-facing recovery banner. */\n\twarnings: string[];\n}\n\nfunction applyEditsToSnapshot(\n\tpreviousText: string,\n\tcurrentText: string,\n\tedits: readonly Edit[],\n\trecoveryWarning: string,\n): RecoveryResult | null {\n\tlet applied: ApplyResult;\n\ttry {\n\t\tapplied = applyEdits(previousText, [...edits]);\n\t} catch {\n\t\treturn null;\n\t}\n\tif (applied.text === previousText) return null;\n\n\tconst patch = Diff.structuredPatch(\"file\", \"file\", previousText, applied.text, \"\", \"\", { context: 3 });\n\tconst merged = Diff.applyPatch(currentText, patch, { fuzzFactor: RECOVERY_FUZZ_FACTOR });\n\tif (typeof merged !== \"string\" || merged === currentText) return null;\n\n\tconst firstChangedLine = findFirstChangedLine(currentText, merged) ?? applied.firstChangedLine;\n\tconst hasNetChange = firstChangedLine !== undefined;\n\tconst warnings = hasNetChange ? [recoveryWarning, ...(applied.warnings ?? [])] : [...(applied.warnings ?? [])];\n\n\treturn { text: merged, firstChangedLine, warnings };\n}\n\nfunction collectAnchorLines(edits: readonly Edit[]): number[] {\n\tconst lines: number[] = [];\n\tfor (const edit of edits) {\n\t\tfor (const anchor of getEditAnchors(edit)) lines.push(anchor.line);\n\t}\n\treturn lines;\n}\n\nfunction getEditAnchors(edit: Edit): Anchor[] {\n\tif (edit.kind === \"delete\") return [edit.anchor];\n\t// Recovery only ever receives already-resolved edits (no `block`); this arm\n\t// exists for type-exhaustiveness over the full `Edit` union.\n\tif (edit.kind === \"block\") return [edit.anchor];\n\treturn edit.cursor.kind === \"before_anchor\" || edit.cursor.kind === \"after_anchor\" ? [edit.cursor.anchor] : [];\n}\n\n/**\n * Returns true when every anchor line in `edits` has identical content in\n * `previousText` and `currentText`. The session-chain replay fast-path\n * requires this: if the prior in-session edit rewrote the line the model is\n * now re-targeting with a stale hash, replaying onto current would silently\n * overwrite the new content with whatever the model authored against the\n * old content — a corruption window, not a recovery.\n */\nfunction verifyAnchorContent(previousText: string, currentText: string, edits: readonly Edit[]): boolean {\n\tconst lines = collectAnchorLines(edits);\n\tif (lines.length === 0) return true;\n\tconst prev = previousText.split(\"\\n\");\n\tconst curr = currentText.split(\"\\n\");\n\tfor (const line of lines) {\n\t\tconst idx = line - 1;\n\t\tif (idx < 0 || idx >= prev.length || idx >= curr.length) return false;\n\t\tif (prev[idx] !== curr[idx]) return false;\n\t}\n\treturn true;\n}\n\nfunction replaySessionChainOnCurrent(\n\tpreviousText: string,\n\tcurrentText: string,\n\tedits: readonly Edit[],\n): RecoveryResult | null {\n\t// Two guards narrow the corruption window. Neither alone is sufficient,\n\t// and even together they don't fully prove correctness — replay is the\n\t// less-certain recovery mode and emits RECOVERY_SESSION_REPLAY_WARNING\n\t// so the caller can verify the diff.\n\t// - Equal line counts: every line number in `edits` still resolves to\n\t// SOME logical row (no net shift across the prior chain). A\n\t// coincidental insert+delete pair can still leave indices pointing\n\t// at different logical rows than the model anchored against.\n\t// - Anchor-content alignment: the row at each anchor's line index has\n\t// identical content in previous and current. Catches the common\n\t// case of a prior edit rewriting the targeted line; can still be\n\t// coincidentally satisfied by a duplicated row at the shifted\n\t// index.\n\tif (previousText.split(\"\\n\").length !== currentText.split(\"\\n\").length) return null;\n\tif (!verifyAnchorContent(previousText, currentText, edits)) return null;\n\tlet applied: ApplyResult;\n\ttry {\n\t\tapplied = applyEdits(currentText, [...edits]);\n\t} catch {\n\t\treturn null;\n\t}\n\tif (applied.text === currentText) return null;\n\treturn {\n\t\ttext: applied.text,\n\t\tfirstChangedLine: applied.firstChangedLine,\n\t\twarnings: [RECOVERY_SESSION_REPLAY_WARNING, ...(applied.warnings ?? [])],\n\t};\n}\n\n/** First 1-indexed line at which `a` and `b` diverge, or `undefined` if equal. */\nfunction findFirstChangedLine(a: string, b: string): number | undefined {\n\tif (a === b) return undefined;\n\tconst aLines = a.split(\"\\n\");\n\tconst bLines = b.split(\"\\n\");\n\tconst max = Math.max(aLines.length, bLines.length);\n\tfor (let i = 0; i < max; i++) {\n\t\tif (aLines[i] !== bLines[i]) return i + 1;\n\t}\n\treturn undefined;\n}\n\nfunction isHeadSnapshot(head: Snapshot | null, snapshot: Snapshot): boolean {\n\treturn head === snapshot;\n}\n\n/**\n * Stateless recovery driver over a {@link SnapshotStore}. Construct once and\n * call {@link Recovery.tryRecover} per stale-tag incident. The default\n * implementation tries two strategies in order:\n *\n * 1. Apply the edits on the full-file version the tag names, then 3-way-merge\n * the resulting patch onto the live content (handles external writes).\n * 2. (Session chain) If that version wasn't the head, replay the edits onto\n * the live content directly when line counts match AND every edit's anchor\n * line content is unchanged between version and current — a prior in-session\n * edit advanced the tag and the model's anchors still name the same logical\n * rows. Emits a dedicated {@link RECOVERY_SESSION_REPLAY_WARNING} because\n * even with both guards a coincidental insert+delete pair on duplicate rows\n * can still land the edit on the wrong row; see {@link replaySessionChainOnCurrent}.\n */\nexport class Recovery {\n\treadonly store: SnapshotStore;\n\tconstructor(store: SnapshotStore) { this.store = store; }\n\t/**\n\t * Attempt recovery. Returns `null` when no path forward is found — the\n\t * caller should then surface a {@link MismatchError}.\n\t */\n\ttryRecover(args: RecoveryArgs): RecoveryResult | null {\n\t\tconst { path, currentText, fileHash, edits } = args;\n\t\tconst snapshot = this.store.byHash(path, fileHash);\n\t\tif (!snapshot) return null;\n\t\tconst isHead = isHeadSnapshot(this.store.head(path), snapshot);\n\t\tconst recoveryWarning = isHead ? RECOVERY_EXTERNAL_WARNING : RECOVERY_SESSION_CHAIN_WARNING;\n\t\tconst merged = applyEditsToSnapshot(snapshot.text, currentText, edits, recoveryWarning);\n\t\tif (merged !== null) return merged;\n\t\t// Session-chain fallback: the 3-way merge on the version refused.\n\t\t// Replay onto current is gated by line-count equality AND\n\t\t// anchor-content alignment — see `replaySessionChainOnCurrent`\n\t\t// for why both guards together still don't fully prove correctness.\n\t\tif (!isHead) return replaySessionChainOnCurrent(snapshot.text, currentText, edits);\n\t\treturn null;\n\t}\n}\n"]}
1
+ {"version":3,"file":"recovery.d.ts","sourceRoot":"","sources":["../../../../src/core/tools/hashline-engine/recovery.ts"],"names":[],"mappings":"AAeA,OAAO,KAAK,EAAY,aAAa,EAAE,MAAM,gBAAgB,CAAC;AAC9D,OAAO,KAAK,EAAuB,IAAI,EAAE,MAAM,YAAY,CAAC;AAO5D,MAAM,WAAW,YAAY;IAC5B,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,EAAE,MAAM,CAAC;IACpB,QAAQ,EAAE,MAAM,CAAC;IACjB,KAAK,EAAE,SAAS,IAAI,EAAE,CAAC;CACvB;AAED,MAAM,WAAW,cAAc;IAC9B,0BAA0B;IAC1B,IAAI,EAAE,MAAM,CAAC;IACb,yFAAyF;IACzF,gBAAgB,EAAE,MAAM,GAAG,SAAS,CAAC;IACrC,qFAAqF;IACrF,QAAQ,EAAE,MAAM,EAAE,CAAC;CACnB;AAkHD;;;;;;;;;;;;;;GAcG;AACH,qBAAa,QAAQ;IACpB,QAAQ,CAAC,KAAK,EAAE,aAAa,CAAC;IAC9B,YAAY,KAAK,EAAE,aAAa,EAAyB;IACzD;;;OAGG;IACH,UAAU,CAAC,IAAI,EAAE,YAAY,GAAG,cAAc,GAAG,IAAI,CAcpD;CACD"}
@@ -1 +1 @@
1
- {"version":3,"file":"snapshots.d.ts","sourceRoot":"","sources":["../../../../src/core/tools/hashline-engine/snapshots.ts"],"names":[],"mappings":"AA2BA;;;GAGG;AACH,MAAM,WAAW,QAAQ;IACxB,8CAA8C;IAC9C,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,0DAA0D;IAC1D,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,mFAAmF;IACnF,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,2DAA2D;IAC3D,UAAU,EAAE,MAAM,CAAC;CACnB;AAED;;;;GAIG;AACH,8BAAsB,aAAa;IAClC,oEAAoE;IACpE,QAAQ,CAAC,IAAI,CAAC,IAAI,EAAE,MAAM,GAAG,QAAQ,GAAG,IAAI,CAAC;IAE7C,kFAAkF;IAClF,QAAQ,CAAC,MAAM,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,QAAQ,GAAG,IAAI,CAAC;IAE7D,iFAAiF;IACjF,aAAa,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,QAAQ,GAAG,IAAI,CAGvE;IAED,4EAA4E;IAC5E,QAAQ,CAAC,MAAM,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,MAAM,CAAC;IAExD,kDAAkD;IAClD,QAAQ,CAAC,UAAU,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI,CAAC;IAExC,kCAAkC;IAClC,QAAQ,CAAC,KAAK,IAAI,IAAI,CAAC;CACvB;AAOD,MAAM,WAAW,4BAA4B;IAC5C,mFAAmF;IACnF,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,sFAAsF;IACtF,kBAAkB,CAAC,EAAE,MAAM,CAAC;IAC5B;;;;OAIG;IACH,aAAa,CAAC,EAAE,MAAM,CAAC;CACvB;AAED;;;;;;;;GAQG;AACH,qBAAa,qBAAsB,SAAQ,aAAa;;IAIvD,YAAY,OAAO,GAAE,4BAAiC,EAYrD;IAED,IAAI,CAAC,IAAI,EAAE,MAAM,GAAG,QAAQ,GAAG,IAAI,CAElC;IAED,MAAM,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,QAAQ,GAAG,IAAI,CAKlD;IAEQ,aAAa,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,QAAQ,GAAG,IAAI,CAEhF;IAED,MAAM,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,MAAM,CAoB7C;IAED,UAAU,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI,CAE7B;IAED,KAAK,IAAI,IAAI,CAEZ;CACD","sourcesContent":["// @generated vendored verbatim from oh-my-pi packages/hashline @ 15b5c1397fc -- DO NOT EDIT.\n// Parity source for the Atomic hashline edit engine (issue #1483); adapted only for Atomic's Node runtime (relative imports, Bun->Node host calls, erasable constructor syntax).\n/**\n * Per-session snapshot store used by {@link Recovery} and {@link Patcher} to\n * bind hashline section tags to the exact file content that minted them.\n *\n * A section tag is a content-derived hash of the *whole file* (see\n * {@link computeFileHash}). Any read of byte-identical content mints the same\n * tag, so reads of one file state fuse onto one anchor and a follow-up edit\n * anchored at any line validates whenever the live file still hashes to it.\n *\n * Producers (typically `read` / `search` / `write` tools) call\n * {@link SnapshotStore.record} with the full normalized text they observed.\n * The store hashes it, dedups against the per-path history, and returns the\n * tag. Consumers (the patcher) resolve an unambiguous stale tag back to the\n * recorded full text via {@link SnapshotStore.byHash} and 3-way-merge the\n * would-be edit onto the live content.\n *\n * The abstract base class lets callers plug in whatever storage they like\n * (LRU, persistent SQLite, etc.). {@link InMemorySnapshotStore} ships as a\n * sensible default backed by `lru-cache`: a bounded set of paths, each with a\n * short history of full-file versions so in-session edit chains can still\n * recover against the version a stale tag names.\n */\nimport { LRUCache } from \"lru-cache/raw\";\nimport { computeFileHash } from \"./format.js\";\n\n/**\n * One full-file version observed at a point in time. The tag the model sees is\n * {@link Snapshot.hash}; recovery replays edits against {@link Snapshot.text}.\n */\nexport interface Snapshot {\n\t/** Canonical path this version belongs to. */\n\treadonly path: string;\n\t/** Full normalized (LF, no BOM) file text as observed. */\n\treadonly text: string;\n\t/** Content-derived tag for {@link Snapshot.text} (see {@link computeFileHash}). */\n\treadonly hash: string;\n\t/** Timestamp (ms since epoch) the version was recorded. */\n\trecordedAt: number;\n}\n\n/**\n * Storage seam for full-file version snapshots. The patcher calls {@link head}\n * for the latest version of a path and {@link byHash} when it needs the\n * specific historical version a section's stale tag names.\n */\nexport abstract class SnapshotStore {\n\t/** Most-recently recorded version for `path`, or `null` if none. */\n\tabstract head(path: string): Snapshot | null;\n\n\t/** Recorded unambiguous version for `path` whose tag equals `hash`, or `null`. */\n\tabstract byHash(path: string, hash: string): Snapshot | null;\n\n\t/** Recorded version for `path` whose tag and full text both match, or `null`. */\n\tbyHashAndText(path: string, hash: string, text: string): Snapshot | null {\n\t\tconst snapshot = this.byHash(path, hash);\n\t\treturn snapshot?.text === text ? snapshot : null;\n\t}\n\n\t/** Record the full normalized text of `path` and return its content tag. */\n\tabstract record(path: string, fullText: string): string;\n\n\t/** Drop the version history for a single path. */\n\tabstract invalidate(path: string): void;\n\n\t/** Drop every version history. */\n\tabstract clear(): void;\n}\n\nconst DEFAULT_MAX_PATHS = 30;\nconst DEFAULT_MAX_VERSIONS_PER_PATH = 4;\n/** Global ceiling on retained snapshot text across all paths (UTF-16 code units). */\nconst DEFAULT_MAX_TOTAL_BYTES = 64 * 1024 * 1024;\n\nexport interface InMemorySnapshotStoreOptions {\n\t/** Maximum number of distinct paths tracked at once (default 30). LRU eviction. */\n\tmaxPaths?: number;\n\t/** Maximum full-file versions retained per path (default 4). Oldest dropped first. */\n\tmaxVersionsPerPath?: number;\n\t/**\n\t * Global ceiling on retained snapshot text summed across every path's\n\t * version history, measured in UTF-16 code units (default 64 MiB).\n\t * Least-recently-used path histories are evicted to stay under it.\n\t */\n\tmaxTotalBytes?: number;\n}\n\n/**\n * In-memory {@link SnapshotStore} backed by `lru-cache`. Per-path history is a\n * short ring of full-file versions (oldest dropped first); per-session path\n * tracking is LRU-bounded so cold paths age out automatically.\n *\n * Recording byte-identical content again refreshes recency and reuses the\n * existing tag (read fusion); recording new content unshifts a fresh version\n * onto the front of the path history.\n */\nexport class InMemorySnapshotStore extends SnapshotStore {\n\treadonly #versions: LRUCache<string, Snapshot[]>;\n\treadonly #maxVersionsPerPath: number;\n\n\tconstructor(options: InMemorySnapshotStoreOptions = {}) {\n\t\tsuper();\n\t\tthis.#versions = new LRUCache<string, Snapshot[]>({\n\t\t\tmax: options.maxPaths ?? DEFAULT_MAX_PATHS,\n\t\t\tmaxSize: options.maxTotalBytes ?? DEFAULT_MAX_TOTAL_BYTES,\n\t\t\tsizeCalculation: history => {\n\t\t\t\tlet total = 1;\n\t\t\t\tfor (const version of history) total += version.text.length;\n\t\t\t\treturn total;\n\t\t\t},\n\t\t});\n\t\tthis.#maxVersionsPerPath = options.maxVersionsPerPath ?? DEFAULT_MAX_VERSIONS_PER_PATH;\n\t}\n\n\thead(path: string): Snapshot | null {\n\t\treturn this.#versions.get(path)?.[0] ?? null;\n\t}\n\n\tbyHash(path: string, hash: string): Snapshot | null {\n\t\tconst matches = this.#versions.get(path)?.filter(version => version.hash === hash) ?? [];\n\t\t// A 4-hex tag can collide. Recovery only proceeds when the tag maps to a\n\t\t// single retained snapshot; otherwise the caller must re-read.\n\t\treturn matches.length === 1 ? matches[0]! : null;\n\t}\n\n\toverride byHashAndText(path: string, hash: string, text: string): Snapshot | null {\n\t\treturn this.#versions.get(path)?.find(version => version.hash === hash && version.text === text) ?? null;\n\t}\n\n\trecord(path: string, fullText: string): string {\n\t\tconst hash = computeFileHash(fullText);\n\t\t// `get` refreshes LRU recency for `path`.\n\t\tconst history = this.#versions.get(path) ?? [];\n\t\tconst existing = history.find(version => version.hash === hash && version.text === fullText);\n\t\tif (existing) {\n\t\t\t// Same content state observed again: refresh recency and promote to\n\t\t\t// head (it is the current file content), then reuse the tag. Hash\n\t\t\t// collisions with different text must be retained as distinct\n\t\t\t// snapshots; the 4-hex tag is only a lookup key, not proof of identity.\n\t\t\texisting.recordedAt = Date.now();\n\t\t\tif (history[0] !== existing) {\n\t\t\t\tthis.#versions.set(path, [existing, ...history.filter(version => version !== existing)]);\n\t\t\t}\n\t\t\treturn hash;\n\t\t}\n\n\t\tconst snapshot: Snapshot = { path, text: fullText, hash, recordedAt: Date.now() };\n\t\tthis.#versions.set(path, [snapshot, ...history].slice(0, this.#maxVersionsPerPath));\n\t\treturn hash;\n\t}\n\n\tinvalidate(path: string): void {\n\t\tthis.#versions.delete(path);\n\t}\n\n\tclear(): void {\n\t\tthis.#versions.clear();\n\t}\n}\n"]}
1
+ {"version":3,"file":"snapshots.d.ts","sourceRoot":"","sources":["../../../../src/core/tools/hashline-engine/snapshots.ts"],"names":[],"mappings":"AA2BA;;;GAGG;AACH,MAAM,WAAW,QAAQ;IACxB,8CAA8C;IAC9C,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,0DAA0D;IAC1D,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,mFAAmF;IACnF,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,2DAA2D;IAC3D,UAAU,EAAE,MAAM,CAAC;CACnB;AAED;;;;GAIG;AACH,8BAAsB,aAAa;IAClC,oEAAoE;IACpE,QAAQ,CAAC,IAAI,CAAC,IAAI,EAAE,MAAM,GAAG,QAAQ,GAAG,IAAI,CAAC;IAE7C,kFAAkF;IAClF,QAAQ,CAAC,MAAM,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,QAAQ,GAAG,IAAI,CAAC;IAE7D,iFAAiF;IACjF,aAAa,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,QAAQ,GAAG,IAAI,CAGvE;IAED,4EAA4E;IAC5E,QAAQ,CAAC,MAAM,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,MAAM,CAAC;IAExD,kDAAkD;IAClD,QAAQ,CAAC,UAAU,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI,CAAC;IAExC,kCAAkC;IAClC,QAAQ,CAAC,KAAK,IAAI,IAAI,CAAC;CACvB;AAOD,MAAM,WAAW,4BAA4B;IAC5C,mFAAmF;IACnF,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,sFAAsF;IACtF,kBAAkB,CAAC,EAAE,MAAM,CAAC;IAC5B;;;;OAIG;IACH,aAAa,CAAC,EAAE,MAAM,CAAC;CACvB;AAED;;;;;;;;GAQG;AACH,qBAAa,qBAAsB,SAAQ,aAAa;;IAIvD,YAAY,OAAO,GAAE,4BAAiC,EAYrD;IAED,IAAI,CAAC,IAAI,EAAE,MAAM,GAAG,QAAQ,GAAG,IAAI,CAElC;IAED,MAAM,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,QAAQ,GAAG,IAAI,CAKlD;IAEQ,aAAa,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,QAAQ,GAAG,IAAI,CAEhF;IAED,MAAM,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,MAAM,CAoB7C;IAED,UAAU,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI,CAE7B;IAED,KAAK,IAAI,IAAI,CAEZ;CACD"}
@@ -1 +1 @@
1
- {"version":3,"file":"stream.d.ts","sourceRoot":"","sources":["../../../../src/core/tools/hashline-engine/stream.ts"],"names":[],"mappings":"AAYA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AAoFhD,wBAAuB,eAAe,CACrC,MAAM,EAAE,cAAc,CAAC,UAAU,CAAC,GAAG,aAAa,CAAC,UAAU,CAAC,EAC9D,OAAO,GAAE,aAAkB,GACzB,cAAc,CAAC,MAAM,CAAC,CAkCxB","sourcesContent":["// @generated vendored verbatim from oh-my-pi packages/hashline @ 15b5c1397fc -- DO NOT EDIT.\n// Parity source for the Atomic hashline edit engine (issue #1483); adapted only for Atomic's Node runtime (relative imports, Bun->Node host calls, erasable constructor syntax).\n/**\n * Lazily format a stream of UTF-8 bytes into hashline-numbered lines, yielded\n * as bounded text chunks. Used to send `read`-style file content to consumers\n * without materializing the full file at once.\n *\n * Each yielded chunk is at most {@link StreamOptions.maxChunkLines} lines and\n * at most {@link StreamOptions.maxChunkBytes} UTF-8 bytes (whichever fires\n * first).\n */\nimport { formatNumberedLine } from \"./format.js\";\nimport type { StreamOptions } from \"./types.js\";\n\ninterface ResolvedStreamOptions {\n\tstartLine: number;\n\tmaxChunkLines: number;\n\tmaxChunkBytes: number;\n}\n\nfunction resolveStreamOptions(options: StreamOptions): ResolvedStreamOptions {\n\treturn {\n\t\tstartLine: options.startLine ?? 1,\n\t\tmaxChunkLines: options.maxChunkLines ?? 200,\n\t\tmaxChunkBytes: options.maxChunkBytes ?? 64 * 1024,\n\t};\n}\n\ninterface ChunkEmitter {\n\tpushLine: (line: string) => string[];\n\tflush: () => string | undefined;\n}\n\nfunction createChunkEmitter(options: ResolvedStreamOptions): ChunkEmitter {\n\tlet lineNumber = options.startLine;\n\tlet outLines: string[] = [];\n\tlet outBytes = 0;\n\n\tconst flush = (): string | undefined => {\n\t\tif (outLines.length === 0) return undefined;\n\t\tconst chunk = outLines.join(\"\\n\");\n\t\toutLines = [];\n\t\toutBytes = 0;\n\t\treturn chunk;\n\t};\n\n\tconst pushLine = (line: string): string[] => {\n\t\tconst formatted = formatNumberedLine(lineNumber, line);\n\t\tlineNumber++;\n\n\t\tconst chunks: string[] = [];\n\t\tconst sepBytes = outLines.length === 0 ? 0 : 1;\n\t\tconst lineBytes = Buffer.byteLength(formatted, \"utf-8\");\n\t\tconst wouldOverflow =\n\t\t\toutLines.length >= options.maxChunkLines || outBytes + sepBytes + lineBytes > options.maxChunkBytes;\n\n\t\tif (outLines.length > 0 && wouldOverflow) {\n\t\t\tconst flushed = flush();\n\t\t\tif (flushed) chunks.push(flushed);\n\t\t}\n\n\t\toutLines.push(formatted);\n\t\toutBytes += (outLines.length === 1 ? 0 : 1) + lineBytes;\n\n\t\tif (outLines.length >= options.maxChunkLines || outBytes >= options.maxChunkBytes) {\n\t\t\tconst flushed = flush();\n\t\t\tif (flushed) chunks.push(flushed);\n\t\t}\n\t\treturn chunks;\n\t};\n\n\treturn { pushLine, flush };\n}\n\nfunction isReadableStream(value: unknown): value is ReadableStream<Uint8Array> {\n\treturn (\n\t\ttypeof value === \"object\" &&\n\t\tvalue !== null &&\n\t\t\"getReader\" in value &&\n\t\ttypeof (value as { getReader?: unknown }).getReader === \"function\"\n\t);\n}\n\nasync function* bytesFromReadableStream(stream: ReadableStream<Uint8Array>): AsyncGenerator<Uint8Array> {\n\tconst reader = stream.getReader();\n\ttry {\n\t\twhile (true) {\n\t\t\tconst { done, value } = await reader.read();\n\t\t\tif (done) return;\n\t\t\tif (value) yield value;\n\t\t}\n\t} finally {\n\t\treader.releaseLock();\n\t}\n}\n\nexport async function* streamHashLines(\n\tsource: ReadableStream<Uint8Array> | AsyncIterable<Uint8Array>,\n\toptions: StreamOptions = {},\n): AsyncGenerator<string> {\n\tconst resolved = resolveStreamOptions(options);\n\tconst decoder = new TextDecoder(\"utf-8\");\n\tconst chunks = isReadableStream(source) ? bytesFromReadableStream(source) : source;\n\tconst emitter = createChunkEmitter(resolved);\n\n\tlet pending = \"\";\n\tlet sawAnyLine = false;\n\n\tfor await (const chunk of chunks) {\n\t\tpending += decoder.decode(chunk, { stream: true });\n\t\tlet nl = pending.indexOf(\"\\n\");\n\t\twhile (nl !== -1) {\n\t\t\tconst raw = pending.slice(0, nl);\n\t\t\tconst line = raw.endsWith(\"\\r\") ? raw.slice(0, -1) : raw;\n\t\t\tsawAnyLine = true;\n\t\t\tfor (const out of emitter.pushLine(line)) yield out;\n\t\t\tpending = pending.slice(nl + 1);\n\t\t\tnl = pending.indexOf(\"\\n\");\n\t\t}\n\t}\n\n\tpending += decoder.decode();\n\tif (pending.length > 0) {\n\t\tsawAnyLine = true;\n\t\tconst tail = pending.endsWith(\"\\r\") ? pending.slice(0, -1) : pending;\n\t\tfor (const out of emitter.pushLine(tail)) yield out;\n\t}\n\tif (!sawAnyLine) {\n\t\tfor (const out of emitter.pushLine(\"\")) yield out;\n\t}\n\n\tconst last = emitter.flush();\n\tif (last) yield last;\n}\n"]}
1
+ {"version":3,"file":"stream.d.ts","sourceRoot":"","sources":["../../../../src/core/tools/hashline-engine/stream.ts"],"names":[],"mappings":"AAYA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AAoFhD,wBAAuB,eAAe,CACrC,MAAM,EAAE,cAAc,CAAC,UAAU,CAAC,GAAG,aAAa,CAAC,UAAU,CAAC,EAC9D,OAAO,GAAE,aAAkB,GACzB,cAAc,CAAC,MAAM,CAAC,CAkCxB"}