@staix/agent-mem 0.41.0 → 0.42.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 +129 -24
- package/src/commands-table.ts +11 -4
- package/src/index.ts +2 -1
- 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 +21 -5
- 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/formats-raise.ts +36 -15
- package/src/memory/formats.ts +26 -10
- package/src/memory/profile-marker-cache.ts +45 -0
- package/src/memory/search-fts.ts +55 -27
- package/src/memory/shard.ts +17 -14
- package/src/memory/store.ts +5 -3
- package/src/memory/sync-cadence.ts +8 -4
- package/src/memory/sync-placement-activation-locks.ts +27 -19
- package/src/memory/sync-placement-active.ts +67 -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 +29 -11
- package/src/memory/sync-placement-inventory.ts +20 -4
- 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 +28 -12
- package/src/memory/sync-placement-writer-listing.ts +38 -13
- package/src/memory/sync-placement-writer-renewal.ts +5 -7
- package/src/memory/topic.ts +14 -0
- package/src/setup-console.ts +49 -23
- package/src/setup-drift.ts +31 -1
- package/src/setup-writer-roots.ts +1 -1
- package/src/setup.ts +66 -10
- 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
|
|
package/src/memory/formats.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { closeSync, constants, fstatSync, openSync, readFileSync, readSync } from "node:fs";
|
|
1
|
+
import { closeSync, constants, fstatSync, lstatSync, openSync, readFileSync, readSync, type BigIntStats } from "node:fs";
|
|
2
2
|
import { join } from "node:path";
|
|
3
3
|
|
|
4
4
|
/**
|
|
@@ -41,15 +41,34 @@ export function formatVersionBelow(reader: string, floor: string): boolean {
|
|
|
41
41
|
return false;
|
|
42
42
|
}
|
|
43
43
|
|
|
44
|
+
// #656: parsed floors by resolved file path plus dev:ino:size:mtimeNs:ctimeNs, so a fence check that runs per row does not reopen
|
|
45
|
+
// 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.
|
|
46
|
+
// ponytail: same-size in-place rewrites within one stat tick are not seen (the profile-marker-cache ceiling); upgrade is a content hash.
|
|
47
|
+
const floorMemo = new Map<string, { stamp: string; floors: FormatFloor[] }>();
|
|
48
|
+
const floorStamp = (s: BigIntStats) => [s.dev, s.ino, s.size, s.mtimeNs, s.ctimeNs].map(String).join(":");
|
|
44
49
|
/** Bounded read of the floor records: undefined when there is no file; anything that is not a regular file of valid records refuses. */
|
|
45
50
|
export function readFormatFloors(home: string): FormatFloor[] | undefined {
|
|
46
|
-
const file = join(home, FORMATS_FILE)
|
|
51
|
+
const file = join(home, FORMATS_FILE);
|
|
52
|
+
let before: BigIntStats | undefined;
|
|
53
|
+
try { before = lstatSync(file, { bigint: true, throwIfNoEntry: false }); } catch { before = undefined; }
|
|
54
|
+
const cached = floorMemo.get(file);
|
|
55
|
+
if (before?.isFile() && cached && cached.stamp === floorStamp(before)) return cached.floors.map(floor => ({ ...floor }));
|
|
56
|
+
floorMemo.delete(file);
|
|
57
|
+
const read = readFormatFloorsUncached(file);
|
|
58
|
+
if (read && before?.isFile() && read.stamp === floorStamp(before)) {
|
|
59
|
+
if (floorMemo.size >= 32) floorMemo.delete(floorMemo.keys().next().value!);
|
|
60
|
+
floorMemo.set(file, { stamp: read.stamp, floors: read.floors.map(floor => ({ ...floor })) });
|
|
61
|
+
}
|
|
62
|
+
return read?.floors;
|
|
63
|
+
}
|
|
64
|
+
function readFormatFloorsUncached(file: string): { floors: FormatFloor[]; stamp: string } | undefined {
|
|
65
|
+
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
66
|
let fd: number;
|
|
48
67
|
try { fd = openSync(file, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK); }
|
|
49
68
|
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;
|
|
69
|
+
let text: string, stamp: string;
|
|
51
70
|
try {
|
|
52
|
-
const stat = fstatSync(fd);
|
|
71
|
+
const stat = fstatSync(fd); stamp = floorStamp(fstatSync(fd, { bigint: true }));
|
|
53
72
|
if (!stat.isFile() || stat.size > MAX_BYTES) throw unreadable("not a regular file of at most 64 KiB");
|
|
54
73
|
const data = Buffer.alloc(MAX_BYTES + 1); let size = 0, n: number;
|
|
55
74
|
while (size < data.length && (n = readSync(fd, data, size, data.length - size, null)) > 0) size += n;
|
|
@@ -60,7 +79,7 @@ export function readFormatFloors(home: string): FormatFloor[] | undefined {
|
|
|
60
79
|
try { value = JSON.parse(text); } catch { throw unreadable("not JSON"); }
|
|
61
80
|
if (!Array.isArray(value) || !value.every(record => record && typeof record === "object" && !Array.isArray(record)
|
|
62
81
|
&& 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 }));
|
|
82
|
+
return { floors: value.map(({ surface, minReader, since }) => ({ surface, minReader, since })), stamp };
|
|
64
83
|
}
|
|
65
84
|
|
|
66
85
|
/** Refuse before touching `surface` when the home records a floor above this release. */
|
|
@@ -79,10 +98,7 @@ export function formatFloorAtLeast(home: string, surface: FormatSurface, minimum
|
|
|
79
98
|
return (readFormatFloors(home) ?? []).some(floor => (floor.surface === surface || floor.surface === "home") && !formatVersionBelow(floor.minReader, minimum));
|
|
80
99
|
}
|
|
81
100
|
|
|
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
|
-
*/
|
|
101
|
+
/** The preview and explicit confirmation a person uses to append a format floor. */
|
|
86
102
|
export function floorRaiseHint(home: string, surface: FormatSurface, minReader: string): string {
|
|
87
|
-
return `
|
|
103
|
+
return `preview amem formats raise ${surface} ${minReader}, then run amem formats raise ${surface} ${minReader} --confirm to append the floor to ${join(home, FORMATS_FILE)}`;
|
|
88
104
|
}
|
|
@@ -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
|
+
}
|
package/src/memory/search-fts.ts
CHANGED
|
@@ -7,18 +7,23 @@ import type { CaptureRow } from "./capture.ts";
|
|
|
7
7
|
/**
|
|
8
8
|
* #13 R5: full-text search over the curated tier with SQLite FTS5 and BM25, replacing substring matching where the
|
|
9
9
|
* platform's sqlite has FTS5 (verified in bun:sqlite on Bun 1.4.2, macOS and Linux). The index lives in its own
|
|
10
|
-
*
|
|
10
|
+
* its versioned search file beside the memory logs: `index.db`'s table set is part of the shared-v1 golden contract and must not
|
|
11
11
|
* gain tables, and the sync .gitignore already keeps every other file machine-local. `search.db` is derived only
|
|
12
12
|
* from curated rows: every add is idempotent by entry id, and a store rebuild, a prune, a lock or any count drift
|
|
13
13
|
* forces a full resync, so the incremental index equals a rebuild.
|
|
14
14
|
*
|
|
15
|
-
* The copy is a DERIVED cache: a locked or failing
|
|
15
|
+
* The copy is a DERIVED cache: a locked or failing search file never fails or stalls a curated write — the apply
|
|
16
16
|
* path marks the copy stale and the next search resyncs it. Its busy timeout is zero: derived writes fail fast and
|
|
17
17
|
* degrade, never queue behind another process's lock (R2's 150 ms hook budget includes the write path).
|
|
18
18
|
*/
|
|
19
19
|
|
|
20
20
|
/** Bumped when the docs table's shape changes: an older copy is dropped and rebuilt from the curated rows. */
|
|
21
|
-
const SEARCH_SCHEMA = "
|
|
21
|
+
const SEARCH_SCHEMA = "3";
|
|
22
|
+
|
|
23
|
+
/** Separate cache files let older and newer releases share a home without rebuilding each other's FTS tables. */
|
|
24
|
+
export function searchFileName(generation?: string): string {
|
|
25
|
+
return generation === undefined ? `search-s${SEARCH_SCHEMA}.db` : `search-${generation}-s${SEARCH_SCHEMA}.db`;
|
|
26
|
+
}
|
|
22
27
|
|
|
23
28
|
let probe: boolean | undefined;
|
|
24
29
|
/** One runtime probe; the answer is cached for the process. */
|
|
@@ -43,11 +48,16 @@ export function setFts5AvailableForTest(value: boolean | undefined): void {
|
|
|
43
48
|
|
|
44
49
|
const KOREAN_PARTICLES = ["에는", "에서", "으로", "에게", "한테", "처럼", "보다", "까지", "부터", "마다", "조차", "마저", "이나", "이랑", "하고", "은", "는", "이", "가", "을", "를", "에", "로", "와", "과", "도", "만", "의", "랑", "나", "라"];
|
|
45
50
|
|
|
46
|
-
/**
|
|
51
|
+
/** Keep at least two characters after removing a common Korean suffix. */
|
|
52
|
+
export function stripKoreanParticle(term: string): string {
|
|
53
|
+
const particle = KOREAN_PARTICLES.find(p => term.endsWith(p) && term.length - p.length >= 2);
|
|
54
|
+
return particle ? term.slice(0, -particle.length) : term;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** The original term plus a common-particle-stripped Korean alternative. */
|
|
47
58
|
function queryVariants(term: string): string[] {
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
return particle ? [term, term.slice(0, -particle.length)] : [term];
|
|
59
|
+
const bare = /[가-힣]/u.test(term) ? stripKoreanParticle(term) : term;
|
|
60
|
+
return bare === term ? [term] : [term, bare];
|
|
51
61
|
}
|
|
52
62
|
|
|
53
63
|
/**
|
|
@@ -62,6 +72,22 @@ export function ftsTerms(q: string): string {
|
|
|
62
72
|
return variants.map((t) => `"${t.replaceAll('"', '""')}" *`).join(" OR ");
|
|
63
73
|
}
|
|
64
74
|
|
|
75
|
+
const joinHangul = (text: string): string => text.replace(/(?<=[가-힣])[ \t]+(?=[가-힣])/gu, "");
|
|
76
|
+
const hangulShadow = (text: string): string => (joinHangul(text).match(/[가-힣]+/gu) ?? []).join(" ");
|
|
77
|
+
const BODY_RANK = "bm25(docs, 1.0, 0.0)";
|
|
78
|
+
const COMPOUND_RANK = "bm25(docs, 1.0, 4.0)";
|
|
79
|
+
|
|
80
|
+
/** The ordinary body lexicon stays separate from the joined Hangul spans. */
|
|
81
|
+
function curatedMatch(query: string, includeCompounds = true): { match: string; rank: string } {
|
|
82
|
+
const terms = ftsTerms(query);
|
|
83
|
+
const trimmed = query.trim();
|
|
84
|
+
const compound = includeCompounds && /^[가-힣]+(?:[ \t]+[가-힣]+)*$/u.test(trimmed) ? joinHangul(trimmed) : "";
|
|
85
|
+
return {
|
|
86
|
+
match: !terms ? "" : `body : (${terms})${compound.length >= 3 ? ` OR hangul : "${compound}" *` : ""}`,
|
|
87
|
+
rank: compound.length >= 3 ? COMPOUND_RANK : BODY_RANK,
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
|
|
65
91
|
export interface CuratedDoc { id: string; at: string; project: string; tier: string; scope: string; body: string }
|
|
66
92
|
export interface RankedRef { ref: string; project: string; tier: string; at: string; rank: number }
|
|
67
93
|
|
|
@@ -84,7 +110,7 @@ export class SearchIndex {
|
|
|
84
110
|
db.run("DELETE FROM meta");
|
|
85
111
|
db.query("INSERT INTO meta (key, value) VALUES ('schema', ?)").run(SEARCH_SCHEMA);
|
|
86
112
|
}
|
|
87
|
-
db.run("CREATE VIRTUAL TABLE IF NOT EXISTS docs USING fts5(body, ref UNINDEXED, project UNINDEXED, tier UNINDEXED, at UNINDEXED, scope UNINDEXED)");
|
|
113
|
+
db.run("CREATE VIRTUAL TABLE IF NOT EXISTS docs USING fts5(body, hangul, ref UNINDEXED, project UNINDEXED, tier UNINDEXED, at UNINDEXED, scope UNINDEXED)");
|
|
88
114
|
// FTS5 has no unique constraint: refs remembers what is indexed, so a repeated or rebuilt row is never doubled.
|
|
89
115
|
db.run("CREATE TABLE IF NOT EXISTS refs (ref TEXT PRIMARY KEY)");
|
|
90
116
|
if (file !== ":memory:") try { chmodSync(file, 0o600); } catch { /* best effort */ }
|
|
@@ -107,7 +133,7 @@ export class SearchIndex {
|
|
|
107
133
|
// confuse it), so idempotency is a plain lookup, never the statement's change count.
|
|
108
134
|
if (db.query("SELECT 1 FROM refs WHERE ref = ?").get(doc.id)) return;
|
|
109
135
|
db.query("INSERT INTO refs (ref) VALUES (?)").run(doc.id);
|
|
110
|
-
db.query("INSERT INTO docs (body, ref, project, tier, at, scope) VALUES (?, ?, ?, ?, ?, ?)").run(doc.body, doc.id, doc.project, doc.tier, doc.at, doc.scope);
|
|
136
|
+
db.query("INSERT INTO docs (body, hangul, ref, project, tier, at, scope) VALUES (?, ?, ?, ?, ?, ?, ?)").run(doc.body, hangulShadow(doc.body), doc.id, doc.project, doc.tier, doc.at, doc.scope);
|
|
111
137
|
db.query("INSERT INTO meta (key, value) VALUES ('curated', '1') ON CONFLICT(key) DO UPDATE SET value = CAST(value AS INTEGER) + 1").run();
|
|
112
138
|
}).immediate();
|
|
113
139
|
} catch { this.markDirty(); } // the FTS copy degrades, the curated write stands
|
|
@@ -138,7 +164,7 @@ export class SearchIndex {
|
|
|
138
164
|
let n = 0;
|
|
139
165
|
for (const doc of load()) {
|
|
140
166
|
db.query("INSERT INTO refs (ref) VALUES (?)").run(doc.id);
|
|
141
|
-
db.query("INSERT INTO docs (body, ref, project, tier, at, scope) VALUES (?, ?, ?, ?, ?, ?)").run(doc.body, doc.id, doc.project, doc.tier, doc.at, doc.scope);
|
|
167
|
+
db.query("INSERT INTO docs (body, hangul, ref, project, tier, at, scope) VALUES (?, ?, ?, ?, ?, ?, ?)").run(doc.body, hangulShadow(doc.body), doc.id, doc.project, doc.tier, doc.at, doc.scope);
|
|
142
168
|
n++;
|
|
143
169
|
}
|
|
144
170
|
db.query("INSERT INTO meta (key, value) VALUES ('curated', ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(String(n));
|
|
@@ -168,17 +194,17 @@ export class SearchIndex {
|
|
|
168
194
|
*/
|
|
169
195
|
query(q: string, limit: number, project?: string | readonly string[], offset = 0): RankedRef[] {
|
|
170
196
|
if (!this.db) return [];
|
|
171
|
-
const match =
|
|
197
|
+
const { match, rank } = curatedMatch(q);
|
|
172
198
|
if (!match) return [];
|
|
173
199
|
const where = project ? "docs MATCH ? AND (project IN (SELECT value FROM json_each(?)) OR scope = 'shared')" : "docs MATCH ?";
|
|
174
200
|
const bind = project ? [match, JSON.stringify(typeof project === "string" ? [project] : project)] : [match];
|
|
175
|
-
return this.db.query(`SELECT ref, project, tier, at,
|
|
201
|
+
return this.db.query(`SELECT ref, project, tier, at, ${rank} AS rank FROM docs WHERE ${where} ORDER BY rank, ref LIMIT ? OFFSET ?`).all(...bind, limit, offset) as RankedRef[];
|
|
176
202
|
}
|
|
177
203
|
|
|
178
204
|
/** Matching identities in chronological keyset pages; raw-corpus BM25 never selects a private-policy window. */
|
|
179
205
|
candidates(q: string, window: ReadWindow): ReadRef[] {
|
|
180
206
|
if (!this.db) return [];
|
|
181
|
-
const match =
|
|
207
|
+
const { match } = curatedMatch(q); if (!match) return [];
|
|
182
208
|
const { columns, where, bind } = readWindowSql(window, "ref");
|
|
183
209
|
where.push("docs MATCH ?"); bind.push(match);
|
|
184
210
|
return (this.db.query(`SELECT ${columns} FROM docs WHERE ${where.join(" AND ")} ORDER BY candidate_position, candidate_id LIMIT ?`)
|
|
@@ -188,7 +214,7 @@ export class SearchIndex {
|
|
|
188
214
|
close(): void { this.db?.close(); }
|
|
189
215
|
}
|
|
190
216
|
|
|
191
|
-
const
|
|
217
|
+
const SCREENED_SUBSTRING_SCORE = rankedScoreSql("-1.0");
|
|
192
218
|
|
|
193
219
|
/** Screened query-local corpus in SQLite-owned TEMP storage, removed even when the process exits. */
|
|
194
220
|
export class ScreenedSearchIndex<T> {
|
|
@@ -204,8 +230,8 @@ export class ScreenedSearchIndex<T> {
|
|
|
204
230
|
if ((db.query("SELECT sqlite_compileoption_used('TEMP_STORE=3') AS memoryOnly").get() as { memoryOnly: number }).memoryOnly) throw Error("disk-backed search unavailable");
|
|
205
231
|
db.run("PRAGMA temp_store = FILE");
|
|
206
232
|
db.run(this.available
|
|
207
|
-
? "CREATE VIRTUAL TABLE temp.docs USING fts5(body, ref UNINDEXED, tier UNINDEXED, at UNINDEXED, payload UNINDEXED, expires UNINDEXED, event UNINDEXED, session UNINDEXED)"
|
|
208
|
-
: "CREATE TEMP TABLE docs (body TEXT, ref TEXT, tier TEXT, at TEXT, payload TEXT, expires REAL, event TEXT, session TEXT)");
|
|
233
|
+
? "CREATE VIRTUAL TABLE temp.docs USING fts5(body, hangul, ref UNINDEXED, tier UNINDEXED, at UNINDEXED, payload UNINDEXED, expires UNINDEXED, event UNINDEXED, session UNINDEXED)"
|
|
234
|
+
: "CREATE TEMP TABLE docs (body TEXT, hangul TEXT, ref TEXT, tier TEXT, at TEXT, payload TEXT, expires REAL, event TEXT, session TEXT)");
|
|
209
235
|
db.run("PRAGMA temp.cache_size = -2048");
|
|
210
236
|
// A platform spill minimum can exceed cache_size (macOS: 20,000 pages).
|
|
211
237
|
// Spill at the cache target so dirty TEMP pages cannot accumulate behind that minimum.
|
|
@@ -215,26 +241,27 @@ export class ScreenedSearchIndex<T> {
|
|
|
215
241
|
}
|
|
216
242
|
|
|
217
243
|
append(rows: readonly { body: string; ref: string; tier: string; at: string; value: T; expiresAt?: string | null; event?: string; session?: string }[]): void {
|
|
218
|
-
const insert = this.db.query("INSERT INTO docs (body, ref, tier, at, payload, expires, event, session) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
|
|
244
|
+
const insert = this.db.query("INSERT INTO docs (body, hangul, ref, tier, at, payload, expires, event, session) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
|
|
219
245
|
this.db.transaction(() => {
|
|
220
246
|
for (const row of rows) {
|
|
221
247
|
const deadline = row.expiresAt == null ? null : Date.parse(row.expiresAt);
|
|
222
248
|
// Invalid deadlines fail closed; this sentinel predates every representable Date.
|
|
223
|
-
insert.run(row.body, row.ref, row.tier, row.at, JSON.stringify(row.value), deadline !== null && !Number.isFinite(deadline) ? Number.MIN_SAFE_INTEGER : deadline, row.event ?? null, row.session ?? null);
|
|
249
|
+
insert.run(row.body, this.available && row.tier !== "capture" ? hangulShadow(row.body) : "", row.ref, row.tier, row.at, JSON.stringify(row.value), deadline !== null && !Number.isFinite(deadline) ? Number.MIN_SAFE_INTEGER : deadline, row.event ?? null, row.session ?? null);
|
|
224
250
|
}
|
|
225
251
|
})();
|
|
226
252
|
}
|
|
227
253
|
|
|
228
254
|
best(query: string, limit: number, now: number, useFts = this.available, explain = false): { value: T; score: number; scoreDetails?: ScoreFactors }[] {
|
|
229
|
-
|
|
230
|
-
|
|
255
|
+
const { match, rank } = curatedMatch(query);
|
|
256
|
+
if (useFts && !match) return [];
|
|
257
|
+
const score = useFts ? rankedScoreSql(rank) : SCREENED_SUBSTRING_SCORE;
|
|
231
258
|
const instant = new Date(now).toISOString();
|
|
232
259
|
const where = "WHERE (expires IS NULL OR expires > ?)" + (useFts ? " AND docs MATCH ?" : "");
|
|
233
|
-
const factors = explain ? rankedScoreSqlDetails(useFts ?
|
|
260
|
+
const factors = explain ? rankedScoreSqlDetails(useFts ? rank : "-1.0", useFts) : undefined;
|
|
234
261
|
const columns = factors ? `, ${factors.rawBm25Rank} AS rawBm25Rank, ${factors.tierFactor} AS tierFactor, ${factors.recencyFactor} AS recencyFactor` : "";
|
|
235
262
|
const statement = this.db.query(`SELECT payload, ${score} AS score${columns} FROM docs ${where} ORDER BY score DESC, ref LIMIT ?`);
|
|
236
|
-
const rows = (explain ? statement.all(instant, instant, now, ...(useFts ? [
|
|
237
|
-
: statement.all(instant, now, ...(useFts ? [
|
|
263
|
+
const rows = (explain ? statement.all(instant, instant, now, ...(useFts ? [match] : []), limit)
|
|
264
|
+
: statement.all(instant, now, ...(useFts ? [match] : []), limit)) as { payload: string; score: number; rawBm25Rank?: number | null; tierFactor?: number | null; recencyFactor?: number | null }[];
|
|
238
265
|
return rows.map(row => {
|
|
239
266
|
const hit: { value: T; score: number; scoreDetails?: ScoreFactors } = { value: JSON.parse(row.payload) as T, score: row.score };
|
|
240
267
|
if (explain) hit.scoreDetails = { rawBm25Rank: row.rawBm25Rank ?? null, tierFactor: row.tierFactor ?? null, recencyFactor: row.recencyFactor ?? null, finalScore: row.score, matchMode: useFts ? "fts5" : "substring" };
|
|
@@ -244,16 +271,17 @@ export class ScreenedSearchIndex<T> {
|
|
|
244
271
|
|
|
245
272
|
/** Weighted capture-only fill after the caller fixes the legacy noncapture slots. The caller has already screened every row before append. */
|
|
246
273
|
bestCaptureGroups(query: string, limit: number, now: number, useFts = this.available, explain = false): { value: T; score: number; scoreDetails?: ScoreFactors }[] {
|
|
247
|
-
|
|
248
|
-
|
|
274
|
+
const { match, rank } = curatedMatch(query, false);
|
|
275
|
+
if (!Number.isSafeInteger(limit) || limit < 1 || useFts && !match) return [];
|
|
276
|
+
const instant = new Date(now).toISOString(), score = useFts ? rankedScoreSql(rank) : SCREENED_SUBSTRING_SCORE;
|
|
249
277
|
const weight = captureEventWeightSql("event");
|
|
250
|
-
const factors = explain ? rankedScoreSqlDetails(useFts ?
|
|
278
|
+
const factors = explain ? rankedScoreSqlDetails(useFts ? rank : "-1.0", useFts) : undefined;
|
|
251
279
|
const columns = factors ? `, ${factors.rawBm25Rank} AS rawBm25Rank, ${factors.tierFactor} AS tierFactor, ${factors.recencyFactor} AS recencyFactor` : "";
|
|
252
280
|
const where = "WHERE tier = 'capture' AND (expires IS NULL OR expires > ?)" + (useFts ? " AND docs MATCH ?" : "");
|
|
253
281
|
const selected: { value: T; score: number; scoreDetails?: ScoreFactors }[] = [], groups = new Set<string>();
|
|
254
282
|
// Sort once in SQLite-owned TEMP storage, then stream past duplicate sessions without growing JS pages or re-sorting OFFSET windows.
|
|
255
283
|
const statement = this.db.query(`SELECT payload, ref, event, session, ${score} AS score${columns} FROM docs ${where} ORDER BY score * ${weight} DESC, ref`);
|
|
256
|
-
const orderedArgs = [instant, ...(explain ? [instant] : []), now, ...(useFts ? [
|
|
284
|
+
const orderedArgs = [instant, ...(explain ? [instant] : []), now, ...(useFts ? [match] : [])];
|
|
257
285
|
for (const row of statement.iterate(...orderedArgs) as Iterable<{ payload: string; ref: string; event: string | null; session: string | null; score: number; rawBm25Rank?: number | null; tierFactor?: number | null; recencyFactor?: number | null }>) {
|
|
258
286
|
const session = typeof row.session === "string" && /^[a-f0-9]{16}$/.test(row.session) ? row.session : undefined;
|
|
259
287
|
const group = session ? `session:${session}` : `row:${row.ref}`;
|
package/src/memory/shard.ts
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import { readActivePlacementBinding } from "./sync-placement-active.ts";
|
|
1
|
+
import { provePlacementShards, readActivePlacementBinding } from "./sync-placement-active.ts";
|
|
2
2
|
import { readEffectiveRealmInventory } from "./sync-placement-realm-effective.ts";
|
|
3
|
-
import {
|
|
4
|
-
import { assertPlacementRuntime, doctorScratchBinding, doctorScratchInventory, SyncPlacementRuntimeError } from "./sync-placement-guard.ts";
|
|
3
|
+
import { assertPlacementRuntime, doctorScratchBinding, doctorScratchInventory, readPlacementV3Marker, SyncPlacementRuntimeError } from "./sync-placement-guard.ts";
|
|
5
4
|
import { assertNoPublicPruneIntent, readPublicPruneView } from "./public-prune-view.ts";
|
|
6
5
|
import { indexFileName } from "./index-file.ts";
|
|
6
|
+
import { searchFileName } from "./search-fts.ts";
|
|
7
7
|
import { createHash, randomBytes } from "node:crypto";
|
|
8
8
|
import { existsSync, linkSync, lstatSync, mkdirSync, opendirSync, readFileSync, rmSync, writeFileSync, type Dir } from "node:fs";
|
|
9
9
|
import { join } from "node:path";
|
|
@@ -116,11 +116,14 @@ export function legacyShardMarkerShape(value: unknown): boolean {
|
|
|
116
116
|
&& typeof row.phase === "string" && ["captured", "active"].includes(row.phase) && typeof row.selectorRevision === "string"
|
|
117
117
|
&& (row.schema !== SHARDED_V2_SCHEMA || !Object.keys(row).some(key => !(SHARDED_V2_FIELDS as readonly string[]).includes(key)));
|
|
118
118
|
}
|
|
119
|
+
function readShardMarker(path: string): Record<string, unknown> | undefined {
|
|
120
|
+
return readPlacementV3Marker(path) ?? (readProfileJSON(path) as Record<string, unknown> | undefined);
|
|
121
|
+
}
|
|
122
|
+
|
|
119
123
|
function shardJournal(memoryDir: string): ShardedJournal {
|
|
120
|
-
const value =
|
|
124
|
+
const value = readShardMarker(join(memoryDir, "shards.json"));
|
|
121
125
|
if (value?.schema === "agent-mem.shards/v3") {
|
|
122
|
-
|
|
123
|
-
return validatePlacementShards(value, profile) as unknown as ShardedJournal;
|
|
126
|
+
return provePlacementShards(value, readShardMarker(join(memoryDir, "profile.json"))).shards as unknown as ShardedJournal;
|
|
124
127
|
}
|
|
125
128
|
if (!value || (value.schema !== SHARDED_SCHEMA && value.schema !== SHARDED_V2_SCHEMA) || !validGeneration(value.generation) || value.phase !== "active" || typeof value.selectorRevision !== "string") throw new Error("no active curated shard migration");
|
|
126
129
|
if (value.schema === SHARDED_V2_SCHEMA && Object.keys(value).some(key => !(SHARDED_V2_FIELDS as readonly string[]).includes(key))) throw new Error("unsupported curated shard view");
|
|
@@ -148,7 +151,7 @@ function shardSnapshot(memoryDir: string, deadline: number) {
|
|
|
148
151
|
journal = current; continue;
|
|
149
152
|
}
|
|
150
153
|
const current = shardJournal(memoryDir);
|
|
151
|
-
if (canonicalJSON(current) !== canonicalJSON(journal)) {
|
|
154
|
+
if (current !== journal && canonicalJSON(current) !== canonicalJSON(journal)) {
|
|
152
155
|
if (!compatibleShardAdvance(journal, current)) throw new Error("curated shard selector changed");
|
|
153
156
|
journal = current; continue;
|
|
154
157
|
}
|
|
@@ -206,18 +209,18 @@ export function assertCuratedShardLayout(memoryDir: string, opts: { project?: st
|
|
|
206
209
|
check(dir, true);
|
|
207
210
|
for (const folder of ["log", "local", "legacy", "legacy/log", "legacy/local", "legacy-main", "legacy-main/log", "legacy-main/local"]) check(join(dir, folder), true);
|
|
208
211
|
for (const name of ["project.json", "generation.json", "generation-seal.json", "migration-sources.json", "machine.json", "legacy/machine.json", "legacy-main/machine.json", "prune-translations.jsonl"]) check(join(dir, name), false);
|
|
209
|
-
for (const database of new Set(["index.db", "index-v2.db", indexFileName(false), indexFileName(true), "search.db", "mutation-lock.db"])) for (const suffix of ["", "-wal", "-shm", "-journal"]) check(join(dir, database + suffix), false);
|
|
212
|
+
for (const database of new Set(["index.db", "index-v2.db", indexFileName(false), indexFileName(true), "search.db", searchFileName(), "mutation-lock.db"])) for (const suffix of ["", "-wal", "-shm", "-journal"]) check(join(dir, database + suffix), false);
|
|
210
213
|
}
|
|
211
214
|
/** Fixed curated paths cannot redirect writes into legacy inputs or another shard.
|
|
212
215
|
* ponytail: same-user concurrent parent replacement needs descriptor-relative opens; fixed preflight does not claim that fence.
|
|
213
216
|
*/
|
|
214
217
|
export function assertCuratedShardPaths(memoryDir: string, opts: { project?: string; user?: boolean }, origin: "cwd binding" | "remote" | "local binding" = "local binding"): void {
|
|
215
218
|
assertPlacementRuntime(memoryDir);
|
|
216
|
-
const selector =
|
|
219
|
+
const selector = readShardMarker(join(memoryDir, "profile.json"));
|
|
217
220
|
let recheckInventory: (() => void) | undefined;
|
|
218
221
|
if (selector?.schema === "agent-mem.profile/v3") {
|
|
219
222
|
const scratch = doctorScratchBinding(memoryDir);
|
|
220
|
-
const active = scratch ?? readActivePlacementBinding(memoryDir, selector,
|
|
223
|
+
const active = scratch ?? readActivePlacementBinding(memoryDir, selector, readShardMarker(join(memoryDir, "shards.json")));
|
|
221
224
|
const keyHash = opts.user ? undefined : createHash("sha256").update(opts.project!).digest("hex");
|
|
222
225
|
// An appended same-epoch extension is part of the inventory a curated write may open (#448); a realm it does not name stays refused.
|
|
223
226
|
const inventory = scratch ? doctorScratchInventory(memoryDir) : active ? readEffectiveRealmInventory(memoryDir, active) : undefined;
|
|
@@ -246,13 +249,13 @@ function inventoryView(inventory: RealmInventory | undefined): PlacementRealmVie
|
|
|
246
249
|
export type PlacementRealmView = { readonly kind: "none" } | { readonly kind: "inventory"; admitted(keyHash: string): boolean; assertCurrent(): void };
|
|
247
250
|
|
|
248
251
|
export function placementRealmView(base: string): PlacementRealmView | undefined {
|
|
249
|
-
let selector:
|
|
250
|
-
try { selector =
|
|
252
|
+
let selector: Record<string, unknown> | undefined;
|
|
253
|
+
try { selector = readShardMarker(join(base, "profile.json")); } catch { return undefined; }
|
|
251
254
|
if (selector?.schema !== "agent-mem.profile/v3") return { kind: "none" };
|
|
252
255
|
// No fallback to `none` here: a malformed v3 home is unproved, not ungated.
|
|
253
256
|
try {
|
|
254
257
|
const scratch = doctorScratchBinding(base);
|
|
255
|
-
const active = scratch ?? readActivePlacementBinding(base, selector,
|
|
258
|
+
const active = scratch ?? readActivePlacementBinding(base, selector, readShardMarker(join(base, "shards.json")));
|
|
256
259
|
return inventoryView(scratch ? doctorScratchInventory(base) : active ? readEffectiveRealmInventory(base, active) : undefined);
|
|
257
260
|
} catch { return undefined; }
|
|
258
261
|
}
|
|
@@ -360,7 +363,7 @@ export function resolveShardProfile(memoryDir: string, opts: { project?: string;
|
|
|
360
363
|
const shardMachine = readProfileJSON(join(dir, "machine.json"), 4096) as { id?: unknown } | undefined;
|
|
361
364
|
if (typeof rootMachine?.id !== "string" || !/^[a-f0-9]{16}$/.test(rootMachine.id) || rootMachine.id !== shardMachine?.id) throw new Error("curated shard machine identity mismatch");
|
|
362
365
|
const final = shardSnapshot(memoryDir, deadline), selector = final.selector;
|
|
363
|
-
if (canonicalJSON(final.journal) !== canonicalJSON(initial.journal) && !compatibleShardAdvance(initial.journal, final.journal)
|
|
366
|
+
if (final.journal !== initial.journal && canonicalJSON(final.journal) !== canonicalJSON(initial.journal) && !compatibleShardAdvance(initial.journal, final.journal)
|
|
364
367
|
|| selector.revision !== final.journal.selectorRevision) throw new Error("curated shard selector changed; resume or inspect migration state");
|
|
365
368
|
if (selector.selector?.schema === "agent-mem.profile/v2" || selector.selector?.schema === "agent-mem.profile/v3") readPublicPruneView(memoryDir, selector.selector.pruneInputSetHash, generation, deadline);
|
|
366
369
|
const legacyMainHome = join(dir, "legacy-main");
|
package/src/memory/store.ts
CHANGED
|
@@ -22,7 +22,7 @@ import { assertProjectActive, lifecycleResolver } from "./lifecycle.ts";
|
|
|
22
22
|
export { machineId, type Machine } from "./machine.ts";
|
|
23
23
|
import { rankedScore, rankedScoreDetails, unrankedScoreDetails, type SearchScoreDetails } from "./search-score.ts";
|
|
24
24
|
export type { SearchScoreDetails } from "./search-score.ts";
|
|
25
|
-
import { readWindowSql, readRef, type ReadWindow, type ReadRef, SearchIndex, captureSearch } from "./search-fts.ts";
|
|
25
|
+
import { readWindowSql, readRef, type ReadWindow, type ReadRef, SearchIndex, captureSearch, searchFileName } from "./search-fts.ts";
|
|
26
26
|
import { assertCuratedShardPaths, ensureShardDescriptor, readShardDescriptor, readShardedSelection, aliasedKeys, effectiveAliases, resolveAlias, resolveShardProfile, shardDir, shardKeyHash, shardMachineDir, userShardDir } from "./shard.ts";
|
|
27
27
|
import { readCaptureConfig, type CaptureRow } from "./capture.ts";
|
|
28
28
|
import { assertSharedV1Op } from "./ops-contract.ts";
|
|
@@ -323,8 +323,10 @@ export class MemoryStore {
|
|
|
323
323
|
db.run("CREATE INDEX IF NOT EXISTS ops_settlement ON ops(target) WHERE op = 'settle'");
|
|
324
324
|
this.db = db;
|
|
325
325
|
this.mutationDb = openedMutation = mutationDatabase(this.dir);
|
|
326
|
-
// One derived FTS copy per profile
|
|
327
|
-
|
|
326
|
+
// One derived FTS copy per profile and schema. Other generations and older readers keep their own files.
|
|
327
|
+
const searchDir = this.profile.sharded ? this.dir : home;
|
|
328
|
+
const searchGeneration = this.profile.kind === "generation" && !this.profile.sharded ? this.profile.generation : undefined;
|
|
329
|
+
this.searchIndex = openedSearch = new SearchIndex(this.recapScratch ? ":memory:" : join(searchDir, searchFileName(searchGeneration)));
|
|
328
330
|
this.memoryBaseDir = home;
|
|
329
331
|
try { chmodSync(indexFile, 0o600); } catch { /* best effort */ }
|
|
330
332
|
if (this.profile.kind === "generation") this.generationIndex = new GenerationIndex({ profile: this.profile, db, now: this.now,
|
|
@@ -131,15 +131,19 @@ const LOCAL = /^(usage:|another (sync|memory mutation|generation|shard sync)|no
|
|
|
131
131
|
export function syncOutcome(error: string | undefined, cause?: StopCause): SyncOutcome {
|
|
132
132
|
if (error === undefined) return "ok";
|
|
133
133
|
// A run its person ended (Ctrl-C, a closing terminal) is not a failure of the remote: the same Ctrl-C reads "fetch failed" or "stopped" depending on which step it hit, so the cause,
|
|
134
|
-
// not the text, decides. Only the deadline
|
|
134
|
+
// not the text, decides. Only the deadline stays a failure to back off from, and the CLI holds it at one step (recordSyncAttempt `hold`).
|
|
135
135
|
if (cause === "person") return "local";
|
|
136
136
|
return LOCAL.test(error.replace(/^amem sync: /, "")) ? "local" : "failed";
|
|
137
137
|
}
|
|
138
138
|
|
|
139
|
-
/**
|
|
140
|
-
|
|
139
|
+
/**
|
|
140
|
+
* Records one attempt. A stamp that cannot be written never fails the sync it describes. `hold` (#657) is a run the `--if-due` deadline
|
|
141
|
+
* stopped: it waits at least one backoff step (15 minutes) but never doubles the wait, so a slow local run is not treated as a failing remote.
|
|
142
|
+
*/
|
|
143
|
+
export function recordSyncAttempt(home: string, ok: boolean, at: number, hold = false): SyncState {
|
|
141
144
|
const prior = readSyncState(home), when = new Date(at).toISOString();
|
|
142
|
-
const
|
|
145
|
+
const failures = ok ? 0 : hold ? Math.max(prior.failures, 1) : Math.min(prior.failures + 1, MAX_FAILURES);
|
|
146
|
+
const next: SyncState = { lastAttemptAt: when, lastOkAt: ok ? when : prior.lastOkAt, failures };
|
|
143
147
|
const file = join(home, SYNC_STATE_FILE), temp = `${file}.${process.pid}.tmp`;
|
|
144
148
|
try {
|
|
145
149
|
mkdirSync(home, { recursive: true, mode: 0o700 });
|
|
@@ -8,21 +8,29 @@ import { assertNoLiveReaders } from "./reader-lease.ts";
|
|
|
8
8
|
import { createPlacementActivationOwner } from "./sync-placement-activation-proof.ts";
|
|
9
9
|
/** #578 Q1: a checkpoint fence never refuses for readers; its `busy` means a placement sync, admission or renewal holds a lock. */
|
|
10
10
|
export const PLACEMENT_CHECKPOINT_BUSY_MESSAGE = "Sync placement checkpoint is busy: a placement sync, admission or renewal holds its lock; wait for it to finish (amem sync --status shows recorded operations), then rerun the same checkpoint command.";
|
|
11
|
-
|
|
12
|
-
export
|
|
13
|
-
|
|
14
|
-
|
|
11
|
+
type PlacementMutationSurface = "checkpoint" | "admit" | "renewal";
|
|
12
|
+
export class PlacementInventoryFenceError extends Error {
|
|
13
|
+
constructor(readonly causeClass: "readers" | "busy", surface?: PlacementMutationSurface) {
|
|
14
|
+
const message = causeClass === "readers"
|
|
15
|
+
? "Sync placement migration is blocked by live readers; close cooperating readers/writers, then run amem migrate --sync-placement --dry-run before retrying."
|
|
16
|
+
: surface === "checkpoint" ? PLACEMENT_CHECKPOINT_BUSY_MESSAGE
|
|
17
|
+
: surface === "admit" ? "Sync placement realm admission is busy; wait for the operation holding its lock (amem sync --status), then run amem migrate --sync-placement --admit <project> --dry-run."
|
|
18
|
+
: surface === "renewal" ? "Sync placement writer renewal is busy; wait for the operation holding its lock (amem sync --status), then run amem migrate --sync-placement --dry-run before retrying."
|
|
19
|
+
: "Sync placement migration is busy; close cooperating readers/writers, then run amem migrate --sync-placement --dry-run before retrying.";
|
|
20
|
+
super(message);
|
|
21
|
+
this.name = "PlacementInventoryFenceError";
|
|
22
|
+
}
|
|
15
23
|
}
|
|
16
|
-
type FenceWork<T
|
|
17
|
-
async function withFences<T>(home:string,directories:readonly string[],
|
|
18
|
-
const fail=(cause:"readers"|"busy"):never=>{throw new PlacementInventoryFenceError(cause
|
|
24
|
+
type FenceWork<T> = (mutation: MutationHandle, owner: ReturnType<typeof createPlacementActivationOwner>) => Promise<T>;
|
|
25
|
+
async function withFences<T>(home: string, directories: readonly string[], work: FenceWork<T>, surface?: PlacementMutationSurface): Promise<T> {
|
|
26
|
+
const fail = (cause: "readers" | "busy"): never => { throw new PlacementInventoryFenceError(cause, surface); };
|
|
19
27
|
return withProfileLock(home,async()=>{
|
|
20
28
|
const releases:(()=>void)[]=[];
|
|
21
29
|
try {
|
|
22
30
|
const transports=["shard-sync","shard-sync-placement"].map(name=>join(home,name)).filter(dir=>lstatSync(dir,{throwIfNoEntry:false})!==undefined);
|
|
23
31
|
const dirs=[...new Set([home,...directories,...transports])].sort();let mutation:MutationHandle|undefined;
|
|
24
32
|
for(const dir of dirs){
|
|
25
|
-
if(
|
|
33
|
+
if(surface === undefined){try{assertNoLiveReaders(dir,{includeShards:true});}catch{fail("readers");}}
|
|
26
34
|
const handle=acquireMutation(dir);if(!handle)fail("busy");releases.push(handle!);if(dir===home)mutation=handle!;
|
|
27
35
|
}
|
|
28
36
|
if(!mutation)fail("busy");
|
|
@@ -31,16 +39,16 @@ async function withFences<T>(home:string,directories:readonly string[],options:{
|
|
|
31
39
|
}finally{for(const release of releases.reverse())release();}
|
|
32
40
|
});
|
|
33
41
|
}
|
|
34
|
-
/**
|
|
35
|
-
export function withPlacementActivationFences<T>(home:string,directories:readonly string[],work:FenceWork<T
|
|
36
|
-
return withFences(home,directories,
|
|
42
|
+
/** Initial activation changes the markers that readers bind to when opening a store. */
|
|
43
|
+
export function withPlacementActivationFences<T>(home: string, directories: readonly string[], work: FenceWork<T>): Promise<T> {
|
|
44
|
+
return withFences(home, directories, work);
|
|
37
45
|
}
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
export function withPlacementCheckpointFences<T>(home:string,directories:readonly string[],work:FenceWork<T>):Promise<T> {
|
|
45
|
-
return
|
|
46
|
+
|
|
47
|
+
/** Active placement mutations leave store bindings intact. The profile lock still blocks new readers. */
|
|
48
|
+
export function withPlacementMutationFences<T>(home: string, directories: readonly string[], work: FenceWork<T>, options: { surface: PlacementMutationSurface }): Promise<T> {
|
|
49
|
+
return withFences(home, directories, work, options.surface);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export function withPlacementCheckpointFences<T>(home: string, directories: readonly string[], work: FenceWork<T>): Promise<T> {
|
|
53
|
+
return withPlacementMutationFences(home, directories, work, { surface: "checkpoint" });
|
|
46
54
|
}
|