@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
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import { validatePlacementBaseV2 } from "./sync-placement-format.ts";
|
|
2
|
+
import { hashJSON } from "./generation.ts";
|
|
3
|
+
import { openPurgeMatcher, previewPurgeMatches, type PurgeSidecarMatch, type PurgeSidecarSource } from "./purge-matcher.ts";
|
|
4
|
+
import { previewSyncPlacementSources, type PlacementSourcePreview } from "./sync-placement-capture.ts";
|
|
5
|
+
import { placementCheckpointPending } from "./sync-placement-checkpoint-storage.ts";
|
|
6
|
+
import { readEffectiveSyncPlacementWriters } from "./sync-placement-effective-writers.ts";
|
|
7
|
+
import { readPlacementJournal, placementWriterJournalToken } from "./sync-placement-journal-storage.ts";
|
|
8
|
+
|
|
9
|
+
const ID = /^[a-f0-9]{32}$/, HASH = /^[a-f0-9]{64}$/;
|
|
10
|
+
export const PURGE_PLAN_MAX_BYTES = 256 * 1024;
|
|
11
|
+
const schema = "agent-mem.purge-plan/v1";
|
|
12
|
+
const unavailable = (): never => { throw new Error("Purge preview cannot verify the active split placement sources; check amem doctor and resolve pending sync or migration work."); };
|
|
13
|
+
const ambiguous = (): never => { throw new Error(/* refusal-by-design: operator-knowledge a person must reconcile the authored provenance or preserved proof. */ "Purge removal would lose an unrelated prune proof or has ambiguous row provenance; review docs/purge-design.md."); };
|
|
14
|
+
|
|
15
|
+
type PurgeRow = { id: string; rowHash: string };
|
|
16
|
+
export interface PurgePreview {
|
|
17
|
+
schema: typeof schema;
|
|
18
|
+
entryId: string;
|
|
19
|
+
source: { epoch: string; generation: string; binding: string; writerRevision: string; journal: string };
|
|
20
|
+
remove: PurgeRow[];
|
|
21
|
+
sidecars: { matches: PurgeSidecarMatch[]; sources: PurgeSidecarSource[] } | null;
|
|
22
|
+
unreached: readonly string[];
|
|
23
|
+
next: string;
|
|
24
|
+
seal: string;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function closure(source: PlacementSourcePreview, entryId: string): PurgeRow[] {
|
|
28
|
+
const rows = new Map<string, { rowHash: string; target: boolean }>();
|
|
29
|
+
const edges = new Map<string, Set<string>>();
|
|
30
|
+
const prunes: { id: string; targets: string[] }[] = [];
|
|
31
|
+
const track = (id: string, rowHash: string, target: boolean, refs: readonly (string | undefined)[]) => {
|
|
32
|
+
const prior = rows.get(id);
|
|
33
|
+
if (prior && (prior.rowHash !== rowHash || prior.target !== target)) return ambiguous();
|
|
34
|
+
rows.set(id, { rowHash, target });
|
|
35
|
+
for (const ref of refs) if (ref && ID.test(ref)) {
|
|
36
|
+
let dependents = edges.get(ref);
|
|
37
|
+
if (!dependents) edges.set(ref, dependents = new Set());
|
|
38
|
+
dependents.add(id);
|
|
39
|
+
}
|
|
40
|
+
};
|
|
41
|
+
for (const { row, key } of source.rows.values()) {
|
|
42
|
+
// A separately authored successor survives when only its optional supersedes pointer names the target.
|
|
43
|
+
const refs = row.op === "note" ? [row.promotedFrom] : row.op === "goal" ? row.dependsOn
|
|
44
|
+
: [row.target, row.op === "supersede" ? row.by : row.op === "suggest" ? row.by?.split(":").at(-1) : undefined];
|
|
45
|
+
track(row.id, key.rowHash, row.op === "note" || row.op === "goal", refs);
|
|
46
|
+
}
|
|
47
|
+
for (const { row, key } of source.specialRows.values()) {
|
|
48
|
+
if (row.op === "vault_link") track(row.id, key.rowHash, false, [row.target]);
|
|
49
|
+
else {
|
|
50
|
+
track(row.id, key.rowHash, false, row.targets.flatMap(target => [target.id, target.basis.id]));
|
|
51
|
+
prunes.push({ id: row.id, targets: row.targets.map(target => target.id) });
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
if (!rows.get(entryId)?.target) throw new Error("The full purge ID was not found in the admitted authored sources; check the entry with amem show.");
|
|
55
|
+
const queue = [entryId], removed = new Set(queue);
|
|
56
|
+
for (const id of queue) for (const dependent of edges.get(id) ?? []) if (!removed.has(dependent)) {
|
|
57
|
+
removed.add(dependent);
|
|
58
|
+
queue.push(dependent);
|
|
59
|
+
}
|
|
60
|
+
// Without a replacement proof, dropping a multi-target witness could reveal an unrelated entry.
|
|
61
|
+
if (prunes.some(prune => removed.has(prune.id) && prune.targets.some(target => !removed.has(target)))) return ambiguous();
|
|
62
|
+
return [...removed].sort().map(id => ({ id, rowHash: rows.get(id)!.rowHash }));
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export function planPurge(home: string, input: { entryId: string; matchFile?: string }): PurgePreview {
|
|
66
|
+
if (!ID.test(input.entryId)) throw new Error("Purge preview requires a full 32-character entry ID; check the identifier with amem show.");
|
|
67
|
+
const source = previewSyncPlacementSources(home), epoch = source.activeHead;
|
|
68
|
+
if (!epoch || placementCheckpointPending(source.home, epoch)) return unavailable();
|
|
69
|
+
const journalToken = placementWriterJournalToken(source.home, epoch);
|
|
70
|
+
const journal = readPlacementJournal(source.home, epoch);
|
|
71
|
+
if (journal.pending || journal.publicationReservation) return unavailable();
|
|
72
|
+
const writers = readEffectiveSyncPlacementWriters(source.home);
|
|
73
|
+
const remove = closure(source, input.entryId);
|
|
74
|
+
const sidecars = input.matchFile === undefined ? null : previewPurgeMatches(source.home, validatePlacementBaseV2(source.base.profile, source.base.shards).shards.machine.id, openPurgeMatcher(input.matchFile));
|
|
75
|
+
source.assertSourcesUnchanged();
|
|
76
|
+
writers.assertCurrent();
|
|
77
|
+
if (placementWriterJournalToken(source.home, epoch) !== journalToken) return unavailable();
|
|
78
|
+
const body: Omit<PurgePreview, "seal"> = {
|
|
79
|
+
schema, entryId: input.entryId,
|
|
80
|
+
source: { epoch, generation: journal.epoch.generation, binding: hashJSON([source.markerHash, source.base.sourceHash, source.base.aliasesHash, source.base.homeHash, source.base.policyHash]),
|
|
81
|
+
writerRevision: writers.revisionHash, journal: journal.headHash },
|
|
82
|
+
remove, sidecars,
|
|
83
|
+
unreached: ["old remote and retained history", "other machines", "legacy and historical copies", "work lists", "spools", "exports and backups",
|
|
84
|
+
...(sidecars ? ["capture and candidates outside the selected matches"] : ["capture and candidates"])],
|
|
85
|
+
next: "Rotate or revoke the leaked credential.",
|
|
86
|
+
};
|
|
87
|
+
const sealed = { ...body, seal: hashJSON(body) };
|
|
88
|
+
if (Buffer.byteLength(JSON.stringify(sealed, null, 2)) + 1 > PURGE_PLAN_MAX_BYTES || !HASH.test(sealed.source.writerRevision)) return unavailable();
|
|
89
|
+
return sealed;
|
|
90
|
+
}
|
|
@@ -0,0 +1,244 @@
|
|
|
1
|
+
// SQLITE_OPEN_URI explicitly: Bun's `{ readonly: true }` omits it, and a Linux SQLite built without SQLITE_USE_URI would read the URI as a file name.
|
|
2
|
+
import { constants as sqlite, Database } from "bun:sqlite";
|
|
3
|
+
import { createHash } from "node:crypto";
|
|
4
|
+
import { closeSync, constants, existsSync, fstatSync, lstatSync, openSync, readdirSync, readSync } from "node:fs";
|
|
5
|
+
import { join } from "node:path";
|
|
6
|
+
import { assertFormatFloor } from "./formats.ts";
|
|
7
|
+
import { INDEX_VERSION, indexFileName } from "./index-file.ts";
|
|
8
|
+
import { lifecycleResolver } from "./lifecycle.ts";
|
|
9
|
+
import type { MemoryPolicy } from "./policy.ts";
|
|
10
|
+
import { assertNoPendingPurge } from "./purge-intent.ts";
|
|
11
|
+
import { readProfileJSON, readSelector } from "./generation.ts";
|
|
12
|
+
import { readShardDescriptor, readShardedSelection, resolveShardProfile, shardDir, shardKeyHash, userShardDir } from "./shard.ts";
|
|
13
|
+
import { DEFAULT_TTL_MS, PROMOTED_KINDS, UNSETTLED_MS, type View } from "./store.ts";
|
|
14
|
+
import { foldLiveState } from "./live-state.ts";
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* #680: a read-only curated lookup by id for read-only hosts (vault-mem `evidence --cross-store`). It opens nothing writable: no mkdir, chmod,
|
|
18
|
+
* schema write, reader lease, machine id, index refresh or rebuild. Each index is opened `readonly`, or `immutable=1` only when no WAL frames
|
|
19
|
+
* are pending; an index that is absent, of another version or behind its logs makes the answer `incomplete` instead of being rebuilt.
|
|
20
|
+
* Liveness is the store's own fold (`foldLiveState`), so a returned view is what `MemoryStore.get` shows; a policy-declined id is simply absent.
|
|
21
|
+
*/
|
|
22
|
+
export interface ReadCuratedEntriesOptions { policy: MemoryPolicy; includeArchived?: boolean; maxRows?: number }
|
|
23
|
+
export interface ReadCuratedEntriesResult { entries: Map<string, View>; incomplete: boolean }
|
|
24
|
+
|
|
25
|
+
export const READ_CURATED_MAX_IDS = 256;
|
|
26
|
+
const MAX_SHARDS = 64;
|
|
27
|
+
|
|
28
|
+
/** Bytes hashed to prove an index current; beyond it the index counts as stale (the bound the plan review set). */
|
|
29
|
+
const FRESHNESS_HASH_BYTES = 16 * 1024 * 1024;
|
|
30
|
+
|
|
31
|
+
interface Source { dir: string; key?: string; generation: boolean; foreign: boolean; /** Shared-v1 holds every project in one store: rows are filtered by their project's lifecycle. */ admits?: (project: string) => boolean }
|
|
32
|
+
|
|
33
|
+
export async function readCuratedEntries(base: string, ids: readonly string[], options: ReadCuratedEntriesOptions): Promise<ReadCuratedEntriesResult> {
|
|
34
|
+
if (!options || typeof options.policy?.screen !== "function") throw new Error(/* refusal-by-design: operator-knowledge a host programming error, fixed in the calling code */ "readCuratedEntries needs a policy");
|
|
35
|
+
const maxRows = options.maxRows ?? READ_CURATED_MAX_IDS;
|
|
36
|
+
if (!Number.isSafeInteger(maxRows) || maxRows < 1 || maxRows > READ_CURATED_MAX_IDS) throw new Error(/* refusal-by-design: operator-knowledge a host programming error, fixed in the calling code */ `maxRows must be 1..${READ_CURATED_MAX_IDS}`);
|
|
37
|
+
if (!Array.isArray(ids) || ids.length > READ_CURATED_MAX_IDS) throw new Error(/* refusal-by-design: operator-knowledge a host programming error, fixed in the calling code */ `at most ${READ_CURATED_MAX_IDS} ids`);
|
|
38
|
+
const wanted = [...new Set(ids.map(id => typeof id === "string" ? id.replace(/^mem:/, "") : "").filter(id => /^[A-Za-z0-9_-]{1,128}$/.test(id)))].slice(0, maxRows);
|
|
39
|
+
const entries = new Map<string, View>();
|
|
40
|
+
let incomplete = wanted.length < new Set(ids).size && ids.length > maxRows;
|
|
41
|
+
// Gates first: a purge barrier or a curated format floor refuses before any store file is opened.
|
|
42
|
+
assertNoPendingPurge(base);
|
|
43
|
+
assertFormatFloor(base, "curated");
|
|
44
|
+
if (!wanted.length) return { entries, incomplete };
|
|
45
|
+
const sources = curatedSources(base, options.includeArchived === true);
|
|
46
|
+
if (sources.incomplete) incomplete = true;
|
|
47
|
+
const budget = { bytes: FRESHNESS_HASH_BYTES };
|
|
48
|
+
const found = new Map<string, View>();
|
|
49
|
+
for (const source of sources.list) {
|
|
50
|
+
const missing = wanted.filter(id => !found.has(id));
|
|
51
|
+
if (!missing.length) break;
|
|
52
|
+
const read = readSource(source, missing, budget);
|
|
53
|
+
if (read === undefined) { incomplete = true; continue; }
|
|
54
|
+
for (const view of read) if (!found.has(view.id)) found.set(view.id, view);
|
|
55
|
+
}
|
|
56
|
+
for (const id of wanted) {
|
|
57
|
+
const view = found.get(id);
|
|
58
|
+
// Screened exactly as returned; a declined view is absent, indistinguishable from a missing one.
|
|
59
|
+
if (view && await options.policy.screen(view)) entries.set(id, view);
|
|
60
|
+
}
|
|
61
|
+
return { entries, incomplete };
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** The curated stores of a home, in lookup order, from read-only metadata only. */
|
|
65
|
+
function curatedSources(base: string, includeArchived: boolean): { list: Source[]; incomplete: boolean } {
|
|
66
|
+
if (!existsSync(join(base, "shards.json"))) {
|
|
67
|
+
// Shared-v1 (or a generation profile in the home itself): one store.
|
|
68
|
+
const selected = readSelector(base).selector;
|
|
69
|
+
if (selected?.kind === "generation" && selected.generation) {
|
|
70
|
+
const state = lifecycleResolver(base);
|
|
71
|
+
const admits = (project: string) => { const lifecycle = state(project); return lifecycle === "active" || lifecycle === "archived" && includeArchived; };
|
|
72
|
+
return { list: [{ dir: join(base, "generations", selected.generation), generation: true, foreign: false, admits }], incomplete: false };
|
|
73
|
+
}
|
|
74
|
+
if (!existsSync(join(base, "log")) && !existsSync(join(base, "local"))) return { list: [], incomplete: false };
|
|
75
|
+
const state = lifecycleResolver(base);
|
|
76
|
+
const admits = (project: string) => { const lifecycle = state(project); return lifecycle === "active" || lifecycle === "archived" && includeArchived; };
|
|
77
|
+
return { list: [{ dir: base, generation: false, foreign: false, admits }], incomplete: false };
|
|
78
|
+
}
|
|
79
|
+
readShardedSelection(base);
|
|
80
|
+
const state = lifecycleResolver(base), list: Source[] = [];
|
|
81
|
+
let incomplete = false;
|
|
82
|
+
const userDir = userShardDir(base);
|
|
83
|
+
if (existsSync(join(userDir, "generation.json"))) {
|
|
84
|
+
try { const profile = resolveShardProfile(base, { user: true }); list.push({ dir: userDir, generation: true, foreign: !!profile.foreignPruneFormat }); } catch { incomplete = true; }
|
|
85
|
+
}
|
|
86
|
+
let hashes: string[] = [];
|
|
87
|
+
try { hashes = readdirSync(join(base, "projects"), { withFileTypes: true }).filter(e => e.isDirectory() && /^[0-9a-f]{16}$/.test(e.name)).map(e => e.name).sort(); } catch { /* no shards */ }
|
|
88
|
+
for (const hash of hashes) {
|
|
89
|
+
const descriptor = readShardDescriptor(base, hash);
|
|
90
|
+
if (!descriptor || shardKeyHash(descriptor.key) !== hash) continue;
|
|
91
|
+
const lifecycle = state(descriptor.key);
|
|
92
|
+
if (lifecycle === "forgotten" || lifecycle === "archived" && !includeArchived) continue;
|
|
93
|
+
const dir = shardDir(base, descriptor.key);
|
|
94
|
+
if (!existsSync(join(dir, "generation.json"))) continue; // capture-only: no curated store
|
|
95
|
+
if (list.length >= MAX_SHARDS) { incomplete = true; break; }
|
|
96
|
+
try { const profile = resolveShardProfile(base, { project: descriptor.key }); list.push({ dir, key: descriptor.key, generation: true, foreign: !!profile.foreignPruneFormat }); }
|
|
97
|
+
catch { incomplete = true; }
|
|
98
|
+
}
|
|
99
|
+
return { list, incomplete };
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* A handle on an existing index that writes nothing, or undefined. Even a `readonly` connection to a WAL database writes its `-shm` index, so the
|
|
104
|
+
* only zero-write form is `immutable=1`, and that is sound only while no WAL frames are pending. With frames pending the index cannot be read
|
|
105
|
+
* without a write, so the caller reports `incomplete` (#680 measured exactly that `-shm` change).
|
|
106
|
+
*/
|
|
107
|
+
function openIndex(file: string): Database | undefined {
|
|
108
|
+
if (!lstatSync(file, { throwIfNoEntry: false })?.isFile()) return undefined;
|
|
109
|
+
const wal = lstatSync(`${file}-wal`, { throwIfNoEntry: false });
|
|
110
|
+
if (wal && !(wal.isFile() && wal.size === 0)) return undefined;
|
|
111
|
+
let db: Database | undefined;
|
|
112
|
+
try {
|
|
113
|
+
db = new Database(`file:${encodeURI(file).replace(/\?/g, "%3F").replace(/#/g, "%23")}?immutable=1`, sqlite.SQLITE_OPEN_READONLY | sqlite.SQLITE_OPEN_URI);
|
|
114
|
+
db.query("SELECT 1 FROM sqlite_master LIMIT 1").get();
|
|
115
|
+
return db;
|
|
116
|
+
} catch { try { db?.close(); } catch { /* nothing to close */ } return undefined; }
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
const segmentFiles = (dir: string): string[] => ["log", "local"].flatMap(folder => {
|
|
120
|
+
try { return readdirSync(join(dir, folder)).filter(name => name.endsWith(".jsonl")).sort().map(name => `${folder}/${name}`); } catch { return []; }
|
|
121
|
+
});
|
|
122
|
+
|
|
123
|
+
/** The sha256 of a file's first `length` bytes, read through one non-following descriptor; undefined when it cannot be proved within budget. */
|
|
124
|
+
function prefixHash(file: string, length: number, budget: { bytes: number }): string | undefined {
|
|
125
|
+
if (length > budget.bytes) return undefined;
|
|
126
|
+
let fd: number;
|
|
127
|
+
try { fd = openSync(file, constants.O_RDONLY | constants.O_NOFOLLOW); } catch { return undefined; }
|
|
128
|
+
try {
|
|
129
|
+
const stat = fstatSync(fd);
|
|
130
|
+
if (!stat.isFile() || stat.size < length) return undefined;
|
|
131
|
+
const bytes = Buffer.alloc(length); let at = 0;
|
|
132
|
+
while (at < length) { const n = readSync(fd, bytes, at, length - at, at); if (n <= 0) return undefined; at += n; }
|
|
133
|
+
budget.bytes -= length;
|
|
134
|
+
return createHash("sha256").update(bytes).digest("hex");
|
|
135
|
+
} finally { closeSync(fd); }
|
|
136
|
+
}
|
|
137
|
+
/** The complete-line length of a segment now; a trailing partial line is not yet indexable, so it does not make the index stale. */
|
|
138
|
+
function completeLength(file: string): number | undefined {
|
|
139
|
+
try {
|
|
140
|
+
const stat = lstatSync(file);
|
|
141
|
+
if (!stat.isFile() || stat.isSymbolicLink()) return undefined;
|
|
142
|
+
if (stat.size === 0) return 0;
|
|
143
|
+
const fd = openSync(file, constants.O_RDONLY | constants.O_NOFOLLOW);
|
|
144
|
+
try {
|
|
145
|
+
// Scan back for the last newline in bounded steps.
|
|
146
|
+
const chunk = Buffer.alloc(65536);
|
|
147
|
+
for (let end = stat.size; end > 0;) {
|
|
148
|
+
const start = Math.max(0, end - chunk.length), n = readSync(fd, chunk, 0, end - start, start);
|
|
149
|
+
const at = chunk.subarray(0, n).lastIndexOf(10);
|
|
150
|
+
if (at >= 0) return start + at + 1;
|
|
151
|
+
end = start;
|
|
152
|
+
}
|
|
153
|
+
return 0;
|
|
154
|
+
} finally { closeSync(fd); }
|
|
155
|
+
} catch { return undefined; }
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/**
|
|
159
|
+
* Proves the index holds every complete line of the store's own segments, without reading the segments into it: the version, each segment's
|
|
160
|
+
* recorded offset equal to its complete length, and the recorded prefix hash equal to the bytes on disk. Any doubt means stale.
|
|
161
|
+
*/
|
|
162
|
+
function indexFresh(db: Database, source: Source, budget: { bytes: number }): boolean {
|
|
163
|
+
try {
|
|
164
|
+
if ((db.query("PRAGMA user_version").get() as { user_version: number }).user_version !== INDEX_VERSION) return false;
|
|
165
|
+
const files = segmentFiles(source.dir);
|
|
166
|
+
const recorded = source.generation
|
|
167
|
+
? db.query("SELECT path AS file, offset, hash FROM generation_segments WHERE source = 'generation'").all() as { file: string; offset: number; hash: string | null }[]
|
|
168
|
+
: db.query("SELECT s.file, s.offset, h.hash FROM segments s LEFT JOIN heads h ON h.file = s.file").all() as { file: string; offset: number; hash: string | null }[];
|
|
169
|
+
const byFile = new Map(recorded.map(row => [row.file, row]));
|
|
170
|
+
if (recorded.some(row => !files.includes(row.file))) return false;
|
|
171
|
+
for (const file of files) {
|
|
172
|
+
const length = completeLength(join(source.dir, file));
|
|
173
|
+
if (length === undefined) return false;
|
|
174
|
+
const row = byFile.get(file);
|
|
175
|
+
if (!row) { if (length > 0) return false; continue; }
|
|
176
|
+
if (row.offset !== length) return false;
|
|
177
|
+
if (length > 0 && (row.hash === null || prefixHash(join(source.dir, file), length, budget) !== row.hash)) return false;
|
|
178
|
+
}
|
|
179
|
+
// Imported (legacy) sources of a generation shard: their checkpoints must still cover the sealed migration inputs.
|
|
180
|
+
if (source.generation) {
|
|
181
|
+
const sealed = readProfileJSON(join(source.dir, "migration-sources.json")) as { sources?: { source?: string; path?: string; offset?: number; hash?: string }[] } | undefined;
|
|
182
|
+
const imported = new Map((db.query("SELECT source, path, offset, hash FROM generation_segments WHERE source != 'generation'").all() as { source: string; path: string; offset: number; hash: string }[])
|
|
183
|
+
.map(row => [`${row.source}:${row.path}`, row]));
|
|
184
|
+
for (const input of sealed?.sources ?? []) {
|
|
185
|
+
const row = imported.get(`${input.source}:${input.path}`);
|
|
186
|
+
if (!row || typeof input.offset !== "number" || row.offset < input.offset) return false;
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
return true;
|
|
190
|
+
} catch { return false; }
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/** The identity of the index and its WAL: `immutable=1` takes no lock, so a read is trusted only when this is the same before and after it. */
|
|
194
|
+
function indexStamp(file: string): string {
|
|
195
|
+
const stamp = (path: string) => { const stat = lstatSync(path, { bigint: true, throwIfNoEntry: false }); return stat ? [stat.dev, stat.ino, stat.size, stat.mtimeNs, stat.ctimeNs].map(String).join(":") : "absent"; };
|
|
196
|
+
return `${stamp(file)}|${stamp(`${file}-wal`)}`;
|
|
197
|
+
}
|
|
198
|
+
/** Test seam (#680 review): runs between the read and its recheck, so a test can write in the gap. */
|
|
199
|
+
let afterRead: ((file: string) => void) | undefined;
|
|
200
|
+
export function setReadCuratedAfterReadHook(hook: ((file: string) => void) | undefined): void { afterRead = hook; }
|
|
201
|
+
|
|
202
|
+
function readSource(source: Source, ids: readonly string[], budget: { bytes: number }): View[] | undefined {
|
|
203
|
+
const file = join(source.dir, indexFileName(source.foreign));
|
|
204
|
+
const before = indexStamp(file);
|
|
205
|
+
const db = openIndex(file);
|
|
206
|
+
if (!db) return undefined;
|
|
207
|
+
let views: View[] | undefined;
|
|
208
|
+
try {
|
|
209
|
+
if (!indexFresh(db, source, budget)) return undefined;
|
|
210
|
+
views = readViews(db, source, ids);
|
|
211
|
+
} catch { return undefined; }
|
|
212
|
+
finally { db.close(); }
|
|
213
|
+
afterRead?.(file);
|
|
214
|
+
// Without locking, a writer that started meanwhile may have checkpointed into the main file: any change to it or its WAL drops this read.
|
|
215
|
+
const wal = lstatSync(`${file}-wal`, { throwIfNoEntry: false });
|
|
216
|
+
if (wal && wal.size > 0 || indexStamp(file) !== before) return undefined;
|
|
217
|
+
return views;
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
function readViews(db: Database, source: Source, ids: readonly string[]): View[] {
|
|
221
|
+
// One read transaction: metadata, ops and bodies describe one snapshot.
|
|
222
|
+
return db.transaction(() => {
|
|
223
|
+
const rows = db.query("SELECT id, at, tier, kind, task, expires, supersedes, promoted_from FROM entries").all() as Record<string, string | null>[];
|
|
224
|
+
const ops = db.query("SELECT id, op, at, target, by FROM ops ORDER BY at, id").all() as { id: string; op: string; at: string; target: string; by: string | null }[];
|
|
225
|
+
const pruned = source.generation ? new Set((db.query("SELECT id FROM generation_targets").all() as { id: string }[]).map(row => row.id)) : undefined;
|
|
226
|
+
const realms = source.generation ? new Map((db.query("SELECT id, own, legacy FROM generation_rows").all() as { id: string; own: number; legacy: number }[]).map(row => [row.id, row])) : undefined;
|
|
227
|
+
const now = Date.now();
|
|
228
|
+
const state = foldLiveState({ now, ttl: DEFAULT_TTL_MS, unsettledMs: UNSETTLED_MS, promotedKinds: PROMOTED_KINDS, rows, ops, realms, pruned });
|
|
229
|
+
const bodies = db.query("SELECT * FROM entries WHERE id IN (SELECT value FROM json_each(?))").all(JSON.stringify(ids)) as Record<string, string | null>[];
|
|
230
|
+
const out: View[] = [];
|
|
231
|
+
for (const r of bodies) {
|
|
232
|
+
const id = r.id!;
|
|
233
|
+
if (pruned?.has(id) || state.forgotten.has(id) || (r.promoted_from && state.forgotten.has(r.promoted_from)) || state.promoted.has(id)) continue;
|
|
234
|
+
if (state.superseded.has(id)) continue;
|
|
235
|
+
if (source.admits && r.scope !== "shared" && !source.admits(r.project!)) continue;
|
|
236
|
+
const expiresAt = state.expiry(r);
|
|
237
|
+
if (expiresAt !== null && Date.parse(expiresAt) <= now) continue;
|
|
238
|
+
out.push({ id, at: r.at!, machine: r.machine!, project: r.project!, scope: r.scope as View["scope"], tier: (state.demoted.has(id) ? "short" : r.tier) as View["tier"], kind: r.kind as View["kind"], peer: r.peer!,
|
|
239
|
+
title: r.title ?? null, text: r.text!, task: r.task ?? null, about: JSON.parse(r.about!), source: r.source!, supersededBy: null, supersedes: state.supersedes.get(id) ?? [],
|
|
240
|
+
promotedFrom: r.promoted_from ?? null, expiresAt, local: r.tier === "short" });
|
|
241
|
+
}
|
|
242
|
+
return out;
|
|
243
|
+
}).deferred();
|
|
244
|
+
}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { assertNoPendingPurge } from "./purge-intent.ts";
|
|
1
2
|
import { lstatSync, mkdirSync, readdirSync, rmSync } from "node:fs";
|
|
2
3
|
import { basename, join } from "node:path";
|
|
3
4
|
import { readProfileJSON, writeProfileJSON } from "./generation.ts";
|
|
@@ -83,6 +84,7 @@ function removeGoneLeases(memoryDir: string, scope: LeaseScope, own: string): vo
|
|
|
83
84
|
}
|
|
84
85
|
|
|
85
86
|
function admitReader(memoryDir: string): void {
|
|
87
|
+
assertNoPendingPurge(memoryDir);
|
|
86
88
|
// The profile lock is created under the same reader admission fence, then held across migration awaits.
|
|
87
89
|
// Even a malformed or stale marker refuses admission; only the profile-lock owner may reclaim it.
|
|
88
90
|
try {
|
|
@@ -108,6 +110,7 @@ export function registerReaderLease(memoryDir: string, options: { busyTimeoutMs?
|
|
|
108
110
|
// Host-only: the supplied hash must already describe this process's pinned native ps identity.
|
|
109
111
|
const signature = inherited ?? options.signature ?? processSignature(pid);
|
|
110
112
|
if (!signature) throw new Error("cannot establish reader lease identity");
|
|
113
|
+
assertNoPendingPurge(memoryDir);
|
|
111
114
|
mkdirSync(memoryDir, { recursive: true, mode: 0o700 });
|
|
112
115
|
// Pin the map key and renewal/verify/close closures to one physical home, not its caller spelling.
|
|
113
116
|
memoryDir = realPath(memoryDir);
|
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}`;
|
|
@@ -442,7 +442,7 @@ function lockDestinations(memoryDir: string, destinations: Iterable<Destination>
|
|
|
442
442
|
try {
|
|
443
443
|
for (const dir of [...destinations].map(destination => destinationDir(memoryDir, destination)).sort()) {
|
|
444
444
|
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
445
|
-
const release = acquireMutation(dir);
|
|
445
|
+
const release = acquireMutation(dir, memoryDir);
|
|
446
446
|
if (!release) throw new Error("curated shard writer lock is busy; retry the shard migration once that writer finishes");
|
|
447
447
|
releases.push(release);
|
|
448
448
|
}
|
|
@@ -524,13 +524,13 @@ export async function migrateShards(options: ShardMigrationOptions): Promise<Sha
|
|
|
524
524
|
const initial = preflight(memoryDir, options, undefined, options.mode === "dry-run");
|
|
525
525
|
if (options.mode === "dry-run") return { mode: options.mode, generation: initial.generation, active: initial.previous?.phase === "active", counts: counts(initial.plan), ...refusalSummary(initial.plan), consequence: CONSEQUENCE, ...removalEvidence(initial.previous) };
|
|
526
526
|
const result = await withProfileLock(memoryDir, async () => {
|
|
527
|
-
const release = acquireMutation(memoryDir);
|
|
527
|
+
const release = acquireMutation(memoryDir, memoryDir);
|
|
528
528
|
if (!release) throw new Error("legacy mutation lock is busy");
|
|
529
529
|
let releaseOwn: (() => void) | undefined;
|
|
530
530
|
let checked: ReturnType<typeof preflight>;
|
|
531
531
|
try {
|
|
532
532
|
if (initial.sourceGeneration) {
|
|
533
|
-
releaseOwn = acquireMutation(generationDir(memoryDir, initial.sourceGeneration));
|
|
533
|
+
releaseOwn = acquireMutation(generationDir(memoryDir, initial.sourceGeneration), memoryDir);
|
|
534
534
|
if (!releaseOwn) throw new Error("selected generation mutation lock is busy");
|
|
535
535
|
}
|
|
536
536
|
checked = preflight(memoryDir, options, initial.generation);
|
package/src/memory/shard-sync.ts
CHANGED
|
@@ -566,7 +566,7 @@ export async function syncShardedMemory(store: MemoryStore, opts: SyncOptions =
|
|
|
566
566
|
if (await (opts.visibility ?? remoteVisibility)(url) !== "private") return fail("shard sync requires positively verified private remote visibility");
|
|
567
567
|
check();
|
|
568
568
|
if (!existsSync(root)) mkdirSync(root, { recursive: true, mode: 0o700 }); directory(root);
|
|
569
|
-
releaseTransport = acquireMutation(root); if (!releaseTransport) return fail("another shard sync mutation is running");
|
|
569
|
+
releaseTransport = acquireMutation(root, store.profile.home); if (!releaseTransport) return fail("another shard sync mutation is running");
|
|
570
570
|
releaseSync = generationSyncLock(root); if (!releaseSync) return fail("another shard sync is running or its owner is unknown");
|
|
571
571
|
if (!existing) {
|
|
572
572
|
// No worktree or index from the legacy home is ever inherited by this private cache.
|
|
@@ -578,12 +578,12 @@ export async function syncShardedMemory(store: MemoryStore, opts: SyncOptions =
|
|
|
578
578
|
const fetchURLs = (await required(["remote", "get-url", "--all", "origin"], "shard sync fetch destination unavailable")).split("\n");
|
|
579
579
|
const pushURLs = (await required(["remote", "get-url", "--push", "--all", "origin"], "shard sync push destination unavailable")).split("\n");
|
|
580
580
|
if (fetchURLs.length !== 1 || fetchURLs[0] !== url || pushURLs.length !== 1 || pushURLs[0] !== url) refuse("shard sync refuses differing or multiple remote destinations");
|
|
581
|
-
homeMutation = v2 ? acquireMutation(store.profile.home) : undefined;
|
|
581
|
+
homeMutation = v2 ? acquireMutation(store.profile.home, store.profile.home) : undefined;
|
|
582
582
|
if (v2 && !homeMutation) refuse("another home selection mutation is running");
|
|
583
583
|
if (homeMutation) releases.push(homeMutation);
|
|
584
584
|
// Cooperating source writers stay excluded across remote reads and final imports. No nested withMutation calls.
|
|
585
585
|
for (const target of [...targets].sort((a, b) => a.store.dir < b.store.dir ? -1 : 1)) {
|
|
586
|
-
const release = acquireMutation(target.store.dir); if (!release) refuse(`${shardSyncLabel(target.realm)}: another source mutation is running`); releases.push(release); target.mutation=release;
|
|
586
|
+
const release = acquireMutation(target.store.dir, store.profile.home); if (!release) refuse(`${shardSyncLabel(target.realm)}: another source mutation is running`); releases.push(release); target.mutation=release;
|
|
587
587
|
if (v2) ensurePublisherBoundary(target.store.profile,release);
|
|
588
588
|
}
|
|
589
589
|
releaseCurated = store.beginCuratedCacheUpdate();
|