@staix/agent-mem 0.23.0 → 0.24.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 +15 -5
- package/package.json +1 -1
- package/src/brief-cache.ts +54 -0
- package/src/brief-capture.ts +82 -0
- package/src/brief-curated-native.ts +32 -0
- package/src/brief-curated.ts +65 -0
- package/src/cli.ts +1 -0
- package/src/curated-brief-cache.ts +29 -0
- package/src/hook-contract.ts +6 -2
- package/src/hook-record.ts +22 -2
- package/src/hook-spool-replay.ts +8 -1
- package/src/hook-spool.ts +2 -2
- package/src/hook-transcript.ts +13 -5
- package/src/hooks.ts +66 -15
- package/src/index.ts +6 -2
- package/src/memory/candidate-pending.ts +6 -2
- package/src/memory/candidates.ts +4 -2
- package/src/memory/capture-input.ts +7 -0
- package/src/memory/capture-plan.ts +10 -0
- package/src/memory/capture.ts +78 -8
- package/src/memory/config.ts +5 -0
- package/src/memory/curated-cache-state.ts +35 -0
- package/src/memory/formats.ts +6 -0
- package/src/memory/generation-index.ts +2 -0
- package/src/memory/generation-sync.ts +3 -0
- package/src/memory/metrics.ts +7 -1
- package/src/memory/migrate.ts +7 -1
- package/src/memory/public-prune-activation.ts +4 -1
- package/src/memory/public-prune-advance.ts +2 -0
- package/src/memory/reader-lease.ts +5 -3
- package/src/memory/record-instruction.ts +26 -0
- package/src/memory/record-variant-log.ts +90 -0
- package/src/memory/shard-migration.ts +4 -1
- package/src/memory/shard-sync.ts +3 -0
- package/src/memory/store.ts +131 -2
- package/src/memory/sync-placement-activation.ts +11 -3
- package/src/memory/sync-placement-transport.ts +3 -0
- package/src/memory/sync.ts +3 -2
- package/src/session-brief-worker.ts +13 -2
- package/src/session-brief.ts +130 -70
- package/src/ui/plugin.ts +104 -30
- package/src/ui/snapshot-cache.ts +141 -0
- package/src/ui/snapshot-revision.ts +87 -0
package/src/memory/migrate.ts
CHANGED
|
@@ -5,6 +5,7 @@ import { legacyEntries, legacyHead, readLegacySnapshot, type LegacyCheckpoint }
|
|
|
5
5
|
import { acquireMutation } from "./mutation.ts";
|
|
6
6
|
import { canonicalPath, realPath } from "./platform.ts";
|
|
7
7
|
import { canonicalJSON, fsyncDirectory, generationDescriptor, generationDir, hashJSON, readProfileJSON, readSelector, resolveProfile, validGeneration, withProfileLock, writeProfileJSON, type BoundProfile } from "./generation.ts";
|
|
8
|
+
import { invalidateCuratedCaches } from "./curated-cache-state.ts";
|
|
8
9
|
import { label, PLAIN, singleLine, type Style } from "./style.ts";
|
|
9
10
|
|
|
10
11
|
export interface SourcePrefix extends LegacyCheckpoint { tailBytes: number }
|
|
@@ -119,7 +120,7 @@ export async function migrate(options: MigrateOptions): Promise<MigrationResult>
|
|
|
119
120
|
if (options.mode === "dry-run") {
|
|
120
121
|
return { mode: options.mode, profile: initial, counts: await counts(memoryDir, options.generation ?? initial.generation, (options.now ?? Date.now)()), consequence };
|
|
121
122
|
}
|
|
122
|
-
|
|
123
|
+
const result = await withProfileLock(memoryDir, async () => {
|
|
123
124
|
refuseShardSelection(memoryDir);
|
|
124
125
|
const selected = readSelector(memoryDir);
|
|
125
126
|
if (selected.revision !== initial.selectorRevision) return changed();
|
|
@@ -136,6 +137,7 @@ export async function migrate(options: MigrateOptions): Promise<MigrationResult>
|
|
|
136
137
|
if (!unavailable && !releaseGeneration) throw new Error("generation mutation lock is busy");
|
|
137
138
|
}
|
|
138
139
|
if (readSelector(memoryDir).revision !== initial.selectorRevision) return changed();
|
|
140
|
+
invalidateCuratedCaches(memoryDir);
|
|
139
141
|
writeProfileJSON(join(memoryDir, "profile.json"), { schema: "agent-mem.profile/v1", kind: "shared-v1" });
|
|
140
142
|
}
|
|
141
143
|
return { mode: options.mode, profile: resolveProfile(memoryDir), consequence };
|
|
@@ -217,12 +219,16 @@ export async function migrate(options: MigrateOptions): Promise<MigrationResult>
|
|
|
217
219
|
if (options.checkpoint) await options.checkpoint("before-selector");
|
|
218
220
|
if (readSelector(memoryDir).revision !== journal.selectorRevision) return changed();
|
|
219
221
|
verifySources(memoryDir, journal.generation, journal.sources, journal.legacyCommit);
|
|
222
|
+
invalidateCuratedCaches(memoryDir);
|
|
220
223
|
writeProfileJSON(join(memoryDir, "profile.json"), { schema: "agent-mem.profile/v1", kind: "generation", generation: journal.generation });
|
|
221
224
|
if (options.checkpoint) await options.checkpoint("after-selector");
|
|
222
225
|
journal.phase = "active"; rememberJournal(memoryDir, journal);
|
|
223
226
|
return { mode: options.mode, profile: resolveProfile(memoryDir), counts: await counts(memoryDir, journal.generation, (options.now ?? Date.now)(), journal.sources, journal.legacyCommit), consequence };
|
|
224
227
|
} finally { releaseGeneration(); }
|
|
225
228
|
});
|
|
229
|
+
// ponytail: profile transitions leave caches missing until the next ordinary off-hook trigger.
|
|
230
|
+
// Upgrade with a snapshot builder that never reopens legacy SQLite or live alias reader leases.
|
|
231
|
+
return result;
|
|
226
232
|
}
|
|
227
233
|
|
|
228
234
|
/** Render a migration result for a person; JSON output remains owned by the CLI. */
|
|
@@ -12,6 +12,7 @@ import { assertNoLiveReaders } from "./reader-lease.ts";
|
|
|
12
12
|
import { aliasLogPath } from "./aliases.ts";
|
|
13
13
|
import { realPath } from "./platform.ts";
|
|
14
14
|
import { buildPublicPruneIndex } from "./store.ts";
|
|
15
|
+
import { invalidateCuratedCaches } from "./curated-cache-state.ts";
|
|
15
16
|
import { reducePublicPruneInputs } from "./public-prune-inputs.ts";
|
|
16
17
|
import { PUBLIC_PRUNE_INTENT, publicPruneViewHash, readPublicPruneViewForActivation, validatePublicPruneView, type PublicPruneViewV1 } from "./public-prune-view.ts";
|
|
17
18
|
|
|
@@ -224,7 +225,7 @@ export async function activatePublicPruneView(options: PublicPruneActivationOpti
|
|
|
224
225
|
}
|
|
225
226
|
return { mode: options.mode, generation: intent.generation, active: true, ...(alreadyActive ? {alreadyActive:true} : {}), realms: intent.realms.length, viewHash: publicPruneViewHash(intent.view), maskBuildCheck: "verified" };
|
|
226
227
|
}
|
|
227
|
-
|
|
228
|
+
const result = await withProfileLock<PublicPruneActivationResult>(home, async () => {
|
|
228
229
|
const releases: (() => void)[] = [];
|
|
229
230
|
try {
|
|
230
231
|
guard(lstatSync(home).dev === rootStat.dev && lstatSync(home).ino === rootStat.ino);
|
|
@@ -249,6 +250,7 @@ export async function activatePublicPruneView(options: PublicPruneActivationOpti
|
|
|
249
250
|
if (!pending && profile === intent.finalProfile && shards === intent.finalShards) return { mode: options.mode, generation: intent.generation, active: true, alreadyActive: true, realms: intent.realms.length, viewHash, maskBuildCheck: "verified" };
|
|
250
251
|
writeImmutableActivationMetadata(intentFile, canonicalJSON(intent) + "\n");
|
|
251
252
|
await options.checkpoint?.("after-intent"); verify(intent, profile, shards);
|
|
253
|
+
invalidateCuratedCaches(home);
|
|
252
254
|
if (shards !== intent.finalShards) { writeProfileJSON(join(home, "shards.json"), JSON.parse(intent.finalShards)); shards = intent.finalShards; }
|
|
253
255
|
await options.checkpoint?.("after-shards"); verify(intent, profile, shards);
|
|
254
256
|
if (profile !== intent.finalProfile) { writeProfileJSON(join(home, "profile.json"), JSON.parse(intent.finalProfile)); profile = intent.finalProfile; }
|
|
@@ -258,4 +260,5 @@ export async function activatePublicPruneView(options: PublicPruneActivationOpti
|
|
|
258
260
|
return { mode: options.mode, generation: intent.generation, active: true, realms: intent.realms.length, viewHash, maskBuildCheck: "verified" };
|
|
259
261
|
} finally { for (const release of releases.reverse()) release(); }
|
|
260
262
|
});
|
|
263
|
+
return result;
|
|
261
264
|
}
|
|
@@ -9,6 +9,7 @@ import { acquireMutation, assertMutationHandle, type MutationHandle } from "./mu
|
|
|
9
9
|
import { createPublicPruneReplayCache, type PublicPruneProjection } from "./public-prune-inputs.ts";
|
|
10
10
|
import { PUBLIC_PRUNE_INTENT, publicPruneViewHash, readPublicPruneViewForActivation, validatePublicPruneView, type PublicPruneViewV1 } from "./public-prune-view.ts";
|
|
11
11
|
import { realPath } from "./platform.ts";
|
|
12
|
+
import { invalidateCuratedCaches } from "./curated-cache-state.ts";
|
|
12
13
|
|
|
13
14
|
export type PublicPruneAdvanceStage = "after-intent" | "after-shards" | "after-profile" | "after-remove";
|
|
14
15
|
export interface PublicPruneAdvanceOptions {
|
|
@@ -120,6 +121,7 @@ function run(intent: AdvanceIntent, provided: readonly MutationHandle[]|undefine
|
|
|
120
121
|
if(profile===intent.finalProfile&&shards===intent.finalShards&&!lstatSync(file,{throwIfNoEntry:false}))return{revision:intent.finalProfileHash,viewHash};
|
|
121
122
|
immutable(join(intent.home,"public-prune-input-sets",viewHash+".json"),canonicalJSON(intent.view)+"\n");
|
|
122
123
|
immutable(file,text);yield "after-intent";verify();guard(raw(file)===text&&raw(join(intent.home,"profile.json"))===profile&&raw(join(intent.home,"shards.json"))===shards);
|
|
124
|
+
invalidateCuratedCaches(intent.home);
|
|
123
125
|
if(shards!==intent.finalShards)replace(join(intent.home,"shards.json"),intent.finalShards);shards=intent.finalShards;
|
|
124
126
|
yield "after-shards";verify();guard(raw(file)===text&&raw(join(intent.home,"profile.json"))===profile&&raw(join(intent.home,"shards.json"))===shards);
|
|
125
127
|
if(profile!==intent.finalProfile)replace(join(intent.home,"profile.json"),intent.finalProfile);profile=intent.finalProfile;
|
|
@@ -2,7 +2,7 @@ import { lstatSync, mkdirSync, readdirSync, rmSync } from "node:fs";
|
|
|
2
2
|
import { join } from "node:path";
|
|
3
3
|
import { readProfileJSON, writeProfileJSON } from "./generation.ts";
|
|
4
4
|
import { readerAdmissionDatabase } from "./mutation.ts";
|
|
5
|
-
import { processLiveness, processSignature } from "./platform.ts";
|
|
5
|
+
import { processLiveness, processSignature, realPath } from "./platform.ts";
|
|
6
6
|
import { waitForPublicPruneWriter } from "./public-prune-view.ts";
|
|
7
7
|
import { profileLockRecoveryError, safeProfileLockMessage } from "./profile-lock-diagnostic.ts";
|
|
8
8
|
|
|
@@ -57,7 +57,7 @@ function admitReader(memoryDir: string): void {
|
|
|
57
57
|
} catch (error) { if(safeProfileLockMessage(error))throw error;throw profileLockRecoveryError(memoryDir) ?? new Error("profile lock prevents reader admission; finish or resume the migration with amem migrate --resume"); }
|
|
58
58
|
}
|
|
59
59
|
|
|
60
|
-
/** One lease per process/home/namespace, reference-counted across handles.
|
|
60
|
+
/** One lease per process/physical home/namespace, reference-counted across handles.
|
|
61
61
|
* Shard scope shares root admission and native identity; it grants no authority.
|
|
62
62
|
* An unref'd timer does not keep the process resident. */
|
|
63
63
|
export function registerReaderLease(memoryDir: string, options: { busyTimeoutMs?: number; signature?: string; scope?: "shard" } = {}): ReaderLease {
|
|
@@ -74,9 +74,11 @@ export function registerReaderLease(memoryDir: string, options: { busyTimeoutMs?
|
|
|
74
74
|
// Host-only: the supplied hash must already describe this process's pinned native ps identity.
|
|
75
75
|
const signature = inherited ?? options.signature ?? processSignature(pid);
|
|
76
76
|
if (!signature) throw new Error("cannot establish reader lease identity");
|
|
77
|
+
mkdirSync(memoryDir, { recursive: true, mode: 0o700 });
|
|
78
|
+
// Pin the map key and renewal/verify/close closures to one physical home, not its caller spelling.
|
|
79
|
+
memoryDir = realPath(memoryDir);
|
|
77
80
|
const file = fileFor(memoryDir, process.pid, signature, scope);
|
|
78
81
|
const busyTimeoutMs = open.get(file)?.busyTimeoutMs ?? requestedTimeout;
|
|
79
|
-
mkdirSync(memoryDir, { recursive: true, mode: 0o700 });
|
|
80
82
|
withFence(memoryDir, () => {
|
|
81
83
|
admitReader(memoryDir);
|
|
82
84
|
const current = open.get(file);
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { closeSync, constants, fstatSync, openSync, readSync } from "node:fs";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import type { RecordInstructionMode } from "../hook-record.ts";
|
|
4
|
+
|
|
5
|
+
/** Person-written selection, separate from the configuration older readers parse. Core never writes it. */
|
|
6
|
+
export const RECORD_INSTRUCTION_FILE = "record-instruction.json";
|
|
7
|
+
const MAX_BYTES = 64 * 1024;
|
|
8
|
+
export function readRecordInstruction(base: string): { mode: RecordInstructionMode; invalid: boolean } {
|
|
9
|
+
let fd: number | undefined;
|
|
10
|
+
try {
|
|
11
|
+
try { fd = openSync(join(base, RECORD_INSTRUCTION_FILE), constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK); }
|
|
12
|
+
catch (error) {
|
|
13
|
+
if ((error as NodeJS.ErrnoException).code === "ENOENT") return { mode: "a", invalid: false };
|
|
14
|
+
return { mode: "a", invalid: true };
|
|
15
|
+
}
|
|
16
|
+
const stat = fstatSync(fd);
|
|
17
|
+
if (!stat.isFile() || stat.nlink !== 1 || stat.uid !== process.getuid?.() || stat.size > MAX_BYTES || (stat.mode & 0o022) !== 0) return { mode: "a", invalid: true };
|
|
18
|
+
const bytes = Buffer.alloc(MAX_BYTES + 1), length = readSync(fd, bytes, 0, bytes.length, 0);
|
|
19
|
+
if (length > MAX_BYTES) return { mode: "a", invalid: true };
|
|
20
|
+
const value: unknown = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes.subarray(0, length)));
|
|
21
|
+
if (!value || typeof value !== "object" || Array.isArray(value) || Object.keys(value).length !== 1 || !Object.hasOwn(value, "instruction")) return { mode: "a", invalid: true };
|
|
22
|
+
const mode = (value as { instruction: unknown }).instruction;
|
|
23
|
+
return mode === "a" || mode === "b" || mode === "alternate" ? { mode, invalid: false } : { mode: "a", invalid: true };
|
|
24
|
+
} catch { return { mode: "a", invalid: true }; }
|
|
25
|
+
finally { if (fd !== undefined) try { closeSync(fd); } catch { /* Selection never refuses a hook. */ } }
|
|
26
|
+
}
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import { closeSync, constants, fstatSync, renameSync, unlinkSync, mkdirSync, openSync, readSync, writeFileSync, writeSync } from "node:fs";
|
|
2
|
+
import { randomUUID } from "node:crypto";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import type { MetricSample } from "./metrics.ts";
|
|
5
|
+
|
|
6
|
+
export const RECORD_VARIANTS_FILE = "record-variants.jsonl";
|
|
7
|
+
export const RECORD_VARIANTS_MAX_BYTES = 4 * 1024 * 1024;
|
|
8
|
+
export const RECORD_VARIANTS_DAYS = 8;
|
|
9
|
+
const DAY = 86400_000, ROW_BYTES = 1024, CAP_TRIM_BYTES = 3 * 1024 * 1024;
|
|
10
|
+
const FIELDS = ["recordEnabled", "recordSessions", "recordTurns", "recordTurnsWithRecords", "recordScanIncomplete", "recordValidRecords", "recordBasisRecords", "recordUnverifiedRecords", "recordInstructionInvalid", "recordInstructionEmitted", "recordBriefBytes", "recordInstructionBytes", "recordInstructionEstimatedTokens"] as const;
|
|
11
|
+
type Event = "SessionStart" | "Stop" | "SessionEnd";
|
|
12
|
+
interface JournalRow { at: string; event: Event; variant: "a" | "b"; capTrimmed?: number; [key: string]: string | number | undefined }
|
|
13
|
+
function row(value: unknown): JournalRow | undefined {
|
|
14
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return;
|
|
15
|
+
const input = value as Record<string, unknown>;
|
|
16
|
+
if (typeof input.at !== "string" || !Number.isFinite(Date.parse(input.at)) || !["SessionStart", "Stop", "SessionEnd"].includes(input.event as string) || input.variant !== "a" && input.variant !== "b") return;
|
|
17
|
+
if (new Date(Date.parse(input.at)).toISOString() !== input.at) return;
|
|
18
|
+
const out: JournalRow = { at: input.at, event: input.event as Event, variant: input.variant };
|
|
19
|
+
for (const key of [...FIELDS, "capTrimmed", "trimmed"] as const) if (Number.isSafeInteger(input[key]) && (input[key] as number) >= 0) out[key] = input[key] as number;
|
|
20
|
+
return out;
|
|
21
|
+
}
|
|
22
|
+
function readTail(fd: number, size: number): string {
|
|
23
|
+
const start = Math.max(0, size - RECORD_VARIANTS_MAX_BYTES), bytes = Buffer.alloc(Math.min(size, RECORD_VARIANTS_MAX_BYTES));
|
|
24
|
+
const length = readSync(fd, bytes, 0, bytes.length, start);
|
|
25
|
+
let text = new TextDecoder("utf-8", { fatal: true }).decode(bytes.subarray(0, length));
|
|
26
|
+
if (start) text = text.slice(text.indexOf("\n") + 1);
|
|
27
|
+
return text;
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* ponytail: bounded observational retention may lose concurrent appends/competing trims
|
|
31
|
+
* between snapshot and rename. An already-open old fd appends to the unlinked inode:
|
|
32
|
+
* its line is lost, not misplaced. Each hook opens/closes its fd, so this window is one write.
|
|
33
|
+
* Readers see a whole file.
|
|
34
|
+
* Upgrade: coordinate append and trim under one lock, or use dated per-day files.
|
|
35
|
+
* Count observed trim markers, never infer a number of lost observations.
|
|
36
|
+
*/
|
|
37
|
+
function trim(base: string, fd: number, size: number, cutoff: number): void {
|
|
38
|
+
const rows: JournalRow[] = [];
|
|
39
|
+
for (const line of readTail(fd, size).split("\n")) {
|
|
40
|
+
if (!line) continue;
|
|
41
|
+
try { const parsed = row(JSON.parse(line)); if (parsed && Date.parse(parsed.at) >= cutoff) rows.push(parsed); } catch { /* Malformed observations are not zeros. */ }
|
|
42
|
+
}
|
|
43
|
+
if (!rows.length) return;
|
|
44
|
+
rows[rows.length - 1]!.trimmed = 1;
|
|
45
|
+
let encoded = rows.map(value => JSON.stringify(value) + "\n");
|
|
46
|
+
let bytes = encoded.reduce((sum, line) => sum + Buffer.byteLength(line), 0), from = 0;
|
|
47
|
+
const capacityTrim = size >= RECORD_VARIANTS_MAX_BYTES;
|
|
48
|
+
const byteTarget = capacityTrim ? CAP_TRIM_BYTES : RECORD_VARIANTS_MAX_BYTES;
|
|
49
|
+
while (from < encoded.length && bytes + 32 > byteTarget) bytes -= Buffer.byteLength(encoded[from++]!);
|
|
50
|
+
if (from || capacityTrim) {
|
|
51
|
+
rows[rows.length - 1]!.capTrimmed = 1;
|
|
52
|
+
encoded[encoded.length - 1] = JSON.stringify(rows[rows.length - 1]) + "\n";
|
|
53
|
+
}
|
|
54
|
+
const kept = encoded.slice(from).join("");
|
|
55
|
+
const temporary = join(base, `${RECORD_VARIANTS_FILE}.tmp-${randomUUID()}`);
|
|
56
|
+
let target: number | undefined;
|
|
57
|
+
try {
|
|
58
|
+
target = openSync(temporary, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_APPEND | constants.O_NOFOLLOW, 0o600);
|
|
59
|
+
writeFileSync(target, kept); closeSync(target); target = undefined;
|
|
60
|
+
renameSync(temporary, join(base, RECORD_VARIANTS_FILE));
|
|
61
|
+
} finally {
|
|
62
|
+
if (target !== undefined) closeSync(target);
|
|
63
|
+
try { unlinkSync(temporary); } catch { /* Renamed or not created. */ }
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
/** One short append per hook. Only explicit numeric fields survive; failures never change a hook outcome. */
|
|
67
|
+
export function appendRecordVariant(base: string, event: string, sample: MetricSample, now = Date.now()): void {
|
|
68
|
+
if (!["SessionStart", "Stop", "SessionEnd"].includes(event) || sample.recordVariant !== "a" && sample.recordVariant !== "b") return;
|
|
69
|
+
let fd: number | undefined;
|
|
70
|
+
try {
|
|
71
|
+
mkdirSync(base, { recursive: true, mode: 0o700 });
|
|
72
|
+
fd = openSync(join(base, RECORD_VARIANTS_FILE), constants.O_RDWR | constants.O_CREAT | constants.O_APPEND | constants.O_NOFOLLOW | constants.O_NONBLOCK, 0o600);
|
|
73
|
+
const stat = fstatSync(fd);
|
|
74
|
+
if (!stat.isFile() || stat.nlink !== 1 || typeof process.getuid === "function" && stat.uid !== process.getuid() || (stat.mode & 0o022) !== 0) return;
|
|
75
|
+
const out = row({ ...sample, at: new Date(now).toISOString(), event, variant: sample.recordVariant })!;
|
|
76
|
+
const line = JSON.stringify(out) + "\n";
|
|
77
|
+
if (Buffer.byteLength(line) > ROW_BYTES) return;
|
|
78
|
+
writeSync(fd, line); // One short O_APPEND write; ordinary calls never read the tail or rewrite.
|
|
79
|
+
const after = fstatSync(fd);
|
|
80
|
+
const probe = Buffer.alloc(Math.min(after.size, ROW_BYTES));
|
|
81
|
+
const length = readSync(fd, probe, 0, probe.length, 0);
|
|
82
|
+
let ageTrim = false;
|
|
83
|
+
try {
|
|
84
|
+
const first = row(JSON.parse(probe.subarray(0, length).toString("utf8").split("\n")[0]!));
|
|
85
|
+
ageTrim = !!first && Date.parse(first.at) < now - 9 * DAY;
|
|
86
|
+
} catch { /* No date evidence: only the size trigger can trim it. */ }
|
|
87
|
+
if (ageTrim || after.size >= RECORD_VARIANTS_MAX_BYTES) trim(base, fd, after.size, now - RECORD_VARIANTS_DAYS * DAY);
|
|
88
|
+
} catch { /* Metrics never deny a tool or disclose the input. */ }
|
|
89
|
+
finally { if (fd !== undefined) try { closeSync(fd); } catch { /* Fail open. */ } }
|
|
90
|
+
}
|
|
@@ -10,6 +10,7 @@ import { canonicalPath, realPath } from "./platform.ts";
|
|
|
10
10
|
import { assertNoLiveReaders } from "./reader-lease.ts";
|
|
11
11
|
import { assertCuratedShardPaths, ensureShardDescriptor, shardDir, SHARDED_SCHEMA, SHARDED_V2_SCHEMA, userShardDir, SHARD_SCHEMA } from "./shard.ts";
|
|
12
12
|
import { buildGenerationIndex, type Entry } from "./store.ts";
|
|
13
|
+
import { invalidateCuratedCaches } from "./curated-cache-state.ts";
|
|
13
14
|
import { readMigrationSources, type SourcePrefix } from "./migrate.ts";
|
|
14
15
|
import { label, PLAIN, singleLine, type Style } from "./style.ts";
|
|
15
16
|
|
|
@@ -510,7 +511,7 @@ export async function migrateShards(options: ShardMigrationOptions): Promise<Sha
|
|
|
510
511
|
// Validate every immutable prune and routing decision before even a profile/mutation lock creates metadata.
|
|
511
512
|
const initial = preflight(memoryDir, options, undefined, options.mode === "dry-run");
|
|
512
513
|
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) };
|
|
513
|
-
|
|
514
|
+
const result = await withProfileLock(memoryDir, async () => {
|
|
514
515
|
const release = acquireMutation(memoryDir);
|
|
515
516
|
if (!release) throw new Error("legacy mutation lock is busy");
|
|
516
517
|
let releaseOwn: (() => void) | undefined;
|
|
@@ -546,6 +547,7 @@ export async function migrateShards(options: ShardMigrationOptions): Promise<Sha
|
|
|
546
547
|
let affected: Set<Destination>;
|
|
547
548
|
try {
|
|
548
549
|
for (const destination of plan.destinations) assessDestination(memoryDir, destination, plan, generation, machine);
|
|
550
|
+
invalidateCuratedCaches(memoryDir);
|
|
549
551
|
if (!alreadyActive) journal.phase = "captured";
|
|
550
552
|
persist();
|
|
551
553
|
affected = writeRoutes(memoryDir, plan, generation, machine);
|
|
@@ -561,6 +563,7 @@ export async function migrateShards(options: ShardMigrationOptions): Promise<Sha
|
|
|
561
563
|
persist();
|
|
562
564
|
return { mode: options.mode, generation, active: true, ...(alreadyActive ? { alreadyActive: true } : {}), counts: counts(plan), ...refusalSummary(plan), consequence: CONSEQUENCE, ...removalEvidence(journal) };
|
|
563
565
|
});
|
|
566
|
+
return result;
|
|
564
567
|
}
|
|
565
568
|
|
|
566
569
|
/** Render a shard migration result for a person; JSON output remains owned by the CLI. */
|
package/src/memory/shard-sync.ts
CHANGED
|
@@ -443,6 +443,7 @@ async function prepareHolds(targets: readonly Target[], root: string, url: strin
|
|
|
443
443
|
}
|
|
444
444
|
}
|
|
445
445
|
export async function syncShardedMemory(store: MemoryStore, opts: SyncOptions = {}, testOnlyUnexpectedError?: (error: unknown) => void, testOnlyPhase?: (phase: SyncPhase) => void): Promise<SyncResult> {
|
|
446
|
+
let releaseCurated: (() => void) | undefined;
|
|
446
447
|
const placementRefusal = placementRuntimeRefusal(store.profile.home, store.profile);
|
|
447
448
|
if (placementRefusal) return { ok: false, pushed: false, entries: 0, error: placementRefusal };
|
|
448
449
|
if (store.profile.publicationFormat === "agent-mem.sync-placement/v1") return (await import("./sync-placement-transport.ts")).syncPlacementMemory(store, opts);
|
|
@@ -541,6 +542,7 @@ export async function syncShardedMemory(store: MemoryStore, opts: SyncOptions =
|
|
|
541
542
|
const release = acquireMutation(target.store.dir); if (!release) refuse(`${shardSyncLabel(target.realm)}: another source mutation is running`); releases.push(release); target.mutation=release;
|
|
542
543
|
if (v2) ensurePublisherBoundary(target.store.profile,release);
|
|
543
544
|
}
|
|
545
|
+
releaseCurated = store.beginCuratedCacheUpdate();
|
|
544
546
|
const blobCache = new Map<string, Buffer>();
|
|
545
547
|
const blob = async (object: string, path: string): Promise<Buffer> => {
|
|
546
548
|
const maximum = path === "shard.json" || isShardManifestPath(path) ? 64 * 1024 : SHARD_PACK_MAX_BYTES, prior = blobCache.get(object);
|
|
@@ -729,6 +731,7 @@ export async function syncShardedMemory(store: MemoryStore, opts: SyncOptions =
|
|
|
729
731
|
for (const release of releases.reverse()) { try { release(); } catch { /* fail-open cleanup */ } }
|
|
730
732
|
try { releaseSync?.(); } catch { /* private lock cleanup */ }
|
|
731
733
|
try { releaseTransport?.(); } catch { /* private lock cleanup */ }
|
|
734
|
+
releaseCurated?.();
|
|
732
735
|
}
|
|
733
736
|
}
|
|
734
737
|
|
package/src/memory/store.ts
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { buildCuratedBriefCache } from "../brief-curated.ts";
|
|
2
|
+
import { curatedProfileBinding, invalidateCuratedCaches } from "./curated-cache-state.ts";
|
|
1
3
|
import { assertPlacementRuntime, placementSelectorRefusal, SyncPlacementRuntimeError } from "./sync-placement-guard.ts";
|
|
2
4
|
import { assertFormatFloor } from "./formats.ts";
|
|
3
5
|
import { readPublicPruneView } from "./public-prune-view.ts";
|
|
@@ -203,7 +205,15 @@ export interface StoreOptions { home?: string; memoryDir?: string; ttlMs?: numbe
|
|
|
203
205
|
|
|
204
206
|
const MIGRATION_BOOTSTRAP = Symbol("migration index bootstrap");
|
|
205
207
|
interface BootstrapBinding { token: typeof MIGRATION_BOOTSTRAP; profile: BoundProfile; limits?: readonly LegacyCheckpoint[]; commit?: string; authoring?: boolean; userOverlay?: MemoryStore; aliasStores?: MemoryStore[] }
|
|
208
|
+
// Defer publication until the outermost source fence in this process has released.
|
|
209
|
+
const curatedDepth = new Map<string, number>();
|
|
210
|
+
const curatedPending = new Map<string, Map<MemoryStore, Set<string>>>();
|
|
211
|
+
let publishingCurated = false;
|
|
212
|
+
|
|
206
213
|
export class MemoryStore {
|
|
214
|
+
private curatedParent?: MemoryStore;
|
|
215
|
+
private curatedRebuildAll = false;
|
|
216
|
+
|
|
207
217
|
readonly dir: string;
|
|
208
218
|
readonly profile: BoundProfile;
|
|
209
219
|
private readonly generationIndex?: GenerationIndex;
|
|
@@ -231,6 +241,7 @@ export class MemoryStore {
|
|
|
231
241
|
this.bootstrapOnly = bootstrap ? bootstrap.authoring !== true : false;
|
|
232
242
|
this.userOverlay = bootstrap?.userOverlay;
|
|
233
243
|
this.aliasStores = bootstrap?.aliasStores ?? [];
|
|
244
|
+
for (const child of [...this.aliasStores, ...(this.userOverlay ? [this.userOverlay] : [])]) child.curatedParent = this;
|
|
234
245
|
this.reconcile = opts.reconcile && opts.reconcile.aliases.length ? { canonical: opts.reconcile.canonical, aliases: [...opts.reconcile.aliases] } : undefined;
|
|
235
246
|
if (opts.memoryDir !== undefined && (opts.home !== undefined || typeof opts.memoryDir !== "string" || !opts.memoryDir.trim())) throw new Error("choose a memory home or one explicit memory directory");
|
|
236
247
|
const home = bootstrap?.profile.home ?? opts.memoryDir ?? (opts.home === undefined ? memoryHome() : join(opts.home, "memory"));
|
|
@@ -287,7 +298,11 @@ export class MemoryStore {
|
|
|
287
298
|
this.memoryBaseDir = home;
|
|
288
299
|
try { chmodSync(indexFile, 0o600); } catch { /* best effort */ }
|
|
289
300
|
if (this.profile.kind === "generation") this.generationIndex = new GenerationIndex({ profile: this.profile, db, now: this.now,
|
|
290
|
-
apply: (line, source) => this.apply(line, source), withMutation: work => this.withMutation(work),
|
|
301
|
+
apply: (line, source) => this.apply(line, source), withMutation: work => this.withMutation(work), beforeCuratedWrite: targets => {
|
|
302
|
+
invalidateCuratedCaches(this.profile.home);
|
|
303
|
+
const rows = this.db.query("SELECT DISTINCT project FROM entries WHERE id IN (SELECT value FROM json_each(?))").all(JSON.stringify(targets)) as { project: string }[];
|
|
304
|
+
this.queueCuratedProjects(rows.map(row => row.project));
|
|
305
|
+
},
|
|
291
306
|
...(bootstrap ? { limits: bootstrap.limits } : {}), ...(bootstrap?.commit ? { commit: bootstrap.commit } : {}) });
|
|
292
307
|
this.refresh();
|
|
293
308
|
} catch (error) {
|
|
@@ -385,7 +400,118 @@ export class MemoryStore {
|
|
|
385
400
|
}
|
|
386
401
|
|
|
387
402
|
private withMutation<T>(work: () => T): T {
|
|
388
|
-
|
|
403
|
+
const release = this.deferCuratedPublication();
|
|
404
|
+
try { return this.mutationDb.transaction(work).immediate(); }
|
|
405
|
+
finally { release(); }
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
private deferCuratedPublication(): () => void {
|
|
409
|
+
const home = this.profile.home;
|
|
410
|
+
curatedDepth.set(home, (curatedDepth.get(home) ?? 0) + 1);
|
|
411
|
+
return () => {
|
|
412
|
+
const depth = (curatedDepth.get(home) ?? 1) - 1;
|
|
413
|
+
if (depth) { curatedDepth.set(home, depth); return; }
|
|
414
|
+
curatedDepth.delete(home);
|
|
415
|
+
if (publishingCurated) return;
|
|
416
|
+
const pending = curatedPending.get(home); curatedPending.delete(home);
|
|
417
|
+
if (!pending) return;
|
|
418
|
+
publishingCurated = true;
|
|
419
|
+
try { for (const [store, projects] of pending) store.publishCurated(projects); }
|
|
420
|
+
finally { publishingCurated = false; }
|
|
421
|
+
};
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
private markCuratedChange(project?: string): void {
|
|
425
|
+
if (this.bootstrapOnly) return;
|
|
426
|
+
invalidateCuratedCaches(this.profile.home);
|
|
427
|
+
this.queueCuratedProjects(project ? [project] : []);
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
private queueCuratedProjects(touched: Iterable<string>): void {
|
|
431
|
+
let owner: MemoryStore = this;
|
|
432
|
+
while (owner.curatedParent) owner = owner.curatedParent;
|
|
433
|
+
const pending = curatedPending.get(this.profile.home) ?? new Map<MemoryStore, Set<string>>();
|
|
434
|
+
const projects = pending.get(owner) ?? new Set<string>();
|
|
435
|
+
for (const project of touched) projects.add(project);
|
|
436
|
+
if (owner.profile.shardKey) projects.add(owner.profile.shardKey);
|
|
437
|
+
pending.set(owner, projects); curatedPending.set(this.profile.home, pending);
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
private curatedProjectRevisions(): Map<string, string> {
|
|
441
|
+
this.ensureFresh();
|
|
442
|
+
const projects = new Map<string, string[]>();
|
|
443
|
+
for (const view of this.views()) {
|
|
444
|
+
const rows = projects.get(view.project) ?? [];
|
|
445
|
+
rows.push(JSON.stringify([view.id, view.tier, view.expiresAt, view.supersededBy]));
|
|
446
|
+
projects.set(view.project, rows);
|
|
447
|
+
}
|
|
448
|
+
return new Map([...projects].map(([project, rows]) => [project, JSON.stringify(rows.sort())]));
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
/** Internal derived-cache port; the sync caller already holds the authoritative writer fences. */
|
|
452
|
+
beginCuratedCacheUpdate(): () => void {
|
|
453
|
+
const release = this.deferCuratedPublication();
|
|
454
|
+
let before: Map<string, string>;
|
|
455
|
+
try { before = this.curatedProjectRevisions(); invalidateCuratedCaches(this.profile.home); }
|
|
456
|
+
catch (error) { release(); throw error; }
|
|
457
|
+
return () => {
|
|
458
|
+
try {
|
|
459
|
+
const after = this.curatedProjectRevisions();
|
|
460
|
+
const touched = [...new Set([...before.keys(), ...after.keys()])].filter(project => before.get(project) !== after.get(project));
|
|
461
|
+
if (touched.length) this.queueCuratedProjects(touched);
|
|
462
|
+
} catch { /* The invalidated cache stays unavailable if the committed source cannot be read. */ }
|
|
463
|
+
finally { release(); }
|
|
464
|
+
};
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
/** Off-hook preparation; callers never invoke this from native SessionStart. */
|
|
468
|
+
prepareCuratedBriefs(projects?: readonly string[]): void {
|
|
469
|
+
try { this.curatedRebuildAll = projects === undefined; this.publishCurated(new Set(projects ?? []), projects?.length === 1 ? this : undefined); }
|
|
470
|
+
catch { /* An off-hook read still succeeds when its optional derived cache cannot be prepared. */ }
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
private publishCurated(input: ReadonlySet<string>, opened?: MemoryStore): void {
|
|
474
|
+
const projects = new Set(input);
|
|
475
|
+
if (this.curatedRebuildAll) {
|
|
476
|
+
this.curatedRebuildAll = false;
|
|
477
|
+
for (const source of this.readStores()) for (const value of source.db.query("SELECT DISTINCT project FROM entries").all() as { project: string }[]) projects.add(value.project);
|
|
478
|
+
const root = join(this.profile.home, "projects");
|
|
479
|
+
if (existsSync(root)) for (const hash of readdirSync(root)) { const descriptor = /^[a-f0-9]{16}$/.test(hash) ? readShardDescriptor(this.profile.home, hash) : undefined; if (descriptor) projects.add(descriptor.key); }
|
|
480
|
+
}
|
|
481
|
+
for (const raw of projects) {
|
|
482
|
+
let view: MemoryStore | undefined;
|
|
483
|
+
try {
|
|
484
|
+
const project = resolveAlias(this.profile.home, raw), aliases = aliasedKeys(this.profile.home, project);
|
|
485
|
+
const common = { memoryDir: this.profile.home, deferPromotions: true, now: this.now, ...(aliases.length ? { reconcile: { canonical: project, aliases } } : {}) };
|
|
486
|
+
const sharded = existsSync(join(this.profile.home, "shards.json"));
|
|
487
|
+
// Cache preparation cannot replace project admission with a user-only view.
|
|
488
|
+
// The ordinary off-hook read may initialize a missing shard only where the source API permits it.
|
|
489
|
+
if (sharded && !existsSync(join(shardDir(this.profile.home, project), "generation.json"))) continue;
|
|
490
|
+
const reusable = opened && (!sharded || opened.profile.shardKey === project)
|
|
491
|
+
&& (aliases.length ? opened.reconcile?.canonical === project && opened.reconcile.aliases.join("\n") === aliases.join("\n") : !opened.reconcile);
|
|
492
|
+
if (opened && !reusable) continue; // Explicit single-project preparation never retries with a second store.
|
|
493
|
+
view = reusable ? opened! : sharded ? openShardStore({ ...common, project }) : new MemoryStore(common);
|
|
494
|
+
view.withStoreFences(() => {
|
|
495
|
+
const selected = readSelector(this.profile.home);
|
|
496
|
+
const shards = sharded ? readShardedSelection(this.profile.home) : null;
|
|
497
|
+
if (view!.profile.selectorRevision !== selected.revision || view!.profile.kind !== (shards ? "generation" : selected.selector?.kind ?? "shared-v1")
|
|
498
|
+
|| view!.profile.generation !== (shards?.generation ?? selected.selector?.generation) || resolveAlias(this.profile.home, raw) !== project
|
|
499
|
+
|| shards && (shards.selectorRevision !== selected.revision || shards.generation !== view!.profile.generation)
|
|
500
|
+
|| aliasedKeys(this.profile.home, project).join("\n") !== aliases.join("\n")
|
|
501
|
+
|| (view!.reconcile?.aliases.join("\n") ?? "") !== aliases.join("\n")) {
|
|
502
|
+
throw Error("curated snapshot source binding changed; retry an off-hook amem brief");
|
|
503
|
+
}
|
|
504
|
+
// Stamp the source handle's inputs, never a newer metadata read that it did not open.
|
|
505
|
+
const binding = JSON.stringify({ selector: selected.revision, shards, aliases });
|
|
506
|
+
ensureShardDescriptor(this.profile.home, project);
|
|
507
|
+
const directory = shardMachineDir(this.profile.home, project, machineId(this.profile.home).id);
|
|
508
|
+
mkdirSync(directory, { recursive: true, mode: 0o700 });
|
|
509
|
+
buildCuratedBriefCache(view!, { base: this.profile.home, project, directory, binding, now: this.now });
|
|
510
|
+
if (curatedProfileBinding(this.profile.home, project) !== binding) rmSync(join(directory, "brief-curated.json"), { force: true });
|
|
511
|
+
});
|
|
512
|
+
} catch { /* Failed derived publication leaves the invalidated cache unavailable; a later mutation retries. */ }
|
|
513
|
+
finally { try { if (view !== opened) view?.close(); } catch { /* Preserve the authoritative mutation result. */ } }
|
|
514
|
+
}
|
|
389
515
|
}
|
|
390
516
|
|
|
391
517
|
/** Synchronous exact-target work under every opened shard's existing writer fence. No read-time promotions. */
|
|
@@ -496,6 +622,8 @@ export class MemoryStore {
|
|
|
496
622
|
return this.withMutation(() => {
|
|
497
623
|
this.generationIndex?.assertAppendable(local, this.machine.id);
|
|
498
624
|
const id = entryId(body);
|
|
625
|
+
const affected = "project" in body ? String(body.project) : "target" in body && typeof body.target === "string" ? (this.db.query("SELECT project FROM entries WHERE id=? OR task=?").get(body.target, body.target) as { project: string } | null)?.project : undefined;
|
|
626
|
+
if (body.op !== "goal" && body.op !== "goal_state" && body.op !== "goal_link") this.markCuratedChange(affected);
|
|
499
627
|
appendFileSync(join(this.dir, local ? "local" : "log", `${this.machine.id}.jsonl`), JSON.stringify({ ...body, id }) + "\n", { mode: 0o600 });
|
|
500
628
|
// The line is durable even if indexing fails; the next refresh catches up from the authoritative log.
|
|
501
629
|
try { this.refresh(); } catch (e) { this.stale = true; this.log(`hub memory index not updated yet: ${(e as Error).message}`); }
|
|
@@ -542,6 +670,7 @@ export class MemoryStore {
|
|
|
542
670
|
// The source tuple also recognizes legacy ids whose nodes depended on the checkout or extractor version.
|
|
543
671
|
const known = this.db.query("SELECT id FROM entries WHERE id = ? OR (source = 'claude-mem' AND project = ? AND at = ? AND text = ?)").get(id, n.project, at, stripPrivateSpans(n.text).slice(0, MAX_TEXT)) as { id: string } | null;
|
|
544
672
|
if (known) return { id: known.id, added: false };
|
|
673
|
+
this.markCuratedChange(n.project);
|
|
545
674
|
appendFileSync(join(this.dir, n.tier === "short" ? "local" : "log", `${this.machine.id}.jsonl`), JSON.stringify({ ...body, id }) + "\n", { mode: 0o600 });
|
|
546
675
|
return { id, added: true };
|
|
547
676
|
});
|
|
@@ -4,6 +4,7 @@ import { closeSync, constants, fstatSync, fsyncSync, lstatSync, openSync } from
|
|
|
4
4
|
import { dirname, join } from "node:path";
|
|
5
5
|
import { types } from "node:util";
|
|
6
6
|
import { canonicalJSON, hashJSON, writeProfileJSON, fsyncDirectory } from "./generation.ts";
|
|
7
|
+
import { invalidateCuratedCaches } from "./curated-cache-state.ts";
|
|
7
8
|
import { assertMutationHandle, type MutationHandle } from "./mutation.ts";
|
|
8
9
|
import { withPlacementActivationFences, PlacementInventoryFenceError } from "./sync-placement-activation-locks.ts";
|
|
9
10
|
import { realPath } from "./platform.ts";
|
|
@@ -134,7 +135,8 @@ export async function activateSyncPlacement(options:PlacementActivationOptions)
|
|
|
134
135
|
if(options.mode==="dry-run")return{mode:options.mode,active:false,forwardOnly:true,quiescence:"deferred-to-apply",realms:source!.base.realms.length,writers:writer!.measurement.roots,source:report};
|
|
135
136
|
if(!pending&&!options.writerRoots.length)throw Error("Initial sync placement apply requires an explicit complete --writer-root inventory; run amem migrate --sync-placement --dry-run, then apply the reviewed roots.");
|
|
136
137
|
const directories=pending?pending.plan.realms.map(realm=>realm.scope==="user"?join(home,"user"):join(home,"projects",realm.keyHash.slice(0,16))):source!.directories;
|
|
137
|
-
try{
|
|
138
|
+
try{
|
|
139
|
+
const result=await withPlacementActivationFences(home,directories,async(mutation,owner)=>{
|
|
138
140
|
let intent=pending;
|
|
139
141
|
const initialCheck=()=>{assertPlacementActivationOwner(owner);source!.assertSourcesUnchanged();writer!.attest();if(requirePlacementHomeFloor(home)!==initialFloorHash)fail("changed");};
|
|
140
142
|
if(!intent){
|
|
@@ -152,7 +154,10 @@ export async function activateSyncPlacement(options:PlacementActivationOptions)
|
|
|
152
154
|
}
|
|
153
155
|
const fixed=intent,epochHash=placementEpochHash(fixed.epoch);
|
|
154
156
|
const metadataCheck=()=>{assertPlacementActivationOwner(owner);requirePlacementHomeFloor(home);if(!committed(home,fixed))fail("changed");readSyncPlacementWriterRoots(home);assertMutationHandle(mutation,home);};
|
|
155
|
-
if(committed(home,fixed))
|
|
157
|
+
if(committed(home,fixed)){
|
|
158
|
+
invalidateCuratedCaches(home);
|
|
159
|
+
return finishCommittedActivation(home,fixed,options,mutation,owner,fixed,report);
|
|
160
|
+
}
|
|
156
161
|
let current:PlacementWriterContext;
|
|
157
162
|
try{current=writer??initialPlacementWriterContext(home,fixed.roots,options.ownRoot);}catch(error){writerInputFailure(error);}
|
|
158
163
|
if(canonicalJSON(current.measurement.writers)!==canonicalJSON(fixed.plan.writers))throw new PlacementActivationInputError("writer root");
|
|
@@ -173,12 +178,15 @@ export async function activateSyncPlacement(options:PlacementActivationOptions)
|
|
|
173
178
|
preparePlacementEpoch(home,fixed.epoch,fixed.plan,{mutation,assertCurrent:check});await options.checkpoint?.("after-epoch");check();
|
|
174
179
|
writeSyncPlacementWriterRoots(home,{epochHash,homeHash:fixed.epoch.homeHash,activationHash:fixed.plan.seal,roots:current.measurement.roots},fixed.plan.writers,{mutation,assertCurrent:check});await options.checkpoint?.("after-root-map");check();
|
|
175
180
|
const final=placementActivationFinalMarkers(fixed),markers=readPlacementRuntimeMarkers(home);
|
|
181
|
+
invalidateCuratedCaches(home);
|
|
176
182
|
if(canonicalJSON(markers.shards)+"\n"!==final.shards)writeProfileJSON(join(home,"shards.json"),JSON.parse(final.shards));else syncFile(join(home,"shards.json"));
|
|
177
183
|
await options.checkpoint?.("after-shards");check();
|
|
178
184
|
if(canonicalJSON(readPlacementRuntimeMarkers(home).profile)+"\n"!==final.profile)writeProfileJSON(join(home,"profile.json"),JSON.parse(final.profile));else syncFile(join(home,"profile.json"));
|
|
179
185
|
await options.checkpoint?.("after-profile");check();
|
|
180
186
|
ensurePlacementFence(home,epochHash,{mutation,assertCurrent:check});await options.checkpoint?.("after-fence");metadataCheck();return finishCommittedActivation(home,fixed,options,mutation,owner,fixed,report);
|
|
181
|
-
});
|
|
187
|
+
});
|
|
188
|
+
return result;
|
|
189
|
+
}catch(error){
|
|
182
190
|
try{options.testOnlyFailure?.(error);}catch{/* observers never affect production outcomes */}
|
|
183
191
|
return rethrowActivationFailure(error);
|
|
184
192
|
}
|
|
@@ -50,6 +50,7 @@ export async function syncPlacementMemory(store: MemoryStore, opts: SyncOptions
|
|
|
50
50
|
class PlacementTransport {
|
|
51
51
|
readonly store: MemoryStore; readonly opts: SyncOptions; readonly phase?: Phase; readonly testOnlyError?: (error:unknown)=>void; readonly home: string; readonly root: string; readonly cache: string;
|
|
52
52
|
readonly releases: (() => void)[] = []; readonly temporary: string[] = []; readonly refs: string[] = [];
|
|
53
|
+
releaseCurated?: () => void;
|
|
53
54
|
targets: Target[] = []; homeMutation?: MutationHandle; rootMutation?: MutationHandle; cacheIdentity?: {dev:number;ino:number}; cacheConfigIdentity?: string; epochHash = ""; journal!: PlacementJournalRead; capture?: PlacementCapture;
|
|
54
55
|
machineId = ""; url = ""; revision = ""; accepted = false; factual = false; attempted = false; lastPolicyCheckUnixMs?: number; lastPolicyHash?: string; policyCheckSource?: "live"|"durable-intent"; attemptHash?: string;
|
|
55
56
|
evaluator?: ReturnType<typeof outboundPolicyEvaluator>; applications?: ShardSyncApplications; current?: Materialized; recovered = false;
|
|
@@ -136,6 +137,7 @@ class PlacementTransport {
|
|
|
136
137
|
const handle = acquireMutation(dir); if (!handle) refuse(); this.releases.push(handle); if (dir === this.home) this.homeMutation = handle;
|
|
137
138
|
for (const target of this.targets) if (target.store.dir === dir) target.mutation = handle;
|
|
138
139
|
}
|
|
140
|
+
this.releaseCurated = this.store.beginCuratedCacheUpdate();
|
|
139
141
|
this.journal = readPlacementJournal(this.home, this.epochHash); this.revision = readSelector(this.home).revision; this.attest();
|
|
140
142
|
if (!existing) await this.required(["init", "--bare", "--template=", "--object-format=sha1", "-q", this.cache]);
|
|
141
143
|
if (!await this.independent()) refuse();
|
|
@@ -495,6 +497,7 @@ class PlacementTransport {
|
|
|
495
497
|
for(const file of this.temporary)try{this.metadata();rmSync(file,{force:true});}catch{}
|
|
496
498
|
}
|
|
497
499
|
for(const release of this.releases.reverse())try{release();}catch{}
|
|
500
|
+
this.releaseCurated?.();
|
|
498
501
|
}
|
|
499
502
|
}
|
|
500
503
|
}
|
package/src/memory/sync.ts
CHANGED
|
@@ -274,10 +274,11 @@ export async function syncMemory(store: MemoryStore, opts: SyncOptions = {}): Pr
|
|
|
274
274
|
if (!opts.remote && !existsSync(join(dir, ".git"))) return fail(noRemote); // never set up: nothing to do, nothing created
|
|
275
275
|
const release = lock(dir);
|
|
276
276
|
if (!release) return fail("another sync is running on this machine");
|
|
277
|
-
let releaseMutation: (() => void) | undefined;
|
|
277
|
+
let releaseMutation: (() => void) | undefined, releaseCurated: (() => void) | undefined;
|
|
278
278
|
try {
|
|
279
279
|
releaseMutation = acquireMutation(dir);
|
|
280
280
|
if (!releaseMutation) return fail("another memory mutation is running on this machine");
|
|
281
|
+
releaseCurated = store.beginCuratedCacheUpdate();
|
|
281
282
|
// Holding sync.lock, no other git runs in this repository: what a killed one left behind is stale.
|
|
282
283
|
rmSync(join(dir, ".git", "index.lock"), { force: true });
|
|
283
284
|
if (existsSync(join(dir, ".git", "MERGE_HEAD"))) await git(dir, ["merge", "--abort"]);
|
|
@@ -341,5 +342,5 @@ export async function syncMemory(store: MemoryStore, opts: SyncOptions = {}): Pr
|
|
|
341
342
|
});
|
|
342
343
|
} catch (e) {
|
|
343
344
|
return fail((e as Error).message.slice(0, 200));
|
|
344
|
-
} finally { try { releaseMutation?.(); } finally { release(); } }
|
|
345
|
+
} finally { try { releaseMutation?.(); } finally { try { releaseCurated?.(); } finally { release(); } } }
|
|
345
346
|
}
|
|
@@ -63,9 +63,10 @@ if (import.meta.main) {
|
|
|
63
63
|
const line = await next();
|
|
64
64
|
if (line === undefined) stop();
|
|
65
65
|
const first = JSON.parse(line) as Record<string, unknown>;
|
|
66
|
-
type Scan = { cwd: string; base: string; transcript: unknown; policy?: BriefOptions["policy"]; deadlineAt: number };
|
|
66
|
+
type Scan = { cwd: string; base: string; transcript: unknown; policy?: BriefOptions["policy"]; deadlineAt: number; event?: "Stop" | "SessionEnd" };
|
|
67
67
|
type DrainOptions = BriefOptions & { current: string; event: string; identity?: unknown; deadlineAt: number; ownedGroup: boolean; hookStartAt?: number };
|
|
68
68
|
const scan = first.scan as Scan | undefined;
|
|
69
|
+
const scanEvent = scan?.event === "Stop" || scan?.event === "SessionEnd" ? scan.event : undefined;
|
|
69
70
|
const deadlineAt = scan?.deadlineAt ?? first.deadlineAt;
|
|
70
71
|
if (!Number.isFinite(deadlineAt) || first.ownedGroup !== true) stop();
|
|
71
72
|
owned = true;
|
|
@@ -89,6 +90,7 @@ if (import.meta.main) {
|
|
|
89
90
|
ready.then(() => { receiptReady = true; }, () => { /* The final drain reports failure inside the owned helper. */ });
|
|
90
91
|
const budget = hookReplayBudget();
|
|
91
92
|
let drainedCount = 0, captured = false, drainStarted = false;
|
|
93
|
+
let summaryThrough = 0, preparedThrough = 0;
|
|
92
94
|
const replay = async (until: number, waitForReady = true) => {
|
|
93
95
|
// Scanning must not wait on native metadata or cold store imports between summary lines.
|
|
94
96
|
// The final replay may await them; publication/backpressure callbacks only use ready resources.
|
|
@@ -107,9 +109,17 @@ if (import.meta.main) {
|
|
|
107
109
|
const drained = await drainHookCaptures({ ...options, base: options.base!, project, expectedScope, timeRemaining: remaining, replayBudget: budget }, (input, receipt) => {
|
|
108
110
|
store ??= new CaptureStore({ memoryDir: options.base!, project, busyTimeoutMs: 0, cwd: options.cwd });
|
|
109
111
|
const appended = store.append(input, { receipt });
|
|
112
|
+
summaryThrough = Math.max(summaryThrough, store.briefCommitId);
|
|
110
113
|
drain({ drained: ++drainedCount }); // DB commit or durable capture-spool acknowledgement, as in the existing contract.
|
|
111
114
|
return appended;
|
|
112
115
|
});
|
|
116
|
+
if (summaryThrough > preparedThrough && store) {
|
|
117
|
+
try {
|
|
118
|
+
const { buildCaptureBriefCache } = await import("./brief-capture.ts");
|
|
119
|
+
await buildCaptureBriefCache(store, { base: options.base!, project, cwd: options.cwd, builtThrough: summaryThrough, policy: options.policy });
|
|
120
|
+
preparedThrough = summaryThrough;
|
|
121
|
+
} catch { /* Derived cache failure never loses committed capture. A later summary retries. */ }
|
|
122
|
+
}
|
|
113
123
|
captured ||= drained.captured.includes(options.current);
|
|
114
124
|
return drained.captured.length > 0;
|
|
115
125
|
};
|
|
@@ -123,7 +133,8 @@ if (import.meta.main) {
|
|
|
123
133
|
const scanned = await scanHookTranscriptTail(scan.transcript, {
|
|
124
134
|
cwd: scan.cwd, base: scan.base, policy: scan.policy, workBudgetMs: 60, deadline: performance.now() + (scanEnd - now()),
|
|
125
135
|
// Same existing oldest-first drain and one shared budget, never a new 32-file allowance per publication.
|
|
126
|
-
|
|
136
|
+
// SessionEnd stages its bounded tail first; pressure and the final replay keep the same allowance.
|
|
137
|
+
onPublication: scanEvent === "SessionEnd" ? undefined : async () => { await replay(scanEnd, false); },
|
|
127
138
|
onBackpressure: () => replay(scanEnd, false),
|
|
128
139
|
});
|
|
129
140
|
if (scanned) progress(scanned);
|