dsh-better-edit 0.1.9 → 0.2.1

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 (58) hide show
  1. package/CHANGELOG.md +32 -0
  2. package/README.md +168 -52
  3. package/README.zh.md +122 -46
  4. package/assets/logo.svg +183 -18
  5. package/lib/contract.js +95 -0
  6. package/lib/drift.js +1 -1
  7. package/lib/edit-diff.js +2 -2
  8. package/lib/edit-engine.js +456 -0
  9. package/lib/edit-pipeline.js +41 -116
  10. package/lib/file-reader.js +1 -2
  11. package/lib/fs-bridge.js +2 -2
  12. package/lib/fs-write.js +3 -46
  13. package/lib/guidance.js +282 -0
  14. package/lib/hash-store.js +246 -13
  15. package/lib/hashline/apply.js +2 -2
  16. package/lib/hashline/hash.js +16 -206
  17. package/lib/hashline/index.js +4 -3
  18. package/lib/hashline/parse.js +1 -1
  19. package/lib/hashline/pure.js +213 -0
  20. package/lib/hashline/resolve.js +1 -5
  21. package/lib/hashline/served.js +2 -2
  22. package/lib/index.js +48 -32
  23. package/lib/paths.js +55 -1
  24. package/lib/prompts.js +53 -49
  25. package/lib/read-and-serve.js +46 -0
  26. package/lib/schema.js +1 -1
  27. package/lib/served-store.js +144 -183
  28. package/lib/tool-batch-edit.js +28 -280
  29. package/lib/tool-edit.js +37 -32
  30. package/lib/tool-read.js +8 -31
  31. package/lib/tool-undo.js +4 -13
  32. package/lib/types/contract.d.ts +39 -0
  33. package/lib/types/edit-engine.d.ts +179 -0
  34. package/lib/types/edit-pipeline.d.ts +10 -17
  35. package/lib/types/fs-write.d.ts +0 -1
  36. package/lib/types/guidance.d.ts +98 -0
  37. package/lib/types/hash-store.d.ts +73 -25
  38. package/lib/types/hashline/hash.d.ts +8 -13
  39. package/lib/types/hashline/index.d.ts +4 -3
  40. package/lib/types/hashline/pure.d.ts +26 -0
  41. package/lib/types/hashline/resolve.d.ts +0 -1
  42. package/lib/types/index.d.ts +4 -0
  43. package/lib/types/paths.d.ts +9 -0
  44. package/lib/types/prompts.d.ts +19 -9
  45. package/lib/types/read-and-serve.d.ts +39 -0
  46. package/lib/types/schema.d.ts +2 -16
  47. package/lib/types/served-store.d.ts +63 -32
  48. package/lib/types/tool-batch-edit.d.ts +4 -1
  49. package/lib/types/tool-undo.d.ts +1 -1
  50. package/lib/undo-edit.js +16 -1
  51. package/lib/write-hook.js +30 -50
  52. package/package.json +5 -3
  53. package/lib/served-state.js +0 -34
  54. package/lib/snapshot-store.js +0 -108
  55. package/lib/types/served-state.d.ts +0 -3
  56. package/lib/types/snapshot-store.d.ts +0 -14
  57. package/lib/types/undo-store.d.ts +0 -14
  58. package/lib/undo-store.js +0 -43
package/lib/paths.js CHANGED
@@ -1,6 +1,8 @@
1
1
  import { homedir } from "node:os";
2
- import { isAbsolute, resolve as resolvePath, join, dirname } from "node:path";
2
+ import { isAbsolute, resolve as resolvePath, join, dirname, parse, sep, } from "node:path";
3
+ import { lstat, readlink } from "node:fs/promises";
3
4
  import { resolveDshHome } from "@deepseek-ai/dsh-home-paths";
