@leolastforce/chalice-hashline-edit 0.0.0-stage → 4.4.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 (64) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +153 -2
  3. package/index.ts +282 -0
  4. package/package.json +79 -4
  5. package/prompts/find-guidelines.md +2 -0
  6. package/prompts/find-snippet.md +1 -0
  7. package/prompts/find.md +1 -0
  8. package/prompts/grep-guidelines.md +2 -0
  9. package/prompts/grep-snippet.md +1 -0
  10. package/prompts/grep.md +1 -0
  11. package/prompts/insert-guidelines.md +1 -0
  12. package/prompts/insert-snippet.md +1 -0
  13. package/prompts/insert.md +1 -0
  14. package/prompts/read-guidelines.md +2 -0
  15. package/prompts/read-snippet.md +1 -0
  16. package/prompts/read.md +1 -0
  17. package/prompts/replace-guidelines.md +4 -0
  18. package/prompts/replace-snippet.md +1 -0
  19. package/prompts/replace.md +1 -0
  20. package/prompts/undo-last-change-guidelines.md +1 -0
  21. package/prompts/undo-last-change-snippet.md +1 -0
  22. package/prompts/undo-last-change.md +1 -0
  23. package/src/anchor-registry.ts +977 -0
  24. package/src/auto-read-all-state.ts +27 -0
  25. package/src/auto-read-all.ts +477 -0
  26. package/src/batch.ts +767 -0
  27. package/src/commit.ts +137 -0
  28. package/src/config-ui.ts +212 -0
  29. package/src/config.ts +235 -0
  30. package/src/constants.ts +26 -0
  31. package/src/edit-common.ts +206 -0
  32. package/src/file-kind.ts +191 -0
  33. package/src/file-reader.ts +135 -0
  34. package/src/find.ts +244 -0
  35. package/src/fs-write.ts +231 -0
  36. package/src/glob.ts +186 -0
  37. package/src/grep.ts +690 -0
  38. package/src/hash-store/cache.ts +18 -0
  39. package/src/hash-store/retry.ts +44 -0
  40. package/src/hash-store/validation.ts +62 -0
  41. package/src/hash-store.ts +609 -0
  42. package/src/hashline/alphabet.ts +21 -0
  43. package/src/hashline/anchor-table.json +1 -0
  44. package/src/hashline/apply.ts +297 -0
  45. package/src/hashline/hash.ts +119 -0
  46. package/src/hashline/hasher.ts +47 -0
  47. package/src/hashline/index.ts +50 -0
  48. package/src/hashline/parse.ts +84 -0
  49. package/src/hashline/resolve.ts +373 -0
  50. package/src/insert.ts +258 -0
  51. package/src/normalize.ts +27 -0
  52. package/src/paths.ts +56 -0
  53. package/src/payload-contract.ts +133 -0
  54. package/src/prompts.ts +13 -0
  55. package/src/read.ts +286 -0
  56. package/src/replace-diff.ts +610 -0
  57. package/src/replace-render.ts +390 -0
  58. package/src/replace-response.ts +166 -0
  59. package/src/replace-undo.ts +270 -0
  60. package/src/replace.ts +318 -0
  61. package/src/served.ts +36 -0
  62. package/src/utils.ts +387 -0
  63. package/src/validation.ts +45 -0
  64. package/src/write-hook.ts +53 -0
