@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,977 @@
1
+ import { chmod, mkdir, open, readFile, readdir, rename, rm, stat, writeFile } from "node:fs/promises";
2
+ import { appendFileSync, chmodSync, statSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ import { createHash } from "node:crypto";
5
+ import { AsyncLocalStorage } from "node:async_hooks";
6
+ import { sessionClaimsDir } from "./paths";
7
+ import { contentChecksum } from "./hashline/hasher";
8
+ import { ANCHOR_COUNT, anchorAt } from "./hashline/alphabet";
9
+ import { HASH_PROBE_STRIDE } from "./hashline/hash";
10
+ import { errCode, splitLines } from "./utils";
11
+ import * as Diff from "hashline-diff";
12
+ import { lineChecksum } from "./hashline";
13
+ import { getAllocatedState, persistSnapshot, type HashStore } from "./hash-store";
14
+ import { ANCHOR_POOL_EXHAUSTED_PREFIX } from "./constants";
15
+
16
+ export type RegistryEvent =
17
+ | { kind: "session"; sessionFile: string }
18
+ | { kind: "allocate"; path: string; rows: [string, string][] }
19
+ | { kind: "free"; path: string; anchors?: string[] }
20
+ | { kind: "minted"; anchors: string[] }
21
+ | { kind: "clear" };
22
+
23
+ export interface OwnedAnchor {
24
+ path: string;
25
+ checksum: string;
26
+ }
27
+
28
+ export interface AnchorSessionContext {
29
+ sessionManager?: {
30
+ getSessionFile?: () => string | undefined;
31
+ getSessionId?: () => string;
32
+ };
33
+ }
34
+
35
+ interface OwnedAnchorMap {
36
+ readonly size: number;
37
+ has(anchor: string): boolean;
38
+ get(anchor: string): OwnedAnchor | undefined;
39
+ set(anchor: string, entry: OwnedAnchor): unknown;
40
+ delete(anchor: string): boolean;
41
+ clear(): void;
42
+ keys(): Iterable<string>;
43
+ values(): Iterable<OwnedAnchor>;
44
+ entries(): Iterable<[string, OwnedAnchor]>;
45
+ [Symbol.iterator](): IterableIterator<[string, OwnedAnchor]>;
46
+ }
47
+
48
+ interface AnchorMintedSet {
49
+ has(anchor: string): boolean;
50
+ add(anchor: string): unknown;
51
+ [Symbol.iterator](): IterableIterator<string>;
52
+ }
53
+
54
+ class ShadowOwnedMap implements OwnedAnchorMap {
55
+ private readonly parent: OwnedAnchorMap;
56
+ private readonly overrides = new Map<string, OwnedAnchor | undefined>();
57
+
58
+ constructor(parent: OwnedAnchorMap) {
59
+ this.parent = parent;
60
+ }
61
+
62
+ has(anchor: string): boolean {
63
+ return this.overrides.has(anchor) ? this.overrides.get(anchor) !== undefined : this.parent.has(anchor);
64
+ }
65
+
66
+ get(anchor: string): OwnedAnchor | undefined {
67
+ return this.overrides.has(anchor) ? this.overrides.get(anchor) : this.parent.get(anchor);
68
+ }
69
+
70
+ set(anchor: string, entry: OwnedAnchor): this {
71
+ this.overrides.set(anchor, entry);
72
+ return this;
73
+ }
74
+
75
+ delete(anchor: string): boolean {
76
+ const owned = this.has(anchor);
77
+ this.overrides.set(anchor, undefined);
78
+ return owned;
79
+ }
80
+
81
+ clear(): void {
82
+ for (const anchor of this.parent.keys()) this.overrides.set(anchor, undefined);
83
+ for (const [anchor, entry] of this.overrides) {
84
+ if (entry !== undefined && !this.parent.has(anchor)) this.overrides.delete(anchor);
85
+ }
86
+ }
87
+
88
+ get size(): number {
89
+ let count = 0;
90
+ for (const _entry of this) count += 1;
91
+ return count;
92
+ }
93
+
94
+ *keys(): IterableIterator<string> {
95
+ for (const [anchor] of this.merged()) yield anchor;
96
+ }
97
+
98
+ *values(): IterableIterator<OwnedAnchor> {
99
+ for (const [, entry] of this.merged()) yield entry;
100
+ }
101
+
102
+ *entries(): IterableIterator<[string, OwnedAnchor]> {
103
+ yield* this.merged();
104
+ }
105
+
106
+ *[Symbol.iterator](): IterableIterator<[string, OwnedAnchor]> {
107
+ yield* this.merged();
108
+ }
109
+
110
+ private *merged(): IterableIterator<[string, OwnedAnchor]> {
111
+ for (const [anchor, entry] of this.parent) {
112
+ if (this.overrides.has(anchor)) {
113
+ const override = this.overrides.get(anchor);
114
+ if (override !== undefined) yield [anchor, override];
115
+ } else {
116
+ yield [anchor, entry];
117
+ }
118
+ }
119
+ for (const [anchor, entry] of this.overrides) {
120
+ if (entry !== undefined && !this.parent.has(anchor)) yield [anchor, entry];
121
+ }
122
+ }
123
+ }
124
+
125
+ class ShadowMintedSet implements AnchorMintedSet {
126
+ private readonly parent: AnchorMintedSet;
127
+ private readonly added = new Set<string>();
128
+
129
+ constructor(parent: AnchorMintedSet) {
130
+ this.parent = parent;
131
+ }
132
+
133
+ has(anchor: string): boolean {
134
+ return this.added.has(anchor) || this.parent.has(anchor);
135
+ }
136
+
137
+ add(anchor: string): this {
138
+ this.added.add(anchor);
139
+ return this;
140
+ }
141
+
142
+ *[Symbol.iterator](): IterableIterator<string> {
143
+ yield* this.parent;
144
+ for (const anchor of this.added) {
145
+ if (!this.parent.has(anchor)) yield anchor;
146
+ }
147
+ }
148
+ }
149
+
150
+ interface SessionState {
151
+ owned: OwnedAnchorMap;
152
+ served: Map<string, Map<string, string>>;
153
+ everMinted: AnchorMintedSet;
154
+ probe: number;
155
+ allocatedChecksum: Map<string, string>;
156
+ }
157
+
158
+ const SIDECAR_SUFFIX = ".registry.jsonl";
159
+ const SIDECAR_COMPACT_LINES = 5000;
160
+ const SIDECAR_COMPACT_BYTES = 1024 * 1024;
161
+ export const SIDECAR_COMPACT_LINE_BYTES = 48 * 1024;
162
+ export const SIDECAR_HEADER_BYTES = 64 * 1024;
163
+ const SIDECAR_HEADER_CHUNK = 4096;
164
+ let currentKey: string | undefined;
165
+ const sidecarByKey = new Map<string, string>();
166
+ const sessionFileByKey = new Map<string, string>();
167
+ const pendingInits = new Map<string, Promise<void>>();
168
+ const loadTokens = new Map<string, object>();
169
+ const registries = new Map<string, SessionState>();
170
+ const sessionScope = new AsyncLocalStorage<string>();
171
+
172
+ function newSessionState(seed?: string): SessionState {
173
+ let probe = 0;
174
+ if (seed) {
175
+ for (const byte of createHash("sha256").update(seed).digest()) {
176
+ probe = (probe * 256 + byte) % ANCHOR_COUNT;
177
+ }
178
+ }
179
+ return { owned: new Map(), served: new Map(), everMinted: new Set(), probe, allocatedChecksum: new Map() };
180
+ }
181
+
182
+ function seedServedFromOwned(state: SessionState): void {
183
+ for (const [anchor, entry] of state.owned) {
184
+ let served = state.served.get(entry.path);
185
+ if (!served) {
186
+ served = new Map();
187
+ state.served.set(entry.path, served);
188
+ }
189
+ served.set(anchor, entry.checksum);
190
+ }
191
+ }
192
+
193
+ export function foldRegistryEvents(events: RegistryEvent[], seed?: string): SessionState {
194
+ const state = newSessionState(seed);
195
+ for (const event of events) {
196
+ if (event.kind === "clear") {
197
+ state.owned.clear();
198
+ } else if (event.kind === "minted") {
199
+ for (const anchor of event.anchors) state.everMinted.add(anchor);
200
+ } else if (event.kind === "allocate") {
201
+ for (const [anchor, checksum] of event.rows) {
202
+ state.owned.set(anchor, { path: event.path, checksum });
203
+ state.everMinted.add(anchor);
204
+ }
205
+ } else if (event.kind === "free") {
206
+ if (event.anchors) {
207
+ for (const anchor of event.anchors) {
208
+ state.owned.delete(anchor);
209
+ }
210
+ } else {
211
+ for (const [anchor, entry] of [...state.owned]) {
212
+ if (entry.path === event.path) {
213
+ state.owned.delete(anchor);
214
+ }
215
+ }
216
+ }
217
+ }
218
+ }
219
+ return state;
220
+ }
221
+
222
+ export function parseRegistryLog(raw: string): RegistryEvent[] {
223
+ const events: RegistryEvent[] = [];
224
+ for (const line of raw.split("\n")) {
225
+ if (!line.trim()) continue;
226
+ try {
227
+ const parsed = JSON.parse(line) as RegistryEvent;
228
+ if (parsed && (parsed.kind === "allocate" || parsed.kind === "free" || parsed.kind === "clear" || parsed.kind === "session" || parsed.kind === "minted")) {
229
+ events.push(parsed);
230
+ }
231
+ } catch {
232
+ continue;
233
+ }
234
+ }
235
+ return events;
236
+ }
237
+
238
+ function sidecarPath(key: string): string {
239
+ return join(sessionClaimsDir(), `${key}${SIDECAR_SUFFIX}`);
240
+ }
241
+
242
+ function sidecarKeyFor(sessionFile: string): string {
243
+ return createHash("sha256").update(sessionFile).digest("hex").slice(0, 24);
244
+ }
245
+ export function shouldCompactSidecar(raw: string): boolean {
246
+ if (raw.length >= SIDECAR_COMPACT_BYTES) return true;
247
+ let lines = 0;
248
+ for (let i = 0; i < raw.length; i++) if (raw.charCodeAt(i) === 10) lines += 1;
249
+ return lines >= SIDECAR_COMPACT_LINES;
250
+ }
251
+
252
+ function parseSessionFileLine(line: string): string | undefined {
253
+ const trimmed = line.trim();
254
+ if (trimmed.length === 0) return undefined;
255
+ try {
256
+ const event = JSON.parse(trimmed) as { kind?: unknown; sessionFile?: unknown };
257
+ if (event.kind === "session" && typeof event.sessionFile === "string" && event.sessionFile.length > 0) return event.sessionFile;
258
+ } catch {
259
+ }
260
+ return undefined;
261
+ }
262
+
263
+ function firstLineSessionFile(raw: string): string | undefined {
264
+ const newline = raw.indexOf("\n");
265
+ return parseSessionFileLine(newline >= 0 ? raw.slice(0, newline) : raw);
266
+ }
267
+
268
+ function chunkBySerializedBytes<T>(items: T[], wrap: (chunk: T[]) => unknown, maxBytes: number): T[][] {
269
+ const chunks: T[][] = [];
270
+ if (items.length === 0) return chunks;
271
+ const overhead = Buffer.byteLength(JSON.stringify(wrap([])), "utf-8");
272
+ let chunk: T[] = [];
273
+ let bytes = overhead;
274
+ for (const item of items) {
275
+ const itemBytes = Buffer.byteLength(JSON.stringify(item), "utf-8");
276
+ const nextBytes = bytes + itemBytes + (chunk.length > 0 ? 1 : 0);
277
+ if (chunk.length > 0 && nextBytes > maxBytes) {
278
+ chunks.push(chunk);
279
+ chunk = [item];
280
+ bytes = overhead + itemBytes;
281
+ } else {
282
+ chunk.push(item);
283
+ bytes = nextBytes;
284
+ }
285
+ }
286
+ chunks.push(chunk);
287
+ return chunks;
288
+ }
289
+
290
+ export function buildCompactedLog(sessionFile: string, state: SessionState): string {
291
+ const byPath = new Map<string, Array<[string, string]>>();
292
+ for (const [anchor, entry] of state.owned) {
293
+ const rows = byPath.get(entry.path) ?? [];
294
+ rows.push([anchor, entry.checksum]);
295
+ byPath.set(entry.path, rows);
296
+ }
297
+ const out: string[] = [JSON.stringify({ kind: "session", sessionFile })];
298
+ for (const [path, rows] of byPath) {
299
+ for (const chunk of chunkBySerializedBytes(rows, (part) => ({ kind: "allocate", path, rows: part }), SIDECAR_COMPACT_LINE_BYTES)) {
300
+ out.push(JSON.stringify({ kind: "allocate", path, rows: chunk }));
301
+ }
302
+ }
303
+ const freedHistory = [...state.everMinted].filter((anchor) => !state.owned.has(anchor));
304
+ for (const chunk of chunkBySerializedBytes(freedHistory, (part) => ({ kind: "minted", anchors: part }), SIDECAR_COMPACT_LINE_BYTES)) {
305
+ out.push(JSON.stringify({ kind: "minted", anchors: chunk }));
306
+ }
307
+ return out.join("\n") + "\n";
308
+ }
309
+ async function compactSidecarIfNeeded(sidecar: string, raw: string, sessionFile: string, state: SessionState, force = false): Promise<void> {
310
+ if (!force && !shouldCompactSidecar(raw)) return;
311
+ const tmp = `${sidecar}.compact-${Date.now()}-${Math.random().toString(36).slice(2)}`;
312
+ try {
313
+ const compacted = buildCompactedLog(sessionFile, state);
314
+ await writeFile(tmp, compacted, { mode: 0o600 });
315
+ if (process.platform !== "win32") {
316
+ try { await chmod(tmp, 0o600); } catch { }
317
+ }
318
+ await rename(tmp, sidecar);
319
+ } catch (error) {
320
+ console.error("Failed to compact anchor registry sidecar:", error);
321
+ try { await rm(tmp, { force: true }); } catch { }
322
+ }
323
+ }
324
+
325
+ async function loadRegistryState(key: string, sessionFile: string, token: object): Promise<void> {
326
+ const sidecar = sidecarPath(key);
327
+ let events: RegistryEvent[] = [];
328
+ let rawLog = "";
329
+ try {
330
+ rawLog = await readFile(sidecar, "utf-8");
331
+ events = parseRegistryLog(rawLog);
332
+ } catch (error) {
333
+ if (errCode(error) !== "ENOENT") {
334
+ console.error("Failed to read anchor registry sidecar:", error);
335
+ }
336
+ }
337
+ const folded = foldRegistryEvents(events, `${key}:${process.pid}`);
338
+ if (loadTokens.get(key) !== token) return;
339
+ seedServedFromOwned(folded);
340
+ registries.set(key, folded);
341
+ sidecarByKey.set(key, sidecar);
342
+ if (rawLog.length > 0) {
343
+ await compactSidecarIfNeeded(sidecar, rawLog, sessionFile, folded, firstLineSessionFile(rawLog) !== sessionFile);
344
+ }
345
+ try {
346
+ await mkdir(sessionClaimsDir(), { recursive: true, mode: 0o700 });
347
+ if (process.platform !== "win32") {
348
+ try { await chmod(sessionClaimsDir(), 0o700); } catch (error) { if (errCode(error) !== "ENOENT") console.error("Failed to secure anchor registry directory:", error); }
349
+ try { await chmod(sidecar, 0o600); } catch (error) { if (errCode(error) !== "ENOENT") console.error("Failed to secure anchor registry sidecar:", error); }
350
+ }
351
+ appendEvent({ kind: "session", sessionFile } satisfies RegistryEvent);
352
+ } catch (error) {
353
+ console.error("Failed to initialize anchor registry sidecar:", error);
354
+ }
355
+ }
356
+
357
+ async function ensureRegistryForKey(key: string, sessionFile: string | undefined): Promise<void> {
358
+ currentKey = key;
359
+ if (registries.has(key)) return;
360
+ const pending = pendingInits.get(key);
361
+ if (pending) {
362
+ await pending;
363
+ return;
364
+ }
365
+ const token: object = {};
366
+ loadTokens.set(key, token);
367
+ const promise = (async () => {
368
+ if (sessionFile === undefined) {
369
+ registries.set(key, newSessionState(key));
370
+ return;
371
+ }
372
+ sessionFileByKey.set(key, sessionFile);
373
+ await loadRegistryState(key, sessionFile, token);
374
+ })();
375
+ pendingInits.set(key, promise);
376
+ try {
377
+ await promise;
378
+ } finally {
379
+ pendingInits.delete(key);
380
+ }
381
+ }
382
+
383
+ export async function initRegistry(sessionFile: string | undefined): Promise<string> {
384
+ if (sessionFile === undefined) {
385
+ const key = `__ephemeral__-${Date.now()}-${Math.random().toString(36).slice(2)}`;
386
+ currentKey = key;
387
+ registries.set(key, newSessionState(key));
388
+ return key;
389
+ }
390
+ const key = sidecarKeyFor(sessionFile);
391
+ await ensureRegistryForKey(key, sessionFile);
392
+ return key;
393
+ }
394
+
395
+ export function sessionKeyFor(ctx: AnchorSessionContext | undefined): string | undefined {
396
+ const sessionFile = sessionFileFor(ctx);
397
+ if (sessionFile !== undefined) return sidecarKeyFor(sessionFile);
398
+ const sessionId = ctx?.sessionManager?.getSessionId?.();
399
+ if (typeof sessionId === "string" && sessionId.length > 0) return `ephemeral:${sessionId}`;
400
+ return undefined;
401
+ }
402
+
403
+ function sessionFileFor(ctx: AnchorSessionContext | undefined): string | undefined {
404
+ const sessionFile = ctx?.sessionManager?.getSessionFile?.();
405
+ return typeof sessionFile === "string" && sessionFile.length > 0 ? sessionFile : undefined;
406
+ }
407
+
408
+ export async function withAnchorSession<T>(ctx: AnchorSessionContext | undefined, fn: () => Promise<T> | T): Promise<T> {
409
+ const key = sessionKeyFor(ctx);
410
+ if (key === undefined) return fn();
411
+ const sessionFile = sessionFileFor(ctx);
412
+ return sessionScope.run(key, async () => {
413
+ await ensureRegistryForKey(key, sessionFile);
414
+ return fn();
415
+ });
416
+ }
417
+
418
+ function activeKey(): string | undefined {
419
+ return sessionScope.getStore() ?? currentKey;
420
+ }
421
+
422
+ function current(): SessionState | undefined {
423
+ const key = activeKey();
424
+ if (!key) return undefined;
425
+ return registries.get(key);
426
+ }
427
+
428
+ function sidecarNeedsSessionRecord(sidecar: string): boolean {
429
+ try {
430
+ return statSync(sidecar).size === 0;
431
+ } catch {
432
+ return true;
433
+ }
434
+ }
435
+
436
+ function ensureSidecarSessionRecord(key: string, sidecar: string): void {
437
+ const sessionFile = sessionFileByKey.get(key);
438
+ if (sessionFile === undefined || !sidecarNeedsSessionRecord(sidecar)) return;
439
+ appendEvent({ kind: "session", sessionFile } satisfies RegistryEvent);
440
+ }
441
+
442
+ function appendEvent(event: RegistryEvent): void {
443
+ const key = activeKey();
444
+ if (!key) return;
445
+ const sidecar = sidecarByKey.get(key);
446
+ if (!sidecar) return;
447
+ try {
448
+ if (event.kind !== "session") ensureSidecarSessionRecord(key, sidecar);
449
+ appendFileSync(sidecar, JSON.stringify(event) + "\n", "utf-8");
450
+ if (process.platform !== "win32") {
451
+ try { chmodSync(sidecar, 0o600); } catch (error) { if (errCode(error) !== "ENOENT") console.error("Failed to secure anchor registry sidecar:", error); }
452
+ }
453
+ } catch (error) {
454
+ console.error("Failed to append registry event:", error);
455
+ }
456
+ }
457
+
458
+ function fingerprintIndex(state: SessionState, path: string): Map<string, string[]> {
459
+ const index = new Map<string, string[]>();
460
+ for (const [anchor, entry] of state.owned) {
461
+ if (entry.path !== path) continue;
462
+ const list = index.get(entry.checksum) ?? [];
463
+ list.push(anchor);
464
+ index.set(entry.checksum, list);
465
+ }
466
+ return index;
467
+ }
468
+
469
+ export const MINT_PROBE_LIMIT = 8192;
470
+
471
+ export function mintAnchor(state: SessionState): string {
472
+ for (let probe = 0; probe < MINT_PROBE_LIMIT; probe++) {
473
+ state.probe = (state.probe + HASH_PROBE_STRIDE) % ANCHOR_COUNT;
474
+ const candidate = anchorAt(state.probe);
475
+ if (!state.owned.has(candidate) && !state.everMinted.has(candidate)) {
476
+ return candidate;
477
+ }
478
+ }
479
+ for (let step = 1; step <= ANCHOR_COUNT; step++) {
480
+ const candidate = anchorAt((state.probe + step) % ANCHOR_COUNT);
481
+ if (!state.owned.has(candidate)) {
482
+ for (const served of state.served.values()) served.delete(candidate);
483
+ return candidate;
484
+ }
485
+ }
486
+ throw new Error(
487
+ `${ANCHOR_POOL_EXHAUSTED_PREFIX}; use write for very large files.`,
488
+ );
489
+ }
490
+
491
+ export function allocateAnchor(path: string, checksum: string): string {
492
+ const state = current();
493
+ if (!state) {
494
+ throw new Error("[E_REGISTRY] The anchor registry is not initialized; call initRegistry on session_start first.");
495
+ }
496
+ const anchor = mintAnchor(state);
497
+ state.everMinted.add(anchor);
498
+ state.owned.set(anchor, { path, checksum });
499
+ appendEvent({ kind: "allocate", path, rows: [[anchor, checksum]] });
500
+ return anchor;
501
+ }
502
+
503
+
504
+
505
+ export function freeAnchors(path: string, anchors?: string[]): void {
506
+ const state = current();
507
+ if (!state) return;
508
+ const freed: string[] = [];
509
+ if (anchors) {
510
+ for (const anchor of anchors) {
511
+ if (state.owned.has(anchor)) {
512
+ freed.push(anchor);
513
+ state.owned.delete(anchor);
514
+ state.served.get(path)?.delete(anchor);
515
+ }
516
+ }
517
+ } else {
518
+ for (const [anchor, entry] of [...state.owned]) {
519
+ if (entry.path === path) {
520
+ freed.push(anchor);
521
+ state.owned.delete(anchor);
522
+ }
523
+ }
524
+ state.served.delete(path);
525
+ }
526
+ if (freed.length > 0) {
527
+ appendEvent({ kind: "free", path, anchors: anchors ?? undefined });
528
+ }
529
+ }
530
+
531
+ export function clearRegistry(): void {
532
+ const state = current();
533
+ if (!state) return;
534
+ state.owned.clear();
535
+ state.served.clear();
536
+ state.allocatedChecksum.clear();
537
+ appendEvent({ kind: "clear" });
538
+ }
539
+
540
+ export function servedForPath(path: string): Map<string, string> | undefined {
541
+ return current()?.served.get(path);
542
+ }
543
+
544
+ export function markServed(
545
+ path: string,
546
+ entries: Array<[string, string]>,
547
+ scope?: ReadonlySet<string>,
548
+ ): void {
549
+ const state = current();
550
+ if (!state) return;
551
+ if (!state.served.has(path) && entries.length === 0 && !scope) return;
552
+ let served = state.served.get(path);
553
+ if (!served) {
554
+ served = new Map();
555
+ state.served.set(path, served);
556
+ }
557
+ if (scope) {
558
+ for (const anchor of [...served.keys()]) {
559
+ if (!scope.has(anchor)) served.delete(anchor);
560
+ }
561
+ }
562
+ for (const [anchor, checksum] of entries) {
563
+ served.set(anchor, checksum);
564
+ }
565
+ }
566
+
567
+ export function ownerOf(anchor: string): OwnedAnchor | undefined {
568
+ return current()?.owned.get(anchor);
569
+ }
570
+
571
+ export function ownersForPath(path: string): Map<string, string> {
572
+ const claims = new Map<string, string>();
573
+ const state = current();
574
+ if (!state) return claims;
575
+ for (const [anchor, entry] of state.owned) {
576
+ if (entry.path === path) claims.set(anchor, entry.checksum);
577
+ }
578
+ return claims;
579
+ }
580
+
581
+ export function ensureRegistry(): void {
582
+ const key = activeKey();
583
+ if (key && registries.has(key)) return;
584
+ initRegistry(undefined).catch(() => undefined);
585
+ }
586
+
587
+ export function shadowStateFrom(state: SessionState): SessionState {
588
+ return {
589
+ owned: new ShadowOwnedMap(state.owned),
590
+ served: new Map(),
591
+ everMinted: new ShadowMintedSet(state.everMinted),
592
+ probe: state.probe,
593
+ allocatedChecksum: state.allocatedChecksum,
594
+ };
595
+ }
596
+
597
+ export interface Aligned {
598
+ anchors: string[];
599
+ freed: string[];
600
+ minted: string[];
601
+ }
602
+
603
+ interface MintedAt {
604
+ index: number;
605
+ anchor: string;
606
+ checksum: string;
607
+ }
608
+
609
+ type ArrayPart = { count: number; added?: boolean; removed?: boolean };
610
+
611
+ function computeParts(
612
+ prevChecksums: string[] | undefined,
613
+ newChecksums: string[],
614
+ ): ArrayPart[] {
615
+ if (!prevChecksums) {
616
+ return [{ count: newChecksums.length, added: true }];
617
+ }
618
+ const min = Math.min(prevChecksums.length, newChecksums.length);
619
+ let prefix = 0;
620
+ while (prefix < min && prevChecksums[prefix] === newChecksums[prefix]) prefix++;
621
+ let suffix = 0;
622
+ while (
623
+ suffix < min - prefix &&
624
+ prevChecksums[prevChecksums.length - 1 - suffix] === newChecksums[newChecksums.length - 1 - suffix]
625
+ ) {
626
+ suffix++;
627
+ }
628
+ if (prefix + suffix >= min && prevChecksums.length === newChecksums.length) {
629
+ return [{ count: newChecksums.length }];
630
+ }
631
+ const prevMid = prevChecksums.slice(prefix, prevChecksums.length - suffix);
632
+ const newMid = newChecksums.slice(prefix, newChecksums.length - suffix);
633
+ if (prevMid.length === 0) {
634
+ return [{ count: prefix }, { count: newMid.length, added: true }, { count: suffix }];
635
+ }
636
+ if (newMid.length === 0) {
637
+ return [{ count: prefix }, { count: prevMid.length, removed: true }, { count: suffix }];
638
+ }
639
+ if (prevMid.length * newMid.length > 4_000_000) {
640
+ return [{ count: prefix }, { count: prevMid.length, removed: true }, { count: newMid.length, added: true }, { count: suffix }];
641
+ }
642
+ const parts: ArrayPart[] = [];
643
+ if (prefix > 0) parts.push({ count: prefix });
644
+ for (const part of Diff.diffArrays(prevMid, newMid) as unknown as Array<{ count?: number; added?: boolean; removed?: boolean }>) {
645
+ parts.push({ count: part.count ?? 0, added: part.added, removed: part.removed });
646
+ }
647
+ if (suffix > 0) parts.push({ count: suffix });
648
+ return parts;
649
+ }
650
+
651
+ export function alignOwnershipWithSpans(
652
+ path: string,
653
+ prevAnchors: string[],
654
+ prevChecksums: string[],
655
+ newChecksums: string[],
656
+ spans: { start: number; end: number; replacementCount: number }[],
657
+ options?: { shadow?: boolean },
658
+ ): Aligned {
659
+ const state = options?.shadow ? shadowStateFrom(current()!) : current()!;
660
+ const freed: { anchor: string; checksum: string }[] = [];
661
+ const minted: MintedAt[] = [];
662
+ const reused = new Set<string>();
663
+ const log = (event: RegistryEvent): void => {
664
+ if (!options?.shadow) appendEvent(event);
665
+ };
666
+
667
+ const sorted = [...spans].sort((a, b) => a.start - b.start);
668
+ const anchors = [...prevAnchors];
669
+ let offset = 0;
670
+ for (const span of sorted) {
671
+ const prevStart = span.start;
672
+ const start = span.start + offset;
673
+ const end = span.end + offset;
674
+ const spanLength = end - start + 1;
675
+ for (let i = start; i <= end; i++) {
676
+ const anchor = anchors[i]!;
677
+ if (state.owned.has(anchor)) {
678
+ state.owned.delete(anchor);
679
+ const checksum = prevChecksums[i - offset] ?? "";
680
+ freed.push({ anchor, checksum });
681
+ }
682
+ }
683
+ const replacement: (string | undefined)[] = new Array(span.replacementCount);
684
+ for (let k = 0; k < span.replacementCount; k++) {
685
+ const positional = k < spanLength ? prevAnchors[prevStart + k] : undefined;
686
+ if (
687
+ positional !== undefined &&
688
+ prevChecksums[prevStart + k] === newChecksums[start + k] &&
689
+ (!state.owned.has(positional) || state.owned.get(positional)!.path === path)
690
+ ) {
691
+ replacement[k] = positional;
692
+ reused.add(positional);
693
+ }
694
+ }
695
+ for (let k = 0; k < span.replacementCount; k++) {
696
+ if (replacement[k] !== undefined) continue;
697
+ const anchor = mintAnchor(state);
698
+ const checksum = newChecksums[start + k]!;
699
+ minted.push({ index: start + k, anchor, checksum });
700
+ state.owned.set(anchor, { path, checksum });
701
+ replacement[k] = anchor;
702
+ }
703
+ const settled = replacement as string[];
704
+ for (let k = 0; k < span.replacementCount; k++) {
705
+ state.everMinted.add(settled[k]!);
706
+ state.owned.set(settled[k]!, { path, checksum: newChecksums[start + k]! });
707
+ }
708
+ anchors.splice(start, spanLength, ...settled);
709
+ offset += span.replacementCount - spanLength;
710
+ }
711
+ const rows: [string, string][] = minted.map((m) => [m.anchor, m.checksum]);
712
+ if (rows.length > 0) log({ kind: "allocate", path, rows });
713
+ const retained = freed.filter((candidate) => !reused.has(candidate.anchor));
714
+ if (retained.length > 0) log({ kind: "free", path, anchors: retained.map((f) => f.anchor) });
715
+ return { anchors, freed: retained.map((f) => f.anchor), minted: minted.map((m) => m.anchor) };
716
+ }
717
+
718
+ export function alignOwnership(
719
+ path: string,
720
+ prevAnchors: string[] | undefined,
721
+ prevChecksums: string[] | undefined,
722
+ newChecksums: string[],
723
+ options?: { shadow?: boolean },
724
+ ): Aligned {
725
+ const state = options?.shadow ? shadowStateFrom(current()!) : current()!;
726
+ const anchors: string[] = new Array(newChecksums.length);
727
+ const freed: { anchor: string; checksum: string }[] = [];
728
+ const minted: MintedAt[] = [];
729
+ const adopted: string[] = [];
730
+ const log = (event: RegistryEvent): void => {
731
+ if (!options?.shadow) appendEvent(event);
732
+ };
733
+ if (prevAnchors) {
734
+ for (const anchor of prevAnchors) state.everMinted.add(anchor);
735
+ }
736
+
737
+ const parts: ArrayPart[] = computeParts(prevChecksums, newChecksums);
738
+ let prevIdx = 0;
739
+ let newIdx = 0;
740
+ for (const part of parts) {
741
+ const count = part.count;
742
+ if (part.added) {
743
+ for (let k = 0; k < count; k++) {
744
+ const checksum = newChecksums[newIdx + k]!;
745
+ const anchor = mintAnchor(state);
746
+ state.everMinted.add(anchor);
747
+ state.owned.set(anchor, { path, checksum });
748
+ minted.push({ index: newIdx + k, anchor, checksum });
749
+ anchors[newIdx + k] = anchor;
750
+ }
751
+ newIdx += count;
752
+ } else if (part.removed) {
753
+ for (let k = 0; k < count; k++) {
754
+ const anchor = prevAnchors![prevIdx + k]!;
755
+ const entry = state.owned.get(anchor);
756
+ if (entry && entry.path === path) {
757
+ state.owned.delete(anchor);
758
+ freed.push({ anchor, checksum: prevChecksums![prevIdx + k]! });
759
+ }
760
+ }
761
+ prevIdx += count;
762
+ } else {
763
+ for (let k = 0; k < count; k++) {
764
+ const anchor = prevAnchors![prevIdx + k]!;
765
+ const entry = state.owned.get(anchor);
766
+ const checksum = newChecksums[newIdx + k]!;
767
+ if (entry && entry.path !== path) {
768
+ const fresh = mintAnchor(state);
769
+ state.owned.set(fresh, { path, checksum });
770
+ anchors[newIdx + k] = fresh;
771
+ } else {
772
+ if (!entry) adopted.push(anchor);
773
+ state.owned.set(anchor, { path, checksum });
774
+ anchors[newIdx + k] = anchor;
775
+ }
776
+ }
777
+ newIdx += count;
778
+ prevIdx += count;
779
+ }
780
+ }
781
+
782
+ const rows: [string, string][] = [];
783
+ for (let i = 0; i < anchors.length; i++) {
784
+ rows.push([anchors[i]!, newChecksums[i]!]);
785
+ }
786
+ const logged = new Set<string>([...minted.map((m) => m.anchor), ...adopted]);
787
+ if (logged.size > 0) log({ kind: "allocate", path, rows: rows.filter(([anchor]) => logged.has(anchor)) });
788
+ if (freed.length > 0) log({ kind: "free", path, anchors: freed.map((f) => f.anchor) });
789
+ return { anchors, freed: freed.map((f) => f.anchor), minted: minted.map((m) => m.anchor) };
790
+ }
791
+
792
+ function snapshotMatchesAllocation(state: SessionState | undefined, path: string, checksum: string): boolean {
793
+ const allocated = state?.allocatedChecksum.get(path);
794
+ return allocated === undefined || allocated === checksum;
795
+ }
796
+
797
+ export async function allocateFileAnchors(
798
+ store: HashStore,
799
+ path: string,
800
+ content: string,
801
+ options?: {
802
+ persist?: boolean;
803
+ shadow?: boolean;
804
+ previous?: { content: string; hashes: string[]; spans?: { start: number; end: number; replacementCount: number }[] };
805
+ },
806
+ ): Promise<string[]> {
807
+ ensureRegistry();
808
+ const registry = current();
809
+ const shadow = options?.shadow === true;
810
+ const lines = splitLines(content);
811
+ const checksums = lines.map(lineChecksum);
812
+ if (options?.previous?.spans) {
813
+ const prevChecksums = splitLines(options.previous.content).map(lineChecksum);
814
+ const aligned = alignOwnershipWithSpans(path, options.previous.hashes, prevChecksums, checksums, options.previous.spans, { shadow });
815
+ if (!shadow && registry) registry.allocatedChecksum.set(path, contentChecksum(content));
816
+ if (!shadow && options.persist !== false) {
817
+ persistSnapshot(store, path, content, aligned.anchors, checksums);
818
+ }
819
+ return aligned.anchors;
820
+ }
821
+ let prevAnchors: string[] | undefined;
822
+ let prevChecksums: string[] | undefined;
823
+ if (options?.previous) {
824
+ prevAnchors = options.previous.hashes;
825
+ prevChecksums = splitLines(options.previous.content).map(lineChecksum);
826
+ } else {
827
+ const previousState = getAllocatedState(store, path, !shadow);
828
+ if (previousState && snapshotMatchesAllocation(registry, path, previousState.contentChecksum)) {
829
+ prevAnchors = previousState.anchors;
830
+ prevChecksums = previousState.checksums;
831
+ if (!prevChecksums && previousState.contentChecksum === contentChecksum(content)) {
832
+ prevChecksums = checksums;
833
+ }
834
+ }
835
+ }
836
+ const aligned: Aligned = prevAnchors
837
+ ? alignOwnership(path, prevAnchors, prevChecksums, checksums, { shadow })
838
+ : (() => {
839
+ const state = shadow ? shadowStateFrom(current()!) : current()!;
840
+ const reuseIndex = fingerprintIndex(state, path);
841
+ const reuseTaken = new Map<string, number>();
842
+ const anchors: string[] = checksums.map((checksum) => {
843
+ const candidates = reuseIndex.get(checksum) ?? [];
844
+ const taken = reuseTaken.get(checksum) ?? 0;
845
+ reuseTaken.set(checksum, taken + 1);
846
+ const anchor = taken < candidates.length ? candidates[taken]! : mintAnchor(state);
847
+ state.everMinted.add(anchor);
848
+ state.owned.set(anchor, { path, checksum });
849
+ return anchor;
850
+ });
851
+ if (!shadow) {
852
+ appendEvent({ kind: "allocate", path, rows: anchors.map((a, i) => [a, checksums[i]!]) });
853
+ }
854
+ return { anchors, freed: [], minted: anchors };
855
+ })();
856
+ if (!shadow && registry) registry.allocatedChecksum.set(path, contentChecksum(content));
857
+ if (!shadow && options?.persist !== false) {
858
+ persistSnapshot(store, path, content, aligned.anchors, checksums);
859
+ }
860
+ return aligned.anchors;
861
+ }
862
+
863
+ export function adoptAnchors(path: string, entries: Map<string, string>): void {
864
+ ensureRegistry();
865
+ const state = current()!;
866
+ let served = state.served.get(path);
867
+ if (!served) {
868
+ served = new Map();
869
+ state.served.set(path, served);
870
+ }
871
+ const adopted: Array<[string, string]> = [];
872
+ for (const [anchor, checksum] of entries) {
873
+ const existing = state.owned.get(anchor);
874
+ if (existing && existing.path !== path) continue;
875
+ state.owned.set(anchor, { path, checksum });
876
+ served.set(anchor, checksum);
877
+ adopted.push([anchor, checksum]);
878
+ }
879
+ if (adopted.length > 0) {
880
+ appendEvent({ kind: "allocate", path, rows: adopted });
881
+ }
882
+ }
883
+
884
+ export function resetRegistryForTests(): void {
885
+ currentKey = undefined;
886
+ sidecarByKey.clear();
887
+ sessionFileByKey.clear();
888
+ pendingInits.clear();
889
+ loadTokens.clear();
890
+ registries.clear();
891
+ }
892
+
893
+ async function readSidecarWindow(sidecar: string): Promise<{ text: string; filled: boolean }> {
894
+ const handle = await open(sidecar, "r");
895
+ const buffer = Buffer.alloc(SIDECAR_HEADER_BYTES);
896
+ try {
897
+ let readBytes = 0;
898
+ while (readBytes < buffer.length) {
899
+ const { bytesRead } = await handle.read(buffer, readBytes, Math.min(SIDECAR_HEADER_CHUNK, buffer.length - readBytes), readBytes);
900
+ if (bytesRead === 0) break;
901
+ readBytes += bytesRead;
902
+ }
903
+ return { text: buffer.subarray(0, readBytes).toString("utf-8"), filled: readBytes === buffer.length };
904
+ } finally {
905
+ await handle.close();
906
+ }
907
+ }
908
+
909
+ export async function readSidecarHeader(sidecar: string): Promise<string> {
910
+ const { text, filled } = await readSidecarWindow(sidecar);
911
+ const newline = text.indexOf("\n");
912
+ if (newline >= 0) return text.slice(0, newline);
913
+ return filled ? "" : text;
914
+ }
915
+
916
+ export async function readSidecarSessionFile(sidecar: string): Promise<string | undefined> {
917
+ const { text } = await readSidecarWindow(sidecar);
918
+ const lastNewline = text.lastIndexOf("\n");
919
+ const complete = lastNewline >= 0 ? text.slice(0, lastNewline).split("\n") : [];
920
+ for (const line of complete) {
921
+ const sessionFile = parseSessionFileLine(line);
922
+ if (sessionFile !== undefined) return sessionFile;
923
+ }
924
+ return parseSessionFileLine(lastNewline >= 0 ? text.slice(lastNewline + 1) : text);
925
+ }
926
+
927
+ export function releaseRegistrySession(key: string): void {
928
+ loadTokens.delete(key);
929
+ if (currentKey === key) currentKey = undefined;
930
+ pendingInits.delete(key);
931
+ sidecarByKey.delete(key);
932
+ sessionFileByKey.delete(key);
933
+ registries.delete(key);
934
+ }
935
+
936
+ function isClaimedSidecar(sidecar: string): boolean {
937
+ for (const claimed of sidecarByKey.values()) {
938
+ if (claimed === sidecar) return true;
939
+ }
940
+ return false;
941
+ }
942
+
943
+ export async function gcRegistrySidecars(): Promise<void> {
944
+ let names: string[];
945
+ try {
946
+ names = await readdir(sessionClaimsDir());
947
+ } catch (error) {
948
+ if (errCode(error) !== "ENOENT") console.error("Failed to list registry sidecars:", error);
949
+ return;
950
+ }
951
+ for (const name of names) {
952
+ if (name.includes(`${SIDECAR_SUFFIX}.compact-`)) {
953
+ const tmpPath = join(sessionClaimsDir(), name);
954
+ try {
955
+ const tmpStat = await stat(tmpPath);
956
+ if (Date.now() - tmpStat.mtimeMs > 60 * 60 * 1000) await rm(tmpPath, { force: true });
957
+ } catch (error) {
958
+ if (errCode(error) !== "ENOENT") console.error("Failed to inspect registry sidecar:", error);
959
+ }
960
+ continue;
961
+ }
962
+ if (!name.endsWith(SIDECAR_SUFFIX)) continue;
963
+ const sidecar = join(sessionClaimsDir(), name);
964
+ if (isClaimedSidecar(sidecar)) continue;
965
+ try {
966
+ const sessionFile = await readSidecarSessionFile(sidecar);
967
+ if (sessionFile === undefined) continue;
968
+ await stat(sessionFile);
969
+ } catch (error) {
970
+ if (errCode(error) === "ENOENT") {
971
+ await rm(sidecar, { force: true });
972
+ } else {
973
+ console.error("Failed to inspect registry sidecar:", error);
974
+ }
975
+ }
976
+ }
977
+ }