@agimon-ai/doompi-file-edit 0.0.1-alpha.6 → 0.0.1-alpha.65

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 (250) hide show
  1. package/README.md +114 -18
  2. package/dist/adapters/EditTracker/EditTracker.cjs +2 -0
  3. package/dist/adapters/EditTracker/EditTracker.cjs.map +1 -0
  4. package/dist/adapters/EditTracker/EditTracker.mjs +2 -0
  5. package/dist/adapters/EditTracker/EditTracker.mjs.map +1 -0
  6. package/dist/adapters/EditorConfigService/EditorConfigService.cjs +2 -0
  7. package/dist/adapters/EditorConfigService/EditorConfigService.cjs.map +1 -0
  8. package/dist/adapters/EditorConfigService/EditorConfigService.mjs +2 -0
  9. package/dist/adapters/EditorConfigService/EditorConfigService.mjs.map +1 -0
  10. package/dist/adapters/EditorLauncher/EditorLauncher.cjs +2 -0
  11. package/dist/adapters/EditorLauncher/EditorLauncher.cjs.map +1 -0
  12. package/dist/adapters/EditorLauncher/EditorLauncher.mjs +2 -0
  13. package/dist/adapters/EditorLauncher/EditorLauncher.mjs.map +1 -0
  14. package/dist/adapters/FileEditPaths/FileEditPaths.cjs +2 -0
  15. package/dist/adapters/FileEditPaths/FileEditPaths.cjs.map +1 -0
  16. package/dist/adapters/FileEditPaths/FileEditPaths.mjs +2 -0
  17. package/dist/adapters/FileEditPaths/FileEditPaths.mjs.map +1 -0
  18. package/dist/adapters/GitDiffService/GitDiffService.cjs +5 -0
  19. package/dist/adapters/GitDiffService/GitDiffService.cjs.map +1 -0
  20. package/dist/adapters/GitDiffService/GitDiffService.mjs +5 -0
  21. package/dist/adapters/GitDiffService/GitDiffService.mjs.map +1 -0
  22. package/dist/adapters/TimelineStore/TimelineStore.cjs +2 -0
  23. package/dist/adapters/TimelineStore/TimelineStore.cjs.map +1 -0
  24. package/dist/adapters/TimelineStore/TimelineStore.mjs +2 -0
  25. package/dist/adapters/TimelineStore/TimelineStore.mjs.map +1 -0
  26. package/dist/adapters/fileEditsApi.cjs +2 -0
  27. package/dist/adapters/fileEditsApi.cjs.map +1 -0
  28. package/dist/adapters/fileEditsApi.d.cts +20 -0
  29. package/dist/adapters/fileEditsApi.d.cts.map +1 -0
  30. package/dist/adapters/fileEditsApi.d.mts +20 -0
  31. package/dist/adapters/fileEditsApi.d.mts.map +1 -0
  32. package/dist/adapters/fileEditsApi.mjs +2 -0
  33. package/dist/adapters/fileEditsApi.mjs.map +1 -0
  34. package/dist/adapters/node/gitStatus.cjs +2 -0
  35. package/dist/adapters/node/gitStatus.cjs.map +1 -0
  36. package/dist/adapters/node/gitStatus.mjs +2 -0
  37. package/dist/adapters/node/gitStatus.mjs.map +1 -0
  38. package/dist/adapters/node/sessionStateSweep.cjs +2 -0
  39. package/dist/adapters/node/sessionStateSweep.cjs.map +1 -0
  40. package/dist/adapters/node/sessionStateSweep.mjs +2 -0
  41. package/dist/adapters/node/sessionStateSweep.mjs.map +1 -0
  42. package/dist/adapters/node/snapshotStore.cjs +2 -0
  43. package/dist/adapters/node/snapshotStore.cjs.map +1 -0
  44. package/dist/adapters/node/snapshotStore.mjs +2 -0
  45. package/dist/adapters/node/snapshotStore.mjs.map +1 -0
  46. package/dist/adapters/node/treeManifest.cjs +2 -0
  47. package/dist/adapters/node/treeManifest.cjs.map +1 -0
  48. package/dist/adapters/node/treeManifest.mjs +2 -0
  49. package/dist/adapters/node/treeManifest.mjs.map +1 -0
  50. package/dist/adapters/pi/extension.cjs +2 -0
  51. package/dist/adapters/pi/extension.cjs.map +1 -0
  52. package/dist/adapters/pi/extension.d.cts +7 -0
  53. package/dist/adapters/pi/extension.d.cts.map +1 -0
  54. package/dist/adapters/pi/extension.d.mts +7 -0
  55. package/dist/adapters/pi/extension.d.mts.map +1 -0
  56. package/dist/adapters/pi/extension.mjs +2 -0
  57. package/dist/adapters/pi/extension.mjs.map +1 -0
  58. package/dist/adapters/process/commandLine.cjs.map +1 -0
  59. package/dist/adapters/process/commandLine.mjs.map +1 -0
  60. package/dist/adapters/webFilesChannel.cjs +2 -0
  61. package/dist/adapters/webFilesChannel.cjs.map +1 -0
  62. package/dist/adapters/webFilesChannel.d.cts +24 -0
  63. package/dist/adapters/webFilesChannel.d.cts.map +1 -0
  64. package/dist/adapters/webFilesChannel.d.mts +24 -0
  65. package/dist/adapters/webFilesChannel.d.mts.map +1 -0
  66. package/dist/adapters/webFilesChannel.mjs +2 -0
  67. package/dist/adapters/webFilesChannel.mjs.map +1 -0
  68. package/dist/container/index.cjs +1 -1
  69. package/dist/container/index.cjs.map +1 -1
  70. package/dist/container/index.d.cts +9 -4
  71. package/dist/container/index.d.cts.map +1 -1
  72. package/dist/container/index.d.mts +9 -4
  73. package/dist/container/index.d.mts.map +1 -1
  74. package/dist/container/index.mjs +1 -1
  75. package/dist/container/index.mjs.map +1 -1
  76. package/dist/extensions/pi.cjs +1 -1
  77. package/dist/extensions/pi.d.cts +1 -1
  78. package/dist/extensions/pi.d.mts +1 -1
  79. package/dist/extensions/pi.mjs +1 -1
  80. package/dist/index.cjs +1 -1
  81. package/dist/index.d.cts +4 -4
  82. package/dist/index.d.mts +4 -4
  83. package/dist/index.mjs +1 -1
  84. package/dist/services/doomIgnore.cjs +2 -0
  85. package/dist/services/doomIgnore.cjs.map +1 -0
  86. package/dist/services/doomIgnore.mjs +2 -0
  87. package/dist/services/doomIgnore.mjs.map +1 -0
  88. package/dist/services/fileChanges.cjs +3 -0
  89. package/dist/services/fileChanges.cjs.map +1 -0
  90. package/dist/services/fileChanges.mjs +3 -0
  91. package/dist/services/fileChanges.mjs.map +1 -0
  92. package/dist/services/lineDiff.cjs +7 -0
  93. package/dist/services/lineDiff.cjs.map +1 -0
  94. package/dist/services/lineDiff.mjs +7 -0
  95. package/dist/services/lineDiff.mjs.map +1 -0
  96. package/dist/sessionApi.cjs +1 -0
  97. package/dist/sessionApi.d.cts +2 -0
  98. package/dist/sessionApi.d.mts +2 -0
  99. package/dist/sessionApi.mjs +1 -0
  100. package/dist/tui/fileEditOverlay.cjs.map +1 -1
  101. package/dist/tui/fileEditOverlay.mjs.map +1 -1
  102. package/dist/tui/fileEditWorkflow.cjs +2 -0
  103. package/dist/tui/fileEditWorkflow.cjs.map +1 -0
  104. package/dist/tui/fileEditWorkflow.mjs +2 -0
  105. package/dist/tui/fileEditWorkflow.mjs.map +1 -0
  106. package/dist/types/domain.d.cts +91 -0
  107. package/dist/types/domain.d.cts.map +1 -0
  108. package/dist/types/domain.d.mts +91 -0
  109. package/dist/types/domain.d.mts.map +1 -0
  110. package/dist/types/editTracker.d.cts +23 -0
  111. package/dist/types/editTracker.d.cts.map +1 -0
  112. package/dist/types/editTracker.d.mts +23 -0
  113. package/dist/types/editTracker.d.mts.map +1 -0
  114. package/dist/types/editorConfigService.d.cts +11 -0
  115. package/dist/types/editorConfigService.d.cts.map +1 -0
  116. package/dist/types/editorConfigService.d.mts +11 -0
  117. package/dist/types/editorConfigService.d.mts.map +1 -0
  118. package/dist/types/editorLauncher.d.cts +17 -0
  119. package/dist/types/editorLauncher.d.cts.map +1 -0
  120. package/dist/types/editorLauncher.d.mts +17 -0
  121. package/dist/types/editorLauncher.d.mts.map +1 -0
  122. package/dist/types/fileEditPaths.d.cts +20 -0
  123. package/dist/types/fileEditPaths.d.cts.map +1 -0
  124. package/dist/types/fileEditPaths.d.mts +20 -0
  125. package/dist/types/fileEditPaths.d.mts.map +1 -0
  126. package/dist/types/fileEditWorkflow.d.cts +7 -0
  127. package/dist/types/fileEditWorkflow.d.cts.map +1 -0
  128. package/dist/types/fileEditWorkflow.d.mts +7 -0
  129. package/dist/types/fileEditWorkflow.d.mts.map +1 -0
  130. package/dist/types/fileEditsApi.cjs +2 -0
  131. package/dist/types/fileEditsApi.cjs.map +1 -0
  132. package/dist/types/fileEditsApi.mjs +2 -0
  133. package/dist/types/fileEditsApi.mjs.map +1 -0
  134. package/dist/types/gitDiffService.d.cts +7 -0
  135. package/dist/types/gitDiffService.d.cts.map +1 -0
  136. package/dist/types/gitDiffService.d.mts +7 -0
  137. package/dist/types/gitDiffService.d.mts.map +1 -0
  138. package/dist/types/index.d.cts +24 -0
  139. package/dist/types/index.d.cts.map +1 -0
  140. package/dist/types/index.d.mts +24 -0
  141. package/dist/types/index.d.mts.map +1 -0
  142. package/dist/types/snapshotStore.d.cts +35 -0
  143. package/dist/types/snapshotStore.d.cts.map +1 -0
  144. package/dist/types/snapshotStore.d.mts +35 -0
  145. package/dist/types/snapshotStore.d.mts.map +1 -0
  146. package/dist/types/timelineStore.d.cts +12 -0
  147. package/dist/types/timelineStore.d.cts.map +1 -0
  148. package/dist/types/timelineStore.d.mts +12 -0
  149. package/dist/types/timelineStore.d.mts.map +1 -0
  150. package/dist/types/treeManifest.d.cts +70 -0
  151. package/dist/types/treeManifest.d.cts.map +1 -0
  152. package/dist/types/treeManifest.d.mts +70 -0
  153. package/dist/types/treeManifest.d.mts.map +1 -0
  154. package/dist/types/webFiles.cjs +2 -0
  155. package/dist/types/webFiles.cjs.map +1 -0
  156. package/dist/types/webFiles.d.cts +32 -0
  157. package/dist/types/webFiles.d.cts.map +1 -0
  158. package/dist/types/webFiles.d.mts +32 -0
  159. package/dist/types/webFiles.d.mts.map +1 -0
  160. package/dist/types/webFiles.mjs +2 -0
  161. package/dist/types/webFiles.mjs.map +1 -0
  162. package/dist/webHub.cjs +1 -0
  163. package/dist/webHub.d.cts +2 -0
  164. package/dist/webHub.d.mts +2 -0
  165. package/dist/webHub.mjs +1 -0
  166. package/package.json +82 -23
  167. package/src/exports/webClient.ts +1 -0
  168. package/src/types/domain.ts +95 -0
  169. package/src/types/fileEditsApi.ts +162 -0
  170. package/src/types/webFiles.ts +37 -0
  171. package/src/web/api/filesApi.ts +149 -0
  172. package/src/web/components/CommentDraft.tsx +69 -0
  173. package/src/web/components/DeleteFileDialog.tsx +56 -0
  174. package/src/web/components/DiffView.tsx +96 -0
  175. package/src/web/components/FilePanel.tsx +521 -0
  176. package/src/web/components/FilePreviewPanel.tsx +151 -0
  177. package/src/web/components/FilesActivitySection.tsx +61 -0
  178. package/src/web/components/FilesBrowser.tsx +263 -0
  179. package/src/web/components/SessionMediaPreview.tsx +40 -0
  180. package/src/web/components/fileLinks.ts +58 -0
  181. package/src/web/index.ts +51 -0
  182. package/src/web/lib/fileView.ts +194 -0
  183. package/src/web/stores/filesStore.ts +108 -0
  184. package/src/web/tsconfig.json +22 -0
  185. package/dist/_virtual/_@oxc-project_runtime@0.143.0/helpers/esm/decorate.cjs +0 -1
  186. package/dist/_virtual/_@oxc-project_runtime@0.143.0/helpers/esm/decorate.mjs +0 -1
  187. package/dist/_virtual/_@oxc-project_runtime@0.143.0/helpers/esm/decorateMetadata.cjs +0 -1
  188. package/dist/_virtual/_@oxc-project_runtime@0.143.0/helpers/esm/decorateMetadata.mjs +0 -1
  189. package/dist/_virtual/_@oxc-project_runtime@0.143.0/helpers/esm/decorateParam.cjs +0 -1
  190. package/dist/_virtual/_@oxc-project_runtime@0.143.0/helpers/esm/decorateParam.mjs +0 -1
  191. package/dist/commandLine.cjs.map +0 -1
  192. package/dist/commandLine.mjs.map +0 -1
  193. package/dist/domain.d.cts +0 -32
  194. package/dist/domain.d.cts.map +0 -1
  195. package/dist/domain.d.mts +0 -32
  196. package/dist/domain.d.mts.map +0 -1
  197. package/dist/extension.cjs +0 -2
  198. package/dist/extension.cjs.map +0 -1
  199. package/dist/extension.d.cts +0 -6
  200. package/dist/extension.d.cts.map +0 -1
  201. package/dist/extension.d.mts +0 -6
  202. package/dist/extension.d.mts.map +0 -1
  203. package/dist/extension.mjs +0 -2
  204. package/dist/extension.mjs.map +0 -1
  205. package/dist/extensions/doom.cjs +0 -2
  206. package/dist/extensions/doom.cjs.map +0 -1
  207. package/dist/extensions/doom.d.cts +0 -6
  208. package/dist/extensions/doom.d.cts.map +0 -1
  209. package/dist/extensions/doom.d.mts +0 -6
  210. package/dist/extensions/doom.d.mts.map +0 -1
  211. package/dist/extensions/doom.mjs +0 -2
  212. package/dist/extensions/doom.mjs.map +0 -1
  213. package/dist/services/EditTracker/EditTracker.cjs +0 -2
  214. package/dist/services/EditTracker/EditTracker.cjs.map +0 -1
  215. package/dist/services/EditTracker/EditTracker.mjs +0 -2
  216. package/dist/services/EditTracker/EditTracker.mjs.map +0 -1
  217. package/dist/services/EditorConfigService/EditorConfigService.cjs +0 -2
  218. package/dist/services/EditorConfigService/EditorConfigService.cjs.map +0 -1
  219. package/dist/services/EditorConfigService/EditorConfigService.mjs +0 -2
  220. package/dist/services/EditorConfigService/EditorConfigService.mjs.map +0 -1
  221. package/dist/services/EditorLauncher/EditorLauncher.cjs +0 -2
  222. package/dist/services/EditorLauncher/EditorLauncher.cjs.map +0 -1
  223. package/dist/services/EditorLauncher/EditorLauncher.mjs +0 -2
  224. package/dist/services/EditorLauncher/EditorLauncher.mjs.map +0 -1
  225. package/dist/services/FileEditPaths/FileEditPaths.cjs +0 -2
  226. package/dist/services/FileEditPaths/FileEditPaths.cjs.map +0 -1
  227. package/dist/services/FileEditPaths/FileEditPaths.mjs +0 -2
  228. package/dist/services/FileEditPaths/FileEditPaths.mjs.map +0 -1
  229. package/dist/services/FileEditWorkflow/FileEditWorkflow.cjs +0 -2
  230. package/dist/services/FileEditWorkflow/FileEditWorkflow.cjs.map +0 -1
  231. package/dist/services/FileEditWorkflow/FileEditWorkflow.mjs +0 -2
  232. package/dist/services/FileEditWorkflow/FileEditWorkflow.mjs.map +0 -1
  233. package/dist/services/GitDiffService/GitDiffService.cjs +0 -5
  234. package/dist/services/GitDiffService/GitDiffService.cjs.map +0 -1
  235. package/dist/services/GitDiffService/GitDiffService.mjs +0 -5
  236. package/dist/services/GitDiffService/GitDiffService.mjs.map +0 -1
  237. package/dist/services/TimelineStore/TimelineStore.cjs +0 -3
  238. package/dist/services/TimelineStore/TimelineStore.cjs.map +0 -1
  239. package/dist/services/TimelineStore/TimelineStore.mjs +0 -3
  240. package/dist/services/TimelineStore/TimelineStore.mjs.map +0 -1
  241. package/dist/types.cjs +0 -2
  242. package/dist/types.cjs.map +0 -1
  243. package/dist/types.d.cts +0 -13
  244. package/dist/types.d.cts.map +0 -1
  245. package/dist/types.d.mts +0 -13
  246. package/dist/types.d.mts.map +0 -1
  247. package/dist/types.mjs +0 -2
  248. package/dist/types.mjs.map +0 -1
  249. /package/dist/{commandLine.cjs → adapters/process/commandLine.cjs} +0 -0
  250. /package/dist/{commandLine.mjs → adapters/process/commandLine.mjs} +0 -0
package/README.md CHANGED
@@ -1,37 +1,133 @@
1
1
  # @agimon-ai/doompi-file-edit
2
2
 
3
- Pi session file edit timeline and external editor overlay.
3
+ A session-scoped file-change timeline and external-editor launcher for Pi.
4
4
 
