dsh-better-edit 0.1.9 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/README.md +12 -0
  3. package/README.zh.md +9 -0
  4. package/assets/logo.svg +183 -18
  5. package/lib/contract.js +95 -0
  6. package/lib/drift.js +1 -1
  7. package/lib/edit-diff.js +2 -2
  8. package/lib/edit-engine.js +456 -0
  9. package/lib/edit-pipeline.js +41 -116
  10. package/lib/file-reader.js +1 -2
  11. package/lib/fs-bridge.js +2 -2
  12. package/lib/fs-write.js +3 -46
  13. package/lib/hash-store.js +246 -13
  14. package/lib/hashline/apply.js +2 -2
  15. package/lib/hashline/hash.js +16 -206
  16. package/lib/hashline/index.js +4 -3
  17. package/lib/hashline/parse.js +1 -1
  18. package/lib/hashline/pure.js +213 -0
  19. package/lib/hashline/resolve.js +1 -5
  20. package/lib/hashline/served.js +2 -2
  21. package/lib/paths.js +55 -1
  22. package/lib/read-and-serve.js +46 -0
  23. package/lib/schema.js +1 -1
  24. package/lib/served-store.js +144 -183
  25. package/lib/tool-batch-edit.js +28 -280
  26. package/lib/tool-edit.js +37 -32
  27. package/lib/tool-read.js +8 -31
  28. package/lib/tool-undo.js +4 -13
  29. package/lib/types/contract.d.ts +39 -0
  30. package/lib/types/edit-engine.d.ts +179 -0
  31. package/lib/types/edit-pipeline.d.ts +10 -17
  32. package/lib/types/fs-write.d.ts +0 -1
  33. package/lib/types/hash-store.d.ts +73 -25
  34. package/lib/types/hashline/hash.d.ts +8 -13
  35. package/lib/types/hashline/index.d.ts +4 -3
  36. package/lib/types/hashline/pure.d.ts +26 -0
  37. package/lib/types/hashline/resolve.d.ts +0 -1
  38. package/lib/types/paths.d.ts +9 -0
  39. package/lib/types/read-and-serve.d.ts +39 -0
  40. package/lib/types/schema.d.ts +2 -16
  41. package/lib/types/served-store.d.ts +63 -32
  42. package/lib/types/tool-batch-edit.d.ts +4 -1
  43. package/lib/types/tool-undo.d.ts +1 -1
  44. package/lib/undo-edit.js +16 -1
  45. package/lib/write-hook.js +30 -50
  46. package/package.json +4 -3
  47. package/lib/served-state.js +0 -34
  48. package/lib/snapshot-store.js +0 -108
  49. package/lib/types/served-state.d.ts +0 -3
  50. package/lib/types/snapshot-store.d.ts +0 -14
  51. package/lib/types/undo-store.d.ts +0 -14
  52. package/lib/undo-store.js +0 -43
@@ -1,3 +1,19 @@
1
+ /**
2
+ * Served state — what the model has been shown, per session and path.
3
+ *
4
+ * This is the ONE module that owns the served-state concept: the served-row
5
+ * merge invariant, the reported-drift set, and the position-reconstruction
6
+ * math used by drift notices. Persistence goes through the hash store's
7
+ * served domain API (`hash-store.ts`); the reject-and-serve errors and range
8
+ * verification live with the hashline module (`hashline/served.ts`); drift
9
+ * computation lives in `drift.ts`. Both import from here.
10
+ *
11
+ * The API is async-only: every operation loads the per-workspace hash store
12
+ * and resolves it through the active workspace context. There is deliberately
13
+ * no sync half — the two-vocabulary, every-op-twice surface it produced is
14
+ * gone.
15
+ * @module dsh-better-edit/served-store
16
+ */
1
17
  import { randomUUID } from "node:crypto";
2
18
  import { HASH_RE } from "./hashline/alphabet.js";
3
19
  import { loadHashStore, withStore } from "./hash-store.js";
@@ -13,246 +29,191 @@ export function sessionKeyFor(sessionId) {
13
29
  fallbackSessionKey ??= randomUUID();
14
30
  return fallbackSessionKey;
15
31
  }
