dsh-better-edit 1.2.4 → 1.2.5
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 +19 -0
- package/lib/domain-errors.js +11 -9
- package/lib/edit-mode.js +11 -0
- package/lib/encoding.js +2 -0
- package/lib/file-encoding-state.js +42 -25
- package/lib/file-view.js +26 -205
- package/lib/fs-bridge.js +14 -49
- package/lib/hashline/anchor-pipeline.js +8 -499
- package/lib/hashline/hash-assign.js +55 -4
- package/lib/hashline/index.js +5 -2
- package/lib/hashline/served-evidence.js +531 -0
- package/lib/index.js +176 -47
- package/lib/mutation/engine.js +10 -13
- package/lib/mutation.js +36 -100
- package/lib/noop-guard.js +24 -39
- package/lib/paths.js +9 -5
- package/lib/read-and-serve.js +51 -53
- package/lib/reclaim.js +65 -0
- package/lib/self-heal.js +6 -10
- package/lib/session-view.js +61 -21
- package/lib/store/index.js +14 -14
- package/lib/store-config.js +4 -5
- package/lib/store-lifecycle.js +1 -1
- package/lib/tool-edit.js +0 -3
- package/lib/tool-read.js +2 -8
- package/lib/tool-str-replace-editor.js +3 -10
- package/lib/tool-undo.js +5 -13
- package/lib/types/contract.d.ts +2 -1
- package/lib/types/domain-errors.d.ts +8 -9
- package/lib/types/edit-mode.d.ts +11 -0
- package/lib/types/encoding.d.ts +1 -0
- package/lib/types/file-encoding-state.d.ts +10 -10
- package/lib/types/file-view.d.ts +18 -56
- package/lib/types/hashline/anchor-pipeline.d.ts +6 -128
- package/lib/types/hashline/hash-assign.d.ts +40 -0
- package/lib/types/hashline/index.d.ts +6 -4
- package/lib/types/hashline/served-evidence.d.ts +152 -0
- package/lib/types/mutation/engine.d.ts +4 -2
- package/lib/types/mutation.d.ts +9 -57
- package/lib/types/noop-guard.d.ts +2 -33
- package/lib/types/paths.d.ts +0 -1
- package/lib/types/reclaim.d.ts +36 -0
- package/lib/types/session-view.d.ts +28 -8
- package/lib/types/store/index.d.ts +12 -11
- package/lib/types/store-config.d.ts +1 -1
- package/lib/types/store-lifecycle.d.ts +12 -2
- package/lib/types/tool-edit.d.ts +0 -2
- package/lib/types/tool-read.d.ts +0 -5
- package/lib/types/tool-str-replace-editor.d.ts +0 -6
- package/lib/types/tool-undo.d.ts +0 -5
- package/package.json +3 -2
- package/lib/drift.js +0 -5
- package/lib/dsh-context.js +0 -5
- package/lib/edit-engine.js +0 -7
- package/lib/edit-normalize.js +0 -9
- package/lib/edit-pipeline.js +0 -6
- package/lib/file-kind.js +0 -6
- package/lib/file-reader.js +0 -6
- package/lib/guidance/index.js +0 -8
- package/lib/hashline/alphabet.js +0 -2
- package/lib/hashline/apply.js +0 -2
- package/lib/hashline/hasher.js +0 -2
- package/lib/hashline/parse.js +0 -2
- package/lib/hashline/pure.js +0 -2
- package/lib/hashline/resolve.js +0 -3
- package/lib/hashline/served.js +0 -2
- package/lib/preview-controller.js +0 -65
- package/lib/read-render.js +0 -6
- package/lib/schema.js +0 -24
- package/lib/served-store.js +0 -5
- package/lib/tool-batch-edit.js +0 -190
- package/lib/truncate.js +0 -6
- package/lib/types/drift.d.ts +0 -5
- package/lib/types/dsh-context.d.ts +0 -5
- package/lib/types/edit-engine.d.ts +0 -7
- package/lib/types/edit-normalize.d.ts +0 -1
- package/lib/types/edit-pipeline.d.ts +0 -6
- package/lib/types/file-kind.d.ts +0 -6
- package/lib/types/file-reader.d.ts +0 -6
- package/lib/types/guidance/index.d.ts +0 -8
- package/lib/types/hashline/alphabet.d.ts +0 -1
- package/lib/types/hashline/apply.d.ts +0 -1
- package/lib/types/hashline/hasher.d.ts +0 -1
- package/lib/types/hashline/parse.d.ts +0 -1
- package/lib/types/hashline/pure.d.ts +0 -1
- package/lib/types/hashline/resolve.d.ts +0 -1
- package/lib/types/hashline/served.d.ts +0 -1
- package/lib/types/preview-controller.d.ts +0 -33
- package/lib/types/read-render.d.ts +0 -6
- package/lib/types/schema.d.ts +0 -25
- package/lib/types/served-store.d.ts +0 -5
- package/lib/types/tool-batch-edit.d.ts +0 -25
- package/lib/types/truncate.d.ts +0 -6
- package/lib/types/validation.d.ts +0 -6
- package/lib/types/workspace.d.ts +0 -5
- package/lib/validation.js +0 -6
- package/lib/workspace.js +0 -5
package/lib/read-and-serve.js
CHANGED
|
@@ -8,11 +8,11 @@
|
|
|
8
8
|
* @module dsh-better-edit/read-and-serve
|
|
9
9
|
*/
|
|
10
10
|
import { abortIf } from "./utils.js";
|
|
11
|
-
import {
|
|
11
|
+
import { readView } from "./file-view.js";
|
|
12
12
|
import { canon } from "./hashline/hash-assign.js";
|
|
13
13
|
import { splitLines } from "./utils.js";
|
|
14
14
|
import { getAutoGuessFooter } from "./fs-bridge.js";
|
|
15
|
-
import {
|
|
15
|
+
import { HASH_SPACE, isPromotableAnchorSpaceExhaustion } from "./hashline/hash-assign.js";
|
|
16
16
|
import { recordServed, clearDriftReported, loadRetiredAnchors, loadServed, loadServedCanons, } from "./session-view.js";
|
|
17
17
|
import { loadServedStore } from "./hash-store.js";
|
|
18
18
|
/** Appended when the file had non-UTF-8 bytes; editing rewrites it as UTF-8. */
|
|
@@ -44,7 +44,8 @@ export async function readAndServe(io, rawPath, cwd, options) {
|
|
|
44
44
|
// Build previous for stable reuse (S): served filtered + canons reconstruction.
|
|
45
45
|
// #62 alignment gate: the reconstructed arrays carry the SERVED index as the line
|
|
46
46
|
// position, which equals the real line number only when the mirror is dense — the
|
|
47
|
-
// `row.position === index` half of the
|
|
47
|
+
// `row.position === index` density half of the serve verdict, which session-view keeps as an
|
|
48
|
+
// ASSERTION about FileView rather than a decision (ADR-0035).
|
|
48
49
|
// With holes (a partial mirror), `mapStableHashes` would match compressed indices
|
|
49
50
|
// against whole-file positions and reshuffle anchors of an UNCHANGED file; pass
|
|
50
51
|
// `previous = undefined` instead and take the content-addressed snapshot path
|
|
@@ -90,53 +91,53 @@ export async function readAndServe(io, rawPath, cwd, options) {
|
|
|
90
91
|
});
|
|
91
92
|
}
|
|
92
93
|
catch (e) {
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
94
|
+
// INVARIANT (promotion is a retired-anchor GC, not a line-count escape hatch): a read that
|
|
95
|
+
// cannot be hashed at all must leave hazard state untouched — so the uncurable refusals
|
|
96
|
+
// (the line cap, and any other non-promotable error) rethrow HERE, before the store is
|
|
97
|
+
// reached. Clearing this (session,path)'s retired anchors for a failure the retry cannot
|
|
98
|
+
// cure would degrade stale-anchor checks while the same error still reaches the model.
|
|
99
|
+
if (!isPromotableAnchorSpaceExhaustion(e))
|
|
100
|
+
throw e;
|
|
101
|
+
const retiredCount = retiredHashes.size;
|
|
102
|
+
const servedCount = servedForNorm.filter((h) => h !== null).length;
|
|
103
|
+
const reservedCount = retiredCount + servedCount;
|
|
104
|
+
// Major GC promotion: clear retired for this (session,path), keep served/canons
|
|
105
|
+
try {
|
|
106
|
+
const store = await loadServedStore();
|
|
107
|
+
store.clearRetiredAnchors(sessionKey, absolutePath);
|
|
99
108
|
try {
|
|
100
|
-
|
|
101
|
-
store.clearRetiredAnchors(sessionKey, absolutePath);
|
|
102
|
-
try {
|
|
103
|
-
store.clearCards(sessionKey, absolutePath);
|
|
104
|
-
}
|
|
105
|
-
catch {
|
|
106
|
-
// Best-effort: card state is a cache; the promotion retry below proceeds without it.
|
|
107
|
-
}
|
|
109
|
+
store.clearCards(sessionKey, absolutePath);
|
|
108
110
|
}
|
|
109
111
|
catch {
|
|
110
|
-
// Best-effort:
|
|
111
|
-
// in-memory reservation state (ADR-0020 R2, promotion/wipe arm).
|
|
112
|
+
// Best-effort: card state is a cache; the promotion retry below proceeds without it.
|
|
112
113
|
}
|
|
113
|
-
// Soft promotion notice: plain non-header text (no [E_] code, no audience).
|
|
114
|
-
promotionWarning = `Anchor space exhausted (retired ${retiredCount} + served ${servedCount} = ${reservedCount} of ${HASH_SPACE}); promotion cleared retired — re-read recommended, stale-anchor checks degraded until next full read.`;
|
|
115
|
-
// Retry ignoring retired (served only) — also drop removedHashes from previous
|
|
116
|
-
retiredHashes = new Set();
|
|
117
|
-
reservedHashes = new Set([...servedForNorm.filter((h) => h !== null)]);
|
|
118
|
-
reservations = { reservedHashes, retiredHashes };
|
|
119
|
-
if (previous)
|
|
120
|
-
previous = { content: previous.content, hashes: previous.hashes };
|
|
121
|
-
view = await readView(io, rawPath, cwd, {
|
|
122
|
-
encoding: options.encoding,
|
|
123
|
-
offset: options.offset,
|
|
124
|
-
limit: options.limit,
|
|
125
|
-
windows: options.windows,
|
|
126
|
-
signal,
|
|
127
|
-
reservedHashes: reservations.reservedHashes,
|
|
128
|
-
retiredHashes: reservations.retiredHashes,
|
|
129
|
-
previous,
|
|
130
|
-
});
|
|
131
114
|
}
|
|
132
|
-
|
|
133
|
-
|
|
115
|
+
catch {
|
|
116
|
+
// Best-effort: a store fault here must not fail the read — the retry proceeds on the
|
|
117
|
+
// in-memory reservation state (ADR-0020 R2, promotion/wipe arm).
|
|
134
118
|
}
|
|
119
|
+
// Soft promotion notice: plain non-header text (no [E_] code, no audience).
|
|
120
|
+
promotionWarning = `Anchor space exhausted (retired ${retiredCount} + served ${servedCount} = ${reservedCount} of ${HASH_SPACE}); promotion cleared retired — re-read recommended, stale-anchor checks degraded until next full read.`;
|
|
121
|
+
// Retry ignoring retired (served only) — also drop removedHashes from previous
|
|
122
|
+
retiredHashes = new Set();
|
|
123
|
+
reservedHashes = new Set([...servedForNorm.filter((h) => h !== null)]);
|
|
124
|
+
reservations = { reservedHashes, retiredHashes };
|
|
125
|
+
if (previous)
|
|
126
|
+
previous = { content: previous.content, hashes: previous.hashes };
|
|
127
|
+
view = await readView(io, rawPath, cwd, {
|
|
128
|
+
encoding: options.encoding,
|
|
129
|
+
offset: options.offset,
|
|
130
|
+
limit: options.limit,
|
|
131
|
+
windows: options.windows,
|
|
132
|
+
signal,
|
|
133
|
+
reservedHashes: reservations.reservedHashes,
|
|
134
|
+
retiredHashes: reservations.retiredHashes,
|
|
135
|
+
previous,
|
|
136
|
+
});
|
|
135
137
|
}
|
|
136
138
|
let servedLanded = true;
|
|
137
139
|
if (view.served.length > 0) {
|
|
138
140
|
const canons = splitLines(view.normalized).map((l) => canon(l));
|
|
139
|
-
const canonServed = canons.map((canonText) => canonText);
|
|
140
141
|
// Pad or trim canons to served length? For now use canons for full file
|
|
141
142
|
const fullCanons = [];
|
|
142
143
|
for (let i = 0; i < view.hashes.length; i++) {
|
|
@@ -146,22 +147,19 @@ export async function readAndServe(io, rawPath, cwd, options) {
|
|
|
146
147
|
hashes: view.hashes,
|
|
147
148
|
canons: fullCanons,
|
|
148
149
|
content: view.normalized,
|
|
150
|
+
// The verdict travels with the serve: FileView computed it from the request shape, this
|
|
151
|
+
// seam only carries it (ADR-0035).
|
|
152
|
+
fullRead: view.fullRead,
|
|
149
153
|
});
|
|
150
154
|
}
|
|
151
|
-
// #69: epoch lifecycle belongs to full reads — a partial (paged or
|
|
152
|
-
//
|
|
153
|
-
//
|
|
154
|
-
// no
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
!hasRequestedWindows(options.windows) &&
|
|
158
|
-
!view.truncation?.truncated;
|
|
159
|
-
if (isFullRead)
|
|
155
|
+
// #69: epoch lifecycle belongs to full reads — a partial (paged or truncated) read merges window
|
|
156
|
+
// rows only and must not clear the drift-reported marks; only a full read resets them. The
|
|
157
|
+
// verdict is `view.fullRead` (ADR-0035): FileView owns the request-shape rule — including
|
|
158
|
+
// `undefined`/`[]` → no windows via `hasRequestedWindows` — so no second predicate exists here
|
|
159
|
+
// to disagree with it.
|
|
160
|
+
if (view.fullRead)
|
|
160
161
|
await clearDriftReported(sessionKey, view.absolutePath);
|
|
161
|
-
const autoFooter = getAutoGuessFooter(view.absolutePath) ??
|
|
162
|
-
getAutoGuessFooter(rawPath) ??
|
|
163
|
-
getAutoGuessFooter(view.absolutePath.replace(/\\/g, "/")) ??
|
|
164
|
-
"";
|
|
162
|
+
const autoFooter = getAutoGuessFooter(view.absolutePath) ?? "";
|
|
165
163
|
const autoWarning = autoFooter || undefined;
|
|
166
164
|
const warning = promotionWarning
|
|
167
165
|
? autoWarning
|
package/lib/reclaim.js
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shared tool reclamation utility for DSH scoped layers.
|
|
3
|
+
* Used by installAgentTools and createSelfHealWatcher.
|
|
4
|
+
* @module dsh-better-edit/reclaim
|
|
5
|
+
*/
|
|
6
|
+
/**
|
|
7
|
+
* Resolve the agent's scoped tool layer from the DSH tools service.
|
|
8
|
+
*/
|
|
9
|
+
export function getAgentScopedToolLayer(toolsSvc, agent) {
|
|
10
|
+
// SAFETY: toolsSvc is the DSH tools service — shape is `layers.scoped: Map<agent, {tools}>` per Cordis internals; narrow at boundary
|
|
11
|
+
return toolsSvc?.layers?.scoped?.get?.(agent)?.tools;
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* Reclaim an entry by deleting it from the scoped layer's data map.
|
|
15
|
+
*/
|
|
16
|
+
export function reclaimToolEntry(layer, name) {
|
|
17
|
+
if (!layer?.data)
|
|
18
|
+
return false;
|
|
19
|
+
try {
|
|
20
|
+
const deleted = layer.data.delete(name);
|
|
21
|
+
return Boolean(deleted && layer.get?.(name) === undefined);
|
|
22
|
+
}
|
|
23
|
+
catch {
|
|
24
|
+
return false;
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Register a tool with collision detection, guarded reclaim, and single retry.
|
|
29
|
+
*/
|
|
30
|
+
export function registerWithReclaim(options) {
|
|
31
|
+
const { toolsSvc, agent, agentCtx, name, def, logger } = options;
|
|
32
|
+
const layer = getAgentScopedToolLayer(toolsSvc, agent);
|
|
33
|
+
const current = layer?.get?.(name) ?? layer?.data?.get?.(name);
|
|
34
|
+
if (current === def)
|
|
35
|
+
return () => { }; // Already registered with same ref; return no-op disposer
|
|
36
|
+
try {
|
|
37
|
+
return agentCtx.tools.register(def);
|
|
38
|
+
}
|
|
39
|
+
catch (initialError) {
|
|
40
|
+
const errorStr = String(initialError);
|
|
41
|
+
const isCollision = errorStr.includes("already registered") || current != null;
|
|
42
|
+
if (!isCollision) {
|
|
43
|
+
logger?.warn(`dsh-better-edit: tool "${name}" registration failed with non-collision error: ${errorStr} (#123)`);
|
|
44
|
+
return undefined;
|
|
45
|
+
}
|
|
46
|
+
if (!layer) {
|
|
47
|
+
logger?.warn(`dsh-better-edit: cannot reclaim tool "${name}" because scoped layer is unresolvable (#123)`);
|
|
48
|
+
return undefined;
|
|
49
|
+
}
|
|
50
|
+
const reclaimed = reclaimToolEntry(layer, name);
|
|
51
|
+
if (!reclaimed) {
|
|
52
|
+
logger?.warn(`dsh-better-edit: cannot reclaim contested tool "${name}" from scoped layer (#123)`);
|
|
53
|
+
return undefined;
|
|
54
|
+
}
|
|
55
|
+
try {
|
|
56
|
+
const dispose = agentCtx.tools.register(def);
|
|
57
|
+
logger?.warn(`dsh-better-edit: reclaimed contested tool "${name}" from peer registration (#123)`);
|
|
58
|
+
return dispose;
|
|
59
|
+
}
|
|
60
|
+
catch (retryError) {
|
|
61
|
+
logger?.warn(`dsh-better-edit: failed to register tool "${name}" after reclaim: ${String(retryError)} (#123)`);
|
|
62
|
+
return undefined;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
}
|
package/lib/self-heal.js
CHANGED
|
@@ -7,6 +7,7 @@
|
|
|
7
7
|
* See Rianico/dsh-better-edit#43.
|
|
8
8
|
* @module dsh-better-edit/self-heal
|
|
9
9
|
*/
|
|
10
|
+
import { getAgentScopedToolLayer, reclaimToolEntry } from "./reclaim.js";
|
|
10
11
|
export function createSelfHealWatcher(options) {
|
|
11
12
|
const { agentId, rootCtx, agent, agentCtx, toolsSvc, hashReadDef, hashEditDef, hashStrReplaceDef, healMinIntervalMs = 1000, } = options;
|
|
12
13
|
const watchEdit = hashEditDef !== undefined;
|
|
@@ -20,8 +21,7 @@ export function createSelfHealWatcher(options) {
|
|
|
20
21
|
try {
|
|
21
22
|
if (selfHealDisabled)
|
|
22
23
|
return;
|
|
23
|
-
|
|
24
|
-
const layer = toolsSvc?.layers?.scoped?.get?.(agent)?.tools;
|
|
24
|
+
const layer = getAgentScopedToolLayer(toolsSvc, agent);
|
|
25
25
|
if (!layer)
|
|
26
26
|
return;
|
|
27
27
|
const currentRead = layer?.get?.("read") ?? layer?.data?.get?.("read");
|
|
@@ -57,17 +57,13 @@ export function createSelfHealWatcher(options) {
|
|
|
57
57
|
const restoreCount = healCount;
|
|
58
58
|
queueMicrotask(() => {
|
|
59
59
|
try {
|
|
60
|
-
|
|
61
|
-
const currentLayer = toolsSvc?.layers?.scoped?.get?.(agent)?.tools;
|
|
60
|
+
const currentLayer = getAgentScopedToolLayer(toolsSvc, agent);
|
|
62
61
|
if (!currentLayer)
|
|
63
62
|
return;
|
|
64
63
|
const restoreTool = (name, def, toolLabel) => {
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
catch {
|
|
69
|
-
// ignore — best-effort delete of intruding entry
|
|
70
|
-
}
|
|
64
|
+
// Best-effort delete of an intruding entry; a failed delete
|
|
65
|
+
// surfaces through the register throw below.
|
|
66
|
+
reclaimToolEntry(currentLayer, name);
|
|
71
67
|
try {
|
|
72
68
|
agentCtx.tools.register(def);
|
|
73
69
|
}
|
package/lib/session-view.js
CHANGED
|
@@ -9,8 +9,8 @@
|
|
|
9
9
|
*
|
|
10
10
|
* Public surface: _mergeServedRows, loadServed, recordServed,
|
|
11
11
|
* recordServedTruncated, driftReported, markDriftReported,
|
|
12
|
-
* clearDriftReported, wipeServedState, servedPositionsOf
|
|
13
|
-
* currentPositionOfDrifted, computeDrift, scanDrift, and
|
|
12
|
+
* clearDriftReported, wipeServedState, servedPositionsOf (re-exported from
|
|
13
|
+
* hashline/served-evidence), currentPositionOfDrifted, computeDrift, scanDrift, and
|
|
14
14
|
* hash-store persistence delegation (ServedPersistence).
|
|
15
15
|
*
|
|
16
16
|
* Ownership: This file OWNS the served-merge invariant
|
|
@@ -25,8 +25,11 @@
|
|
|
25
25
|
import { ALPH, HASH_LEN, HASH_SPACE, HASH_RE, canon } from "./hashline/hash-assign.js";
|
|
26
26
|
import { loadServedStore, withStore, DRIFT_EPISODE_PREFIX, DRIFT_EPISODE_RE, } from "./hash-store.js";
|
|
27
27
|
import { SERVED_ECHO_CAP } from "./constants.js";
|
|
28
|
-
import { fmtServedRows } from "./hashline/
|
|
28
|
+
import { fmtServedRows, moreRowsHint, servedPositionsOf } from "./hashline/served-evidence.js";
|
|
29
29
|
import { splitLines } from "./utils.js";
|
|
30
|
+
// Re-exported from the served-evidence leaf (ADR-0037): the scan is pure and the
|
|
31
|
+
// verifier needs it, so the seam that owns it is the evidence module.
|
|
32
|
+
export { servedPositionsOf };
|
|
30
33
|
// --- hash-store re-export (persistence note) ---
|
|
31
34
|
export { loadHashStore, loadServedStore, shutdownHashStore, withStore } from "./hash-store.js";
|
|
32
35
|
/**
|
|
@@ -83,16 +86,32 @@ function addRetiredAnchors(store, sessionKey, path, hashes) {
|
|
|
83
86
|
const additions = [...hashes];
|
|
84
87
|
if (additions.length === 0)
|
|
85
88
|
return;
|
|
86
|
-
|
|
89
|
+
// Contract first, dedupe second: an invalid hash is rejected whether or not it is new.
|
|
87
90
|
for (const hash of additions) {
|
|
88
91
|
if (!HASH_RE.test(hash)) {
|
|
89
92
|
throw new TypeError(`Invalid retired hash: ${hash}`);
|
|
90
93
|
}
|
|
91
|
-
retired.add(hash);
|
|
92
94
|
}
|
|
93
|
-
//
|
|
94
|
-
//
|
|
95
|
-
|
|
95
|
+
// WHY (ADR-0036): ONE writer, ONE serialization. `sweepAndRetire` and
|
|
96
|
+
// `unretireAnchorsInStore` read and write `RetiredEntry[]`; this appender is the third
|
|
97
|
+
// writer of the same column, so it must too — an appended entry carries `deathPos: null`
|
|
98
|
+
// (unknown position) while every existing entry keeps its own death position. Writing
|
|
99
|
+
// bare strings here rewrote the whole column into the shape `parseRetiredJson` coerces to
|
|
100
|
+
// `deathPos: null`, which no incremental sweep can free (accumulation until a full read).
|
|
101
|
+
// `store.getRetiredAnchors` stays the READ-side projection and is not used for writing.
|
|
102
|
+
const existing = store.getRetiredEntries(sessionKey, path);
|
|
103
|
+
const known = new Set(existing.map((entry) => entry.hash));
|
|
104
|
+
const appended = [];
|
|
105
|
+
for (const hash of additions) {
|
|
106
|
+
if (known.has(hash))
|
|
107
|
+
continue;
|
|
108
|
+
known.add(hash);
|
|
109
|
+
appended.push({ hash, deathPos: null });
|
|
110
|
+
}
|
|
111
|
+
// Idempotent retirement must not bump the row.
|
|
112
|
+
if (appended.length === 0)
|
|
113
|
+
return;
|
|
114
|
+
store.upsertRetiredAnchors(sessionKey, path, JSON.stringify([...existing, ...appended]));
|
|
96
115
|
}
|
|
97
116
|
function displacedEntries(current, updated) {
|
|
98
117
|
const remaining = new Set(updated.filter((hash) => hash !== null));
|
|
@@ -106,7 +125,8 @@ function displacedEntries(current, updated) {
|
|
|
106
125
|
return entries;
|
|
107
126
|
}
|
|
108
127
|
// deathPos=null = legacy/unknown position (pre-GC String[] format or migration).
|
|
109
|
-
// These entries are NOT swept incrementally — retained until full-
|
|
128
|
+
// These entries are NOT swept incrementally — retained until a full-read serve (the `fullRead`
|
|
129
|
+
// verdict) or major-GC promotion clears retired.
|
|
110
130
|
// Incremental hazard sweep only frees deathPos (number) whose card was re-observed; null survives partial sweeps by design (minor leak documented here) and is drained only on epoch promotion/full read.
|
|
111
131
|
function sweepAndRetire(store, sessionKey, path, current, updated, rows) {
|
|
112
132
|
const servedPositions = new Set(rows.map((r) => r.position));
|
|
@@ -170,6 +190,22 @@ export function unretireAnchorsInStore(store, sessionKey, path, hashes) {
|
|
|
170
190
|
store.upsertRetiredAnchors(sessionKey, path, JSON.stringify(kept));
|
|
171
191
|
}
|
|
172
192
|
}
|
|
193
|
+
/**
|
|
194
|
+
* Assertion about FileView, never a decision (ADR-0035): a full-read verdict must arrive with a
|
|
195
|
+
* dense mirror — `rows` covering every hash of the file, in order, hash for hash. Rows that fall
|
|
196
|
+
* short of that were served by a read that also claims to have shown the whole file; the two
|
|
197
|
+
* cannot both be right, so the disagreement is reported with the path and the counts, and the
|
|
198
|
+
* verdict still decides (a warning must not silently become a second authority).
|
|
199
|
+
*/
|
|
200
|
+
function warnOnNonDenseFullReadMirror(path, rows, full) {
|
|
201
|
+
const dense = rows.length === full.hashes.length &&
|
|
202
|
+
rows.every((row, index) => row.position === index && row.hash === full.hashes[index]);
|
|
203
|
+
if (dense)
|
|
204
|
+
return;
|
|
205
|
+
console.warn(`dsh-better-edit: full read of ${path} served a non-dense mirror (${rows.length} row(s) for ` +
|
|
206
|
+
`${full.hashes.length} hash(es)) — proceeding on the full-read verdict; FileView.served ` +
|
|
207
|
+
`disagrees with FileView.hashes.`);
|
|
208
|
+
}
|
|
173
209
|
/**
|
|
174
210
|
* Funnel for lease granting: materialize-or-adopt the serve snapshot and grant
|
|
175
211
|
* leases for the served rows as-is. Caller-owned transaction: this must run
|
|
@@ -195,6 +231,10 @@ function grantServeLeases(store, sessionKey, path, rows, hashes, content) {
|
|
|
195
231
|
* `false` means the write rolled back and no lease was granted, so the caller must not advertise
|
|
196
232
|
* the rows' anchors as usable: that is a partial failure of the caller's operation, not a failed
|
|
197
233
|
* operation. The best-effort contract is unchanged — this never throws.
|
|
234
|
+
*
|
|
235
|
+
* The context's `fullRead` verdict — not the shape of `rows` — decides whether this serve also
|
|
236
|
+
* performs the full-read effects (clearing retired anchors and hazard cards, overwriting the whole
|
|
237
|
+
* canon array); everything else here belongs to every serve alike (ADR-0035).
|
|
198
238
|
*/
|
|
199
239
|
export async function recordServed(sessionKey, path, rows, lineCount, full) {
|
|
200
240
|
// Nothing to record, so nothing can fail: vacuously landed.
|
|
@@ -202,9 +242,12 @@ export async function recordServed(sessionKey, path, rows, lineCount, full) {
|
|
|
202
242
|
return true;
|
|
203
243
|
try {
|
|
204
244
|
const store = await loadServedStore();
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
245
|
+
// The verdict is the caller's, not ours (ADR-0035): FileView knows the request shape, this
|
|
246
|
+
// seam only sees rows. The density check that used to decide here is the assertion below —
|
|
247
|
+
// it reports a FileView/rows disagreement and then gets out of the verdict's way.
|
|
248
|
+
const isFullRead = full?.fullRead === true;
|
|
249
|
+
if (isFullRead && full !== undefined)
|
|
250
|
+
warnOnNonDenseFullReadMirror(path, rows, full);
|
|
208
251
|
withStore(() => {
|
|
209
252
|
const current = store.getServed(sessionKey, path);
|
|
210
253
|
const updated = _mergeServedRows(current, rows, lineCount === undefined ? undefined : { truncateTo: lineCount });
|
|
@@ -244,6 +287,11 @@ export async function recordServed(sessionKey, path, rows, lineCount, full) {
|
|
|
244
287
|
sweepAndRetire(store, sessionKey, path, current, updated, rows);
|
|
245
288
|
}
|
|
246
289
|
// Pair #6: the lease grant and the `served` row it derives from are ONE unit.
|
|
290
|
+
//
|
|
291
|
+
// WHY the grant is NOT gated on the full-read verdict (ADR-0035): a served anchor is
|
|
292
|
+
// editable only through its lease, and a lease is stamped with the snapshot it belongs to,
|
|
293
|
+
// so a page still commits the content it showed. Gate this and a displayed anchor becomes
|
|
294
|
+
// uneditable (`E_UNKNOWN_ANCHOR` on page-then-edit, 12 cells across 7 files).
|
|
247
295
|
grantServeLeases(store, sessionKey, path, rows, full?.hashes, full?.content);
|
|
248
296
|
});
|
|
249
297
|
return true;
|
|
@@ -351,14 +399,6 @@ export async function wipeServedState(sessionKey) {
|
|
|
351
399
|
console.error("Failed to wipe served state:", error);
|
|
352
400
|
}
|
|
353
401
|
}
|
|
354
|
-
export function servedPositionsOf(served, hash) {
|
|
355
|
-
const out = [];
|
|
356
|
-
for (let i = 0; i < served.length; i++) {
|
|
357
|
-
if (served[i] === hash)
|
|
358
|
-
out.push(i);
|
|
359
|
-
}
|
|
360
|
-
return out;
|
|
361
|
-
}
|
|
362
402
|
function nearestSurvivingPosition(served, surviving, from, direction) {
|
|
363
403
|
if (direction === "below") {
|
|
364
404
|
for (let q = from - 1; q >= 0; q--) {
|
|
@@ -545,7 +585,7 @@ export function computeDrift(input) {
|
|
|
545
585
|
drifted: driftedSet.has(position),
|
|
546
586
|
}));
|
|
547
587
|
const rowsText = fmtServedRows(rows, resultLines);
|
|
548
|
-
const moreText = unshown > 0 ? `\n
|
|
588
|
+
const moreText = unshown > 0 ? `\n${moreRowsHint(unshown, "re-read to see")}` : "";
|
|
549
589
|
return {
|
|
550
590
|
text: `${DRIFT_NOTICE_HEADING} ${countLabel} changed outside the range:\n${rowsText}${moreText}`,
|
|
551
591
|
rows,
|
package/lib/store/index.js
CHANGED
|
@@ -1,28 +1,28 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Store —
|
|
2
|
+
* Store — seam VIEW over tenancy + lifecycle + path resolution.
|
|
3
3
|
*
|
|
4
|
-
* Single seam that answers "which store, where, and is it open?"
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
-
*
|
|
4
|
+
* Single seam that answers "which store, where, and is it open?" for its
|
|
5
|
+
* consumers. This file owns no behaviour: every export below is a re-export
|
|
6
|
+
* of code owned by a leaf module.
|
|
7
|
+
*
|
|
8
|
+
* Ownership direction, stated once and not to be inverted:
|
|
9
|
+
* `store-config` → `store-tenancy` → this barrel, and `hash-store` → this
|
|
10
|
+
* barrel. The leaves hold the code — `store-tenancy` resolves where the DB
|
|
11
|
+
* lives and imports `loadConfig` FROM `store-config`, which resolves its own
|
|
12
|
+
* path through `resolveDshHome` — while this file is the view they surface
|
|
13
|
+
* through.
|
|
10
14
|
*
|
|
11
15
|
* YAGNI-gated: DB plumbing (openDb/buildStore/quarantine/busy-retry/
|
|
12
16
|
* WAL/legacy JSON migration) stays in hash-store for now and is
|
|
13
17
|
* re-exported here for testability without importing domain helpers
|
|
14
|
-
* — full plumbing move is deferred to avoid contract risk.
|
|
15
|
-
* store-tenancy/store-lifecycle files are kept as compat shims
|
|
16
|
-
* re-exporting from this seam (reversible).
|
|
18
|
+
* — full plumbing move is deferred to avoid contract risk.
|
|
17
19
|
*
|
|
18
20
|
* @module dsh-better-edit/store
|
|
19
21
|
*/
|
|
20
|
-
// Tenancy — re-
|
|
22
|
+
// Tenancy — re-exported from its owner (`store-tenancy`), surfaced here
|
|
21
23
|
export { tenancyFor, configDir, hashStorePath, hashStoreDir, legacyHashStorePath, loadConfig, _resetConfigCache, expand, } from "../store-tenancy.js";
|
|
22
|
-
// Lifecycle — re-
|
|
24
|
+
// Lifecycle — re-exported from its owner (`store-lifecycle`)
|
|
23
25
|
export { onStoreOpen, onAppStart, onSessionStart, setStoresGetter, runCentralJanitorIfDue, _resetLifecycleForTests, } from "../store-lifecycle.js";
|
|
24
|
-
// StoreConfig path helper — canonical Store seam entry for config consumers
|
|
25
|
-
export { loadConfig as loadStoreConfig } from "../store-config.js";
|
|
26
26
|
// Hash-store plumbing re-exported for testability without domain coupling
|
|
27
27
|
// (future: move openDb/buildStore/quarantine/busy-retry here)
|
|
28
28
|
export { isCorruptionError, loadHashStore, shutdownHashStore, withStore, findSnapshotPathsByHashes, upsertSnapshotFor, } from "../hash-store.js";
|
package/lib/store-config.js
CHANGED
|
@@ -11,6 +11,7 @@ import { mkdir, writeFile } from "node:fs/promises";
|
|
|
11
11
|
import { resolveDshHome } from "@deepseek-ai/dsh-home-paths";
|
|
12
12
|
import { z } from "zod";
|
|
13
13
|
import { errCode } from "./utils.js";
|
|
14
|
+
import { SUPPORTED_ENCODINGS } from "./encoding.js";
|
|
14
15
|
// ---- helpers (pure, no IO) ----
|
|
15
16
|
function homeBase() {
|
|
16
17
|
const envHome = process.env.HOME;
|
|
@@ -93,9 +94,7 @@ const StoreConfigSchema = z.object({
|
|
|
93
94
|
autoGitignore: z.boolean().default(false), // workspace only: auto-append ".dsh_better_edit/" to .gitignore when .git exists but entry missing (false = warn once)
|
|
94
95
|
autoGuessEncoding: z.boolean().default(false), // VS Code files.autoGuessEncoding — deterministic BOM→UTF-8 first, model-assisted top-3 only when true
|
|
95
96
|
normalizeToUtf8: z.boolean().default(false), // when true, legacy files (GBK etc.) migrate to UTF-8 on first edit/write
|
|
96
|
-
supportedEncodings: z
|
|
97
|
-
.array(z.string())
|
|
98
|
-
.default(["gbk", "big5", "shift_jis", "euc-kr", "windows-1251", "iso-8859-1"]),
|
|
97
|
+
supportedEncodings: z.array(z.string()).default([...SUPPORTED_ENCODINGS]),
|
|
99
98
|
undo_ttl_s: z.number().int().min(-1).default(604800), // undo history TTL in seconds; -1 = keep forever (default 604800 = 7 days)
|
|
100
99
|
storeMaxAgeS: z.number().int().min(1).default(2592000), // central janitor: max idle age in seconds before evicting runtime/<name>-<hash8>/ (default 2592000 = 30 days)
|
|
101
100
|
storeMaxTotalBytes: z.number().int().min(0).default(524288000), // central janitor: max total bytes under runtime/ before LRU eviction (default 524288000 = 500 MB)
|
|
@@ -131,7 +130,7 @@ autoGuessEncoding: false
|
|
|
131
130
|
# when true, legacy files (GBK etc.) migrate to UTF-8 on first write
|
|
132
131
|
normalizeToUtf8: false
|
|
133
132
|
# allowlist scored for top-3 previews when autoGuessEncoding:true
|
|
134
|
-
supportedEncodings: [
|
|
133
|
+
supportedEncodings: [${SUPPORTED_ENCODINGS.join(", ")}]
|
|
135
134
|
|
|
136
135
|
# undo history TTL in seconds; -1 = keep forever (default 604800 = 7 days)
|
|
137
136
|
undo_ttl_s: 604800
|
|
@@ -355,7 +354,7 @@ function complementMissingFieldsSync(yamlPath, yamlPartial) {
|
|
|
355
354
|
if (yamlPartial.normalizeToUtf8 === undefined)
|
|
356
355
|
missingLines.push("normalizeToUtf8: false");
|
|
357
356
|
if (yamlPartial.supportedEncodings === undefined)
|
|
358
|
-
missingLines.push(
|
|
357
|
+
missingLines.push(`supportedEncodings: [${SUPPORTED_ENCODINGS.join(", ")}]`);
|
|
359
358
|
if (yamlPartial.undo_ttl_s === undefined)
|
|
360
359
|
missingLines.push("undo_ttl_s: 604800");
|
|
361
360
|
if (yamlPartial.storeMaxAgeS === undefined)
|
package/lib/store-lifecycle.js
CHANGED
|
@@ -15,7 +15,7 @@ import { readdir, rm, stat } from "node:fs/promises";
|
|
|
15
15
|
import { dirname, join } from "node:path";
|
|
16
16
|
import { DatabaseSync } from "node:sqlite";
|
|
17
17
|
import { resolveDshHome } from "@deepseek-ai/dsh-home-paths";
|
|
18
|
-
import {
|
|
18
|
+
import { loadConfig } from "./store-config.js";
|
|
19
19
|
import { workspaceCwd } from "./workspace-context.js";
|
|
20
20
|
import { errCode, splitLines } from "./utils.js";
|
|
21
21
|
import { HASH_STORE_BUSY_TIMEOUT, SERVED_TTL_MS } from "./constants.js";
|
package/lib/tool-edit.js
CHANGED
package/lib/tool-read.js
CHANGED
|
@@ -9,7 +9,7 @@ import { defineTool } from "@deepseek-ai/dsh-tools";
|
|
|
9
9
|
import { normalizeRequest as normReq, assertReadRequest, pathSchema } from "./contract.js";
|
|
10
10
|
import { readAndServe } from "./read-and-serve.js";
|
|
11
11
|
import { READ_DESCRIPTION } from "./prompts.js";
|
|
12
|
-
import { normalizeEncoding } from "./encoding.js";
|
|
12
|
+
import { normalizeEncoding, SUPPORTED_ENCODINGS_LABEL } from "./encoding.js";
|
|
13
13
|
import { DomainError } from "./domain-errors.js";
|
|
14
14
|
import { MAX_READ_WINDOWS } from "./file-view.js";
|
|
15
15
|
import { renderTextWarning } from "./render-text-warning.js";
|
|
@@ -82,7 +82,7 @@ export function buildReadTool(io) {
|
|
|
82
82
|
const norm = normalizeEncoding(String(encoding));
|
|
83
83
|
if (!norm)
|
|
84
84
|
throw new DomainError("E_BAD_PAYLOAD", {
|
|
85
|
-
message: `Unknown encoding: ${String(encoding)}. Supported:
|
|
85
|
+
message: `Unknown encoding: ${String(encoding)}. Supported: ${SUPPORTED_ENCODINGS_LABEL}`,
|
|
86
86
|
});
|
|
87
87
|
}
|
|
88
88
|
const canonical = normReq(args);
|
|
@@ -105,9 +105,3 @@ export function buildReadTool(io) {
|
|
|
105
105
|
},
|
|
106
106
|
});
|
|
107
107
|
}
|
|
108
|
-
/**
|
|
109
|
-
* Register the hashline tool on the calling agent’s scope (own layer).
|
|
110
|
-
*/
|
|
111
|
-
export function registerReadTool(_rootCtx, agentCtx, io) {
|
|
112
|
-
return agentCtx.tools.register(buildReadTool(io));
|
|
113
|
-
}
|
|
@@ -142,11 +142,8 @@ function restoreForSave(content, absolutePath) {
|
|
|
142
142
|
displayPath: absolutePath,
|
|
143
143
|
}).textToWrite;
|
|
144
144
|
}
|
|
145
|
-
function autoGuessWarning(absolutePath
|
|
146
|
-
return
|
|
147
|
-
getAutoGuessFooter(rawPath) ??
|
|
148
|
-
getAutoGuessFooter(absolutePath.replace(/\\/g, "/")) ??
|
|
149
|
-
undefined);
|
|
145
|
+
function autoGuessWarning(absolutePath) {
|
|
146
|
+
return getAutoGuessFooter(absolutePath);
|
|
150
147
|
}
|
|
151
148
|
export function buildStrReplaceEditorTool(io, sandbox) {
|
|
152
149
|
return defineTool({
|
|
@@ -245,7 +242,7 @@ export function buildStrReplaceEditorTool(io, sandbox) {
|
|
|
245
242
|
}
|
|
246
243
|
}
|
|
247
244
|
}
|
|
248
|
-
const warning = autoGuessWarning(absolutePath
|
|
245
|
+
const warning = autoGuessWarning(absolutePath);
|
|
249
246
|
return warning ? { text: out, warning } : { text: out };
|
|
250
247
|
}
|
|
251
248
|
if (cmd === "create") {
|
|
@@ -326,7 +323,3 @@ export function buildStrReplaceEditorTool(io, sandbox) {
|
|
|
326
323
|
},
|
|
327
324
|
});
|
|
328
325
|
}
|
|
329
|
-
/** Register the shadow `str_replace_editor` on the calling agent's scope (own layer). */
|
|
330
|
-
export function registerStrReplaceEditorTool(agentCtx, io, sandbox) {
|
|
331
|
-
return agentCtx.tools.register(buildStrReplaceEditorTool(io, sandbox));
|
|
332
|
-
}
|
package/lib/tool-undo.js
CHANGED
|
@@ -11,7 +11,7 @@ import { DomainError, formatError } from "./domain-errors.js";
|
|
|
11
11
|
import { assertUndoRequest } from "./contract.js";
|
|
12
12
|
import { normalizeRequest as normReq } from "./contract.js";
|
|
13
13
|
import { loadHashStore, withStore } from "./hash-store.js";
|
|
14
|
-
import {
|
|
14
|
+
import { HASH_SPACE, canon, contentChecksum, isPromotableAnchorSpaceExhaustion, } from "./hashline/hash-assign.js";
|
|
15
15
|
import { lineHashes } from "./hashline/hash.js";
|
|
16
16
|
import { changedRange } from "./hashline/anchor-pipeline.js";
|
|
17
17
|
import { getUndo, clearUndo } from "./undo-edit.js";
|
|
@@ -21,28 +21,26 @@ import { execCwd, execSessionKey } from "./workspace-context.js";
|
|
|
21
21
|
import { withWorkspace } from "./workspace-context.js";
|
|
22
22
|
import { encodingHintAtVersion, getEncodingState, prepareForSave } from "./file-encoding-state.js";
|
|
23
23
|
import { loadConfig } from "./store-config.js";
|
|
24
|
-
function isAnchorSpaceExhausted(e) {
|
|
25
|
-
return (e instanceof AnchorSpaceExhaustedError ||
|
|
26
|
-
(e instanceof Error && e.message.includes("probing failed over")));
|
|
27
|
-
}
|
|
28
24
|
/**
|
|
29
25
|
* Anchor-space exhaustion guard mirrored from the edit path (`retryLineHashesWithPromotion` in
|
|
30
26
|
* src/mutation/engine.ts): clear this (session, path)'s retired anchors once to promote hash space
|
|
31
27
|
* and retry; a retry that still exhausts is a typed hard capacity refusal, never a raw probe error.
|
|
28
|
+
* The exhaustion test itself is shared (`isPromotableAnchorSpaceExhaustion`) — see its docblock
|
|
29
|
+
* for why promotion's question is narrower than "is this exhaustion".
|
|
32
30
|
*/
|
|
33
31
|
async function hashWithAnchorSpacePromotion(fn, onPromote) {
|
|
34
32
|
try {
|
|
35
33
|
return await fn();
|
|
36
34
|
}
|
|
37
35
|
catch (error) {
|
|
38
|
-
if (!
|
|
36
|
+
if (!isPromotableAnchorSpaceExhaustion(error))
|
|
39
37
|
throw error;
|
|
40
38
|
await onPromote();
|
|
41
39
|
try {
|
|
42
40
|
return await fn();
|
|
43
41
|
}
|
|
44
42
|
catch (retryError) {
|
|
45
|
-
if (
|
|
43
|
+
if (isPromotableAnchorSpaceExhaustion(retryError))
|
|
46
44
|
throw new DomainError("E_LARGE_FILE", { limitKind: "hash-space", limit: HASH_SPACE });
|
|
47
45
|
throw retryError;
|
|
48
46
|
}
|
|
@@ -242,9 +240,3 @@ export function buildUndoTool(io, sandbox) {
|
|
|
242
240
|
},
|
|
243
241
|
});
|
|
244
242
|
}
|
|
245
|
-
/**
|
|
246
|
-
* Register the hashline tool on the calling agent’s scope (own layer).
|
|
247
|
-
*/
|
|
248
|
-
export function registerUndoTool(_rootCtx, agentCtx, io, sandbox) {
|
|
249
|
-
return agentCtx.tools.register(buildUndoTool(io, sandbox));
|
|
250
|
-
}
|
package/lib/types/contract.d.ts
CHANGED
|
@@ -9,7 +9,8 @@
|
|
|
9
9
|
* @module dsh-better-edit/contract
|
|
10
10
|
*/
|
|
11
11
|
import type { ReadWindow } from "./file-view.js";
|
|
12
|
-
|
|
12
|
+
import type { EditMode } from "./edit-mode.js";
|
|
13
|
+
export type { EditMode };
|
|
13
14
|
export type EditItem = {
|
|
14
15
|
anchor_from: string;
|
|
15
16
|
anchor_to: string;
|