@staix/agent-mem 0.41.0 → 0.43.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/.claude-plugin/plugin.json +1 -1
- package/README.md +2 -2
- package/package.json +4 -3
- package/src/cli.ts +161 -27
- package/src/commands-table.ts +17 -6
- package/src/index.ts +4 -1
- package/src/ingest-hosts.ts +440 -0
- package/src/mcp-bounds.ts +3 -0
- package/src/mcp-memory.ts +64 -10
- package/src/mcp.ts +36 -121
- package/src/memory/candidates.ts +33 -5
- package/src/memory/capture.ts +23 -0
- package/src/memory/commands.ts +6 -3
- package/src/memory/config.ts +26 -0
- package/src/memory/consolidation-clusters.ts +13 -2
- package/src/memory/doctor-text.ts +4 -1
- package/src/memory/doctor.ts +8 -5
- package/src/memory/formats-raise.ts +37 -16
- package/src/memory/formats.ts +37 -10
- package/src/memory/generation-sync.ts +1 -1
- package/src/memory/home-binding-fence.ts +2 -1
- package/src/memory/live-state.ts +85 -0
- package/src/memory/migrate.ts +3 -3
- package/src/memory/mutation.ts +6 -3
- package/src/memory/profile-marker-cache.ts +45 -0
- package/src/memory/public-prune-activation.ts +1 -1
- package/src/memory/public-prune-advance.ts +1 -1
- package/src/memory/public-prune-inputs.ts +1 -1
- package/src/memory/purge-intent.ts +27 -0
- package/src/memory/purge-matcher.ts +101 -0
- package/src/memory/purge-plan.ts +90 -0
- package/src/memory/read-curated-entries.ts +244 -0
- package/src/memory/reader-lease.ts +3 -0
- package/src/memory/search-fts.ts +55 -27
- package/src/memory/shard-migration.ts +3 -3
- package/src/memory/shard-sync.ts +3 -3
- package/src/memory/shard.ts +17 -14
- package/src/memory/store.ts +9 -72
- package/src/memory/sync-cadence.ts +8 -4
- package/src/memory/sync-placement-activation-locks.ts +39 -22
- package/src/memory/sync-placement-active.ts +69 -19
- package/src/memory/sync-placement-advertisement.ts +25 -3
- package/src/memory/sync-placement-checkpoint-person.ts +8 -14
- package/src/memory/sync-placement-effective-writers.ts +4 -3
- package/src/memory/sync-placement-guard.ts +31 -11
- package/src/memory/sync-placement-inventory.ts +20 -4
- package/src/memory/sync-placement-journal.ts +1 -1
- package/src/memory/sync-placement-realm-admission.ts +16 -11
- package/src/memory/sync-placement-refusal.ts +7 -0
- package/src/memory/sync-placement-remote-admission.ts +31 -13
- package/src/memory/sync-placement-remote-refusal.ts +1 -1
- package/src/memory/sync-placement-remote-stage.ts +1 -1
- package/src/memory/sync-placement-transport.ts +36 -15
- package/src/memory/sync-placement-writer-listing.ts +38 -13
- package/src/memory/sync-placement-writer-renewal.ts +5 -7
- package/src/memory/sync.ts +3 -2
- package/src/memory/topic.ts +14 -0
- package/src/setup-console.ts +49 -23
- package/src/setup-drift.ts +35 -4
- package/src/setup-owned.ts +9 -1
- package/src/setup-writer-roots.ts +1 -1
- package/src/setup.ts +102 -16
- package/src/sync-placement-writer-context.ts +1 -1
|
@@ -14,9 +14,11 @@ const PLAIN = /^(\d+)\.(\d+)\.(\d+)$/;
|
|
|
14
14
|
const MAX_WRITERS = 256, PACKAGE_BYTES = 64 * 1024, MAX_ANCESTORS = 12;
|
|
15
15
|
export type FormatRaiseSurface = typeof FORMAT_SURFACES[number] | "home";
|
|
16
16
|
export interface FormatWriter { source: "setup" | "sync-placement" | "running" | "library-host" | "self"; root: string; version: string | null; pid?: number; host?: string }
|
|
17
|
-
|
|
17
|
+
/** `processArgs`: the process table's argument lines, when it could be read; without them no root is retired as absent. */
|
|
18
|
+
export interface FormatWriterInventory { writers: FormatWriter[]; incomplete: string[]; processArgs?: readonly string[] }
|
|
18
19
|
export interface FormatRaisePlan {
|
|
19
|
-
|
|
20
|
+
/** #660: `absent` lists setup and placement inventory roots removed from disk that no live process runs from; they cannot write here and are not counted. */
|
|
21
|
+
home: string; file: string; record: FormatFloor; writers: FormatWriter[]; below: FormatWriter[]; absent: FormatWriter[]; incomplete: string[];
|
|
20
22
|
existing: FormatFloor[]; alreadyAtLeast: boolean; ready: boolean;
|
|
21
23
|
}
|
|
22
24
|
|
|
@@ -27,6 +29,14 @@ export function versionBelow(version: string, floor: string): boolean {
|
|
|
27
29
|
return false;
|
|
28
30
|
}
|
|
29
31
|
|
|
32
|
+
/**
|
|
33
|
+
* #634/#660: an install whose root no longer exists (ENOENT or ENOTDIR on the root itself). An existing root with a missing or
|
|
34
|
+
* unreadable package.json is not absent: it can still run, so a floor check keeps refusing it.
|
|
35
|
+
*/
|
|
36
|
+
export function installAbsent(root: string): boolean {
|
|
37
|
+
try { lstatSync(root); return false; } catch (error) { const code = (error as NodeJS.ErrnoException).code; return code === "ENOENT" || code === "ENOTDIR"; }
|
|
38
|
+
}
|
|
39
|
+
|
|
30
40
|
/** The version of an amem install root, or null when it is not a readable `@staix/agent-mem` package with a plain release version. */
|
|
31
41
|
export function installVersion(root: string): string | null {
|
|
32
42
|
let fd: number | undefined;
|
|
@@ -45,18 +55,21 @@ export function installVersion(root: string): string | null {
|
|
|
45
55
|
* it as a library (ahub, vmem), found as `node_modules/@staix/agent-mem` in an ancestor of a script path on its command line. Bounded.
|
|
46
56
|
* `embedded(dir)` answers whether `dir/node_modules/@staix/agent-mem` exists; it defaults to the filesystem.
|
|
47
57
|
*/
|
|
48
|
-
|
|
58
|
+
const defaultEmbedded = (dir: string) => existsSync(join(dir, "node_modules", "@staix", "agent-mem", "package.json"));
|
|
59
|
+
/** #660: the `node_modules/@staix/agent-mem` in the nearest of a script's ancestors (at most MAX_ANCESTORS), or null. Bounded, no crawl. */
|
|
60
|
+
export function embeddedAmemRoot(script: string, embedded: (dir: string) => boolean = defaultEmbedded, memo = new Map<string, string | null>()): string | null {
|
|
61
|
+
let dir = dirname(script);
|
|
62
|
+
for (let depth = 0; depth < MAX_ANCESTORS && dir !== dirname(dir); depth++, dir = dirname(dir)) {
|
|
63
|
+
if (memo.has(dir)) return memo.get(dir)!;
|
|
64
|
+
let found: string | null = null;
|
|
65
|
+
try { if (embedded(dir)) found = join(dir, "node_modules", "@staix", "agent-mem"); } catch { /* unreadable: look further up */ }
|
|
66
|
+
if (found) { memo.set(dir, found); return found; }
|
|
67
|
+
}
|
|
68
|
+
return null;
|
|
69
|
+
}
|
|
70
|
+
export function runningAmemRoots(table: () => string, embedded: (dir: string) => boolean = defaultEmbedded): { pid: number; root: string; host?: string }[] {
|
|
49
71
|
const out: { pid: number; root: string; host?: string }[] = [], memo = new Map<string, string | null>();
|
|
50
|
-
const library = (script: string)
|
|
51
|
-
let dir = dirname(script);
|
|
52
|
-
for (let depth = 0; depth < MAX_ANCESTORS && dir !== dirname(dir); depth++, dir = dirname(dir)) {
|
|
53
|
-
if (memo.has(dir)) return memo.get(dir)!;
|
|
54
|
-
let found: string | null = null;
|
|
55
|
-
try { if (embedded(dir)) found = join(dir, "node_modules", "@staix", "agent-mem"); } catch { /* unreadable: look further up */ }
|
|
56
|
-
if (found) { memo.set(dir, found); return found; }
|
|
57
|
-
}
|
|
58
|
-
return null;
|
|
59
|
-
};
|
|
72
|
+
const library = (script: string) => embeddedAmemRoot(script, embedded, memo);
|
|
60
73
|
for (const line of table().split("\n")) {
|
|
61
74
|
const match = /^\s*(\d+)\s+(.*)$/.exec(line); if (!match) continue;
|
|
62
75
|
const pid = Number(match[1]); if (pid === process.pid) continue;
|
|
@@ -78,9 +91,17 @@ export function planFormatRaise(home: string, surface: string, minReader: string
|
|
|
78
91
|
if (!PLAIN.test(minReader)) throw new Error("minReader must be a plain release version such as 0.27.0");
|
|
79
92
|
const base = realPath(home), existing = readFormatFloors(base) ?? [];
|
|
80
93
|
const record: FormatFloor = { surface, minReader, since: now().toISOString().slice(0, 10) };
|
|
81
|
-
const
|
|
94
|
+
const live = new Set(inventory.writers.filter(writer => writer.source === "running" || writer.source === "library-host" || writer.source === "self").map(writer => writer.root));
|
|
95
|
+
// A deleted bundle can still be loaded by a surviving host: an argument under the root, or a host script whose bounded
|
|
96
|
+
// ancestor layout (the one discovery uses) places this root as its embedded bundle, keeps it counted.
|
|
97
|
+
const scripts = inventory.processArgs?.flatMap(line => line.split(/\s+/).filter(token => token.startsWith("/"))) ?? [];
|
|
98
|
+
const referenced = (root: string) => inventory.processArgs!.some(line => line.includes(`${root}/`))
|
|
99
|
+
|| scripts.some(script => embeddedAmemRoot(script, dir => join(dir, "node_modules", "@staix", "agent-mem") === root) === root);
|
|
100
|
+
const absent = inventory.processArgs === undefined ? [] : inventory.writers.filter(writer => (writer.source === "setup" || writer.source === "sync-placement") && writer.version === null
|
|
101
|
+
&& !live.has(writer.root) && installAbsent(writer.root) && !referenced(writer.root));
|
|
102
|
+
const below = inventory.writers.filter(writer => !absent.includes(writer) && (writer.version === null || versionBelow(writer.version, minReader)));
|
|
82
103
|
const alreadyAtLeast = existing.some(floor => floor.surface === surface && PLAIN.test(floor.minReader) && !versionBelow(floor.minReader, minReader));
|
|
83
|
-
return { home: base, file: join(base, FORMATS_FILE), record, writers: inventory.writers, below, incomplete: inventory.incomplete, existing, alreadyAtLeast,
|
|
104
|
+
return { home: base, file: join(base, FORMATS_FILE), record, writers: inventory.writers, below, absent, incomplete: inventory.incomplete, existing, alreadyAtLeast,
|
|
84
105
|
ready: !below.length && !inventory.incomplete.length && !alreadyAtLeast };
|
|
85
106
|
}
|
|
86
107
|
|
|
@@ -94,7 +115,7 @@ export function formatRaiseRefusal(plan: FormatRaisePlan): string | undefined {
|
|
|
94
115
|
/** Appends the planned record under the home's mutation fence after rechecking the floors and the inventory are unchanged. */
|
|
95
116
|
export function applyFormatRaise(plan: FormatRaisePlan, recheck: () => FormatRaisePlan): FormatFloor {
|
|
96
117
|
const refusal = formatRaiseRefusal(plan); if (refusal) throw new Error(refusal);
|
|
97
|
-
const release = acquireMutation(plan.home); if (!release) throw new Error("another memory writer holds this home; rerun when it finishes");
|
|
118
|
+
const release = acquireMutation(plan.home, plan.home); if (!release) throw new Error("another memory writer holds this home; rerun when it finishes");
|
|
98
119
|
try {
|
|
99
120
|
const fresh = recheck();
|
|
100
121
|
if (JSON.stringify(fresh.existing) !== JSON.stringify(plan.existing) || JSON.stringify(fresh.writers) !== JSON.stringify(plan.writers)) throw new Error("formats.json or the writer inventory changed since the preview; rerun the preview");
|
package/src/memory/formats.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { assertNoPendingPurge } from "./purge-intent.ts";
|
|
2
|
+
import { closeSync, constants, fstatSync, lstatSync, openSync, readFileSync, readSync, type BigIntStats } from "node:fs";
|
|
2
3
|
import { join } from "node:path";
|
|
3
4
|
|
|
4
5
|
/**
|
|
@@ -41,15 +42,34 @@ export function formatVersionBelow(reader: string, floor: string): boolean {
|
|
|
41
42
|
return false;
|
|
42
43
|
}
|
|
43
44
|
|
|
45
|
+
// #656: parsed floors by resolved file path plus dev:ino:size:mtimeNs:ctimeNs, so a fence check that runs per row does not reopen
|
|
46
|
+
// the file. A stat error or any stamp change takes the full read; only a read whose open stamp equals its pre-open stamp is kept.
|
|
47
|
+
// ponytail: same-size in-place rewrites within one stat tick are not seen (the profile-marker-cache ceiling); upgrade is a content hash.
|
|
48
|
+
const floorMemo = new Map<string, { stamp: string; floors: FormatFloor[] }>();
|
|
49
|
+
const floorStamp = (s: BigIntStats) => [s.dev, s.ino, s.size, s.mtimeNs, s.ctimeNs].map(String).join(":");
|
|
44
50
|
/** Bounded read of the floor records: undefined when there is no file; anything that is not a regular file of valid records refuses. */
|
|
45
51
|
export function readFormatFloors(home: string): FormatFloor[] | undefined {
|
|
46
|
-
const file = join(home, FORMATS_FILE)
|
|
52
|
+
const file = join(home, FORMATS_FILE);
|
|
53
|
+
let before: BigIntStats | undefined;
|
|
54
|
+
try { before = lstatSync(file, { bigint: true, throwIfNoEntry: false }); } catch { before = undefined; }
|
|
55
|
+
const cached = floorMemo.get(file);
|
|
56
|
+
if (before?.isFile() && cached && cached.stamp === floorStamp(before)) return cached.floors.map(floor => ({ ...floor }));
|
|
57
|
+
floorMemo.delete(file);
|
|
58
|
+
const read = readFormatFloorsUncached(file);
|
|
59
|
+
if (read && before?.isFile() && read.stamp === floorStamp(before)) {
|
|
60
|
+
if (floorMemo.size >= 32) floorMemo.delete(floorMemo.keys().next().value!);
|
|
61
|
+
floorMemo.set(file, { stamp: read.stamp, floors: read.floors.map(floor => ({ ...floor })) });
|
|
62
|
+
}
|
|
63
|
+
return read?.floors;
|
|
64
|
+
}
|
|
65
|
+
function readFormatFloorsUncached(file: string): { floors: FormatFloor[]; stamp: string } | undefined {
|
|
66
|
+
const unreadable = (why: string) => new FormatFloorError("format_floor_unreadable", `${file}: ${why}; nothing was read or written. Fix or restore the file (it is append-only and written by a person).`);
|
|
47
67
|
let fd: number;
|
|
48
68
|
try { fd = openSync(file, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK); }
|
|
49
69
|
catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT" || (error as NodeJS.ErrnoException).code === "ENOTDIR") return undefined; throw unreadable("not a readable regular file"); }
|
|
50
|
-
let text: string;
|
|
70
|
+
let text: string, stamp: string;
|
|
51
71
|
try {
|
|
52
|
-
const stat = fstatSync(fd);
|
|
72
|
+
const stat = fstatSync(fd); stamp = floorStamp(fstatSync(fd, { bigint: true }));
|
|
53
73
|
if (!stat.isFile() || stat.size > MAX_BYTES) throw unreadable("not a regular file of at most 64 KiB");
|
|
54
74
|
const data = Buffer.alloc(MAX_BYTES + 1); let size = 0, n: number;
|
|
55
75
|
while (size < data.length && (n = readSync(fd, data, size, data.length - size, null)) > 0) size += n;
|
|
@@ -60,11 +80,12 @@ export function readFormatFloors(home: string): FormatFloor[] | undefined {
|
|
|
60
80
|
try { value = JSON.parse(text); } catch { throw unreadable("not JSON"); }
|
|
61
81
|
if (!Array.isArray(value) || !value.every(record => record && typeof record === "object" && !Array.isArray(record)
|
|
62
82
|
&& typeof record.surface === "string" && typeof record.minReader === "string" && SEMVER.test(record.minReader) && typeof record.since === "string")) throw unreadable("not an array of { surface, minReader, since } records");
|
|
63
|
-
return value.map(({ surface, minReader, since }) => ({ surface, minReader, since }));
|
|
83
|
+
return { floors: value.map(({ surface, minReader, since }) => ({ surface, minReader, since })), stamp };
|
|
64
84
|
}
|
|
65
85
|
|
|
66
86
|
/** Refuse before touching `surface` when the home records a floor above this release. */
|
|
67
87
|
export function assertFormatFloor(home: string, surface: FormatSurface): void {
|
|
88
|
+
assertNoPendingPurge(home);
|
|
68
89
|
const floors = readFormatFloors(home);
|
|
69
90
|
if (!floors) return;
|
|
70
91
|
const reader = READER_VERSION ?? "unknown";
|
|
@@ -79,10 +100,16 @@ export function formatFloorAtLeast(home: string, surface: FormatSurface, minimum
|
|
|
79
100
|
return (readFormatFloors(home) ?? []).some(floor => (floor.surface === surface || floor.surface === "home") && !formatVersionBelow(floor.minReader, minimum));
|
|
80
101
|
}
|
|
81
102
|
|
|
82
|
-
/**
|
|
83
|
-
* The step a person takes to raise a floor: the exact record, the file it goes in, and that this package never writes that file. It is the
|
|
84
|
-
* next step a refusal names, so the writer that refuses keeps the path and the record from one place.
|
|
85
|
-
*/
|
|
103
|
+
/** The preview and explicit confirmation a person uses to append a format floor. */
|
|
86
104
|
export function floorRaiseHint(home: string, surface: FormatSurface, minReader: string): string {
|
|
87
|
-
return `
|
|
105
|
+
return `preview amem formats raise ${surface} ${minReader}, then run amem formats raise ${surface} ${minReader} --confirm to append the floor to ${join(home, FORMATS_FILE)}`;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
/** Validate the existing explicit floor before a confirmed local purge installs its intent. */
|
|
110
|
+
export function assertPurgeFormatFloors(home: string, minimum: string, sidecars: readonly ("capture" | "candidates")[] = []): void {
|
|
111
|
+
for (const surface of ["curated", "sync", ...sidecars] as const) {
|
|
112
|
+
assertFormatFloor(home, surface);
|
|
113
|
+
if (!formatFloorAtLeast(home, surface, minimum)) throw new Error(`Local purge requires a ${surface} floor of ${minimum}; ${floorRaiseHint(home, surface, minimum)}.`);
|
|
114
|
+
}
|
|
88
115
|
}
|
|
@@ -97,7 +97,7 @@ export async function syncGenerationMemory(store: MemoryStore, opts: SyncOptions
|
|
|
97
97
|
if (typeof url !== "string" || !url || url.length > 4096 || url.startsWith("-") || /[\r\n\0]/.test(url)) return result("generation sync remote is invalid");
|
|
98
98
|
if (await (opts.visibility ?? remoteVisibility)(url) !== "private") return result("generation sync requires positively verified private remote visibility");
|
|
99
99
|
if (opts.signal?.aborted) return result("stopped");
|
|
100
|
-
releaseMutation = acquireMutation(dir);
|
|
100
|
+
releaseMutation = acquireMutation(dir, store.profile.home);
|
|
101
101
|
if (!releaseMutation) return result("another generation mutation is running");
|
|
102
102
|
releaseCurated = store.beginCuratedCacheUpdate();
|
|
103
103
|
releaseSync = lockSync(dir);
|
|
@@ -11,6 +11,7 @@
|
|
|
11
11
|
* whole set: each path is opened, fstat-ed, read and re-checked against its path, and a mismatch sends the caller back
|
|
12
12
|
* to the full read for that call. Nothing here claims more than that every comparable input was compared.
|
|
13
13
|
*/
|
|
14
|
+
import { PURGE_INTENT_FILE } from "./purge-intent.ts";
|
|
14
15
|
import { createHash } from "node:crypto";
|
|
15
16
|
import { closeSync, constants, fstatSync, lstatSync, openSync, readSync, type BigIntStats } from "node:fs";
|
|
16
17
|
import { join } from "node:path";
|
|
@@ -85,7 +86,7 @@ export interface FenceSelector { readonly pruneInputSetHash?: string; readonly p
|
|
|
85
86
|
*/
|
|
86
87
|
export function homeBindingPaths(home: string, selector: FenceSelector | undefined, reported: readonly string[] = []): string[] {
|
|
87
88
|
const paths = [home, join(home, "profile.json"), join(home, "shards.json"), join(home, "aliases.jsonl"),
|
|
88
|
-
join(home, "lifecycle.jsonl"), join(home, "profile.lock"), join(home, PUBLIC_PRUNE_INTENT), join(home, "public-prune-input-sets")];
|
|
89
|
+
join(home, "lifecycle.jsonl"), join(home, "profile.lock"), join(home, PURGE_INTENT_FILE), join(home, PUBLIC_PRUNE_INTENT), join(home, "public-prune-input-sets")];
|
|
89
90
|
if (selector?.pruneInputSetHash) paths.push(join(home, "public-prune-input-sets", `${selector.pruneInputSetHash}.json`));
|
|
90
91
|
paths.push(join(home, PLACEMENT_ACTIVATION_INTENT), join(home, "sync-placement"), join(home, "sync-placement", "epochs"), join(home, "sync-placement", "active.json"));
|
|
91
92
|
if (selector?.placementHead) {
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import type { Kind } from "./store.ts";
|
|
2
|
+
|
|
3
|
+
// Only a type import from store.ts: the store passes its promoted kinds and unsettled horizon in, so this module adds no runtime cycle.
|
|
4
|
+
/** The lifecycle fold every curated read shares (#680): forgotten, demoted, settled, superseded (with cycle breaking), promoted copies and expiry, from index metadata alone. Pure: it reads nothing. */
|
|
5
|
+
export interface LiveStateInput {
|
|
6
|
+
now: number; ttl: number; unsettledMs: number; promotedKinds: readonly Kind[]; rows: Record<string, string | null>[];
|
|
7
|
+
ops: { id: string; op: string; at: string; target: string; by: string | null }[];
|
|
8
|
+
realms?: Map<string, { id: string; own: number; legacy: number }> | undefined; pruned?: Set<string> | undefined; forgotten?: Iterable<string>;
|
|
9
|
+
}
|
|
10
|
+
export interface LiveState {
|
|
11
|
+
forgotten: Set<string>; demoted: Map<string, string>; promoted: Set<string>; superseded: Map<string, string>; supersedes: Map<string, string[]>;
|
|
12
|
+
expiry: (r: Record<string, string | null>) => string | null;
|
|
13
|
+
}
|
|
14
|
+
export function foldLiveState(input: LiveStateInput): LiveState {
|
|
15
|
+
const { now, rows, ops, realms, pruned } = input;
|
|
16
|
+
const born = realms ? new Set([...realms.values()].filter(row => row.own).map(row => row.id)) : undefined;
|
|
17
|
+
const forgotten = new Set([...ops.filter((o) => o.op === "forget").map((o) => o.target), ...(input.forgotten ?? [])]);
|
|
18
|
+
// Deadlines were fixed when the entries were written, so every process (whatever its own TTL) prunes the same rows.
|
|
19
|
+
const deadline = (o: { at: string; by: string | null }) => o.by && !Number.isNaN(Date.parse(o.by)) ? o.by : new Date(Date.parse(o.at) + input.ttl).toISOString();
|
|
20
|
+
const demoted = new Map(ops.filter((o) => o.op === "demote").map((o) => [o.target, deadline(o)]));
|
|
21
|
+
const settled = new Map<string, string>();
|
|
22
|
+
const settlementKey = (id: string, task: string) => born ? `${born.has(id)}:${task}` : task;
|
|
23
|
+
for (const o of ops) if (o.op === "settle") {
|
|
24
|
+
const source = realms?.get(o.id);
|
|
25
|
+
const keys = !realms ? [o.target] : [
|
|
26
|
+
...(source?.own ? [`true:${o.target}`] : []),
|
|
27
|
+
...(source?.legacy || !source?.own ? [`false:${o.target}`] : []),
|
|
28
|
+
];
|
|
29
|
+
for (const key of keys) if (!settled.has(key)) settled.set(key, deadline(o));
|
|
30
|
+
}
|
|
31
|
+
const superseded = new Map<string, string>(), supersededAt = new Map<string, string>();
|
|
32
|
+
// Relations from ops and from notes' own `supersedes` fold together by write time (then id): the latest intent wins.
|
|
33
|
+
const relate = (old: string, newer: string, when: string) => { if (!(when < (supersededAt.get(old) ?? ""))) { superseded.set(old, newer); supersededAt.set(old, when); } };
|
|
34
|
+
for (const o of ops) if (o.op === "supersede" && o.by) relate(o.target, o.by, `${o.at} ${o.by}`);
|
|
35
|
+
const promoted = new Set<string>();
|
|
36
|
+
for (const r of rows) { if (r.supersedes) relate(r.supersedes, r.id!, `${r.at} ${r.id}`); if (r.promoted_from) promoted.add(r.promoted_from); }
|
|
37
|
+
const expiry = (r: Record<string, string | null>): string | null => {
|
|
38
|
+
const id = r.id!;
|
|
39
|
+
if ((demoted.has(id) ? "short" : r.tier) !== "short") return null;
|
|
40
|
+
// A decision, contract or fail of a settled task not yet copied to long-term waits for its promotion, never expires
|
|
41
|
+
// first; a note saved short-term after the settlement carries its own deadline and stays short-term.
|
|
42
|
+
// A superseded one is held too: if its replacement goes, it shows again, and a rebuild must find it the same way.
|
|
43
|
+
const taskDeadline = r.task ? settled.get(settlementKey(id, r.task)) : undefined;
|
|
44
|
+
if (r.tier === "short" && !demoted.has(id) && !r.expires && taskDeadline && input.promotedKinds.includes(r.kind as Kind)) return null;
|
|
45
|
+
// A deadline written into the note (no task, a late note, an explicit short horizon) is its own, whatever the task does.
|
|
46
|
+
return demoted.get(id) ?? r.expires ?? (r.task ? taskDeadline ?? new Date(Date.parse(r.at!) + input.unsettledMs).toISOString() : new Date(Date.parse(r.at!) + input.ttl).toISOString());
|
|
47
|
+
};
|
|
48
|
+
// A newer entry that was forgotten, expired or pruned no longer replaces anything: the older one shows again. A
|
|
49
|
+
// promoted source lives on as its copy.
|
|
50
|
+
const byId = new Map(rows.map((r) => [r.id!, r]));
|
|
51
|
+
const copyOf = new Map(rows.filter((r) => r.promoted_from).map((r) => [r.promoted_from!, r.id!]));
|
|
52
|
+
const gone = (id: string): boolean => {
|
|
53
|
+
if (pruned?.has(id)) return true;
|
|
54
|
+
const r = byId.get(id);
|
|
55
|
+
if (!r || forgotten.has(id) || (r.promoted_from && forgotten.has(r.promoted_from))) return true;
|
|
56
|
+
const copy = copyOf.get(id);
|
|
57
|
+
if (copy) return gone(copy);
|
|
58
|
+
const e = expiry(r);
|
|
59
|
+
return e !== null && Date.parse(e) <= now;
|
|
60
|
+
};
|
|
61
|
+
// A promoted entry lives on as its copy, on either side of a relation: a promoted replacement still replaces, and a
|
|
62
|
+
// promoted entry that was replaced stays replaced.
|
|
63
|
+
const last = (id: string) => { let to = id; for (let c = copyOf.get(to); c; c = copyOf.get(to)) to = c; return to; };
|
|
64
|
+
for (const [old, newer] of [...superseded]) {
|
|
65
|
+
superseded.set(old, last(newer));
|
|
66
|
+
const copy = last(old);
|
|
67
|
+
if (copy !== old && !superseded.has(copy)) { superseded.set(copy, last(newer)); supersededAt.set(copy, supersededAt.get(old)!); }
|
|
68
|
+
}
|
|
69
|
+
for (const [old, newer] of superseded) if (gone(newer)) superseded.delete(old);
|
|
70
|
+
// Supersessions made apart (two processes, two machines) can close a cycle that would hide every entry in it: the
|
|
71
|
+
// earliest relation in the cycle gives way, so the latest intent stands, the same in every process. Each entry has
|
|
72
|
+
// one replacement, so a chain holds at most one cycle.
|
|
73
|
+
const when = (id: string) => `${supersededAt.get(id) ?? ""} ${id}`; // write time, then ids: the same in every process
|
|
74
|
+
for (const start of [...superseded.keys()]) {
|
|
75
|
+
const seen: string[] = [];
|
|
76
|
+
for (let at: string | undefined = start; at !== undefined && superseded.has(at); at = superseded.get(at)) {
|
|
77
|
+
const i = seen.indexOf(at);
|
|
78
|
+
if (i >= 0) { superseded.delete(seen.slice(i).reduce((x, y) => (when(y) < when(x) ? y : x))); break; }
|
|
79
|
+
seen.push(at);
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
const supersedes = new Map<string, string[]>(); // the reverse: what each newer entry replaced
|
|
83
|
+
for (const [old, newer] of superseded) supersedes.set(newer, [...(supersedes.get(newer) ?? []), old]);
|
|
84
|
+
return { forgotten, demoted, promoted, superseded, supersedes, expiry };
|
|
85
|
+
}
|
package/src/memory/migrate.ts
CHANGED
|
@@ -132,7 +132,7 @@ export async function migrate(options: MigrateOptions): Promise<MigrationResult>
|
|
|
132
132
|
const safeDirectory = (path: string) => existsSync(path) && lstatSync(path).isDirectory() && !lstatSync(path).isSymbolicLink();
|
|
133
133
|
if (safeDirectory(parent) && safeDirectory(initial.dir) && existsSync(file) && lstatSync(file).isFile() && !lstatSync(file).isSymbolicLink()) {
|
|
134
134
|
let unavailable = false;
|
|
135
|
-
try { releaseGeneration = acquireMutation(initial.dir); } catch { unavailable = true; }
|
|
135
|
+
try { releaseGeneration = acquireMutation(initial.dir, memoryDir); } catch { unavailable = true; }
|
|
136
136
|
if (!unavailable && !releaseGeneration) throw new Error("generation mutation lock is busy");
|
|
137
137
|
}
|
|
138
138
|
if (readSelector(memoryDir).revision !== initial.selectorRevision) return changed();
|
|
@@ -167,7 +167,7 @@ export async function migrate(options: MigrateOptions): Promise<MigrationResult>
|
|
|
167
167
|
if (!existing || existing.id !== machine.id || typeof existing.label !== "string") return changed();
|
|
168
168
|
generationMachine = { id: machine.id, label: existing.label };
|
|
169
169
|
}
|
|
170
|
-
const releaseLegacy = acquireMutation(memoryDir);
|
|
170
|
+
const releaseLegacy = acquireMutation(memoryDir, memoryDir);
|
|
171
171
|
if (!releaseLegacy) throw new Error("legacy mutation lock is busy");
|
|
172
172
|
let sources: SourcePrefix[], legacyCommit: string | undefined;
|
|
173
173
|
try {
|
|
@@ -200,7 +200,7 @@ export async function migrate(options: MigrateOptions): Promise<MigrationResult>
|
|
|
200
200
|
|| canonicalJSON(readProfileJSON(join(dir, "machine.json"))) !== canonicalJSON(journal.machine) || journal.machine.id !== machine.id) return changed();
|
|
201
201
|
verifySources(memoryDir, journal.generation, journal.sources, journal.legacyCommit);
|
|
202
202
|
const profile: BoundProfile = { kind: "generation", home: memoryDir, dir, generation: journal.generation, selectorRevision: journal.selectorRevision };
|
|
203
|
-
const releaseGeneration = acquireMutation(dir);
|
|
203
|
+
const releaseGeneration = acquireMutation(dir, memoryDir);
|
|
204
204
|
if (!releaseGeneration) throw new Error("generation mutation lock is busy");
|
|
205
205
|
try {
|
|
206
206
|
if (journal.phase !== "sealed" && journal.phase !== "active") writeSources(memoryDir, journal);
|
package/src/memory/mutation.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { assertNoPendingPurge } from "./purge-intent.ts";
|
|
1
2
|
import { Database } from "bun:sqlite";
|
|
2
3
|
import { chmodSync, lstatSync } from "node:fs";
|
|
3
4
|
import { join } from "node:path";
|
|
@@ -25,10 +26,12 @@ export function assertMutationHandle(handle: MutationHandle, dir: string): void
|
|
|
25
26
|
|| realPath(dir) !== state.dir || stat.dev !== state.dev || stat.ino !== state.ino) throw new Error("mutation handle unavailable or directory changed");
|
|
26
27
|
}
|
|
27
28
|
/** Sync holds a separate connection across awaits; an unrelated call cannot bypass it. */
|
|
28
|
-
export function acquireMutation(dir: string): MutationHandle | undefined {
|
|
29
|
+
export function acquireMutation(dir: string, memoryHome: string): MutationHandle | undefined {
|
|
29
30
|
const stat = lstatSync(dir);
|
|
30
31
|
if (stat.isSymbolicLink() || !stat.isDirectory()) throw new Error("mutation directory unavailable");
|
|
31
|
-
const canonical = realPath(dir)
|
|
32
|
+
const canonical = realPath(dir);
|
|
33
|
+
assertNoPendingPurge(memoryHome);
|
|
34
|
+
const db = mutationDatabase(canonical);
|
|
32
35
|
try { db.run("BEGIN IMMEDIATE"); }
|
|
33
36
|
catch { db.close(); return undefined; }
|
|
34
37
|
const release = (() => {
|
|
@@ -38,7 +41,7 @@ export function acquireMutation(dir: string): MutationHandle | undefined {
|
|
|
38
41
|
try { db.run("ROLLBACK"); } finally { db.close(); }
|
|
39
42
|
}) as MutationHandle;
|
|
40
43
|
mutations.set(release, { dir: canonical, dev: stat.dev, ino: stat.ino, db, active: true });
|
|
41
|
-
try { assertMutationHandle(release, dir); } catch (error) { release(); throw error; }
|
|
44
|
+
try { assertMutationHandle(release, dir); assertNoPendingPurge(memoryHome); } catch (error) { release(); throw error; }
|
|
42
45
|
return release;
|
|
43
46
|
}
|
|
44
47
|
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { lstatSync, type BigIntStats } from "node:fs";
|
|
2
|
+
|
|
3
|
+
export function sameMetadataStamp(a: BigIntStats, b: BigIntStats): boolean {
|
|
4
|
+
return a.dev === b.dev && a.ino === b.ino && a.size === b.size && a.mtimeNs === b.mtimeNs && a.ctimeNs === b.ctimeNs;
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
export function freezeMetadata<T>(value: T): T {
|
|
8
|
+
if (value && typeof value === "object" && !Object.isFrozen(value)) {
|
|
9
|
+
for (const child of Object.values(value)) freezeMetadata(child);
|
|
10
|
+
Object.freeze(value);
|
|
11
|
+
}
|
|
12
|
+
return value;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
const snapshots = new WeakSet<object>();
|
|
16
|
+
export function isMetadataSnapshot(value: unknown): value is object {
|
|
17
|
+
return !!value && typeof value === "object" && snapshots.has(value);
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** Each reader owns its cache and keeps its own parsing, permission and refusal rules. */
|
|
21
|
+
export function metadataReader(read: (path: string) => { stamp: BigIntStats; value: unknown } | undefined) {
|
|
22
|
+
// ponytail: 32 file snapshots per reader across all homes; partition by home if alternating homes churn the cache.
|
|
23
|
+
const entries = new Map<string, { stamp: BigIntStats; value: unknown }>();
|
|
24
|
+
return (path: string): unknown | undefined => {
|
|
25
|
+
let before: BigIntStats | undefined;
|
|
26
|
+
try { before = lstatSync(path, { bigint: true, throwIfNoEntry: false }); }
|
|
27
|
+
catch { entries.delete(path); return read(path)?.value; }
|
|
28
|
+
const entry = entries.get(path);
|
|
29
|
+
if (before?.isFile() && entry && sameMetadataStamp(before, entry.stamp)) {
|
|
30
|
+
entries.delete(path);
|
|
31
|
+
entries.set(path, entry);
|
|
32
|
+
return entry.value;
|
|
33
|
+
}
|
|
34
|
+
entries.delete(path);
|
|
35
|
+
const result = read(path);
|
|
36
|
+
if (!result) return undefined;
|
|
37
|
+
const { value, stamp } = result;
|
|
38
|
+
if (!before?.isFile() || !sameMetadataStamp(before, stamp)) return value;
|
|
39
|
+
try { freezeMetadata(value); } catch { return value; }
|
|
40
|
+
if (value && typeof value === "object") snapshots.add(value);
|
|
41
|
+
if (entries.size === 32) entries.delete(entries.keys().next().value!);
|
|
42
|
+
entries.set(path, { stamp, value });
|
|
43
|
+
return value;
|
|
44
|
+
};
|
|
45
|
+
}
|
|
@@ -230,7 +230,7 @@ export async function activatePublicPruneView(options: PublicPruneActivationOpti
|
|
|
230
230
|
try {
|
|
231
231
|
guard(lstatSync(home).dev === rootStat.dev && lstatSync(home).ino === rootStat.ino);
|
|
232
232
|
const dirs = [...new Set([home, ...intent.realms.map(realm => realm.profile.dir)])].sort();
|
|
233
|
-
for (const dir of dirs) { assertNoLiveReaders(dir, {includeShards:true}); const release = acquireMutation(dir); guard(release); releases.push(release); }
|
|
233
|
+
for (const dir of dirs) { assertNoLiveReaders(dir, {includeShards:true}); const release = acquireMutation(dir, home); guard(release); releases.push(release); }
|
|
234
234
|
validateAdvance(intent);
|
|
235
235
|
if (pending) writeImmutableActivationMetadata(intentFile, canonicalJSON(intent) + "\n");
|
|
236
236
|
if (!pending) {
|
|
@@ -108,7 +108,7 @@ function run(intent: AdvanceIntent, provided: readonly MutationHandle[]|undefine
|
|
|
108
108
|
const checks=proofs(intent), releases:MutationHandle[]=[];
|
|
109
109
|
const work=()=>{
|
|
110
110
|
const dirs=[intent.home,...intent.bindings.map(item=>item.dir)].sort();
|
|
111
|
-
const handles=provided??dirs.map(dir=>{const lease=acquireMutation(dir);guard(lease);releases.push(lease);return lease;});
|
|
111
|
+
const handles=provided??dirs.map(dir=>{const lease=acquireMutation(dir, intent.home);guard(lease);releases.push(lease);return lease;});
|
|
112
112
|
const verify=()=>{
|
|
113
113
|
const root=owned(intent.home,true);guard(root.dev===intent.root.dev&&root.ino===intent.root.ino&&hashJSON(optional(aliasLogPath(intent.home)))===intent.root.aliasesHash&&hashJSON(raw(join(intent.home,"machine.json")))===intent.root.machineHash);
|
|
114
114
|
for(const dir of dirs){let found=false;for(const handle of handles){try{assertMutationHandle(handle,dir);found=true;break;}catch{}}guard(found);}
|
|
@@ -311,7 +311,7 @@ export function persistPublicPruneInput(plan: PublicPruneInputPlan, options: { o
|
|
|
311
311
|
}; current();
|
|
312
312
|
// The shared SQLite lock is an ownership fence, never an archive or membership source.
|
|
313
313
|
for (const suffix of ["", "-wal", "-shm", "-journal"]) { const stat = lstatSync(join(dir, "mutation-lock.db" + suffix), { throwIfNoEntry: false }); if (stat) privateStat(stat); }
|
|
314
|
-
const release = options.mutation ?? acquireMutation(dir); guard(release); assertMutationHandle(release, dir); try {
|
|
314
|
+
const release = options.mutation ?? acquireMutation(dir, dir); guard(release); assertMutationHandle(release, dir); try {
|
|
315
315
|
current(); assertMutationHandle(release, dir); recoverLinkedTemps(dir, release); current(); const previous = expected.inputSetHash;
|
|
316
316
|
const members = previous ? replay({ realm: expected.realm, receivingGeneration: expected.receivingGeneration, ...(expected.publicationFormat ? {publicationFormat:expected.publicationFormat} : {}), inputSetHash: previous }, (kind, id) => read(dir, kind, id)).inputs : [];
|
|
317
317
|
const inputHash = prepared.input && hashJSON(prepared.input), includes = inputHash !== undefined && members.includes(inputHash);
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { lstatSync } from "node:fs";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
|
|
4
|
+
/** Stable-home barriers. Even malformed or link-shaped evidence blocks access. */
|
|
5
|
+
export const PURGE_INTENT_FILE = "purge-intent.json";
|
|
6
|
+
export const PURGE_PUBLICATION_BLOCK_FILE = "purge-publication-block.json";
|
|
7
|
+
export const PURGE_PENDING = "A local purge is pending; keep the home closed and use amem doctor to check status.";
|
|
8
|
+
export const PURGE_PUBLICATION_BLOCKED = "Publication is blocked after a local purge; see docs/purge-design.md, First implementation: local purge and manual remote move.";
|
|
9
|
+
|
|
10
|
+
function barrierPresent(home: string, file: string): boolean {
|
|
11
|
+
try { return lstatSync(join(home, file), { throwIfNoEntry: false }) !== undefined; }
|
|
12
|
+
catch { return true; }
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export function purgePending(home: string): boolean {
|
|
16
|
+
return barrierPresent(home, PURGE_INTENT_FILE);
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export function assertNoPendingPurge(home: string): void {
|
|
20
|
+
if (purgePending(home)) throw new Error(PURGE_PENDING);
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** Local-first: alternate remote spellings never bypass this home-wide block. */
|
|
24
|
+
export function purgePublicationRefusal(home: string): string | undefined {
|
|
25
|
+
if (purgePending(home)) return PURGE_PENDING;
|
|
26
|
+
if (barrierPresent(home, PURGE_PUBLICATION_BLOCK_FILE)) return PURGE_PUBLICATION_BLOCKED;
|
|
27
|
+
}
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
import { Database, constants as sqlite } from "bun:sqlite";
|
|
2
|
+
import { closeSync, constants, fstatSync, lstatSync, openSync, readdirSync, readSync } from "node:fs";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import { pathToFileURL } from "node:url";
|
|
5
|
+
import { hashJSON } from "./generation.ts";
|
|
6
|
+
import { realPath } from "./platform.ts";
|
|
7
|
+
|
|
8
|
+
const MATCHER_BYTES = 4096, MAX_ROWS = 4_000_000, MAX_MATCHES = 1000, MAX_SHARDS = 4096, MAX_SCAN_MS = 120_000;
|
|
9
|
+
const unavailable = (): never => { throw new Error(/* refusal-by-design: operator-knowledge close the sidecar readers or supply a private bounded file. */ "Purge matcher input is unavailable, unclean or over its preview bound; close capture and candidate readers and check docs/purge-design.md."); };
|
|
10
|
+
const stamp = (stat: ReturnType<typeof fstatSync>) => [stat.dev, stat.ino, stat.size, stat.mtimeMs, stat.ctimeMs].join(":");
|
|
11
|
+
|
|
12
|
+
function privateBytes(file: string, maximum: number): Buffer {
|
|
13
|
+
const fd = openSync(file, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
|
|
14
|
+
try {
|
|
15
|
+
const before = fstatSync(fd);
|
|
16
|
+
if (!before.isFile() || before.nlink !== 1 || before.uid !== process.getuid?.() || (before.mode & 0o077) !== 0 || before.size > maximum) return unavailable();
|
|
17
|
+
const result = Buffer.alloc(before.size);
|
|
18
|
+
let offset = 0;
|
|
19
|
+
while (offset < result.length) {
|
|
20
|
+
const count = readSync(fd, result, offset, result.length - offset, offset);
|
|
21
|
+
if (!count) return unavailable();
|
|
22
|
+
offset += count;
|
|
23
|
+
}
|
|
24
|
+
if (stamp(fstatSync(fd)) !== stamp(before) || stamp(lstatSync(file)) !== stamp(before)) return unavailable();
|
|
25
|
+
return result;
|
|
26
|
+
} finally { closeSync(fd); }
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export function openPurgeMatcher(file: string): string {
|
|
30
|
+
try {
|
|
31
|
+
const raw = new TextDecoder("utf-8", { fatal: true }).decode(privateBytes(file, MATCHER_BYTES));
|
|
32
|
+
if (!raw.length || raw.includes(String.fromCharCode(0))) return unavailable();
|
|
33
|
+
return raw;
|
|
34
|
+
} catch { return unavailable(); }
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export interface PurgeSidecarMatch { store: "capture" | "candidate"; location: string; id: string; rowHash: string }
|
|
38
|
+
export interface PurgeSidecarSource { store: PurgeSidecarMatch["store"]; location: string; hash: string }
|
|
39
|
+
function contains(value: unknown, needle: string): boolean {
|
|
40
|
+
const pending = [value];
|
|
41
|
+
while (pending.length) {
|
|
42
|
+
const next = pending.pop();
|
|
43
|
+
if (typeof next === "string" && next.includes(needle)) return true;
|
|
44
|
+
if (next && typeof next === "object") for (const child of Object.values(next)) pending.push(child);
|
|
45
|
+
}
|
|
46
|
+
return false;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** Stream immutable, checkpointed databases without opening SQLite sidecars or copying the main files. */
|
|
50
|
+
export function previewPurgeMatches(home: string, machine: string, needle: string): { matches: PurgeSidecarMatch[]; sources: PurgeSidecarSource[] } {
|
|
51
|
+
try {
|
|
52
|
+
const files: { store: PurgeSidecarMatch["store"]; location: string; file: string }[] = [];
|
|
53
|
+
const projects = join(home, "projects"), root = lstatSync(projects, { throwIfNoEntry: false });
|
|
54
|
+
if (root && (!root.isDirectory() || realPath(projects) !== projects)) return unavailable();
|
|
55
|
+
const dirs = root ? readdirSync(projects).sort() : [];
|
|
56
|
+
if (dirs.length > MAX_SHARDS) return unavailable();
|
|
57
|
+
for (const location of dirs) if (/^[a-f0-9]{16}$/.test(location)) files.push({ store: "capture", location, file: join(projects, location, "machine", machine, "capture.db") });
|
|
58
|
+
files.push({ store: "candidate", location: "home", file: join(home, "candidates.db") });
|
|
59
|
+
const matches: PurgeSidecarMatch[] = [], sources: PurgeSidecarSource[] = [];
|
|
60
|
+
let rowsLeft = MAX_ROWS;
|
|
61
|
+
const deadline = performance.now() + MAX_SCAN_MS;
|
|
62
|
+
const observed: { file: string; stamp: string }[] = [];
|
|
63
|
+
const state = (file: string) => {
|
|
64
|
+
const db = lstatSync(file, { bigint: true, throwIfNoEntry: false });
|
|
65
|
+
for (const suffix of ["-wal", "-journal"]) {
|
|
66
|
+
const sidecar = lstatSync(file + suffix, { throwIfNoEntry: false });
|
|
67
|
+
if (sidecar && (!sidecar.isFile() || sidecar.size !== 0)) return unavailable();
|
|
68
|
+
}
|
|
69
|
+
if (db && (!db.isFile() || db.nlink !== 1n || db.uid !== BigInt(process.getuid?.() ?? -1)
|
|
70
|
+
|| (db.mode & 0o077n) !== 0n || realPath(file) !== file)) return unavailable();
|
|
71
|
+
return db ? [db.dev, db.ino, db.size, db.mtimeNs, db.ctimeNs].join(":") : "absent";
|
|
72
|
+
};
|
|
73
|
+
for (const { store, location, file } of files) {
|
|
74
|
+
const before = state(file);
|
|
75
|
+
observed.push({ file, stamp: before });
|
|
76
|
+
if (before === "absent") continue;
|
|
77
|
+
if (performance.now() >= deadline) return unavailable();
|
|
78
|
+
// Bun's boolean readonly option omits SQLITE_OPEN_URI. SQLite builds without USE_URI need the flag explicitly.
|
|
79
|
+
const db = new Database(`${pathToFileURL(file).href}?immutable=1`, sqlite.SQLITE_OPEN_READONLY | sqlite.SQLITE_OPEN_URI);
|
|
80
|
+
try {
|
|
81
|
+
const table = store === "capture" ? "rows" : "candidates";
|
|
82
|
+
if (!db.query("SELECT 1 FROM sqlite_schema WHERE type = 'table' AND name = ?").get(table)) return unavailable();
|
|
83
|
+
const query = `SELECT * FROM ${table} ORDER BY id LIMIT ?`;
|
|
84
|
+
for (const row of db.query(query).iterate(rowsLeft + 1) as Iterable<Record<string, unknown>>) {
|
|
85
|
+
if (--rowsLeft < 0 || performance.now() >= deadline) return unavailable();
|
|
86
|
+
const input = store === "capture" ? [row.excerpt, JSON.parse(String(row.paths)), row.tool] : JSON.parse(String(row.payload));
|
|
87
|
+
if (!contains(input, needle)) continue;
|
|
88
|
+
if (store === "capture" ? typeof row.id !== "number" || !Number.isSafeInteger(row.id) || row.id < 1
|
|
89
|
+
: typeof row.id !== "string" || !/^[a-f0-9]{64}$/.test(row.id)) return unavailable();
|
|
90
|
+
if (matches.length >= MAX_MATCHES) return unavailable();
|
|
91
|
+
matches.push({ store, location, id: String(row.id), rowHash: hashJSON(row) });
|
|
92
|
+
}
|
|
93
|
+
} finally { db.close(); }
|
|
94
|
+
if (state(file) !== before) return unavailable();
|
|
95
|
+
// The source digest binds filesystem identity; every selected row also carries its own content hash.
|
|
96
|
+
sources.push({ store, location, hash: hashJSON(before) });
|
|
97
|
+
}
|
|
98
|
+
if (observed.some(item => state(item.file) !== item.stamp) || (root && JSON.stringify(readdirSync(projects).sort()) !== JSON.stringify(dirs))) return unavailable();
|
|
99
|
+
return { matches, sources };
|
|
100
|
+
} catch { return unavailable(); }
|
|
101
|
+
}
|