@staix/agent-mem 0.28.2 → 0.30.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 +17 -11
- package/package.json +3 -2
- package/src/brief-work.ts +142 -0
- package/src/cli.ts +97 -17
- package/src/commands-table.ts +6 -0
- package/src/mcp-memory.ts +37 -9
- package/src/memory/bridge.ts +26 -1
- package/src/memory/capacity.ts +5 -2
- package/src/memory/catalog.ts +10 -1
- package/src/memory/commands.ts +5 -3
- package/src/memory/curated-cache-state.ts +10 -7
- package/src/memory/doctor.ts +32 -26
- package/src/memory/formats.ts +4 -3
- package/src/memory/generation-index.ts +79 -17
- package/src/memory/index-file.ts +2 -2
- package/src/memory/intent-brief.ts +34 -6
- package/src/memory/metrics.ts +174 -14
- package/src/memory/shard-bridge.ts +18 -6
- package/src/memory/shard-sync-format.ts +18 -0
- package/src/memory/shard-sync-history.ts +6 -0
- package/src/memory/shard-sync.ts +52 -4
- package/src/memory/shard.ts +33 -13
- package/src/memory/store.ts +147 -41
- package/src/memory/sync-placement-bound.ts +21 -4
- package/src/memory/sync-placement-cache.ts +16 -1
- package/src/memory/sync-placement-capture.ts +67 -19
- package/src/memory/sync-placement-checkpoint-format.ts +199 -0
- package/src/memory/sync-placement-checkpoint-person.ts +209 -0
- package/src/memory/sync-placement-checkpoint-prospective.ts +141 -0
- package/src/memory/sync-placement-checkpoint-storage.ts +218 -0
- package/src/memory/sync-placement-checkpoint.ts +234 -0
- package/src/memory/sync-placement-dependencies.ts +42 -9
- package/src/memory/sync-placement-effective-writers.ts +12 -6
- package/src/memory/sync-placement-git.ts +17 -7
- package/src/memory/sync-placement-guard.ts +52 -1
- package/src/memory/sync-placement-inspection-evidence.ts +1 -1
- package/src/memory/sync-placement-inventory.ts +141 -0
- package/src/memory/sync-placement-journal-format.ts +4 -1
- package/src/memory/sync-placement-journal-storage.ts +148 -28
- package/src/memory/sync-placement-journal.ts +13 -4
- package/src/memory/sync-placement-materialize.ts +47 -22
- package/src/memory/sync-placement-projection.ts +7 -1
- package/src/memory/sync-placement-publication-events.ts +42 -0
- package/src/memory/sync-placement-publication-plan.ts +26 -5
- package/src/memory/sync-placement-realm-admission-storage.ts +128 -0
- package/src/memory/sync-placement-realm-admission.ts +352 -0
- package/src/memory/sync-placement-realm-attribution.ts +23 -0
- package/src/memory/sync-placement-realm-discovery.ts +42 -0
- package/src/memory/sync-placement-realm-effective.ts +71 -0
- package/src/memory/sync-placement-realm-extension-format.ts +66 -0
- package/src/memory/sync-placement-realm-extension-storage.ts +82 -0
- package/src/memory/sync-placement-realm-intent-format.ts +55 -0
- package/src/memory/sync-placement-realm-intent-storage.ts +123 -0
- package/src/memory/sync-placement-realm-pending.ts +27 -0
- package/src/memory/sync-placement-realm-proof.ts +131 -0
- package/src/memory/sync-placement-realm-torn.ts +26 -0
- package/src/memory/sync-placement-remote-admission.ts +190 -0
- package/src/memory/sync-placement-remote-adoption-format.ts +54 -0
- package/src/memory/sync-placement-remote-materialization.ts +49 -0
- package/src/memory/sync-placement-remote-refusal.ts +21 -0
- package/src/memory/sync-placement-remote-stage.ts +275 -0
- package/src/memory/sync-placement-transport.ts +268 -79
- package/src/memory/sync-placement-writer-history.ts +75 -17
- package/src/memory/sync-placement-writer-renewal.ts +18 -10
- package/src/memory/sync-placement-writer-revision-format.ts +16 -13
- package/src/memory/sync-placement-yield.ts +44 -0
- package/src/memory/sync-progress.ts +47 -6
- package/src/memory/sync.ts +26 -1
- package/src/memory/work-lists.ts +129 -9
- package/src/session-brief.ts +34 -1
- package/src/sync-placement-writer-context.ts +5 -5
- package/src/ui/plugin.ts +1 -1
|
@@ -3,6 +3,7 @@ import { createHash } from "node:crypto";
|
|
|
3
3
|
import { types } from "node:util";
|
|
4
4
|
import { PUBLIC_PRUNE_REPLAY_MAX_BYTES } from "./public-prune-input-chain.ts";
|
|
5
5
|
import { decodePlacementTransportDescriptor, decodeShardManifest, isShardManifestPath, SHARD_PACK_MAX_BYTES, type ShardSyncRealm } from "./shard-sync-format.ts";
|
|
6
|
+
import { drainSteps, drainStepsAsync, type CooperativeYield } from "./sync-placement-yield.ts";
|
|
6
7
|
|
|
7
8
|
export interface PlannedGitObject { type: "blob" | "tree" | "commit"; oid: string; bytes: Buffer; path: string | null }
|
|
8
9
|
export interface PlacementGitObjects { objects: PlannedGitObject[]; tree: string; commit: string }
|
|
@@ -27,10 +28,17 @@ function object(type: PlannedGitObject["type"], bytes: Buffer, path: string | nu
|
|
|
27
28
|
* Retained public bytes share the existing replay bound; new source's separate 8MiB allowance is the caller's proof. */
|
|
28
29
|
export function compilePlacementGitObjects(files: ReadonlyMap<string, Uint8Array>, parent: string | null, createdUnixSeconds: number,
|
|
29
30
|
previous?: { tree: string; commit: string }): PlacementGitObjects {
|
|
30
|
-
try { return
|
|
31
|
+
try { return drainSteps(compileSteps(files, parent, createdUnixSeconds, previous)); } catch { return fail(); }
|
|
31
32
|
}
|
|
32
|
-
|
|
33
|
-
|
|
33
|
+
/** #470: the same objects, awaiting the caller's event loop between entries and tree nodes; bytes and ids are identical. */
|
|
34
|
+
export async function compilePlacementGitObjectsAsync(files: ReadonlyMap<string, Uint8Array>, parent: string | null, createdUnixSeconds: number,
|
|
35
|
+
previous?: { tree: string; commit: string }, yieldPoint?: CooperativeYield): Promise<PlacementGitObjects> {
|
|
36
|
+
try { return await drainStepsAsync(compileSteps(files, parent, createdUnixSeconds, previous), yieldPoint); } catch { return fail(); }
|
|
37
|
+
}
|
|
38
|
+
/** Objects between step boundaries: at most 128 blob hashes per uninterrupted stretch. */
|
|
39
|
+
const STEP_OBJECTS = 128;
|
|
40
|
+
function* compileSteps(files: ReadonlyMap<string, Uint8Array>, parent: string | null, createdUnixSeconds: number,
|
|
41
|
+
previous?: { tree: string; commit: string }): Generator<void, PlacementGitObjects, void> {
|
|
34
42
|
if (!files || typeof files !== "object" || types.isProxy(files) || Object.getPrototypeOf(files) !== Map.prototype
|
|
35
43
|
|| !Number.isSafeInteger(createdUnixSeconds) || createdUnixSeconds < 0 || parent !== null && !oid(parent)) return fail();
|
|
36
44
|
const count = mapSize.call(files);
|
|
@@ -42,9 +50,10 @@ function compile(files: ReadonlyMap<string, Uint8Array>, parent: string | null,
|
|
|
42
50
|
|| !oid(fields.tree.value) || !oid(fields.commit.value)) return fail();
|
|
43
51
|
previous = { tree: fields.tree.value, commit: fields.commit.value };
|
|
44
52
|
}
|
|
45
|
-
const entries: { path: string; bytes: Buffer }[] = []; let total = 0;
|
|
53
|
+
const entries: { path: string; bytes: Buffer }[] = []; let total = 0, stepped = 0;
|
|
46
54
|
for (const [path, value] of Map.prototype.entries.call(files) as Iterable<[unknown, unknown]>) {
|
|
47
55
|
if (typeof path !== "string" || types.isProxy(value) || !(value instanceof Uint8Array)) return fail();
|
|
56
|
+
if (++stepped >= STEP_OBJECTS) { stepped = 0; yield; }
|
|
48
57
|
const pack = PACK.exec(path), validPack = pack?.[0] === path;
|
|
49
58
|
if (path !== "shard.json" && !validPack && !isShardManifestPath(path)) return fail();
|
|
50
59
|
const length = getLength.call(value) as number, maximum = validPack ? SHARD_PACK_MAX_BYTES : 64 * 1024;
|
|
@@ -70,10 +79,11 @@ function compile(files: ReadonlyMap<string, Uint8Array>, parent: string | null,
|
|
|
70
79
|
for (const name of parts.slice(0, -1)) { if (target.blobs.has(name)) return fail(); let next = target.directories.get(name); if (!next) target.directories.set(name, next = node()); target = next; }
|
|
71
80
|
const name = parts.at(-1)!; if (target.directories.has(name) || target.blobs.has(name)) return fail(); target.blobs.set(name, blob.oid);
|
|
72
81
|
}
|
|
73
|
-
const buildTree = (tree: TreeNode, path: string): string
|
|
82
|
+
const buildTree = function* (tree: TreeNode, path: string): Generator<void, string, void> {
|
|
74
83
|
const children: { name: string; oid: string; directory: boolean }[] = [...tree.blobs].map(([name, id]) => ({ name, oid: id, directory: false }));
|
|
84
|
+
if (++stepped >= STEP_OBJECTS) { stepped = 0; yield; }
|
|
75
85
|
for (const [name, directory] of [...tree.directories].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0))
|
|
76
|
-
children.push({ name, oid: buildTree(directory, path ? `${path}/${name}` : name), directory: true });
|
|
86
|
+
children.push({ name, oid: yield* buildTree(directory, path ? `${path}/${name}` : name), directory: true });
|
|
77
87
|
children.sort((a,b) => Buffer.compare(Buffer.from(a.name + (a.directory ? "/" : "")), Buffer.from(b.name + (b.directory ? "/" : ""))));
|
|
78
88
|
let length = 0; const chunks: Buffer[] = [];
|
|
79
89
|
for (const child of children) {
|
|
@@ -82,7 +92,7 @@ function compile(files: ReadonlyMap<string, Uint8Array>, parent: string | null,
|
|
|
82
92
|
}
|
|
83
93
|
const result = object("tree", Buffer.concat(chunks, length), path); trees.push(result); return result.oid;
|
|
84
94
|
};
|
|
85
|
-
const tree = buildTree(root, "");
|
|
95
|
+
const tree = yield* buildTree(root, "");
|
|
86
96
|
trees.sort((a,b) => (b.path ? b.path.split("/").length : 0) - (a.path ? a.path.split("/").length : 0)
|
|
87
97
|
|| (a.path! < b.path! ? -1 : a.path! > b.path! ? 1 : 0));
|
|
88
98
|
objects.push(...trees);
|
|
@@ -1,4 +1,10 @@
|
|
|
1
|
-
import { readActivePlacementBinding } from "./sync-placement-active.ts";
|
|
1
|
+
import { readActivePlacementBinding, type ActivePlacementBinding } from "./sync-placement-active.ts";
|
|
2
|
+
import { readEffectiveRealmInventory, type EffectiveRealmInventory } from "./sync-placement-realm-effective.ts";
|
|
3
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
4
|
+
import { tmpdir } from "node:os";
|
|
5
|
+
import { mkdirSync, mkdtempSync, rmSync } from "node:fs";
|
|
6
|
+
import { canonicalJSON } from "./generation.ts";
|
|
7
|
+
import { realPath } from "./platform.ts";
|
|
2
8
|
import { types } from "node:util";
|
|
3
9
|
/** Closed activation metadata admits v3 readers; publication still requires full journal/source/policy proof. */
|
|
4
10
|
import { closeSync, constants, fstatSync, lstatSync, openSync, readSync, type BigIntStats } from "node:fs";
|
|
@@ -9,6 +15,49 @@ import { PLACEMENT_PROFILE_SCHEMA, PLACEMENT_SHARDS_SCHEMA, validatePlacementPro
|
|
|
9
15
|
import { PLACEMENT_ACTIVATION_INTENT } from "./sync-placement-activation-path.ts";
|
|
10
16
|
import { profileLockRefusal, rememberProfileLockError } from "./profile-lock-diagnostic.ts";
|
|
11
17
|
|
|
18
|
+
// The capability can only name the fresh scratch home made below, never a caller-supplied directory.
|
|
19
|
+
const doctorContext = new AsyncLocalStorage<{ home: string; dev: bigint; ino: bigint; realHome: string; binding?: ActivePlacementBinding }>();
|
|
20
|
+
export async function withDoctorPlacementScratch<T>(realHome: string, adopt: (dir: string) => void, run: (scratch: string) => Promise<T>): Promise<T> {
|
|
21
|
+
const scratch = mkdtempSync(join(tmpdir(), `amem-doctor-${process.pid}-`));
|
|
22
|
+
try {
|
|
23
|
+
adopt(scratch);
|
|
24
|
+
const directory = join(scratch, "home"); mkdirSync(directory, { mode: 0o700 });
|
|
25
|
+
const home = realPath(directory);
|
|
26
|
+
const stat = lstatSync(home, { bigint: true });
|
|
27
|
+
let binding: ActivePlacementBinding | undefined;
|
|
28
|
+
try {
|
|
29
|
+
if (!placementRuntimeRefusal(realHome)) {
|
|
30
|
+
const markers = readPlacementRuntimeMarkers(realHome);
|
|
31
|
+
if (schema(markers.profile) === PLACEMENT_PROFILE_SCHEMA) binding = readActivePlacementBinding(realHome, markers.profile, markers.shards);
|
|
32
|
+
}
|
|
33
|
+
} catch { /* A changed real binding leaves scratch unadmitted; doctor reports its real-home refusal. */ }
|
|
34
|
+
return await doctorContext.run({ home, dev: stat.dev, ino: stat.ino, realHome, binding }, () => run(scratch));
|
|
35
|
+
} finally { rmSync(scratch, { recursive: true, force: true }); }
|
|
36
|
+
}
|
|
37
|
+
/** A scratch binding is valid only while the original v3 home and both copied markers still match. */
|
|
38
|
+
export function doctorScratchBinding(home: string): ActivePlacementBinding | undefined {
|
|
39
|
+
const context = doctorContext.getStore();
|
|
40
|
+
if (!context?.binding) return undefined;
|
|
41
|
+
try {
|
|
42
|
+
if (realPath(home) !== context.home) return undefined;
|
|
43
|
+
const stat = lstatSync(home, { bigint: true });
|
|
44
|
+
if (!stat.isDirectory() || stat.isSymbolicLink() || stat.dev !== context.dev || stat.ino !== context.ino) return undefined;
|
|
45
|
+
const real = readPlacementRuntimeMarkers(context.realHome), copy = readPlacementRuntimeMarkers(home);
|
|
46
|
+
if (placementRuntimeRefusal(context.realHome) || canonicalJSON(real) !== canonicalJSON(copy)) return undefined;
|
|
47
|
+
return readActivePlacementBinding(context.realHome, real.profile, real.shards);
|
|
48
|
+
} catch { return undefined; }
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** Only the private doctor scratch capability can borrow the real home's freshly verified inventory. */
|
|
52
|
+
export function doctorScratchInventory(home: string): EffectiveRealmInventory | undefined {
|
|
53
|
+
const binding = doctorScratchBinding(home), context = doctorContext.getStore();
|
|
54
|
+
if (!binding || !context) return undefined;
|
|
55
|
+
const inventory = readEffectiveRealmInventory(context.realHome, binding);
|
|
56
|
+
if (!doctorScratchBinding(home)) return undefined;
|
|
57
|
+
inventory.assertCurrent();
|
|
58
|
+
return inventory;
|
|
59
|
+
}
|
|
60
|
+
|
|
12
61
|
export const PLACEMENT_STAGE1_REFUSAL = "sync placement v3 requires matching durable activation metadata; keep the current compatible profile active until person-authorized activation is complete";
|
|
13
62
|
export const PLACEMENT_MARKER_REFUSAL = "sync placement metadata is invalid or unsupported; person inspection and a compatible reader are required before continuing";
|
|
14
63
|
export const PLACEMENT_ACTIVATION_PENDING = "sync placement activation is pending or incomplete; have the person inspect retained evidence and run amem migrate --sync-placement --resume, or --abandon only while both markers retain their original v2 bytes";
|
|
@@ -66,6 +115,7 @@ export function placementMarkerRefusal(profile: unknown, shards: unknown): strin
|
|
|
66
115
|
/** Selector preflight only recognizes v3. Legacy malformed/split metadata must retain its existing reader/recovery path. */
|
|
67
116
|
// This narrow probe is not a data/transport gate; effects must still use the full runtime guard.
|
|
68
117
|
export function placementSelectorRefusal(home: string): string | undefined {
|
|
118
|
+
if (doctorScratchBinding(home)) return undefined;
|
|
69
119
|
const refusal=selectorRefusal(home);return refusal?profileLockRefusal(home)??refusal:undefined;
|
|
70
120
|
}
|
|
71
121
|
function selectorRefusal(home:string):string|undefined {
|
|
@@ -92,6 +142,7 @@ function placementFencePresent(home: string): boolean {
|
|
|
92
142
|
/** Bounded activation/view metadata only; no data/index open, cache mutation, lock or child/network call.
|
|
93
143
|
* The v3 publication coordinator separately proves the complete journal, selected sources and policy. */
|
|
94
144
|
export function placementRuntimeRefusal(home: string, bound?: Pick<BoundProfile,"kind"|"sharded"|"generation"|"publicationFormat"|"placementHead">): string | undefined {
|
|
145
|
+
if (doctorScratchBinding(home)) return undefined;
|
|
95
146
|
try { const fenced = placementFencePresent(home), pending = placementActivationPending(home), markers = readPlacementRuntimeMarkers(home);
|
|
96
147
|
const refusal = placementMarkerRefusal(markers.profile, markers.shards);
|
|
97
148
|
if (refusal === PLACEMENT_STAGE1_REFUSAL) {
|
|
@@ -29,7 +29,7 @@ export function captureInspectionJournal(home: string, epochHash: string): Inspe
|
|
|
29
29
|
const captured = capturePlacementPublicationMetadata(home, epochHash, io => {
|
|
30
30
|
const journal = io.journal();
|
|
31
31
|
if (journal.pending) throw new SyncPlacementJournalError("pending");
|
|
32
|
-
const attempts = new Set<string>();
|
|
32
|
+
const attempts = new Set<string>(io.archivedPublications());
|
|
33
33
|
for (const name of io.names()) {
|
|
34
34
|
const match = /^publication-([a-f0-9]{64})-/.exec(name);
|
|
35
35
|
if (match) attempts.add(match[1]!);
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* #450: one `amem sync` under an active placement covers the whole activated realm inventory, not only the cwd binding.
|
|
3
|
+
*
|
|
4
|
+
* The persisted publication plan still holds at most two targets (0.28.x readers validate exactly that), so the inventory
|
|
5
|
+
* runs as sequential publications of at most two realms each. Atomicity, journal, reservation and crash recovery are those
|
|
6
|
+
* of one publication, unchanged; nothing is atomic across the whole inventory. Order is deterministic: the user realm is
|
|
7
|
+
* in the first publication, then project realms by key hash. A publication that does not succeed stops the run before the
|
|
8
|
+
* next one. A retained publication reservation is resumed first, through its own realms, before any new publication.
|
|
9
|
+
*
|
|
10
|
+
* ponytail: ceil(N/2) publications. One N-target plan behind an explicitly raised `sync` floor is the upgrade path.
|
|
11
|
+
*/
|
|
12
|
+
import { createHash } from "node:crypto";
|
|
13
|
+
import { existsSync, lstatSync } from "node:fs";
|
|
14
|
+
import { join } from "node:path";
|
|
15
|
+
import { readActivePlacementBinding } from "./sync-placement-active.ts";
|
|
16
|
+
import { readPlacementRuntimeMarkers } from "./sync-placement-guard.ts";
|
|
17
|
+
import { readPlacementJournal } from "./sync-placement-journal-storage.ts";
|
|
18
|
+
import { PLACEMENT_CHECKPOINT_PENDING_MESSAGE, placementCheckpointPending } from "./sync-placement-checkpoint-storage.ts";
|
|
19
|
+
import { readPlacementPublication } from "./sync-placement-publication-storage.ts";
|
|
20
|
+
import { readEffectiveRealmInventory } from "./sync-placement-realm-effective.ts";
|
|
21
|
+
import { readShardDescriptor, shardDir, userShardDir } from "./shard.ts";
|
|
22
|
+
import { projectState } from "./lifecycle.ts";
|
|
23
|
+
import type { PlacementRealm } from "./sync-placement-journal-format.ts";
|
|
24
|
+
import type { SyncOptions, SyncResult } from "./sync.ts";
|
|
25
|
+
import type { MemoryStore } from "./store.ts";
|
|
26
|
+
|
|
27
|
+
const digest = (value: string) => createHash("sha256").update(value).digest("hex");
|
|
28
|
+
const PUBLICATION_TARGETS = 2;
|
|
29
|
+
|
|
30
|
+
/** One activated realm with its local key (the project key is resolved from the local descriptor; user has none). */
|
|
31
|
+
export type InventoryRealm = { scope: "user" } | { scope: "project"; key: string; keyHash: string };
|
|
32
|
+
export type PlacementRealmOutcome = "committed" | "not-needed" | "unknown" | "failed" | "not-run" | "not-local" | "inactive";
|
|
33
|
+
/** Per-realm receipt: identifiers only (the user realm or the full key hash), never a project name, row or path. */
|
|
34
|
+
export interface PlacementRealmResult { realm: "user" | string; outcome: PlacementRealmOutcome; publication?: number }
|
|
35
|
+
|
|
36
|
+
const label = (realm: PlacementRealm | InventoryRealm): string => realm.scope === "user" ? "user" : realm.keyHash;
|
|
37
|
+
|
|
38
|
+
/** The effective activated inventory in publication order; realms without a local curated shard are reported, never opened or initialized.
|
|
39
|
+
* The inventory is the effective one (#448): a realm admitted after activation by an appended extension joins it exactly like an activated realm.
|
|
40
|
+
*/
|
|
41
|
+
export function placementInventory(home: string): { local: InventoryRealm[]; missing: string[]; inactive: string[] } {
|
|
42
|
+
const markers = readPlacementRuntimeMarkers(home), active = readActivePlacementBinding(home, markers.profile, markers.shards);
|
|
43
|
+
if (!active) throw new Error("sync placement activation metadata unavailable or changed; inspect the retained activation before continuing");
|
|
44
|
+
const { realms } = readEffectiveRealmInventory(home, active);
|
|
45
|
+
const local: InventoryRealm[] = [], missing: string[] = [], inactive: string[] = [];
|
|
46
|
+
for (const realm of realms) {
|
|
47
|
+
if (realm.scope === "user") { if (existsSync(join(userShardDir(home), "generation.json"))) local.unshift({ scope: "user" }); else missing.push("user"); continue; }
|
|
48
|
+
const descriptor = readShardDescriptor(home, realm.keyHash.slice(0, 16));
|
|
49
|
+
if (!descriptor || digest(descriptor.key) !== realm.keyHash || !lstatSync(join(shardDir(home, descriptor.key), "generation.json"), { throwIfNoEntry: false })) { missing.push(realm.keyHash); continue; }
|
|
50
|
+
// An archived or forgotten project is never opened for publication; its realm is reported and left as it is.
|
|
51
|
+
if (projectState(home, descriptor.key) !== "active") { inactive.push(realm.keyHash); continue; }
|
|
52
|
+
local.push({ scope: "project", key: descriptor.key, keyHash: realm.keyHash });
|
|
53
|
+
}
|
|
54
|
+
const user = local.filter(realm => realm.scope === "user"), projects = local.filter((realm): realm is Extract<InventoryRealm, { scope: "project" }> => realm.scope === "project")
|
|
55
|
+
.sort((a, b) => a.keyHash < b.keyHash ? -1 : a.keyHash > b.keyHash ? 1 : 0);
|
|
56
|
+
return { local: [...user, ...projects], missing: missing.sort(), inactive: inactive.sort() };
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** Deterministic publication batches of at most two realms; the user realm is always in the first. */
|
|
60
|
+
export function placementInventoryBatches(realms: readonly InventoryRealm[]): InventoryRealm[][] {
|
|
61
|
+
const batches: InventoryRealm[][] = [];
|
|
62
|
+
for (let at = 0; at < realms.length; at += PUBLICATION_TARGETS) batches.push(realms.slice(at, at + PUBLICATION_TARGETS));
|
|
63
|
+
return batches;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export interface PlacementInventoryPorts {
|
|
67
|
+
/** Opens exactly one realm's curated shard (no user overlay, no alias stores). */
|
|
68
|
+
open(realm: InventoryRealm): MemoryStore;
|
|
69
|
+
/** Releases a store from `open`; a store the caller already held is left open. */
|
|
70
|
+
close(store: MemoryStore): void;
|
|
71
|
+
/** Runs one unchanged two-target placement publication over the given opened stores. */
|
|
72
|
+
publish(primary: MemoryStore, targets: readonly MemoryStore[], opts: SyncOptions): Promise<SyncResult>;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function sum(results: readonly SyncResult[]): Pick<SyncResult, "entries" | "pushed"> & { exported: number; withheld: number } {
|
|
76
|
+
return { entries: results.reduce((n, r) => n + r.entries, 0), pushed: results.some(r => r.pushed),
|
|
77
|
+
exported: results.reduce((n, r) => n + (r.placementPublication?.exported ?? 0), 0), withheld: results.reduce((n, r) => n + (r.placementPublication?.withheld ?? 0), 0) };
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** Retained publication realms (by label), when a reservation exists; resumed before any new publication. */
|
|
81
|
+
function retainedRealms(home: string): string[] | undefined {
|
|
82
|
+
const markers = readPlacementRuntimeMarkers(home), active = readActivePlacementBinding(home, markers.profile, markers.shards);
|
|
83
|
+
if (!active) return undefined;
|
|
84
|
+
const reservation = readPlacementJournal(home, active.profile.placementHead).publicationReservation;
|
|
85
|
+
if (!reservation) return undefined;
|
|
86
|
+
return readPlacementPublication(home, active.profile.placementHead, reservation.attemptHash).bundle.root.targets.map(target => label(target.realm));
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
export async function syncPlacementInventory(home: string, opts: SyncOptions, ports: PlacementInventoryPorts): Promise<SyncResult & { placementRealms: PlacementRealmResult[] }> {
|
|
90
|
+
// #288 step 3: a started checkpoint pauses every placement effect before any journal read, with its own cause and next step.
|
|
91
|
+
const markers = readPlacementRuntimeMarkers(home), binding = readActivePlacementBinding(home, markers.profile, markers.shards);
|
|
92
|
+
if (binding && placementCheckpointPending(home, binding.profile.placementHead))
|
|
93
|
+
return { ok: false, pushed: false, entries: 0, error: PLACEMENT_CHECKPOINT_PENDING_MESSAGE, failure: { cause: "checkpoint-pending" }, placementRealms: [] };
|
|
94
|
+
const { local, missing, inactive } = placementInventory(home);
|
|
95
|
+
const retained = retainedRealms(home);
|
|
96
|
+
let order = local;
|
|
97
|
+
if (retained) {
|
|
98
|
+
// The retained plan names its own realms; it runs first, exactly as recorded, then the rest in the usual order.
|
|
99
|
+
const first = retained.map(name => local.find(realm => label(realm) === name));
|
|
100
|
+
if (first.some(realm => !realm)) throw new Error("a retained placement publication names a realm without a local curated shard; inspect it before continuing");
|
|
101
|
+
order = [...first as InventoryRealm[], ...local.filter(realm => !retained.includes(label(realm)))];
|
|
102
|
+
}
|
|
103
|
+
const batches = retained ? [order.slice(0, retained.length), ...placementInventoryBatches(order.slice(retained.length))] : placementInventoryBatches(order);
|
|
104
|
+
const realms: PlacementRealmResult[] = [...missing.map(realm => ({ realm, outcome: "not-local" as const })), ...inactive.map(realm => ({ realm, outcome: "inactive" as const }))];
|
|
105
|
+
const progress = opts.progress, total = batches.filter(batch => batch.length).length;
|
|
106
|
+
// One reporter for the whole run: each publication reports its phases, but only this driver reports the terminal state.
|
|
107
|
+
const report = (completed: number) => progress?.inventory({ publications: total, completed, realms: order.length,
|
|
108
|
+
outcomes: realms.map(item => ({ realm: item.realm === "user" ? "user" : item.realm.slice(0, 16), outcome: item.outcome })) });
|
|
109
|
+
progress?.deferFinish(true); report(0);
|
|
110
|
+
let completed = 0;
|
|
111
|
+
const results: SyncResult[] = [];
|
|
112
|
+
let stopped: SyncResult | undefined;
|
|
113
|
+
for (const [index, batch] of batches.entries()) {
|
|
114
|
+
if (!batch.length) continue;
|
|
115
|
+
if (stopped) { for (const realm of batch) realms.push({ realm: label(realm), outcome: "not-run" }); continue; }
|
|
116
|
+
if (opts.signal?.aborted) { stopped = { ok: false, pushed: false, entries: 0, error: "stopped", failure: { cause: "stopped" } }; for (const realm of batch) realms.push({ realm: label(realm), outcome: "not-run" }); continue; }
|
|
117
|
+
const stores: MemoryStore[] = [];
|
|
118
|
+
let result: SyncResult;
|
|
119
|
+
try {
|
|
120
|
+
for (const realm of batch) stores.push(ports.open(realm));
|
|
121
|
+
result = await ports.publish(stores[0]!, stores, opts);
|
|
122
|
+
} catch (error) {
|
|
123
|
+
result = { ok: false, pushed: false, entries: 0, error: (error as Error).message, failure: { cause: "unavailable" } };
|
|
124
|
+
} finally { for (const store of stores.reverse()) try { ports.close(store); } catch { /* preserve the publication result */ } }
|
|
125
|
+
results.push(result);
|
|
126
|
+
const outcome: PlacementRealmOutcome = result.ok ? result.placementPublication?.outcome ?? "not-needed" : result.placementPublication?.outcome === "unknown" ? "unknown" : "failed";
|
|
127
|
+
for (const realm of batch) realms.push({ realm: label(realm), outcome, publication: index + 1 });
|
|
128
|
+
if (!result.ok) stopped = result;
|
|
129
|
+
else completed++;
|
|
130
|
+
report(completed);
|
|
131
|
+
}
|
|
132
|
+
if (stopped) report(completed);
|
|
133
|
+
progress?.deferFinish(false);
|
|
134
|
+
if (stopped) progress?.finish(opts.signal?.aborted ? "cancelled" : "failed", opts.signal?.aborted ? "cancelled" : "unavailable");
|
|
135
|
+
else progress?.finish("succeeded");
|
|
136
|
+
const totals = sum(results), last = stopped ?? results.at(-1);
|
|
137
|
+
const base: SyncResult = last ? { ...last } : { ok: true, pushed: false, entries: 0 };
|
|
138
|
+
return { ...base, ok: !stopped, pushed: totals.pushed, entries: totals.entries,
|
|
139
|
+
...(base.placementPublication ? { placementPublication: { ...base.placementPublication, exported: totals.exported, withheld: totals.withheld } } : {}),
|
|
140
|
+
...(stopped?.error !== undefined ? { error: stopped.error } : {}), placementRealms: realms };
|
|
141
|
+
}
|
|
@@ -8,13 +8,16 @@ export const PLACEMENT_RECORD_SCHEMA = "agent-mem.sync-placement-record/v1";
|
|
|
8
8
|
export const PLACEMENT_ACTIVE_FENCE_SCHEMA = "agent-mem.sync-placement-fence/v1";
|
|
9
9
|
export const PLACEMENT_JOURNAL_MAX_RECORDS = 20_000, PLACEMENT_JOURNAL_MAX_OBJECTS = 256;
|
|
10
10
|
export const PLACEMENT_JOURNAL_CHUNK_MAX_BYTES = 64 * 1024, PLACEMENT_JOURNAL_ROOT_MAX_BYTES = 256 * 1024;
|
|
11
|
-
export type SyncPlacementJournalErrorCode = "invalid" | "corrupt" | "bound" | "conflict" | "pending" | "changed" | "authorization" | "policy" | "local" | "busy";
|
|
11
|
+
export type SyncPlacementJournalErrorCode = "invalid" | "corrupt" | "bound" | "conflict" | "pending" | "checkpoint-pending" | "changed" | "authorization" | "policy" | "local" | "busy";
|
|
12
|
+
export const PLACEMENT_CHECKPOINT_COMMAND = "amem migrate --sync-placement --checkpoint";
|
|
13
|
+
export const PLACEMENT_CHECKPOINT_PENDING_MESSAGE = `A placement checkpoint is pending; placement effects are paused until it finishes. Run ${PLACEMENT_CHECKPOINT_COMMAND} --resume to complete its recorded bytes, or ${PLACEMENT_CHECKPOINT_COMMAND} --abandon if its commit line has not started.`;
|
|
12
14
|
const messages: Record<SyncPlacementJournalErrorCode, string> = {
|
|
13
15
|
invalid: "Sync placement journal data is invalid or unsupported; inspect the retained state and use a compatible runtime.",
|
|
14
16
|
corrupt: "Sync placement journal evidence is incomplete or inconsistent; restore the exact retained evidence before continuing.",
|
|
15
17
|
bound: "Sync placement journal exceeds its supported bounds; a person-reviewed bounded epoch transition is required.",
|
|
16
18
|
conflict: "Sync placement journal identity or request conflicts with retained evidence; inspect the exact request before retrying.",
|
|
17
19
|
pending: "Sync placement journal has an unfinished transaction; resume its exact recorded request before continuing.",
|
|
20
|
+
"checkpoint-pending": PLACEMENT_CHECKPOINT_PENDING_MESSAGE,
|
|
18
21
|
changed: "Sync placement journal or source bindings changed; capture and review a fresh request before continuing.",
|
|
19
22
|
authorization: "Sync placement change requires explicit person authorization of the exact reviewed request.",
|
|
20
23
|
policy: "Current mandatory policy refuses this sync placement change; inspect its safe policy classification.",
|