dsh-better-edit 0.5.0 → 0.6.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.
- package/CHANGELOG.md +20 -2
- package/README.md +1 -1
- package/lib/contract.js +1 -1
- package/lib/edit-engine.js +4 -454
- package/lib/edit-response.js +24 -2
- package/lib/encoding.js +308 -0
- package/lib/file-encoding-state.js +263 -0
- package/lib/file-view.js +1 -1
- package/lib/fs-bridge.js +124 -19
- package/lib/hash-store.js +1 -2
- package/lib/hashline/anchor-pipeline.js +19 -165
- package/lib/index.js +2 -2
- package/lib/mutation/engine.js +388 -0
- package/lib/mutation.js +84 -11
- package/lib/paths.js +1 -1
- package/lib/read-and-serve.js +5 -0
- package/lib/session-view.js +16 -49
- package/lib/store/index.js +28 -0
- package/lib/store-config.js +132 -2
- package/lib/store-lifecycle.js +1 -1
- package/lib/tool-edit.js +2 -2
- package/lib/tool-read.js +26 -6
- package/lib/tool-undo.js +2 -2
- package/lib/types/contract.d.ts +1 -0
- package/lib/types/edit-diff.d.ts +1 -1
- package/lib/types/edit-engine.d.ts +4 -176
- package/lib/types/edit-response.d.ts +1 -1
- package/lib/types/encoding.d.ts +46 -0
- package/lib/types/file-encoding-state.d.ts +77 -0
- package/lib/types/file-view.d.ts +2 -1
- package/lib/types/fs-bridge.d.ts +5 -1
- package/lib/types/hashline/anchor-pipeline.d.ts +6 -20
- package/lib/types/hashline/index.d.ts +1 -1
- package/lib/types/mutation/engine.d.ts +143 -0
- package/lib/types/mutation.d.ts +30 -5
- package/lib/types/paths.d.ts +1 -1
- package/lib/types/read-and-serve.d.ts +4 -1
- package/lib/types/session-view.d.ts +16 -30
- package/lib/types/store/index.d.ts +25 -0
- package/lib/types/store-config.d.ts +10 -1
- package/lib/types/workspace-context.d.ts +23 -0
- package/lib/workspace-context.js +44 -0
- package/lib/write-hook.js +2 -1
- package/package.json +5 -1
package/lib/fs-bridge.js
CHANGED
|
@@ -16,8 +16,15 @@
|
|
|
16
16
|
*/
|
|
17
17
|
import { readFile } from "node:fs/promises";
|
|
18
18
|
import { writeAtomic } from "./fs-write.js";
|
|
19
|
+
import { loadConfig } from "./store-config.js";
|
|
19
20
|
import { fileSnap } from "./file-reader.js";
|
|
20
21
|
import { resolveTarget, toCwd } from "./paths.js";
|
|
22
|
+
import { decodeForOpen, recordOpenState, recordFooter, getEncodingState as _getEncodingState, setEncodingState as _setEncodingState, clearEncodingState as _clearEncodingState, getAutoGuessFooter as _getAutoGuessFooter, setAutoGuessFooter as _setAutoGuessFooter, clearAutoGuessFooter as _clearAutoGuessFooter, invalidateIfStale, prepareForSave, } from "./file-encoding-state.js";
|
|
23
|
+
export { _getEncodingState as getEncodingState, _setEncodingState as setEncodingState, _clearEncodingState as clearEncodingState, _getAutoGuessFooter as getAutoGuessFooter, _setAutoGuessFooter as setAutoGuessFooter, _clearAutoGuessFooter as clearAutoGuessFooter, };
|
|
24
|
+
// Keep alias for tests that import getAutoGuessFooter via fs-bridge
|
|
25
|
+
export function getAutoGuessFooterCompat(k) {
|
|
26
|
+
return _getAutoGuessFooter(k);
|
|
27
|
+
}
|
|
21
28
|
/**
|
|
22
29
|
* Map an `ctx.fs` failure onto the hashline model-facing vocabulary so the
|
|
23
30
|
* model sees the same structured error codes as the pure pipeline.
|
|
@@ -28,7 +35,6 @@ import { resolveTarget, toCwd } from "./paths.js";
|
|
|
28
35
|
export function mapFsError(error, displayPath) {
|
|
29
36
|
if (error instanceof Error &&
|
|
30
37
|
typeof error.code === "string") {
|
|
31
|
-
// SAFETY: `error` narrowed to Error with string `code` above — typed extraction for FS code switch
|
|
32
38
|
const code = error.code;
|
|
33
39
|
if (code === "FS_NOT_FOUND") {
|
|
34
40
|
throw new Error(`[E_NOT_FOUND] File not found: ${displayPath}`);
|
|
@@ -37,7 +43,13 @@ export function mapFsError(error, displayPath) {
|
|
|
37
43
|
throw new Error(`[E_ACCESS] Cannot access file: ${displayPath}`);
|
|
38
44
|
}
|
|
39
45
|
if (code === "FS_NOT_TEXT" || code === "FS_NOT_REGULAR_FILE") {
|
|
40
|
-
throw new Error(`[E_NOT_TEXT] Path is not a readable UTF-8 text file: ${displayPath}. Hashline editing only supports text files.`);
|
|
46
|
+
throw new Error(`[E_NOT_TEXT] Path is not a readable UTF-8 text file: ${displayPath}. Hashline editing only supports text files. Try read({encoding: "gbk"}) or enable autoGuessEncoding.`);
|
|
47
|
+
}
|
|
48
|
+
if (code === "FS_BAD_ENCODING") {
|
|
49
|
+
throw new Error(`[E_BAD_ENCODING] Unknown encoding for ${displayPath}. Supported: utf8, gbk, big5, shift_jis, euc-kr, windows-1251, iso-8859-1`);
|
|
50
|
+
}
|
|
51
|
+
if (code === "FS_DECODE_FAILED") {
|
|
52
|
+
throw new Error(`[E_DECODE_FAILED] Bytes in ${displayPath} cannot be decoded with requested encoding.`);
|
|
41
53
|
}
|
|
42
54
|
if (code === "FS_STALE_VERSION") {
|
|
43
55
|
throw new Error(`[E_RANGE_STALE] The file changed on disk since it was read (version guard rejected the write). Call read() to get fresh anchors, then retry.`);
|
|
@@ -98,40 +110,101 @@ export function ctxFsIO(fs, ctx) {
|
|
|
98
110
|
});
|
|
99
111
|
return fs.processPath(target);
|
|
100
112
|
},
|
|
101
|
-
async readText(absolutePath, signal) {
|
|
113
|
+
async readText(absolutePath, signal, encodingHint) {
|
|
114
|
+
// explicit encoding override (Reopen with Encoding) — bytes + seam
|
|
115
|
+
if (encodingHint) {
|
|
116
|
+
const target = await fs.resolve(absolutePath, { ...(signal === undefined ? {} : { signal }) });
|
|
117
|
+
const info = await fs.stat(target, signal);
|
|
118
|
+
const maxBytes = info?.size ?? 10 * 1024 * 1024;
|
|
119
|
+
const bytes = await fs.readBytes(target, signal, maxBytes);
|
|
120
|
+
const cfg = loadConfig();
|
|
121
|
+
const decoded = await decodeForOpen(bytes, cfg, { encodingHint, displayPath: absolutePath });
|
|
122
|
+
const targetKey = String(target.targetKey ?? absolutePath);
|
|
123
|
+
recordOpenState(targetKey, decoded.text, decoded.encoding, decoded.hasBOM, info?.version);
|
|
124
|
+
if (decoded.footer)
|
|
125
|
+
recordFooter(targetKey, decoded.footer);
|
|
126
|
+
return decoded.text;
|
|
127
|
+
}
|
|
102
128
|
try {
|
|
103
129
|
const target = await fs.resolve(absolutePath, {
|
|
104
130
|
...(signal === undefined ? {} : { signal }),
|
|
105
131
|
});
|
|
106
132
|
const text = await fs.readText(target, signal);
|
|
107
|
-
|
|
133
|
+
const restored = await restoreStrippedUtf8Bom(fs, target, text, signal);
|
|
134
|
+
// record file encoding state for round-trip (BOM + lineEnding)
|
|
135
|
+
// Do not probe fs.stat when BOM is already preserved — keep the no-probe guarantee
|
|
136
|
+
// tested in fs-bridge.policy.test.ts (keeps a BOM already preserved without probing)
|
|
137
|
+
try {
|
|
138
|
+
const targetKey = String(target.targetKey ?? absolutePath);
|
|
139
|
+
const hasBOM = restored.startsWith(UTF8_BOM);
|
|
140
|
+
const clean = hasBOM ? restored.slice(1) : restored;
|
|
141
|
+
// use seam to record with correct lineEnding detection; version left undefined
|
|
142
|
+
// to avoid extra stat (the success path must stay probe-free when BOM preserved)
|
|
143
|
+
recordOpenState(targetKey, clean, hasBOM ? "utf8bom" : "utf8", hasBOM, undefined);
|
|
144
|
+
// clear any stale autoGuess footer on clean UTF-8 read
|
|
145
|
+
_clearAutoGuessFooter(targetKey);
|
|
146
|
+
}
|
|
147
|
+
catch {
|
|
148
|
+
// best-effort
|
|
149
|
+
}
|
|
150
|
+
return restored;
|
|
108
151
|
}
|
|
109
152
|
catch (error) {
|
|
153
|
+
const isNotText = error instanceof Error && error.code === "FS_NOT_TEXT";
|
|
154
|
+
if (isNotText) {
|
|
155
|
+
const cfg = loadConfig();
|
|
156
|
+
const target = await fs.resolve(absolutePath, { ...(signal === undefined ? {} : { signal }) });
|
|
157
|
+
const info = await fs.stat(target, signal);
|
|
158
|
+
const maxBytes = info?.size ?? 10 * 1024 * 1024;
|
|
159
|
+
if (info && info.size !== undefined && info.size > maxBytes)
|
|
160
|
+
throw error;
|
|
161
|
+
const bytes = await fs.readBytes(target, signal, maxBytes);
|
|
162
|
+
const targetKey = String(target.targetKey ?? absolutePath);
|
|
163
|
+
// Delegate deterministic admission to the deep seam
|
|
164
|
+
const decoded = await decodeForOpen(bytes, cfg, { displayPath: absolutePath });
|
|
165
|
+
recordOpenState(targetKey, decoded.text, decoded.encoding, decoded.hasBOM, info?.version);
|
|
166
|
+
if (decoded.footer)
|
|
167
|
+
recordFooter(targetKey, decoded.footer);
|
|
168
|
+
return decoded.text;
|
|
169
|
+
}
|
|
110
170
|
return mapFsError(error, absolutePath);
|
|
111
171
|
}
|
|
112
172
|
},
|
|
113
173
|
async writeText(absolutePath, content, signal, exec, sandboxPolicy) {
|
|
174
|
+
// handle drift invalidation before encode — seam owns version check
|
|
175
|
+
try {
|
|
176
|
+
const targetTmp = await fs.resolve(absolutePath, { ...(signal === undefined ? {} : { signal }) });
|
|
177
|
+
const key = String(targetTmp.targetKey ?? absolutePath);
|
|
178
|
+
const info = await fs.stat(targetTmp, signal).catch(() => undefined);
|
|
179
|
+
invalidateIfStale(key, info?.version);
|
|
180
|
+
}
|
|
181
|
+
catch { } // biome-ignore: best-effort
|
|
114
182
|
try {
|
|
115
183
|
const target = await fs.resolve(absolutePath, {
|
|
116
184
|
...(signal === undefined ? {} : { signal }),
|
|
117
185
|
});
|
|
118
|
-
// Single-slot decision: the observation policy produces
|
|
119
|
-
// createIfAbsent / replaceIfVersion; the bare default is
|
|
120
|
-
// undefined (unconditional) when no policy is mounted.
|
|
121
186
|
const intent = await ctx.waterfall("fs/write-intent", target, exec, () => undefined);
|
|
122
|
-
//
|
|
123
|
-
//
|
|
124
|
-
//
|
|
125
|
-
|
|
187
|
+
// Seam owns Save-with-Encoding memo update and normalizeToUtf8 check.
|
|
188
|
+
// Provider expects UTF-8 string; for legacy without normalize we keep
|
|
189
|
+
// string as-is (next read re-detects via version bump).
|
|
190
|
+
try {
|
|
191
|
+
const cfgW = loadConfig();
|
|
192
|
+
const key = String(target.targetKey ?? absolutePath);
|
|
193
|
+
// Honor manual override if content was produced via write({encoding}) — not wired here,
|
|
194
|
+
// encodingHint is not part of writeText signature for ctxFsIO in current call sites.
|
|
195
|
+
// Check existing memo for legacy preservation.
|
|
196
|
+
const existing = _getEncodingState(key);
|
|
197
|
+
const prep = prepareForSave(content, existing, { normalizeToUtf8: cfgW.normalizeToUtf8 });
|
|
198
|
+
// For Save with Encoding hint, prepareForSave would create newState — not used in this path (tool-undo/write-hook carry hint separately)
|
|
199
|
+
if (prep.newState)
|
|
200
|
+
_setEncodingState(key, prep.newState);
|
|
201
|
+
// content stays as UTF-8 string for provider; prep.textToWrite is same as content
|
|
202
|
+
}
|
|
203
|
+
catch { } // biome-ignore: best-effort
|
|
126
204
|
const outcome = await fs.writeText(target, content, intent, signal, sandboxPolicy);
|
|
127
|
-
// Record the present observation (a no-op when no policy
|
|
128
|
-
// plugin listens), so later built-in tools see the new version.
|
|
129
205
|
ctx.emit("fs/observed", target, { kind: "present", version: outcome.version }, exec);
|
|
130
206
|
}
|
|
131
207
|
catch (error) {
|
|
132
|
-
// FS_SANDBOX_DENIED passes through raw; the tool layer maps it
|
|
133
|
-
// to the shared [sandbox: …] marker + escalation hint via its
|
|
134
|
-
// sandbox controller.
|
|
135
208
|
return mapFsError(error, absolutePath);
|
|
136
209
|
}
|
|
137
210
|
},
|
|
@@ -146,7 +219,6 @@ export function ctxFsIO(fs, ctx) {
|
|
|
146
219
|
}
|
|
147
220
|
}
|
|
148
221
|
catch (error) {
|
|
149
|
-
// A failed observation must not fail the read that preceded it.
|
|
150
222
|
console.error(`dsh-better-edit: fs/observed emission failed for ${absolutePath}: ${error instanceof Error ? error.message : String(error)}`);
|
|
151
223
|
}
|
|
152
224
|
},
|
|
@@ -170,12 +242,45 @@ export function localIO() {
|
|
|
170
242
|
async resolve(path, cwd) {
|
|
171
243
|
return resolveTarget(toCwd(path, cwd ?? process.cwd()));
|
|
172
244
|
},
|
|
173
|
-
async readText(absolutePath, signal) {
|
|
245
|
+
async readText(absolutePath, signal, encodingHint) {
|
|
174
246
|
signal?.throwIfAborted();
|
|
175
|
-
|
|
247
|
+
if (encodingHint) {
|
|
248
|
+
const bytes = await readFile(absolutePath);
|
|
249
|
+
const cfg = loadConfig();
|
|
250
|
+
const decoded = await decodeForOpen(bytes, cfg, { encodingHint, displayPath: absolutePath });
|
|
251
|
+
const info = await fileSnap(absolutePath).catch(() => undefined);
|
|
252
|
+
recordOpenState(absolutePath, decoded.text, decoded.encoding, decoded.hasBOM, info?.snapshotId);
|
|
253
|
+
if (decoded.footer)
|
|
254
|
+
recordFooter(absolutePath, decoded.footer);
|
|
255
|
+
return decoded.text;
|
|
256
|
+
}
|
|
257
|
+
// Deterministic path via seam, with local fallback for E_NOT_TEXT when autoGuess off
|
|
258
|
+
try {
|
|
259
|
+
const bytes = await readFile(absolutePath);
|
|
260
|
+
const cfgL = loadConfig();
|
|
261
|
+
const decoded = await decodeForOpen(bytes, cfgL, { displayPath: absolutePath });
|
|
262
|
+
const info = await fileSnap(absolutePath).catch(() => undefined);
|
|
263
|
+
recordOpenState(absolutePath, decoded.text, decoded.encoding, decoded.hasBOM, info?.snapshotId);
|
|
264
|
+
if (decoded.footer)
|
|
265
|
+
recordFooter(absolutePath, decoded.footer);
|
|
266
|
+
return decoded.text;
|
|
267
|
+
}
|
|
268
|
+
catch (error) {
|
|
269
|
+
// Local fallback: when autoGuess off, E_NOT_TEXT should fall back to raw UTF-8 with � (no throw)
|
|
270
|
+
if (error instanceof Error && error.message.includes("[E_NOT_TEXT]")) {
|
|
271
|
+
return readFile(absolutePath, "utf-8");
|
|
272
|
+
}
|
|
273
|
+
throw error;
|
|
274
|
+
}
|
|
176
275
|
},
|
|
177
276
|
async writeText(absolutePath, content, signal, _exec, _sandboxPolicy) {
|
|
178
277
|
signal?.throwIfAborted();
|
|
278
|
+
// Invalidate stale memo before write, and handle lineEnding via seam if needed
|
|
279
|
+
try {
|
|
280
|
+
const info = await fileSnap(absolutePath).catch(() => undefined);
|
|
281
|
+
invalidateIfStale(absolutePath, info?.snapshotId);
|
|
282
|
+
}
|
|
283
|
+
catch { }
|
|
179
284
|
await writeAtomic(absolutePath, content);
|
|
180
285
|
},
|
|
181
286
|
async emitObserved() {
|
package/lib/hash-store.js
CHANGED
|
@@ -19,7 +19,7 @@ import { dirname, join } from "node:path";
|
|
|
19
19
|
import { DatabaseSync } from "node:sqlite";
|
|
20
20
|
import { hashStorePath } from "./store-tenancy.js";
|
|
21
21
|
import { onStoreOpen, setStoresGetter } from "./store-lifecycle.js";
|
|
22
|
-
import { workspaceCwd } from "./workspace.js";
|
|
22
|
+
import { workspaceCwd } from "./workspace-context.js";
|
|
23
23
|
import { errCode, splitLines } from "./utils.js";
|
|
24
24
|
import { initHasher, contentChecksum, HASH_RE, CANON_VERSION, } from "./hashline/hash-assign.js";
|
|
25
25
|
import { HASH_STORE_VERSION, HASH_STORE_BUSY_TIMEOUT, SERVED_TTL_MS, } from "./constants.js";
|
|
@@ -110,7 +110,6 @@ function openDbWithBusyRetry(storePath) {
|
|
|
110
110
|
const stores = new Map();
|
|
111
111
|
const openings = new Map();
|
|
112
112
|
setStoresGetter(() => stores, () => openings);
|
|
113
|
-
const exitHandlerRegistered = false;
|
|
114
113
|
function openDb(storePath) {
|
|
115
114
|
const db = new DatabaseSync(storePath, {
|
|
116
115
|
timeout: HASH_STORE_BUSY_TIMEOUT,
|
|
@@ -2,25 +2,23 @@
|
|
|
2
2
|
* AnchorPipeline — deep module owning the anchor autofix chain.
|
|
3
3
|
*
|
|
4
4
|
* Single ordering invariant (private):
|
|
5
|
-
* swapReversed → stripBare → stripDiff → valEdit →
|
|
5
|
+
* swapReversed → stripBare → stripDiff → valEdit → verifyServed → resToSpan
|
|
6
6
|
*
|
|
7
|
-
*
|
|
8
|
-
* were split across resolve.ts / apply.ts with an implicit coupling.
|
|
9
|
-
* This seam co-locates that invariant. Public surface is two functions:
|
|
7
|
+
* This seam co-locates the ordering invariant. Public surface is two functions:
|
|
10
8
|
* resEdit — pre-validation (tool-layer, no file state)
|
|
11
9
|
* applyEdit — full pipeline (file + hashes + served verification)
|
|
12
10
|
*
|
|
13
11
|
* Private to this seam (not re-exported): stripBarePrefixes, stripDiffPrefixes,
|
|
14
|
-
* swapReversedRanges, valEdit,
|
|
12
|
+
* swapReversedRanges, valEdit, warnUnicodeEsc,
|
|
15
13
|
* resAnchorFromMap, assertAligned, etc. They remain exported from resolve.ts
|
|
16
14
|
* for backwards compat but are marked @internal and should be imported via this
|
|
17
15
|
* module only.
|
|
18
16
|
*
|
|
19
17
|
* @module dsh-better-edit/hashline/anchor-pipeline
|
|
20
18
|
*/
|
|
21
|
-
import { abortIf, splitLines, rejectUnknownFields,
|
|
19
|
+
import { abortIf, splitLines, rejectUnknownFields, clipLine } from "../utils.js";
|
|
22
20
|
import { HASH_CLASS, HL_BARE_PREFIX_RE, HL_PREFIX_PLUS_RE, HL_PREFIX_MINUS_RE, HASH_SEP, ANCHOR_LEN, ALPH_RE, canon, lineHashesPure, getCanonForHash, rememberHashCanon } from "./hash-assign.js";
|
|
23
|
-
import { recordServed, servedPositionsOf } from "../
|
|
21
|
+
import { recordServed, servedPositionsOf } from "../session-view.js";
|
|
24
22
|
import { SERVED_ECHO_CAP } from "../constants.js";
|
|
25
23
|
import { NEW_CONTENT_NOT_STRING_MSG } from "../constants.js";
|
|
26
24
|
function diagRef(ref) {
|
|
@@ -281,126 +279,10 @@ function swapReversedRanges(edit, fileHashes, warnings) {
|
|
|
281
279
|
warnings.push(`[E_BAD_OP] reversed remove_from/remove_to (${startRef.hash} after ${endRef.hash}); swapped.`);
|
|
282
280
|
return { ...edit, hash_bounds: [endRef, startRef] };
|
|
283
281
|
}
|
|
284
|
-
function trailingDups(contentLines, fileLines, endLine) {
|
|
285
|
-
const start = lastNonEmptyIndex(contentLines);
|
|
286
|
-
if (start < 0)
|
|
287
|
-
return [];
|
|
288
|
-
const dups = [];
|
|
289
|
-
const maxK = Math.min(start + 1, fileLines.length - endLine);
|
|
290
|
-
for (let k = 0; k < maxK; k++) {
|
|
291
|
-
if (contentLines[start - k] !== fileLines[endLine + k])
|
|
292
|
-
break;
|
|
293
|
-
dups.push({ kind: "trailing", replacementLineIndex: start - k });
|
|
294
|
-
}
|
|
295
|
-
return dups;
|
|
296
|
-
}
|
|
297
|
-
function leadingDups(contentLines, fileLines, startLine) {
|
|
298
|
-
const start = firstNonEmptyIndex(contentLines);
|
|
299
|
-
if (start < 0)
|
|
300
|
-
return [];
|
|
301
|
-
const dups = [];
|
|
302
|
-
const maxK = Math.min(contentLines.length - start, startLine - 1);
|
|
303
|
-
for (let k = 0; k < maxK; k++) {
|
|
304
|
-
if (contentLines[start + k] !== fileLines[startLine - 2 - k])
|
|
305
|
-
break;
|
|
306
|
-
dups.push({ kind: "leading", replacementLineIndex: start + k });
|
|
307
|
-
}
|
|
308
|
-
return dups;
|
|
309
|
-
}
|
|
310
|
-
function sectionIsUnique(canonLines, start, length) {
|
|
311
|
-
let count = 0;
|
|
312
|
-
for (let i = 0; i + length <= canonLines.length; i++) {
|
|
313
|
-
let k = 0;
|
|
314
|
-
while (k < length && canonLines[i + k] === canonLines[start + k])
|
|
315
|
-
k++;
|
|
316
|
-
if (k < length)
|
|
317
|
-
continue;
|
|
318
|
-
count++;
|
|
319
|
-
if (count > 1)
|
|
320
|
-
return false;
|
|
321
|
-
}
|
|
322
|
-
return true;
|
|
323
|
-
}
|
|
324
|
-
function firstNewAfterDups(contentLines, rangeLines, canonLines, endLine) {
|
|
325
|
-
const firstNew = findNewEdge(contentLines, rangeLines, false);
|
|
326
|
-
if (!firstNew)
|
|
327
|
-
return [];
|
|
328
|
-
const maxK = Math.min(contentLines.length - firstNew.index, canonLines.length - endLine);
|
|
329
|
-
let runLen = 0;
|
|
330
|
-
while (runLen < maxK &&
|
|
331
|
-
canon(contentLines[firstNew.index + runLen]) ===
|
|
332
|
-
canonLines[endLine + runLen]) {
|
|
333
|
-
runLen++;
|
|
334
|
-
}
|
|
335
|
-
if (runLen === 0 || !sectionIsUnique(canonLines, endLine, runLen))
|
|
336
|
-
return [];
|
|
337
|
-
const dups = [];
|
|
338
|
-
for (let k = 0; k < runLen; k++) {
|
|
339
|
-
dups.push({
|
|
340
|
-
kind: "first-new-after",
|
|
341
|
-
replacementLineIndex: firstNew.index + k,
|
|
342
|
-
});
|
|
343
|
-
}
|
|
344
|
-
return dups;
|
|
345
|
-
}
|
|
346
|
-
function lastNewBeforeDups(contentLines, rangeLines, canonLines, startLine) {
|
|
347
|
-
const lastNew = findNewEdge(contentLines, rangeLines, true);
|
|
348
|
-
if (!lastNew)
|
|
349
|
-
return [];
|
|
350
|
-
const maxK = Math.min(lastNew.index + 1, startLine - 1);
|
|
351
|
-
let runLen = 0;
|
|
352
|
-
while (runLen < maxK &&
|
|
353
|
-
canon(contentLines[lastNew.index - runLen]) ===
|
|
354
|
-
canonLines[startLine - 2 - runLen]) {
|
|
355
|
-
runLen++;
|
|
356
|
-
}
|
|
357
|
-
if (runLen === 0)
|
|
358
|
-
return [];
|
|
359
|
-
const sectionStart = startLine - 1 - runLen;
|
|
360
|
-
if (!sectionIsUnique(canonLines, sectionStart, runLen))
|
|
361
|
-
return [];
|
|
362
|
-
const dups = [];
|
|
363
|
-
for (let k = 0; k < runLen; k++) {
|
|
364
|
-
dups.push({
|
|
365
|
-
kind: "last-new-before",
|
|
366
|
-
replacementLineIndex: lastNew.index - k,
|
|
367
|
-
});
|
|
368
|
-
}
|
|
369
|
-
return dups;
|
|
370
|
-
}
|
|
371
|
-
function canonCounts(lines) {
|
|
372
|
-
const counts = new Map();
|
|
373
|
-
for (const line of lines) {
|
|
374
|
-
const key = canon(line);
|
|
375
|
-
counts.set(key, (counts.get(key) ?? 0) + 1);
|
|
376
|
-
}
|
|
377
|
-
return counts;
|
|
378
|
-
}
|
|
379
282
|
/** @internal — private to anchor-pipeline seam */
|
|
380
|
-
export function findNewEdge(contentLines, rangeLines, fromEnd) {
|
|
381
|
-
const multiset = canonCounts(rangeLines);
|
|
382
|
-
const step = fromEnd ? -1 : 1;
|
|
383
|
-
const start = fromEnd ? contentLines.length - 1 : 0;
|
|
384
|
-
for (let i = start; i >= 0 && i < contentLines.length; i += step) {
|
|
385
|
-
const line = contentLines[i];
|
|
386
|
-
if (line.length === 0)
|
|
387
|
-
continue;
|
|
388
|
-
const key = canon(line);
|
|
389
|
-
const count = multiset.get(key) ?? 0;
|
|
390
|
-
if (count > 0) {
|
|
391
|
-
multiset.set(key, count - 1);
|
|
392
|
-
}
|
|
393
|
-
else {
|
|
394
|
-
return { index: i, line };
|
|
395
|
-
}
|
|
396
|
-
}
|
|
397
|
-
return undefined;
|
|
398
|
-
}
|
|
399
|
-
/** @internal — private to anchor-pipeline seam: detection + boundaryDups belongs to AnchorPipeline ordering */
|
|
400
283
|
function valEdit(edit, fileLines, fileHashes, warnings, signal) {
|
|
401
284
|
assertAligned(fileLines, fileHashes, "valEdit");
|
|
402
285
|
const mismatches = [];
|
|
403
|
-
const boundaryDups = [];
|
|
404
286
|
const hashIndex = new Map();
|
|
405
287
|
for (let i = 0; i < fileHashes.length; i++) {
|
|
406
288
|
const h = fileHashes[i];
|
|
@@ -430,24 +312,21 @@ function valEdit(edit, fileLines, fileHashes, warnings, signal) {
|
|
|
430
312
|
if (endMismatch && endMismatch.kind === "not_found")
|
|
431
313
|
endMismatch.context = startResolved;
|
|
432
314
|
}
|
|
433
|
-
return { resolved: undefined, mismatches
|
|
315
|
+
return { resolved: undefined, mismatches };
|
|
434
316
|
}
|
|
435
317
|
if (startResolved.line > endResolved.line) {
|
|
436
318
|
throw new Error(`[E_BAD_OP] Range start line ${startResolved.line} must be <= end line ${endResolved.line} (anchors ${edit.hash_bounds[0].hash} and ${edit.hash_bounds[1].hash}).`);
|
|
437
319
|
}
|
|
438
320
|
const endLine = endResolved.line;
|
|
439
|
-
const rangeLines = fileLines.slice(startResolved.line - 1, endLine);
|
|
440
|
-
const canonLines = fileLines.map((line) => canon(line));
|
|
441
|
-
boundaryDups.push(...trailingDups(edit.content_lines, fileLines, endLine), ...leadingDups(edit.content_lines, fileLines, startResolved.line), ...firstNewAfterDups(edit.content_lines, rangeLines, canonLines, endLine), ...lastNewBeforeDups(edit.content_lines, rangeLines, canonLines, startResolved.line));
|
|
442
321
|
return {
|
|
443
322
|
resolved: {
|
|
444
323
|
content_lines: edit.content_lines,
|
|
445
324
|
hash_bounds: [startResolved, endResolved],
|
|
446
325
|
},
|
|
447
326
|
mismatches,
|
|
448
|
-
boundaryDups,
|
|
449
327
|
};
|
|
450
328
|
}
|
|
329
|
+
export function findNewEdge() { return undefined; }
|
|
451
330
|
export { warnUnicodeEsc };
|
|
452
331
|
export class ServedRejectionError extends Error {
|
|
453
332
|
code;
|
|
@@ -876,47 +755,13 @@ export function applyEdit(content, edit, signal, precomputedHashes, filePath, se
|
|
|
876
755
|
const warnings = [];
|
|
877
756
|
const rangeFixed = swapReversedRanges(edit, fileHashes, warnings);
|
|
878
757
|
const prefixFixed = stripDiffPrefixes(stripBarePrefixes(rangeFixed, fileHashes, warnings), warnings);
|
|
879
|
-
const { resolved: initialResolved, mismatches,
|
|
758
|
+
const { resolved: initialResolved, mismatches, } = valEdit(prefixFixed, lineIndex.fileLines, fileHashes, warnings, signal);
|
|
880
759
|
if (mismatches.length || !initialResolved) {
|
|
881
760
|
const { message, servedRows } = fmtMismatchWithServes(mismatches, lineIndex.fileLines, fileHashes, filePath);
|
|
882
761
|
throw new AnchorMismatchError(message, servedRows);
|
|
883
762
|
}
|
|
884
763
|
warnUnicodeEsc(prefixFixed, warnings);
|
|
885
|
-
|
|
886
|
-
let autoFixes;
|
|
887
|
-
if (boundaryDups.length > 0) {
|
|
888
|
-
autoFixes = [];
|
|
889
|
-
const correctedEdit = {
|
|
890
|
-
...prefixFixed,
|
|
891
|
-
content_lines: [...prefixFixed.content_lines],
|
|
892
|
-
};
|
|
893
|
-
const seen = new Set();
|
|
894
|
-
const uniqueDups = [];
|
|
895
|
-
for (const dup of boundaryDups) {
|
|
896
|
-
if (seen.has(dup.replacementLineIndex))
|
|
897
|
-
continue;
|
|
898
|
-
seen.add(dup.replacementLineIndex);
|
|
899
|
-
uniqueDups.push(dup);
|
|
900
|
-
}
|
|
901
|
-
const dupsByIndex = uniqueDups.sort((a, b) => b.replacementLineIndex - a.replacementLineIndex);
|
|
902
|
-
for (const dup of dupsByIndex) {
|
|
903
|
-
const idx = dup.replacementLineIndex;
|
|
904
|
-
if (idx < 0 || idx >= correctedEdit.content_lines.length)
|
|
905
|
-
continue;
|
|
906
|
-
const removed = correctedEdit.content_lines.splice(idx, 1)[0];
|
|
907
|
-
autoFixes.push({
|
|
908
|
-
kind: dup.kind,
|
|
909
|
-
removedLine: removed,
|
|
910
|
-
removedLineIndex: idx,
|
|
911
|
-
});
|
|
912
|
-
}
|
|
913
|
-
const correctedResult = valEdit(correctedEdit, lineIndex.fileLines, fileHashes, warnings, signal);
|
|
914
|
-
if (correctedResult.mismatches.length || !correctedResult.resolved) {
|
|
915
|
-
const { message, servedRows } = fmtMismatchWithServes(correctedResult.mismatches, lineIndex.fileLines, fileHashes, filePath);
|
|
916
|
-
throw new AnchorMismatchError(message, servedRows);
|
|
917
|
-
}
|
|
918
|
-
resolved = correctedResult.resolved;
|
|
919
|
-
}
|
|
764
|
+
const resolved = initialResolved;
|
|
920
765
|
if (served) {
|
|
921
766
|
const startLineEcho = resolved.hash_bounds[0].line;
|
|
922
767
|
const rawEcho = findEditHashEcho(edit.content_lines, served, startLineEcho);
|
|
@@ -965,7 +810,6 @@ export function applyEdit(content, edit, signal, precomputedHashes, filePath, se
|
|
|
965
810
|
lastChangedLine: changed?.lastChangedLine,
|
|
966
811
|
range: resolvedRange(resolved),
|
|
967
812
|
...(warnings.length ? { warnings } : {}),
|
|
968
|
-
...(autoFixes ? { autoFixes } : {}),
|
|
969
813
|
};
|
|
970
814
|
}
|
|
971
815
|
function resolvedRange(resolved) {
|
|
@@ -1019,3 +863,13 @@ export function changedRange(original, result) {
|
|
|
1019
863
|
lastChangedLine: Math.max(first, lastRes) + 1,
|
|
1020
864
|
};
|
|
1021
865
|
}
|
|
866
|
+
// ---------------------------------------------------------------------------
|
|
867
|
+
// Sealed seam — single public entry for hashline (Candidate 5)
|
|
868
|
+
// HashAssign allocation + hash persistence re-exported here so callers import
|
|
869
|
+
// only from anchor-pipeline. Private modules (hash-assign, hash, hasher,
|
|
870
|
+
// alphabet, pure, parse, apply, resolve, served) are @internal and guarded
|
|
871
|
+
// by biome noRestrictedImports. Deleting this re-export block would scatter
|
|
872
|
+
// the hashline surface again — it concentrates (deep).
|
|
873
|
+
// ---------------------------------------------------------------------------
|
|
874
|
+
export { HASH_RE, HASH_CLASS, HASH_SEP, ANCHOR_LEN, ALPH_RE, ALPH, HASH_LEN, HASH_SPACE, MAX_HASH_LINES, HASH_PROBE_STRIDE, CANON_VERSION, canon, lineHashesPure, mapStableHashes, initHasher, contentChecksum, getCanonForHash, rememberHashCanon, } from "./hash-assign.js";
|
|
875
|
+
export { lineHashes } from "./hash.js";
|
package/lib/index.js
CHANGED
|
@@ -23,9 +23,9 @@ import { registerUndoTool } from "./tool-undo.js";
|
|
|
23
23
|
import { registerWriteHook } from "./write-hook.js";
|
|
24
24
|
import { initHasher } from "./hashline/hash-assign.js";
|
|
25
25
|
import { composeSections, ensurePresetGuidance, GUIDANCE_SECTIONS, } from "./guidance.js";
|
|
26
|
-
import { configDir } from "./
|
|
26
|
+
import { configDir } from "./store/index.js";
|
|
27
27
|
import { ensureDefaultConfig } from "./store-config.js";
|
|
28
|
-
import { onAppStart, onSessionStart } from "./store
|
|
28
|
+
import { onAppStart, onSessionStart } from "./store/index.js";
|
|
29
29
|
/** Cordis plugin name used by loader diagnostics. */
|
|
30
30
|
export const name = "dsh-better-edit";
|
|
31
31
|
/**
|