@staix/agent-mem 0.26.1 → 0.26.3
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 +4 -1
- package/package.json +1 -1
- package/src/cli.ts +31 -1
- package/src/commands-table.ts +3 -1
- package/src/memory/bridge.ts +3 -1
- package/src/memory/config.ts +11 -1
- package/src/memory/shard-sync-history.ts +5 -1
- 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 +27 -9
- package/src/memory/sync-placement-dependencies.ts +6 -4
- package/src/memory/sync-placement-inspection.ts +1 -1
- 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-transport.ts +100 -41
- package/src/memory/sync-progress.ts +192 -0
- package/src/memory/sync.ts +14 -3
|
@@ -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: {
|