@staix/agent-mem 0.26.2 → 0.27.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 +8 -3
- package/package.json +1 -1
- package/src/brief-curated-native.ts +1 -1
- package/src/brief-curated.ts +5 -0
- package/src/cli.ts +31 -1
- package/src/commands-table.ts +5 -3
- package/src/hooks.ts +9 -4
- package/src/index.ts +1 -0
- package/src/mcp-memory.ts +10 -2
- package/src/mcp.ts +1 -1
- package/src/memory/commands.ts +13 -5
- package/src/memory/config.ts +11 -1
- package/src/memory/metrics.ts +40 -1
- package/src/memory/recall-staleness.ts +7 -4
- package/src/memory/shard-sync-history.ts +5 -1
- package/src/memory/store.ts +22 -9
- package/src/memory/sync-placement-active.ts +21 -0
- package/src/memory/sync-placement-bound.ts +39 -0
- package/src/memory/sync-placement-capture.ts +2 -1
- package/src/memory/sync-placement-dependencies.ts +6 -4
- package/src/memory/sync-placement-journal-storage.ts +70 -15
- package/src/memory/sync-placement-materialize.ts +20 -9
- package/src/memory/sync-placement-projection.ts +10 -1
- package/src/memory/sync-placement-publication-plan.ts +4 -2
- package/src/memory/sync-placement-refusal-category.ts +3 -0
- package/src/memory/sync-placement-refusal.ts +49 -0
- package/src/memory/sync-placement-transport.ts +138 -59
- package/src/memory/sync-progress.ts +197 -0
- package/src/memory/sync.ts +17 -3
- package/src/memory/task-group.ts +33 -0
- package/src/session-brief.ts +39 -13
package/src/memory/store.ts
CHANGED
|
@@ -32,6 +32,7 @@ import { readMigrationSources } from "./migrate.ts";
|
|
|
32
32
|
import type { PruneSourceRow, PruneStorePort } from "./prune.ts";
|
|
33
33
|
import { isDeepStrictEqual } from "node:util";
|
|
34
34
|
import { registerReaderLease, type ReaderLease } from "./reader-lease.ts";
|
|
35
|
+
import { groupByTask, taskGroupKey } from "./task-group.ts";
|
|
35
36
|
|
|
36
37
|
/**
|
|
37
38
|
* #258: the hub's own memory. Append-only JSONL logs are the truth: `log/<machine>.jsonl` holds long-term entries and
|
|
@@ -181,8 +182,12 @@ export interface SearchFilter extends Filter {
|
|
|
181
182
|
explain?: boolean;
|
|
182
183
|
/** A host that writes capture with a `retentionDays` override passes the same value here; files decide otherwise. */
|
|
183
184
|
captureRetentionDays?: number;
|
|
185
|
+
/** #423: fold curated hits that share a task into the best-scoring one (default true); false returns every hit. */
|
|
186
|
+
groupTasks?: boolean;
|
|
184
187
|
}
|
|
185
|
-
export interface SearchHit { source: "curated" | "capture"; score: number;
|
|
188
|
+
export interface SearchHit { source: "curated" | "capture"; score: number;
|
|
189
|
+
/** #423: curated hits of the same task folded into this one (absent when none, or with `groupTasks: false`). */
|
|
190
|
+
folded?: number; scoreDetails?: SearchScoreDetails; view?: View; capture?: CaptureRow }
|
|
186
191
|
export interface SearchResult { engine: "fts5" | "substring"; hits: SearchHit[] }
|
|
187
192
|
export interface Graph { nodes: { id: Node; type: string; label: string; kind?: string; tier?: Tier }[]; edges: { from: Node; to: Node; rel: string }[] }
|
|
188
193
|
|
|
@@ -1269,11 +1274,15 @@ export class MemoryStore {
|
|
|
1269
1274
|
*/
|
|
1270
1275
|
search(q: string, f: SearchFilter = {}): SearchResult {
|
|
1271
1276
|
const limit = f.limit ?? 200;
|
|
1272
|
-
if (!this.searchIndex.available)
|
|
1273
|
-
const
|
|
1274
|
-
|
|
1275
|
-
return
|
|
1276
|
-
|
|
1277
|
+
if (!this.searchIndex.available) {
|
|
1278
|
+
const listed = this.list({ ...f, q, limit: f.groupTasks === false ? f.limit : Number.MAX_SAFE_INTEGER });
|
|
1279
|
+
const kept = f.groupTasks === false ? listed.map(item => ({ item, folded: 0 })) : groupByTask(listed, view => view).slice(0, f.limit ?? 200);
|
|
1280
|
+
return { engine: "substring", hits: kept.map(({ item: view, folded }) => {
|
|
1281
|
+
const hit: SearchHit = { source: "curated", score: 0, view, ...(folded ? { folded } : {}) };
|
|
1282
|
+
if (f.explain) hit.scoreDetails = unrankedScoreDetails("curated", hit.score);
|
|
1283
|
+
return hit;
|
|
1284
|
+
}) };
|
|
1285
|
+
}
|
|
1277
1286
|
const visible = new Map(this.live(f).filter((v) => (!f.project || this.inScope(v.project, f.project) || v.scope === "shared")
|
|
1278
1287
|
&& (!f.since || Date.parse(v.at) >= Date.parse(f.since)) && (f.includeSuperseded || !v.supersededBy)).map((v) => [v.id, v]));
|
|
1279
1288
|
for (const store of this.readStores()) store.syncSearchIndex();
|
|
@@ -1290,14 +1299,17 @@ export class MemoryStore {
|
|
|
1290
1299
|
const page = Math.max(limit * 4, 32);
|
|
1291
1300
|
for (const store of visible.size ? this.readStores() : []) {
|
|
1292
1301
|
let found = 0;
|
|
1293
|
-
const seen = new Set<string>(); // another process's sync between pages can shift offsets and repeat a ref
|
|
1302
|
+
const seen = new Set<string>(), groups = new Set<string>(); // another process's sync between pages can shift offsets and repeat a ref
|
|
1294
1303
|
for (let offset = 0; found < limit; offset += page) {
|
|
1295
1304
|
const ranked = store.searchIndex.query(q, page, f.project === undefined ? undefined : this.scopeKeys(f.project), offset);
|
|
1296
1305
|
for (const hit of ranked) {
|
|
1297
1306
|
const view = visible.get(hit.ref);
|
|
1298
1307
|
if (!view || seen.has(hit.ref)) continue;
|
|
1299
1308
|
seen.add(hit.ref);
|
|
1300
|
-
|
|
1309
|
+
// #423: a folded same-task hit takes no slot, so the walk goes on until `limit` distinct groups.
|
|
1310
|
+
const group = f.groupTasks === false ? undefined : taskGroupKey(view);
|
|
1311
|
+
if (group === undefined || !groups.has(group)) found++;
|
|
1312
|
+
if (group !== undefined) groups.add(group);
|
|
1301
1313
|
const selected: SearchHit = { source: "curated", score: rankedScore(hit.rank, view.tier, hit.at, now), view };
|
|
1302
1314
|
if (f.explain) selected.scoreDetails = rankedScoreDetails("curated", hit.rank, view.tier, hit.at, now, selected.score);
|
|
1303
1315
|
hits.push(selected);
|
|
@@ -1334,7 +1346,8 @@ export class MemoryStore {
|
|
|
1334
1346
|
}
|
|
1335
1347
|
const ref = (h: SearchHit): string => h.view?.id ?? String(h.capture?.id ?? 0).padStart(12, "0");
|
|
1336
1348
|
hits.sort((a, b) => b.score - a.score || ref(a).localeCompare(ref(b)));
|
|
1337
|
-
const
|
|
1349
|
+
const grouped = f.groupTasks === false ? hits : groupByTask(hits, hit => hit.view).map(({ item, folded }) => folded ? { ...item, folded } : item);
|
|
1350
|
+
const baseline = grouped.slice(0, limit), captureSlots = baseline.filter(hit => hit.source === "capture").length;
|
|
1338
1351
|
if (!captureSlots || !captureShard) return { engine: "fts5", hits: baseline };
|
|
1339
1352
|
// Stream session representatives in complete weighted-score order; the legacy
|
|
1340
1353
|
// baseline above still owns noncapture slots and exposed scores remain unweighted.
|
|
@@ -35,10 +35,30 @@ export function assertPlacementViewAdvance(home: string, activation: SyncPlaceme
|
|
|
35
35
|
if (old !== undefined && !chain.commitments.includes(old)) fail();
|
|
36
36
|
}
|
|
37
37
|
}
|
|
38
|
+
/**
|
|
39
|
+
* Last verified binding keyed by the lstat stamps of every object the full read checks (#420). A sync calls this several
|
|
40
|
+
* times per fence check; an unchanged stamp is the same identity the full read already accepts between its own reads.
|
|
41
|
+
* ponytail: one entry per process; drop it if a same-size rewrite inside one timestamp tick must be caught across calls.
|
|
42
|
+
*/
|
|
43
|
+
const freeze = <T>(value: T): T => { if (value && typeof value === "object" && !Object.isFrozen(value)) { for (const inner of Object.values(value)) freeze(inner); Object.freeze(value); } return value; };
|
|
44
|
+
let bindingMemo: { key: string; value: Pick<ActivePlacementBinding, "epoch" | "activation"> } | undefined;
|
|
38
45
|
/** No mutation/reader registration/index open. Missing preparation is distinct from malformed retained evidence. */
|
|
39
46
|
export function readActivePlacementBinding(homeInput: string, profileInput: unknown, shardsInput: unknown): ActivePlacementBinding | undefined {
|
|
40
47
|
const profile = validatePlacementProfile(profileInput), shards = validatePlacementShards(shardsInput, profile);
|
|
41
48
|
const home = realPath(homeInput), root = lstatSync(home, { bigint: true }); owned(root, true);
|
|
49
|
+
const stampKey = () => {
|
|
50
|
+
const dir = join(home, "sync-placement", "epochs", profile.placementHead), stamps: string[] = [];
|
|
51
|
+
for (const [file, isDir] of [[home, true], [join(home, "sync-placement"), true], [join(home, "sync-placement", "epochs"), true], [dir, true], [join(dir, "epoch.json"), false],
|
|
52
|
+
[join(dir, "activation.json"), false], [join(home, "sync-placement", "active.json"), false], [join(home, "profile.json"), false], [join(home, "shards.json"), false]] as const) {
|
|
53
|
+
const st = lstatSync(file, { bigint: true, throwIfNoEntry: false }); if (!st) return undefined; owned(st, isDir);
|
|
54
|
+
stamps.push([st.dev, st.ino, st.size, st.mtimeNs, st.ctimeNs].map(String).join(":"));
|
|
55
|
+
}
|
|
56
|
+
return canonicalJSON([home, canonicalJSON(profile), canonicalJSON(shards), stamps]);
|
|
57
|
+
}, memoKey = stampKey();
|
|
58
|
+
if (memoKey !== undefined && bindingMemo?.key === memoKey) {
|
|
59
|
+
assertPlacementViewAdvance(home, bindingMemo.value.activation, profile, shards);
|
|
60
|
+
return { profile, shards, epoch: bindingMemo.value.epoch, activation: bindingMemo.value.activation };
|
|
61
|
+
}
|
|
42
62
|
const checks: (() => void)[] = [() => { const now = lstatSync(home, { bigint: true }); owned(now, true); if (now.dev !== root.dev || now.ino !== root.ino) fail(); }];
|
|
43
63
|
const directory = (dir: string): boolean => {
|
|
44
64
|
const s = lstatSync(dir, { bigint: true, throwIfNoEntry: false }); if (!s) return false; owned(s, true);
|
|
@@ -71,5 +91,6 @@ export function readActivePlacementBinding(homeInput: string, profileInput: unkn
|
|
|
71
91
|
if (read(join(home, "profile.json"))?.text !== canonicalJSON(profile) + "\n" || read(join(home, "shards.json"))?.text !== canonicalJSON(shards) + "\n") fail();
|
|
72
92
|
assertPlacementViewAdvance(home, activation, profile, shards);
|
|
73
93
|
for (const check of checks) check();
|
|
94
|
+
if (memoKey !== undefined && stampKey() === memoKey) bindingMemo = { key: memoKey, value: { epoch: freeze(epoch), activation: freeze(activation) } };
|
|
74
95
|
return { profile, shards, epoch, activation };
|
|
75
96
|
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
/** Placement sync size contract and its privacy-safe refusal receipt (#419). Numbers only: no row, path or policy text. */
|
|
2
|
+
import { types } from "node:util";
|
|
3
|
+
import { SyncPlacementJournalError } from "./sync-placement-journal-format.ts";
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* One source envelope from activation to first sync: home-wide capture, the selected-source prefixes a publication
|
|
7
|
+
* plan binds, and the canonical rows materialization admits (selected sources plus verified incoming rows) share
|
|
8
|
+
* 64 MiB and 20000 rows. Journal limits are separate and unchanged (20000 records and 256 objects per epoch).
|
|
9
|
+
*/
|
|
10
|
+
export const PLACEMENT_SOURCE_MAX_BYTES = 64 * 1024 * 1024, PLACEMENT_SOURCE_MAX_ROWS = 20000;
|
|
11
|
+
|
|
12
|
+
export type PlacementSyncBoundPhase = "source-capture" | "materialization" | "publication-plan";
|
|
13
|
+
const KINDS = ["source-bytes", "source-rows", "journal-records", "journal-objects", "bytes", "rows", "source-files", "metadata-bytes", "row-bytes", "retained-identities"] as const;
|
|
14
|
+
export type PlacementSyncBoundKind = typeof KINDS[number];
|
|
15
|
+
export interface PlacementSyncBound { phase: PlacementSyncBoundPhase; kind: PlacementSyncBoundKind; limit: number; observed: number }
|
|
16
|
+
|
|
17
|
+
const phases: Record<PlacementSyncBoundPhase, string> = { "source-capture": "source capture", materialization: "materialization", "publication-plan": "publication planning" };
|
|
18
|
+
export function placementSyncBoundMessage(bound: PlacementSyncBound): string {
|
|
19
|
+
const remedy = bound.kind === "journal-records" || bound.kind === "journal-objects"
|
|
20
|
+
? "The active epoch journal cannot hold this publication; retain the inputs and report this bound."
|
|
21
|
+
: "Retain the inputs and report this bound; no row was omitted to fit.";
|
|
22
|
+
return `Placement sync refused before any publication attempt: ${phases[bound.phase]} exceeds its supported ${bound.kind} bound (observed ${bound.observed}, limit ${bound.limit}). No source, selector, epoch, journal or remote ref was changed. ${remedy}`;
|
|
23
|
+
}
|
|
24
|
+
/** Expected input refusal before a publication attempt exists. Code stays "bound" for existing callers. */
|
|
25
|
+
export class PlacementSyncBoundError extends SyncPlacementJournalError {
|
|
26
|
+
constructor(readonly bound: PlacementSyncBound) { super("bound"); this.message = placementSyncBoundMessage(bound); this.name = "PlacementSyncBoundError"; }
|
|
27
|
+
}
|
|
28
|
+
/** Only allowlisted own data properties of a journal bound error become a receipt; any other exception yields none. */
|
|
29
|
+
export function placementSyncBoundReceipt(error: unknown): PlacementSyncBound | undefined {
|
|
30
|
+
try {
|
|
31
|
+
if (!error || typeof error !== "object" || types.isProxy(error) || !(error instanceof SyncPlacementJournalError)) return undefined;
|
|
32
|
+
const own = (object: object, key: string): unknown => Object.getOwnPropertyDescriptor(object, key)?.value;
|
|
33
|
+
const raw = own(error, "bound"); if (own(error, "code") !== "bound" || !raw || typeof raw !== "object" || types.isProxy(raw)) return undefined;
|
|
34
|
+
const kind = own(raw, "kind"), limit = own(raw, "limit"), observed = own(raw, "observed"), phase = own(raw, "phase") ?? "source-capture";
|
|
35
|
+
if (typeof kind !== "string" || !(KINDS as readonly string[]).includes(kind) || typeof phase !== "string" || !Object.hasOwn(phases, phase)
|
|
36
|
+
|| typeof limit !== "number" || !Number.isSafeInteger(limit) || limit < 0 || typeof observed !== "number" || !Number.isSafeInteger(observed) || observed < 0) return undefined;
|
|
37
|
+
return { phase: phase as PlacementSyncBoundPhase, kind: kind as PlacementSyncBoundKind, limit, observed };
|
|
38
|
+
} catch { return undefined; }
|
|
39
|
+
}
|
|
@@ -23,9 +23,10 @@ import { activationSourceMarkers, assertPlacementActivationOwner, type Placement
|
|
|
23
23
|
import { readEffectiveSyncPlacementWriters, writerBoundPlacementContextHash, writerInventoryEvidence, type EffectiveSyncPlacementWriters } from "./sync-placement-effective-writers.ts";
|
|
24
24
|
import { SharedWriterRevisionError } from "./sync-placement-writer-revision-format.ts";
|
|
25
25
|
import { inspectionBoundReceipt, type InspectionBound } from "./inspection-bound.ts";
|
|
26
|
+
import { PLACEMENT_SOURCE_MAX_BYTES, PLACEMENT_SOURCE_MAX_ROWS } from "./sync-placement-bound.ts";
|
|
26
27
|
|
|
27
28
|
/** Home-wide source capture ceilings. Every file is read twice (bytes, then a stable recheck), so the read budget is 2x. */
|
|
28
|
-
export const PLACEMENT_CAPTURE_MAX_SOURCE_BYTES =
|
|
29
|
+
export const PLACEMENT_CAPTURE_MAX_SOURCE_BYTES = PLACEMENT_SOURCE_MAX_BYTES, PLACEMENT_CAPTURE_MAX_ROWS = PLACEMENT_SOURCE_MAX_ROWS;
|
|
29
30
|
/** Source capture refusal before any effect. Code stays "bound" for existing callers; the message names the phase and bound. */
|
|
30
31
|
export class PlacementSourceBoundError extends SyncPlacementJournalError {
|
|
31
32
|
constructor(readonly bound?: InspectionBound) {
|
|
@@ -6,6 +6,7 @@ import { validatePruneRow } from "./prune.ts";
|
|
|
6
6
|
import { SUGGESTED } from "./store.ts";
|
|
7
7
|
import { placementKeyId, validatePlacementKey, type PlacementKey, type PlacementRealm } from "./sync-placement-journal-format.ts";
|
|
8
8
|
import type { OutboundVerdict, SyncPolicyCategory } from "./sync-screen.ts";
|
|
9
|
+
import { PLACEMENT_SOURCE_MAX_BYTES, PLACEMENT_SOURCE_MAX_ROWS } from "./sync-placement-bound.ts";
|
|
9
10
|
|
|
10
11
|
export interface DependencySource {
|
|
11
12
|
key: PlacementKey; row: unknown; sourcePlacement: "local" | "synced"; policy: OutboundVerdict; held: boolean;
|
|
@@ -85,11 +86,12 @@ function preflight(raw: unknown): void {
|
|
|
85
86
|
const source = descriptors(sources.own[String(i)]!.value), row = source.row;
|
|
86
87
|
if (!row || !("value" in row)) return fail();
|
|
87
88
|
bytes += size(row.value, 0) + 1;
|
|
88
|
-
if (bytes >
|
|
89
|
+
if (bytes > PLACEMENT_SOURCE_MAX_BYTES) fail();
|
|
89
90
|
}
|
|
90
91
|
for (const key of ["publicEndpoints", "verifiedPrunes"]) if (fields[key]) arrayFields(fields[key]!.value, 20000);
|
|
91
92
|
}
|
|
92
|
-
/** ponytail: descriptor-only JSON safety stops at
|
|
93
|
+
/** ponytail: descriptor-only JSON safety stops at depth 64, one million nodes and twice the 64 MiB source envelope
|
|
94
|
+
* (selected rows plus already-public endpoint evidence, which never exceeds the rows it backs; #419, 16 MiB before 0.26.3).
|
|
93
95
|
* A reviewed chunked endpoint interface is required before larger proofs can enter this compiler. */
|
|
94
96
|
function copyInput(value: unknown): unknown {
|
|
95
97
|
let bytes = 0, nodes = 0;
|
|
@@ -98,7 +100,7 @@ function copyInput(value: unknown): unknown {
|
|
|
98
100
|
if (++nodes > 1_000_000 || depth > 64) fail();
|
|
99
101
|
if (v === null || typeof v === "boolean") { bytes += 5; return v; }
|
|
100
102
|
if (typeof v === "number") { if (!Number.isFinite(v)) fail(); bytes += 24; return v; }
|
|
101
|
-
if (typeof v === "string") { bytes += Buffer.byteLength(v); if (bytes >
|
|
103
|
+
if (typeof v === "string") { bytes += Buffer.byteLength(v); if (bytes > 2 * PLACEMENT_SOURCE_MAX_BYTES) fail(); return v; }
|
|
102
104
|
if (!v || typeof v !== "object" || types.isProxy(v) || seen.has(v) || Object.getOwnPropertySymbols(v).length) fail();
|
|
103
105
|
const array = Array.isArray(v), proto = Object.getPrototypeOf(v);
|
|
104
106
|
if (array ? proto !== Array.prototype : proto !== Object.prototype && proto !== null) fail();
|
|
@@ -168,7 +170,7 @@ function compile(raw: PlacementDependencyInput): DependencyDecision[] {
|
|
|
168
170
|
const key = validatePlacementKey(item.key), row = object(item.row), id = placementKeyId(key);
|
|
169
171
|
if (!selected.has(realmId(key.realm)) || row.id !== key.id || hashJSON(row) !== key.rowHash) fail();
|
|
170
172
|
if (hashes.has(key.id) && hashes.get(key.id) !== key.rowHash) fail(); hashes.set(key.id, key.rowHash);
|
|
171
|
-
if (output && (sourceBytes += Buffer.byteLength(canonicalJSON(row) + "\n")) >
|
|
173
|
+
if (output && (sourceBytes += Buffer.byteLength(canonicalJSON(row) + "\n")) > PLACEMENT_SOURCE_MAX_BYTES + PLACEMENT_SOURCE_MAX_ROWS) fail();
|
|
172
174
|
let policy: OutboundVerdict = { ok: true };
|
|
173
175
|
if (output) {
|
|
174
176
|
const verdict = object(item.policy); keys(verdict, ["ok"], ["category"]);
|
|
@@ -119,15 +119,36 @@ function intent(value: unknown, epochHash: string): Intent {
|
|
|
119
119
|
|| input.lineHash !== digest(line(record)) || input.prefixBytes + line(record).length > PLACEMENT_JOURNAL_CHUNK_MAX_BYTES) return fail();
|
|
120
120
|
return { schema: input.schema, epochHash, record, chunk: input.chunk, prefixBytes: input.prefixBytes, prefixHash: input.prefixHash, lineHash: input.lineHash };
|
|
121
121
|
}
|
|
122
|
+
const stamp = (stat: BigIntStats) => [String(stat.dev), String(stat.ino), String(stat.size), String(stat.mtimeNs), String(stat.ctimeNs)].join(":");
|
|
123
|
+
const freeze = <T>(value: T): T => { if (value && typeof value === "object" && !Object.isFrozen(value)) { for (const inner of Object.values(value)) freeze(inner); Object.freeze(value); } return value; };
|
|
124
|
+
/**
|
|
125
|
+
* Decoded journal prefix (every chunk but the last) keyed by directory and the stat stamps of epoch.json and those chunks (#420).
|
|
126
|
+
* Appends only grow the last chunk or add a new one, so a sync re-decodes at most one 64 KiB chunk per snapshot instead of
|
|
127
|
+
* the whole journal. A changed stamp is a miss and the chunk is read and decoded again; the end-of-snapshot token check still runs.
|
|
128
|
+
* ponytail: one entry per process and stat stamps as identity (the same trust the token check already gives an unchanged file);
|
|
129
|
+
* keep a content digest per chunk if an in-place same-size rewrite inside one timestamp tick must be caught.
|
|
130
|
+
*/
|
|
131
|
+
let journalPrefix: { key: string; count: number; records: PlacementRecord[]; chunks: Chunk[]; projection: PlacementProjection } | undefined;
|
|
132
|
+
/** Decoded last chunk, matched by its bytes: a grown last chunk decodes only the appended suffix (#420). */
|
|
133
|
+
let journalTail: { key: string; name: string; bytes: Buffer; records: PlacementRecord[]; projection: PlacementProjection } | undefined;
|
|
134
|
+
/** Whole snapshot for an unchanged inventory token (every file snapshot reads is in it). Callers get fresh arrays and a projection clone. */
|
|
135
|
+
let journalSnapshot: { token: string; value: Snapshot } | undefined;
|
|
136
|
+
/** Drop every decoded journal/publication memo; a sync calls this when it ends so a resident host never keeps a journal's records. */
|
|
137
|
+
export function releasePlacementStorageCaches(): void { journalPrefix = undefined; journalTail = undefined; journalSnapshot = undefined; publicationBundle = undefined; reservationRoot = undefined; }
|
|
138
|
+
// Records are frozen and shared (the bulk); every small mutable field is a fresh copy, so a caller's mutation never reaches the memo.
|
|
139
|
+
const detachSnapshot = (value: Snapshot): Snapshot => ({ ...value, records: value.records.map(freeze), chunks: value.chunks.map(chunk => ({ ...chunk })), projection: value.projection.clone(),
|
|
140
|
+
epoch: structuredClone(value.epoch), activation: structuredClone(value.activation),
|
|
141
|
+
...(value.intent ? { intent: structuredClone(value.intent) } : {}), ...(value.pendingRecord ? { pendingRecord: structuredClone(value.pendingRecord) } : {}) });
|
|
122
142
|
function snapshot(p: Paths): Snapshot {
|
|
123
143
|
const before = inventory(p);
|
|
144
|
+
if (journalSnapshot?.token === canonicalJSON([p.dir, before.token])) return detachSnapshot(journalSnapshot.value);
|
|
124
145
|
const epoch = decode(readOwned(join(p.dir, "epoch.json"), PLACEMENT_JOURNAL_ROOT_MAX_BYTES), validatePlacementEpoch);
|
|
125
146
|
if (placementEpochHash(epoch) !== p.hash) return fail("conflict");
|
|
126
147
|
const plan = decode(readOwned(join(p.dir, "activation.json"), PLACEMENT_JOURNAL_ROOT_MAX_BYTES), value => activation(epoch, p.hash, value));
|
|
127
148
|
const pendingBytes = readOwned(join(p.dir, "append-intent.json"), PLACEMENT_JOURNAL_ROOT_MAX_BYTES);
|
|
128
149
|
const intentPending = pendingBytes !== undefined && (!pendingBytes.length || pendingBytes.at(-1) !== 10);
|
|
129
150
|
const pending = pendingBytes && !intentPending ? decode(pendingBytes, value => intent(value, p.hash)) : undefined;
|
|
130
|
-
|
|
151
|
+
let projection = new PlacementProjection(epoch); const records: PlacementRecord[] = [], chunks: Chunk[] = [];
|
|
131
152
|
const apply = (bytes: Buffer) => {
|
|
132
153
|
let start = 0;
|
|
133
154
|
while (start < bytes.length) {
|
|
@@ -137,7 +158,13 @@ function snapshot(p: Paths): Snapshot {
|
|
|
137
158
|
}
|
|
138
159
|
};
|
|
139
160
|
const chunkNames = [...before.files.keys()].filter(name => /^records-\d{5}\.jsonl$/.test(name));
|
|
161
|
+
const prefixKey = (count: number) => canonicalJSON([p.dir, stamp(before.files.get("epoch.json")!), chunkNames.slice(0, count).map(name => [name, stamp(before.files.get(name)!)])]);
|
|
162
|
+
const cached = journalPrefix && journalPrefix.count < chunkNames.length && journalPrefix.key === prefixKey(journalPrefix.count) ? journalPrefix : undefined;
|
|
163
|
+
let prefix: typeof journalPrefix, tail: typeof journalTail;
|
|
164
|
+
if (cached) { projection = cached.projection.clone(); records.push(...cached.records); chunks.push(...cached.chunks); }
|
|
140
165
|
for (const [index, name] of chunkNames.entries()) {
|
|
166
|
+
if (index < (cached?.count ?? 0)) continue;
|
|
167
|
+
if (index > 0 && index === chunkNames.length - 1) prefix = { key: prefixKey(index), count: index, records: records.map(freeze), chunks: [...chunks], projection: projection.clone() };
|
|
141
168
|
if (name !== `records-${String(index).padStart(5, "0")}.jsonl`) fail();
|
|
142
169
|
const bytes = readOwned(join(p.dir, name), PLACEMENT_JOURNAL_CHUNK_MAX_BYTES)!;
|
|
143
170
|
chunks.push({ name, size: bytes.length, hash: digest(bytes) });
|
|
@@ -148,7 +175,14 @@ function snapshot(p: Paths): Snapshot {
|
|
|
148
175
|
const suffix = bytes.subarray(pending.prefixBytes), expected = line(pending.record);
|
|
149
176
|
if (suffix.length > expected.length || !expected.subarray(0, suffix.length).equals(suffix)) fail();
|
|
150
177
|
if (suffix.length === expected.length) apply(suffix);
|
|
151
|
-
} else {
|
|
178
|
+
} else {
|
|
179
|
+
if (!bytes.length) fail();
|
|
180
|
+
const last = index === chunkNames.length - 1, known = last ? journalTail : undefined;
|
|
181
|
+
if (known && known.key === prefixKey(index) && known.name === name && bytes.length >= known.bytes.length && bytes.subarray(0, known.bytes.length).equals(known.bytes)) {
|
|
182
|
+
projection = known.projection.clone(); records.length = 0; records.push(...known.records); apply(bytes.subarray(known.bytes.length));
|
|
183
|
+
} else apply(bytes);
|
|
184
|
+
if (last) tail = { key: prefixKey(index), name, bytes: Buffer.from(bytes), records: records.map(freeze), projection: projection.clone() };
|
|
185
|
+
}
|
|
152
186
|
}
|
|
153
187
|
if (pending) {
|
|
154
188
|
const found = chunkNames.includes(pending.chunk);
|
|
@@ -167,7 +201,11 @@ function snapshot(p: Paths): Snapshot {
|
|
|
167
201
|
if ((records.length > 0 || pendingBytes !== undefined) && (!activeFence || fencePending || activeFence.epochHash !== p.hash
|
|
168
202
|
|| activeFence.homeHash !== epoch.homeHash || activeFence.generation !== epoch.generation)) fail();
|
|
169
203
|
if (inventory(p).token !== before.token) fail("changed");
|
|
170
|
-
|
|
204
|
+
if (prefix) journalPrefix = prefix;
|
|
205
|
+
if (tail) journalTail = tail;
|
|
206
|
+
const result: Snapshot = { epoch, activation: plan, records, projection, headHash: projection.headHash, sequence: projection.sequence, objects: before.files.size + 1 + before.renewalObjects, pending: !!pending || intentPending || fencePending, chunks, intentPending, fencePending, ...(pending ? { pendingRecordSequence: pending.record.sequence, pendingRecord: validatePlacementRecord(pending.record) } : {}), ...(pending ? { intent: pending } : {}) };
|
|
207
|
+
journalSnapshot = { token: canonicalJSON([p.dir, before.token]), value: detachSnapshot(result) };
|
|
208
|
+
return result;
|
|
171
209
|
}
|
|
172
210
|
export function readPlacementJournal(home: string, epochHash: string): PlacementJournalRead {
|
|
173
211
|
return protectedIO(() => {
|
|
@@ -349,14 +387,23 @@ export interface PlacementPublicationStored {
|
|
|
349
387
|
bundle: PlacementPublicationBundle; phase: "prepared" | "artifact-built" | "publication-intent" | "completed";
|
|
350
388
|
facts: PlacementPublicationFact[]; pending: boolean; pendingPhase?: PlacementPublicationFact["phase"];
|
|
351
389
|
}
|
|
390
|
+
/** Validated plan bundle keyed by the stat stamps of epoch.json, the root and every plan chunk (#420); same ceiling as journalPrefix. */
|
|
391
|
+
let publicationBundle: { key: string; bundle: PlacementPublicationBundle } | undefined;
|
|
352
392
|
function publicationRead(p: Paths, attemptHash: string): PlacementPublicationStored {
|
|
353
|
-
const stem = `publication-${attemptHash}-`,
|
|
354
|
-
const
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
393
|
+
const stem = `publication-${attemptHash}-`, files = inventory(p).files;
|
|
394
|
+
const keyOf = (found: Map<string, BigIntStats>) => canonicalJSON([p.dir, attemptHash, [...found].filter(([name]) => name === "epoch.json" || name === stem + "root.json" || name.startsWith(stem + "chunk-")).map(([name, stat]) => [name, stamp(stat)])]);
|
|
395
|
+
const key = keyOf(files);
|
|
396
|
+
let bundle = publicationBundle?.key === key ? publicationBundle.bundle : undefined;
|
|
397
|
+
if (!bundle) {
|
|
398
|
+
const root = decode(readOwned(join(p.dir, stem + "root.json"), PLACEMENT_JOURNAL_ROOT_MAX_BYTES), validatePlacementPublicationRoot);
|
|
399
|
+
const epoch = decode(readOwned(join(p.dir, "epoch.json"), PLACEMENT_JOURNAL_ROOT_MAX_BYTES), validatePlacementEpoch);
|
|
400
|
+
if (root.seal !== attemptHash || root.epochHash !== p.hash || root.generation !== epoch.generation || root.homeHash !== epoch.homeHash) fail("corrupt");
|
|
401
|
+
const chunks = root.chunks.map(c => decode(readOwned(join(p.dir, `${stem}chunk-${String(c.index).padStart(5, "0")}.json`), PLACEMENT_JOURNAL_CHUNK_MAX_BYTES), value => value));
|
|
402
|
+
bundle = freeze(validatePlacementPublicationBundle({ root, chunks }));
|
|
403
|
+
if (keyOf(inventory(p).files) === key) publicationBundle = { key, bundle }; // Never cache bytes read across a concurrent change.
|
|
404
|
+
}
|
|
405
|
+
const root = bundle.root, allowed = new Set(publicationFileNames(root));
|
|
406
|
+
for (const name of files.keys()) if (name.startsWith(stem) && !allowed.has(name)) fail("corrupt");
|
|
360
407
|
const facts: PlacementPublicationFact[] = []; let phase: PlacementPublicationStored["phase"] = "prepared", pending = false, absent = false; let pendingPhase: PlacementPublicationFact["phase"] | undefined;
|
|
361
408
|
for (const [index, suffix] of ["artifact", "intent", "receipt"].entries()) {
|
|
362
409
|
const bytes = readOwned(join(p.dir, stem + suffix + ".json"), PLACEMENT_JOURNAL_ROOT_MAX_BYTES);
|
|
@@ -409,12 +456,20 @@ function reservedPublicationJournalNames(p: Paths): string[] {
|
|
|
409
456
|
for (const root of complete) names.push(...placementPublicationReservedJournalNames(root, read, sizes));
|
|
410
457
|
return names;
|
|
411
458
|
}
|
|
459
|
+
/** A complete (newline-terminated) root is immutable: keep the last decoded one by its stat stamp (#420), same ceiling as journalPrefix. */
|
|
460
|
+
let reservationRoot: { key: string; root: PlacementPublicationRoot } | undefined;
|
|
412
461
|
function publicationRootsForReservation(p: Paths): PlacementPublicationRoot[] {
|
|
413
|
-
const roots: PlacementPublicationRoot[] = [];
|
|
414
|
-
for (const name of
|
|
415
|
-
const
|
|
416
|
-
|
|
417
|
-
|
|
462
|
+
const roots: PlacementPublicationRoot[] = [], files = inventory(p).files;
|
|
463
|
+
for (const [name, stat] of files) if (/^publication-[a-f0-9]{64}-root\.json$/.test(name)) {
|
|
464
|
+
const key = canonicalJSON([p.dir, name, stamp(stat)]);
|
|
465
|
+
let root = reservationRoot?.key === key ? reservationRoot.root : undefined;
|
|
466
|
+
if (!root) {
|
|
467
|
+
const bytes = readOwned(join(p.dir, name), PLACEMENT_JOURNAL_ROOT_MAX_BYTES);
|
|
468
|
+
if (!bytes?.length || bytes.at(-1) !== 10) continue;
|
|
469
|
+
root = freeze(decode(bytes, validatePlacementPublicationRoot));
|
|
470
|
+
const now = state(join(p.dir, name)); if (now && stamp(now) === stamp(stat)) reservationRoot = { key, root };
|
|
471
|
+
}
|
|
472
|
+
const receiptBytes = readOwned(join(p.dir, `publication-${root.seal}-receipt.json`), PLACEMENT_JOURNAL_ROOT_MAX_BYTES);
|
|
418
473
|
if (receiptBytes?.length && receiptBytes.at(-1) === 10) {
|
|
419
474
|
const read = publicationRead(p, root.seal); if (read.phase === "completed" && !read.pending) continue;
|
|
420
475
|
}
|
|
@@ -1,12 +1,13 @@
|
|
|
1
1
|
/** Shared internal row materialization. All source/transport authority and effect boundaries belong to the caller. */
|
|
2
2
|
import { createHash } from "node:crypto";
|
|
3
3
|
import { canonicalJSON, hashJSON } from "./generation.ts";
|
|
4
|
-
import {
|
|
4
|
+
import type { OutboundVerdict } from "./sync-screen.ts";
|
|
5
|
+
import { PLACEMENT_SOURCE_MAX_BYTES, PLACEMENT_SOURCE_MAX_ROWS, PlacementSyncBoundError } from "./sync-placement-bound.ts";
|
|
5
6
|
import type { PlacementCapture } from "./sync-placement-capture.ts";
|
|
6
7
|
import { compilePlacementDependencies, type DependencySource, type VerifiedDependencyEndpoint } from "./sync-placement-dependencies.ts";
|
|
7
8
|
import { compilePlacementGitObjects, type PlannedGitObject } from "./sync-placement-git.ts";
|
|
8
9
|
import { PLACEMENT_DESCRIPTOR_SCHEMA, PLACEMENT_FORMAT } from "./sync-placement-format.ts";
|
|
9
|
-
import { placementKeyId,
|
|
10
|
+
import { placementKeyId, type PlacementKey, type PlacementRealm } from "./sync-placement-journal-format.ts";
|
|
10
11
|
import type { PlacementProjection } from "./sync-placement-projection.ts";
|
|
11
12
|
import type { PlacementPublicationBundle, PlacementPublicationDecision, PlacementPublicationObject, PlacementPublicationTarget } from "./sync-placement-publication-plan.ts";
|
|
12
13
|
import type { ShardHistory } from "./shard-sync-history.ts";
|
|
@@ -26,6 +27,8 @@ export interface PlacementMaterializeInput {
|
|
|
26
27
|
readTree(index: number, head: string): Promise<string>;
|
|
27
28
|
publisherLineages(index: number, rows: readonly PruneRow[]): ReadonlyMap<string, PublicPruneLineage>;
|
|
28
29
|
createdUnixSeconds: number; frozen?: PlacementPublicationBundle;
|
|
30
|
+
/** Advisory telemetry only (#418): phase names and unit counts, never a row, key or verdict detail. */
|
|
31
|
+
progress?: { phase(name: "policy-evaluation" | "dependency-decisions" | "artifact-construction", unit?: "rows", total?: number): void; advance(): void };
|
|
29
32
|
}
|
|
30
33
|
export interface PlacementMaterializeTargetResult { candidate: ShardHistory; objects: PlannedGitObject[]; commit?: string }
|
|
31
34
|
export interface PlacementMaterializeResult {
|
|
@@ -54,26 +57,33 @@ export async function materializePlacementRows(input: PlacementMaterializeInput)
|
|
|
54
57
|
const {capture,projection,old,frozen,createdUnixSeconds}=input;
|
|
55
58
|
const workTargets = input.targets.map(target => ({...target,objects:[] as PlannedGitObject[],commit:undefined as string|undefined,candidate:undefined as ShardHistory|undefined}));
|
|
56
59
|
const sources: DependencySource[] = [], blocked = new Set<string>(), verified = input.verifiedPrunes;
|
|
57
|
-
|
|
58
|
-
|
|
60
|
+
// Collect every selected original first: size admission below is pure and precedes the first policy evaluation
|
|
61
|
+
// (and its writer proofs), so an unsupported source set refuses before any expensive per-row work (#419).
|
|
62
|
+
const admitted: Omit<DependencySource, "policy">[] = [], seenSources = new Set<string>();
|
|
59
63
|
const prunedByTarget = new Map(workTargets.map(target => [target, target.pruned]));
|
|
60
64
|
for (const source of capture.rows.values()) {
|
|
61
65
|
const target = workTargets.find(target => sameRealm(physical(target), source.key.realm)); if (!target) refuse();
|
|
62
66
|
const pruned = prunedByTarget.get(target)!.has(source.key.id) && !target.fetched.has(source.key.id);
|
|
63
67
|
if (pruned) blocked.add(placementKeyId(source.key));
|
|
64
|
-
|
|
68
|
+
seenSources.add(placementKeyId(source.key)); admitted.push({ key: source.key, row: source.row, sourcePlacement: source.sourcePlacement, held: !!projection.get(source.key)?.held || !!pruned });
|
|
65
69
|
}
|
|
66
70
|
for (const target of workTargets) for (const row of target.localPrunes.values()) {
|
|
67
|
-
const key = keyFor(target,row)
|
|
68
|
-
|
|
71
|
+
const key = keyFor(target,row), id = placementKeyId(key); if (seenSources.has(id)) continue;
|
|
72
|
+
seenSources.add(id); admitted.push({ key, row, sourcePlacement: "synced", held: !!projection.get(key)?.held });
|
|
69
73
|
}
|
|
70
74
|
// Incoming verified occurrences are selected immutable originals too. Classify them before import so a private
|
|
71
75
|
// remote goal cannot temporarily authorize a new dependent, and exposure/holds are durable in this same attempt.
|
|
72
|
-
const seenSources=new Set(sources.map(source=>placementKeyId(source.key)));
|
|
73
76
|
for(const [index,target]of workTargets.entries())for(const row of old[index]?.rows.values()??[])if(row.op!=="prune"||row.generation===target.generation){
|
|
74
77
|
const key=keyFor(target,row),id=placementKeyId(key);if(seenSources.has(id))continue;seenSources.add(id);
|
|
75
|
-
|
|
78
|
+
admitted.push({key,row,sourcePlacement:"synced",held:!!projection.get(key)?.held});
|
|
76
79
|
}
|
|
80
|
+
// Source size, not outbound size: local and declined rows count too, because their decisions are bound in the plan.
|
|
81
|
+
if (admitted.length > PLACEMENT_SOURCE_MAX_ROWS) throw new PlacementSyncBoundError({ phase: "materialization", kind: "source-rows", limit: PLACEMENT_SOURCE_MAX_ROWS, observed: admitted.length });
|
|
82
|
+
let sourceBytes = 0; for (const source of admitted) sourceBytes += Buffer.byteLength(canonicalJSON(source.row));
|
|
83
|
+
if (sourceBytes > PLACEMENT_SOURCE_MAX_BYTES) throw new PlacementSyncBoundError({ phase: "materialization", kind: "source-bytes", limit: PLACEMENT_SOURCE_MAX_BYTES, observed: sourceBytes });
|
|
84
|
+
input.progress?.phase("policy-evaluation", "rows", admitted.length);
|
|
85
|
+
for (const source of admitted) { sources.push({ ...source, policy: input.evaluate(source.row) }); input.progress?.advance(); }
|
|
86
|
+
input.progress?.phase("dependency-decisions");
|
|
77
87
|
// Strong endpoints are already in sources and current holds cannot be bypassed by past publication. Only
|
|
78
88
|
// deletion/prune exceptions need a second verified occurrence fact; do not duplicate every historical body.
|
|
79
89
|
const publicNeeded=new Set<string>();
|
|
@@ -126,6 +136,7 @@ export async function materializePlacementRows(input: PlacementMaterializeInput)
|
|
|
126
136
|
}
|
|
127
137
|
}
|
|
128
138
|
target.objects=[];
|
|
139
|
+
if(pass===0&&index===0)input.progress?.phase("artifact-construction");
|
|
129
140
|
if(publish){
|
|
130
141
|
const previous=old[index]&&target.remote?{tree:await input.readTree(index,frozen?.root.targets[index]?.expectedRemoteHead??target.remote!),commit:frozen?.root.targets[index]?.expectedRemoteHead??target.remote!}:undefined;
|
|
131
142
|
const objects=compilePlacementGitObjects(files,frozen?.root.targets[index]?.expectedRemoteHead??target.remote??null,createdUnixSeconds,previous);target.objects=objects.objects;target.commit=objects.commit;
|
|
@@ -17,12 +17,21 @@ const identity = (key: PlacementKey) => canonicalJSON([key.realm, key.id]);
|
|
|
17
17
|
/** Data projection only. Journal fields and committed-outcome syntax are not person or remote-proof credentials. */
|
|
18
18
|
export class PlacementProjection {
|
|
19
19
|
readonly #epochHash: string;
|
|
20
|
+
readonly #epoch: PlacementEpoch;
|
|
20
21
|
#sequence = 0;
|
|
21
22
|
#headHash: string;
|
|
22
23
|
readonly #states = new Map<string, PlacementProjectedState>();
|
|
23
24
|
readonly #rowHashes = new Map<string, string>();
|
|
24
25
|
readonly #requests = new Map<string, PlacementRecord>();
|
|
25
|
-
constructor(epoch: PlacementEpoch) { this.#epochHash = placementEpochHash(
|
|
26
|
+
constructor(epoch: PlacementEpoch) { this.#epoch = validatePlacementEpoch(epoch); this.#epochHash = placementEpochHash(this.#epoch); this.#headHash = this.#epochHash; }
|
|
27
|
+
/** Independent copy: stored states and records are never mutated in place (apply copies, readers get copies), so sharing them is safe. */
|
|
28
|
+
clone(): PlacementProjection {
|
|
29
|
+
const out = new PlacementProjection(this.#epoch); out.#sequence = this.#sequence; out.#headHash = this.#headHash;
|
|
30
|
+
for (const [key, value] of this.#states) out.#states.set(key, value);
|
|
31
|
+
for (const [key, value] of this.#rowHashes) out.#rowHashes.set(key, value);
|
|
32
|
+
for (const [key, value] of this.#requests) out.#requests.set(key, value);
|
|
33
|
+
return out;
|
|
34
|
+
}
|
|
26
35
|
get epochHash(): string { return this.#epochHash; }
|
|
27
36
|
get sequence(): number { return this.#sequence; }
|
|
28
37
|
get headHash(): string { return this.#headHash; }
|
|
@@ -9,6 +9,7 @@ export const PLACEMENT_PUBLICATION_PLAN_SCHEMA = "agent-mem.sync-placement-publi
|
|
|
9
9
|
export const PLACEMENT_PUBLICATION_CHUNK_SCHEMA = "agent-mem.sync-placement-publication-chunk/v1";
|
|
10
10
|
export const PLACEMENT_PUBLICATION_FACT_SCHEMA = "agent-mem.sync-placement-publication-fact/v1";
|
|
11
11
|
/** Closed hold/outcome events fit this bound; reserve future journal capacity before any publication effect. */
|
|
12
|
+
import { PLACEMENT_SOURCE_MAX_BYTES } from "./sync-placement-bound.ts";
|
|
12
13
|
export const PLACEMENT_PUBLICATION_RECORD_MAX_BYTES = 2048;
|
|
13
14
|
export interface PlacementPublicationSource {
|
|
14
15
|
realm: PlacementRealm; source: "generation" | "legacy-local" | "legacy-main"; pathHash: string;
|
|
@@ -66,7 +67,7 @@ function bounded<T>(value: T, maximum: number): T { if (publicationBytes(value).
|
|
|
66
67
|
function item(kind: PlacementPublicationChunkKind, input: unknown): PlacementPublicationSource | PlacementPublicationDecision | PlacementPublicationObject {
|
|
67
68
|
if (kind === "sources") {
|
|
68
69
|
const v = object(input, ["realm", "source", "pathHash", "dev", "ino", "byteLength", "hash", "mtimeNs", "ctimeNs"]);
|
|
69
|
-
if (!["generation", "legacy-local", "legacy-main"].includes(v.source as string) || !hex(v.pathHash) || !hex(v.hash) || !number(v.byteLength,
|
|
70
|
+
if (!["generation", "legacy-local", "legacy-main"].includes(v.source as string) || !hex(v.pathHash) || !hex(v.hash) || !number(v.byteLength, PLACEMENT_SOURCE_MAX_BYTES)
|
|
70
71
|
|| ![v.dev, v.ino].every(x => typeof x === "string" && !/[\r\n]/.test(x) && /^(?:0|[1-9][0-9]{0,31})$/.test(x))
|
|
71
72
|
|| ![v.mtimeNs, v.ctimeNs].every(x => typeof x === "string" && !/[\r\n]/.test(x) && /^-?(?:0|[1-9][0-9]{0,31})$/.test(x))) return fail();
|
|
72
73
|
return { realm: realm(v.realm), source: v.source as PlacementPublicationSource["source"], pathHash: v.pathHash, dev: v.dev as string, ino: v.ino as string, byteLength: v.byteLength, hash: v.hash, mtimeNs: v.mtimeNs as string, ctimeNs: v.ctimeNs as string };
|
|
@@ -142,7 +143,8 @@ export function validatePlacementPublicationBundle(input: unknown): PlacementPub
|
|
|
142
143
|
const key = chunk.kind + identity; if (seen.has(key)) return fail(); seen.add(key);
|
|
143
144
|
}
|
|
144
145
|
}
|
|
145
|
-
|
|
146
|
+
// The selected prefixes are a subset of what capture admitted under the same ceiling (#419); 8 MiB before 0.26.3.
|
|
147
|
+
if (sourceBytes > PLACEMENT_SOURCE_MAX_BYTES) return fail("bound");
|
|
146
148
|
return { root, chunks };
|
|
147
149
|
}
|
|
148
150
|
export function planPlacementPublication(input: Omit<PlacementPublicationRoot, "schema" | "chunks" | "seal">, items: {
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
/** #426: the fixed refusal categories of a placement sync; shared by the transport and the progress sidecar. */
|
|
2
|
+
export const PLACEMENT_REFUSAL_CATEGORIES = ["epoch", "source-selection", "policy", "remote", "writer-pin", "size-bound", "lock", "other"] as const;
|
|
3
|
+
export type PlacementRefusalCategory = typeof PLACEMENT_REFUSAL_CATEGORIES[number];
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* #426: why a placement sync refused before a publication attempt existed, as a fixed category and the phase it was in.
|
|
3
|
+
* Category, phase and next step are fixed strings: no path, row content, URL or secret ever reaches the message.
|
|
4
|
+
*/
|
|
5
|
+
import { types } from "node:util";
|
|
6
|
+
import type { SyncProgressPhase } from "./sync-progress.ts";
|
|
7
|
+
|
|
8
|
+
import { PLACEMENT_REFUSAL_CATEGORIES, type PlacementRefusalCategory } from "./sync-placement-refusal-category.ts";
|
|
9
|
+
export { PLACEMENT_REFUSAL_CATEGORIES, type PlacementRefusalCategory };
|
|
10
|
+
|
|
11
|
+
/** One next step per category (AC2). */
|
|
12
|
+
const NEXT: Record<PlacementRefusalCategory, string> = {
|
|
13
|
+
epoch: "Check the active placement epoch with amem migrate --sync-placement --dry-run; do not restore v2 markers.",
|
|
14
|
+
"source-selection": "Another writer changed the selected sources during the run; close other memory writers, then rerun amem sync.",
|
|
15
|
+
policy: "The memory policy changed or is not attested; reload the host so it passes the current policy, then rerun amem sync.",
|
|
16
|
+
remote: "Check the private sync remote (amem sync --remote <url> once, and that the repository is private and reachable), then rerun amem sync.",
|
|
17
|
+
"writer-pin": "A writer sharing this home no longer matches its recorded install; upgrade it to the pinned version, or have the person review amem migrate --sync-placement --dry-run --writer-root <install root> to re-pin it, then rerun amem sync.",
|
|
18
|
+
"size-bound": "Retain the inputs and report this bound; no row was omitted to fit.",
|
|
19
|
+
lock: "Another sync or memory writer holds this home; wait for it to finish (amem sync --status), then rerun amem sync.",
|
|
20
|
+
other: "Rerun amem sync; if it refuses again, report the category and phase shown here.",
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
/** A refusal raised by the transport itself, tagged where the failing check is known. */
|
|
24
|
+
export class PlacementSyncRefusal extends Error {
|
|
25
|
+
readonly category: PlacementRefusalCategory;
|
|
26
|
+
constructor(category: PlacementRefusalCategory = "other") {
|
|
27
|
+
const safe = (PLACEMENT_REFUSAL_CATEGORIES as readonly string[]).includes(category) ? category : "other";
|
|
28
|
+
super("placement sync unavailable"); this.name = "PlacementSyncRefusal"; this.category = safe;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Reads only an own, allowlisted `category` of a real PlacementSyncRefusal; anything else is `undefined`. */
|
|
33
|
+
export function placementRefusalCategoryOf(error: unknown): PlacementRefusalCategory | undefined {
|
|
34
|
+
try {
|
|
35
|
+
if (!error || typeof error !== "object" || types.isProxy(error) || !(error instanceof PlacementSyncRefusal)) return undefined;
|
|
36
|
+
const value = Object.getOwnPropertyDescriptor(error, "category")?.value;
|
|
37
|
+
return typeof value === "string" && (PLACEMENT_REFUSAL_CATEGORIES as readonly string[]).includes(value) ? value as PlacementRefusalCategory : undefined;
|
|
38
|
+
} catch { return undefined; }
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export function placementRefusalNextStep(category: PlacementRefusalCategory): string { return NEXT[category]; }
|
|
42
|
+
|
|
43
|
+
/** AC1/AC4: the person-facing refusal. `other` keeps the generic wording and still names the phase. */
|
|
44
|
+
export function placementRefusalMessage(category: PlacementRefusalCategory, phase: SyncProgressPhase): string {
|
|
45
|
+
const where = phase.replaceAll("-", " ");
|
|
46
|
+
return category === "other"
|
|
47
|
+
? `Placement sync is unavailable (category other, phase ${where}); verify the active epoch, selected sources, policy, private remote and writer pins before retrying. ${NEXT.other}`
|
|
48
|
+
: `Placement sync refused (category ${category}, phase ${where}). ${NEXT[category]}`;
|
|
49
|
+
}
|