@leolastforce/chalice-hashline-edit 0.0.0-stage → 4.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +153 -2
  3. package/index.ts +282 -0
  4. package/package.json +79 -4
  5. package/prompts/find-guidelines.md +2 -0
  6. package/prompts/find-snippet.md +1 -0
  7. package/prompts/find.md +1 -0
  8. package/prompts/grep-guidelines.md +2 -0
  9. package/prompts/grep-snippet.md +1 -0
  10. package/prompts/grep.md +1 -0
  11. package/prompts/insert-guidelines.md +1 -0
  12. package/prompts/insert-snippet.md +1 -0
  13. package/prompts/insert.md +1 -0
  14. package/prompts/read-guidelines.md +2 -0
  15. package/prompts/read-snippet.md +1 -0
  16. package/prompts/read.md +1 -0
  17. package/prompts/replace-guidelines.md +4 -0
  18. package/prompts/replace-snippet.md +1 -0
  19. package/prompts/replace.md +1 -0
  20. package/prompts/undo-last-change-guidelines.md +1 -0
  21. package/prompts/undo-last-change-snippet.md +1 -0
  22. package/prompts/undo-last-change.md +1 -0
  23. package/src/anchor-registry.ts +977 -0
  24. package/src/auto-read-all-state.ts +27 -0
  25. package/src/auto-read-all.ts +477 -0
  26. package/src/batch.ts +767 -0
  27. package/src/commit.ts +137 -0
  28. package/src/config-ui.ts +212 -0
  29. package/src/config.ts +235 -0
  30. package/src/constants.ts +26 -0
  31. package/src/edit-common.ts +206 -0
  32. package/src/file-kind.ts +191 -0
  33. package/src/file-reader.ts +135 -0
  34. package/src/find.ts +244 -0
  35. package/src/fs-write.ts +231 -0
  36. package/src/glob.ts +186 -0
  37. package/src/grep.ts +690 -0
  38. package/src/hash-store/cache.ts +18 -0
  39. package/src/hash-store/retry.ts +44 -0
  40. package/src/hash-store/validation.ts +62 -0
  41. package/src/hash-store.ts +609 -0
  42. package/src/hashline/alphabet.ts +21 -0
  43. package/src/hashline/anchor-table.json +1 -0
  44. package/src/hashline/apply.ts +297 -0
  45. package/src/hashline/hash.ts +119 -0
  46. package/src/hashline/hasher.ts +47 -0
  47. package/src/hashline/index.ts +50 -0
  48. package/src/hashline/parse.ts +84 -0
  49. package/src/hashline/resolve.ts +373 -0
  50. package/src/insert.ts +258 -0
  51. package/src/normalize.ts +27 -0
  52. package/src/paths.ts +56 -0
  53. package/src/payload-contract.ts +133 -0
  54. package/src/prompts.ts +13 -0
  55. package/src/read.ts +286 -0
  56. package/src/replace-diff.ts +610 -0
  57. package/src/replace-render.ts +390 -0
  58. package/src/replace-response.ts +166 -0
  59. package/src/replace-undo.ts +270 -0
  60. package/src/replace.ts +318 -0
  61. package/src/served.ts +36 -0
  62. package/src/utils.ts +387 -0
  63. package/src/validation.ts +45 -0
  64. package/src/write-hook.ts +53 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 RimuruW and Yugimob
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,154 @@
1
- # Temporary Holding Version
1
+ > This is a chalice package, check out github.com/leolastforce/Chalice
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ > This is a fork of original package pi-hashline-edit-pro (v4.4.0), with minor edits as of december 5th 2026. This is to gain control over version, apply changes easily, etc.. For the chalice ecosystem
4
+
5
+ > Text past here is generated docs:
6
+
7
+ # Hashline editing
8
+
9
+ Anchor-based file editing for Pi. Every line of a read is prefixed with a 4-character,
10
+ letters-only anchor (`Hasu│content`). Edits target those anchors instead of line numbers or fuzzy
11
+ text matches; stale or ambiguous anchors are rejected rather than guessed. Undo state is stored in
12
+ SQLite and survives restarts.
13
+
14
+ ## Install
15
+
16
+ ```bash
17
+ pi install npm:@leolastforce/chalice-hashline-edit
18
+ ```
19
+
20
+ Try it for one session, or from a source checkout:
21
+
22
+ ```bash
23
+ pi -e npm:@leolastforce/chalice-hashline-edit
24
+ pi -e ./Chalice/HashlineEditing # from the repo root
25
+ ```
26
+
27
+ Requirements: stock Pi (its `@earendil-works/*` packages and `typebox` are peers supplied by the
28
+ host), Node >= 22.19 for `node:sqlite`, and `rg` on `PATH` or in Pi's agent `bin/` directory.
29
+ `git` is optional and only improves auto-read-all discovery. npm installs the runtime dependencies
30
+ (`diff`, `file-type`, `xxhash-wasm`) with the package.
31
+
32
+ ## How it works
33
+
34
+ - `read` returns `anchor│content` rows. Page long files with `offset`/`limit`; images attach
35
+ visually, binary files and directories are rejected, and an empty file returns one empty row you
36
+ can replace to seed content.
37
+ - `replace` takes `remove_from`/`remove_to` as bare anchors and `replacement_lines` as one string
38
+ per line (`[]` deletes). `insert` adds lines before or after one anchor; the anchor line stays.
39
+ - Multiple `replace`/`insert` calls on the same file in one message form one batch with a single
40
+ combined diff and one undo entry. Overlapping ranges abort that file's batch unwritten.
41
+ - After an edit, the diff's `+anchor│` and ` anchor│` rows carry fresh anchors, so follow-up edits
42
+ do not need another read. Never anchor on `-anchor│` rows — those anchors were freed.
43
+ - Anchors are owned per session. `/clear-anchors` drops the claims; they are re-claimed on the next
44
+ read. A file with more lines than the anchor pool is rejected instead of being partially served.
45
+ - Pi's built-in `edit` tool is disabled at session start. With `anchorGrepEnabled`, built-in `grep`
46
+ is replaced by `anchor_grep`, whose hits already carry anchors for direct editing.
47
+ - `autoRead` (default on) appends fresh anchors after a `write`, and post-edit diffs after
48
+ `replace`, `insert` or `undo_last_change`, so the model keeps a current view of the file.
49
+
50
+ ## Tools
51
+
52
+ | Tool | Role |
53
+ |---|---|
54
+ | `read` | Read a text file as `anchor│content` rows; page with `offset`/`limit`. |
55
+ | `replace` | Replace a range of lines by two bare anchors; `[]` deletes, `[""]` is one blank line. |
56
+ | `insert` | Insert lines after or before one anchor line; one string per line, no `│` prefixes or embedded newlines. |
57
+ | `anchor_grep` | Ripgrep search returning `lineNumber │ anchor│content` hits usable directly in edits. Supports `literal`, `glob`, `context` and `limit`. |
58
+ | `find` | Glob-based path discovery; returns paths, not anchors — read a path before editing it. |
59
+ | `undo_last_change` | Revert the last `replace`/`insert` on a file, including BOM and line endings. Refuses with `[E_UNDO_STALE]` if the file changed since. |
60
+
61
+ Tool descriptions and their guideline bullets are loaded from `prompts/*.md`, so the model sees the
62
+ same rules documented here.
63
+
64
+ ## Commands
65
+
66
+ | Command | Effect |
67
+ |---|---|
68
+ | `/hashline-config` | Open the settings overlay: auto-read, auto-read all and its ignore list, diff context, anchor grep, require-path, strict input. Interactive mode only. |
69
+ | `/clear-anchors` | Clear this session's anchor claims; anchors are re-claimed on the next read. |
70
+
71
+ ## Configuration
72
+
73
+ Config lives outside Pi's `settings.json`, in
74
+ `$XDG_CONFIG_HOME/pi-hashline-edit-pro/config.json` (default `~/.config/pi-hashline-edit-pro/config.json`).
75
+ The same directory holds `hash-store.sqlite` (anchor/undo snapshots) and `sessions/` (anchor
76
+ claims). A corrupt config is renamed to `config.json.corrupt-*`, reset to defaults, and reported as
77
+ a warning at startup.
78
+
79
+ | Key | Default | Effect |
80
+ |---|---|---|
81
+ | `autoRead` | `true` | Attach anchors after `write` and post-edit diffs after edits. |
82
+ | `anchorGrepEnabled` | `true` | Use `anchor_grep` instead of Pi's built-in `grep`. |
83
+ | `autoReadAll` | `"off"` | `off`, `on`, or `git`. Attach project files with anchors on the first turn. |
84
+ | `autoReadAllIgnore` | `[]` | Extra folders, files or globs to skip, comma-separated. |
85
+ | `diffContextLines` | `1` | Surrounding lines in post-edit diffs; 0–10. |
86
+ | `requirePath` | `false` | Make `path` required in `replace`/`insert` instead of resolving files by anchor alone (useful in RPC mode). |
87
+ | `strictInput` | `false` | Reject auto-fixable input slips instead of fixing them with warnings. |
88
+
89
+ ```json
90
+ {
91
+ "autoRead": true,
92
+ "anchorGrepEnabled": true,
93
+ "autoReadAll": "git",
94
+ "autoReadAllIgnore": ["dist", "coverage"],
95
+ "diffContextLines": 2,
96
+ "requirePath": false,
97
+ "strictInput": false
98
+ }
99
+ ```
100
+
101
+ Changes made in `/hashline-config` apply immediately: edit tools are re-registered and the active
102
+ tool set is updated. Startup state is read once at `session_start`.
103
+
104
+ ## Auto-read all
105
+
106
+ Before the first agent turn, this mode attaches every non-ignored project file with live anchors in
107
+ one custom message (`hashline-auto-read-all`), once per session. `git` mode uses `git ls-files` and
108
+ attaches nothing outside a git repository; `on` falls back to `rg --files` and then a filesystem
109
+ walk. Discovery is capped at 500 files and 200 KB per file, with a total budget between 200 KB and
110
+ 2 MB derived from the model's context window. `E_AUTO_READ_ALL` on a read means the file is still
111
+ exactly as it was when attached.
112
+
113
+ ## Integration
114
+
115
+ The extension reacts to Pi's `session_start`, `session_shutdown`, `before_agent_start`,
116
+ `message_end`, `turn_end`, `tool_call` and `tool_result` events. It also answers the
117
+ `chalice:hashline-resolve-target` event on Pi's event bus, which lets another Chalice module resolve
118
+ an anchor target to a path without depending on this module's internals.
119
+
120
+ ## Known limitations
121
+
122
+ - `rg` must be on `PATH` or in Pi's agent `bin/`. The last fallback tries
123
+ `require.resolve("@earendil-works/pi-coding-agent/package.json")`, which Pi's `exports` map
124
+ blocks, so that path currently fails. Install ripgrep or let Pi download it to
125
+ `~/.pi/agent/bin/rg`.
126
+ - `undo_last_change` reverts only the last `replace`/`insert` per file; a `write` clears the undo
127
+ record, and an external change makes undo refuse with `[E_UNDO_STALE]`.
128
+ - There is no `/chalicesettings` section yet; configuration is `/hashline-config` or `config.json`.
129
+ - `node:sqlite` is still experimental on Node 22, so sessions print an ExperimentalWarning.
130
+
131
+ ## Source layout
132
+
133
+ | Path | Role |
134
+ |---|---|
135
+ | `index.ts` | Pi wiring, tool registration, session lifecycle, auto-read and batch handling. |
136
+ | `src/hashline/` | Anchor alphabet/table, hashing, parsing and stale-anchor resolution. |
137
+ | `src/hash-store*` | SQLite snapshots, retries, validation and the legacy JSON store migration. |
138
+ | `src/{read,replace,insert,grep,find,replace-undo}.ts` | The six tools. |
139
+ | `src/config*.ts` | Config file, locking and the settings overlay. |
140
+ | `src/auto-read-all*` | First-turn file discovery and injection. |
141
+ | `prompts/` | Tool descriptions, snippets and guideline bullets shown to the model. |
142
+
143
+ ## Development
144
+
145
+ From the repo root:
146
+
147
+ ```bash
148
+ ./distro/run-tui.sh # launch the distro with this module
149
+ node distro/harness.mjs # load every package alone and together
150
+ ```
151
+
152
+ ## License and attribution
153
+
154
+ MIT. Fork of `pi-hashline-edit-pro` 4.4.0; attribution is in [CREDITS.md](../../CREDITS.md).
package/index.ts ADDED
@@ -0,0 +1,282 @@
1
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+ import { DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES } from "@earendil-works/pi-coding-agent";
3
+ import { initHasher, lineChecksum } from "./src/hashline";
4
+ import { regReplace } from "./src/replace";
5
+ import { regInsert } from "./src/insert";
6
+ import { regGrep } from "./src/grep";
7
+ import { regFind } from "./src/find";
8
+ import { regUndo, clearUndo } from "./src/replace-undo";
9
+ import { regRead, fmtReadPreview } from "./src/read";
10
+ import { buildAutoReadAllInjection, autoReadAllBudget } from "./src/auto-read-all";
11
+ import { clearAutoReadAllComplete } from "./src/auto-read-all-state";
12
+ import type { RMetrics } from "./src/replace-response";
13
+ import type { ReplaceDetails } from "./src/replace";
14
+ import { extractWarnings } from "./src/replace-render";
15
+ import { MAX_HASH_LINES } from "./src/hashline";
16
+ import type { AutoReadAllMode } from "./src/config";
17
+ import {
18
+ readConfigWithStatus,
19
+ toggleAutoRead,
20
+ cycleAutoReadAllMode,
21
+ toggleAnchorGrep,
22
+ toggleRequirePath,
23
+ toggleStrictInput,
24
+ adjustDiffContextLines,
25
+ setAutoReadAllIgnoreFromText,
26
+ } from "./src/config";
27
+ import { loadHashStore, persistSnapshot, pruneMissing } from "./src/hash-store";
28
+ import { initRegistry, gcRegistrySidecars, clearRegistry, freeAnchors, sessionKeyFor, withAnchorSession, releaseRegistrySession } from "./src/anchor-registry";
29
+ import { serveRows } from "./src/served";
30
+ import { finalizeTurn, planAssistantMessage } from "./src/batch";
31
+ import { currentEditFlags, resolveEditTarget } from "./src/edit-common";
32
+ import { HashlineConfigOverlay } from "./src/config-ui";
33
+ import { registerWriteHook } from "./src/write-hook";
34
+ import { readNormFile } from "./src/file-reader";
35
+ import { loadFileKindAndText } from "./src/file-kind";
36
+ import { resolveInCwd } from "./src/fs-write";
37
+ import { valAccess } from "./src/validation";
38
+ import { splitLines } from "./src/utils";
39
+ import { AUTO_READ_ALL_CUSTOM_TYPE } from "./src/constants";
40
+
41
+ export default function (pi: ExtensionAPI): void {
42
+ pi.events.on("chalice:hashline-resolve-target", (value) => {
43
+ const request = value as { ctx: ExtensionContext; first: string; last?: string; respond: (result: Promise<string>) => void };
44
+ request.respond(withAnchorSession(request.ctx, () => resolveEditTarget(request.first, request.last)));
45
+ });
46
+
47
+ regRead(pi);
48
+
49
+ regReplace(pi);
50
+ regInsert(pi);
51
+ regGrep(pi);
52
+ regFind(pi);
53
+ regUndo(pi);
54
+ registerWriteHook(pi);
55
+
56
+ let autoRead = true;
57
+ let autoReadAll: AutoReadAllMode = "off";
58
+ let autoReadAllIgnore: string[] = [];
59
+ let autoReadAllInjected = false;
60
+ let grepWasActive = false;
61
+
62
+ async function refreshEditTools(): Promise<void> {
63
+ try {
64
+ const flags = await currentEditFlags();
65
+ regRead(pi, flags);
66
+ regReplace(pi, flags);
67
+ regInsert(pi, flags);
68
+ regUndo(pi, flags);
69
+ } catch (error) {
70
+ console.error("Failed to refresh edit tools:", error);
71
+ }
72
+ }
73
+
74
+ pi.on("session_start", async (_event, ctx) => withAnchorSession(ctx, async () => {
75
+ const active = pi.getActiveTools();
76
+ grepWasActive = active.includes("grep");
77
+ pi.setActiveTools(active.filter((t) => t !== "edit"));
78
+ await initHasher();
79
+ loadHashStore()
80
+ .then(async store => {
81
+ const missing = await pruneMissing(store);
82
+ for (const path of missing) freeAnchors(path);
83
+ })
84
+ .catch(err => {
85
+ console.error("Failed to load hash store:", err);
86
+ });
87
+ const sessionManager = (ctx as { sessionManager?: { getSessionFile?: () => string | undefined } }).sessionManager;
88
+ const sessionFile = sessionManager?.getSessionFile?.();
89
+ if (sessionKeyFor(ctx) === undefined) await initRegistry(sessionFile);
90
+ await gcRegistrySidecars();
91
+ const { config, corrupted } = await readConfigWithStatus();
92
+ if (corrupted && (ctx as { hasUI?: boolean }).hasUI) ctx.ui.notify("Hashline config was corrupt and was reset to defaults", "warning");
93
+ autoRead = config.autoRead;
94
+ autoReadAll = config.autoReadAll ?? "off";
95
+ autoReadAllIgnore = config.autoReadAllIgnore ?? [];
96
+ const sessionBranch = (ctx as { sessionManager?: { getBranch?: () => Array<{ type?: string; customType?: string }> } }).sessionManager?.getBranch?.() ?? [];
97
+ autoReadAllInjected = sessionBranch.some((entry) => entry.type === "custom_message" && entry.customType === AUTO_READ_ALL_CUSTOM_TYPE);
98
+ await refreshEditTools();
99
+ pi.setActiveTools(
100
+ pi.getActiveTools().filter((t) =>
101
+ config.anchorGrepEnabled ? t !== "grep" : t !== "anchor_grep",
102
+ ),
103
+ );
104
+ const debugValue = process.env.PI_HASHLINE_DEBUG;
105
+ if (debugValue === "1" || debugValue === "true") {
106
+ ctx.ui.notify(`Hashline Edit mode active`, "info");
107
+ }
108
+ }));
109
+
110
+ pi.on("session_shutdown", async (_event, ctx) => {
111
+ try {
112
+ const key = sessionKeyFor(ctx);
113
+ clearAutoReadAllComplete(key);
114
+ if (key !== undefined) releaseRegistrySession(key);
115
+ } catch (error) {
116
+ console.error("Failed to release anchor registry session:", error);
117
+ }
118
+ });
119
+
120
+ pi.on("before_agent_start", async (_event, ctx) => withAnchorSession(ctx, async () => {
121
+ if (autoReadAll === "off" || autoReadAllInjected) return;
122
+ autoReadAllInjected = true;
123
+ try {
124
+ const injection = await buildAutoReadAllInjection(ctx.cwd, autoReadAllBudget(ctx.model), autoReadAll, autoReadAllIgnore, sessionKeyFor(ctx));
125
+ if (!injection) return;
126
+ if (ctx.hasUI) ctx.ui.notify(`Auto-read all: attached ${injection.files} file(s) with anchors`, "info");
127
+ return { message: { customType: AUTO_READ_ALL_CUSTOM_TYPE, content: injection.text, display: false } };
128
+ } catch (error) {
129
+ console.error("Auto-read all failed:", error);
130
+ return;
131
+ }
132
+ }));
133
+
134
+ pi.registerCommand("hashline-config", {
135
+ description: "Open the hashline settings window (auto-read, auto-read all, ignore folders/files, diff context, grep, path, strict input)",
136
+ handler: async (_args, ctx) => {
137
+ if (!ctx.hasUI) {
138
+ ctx.ui.notify("/hashline-config requires interactive mode", "error");
139
+ return;
140
+ }
141
+ await ctx.ui.custom<void>(async (tui, theme, _keybindings, done) => {
142
+ const overlay = new HashlineConfigOverlay({
143
+ tui,
144
+ theme,
145
+ done,
146
+ onToggle: async (key, delta, value) => {
147
+ if (key === "autoRead") autoRead = await toggleAutoRead();
148
+ else if (key === "autoReadAll") { autoReadAll = await cycleAutoReadAllMode(); autoReadAllInjected = false; }
149
+ else if (key === "autoReadAllIgnore") autoReadAllIgnore = await setAutoReadAllIgnoreFromText(value ?? "");
150
+ else if (key === "diffContextLines") await adjustDiffContextLines(delta ?? 1);
151
+ else if (key === "anchorGrepEnabled") {
152
+ const enabled = await toggleAnchorGrep();
153
+ const active = pi.getActiveTools();
154
+ pi.setActiveTools(enabled ? [...new Set([...active.filter((t) => t !== "grep"), "anchor_grep"])] : [...new Set([...active.filter((t) => t !== "anchor_grep"), ...(grepWasActive ? ["grep"] : [])])]);
155
+ }
156
+ else if (key === "requirePath") await toggleRequirePath();
157
+ else if (key === "strictInput") await toggleStrictInput();
158
+ await refreshEditTools();
159
+ },
160
+ });
161
+ await overlay.load();
162
+ return overlay;
163
+ }, {
164
+ overlay: true,
165
+ overlayOptions: { anchor: "center", width: "90%", minWidth: 60, maxHeight: "90%" },
166
+ });
167
+ },
168
+ });
169
+
170
+ pi.registerCommand("clear-anchors", {
171
+ description: "Clear the session's anchor claims (path-free resolution state); anchors are re-claimed on the next read",
172
+ handler: async (_args, ctx) => withAnchorSession(ctx, async () => {
173
+ clearRegistry();
174
+ ctx.ui.notify(`Anchor claims cleared for this session`, "info");
175
+ }),
176
+ });
177
+ pi.on("message_end", async (event, ctx) => withAnchorSession(ctx, async () => {
178
+ try {
179
+ await planAssistantMessage(event.message, ctx.cwd);
180
+ } catch (error) {
181
+ console.error("Failed to plan edit batch:", error);
182
+ }
183
+ }));
184
+ pi.on("turn_end", async (event) => {
185
+ try {
186
+ const ids = (event.toolResults ?? []).map((result) => (result as { toolCallId?: unknown }).toolCallId).filter((id): id is string => typeof id === "string");
187
+ await finalizeTurn(ids);
188
+ } catch (error) {
189
+ console.error("Failed to finalize edit batch:", error);
190
+ }
191
+ });
192
+ pi.on("tool_result", async (event, ctx) => withAnchorSession(ctx, async () => {
193
+ if (event.isError) return;
194
+
195
+ if (event.toolName === "write") {
196
+ const writtenPath = (event.input as Record<string, unknown>)?.path;
197
+ let resolvedPath: string | undefined;
198
+ if (typeof writtenPath === "string") {
199
+ try {
200
+ resolvedPath = (await resolveInCwd(writtenPath, ctx.cwd)).resolved;
201
+ freeAnchors(resolvedPath);
202
+ await clearUndo(resolvedPath);
203
+ } catch (error) {
204
+ console.error("Failed to clear undo after write:", error);
205
+ }
206
+ }
207
+ if (!autoRead) return;
208
+ if (typeof writtenPath !== "string") return;
209
+ try {
210
+ resolvedPath ??= (await resolveInCwd(writtenPath, ctx.cwd)).resolved;
211
+ await valAccess(resolvedPath, writtenPath);
212
+ const file = await loadFileKindAndText(resolvedPath, { maxLines: MAX_HASH_LINES, displayPath: writtenPath });
213
+ if (file.kind !== "text") return;
214
+ const { normalized, fileHashes, absolutePath } = await readNormFile(
215
+ writtenPath, ctx.cwd, { maxLines: MAX_HASH_LINES, preloadedFile: file },
216
+ );
217
+ const preview = await fmtReadPreview(
218
+ normalized,
219
+ {},
220
+ fileHashes,
221
+ absolutePath,
222
+ DEFAULT_MAX_BYTES,
223
+ DEFAULT_MAX_LINES,
224
+ );
225
+ const fileLines = splitLines(normalized);
226
+ persistSnapshot(await loadHashStore(), absolutePath, normalized, fileHashes, fileLines.map(lineChecksum));
227
+ serveRows(absolutePath, fileHashes, fileLines, preview.servedHashes);
228
+ return {
229
+ content: [
230
+ ...(event.content ?? []),
231
+ { type: "text", text: `\n\n--- Auto-read (hashline anchors) ---\n${preview.text}` },
232
+ ],
233
+ };
234
+ } catch (error) {
235
+ console.error("Auto-read after write failed:", error);
236
+ const message = error instanceof Error ? error.message : String(error);
237
+ return {
238
+ content: [
239
+ ...(event.content ?? []),
240
+ { type: "text", text: `\n\n--- Auto-read failed: ${message} ---` },
241
+ ],
242
+ };
243
+ }
244
+ }
245
+
246
+ if (
247
+ event.toolName !== "replace" &&
248
+ event.toolName !== "insert" &&
249
+ event.toolName !== "undo_last_change"
250
+ ) return;
251
+ if (!autoRead) return;
252
+
253
+ const metrics = (event.details as { metrics?: RMetrics } | undefined)?.metrics;
254
+ if (metrics?.classification === "noop") return;
255
+
256
+ const batched = (event.details as { batch?: { last?: boolean } } | undefined)?.batch;
257
+ if (batched?.last === false) return;
258
+ const toolDetails = event.details as ReplaceDetails | undefined;
259
+ const diff = toolDetails?.diff;
260
+ const detailWarnings = Array.isArray(toolDetails?.warnings) ? toolDetails.warnings.filter((w): w is string => typeof w === "string") : [];
261
+ if (typeof diff !== "string") return;
262
+ const hasDiff = diff.length > 0;
263
+
264
+ const rendered = (event.content ?? [])
265
+ .filter(
266
+ (entry): entry is { type: "text"; text: string } =>
267
+ entry.type === "text" && typeof entry.text === "string",
268
+ )
269
+ .map((entry) => entry.text)
270
+ .join("\n");
271
+ const warnings = detailWarnings.length ? `Warnings:\n${detailWarnings.join("\n")}` : extractWarnings(rendered);
272
+ const hint = hasDiff ? (warnings ? `${diff}\n\n${warnings}` : diff) : warnings ? `[post-edit] applied successfully; the diff is empty (whitespace-only change).\n\n${warnings}` : "[post-edit] applied successfully; the diff is empty (whitespace-only change).";
273
+ return {
274
+ content: [
275
+ {
276
+ type: "text",
277
+ text: hint,
278
+ },
279
+ ],
280
+ };
281
+ }));
282
+ }
package/package.json CHANGED
@@ -1,6 +1,81 @@
1
1
  {
2
2
  "name": "@leolastforce/chalice-hashline-edit",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "4.4.0",
4
+ "type": "module",
5
+ "description": "[ORIGINAL EXTENSION: pi-hashline-edit-pro (v4.4.0)] Chalice module for anchor based edits",
6
+ "main": "index.ts",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/YuGiMob/pi-hashline-edit-pro.git"
10
+ },
11
+ "author": "pi-hashline-edit-pro contributors",
12
+ "keywords": [
13
+ "chalice",
14
+ "pi-package",
15
+ "pi",
16
+ "coding-agent",
17
+ "extension",
18
+ "hashline",
19
+ "hash-anchored",
20
+ "hash",
21
+ "anchors",
22
+ "read",
23
+ "replace",
24
+ "edit",
25
+ "undo",
26
+ "file-editing",
27
+ "stable"
28
+ ],
29
+ "license": "MIT",
30
+ "files": [
31
+ "index.ts",
32
+ "src",
33
+ "prompts",
34
+ "README.md",
35
+ "LICENSE"
36
+ ],
37
+ "pi": {
38
+ "extensions": [
39
+ "./index.ts"
40
+ ]
41
+ },
42
+ "dependencies": {
43
+ "diff": "^9.0.0",
44
+ "file-type": "^22.0.2",
45
+ "xxhash-wasm": "^1.1.0"
46
+ },
47
+ "publishConfig": {
48
+ "access": "public"
49
+ },
50
+ "peerDependencies": {
51
+ "@earendil-works/pi-coding-agent": ">=0.84.0",
52
+ "@earendil-works/pi-tui": "*",
53
+ "typebox": "*"
54
+ },
55
+ "engines": {
56
+ "node": ">=22.19.0"
57
+ },
58
+ "scripts": {
59
+ "test": "vitest run",
60
+ "test:unit": "vitest run --config vitest.unit.config.ts",
61
+ "test:watch": "vitest",
62
+ "test:coverage": "vitest run --coverage --coverage.thresholds.lines=90 --coverage.thresholds.statements=90 --coverage.thresholds.functions=85 --coverage.thresholds.branches=80",
63
+ "lint": "eslint \"src/**/*.ts\" \"index.ts\" \"test/**/*.ts\"",
64
+ "typecheck": "tsc --noEmit"
65
+ },
66
+ "devDependencies": {
67
+ "@earendil-works/pi-coding-agent": "^0.87.0",
68
+ "@eslint/js": "^10.0.1",
69
+ "@types/node": "^24",
70
+ "@vitest/coverage-v8": "^4.1.11",
71
+ "eslint": "^10.9.1",
72
+ "typescript": "^5.9.3",
73
+ "typescript-eslint": "^8.68.0",
74
+ "vitest": "^4.1.11"
75
+ },
76
+ "allowScripts": {
77
+ "@google/genai@1.52.0": true,
78
+ "koffi@2.16.2": true,
79
+ "protobufjs@7.6.4": true
80
+ }
81
+ }
@@ -0,0 +1,2 @@
1
+ - `find`: use it for path/name discovery when `anchor_grep` would only match content; `*` crosses directories, so anchor subtree patterns with `src/**/*.ts`.
2
+ - `find`: results are paths, not anchors. Call `read` on a path before editing it.
@@ -0,0 +1 @@
1
+ List files by glob when you know the name/shape but not the location; then read to get anchors
@@ -0,0 +1 @@
1
+ List files whose path matches a glob pattern, using ripgrep. Returns matching paths relative to the working directory, one per line, sorted. Respects `.gitignore`, always skips `.git`, and skips binary and image files silently. `*` crosses directories, so `*.ts` matches `src/a.ts`; use `src/**/*.spec.ts` to anchor to a subtree. Results are capped at `limit` (default 1000) and at 2000 rows or 50KB; raise `limit` or narrow `path` / `pattern` when truncated. After finding a path, read it to get hashline anchors for editing.
@@ -0,0 +1,2 @@
1
+ - `anchor_grep`: hits and `context` rows come back as `lineNumber │ anchor│content` — target them with `replace`/`insert` directly; `lineNumber` enables jump-to-line.
2
+ - `anchor_grep`: binary/image files are skipped silently.
@@ -0,0 +1 @@
1
+ Search with `lineNumber │ anchor│content` hits usable directly for `replace`/`insert`; use `literal`/`glob`/`context`
@@ -0,0 +1 @@
1
+ Search text files with ripgrep. Hits and context lines come back as `lineNumber │ anchor│content` rows, editable with replace or insert without a new read; the `=== path ===` header and line numbers locate the match. Searches respect `.gitignore`, always skip `.git`, and skip binary and image files silently. A match over 500 bytes is shown as a `...` fragment around the hit, but its anchor still covers the whole line. When cut by match limit, raise `limit` (default 100); when cut by rows/bytes, refine `pattern` / narrow path.
@@ -0,0 +1 @@
1
+
@@ -0,0 +1 @@
1
+ Insert `lines` after or before an anchor line: the anchor line stays, `lines` are bare without `│`, one per element
@@ -0,0 +1 @@
1
+ Insert lines after or before one existing line in a text file, addressed by a bare anchor from any served anchor│content row. The anchor line is preserved: `lines` go after it with `direction: "after"` or before it with `direction: "before"`, one string per line, no anchor prefixes, no embedded newlines. Inserted lines are written exactly as given; nothing else in the file changes. Multiple `replace`/`insert` calls on the same file in one message form one batch per file: earlier calls reply `In batch N` and the last call shows the combined diff, with one undo for the whole batch.
@@ -0,0 +1,2 @@
1
+ - `read`: call again after an edit when you need anchors you lack — post-edit diff `+anchor│`/` anchor│` rows and any served `anchor│content` rows already carry fresh anchors for the changed range.
2
+ - `read`: `E_AUTO_READ_ALL` on an attached file means its content is still exactly as it was when attached at the start of this session.
@@ -0,0 +1 @@
1
+ Read a file; each line returned as anchor│content
@@ -0,0 +1 @@
1
+ Read a text file and return it as `anchor│content` rows, one per line: a 4-character anchor (letters only), the `│` separator, then the line content. Target lines in replace and insert by anchor, never by content or line number. Page long files with `offset` and `limit`; when the output says truncated, continue with the hinted `offset/limit`. Images attach visually; binary, directory, and UTF-16/UTF-32 text are rejected; an empty file returns one empty row you can replace to seed content.
@@ -0,0 +1,4 @@
1
+ - `replace`: edit with `replace`/`insert`, not `sed -i` or heredocs — anchor edits are verified against what was shown and undoable.
2
+ - `replace`: `replacement_lines` `[""]` is one blank line; pasted `anchor│` prefixes are stripped automatically (single line: same anchor for `remove_from` and `remove_to`).
3
+ - `replace`: never anchor on `-anchor│` rows of the post-edit diff, those anchors were freed by the edit. Check each batch diff before the next turn's edits on that file.
4
+ - `replace`: same-file same-message batches must target disjoint ranges; an overlap or member failure aborts only that file's batch unwritten. Unresolvable calls stay solo and don't abort.
@@ -0,0 +1 @@
1
+ Replace lines by anchor: bare anchors in `remove_from`/`remove_to`, bare lines in `replacement_lines` without `│`, one edit per call
@@ -0,0 +1 @@
1
+ Replace a range of lines (or a single line) in a text file, targeted by 4-character anchors from any served anchor│content row. Give `remove_from` and `remove_to` as bare anchors marking the first and last line to remove, and `replacement_lines` as one string per new line with no anchor prefixes and no embedded newlines; `[]` deletes the range. Anchor follow-up edits on the `+anchor│` and ` anchor│` rows of the post-edit diff instead of re-reading. Multiple `replace`/`insert` calls on the same file in one message form one batch per file: earlier calls reply `In batch N` and the last call shows the combined diff, with one undo for the whole batch.
@@ -0,0 +1 @@
1
+ - `undo_last_change`: only the last `replace`/`insert` per file is undoable; a `write` clears it, so undo right after a bad diff — review the diff's `-anchor│` rows first to confirm what you're restoring.
@@ -0,0 +1 @@
1
+ Single-level undo: reverts a file's last `replace` or `insert`
@@ -0,0 +1 @@
1
+ Undo the last replace or insert on a file, restoring the previous content, BOM, and line endings. Use it when an edit removed or changed the wrong lines. If the file changed since that edit, the undo is refused with `[E_UNDO_STALE]` and nothing is modified: the record is kept, so verify the current state with read and stop instead of forcing the undo. A file deleted since the edit is restored. If the output says truncated, use read to see the full file.