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.
- package/CHANGELOG.md +32 -0
- package/README.md +168 -52
- package/README.zh.md +122 -46
- package/assets/logo.svg +183 -18
- package/lib/contract.js +95 -0
- package/lib/drift.js +1 -1
- package/lib/edit-diff.js +2 -2
- package/lib/edit-engine.js +456 -0
- package/lib/edit-pipeline.js +41 -116
- package/lib/file-reader.js +1 -2
- package/lib/fs-bridge.js +2 -2
- package/lib/fs-write.js +3 -46
- package/lib/guidance.js +282 -0
- package/lib/hash-store.js +246 -13
- package/lib/hashline/apply.js +2 -2
- package/lib/hashline/hash.js +16 -206
- package/lib/hashline/index.js +4 -3
- package/lib/hashline/parse.js +1 -1
- package/lib/hashline/pure.js +213 -0
- package/lib/hashline/resolve.js +1 -5
- package/lib/hashline/served.js +2 -2
- package/lib/index.js +48 -32
- package/lib/paths.js +55 -1
- package/lib/prompts.js +53 -49
- package/lib/read-and-serve.js +46 -0
- package/lib/schema.js +1 -1
- package/lib/served-store.js +144 -183
- package/lib/tool-batch-edit.js +28 -280
- package/lib/tool-edit.js +37 -32
- package/lib/tool-read.js +8 -31
- package/lib/tool-undo.js +4 -13
- package/lib/types/contract.d.ts +39 -0
- package/lib/types/edit-engine.d.ts +179 -0
- package/lib/types/edit-pipeline.d.ts +10 -17
- package/lib/types/fs-write.d.ts +0 -1
- package/lib/types/guidance.d.ts +98 -0
- package/lib/types/hash-store.d.ts +73 -25
- package/lib/types/hashline/hash.d.ts +8 -13
- package/lib/types/hashline/index.d.ts +4 -3
- package/lib/types/hashline/pure.d.ts +26 -0
- package/lib/types/hashline/resolve.d.ts +0 -1
- package/lib/types/index.d.ts +4 -0
- package/lib/types/paths.d.ts +9 -0
- package/lib/types/prompts.d.ts +19 -9
- package/lib/types/read-and-serve.d.ts +39 -0
- package/lib/types/schema.d.ts +2 -16
- package/lib/types/served-store.d.ts +63 -32
- package/lib/types/tool-batch-edit.d.ts +4 -1
- package/lib/types/tool-undo.d.ts +1 -1
- package/lib/undo-edit.js +16 -1
- package/lib/write-hook.js +30 -50
- package/package.json +5 -3
- package/lib/served-state.js +0 -34
- package/lib/snapshot-store.js +0 -108
- package/lib/types/served-state.d.ts +0 -3
- package/lib/types/snapshot-store.d.ts +0 -14
- package/lib/types/undo-store.d.ts +0 -14
- 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;
|
|
4
|
-
* `tool:*` system-prompt sections carry the
|
|
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 =
|
|
9
|
-
|
|
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
|
-
|
|
12
|
-
export const
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
export const
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
export const BATCH_EDIT_DESCRIPTION =
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
export const
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
export const UNDO_DESCRIPTION =
|
|
50
|
-
|
|
51
|
-
export const
|
|
52
|
-
|
|
53
|
-
|
|
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
|
-
* `
|
|
6
|
+
* `assertEditRequest` after `normalizeFilePath` aliasing.
|
|
7
7
|
* @module dsh-better-edit/schema
|
|
8
8
|
*/
|
|
9
9
|
export const replacementTextSchema = {
|
package/lib/served-store.js
CHANGED
|
@@ -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
|
-
*
|
|
105
|
-
*
|
|
106
|
-
*
|
|
107
|
-
*
|
|
108
|
-
*
|
|
109
|
-
*
|
|
110
|
-
*
|
|
111
|
-
*
|
|
112
|
-
*
|
|
113
|
-
*
|
|
114
|
-
*
|
|
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
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
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
|
-
|
|
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(
|
|
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
|
-
|
|
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(
|
|
103
|
+
console.error("Failed to record served rows:", error);
|
|
205
104
|
}
|
|
206
105
|
}
|
|
207
106
|
/**
|
|
208
|
-
*
|
|
209
|
-
*
|
|
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
|
-
|
|
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(
|
|
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
|
|
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
|
-
|
|
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
|
-
|
|
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(
|
|
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
|
+
}
|