dsh-better-edit 0.8.1 → 1.0.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 +162 -97
- package/README.md +2 -2
- package/README.zh.md +3 -3
- package/cordis.patch.yml +1 -1
- package/lib/constants.js +19 -4
- package/lib/contract.js +136 -79
- package/lib/domain-errors.js +570 -0
- package/lib/edit-diff.js +33 -7
- package/lib/file-encoding-state.js +27 -7
- package/lib/file-view.js +305 -82
- package/lib/fs-bridge.js +23 -7
- package/lib/hash-store.js +404 -278
- package/lib/hashline/anchor-pipeline.js +586 -378
- package/lib/hashline/hash-assign.js +21 -22
- package/lib/hashline/hash.js +6 -6
- package/lib/hashline/index.js +1 -1
- package/lib/hashline/resolve.js +1 -1
- package/lib/hashline/served-guard.js +181 -0
- package/lib/index.js +2 -2
- package/lib/mutation/engine.js +392 -96
- package/lib/mutation.js +22 -130
- package/lib/noop-guard.js +20 -9
- package/lib/prompts.js +20 -18
- package/lib/read-and-serve.js +44 -20
- package/lib/sandbox.js +1 -1
- package/lib/session-view.js +57 -43
- package/lib/snapshot-store/index.js +97 -0
- package/lib/snapshot-store/lineage-store.js +400 -0
- package/lib/snapshot-store/migrate.js +80 -0
- package/lib/snapshot-store/pairing.js +412 -0
- package/lib/snapshot-store/txn.js +63 -0
- package/lib/snapshot-store/vacuum.js +243 -0
- package/lib/store-lifecycle.js +13 -1
- package/lib/store-retry.js +34 -0
- package/lib/tool-edit.js +90 -44
- package/lib/tool-read.js +29 -1
- package/lib/tool-str-replace-editor.js +59 -24
- package/lib/tool-undo.js +25 -8
- package/lib/types/constants.d.ts +5 -2
- package/lib/types/contract.d.ts +76 -71
- package/lib/types/domain-errors.d.ts +410 -0
- package/lib/types/edit-response.d.ts +1 -1
- package/lib/types/file-encoding-state.d.ts +1 -0
- package/lib/types/file-view.d.ts +35 -6
- package/lib/types/hash-store.d.ts +38 -19
- package/lib/types/hashline/anchor-pipeline.d.ts +117 -36
- package/lib/types/hashline/hash-assign.d.ts +5 -5
- package/lib/types/hashline/hash.d.ts +1 -1
- package/lib/types/hashline/index.d.ts +2 -2
- package/lib/types/hashline/served-guard.d.ts +100 -0
- package/lib/types/index.d.ts +2 -2
- package/lib/types/mutation/engine.d.ts +49 -30
- package/lib/types/mutation.d.ts +1 -39
- package/lib/types/noop-guard.d.ts +4 -4
- package/lib/types/prompts.d.ts +1 -1
- package/lib/types/read-and-serve.d.ts +6 -0
- package/lib/types/sandbox.d.ts +1 -1
- package/lib/types/session-view.d.ts +38 -9
- package/lib/types/snapshot-store/index.d.ts +28 -0
- package/lib/types/snapshot-store/lineage-store.d.ts +96 -0
- package/lib/types/snapshot-store/migrate.d.ts +16 -0
- package/lib/types/snapshot-store/pairing.d.ts +99 -0
- package/lib/types/snapshot-store/txn.d.ts +12 -0
- package/lib/types/snapshot-store/vacuum.d.ts +79 -0
- package/lib/types/store-lifecycle.d.ts +0 -1
- package/lib/types/store-retry.d.ts +6 -0
- package/lib/types/tool-edit.d.ts +2 -2
- package/lib/types/tool-str-replace-editor.d.ts +10 -4
- package/lib/types/utils.d.ts +5 -6
- package/lib/types/workspace-context.d.ts +0 -1
- package/lib/undo-edit.js +27 -11
- package/lib/utils.js +12 -12
- package/lib/workspace-context.js +4 -8
- package/lib/write-hook.js +13 -4
- package/package.json +9 -10
|
@@ -0,0 +1,412 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Scaled recursive patience pairing (spec §5.2): aligns a previous snapshot's lines to the
|
|
3
|
+
* current snapshot's lines so `line_id`s survive reorders, inserts, and deletes.
|
|
4
|
+
*
|
|
5
|
+
* The engine has four phases, all fail-closed: an ambiguous interval pairs nothing rather
|
|
6
|
+
* than guessing coordinates.
|
|
7
|
+
*
|
|
8
|
+
* 1. Locally unique canon anchors become candidate pins (`findUniquePins`).
|
|
9
|
+
* 2. The candidate pins' minimal-displacement LIS backbone is their unconditional
|
|
10
|
+
* intersection across every maximum-length, minimum-Δ subsequence
|
|
11
|
+
* (`findStablePinBackbone`, two-pass DP over patience-sorted ranks).
|
|
12
|
+
* 3. Pinless rigid runs with identical canon sequences zip pairwise (Probe N).
|
|
13
|
+
* 4. Bounded leaf intervals align on a unique LCS embedding only: a pairing is emitted when
|
|
14
|
+
* it lies on every maximal traceback path, so an interval with several optimal pairings
|
|
15
|
+
* stays UNPAIRED / RETIRED.
|
|
16
|
+
*
|
|
17
|
+
* When the backbone is empty the interval falls straight through to leaf handling: the
|
|
18
|
+
* engine never recurses on identical bounds, so alignment cannot starve the scan budget.
|
|
19
|
+
*
|
|
20
|
+
* Invariant: `prevLines` and `currLines` are contiguous ascending 1-based line numbers
|
|
21
|
+
* (spec §5.2 descriptor shape), so a descriptor's index + 1 is its line number.
|
|
22
|
+
*
|
|
23
|
+
* @module dsh-better-edit/snapshot-store/pairing
|
|
24
|
+
*/
|
|
25
|
+
const MAX_LEAF_LINES = 2000;
|
|
26
|
+
const MAX_LEAF_CELLS = 4_000_000;
|
|
27
|
+
const MIN_SCAN_BUDGET = 100_000;
|
|
28
|
+
const BUDGET_LINES_FACTOR = 4;
|
|
29
|
+
const MAXIMAL_PAIRING_CAP = 2;
|
|
30
|
+
/** Dynamic scan budget: `MAX(100000, 4 * (prevLines + currLines))` (spec §5.1/§5.2). */
|
|
31
|
+
export function pairingScanBudget(prevCount, currCount) {
|
|
32
|
+
return Math.max(MIN_SCAN_BUDGET, BUDGET_LINES_FACTOR * (prevCount + currCount));
|
|
33
|
+
}
|
|
34
|
+
/** First index whose value is `>= target` in an ascending array. */
|
|
35
|
+
function lowerBound(values, target) {
|
|
36
|
+
let lo = 0;
|
|
37
|
+
let hi = values.length;
|
|
38
|
+
while (lo < hi) {
|
|
39
|
+
const mid = (lo + hi) >>> 1;
|
|
40
|
+
if (values[mid] < target)
|
|
41
|
+
lo = mid + 1;
|
|
42
|
+
else
|
|
43
|
+
hi = mid;
|
|
44
|
+
}
|
|
45
|
+
return lo;
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* WHY: per-rank prefix-min indexes keep the minimal-displacement LIS at O(m log m): a
|
|
49
|
+
* WHY: Fenwick over each rank's compressed `currLine` coordinates answers "min displacement of a
|
|
50
|
+
* WHY: length-(k-1) subsequence ending before this coordinate" in O(log m) without an O(m²)
|
|
51
|
+
* WHY: scan over predecessors.
|
|
52
|
+
*/
|
|
53
|
+
class RankDisplacementIndex {
|
|
54
|
+
sorted;
|
|
55
|
+
tree;
|
|
56
|
+
constructor(values) {
|
|
57
|
+
this.sorted = [...new Set(values)].sort((a, b) => a - b);
|
|
58
|
+
this.tree = new Float64Array(this.sorted.length + 1);
|
|
59
|
+
this.tree.fill(Infinity);
|
|
60
|
+
}
|
|
61
|
+
queryBelow(value) {
|
|
62
|
+
let idx = lowerBound(this.sorted, value);
|
|
63
|
+
let best = Infinity;
|
|
64
|
+
while (idx > 0) {
|
|
65
|
+
const candidate = this.tree[idx];
|
|
66
|
+
if (candidate < best)
|
|
67
|
+
best = candidate;
|
|
68
|
+
idx -= idx & -idx;
|
|
69
|
+
}
|
|
70
|
+
return best;
|
|
71
|
+
}
|
|
72
|
+
update(value, candidate) {
|
|
73
|
+
let idx = lowerBound(this.sorted, value) + 1;
|
|
74
|
+
const size = this.sorted.length;
|
|
75
|
+
while (idx <= size) {
|
|
76
|
+
if (candidate < this.tree[idx])
|
|
77
|
+
this.tree[idx] = candidate;
|
|
78
|
+
idx += idx & -idx;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
/**
|
|
83
|
+
* Forward pass of the ∩LIS_minΔ DP (spec §3.4.3): for every pin, the length of the longest
|
|
84
|
+
* strictly increasing `currLine` subsequence ending at it and the minimum total `|prevLine -
|
|
85
|
+
* currLine|` displacement among those. Patience sorting fixes the lengths; per-rank Fenwick
|
|
86
|
+
* indexes carry the displacement minima.
|
|
87
|
+
*/
|
|
88
|
+
function computeLengthAndMinDisplacement(pins) {
|
|
89
|
+
const count = pins.length;
|
|
90
|
+
const lengths = Array.from({ length: count }, () => 0);
|
|
91
|
+
const displacements = Array.from({ length: count }, () => 0);
|
|
92
|
+
if (count === 0)
|
|
93
|
+
return { lengths, displacements };
|
|
94
|
+
const tails = [];
|
|
95
|
+
for (let i = 0; i < count; i++) {
|
|
96
|
+
const currLine = pins[i].currLine;
|
|
97
|
+
const slot = lowerBound(tails, currLine);
|
|
98
|
+
lengths[i] = slot + 1;
|
|
99
|
+
if (slot === tails.length)
|
|
100
|
+
tails.push(currLine);
|
|
101
|
+
else
|
|
102
|
+
tails[slot] = currLine;
|
|
103
|
+
}
|
|
104
|
+
const rankValues = Array.from({ length: tails.length }, () => []);
|
|
105
|
+
for (let i = 0; i < count; i++)
|
|
106
|
+
rankValues[lengths[i] - 1].push(pins[i].currLine);
|
|
107
|
+
const indexes = rankValues.map((values) => new RankDisplacementIndex(values));
|
|
108
|
+
for (let i = 0; i < count; i++) {
|
|
109
|
+
const pin = pins[i];
|
|
110
|
+
const rank = lengths[i];
|
|
111
|
+
let shortest = pin.displacement;
|
|
112
|
+
if (rank > 1) {
|
|
113
|
+
// WHY: the predecessor with rank-1 is guaranteed to have been processed already
|
|
114
|
+
// WHY: (pins arrive in ascending prevLine), so a finite minimum always exists when rank > 1.
|
|
115
|
+
const predecessor = indexes[rank - 2].queryBelow(pin.currLine);
|
|
116
|
+
if (predecessor !== Infinity)
|
|
117
|
+
shortest += predecessor;
|
|
118
|
+
}
|
|
119
|
+
displacements[i] = shortest;
|
|
120
|
+
indexes[rank - 1].update(pin.currLine, shortest);
|
|
121
|
+
}
|
|
122
|
+
return { lengths, displacements };
|
|
123
|
+
}
|
|
124
|
+
function pinDisplacement(pin) {
|
|
125
|
+
return Math.abs(pin.prevLine - pin.currLine);
|
|
126
|
+
}
|
|
127
|
+
/**
|
|
128
|
+
* Candidate Anchor Pins: a canon that occurs exactly once in `prev[pStart..pEnd]` and
|
|
129
|
+
* exactly once in `curr[cStart..cEnd]` (spec §3.4.1). Every other line is duplicated or
|
|
130
|
+
* absent on one side, so pairing it would guess.
|
|
131
|
+
*/
|
|
132
|
+
export function findUniquePins(prevLines, currLines, pStart, pEnd, cStart, cEnd) {
|
|
133
|
+
const prevCounts = new Map();
|
|
134
|
+
for (let p = pStart; p <= pEnd; p++) {
|
|
135
|
+
const key = prevLines[p - 1].canonHash;
|
|
136
|
+
prevCounts.set(key, (prevCounts.get(key) ?? 0) + 1);
|
|
137
|
+
}
|
|
138
|
+
const currCounts = new Map();
|
|
139
|
+
const currPositions = new Map();
|
|
140
|
+
for (let c = cStart; c <= cEnd; c++) {
|
|
141
|
+
const key = currLines[c - 1].canonHash;
|
|
142
|
+
currCounts.set(key, (currCounts.get(key) ?? 0) + 1);
|
|
143
|
+
currPositions.set(key, c);
|
|
144
|
+
}
|
|
145
|
+
const pins = [];
|
|
146
|
+
for (let p = pStart; p <= pEnd; p++) {
|
|
147
|
+
const key = prevLines[p - 1].canonHash;
|
|
148
|
+
if (prevCounts.get(key) !== 1 || currCounts.get(key) !== 1)
|
|
149
|
+
continue;
|
|
150
|
+
const currLine = currPositions.get(key);
|
|
151
|
+
if (currLine === undefined)
|
|
152
|
+
continue;
|
|
153
|
+
pins.push({ prevLine: p, currLine });
|
|
154
|
+
}
|
|
155
|
+
return pins;
|
|
156
|
+
}
|
|
157
|
+
/**
|
|
158
|
+
* Unconditional intersection of every maximum-length, minimum-displacement increasing
|
|
159
|
+
* subsequence of `pins` (spec §3.4.3). Pins arrive sorted by ascending `prevLine`; the
|
|
160
|
+
* backward pass mirrors the forward pass over negated `currLine` coordinates.
|
|
161
|
+
*
|
|
162
|
+
* A pin belongs to the intersection iff it lies on a minimal-displacement LIS *and* no
|
|
163
|
+
* other minimal-displacement pin shares its rank — otherwise a competing optimal
|
|
164
|
+
* subsequence could bypass it.
|
|
165
|
+
*/
|
|
166
|
+
export function findStablePinBackbone(pins) {
|
|
167
|
+
const count = pins.length;
|
|
168
|
+
if (count === 0)
|
|
169
|
+
return [];
|
|
170
|
+
const weighted = pins.map((pin) => ({
|
|
171
|
+
prevLine: pin.prevLine,
|
|
172
|
+
currLine: pin.currLine,
|
|
173
|
+
displacement: pinDisplacement(pin),
|
|
174
|
+
}));
|
|
175
|
+
const forward = computeLengthAndMinDisplacement(weighted);
|
|
176
|
+
const reversed = weighted
|
|
177
|
+
.map((pin) => ({
|
|
178
|
+
prevLine: pin.prevLine,
|
|
179
|
+
currLine: -pin.currLine,
|
|
180
|
+
displacement: pin.displacement,
|
|
181
|
+
}))
|
|
182
|
+
.reverse();
|
|
183
|
+
const backward = computeLengthAndMinDisplacement(reversed);
|
|
184
|
+
const lengths = forward.lengths;
|
|
185
|
+
const displacements = forward.displacements;
|
|
186
|
+
const suffixLengths = Array.from({ length: count }, () => 0);
|
|
187
|
+
const suffixDisplacements = Array.from({ length: count }, () => 0);
|
|
188
|
+
for (let i = 0; i < count; i++) {
|
|
189
|
+
const j = count - 1 - i;
|
|
190
|
+
suffixLengths[i] = backward.lengths[j];
|
|
191
|
+
suffixDisplacements[i] = backward.displacements[j];
|
|
192
|
+
}
|
|
193
|
+
let bestLength = 0;
|
|
194
|
+
for (let i = 0; i < count; i++)
|
|
195
|
+
if (lengths[i] > bestLength)
|
|
196
|
+
bestLength = lengths[i];
|
|
197
|
+
let bestDisplacement = Infinity;
|
|
198
|
+
for (let i = 0; i < count; i++) {
|
|
199
|
+
if (lengths[i] + suffixLengths[i] - 1 !== bestLength)
|
|
200
|
+
continue;
|
|
201
|
+
const total = displacements[i] + suffixDisplacements[i] - weighted[i].displacement;
|
|
202
|
+
if (total < bestDisplacement)
|
|
203
|
+
bestDisplacement = total;
|
|
204
|
+
}
|
|
205
|
+
const optimalAtRank = new Map();
|
|
206
|
+
const optimal = Array.from({ length: count }, () => false);
|
|
207
|
+
for (let i = 0; i < count; i++) {
|
|
208
|
+
if (lengths[i] + suffixLengths[i] - 1 !== bestLength)
|
|
209
|
+
continue;
|
|
210
|
+
const total = displacements[i] + suffixDisplacements[i] - weighted[i].displacement;
|
|
211
|
+
if (total !== bestDisplacement)
|
|
212
|
+
continue;
|
|
213
|
+
optimal[i] = true;
|
|
214
|
+
const rank = lengths[i];
|
|
215
|
+
optimalAtRank.set(rank, (optimalAtRank.get(rank) ?? 0) + 1);
|
|
216
|
+
}
|
|
217
|
+
const stable = [];
|
|
218
|
+
for (let i = 0; i < count; i++) {
|
|
219
|
+
if (!optimal[i])
|
|
220
|
+
continue;
|
|
221
|
+
if (optimalAtRank.get(lengths[i]) !== 1)
|
|
222
|
+
continue;
|
|
223
|
+
stable.push(pins[i]);
|
|
224
|
+
}
|
|
225
|
+
return stable;
|
|
226
|
+
}
|
|
227
|
+
/**
|
|
228
|
+
* Bounded leaf alignment (spec §3.4.4). Uniqueness is **embedding-level**: a pairing survives
|
|
229
|
+
* only when it lies on every maximal traceback path, and an interval with more than one maximum
|
|
230
|
+
* pairing pairs nothing (its lines stay UNPAIRED / RETIRED).
|
|
231
|
+
*
|
|
232
|
+
* `pairingCount` is the exact number of maximum pairings (embeddings) of the optimal LCS in the
|
|
233
|
+
* sub-interval, capped at 2 so the decision stays polynomial. It deliberately counts neither
|
|
234
|
+
* distinct canon strings nor DP orderings:
|
|
235
|
+
* - A repeated canon that can be matched in two places counts twice, although the LCS string is
|
|
236
|
+
* the same: `[A, A, A]` vs `[A, A]` counts 3, not 1.
|
|
237
|
+
* - Two orderings of down/right skips around the same matched lines count once, because they are
|
|
238
|
+
* the same embedding: `[A, X, B]` vs `[A, Y, B]` counts 1, not 2.
|
|
239
|
+
*
|
|
240
|
+
* The recurrence is a first-pair decomposition. For the region starting at `(i, j)` with optimal
|
|
241
|
+
* length `target`, every maximum pairing either matches `i` with `j` (only possible when the
|
|
242
|
+
* canons agree, and then it extends a maximum pairing of `(i + 1, j + 1)`), or leaves at least
|
|
243
|
+
* one of the two lines unmatched, which is a maximum pairing of `(i + 1, j)` and/or `(i, j + 1)`
|
|
244
|
+
* at the same length. The overlap of those two jump regions is subtracted, so each pairing is
|
|
245
|
+
* counted exactly once. The cap is applied after the inclusion-exclusion subtraction, and because
|
|
246
|
+
* `|A ∪ B| == 1` forces `A` and `B` to be the same singleton, the `=== 1` test that drives
|
|
247
|
+
* `isUnique` stays exact under the cap.
|
|
248
|
+
*/
|
|
249
|
+
export function computeLCSPaths(prevLines, currLines, pStart, pEnd, cStart, cEnd) {
|
|
250
|
+
const pCount = pEnd - pStart + 1;
|
|
251
|
+
const cCount = cEnd - cStart + 1;
|
|
252
|
+
const stride = cCount + 1;
|
|
253
|
+
const suffix = new Int32Array((pCount + 1) * stride);
|
|
254
|
+
const pairingCount = new Int32Array((pCount + 1) * stride);
|
|
255
|
+
for (let i = pCount - 1; i >= 0; i--) {
|
|
256
|
+
const pKey = prevLines[pStart - 1 + i].canonHash;
|
|
257
|
+
const row = i * stride;
|
|
258
|
+
const nextRow = row + stride;
|
|
259
|
+
for (let j = cCount - 1; j >= 0; j--) {
|
|
260
|
+
const cKey = currLines[cStart - 1 + j].canonHash;
|
|
261
|
+
const diagonal = suffix[nextRow + j + 1];
|
|
262
|
+
suffix[row + j] =
|
|
263
|
+
pKey === cKey ? diagonal + 1 : Math.max(suffix[nextRow + j], suffix[row + j + 1]);
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
for (let i = pCount; i >= 0; i--) {
|
|
267
|
+
for (let j = cCount; j >= 0; j--) {
|
|
268
|
+
const index = i * stride + j;
|
|
269
|
+
if (i === pCount || j === cCount) {
|
|
270
|
+
pairingCount[index] = 1;
|
|
271
|
+
continue;
|
|
272
|
+
}
|
|
273
|
+
const target = suffix[index];
|
|
274
|
+
if (target === 0) {
|
|
275
|
+
pairingCount[index] = 1;
|
|
276
|
+
continue;
|
|
277
|
+
}
|
|
278
|
+
const diagonal = suffix[(i + 1) * stride + (j + 1)];
|
|
279
|
+
const down = suffix[(i + 1) * stride + j];
|
|
280
|
+
const right = suffix[i * stride + (j + 1)];
|
|
281
|
+
const diagonalCount = pairingCount[(i + 1) * stride + (j + 1)];
|
|
282
|
+
let total = 0;
|
|
283
|
+
if (down === target)
|
|
284
|
+
total += pairingCount[(i + 1) * stride + j];
|
|
285
|
+
if (right === target)
|
|
286
|
+
total += pairingCount[i * stride + (j + 1)];
|
|
287
|
+
if (diagonal === target)
|
|
288
|
+
total -= diagonalCount;
|
|
289
|
+
const pKey = prevLines[pStart - 1 + i].canonHash;
|
|
290
|
+
const cKey = currLines[cStart - 1 + j].canonHash;
|
|
291
|
+
if (pKey === cKey && diagonal + 1 === target)
|
|
292
|
+
total += diagonalCount;
|
|
293
|
+
pairingCount[index] = total > MAXIMAL_PAIRING_CAP ? MAXIMAL_PAIRING_CAP : total;
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
const isUnique = pairingCount[0] === 1;
|
|
297
|
+
const pairs = [];
|
|
298
|
+
if (isUnique) {
|
|
299
|
+
let i = 0;
|
|
300
|
+
let j = 0;
|
|
301
|
+
while (i < pCount && j < cCount) {
|
|
302
|
+
const target = suffix[i * stride + j];
|
|
303
|
+
if (target === 0)
|
|
304
|
+
break;
|
|
305
|
+
const diagonal = suffix[(i + 1) * stride + (j + 1)];
|
|
306
|
+
const pKey = prevLines[pStart - 1 + i].canonHash;
|
|
307
|
+
const cKey = currLines[cStart - 1 + j].canonHash;
|
|
308
|
+
// WHY: with `pairingCount[i][j] === 1` each step has exactly one pairing-optimal
|
|
309
|
+
// WHY: continuation, so this preference order reproduces *the* unique embedding. A canon
|
|
310
|
+
// WHY: match that preserves the optimum must be in it (a maximum path through that pair
|
|
311
|
+
// WHY: would otherwise be a second embedding), and when skipping both lines is optimal
|
|
312
|
+
// WHY: the unique embedding can only continue inside `(i + 1, j + 1)`.
|
|
313
|
+
if (pKey === cKey && diagonal + 1 === target) {
|
|
314
|
+
pairs.push([pStart + i, cStart + j]);
|
|
315
|
+
i++;
|
|
316
|
+
j++;
|
|
317
|
+
continue;
|
|
318
|
+
}
|
|
319
|
+
if (diagonal === target) {
|
|
320
|
+
i++;
|
|
321
|
+
j++;
|
|
322
|
+
continue;
|
|
323
|
+
}
|
|
324
|
+
if (suffix[(i + 1) * stride + j] === target) {
|
|
325
|
+
i++;
|
|
326
|
+
continue;
|
|
327
|
+
}
|
|
328
|
+
j++;
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
return { isUnique, pairs };
|
|
332
|
+
}
|
|
333
|
+
/**
|
|
334
|
+
* Fail-closed monotonicity assertion (spec §3.8): paired coordinates must be strictly
|
|
335
|
+
* increasing in both snapshots, so a later previous line can never map to an earlier
|
|
336
|
+
* current line.
|
|
337
|
+
*/
|
|
338
|
+
export function assertMonotonicPairing(pairing) {
|
|
339
|
+
const sorted = [...pairing.entries()].sort((a, b) => a[0] - b[0]);
|
|
340
|
+
let lastCurr = 0;
|
|
341
|
+
for (const [prev, curr] of sorted) {
|
|
342
|
+
if (curr <= lastCurr) {
|
|
343
|
+
throw new Error(`Pairing monotonicity violation: ${prev} -> ${curr} <= ${lastCurr}`);
|
|
344
|
+
}
|
|
345
|
+
lastCurr = curr;
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
/**
|
|
349
|
+
* Pair previous snapshot lines to current snapshot lines (spec §5.2), returning
|
|
350
|
+
* `prevLineNumber -> currLineNumber`. Unpaired lines are omitted, which retires their
|
|
351
|
+
* `line_id`s fail-closed downstream.
|
|
352
|
+
*/
|
|
353
|
+
export function pairSnapshots(prevLines, currLines, options) {
|
|
354
|
+
const pairing = new Map();
|
|
355
|
+
let scanBudget = options?.scanBudget ?? pairingScanBudget(prevLines.length, currLines.length);
|
|
356
|
+
function alignRecursive(pStart, pEnd, cStart, cEnd) {
|
|
357
|
+
if (pStart > pEnd || cStart > cEnd)
|
|
358
|
+
return;
|
|
359
|
+
const intervalLength = pEnd - pStart + 1 + (cEnd - cStart + 1);
|
|
360
|
+
if (scanBudget < intervalLength)
|
|
361
|
+
return;
|
|
362
|
+
scanBudget -= intervalLength;
|
|
363
|
+
const candidatePins = findUniquePins(prevLines, currLines, pStart, pEnd, cStart, cEnd);
|
|
364
|
+
if (candidatePins.length > 0) {
|
|
365
|
+
const stablePins = findStablePinBackbone(candidatePins);
|
|
366
|
+
if (stablePins.length > 0) {
|
|
367
|
+
let pCursor = pStart;
|
|
368
|
+
let cCursor = cStart;
|
|
369
|
+
for (const pin of stablePins) {
|
|
370
|
+
alignRecursive(pCursor, pin.prevLine - 1, cCursor, pin.currLine - 1);
|
|
371
|
+
pairing.set(pin.prevLine, pin.currLine);
|
|
372
|
+
pCursor = pin.prevLine + 1;
|
|
373
|
+
cCursor = pin.currLine + 1;
|
|
374
|
+
}
|
|
375
|
+
alignRecursive(pCursor, pEnd, cCursor, cEnd);
|
|
376
|
+
return;
|
|
377
|
+
}
|
|
378
|
+
// WHY: contested candidate pins leave the backbone empty. Recursing on identical
|
|
379
|
+
// WHY: bounds here would never shrink the interval; fall through to leaf handling
|
|
380
|
+
// WHY: instead so progress and the scan budget are both guaranteed.
|
|
381
|
+
}
|
|
382
|
+
const pCount = pEnd - pStart + 1;
|
|
383
|
+
const cCount = cEnd - cStart + 1;
|
|
384
|
+
if (pCount === cCount) {
|
|
385
|
+
let identical = true;
|
|
386
|
+
for (let i = 0; i < pCount; i++) {
|
|
387
|
+
if (prevLines[pStart - 1 + i].canonHash !== currLines[cStart - 1 + i].canonHash) {
|
|
388
|
+
identical = false;
|
|
389
|
+
break;
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
if (identical) {
|
|
393
|
+
// WHY: equal counts with an identical canon sequence is a pure shift of a rigid
|
|
394
|
+
// WHY: run: the only sound pairing is the positional zip (spec §3.5.1, Probe N).
|
|
395
|
+
for (let i = 0; i < pCount; i++)
|
|
396
|
+
pairing.set(pStart + i, cStart + i);
|
|
397
|
+
return;
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
if (pCount > MAX_LEAF_LINES || cCount > MAX_LEAF_LINES || pCount * cCount > MAX_LEAF_CELLS) {
|
|
401
|
+
return;
|
|
402
|
+
}
|
|
403
|
+
const lcs = computeLCSPaths(prevLines, currLines, pStart, pEnd, cStart, cEnd);
|
|
404
|
+
if (lcs.isUnique) {
|
|
405
|
+
for (const [prevLine, currLine] of lcs.pairs)
|
|
406
|
+
pairing.set(prevLine, currLine);
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
alignRecursive(1, prevLines.length, 1, currLines.length);
|
|
410
|
+
assertMonotonicPairing(pairing);
|
|
411
|
+
return pairing;
|
|
412
|
+
}
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The single re-entrant transaction owner for the store's `DatabaseSync` handle.
|
|
3
|
+
*
|
|
4
|
+
* Why one owner: SQLite throws `cannot start a transaction within a transaction`
|
|
5
|
+
* on a nested `BEGIN`. Every writer reachable from a live store therefore routes
|
|
6
|
+
* through this function, and the nesting contract below is the whole policy.
|
|
7
|
+
*
|
|
8
|
+
* Nesting contract:
|
|
9
|
+
* - Exactly one `BEGIN IMMEDIATE` site is reachable from a live store: the
|
|
10
|
+
* non-nested branch of this function. `hash-store`'s `withStore` / undo pair
|
|
11
|
+
* and `lineage-store`'s `commitSnapshot` all delegate here.
|
|
12
|
+
* - A nested caller (same handle already inside a transaction) joins the outer
|
|
13
|
+
* unit: `fn` runs directly, with no BEGIN / COMMIT / ROLLBACK of its own.
|
|
14
|
+
* - A nested failure propagates to the outermost owner, which is the only place
|
|
15
|
+
* that rolls back. Inner callers never swallow the error — swallowing would let
|
|
16
|
+
* the outer COMMIT persist a half-written pair.
|
|
17
|
+
* - Two more `BEGIN IMMEDIATE` sites exist on a store handle, but both are PRE-STORE
|
|
18
|
+
* only and can never nest under this owner: `snapshot-store/migrate.ts:67` (fresh
|
|
19
|
+
* handle during `openStore`) and `hash-store.ts:471` (`migrateForward`, during
|
|
20
|
+
* `buildStore`, before any store object exists). A grep-auditor counts three BEGIN
|
|
21
|
+
* sites in total; exactly one of them is reachable from a live store.
|
|
22
|
+
*
|
|
23
|
+
* Retry policy (shared `withBusyRetry`, store-retry): this owner retries the two
|
|
24
|
+
* ACQUISITION points — `BEGIN IMMEDIATE` (lock acquisition) and `COMMIT` (lock
|
|
25
|
+
* release; a busy COMMIT leaves the transaction open and is retryable). It does NOT
|
|
26
|
+
* retry the body: statement-level retry belongs to the family that owns the
|
|
27
|
+
* statement. `hash-store`'s `stmts` wrappers and `snapshot-store/index.ts` wrap each
|
|
28
|
+
* `.run`, and `lineage-store.ts` wraps all ten of its own `.run` sites. Each
|
|
29
|
+
* acquisition point therefore gets up to 4 attempts (`BUSY_RETRIES = 3` in
|
|
30
|
+
* `store-retry.ts`) with the shared 100 ms backoff; the body is attempted once.
|
|
31
|
+
* @module dsh-better-edit/snapshot-store/txn
|
|
32
|
+
*/
|
|
33
|
+
import { withBusyRetry } from "../store-retry.js";
|
|
34
|
+
/** Run `fn` in one transaction on `db`, or join the transaction already open on it. */
|
|
35
|
+
export function withTransaction(db, fn) {
|
|
36
|
+
if (db.isTransaction) {
|
|
37
|
+
fn();
|
|
38
|
+
return;
|
|
39
|
+
}
|
|
40
|
+
// Retry the ACQUISITION points only. Statement-level retry belongs to the family
|
|
41
|
+
// that owns the statement (hash-store's `stmts` wrappers, snapshot-store/index.ts,
|
|
42
|
+
// lineage-store.ts), so re-running the whole body here would multiply attempts 4x
|
|
43
|
+
// and duplicate work the inner retry had already rolled back.
|
|
44
|
+
withBusyRetry(() => {
|
|
45
|
+
db.exec("BEGIN IMMEDIATE");
|
|
46
|
+
});
|
|
47
|
+
try {
|
|
48
|
+
fn();
|
|
49
|
+
// COMMIT is the lock release: a busy COMMIT leaves the transaction open.
|
|
50
|
+
withBusyRetry(() => {
|
|
51
|
+
db.exec("COMMIT");
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
catch (error) {
|
|
55
|
+
try {
|
|
56
|
+
db.exec("ROLLBACK");
|
|
57
|
+
}
|
|
58
|
+
catch (rollbackError) {
|
|
59
|
+
console.warn(rollbackError); // best-effort rollback; the original error propagates
|
|
60
|
+
}
|
|
61
|
+
throw error;
|
|
62
|
+
}
|
|
63
|
+
}
|