@staix/agent-mem 0.42.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 +1 -1
- package/package.json +2 -2
- package/src/cli.ts +32 -3
- package/src/commands-table.ts +6 -2
- package/src/index.ts +2 -0
- package/src/ingest-hosts.ts +440 -0
- package/src/memory/candidates.ts +12 -0
- package/src/memory/capture.ts +23 -0
- package/src/memory/doctor.ts +8 -5
- package/src/memory/formats-raise.ts +1 -1
- package/src/memory/formats.ts +11 -0
- 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/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/shard-migration.ts +3 -3
- package/src/memory/shard-sync.ts +3 -3
- package/src/memory/store.ts +4 -69
- package/src/memory/sync-placement-activation-locks.ts +12 -3
- package/src/memory/sync-placement-active.ts +2 -0
- package/src/memory/sync-placement-guard.ts +2 -0
- package/src/memory/sync-placement-journal.ts +1 -1
- package/src/memory/sync-placement-transport.ts +8 -3
- package/src/memory/sync.ts +3 -2
- package/src/setup-console.ts +1 -1
- package/src/setup-drift.ts +4 -3
- package/src/setup-owned.ts +9 -1
- package/src/setup.ts +36 -6
|
@@ -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);
|
|
@@ -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();
|
package/src/memory/store.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { assertNoPendingPurge } from "./purge-intent.ts";
|
|
1
2
|
import { RECAP_SCRATCH } from "./recap-scratch.ts";
|
|
2
3
|
import { buildCuratedBriefCache, buildPreferenceBriefCache } from "../brief-curated.ts";
|
|
3
4
|
import { PREFERENCE_SLOT } from "./preference-brief.ts";
|
|
@@ -35,6 +36,7 @@ import { isDeepStrictEqual } from "node:util";
|
|
|
35
36
|
import { registerReaderLease, type ReaderLease } from "./reader-lease.ts";
|
|
36
37
|
import { recordBriefPublicationFailure } from "./metrics.ts";
|
|
37
38
|
import { groupByTask, taskGroupKey } from "./task-group.ts";
|
|
39
|
+
import { foldLiveState } from "./live-state.ts";
|
|
38
40
|
|
|
39
41
|
/**
|
|
40
42
|
* #258: the hub's own memory. Append-only JSONL logs are the truth: `log/<machine>.jsonl` holds long-term entries and
|
|
@@ -434,7 +436,7 @@ export class MemoryStore {
|
|
|
434
436
|
|
|
435
437
|
private withMutation<T>(work: () => T): T {
|
|
436
438
|
const release = this.deferCuratedPublication();
|
|
437
|
-
try { return this.mutationDb.transaction(work).immediate(); }
|
|
439
|
+
try { return this.mutationDb.transaction(() => { assertNoPendingPurge(this.profile.home); return work(); }).immediate(); }
|
|
438
440
|
finally { release(); }
|
|
439
441
|
}
|
|
440
442
|
|
|
@@ -1215,74 +1217,7 @@ export class MemoryStore {
|
|
|
1215
1217
|
: "SELECT * FROM entries") as Record<string, string | null>[];
|
|
1216
1218
|
const ops = projection?.ops ?? this.readRows("SELECT id, op, at, target, by FROM ops ORDER BY at, id") as { id: string; op: string; at: string; target: string; by: string | null }[];
|
|
1217
1219
|
const realms = projection ? projection.realms : this.generationIndex ? new Map((this.readRows("SELECT id,own,legacy FROM generation_rows") as { id: string; own: number; legacy: number }[]).map(row => [row.id, row])) : undefined;
|
|
1218
|
-
const
|
|
1219
|
-
const forgotten = new Set([...ops.filter((o) => o.op === "forget").map((o) => o.target), ...(projection?.forgotten ?? [])]);
|
|
1220
|
-
// Deadlines were fixed when the entries were written, so every process (whatever its own TTL) prunes the same rows.
|
|
1221
|
-
const deadline = (o: { at: string; by: string | null }) => o.by && !Number.isNaN(Date.parse(o.by)) ? o.by : new Date(Date.parse(o.at) + this.ttl).toISOString();
|
|
1222
|
-
const demoted = new Map(ops.filter((o) => o.op === "demote").map((o) => [o.target, deadline(o)]));
|
|
1223
|
-
const settled = new Map<string, string>();
|
|
1224
|
-
const settlementKey = (id: string, task: string) => born ? `${born.has(id)}:${task}` : task;
|
|
1225
|
-
for (const o of ops) if (o.op === "settle") {
|
|
1226
|
-
const source = realms?.get(o.id);
|
|
1227
|
-
const keys = !realms ? [o.target] : [
|
|
1228
|
-
...(source?.own ? [`true:${o.target}`] : []),
|
|
1229
|
-
...(source?.legacy || !source?.own ? [`false:${o.target}`] : []),
|
|
1230
|
-
];
|
|
1231
|
-
for (const key of keys) if (!settled.has(key)) settled.set(key, deadline(o));
|
|
1232
|
-
}
|
|
1233
|
-
const superseded = new Map<string, string>(), supersededAt = new Map<string, string>();
|
|
1234
|
-
// Relations from ops and from notes' own `supersedes` fold together by write time (then id): the latest intent wins.
|
|
1235
|
-
const relate = (old: string, newer: string, when: string) => { if (!(when < (supersededAt.get(old) ?? ""))) { superseded.set(old, newer); supersededAt.set(old, when); } };
|
|
1236
|
-
for (const o of ops) if (o.op === "supersede" && o.by) relate(o.target, o.by, `${o.at} ${o.by}`);
|
|
1237
|
-
const promoted = new Set<string>();
|
|
1238
|
-
for (const r of rows) { if (r.supersedes) relate(r.supersedes, r.id!, `${r.at} ${r.id}`); if (r.promoted_from) promoted.add(r.promoted_from); }
|
|
1239
|
-
const expiry = (r: Record<string, string | null>): string | null => {
|
|
1240
|
-
const id = r.id!;
|
|
1241
|
-
if ((demoted.has(id) ? "short" : r.tier) !== "short") return null;
|
|
1242
|
-
// A decision, contract or fail of a settled task not yet copied to long-term waits for its promotion, never expires
|
|
1243
|
-
// first; a note saved short-term after the settlement carries its own deadline and stays short-term.
|
|
1244
|
-
// A superseded one is held too: if its replacement goes, it shows again, and a rebuild must find it the same way.
|
|
1245
|
-
const taskDeadline = r.task ? settled.get(settlementKey(id, r.task)) : undefined;
|
|
1246
|
-
if (r.tier === "short" && !demoted.has(id) && !r.expires && taskDeadline && PROMOTED_KINDS.includes(r.kind as Kind)) return null;
|
|
1247
|
-
// A deadline written into the note (no task, a late note, an explicit short horizon) is its own, whatever the task does.
|
|
1248
|
-
return demoted.get(id) ?? r.expires ?? (r.task ? taskDeadline ?? new Date(Date.parse(r.at!) + UNSETTLED_MS).toISOString() : new Date(Date.parse(r.at!) + this.ttl).toISOString());
|
|
1249
|
-
};
|
|
1250
|
-
// A newer entry that was forgotten, expired or pruned no longer replaces anything: the older one shows again. A
|
|
1251
|
-
// promoted source lives on as its copy.
|
|
1252
|
-
const byId = new Map(rows.map((r) => [r.id!, r]));
|
|
1253
|
-
const copyOf = new Map(rows.filter((r) => r.promoted_from).map((r) => [r.promoted_from!, r.id!]));
|
|
1254
|
-
const gone = (id: string): boolean => {
|
|
1255
|
-
if (pruned?.has(id)) return true;
|
|
1256
|
-
const r = byId.get(id);
|
|
1257
|
-
if (!r || forgotten.has(id) || (r.promoted_from && forgotten.has(r.promoted_from))) return true;
|
|
1258
|
-
const copy = copyOf.get(id);
|
|
1259
|
-
if (copy) return gone(copy);
|
|
1260
|
-
const e = expiry(r);
|
|
1261
|
-
return e !== null && Date.parse(e) <= now;
|
|
1262
|
-
};
|
|
1263
|
-
// A promoted entry lives on as its copy, on either side of a relation: a promoted replacement still replaces, and a
|
|
1264
|
-
// promoted entry that was replaced stays replaced.
|
|
1265
|
-
const last = (id: string) => { let to = id; for (let c = copyOf.get(to); c; c = copyOf.get(to)) to = c; return to; };
|
|
1266
|
-
for (const [old, newer] of [...superseded]) {
|
|
1267
|
-
superseded.set(old, last(newer));
|
|
1268
|
-
const copy = last(old);
|
|
1269
|
-
if (copy !== old && !superseded.has(copy)) { superseded.set(copy, last(newer)); supersededAt.set(copy, supersededAt.get(old)!); }
|
|
1270
|
-
}
|
|
1271
|
-
for (const [old, newer] of superseded) if (gone(newer)) superseded.delete(old);
|
|
1272
|
-
// Supersessions made apart (two processes, two machines) can close a cycle that would hide every entry in it: the
|
|
1273
|
-
// earliest relation in the cycle gives way, so the latest intent stands, the same in every process. Each entry has
|
|
1274
|
-
// one replacement, so a chain holds at most one cycle.
|
|
1275
|
-
const when = (id: string) => `${supersededAt.get(id) ?? ""} ${id}`; // write time, then ids: the same in every process
|
|
1276
|
-
for (const start of [...superseded.keys()]) {
|
|
1277
|
-
const seen: string[] = [];
|
|
1278
|
-
for (let at: string | undefined = start; at !== undefined && superseded.has(at); at = superseded.get(at)) {
|
|
1279
|
-
const i = seen.indexOf(at);
|
|
1280
|
-
if (i >= 0) { superseded.delete(seen.slice(i).reduce((x, y) => (when(y) < when(x) ? y : x))); break; }
|
|
1281
|
-
seen.push(at);
|
|
1282
|
-
}
|
|
1283
|
-
}
|
|
1284
|
-
const supersedes = new Map<string, string[]>(); // the reverse: what each newer entry replaced
|
|
1285
|
-
for (const [old, newer] of superseded) supersedes.set(newer, [...(supersedes.get(newer) ?? []), old]);
|
|
1220
|
+
const { forgotten, demoted, promoted, superseded, supersedes, expiry } = foldLiveState({ now, ttl: this.ttl, unsettledMs: UNSETTLED_MS, promotedKinds: PROMOTED_KINDS, rows, ops, realms, pruned, ...(projection ? { forgotten: projection.forgotten } : {}) });
|
|
1286
1221
|
let candidates = rows;
|
|
1287
1222
|
if (selecting) {
|
|
1288
1223
|
const hidden: string[] = [], expiredIds: string[] = [];
|
|
@@ -1,8 +1,9 @@
|
|
|
1
|
+
import { PURGE_PUBLICATION_BLOCK_FILE, purgePending } from "./purge-intent.ts";
|
|
1
2
|
/** Shared person-migration fences. No serialized value grants ownership. */
|
|
2
3
|
import { lstatSync } from "node:fs";
|
|
3
4
|
import { join } from "node:path";
|
|
4
|
-
import { withProfileLock } from "./generation.ts";
|
|
5
|
-
import { acquireMutation, type MutationHandle } from "./mutation.ts";
|
|
5
|
+
import { withProfileLock, writeProfileJSON } from "./generation.ts";
|
|
6
|
+
import { acquireMutation, assertMutationHandle, type MutationHandle } from "./mutation.ts";
|
|
6
7
|
import { generationSyncLock } from "./generation-sync.ts";
|
|
7
8
|
import { assertNoLiveReaders } from "./reader-lease.ts";
|
|
8
9
|
import { createPlacementActivationOwner } from "./sync-placement-activation-proof.ts";
|
|
@@ -31,7 +32,7 @@ async function withFences<T>(home: string, directories: readonly string[], work:
|
|
|
31
32
|
const dirs=[...new Set([home,...directories,...transports])].sort();let mutation:MutationHandle|undefined;
|
|
32
33
|
for(const dir of dirs){
|
|
33
34
|
if(surface === undefined){try{assertNoLiveReaders(dir,{includeShards:true});}catch{fail("readers");}}
|
|
34
|
-
const handle=acquireMutation(dir);if(!handle)fail("busy");releases.push(handle!);if(dir===home)mutation=handle!;
|
|
35
|
+
const handle=acquireMutation(dir, home);if(!handle)fail("busy");releases.push(handle!);if(dir===home)mutation=handle!;
|
|
35
36
|
}
|
|
36
37
|
if(!mutation)fail("busy");
|
|
37
38
|
for(const dir of [home,...transports]){const release=generationSyncLock(dir);if(!release)fail("busy");releases.push(release!);}
|
|
@@ -52,3 +53,11 @@ export function withPlacementMutationFences<T>(home: string, directories: readon
|
|
|
52
53
|
export function withPlacementCheckpointFences<T>(home: string, directories: readonly string[], work: FenceWork<T>): Promise<T> {
|
|
53
54
|
return withPlacementMutationFences(home, directories, work, { surface: "checkpoint" });
|
|
54
55
|
}
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
/** Install before admitting the successor. The home-wide block survives intent cleanup. */
|
|
59
|
+
export function writePurgePublicationBlock(home: string, mutation: MutationHandle): void {
|
|
60
|
+
assertMutationHandle(mutation, home);
|
|
61
|
+
if (!purgePending(home)) throw new Error("Purge publication block requires a pending local cut; use amem doctor to check the home before retrying.");
|
|
62
|
+
writeProfileJSON(join(home, PURGE_PUBLICATION_BLOCK_FILE), { schema: "agent-mem.purge-publication-block/v1" });
|
|
63
|
+
}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { assertNoPendingPurge } from "./purge-intent.ts";
|
|
1
2
|
import { freezeMetadata, isMetadataSnapshot, sameMetadataStamp } from "./profile-marker-cache.ts";
|
|
2
3
|
/** Metadata-only v3 admission. Publication still requires the complete journal/source/policy proof. */
|
|
3
4
|
import { closeSync, constants, fstatSync, lstatSync, openSync, readSync, type BigIntStats } from "node:fs";
|
|
@@ -84,6 +85,7 @@ const snapshotBindings = new WeakMap<object, { key: string; profileInput: object
|
|
|
84
85
|
let valueBinding: { key: string; value: BindingProof } | undefined;
|
|
85
86
|
/** No mutation/reader registration/index open. Missing preparation is distinct from malformed retained evidence. */
|
|
86
87
|
export function readActivePlacementBinding(homeInput: string, profileInput: unknown, shardsInput: unknown): ActivePlacementBinding | undefined {
|
|
88
|
+
assertNoPendingPurge(homeInput);
|
|
87
89
|
const { profile, shards } = provePlacementShards(shardsInput, profileInput);
|
|
88
90
|
const home = realPath(homeInput), root = lstatSync(home, { bigint: true }); owned(root, true);
|
|
89
91
|
const stampKey = () => {
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { PURGE_PENDING, purgePending } from "./purge-intent.ts";
|
|
1
2
|
import { metadataReader, sameMetadataStamp } from "./profile-marker-cache.ts";
|
|
2
3
|
import { provePlacementShards, readActivePlacementBinding, type ActivePlacementBinding } from "./sync-placement-active.ts";
|
|
3
4
|
import { readEffectiveRealmInventory, type EffectiveRealmInventory } from "./sync-placement-realm-effective.ts";
|
|
@@ -176,6 +177,7 @@ function placementFencePresent(home: string): boolean {
|
|
|
176
177
|
* The v3 publication coordinator separately proves the complete journal, selected sources and policy. */
|
|
177
178
|
export function placementRuntimeRefusal(home: string, bound?: Pick<BoundProfile,"kind"|"sharded"|"generation"|"publicationFormat"|"placementHead">): string | undefined {
|
|
178
179
|
if (doctorScratchBinding(home)) return undefined;
|
|
180
|
+
if (purgePending(home)) return PURGE_PENDING;
|
|
179
181
|
try { const fenced = placementFencePresent(home), pending = placementActivationPending(home), markers = runtimeMarkers(home);
|
|
180
182
|
const refusal = placementMarkerRefusal(markers.profile, markers.shards);
|
|
181
183
|
if (refusal === PLACEMENT_STAGE1_REFUSAL) {
|
|
@@ -48,7 +48,7 @@ function fenced<T>(capture: PlacementCapture, work: (homeMutation: MutationHandl
|
|
|
48
48
|
try {
|
|
49
49
|
let homeMutation: MutationHandle | undefined;
|
|
50
50
|
for (const dir of capture.directories) {
|
|
51
|
-
const handle = acquireMutation(dir); if (!handle) fail("busy");
|
|
51
|
+
const handle = acquireMutation(dir, capture.home); if (!handle) fail("busy");
|
|
52
52
|
handles.push(handle); if (dir === capture.home) homeMutation = handle;
|
|
53
53
|
}
|
|
54
54
|
capture.assertCurrent(); if (!homeMutation) fail();
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { purgePublicationRefusal } from "./purge-intent.ts";
|
|
1
2
|
/** Activated placement transport. The public sync entrypoint owns dispatch; this module never activates a profile. */
|
|
2
3
|
import { createHash, randomBytes } from "node:crypto";
|
|
3
4
|
import { constants, closeSync, existsSync, fsyncSync, lstatSync, mkdirSync, openSync, readdirSync, rmSync, writeSync, type BigIntStats } from "node:fs";
|
|
@@ -91,6 +92,8 @@ function directory(file: string): void { const s = lstatSync(file); if (!s.isDir
|
|
|
91
92
|
function emptyHistory(): ShardHistory { return { rows: new Map(), files: new Map(), origins: new Map(), manifests: new Map(), version: "v3" }; }
|
|
92
93
|
/** Internal phase observer is a fault seam, not part of SyncOptions or the package barrel. */
|
|
93
94
|
export async function syncPlacementMemory(store: MemoryStore, opts: SyncOptions = {}, phase?: Phase, testOnlyError?: (error:unknown)=>void, testOnlyClock?: () => number, targets?: readonly MemoryStore[]): Promise<SyncResult> {
|
|
95
|
+
const refusal = purgePublicationRefusal(store.profile.home);
|
|
96
|
+
if (refusal) return { ok: false, pushed: false, entries: 0, error: refusal };
|
|
94
97
|
return new PlacementTransport(store, opts, phase, testOnlyError, testOnlyClock, targets).run();
|
|
95
98
|
}
|
|
96
99
|
|
|
@@ -206,7 +209,7 @@ export async function prepareRemotePlacementRealm(homeInput: string, project: st
|
|
|
206
209
|
catch { return refuse("source-selection"); }
|
|
207
210
|
ctx.check();
|
|
208
211
|
};
|
|
209
|
-
check(); releaseRoot = acquireMutation(ctx.root); if (!releaseRoot) return refuse("lock");
|
|
212
|
+
check(); releaseRoot = acquireMutation(ctx.root, ctx.home); if (!releaseRoot) return refuse("lock");
|
|
210
213
|
releaseSync = generationSyncLock(ctx.root); if (!releaseSync) return refuse("lock");
|
|
211
214
|
const gitBytes = async (args: string[], max: number) => { check(); const result = await generationSyncGitBytes(ctx.root, ctx.args(args), opts.signal, undefined, max); check(); if (result.code !== 0) return refuse("remote"); return Buffer.from(result.out); };
|
|
212
215
|
const advertised = await gitBytes(["ls-remote", "--refs", ctx.url, ref], 256);
|
|
@@ -364,10 +367,10 @@ class PlacementTransport {
|
|
|
364
367
|
if (await this.call(() => placementVisibility(this.opts, this.url, this.opts.visibility ?? remoteVisibility)) !== "private") refuse("remote");
|
|
365
368
|
await yieldTurn(); this.prove(); // a host callout ends any reusable proof
|
|
366
369
|
if (!existsSync(this.root)) mkdirSync(this.root, { mode: 0o700 });
|
|
367
|
-
const transport = acquireMutation(this.root); if (!transport) refuse("lock"); this.rootMutation=transport; this.releases.push(transport);
|
|
370
|
+
const transport = acquireMutation(this.root, this.home); if (!transport) refuse("lock"); this.rootMutation=transport; this.releases.push(transport);
|
|
368
371
|
const sync = generationSyncLock(this.root); if (!sync) refuse("lock"); this.releases.push(sync); this.syncLockHeld=true;
|
|
369
372
|
for (const dir of [...new Set([this.home, ...this.targets.map(target => target.store.dir)])].sort()) {
|
|
370
|
-
const handle = acquireMutation(dir); if (!handle) refuse("lock"); this.releases.push(handle); if (dir === this.home) this.homeMutation = handle;
|
|
373
|
+
const handle = acquireMutation(dir, this.home); if (!handle) refuse("lock"); this.releases.push(handle); if (dir === this.home) this.homeMutation = handle;
|
|
371
374
|
for (const target of this.targets) if (target.store.dir === dir) target.mutation = handle;
|
|
372
375
|
}
|
|
373
376
|
// #450: each explicitly selected realm tracks and republishes its own curated cache.
|
|
@@ -838,6 +841,8 @@ class PlacementTransport {
|
|
|
838
841
|
installedGuard();
|
|
839
842
|
this.lastPolicyCheckUnixMs=Date.now(); this.lastPolicyHash=material.bundle.root.policyHash;this.policyCheckSource="live";
|
|
840
843
|
const participating=material.bundle.root.targets.map((target,index)=>({target,index})).filter(item=>item.target.publish);
|
|
844
|
+
const refusal = purgePublicationRefusal(this.home);
|
|
845
|
+
if (refusal) return this.result(false, this.attemptHash ? "unknown" : "not-needed", refusal);
|
|
841
846
|
this.attempted=participating.length>0;
|
|
842
847
|
// #626: a push moves advertised refs, so no later publication of this run may reuse the advertisement read before it.
|
|
843
848
|
if(this.attempted)placementAdvertisement(this.opts)?.delete(this.url);
|