dsh-better-edit 0.2.2 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (85) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/README.md +317 -240
  3. package/README.zh.md +19 -11
  4. package/lib/constants.js +3 -1
  5. package/lib/contract.js +159 -63
  6. package/lib/drift.js +5 -98
  7. package/lib/dsh-context.js +2 -24
  8. package/lib/edit-engine.js +9 -8
  9. package/lib/edit-pipeline.js +3 -121
  10. package/lib/edit-response.js +16 -8
  11. package/lib/file-kind.js +6 -121
  12. package/lib/file-reader.js +4 -77
  13. package/lib/file-view.js +486 -0
  14. package/lib/guidance/index.js +8 -0
  15. package/lib/guidance/materialize.js +212 -0
  16. package/lib/guidance/parse.js +80 -0
  17. package/lib/guidance/resolve.js +116 -0
  18. package/lib/guidance.js +6 -388
  19. package/lib/hash-store.js +6 -4
  20. package/lib/hashline/alphabet.js +2 -6
  21. package/lib/hashline/anchor-pipeline.js +786 -0
  22. package/lib/hashline/apply.js +2 -223
  23. package/lib/hashline/hash-assign.js +255 -0
  24. package/lib/hashline/hash.js +67 -29
  25. package/lib/hashline/hasher.js +2 -23
  26. package/lib/hashline/index.js +9 -4
  27. package/lib/hashline/parse.js +2 -35
  28. package/lib/hashline/pure.js +2 -213
  29. package/lib/hashline/resolve.js +3 -361
  30. package/lib/hashline/served.js +2 -120
  31. package/lib/index.js +1 -3
  32. package/lib/mutation.js +266 -0
  33. package/lib/noop-guard.js +20 -0
  34. package/lib/preview-controller.js +65 -0
  35. package/lib/prompts.js +14 -20
  36. package/lib/read-and-serve.js +23 -23
  37. package/lib/read-render.js +3 -139
  38. package/lib/served-store.js +2 -216
  39. package/lib/session-view.js +332 -0
  40. package/lib/tool-batch-edit.js +9 -10
  41. package/lib/tool-edit.js +73 -129
  42. package/lib/tool-read.js +3 -5
  43. package/lib/tool-undo.js +16 -10
  44. package/lib/truncate.js +3 -95
  45. package/lib/types/constants.d.ts +2 -0
  46. package/lib/types/contract.d.ts +120 -15
  47. package/lib/types/drift.d.ts +5 -29
  48. package/lib/types/dsh-context.d.ts +2 -20
  49. package/lib/types/edit-engine.d.ts +2 -2
  50. package/lib/types/edit-pipeline.d.ts +3 -44
  51. package/lib/types/file-kind.d.ts +6 -18
  52. package/lib/types/file-reader.d.ts +4 -45
  53. package/lib/types/file-view.d.ts +139 -0
  54. package/lib/types/guidance/index.d.ts +8 -0
  55. package/lib/types/guidance/materialize.d.ts +23 -0
  56. package/lib/types/guidance/parse.d.ts +36 -0
  57. package/lib/types/guidance/resolve.d.ts +55 -0
  58. package/lib/types/guidance.d.ts +6 -127
  59. package/lib/types/hashline/alphabet.d.ts +1 -5
  60. package/lib/types/hashline/anchor-pipeline.d.ts +127 -0
  61. package/lib/types/hashline/apply.d.ts +1 -22
  62. package/lib/types/hashline/hash-assign.d.ts +25 -0
  63. package/lib/types/hashline/hash.d.ts +8 -9
  64. package/lib/types/hashline/hasher.d.ts +1 -8
  65. package/lib/types/hashline/index.d.ts +12 -4
  66. package/lib/types/hashline/parse.d.ts +1 -7
  67. package/lib/types/hashline/pure.d.ts +1 -26
  68. package/lib/types/hashline/resolve.d.ts +1 -58
  69. package/lib/types/hashline/served.d.ts +1 -43
  70. package/lib/types/mutation.d.ts +131 -0
  71. package/lib/types/noop-guard.d.ts +29 -0
  72. package/lib/types/preview-controller.d.ts +33 -0
  73. package/lib/types/prompts.d.ts +9 -9
  74. package/lib/types/read-and-serve.d.ts +6 -5
  75. package/lib/types/read-render.d.ts +3 -18
  76. package/lib/types/served-store.d.ts +2 -81
  77. package/lib/types/session-view.d.ts +92 -0
  78. package/lib/types/tool-edit.d.ts +3 -14
  79. package/lib/types/truncate.d.ts +3 -29
  80. package/lib/types/validation.d.ts +6 -7
  81. package/lib/types/workspace.d.ts +2 -21
  82. package/lib/validation.js +6 -33
  83. package/lib/workspace.js +2 -27
  84. package/lib/write-hook.js +2 -2
  85. package/package.json +2 -2