5
+ import { errCode } from "./utils.js";
4
6
  /**
5
7
  * On-disk home for dsh-better-edit state. Inside a tool call the store lives
6
8
  * co-located with the files being edited: `<workspace>/.dsh_better_edit/` (the
@@ -41,3 +43,55 @@ export function toCwd(filePath, cwd) {
41
43
  const expanded = expand(filePath);
42
44
  return isAbsolute(expanded) ? expanded : resolvePath(cwd, expanded);
43
45
  }
46
+ /**
47
+ * Canonicalize a path, resolving every symlink component to its target
48
+ * (loop-guarded, ELOOP on cycles). Non-existent final components resolve
49
+ * lexically — the canonical form of a not-yet-created file. The hashline
50
+ * tools key their state by canonical absolute paths, so the same file reached
51
+ * through different symlink spellings lands on the same store rows.
52
+ * @param path - the path to canonicalize (absolute or relative).
53
+ */
54
+ export async function resolveTarget(path) {
55
+ const absolutePath = resolvePath(path);
56
+ const { root } = parse(absolutePath);
57
+ const parts = absolutePath
58
+ .slice(root.length)
59
+ .split(sep)
60
+ .filter((part) => part.length > 0);
61
+ const visitedSymlinks = new Set();
62
+ async function resParts(currentPath, remainingParts) {
63
+ if (remainingParts.length === 0) {
64
+ return currentPath;
65
+ }
66
+ const [nextPart, ...tail] = remainingParts;
67
+ const candidatePath = join(currentPath, nextPart);
68
+ try {
69
+ const candidateStats = await lstat(candidatePath);
70
+ if (!candidateStats.isSymbolicLink()) {
71
+ return resParts(candidatePath, tail);
72
+ }
73
+ if (visitedSymlinks.has(candidatePath)) {
74
+ const error = new Error(`Too many symbolic links while resolving ${path}`);
75
+ error.code = "ELOOP";
76
+ throw error;
77
+ }
78
+ visitedSymlinks.add(candidatePath);
79
+ const linkTargetPath = resolvePath(dirname(candidatePath), await readlink(candidatePath));
80
+ const targetParts = linkTargetPath
81
+ .slice(parse(linkTargetPath).root.length)
82
+ .split(sep)
83
+ .filter((part) => part.length > 0);
84
+ return resParts(parse(linkTargetPath).root, [
85
+ ...targetParts,
86
+ ...tail,
87
+ ]);
88
+ }
89
+ catch (error) {
90
+ if (errCode(error) === "ENOENT") {
91
+ return join(candidatePath, ...tail);
92
+ }
93
+ throw error;
94
+ }
95
+ }
96
+ return resParts(root, parts);
97
+ }
package/lib/prompts.js CHANGED
@@ -1,54 +1,58 @@
1
1
  /**
2
2
  * Model-facing prompt text for the hashline tools, embedded so the bundle
3
- * ships no external prompt files. Each tool's description is short; the
4
- * `tool:*` system-prompt sections carry the full usage guidance the model
5
- * reads when the tools are presented.
3
+ * ships no external prompt files. Each tool's schema `description` is short;
4
+ * the `tool:*` system-prompt sections carry the brief guidance the model
5
+ * reads when the tools are presented. Guidance is uniform: a one-line opener
6
+ * followed by tight bullets.
6
7
  * @module dsh-better-edit/prompts
7
8
  */
8
- export const EDIT_DESCRIPTION = 'Edit a range of lines in a text file, targeted by the 3-char HASH anchors from read output. ' +
9
- 'remove_from and remove_to must each be a BARE 3-character hash: copy only the hash from the ' +
9
+ export const EDIT_DESCRIPTION = "Edit a range of lines in a text file, targeted by the 3-char HASH anchors from read output. " +
10
+ "remove_from and remove_to must each be a BARE 3-character hash: copy only the hash from the " +
10
11
  'leftmost column of a read row (row `ve7│function hello() {` means `"remove_from": "ve7"`). ' +