16
- function isValidServedList(value) {
17
- if (!Array.isArray(value))
18
- return false;
19
- for (const entry of value) {
20
- if (entry === null)
21
- continue;
22
- if (typeof entry !== "string" || !HASH_RE.test(entry))
23
- return false;
24
- }
25
- return true;
26
- }
27
- export function getServed(store, sessionKey, path) {
28
- const row = store.stmts.servedGet(sessionKey, path);
29
- if (!row)
30
- return [];
31
- try {
32
- const parsed = JSON.parse(row.hashes);
33
- if (isValidServedList(parsed))
34
- return parsed;
35
- store.stmts.servedDelete(sessionKey, path);
36
- return [];
37
- }
38
- catch {
39
- store.stmts.servedDelete(sessionKey, path);
40
- return [];
41
- }
42
- }
43
- export function upsertServed(store, sessionKey, path, entries) {
44
- if (entries.length === 0)
45
- return;
46
- withStore(() => {
47
- const updated = getServed(store, sessionKey, path).slice();
48
- for (const entry of entries) {
49
- if (!Number.isInteger(entry.position) || entry.position < 0) {
50
- throw new TypeError(`Invalid served position: ${entry.position}`);
51
- }
52
- if (entry.hash !== null &&
53
- (typeof entry.hash !== "string" || !HASH_RE.test(entry.hash))) {
54
- throw new TypeError(`Invalid served hash: ${String(entry.hash)}`);
55
- }
56
- while (updated.length <= entry.position)
57
- updated.push(null);
58
- updated[entry.position] = entry.hash;
59
- }
60
- while (updated.length > 0 && updated[updated.length - 1] === null)
61
- updated.pop();
62
- store.stmts.servedUpsert(sessionKey, path, JSON.stringify(updated), Date.now());
63
- });
64
- }
65
- export function recordServes(store, sessionKey, path, rows, lineCount) {
66
- if (rows.length === 0)
67
- return;
68
- try {
69
- if (lineCount === undefined) {
70
- upsertServed(store, sessionKey, path, rows);
71
- return;
72
- }
73
- // A serve of the CURRENT file state must never leave hashes at
74
- // positions beyond the file's line count: a stale tail would hold a
75
- // surviving line's hash at its OLD position while the new serve holds
76
- // it at its current one, and the duplicate makes every later edit on
77
- // that line fail E_RANGE_UNVERIFIED ("served at N positions").
78
- withStore(() => {
79
- const updated = getServed(store, sessionKey, path).slice();
80
- if (updated.length > lineCount)
81
- updated.length = lineCount;
82
- for (const entry of rows) {
83
- if (!Number.isInteger(entry.position) || entry.position < 0) {
84
- throw new TypeError(`Invalid served position: ${entry.position}`);
85
- }
86
- if (entry.hash !== null &&
87
- (typeof entry.hash !== "string" || !HASH_RE.test(entry.hash))) {
88
- throw new TypeError(`Invalid served hash: ${String(entry.hash)}`);
89
- }
90
- while (updated.length <= entry.position)
91
- updated.push(null);
92
- updated[entry.position] = entry.hash;
93
- }
94
- while (updated.length > 0 && updated[updated.length - 1] === null)
95
- updated.pop();
96
- store.stmts.servedUpsert(sessionKey, path, JSON.stringify(updated), Date.now());
97
- });
98
- }
99
- catch (error) {
100
- console.error("Failed to record served rows:", error);
101
- }
102
- }
103
32
  /**
104
- * Record post-mutation diff serves against the file's CURRENT length. Before
105
- * upserting the diff rows, positions beyond `lineCount` are dropped from the
106
- * stored array: after an edit/undo the file has a new shape, and a hash that
107
- * survived into the diff must not keep its pre-edit position claim — that
108
- * stale claim is what makes a chained edit's boundary anchor look ambiguous
109
- * (`E_RANGE_UNVERIFIED`) instead of verifying cleanly.
110
- * @param store - open hash store.
111
- * @param sessionKey - the session whose served rows are being updated.
112
- * @param path - canonical absolute path.
113
- * @param rows - diff rows (position → post-mutation hash) to record.
114
- * @param lineCount - the file's line count AFTER the mutation.
33
+ * Merge served rows into a copy of the stored array. This single helper owns
34
+ * the served-merge invariant shared by {@link recordServed} and
35
+ * {@link recordServedTruncated}:
36
+ *
37
+ * - positions are validated before anything is written (invalid rows throw
38
+ * and never reach the store);
39
+ * - when `truncateTo` is given, positions beyond the file's line count are
40
+ * dropped FIRST — a serve of the current file state must never leave a hash
41
+ * at an old position beyond the line count, because that stale claim makes
42
+ * a chained edit's boundary anchor look ambiguous (`E_RANGE_UNVERIFIED`,
43
+ * "served at N positions") instead of verifying cleanly;
44
+ * - when `clearFrom` is given, positions at/after the mutation's first
45
+ * changed line are re-shaped by the edit, so the model's previous view of
46
+ * them is cleared before the diff rows land;
47
+ * - trailing never-served markers are trimmed so an empty tail never grows
48
+ * the stored array.
49
+ *
50
+ * Underscore-prefixed: internal, exported only so the invariant has a direct
51
+ * test seam.
115
52
  */