@@ -1,142 +1,6 @@
1
1
  /**
2
- * Hash-anchored read rendering: turn normalized text into `HASH│content` rows
3
- * with pagination hints, oversized-line markers, and served-row bookkeeping.
4
- * Ported from pi-hashline-edit-lsz's read tool (pi APIs replaced by local
5
- * helpers).
2
+ * @deprecated — private to FileView seam. Use `from "./file-view.js"` instead.
3
+ * Thin shim re-exporting the read path now owned by FileView.
6
4
  * @module dsh-better-edit/read-render
7
5
  */
8
- import { lineHashes, fmtRegion, HASH_SEP, MAX_HASH_LINES } from './hashline/index.js';
9
- import { visLines } from './utils.js';
10
- import { MAX_READ_LINE_BYTES } from './constants.js';
11
- import { formatSize, truncateHead, DEFAULT_MAX_LINES } from './truncate.js';
12
- function normPosInt(value, name) {
13
- if (value === undefined)
14
- return undefined;
15
- if (!Number.isInteger(value) || value < 1) {
16
- throw new Error(`[E_BAD_SHAPE] Read request field "${name}" must be a positive integer.`);
17
- }
18
- return value;
19
- }
20
- export function formatPaginationHint(startLine, endLine, totalLines, nextOffset, byteLimit) {
21
- const sizeSuffix = byteLimit !== undefined ? ` (${formatSize(byteLimit)} limit)` : '';
22
- return `[Showing lines ${startLine}-${endLine} of ${totalLines}${sizeSuffix}. Use offset=${nextOffset} to continue.]`;
23
- }
24
- export async function fmtReadPreview(text, options, precomputedHashes, path, maxLineBytes = MAX_READ_LINE_BYTES, maxTruncLines = DEFAULT_MAX_LINES) {
25
- const allLines = visLines(text);
26
- const totalLines = allLines.length;
27
- const startLine = normPosInt(options.offset, 'offset') ?? 1;
28
- if (totalLines === 0) {
29
- if (startLine === 1) {
30
- const allHashes = precomputedHashes ??
31
- (await (path ? lineHashes(text, path) : lineHashes(text)));
32
- const emptyLineHash = allHashes[0];
33
- return {
34
- text: `${emptyLineHash}${HASH_SEP}\n[File is empty. Use edit to insert content.]`,
35
- served: [{ position: 0, hash: emptyLineHash }],
36
- };
37
- }
38
- return {
39
- text: `Offset ${startLine} is beyond end of file (0 lines total). The file is empty. Use edit to insert content.`,
40
- served: [],
41
- };
42
- }
43
- if (startLine > totalLines) {
44
- return {
45
- text: `Offset ${startLine} is beyond end of file (${totalLines} lines total). Use offset=1 to read from the start, or offset=${totalLines} to read the last line.`,
46
- served: [],
47
- };
48
- }
49
- const limit = normPosInt(options.limit, 'limit');
50
- const endIdx = limit
51
- ? Math.min(startLine - 1 + limit, totalLines)
52
- : totalLines;
53
- const selected = allLines.slice(startLine - 1, endIdx);
54
- const allHashes = precomputedHashes ??
55
- (await (path ? lineHashes(text, path) : lineHashes(text)));
56
- const selectedHashes = allHashes.slice(startLine - 1, endIdx);
57
- const formatted = fmtRegion(selectedHashes, selected);
58
- const maxBytes = maxLineBytes;
59
- const rowSizes = selected.map((line, index) => ({
60
- lineNumber: startLine + index,
61
- bytes: Buffer.byteLength(`${selectedHashes[index]}${HASH_SEP}${line}`, 'utf-8'),
62
- }));
63
- if (rowSizes.some((row) => row.bytes > maxBytes)) {
64
- const oversized = rowSizes.filter((row) => row.bytes > maxBytes);
65
- const rows = rowSizes.map((row, index) => row.bytes > maxBytes
66
- ? `[Line ${row.lineNumber} is ${formatSize(row.bytes)}, exceeds ${formatSize(maxBytes)}; content not shown. Use bash: sed -n '${row.lineNumber}p' <path> | head -c ${maxBytes}]`
67
- : fmtRegion([selectedHashes[index]], [selected[index]]));
68
- const skippedTruncation = truncateHead(rows.join('\n'), {
69
- maxBytes,
70
- maxLines: maxTruncLines,
71
- });
72
- const shownRowCount = skippedTruncation.content === ''
73
- ? 0
74
- : skippedTruncation.content.split('\n').length;
75
- const lastShownLine = shownRowCount > 0 ? startLine + shownRowCount - 1 : startLine - 1;
76
- const lineLabel = oversized.length === 1
77
- ? `Line ${oversized[0].lineNumber}`
78
- : `Lines ${oversized.map((row) => row.lineNumber).join(', ')}`;
79
- const verb = oversized.length === 1 ? 'exceeds' : 'exceed';
80
- const addresses = oversized.map((row) => `${row.lineNumber}p`).join(';');
81
- const warning = `[${lineLabel} ${verb} ${formatSize(maxBytes)}; content not shown because hashline anchors require full lines. Inspect with bash: sed -n '${addresses}' <path> | head -c ${maxBytes}]`;
82
- let preview = skippedTruncation.content;
83
- let nextOffset;
84
- if (shownRowCount > 0 &&
85
- (skippedTruncation.truncated || lastShownLine < totalLines)) {
86
- nextOffset = lastShownLine + 1;
87
- preview += `\n\n${warning}\n${formatPaginationHint(startLine, lastShownLine, totalLines, nextOffset, skippedTruncation.truncated ? skippedTruncation.maxBytes : undefined)}`;
88
- }
89
- else {
90
- preview += `\n\n${warning}`;
91
- }
92
- const served = [];
93
- for (let index = 0; index < shownRowCount; index++) {
94
- if (rowSizes[index].bytes <= maxBytes) {
95
- served.push({
96
- position: startLine - 1 + index,
97
- hash: selectedHashes[index],
98
- });
99
- }
100
- }
101
- return {
102
- text: preview,
103
- truncation: skippedTruncation.truncated ? skippedTruncation : undefined,
104
- ...(nextOffset !== undefined ? { nextOffset } : {}),
105
- served,
106
- };
107
- }
108
- const truncation = truncateHead(formatted, {
109
- maxBytes,
110
- maxLines: maxTruncLines,
111
- });
112
- let preview = truncation.content;
113
- let nextOffset;
114
- if (truncation.truncated) {
115
- const endLineDisplay = startLine + truncation.outputLines - 1;
116
- nextOffset = endLineDisplay + 1;
117
- if (truncation.truncatedBy === 'lines') {
118
- preview += `\n\n${formatPaginationHint(startLine, endLineDisplay, totalLines, nextOffset)}`;
119
- }
120
- else {
121
- preview += `\n\n${formatPaginationHint(startLine, endLineDisplay, totalLines, nextOffset, truncation.maxBytes)}`;
122
- }
123
- }
124
- else if (endIdx < totalLines) {
125
- nextOffset = endIdx + 1;
126
- preview += `\n\n${formatPaginationHint(startLine, endIdx, totalLines, nextOffset)}`;
127
- }
128
- const served = [];
129
- for (let index = 0; index < truncation.outputLines; index++) {
130
- served.push({
131
- position: startLine - 1 + index,
132
- hash: selectedHashes[index],
133
- });
134
- }
135
- return {
136
- text: preview,
137
- truncation: truncation.truncated ? truncation : undefined,
138
- ...(nextOffset !== undefined ? { nextOffset } : {}),
139
- served,
140
- };
141
- }
142
- export { MAX_HASH_LINES };
6
+ export * from "./file-view.js";
@@ -1,219 +1,5 @@
1
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.
2
+ * @deprecated — private to SessionView seam. Use `from "./session-view.js"` instead.
15
3
  * @module dsh-better-edit/served-store