11
- 'Never pass the line content, a code line, or a paragraph into these fields.';
12
- export const EDIT_SNIPPET = 'Edit lines in a text file via bare 3-char HASH anchors from read — hash only, never line content; anchor exactly the lines that change; one edit per tool call';
13
- export const EDIT_GUIDELINES = [
14
- '`edit`: remove_from and remove_to take ONLY the bare 3-char hash — read row `ve7│function hello() {` means `"remove_from": "ve7"`. Never paste the line content, a code line, a paragraph, or the whole `HASH│content` row into these fields.',
15
- '`edit`: remove_from and remove_to mark the exact lines that are REMOVED, and replacement_text is their complete replacement applied in order; nothing outside the range changes. Every line inside the range that is not reproduced byte-exact in replacement_text is deleted from the file.',
16
- '`edit`: keep the range as tight as the change — anchor only the first and last line that actually change, never a whole function, class, or import block when only part of it changes.',
17
- '`edit`: to edit a single line, set both remove_from and remove_to to the same hash: remove_from: "<HASH>", remove_to: "<HASH>".',
18
- '`edit`: when copying a line from read output, remove its HASH│ prefix and keep the leading whitespace exactly as shown.',
19
- '`edit`: every `\\n` in replacement_text separates lines, so a trailing `\\n` adds a final empty line. Mirror the removed lines exactly: a range that ends on a blank line must end replacement_text with `\\n` (e.g. `"code\\n"`), and a replacement whose last line is not blank must not end with `\\n`. To add a blank line after a line, end replacement_text with an explicit empty line after it (e.g. `"X\\n"` adds a blank after X). A replacement that is only blank lines is written as one `\\n` per blank line.',
20
- '`edit`: when the tool shows the post-edit diff, its rows are the fresh anchors for the new file — `+HASH│` and ` HASH│` rows carry current hashes and unchanged lines keep their previous hashes, so you can anchor follow-up edits on the diff.',
21
- '`edit`: the tool verifies every line of your range against what it served you. If the file changed since it was served, or a line was never served, the edit is hard-rejected — `[E_RANGE_STALE]` or `[E_RANGE_UNSERVED]` names the first offending line and echoes the current range as fresh `HASH│content` rows. Copy remove_from/remove_to from those echoed rows and retry — the rows count as serves.',
22
- '`edit`: only rows the tool delivered count as serves — read output, post-edit diffs, and rejection echoes. Content you saw through bash or another channel is not served state; a range over it is rejected as never-served or unverifiable, and there is no way to waive that check.',
23
- '`edit`: do not issue multiple edit calls on the same file in one message. Use `batch_edit` for multiple edits — it validates every edit before writing anything, applies the whole batch all-or-nothing, and returns one combined diff per file.',
24
- ];
25
- export const READ_DESCRIPTION = 'Read a text file; each line returned as HASH│content with a 3-char alphanumeric hash. ' +
26
- 'No line numbers — use the HASH as the anchor in edit calls. Binary/directory → rejected; ' +
27
- 'empty → HASH│ (edit to insert); pageable with offset/limit; BOM stripped; non-UTF-8 shown as U+FFFD.';
28
- export const READ_SNIPPET = 'Read a file; each line returned as HASH│content';
29
- export const READ_GUIDELINES = [
30
- '`read`: call only when you need information the tool never served you — a page you never saw, content past the post-edit diff. `edit` verifies every line of your range against what the tool served; a rejection echoes the current range as fresh `HASH│content` rows to retry on.',
31
- '`read`: the post-edit diff rows from edit/undo and the drift-notice rows also carry fresh anchors for the lines they show.',
32
- ];
33
- export const BATCH_EDIT_DESCRIPTION = 'Apply several edits in one atomic call. Each item is exactly like the edit tool: ' +
34
- '{ path?, remove_from, remove_to, replacement_text }, where remove_from and remove_to are ' +
35
- 'bare 3-char hashes from read or diff output. Items targeting the same file are applied in order. ' +
36
- 'Every item is verified against what the tool served you before ANYTHING is written: if any item ' +
37
- 'fails — stale or ambiguous anchor, changed range interior, never-served line — the whole batch ' +
38
- 'is rejected and no file changes. The failing item\u2019s current range is served back as fresh ' +
39
- 'HASH│content rows so you can retry without a read. Use batch_edit whenever you have multiple ' +
40
- 'edits; do not issue several edit calls in one message.';
41
- export const BATCH_EDIT_GUIDELINES = [
42
- 'batch_edit: each item takes the same fields as edit — { path?, remove_from, remove_to, replacement_text }. remove_from and remove_to take ONLY the bare 3-char hash from read/diff output; never the line content.',
43
- 'batch_edit: items are applied in order. Edits to the same file must not overlap — an item whose range was changed by an earlier item in the batch is rejected.',
44
- 'batch_edit: the whole batch is all-or-nothing. If any item fails validation, nothing is written anywhere; the failing item\u2019s current range is echoed as fresh HASH│content rows that count as serves.',
45
- 'batch_edit: every item is verified against what the tool served you — stale anchors, changed interiors, or never-served lines reject the batch.',
46
- 'batch_edit: a noop item (the range already contains the replacement text) is reported without failing the batch; an all-noop batch reports no changes.',
47
- 'batch_edit: the result is one combined diff per file with fresh anchors — anchor follow-up edits on those rows without re-reading.',
48
- ];
49
- export const UNDO_DESCRIPTION = 'Undo the last edit on a file, reverting it to its previous state. Use when an edit produced ' +
50
- 'incorrect results (e.g., wrong content, duplicated lines, broken syntax).';
51
- export const UNDO_GUIDELINES = [
52
- '`undo_last_edit`: reverts only the most recent edit on the file — any write to the file clears the undo history, so call it immediately after a bad edit. An edit is bad when its post-edit diff shows `-HASH│` rows for lines you meant to keep (a closing brace, import, or declaration).',
53
- '`undo_last_edit`: when the tool shows the post-edit diff, its `+HASH│` and ` HASH│` rows are the fresh anchors for the restored file, so follow-up edits can anchor on the diff.',
54
- ];
12
+ "Never pass the line content, a code line, or a paragraph into these fields.";
13
+ export const EDIT_GUIDANCE = {
14
+ intro: "Edit a range of lines via a bare 3-char HASH anchor from read output — never by line content.",
15
+ lines: [
16
+ "`edit`: anchor the exact first and last lines that change by their stripped hash (`ve7`, not `ve7│function…`). A single line uses the same hash in both fields; never anchor a whole function or import block when part of it changes.",
17
+ "`edit`: replacement_text is byte-exact for the whole range — every line inside it you do not reproduce byte-exact is deleted, and leading whitespace is preserved exactly.",
18
+ "`edit`: `\\n` is a line break, so a range ending on a blank line must end replacement_text with `\\n` and a non-blank last line must not; a blank-line run is one `\\n` per blank line.",
19
+ "`edit`: the post-edit diff rows carry fresh anchors for follow-ups. A stale or never-served range is hard-rejected (`[E_RANGE_STALE]` / `[E_RANGE_UNSERVED]`); copy the echoed rows and retry — only tool-served rows count.",
20
+ "`edit`: for multiple edits to one file, use batch_edit — it validates every item before writing and applies them all-or-nothing.",
21
+ ],
22
+ };
23
+ export const READ_DESCRIPTION = "Read a text file; each line returned as HASH│content with a 3-char alphanumeric hash. " +
24
+ "No line numbers — use the HASH as the anchor in edit calls. Binary/directory → rejected; " +
25
+ "empty → HASH│ (edit to insert); pageable with offset/limit; BOM stripped; non-UTF-8 shown as U+FFFD.";
26
+ export const READ_GUIDANCE = {
27
+ intro: "Use read, not shell commands, to inspect text files and obtain the HASH anchors the editing tools require.",
28
+ lines: [
29
+ "`read`: call it only for content the tools have not served — a page you never saw, or lines past the post-edit diff.",
30
+ "`read`: each row is `HASH│content`; the HASH is the anchor (no line numbers). Rejection echoes return fresh rows that count as serves.",
31
+ "`read`: binary/directory rejects; page large files with offset/limit.",
32
+ ],
33
+ };
34
+ export const BATCH_EDIT_DESCRIPTION = "Apply several edits in one atomic call. Each item is exactly like the edit tool: " +
35
+ "{ path?, remove_from, remove_to, replacement_text }, where remove_from and remove_to are " +
36
+ "bare 3-char hashes from read or diff output. Items targeting the same file are applied in order. " +
37
+ "Every item is verified against what the tool served you before ANYTHING is written: if any item " +
38
+ "fails — stale or ambiguous anchor, changed range interior, never-served line — the whole batch " +
39
+ "is rejected and no file changes. The failing item\u2019s current range is served back as fresh " +
40
+ "HASH│content rows so you can retry without a read. Use batch_edit whenever you have multiple " +
41
+ "edits; do not issue several edit calls in one message.";
42
+ export const BATCH_EDIT_GUIDANCE = {
43
+ intro: "Apply several edits in one atomic call.",
44
+ lines: [
45
+ "`batch_edit`: each item is edit\u2019s shape — { path?, remove_from, remove_to, replacement_text } — with bare hash anchors; items apply in order, and same-file ranges must not overlap.",
46
+ "`batch_edit`: all-or-nothing — any failing item writes nothing anywhere and echoes its current range as fresh rows that count as serves.",
47
+ "`batch_edit`: a no-op item is reported without failing; the result is one combined diff per file with fresh anchors.",
48
+ ],
49
+ };
50
+ export const UNDO_DESCRIPTION = "Undo the last edit on a file, reverting it to its previous state. Use when an edit produced " +
51
+ "incorrect results (e.g., wrong content, duplicated lines, broken syntax).";
52
+ export const UNDO_GUIDANCE = {
53
+ intro: "Revert the last edit on a file.",
54
+ lines: [
55
+ "`undo_last_edit`: reverts only the most recent edit — any write clears history, so call it immediately after a bad edit.",
56
+ "`undo_last_edit`: the restored diff\u2019s `+HASH│` and ` HASH│` rows are fresh anchors for follow-up edits.",
57
+ ],
58
+ };
@@ -0,0 +1,46 @@
1
+ /**
2
+ * The shared read-and-serve operation: resolve → read → normalize → render
3
+ * the hashline preview → record the served rows → clear the drift marks →
4
+ * append the UTF-8 rewrite note. Used by the `read` tool and by the write
5
+ * auto-read hook, so the model is always shown fresh anchors the same way no
6
+ * matter which tool produced the read.
7
+ * @module dsh-better-edit/read-and-serve
8
+ */
9
+ import { abortIf } from "./utils.js";
10
+ import { normFromText } from "./file-reader.js";
11
+ import { fmtReadPreview, MAX_HASH_LINES } from "./read-render.js";
12
+ import { recordServed, clearDriftReported } from "./served-store.js";
13
+ /** Appended when the file had non-UTF-8 bytes; editing rewrites it as UTF-8. */
14
+ export const UTF8_REWRITE_NOTE = "[Non-UTF-8 bytes shown as U+FFFD; editing rewrites the file as UTF-8.]";
15
+ /**
16
+ * Perform one read-and-serve: normalize the file at `rawPath`, render its
17
+ * hashline preview, record the shown rows as served for the session, and clear
18
+ * the reported-drift marks (a fresh read resets them). The returned text
19
+ * carries the UTF-8 rewrite note when the file had decode errors.
20
+ *
21
+ * Emits nothing on the fs-observation gate — callers that need the
22
+ * observation recorded (the `read` tool) do that themselves with their exec
23
+ * context.
24
+ */
25
+ export async function readAndServe(io, rawPath, cwd, options) {
26
+ const { sessionKey, signal } = options;
27
+ abortIf(signal);
28
+ const absolutePath = await io.resolve(rawPath, cwd, signal);
29
+ const rawText = await io.readText(absolutePath, signal);
30
+ const { normalized, fileHashes, hadUtf8DecodeErrors } = await normFromText({
31
+ absolutePath,
32
+ rawText,
33
+ displayPath: rawPath,
34
+ signal,
35
+ maxLines: MAX_HASH_LINES,
36
+ });
37
+ const preview = await fmtReadPreview(normalized, { offset: options.offset, limit: options.limit }, fileHashes, absolutePath);
38
+ if (preview.served.length > 0) {
39
+ await recordServed(sessionKey, absolutePath, preview.served, fileHashes.length);
40
+ }
41
+ await clearDriftReported(sessionKey, absolutePath);
42
+ const text = hadUtf8DecodeErrors
43
+ ? `${preview.text}\n\n${UTF8_REWRITE_NOTE}`
44
+ : preview.text;
45
+ return { text, served: preview.served, hadUtf8DecodeErrors, absolutePath };
46
+ }
package/lib/schema.js CHANGED
@@ -3,7 +3,7 @@
3
3
  * the dsh schema DSL (not TypeBox). `path` is deliberately NOT `required` at