5
- A timeline of every file the session edited, plus an external editor handoff.
5
+ Part of the [DoomPi distribution](https://www.npmjs.com/package/@agimon-ai/doompi).
6
6
 
7
- Part of [Doompi](https://www.npmjs.com/package/@agimon-ai/doompi), a coding agent that loads
8
- only the skills and tools you name. This package is composed by Doompi and is not usually
9
- installed on its own.
7
+ The package tracks files changed through session tool calls and captures content for diffs, without
8
+ requiring a Git repository. `edit` and `write` name their file in the call, so the package can capture
9
+ the before and after content within its size and format limits. Bash calls instead trigger a bounded
10
+ tree comparison. See [What this cannot see](#what-this-cannot-see) for gaps in that coverage.
11
+
12
+ > **Alpha:** timeline and UI contracts may change between releases.
13
+
14
+ ## Requirements
15
+
16
+ - Node.js 22.19.0 or newer
17
+ - Pi 0.85.0 and Pi TUI 0.85.0
18
+ - Git for diffs against `HEAD`
10
19
 
11
20
  ## Install
12
21
 
22
+ `doompi init` and `dpi init` include File Edit in `default.packages` in `.doom/modes.yaml`.
23
+ Remove it or move it to a named layer to change which major modes load it. Standalone Pi loads the
24
+ same extension:
25
+
13
26
  ```bash
14
- npm install @agimon-ai/doompi-file-edit
27
+ pi install npm:@agimon-ai/doompi-file-edit
28
+ ```
29
+
30
+ | Entry | Purpose |
31
+ | ------------------------------------------- | -------------------------------------------- |
32
+ | `@agimon-ai/doompi-file-edit/extensions/pi` | Timeline and DoomPi Leader shortcut |
33
+ | `@agimon-ai/doompi-file-edit/session-api` | HTTP routes the cockpit reads a file through |
34
+ | `@agimon-ai/doompi-file-edit/web-hub` | Hub channel publishing the changed-file list |
35
+ | `@agimon-ai/doompi-file-edit` | Library API |
36
+
37
+ ## Open the timeline
38
+
39
+ Use `SPC e f` in DoomPi. Select a file to inspect its diff or open it in the configured editor.
40
+
41
+ TUI diffs compare the working tree with Git `HEAD` and are capped at 200 lines and 256 KiB. The
42
+ overlay and external-editor handoff require an interactive TUI. Headless hosts can consume the
43
+ timeline services but cannot display the panel.
44
+
45
+ ## In the cockpit
46
+
47
+ The `# files` group in the activity dock lists every file the session changed. Selecting one opens a
48
+ temporary tab holding three views of it:
49
+
50
+ - **diff**: what the session did to the file, followed by each recorded change on its own, so a file
51
+ edited four times shows four distinct diffs rather than one merged blur.
52
+ - **source**: the file as it stands, editable. Saving writes straight to disk and is refused if the
53
+ file changed since it was opened, so a hand edit cannot silently discard what the agent wrote.
54
+ - **preview**: rendered Markdown, or HTML in a sandboxed frame.
55
+
56
+ Selecting text in any view raises a comment box. Comments queue on the tab and one **send review**
57
+ builds a single message quoting each anchor, so several comments cost one turn.
58
+
59
+ Diffs here do not use Git. The package captures the file's content before an `edit` or `write` runs
60
+ and keeps it, content-addressed, beside the session timeline; both go when the session ends.
61
+
62
+ ### What this cannot see
63
+
64
+ - A file the session changed and then deleted. The dock lists things to open, so a row that can only
65
+ answer "this is gone" is left out. The timeline still holds the change, so a tab already open on
66
+ the file keeps working and says why it has nothing to show.
67
+ - A file changed by a background process that outlives its Bash call. The tree is compared when the
68
+ call ends.
69
+ - A file changed outside any tool. There is no always-on watcher.
70
+ - Content past 1 MiB, and binary files. These are listed as changed, without content.
71
+ - A file found only by comparing the tree has no baseline, so it is listed, readable and editable,
72
+ but never diffed. Rows and versions say so rather than showing an empty diff.
73
+ - The tree walk skips dependency and build directories and is capped on entries and depth, so a very
74
+ deep or very large checkout can under-report.
75
+
76
+ ## Configure the editor
77
+
78
+ Set the shared DoomPi configuration in `~/.pi/.doom/config.yaml`:
79
+
80
+ ```yaml
81
+ editor:
82
+ command: nvim +{line} {file}
15
83
  ```
16
84
 
17
- ## How it loads
85
+ For a standalone installation, the package falls back to
86
+ `~/.pi/agent/doom-file-edit/config.yaml`. Resolution order is:
87
+
88
+ 1. DoomPi `editor.command`;
89
+ 2. package fallback configuration;
90
+ 3. `$VISUAL`;
91
+ 4. `$EDITOR`;
92
+ 5. `nano {file}` on Unix-like systems.
93
+
94
+ Only `{file}` and `{line}` placeholders are expanded. The command is split and spawned directly,
95
+ not passed through a shell, so shell operators and expansions are not interpreted.
18
96
 
19
- Doompi loads this unconditionally. It is core, not a layer, so it does not appear in
20
- `.doom/modes.yaml`: making it optional would only create broken configurations.
97
+ ## Data behavior
21
98
 
22
- Extension entry: `@agimon-ai/doompi-file-edit/extensions/doom`
99
+ The timeline contains file paths, and the snapshot store holds copies of the file content the
100
+ session changed. That content can be sensitive. Both live under the Pi agent directory,
101
+ `$PI_CODING_AGENT_DIR` or `~/.pi/agent/doom-file-edit`, never inside the working tree, and should be
102
+ protected with the same access controls as Pi session data.
23
103
 
24
- ## Leader
104
+ A session removes its own timeline and snapshots when it ends. A session that is killed cannot, so
105
+ each session also sweeps state that no longer belongs to anyone: a timeline and its snapshots are
106
+ removed once nothing has written to them for a week. An older build kept this state in the
107
+ repository's git common directory, and that directory is cleared away under the same rule.
25
108
 
26
- `SPC e f` opens session edits, once the extension is loaded.
109
+ The session API reads and writes only files the timeline already records, so a request cannot reach
110
+ a file this session never changed.
27
111
 
28
- ## Entry points
112
+ ## Public API
113
+
114
+ ```ts
115
+ import { createFileEditContainer, fileEditExtension } from '@agimon-ai/doompi-file-edit';
116
+ import type { FileDiff, FileEditEntry } from '@agimon-ai/doompi-file-edit';
117
+ ```
118
+
119
+ The root also exports editor-resolution and timeline domain types for host integrations.
120
+
121
+ ## Development
122
+
123
+ ```bash
124
+ pnpm build
125
+ pnpm typecheck
126
+ pnpm test
127
+ pnpm lint
128
+ ```
29
129
 
30
- | Import |
31
- | --------------------------------------------- |
32
- | `@agimon-ai/doompi-file-edit` |
33
- | `@agimon-ai/doompi-file-edit/extensions/pi` |
34
- | `@agimon-ai/doompi-file-edit/extensions/doom` |
130
+ Maintained by [Agimon](https://agimon.ai/about).
35
131
 
36
132
  ## License
37
133
 
@@ -0,0 +1,2 @@
1
+ const e=require("../../_virtual/_rolldown/runtime.cjs"),t=require("../../services/lineDiff.cjs");let n=require("node:path");n=e.__toESM(n,1);const r=`bash`;function i(e,t){if(!e||typeof e!=`object`)return;let n=e[t];return typeof n==`string`?n:void 0}var a=class{timeline;snapshots;manifests;pending=new Map;bracketed=new Map;manifest;excluded=[];isIgnored;contents=new Map;now;git;constructor(e,t,n,r={}){this.timeline=e,this.snapshots=t,this.manifests=n,this.now=r.now??Date.now,this.git=r.git}reset(e={}){this.pending.clear(),this.bracketed.clear(),this.contents.clear(),this.manifest=void 0,this.excluded=e.exclude??[],this.isIgnored=e.isIgnored}async start(e,t,a,o){if(t===`edit`||t===`write`){let r=i(a,`path`);if(!r)return;let s=n.default.resolve(o,r),[c,l]=await Promise.all([this.snapshots.capture(s),this.manifests.fingerprint(s)]);this.pending.set(e,{tool:t,filePath:s,before:c,existed:l!==void 0});return}t===r&&(this.bracketed.set(e,this.now()),this.manifest??=await this.manifests.take(o,this.excluded))}async end(e,t,n){let r=this.pending.get(e);this.pending.delete(e);let i=this.bracketed.get(e);if(this.bracketed.delete(e),r){t||await this.recordTool(r);return}i!==void 0&&await this.recordScan(n,i)}async recordTool(e){let t=await this.snapshots.capture(e.filePath),n=!e.existed,r=await this.countChanges(e.before,t,n);t!==void 0&&this.contents.set(e.filePath,t),await this.append({version:2,path:e.filePath,tool:e.tool,at:this.now(),origin:`tool`,...e.before===void 0?{}:{before:e.before},...t===void 0?{}:{after:t},...n?{created:!0}:{},...r}),await this.remember(e.filePath)}async recordScan(e,t){let n=this.manifest;if(n===void 0)return;let i=await this.manifests.take(e,this.excluded);this.manifest=i;let a=this.isIgnored,o=this.manifests.changed(n,i).filter(e=>a===void 0||!a(e)),s=await this.writtenDuring(o,t);if(s.length===0)return;let c=await this.unchangedInGit(e,s);for(let e of s){let t=this.contents.get(e);if(t===void 0&&c.has(e))continue;let a=n.entries.get(e),o=i.entries.get(e),s=o===void 0?void 0:await this.snapshots.capture(e);if(s!==void 0&&this.contents.set(e,s),s!==void 0&&s===t)continue;let l=a===void 0||o===void 0||this.manifests.sizeChanged(a,o)||t!==void 0&&s!==void 0&&s!==t;await this.append({version:2,path:e,tool:r,at:this.now(),origin:`scan`,...l?{verified:!0}:{},...s===void 0?{}:{after:s}})}}async writtenDuring(e,t){let n=t-1e3,r=[];for(let t of e){let e=await this.manifests.modifiedAt(t);(e===void 0||e>=n)&&r.push(t)}return r}async unchangedInGit(e,t){let n=t.filter(e=>!this.contents.has(e));return this.git===void 0||n.length===0?new Set:this.git.unchanged(e,n)}async countChanges(e,n,r){if(n===void 0)return{};if(e===void 0){if(!r)return{};let e=await this.snapshots.read(n);if(e===void 0)return{};let i=t.lineDiffFromEmpty(e);return{additions:i.additions,removals:i.removals}}if(e===n)return{additions:0,removals:0};let[i,a]=await Promise.all([this.snapshots.read(e),this.snapshots.read(n)]);if(i===void 0||a===void 0)return{};let o=t.lineDiff(i,a);return{additions:o.additions,removals:o.removals}}async append(e){(e.before===void 0||e.before!==e.after)&&await this.timeline.append(e)}async remember(e){if(this.manifest===void 0)return;let t=new Map(this.manifest.entries),n=await this.manifests.fingerprint(e);n===void 0?t.delete(e):t.set(e,n),this.manifest={entries:t,truncated:this.manifest.truncated}}};exports.EditTracker=a;
2
+ //# sourceMappingURL=EditTracker.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"EditTracker.cjs","names":["path","lineDiffFromEmpty","lineDiff"],"sources":["../../../src/adapters/EditTracker/EditTracker.ts"],"sourcesContent":["import path from 'node:path';\nimport { lineDiff, lineDiffFromEmpty } from '../../services/lineDiff.ts';\nimport type { FileEditTool, TimelineEvent } from '../../types/domain';\nimport type { IEditTracker } from '../../types/editTracker';\nimport type { GitStatusPort } from '../../types/gitStatus.ts';\nimport type { SnapshotStorePort } from '../../types/snapshotStore.ts';\nimport type { ITimelineStore } from '../../types/timelineStore';\nimport type { TreeManifest, TreeManifestPort } from '../../types/treeManifest.ts';\n\nconst EDIT_TOOL = 'edit';\nconst WRITE_TOOL = 'write';\nconst BASH_TOOL = 'bash';\n\n/**\n * Records what the session changed, and captures enough of it to be diffed.\n *\n * Two mechanisms, because one is not enough. `edit` and `write` name their file\n * in the call arguments, so the content is read before the tool runs and both\n * sides of the change are known exactly. `bash` names nothing reliable: the\n * agent can write a script and run it, and reading path-shaped tokens out of\n * the command would miss every file that script touches. So a bash call is\n * bracketed by tree manifests instead, and whatever moved between them is\n * recorded, however it was written.\n *\n * A manifest-found path is recorded without a baseline, because it was only\n * identified after it had already changed. That is a real limit and the wire\n * carries it as `origin: 'scan'` rather than pretending a diff exists.\n *\n * A manifest compares size and modification time, and it compares the tree as\n * this tracker last walked it against the tree now, so it answers whether a\n * file differs, never when it moved. A path a previous session left dirty, or\n * one a checkout or an install rewrote, differs exactly like a path the command\n * just wrote. So a candidate is called verified only when something actually\n * proves its bytes moved: it appeared, it vanished, its recorded size differs,\n * or its content hash differs from one this session already took. Absence of\n * proof is not proof, so a candidate that shows none of those is still\n * recorded, because the timeline is the evidence, but it goes out unverified\n * and every surface leaves it out.\n */\ninterface PendingEdit {\n tool: 'edit' | 'write';\n filePath: string;\n before: string | undefined;\n /**\n * Whether the file was there when the call began. A missing `before` cannot\n * say on its own: content is left uncaptured both for a file that does not\n * exist and for one too large or too binary to store.\n */\n existed: boolean;\n}\n\nfunction objectValue(value: unknown, key: string): string | undefined {\n if (!value || typeof value !== 'object') return undefined;\n const found = (value as Record<string, unknown>)[key];\n return typeof found === 'string' ? found : undefined;\n}\n\nexport interface EditTrackerOptions {\n /** Injectable so a test can pin the recorded timestamps. */\n now?: () => number;\n /**\n * Decides whether a first-seen scan candidate actually changed. Optional:\n * without it the tracker keeps recording every candidate it cannot disprove.\n */\n git?: GitStatusPort;\n}\n\n/**\n * How far before a call started a write may claim to have happened and still be\n * attributed to it. A working tree can sit on a filesystem that stores whole\n * seconds, which floors a write made just after the call began to a stamp just\n * before it, and the cost of being generous here is one second of the staleness\n * this check exists to remove.\n */\nconst MODIFIED_TOLERANCE_MS = 1000;\n\nexport class EditTracker implements IEditTracker {\n private readonly pending = new Map<string, PendingEdit>();\n /** Start time per in-flight bash call, so its end knows what it may claim. */\n private readonly bracketed = new Map<string, number>();\n /**\n * The tree as this tracker last saw it. A bash call compares against it and\n * then replaces it, so each call costs one walk rather than two, and a change\n * made between calls is still noticed on the next one.\n */\n private manifest: TreeManifest | undefined;\n /**\n * This package's own storage, which the walk must never report. The timeline\n * and its snapshots can land inside the tree being watched, and recording\n * them would make every change cause another one.\n */\n private excluded: readonly string[] = [];\n /**\n * The project's own ignore rules. A path the project disowns is not worth a\n * git call, a read, or a stored copy of its content, so it is dropped before\n * it costs any of them.\n */\n private isIgnored: ((filePath: string) => boolean) | undefined;\n /**\n * The last content hash this session saw per path, from either mechanism.\n * A candidate whose hash has not moved was touched, not edited.\n */\n private readonly contents = new Map<string, string>();\n private readonly now: () => number;\n private readonly git: GitStatusPort | undefined;\n\n constructor(\n private readonly timeline: ITimelineStore,\n private readonly snapshots: SnapshotStorePort,\n private readonly manifests: TreeManifestPort,\n options: EditTrackerOptions = {},\n ) {\n this.now = options.now ?? Date.now;\n this.git = options.git;\n }\n\n /**\n * Forgets the previous session's tree so a new one does not inherit its\n * baseline, and takes the paths this session's own bookkeeping occupies.\n */\n reset(options: { exclude?: readonly string[]; isIgnored?: (filePath: string) => boolean } = {}): void {\n this.pending.clear();\n this.bracketed.clear();\n this.contents.clear();\n this.manifest = undefined;\n this.excluded = options.exclude ?? [];\n this.isIgnored = options.isIgnored;\n }\n\n async start(id: string, tool: string, args: unknown, cwd: string): Promise<void> {\n if (tool === EDIT_TOOL || tool === WRITE_TOOL) {\n const supplied = objectValue(args, 'path');\n if (!supplied) return;\n const filePath = path.resolve(cwd, supplied);\n // Both are read before the tool runs. The fingerprint is the only thing\n // that tells a file being created from one whose content could not be\n // captured, because a capture answers undefined for either.\n const [before, fingerprint] = await Promise.all([\n this.snapshots.capture(filePath),\n this.manifests.fingerprint(filePath),\n ]);\n this.pending.set(id, { tool, filePath, before, existed: fingerprint !== undefined });\n return;\n }\n if (tool !== BASH_TOOL) return;\n // Read before the baseline walk, which is the one thing here that can take\n // long enough to matter: a write that races it belongs to this call.\n this.bracketed.set(id, this.now());\n // The first bash call of a session has nothing to compare against, so it\n // pays for the baseline walk; every later call reuses the previous end.\n this.manifest ??= await this.manifests.take(cwd, this.excluded);\n }\n\n async end(id: string, isError: boolean, cwd: string): Promise<void> {\n const pending = this.pending.get(id);\n this.pending.delete(id);\n const startedAt = this.bracketed.get(id);\n this.bracketed.delete(id);\n if (pending) {\n // A failed edit or write never landed, and its arguments named the file,\n // so there is nothing left to look for.\n if (!isError) await this.recordTool(pending);\n return;\n }\n // A failed command may still have written before it failed. Skipping the\n // walk would leave the baseline stale and hand those writes to whichever\n // call closes next.\n if (startedAt !== undefined) await this.recordScan(cwd, startedAt);\n }\n\n /** An `edit` or `write` whose file was read on both sides of the call. */\n private async recordTool(pending: PendingEdit): Promise<void> {\n const after = await this.snapshots.capture(pending.filePath);\n const created = !pending.existed;\n const counts = await this.countChanges(pending.before, after, created);\n if (after !== undefined) this.contents.set(pending.filePath, after);\n await this.append({\n version: 2,\n path: pending.filePath,\n tool: pending.tool,\n at: this.now(),\n origin: 'tool',\n ...(pending.before === undefined ? {} : { before: pending.before }),\n ...(after === undefined ? {} : { after }),\n ...(created ? { created: true } : {}),\n ...counts,\n });\n // The tool already accounted for this path, so the next bash comparison\n // must not report it a second time under its own name.\n await this.remember(pending.filePath);\n }\n\n /** Whatever a bash call actually edited, however the command wrote it. */\n private async recordScan(cwd: string, startedAt: number): Promise<void> {\n const before = this.manifest;\n if (before === undefined) return;\n const after = await this.manifests.take(cwd, this.excluded);\n this.manifest = after;\n const disowned = this.isIgnored;\n const named = this.manifests\n .changed(before, after)\n .filter((filePath) => disowned === undefined || !disowned(filePath));\n const candidates = await this.writtenDuring(named, startedAt);\n if (candidates.length === 0) return;\n const unchanged = await this.unchangedInGit(cwd, candidates);\n for (const filePath of candidates) {\n const known = this.contents.get(filePath);\n // Asked before the file is read: a path git vouches for is worth neither\n // the read nor the stored copy that reading it leaves behind.\n if (known === undefined && unchanged.has(filePath)) continue;\n const beforePrint = before.entries.get(filePath);\n const afterPrint = after.entries.get(filePath);\n // A path that is gone has nothing to read, and reading it back would only\n // confirm that.\n const captured = afterPrint === undefined ? undefined : await this.snapshots.capture(filePath);\n if (captured !== undefined) this.contents.set(filePath, captured);\n // The bytes are the ones this session already recorded: the call moved the\n // modification time and nothing else.\n if (captured !== undefined && captured === known) continue;\n const proven =\n beforePrint === undefined ||\n afterPrint === undefined ||\n this.manifests.sizeChanged(beforePrint, afterPrint) ||\n (known !== undefined && captured !== undefined && captured !== known);\n await this.append({\n version: 2,\n path: filePath,\n tool: BASH_TOOL,\n at: this.now(),\n origin: 'scan',\n ...(proven ? { verified: true } : {}),\n ...(captured === undefined ? {} : { after: captured }),\n });\n }\n }\n\n /**\n * Narrows candidates to the ones that could have been written by the call\n * being closed.\n *\n * This is what keeps a working tree that was already dirty out of the list. A\n * file whose bytes were last written before the call began was differed by\n * something else, whatever moved its fingerprint. A file that is no longer\n * there has no time to read and a delete is a change the call may well have\n * made, so it stays a candidate.\n */\n private async writtenDuring(candidates: readonly string[], startedAt: number): Promise<string[]> {\n const floor = startedAt - MODIFIED_TOLERANCE_MS;\n const written: string[] = [];\n for (const filePath of candidates) {\n const modifiedAt = await this.manifests.modifiedAt(filePath);\n if (modifiedAt === undefined || modifiedAt >= floor) written.push(filePath);\n }\n return written;\n }\n\n /** Which candidates git tracks and reports as untouched; empty when it cannot say. */\n private async unchangedInGit(cwd: string, candidates: readonly string[]): Promise<ReadonlySet<string>> {\n const unseen = candidates.filter((filePath) => !this.contents.has(filePath));\n if (this.git === undefined || unseen.length === 0) return new Set();\n return this.git.unchanged(cwd, unseen);\n }\n\n /** How many lines moved, when there is enough captured content to say. */\n private async countChanges(\n before: string | undefined,\n after: string | undefined,\n created: boolean,\n ): Promise<{ additions?: number; removals?: number }> {\n if (after === undefined) return {};\n if (before === undefined) {\n // A file that did not exist has an empty baseline, so every line it now\n // holds is an addition. A file that existed but went uncaptured has no\n // baseline to count against at all.\n if (!created) return {};\n const createdText = await this.snapshots.read(after);\n if (createdText === undefined) return {};\n const fresh = lineDiffFromEmpty(createdText);\n return { additions: fresh.additions, removals: fresh.removals };\n }\n if (before === after) return { additions: 0, removals: 0 };\n const [beforeText, afterText] = await Promise.all([this.snapshots.read(before), this.snapshots.read(after)]);\n if (beforeText === undefined || afterText === undefined) return {};\n const diff = lineDiff(beforeText, afterText);\n return { additions: diff.additions, removals: diff.removals };\n }\n\n /** Records the change unless it turned out to be no change at all. */\n private async append(event: TimelineEvent): Promise<void> {\n if (event.before !== undefined && event.before === event.after) return;\n await this.timeline.append(event);\n }\n\n /**\n * Folds a path the tool layer just handled into the tracked manifest, so the\n * next bash comparison sees it as already accounted for.\n *\n * The fingerprint has to be the one a walk would read, not a stand-in, or the\n * next comparison reports the file again under bash and every tool edit is\n * recorded twice.\n */\n private async remember(filePath: string): Promise<void> {\n if (this.manifest === undefined) return;\n const entries = new Map(this.manifest.entries);\n const fingerprint = await this.manifests.fingerprint(filePath);\n if (fingerprint === undefined) entries.delete(filePath);\n else entries.set(filePath, fingerprint);\n this.manifest = { entries, truncated: this.manifest.truncated };\n }\n}\n\n/** The tools this tracker knows how to attribute a change to. */\nexport const TRACKED_TOOLS: readonly FileEditTool[] = [EDIT_TOOL, WRITE_TOOL, BASH_TOOL];\n"],"mappings":"6IASA,MAEM,EAAY,OAwClB,SAAS,EAAY,EAAgB,EAAiC,CACpE,GAAI,CAAC,GAAS,OAAO,GAAU,SAAU,OACzC,IAAM,EAAS,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MAAO,CAAC,EACjC,GAAI,IAAW,IAAA,GAAW,CAIxB,GAAI,CAAC,EAAS,MAAO,CAAC,EACtB,IAAM,EAAc,MAAM,KAAK,UAAU,KAAK,CAAK,EACnD,GAAI,IAAgB,IAAA,GAAW,MAAO,CAAC,EACvC,IAAM,EAAQC,EAAAA,kBAAkB,CAAW,EAC3C,MAAO,CAAE,UAAW,EAAM,UAAW,SAAU,EAAM,QAAS,CAChE,CACA,GAAI,IAAW,EAAO,MAAO,CAAE,UAAW,EAAG,SAAU,CAAE,EACzD,GAAM,CAAC,EAAY,GAAa,MAAM,QAAQ,IAAI,CAAC,KAAK,UAAU,KAAK,CAAM,EAAG,KAAK,UAAU,KAAK,CAAK,CAAC,CAAC,EAC3G,GAAI,IAAe,IAAA,IAAa,IAAc,IAAA,GAAW,MAAO,CAAC,EACjE,IAAM,EAAOC,EAAAA,SAAS,EAAY,CAAS,EAC3C,MAAO,CAAE,UAAW,EAAK,UAAW,SAAU,EAAK,QAAS,CAC9D,CAGA,MAAc,OAAO,EAAqC,EACpD,EAAM,SAAW,IAAA,IAAa,EAAM,SAAW,EAAM,QACzD,MAAM,KAAK,SAAS,OAAO,CAAK,CAClC,CAUA,MAAc,SAAS,EAAiC,CACtD,GAAI,KAAK,WAAa,IAAA,GAAW,OACjC,IAAM,EAAU,IAAI,IAAI,KAAK,SAAS,OAAO,EACvC,EAAc,MAAM,KAAK,UAAU,YAAY,CAAQ,EACzD,IAAgB,IAAA,GAAW,EAAQ,OAAO,CAAQ,EACjD,EAAQ,IAAI,EAAU,CAAW,EACtC,KAAK,SAAW,CAAE,UAAS,UAAW,KAAK,SAAS,SAAU,CAChE,CACF"}
@@ -0,0 +1,2 @@
1
+ import{lineDiff as e,lineDiffFromEmpty as t}from"../../services/lineDiff.mjs";import n from"node:path";const r=`bash`;function i(e,t){if(!e||typeof e!=`object`)return;let n=e[t];return typeof n==`string`?n:void 0}var a=class{timeline;snapshots;manifests;pending=new Map;bracketed=new Map;manifest;excluded=[];isIgnored;contents=new Map;now;git;constructor(e,t,n,r={}){this.timeline=e,this.snapshots=t,this.manifests=n,this.now=r.now??Date.now,this.git=r.git}reset(e={}){this.pending.clear(),this.bracketed.clear(),this.contents.clear(),this.manifest=void 0,this.excluded=e.exclude??[],this.isIgnored=e.isIgnored}async start(e,t,a,o){if(t===`edit`||t===`write`){let r=i(a,`path`);if(!r)return;let s=n.resolve(o,r),[c,l]=await Promise.all([this.snapshots.capture(s),this.manifests.fingerprint(s)]);this.pending.set(e,{tool:t,filePath:s,before:c,existed:l!==void 0});return}t===r&&(this.bracketed.set(e,this.now()),this.manifest??=await this.manifests.take(o,this.excluded))}async end(e,t,n){let r=this.pending.get(e);this.pending.delete(e);let i=this.bracketed.get(e);if(this.bracketed.delete(e),r){t||await this.recordTool(r);return}i!==void 0&&await this.recordScan(n,i)}async recordTool(e){let t=await this.snapshots.capture(e.filePath),n=!e.existed,r=await this.countChanges(e.before,t,n);t!==void 0&&this.contents.set(e.filePath,t),await this.append({version:2,path:e.filePath,tool:e.tool,at:this.now(),origin:`tool`,...e.before===void 0?{}:{before:e.before},...t===void 0?{}:{after:t},...n?{created:!0}:{},...r}),await this.remember(e.filePath)}async recordScan(e,t){let n=this.manifest;if(n===void 0)return;let i=await this.manifests.take(e,this.excluded);this.manifest=i;let a=this.isIgnored,o=this.manifests.changed(n,i).filter(e=>a===void 0||!a(e)),s=await this.writtenDuring(o,t);if(s.length===0)return;let c=await this.unchangedInGit(e,s);for(let e of s){let t=this.contents.get(e);if(t===void 0&&c.has(e))continue;let a=n.entries.get(e),o=i.entries.get(e),s=o===void 0?void 0:await this.snapshots.capture(e);if(s!==void 0&&this.contents.set(e,s),s!==void 0&&s===t)continue;let l=a===void 0||o===void 0||this.manifests.sizeChanged(a,o)||t!==void 0&&s!==void 0&&s!==t;await this.append({version:2,path:e,tool:r,at:this.now(),origin:`scan`,...l?{verified:!0}:{},...s===void 0?{}:{after:s}})}}async writtenDuring(e,t){let n=t-1e3,r=[];for(let t of e){let e=await this.manifests.modifiedAt(t);(e===void 0||e>=n)&&r.push(t)}return r}async unchangedInGit(e,t){let n=t.filter(e=>!this.contents.has(e));return this.git===void 0||n.length===0?new Set:this.git.unchanged(e,n)}async countChanges(n,r,i){if(r===void 0)return{};if(n===void 0){if(!i)return{};let e=await this.snapshots.read(r);if(e===void 0)return{};let n=t(e);return{additions:n.additions,removals:n.removals}}if(n===r)return{additions:0,removals:0};let[a,o]=await Promise.all([this.snapshots.read(n),this.snapshots.read(r)]);if(a===void 0||o===void 0)return{};let s=e(a,o);return{additions:s.additions,removals:s.removals}}async append(e){(e.before===void 0||e.before!==e.after)&&await this.timeline.append(e)}async remember(e){if(this.manifest===void 0)return;let t=new Map(this.manifest.entries),n=await this.manifests.fingerprint(e);n===void 0?t.delete(e):t.set(e,n),this.manifest={entries:t,truncated:this.manifest.truncated}}};export{a as EditTracker};
2
+ //# sourceMappingURL=EditTracker.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"EditTracker.mjs","names":[],"sources":["../../../src/adapters/EditTracker/EditTracker.ts"],"sourcesContent":["import path from 'node:path';\nimport { lineDiff, lineDiffFromEmpty } from '../../services/lineDiff.ts';\nimport type { FileEditTool, TimelineEvent } from '../../types/domain';\nimport type { IEditTracker } from '../../types/editTracker';\nimport type { GitStatusPort } from '../../types/gitStatus.ts';\nimport type { SnapshotStorePort } from '../../types/snapshotStore.ts';\nimport type { ITimelineStore } from '../../types/timelineStore';\nimport type { TreeManifest, TreeManifestPort } from '../../types/treeManifest.ts';\n\nconst EDIT_TOOL = 'edit';\nconst WRITE_TOOL = 'write';\nconst BASH_TOOL = 'bash';\n\n/**\n * Records what the session changed, and captures enough of it to be diffed.\n *\n * Two mechanisms, because one is not enough. `edit` and `write` name their file\n * in the call arguments, so the content is read before the tool runs and both\n * sides of the change are known exactly. `bash` names nothing reliable: the\n * agent can write a script and run it, and reading path-shaped tokens out of\n * the command would miss every file that script touches. So a bash call is\n * bracketed by tree manifests instead, and whatever moved between them is\n * recorded, however it was written.\n *\n * A manifest-found path is recorded without a baseline, because it was only\n * identified after it had already changed. That is a real limit and the wire\n * carries it as `origin: 'scan'` rather than pretending a diff exists.\n *\n * A manifest compares size and modification time, and it compares the tree as\n * this tracker last walked it against the tree now, so it answers whether a\n * file differs, never when it moved. A path a previous session left dirty, or\n * one a checkout or an install rewrote, differs exactly like a path the command\n * just wrote. So a candidate is called verified only when something actually\n * proves its bytes moved: it appeared, it vanished, its recorded size differs,\n * or its content hash differs from one this session already took. Absence of\n * proof is not proof, so a candidate that shows none of those is still\n * recorded, because the timeline is the evidence, but it goes out unverified\n * and every surface leaves it out.\n */\ninterface PendingEdit {\n tool: 'edit' | 'write';\n filePath: string;\n before: string | undefined;\n /**\n * Whether the file was there when the call began. A missing `before` cannot\n * say on its own: content is left uncaptured both for a file that does not\n * exist and for one too large or too binary to store.\n */\n existed: boolean;\n}\n\nfunction objectValue(value: unknown, key: string): string | undefined {\n if (!value || typeof value !== 'object') return undefined;\n const found = (value as Record<string, unknown>)[key];\n return typeof found === 'string' ? found : undefined;\n}\n\nexport interface EditTrackerOptions {\n /** Injectable so a test can pin the recorded timestamps. */\n now?: () => number;\n /**\n * Decides whether a first-seen scan candidate actually changed. Optional:\n * without it the tracker keeps recording every candidate it cannot disprove.\n */\n git?: GitStatusPort;\n}\n\n/**\n * How far before a call started a write may claim to have happened and still be\n * attributed to it. A working tree can sit on a filesystem that stores whole\n * seconds, which floors a write made just after the call began to a stamp just\n * before it, and the cost of being generous here is one second of the staleness\n * this check exists to remove.\n */\nconst MODIFIED_TOLERANCE_MS = 1000;\n\nexport class EditTracker implements IEditTracker {\n private readonly pending = new Map<string, PendingEdit>();\n /** Start time per in-flight bash call, so its end knows what it may claim. */\n private readonly bracketed = new Map<string, number>();\n /**\n * The tree as this tracker last saw it. A bash call compares against it and\n * then replaces it, so each call costs one walk rather than two, and a change\n * made between calls is still noticed on the next one.\n */\n private manifest: TreeManifest | undefined;\n /**\n * This package's own storage, which the walk must never report. The timeline\n * and its snapshots can land inside the tree being watched, and recording\n * them would make every change cause another one.\n */\n private excluded: readonly string[] = [];\n /**\n * The project's own ignore rules. A path the project disowns is not worth a\n * git call, a read, or a stored copy of its content, so it is dropped before\n * it costs any of them.\n */\n private isIgnored: ((filePath: string) => boolean) | undefined;\n /**\n * The last content hash this session saw per path, from either mechanism.\n * A candidate whose hash has not moved was touched, not edited.\n */\n private readonly contents = new Map<string, string>();\n private readonly now: () => number;\n private readonly git: GitStatusPort | undefined;\n\n constructor(\n private readonly timeline: ITimelineStore,\n private readonly snapshots: SnapshotStorePort,\n private readonly manifests: TreeManifestPort,\n options: EditTrackerOptions = {},\n ) {\n this.now = options.now ?? Date.now;\n this.git = options.git;\n }\n\n /**\n * Forgets the previous session's tree so a new one does not inherit its\n * baseline, and takes the paths this session's own bookkeeping occupies.\n */\n reset(options: { exclude?: readonly string[]; isIgnored?: (filePath: string) => boolean } = {}): void {\n this.pending.clear();\n this.bracketed.clear();\n this.contents.clear();\n this.manifest = undefined;\n this.excluded = options.exclude ?? [];\n this.isIgnored = options.isIgnored;\n }\n\n async start(id: string, tool: string, args: unknown, cwd: string): Promise<void> {\n if (tool === EDIT_TOOL || tool === WRITE_TOOL) {\n const supplied = objectValue(args, 'path');\n if (!supplied) return;\n const filePath = path.resolve(cwd, supplied);\n // Both are read before the tool runs. The fingerprint is the only thing\n // that tells a file being created from one whose content could not be\n // captured, because a capture answers undefined for either.\n const [before, fingerprint] = await Promise.all([\n this.snapshots.capture(filePath),\n this.manifests.fingerprint(filePath),\n ]);\n this.pending.set(id, { tool, filePath, before, existed: fingerprint !== undefined });\n return;\n }\n if (tool !== BASH_TOOL) return;\n // Read before the baseline walk, which is the one thing here that can take\n // long enough to matter: a write that races it belongs to this call.\n this.bracketed.set(id, this.now());\n // The first bash call of a session has nothing to compare against, so it\n // pays for the baseline walk; every later call reuses the previous end.\n this.manifest ??= await this.manifests.take(cwd, this.excluded);\n }\n\n async end(id: string, isError: boolean, cwd: string): Promise<void> {\n const pending = this.pending.get(id);\n this.pending.delete(id);\n const startedAt = this.bracketed.get(id);\n this.bracketed.delete(id);\n if (pending) {\n // A failed edit or write never landed, and its arguments named the file,\n // so there is nothing left to look for.\n if (!isError) await this.recordTool(pending);\n return;\n }\n // A failed command may still have written before it failed. Skipping the\n // walk would leave the baseline stale and hand those writes to whichever\n // call closes next.\n if (startedAt !== undefined) await this.recordScan(cwd, startedAt);\n }\n\n /** An `edit` or `write` whose file was read on both sides of the call. */\n private async recordTool(pending: PendingEdit): Promise<void> {\n const after = await this.snapshots.capture(pending.filePath);\n const created = !pending.existed;\n const counts = await this.countChanges(pending.before, after, created);\n if (after !== undefined) this.contents.set(pending.filePath, after);\n await this.append({\n version: 2,\n path: pending.filePath,\n tool: pending.tool,\n at: this.now(),\n origin: 'tool',\n ...(pending.before === undefined ? {} : { before: pending.before }),\n ...(after === undefined ? {} : { after }),\n ...(created ? { created: true } : {}),\n ...counts,\n });\n // The tool already accounted for this path, so the next bash comparison\n // must not report it a second time under its own name.\n await this.remember(pending.filePath);\n }\n\n /** Whatever a bash call actually edited, however the command wrote it. */\n private async recordScan(cwd: string, startedAt: number): Promise<void> {\n const before = this.manifest;\n if (before === undefined) return;\n const after = await this.manifests.take(cwd, this.excluded);\n this.manifest = after;\n const disowned = this.isIgnored;\n const named = this.manifests\n .changed(before, after)\n .filter((filePath) => disowned === undefined || !disowned(filePath));\n const candidates = await this.writtenDuring(named, startedAt);\n if (candidates.length === 0) return;\n const unchanged = await this.unchangedInGit(cwd, candidates);\n for (const filePath of candidates) {\n const known = this.contents.get(filePath);\n // Asked before the file is read: a path git vouches for is worth neither\n // the read nor the stored copy that reading it leaves behind.\n if (known === undefined && unchanged.has(filePath)) continue;\n const beforePrint = before.entries.get(filePath);\n const afterPrint = after.entries.get(filePath);\n // A path that is gone has nothing to read, and reading it back would only\n // confirm that.\n const captured = afterPrint === undefined ? undefined : await this.snapshots.capture(filePath);\n if (captured !== undefined) this.contents.set(filePath, captured);\n // The bytes are the ones this session already recorded: the call moved the\n // modification time and nothing else.\n if (captured !== undefined && captured === known) continue;\n const proven =\n beforePrint === undefined ||\n afterPrint === undefined ||\n this.manifests.sizeChanged(beforePrint, afterPrint) ||\n (known !== undefined && captured !== undefined && captured !== known);\n await this.append({\n version: 2,\n path: filePath,\n tool: BASH_TOOL,\n at: this.now(),\n origin: 'scan',\n ...(proven ? { verified: true } : {}),\n ...(captured === undefined ? {} : { after: captured }),\n });\n }\n }\n\n /**\n * Narrows candidates to the ones that could have been written by the call\n * being closed.\n *\n * This is what keeps a working tree that was already dirty out of the list. A\n * file whose bytes were last written before the call began was differed by\n * something else, whatever moved its fingerprint. A file that is no longer\n * there has no time to read and a delete is a change the call may well have\n * made, so it stays a candidate.\n */\n private async writtenDuring(candidates: readonly string[], startedAt: number): Promise<string[]> {\n const floor = startedAt - MODIFIED_TOLERANCE_MS;\n const written: string[] = [];\n for (const filePath of candidates) {\n const modifiedAt = await this.manifests.modifiedAt(filePath);\n if (modifiedAt === undefined || modifiedAt >= floor) written.push(filePath);\n }\n return written;\n }\n\n /** Which candidates git tracks and reports as untouched; empty when it cannot say. */\n private async unchangedInGit(cwd: string, candidates: readonly string[]): Promise<ReadonlySet<string>> {\n const unseen = candidates.filter((filePath) => !this.contents.has(filePath));\n if (this.git === undefined || unseen.length === 0) return new Set();\n return this.git.unchanged(cwd, unseen);\n }\n\n /** How many lines moved, when there is enough captured content to say. */\n private async countChanges(\n before: string | undefined,\n after: string | undefined,\n created: boolean,\n ): Promise<{ additions?: number; removals?: number }> {\n if (after === undefined) return {};\n if (before === undefined) {\n // A file that did not exist has an empty baseline, so every line it now\n // holds is an addition. A file that existed but went uncaptured has no\n // baseline to count against at all.\n if (!created) return {};\n const createdText = await this.snapshots.read(after);\n if (createdText === undefined) return {};\n const fresh = lineDiffFromEmpty(createdText);\n return { additions: fresh.additions, removals: fresh.removals };\n }\n if (before === after) return { additions: 0, removals: 0 };\n const [beforeText, afterText] = await Promise.all([this.snapshots.read(before), this.snapshots.read(after)]);\n if (beforeText === undefined || afterText === undefined) return {};\n const diff = lineDiff(beforeText, afterText);\n return { additions: diff.additions, removals: diff.removals };\n }\n\n /** Records the change unless it turned out to be no change at all. */\n private async append(event: TimelineEvent): Promise<void> {\n if (event.before !== undefined && event.before === event.after) return;\n await this.timeline.append(event);\n }\n\n /**\n * Folds a path the tool layer just handled into the tracked manifest, so the\n * next bash comparison sees it as already accounted for.\n *\n * The fingerprint has to be the one a walk would read, not a stand-in, or the\n * next comparison reports the file again under bash and every tool edit is\n * recorded twice.\n */\n private async remember(filePath: string): Promise<void> {\n if (this.manifest === undefined) return;\n const entries = new Map(this.manifest.entries);\n const fingerprint = await this.manifests.fingerprint(filePath);\n if (fingerprint === undefined) entries.delete(filePath);\n else entries.set(filePath, fingerprint);\n this.manifest = { entries, truncated: this.manifest.truncated };\n }\n}\n\n/** The tools this tracker knows how to attribute a change to. */\nexport const TRACKED_TOOLS: readonly FileEditTool[] = [EDIT_TOOL, WRITE_TOOL, BASH_TOOL];\n"],"mappings":"uGASA,MAEM,EAAY,OAwClB,SAAS,EAAY,EAAgB,EAAiC,CACpE,GAAI,CAAC,GAAS,OAAO,GAAU,SAAU,OACzC,IAAM,EAAS,EAAkC,GACjD,OAAO,OAAO,GAAU,SAAW,EAAQ,IAAA,EAC7C,CAqBA,IAAa,EAAb,KAAiD,CA+B5B,SACA,UACA,UAhCnB,QAA2B,IAAI,IAE/B,UAA6B,IAAI,IAMjC,SAMA,SAAsC,CAAC,EAMvC,UAKA,SAA4B,IAAI,IAChC,IACA,IAEA,YACE,EACA,EACA,EACA,EAA8B,CAAC,EAC/B,CAJiB,KAAA,SAAA,EACA,KAAA,UAAA,EACA,KAAA,UAAA,EAGjB,KAAK,IAAM,EAAQ,KAAO,KAAK,IAC/B,KAAK,IAAM,EAAQ,GACrB,CAMA,MAAM,EAAsF,CAAC,EAAS,CACpG,KAAK,QAAQ,MAAM,EACnB,KAAK,UAAU,MAAM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AAA,IAAa,IAAc,IAAA,GAAW,MAAO,CAAC,EACjE,IAAM,EAAO,EAAS,EAAY,CAAS,EAC3C,MAAO,CAAE,UAAW,EAAK,UAAW,SAAU,EAAK,QAAS,CAC9D,CAGA,MAAc,OAAO,EAAqC,EACpD,EAAM,SAAW,IAAA,IAAa,EAAM,SAAW,EAAM,QACzD,MAAM,KAAK,SAAS,OAAO,CAAK,CAClC,CAUA,MAAc,SAAS,EAAiC,CACtD,GAAI,KAAK,WAAa,IAAA,GAAW,OACjC,IAAM,EAAU,IAAI,IAAI,KAAK,SAAS,OAAO,EACvC,EAAc,MAAM,KAAK,UAAU,YAAY,CAAQ,EACzD,IAAgB,IAAA,GAAW,EAAQ,OAAO,CAAQ,EACjD,EAAQ,IAAI,EAAU,CAAW,EACtC,KAAK,SAAW,CAAE,UAAS,UAAW,KAAK,SAAS,SAAU,CAChE,CACF"}
@@ -0,0 +1,2 @@
1
+ const e=require("../../_virtual/_rolldown/runtime.cjs");let t=require("node:path");t=e.__toESM(t,1);let n=require("node:fs/promises");n=e.__toESM(n,1);let r=require("node:os");r=e.__toESM(r,1);let i=require("@agimon-ai/doompi-config");const a=/^\s*command:\s*(.+?)\s*$/mu;function o(){return process.env.PI_CODING_AGENT_DIR||t.default.join(r.default.homedir(),`.pi`,`agent`)}var s=class{path(){return(0,i.globalDoomConfigPath)()}packagePath(){return t.default.join(o(),`doom-file-edit`,`config.yaml`)}async command(){return await this.read(this.path())??await this.read(this.packagePath())}async read(e){try{let t=await n.default.readFile(e,`utf8`),r=/^editor:\s*\n((?:[ \t]+.*(?:\n|$))*)/mu.exec(t)?.[1];if(!r)return;let i=a.exec(r)?.[1]?.trim();if(!i)return;if(/^(?:[-+]?\d+(?:\.\d+)?|true|false|null)$/u.test(i))throw Error(`${e}: editor.command must be a string`);return i.replace(/^(?:"([\s\S]*)"|'([\s\S]*)')$/u,`$1$2`)}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return;throw e}}};exports.EditorConfigService=s;
2
+ //# sourceMappingURL=EditorConfigService.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"EditorConfigService.cjs","names":["path","os","globalDoomConfigPath","fs"],"sources":["../../../src/adapters/EditorConfigService/EditorConfigService.ts"],"sourcesContent":["import fs from 'node:fs/promises';\nimport os from 'node:os';\nimport path from 'node:path';\nimport { globalDoomConfigPath } from '@agimon-ai/doompi-config';\nimport type { IEditorConfigService } from '../../types/editorConfigService';\n\nconst commandPattern = /^\\s*command:\\s*(.+?)\\s*$/mu;\n\nfunction agentDirectory(): string {\n return process.env.PI_CODING_AGENT_DIR || path.join(os.homedir(), '.pi', 'agent');\n}\n\nexport class EditorConfigService implements IEditorConfigService {\n path(): string {\n return globalDoomConfigPath();\n }\n\n packagePath(): string {\n return path.join(agentDirectory(), 'doom-file-edit', 'config.yaml');\n }\n\n async command(): Promise<string | undefined> {\n // Shared Doom config owns `editor:`; the package-scoped file is the\n // fallback for standalone installs that have no Doom config.\n return (await this.read(this.path())) ?? (await this.read(this.packagePath()));\n }\n\n private async read(filePath: string): Promise<string | undefined> {\n try {\n const content = await fs.readFile(filePath, 'utf8');\n const editorSection = /^editor:\\s*\\n((?:[ \\t]+.*(?:\\n|$))*)/mu.exec(content)?.[1];\n if (!editorSection) return undefined;\n const value = commandPattern.exec(editorSection)?.[1]?.trim();\n if (!value) return undefined;\n if (/^(?:[-+]?\\d+(?:\\.\\d+)?|true|false|null)$/u.test(value)) {\n throw new Error(`${filePath}: editor.command must be a string`);\n }\n return value.replace(/^(?:\"([\\s\\S]*)\"|'([\\s\\S]*)')$/u, '$1$2');\n } catch (error) {\n if (error instanceof Error && 'code' in error && error.code === 'ENOENT') return undefined;\n throw error;\n }\n }\n}\n"],"mappings":"2OAMA,MAAM,EAAiB,6BAEvB,SAAS,GAAyB,CAChC,OAAO,QAAQ,IAAI,qBAAuBA,EAAAA,QAAK,KAAKC,EAAAA,QAAG,QAAQ,EAAG,MAAO,OAAO,CAClF,CAEA,IAAa,EAAb,KAAiE,CAC/D,MAAe,CACb,OAAA,EAAOC,EAAAA,qBAAAA,CAAqB,CAC9B,CAEA,aAAsB,CACpB,OAAOF,EAAAA,QAAK,KAAK,EAAe,EAAG,iBAAkB,aAAa,CACpE,CAEA,MAAM,SAAuC,CAG3C,OAAQ,MAAM,KAAK,KAAK,KAAK,KAAK,CAAC,GAAO,MAAM,KAAK,KAAK,KAAK,YAAY,CAAC,CAC9E,CAEA,MAAc,KAAK,EAA+C,CAChE,GAAI,CACF,IAAM,EAAU,MAAMG,EAAAA,QAAG,SAAS,EAAU,MAAM,EAC5C,EAAgB,yCAAyC,KAAK,CAAO,CAAC,GAAG,GAC/E,GAAI,CAAC,EAAe,OACpB,IAAM,EAAQ,EAAe,KAAK,CAAa,CAAC,GAAG,EAAE,EAAE,KAAK,EAC5D,GAAI,CAAC,EAAO,OACZ,GAAI,4CAA4C,KAAK,CAAK,EACxD,MAAU,MAAM,GAAG,EAAS,kCAAkC,EAEhE,OAAO,EAAM,QAAQ,iCAAkC,MAAM,CAC/D,OAAS,EAAO,CACd,GAAI,aAAiB,OAAS,SAAU,GAAS,EAAM,OAAS,SAAU,OAC1E,MAAM,CACR,CACF,CACF"}
@@ -0,0 +1,2 @@
1
+ import e from"node:path";import t from"node:fs/promises";import n from"node:os";import{globalDoomConfigPath as r}from"@agimon-ai/doompi-config";const i=/^\s*command:\s*(.+?)\s*$/mu;function a(){return process.env.PI_CODING_AGENT_DIR||e.join(n.homedir(),`.pi`,`agent`)}var o=class{path(){return r()}packagePath(){return e.join(a(),`doom-file-edit`,`config.yaml`)}async command(){return await this.read(this.path())??await this.read(this.packagePath())}async read(e){try{let n=await t.readFile(e,`utf8`),r=/^editor:\s*\n((?:[ \t]+.*(?:\n|$))*)/mu.exec(n)?.[1];if(!r)return;let a=i.exec(r)?.[1]?.trim();if(!a)return;if(/^(?:[-+]?\d+(?:\.\d+)?|true|false|null)$/u.test(a))throw Error(`${e}: editor.command must be a string`);return a.replace(/^(?:"([\s\S]*)"|'([\s\S]*)')$/u,`$1$2`)}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return;throw e}}};export{o as EditorConfigService};
2
+ //# sourceMappingURL=EditorConfigService.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"EditorConfigService.mjs","names":[],"sources":["../../../src/adapters/EditorConfigService/EditorConfigService.ts"],"sourcesContent":["import fs from 'node:fs/promises';\nimport os from 'node:os';\nimport path from 'node:path';\nimport { globalDoomConfigPath } from '@agimon-ai/doompi-config';\nimport type { IEditorConfigService } from '../../types/editorConfigService';\n\nconst commandPattern = /^\\s*command:\\s*(.+?)\\s*$/mu;\n\nfunction agentDirectory(): string {\n return process.env.PI_CODING_AGENT_DIR || path.join(os.homedir(), '.pi', 'agent');\n}\n\nexport class EditorConfigService implements IEditorConfigService {\n path(): string {\n return globalDoomConfigPath();\n }\n\n packagePath(): string {\n return path.join(agentDirectory(), 'doom-file-edit', 'config.yaml');\n }\n\n async command(): Promise<string | undefined> {\n // Shared Doom config owns `editor:`; the package-scoped file is the\n // fallback for standalone installs that have no Doom config.\n return (await this.read(this.path())) ?? (await this.read(this.packagePath()));\n }\n\n private async read(filePath: string): Promise<string | undefined> {\n try {\n const content = await fs.readFile(filePath, 'utf8');\n const editorSection = /^editor:\\s*\\n((?:[ \\t]+.*(?:\\n|$))*)/mu.exec(content)?.[1];\n if (!editorSection) return undefined;\n const value = commandPattern.exec(editorSection)?.[1]?.trim();\n if (!value) return undefined;\n if (/^(?:[-+]?\\d+(?:\\.\\d+)?|true|false|null)$/u.test(value)) {\n throw new Error(`${filePath}: editor.command must be a string`);\n }\n return value.replace(/^(?:\"([\\s\\S]*)\"|'([\\s\\S]*)')$/u, '$1$2');\n } catch (error) {\n if (error instanceof Error && 'code' in error && error.code === 'ENOENT') return undefined;\n throw error;\n }\n }\n}\n"],"mappings":"gJAMA,MAAM,EAAiB,6BAEvB,SAAS,GAAyB,CAChC,OAAO,QAAQ,IAAI,qBAAuB,EAAK,KAAK,EAAG,QAAQ,EAAG,MAAO,OAAO,CAClF,CAEA,IAAa,EAAb,KAAiE,CAC/D,MAAe,CACb,OAAO,EAAqB,CAC9B,CAEA,aAAsB,CACpB,OAAO,EAAK,KAAK,EAAe,EAAG,iBAAkB,aAAa,CACpE,CAEA,MAAM,SAAuC,CAG3C,OAAQ,MAAM,KAAK,KAAK,KAAK,KAAK,CAAC,GAAO,MAAM,KAAK,KAAK,KAAK,YAAY,CAAC,CAC9E,CAEA,MAAc,KAAK,EAA+C,CAChE,GAAI,CACF,IAAM,EAAU,MAAM,EAAG,SAAS,EAAU,MAAM,EAC5C,EAAgB,yCAAyC,KAAK,CAAO,CAAC,GAAG,GAC/E,GAAI,CAAC,EAAe,OACpB,IAAM,EAAQ,EAAe,KAAK,CAAa,CAAC,GAAG,EAAE,EAAE,KAAK,EAC5D,GAAI,CAAC,EAAO,OACZ,GAAI,4CAA4C,KAAK,CAAK,EACxD,MAAU,MAAM,GAAG,EAAS,kCAAkC,EAEhE,OAAO,EAAM,QAAQ,iCAAkC,MAAM,CAC/D,OAAS,EAAO,CACd,GAAI,aAAiB,OAAS,SAAU,GAAS,EAAM,OAAS,SAAU,OAC1E,MAAM,CACR,CACF,CACF"}
@@ -0,0 +1,2 @@
1
+ const e=require("../../_virtual/_rolldown/runtime.cjs"),t=require("../process/commandLine.cjs");let n=require("node:path");n=e.__toESM(n,1);let r=require("node:fs/promises");r=e.__toESM(r,1);let i=require("cross-spawn");i=e.__toESM(i,1);var a=class{config;constructor(e){this.config=e}async resolve(e=process.env,n=process.platform){let r=await this.config.command(),i=[...r?[{template:r,source:`configured`}]:[],...e.VISUAL?[{template:e.VISUAL,source:`VISUAL`}]:[],...e.EDITOR?[{template:e.EDITOR,source:`EDITOR`}]:[],{template:n===`win32`?`notepad {file}`:`nano {file}`,source:`fallback`}];for(let r of i){let i=t.splitCommandLine(r.template)[0];if(i&&await this.isExecutable(i,e,n))return r}}async launch(e,n,r){try{let a=await this.resolve();if(!a)return{success:!1,error:`No editor command could be resolved`};let[o,...s]=t.expandEditorTemplate(a.template,e,n);if(!o)return{success:!1,error:`Editor command must not be empty`};r.stop();try{await new Promise((e,t)=>{let n=(0,i.default)(o,s,{stdio:`inherit`,shell:!1});n.once(`error`,t),n.once(`exit`,()=>e())})}finally{r.start(),r.requestRender(!0)}return{success:!0}}catch(e){return{success:!1,error:e instanceof Error?e.message:String(e)}}}async isExecutable(e,t,i){let a=i===`win32`?(t.PATHEXT??`.EXE;.CMD;.BAT`).split(`;`):[``],o=n.default.isAbsolute(e)||e.includes(n.default.sep)?[``]:(t.PATH??``).split(n.default.delimiter);for(let t of o)for(let o of a){let a=t?n.default.join(t,`${e}${o}`):`${e}${o}`;try{return await r.default.access(a,i===`win32`?r.default.constants.F_OK:r.default.constants.X_OK),!0}catch(e){if(!(e instanceof Error&&`code`in e&&(e.code===`ENOENT`||e.code===`EACCES`)))throw e}}return!1}};exports.EditorLauncher=a;
2
+ //# sourceMappingURL=EditorLauncher.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"EditorLauncher.cjs","names":["splitCommandLine","expandEditorTemplate","spawn","path","fs"],"sources":["../../../src/adapters/EditorLauncher/EditorLauncher.ts"],"sourcesContent":["import fs from 'node:fs/promises';\nimport path from 'node:path';\nimport spawn from 'cross-spawn';\nimport { expandEditorTemplate, splitCommandLine } from '../../adapters/process/commandLine.ts';\nimport type { IEditorConfigService } from '../../types/editorConfigService';\nimport type { ResolvedEditor } from '../../types/domain';\nimport type { EditorLaunchResult, EditorTui, IEditorLauncher } from '../../types/editorLauncher';\n\nexport class EditorLauncher implements IEditorLauncher {\n constructor(private readonly config: IEditorConfigService) {}\n\n async resolve(\n env: NodeJS.ProcessEnv = process.env,\n platform: NodeJS.Platform = process.platform,\n ): Promise<ResolvedEditor | undefined> {\n const configured = await this.config.command();\n const candidates: ResolvedEditor[] = [\n ...(configured ? [{ template: configured, source: 'configured' as const }] : []),\n ...(env.VISUAL ? [{ template: env.VISUAL, source: 'VISUAL' as const }] : []),\n ...(env.EDITOR ? [{ template: env.EDITOR, source: 'EDITOR' as const }] : []),\n { template: platform === 'win32' ? 'notepad {file}' : 'nano {file}', source: 'fallback' },\n ];\n for (const candidate of candidates) {\n const executable = splitCommandLine(candidate.template)[0];\n if (executable && (await this.isExecutable(executable, env, platform))) return candidate;\n }\n return undefined;\n }\n\n async launch(filePath: string, line: number, tui: EditorTui): Promise<EditorLaunchResult> {\n try {\n const editor = await this.resolve();\n if (!editor) return { success: false, error: 'No editor command could be resolved' };\n const [command, ...args] = expandEditorTemplate(editor.template, filePath, line);\n if (!command) return { success: false, error: 'Editor command must not be empty' };\n tui.stop();\n try {\n await new Promise<void>((resolve, reject) => {\n const child = spawn(command, args, { stdio: 'inherit', shell: false });\n child.once('error', reject);\n child.once('exit', () => resolve());\n });\n } finally {\n tui.start();\n tui.requestRender(true);\n }\n return { success: true };\n } catch (error) {\n return { success: false, error: error instanceof Error ? error.message : String(error) };\n }\n }\n\n private async isExecutable(command: string, env: NodeJS.ProcessEnv, platform: NodeJS.Platform): Promise<boolean> {\n const extensions = platform === 'win32' ? (env.PATHEXT ?? '.EXE;.CMD;.BAT').split(';') : [''];\n const locations =\n path.isAbsolute(command) || command.includes(path.sep) ? [''] : (env.PATH ?? '').split(path.delimiter);\n for (const location of locations) {\n for (const extension of extensions) {\n const candidate = location ? path.join(location, `${command}${extension}`) : `${command}${extension}`;\n try {\n await fs.access(candidate, platform === 'win32' ? fs.constants.F_OK : fs.constants.X_OK);\n return true;\n } catch (error) {\n if (!(error instanceof Error && 'code' in error && (error.code === 'ENOENT' || error.code === 'EACCES')))\n throw error;\n }\n }\n }\n return false;\n }\n}\n"],"mappings":"6OAQA,IAAa,EAAb,KAAuD,CACxB,OAA7B,YAAY,EAA+C,CAA9B,KAAA,OAAA,CAA+B,CAE5D,MAAM,QACJ,EAAyB,QAAQ,IACjC,EAA4B,QAAQ,SACC,CACrC,IAAM,EAAa,MAAM,KAAK,OAAO,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CAEA,MAAc,aAAa,EAAiB,EAAwB,EAA6C,CAC/G,IAAM,EAAa,IAAa,SAAW,EAAI,SAAW,iBAAA,CAAkB,MAAM,GAAG,EAAI,CAAC,EAAE,EACtF,EACJC,EAAAA,QAAK,WAAW,CAAO,GAAK,EAAQ,SAASA,EAAAA,QAAK,GAAG,EAAI,CAAC,EAAE,GAAK,EAAI,MAAQ,GAAA,CAAI,MAAMA,EAAAA,QAAK,SAAS,EACvG,IAAK,IAAM,KAAY,EACrB,IAAK,IAAM,KAAa,EAAY,CAClC,IAAM,EAAY,EAAWA,EAAAA,QAAK,KAAK,EAAU,GAAG,IAAU,GAAW,EAAI,GAAG,IAAU,IAC1F,GAAI,CAEF,OADA,MAAMC,EAAAA,QAAG,OAAO,EAAW,IAAa,QAAUA,EAAAA,QAAG,UAAU,KAAOA,EAAAA,QAAG,UAAU,IAAI,EAChF,EACT,OAAS,EAAO,CACd,GAAI,EAAE,aAAiB,OAAS,SAAU,IAAU,EAAM,OAAS,UAAY,EAAM,OAAS,WAC5F,MAAM,CACV,CACF,CAEF,MAAO,EACT,CACF"}
@@ -0,0 +1,2 @@
1
+ import{expandEditorTemplate as e,splitCommandLine as t}from"../process/commandLine.mjs";import n from"node:path";import r from"node:fs/promises";import i from"cross-spawn";var a=class{config;constructor(e){this.config=e}async resolve(e=process.env,n=process.platform){let r=await this.config.command(),i=[...r?[{template:r,source:`configured`}]:[],...e.VISUAL?[{template:e.VISUAL,source:`VISUAL`}]:[],...e.EDITOR?[{template:e.EDITOR,source:`EDITOR`}]:[],{template:n===`win32`?`notepad {file}`:`nano {file}`,source:`fallback`}];for(let r of i){let i=t(r.template)[0];if(i&&await this.isExecutable(i,e,n))return r}}async launch(t,n,r){try{let a=await this.resolve();if(!a)return{success:!1,error:`No editor command could be resolved`};let[o,...s]=e(a.template,t,n);if(!o)return{success:!1,error:`Editor command must not be empty`};r.stop();try{await new Promise((e,t)=>{let n=i(o,s,{stdio:`inherit`,shell:!1});n.once(`error`,t),n.once(`exit`,()=>e())})}finally{r.start(),r.requestRender(!0)}return{success:!0}}catch(e){return{success:!1,error:e instanceof Error?e.message:String(e)}}}async isExecutable(e,t,i){let a=i===`win32`?(t.PATHEXT??`.EXE;.CMD;.BAT`).split(`;`):[``],o=n.isAbsolute(e)||e.includes(n.sep)?[``]:(t.PATH??``).split(n.delimiter);for(let t of o)for(let o of a){let a=t?n.join(t,`${e}${o}`):`${e}${o}`;try{return await r.access(a,i===`win32`?r.constants.F_OK:r.constants.X_OK),!0}catch(e){if(!(e instanceof Error&&`code`in e&&(e.code===`ENOENT`||e.code===`EACCES`)))throw e}}return!1}};export{a as EditorLauncher};
2
+ //# sourceMappingURL=EditorLauncher.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"EditorLauncher.mjs","names":[],"sources":["../../../src/adapters/EditorLauncher/EditorLauncher.ts"],"sourcesContent":["import fs from 'node:fs/promises';\nimport path from 'node:path';\nimport spawn from 'cross-spawn';\nimport { expandEditorTemplate, splitCommandLine } from '../../adapters/process/commandLine.ts';\nimport type { IEditorConfigService } from '../../types/editorConfigService';\nimport type { ResolvedEditor } from '../../types/domain';\nimport type { EditorLaunchResult, EditorTui, IEditorLauncher } from '../../types/editorLauncher';\n\nexport class EditorLauncher implements IEditorLauncher {\n constructor(private readonly config: IEditorConfigService) {}\n\n async resolve(\n env: NodeJS.ProcessEnv = process.env,\n platform: NodeJS.Platform = process.platform,\n ): Promise<ResolvedEditor | undefined> {\n const configured = await this.config.command();\n const candidates: ResolvedEditor[] = [\n ...(configured ? [{ template: configured, source: 'configured' as const }] : []),\n ...(env.VISUAL ? [{ template: env.VISUAL, source: 'VISUAL' as const }] : []),\n ...(env.EDITOR ? [{ template: env.EDITOR, source: 'EDITOR' as const }] : []),\n { template: platform === 'win32' ? 'notepad {file}' : 'nano {file}', source: 'fallback' },\n ];\n for (const candidate of candidates) {\n const executable = splitCommandLine(candidate.template)[0];\n if (executable && (await this.isExecutable(executable, env, platform))) return candidate;\n }\n return undefined;\n }\n\n async launch(filePath: string, line: number, tui: EditorTui): Promise<EditorLaunchResult> {\n try {\n const editor = await this.resolve();\n if (!editor) return { success: false, error: 'No editor command could be resolved' };\n const [command, ...args] = expandEditorTemplate(editor.template, filePath, line);\n if (!command) return { success: false, error: 'Editor command must not be empty' };\n tui.stop();\n try {\n await new Promise<void>((resolve, reject) => {\n const child = spawn(command, args, { stdio: 'inherit', shell: false });\n child.once('error', reject);\n child.once('exit', () => resolve());\n });\n } finally {\n tui.start();\n tui.requestRender(true);\n }\n return { success: true };\n } catch (error) {\n return { success: false, error: error instanceof Error ? error.message : String(error) };\n }\n }\n\n private async isExecutable(command: string, env: NodeJS.ProcessEnv, platform: NodeJS.Platform): Promise<boolean> {\n const extensions = platform === 'win32' ? (env.PATHEXT ?? '.EXE;.CMD;.BAT').split(';') : [''];\n const locations =\n path.isAbsolute(command) || command.includes(path.sep) ? [''] : (env.PATH ?? '').split(path.delimiter);\n for (const location of locations) {\n for (const extension of extensions) {\n const candidate = location ? path.join(location, `${command}${extension}`) : `${command}${extension}`;\n try {\n await fs.access(candidate, platform === 'win32' ? fs.constants.F_OK : fs.constants.X_OK);\n return true;\n } catch (error) {\n if (!(error instanceof Error && 'code' in error && (error.code === 'ENOENT' || error.code === 'EACCES')))\n throw error;\n }\n }\n }\n return false;\n }\n}\n"],"mappings":"4KAQA,IAAa,EAAb,KAAuD,CACxB,OAA7B,YAAY,EAA+C,CAA9B,KAAA,OAAA,CAA+B,CAE5D,MAAM,QACJ,EAAyB,QAAQ,IACjC,EAA4B,QAAQ,SACC,CACrC,IAAM,EAAa,MAAM,KAAK,OAAO,QAAQ,EACvC,EAA+B,CACnC,GAAI,EAAa,CAAC,CAAE,SAAU,EAAY,OAAQ,YAAsB,CAAC,EAAI,CAAC,EAC9E,GAAI,EAAI,OAAS,CAAC,CAAE,SAAU,EAAI,OAAQ,OAAQ,QAAkB,CAAC,EAAI,CAAC,EAC1E,GAAI,EAAI,OAAS,CAAC,CAAE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vG,IAAK,IAAM,KAAY,EACrB,IAAK,IAAM,KAAa,EAAY,CAClC,IAAM,EAAY,EAAW,EAAK,KAAK,EAAU,GAAG,IAAU,GAAW,EAAI,GAAG,IAAU,IAC1F,GAAI,CAEF,OADA,MAAM,EAAG,OAAO,EAAW,IAAa,QAAU,EAAG,UAAU,KAAO,EAAG,UAAU,IAAI,EAChF,EACT,OAAS,EAAO,CACd,GAAI,EAAE,aAAiB,OAAS,SAAU,IAAU,EAAM,OAAS,UAAY,EAAM,OAAS,WAC5F,MAAM,CACV,CACF,CAEF,MAAO,EACT,CACF"}
@@ -0,0 +1,2 @@
1
+ const e=require("../../_virtual/_rolldown/runtime.cjs");let t=require("node:fs");t=e.__toESM(t,1);let n=require("node:path");n=e.__toESM(n,1);let r=require("@agimon-ai/doompi-extension-contracts/child-process"),i=require("node:os");i=e.__toESM(i,1);let a=require("node:child_process"),o=require("node:crypto");const s=`doom-file-edit`,c=[`.pi`,`agent`];function l(e){return(0,o.createHash)(`sha256`).update(e).digest(`hex`).slice(0,16)}var u=class{sessionKey(e,t=process.env){if(t[r.SUBAGENT_CHILD_ENV]){let e=t[r.SUBAGENT_PARENT_SESSION_ENV];if(e)return e}return e}stateDirectory(){let e=process.env.PI_CODING_AGENT_DIR?.trim(),t=e===void 0||e===``?n.default.join(i.default.homedir(),...c):e;return n.default.join(t,s)}timelinePath(e,r){let i=this.stateDirectory();return t.default.mkdirSync(i,{recursive:!0}),n.default.join(i,`${l(t.default.realpathSync(e))}-${l(r)}.jsonl`)}snapshotsPath(e,t){return`${this.timelinePath(e,t).replace(/\.jsonl$/u,``)}.blobs`}legacyStateDirectory(e){let t=this.gitCommonDirectory(e);return t===void 0?void 0:n.default.join(t,s)}gitCommonDirectory(e){try{return(0,a.execFileSync)(`git`,[`rev-parse`,`--path-format=absolute`,`--git-common-dir`],{cwd:e,encoding:`utf8`,stdio:[`ignore`,`pipe`,`ignore`]}).trim()||void 0}catch(e){if(e instanceof Error)return;throw e}}};exports.FileEditPaths=u;
2
+ //# sourceMappingURL=FileEditPaths.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"FileEditPaths.cjs","names":["createHash","SUBAGENT_CHILD_ENV","SUBAGENT_PARENT_SESSION_ENV","path","os","fs","execFileSync"],"sources":["../../../src/adapters/FileEditPaths/FileEditPaths.ts"],"sourcesContent":["import { execFileSync } from 'node:child_process';\nimport { createHash } from 'node:crypto';\nimport fs from 'node:fs';\nimport os from 'node:os';\nimport path from 'node:path';\nimport { SUBAGENT_CHILD_ENV, SUBAGENT_PARENT_SESSION_ENV } from '@agimon-ai/doompi-extension-contracts/child-process';\nimport type { IFileEditPaths } from '../../types/fileEditPaths';\n\n/** The directory this package owns, under whichever root holds agent state. */\nconst STATE_DIRECTORY = 'doom-file-edit';\nconst AGENT_DIRECTORY = ['.pi', 'agent'];\n\nfunction hash(value: string): string {\n return createHash('sha256').update(value).digest('hex').slice(0, 16);\n}\n\nexport class FileEditPaths implements IFileEditPaths {\n sessionKey(sessionId: string, env: NodeJS.ProcessEnv = process.env): string {\n if (env[SUBAGENT_CHILD_ENV]) {\n const parent = env[SUBAGENT_PARENT_SESSION_ENV];\n if (parent) return parent;\n }\n return sessionId;\n }\n\n /**\n * Where every session's state lives: the Pi agent directory, the same root\n * every other Doom package writes to, and never inside the working tree.\n *\n * An earlier layout put this in the repository's git common directory. That\n * is git's own storage: nothing in git's lifecycle prunes a directory we add\n * to it, a linked worktree writes into the main checkout rather than its own,\n * a submodule writes inside `.git/modules`, and `PI_CODING_AGENT_DIR` was\n * ignored outright. The snapshots are verbatim copies of files the session\n * touched, so where they land is a question about handling content, not a\n * question about convenience.\n */\n stateDirectory(): string {\n const configured = process.env.PI_CODING_AGENT_DIR?.trim();\n const root =\n configured === undefined || configured === '' ? path.join(os.homedir(), ...AGENT_DIRECTORY) : configured;\n return path.join(root, STATE_DIRECTORY);\n }\n\n /**\n * One session's timeline, named from its working directory and its session so\n * the hub and the session API can find it from another process knowing only\n * those two things.\n */\n timelinePath(cwd: string, sessionKey: string): string {\n const directory = this.stateDirectory();\n fs.mkdirSync(directory, { recursive: true });\n return path.join(directory, `${hash(fs.realpathSync(cwd))}-${hash(sessionKey)}.jsonl`);\n }\n\n /**\n * Where this session's content snapshots live: beside its timeline and named\n * after it, so the two are found together and cleared together.\n */\n snapshotsPath(cwd: string, sessionKey: string): string {\n return `${this.timelinePath(cwd, sessionKey).replace(/\\.jsonl$/u, '')}.blobs`;\n }\n\n legacyStateDirectory(cwd: string): string | undefined {\n const common = this.gitCommonDirectory(cwd);\n return common === undefined ? undefined : path.join(common, STATE_DIRECTORY);\n }\n\n /** Only still read so the state an older build left behind can be cleared away. */\n private gitCommonDirectory(cwd: string): string | undefined {\n try {\n const result = execFileSync('git', ['rev-parse', '--path-format=absolute', '--git-common-dir'], {\n cwd,\n encoding: 'utf8',\n stdio: ['ignore', 'pipe', 'ignore'],\n }).trim();\n return result || undefined;\n } catch (error) {\n if (error instanceof Error) return undefined;\n throw error;\n }\n }\n}\n"],"mappings":"sTASA,MAAM,EAAkB,iBAClB,EAAkB,CAAC,MAAO,OAAO,EAEvC,SAAS,EAAK,EAAuB,CACnC,OAAA,EAAOA,EAAAA,WAAAA,CAAW,QAAQ,CAAC,CAAC,OAAO,CAAK,CAAC,CAAC,OAAO,KAAK,CAAC,CAAC,MAAM,EAAG,EAAE,CACrE,CAEA,IAAa,EAAb,KAAqD,CACnD,WAAW,EAAmB,EAAyB,QAAQ,IAAa,CAC1E,GAAI,EAAIC,EAAAA,oBAAqB,CAC3B,IAAM,EAAS,EAAIC,EAAAA,6BACnB,GAAI,EAAQ,OAAO,CACrB,CACA,OAAO,CACT,CAcA,gBAAyB,CACvB,IAAM,EAAa,QAAQ,IAAI,qBAAqB,KAAK,EACnD,EACJ,IAAe,IAAA,IAAa,IAAe,GAAKC,EAAAA,QAAK,KAAKC,EAAAA,QAAG,QAAQ,EAAG,GAAG,CAAe,EAAI,EAChG,OAAOD,EAAAA,QAAK,KAAK,EAAM,CAAe,CACxC,CAOA,aAAa,EAAa,EAA4B,CACpD,IAAM,EAAY,KAAK,eAAe,EAEtC,OADA,EAAA,QAAG,UAAU,EAAW,CAAE,UAAW,EAAK,CAAC,EACpCA,EAAAA,QAAK,KAAK,EAAW,GAAG,EAAKE,EAAAA,QAAG,aAAa,CAAG,CAAC,EAAE,GAAG,EAAK,CAAU,EAAE,OAAO,CACvF,CAMA,cAAc,EAAa,EAA4B,CACrD,MAAO,GAAG,KAAK,aAAa,EAAK,CAAU,CAAC,CAAC,QAAQ,YAAa,EAAE,EAAE,OACxE,CAEA,qBAAqB,EAAiC,CACpD,IAAM,EAAS,KAAK,mBAAmB,CAAG,EAC1C,OAAO,IAAW,IAAA,GAAY,IAAA,GAAYF,EAAAA,QAAK,KAAK,EAAQ,CAAe,CAC7E,CAGA,mBAA2B,EAAiC,CAC1D,GAAI,CAMF,OAAA,EALeG,EAAAA,aAAAA,CAAa,MAAO,CAAC,YAAa,yBAA0B,kBAAkB,EAAG,CAC9F,MACA,SAAU,OACV,MAAO,CAAC,SAAU,OAAQ,QAAQ,CACpC,CAAC,CAAC,CAAC,KACS,GAAK,IAAA,EACnB,OAAS,EAAO,CACd,GAAI,aAAiB,MAAO,OAC5B,MAAM,CACR,CACF,CACF"}
@@ -0,0 +1,2 @@
1
+ import e from"node:fs";import t from"node:path";import{SUBAGENT_CHILD_ENV as n,SUBAGENT_PARENT_SESSION_ENV as r}from"@agimon-ai/doompi-extension-contracts/child-process";import i from"node:os";import{execFileSync as a}from"node:child_process";import{createHash as o}from"node:crypto";const s=`doom-file-edit`,c=[`.pi`,`agent`];function l(e){return o(`sha256`).update(e).digest(`hex`).slice(0,16)}var u=class{sessionKey(e,t=process.env){if(t[n]){let e=t[r];if(e)return e}return e}stateDirectory(){let e=process.env.PI_CODING_AGENT_DIR?.trim(),n=e===void 0||e===``?t.join(i.homedir(),...c):e;return t.join(n,s)}timelinePath(n,r){let i=this.stateDirectory();return e.mkdirSync(i,{recursive:!0}),t.join(i,`${l(e.realpathSync(n))}-${l(r)}.jsonl`)}snapshotsPath(e,t){return`${this.timelinePath(e,t).replace(/\.jsonl$/u,``)}.blobs`}legacyStateDirectory(e){let n=this.gitCommonDirectory(e);return n===void 0?void 0:t.join(n,s)}gitCommonDirectory(e){try{return a(`git`,[`rev-parse`,`--path-format=absolute`,`--git-common-dir`],{cwd:e,encoding:`utf8`,stdio:[`ignore`,`pipe`,`ignore`]}).trim()||void 0}catch(e){if(e instanceof Error)return;throw e}}};export{u as FileEditPaths};
2
+ //# sourceMappingURL=FileEditPaths.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"FileEditPaths.mjs","names":[],"sources":["../../../src/adapters/FileEditPaths/FileEditPaths.ts"],"sourcesContent":["import { execFileSync } from 'node:child_process';\nimport { createHash } from 'node:crypto';\nimport fs from 'node:fs';\nimport os from 'node:os';\nimport path from 'node:path';\nimport { SUBAGENT_CHILD_ENV, SUBAGENT_PARENT_SESSION_ENV } from '@agimon-ai/doompi-extension-contracts/child-process';\nimport type { IFileEditPaths } from '../../types/fileEditPaths';\n\n/** The directory this package owns, under whichever root holds agent state. */\nconst STATE_DIRECTORY = 'doom-file-edit';\nconst AGENT_DIRECTORY = ['.pi', 'agent'];\n\nfunction hash(value: string): string {\n return createHash('sha256').update(value).digest('hex').slice(0, 16);\n}\n\nexport class FileEditPaths implements IFileEditPaths {\n sessionKey(sessionId: string, env: NodeJS.ProcessEnv = process.env): string {\n if (env[SUBAGENT_CHILD_ENV]) {\n const parent = env[SUBAGENT_PARENT_SESSION_ENV];\n if (parent) return parent;\n }\n return sessionId;\n }\n\n /**\n * Where every session's state lives: the Pi agent directory, the same root\n * every other Doom package writes to, and never inside the working tree.\n *\n * An earlier layout put this in the repository's git common directory. That\n * is git's own storage: nothing in git's lifecycle prunes a directory we add\n * to it, a linked worktree writes into the main checkout rather than its own,\n * a submodule writes inside `.git/modules`, and `PI_CODING_AGENT_DIR` was\n * ignored outright. The snapshots are verbatim copies of files the session\n * touched, so where they land is a question about handling content, not a\n * question about convenience.\n */\n stateDirectory(): string {\n const configured = process.env.PI_CODING_AGENT_DIR?.trim();\n const root =\n configured === undefined || configured === '' ? path.join(os.homedir(), ...AGENT_DIRECTORY) : configured;\n return path.join(root, STATE_DIRECTORY);\n }\n\n /**\n * One session's timeline, named from its working directory and its session so\n * the hub and the session API can find it from another process knowing only\n * those two things.\n */\n timelinePath(cwd: string, sessionKey: string): string {\n const directory = this.stateDirectory();\n fs.mkdirSync(directory, { recursive: true });\n return path.join(directory, `${hash(fs.realpathSync(cwd))}-${hash(sessionKey)}.jsonl`);\n }\n\n /**\n * Where this session's content snapshots live: beside its timeline and named\n * after it, so the two are found together and cleared together.\n */\n snapshotsPath(cwd: string, sessionKey: string): string {\n return `${this.timelinePath(cwd, sessionKey).replace(/\\.jsonl$/u, '')}.blobs`;\n }\n\n legacyStateDirectory(cwd: string): string | undefined {\n const common = this.gitCommonDirectory(cwd);\n return common === undefined ? undefined : path.join(common, STATE_DIRECTORY);\n }\n\n /** Only still read so the state an older build left behind can be cleared away. */\n private gitCommonDirectory(cwd: string): string | undefined {\n try {\n const result = execFileSync('git', ['rev-parse', '--path-format=absolute', '--git-common-dir'], {\n cwd,\n encoding: 'utf8',\n stdio: ['ignore', 'pipe', 'ignore'],\n }).trim();\n return result || undefined;\n } catch (error) {\n if (error instanceof Error) return undefined;\n throw error;\n }\n }\n}\n"],"mappings":"4RASA,MAAM,EAAkB,iBAClB,EAAkB,CAAC,MAAO,OAAO,EAEvC,SAAS,EAAK,EAAuB,CACnC,OAAO,EAAW,QAAQ,CAAC,CAAC,OAAO,CAAK,CAAC,CAAC,OAAO,KAAK,CAAC,CAAC,MAAM,EAAG,EAAE,CACrE,CAEA,IAAa,EAAb,KAAqD,CACnD,WAAW,EAAmB,EAAyB,QAAQ,IAAa,CAC1E,GAAI,EAAI,GAAqB,CAC3B,IAAM,EAAS,EAAI,GACnB,GAAI,EAAQ,OAAO,CACrB,CACA,OAAO,CACT,CAcA,gBAAyB,CACvB,IAAM,EAAa,QAAQ,IAAI,qBAAqB,KAAK,EACnD,EACJ,IAAe,IAAA,IAAa,IAAe,GAAK,EAAK,KAAK,EAAG,QAAQ,EAAG,GAAG,CAAe,EAAI,EAChG,OAAO,EAAK,KAAK,EAAM,CAAe,CACxC,CAOA,aAAa,EAAa,EAA4B,CACpD,IAAM,EAAY,KAAK,eAAe,EAEtC,OADA,EAAG,UAAU,EAAW,CAAE,UAAW,EAAK,CAAC,EACpC,EAAK,KAAK,EAAW,GAAG,EAAK,EAAG,aAAa,CAAG,CAAC,EAAE,GAAG,EAAK,CAAU,EAAE,OAAO,CACvF,CAMA,cAAc,EAAa,EAA4B,CACrD,MAAO,GAAG,KAAK,aAAa,EAAK,CAAU,CAAC,CAAC,QAAQ,YAAa,EAAE,EAAE,OACxE,CAEA,qBAAqB,EAAiC,CACpD,IAAM,EAAS,KAAK,mBAAmB,CAAG,EAC1C,OAAO,IAAW,IAAA,GAAY,IAAA,GAAY,EAAK,KAAK,EAAQ,CAAe,CAC7E,CAGA,mBAA2B,EAAiC,CAC1D,GAAI,CAMF,OALe,EAAa,MAAO,CAAC,YAAa,yBAA0B,kBAAkB,EAAG,CAC9F,MACA,SAAU,OACV,MAAO,CAAC,SAAU,OAAQ,QAAQ,CACpC,CAAC,CAAC,CAAC,KACS,GAAK,IAAA,EACnB,OAAS,EAAO,CACd,GAAI,aAAiB,MAAO,OAC5B,MAAM,CACR,CACF,CACF"}
@@ -0,0 +1,5 @@
1
+ const e=require("../../_virtual/_rolldown/runtime.cjs");let t=require("node:path");t=e.__toESM(t,1);let n=require("node:fs/promises");n=e.__toESM(n,1);let r=require("node:child_process");const i=262144,a=8192;function o(e,t){let n=t||e.length>200,r=e.slice(0,200);return n&&r.push(`... diff truncated at 200 lines / ${i} bytes ...`),{lines:r,truncated:n}}function s(e,t,n,r){let s=r.byteLength>=i;if(r.subarray(0,a).includes(0))return{path:e,state:`binary`,lines:[`Binary file changed (${r.byteLength} bytes shown by git)`],additions:0,removals:0,tracked:n,truncated:s,suggestedLine:1};let c=o(r.subarray(0,i).toString(`utf8`).split(`
2
+ `),s),l=c.lines.filter(e=>e.startsWith(`+`)&&!e.startsWith(`+++`)).length,u=c.lines.filter(e=>e.startsWith(`-`)&&!e.startsWith(`---`)).length,d=c.lines.find(e=>e.startsWith(`@@`))?.match(/\+(\d+)/u);return{path:e,state:t,lines:c.lines,additions:l,removals:u,tracked:n,truncated:c.truncated,suggestedLine:Number(d?.[1]??1)}}var c=class{async diff(e,i){let a=t.default.resolve(e,i),o=t.default.relative(e,a),c=this.isTracked(e,o),l=!0;try{await n.default.access(a)}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)l=!1;else throw e}if(!c&&!l)return s(a,`deleted`,!1,Buffer.from(`File no longer exists`));if(!c)return this.fullAdd(a);let u=(0,r.spawnSync)(`git`,[`diff`,`--no-ext-diff`,`--no-color`,`--unified=3`,`HEAD`,`--`,o],{cwd:e,encoding:`buffer`,maxBuffer:262144}).stdout??Buffer.alloc(0);return l&&/^(Binary files .* differ|GIT binary patch)$/mu.test(u.toString(`utf8`))?{path:a,state:`binary`,lines:[`Binary tracked file changed`],additions:0,removals:0,tracked:!0,truncated:!1,suggestedLine:1}:s(a,l?u.length>0?`modified`:`unchanged`:`deleted`,!0,u)}isTracked(e,t){return(0,r.spawnSync)(`git`,[`ls-files`,`--error-unmatch`,`--`,t],{cwd:e,stdio:`ignore`}).status===0}async fullAdd(e){let r=await n.default.open(e,`r`);try{let n=Buffer.alloc(i),{bytesRead:o}=await r.read(n,0,n.length,0),c=n.subarray(0,o);if(c.subarray(0,a).includes(0))return s(e,`binary`,!1,Buffer.from(`Binary untracked file (${o}+ bytes)`));let l=c.toString(`utf8`).split(`
3
+ `).map(e=>`+${e}`).join(`
4
+ `),u=`--- /dev/null\n+++ b/${t.default.basename(e)}\n@@ -0,0 +1 @@\n`;return s(e,`added`,!1,Buffer.from(u+l))}finally{await r.close()}}};exports.GitDiffService=c,exports.MAX_DIFF_BYTES=i;
5
+ //# sourceMappingURL=GitDiffService.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"GitDiffService.cjs","names":["path","fs","spawnSync"],"sources":["../../../src/adapters/GitDiffService/GitDiffService.ts"],"sourcesContent":["import { spawnSync } from 'node:child_process';\nimport fs from 'node:fs/promises';\nimport path from 'node:path';\nimport type { FileDiff, FileEditState } from '../../types/domain';\nimport type { IGitDiffService } from '../../types/gitDiffService';\n\nexport const MAX_DIFF_LINES = 200;\nexport const MAX_DIFF_BYTES = 256 * 1024;\nconst BINARY_SAMPLE_BYTES = 8192;\n\nfunction capLines(lines: string[], byteTruncated: boolean): { lines: string[]; truncated: boolean } {\n const truncated = byteTruncated || lines.length > MAX_DIFF_LINES;\n const visible = lines.slice(0, MAX_DIFF_LINES);\n if (truncated) visible.push(`... diff truncated at ${MAX_DIFF_LINES} lines / ${MAX_DIFF_BYTES} bytes ...`);\n return { lines: visible, truncated };\n}\n\nfunction summarize(pathValue: string, state: FileEditState, tracked: boolean, raw: Buffer): FileDiff {\n const byteTruncated = raw.byteLength >= MAX_DIFF_BYTES;\n if (raw.subarray(0, BINARY_SAMPLE_BYTES).includes(0)) {\n return {\n path: pathValue,\n state: 'binary',\n lines: [`Binary file changed (${raw.byteLength} bytes shown by git)`],\n additions: 0,\n removals: 0,\n tracked,\n truncated: byteTruncated,\n suggestedLine: 1,\n };\n }\n const capped = capLines(raw.subarray(0, MAX_DIFF_BYTES).toString('utf8').split('\\n'), byteTruncated);\n const additions = capped.lines.filter((line) => line.startsWith('+') && !line.startsWith('+++')).length;\n const removals = capped.lines.filter((line) => line.startsWith('-') && !line.startsWith('---')).length;\n const hunk = capped.lines.find((line) => line.startsWith('@@'))?.match(/\\+(\\d+)/u);\n return {\n path: pathValue,\n state,\n lines: capped.lines,\n additions,\n removals,\n tracked,\n truncated: capped.truncated,\n suggestedLine: Number(hunk?.[1] ?? 1),\n };\n}\n\nexport class GitDiffService implements IGitDiffService {\n async diff(cwd: string, filePath: string): Promise<FileDiff> {\n const absolute = path.resolve(cwd, filePath);\n const relative = path.relative(cwd, absolute);\n const tracked = this.isTracked(cwd, relative);\n let exists = true;\n try {\n await fs.access(absolute);\n } catch (error) {\n if (error instanceof Error && 'code' in error && error.code === 'ENOENT') exists = false;\n else throw error;\n }\n if (!tracked && !exists) return summarize(absolute, 'deleted', false, Buffer.from('File no longer exists'));\n if (!tracked) return this.fullAdd(absolute);\n const result = spawnSync('git', ['diff', '--no-ext-diff', '--no-color', '--unified=3', 'HEAD', '--', relative], {\n cwd,\n encoding: 'buffer',\n maxBuffer: MAX_DIFF_BYTES,\n });\n const output = result.stdout ?? Buffer.alloc(0);\n if (exists && /^(Binary files .* differ|GIT binary patch)$/mu.test(output.toString('utf8'))) {\n return {\n path: absolute,\n state: 'binary',\n lines: ['Binary tracked file changed'],\n additions: 0,\n removals: 0,\n tracked: true,\n truncated: false,\n suggestedLine: 1,\n };\n }\n const state: FileEditState = exists ? (output.length > 0 ? 'modified' : 'unchanged') : 'deleted';\n return summarize(absolute, state, true, output);\n }\n\n private isTracked(cwd: string, relative: string): boolean {\n return spawnSync('git', ['ls-files', '--error-unmatch', '--', relative], { cwd, stdio: 'ignore' }).status === 0;\n }\n\n private async fullAdd(filePath: string): Promise<FileDiff> {\n const handle = await fs.open(filePath, 'r');\n try {\n const buffer = Buffer.alloc(MAX_DIFF_BYTES);\n const { bytesRead } = await handle.read(buffer, 0, buffer.length, 0);\n const sample = buffer.subarray(0, bytesRead);\n if (sample.subarray(0, BINARY_SAMPLE_BYTES).includes(0)) {\n return summarize(filePath, 'binary', false, Buffer.from(`Binary untracked file (${bytesRead}+ bytes)`));\n }\n const body = sample\n .toString('utf8')\n .split('\\n')\n .map((line) => `+${line}`)\n .join('\\n');\n const header = `--- /dev/null\\n+++ b/${path.basename(filePath)}\\n@@ -0,0 +1 @@\\n`;\n return summarize(filePath, 'added', false, Buffer.from(header + body));\n } finally {\n await handle.close();\n }\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,EAAU,SAAU,GAAO,OAAO,KAAK,0BAA0B,EAAU,SAAS,CAAC,EAExG,IAAM,EAAO,EACV,SAAS,MAAM,CAAC,CAChB,MAAM;CAAI,CAAC,CACX,IAAK,GAAS,IAAI,GAAM,CAAC,CACzB,KAAK;CAAI,EACN,EAAS,wBAAwBD,EAAAA,QAAK,SAAS,CAAQ,EAAE,mBAC/D,OAAO,EAAU,EAAU,QAAS,GAAO,OAAO,KAAK,EAAS,CAAI,CAAC,CACvE,QAAU,CACR,MAAM,EAAO,MAAM,CACrB,CACF,CACF"}
@@ -0,0 +1,5 @@
1
+ import e from"node:path";import t from"node:fs/promises";import{spawnSync as n}from"node:child_process";const r=262144,i=8192;function a(e,t){let n=t||e.length>200,i=e.slice(0,200);return n&&i.push(`... diff truncated at 200 lines / ${r} bytes ...`),{lines:i,truncated:n}}function o(e,t,n,o){let s=o.byteLength>=r;if(o.subarray(0,i).includes(0))return{path:e,state:`binary`,lines:[`Binary file changed (${o.byteLength} bytes shown by git)`],additions:0,removals:0,tracked:n,truncated:s,suggestedLine:1};let c=a(o.subarray(0,r).toString(`utf8`).split(`
2
+ `),s),l=c.lines.filter(e=>e.startsWith(`+`)&&!e.startsWith(`+++`)).length,u=c.lines.filter(e=>e.startsWith(`-`)&&!e.startsWith(`---`)).length,d=c.lines.find(e=>e.startsWith(`@@`))?.match(/\+(\d+)/u);return{path:e,state:t,lines:c.lines,additions:l,removals:u,tracked:n,truncated:c.truncated,suggestedLine:Number(d?.[1]??1)}}var s=class{async diff(r,i){let a=e.resolve(r,i),s=e.relative(r,a),c=this.isTracked(r,s),l=!0;try{await t.access(a)}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)l=!1;else throw e}if(!c&&!l)return o(a,`deleted`,!1,Buffer.from(`File no longer exists`));if(!c)return this.fullAdd(a);let u=n(`git`,[`diff`,`--no-ext-diff`,`--no-color`,`--unified=3`,`HEAD`,`--`,s],{cwd:r,encoding:`buffer`,maxBuffer:262144}).stdout??Buffer.alloc(0);return l&&/^(Binary files .* differ|GIT binary patch)$/mu.test(u.toString(`utf8`))?{path:a,state:`binary`,lines:[`Binary tracked file changed`],additions:0,removals:0,tracked:!0,truncated:!1,suggestedLine:1}:o(a,l?u.length>0?`modified`:`unchanged`:`deleted`,!0,u)}isTracked(e,t){return n(`git`,[`ls-files`,`--error-unmatch`,`--`,t],{cwd:e,stdio:`ignore`}).status===0}async fullAdd(n){let a=await t.open(n,`r`);try{let t=Buffer.alloc(r),{bytesRead:s}=await a.read(t,0,t.length,0),c=t.subarray(0,s);if(c.subarray(0,i).includes(0))return o(n,`binary`,!1,Buffer.from(`Binary untracked file (${s}+ bytes)`));let l=c.toString(`utf8`).split(`
3
+ `).map(e=>`+${e}`).join(`
4
+ `),u=`--- /dev/null\n+++ b/${e.basename(n)}\n@@ -0,0 +1 @@\n`;return o(n,`added`,!1,Buffer.from(u+l))}finally{await a.close()}}};export{s as GitDiffService,r as MAX_DIFF_BYTES};
5
+ //# sourceMappingURL=GitDiffService.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"GitDiffService.mjs","names":[],"sources":["../../../src/adapters/GitDiffService/GitDiffService.ts"],"sourcesContent":["import { spawnSync } from 'node:child_process';\nimport fs from 'node:fs/promises';\nimport path from 'node:path';\nimport type { FileDiff, FileEditState } from '../../types/domain';\nimport type { IGitDiffService } from '../../types/gitDiffService';\n\nexport const MAX_DIFF_LINES = 200;\nexport const MAX_DIFF_BYTES = 256 * 1024;\nconst BINARY_SAMPLE_BYTES = 8192;\n\nfunction capLines(lines: string[], byteTruncated: boolean): { lines: string[]; truncated: boolean } {\n const truncated = byteTruncated || lines.length > MAX_DIFF_LINES;\n const visible = lines.slice(0, MAX_DIFF_LINES);\n if (truncated) visible.push(`... diff truncated at ${MAX_DIFF_LINES} lines / ${MAX_DIFF_BYTES} bytes ...`);\n return { lines: visible, truncated };\n}\n\nfunction summarize(pathValue: string, state: FileEditState, tracked: boolean, raw: Buffer): FileDiff {\n const byteTruncated = raw.byteLength >= MAX_DIFF_BYTES;\n if (raw.subarray(0, BINARY_SAMPLE_BYTES).includes(0)) {\n return {\n path: pathValue,\n state: 'binary',\n lines: [`Binary file changed (${raw.byteLength} bytes shown by git)`],\n additions: 0,\n removals: 0,\n tracked,\n truncated: byteTruncated,\n suggestedLine: 1,\n };\n }\n const capped = capLines(raw.subarray(0, MAX_DIFF_BYTES).toString('utf8').split('\\n'), byteTruncated);\n const additions = capped.lines.filter((line) => line.startsWith('+') && !line.startsWith('+++')).length;\n const removals = capped.lines.filter((line) => line.startsWith('-') && !line.startsWith('---')).length;\n const hunk = capped.lines.find((line) => line.startsWith('@@'))?.match(/\\+(\\d+)/u);\n return {\n path: pathValue,\n state,\n lines: capped.lines,\n additions,\n removals,\n tracked,\n truncated: capped.truncated,\n suggestedLine: Number(hunk?.[1] ?? 1),\n };\n}\n\nexport class GitDiffService implements IGitDiffService {\n async diff(cwd: string, filePath: string): Promise<FileDiff> {\n const absolute = path.resolve(cwd, filePath);\n const relative = path.relative(cwd, absolute);\n const tracked = this.isTracked(cwd, relative);\n let exists = true;\n try {\n await fs.access(absolute);\n } catch (error) {\n if (error instanceof Error && 'code' in error && error.code === 'ENOENT') exists = false;\n else throw error;\n }\n if (!tracked && !exists) return summarize(absolute, 'deleted', false, Buffer.from('File no longer exists'));\n if (!tracked) return this.fullAdd(absolute);\n const result = spawnSync('git', ['diff', '--no-ext-diff', '--no-color', '--unified=3', 'HEAD', '--', relative], {\n cwd,\n encoding: 'buffer',\n maxBuffer: MAX_DIFF_BYTES,\n });\n const output = result.stdout ?? Buffer.alloc(0);\n if (exists && /^(Binary files .* differ|GIT binary patch)$/mu.test(output.toString('utf8'))) {\n return {\n path: absolute,\n state: 'binary',\n lines: ['Binary tracked file changed'],\n additions: 0,\n removals: 0,\n tracked: true,\n truncated: false,\n suggestedLine: 1,\n };\n }\n const state: FileEditState = exists ? (output.length > 0 ? 'modified' : 'unchanged') : 'deleted';\n return summarize(absolute, state, true, output);\n }\n\n private isTracked(cwd: string, relative: string): boolean {\n return spawnSync('git', ['ls-files', '--error-unmatch', '--', relative], { cwd, stdio: 'ignore' }).status === 0;\n }\n\n private async fullAdd(filePath: string): Promise<FileDiff> {\n const handle = await fs.open(filePath, 'r');\n try {\n const buffer = Buffer.alloc(MAX_DIFF_BYTES);\n const { bytesRead } = await handle.read(buffer, 0, buffer.length, 0);\n const sample = buffer.subarray(0, bytesRead);\n if (sample.subarray(0, BINARY_SAMPLE_BYTES).includes(0)) {\n return summarize(filePath, 'binary', false, Buffer.from(`Binary untracked file (${bytesRead}+ bytes)`));\n }\n const body = sample\n .toString('utf8')\n .split('\\n')\n .map((line) => `+${line}`)\n .join('\\n');\n const header = `--- /dev/null\\n+++ b/${path.basename(filePath)}\\n@@ -0,0 +1 @@\\n`;\n return summarize(filePath, 'added', false, Buffer.from(header + body));\n } finally {\n await handle.close();\n }\n }\n}\n"],"mappings":"wGAOA,MAAa,EAAiB,OACxB,EAAsB,KAE5B,SAAS,EAAS,EAAiB,EAAiE,CAClG,IAAM,EAAY,GAAiB,EAAM,OAAA,IACnC,EAAU,EAAM,MAAM,EAAA,GAAiB,EAE7C,OADI,GAAW,EAAQ,KAAK,qCAAmD,EAAe,WAAW,EAClG,CAAE,MAAO,EAAS,WAAU,CACrC,CAEA,SAAS,EAAU,EAAmB,EAAsB,EAAkB,EAAuB,CACnG,IAAM,EAAgB,EAAI,YAAc,EACxC,GAAI,EAAI,SAAS,EAAG,CAAmB,CAAC,CAAC,SAAS,CAAC,EACjD,MAAO,CACL,KAAM,EACN,MAAO,SACP,MAAO,CAAC,wBAAwB,EAAI,WAAW,qBAAqB,EACpE,UAAW,EACX,SAAU,EACV,UACA,UAAW,EACX,cAAe,CACjB,EAEF,IAAM,EAAS,EAAS,EAAI,SAAS,EAAG,CAAc,CAAC,CAAC,SAAS,MAAM,CAAC,CAAC,MAAM;CAAI,EAAG,CAAa,EAC7F,EAAY,EAAO,MAAM,OAAQ,GAAS,EAAK,W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e,UACrD,GAAM,CAAM,CAChD,CAEA,UAAkB,EAAa,EAA2B,CACxD,OAAO,EAAU,MAAO,CAAC,WAAY,kBAAmB,KAAM,CAAQ,EAAG,CAAE,MAAK,MAAO,QAAS,CAAC,CAAC,CAAC,SAAW,CAChH,CAEA,MAAc,QAAQ,EAAqC,CACzD,IAAM,EAAS,MAAM,EAAG,KAAK,EAAU,GAAG,EAC1C,GAAI,CACF,IAAM,EAAS,OAAO,MAAM,CAAc,EACpC,CAAE,aAAc,MAAM,EAAO,KAAK,EAAQ,EAAG,EAAO,OAAQ,CAAC,EAC7D,EAAS,EAAO,SAAS,EAAG,CAAS,EAC3C,GAAI,EAAO,SAAS,EAAG,CAAmB,CAAC,CAAC,SAAS,CAAC,EACpD,OAAO,EAAU,EAAU,SAAU,GAAO,OAAO,KAAK,0BAA0B,EAAU,SAAS,CAAC,EAExG,IAAM,EAAO,EACV,SAAS,MAAM,CAAC,CAChB,MAAM;CAAI,CAAC,CACX,IAAK,GAAS,IAAI,GAAM,CAAC,CACzB,KAAK;CAAI,EACN,EAAS,wBAAwB,EAAK,SAAS,CAAQ,EAAE,mBAC/D,OAAO,EAAU,EAAU,QAAS,GAAO,OAAO,KAAK,EAAS,CAAI,CAAC,CACvE,QAAU,CACR,MAAM,EAAO,MAAM,CACrB,CACF,CACF"}
@@ -0,0 +1,2 @@
1
+ const e=require("../../_virtual/_rolldown/runtime.cjs"),t=require("../../services/fileChanges.cjs");let n=require("node:fs/promises");n=e.__toESM(n,1);function r(e,t){return e instanceof Error&&`code`in e&&e.code===t}var i=class{filePath;initialize(e){this.filePath=e}async append(e){await this.withLock(async()=>n.default.appendFile(this.requirePath(),`${JSON.stringify(e)}\n`,`utf8`))}async list(){return t.foldEntries(t.confirmedChanges(await this.events()))}async versions(e){return t.foldVersions(t.confirmedChanges(await this.events()),e)}async clear(){try{await n.default.unlink(this.requirePath())}catch(e){if(!r(e,`ENOENT`))throw e}}async events(){let e;try{e=await n.default.readFile(this.requirePath(),`utf8`)}catch(e){if(r(e,`ENOENT`))return[];throw e}return t.parseTimeline(e,e=>console.warn(`Ignoring malformed file edit timeline line: ${e.slice(0,200)}`))}requirePath(){if(!this.filePath)throw Error(`Timeline store is not initialized`);return this.filePath}async withLock(e){let t=`${this.requirePath()}.lock`,n=await this.acquire(t);try{return await e()}finally{await n.close(),await this.release(t)}}async acquire(e){for(let t=0;t<400;t+=1)try{return await n.default.open(e,`wx`)}catch(t){if(!r(t,`EEXIST`))throw t;if(await this.breakStale(e))continue;await new Promise(e=>setTimeout(e,25))}throw Error(`Timed out acquiring timeline lock ${e}`)}async breakStale(e){try{let t=await n.default.stat(e);return Date.now()-t.mtimeMs<3e4?!1:(await n.default.unlink(e),!0)}catch(e){if(r(e,`ENOENT`))return!0;throw e}}async release(e){try{await n.default.unlink(e)}catch(e){r(e,`ENOENT`)||console.warn(`Could not remove timeline lock: ${String(e)}`)}}};exports.TimelineStore=i;
2
+ //# sourceMappingURL=TimelineStore.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"TimelineStore.cjs","names":["fs","foldEntries","confirmedChanges","foldVersions","parseTimeline"],"sources":["../../../src/adapters/TimelineStore/TimelineStore.ts"],"sourcesContent":["import fs, { type FileHandle } from 'node:fs/promises';\nimport {\n type AnyTimelineEvent,\n confirmedChanges,\n foldEntries,\n foldVersions,\n parseTimeline,\n} from '../../services/fileChanges.ts';\nimport type { FileEditEntry, FileEditVersion, TimelineEvent } from '../../types/domain';\nimport type { ITimelineStore } from '../../types/timelineStore';\n\nconst LOCK_RETRY_MS = 25;\nconst LOCK_RETRIES = 400;\n/**\n * How long a lock file may sit untouched before a waiter treats it as abandoned.\n *\n * An append writes one line, so a holder that has been there for half a minute\n * is a process that died without unlinking. Without this, that one file would\n * block every later append to the same timeline permanently.\n */\nconst LOCK_STALE_MS = 30_000;\n\nfunction hasCode(error: unknown, code: string): boolean {\n return error instanceof Error && 'code' in error && error.code === code;\n}\n\nexport class TimelineStore implements ITimelineStore {\n private filePath: string | undefined;\n\n initialize(filePath: string): void {\n this.filePath = filePath;\n }\n\n async append(event: TimelineEvent): Promise<void> {\n await this.withLock(async () => fs.appendFile(this.requirePath(), `${JSON.stringify(event)}\\n`, 'utf8'));\n }\n\n async list(): Promise<FileEditEntry[]> {\n // Listing shows what was edited, so a path a command only touched is left out.\n return foldEntries(confirmedChanges(await this.events()));\n }\n\n async versions(filePath: string): Promise<FileEditVersion[]> {\n // Same bar as the listing above: a file's history must not reintroduce the\n // touches the list already left out.\n return foldVersions(confirmedChanges(await this.events()), filePath);\n }\n\n async clear(): Promise<void> {\n try {\n await fs.unlink(this.requirePath());\n } catch (error) {\n if (!hasCode(error, 'ENOENT')) throw error;\n }\n }\n\n /** Every recorded change, or none at all when the session has not written yet. */\n private async events(): Promise<AnyTimelineEvent[]> {\n let content: string;\n try {\n content = await fs.readFile(this.requirePath(), 'utf8');\n } catch (error) {\n if (hasCode(error, 'ENOENT')) return [];\n throw error;\n }\n return parseTimeline(content, (line) =>\n console.warn(`Ignoring malformed file edit timeline line: ${line.slice(0, 200)}`),\n );\n }\n\n private requirePath(): string {\n if (!this.filePath) throw new Error('Timeline store is not initialized');\n return this.filePath;\n }\n\n private async withLock<T>(operation: () => Promise<T>): Promise<T> {\n const lockPath = `${this.requirePath()}.lock`;\n const lock = await this.acquire(lockPath);\n try {\n return await operation();\n } finally {\n await lock.close();\n await this.release(lockPath);\n }\n }\n\n /** Waits for the lock file, breaking one an earlier process left behind. */\n private async acquire(lockPath: string): Promise<FileHandle> {\n for (let attempt = 0; attempt < LOCK_RETRIES; attempt += 1) {\n try {\n return await fs.open(lockPath, 'wx');\n } catch (error) {\n if (!hasCode(error, 'EEXIST')) throw error;\n if (await this.breakStale(lockPath)) continue;\n await new Promise((resolve) => setTimeout(resolve, LOCK_RETRY_MS));\n }\n }\n throw new Error(`Timed out acquiring timeline lock ${lockPath}`);\n }\n\n /** Whether the lock is now free to take, having removed it when its holder is gone. */\n private async breakStale(lockPath: string): Promise<boolean> {\n try {\n const stats = await fs.stat(lockPath);\n if (Date.now() - stats.mtimeMs < LOCK_STALE_MS) return false;\n await fs.unlink(lockPath);\n return true;\n } catch (error) {\n // Already gone, or another waiter broke it first: either way, try again.\n if (hasCode(error, 'ENOENT')) return true;\n throw error;\n }\n }\n\n private async release(lockPath: string): Promise<void> {\n try {\n await fs.unlink(lockPath);\n } catch (error) {\n if (!hasCode(error, 'ENOENT')) console.warn(`Could not remove timeline lock: ${String(error)}`);\n }\n }\n}\n"],"mappings":"uJAsBA,SAAS,EAAQ,EAAgB,EAAuB,CACtD,OAAO,aAAiB,OAAS,SAAU,GAAS,EAAM,OAAS,CACrE,CAEA,IAAa,EAAb,KAAqD,CACnD,SAEA,WAAW,EAAwB,CACjC,KAAK,SAAW,CAClB,CAEA,MAAM,OAAO,EAAqC,CAChD,MAAM,KAAK,SAAS,SAAYA,EAAAA,QAAG,WAAW,KAAK,YAAY,EAAG,GAAG,KAAK,UAAU,CAAK,EAAE,IAAK,MAAM,CAAC,CACzG,CAEA,MAAM,MAAiC,CAErC,OAAOC,EAAAA,YAAYC,EAAAA,iBAAiB,MAAM,KAAK,OAAO,CAAC,CAAC,CAC1D,CAEA,MAAM,SAAS,EAA8C,CAG3D,OAAOC,EAAAA,aAAaD,EAAAA,iBAAiB,MAAM,KAAK,OAAO,CAAC,EAAG,CAAQ,CACrE,CAEA,MAAM,OAAuB,CAC3B,GAAI,CACF,MAAMF,EAAAA,QAAG,OAAO,KAAK,YAAY,CAAC,CACpC,OAAS,EAAO,CACd,GAAI,CAAC,EAAQ,EAAO,QAAQ,EAAG,MAAM,CACvC,CACF,CAGA,MAAc,QAAsC,CAClD,IAAI,EACJ,GAAI,CACF,EAAU,MAAMA,EAAAA,QAAG,SAAS,KAAK,YAAY,EAAG,MAAM,CACxD,OAAS,EAAO,CACd,GAAI,EAAQ,EAAO,QAAQ,EAAG,MAAO,CAAC,EACtC,MAAM,CACR,CACA,OAAOI,EAAAA,cAAc,EAAU,GAC7B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parseTimeline as r}from"../../services/fileChanges.mjs";import i from"node:fs/promises";function a(e,t){return e instanceof Error&&`code`in e&&e.code===t}var o=class{filePath;initialize(e){this.filePath=e}async append(e){await this.withLock(async()=>i.appendFile(this.requirePath(),`${JSON.stringify(e)}\n`,`utf8`))}async list(){return t(e(await this.events()))}async versions(t){return n(e(await this.events()),t)}async clear(){try{await i.unlink(this.requirePath())}catch(e){if(!a(e,`ENOENT`))throw e}}async events(){let e;try{e=await i.readFile(this.requirePath(),`utf8`)}catch(e){if(a(e,`ENOENT`))return[];throw e}return r(e,e=>console.warn(`Ignoring malformed file edit timeline line: ${e.slice(0,200)}`))}requirePath(){if(!this.filePath)throw Error(`Timeline store is not initialized`);return this.filePath}async withLock(e){let t=`${this.requirePath()}.lock`,n=await this.acquire(t);try{return await e()}finally{await n.close(),await this.release(t)}}async acquire(e){for(let t=0;t<400;t+=1)try{return await i.open(e,`wx`)}catch(t){if(!a(t,`EEXIST`))throw t;if(await this.breakStale(e))continue;await new Promise(e=>setTimeout(e,25))}throw Error(`Timed out acquiring timeline lock ${e}`)}async breakStale(e){try{let t=await i.stat(e);return Date.now()-t.mtimeMs<3e4?!1:(await i.unlink(e),!0)}catch(e){if(a(e,`ENOENT`))return!0;throw e}}async release(e){try{await i.unlink(e)}catch(e){a(e,`ENOENT`)||console.warn(`Could not remove timeline lock: ${String(e)}`)}}};export{o as TimelineStore};
2
+ //# sourceMappingURL=TimelineStore.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"TimelineStore.mjs","names":[],"sources":["../../../src/adapters/TimelineStore/TimelineStore.ts"],"sourcesContent":["import fs, { type FileHandle } from 'node:fs/promises';\nimport {\n type AnyTimelineEvent,\n confirmedChanges,\n foldEntries,\n foldVersions,\n parseTimeline,\n} from '../../services/fileChanges.ts';\nimport type { FileEditEntry, FileEditVersion, TimelineEvent } from '../../types/domain';\nimport type { ITimelineStore } from '../../types/timelineStore';\n\nconst LOCK_RETRY_MS = 25;\nconst LOCK_RETRIES = 400;\n/**\n * How long a lock file may sit untouched before a waiter treats it as abandoned.\n *\n * An append writes one line, so a holder that has been there for half a minute\n * is a process that died without unlinking. Without this, that one file would\n * block every later append to the same timeline permanently.\n */\nconst LOCK_STALE_MS = 30_000;\n\nfunction hasCode(error: unknown, code: string): boolean {\n return error instanceof Error && 'code' in error && error.code === code;\n}\n\nexport class TimelineStore implements ITimelineStore {\n private filePath: string | undefined;\n\n initialize(filePath: string): void {\n this.filePath = filePath;\n }\n\n async append(event: TimelineEvent): Promise<void> {\n await this.withLock(async () => fs.appendFile(this.requirePath(), `${JSON.stringify(event)}\\n`, 'utf8'));\n }\n\n async list(): Promise<FileEditEntry[]> {\n // Listing shows what was edited, so a path a command only touched is left out.\n return foldEntries(confirmedChanges(await this.events()));\n }\n\n async versions(filePath: string): Promise<FileEditVersion[]> {\n // Same bar as the listing above: a file's history must not reintroduce the\n // touches the list already left out.\n return foldVersions(confirmedChanges(await this.events()), filePath);\n }\n\n async clear(): Promise<void> {\n try {\n await fs.unlink(this.requirePath());\n } catch (error) {\n if (!hasCode(error, 'ENOENT')) throw error;\n }\n }\n\n /** Every recorded change, or none at all when the session has not written yet. */\n private async events(): Promise<AnyTimelineEvent[]> {\n let content: string;\n try {\n content = await fs.readFile(this.requirePath(), 'utf8');\n } catch (error) {\n if (hasCode(error, 'ENOENT')) return [];\n throw error;\n }\n return parseTimeline(content, (line) =>\n console.warn(`Ignoring malformed file edit timeline line: ${line.slice(0, 200)}`),\n );\n }\n\n private requirePath(): string {\n if (!this.filePath) throw new Error('Timeline store is not initialized');\n return this.filePath;\n }\n\n private async withLock<T>(operation: () => Promise<T>): Promise<T> {\n const lockPath = `${this.requirePath()}.lock`;\n const lock = await this.acquire(lockPath);\n try {\n return await operation();\n } finally {\n await lock.close();\n await this.release(lockPath);\n }\n }\n\n /** Waits for the lock file, breaking one an earlier process left behind. */\n private async acquire(lockPath: string): Promise<FileHandle> {\n for (let attempt = 0; attempt < LOCK_RETRIES; attempt += 1) {\n try {\n return await fs.open(lockPath, 'wx');\n } catch (error) {\n if (!hasCode(error, 'EEXIST')) throw error;\n if (await this.breakStale(lockPath)) continue;\n await new Promise((resolve) => setTimeout(resolve, LOCK_RETRY_MS));\n }\n }\n throw new Error(`Timed out acquiring timeline lock ${lockPath}`);\n }\n\n /** Whether the lock is now free to take, having removed it when its holder is gone. */\n private async breakStale(lockPath: string): Promise<boolean> {\n try {\n const stats = await fs.stat(lockPath);\n if (Date.now() - stats.mtimeMs < LOCK_STALE_MS) return false;\n await fs.unlink(lockPath);\n return true;\n } catch (error) {\n // Already gone, or another waiter broke it first: either way, try again.\n if (hasCode(error, 'ENOENT')) return true;\n throw error;\n }\n }\n\n private async release(lockPath: string): Promise<void> {\n try {\n await fs.unlink(lockPath);\n } catch (error) {\n if (!hasCode(error, 'ENOENT')) console.warn(`Could not remove timeline lock: ${String(error)}`);\n }\n }\n}\n"],"mappings":"wJAsBA,SAAS,EAAQ,EAAgB,EAAuB,CACtD,OAAO,aAAiB,OAAS,SAAU,GAAS,EAAM,OAAS,CACrE,CAEA,IAAa,EAAb,KAAqD,CACnD,SAEA,WAAW,EAAwB,CACjC,KAAK,SAAW,CAClB,CAEA,MAAM,OAAO,EAAqC,CAChD,MAAM,KAAK,SAAS,SAAY,EAAG,WAAW,KAAK,YAAY,EAAG,GAAG,KAAK,UAAU,CAAK,EAAE,IAAK,MAAM,CAAC,CACzG,CAEA,MAAM,MAAiC,CAErC,OAAO,EAAY,EAAiB,MAAM,KAAK,OAAO,CAAC,CAAC,CAC1D,CAEA,MAAM,SAAS,EAA8C,CAG3D,OAAO,EAAa,EAAiB,MAAM,KAAK,OAAO,CAAC,EAAG,CAAQ,CACrE,CAEA,MAAM,OAAuB,CAC3B,GAAI,CACF,MAAM,EAAG,OAAO,KAAK,YAAY,CAAC,CACpC,OAAS,EAAO,CACd,GAAI,CAAC,EAAQ,EAAO,QAAQ,EAAG,MAAM,CACvC,CACF,CAGA,MAAc,QAAsC,CAClD,IAA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ACT,EAAQ,EAAO,QAAQ,GAAG,QAAQ,KAAK,mCAAmC,OAAO,CAAK,GAAG,CAChG,CACF,CACF"}
@@ -0,0 +1,2 @@
1
+ const e=require("../_virtual/_rolldown/runtime.cjs"),t=require("../services/lineDiff.cjs"),n=require("./FileEditPaths/FileEditPaths.cjs"),r=require("./node/snapshotStore.cjs"),i=require("../services/fileChanges.cjs"),a=require("./TimelineStore/TimelineStore.cjs"),o=require("../types/fileEditsApi.cjs");let s=require("node:path");s=e.__toESM(s,1);let c=require("node:fs/promises");c=e.__toESM(c,1);let l=require("node:crypto"),u=require("hono");const d=1048576,f=`changed by a command, so no baseline was captured; showing the file as it stands`,p=`the previous content could not be captured: it was binary or past the size cap`,m=`the changed region was too large to match line by line`;function h(e){return(0,l.createHash)(`sha256`).update(e,`utf8`).digest(`hex`)}function g(e,t){return e instanceof Error&&`code`in e&&e.code===t}function _(e){return e instanceof Error?e.message:String(e)}async function v(e){let t;try{t=await c.default.readFile(e)}catch{return{content:``,hash:``,unavailable:!0,reason:`the file no longer exists`}}if(t.byteLength>1048576)return{content:``,hash:``,unavailable:!0,reason:`the file is larger than ${d} bytes`};if(t.subarray(0,8192).includes(0))return{content:``,hash:``,unavailable:!0,reason:`the file is binary`};let n=t.toString(`utf8`);return{content:n,hash:h(n),unavailable:!1}}function y(e,t){return t===e||t.startsWith(`${e}${s.default.sep}`)}async function b(e,t){let n,r;try{n=await c.default.realpath(e),r=await c.default.realpath(t)}catch{return!0}return y(n,r)}async function x(e,n){let r={index:e.index,tool:e.tool,at:e.at,origin:e.origin,additions:e.additions??0,removals:e.removals??0},i=e.before===void 0&&e.created===!0;if(e.after===void 0||e.before===void 0&&!i)return e.origin===`tool`?{...r,note:e.after===void 0?`the new content could not be captured: the file is binary or past the size cap`:p}:{...r,note:e.tool===`bash`?f:`recorded before this session began capturing content, so there is no diff for it`};let a=await n.read(e.after);if(a===void 0)return{...r,note:`the content behind this change is no longer held`};if(e.before===void 0){let e=t.lineDiffFromEmpty(a);return{...r,additions:e.additions,removals:e.removals,hunks:e.hunks,...e.approximate?{note:m}:{}}}let o=await n.read(e.before);if(o===void 0)return{...r,note:`the content behind this change is no longer held`};let s=t.lineDiff(o,a);return{...r,additions:s.additions,removals:s.removals,hunks:s.hunks,...s.approximate?{note:m}:{}}}async function S(e,n,r){let a=e[0]?.created===!0,o=i.baselineOf(e);if(!a&&o===void 0)return{additions:0,removals:0,note:e[0]?.origin===`tool`?p:f};if(n.unavailable)return{additions:0,removals:0,note:n.reason??`the file cannot be read`};if(a||o===void 0){let e=t.lineDiffFromEmpty(n.content);return{additions:e.additions,removals:e.removals,hunks:e.hunks,...e.approximate?{note:m}:{}}}let s=await r.read(o);if(s===void 0)return{additions:0,removals:0,note:`the content this session started from is no longer held`};let c=t.lineDiff(s,n.content);return{additions:c.additions,removals:c.removals,hunks:c.hunks,...c.approximate?{note:m}:{}}}function C(e={}){let t=e.timeline??new a.TimelineStore,i=e.snapshots??new r.NodeSnapshotStoreAdapter,l=e.paths??new n.FileEditPaths,d=e.cwd??``,f=new u.Hono;if(e.sessionId!==void 0&&d!==``){let n=l.sessionKey(e.sessionId);e.timeline===void 0&&t.initialize(l.timelinePath(d,n)),e.snapshots===void 0&&i.initialize(l.snapshotsPath(d,n))}let p=async e=>{if(e===void 0||e===``)return;let n=await t.versions(s.default.resolve(d,e));return n.length===0?void 0:n};return f.get(`/detail`,async e=>{let t=e.req.query(o.PATH_QUERY_PARAM),n=await p(t);if(n===void 0||t===void 0)return e.json({error:`This session recorded no changes to that file.`},404);let r=s.default.resolve(d,t),a=await v(r),c={path:r,relPath:d===``?r:s.default.relative(d,r),versions:await Promise.all(n.map(e=>x(e,i))),cumulative:await S(n,a,i),working:a};return e.json(c)}),f.get(`/preview`,async e=>{let t=e.req.query(o.PATH_QUERY_PARAM);if(t===void 0||t===``||t.includes(`\0`))return e.json({error:`A preview names a path.`},400);if(d===``)return e.json({error:`This session has no working directory to read from.`},403);let n=s.default.resolve(d),r=s.default.resolve(n,t);if(!y(n,r)||!await b(n,r))return e.json({error:`The path leaves the session directory.`},403);let i={path:r,relPath:s.default.relative(n,r),working:await v(r)};return e.json(i)}),f.put(`/content`,async e=>{let t;try{t=await e.req.json()}catch{return e.json({error:`The save body is not JSON.`},400)}if(typeof t.path!=`string`||typeof t.content!=`string`)return e.json({error:`A save names a path and the content to write.`},400);if(await p(t.path)===void 0)return e.json({error:`This session recorded no changes to that file.`},404);let n=s.default.resolve(d,t.path),r=await v(n);if(r.unavailable)return e.json({error:r.reason??`The file cannot be read.`},409);if(r.hash!==t.expectedHash)return e.json({error:`The file changed since it was opened.`,hash:r.hash},409);await c.default.writeFile(n,t.content,`utf8`);let i={hash:h(t.content)};return e.json(i)}),f.delete(`/content`,async e=>{let t=e.req.query(o.PATH_QUERY_PARAM);if(await p(t)===void 0||t===void 0)return e.json({error:`This session recorded no changes to that file.`},404);let n=s.default.resolve(d,t);try{await c.default.unlink(n)}catch(t){if(!g(t,`ENOENT`))return e.json({error:`The file could not be deleted: ${_(t)}`},409)}return e.body(null,204)}),f}const w={basePath:o.API_BASE_PATH,start(e){let t=C({...e.sessionId===void 0?{}:{sessionId:e.sessionId},...e.cwd===void 0?{}:{cwd:e.cwd}});return{fetch:e=>t.fetch(e),close:()=>void 0}}};exports.MAX_WORKING_BYTES=d,exports.api=w,exports.createFileEditsApi=C;
2
+ //# sourceMappingURL=fileEditsApi.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"fileEditsApi.cjs","names":["createHash","fs","path","lineDiffFromEmpty","lineDiff","baselineOf","TimelineStore","NodeSnapshotStoreAdapter","FileEditPaths","Hono","PATH_QUERY_PARAM","API_BASE_PATH"],"sources":["../../src/adapters/fileEditsApi.ts"],"sourcesContent":["import { createHash } from 'node:crypto';\nimport fs from 'node:fs/promises';\nimport path from 'node:path';\nimport type { DoomApi, DoomApiContext, DoomApiHandler } from '@agimon-ai/doompi-extension-contracts/package-api';\nimport { Hono } from 'hono';\nimport { baselineOf } from '../services/fileChanges.ts';\nimport { lineDiff, lineDiffFromEmpty } from '../services/lineDiff.ts';\nimport type { FileEditVersion } from '../types/domain.ts';\nimport {\n API_BASE_PATH,\n type FileEditsCumulativeView,\n type FileEditsDetailView,\n type FileEditsPreviewView,\n type FileEditsSaveRequest,\n type FileEditsSaveView,\n type FileEditsVersionView,\n type FileEditsWorkingView,\n PATH_QUERY_PARAM,\n} from '../types/fileEditsApi.ts';\nimport type { IFileEditPaths } from '../types/fileEditPaths.ts';\nimport type { SnapshotStorePort } from '../types/snapshotStore.ts';\nimport type { ITimelineStore } from '../types/timelineStore.ts';\nimport { FileEditPaths } from './FileEditPaths/FileEditPaths.ts';\nimport { NodeSnapshotStoreAdapter } from './node/snapshotStore.ts';\nimport { TimelineStore } from './TimelineStore/TimelineStore.ts';\n\n/**\n * This package's HTTP surface: one file's history, and the manual save.\n *\n * Routes are relative to the mount its host gives it, so nothing here repeats\n * where it was mounted. The host is one session's own server, which is what\n * makes the session id and working directory available without the page\n * supplying either: a page names a file, never a session's private paths.\n *\n * The detail route answers everything a reader needs to open a changed file,\n * because splitting it would make the page stitch three responses together for\n * one click. The save route is the only mutation, and it refuses unless the\n * reader proves they were looking at the content that is still on disk. The\n * preview route is the read-only way in to a file the session never changed,\n * bounded by the working directory instead of by the timeline.\n */\n\n/** Past this, the working view reports the file rather than carrying it. */\nexport const MAX_WORKING_BYTES = 1024 * 1024;\n\nconst BINARY_SAMPLE_BYTES = 8192;\nconst NO_BASELINE_NOTE = 'changed by a command, so no baseline was captured; showing the file as it stands';\n/**\n * A change the tool layer named but never captured content for. That is what\n * every record written before this package learned to snapshot looks like, and\n * calling those \"changed by a command\" would be wrong: the tool is right there\n * in the record.\n */\nconst NO_SNAPSHOT_NOTE = 'recorded before this session began capturing content, so there is no diff for it';\nconst NO_AFTER_NOTE = 'the new content could not be captured: the file is binary or past the size cap';\nconst NO_BEFORE_NOTE = 'the previous content could not be captured: it was binary or past the size cap';\nconst APPROXIMATE_NOTE = 'the changed region was too large to match line by line';\n\nexport interface FileEditsApiOptions {\n /** The session these routes answer for; absent when the host is the hub. */\n sessionId?: string;\n /** The session's working directory, which relative paths are shown against. */\n cwd?: string;\n timeline?: ITimelineStore;\n snapshots?: SnapshotStorePort;\n paths?: IFileEditPaths;\n}\n\nfunction hashOf(content: string): string {\n return createHash('sha256').update(content, 'utf8').digest('hex');\n}\n\nfunction hasCode(error: unknown, code: string): boolean {\n return error instanceof Error && 'code' in error && error.code === code;\n}\n\nfunction describe(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\n/** Reads the file as the source view will show it, or says why it cannot. */\nasync function readWorking(filePath: string): Promise<FileEditsWorkingView> {\n let raw: Buffer;\n try {\n raw = await fs.readFile(filePath);\n } catch {\n return { content: '', hash: '', unavailable: true, reason: 'the file no longer exists' };\n }\n if (raw.byteLength > MAX_WORKING_BYTES) {\n return { content: '', hash: '', unavailable: true, reason: `the file is larger than ${MAX_WORKING_BYTES} bytes` };\n }\n if (raw.subarray(0, BINARY_SAMPLE_BYTES).includes(0)) {\n return { content: '', hash: '', unavailable: true, reason: 'the file is binary' };\n }\n const content = raw.toString('utf8');\n return { content, hash: hashOf(content), unavailable: false };\n}\n\nfunction isInside(root: string, candidate: string): boolean {\n return candidate === root || candidate.startsWith(`${root}${path.sep}`);\n}\n\n/**\n * The same containment check after symlinks are followed. A path that does not\n * exist yet resolves to nothing, and there is nothing to hand out, so it\n * passes and the read below reports it missing.\n */\nasync function isRealPathInside(root: string, candidate: string): Promise<boolean> {\n let realRoot: string;\n let real: string;\n try {\n realRoot = await fs.realpath(root);\n real = await fs.realpath(candidate);\n } catch {\n return true;\n }\n return isInside(realRoot, real);\n}\n\n/**\n * One recorded change as the page renders it. A change with both sides captured\n * carries its own diff; one without says why, rather than showing nothing.\n *\n * A file this session created counts as captured on both sides. Its baseline is\n * empty rather than missing, so the whole file reads as arriving at once, which\n * is exactly what happened.\n */\nasync function toVersionView(version: FileEditVersion, snapshots: SnapshotStorePort): Promise<FileEditsVersionView> {\n const view: FileEditsVersionView = {\n index: version.index,\n tool: version.tool,\n at: version.at,\n origin: version.origin,\n additions: version.additions ?? 0,\n removals: version.removals ?? 0,\n };\n const createdHere = version.before === undefined && version.created === true;\n if (version.after === undefined || (version.before === undefined && !createdHere)) {\n // A scan found the path only after it changed, so no baseline exists. A\n // tool named the path but content was not stored: either it did not fit, or\n // the record predates content capture, which the tool tells apart.\n if (version.origin === 'tool') {\n return { ...view, note: version.after === undefined ? NO_AFTER_NOTE : NO_BEFORE_NOTE };\n }\n return { ...view, note: version.tool === 'bash' ? NO_BASELINE_NOTE : NO_SNAPSHOT_NOTE };\n }\n const after = await snapshots.read(version.after);\n if (after === undefined) {\n return { ...view, note: 'the content behind this change is no longer held' };\n }\n if (version.before === undefined) {\n const fresh = lineDiffFromEmpty(after);\n return {\n ...view,\n additions: fresh.additions,\n removals: fresh.removals,\n hunks: fresh.hunks,\n ...(fresh.approximate ? { note: APPROXIMATE_NOTE } : {}),\n };\n }\n const before = await snapshots.read(version.before);\n if (before === undefined) {\n return { ...view, note: 'the content behind this change is no longer held' };\n }\n const diff = lineDiff(before, after);\n return {\n ...view,\n additions: diff.additions,\n removals: diff.removals,\n hunks: diff.hunks,\n ...(diff.approximate ? { note: APPROXIMATE_NOTE } : {}),\n };\n}\n\n/** Everything the session did to the file: its oldest baseline against what is on disk now. */\nasync function toCumulativeView(\n versions: readonly FileEditVersion[],\n working: FileEditsWorkingView,\n snapshots: SnapshotStorePort,\n): Promise<FileEditsCumulativeView> {\n // A file this session created starts from nothing, and nothing is a baseline\n // the snapshot store never has to hold.\n const createdHere = versions[0]?.created === true;\n const baseline = baselineOf(versions);\n if (!createdHere && baseline === undefined) {\n return {\n additions: 0,\n removals: 0,\n note: versions[0]?.origin === 'tool' ? NO_BEFORE_NOTE : NO_BASELINE_NOTE,\n };\n }\n if (working.unavailable) {\n return { additions: 0, removals: 0, note: working.reason ?? 'the file cannot be read' };\n }\n if (createdHere || baseline === undefined) {\n const fresh = lineDiffFromEmpty(working.content);\n return {\n additions: fresh.additions,\n removals: fresh.removals,\n hunks: fresh.hunks,\n ...(fresh.approximate ? { note: APPROXIMATE_NOTE } : {}),\n };\n }\n const before = await snapshots.read(baseline);\n if (before === undefined) {\n return { additions: 0, removals: 0, note: 'the content this session started from is no longer held' };\n }\n const diff = lineDiff(before, working.content);\n return {\n additions: diff.additions,\n removals: diff.removals,\n hunks: diff.hunks,\n ...(diff.approximate ? { note: APPROXIMATE_NOTE } : {}),\n };\n}\n\nexport function createFileEditsApi(options: FileEditsApiOptions = {}): Hono {\n const timeline = options.timeline ?? new TimelineStore();\n const snapshots = options.snapshots ?? new NodeSnapshotStoreAdapter();\n const paths = options.paths ?? new FileEditPaths();\n const cwd = options.cwd ?? '';\n const app = new Hono();\n\n // The routes and the extension run in different processes, so this half\n // opens the same two locations from the same inputs rather than sharing an\n // instance with the half that writes them.\n //\n // Only what this function built gets pointed at them. A store handed in\n // through the options arrives already configured, and repointing it would\n // make the option a lie: the caller would be injecting a store the routes\n // then read somewhere else entirely.\n if (options.sessionId !== undefined && cwd !== '') {\n const sessionKey = paths.sessionKey(options.sessionId);\n if (options.timeline === undefined) timeline.initialize(paths.timelinePath(cwd, sessionKey));\n if (options.snapshots === undefined) snapshots.initialize(paths.snapshotsPath(cwd, sessionKey));\n }\n\n /**\n * The file a request names, rejected unless this session actually recorded a\n * change to it. That check is the authorization: these routes read and write\n * whatever path they are handed, so the timeline is what bounds them to files\n * the session already touched.\n */\n const recordedVersions = async (filePath: string | undefined): Promise<FileEditVersion[] | undefined> => {\n if (filePath === undefined || filePath === '') return undefined;\n const versions = await timeline.versions(path.resolve(cwd, filePath));\n return versions.length === 0 ? undefined : versions;\n };\n\n app.get('/detail', async (context) => {\n const requested = context.req.query(PATH_QUERY_PARAM);\n const versions = await recordedVersions(requested);\n if (versions === undefined || requested === undefined) {\n return context.json({ error: 'This session recorded no changes to that file.' }, 404);\n }\n const filePath = path.resolve(cwd, requested);\n const working = await readWorking(filePath);\n const body: FileEditsDetailView = {\n path: filePath,\n relPath: cwd === '' ? filePath : path.relative(cwd, filePath),\n versions: await Promise.all(versions.map((version) => toVersionView(version, snapshots))),\n cumulative: await toCumulativeView(versions, working, snapshots),\n working,\n };\n return context.json(body);\n });\n\n /**\n * The file a request names, read only, for a file the timeline knows nothing\n * about: a path the agent read but never changed is still a path the reader\n * clicked, and refusing it would leave the link dead.\n *\n * The working directory is the boundary here, since the timeline is not.\n * Containment is checked lexically and again on the real path, so a symlink\n * inside the tree cannot hand out something beyond it, and a host that gave\n * these routes no working directory has no boundary to enforce and so serves\n * nothing.\n */\n app.get('/preview', async (context) => {\n const requested = context.req.query(PATH_QUERY_PARAM);\n if (requested === undefined || requested === '' || requested.includes('\\0')) {\n return context.json({ error: 'A preview names a path.' }, 400);\n }\n if (cwd === '') return context.json({ error: 'This session has no working directory to read from.' }, 403);\n const root = path.resolve(cwd);\n const filePath = path.resolve(root, requested);\n if (!isInside(root, filePath) || !(await isRealPathInside(root, filePath))) {\n return context.json({ error: 'The path leaves the session directory.' }, 403);\n }\n const body: FileEditsPreviewView = {\n path: filePath,\n relPath: path.relative(root, filePath),\n working: await readWorking(filePath),\n };\n return context.json(body);\n });\n\n app.put('/content', async (context) => {\n let request: FileEditsSaveRequest;\n try {\n request = (await context.req.json()) as FileEditsSaveRequest;\n } catch {\n return context.json({ error: 'The save body is not JSON.' }, 400);\n }\n if (typeof request.path !== 'string' || typeof request.content !== 'string') {\n return context.json({ error: 'A save names a path and the content to write.' }, 400);\n }\n if ((await recordedVersions(request.path)) === undefined) {\n return context.json({ error: 'This session recorded no changes to that file.' }, 404);\n }\n const filePath = path.resolve(cwd, request.path);\n const current = await readWorking(filePath);\n if (current.unavailable) {\n return context.json({ error: current.reason ?? 'The file cannot be read.' }, 409);\n }\n // The agent runs in the same working directory, so it can rewrite the file\n // while a reader is still editing it. Refusing on a moved hash is what\n // stops the save from silently discarding whatever it did.\n if (current.hash !== request.expectedHash) {\n return context.json({ error: 'The file changed since it was opened.', hash: current.hash }, 409);\n }\n await fs.writeFile(filePath, request.content, 'utf8');\n const body: FileEditsSaveView = { hash: hashOf(request.content) };\n return context.json(body);\n });\n\n app.delete('/content', async (context) => {\n const requested = context.req.query(PATH_QUERY_PARAM);\n if ((await recordedVersions(requested)) === undefined || requested === undefined) {\n return context.json({ error: 'This session recorded no changes to that file.' }, 404);\n }\n const filePath = path.resolve(cwd, requested);\n try {\n await fs.unlink(filePath);\n } catch (error) {\n // Already gone is the outcome the caller wanted, so it is not a failure.\n if (!hasCode(error, 'ENOENT')) {\n return context.json({ error: `The file could not be deleted: ${describe(error)}` }, 409);\n }\n }\n return context.body(null, 204);\n });\n\n return app;\n}\n\n/** The named export a host imports from this package's built entry. */\nexport const api: DoomApi = {\n basePath: API_BASE_PATH,\n start(context: DoomApiContext): DoomApiHandler {\n const app = createFileEditsApi({\n ...(context.sessionId === undefined ? {} : { sessionId: context.sessionId }),\n ...(context.cwd === undefined ? {} : { cwd: context.cwd }),\n });\n return {\n fetch: (request) => app.fetch(request),\n // Nothing outlives a request here: every route reads, answers and closes.\n close: () => undefined,\n };\n },\n};\n"],"mappings":"6bA2CA,MAAa,EAAoB,QAG3B,EAAmB,mFASnB,EAAiB,iFACjB,EAAmB,yDAYzB,SAAS,EAAO,EAAyB,CACvC,OAAA,EAAOA,EAAAA,WAAAA,CAAW,QAAQ,CAAC,CAAC,OAAO,EAAS,MAAM,CAAC,CAAC,OAAO,KAAK,CAClE,CAEA,SAAS,EAAQ,EAAgB,EAAuB,CACtD,OAAO,aAAiB,OAAS,SAAU,GAAS,EAAM,OAAS,CACrE,CAEA,SAAS,EAAS,EAAwB,CACxC,OAAO,aAAiB,MAAQ,EAAM,QAAU,OAAO,CAAK,CAC9D,CAGA,eAAe,EAAY,EAAiD,CAC1E,IAAI,EACJ,GAAI,CACF,EAAM,MAAMC,EAAAA,QAAG,SAAS,CAAQ,CAClC,MAAQ,CACN,MAAO,CAAE,QAAS,GAAI,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