16
4
  */
17
- import { randomUUID } from "node:crypto";
18
- import { HASH_RE } from "./hashline/alphabet.js";
19
- import { loadHashStore, withStore } from "./hash-store.js";
20
- let fallbackSessionKey;
21
- /**
22
- * Map a caller to the served-state session key. dsh passes the live session id
23
- * (`exec.agent.session.id`); callers without one (tests, previews) share a
24
- * process-local fallback so hashline verification never fabricates a session.
25
- */
26
- export function sessionKeyFor(sessionId) {
27
- if (sessionId && sessionId.length > 0)
28
- return sessionId;
29
- fallbackSessionKey ??= randomUUID();
30
- return fallbackSessionKey;
31
- }
32
- /**
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.
52
- */
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;
74
- }
75
- while (updated.length > 0 && updated[updated.length - 1] === null)
76
- updated.pop();
77
- return updated;
78
- }
79
- /** The served array for one session+path, or `[]` when nothing was served. */
80
- export async function loadServed(sessionKey, path) {
81
- const store = await loadHashStore();
82
- return store.getServed(sessionKey, path);
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
- */
91
- export async function recordServed(sessionKey, path, rows, lineCount) {
92
- if (rows.length === 0)
93
- return;
94
- try {
95
- const store = await loadHashStore();
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
- });
101
- }
102
- catch (error) {
103
- console.error("Failed to record served rows:", error);
104
- }
105
- }
106
- /**
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.
111
- */
112
- export async function recordServedTruncated(sessionKey, path, rows, lineCount, clearFrom = 0) {
113
- if (rows.length === 0)
114
- return;
115
- try {
116
- const store = await loadHashStore();
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
- });
125
- }
126
- catch (error) {
127
- console.error("Failed to record truncated served rows:", error);
128
- }
129
- }
130
- /** The hashes already reported as drifted for one session+path. */
131
- export async function driftReported(sessionKey, path) {
132
- try {
133
- const store = await loadHashStore();
134
- return store.getServedReported(sessionKey, path);
135
- }
136
- catch (error) {
137
- console.error("Failed to load reported drift set:", error);
138
- return new Set();
139
- }
140
- }
141
- /** Mark hashes as already reported as drifted, so later notices skip them. */
142
- export async function markDriftReported(sessionKey, path, hashes) {
143
- try {
144
- const valid = hashes.filter((hash) => HASH_RE.test(hash));
145
- if (valid.length === 0)
146
- return;
147
- const store = await loadHashStore();
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
- });
154
- }
155
- catch (error) {
156
- console.error("Failed to record reported drift set:", error);
157
- }
158
- }
159
- /** Clear the reported-drift set for one session+path (a fresh read resets it). */
160
- export async function clearDriftReported(sessionKey, path) {
161
- try {
162
- const store = await loadHashStore();
163
- withStore(() => {
164
- store.clearServedReported(sessionKey, path);
165
- });
166
- }
167
- catch (error) {
168
- console.error("Failed to clear reported drift set:", error);
169
- }
170
- }
171
- /** Drop every served row and reported-drift mark for one session. */
172
- export async function wipeServedState(sessionKey) {
173
- try {
174
- const store = await loadHashStore();
175
- store.wipeServed(sessionKey);
176
- }
177
- catch (error) {
178
- console.error("Failed to wipe served state:", error);
179
- }
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
- }
5
+ export * from "./session-view.js";