@@ -0,0 +1,609 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { existsSync } from "node:fs";
3
+ import { chmod, readFile, rename, mkdir, stat } from "node:fs/promises";
4
+ import { hashStorePath, hashStoreDir, legacyHashStorePath } from "./paths";
5
+ import { errCode, isRec, splitLines } from "./utils";
6
+ import { initHasher, contentChecksum, lineChecksum } from "./hashline/hasher";
7
+ import { HASH_STORE_VERSION, HASH_STORE_BUSY_TIMEOUT } from "./constants";
8
+ import {
9
+ isValidHashList,
10
+ parseStoredHashes,
11
+ isValidSnapshot,
12
+ isCorruptionError,
13
+ parseHashList,
14
+ } from "./hash-store/validation";
15
+ import {
16
+ withBusyRetry,
17
+ retriedWrite,
18
+ withBusyRetryAsync,
19
+ } from "./hash-store/retry";
20
+ import { snapshotCache, cacheSnapshot, SNAPSHOT_CACHE_LIMIT } from "./hash-store/cache";
21
+
22
+ export { isValidHashList, parseHashList, parseStoredHashes, isCorruptionError };
23
+ export { SNAPSHOT_CACHE_LIMIT };
24
+ export const STORE_NOT_OPEN_MESSAGE = "Hash store is not open; transactional update aborted";
25
+ export const STORE_SHUT_DOWN_MESSAGE = "Hash store was shut down while it was opening; call loadHashStore again.";
26
+
27
+ type SqlParams = (string | number | null)[];
28
+
29
+ interface RawStatement {
30
+ get(...params: SqlParams): unknown;
31
+ all(...params: SqlParams): unknown;
32
+ run(...params: SqlParams): unknown;
33
+ }
34
+ interface RawDb {
35
+ exec(sql: string): void;
36
+ prepare(sql: string): RawStatement;
37
+ close(): void;
38
+ readonly isOpen: boolean;
39
+ }
40
+ export type SqliteEngine = "node:sqlite" | "bun:sqlite";
41
+
42
+ interface BunStatementLike {
43
+ get(...params: SqlParams): unknown;
44
+ all(...params: SqlParams): unknown[];
45
+ run(...params: SqlParams): unknown;
46
+ }
47
+
48
+ interface BunDbLike {
49
+ exec(sql: string): void;
50
+ prepare(sql: string): BunStatementLike;
51
+ close(): void;
52
+ }
53
+
54
+ function wrapBunDatabase(mod: { Database: new (path: string) => BunDbLike }): (path: string) => RawDb {
55
+ return (path) => {
56
+ const db = new mod.Database(path);
57
+ db.exec(`PRAGMA busy_timeout = ${HASH_STORE_BUSY_TIMEOUT}`);
58
+ let closed = false;
59
+ return {
60
+ exec: (sql) => db.exec(sql),
61
+ prepare: (sql) => {
62
+ const stmt = db.prepare(sql);
63
+ return {
64
+ get: (...params) => stmt.get(...params) ?? undefined,
65
+ all: (...params) => stmt.all(...params),
66
+ run: (...params) => stmt.run(...params),
67
+ };
68
+ },
69
+ close: () => {
70
+ if (!closed) {
71
+ closed = true;
72
+ db.close();
73
+ }
74
+ },
75
+ get isOpen() {
76
+ return !closed;
77
+ },
78
+ };
79
+ };
80
+ }
81
+
82
+ async function loadNodeEngine(): Promise<{ engine: SqliteEngine; open: (path: string) => RawDb }> {
83
+ const { DatabaseSync } = await import("node:sqlite");
84
+ return {
85
+ engine: "node:sqlite",
86
+ open: (path) => new DatabaseSync(path, { timeout: HASH_STORE_BUSY_TIMEOUT }) as unknown as RawDb,
87
+ };
88
+ }
89
+
90
+ async function loadBunEngine(): Promise<{ engine: SqliteEngine; open: (path: string) => RawDb }> {
91
+ const specifier = "bun:sqlite";
92
+ const mod = await import(specifier) as { Database: new (path: string) => BunDbLike };
93
+ return { engine: "bun:sqlite", open: wrapBunDatabase(mod) };
94
+ }
95
+
96
+ const isBunRuntime = typeof process !== "undefined" && typeof (process.versions as Record<string, string | undefined>).bun === "string";
97
+
98
+ async function selectSqliteEngine(): Promise<{ engine: SqliteEngine; open: (path: string) => RawDb }> {
99
+ const candidates = isBunRuntime ? [loadBunEngine, loadNodeEngine] : [loadNodeEngine, loadBunEngine];
100
+ let lastError: unknown;
101
+ for (const candidate of candidates) {
102
+ try {
103
+ return await candidate();
104
+ } catch (error) {
105
+ lastError = error;
106
+ }
107
+ }
108
+ const detail = lastError instanceof Error ? lastError.message : String(lastError);
109
+ throw new Error(`[E_STORE_UNAVAILABLE] No SQLite runtime available (node:sqlite and bun:sqlite both failed to load): ${detail}`);
110
+ }
111
+
112
+ const selectedEngine = await selectSqliteEngine();
113
+ const sqliteEngine: SqliteEngine = selectedEngine.engine;
114
+ const openDbFn = selectedEngine.open;
115
+
116
+ interface Prepared {
117
+ get: (...params: SqlParams) => Record<string, unknown> | undefined;
118
+ getState: (...params: SqlParams) => Record<string, unknown> | undefined;
119
+ allPaths: (...params: SqlParams) => Record<string, unknown>[];
120
+ deleteOne: (...params: SqlParams) => void;
121
+ upsert: (...params: SqlParams) => void;
122
+ undoUpsert: (...params: SqlParams) => void;
123
+ undoGet: (...params: SqlParams) => Record<string, unknown> | undefined;
124
+ undoDelete: (...params: SqlParams) => void;
125
+ snapshotTime: (...params: SqlParams) => Record<string, unknown> | undefined;
126
+ undoTime: (...params: SqlParams) => Record<string, unknown> | undefined;
127
+ }
128
+
129
+ export interface HashStore {
130
+ readonly stmts: Prepared;
131
+ readonly engine: SqliteEngine;
132
+ }
133
+
134
+ export interface UndoRecord {
135
+ content: string;
136
+ bom: string;
137
+ ending: string;
138
+ hashes: string[];
139
+ resultContent: string;
140
+ mode?: number;
141
+ }
142
+
143
+ let cachedDb: { path: string; db: RawDb; stmts: Prepared } | null = null;
144
+ let opening: { path: string; promise: Promise<HashStore> } | null = null;
145
+ let exitHandlerRegistered = false;
146
+ let storeEpoch = 0;
147
+ const liveDbs = new Set<RawDb>();
148
+
149
+ function openDb(storePath: string): { db: RawDb; stmts: Prepared } {
150
+ const db = openDbFn(storePath);
151
+ liveDbs.add(db);
152
+ try {
153
+ return buildStore(db);
154
+ } catch (error) {
155
+ shutdownDb(db);
156
+ throw error;
157
+ }
158
+ }
159
+
160
+ function buildStore(db: RawDb): { db: RawDb; stmts: Prepared } {
161
+ db.exec("PRAGMA journal_mode = WAL");
162
+ db.exec("PRAGMA synchronous = NORMAL");
163
+ db.exec(
164
+ "CREATE TABLE IF NOT EXISTS snapshots (" +
165
+ "path TEXT PRIMARY KEY, " +
166
+ "checksum TEXT NOT NULL, " +
167
+ "line_count INTEGER NOT NULL, " +
168
+ "hashes TEXT NOT NULL, " +
169
+ "updated_at INTEGER NOT NULL" +
170
+ ")"
171
+ );
172
+ db.exec(
173
+ "CREATE TABLE IF NOT EXISTS meta (" +
174
+ "key TEXT PRIMARY KEY, " +
175
+ "value TEXT NOT NULL" +
176
+ ")"
177
+ );
178
+ db.exec(
179
+ "CREATE TABLE IF NOT EXISTS undo (" +
180
+ "path TEXT PRIMARY KEY, " +
181
+ "content TEXT NOT NULL, " +
182
+ "bom TEXT NOT NULL, " +
183
+ "ending TEXT NOT NULL, " +
184
+ "hashes TEXT NOT NULL, " +
185
+ "result_content TEXT NOT NULL, " +
186
+ "updated_at INTEGER NOT NULL" +
187
+ ")"
188
+ );
189
+ try {
190
+ db.exec("ALTER TABLE snapshots ADD COLUMN line_checksums TEXT");
191
+ } catch {}
192
+ try {
193
+ db.exec("ALTER TABLE undo ADD COLUMN mode INTEGER");
194
+ } catch {}
195
+ const versionRow = db.prepare("SELECT value FROM meta WHERE key = 'version'").get() as { value?: string } | undefined;
196
+ if (versionRow && versionRow.value !== String(HASH_STORE_VERSION)) {
197
+ db.exec("DELETE FROM snapshots");
198
+ db.exec("DELETE FROM undo");
199
+ }
200
+ db.prepare(
201
+ "INSERT INTO meta (key, value) VALUES ('version', ?) " +
202
+ "ON CONFLICT(key) DO UPDATE SET value = excluded.value"
203
+ ).run(String(HASH_STORE_VERSION));
204
+ const getStmt = db.prepare("SELECT hashes FROM snapshots WHERE path = ? AND checksum = ? AND line_count = ?");
205
+ const getStateStmt = db.prepare("SELECT checksum, hashes, line_checksums FROM snapshots WHERE path = ?");
206
+ const allStmt = db.prepare("SELECT path FROM snapshots UNION SELECT path FROM undo");
207
+ const delStmt = db.prepare("DELETE FROM snapshots WHERE path = ?");
208
+ const upsertStmt = db.prepare(
209
+ "INSERT INTO snapshots (path, checksum, line_count, hashes, line_checksums, updated_at) VALUES (?, ?, ?, ?, ?, ?) " +
210
+ "ON CONFLICT(path) DO UPDATE SET checksum = excluded.checksum, line_count = excluded.line_count, hashes = excluded.hashes, line_checksums = excluded.line_checksums, updated_at = excluded.updated_at"
211
+ );
212
+ const undoUpsertStmt = db.prepare(
213
+ "INSERT INTO undo (path, content, bom, ending, hashes, result_content, mode, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?) " +
214
+ "ON CONFLICT(path) DO UPDATE SET content = excluded.content, bom = excluded.bom, ending = excluded.ending, hashes = excluded.hashes, result_content = excluded.result_content, mode = excluded.mode, updated_at = excluded.updated_at"
215
+ );
216
+ const undoGetStmt = db.prepare(
217
+ "SELECT content, bom, ending, hashes, result_content, mode FROM undo WHERE path = ?"
218
+ );
219
+ const undoDelStmt = db.prepare("DELETE FROM undo WHERE path = ?");
220
+ const snapshotTimeStmt = db.prepare("SELECT updated_at FROM snapshots WHERE path = ?");
221
+ const undoTimeStmt = db.prepare("SELECT updated_at FROM undo WHERE path = ?");
222
+ const stmts: Prepared = {
223
+ get: (...params) => getStmt.get(...params) as Record<string, unknown> | undefined,
224
+ getState: (...params) => getStateStmt.get(...params) as Record<string, unknown> | undefined,
225
+ allPaths: (...params) => withBusyRetry(() => allStmt.all(...params) as Record<string, unknown>[]),
226
+ deleteOne: retriedWrite(delStmt),
227
+ upsert: retriedWrite(upsertStmt),
228
+ undoUpsert: retriedWrite(undoUpsertStmt),
229
+ undoGet: (...params) => undoGetStmt.get(...params) as Record<string, unknown> | undefined,
230
+ undoDelete: retriedWrite(undoDelStmt),
231
+ snapshotTime: (...params) => snapshotTimeStmt.get(...params) as Record<string, unknown> | undefined,
232
+ undoTime: (...params) => undoTimeStmt.get(...params) as Record<string, unknown> | undefined,
233
+ };
234
+ return { db, stmts };
235
+ }
236
+
237
+ function isHealthy(db: RawDb): boolean {
238
+ try {
239
+ const row = db.prepare("PRAGMA quick_check").get() as { quick_check?: string } | undefined;
240
+ return row?.quick_check === "ok";
241
+ } catch (error) {
242
+ if (isCorruptionError(error)) return false;
243
+ return true;
244
+ }
245
+ }
246
+
247
+ async function quarantineStore(storePath: string): Promise<void> {
248
+ const suffix = `.corrupt-${Date.now()}-${process.pid}-${randomUUID()}`;
249
+ for (const candidate of [storePath, `${storePath}-wal`, `${storePath}-shm`]) {
250
+ try {
251
+ await rename(candidate, `${candidate}${suffix}`);
252
+ } catch (error) {
253
+ if (errCode(error) !== "ENOENT") {
254
+ console.error("Failed to quarantine corrupt hash store file:", error);
255
+ }
256
+ }
257
+ }
258
+ }
259
+
260
+ function shutdownDb(db: RawDb): void {
261
+ if (!liveDbs.delete(db)) return;
262
+ try {
263
+ db.exec("PRAGMA wal_checkpoint(TRUNCATE)");
264
+ } catch {
265
+ }
266
+ try {
267
+ db.close();
268
+ } catch {
269
+ }
270
+ }
271
+
272
+ async function openStore(storePath: string): Promise<HashStore> {
273
+ if (cachedDb && cachedDb.path === storePath && cachedDb.db.isOpen) {
274
+ return { stmts: cachedDb.stmts, engine: sqliteEngine };
275
+ }
276
+ if (cachedDb) shutdownHashStore();
277
+ const epoch = storeEpoch;
278
+ await initHasher();
279
+ await mkdir(hashStoreDir(), { recursive: true, mode: 0o700 });
280
+ if (process.platform !== "win32") {
281
+ await chmod(hashStoreDir(), 0o700);
282
+ }
283
+
284
+ let existed = existsSync(storePath);
285
+ let opened: { db: RawDb; stmts: Prepared };
286
+ try {
287
+ opened = await withBusyRetryAsync(() => openDb(storePath));
288
+ } catch (error) {
289
+ if (!isCorruptionError(error)) throw error;
290
+ console.error("Hash store failed to open, rebuilding:", error);
291
+ await quarantineStore(storePath);
292
+ existed = false;
293
+ opened = await withBusyRetryAsync(() => openDb(storePath));
294
+ }
295
+ if (!isHealthy(opened.db)) {
296
+ shutdownDb(opened.db);
297
+ await quarantineStore(storePath);
298
+ existed = false;
299
+ opened = await withBusyRetryAsync(() => openDb(storePath));
300
+ }
301
+ const { db, stmts } = opened;
302
+ try {
303
+ const autoVacuum = (db.prepare("PRAGMA auto_vacuum").get() as { auto_vacuum: number }).auto_vacuum;
304
+ const pageCount = (db.prepare("PRAGMA page_count").get() as { page_count: number }).page_count;
305
+ const freelist = (db.prepare("PRAGMA freelist_count").get() as { freelist_count: number }).freelist_count;
306
+ if (autoVacuum === 0 && !existed) {
307
+ db.exec("PRAGMA auto_vacuum=INCREMENTAL");
308
+ } else if (freelist > 50 && freelist * 5 > pageCount) {
309
+ try {
310
+ db.exec("PRAGMA incremental_vacuum(50)");
311
+ } catch {
312
+ db.exec("VACUUM");
313
+ }
314
+ }
315
+ } catch {}
316
+
317
+ if (process.platform !== "win32") {
318
+ for (const candidate of [storePath, `${storePath}-wal`, `${storePath}-shm`]) {
319
+ try {
320
+ await chmod(candidate, 0o600);
321
+ } catch (error) {
322
+ if (errCode(error) !== "ENOENT") throw error;
323
+ }
324
+ }
325
+ }
326
+
327
+ if (!existed) {
328
+ try {
329
+ await migrateLegacy(db);
330
+ } catch (error) {
331
+ console.error("Hash store migration failed; continuing without legacy import:", error);
332
+ }
333
+ }
334
+ if (storeEpoch !== epoch) {
335
+ shutdownDb(db);
336
+ throw new Error(STORE_SHUT_DOWN_MESSAGE);
337
+ }
338
+ cachedDb = { path: storePath, db, stmts };
339
+
340
+ if (!exitHandlerRegistered) {
341
+ exitHandlerRegistered = true;
342
+ process.once("exit", () => shutdownHashStore());
343
+ for (const sig of ["SIGINT", "SIGTERM"] as const) {
344
+ process.once(sig, () => {
345
+ shutdownHashStore();
346
+ process.kill(process.pid, sig);
347
+ });
348
+ }
349
+ }
350
+
351
+ return { stmts, engine: sqliteEngine };
352
+ }
353
+
354
+ export function loadHashStore(): Promise<HashStore> {
355
+ const storePath = hashStorePath();
356
+ if (cachedDb && cachedDb.path === storePath && cachedDb.db.isOpen) {
357
+ return Promise.resolve({ stmts: cachedDb.stmts, engine: sqliteEngine });
358
+ }
359
+ if (opening && opening.path === storePath) {
360
+ return opening.promise;
361
+ }
362
+ const promise = openStore(storePath).finally(() => {
363
+ if (opening?.promise === promise) opening = null;
364
+ });
365
+ opening = { path: storePath, promise };
366
+ return promise;
367
+ }
368
+
369
+ export function shutdownHashStore(): void {
370
+ storeEpoch += 1;
371
+ if (cachedDb) {
372
+ shutdownDb(cachedDb.db);
373
+ cachedDb = null;
374
+ }
375
+ for (const db of [...liveDbs]) shutdownDb(db);
376
+ opening = null;
377
+ snapshotCache.clear();
378
+ }
379
+
380
+ function withTransaction(db: RawDb, fn: () => void): void {
381
+ withBusyRetry(() => {
382
+ db.exec("BEGIN IMMEDIATE");
383
+ try {
384
+ fn();
385
+ db.exec("COMMIT");
386
+ } catch (e) {
387
+ try { db.exec("ROLLBACK"); } catch {}
388
+ throw e;
389
+ }
390
+ });
391
+ }
392
+
393
+ export function withStore(fn: () => void): void {
394
+ if (!cachedDb || !cachedDb.db.isOpen) {
395
+ throw new Error(STORE_NOT_OPEN_MESSAGE);
396
+ }
397
+ withTransaction(cachedDb.db, fn);
398
+ }
399
+
400
+ async function migrateLegacy(db: RawDb): Promise<void> {
401
+ const legacyPath = legacyHashStorePath();
402
+ let content: string;
403
+ try {
404
+ content = await readFile(legacyPath, "utf-8");
405
+ } catch (error: unknown) {
406
+ if (errCode(error) === "ENOENT") return;
407
+ console.error("Failed to read legacy hash store for migration:", error);
408
+ return;
409
+ }
410
+
411
+ let parsed: { snapshots?: Record<string, unknown> };
412
+ try {
413
+ parsed = JSON.parse(content) as typeof parsed;
414
+ } catch (error) {
415
+ console.error("Failed to parse legacy hash store, skipping migration:", error);
416
+ return;
417
+ }
418
+
419
+ const raw = parsed.snapshots;
420
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return;
421
+
422
+ const rows: [string, string, number, string, string, number][] = [];
423
+ for (const [key, value] of Object.entries(raw)) {
424
+ if (
425
+ isRec(value) &&
426
+ Array.isArray(value.hashes) &&
427
+ new Set(value.hashes).size !== value.hashes.length
428
+ ) {
429
+ console.warn(
430
+ `Skipped legacy snapshot with duplicate hashes for ${key}; it will be re-hashed on next read.`,
431
+ );
432
+ continue;
433
+ }
434
+ if (!isValidSnapshot(value)) continue;
435
+ rows.push([
436
+ key,
437
+ contentChecksum(value.content),
438
+ splitLines(value.content).length,
439
+ JSON.stringify(value.hashes),
440
+ JSON.stringify(splitLines(value.content).map(lineChecksum)),
441
+ Date.now(),
442
+ ]);
443
+ }
444
+ if (rows.length > 0) {
445
+ withTransaction(db, () => {
446
+ const stmt = db.prepare(
447
+ "INSERT OR REPLACE INTO snapshots (path, checksum, line_count, hashes, line_checksums, updated_at) VALUES (?, ?, ?, ?, ?, ?)"
448
+ );
449
+ for (const row of rows) stmt.run(...row);
450
+ });
451
+ }
452
+
453
+ try {
454
+ await rename(legacyPath, `${legacyPath}.bak`);
455
+ } catch (error) {
456
+ console.error("Failed to rename legacy hash store after migration:", error);
457
+ }
458
+ }
459
+
460
+ export function getSnapshot(
461
+ store: HashStore,
462
+ path: string,
463
+ content: string,
464
+ deleteCorrupt = true,
465
+ ): string[] | undefined {
466
+ const checksum = contentChecksum(content);
467
+ const lineCount = splitLines(content).length;
468
+ const cached = snapshotCache.get(path);
469
+ if (cached && cached.checksum === checksum && cached.lineCount === lineCount) {
470
+ snapshotCache.delete(path);
471
+ snapshotCache.set(path, cached);
472
+ return cached.hashes.slice();
473
+ }
474
+ const row = withBusyRetry(() => store.stmts.get(path, checksum, lineCount));
475
+ const parsed = parseStoredHashes(row, () => {
476
+ if (deleteCorrupt) store.stmts.deleteOne(path);
477
+ snapshotCache.delete(path);
478
+ });
479
+ if (!parsed) return undefined;
480
+ cacheSnapshot(path, checksum, lineCount, parsed);
481
+ return parsed;
482
+ }
483
+
484
+ export function upsertSnapshot(
485
+ store: HashStore,
486
+ path: string,
487
+ checksum: string,
488
+ lineCount: number,
489
+ hashes: string[],
490
+ lineChecksums?: string[],
491
+ ): void {
492
+ store.stmts.upsert(path, checksum, lineCount, JSON.stringify(hashes), lineChecksums ? JSON.stringify(lineChecksums) : "", Date.now());
493
+ cacheSnapshot(path, checksum, lineCount, hashes);
494
+ }
495
+ export function persistSnapshot(
496
+ store: HashStore,
497
+ path: string,
498
+ content: string,
499
+ hashes: string[],
500
+ lineChecksums?: string[],
501
+ ): void {
502
+ upsertSnapshot(store, path, contentChecksum(content), splitLines(content).length, hashes, lineChecksums);
503
+ }
504
+
505
+ export interface AllocatedState {
506
+ anchors: string[];
507
+ checksums: string[] | undefined;
508
+ contentChecksum: string;
509
+ }
510
+
511
+ export function getAllocatedState(store: HashStore, path: string, deleteCorrupt = true): AllocatedState | undefined {
512
+ const row = withBusyRetry(() => store.stmts.getState(path)) as
513
+ | { checksum?: unknown; hashes?: unknown; line_checksums?: unknown }
514
+ | undefined;
515
+ if (!row || typeof row.checksum !== "string") return undefined;
516
+ const parsedAnchors = parseStoredHashes({ hashes: row.hashes }, () => {
517
+ if (deleteCorrupt) store.stmts.deleteOne(path);
518
+ snapshotCache.delete(path);
519
+ });
520
+ if (!parsedAnchors) return undefined;
521
+ let checksums: string[] | undefined;
522
+ if (typeof row.line_checksums === "string" && row.line_checksums.length > 0) {
523
+ try {
524
+ const parsed = JSON.parse(row.line_checksums) as unknown;
525
+ if (Array.isArray(parsed) && parsed.every((c) => typeof c === "string")) {
526
+ checksums = parsed as string[];
527
+ }
528
+ } catch {
529
+ checksums = undefined;
530
+ }
531
+ }
532
+ return { anchors: parsedAnchors, checksums, contentChecksum: row.checksum };
533
+ }
534
+
535
+ export function upsertUndo(store: HashStore, path: string, entry: UndoRecord): void {
536
+ store.stmts.undoUpsert(
537
+ path,
538
+ entry.content,
539
+ entry.bom,
540
+ entry.ending,
541
+ JSON.stringify(entry.hashes),
542
+ entry.resultContent,
543
+ typeof entry.mode === "number" ? entry.mode : null,
544
+ Date.now(),
545
+ );
546
+ }
547
+
548
+ export function getUndoEntry(store: HashStore, path: string): UndoRecord | undefined {
549
+ const row = withBusyRetry(() => store.stmts.undoGet(path));
550
+ if (!row) return undefined;
551
+ const parsed = parseStoredHashes(row, () => store.stmts.undoDelete(path));
552
+ if (!parsed) return undefined;
553
+ return {
554
+ content: row.content as string,
555
+ bom: row.bom as string,
556
+ ending: row.ending as string,
557
+ hashes: parsed,
558
+ resultContent: row.result_content as string,
559
+ ...(typeof row.mode === "number" ? { mode: row.mode } : {}),
560
+ };
561
+ }
562
+
563
+ export function deleteUndo(store: HashStore, path: string): void {
564
+ store.stmts.undoDelete(path);
565
+ }
566
+
567
+ const STAT_BATCH = 64;
568
+
569
+ async function statMissing(rows: { path: string }[]): Promise<string[]> {
570
+ const missing: string[] = [];
571
+ for (let i = 0; i < rows.length; i += STAT_BATCH) {
572
+ const batch = rows.slice(i, i + STAT_BATCH);
573
+ const results = await Promise.all(
574
+ batch.map(async (row) => {
575
+ try {
576
+ await stat(row.path);
577
+ return undefined;
578
+ } catch (error: unknown) {
579
+ const code = errCode(error);
580
+ if (code !== "ENOENT" && code !== "ENOTDIR") {
581
+ console.error("Failed to stat hash store path:", row.path, error);
582
+ return undefined;
583
+ }
584
+ return row.path;
585
+ }
586
+ }),
587
+ );
588
+ for (const path of results) {
589
+ if (path !== undefined) missing.push(path);
590
+ }
591
+ }
592
+ return missing;
593
+ }
594
+
595
+ export async function pruneMissing(store: HashStore): Promise<string[]> {
596
+ const rows = store.stmts.allPaths() as { path: string }[];
597
+ const missing = await statMissing(rows);
598
+ if (missing.length === 0) return [];
599
+ withStore(() => {
600
+ for (const path of missing) {
601
+ store.stmts.deleteOne(path);
602
+ }
603
+ });
604
+ for (const path of missing) snapshotCache.delete(path);
605
+ return missing;
606
+ }
607
+
608
+
609
+
@@ -0,0 +1,21 @@
1
+ import anchorData from "./anchor-table.json";
2
+ const rawAnchors: unknown = (anchorData as { anchors?: unknown }).anchors;
3
+ if (typeof rawAnchors !== "string" || rawAnchors.length === 0 || rawAnchors.length % 4 !== 0) {
4
+ throw new Error("[E_REGISTRY] Anchor table is missing or corrupt; reinstall pi-hashline-edit-pro.");
5
+ }
6
+ const TABLE: string = rawAnchors;
7
+ export const HASH_LEN = 4;
8
+ export const ANCHOR_COUNT = TABLE.length / HASH_LEN;
9
+ const LETTERS = "A-Za-z";
10
+
11
+ export const ALPH_RE = new RegExp(`^[${LETTERS}]+$`);
12
+
13
+ export const HASH_CLASS = `[${LETTERS}]{${HASH_LEN}}`;
14
+
15
+ export const HASH_RUN = `[${LETTERS}]{${HASH_LEN},${HASH_LEN + 1}}`;
16
+
17
+ export const HASH_RE = new RegExp(`^${HASH_CLASS}$`);
18
+
19
+ export function anchorAt(idx: number): string {
20
+ return TABLE.slice(idx * HASH_LEN, idx * HASH_LEN + HASH_LEN);
21
+ }