116
- export function recordServesTruncated(store, sessionKey, path, rows, lineCount, clearFrom = 0) {
117
- if (rows.length === 0)
118
- return;
119
- try {
120
- withStore(() => {
121
- const updated = getServed(store, sessionKey, path).slice();
122
- if (updated.length > lineCount)
123
- updated.length = lineCount;
124
- // Positions at/after the mutation's first changed line are
125
- // re-shaped by the edit: the model's previous view of them no
126
- // longer holds (line positions shift, and only the diff window
127
- // below is what it now saw). Clear them so a stale hash never
128
- // makes a boundary anchor look ambiguous; the unchanged prefix
129
- // before the edit keeps its claims (same content, same position).
130
- for (let i = clearFrom; i < updated.length; i++)
131
- updated[i] = null;
132
- for (const entry of rows) {
133
- if (!Number.isInteger(entry.position) || entry.position < 0) {
134
- throw new TypeError(`Invalid served position: ${entry.position}`);
135
- }
136
- if (entry.hash !== null &&
137
- (typeof entry.hash !== 'string' || !HASH_RE.test(entry.hash))) {
138
- throw new TypeError(`Invalid served hash: ${String(entry.hash)}`);
139
- }
140
- while (updated.length <= entry.position)
141
- updated.push(null);
142
- updated[entry.position] = entry.hash;
143
- }
144
- while (updated.length > 0 && updated[updated.length - 1] === null)
145
- updated.pop();
146
- store.stmts.servedUpsert(sessionKey, path, JSON.stringify(updated), Date.now());
147
- });
148
- }
149
- catch (error) {
150
- console.error('Failed to record truncated served rows:', error);
151
- }
152
- }
153
- export function getReported(store, sessionKey, path) {
154
- const row = store.stmts.servedGet(sessionKey, path);
155
- if (!row)
156
- return new Set();
157
- const raw = row.reported;
158
- if (typeof raw !== "string" || raw.length === 0)
159
- return new Set();
160
- try {
161
- const parsed = JSON.parse(raw);
162
- if (!Array.isArray(parsed))
163
- return new Set();
164
- return new Set(parsed.filter((h) => typeof h === "string" && HASH_RE.test(h)));
165
- }
166
- catch {
167
- return new Set();
53
+ export function _mergeServedRows(current, rows, options) {
54
+ const updated = current.slice();
55
+ if (options?.truncateTo !== undefined &&
56
+ updated.length > options.truncateTo) {
57
+ updated.length = options.truncateTo;
58
+ }
59
+ if (options?.clearFrom !== undefined) {
60
+ for (let i = options.clearFrom; i < updated.length; i++)
61
+ updated[i] = null;
62
+ }
63
+ for (const entry of rows) {
64
+ if (!Number.isInteger(entry.position) || entry.position < 0) {
65
+ throw new TypeError(`Invalid served position: ${entry.position}`);
66
+ }
67
+ if (entry.hash !== null &&
68
+ (typeof entry.hash !== "string" || !HASH_RE.test(entry.hash))) {
69
+ throw new TypeError(`Invalid served hash: ${String(entry.hash)}`);
70
+ }
71
+ while (updated.length <= entry.position)
72
+ updated.push(null);
73
+ updated[entry.position] = entry.hash;
168
74
  }
75
+ while (updated.length > 0 && updated[updated.length - 1] === null)
76
+ updated.pop();
77
+ return updated;
169
78
  }
170
- export function addReported(store, sessionKey, path, hashes) {
171
- const valid = hashes.filter((hash) => HASH_RE.test(hash));
172
- if (valid.length === 0)
173
- return;
174
- withStore(() => {
175
- const current = getReported(store, sessionKey, path);
176
- for (const hash of valid)
177
- current.add(hash);
178
- store.stmts.servedReportedUpsert(sessionKey, path, JSON.stringify([...current]), Date.now());
179
- });
180
- }
181
- export function clearReported(store, sessionKey, path) {
182
- withStore(() => {
183
- store.stmts.servedReportedClear(sessionKey, Date.now(), path);
184
- });
185
- }
186
- export function deleteServed(store, sessionKey, path) {
187
- store.stmts.servedDelete(sessionKey, path);
188
- }
189
- export function wipeServed(store, sessionKey) {
190
- store.stmts.servedWipe(sessionKey);
191
- }
79
+ /** The served array for one session+path, or `[]` when nothing was served. */
192
80
  export async function loadServed(sessionKey, path) {
193
81
  const store = await loadHashStore();
194
- return getServed(store, sessionKey, path);
82
+ return store.getServed(sessionKey, path);
195
83
  }
84
+ /**
85
+ * Record served rows for one session+path. Without `lineCount` the rows merge
86
+ * into the stored array as-is; with it, the stored array is truncated to the
87
+ * file's current line count before the rows land (see
88
+ * {@link _mergeServedRows} for why). Failures are logged, never thrown — a
89
+ * store problem must not fail the read that produced these rows.
90
+ */
196
91
  export async function recordServed(sessionKey, path, rows, lineCount) {
197
92
  if (rows.length === 0)
198
93
  return;
199
94
  try {
200
95
  const store = await loadHashStore();
201
- recordServes(store, sessionKey, path, rows, lineCount);
96
+ withStore(() => {
97
+ const current = store.getServed(sessionKey, path);
98
+ const updated = _mergeServedRows(current, rows, lineCount === undefined ? undefined : { truncateTo: lineCount });
99
+ store.upsertServed(sessionKey, path, JSON.stringify(updated));
100
+ });
202
101
  }
203
102
  catch (error) {
204
- console.error('Failed to record served rows:', error);
103
+ console.error("Failed to record served rows:", error);
205
104
  }
206
105
  }
207
106
  /**
208
- * Async sibling of {@link recordServesTruncated}: record post-mutation diff
209
- * rows against the file's current line count.
107
+ * Record post-mutation diff serves against the file's CURRENT length. The
108
+ * stored array is truncated to `lineCount` and cleared from `clearFrom`
109
+ * (the edit's first changed line) before the diff rows land, so a hash that
110
+ * survived into the diff never keeps its pre-edit position claim.
210
111
  */
211
112
  export async function recordServedTruncated(sessionKey, path, rows, lineCount, clearFrom = 0) {
212
113
  if (rows.length === 0)
213
114
  return;
214
115
  try {
215
116
  const store = await loadHashStore();
216
- recordServesTruncated(store, sessionKey, path, rows, lineCount, clearFrom);
117
+ withStore(() => {
118
+ const current = store.getServed(sessionKey, path);
119
+ const updated = _mergeServedRows(current, rows, {
120
+ truncateTo: lineCount,
121
+ clearFrom,
122
+ });
123
+ store.upsertServed(sessionKey, path, JSON.stringify(updated));
124
+ });
217
125
  }
218
126
  catch (error) {
219
- console.error('Failed to record truncated served rows:', error);
127
+ console.error("Failed to record truncated served rows:", error);
220
128
  }
221
129
  }
130
+ /** The hashes already reported as drifted for one session+path. */
222
131
  export async function driftReported(sessionKey, path) {
223
132
  try {
224
133
  const store = await loadHashStore();
225
- return getReported(store, sessionKey, path);
134
+ return store.getServedReported(sessionKey, path);
226
135
  }
227
136
  catch (error) {
228
137
  console.error("Failed to load reported drift set:", error);
229
138
  return new Set();
230
139
  }
231
140
  }
141
+ /** Mark hashes as already reported as drifted, so later notices skip them. */
232
142
  export async function markDriftReported(sessionKey, path, hashes) {
233
143
  try {
144
+ const valid = hashes.filter((hash) => HASH_RE.test(hash));
145
+ if (valid.length === 0)
146
+ return;
234
147
  const store = await loadHashStore();
235
- addReported(store, sessionKey, path, hashes);
148
+ withStore(() => {
149
+ const current = store.getServedReported(sessionKey, path);
150
+ for (const hash of valid)
151
+ current.add(hash);
152
+ store.upsertServedReported(sessionKey, path, JSON.stringify([...current]));
153
+ });
236
154
  }
237
155
  catch (error) {
238
156
  console.error("Failed to record reported drift set:", error);
239
157
  }
240
158
  }
159
+ /** Clear the reported-drift set for one session+path (a fresh read resets it). */
241
160
  export async function clearDriftReported(sessionKey, path) {
242
161
  try {
243
162
  const store = await loadHashStore();
244
- clearReported(store, sessionKey, path);
163
+ withStore(() => {
164
+ store.clearServedReported(sessionKey, path);
165
+ });
245
166
  }
246
167
  catch (error) {
247
168
  console.error("Failed to clear reported drift set:", error);
248
169
  }
249
170
  }
171
+ /** Drop every served row and reported-drift mark for one session. */
250
172
  export async function wipeServedState(sessionKey) {
251
173
  try {
252
174
  const store = await loadHashStore();
253
- wipeServed(store, sessionKey);
175
+ store.wipeServed(sessionKey);
254
176
  }
255
177
  catch (error) {
256
178
  console.error("Failed to wipe served state:", error);
257
179
  }
258
180
  }
181
+ /** Every served position of a hash in a served array (the E_RANGE_UNVERIFIED probe). */
182
+ export function servedPositionsOf(served, hash) {
183
+ const out = [];
184
+ for (let i = 0; i < served.length; i++) {
185
+ if (served[i] === hash)
186
+ out.push(i);
187
+ }
188
+ return out;
189
+ }
190
+ function nearestSurvivingPosition(served, surviving, from, direction) {
191
+ if (direction === "below") {
192
+ for (let q = from - 1; q >= 0; q--) {
193
+ const hash = served[q];
194
+ if (hash !== null && surviving.has(hash))
195
+ return q;
196
+ }
197
+ return undefined;
198
+ }
199
+ for (let q = from + 1; q < served.length; q++) {
200
+ const hash = served[q];
201
+ if (hash !== null && surviving.has(hash))
202
+ return q;
203
+ }
204
+ return undefined;
205
+ }
206
+ /**
207
+ * Reconstruct where a drifted hash sits in the current file: map through the
208
+ * nearest surviving served neighbor (below, else above), else fall back to
209
+ * the served index plus the range's line delta.
210
+ */
211
+ export function currentPositionOfDrifted(served, currentPositions, surviving, servedIndex, delta) {
212
+ const below = nearestSurvivingPosition(served, surviving, servedIndex, "below");
213
+ if (below !== undefined)
214
+ return currentPositions.get(served[below]) + 1;
215
+ const above = nearestSurvivingPosition(served, surviving, servedIndex, "above");
216
+ if (above !== undefined)
217
+ return currentPositions.get(served[above]) - 1;
218
+ return servedIndex + delta;
219
+ }