4
4
  * the schema level: the tools accept the built-in `file_path` spelling too
5
5
  * (the implicit parameter root stays open), and enforce path presence in
6
- * `assertReq` after `normalizeFilePath` aliasing.
6
+ * `assertEditRequest` after `normalizeFilePath` aliasing.
7
7
  * @module dsh-better-edit/schema
8
8
  */
9
9
  export const replacementTextSchema = {
@@ -1,3 +1,19 @@
1
+ /**
2
+ * Served state — what the model has been shown, per session and path.
3
+ *
4
+ * This is the ONE module that owns the served-state concept: the served-row
5
+ * merge invariant, the reported-drift set, and the position-reconstruction
6
+ * math used by drift notices. Persistence goes through the hash store's
7
+ * served domain API (`hash-store.ts`); the reject-and-serve errors and range
8
+ * verification live with the hashline module (`hashline/served.ts`); drift
9
+ * computation lives in `drift.ts`. Both import from here.
10
+ *
11
+ * The API is async-only: every operation loads the per-workspace hash store
12
+ * and resolves it through the active workspace context. There is deliberately
13
+ * no sync half — the two-vocabulary, every-op-twice surface it produced is
14
+ * gone.
15
+ * @module dsh-better-edit/served-store
16
+ */
1
17
  import { randomUUID } from "node:crypto";
2
18
  import { HASH_RE } from "./hashline/alphabet.js";
3
19
  import { loadHashStore, withStore } from "./hash-store.js";
@@ -13,246 +29,191 @@ export function sessionKeyFor(sessionId) {
13
29
  fallbackSessionKey ??= randomUUID();
14
30
  return fallbackSessionKey;
15
31
  }
16
- function isValidServedList(value) {
17
- if (!Array.isArray(value))
18
- return false;
19
- for (const entry of value) {
20
- if (entry === null)
21
- continue;
22
- if (typeof entry !== "string" || !HASH_RE.test(entry))
23
- return false;
24
- }
25
- return true;
26
- }
27
- export function getServed(store, sessionKey, path) {
28
- const row = store.stmts.servedGet(sessionKey, path);
29
- if (!row)
30
- return [];
31
- try {
32
- const parsed = JSON.parse(row.hashes);
33
- if (isValidServedList(parsed))
34
- return parsed;
35
- store.stmts.servedDelete(sessionKey, path);
36
- return [];
37
- }
38
- catch {
39
- store.stmts.servedDelete(sessionKey, path);
40
- return [];
41
- }
42
- }
43
- export function upsertServed(store, sessionKey, path, entries) {
44
- if (entries.length === 0)
45
- return;
46
- withStore(() => {
47
- const updated = getServed(store, sessionKey, path).slice();
48
- for (const entry of entries) {
49
- if (!Number.isInteger(entry.position) || entry.position < 0) {
50
- throw new TypeError(`Invalid served position: ${entry.position}`);
51
- }
52
- if (entry.hash !== null &&
53
- (typeof entry.hash !== "string" || !HASH_RE.test(entry.hash))) {
54
- throw new TypeError(`Invalid served hash: ${String(entry.hash)}`);
55
- }
56
- while (updated.length <= entry.position)
57
- updated.push(null);
58
- updated[entry.position] = entry.hash;
59
- }
60
- while (updated.length > 0 && updated[updated.length - 1] === null)
61
- updated.pop();
62
- store.stmts.servedUpsert(sessionKey, path, JSON.stringify(updated), Date.now());
63
- });
64
- }
65
- export function recordServes(store, sessionKey, path, rows, lineCount) {
66
- if (rows.length === 0)
67
- return;
68
- try {
69
- if (lineCount === undefined) {
70
- upsertServed(store, sessionKey, path, rows);
71
- return;
72
- }
73
- // A serve of the CURRENT file state must never leave hashes at
74
- // positions beyond the file's line count: a stale tail would hold a
75
- // surviving line's hash at its OLD position while the new serve holds
76
- // it at its current one, and the duplicate makes every later edit on
77
- // that line fail E_RANGE_UNVERIFIED ("served at N positions").
78
- withStore(() => {
79
- const updated = getServed(store, sessionKey, path).slice();
80
- if (updated.length > lineCount)
81
- updated.length = lineCount;
82
- for (const entry of rows) {
83
- if (!Number.isInteger(entry.position) || entry.position < 0) {
84
- throw new TypeError(`Invalid served position: ${entry.position}`);
85
- }
86
- if (entry.hash !== null &&
87
- (typeof entry.hash !== "string" || !HASH_RE.test(entry.hash))) {
88
- throw new TypeError(`Invalid served hash: ${String(entry.hash)}`);
89
- }
90
- while (updated.length <= entry.position)
91
- updated.push(null);
92
- updated[entry.position] = entry.hash;
93
- }
94
- while (updated.length > 0 && updated[updated.length - 1] === null)
95
- updated.pop();
96
- store.stmts.servedUpsert(sessionKey, path, JSON.stringify(updated), Date.now());
97
- });
98
- }
99
- catch (error) {
100
- console.error("Failed to record served rows:", error);
101
- }
102
- }
103
32
  /**
104
- * Record post-mutation diff serves against the file's CURRENT length. Before
105
- * upserting the diff rows, positions beyond `lineCount` are dropped from the
106
- * stored array: after an edit/undo the file has a new shape, and a hash that
107
- * survived into the diff must not keep its pre-edit position claim — that
108
- * stale claim is what makes a chained edit's boundary anchor look ambiguous
109
- * (`E_RANGE_UNVERIFIED`) instead of verifying cleanly.
110
- * @param store - open hash store.
111
- * @param sessionKey - the session whose served rows are being updated.
112
- * @param path - canonical absolute path.
113
- * @param rows - diff rows (position → post-mutation hash) to record.
114
- * @param lineCount - the file's line count AFTER the mutation.
33
+ * Merge served rows into a copy of the stored array. This single helper owns
34
+ * the served-merge invariant shared by {@link recordServed} and
35
+ * {@link recordServedTruncated}:
36
+ *
37
+ * - positions are validated before anything is written (invalid rows throw
38
+ * and never reach the store);
39
+ * - when `truncateTo` is given, positions beyond the file's line count are
40
+ * dropped FIRST — a serve of the current file state must never leave a hash
41
+ * at an old position beyond the line count, because that stale claim makes
42
+ * a chained edit's boundary anchor look ambiguous (`E_RANGE_UNVERIFIED`,
43
+ * "served at N positions") instead of verifying cleanly;
44
+ * - when `clearFrom` is given, positions at/after the mutation's first
45
+ * changed line are re-shaped by the edit, so the model's previous view of
46
+ * them is cleared before the diff rows land;
47
+ * - trailing never-served markers are trimmed so an empty tail never grows
48
+ * the stored array.
49
+ *
50
+ * Underscore-prefixed: internal, exported only so the invariant has a direct
51
+ * test seam.
115
52
  */
116
- export function recordServesTruncated(store, sessionKey, path, rows, lineCount, clearFrom = 0) {
117
- if (rows.length === 0)
118
- return;
119
- try {
120
- withStore(() => {
121
- const updated = getServed(store, sessionKey, path).slice();
122
- if (updated.length > lineCount)
123
- updated.length = lineCount;
124
- // Positions at/after the mutation's first changed line are
125
- // re-shaped by the edit: the model's previous view of them no
126
- // longer holds (line positions shift, and only the diff window
127
- // below is what it now saw). Clear them so a stale hash never
128
- // makes a boundary anchor look ambiguous; the unchanged prefix
129
- // before the edit keeps its claims (same content, same position).
130
- for (let i = clearFrom; i < updated.length; i++)
131
- updated[i] = null;
132
- for (const entry of rows) {
133
- if (!Number.isInteger(entry.position) || entry.position < 0) {
134
- throw new TypeError(`Invalid served position: ${entry.position}`);
135
- }
136
- if (entry.hash !== null &&
137
- (typeof entry.hash !== 'string' || !HASH_RE.test(entry.hash))) {
138
- throw new TypeError(`Invalid served hash: ${String(entry.hash)}`);
139
- }
140
- while (updated.length <= entry.position)
141
- updated.push(null);
142
- updated[entry.position] = entry.hash;
143
- }
144
- while (updated.length > 0 && updated[updated.length - 1] === null)
145
- updated.pop();
146
- store.stmts.servedUpsert(sessionKey, path, JSON.stringify(updated), Date.now());
147
- });
148
- }
149
- catch (error) {
150
- console.error('Failed to record truncated served rows:', error);
151
- }
152
- }
153
- export function getReported(store, sessionKey, path) {
154
- const row = store.stmts.servedGet(sessionKey, path);
155
- if (!row)
156
- return new Set();
157
- const raw = row.reported;
158
- if (typeof raw !== "string" || raw.length === 0)
159
- return new Set();
160
- try {
161
- const parsed = JSON.parse(raw);
162
- if (!Array.isArray(parsed))
163
- return new Set();
164
- return new Set(parsed.filter((h) => typeof h === "string" && HASH_RE.test(h)));
165
- }
166
- catch {
167
- return new Set();
53
+ export function _mergeServedRows(current, rows, options) {
54
+ const updated = current.slice();
55
+ if (options?.truncateTo !== undefined &&
56
+ updated.length > options.truncateTo) {
57
+ updated.length = options.truncateTo;
58
+ }
59
+ if (options?.clearFrom !== undefined) {
60
+ for (let i = options.clearFrom; i < updated.length; i++)
61
+ updated[i] = null;
62
+ }
63
+ for (const entry of rows) {
64
+ if (!Number.isInteger(entry.position) || entry.position < 0) {
65
+ throw new TypeError(`Invalid served position: ${entry.position}`);
66
+ }
67
+ if (entry.hash !== null &&
68
+ (typeof entry.hash !== "string" || !HASH_RE.test(entry.hash))) {
69
+ throw new TypeError(`Invalid served hash: ${String(entry.hash)}`);
70
+ }
71
+ while (updated.length <= entry.position)
72
+ updated.push(null);
73
+ updated[entry.position] = entry.hash;
168
74
  }
75
+ while (updated.length > 0 && updated[updated.length - 1] === null)
76
+ updated.pop();
77
+ return updated;
169
78
  }
170
- export function addReported(store, sessionKey, path, hashes) {
171
- const valid = hashes.filter((hash) => HASH_RE.test(hash));
172
- if (valid.length === 0)
173
- return;
174
- withStore(() => {
175
- const current = getReported(store, sessionKey, path);
176
- for (const hash of valid)
177
- current.add(hash);
178
- store.stmts.servedReportedUpsert(sessionKey, path, JSON.stringify([...current]), Date.now());
179
- });
180
- }
181
- export function clearReported(store, sessionKey, path) {
182
- withStore(() => {
183
- store.stmts.servedReportedClear(sessionKey, Date.now(), path);
184
- });
185
- }
186
- export function deleteServed(store, sessionKey, path) {
187
- store.stmts.servedDelete(sessionKey, path);
188
- }
189
- export function wipeServed(store, sessionKey) {
190
- store.stmts.servedWipe(sessionKey);
191
- }
79
+ /** The served array for one session+path, or `[]` when nothing was served. */
192
80
  export async function loadServed(sessionKey, path) {
193
81
  const store = await loadHashStore();
194
- return getServed(store, sessionKey, path);
82
+ return store.getServed(sessionKey, path);
195
83
  }
84
+ /**
85
+ * Record served rows for one session+path. Without `lineCount` the rows merge
86
+ * into the stored array as-is; with it, the stored array is truncated to the
87
+ * file's current line count before the rows land (see
88
+ * {@link _mergeServedRows} for why). Failures are logged, never thrown — a
89
+ * store problem must not fail the read that produced these rows.
90
+ */
196
91
  export async function recordServed(sessionKey, path, rows, lineCount) {
197
92
  if (rows.length === 0)
198
93
  return;
199
94
  try {
200
95
  const store = await loadHashStore();
201
- recordServes(store, sessionKey, path, rows, lineCount);
96
+ withStore(() => {
97
+ const current = store.getServed(sessionKey, path);
98
+ const updated = _mergeServedRows(current, rows, lineCount === undefined ? undefined : { truncateTo: lineCount });
99
+ store.upsertServed(sessionKey, path, JSON.stringify(updated));
100
+ });
202
101
  }
203
102
  catch (error) {
204
- console.error('Failed to record served rows:', error);
103
+ console.error("Failed to record served rows:", error);
205
104
  }
206
105
  }
207
106
  /**
208
- * Async sibling of {@link recordServesTruncated}: record post-mutation diff
209
- * rows against the file's current line count.
107
+ * Record post-mutation diff serves against the file's CURRENT length. The
108
+ * stored array is truncated to `lineCount` and cleared from `clearFrom`
109
+ * (the edit's first changed line) before the diff rows land, so a hash that
110
+ * survived into the diff never keeps its pre-edit position claim.
210
111
  */
211
112
  export async function recordServedTruncated(sessionKey, path, rows, lineCount, clearFrom = 0) {
212
113
  if (rows.length === 0)
213
114
  return;
214
115
  try {
215
116
  const store = await loadHashStore();
216
- recordServesTruncated(store, sessionKey, path, rows, lineCount, clearFrom);
117
+ withStore(() => {
118
+ const current = store.getServed(sessionKey, path);
119
+ const updated = _mergeServedRows(current, rows, {
120
+ truncateTo: lineCount,
121
+ clearFrom,
122
+ });
123
+ store.upsertServed(sessionKey, path, JSON.stringify(updated));
124
+ });
217
125
  }
218
126
  catch (error) {
219
- console.error('Failed to record truncated served rows:', error);
127
+ console.error("Failed to record truncated served rows:", error);
220
128
  }
221
129
  }
130
+ /** The hashes already reported as drifted for one session+path. */
222
131
  export async function driftReported(sessionKey, path) {
223
132
  try {
224
133
  const store = await loadHashStore();
225
- return getReported(store, sessionKey, path);
134
+ return store.getServedReported(sessionKey, path);
226
135
  }
227
136
  catch (error) {
228
137
  console.error("Failed to load reported drift set:", error);
229
138
  return new Set();
230
139
  }
231
140
  }
141
+ /** Mark hashes as already reported as drifted, so later notices skip them. */
232
142
  export async function markDriftReported(sessionKey, path, hashes) {
233
143
  try {
144
+ const valid = hashes.filter((hash) => HASH_RE.test(hash));
145
+ if (valid.length === 0)
146
+ return;
234
147
  const store = await loadHashStore();
235
- addReported(store, sessionKey, path, hashes);
148
+ withStore(() => {
149
+ const current = store.getServedReported(sessionKey, path);
150
+ for (const hash of valid)
151
+ current.add(hash);
152
+ store.upsertServedReported(sessionKey, path, JSON.stringify([...current]));
153
+ });
236
154
  }
237
155
  catch (error) {
238
156
  console.error("Failed to record reported drift set:", error);
239
157
  }
240
158
  }
159
+ /** Clear the reported-drift set for one session+path (a fresh read resets it). */
241
160
  export async function clearDriftReported(sessionKey, path) {
242
161
  try {
243
162
  const store = await loadHashStore();
244
- clearReported(store, sessionKey, path);
163
+ withStore(() => {
164
+ store.clearServedReported(sessionKey, path);
165
+ });
245
166
  }
246
167
  catch (error) {
247
168
  console.error("Failed to clear reported drift set:", error);
248
169
  }
249
170
  }
171
+ /** Drop every served row and reported-drift mark for one session. */
250
172
  export async function wipeServedState(sessionKey) {
251
173
  try {
252
174
  const store = await loadHashStore();
253
- wipeServed(store, sessionKey);
175
+ store.wipeServed(sessionKey);
254
176
  }
255
177
  catch (error) {
256
178
  console.error("Failed to wipe served state:", error);
257
179
  }
258
180
  }
181
+ /** Every served position of a hash in a served array (the E_RANGE_UNVERIFIED probe). */
182
+ export function servedPositionsOf(served, hash) {
183
+ const out = [];
184
+ for (let i = 0; i < served.length; i++) {
185
+ if (served[i] === hash)
186
+ out.push(i);
187
+ }
188
+ return out;
189
+ }
190
+ function nearestSurvivingPosition(served, surviving, from, direction) {
191
+ if (direction === "below") {
192
+ for (let q = from - 1; q >= 0; q--) {
193
+ const hash = served[q];
194
+ if (hash !== null && surviving.has(hash))
195
+ return q;
196
+ }
197
+ return undefined;
198
+ }
199
+ for (let q = from + 1; q < served.length; q++) {
200
+ const hash = served[q];
201
+ if (hash !== null && surviving.has(hash))
202
+ return q;
203
+ }
204
+ return undefined;
205
+ }
206
+ /**
207
+ * Reconstruct where a drifted hash sits in the current file: map through the
208
+ * nearest surviving served neighbor (below, else above), else fall back to
209
+ * the served index plus the range's line delta.
210
+ */
211
+ export function currentPositionOfDrifted(served, currentPositions, surviving, servedIndex, delta) {
212
+ const below = nearestSurvivingPosition(served, surviving, servedIndex, "below");
213
+ if (below !== undefined)
214
+ return currentPositions.get(served[below]) + 1;
215
+ const above = nearestSurvivingPosition(served, surviving, servedIndex, "above");
216
+ if (above !== undefined)
217
+ return currentPositions.get(served[above]) - 1;
218
+ return servedIndex + delta;
219
+ }