@staix/agent-mem 0.38.0 → 0.40.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/plugin.json +1 -1
- package/README.md +1 -1
- package/package.json +1 -1
- package/src/brief-curated.ts +8 -4
- package/src/cli-agent-reads.ts +2 -1
- package/src/cli.ts +82 -32
- package/src/commands-table.ts +6 -3
- package/src/hooks.ts +4 -0
- package/src/index.ts +5 -0
- package/src/memory/capacity-text.ts +100 -0
- package/src/memory/capacity.ts +0 -92
- package/src/memory/commands.ts +6 -1
- package/src/memory/curated-cache-state.ts +22 -3
- package/src/memory/doctor-text.ts +148 -0
- package/src/memory/doctor.ts +19 -141
- package/src/memory/eval-audit-text.ts +62 -0
- package/src/memory/eval-audit.ts +0 -57
- package/src/memory/eval-text.ts +32 -0
- package/src/memory/eval.ts +0 -28
- package/src/memory/formats.ts +2 -0
- package/src/memory/gc-text.ts +22 -0
- package/src/memory/gc.ts +0 -19
- package/src/memory/generation-index.ts +1 -1
- package/src/memory/index-file.ts +1 -1
- package/src/memory/metrics.ts +18 -10
- package/src/memory/migrate-text.ts +32 -0
- package/src/memory/migrate.ts +0 -29
- package/src/memory/project-export.ts +9 -4
- package/src/memory/prune-text.ts +29 -0
- package/src/memory/prune.ts +0 -26
- package/src/memory/report-text.ts +2 -0
- package/src/memory/roots.ts +145 -0
- package/src/memory/shard-migration-text.ts +40 -0
- package/src/memory/shard-migration.ts +0 -37
- package/src/memory/status-text.ts +5 -1
- package/src/memory/store.ts +112 -17
- package/src/memory/sync-placement-activation-locks.ts +7 -5
- package/src/memory/sync-placement-advertisement.ts +18 -0
- package/src/memory/sync-placement-bound.ts +2 -2
- package/src/memory/sync-placement-checkpoint-person.ts +2 -2
- package/src/memory/sync-placement-inventory.ts +4 -1
- package/src/memory/sync-placement-noop-cache.ts +93 -0
- package/src/memory/sync-placement-refusal-category.ts +18 -0
- package/src/memory/sync-placement-transport.ts +80 -13
- package/src/memory/sync-placement-writer-renewal.ts +3 -1
- package/src/memory/sync-progress-text.ts +7 -0
- package/src/memory/sync-progress.ts +21 -7
- package/src/memory/sync-screen.ts +13 -0
- package/src/memory/work-lists.ts +6 -4
- package/src/session-brief.ts +16 -2
- package/src/setup-drift.ts +1 -1
- package/src/setup-writer-roots.ts +136 -0
- package/src/setup.ts +8 -118
- package/src/sync-placement-writer-context.ts +9 -4
- package/src/ui/inbox.ts +1 -1
- package/src/ui/plugin.ts +4 -2
- package/src/work-brief-preparation.ts +28 -0
|
@@ -26,7 +26,7 @@ import { withPlacementCheckpointFences } from "./sync-placement-activation-locks
|
|
|
26
26
|
import { assertPlacementActivationOwner } from "./sync-placement-activation-proof.ts";
|
|
27
27
|
import { placementFenceDirectories } from "./sync-placement-writer-renewal.ts";
|
|
28
28
|
import { initialPlacementWriterContext } from "../sync-placement-writer-context.ts";
|
|
29
|
-
import { readSetupWriterRoots, SetupWriterRootsError } from "../setup.ts";
|
|
29
|
+
import { readSetupWriterRoots, SetupWriterRootsError } from "../setup-writer-roots.ts";
|
|
30
30
|
import { checkpointProspective, type CheckpointProspective } from "./sync-placement-checkpoint-prospective.ts";
|
|
31
31
|
import { ShardHistoryError, type ShardHistoryCause } from "./shard-sync-history.ts";
|
|
32
32
|
|
|
@@ -126,7 +126,7 @@ export async function previewPlacementCheckpoint(homeInput: string, opts: { writ
|
|
|
126
126
|
const minReader = PLACEMENT_CHECKPOINT_MIN_READER;
|
|
127
127
|
return { mode: "checkpoint-preview", window: window.window, nextWindow: intent.window, journalObjects, currentObjects: journal.objects, headroom,
|
|
128
128
|
floorReady: homeFloorAtLeast(home, minReader), requiredHomeFloor: minReader, writers: roots.length, planHash: intent.seal, plan: intent,
|
|
129
|
-
nextStep:
|
|
129
|
+
nextStep: `(umask 077; set -C; ${CHECKPOINT_PREVIEW} --writer-root <install root> --json > checkpoint-plan.json), repeating --writer-root for every install, then ${CHECKPOINT_PREVIEW} --confirm --plan checkpoint-plan.json with the same --writer-root list` };
|
|
130
130
|
}
|
|
131
131
|
async function checkpointHeadroom(home: string, intent: CheckpointIntent): Promise<{ headroom: PlacementCheckpointHeadroom; journalObjects: PlacementJournalObjectComposition; assertCurrent(): void }> {
|
|
132
132
|
const epochHash = intent.epochHash, prospective = await checkpointProspective(home).catch(historyRefusal);
|
|
@@ -22,6 +22,7 @@ import { isLocalKey, localKeyOptInMessage, readShardDescriptor, shardDir, userSh
|
|
|
22
22
|
import { projectState } from "./lifecycle.ts";
|
|
23
23
|
import { SyncPlacementJournalError, type PlacementRealm } from "./sync-placement-journal-format.ts";
|
|
24
24
|
import type { SyncOptions, SyncResult } from "./sync.ts";
|
|
25
|
+
import { bindPlacementAdvertisement } from "./sync-placement-advertisement.ts";
|
|
25
26
|
import type { MemoryStore } from "./store.ts";
|
|
26
27
|
|
|
27
28
|
const digest = (value: string) => createHash("sha256").update(value).digest("hex");
|
|
@@ -98,7 +99,9 @@ function journalRefusal(error: unknown): (SyncResult & { placementRealms: Placem
|
|
|
98
99
|
failure: { cause: code === "checkpoint-pending" ? "checkpoint-pending" : "unavailable" }, placementRealms: [] };
|
|
99
100
|
}
|
|
100
101
|
|
|
101
|
-
export async function syncPlacementInventory(home: string,
|
|
102
|
+
export async function syncPlacementInventory(home: string, callerOpts: SyncOptions, ports: PlacementInventoryPorts): Promise<SyncResult & { placementRealms: PlacementRealmResult[] }> {
|
|
103
|
+
// #626: one remote advertisement per run, shared by its publications (never one a caller passed in).
|
|
104
|
+
const opts: SyncOptions = bindPlacementAdvertisement({ ...callerOpts });
|
|
102
105
|
let local: InventoryRealm[], missing: string[], inactive: string[], retained: string[] | undefined;
|
|
103
106
|
try {
|
|
104
107
|
// #288 step 3: a started checkpoint pauses every placement effect before any journal read, with its own cause and next step.
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* #612: a derived, machine-local cache that lets a placement publication with nothing to do skip policy evaluation.
|
|
3
|
+
* It holds one key digest and the four not-needed decision counts, never a path, row id or text. It is never read
|
|
4
|
+
* for publication, capture or import: a hit only returns `not-needed` with the stored counts, and any read failure,
|
|
5
|
+
* unknown schema, size overrun, bad count, foreign owner, loose mode, link or key mismatch takes the full path.
|
|
6
|
+
* Deleting it is always safe. Every operation stays inside `<home>/sync-noop-cache/` and touches nothing else.
|
|
7
|
+
* ponytail: one file per publication slot (sha256 of the epoch and its selected realms); the upgrade path is pruning
|
|
8
|
+
* slots not seen in the last inventory run if stale slots ever accumulate past a handful per home.
|
|
9
|
+
*/
|
|
10
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
11
|
+
import { closeSync, constants, fstatSync, fsyncSync, lstatSync, mkdirSync, openSync, readSync, renameSync, unlinkSync, writeSync, type Stats } from "node:fs";
|
|
12
|
+
import { join } from "node:path";
|
|
13
|
+
import { canonicalJSON } from "./generation.ts";
|
|
14
|
+
|
|
15
|
+
export const PLACEMENT_NOOP_CACHE_SCHEMA = "agent-mem.placement-noop-cache/v1";
|
|
16
|
+
export const PLACEMENT_NOOP_CACHE_MAX_BYTES = 512;
|
|
17
|
+
export const PLACEMENT_NOOP_CACHE_DIR = "sync-noop-cache";
|
|
18
|
+
|
|
19
|
+
export interface PlacementNoopCounts { permitted: number; local: number; declined: number; held: number }
|
|
20
|
+
export interface PlacementNoopKeyInput {
|
|
21
|
+
version: string; writersHash: string; screenIdentity: string | null; policyHash: string; sourceHash: string; aliasesHash: string; contextHash: string; markerHash: string;
|
|
22
|
+
remoteHash: string; journal: { sequence: number; headHash: string };
|
|
23
|
+
targets: readonly { remote: string | null; local: string | null; pruned: readonly string[]; fetched: readonly string[] }[];
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
const sha = (value: string) => createHash("sha256").update(value).digest("hex");
|
|
27
|
+
const HEX64 = /^[a-f0-9]{64}$/;
|
|
28
|
+
|
|
29
|
+
/** The reuse key: every input a no-op decision depends on. Any change produces a different digest. */
|
|
30
|
+
export function placementNoopKey(input: PlacementNoopKeyInput): string {
|
|
31
|
+
return sha(canonicalJSON({ ...input, targets: input.targets.map(t => ({ ...t, pruned: [...t.pruned].sort(), fetched: [...t.fetched].sort() })) }));
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
const uid = () => process.getuid?.();
|
|
35
|
+
/** Owned by this user, no group/other bits, and the expected type. Symbolic links never qualify. */
|
|
36
|
+
function privateNode(stat: Stats | undefined, kind: "dir" | "file"): boolean {
|
|
37
|
+
if (!stat || stat.isSymbolicLink() || (kind === "dir" ? !stat.isDirectory() : !stat.isFile())) return false;
|
|
38
|
+
const owner = uid(); return (owner === undefined || stat.uid === owner) && (stat.mode & 0o077) === 0;
|
|
39
|
+
}
|
|
40
|
+
function cacheDir(home: string): string | undefined {
|
|
41
|
+
const dir = join(home, PLACEMENT_NOOP_CACHE_DIR);
|
|
42
|
+
try { return privateNode(lstatSync(dir, { throwIfNoEntry: false }), "dir") ? dir : undefined; } catch { return undefined; }
|
|
43
|
+
}
|
|
44
|
+
const count = (value: unknown): value is number => typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
|
|
45
|
+
const NOFOLLOW = constants.O_NOFOLLOW ?? 0, NONBLOCK = constants.O_NONBLOCK ?? 0;
|
|
46
|
+
|
|
47
|
+
/** Stored counts when the file holds exactly `key`; undefined on any other state. Never throws, never writes. */
|
|
48
|
+
export function readPlacementNoopCache(home: string, slot: string, key: string): PlacementNoopCounts | undefined {
|
|
49
|
+
if (!HEX64.test(slot)) return undefined;
|
|
50
|
+
const dir = cacheDir(home); if (!dir) return undefined;
|
|
51
|
+
let fd: number | undefined;
|
|
52
|
+
try {
|
|
53
|
+
fd = openSync(join(dir, `${slot}.json`), constants.O_RDONLY | NOFOLLOW | NONBLOCK);
|
|
54
|
+
const stat = fstatSync(fd); if (!privateNode(stat, "file") || stat.size > PLACEMENT_NOOP_CACHE_MAX_BYTES) return undefined;
|
|
55
|
+
const buffer = Buffer.alloc(PLACEMENT_NOOP_CACHE_MAX_BYTES + 1); let length = 0, read = 0;
|
|
56
|
+
while ((read = readSync(fd, buffer, length, buffer.length - length, null)) > 0) { length += read; if (length > PLACEMENT_NOOP_CACHE_MAX_BYTES) return undefined; }
|
|
57
|
+
if (!cacheDir(home)) return undefined; // the directory must still be the private one after the read
|
|
58
|
+
const value = JSON.parse(buffer.subarray(0, length).toString("utf8")) as Record<string, unknown>;
|
|
59
|
+
if (!value || typeof value !== "object" || Array.isArray(value) || Object.keys(value).length !== 3) return undefined;
|
|
60
|
+
if (value.schema !== PLACEMENT_NOOP_CACHE_SCHEMA || typeof value.key !== "string" || !HEX64.test(value.key) || value.key !== key) return undefined;
|
|
61
|
+
const c = value.counts as Record<string, unknown> | null;
|
|
62
|
+
if (!c || typeof c !== "object" || Array.isArray(c) || Object.keys(c).length !== 4) return undefined;
|
|
63
|
+
if (!count(c.permitted) || !count(c.local) || !count(c.declined) || !count(c.held)) return undefined;
|
|
64
|
+
return { permitted: c.permitted, local: c.local, declined: c.declined, held: c.held };
|
|
65
|
+
} catch { return undefined; }
|
|
66
|
+
finally { if (fd !== undefined) try { closeSync(fd); } catch { /* cache only */ } }
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** Atomic private write (0700 directory, 0600 file, exclusive temporary then rename). Best effort: a failure only loses the cache. */
|
|
70
|
+
export function writePlacementNoopCache(home: string, slot: string, key: string, counts: PlacementNoopCounts): void {
|
|
71
|
+
if (!HEX64.test(slot) || !HEX64.test(key) || ![counts.permitted, counts.local, counts.declined, counts.held].every(count)) return;
|
|
72
|
+
const bytes = Buffer.from(canonicalJSON({ schema: PLACEMENT_NOOP_CACHE_SCHEMA, key, counts: { permitted: counts.permitted, local: counts.local, declined: counts.declined, held: counts.held } }) + "\n");
|
|
73
|
+
if (bytes.length > PLACEMENT_NOOP_CACHE_MAX_BYTES) return;
|
|
74
|
+
try { mkdirSync(join(home, PLACEMENT_NOOP_CACHE_DIR), { mode: 0o700 }); } catch { /* exists or unavailable: checked next */ }
|
|
75
|
+
const dir = cacheDir(home); if (!dir) return;
|
|
76
|
+
const temp = join(dir, `.${randomBytes(8).toString("hex")}.tmp`); let created = false;
|
|
77
|
+
try {
|
|
78
|
+
const fd = openSync(temp, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | NOFOLLOW, 0o600); created = true;
|
|
79
|
+
try { writeSync(fd, bytes); fsyncSync(fd); } finally { closeSync(fd); }
|
|
80
|
+
if (!cacheDir(home)) return;
|
|
81
|
+
const target = join(dir, `${slot}.json`), prior = lstatSync(target, { throwIfNoEntry: false });
|
|
82
|
+
if (prior && !prior.isFile()) return; // never replace a link or directory someone else put there
|
|
83
|
+
renameSync(temp, target); created = false;
|
|
84
|
+
} catch { /* cache only */ }
|
|
85
|
+
finally { if (created) try { unlinkSync(temp); } catch { /* cache only */ } }
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** Invalidate one slot: any outcome other than not-needed. Removes only a regular file inside the private directory. Never throws. */
|
|
89
|
+
export function clearPlacementNoopCache(home: string, slot: string): void {
|
|
90
|
+
if (!HEX64.test(slot)) return;
|
|
91
|
+
const dir = cacheDir(home); if (!dir) return;
|
|
92
|
+
try { const path = join(dir, `${slot}.json`), stat = lstatSync(path, { throwIfNoEntry: false }); if (stat?.isFile()) unlinkSync(path); } catch { /* cache only */ }
|
|
93
|
+
}
|
|
@@ -1,3 +1,21 @@
|
|
|
1
|
+
import type { PlacementWriterRootCategory } from "../sync-placement-writer-context.ts";
|
|
2
|
+
|
|
1
3
|
/** #426: the fixed refusal categories of a placement sync; shared by the transport and the progress sidecar. */
|
|
2
4
|
export const PLACEMENT_REFUSAL_CATEGORIES = ["epoch", "source-selection", "policy", "remote", "writer-pin", "size-bound", "lock", "other"] as const;
|
|
3
5
|
export type PlacementRefusalCategory = typeof PLACEMENT_REFUSAL_CATEGORIES[number];
|
|
6
|
+
|
|
7
|
+
/** #613: only these two fixed writer-proof facts may be retained. */
|
|
8
|
+
export const WRITER_ROOT_CATEGORIES = ["running CLI", "host package", "setup receipt", "declared writer", "active locator", "home floor", "writer renewal"] as const satisfies readonly PlacementWriterRootCategory[];
|
|
9
|
+
export const WRITER_CAUSE_CLASSES = ["missing", "changed", "unavailable"] as const;
|
|
10
|
+
export interface PlacementWriterRefusal {
|
|
11
|
+
causeClass: typeof WRITER_CAUSE_CLASSES[number];
|
|
12
|
+
rootCategory: PlacementWriterRootCategory;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export function validPlacementWriterRefusal(value: unknown): value is PlacementWriterRefusal {
|
|
16
|
+
if (!value || typeof value !== "object" || Array.isArray(value) || Object.keys(value).length !== 2) return false;
|
|
17
|
+
const { causeClass, rootCategory } = value as Record<string, unknown>;
|
|
18
|
+
return Object.hasOwn(value, "causeClass") && Object.hasOwn(value, "rootCategory")
|
|
19
|
+
&& (WRITER_CAUSE_CLASSES as readonly unknown[]).includes(causeClass)
|
|
20
|
+
&& (WRITER_ROOT_CATEGORIES as readonly unknown[]).includes(rootCategory);
|
|
21
|
+
}
|
|
@@ -4,11 +4,12 @@ import { constants, closeSync, existsSync, fsyncSync, lstatSync, mkdirSync, open
|
|
|
4
4
|
import { join } from "node:path";
|
|
5
5
|
import { canonicalJSON, hashJSON, readSelector } from "./generation.ts";
|
|
6
6
|
import { generationSyncLock } from "./generation-sync.ts";
|
|
7
|
+
import { placementAdvertisement } from "./sync-placement-advertisement.ts";
|
|
7
8
|
import { generationSyncGit, generationSyncGitBytes, remoteVisibility, type SyncFailureCause, type SyncOptions, type SyncResult } from "./sync.ts";
|
|
8
9
|
import { acquireMutation, assertMutationHandle, type MutationHandle } from "./mutation.ts";
|
|
9
10
|
import { isLocalKey, localKeyOptInMessage, PlacementRealmRefusal, resolveShardProfile } from "./shard.ts";
|
|
10
11
|
import { memoryPolicySnapshot } from "./policy.ts";
|
|
11
|
-
import { outboundPolicyEvaluator } from "./sync-screen.ts";
|
|
12
|
+
import { outboundPolicyEvaluator, rowScreenIdentity } from "./sync-screen.ts";
|
|
12
13
|
import { readActivePlacementBinding } from "./sync-placement-active.ts";
|
|
13
14
|
import { readPlacementRuntimeMarkers } from "./sync-placement-guard.ts";
|
|
14
15
|
import { captureSyncPlacementContextAsync, placementCaptureContextHash, previewSyncPlacementSources, type PlacementCapture, type PlacementPendingSource } from "./sync-placement-capture.ts";
|
|
@@ -21,7 +22,8 @@ import { PLACEMENT_FORMAT, PLACEMENT_PROFILE_SCHEMA, SyncPlacementFormatError }
|
|
|
21
22
|
import { PLACEMENT_JOURNAL_MAX_RECORDS, PLACEMENT_JOURNAL_MAX_OBJECTS, createPlacementRecord, placementKeyId, type PlacementEvent, type PlacementRealm, type PlacementRecord } from "./sync-placement-journal-format.ts";
|
|
22
23
|
import { rebuildPlacementProjection, type PlacementProjection } from "./sync-placement-projection.ts";
|
|
23
24
|
import { readPlacementJournal, readPlacementWriterJournalAnchors, placementWriterJournalToken, appendPlacementEvent, appendPlacementEvents, releasePlacementStorageCaches, ensurePlacementPublicationDurability, readPlacementPublicationMetadata, placementDecisionOwners, placementJournalObjectComposition, placementJournalObjectCompositionText, type PlacementJournalObjectComposition, type PlacementJournalRead, type PlacementStorageOptions } from "./sync-placement-journal-storage.ts";
|
|
24
|
-
import { formatFloorAtLeast } from "./formats.ts";
|
|
25
|
+
import { amemReaderVersion, formatFloorAtLeast } from "./formats.ts";
|
|
26
|
+
import { clearPlacementNoopCache, placementNoopKey, readPlacementNoopCache, writePlacementNoopCache, type PlacementNoopCounts } from "./sync-placement-noop-cache.ts";
|
|
25
27
|
import { preparePlacementPublication, readPlacementPublication, recordPlacementPublicationPhase, type PlacementPublicationRead } from "./sync-placement-publication-storage.ts";
|
|
26
28
|
import { planPlacementPublication, planPlacementPublicationAsync, planPlacementPublicationV2Async, placementDecisionReuseEnabled, PLACEMENT_PUBLICATION_PLAN_V2_SCHEMA, publicationBytes, publicationFileNames, type PlacementPublicationBundle, type PlacementPublicationDecision, type PlacementPublicationSource, type PlacementPublicationObject } from "./sync-placement-publication-plan.ts";
|
|
27
29
|
import { placementPublicationEventSteps } from "./sync-placement-publication-events.ts";
|
|
@@ -293,6 +295,24 @@ class PlacementTransport {
|
|
|
293
295
|
phaseNow: SyncProgressPhase = "writer-verification";
|
|
294
296
|
enter(...args: Parameters<SyncProgress["phase"]>): void { this.phaseNow = args[0]; this.progress?.phase(...args); }
|
|
295
297
|
refusal?: PlacementRefusalCategory;
|
|
298
|
+
/** #612: the last materialization's decision counts, and the counts a no-op cache hit returned. */
|
|
299
|
+
decisionCounts?: PlacementNoopCounts; noopHit?: PlacementNoopCounts; noopKept=false; syncLockHeld=false;
|
|
300
|
+
/** #612: optional slot deletion runs only with the sync lock and every mutation fence positively held and still current. */
|
|
301
|
+
holdsNoopFences(): boolean {
|
|
302
|
+
if(!this.syncLockHeld||!this.rootMutation||!this.homeMutation||!this.targets.length||this.targets.some(target=>!target.mutation))return false;
|
|
303
|
+
try{this.metadata();return true;}catch{return false;}
|
|
304
|
+
}
|
|
305
|
+
/** #612: the no-op reuse key over this run's captured and freshly read inputs; undefined when any input is missing. */
|
|
306
|
+
noopSlot(): string { return digest(canonicalJSON({epochHash:this.epochHash,realms:this.targets.map(physical)})); }
|
|
307
|
+
noopKey(): string|undefined {
|
|
308
|
+
const capture=this.capture,version=amemReaderVersion();if(!capture||!version||!this.writerInventory||!this.epochHash)return undefined;
|
|
309
|
+
// An arbitrary host screen has no cross-run identity, so it always takes the full path; only the package's deterministic screen binds.
|
|
310
|
+
const screenIdentity=this.opts.screen===undefined?null:rowScreenIdentity(this.opts.screen);if(screenIdentity===undefined)return undefined;
|
|
311
|
+
return placementNoopKey({version,screenIdentity,writersHash:hashJSON({writers:this.writerInventory.writers,revision:this.writerInventory.revisionHash??null}),
|
|
312
|
+
policyHash:capture.context.policyHash,sourceHash:capture.context.sourceHash,aliasesHash:capture.context.aliasesHash,contextHash:placementCaptureContextHash(capture),
|
|
313
|
+
markerHash:capture.markerHash,remoteHash:digest(this.url),journal:{sequence:this.journal.sequence,headHash:this.journal.headHash},
|
|
314
|
+
targets:this.targets.map(target=>({remote:target.remote??null,local:target.local??null,pruned:[...(target.store.prunePort().snapshot().pruned??[])],fetched:[...target.fetched]}))});
|
|
315
|
+
}
|
|
296
316
|
async observe(phase: PlacementSyncPhase): Promise<void> { await this.phase?.(phase); }
|
|
297
317
|
storage(factual = false): PlacementStorageOptions { if (!this.homeMutation) refuse(); return { mutation: this.homeMutation, assertCurrent: factual ? () => this.metadata() : this.check, ...(this.attemptHash ? { publicationAttemptHash: this.attemptHash } : {}) }; }
|
|
298
318
|
configStamp():string {
|
|
@@ -342,7 +362,7 @@ class PlacementTransport {
|
|
|
342
362
|
await yieldTurn(); this.prove(); // a host callout ends any reusable proof
|
|
343
363
|
if (!existsSync(this.root)) mkdirSync(this.root, { mode: 0o700 });
|
|
344
364
|
const transport = acquireMutation(this.root); if (!transport) refuse("lock"); this.rootMutation=transport; this.releases.push(transport);
|
|
345
|
-
const sync = generationSyncLock(this.root); if (!sync) refuse("lock"); this.releases.push(sync);
|
|
365
|
+
const sync = generationSyncLock(this.root); if (!sync) refuse("lock"); this.releases.push(sync); this.syncLockHeld=true;
|
|
346
366
|
for (const dir of [...new Set([this.home, ...this.targets.map(target => target.store.dir)])].sort()) {
|
|
347
367
|
const handle = acquireMutation(dir); if (!handle) refuse("lock"); this.releases.push(handle); if (dir === this.home) this.homeMutation = handle;
|
|
348
368
|
for (const target of this.targets) if (target.store.dir === dir) target.mutation = handle;
|
|
@@ -376,17 +396,45 @@ class PlacementTransport {
|
|
|
376
396
|
const result = await this.call(() => generationSyncGitBytes(this.root, this.args(["cat-file", "blob", object]), this.opts.signal, undefined, limit));
|
|
377
397
|
if (result.code !== 0 || result.out.length < 1) refuse(); return Buffer.from(result.out);
|
|
378
398
|
}
|
|
399
|
+
/**
|
|
400
|
+
* #626: the placement refs as the remote advertises them, read once per inventory run. One `ls-remote` costs a
|
|
401
|
+
* network round trip, and a run used to pay it once per target. The advertisement is the same read the per-ref call
|
|
402
|
+
* made, so each target still proves its tip against it; a ref this run's push moved is dropped from it (see finish).
|
|
403
|
+
*/
|
|
404
|
+
async advertisement(): Promise<ReadonlyMap<string, string>> {
|
|
405
|
+
const shared = placementAdvertisement(this.opts);
|
|
406
|
+
const cached = shared?.get(this.url);
|
|
407
|
+
if (cached) return cached;
|
|
408
|
+
const result = await this.call(() => generationSyncGitBytes(this.root, this.args(["ls-remote", "--refs", "origin", "refs/heads/amem/u", "refs/heads/amem/p/*"]), this.opts.signal, undefined, REMOTE_REALM_ADVERTISEMENT_BYTES));
|
|
409
|
+
if (result.code !== 0) refuse("remote");
|
|
410
|
+
let text: string; try { text = new TextDecoder("utf-8", { fatal: true }).decode(result.out); } catch { return refuse("remote"); }
|
|
411
|
+
const refs = new Map<string, string>();
|
|
412
|
+
for (const line of text.split("\n")) {
|
|
413
|
+
if (!line) continue;
|
|
414
|
+
const fields = line.split("\t"); if (fields.length !== 2 || !oid(fields[0]) || !/^refs\/heads\/amem\/(?:u|p\/[0-9a-f]{16})$/.test(fields[1]!) || refs.has(fields[1]!)) refuse("remote");
|
|
415
|
+
refs.set(fields[1]!, fields[0]!);
|
|
416
|
+
}
|
|
417
|
+
shared?.set(this.url, refs);
|
|
418
|
+
return refs;
|
|
419
|
+
}
|
|
379
420
|
async fetch(): Promise<void> {
|
|
421
|
+
const advertisement = await this.advertisement();
|
|
380
422
|
for (const target of this.targets) {
|
|
381
423
|
const ref = shardSyncRef(target.realm); if ((await this.git(["symbolic-ref", "--quiet", ref])).code !== 1) refuse();
|
|
382
424
|
const cached = await this.git(["rev-parse", "--verify", "--quiet", ref]);
|
|
383
425
|
if (cached.code !== 0 && cached.code !== 1 || cached.code === 0 && !oid(cached.out)) refuse(); target.local = cached.code === 0 ? cached.out : undefined;
|
|
384
|
-
const advertised =
|
|
385
|
-
if (advertised
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
426
|
+
const advertised = advertisement.get(ref);
|
|
427
|
+
if (advertised === undefined) { if (target.local && !this.journal.publicationReservation) refuse(); target.remote = undefined; target.remoteHistory = undefined; continue; }
|
|
428
|
+
let tip: string;
|
|
429
|
+
if (target.local === advertised) {
|
|
430
|
+
// #626: the advertised tip is already the verified cached ref, so its objects are local; fetching it again only
|
|
431
|
+
// repeats a round trip. Equality with the advertisement is the same proof the fetched incoming ref gave.
|
|
432
|
+
tip = advertised;
|
|
433
|
+
} else {
|
|
434
|
+
const incoming = `refs/amem/placement-incoming/${randomBytes(16).toString("hex")}`; this.refs.push(incoming);
|
|
435
|
+
await this.required(["fetch", "-q", "--no-tags", "--no-write-fetch-head", "--no-recurse-submodules", "origin", `${ref}:${incoming}`]);
|
|
436
|
+
tip = await this.required(["rev-parse", "--verify", incoming]); if (!oid(tip) || tip !== advertised) refuse();
|
|
437
|
+
}
|
|
390
438
|
if (target.local && !await target.auditor.verifiedAncestor(target.local, tip) && !this.journal.publicationReservation) refuse();
|
|
391
439
|
target.remote = tip; target.remoteHistory = await target.auditor.history(tip);
|
|
392
440
|
target.rows = new Map(target.remoteHistory.rows); target.fetched = new Set(target.remoteHistory.rows.keys()); target.origins = new Map(target.remoteHistory.origins);
|
|
@@ -459,11 +507,11 @@ class PlacementTransport {
|
|
|
459
507
|
this.prove();
|
|
460
508
|
for(const [index,target]of this.targets.entries())Object.assign(target,materialized.targets[index]!);
|
|
461
509
|
const {decisions,plannedTargets:targets,objects}=materialized;
|
|
462
|
-
|
|
510
|
+
{
|
|
463
511
|
// Each decision lands in one bucket: policy-declined, source-local, or held for a journal/dependency reason.
|
|
464
512
|
const counts={permitted:0,local:0,declined:0,held:0},other=new Set(["journal-hold","related-local","unsupported-reference","unverified-prune"]);
|
|
465
513
|
for(const d of decisions)counts[d.eligible?"permitted":d.reason==="source-local"?"local":d.reason&&!other.has(d.reason)?"declined":"held"]++;
|
|
466
|
-
this.progress
|
|
514
|
+
this.decisionCounts=counts;this.progress?.counts(counts);
|
|
467
515
|
}
|
|
468
516
|
this.enter("publication-plan");
|
|
469
517
|
const body={epochHash:this.epochHash,generation:this.journal.epoch.generation,homeHash:capture.context.homeHash,contextHash:placementCaptureContextHash(capture),markerHash:capture.markerHash,
|
|
@@ -680,7 +728,7 @@ class PlacementTransport {
|
|
|
680
728
|
const cause:SyncFailureCause|undefined=ok?undefined:this.opts.signal?.aborted?"stopped":this.bound?"bound":outcome==="unknown"?"unknown-outcome":this.failureCause??(this.refusal?"refusal":"unavailable");
|
|
681
729
|
return{ok,pushed:this.accepted&&(this.attempted||this.recovered&&!!this.current?.bundle.root.targets.some(target=>target.publish)),entries:this.current?.exported??0,...(error?{error}:{}),
|
|
682
730
|
...(cause?{failure:{cause,...(cause==="refusal"&&this.refusal?{category:this.refusal}:{})}}:{}),...(this.applications?{pruneApplication:{...this.applications.application}}:{}),
|
|
683
|
-
placementPublication:{...(this.attemptHash?{attemptHash:this.attemptHash}:{}),outcome,...(this.bound?{bound:this.bound}:{}),...(this.journalObjects?{journalObjects:this.journalObjects}:{}),...(this.refusal?{refusal:{category:this.refusal,phase:this.phaseNow}}:{}),withheld:this.current?.withheld??0,exported:this.current?.exported??0,
|
|
731
|
+
placementPublication:{...(this.attemptHash?{attemptHash:this.attemptHash}:{}),outcome,...(this.bound?{bound:this.bound}:{}),...(this.journalObjects?{journalObjects:this.journalObjects}:{}),...(this.refusal?{refusal:{category:this.refusal,phase:this.phaseNow}}:{}),withheld:this.current?.withheld??(this.noopHit?this.noopHit.local+this.noopHit.declined+this.noopHit.held:0),exported:this.current?.exported??0,
|
|
684
732
|
...(this.lastPolicyHash?{lastPolicyHash:this.lastPolicyHash}:{}),...(this.lastPolicyCheckUnixMs!==undefined?{lastPolicyCheckUnixMs:this.lastPolicyCheckUnixMs,policyCheckSource:this.policyCheckSource??(this.recovered?"durable-intent" as const:"live" as const)}:{}),
|
|
685
733
|
policyCeiling:"last-positive-check-before-in-flight-push",...(this.recovered?{recovered:true}:{})}};
|
|
686
734
|
}
|
|
@@ -732,6 +780,16 @@ class PlacementTransport {
|
|
|
732
780
|
&&root.policyHash===this.capture!.context.policyHash&&root.targets.every((target,index)=>target.expectedRemoteHead===(this.targets[index]?.remote??null));
|
|
733
781
|
if(!stable)return await this.terminalUnknown(retained);
|
|
734
782
|
}
|
|
783
|
+
// #612: a fresh attempt whose every no-op input equals the last not-needed run skips policy evaluation; any mismatch takes the full path.
|
|
784
|
+
const noopKey=retained?undefined:this.noopKey();
|
|
785
|
+
if(noopKey){
|
|
786
|
+
const hit=readPlacementNoopCache(this.home,this.noopSlot(),noopKey);
|
|
787
|
+
if(hit){
|
|
788
|
+
await yieldTurn();const applications=await this.applicationCoordinator();await applications.prepare();
|
|
789
|
+
if(!this.importsNeeded()){this.prove();this.noopHit=hit;this.noopKept=true;this.progress?.counts(hit);this.attemptHash=undefined;return this.result(true,"not-needed");}
|
|
790
|
+
}
|
|
791
|
+
}
|
|
792
|
+
clearPlacementNoopCache(this.home,this.noopSlot());
|
|
735
793
|
const frontier=retained?{...this.journal,sequence:retained.bundle.root.journal.sequence,headHash:retained.bundle.root.journal.headHash}:this.journal;
|
|
736
794
|
const material=await this.materialize(retained?.bundle.root.createdUnixSeconds??Math.floor(Date.now()/1000),frontier,retained?.bundle);
|
|
737
795
|
const changed=material.bundle.root.targets.some((target,index)=>target.publish&&target.commit!==(this.targets[index]!.remote??null));
|
|
@@ -749,7 +807,11 @@ class PlacementTransport {
|
|
|
749
807
|
}
|
|
750
808
|
this.current=material;this.attemptHash=material.bundle.root.seal;
|
|
751
809
|
await yieldTurn();const applications=await this.applicationCoordinator();await applications.prepare();
|
|
752
|
-
if(!retained&&!material.events.length&&!changed&&!this.importsNeeded()){
|
|
810
|
+
if(!retained&&!material.events.length&&!changed&&!this.importsNeeded()){
|
|
811
|
+
this.attemptHash=undefined;
|
|
812
|
+
if(noopKey&&this.decisionCounts&&noopKey===this.noopKey()){writePlacementNoopCache(this.home,this.noopSlot(),noopKey,this.decisionCounts);this.noopKept=true;}
|
|
813
|
+
return this.result(true,"not-needed");
|
|
814
|
+
}
|
|
753
815
|
if(!retained){await this.observe("before-plan-fsync");await yieldTurn();this.prove();preparePlacementPublication(this.home,material.bundle,this.storage());await this.observe("plan-fsynced");await yieldTurn();this.prove();}
|
|
754
816
|
// One mutation batch: a complete proof on each side, fence checks (and at most 1 s of proof reuse) per record.
|
|
755
817
|
this.prove();await this.appendThrough(material.bundle,material.events,material.preCount);this.prove();
|
|
@@ -766,6 +828,8 @@ class PlacementTransport {
|
|
|
766
828
|
this.lastPolicyCheckUnixMs=Date.now(); this.lastPolicyHash=material.bundle.root.policyHash;this.policyCheckSource="live";
|
|
767
829
|
const participating=material.bundle.root.targets.map((target,index)=>({target,index})).filter(item=>item.target.publish);
|
|
768
830
|
this.attempted=participating.length>0;
|
|
831
|
+
// #626: a push moves advertised refs, so no later publication of this run may reuse the advertisement read before it.
|
|
832
|
+
if(this.attempted)placementAdvertisement(this.opts)?.delete(this.url);
|
|
769
833
|
const sent=participating.length?await generationSyncGit(this.root,this.args(["push","--atomic","--no-follow-tags","-q",...participating.map(({target,index})=>`--force-with-lease=${shardSyncRef(this.targets[index]!.realm)}:${target.expectedRemoteHead??""}`),"origin",...participating.map(({target,index})=>`${target.commit}:${shardSyncRef(this.targets[index]!.realm)}`)]),this.opts.signal):{code:0};
|
|
770
834
|
this.accepted=sent.code===0;await this.observe("cas-returned");
|
|
771
835
|
if(!this.accepted)return this.result(false,"unknown","The placement publication outcome is unknown; retained receipts may have published. Recheck this exact attempt before retrying.");
|
|
@@ -791,6 +855,9 @@ class PlacementTransport {
|
|
|
791
855
|
return this.result(false,"not-needed",placementRefusalMessage(this.refusal,this.phaseNow));
|
|
792
856
|
}finally{
|
|
793
857
|
let ownedCache=true;try{this.metadata();}catch{ownedCache=false;}
|
|
858
|
+
// #612: every terminal path other than a full-path not-needed or a cache hit invalidates its slot, but only once admission
|
|
859
|
+
// completed: the sync lock and every mutation fence are held and current. A run refused before that leaves the slot alone.
|
|
860
|
+
if(!this.noopKept&&this.epochHash&&this.holdsNoopFences())try{clearPlacementNoopCache(this.home,this.noopSlot());}catch{}
|
|
794
861
|
if(ownedCache){
|
|
795
862
|
for(const ref of this.refs)try{this.metadata();await generationSyncGit(this.root,this.args(["update-ref","--no-deref","-d",ref]),undefined);}catch{}
|
|
796
863
|
for(const file of this.temporary)try{this.metadata();rmSync(file,{force:true});}catch{}
|
|
@@ -15,7 +15,9 @@ import { readWriterHistory, writeWriterRenewalIntent, writeWriterRevision, appen
|
|
|
15
15
|
import { createWriterRevision, createWriterCommit, createWriterRenewalIntent, writerRevisionWriters, WRITER_REVISION_SCHEMA, WRITER_RENEWAL_INTENT_SCHEMA, WRITER_REVISION_LIMIT, WRITER_COMMIT_LOG, SharedWriterRevisionError, type WriterRenewalIntent } from "./sync-placement-writer-revision-format.ts";
|
|
16
16
|
import { requireWriterRenewalHomeFloor } from "./sync-placement-prerequisites.ts";
|
|
17
17
|
import { resolvePlacementWindow } from "./sync-placement-checkpoint-storage.ts";
|
|
18
|
-
import { withPlacementActivationFences } from "./sync-placement-activation-locks.ts";
|
|
18
|
+
import { withPlacementActivationFences as activationFences } from "./sync-placement-activation-locks.ts";
|
|
19
|
+
/** #624: renewal runs on an active inventory, so its readers refusal names the checkpoint continuation. */
|
|
20
|
+
const withPlacementActivationFences: typeof activationFences = (home, directories, work) => activationFences(home, directories, work, { renewal: true });
|
|
19
21
|
import { assertPlacementActivationOwner, type PlacementActivationOwner } from "./sync-placement-activation-proof.ts";
|
|
20
22
|
import { previewSyncPlacementSources, previewOwnedSyncPlacementSources } from "./sync-placement-capture.ts";
|
|
21
23
|
import { captureInspectionPendingPrunes } from "./sync-placement-inspection-pending.ts";
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { PlacementWriterRefusal } from "./sync-placement-refusal-category.ts";
|
|
2
|
+
|
|
3
|
+
export function writerRefusalText({ causeClass, rootCategory }: PlacementWriterRefusal): string {
|
|
4
|
+
const writerRoot = rootCategory !== "active locator" && rootCategory !== "home floor";
|
|
5
|
+
const renewal = rootCategory === "writer renewal" || (writerRoot && causeClass !== "unavailable");
|
|
6
|
+
return `${renewal ? "writer renewal needed" : "writer proof refused"} (${rootCategory}, ${causeClass})`;
|
|
7
|
+
}
|
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
import { randomBytes } from "node:crypto";
|
|
10
10
|
import { closeSync, constants, fstatSync, lstatSync, mkdirSync, openSync, opendirSync, readSync, renameSync, rmSync, writeFileSync } from "node:fs";
|
|
11
11
|
import { join } from "node:path";
|
|
12
|
-
import { PLACEMENT_REFUSAL_CATEGORIES, type PlacementRefusalCategory } from "./sync-placement-refusal-category.ts";
|
|
12
|
+
import { PLACEMENT_REFUSAL_CATEGORIES, validPlacementWriterRefusal, type PlacementRefusalCategory, type PlacementWriterRefusal } from "./sync-placement-refusal-category.ts";
|
|
13
13
|
import { processLiveness, processSignature, type Liveness } from "./platform.ts";
|
|
14
14
|
|
|
15
15
|
export const SYNC_PROGRESS_SCHEMA = "agent-mem.sync-progress/v1", SYNC_PROGRESS_INTERVAL_MS = 1000, SYNC_PROGRESS_DIR = "sync-status";
|
|
@@ -48,6 +48,16 @@ export interface SyncProgressSnapshot {
|
|
|
48
48
|
/** #426: for a failed placement sync, the fixed category of the check that refused (allowlisted, no text). */
|
|
49
49
|
category?: PlacementRefusalCategory;
|
|
50
50
|
}
|
|
51
|
+
interface SyncStatusSnapshot extends SyncProgressSnapshot {
|
|
52
|
+
writerRefusal?: PlacementWriterRefusal;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** The CLI attaches its typed writer evidence only at a failed terminal checkpoint. */
|
|
56
|
+
export function syncStatusSnapshot(snapshot: SyncProgressSnapshot, writerRefusal?: PlacementWriterRefusal): SyncStatusSnapshot {
|
|
57
|
+
if (snapshot.state !== "failed" || !validPlacementWriterRefusal(writerRefusal)) return snapshot;
|
|
58
|
+
return { ...snapshot, writerRefusal: { causeClass: writerRefusal.causeClass, rootCategory: writerRefusal.rootCategory } };
|
|
59
|
+
}
|
|
60
|
+
|
|
51
61
|
export type SyncProgressSink = (snapshot: SyncProgressSnapshot) => void;
|
|
52
62
|
export interface SyncProgressOptions { sink: SyncProgressSink; intervalMs?: number; now?: () => number; mono?: () => number; operationId?: string }
|
|
53
63
|
|
|
@@ -157,7 +167,7 @@ function readBounded(file: string): Buffer | undefined {
|
|
|
157
167
|
}
|
|
158
168
|
const count = (value: unknown): value is number => typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
|
|
159
169
|
/** Allowlisted enumerations and non-negative integers only: a tampered sidecar cannot inject text into a terminal. */
|
|
160
|
-
function validate(value: unknown, operationId: string): { snapshot:
|
|
170
|
+
function validate(value: unknown, operationId: string): { snapshot: SyncStatusSnapshot; owner: Owner } | undefined {
|
|
161
171
|
if (!value || typeof value !== "object" || Array.isArray(value)) return undefined;
|
|
162
172
|
const v = value as Record<string, unknown>, owner = v.owner as Record<string, unknown> | undefined, proofs = v.proofs as Record<string, unknown> | undefined, counts = v.counts as Record<string, unknown> | undefined, inventory = v.inventory as Record<string, unknown> | undefined;
|
|
163
173
|
if (v.schema !== SYNC_PROGRESS_SCHEMA || v.operationId !== operationId || !(STATES as readonly unknown[]).includes(v.state) || !(PHASES as readonly unknown[]).includes(v.phase)
|
|
@@ -166,12 +176,13 @@ function validate(value: unknown, operationId: string): { snapshot: SyncProgress
|
|
|
166
176
|
|| v.unit !== undefined && (!(UNITS as readonly unknown[]).includes(v.unit) || !count(v.completed)) || v.total !== undefined && !count(v.total)
|
|
167
177
|
|| v.cause !== undefined && !(CAUSES as readonly unknown[]).includes(v.cause)
|
|
168
178
|
|| v.category !== undefined && !(PLACEMENT_REFUSAL_CATEGORIES as readonly unknown[]).includes(v.category)
|
|
179
|
+
|| v.writerRefusal !== undefined && (v.state !== "failed" || !validPlacementWriterRefusal(v.writerRefusal))
|
|
169
180
|
|| counts !== undefined && ![counts.permitted, counts.local, counts.declined, counts.held].every(count)
|
|
170
181
|
|| inventory !== undefined && (!inventory || typeof inventory !== "object" || ![inventory.publications, inventory.completed, inventory.realms].every(count) || (inventory.completed as number) > (inventory.publications as number)
|
|
171
182
|
|| inventory.truncated !== undefined && inventory.truncated !== true
|
|
172
183
|
|| inventory.outcomes !== undefined && (!Array.isArray(inventory.outcomes) || inventory.outcomes.length > MAX_REALM_OUTCOMES
|
|
173
184
|
|| inventory.outcomes.some((item: unknown) => !item || typeof item !== "object" || !realmLabel((item as { realm?: unknown }).realm) || !(SYNC_REALM_OUTCOMES as readonly unknown[]).includes((item as { outcome?: unknown }).outcome))))) return undefined;
|
|
174
|
-
const snapshot:
|
|
185
|
+
const snapshot: SyncStatusSnapshot = { schema: SYNC_PROGRESS_SCHEMA, operationId, state: v.state as SyncProgressState, phase: v.phase as SyncProgressPhase, attempt: v.attempt as number,
|
|
175
186
|
startedUnixMs: v.startedUnixMs as number, elapsedMs: v.elapsedMs as number, phaseElapsedMs: v.phaseElapsedMs as number,
|
|
176
187
|
...(v.unit !== undefined ? { unit: v.unit as SyncProgressUnit, completed: v.completed as number, ...(v.total !== undefined ? { total: v.total as number } : {}) } : {}),
|
|
177
188
|
...(counts ? { counts: { permitted: counts.permitted as number, local: counts.local as number, declined: counts.declined as number, held: counts.held as number } } : {}),
|
|
@@ -179,10 +190,11 @@ function validate(value: unknown, operationId: string): { snapshot: SyncProgress
|
|
|
179
190
|
...(inventory ? { inventory: { publications: inventory.publications as number, completed: inventory.completed as number, realms: inventory.realms as number,
|
|
180
191
|
...(Array.isArray(inventory.outcomes) ? { outcomes: (inventory.outcomes as { realm: string; outcome: SyncRealmOutcome }[]).map(item => ({ realm: item.realm, outcome: item.outcome })) } : {}),
|
|
181
192
|
...(inventory.truncated === true ? { truncated: true } : {}) } } : {}),
|
|
182
|
-
...(v.cause !== undefined ? { cause: v.cause as SyncProgressCause } : {}), ...(v.category !== undefined ? { category: v.category as PlacementRefusalCategory } : {})
|
|
193
|
+
...(v.cause !== undefined ? { cause: v.cause as SyncProgressCause } : {}), ...(v.category !== undefined ? { category: v.category as PlacementRefusalCategory } : {}),
|
|
194
|
+
...(v.writerRefusal !== undefined ? { writerRefusal: v.writerRefusal as PlacementWriterRefusal } : {}) };
|
|
183
195
|
return { snapshot, owner: { pid: owner.pid as number, ...(typeof owner.signature === "string" ? { signature: owner.signature } : {}) } };
|
|
184
196
|
}
|
|
185
|
-
function load(dir: string, name: string): { snapshot:
|
|
197
|
+
function load(dir: string, name: string): { snapshot: SyncStatusSnapshot; owner: Owner } | undefined {
|
|
186
198
|
try { const bytes = readBounded(join(dir, name)); return bytes ? validate(JSON.parse(bytes.toString("utf8")), name.slice(0, 16)) : undefined; } catch { return undefined; }
|
|
187
199
|
}
|
|
188
200
|
|
|
@@ -194,6 +206,8 @@ function load(dir: string, name: string): { snapshot: SyncProgressSnapshot; owne
|
|
|
194
206
|
export function syncProgressSidecar(home: string, owner: Owner = { pid: process.pid, ...(processSignature(process.pid) ? { signature: processSignature(process.pid)! } : {}) }): SyncProgressSink {
|
|
195
207
|
const dir = join(home, SYNC_PROGRESS_DIR); let ready = false;
|
|
196
208
|
return snapshot => {
|
|
209
|
+
const body = JSON.stringify({ ...snapshot, owner }) + "\n";
|
|
210
|
+
if (Buffer.byteLength(body) > MAX_BYTES) throw new Error("sync status exceeds its byte bound");
|
|
197
211
|
if (!ready) {
|
|
198
212
|
mkdirSync(dir, { mode: 0o700, recursive: true }); if (!privateDirectory(dir)) throw new Error("sync status directory unavailable");
|
|
199
213
|
const kept = names(dir).filter(name => name !== `${snapshot.operationId}.json`).map(name => ({ name, mtimeMs: lstatSync(join(dir, name), { throwIfNoEntry: false })?.mtimeMs ?? 0 })).sort((a, b) => b.mtimeMs - a.mtimeMs);
|
|
@@ -204,11 +218,11 @@ export function syncProgressSidecar(home: string, owner: Owner = { pid: process.
|
|
|
204
218
|
ready = true;
|
|
205
219
|
}
|
|
206
220
|
const file = join(dir, `${snapshot.operationId}.json`), temporary = join(dir, `.${snapshot.operationId}.tmp`);
|
|
207
|
-
rmSync(temporary, { force: true }); writeFileSync(temporary,
|
|
221
|
+
rmSync(temporary, { force: true }); writeFileSync(temporary, body, { mode: 0o600, flag: "wx" }); renameSync(temporary, file);
|
|
208
222
|
};
|
|
209
223
|
}
|
|
210
224
|
|
|
211
|
-
export interface SyncOperationStatus extends
|
|
225
|
+
export interface SyncOperationStatus extends SyncStatusSnapshot { ownerLiveness: Liveness; lastAliveAgoMs: number; lastWorkProgressAgoMs: number }
|
|
212
226
|
export interface SyncStatusReport { operations: SyncOperationStatus[]; malformed: number }
|
|
213
227
|
/**
|
|
214
228
|
* Read-only status for another terminal: opens no realm, takes no lock, renews no proof and writes nothing. A running
|
|
@@ -65,6 +65,19 @@ export function syncOutboundContent(row: unknown): Record<string, unknown> {
|
|
|
65
65
|
|
|
66
66
|
/** A row passes when the machine's configured policy and the caller's extra screen (if any) both accept its text. */
|
|
67
67
|
export type RowScreen = (row: Record<string, unknown>) => boolean;
|
|
68
|
+
/**
|
|
69
|
+
* #612: screens whose verdict is a pure function of standalone policy options, recorded with the canonical digest of those
|
|
70
|
+
* options. Package-internal: only these may share a cross-run no-op cache identity; any other host callback has none and
|
|
71
|
+
* always takes the full path.
|
|
72
|
+
*/
|
|
73
|
+
const deterministicScreens = new WeakMap<RowScreen, string>();
|
|
74
|
+
export function deterministicRowScreen(options: { denyPaths?: readonly string[]; piiPatterns?: readonly string[] }): RowScreen {
|
|
75
|
+
const frozen = { denyPaths: [...(options.denyPaths ?? [])], piiPatterns: [...(options.piiPatterns ?? [])] }, policy = createStandalonePolicy(frozen);
|
|
76
|
+
const screen: RowScreen = row => policy.screenStandalone(row);
|
|
77
|
+
deterministicScreens.set(screen, createHash("sha256").update(JSON.stringify(frozen)).digest("hex")); return screen;
|
|
78
|
+
}
|
|
79
|
+
/** The cross-run identity of a screen, or undefined for an arbitrary callback (which has none). */
|
|
80
|
+
export function rowScreenIdentity(screen: RowScreen): string | undefined { return deterministicScreens.get(screen); }
|
|
68
81
|
export type SyncPolicyCategory = StandalonePolicyDecline | "host";
|
|
69
82
|
export type OutboundVerdict = { ok: true } | { ok: false; category: SyncPolicyCategory };
|
|
70
83
|
/** One evaluator for actual sync and public inspection, with the same projection and AND composition. */
|
package/src/memory/work-lists.ts
CHANGED
|
@@ -10,6 +10,7 @@ import { canonicalPath } from "./platform.ts";
|
|
|
10
10
|
import { looksSecret } from "./screen.ts";
|
|
11
11
|
import { stripPrivateDeep, stripPrivateSpans } from "./private-spans.ts";
|
|
12
12
|
import { ensureShardDescriptor, resolveAlias, shardDir } from "./shard.ts";
|
|
13
|
+
import { recordBriefPublicationFailure } from "./metrics.ts";
|
|
13
14
|
import { machineId } from "./machine.ts";
|
|
14
15
|
import type { WorkBrief, WorkBriefBinding, WorkSegment } from "../brief-work.ts";
|
|
15
16
|
import { WORK_BRIEF_BYTES, WORK_BRIEF_VIEWS, pruneWorkBriefs, readWorkBrief, reserveWorkBriefSlot, workLogSegments, workPolicyRevision, writeWorkBrief } from "../brief-work.ts";
|
|
@@ -437,7 +438,7 @@ export class WorkListStore {
|
|
|
437
438
|
const revision = workPolicyRevision(effective);
|
|
438
439
|
if (revision !== workPolicyRevision(home)) await this.publishPolicyBrief(effective, revision, row, frame);
|
|
439
440
|
}
|
|
440
|
-
} catch {
|
|
441
|
+
} catch { recordBriefPublicationFailure(this.base, "work", "write_failed"); }
|
|
441
442
|
}
|
|
442
443
|
|
|
443
444
|
private async publishPolicyBrief(options: StandalonePolicyOptions, revision: string | undefined, row?: WorkRow, frame?: WriteFrame): Promise<void> {
|
|
@@ -451,7 +452,7 @@ export class WorkListStore {
|
|
|
451
452
|
this.briefRetryWrites.delete(key);
|
|
452
453
|
const standalone = createStandalonePolicy({ denyPaths: options.denyPaths, piiPatterns: options.piiPatterns });
|
|
453
454
|
const segments = workLogSegments(this.base, this.project, this.aliased.map(store => store.project));
|
|
454
|
-
if (!segments) return;
|
|
455
|
+
if (!segments) return recordBriefPublicationFailure(this.base, "work", "source_unavailable");
|
|
455
456
|
const binding = { base: this.base, project: this.project, machine: this.machine, ...(revision ? { revision } : {}) };
|
|
456
457
|
const policy = workPolicyRevision(options);
|
|
457
458
|
if (row && frame?.prior && frame.ordered) {
|
|
@@ -466,8 +467,8 @@ export class WorkListStore {
|
|
|
466
467
|
}
|
|
467
468
|
const views = await this.read(undefined, true, input => standalone.screenStandalone(input));
|
|
468
469
|
const rest = workLogSegments(this.base, this.project, this.aliased.map(store => store.project));
|
|
469
|
-
if (!rest || JSON.stringify(segments) !== JSON.stringify(rest)) return;
|
|
470
|
-
if (revision && (!this.briefPolicyOptions || workPolicyRevision(this.briefPolicyOptions()) !== revision)) return;
|
|
470
|
+
if (!rest || JSON.stringify(segments) !== JSON.stringify(rest)) return recordBriefPublicationFailure(this.base, "work", "frontier_changed");
|
|
471
|
+
if (revision && (!this.briefPolicyOptions || workPolicyRevision(this.briefPolicyOptions()) !== revision)) return recordBriefPublicationFailure(this.base, "work", "binding_changed");
|
|
471
472
|
this.publish(binding, { schema: "agent-mem.brief-work/v1", project: this.project, segments, policy,
|
|
472
473
|
rows: views.slice(0, WORK_BRIEF_VIEWS).map(source => ({ source })), truncated: views.length > WORK_BRIEF_VIEWS }, key, shrinkRetry);
|
|
473
474
|
}
|
|
@@ -481,6 +482,7 @@ export class WorkListStore {
|
|
|
481
482
|
return ok;
|
|
482
483
|
});
|
|
483
484
|
if (!written) {
|
|
485
|
+
recordBriefPublicationFailure(this.base, "work", "byte_bound");
|
|
484
486
|
this.briefRetryWrites.set(key, { remaining: 1024, shrinkCooldown: shrinkRetry ? 128 : 0 });
|
|
485
487
|
if (this.briefRetryWrites.size > 5) this.briefRetryWrites.delete(this.briefRetryWrites.keys().next().value!);
|
|
486
488
|
}
|
package/src/session-brief.ts
CHANGED
|
@@ -18,6 +18,7 @@ import { createStandalonePolicy, type StandalonePolicyOptions } from "./memory/p
|
|
|
18
18
|
import { configuredPolicyOptions, loadAmemConfig, repoConfigRoot } from "./memory/config.ts";
|
|
19
19
|
import { pendingLine, pendingSummary } from "./memory/candidate-pending.ts";
|
|
20
20
|
import { memoryProjectKey } from "./memory/project.ts";
|
|
21
|
+
import { curatedCount, projectTransition, transitionNotice } from "./memory/roots.ts";
|
|
21
22
|
import { registerReaderLease } from "./memory/reader-lease.ts";
|
|
22
23
|
import { type ReadRef, type ReadWindow } from "./memory/search-fts.ts";
|
|
23
24
|
import { briefFailureReason } from "./memory/metrics.ts";
|
|
@@ -179,6 +180,14 @@ export async function sessionStartBrief(options: BriefOptions): Promise<BriefRes
|
|
|
179
180
|
// F7: one line, "N candidates pending, oldest expires in D days", only when some wait, so a brief with none is byte-identical to before. It is numbers only (no candidate text),
|
|
180
181
|
// read-only (no database is created, pruned or altered here, and neither the brief nor the hook ever stamps a candidate as shown: only `amem review walk` does) and reserved out of the
|
|
181
182
|
// same byte budget as everything else; when it does not fit it is left out.
|
|
183
|
+
// #581: one notice line when this working root last resolved to a different, unjoined key. A bounded local read
|
|
184
|
+
// (roots.jsonl tail, aliases.jsonl, one read-only index count); any failure yields no line. Reserved first.
|
|
185
|
+
let transitionLine: string | undefined;
|
|
186
|
+
if (!options.measureOnly) {
|
|
187
|
+
const transition = projectTransition(base, cwd, requested, key => curatedCount(base, key, shardDir));
|
|
188
|
+
const notice = transition ? transitionNotice(transition) : undefined;
|
|
189
|
+
if (notice !== undefined && Buffer.byteLength(notice) + 1 <= remaining) { remaining -= Buffer.byteLength(notice) + 1; transitionLine = notice; }
|
|
190
|
+
}
|
|
182
191
|
let candidateLine: string | undefined;
|
|
183
192
|
const line = pendingLine(pendingSummary(base, [project, ...aliases], (options.now ?? Date.now)()));
|
|
184
193
|
if (line !== undefined && Buffer.byteLength(line) + 1 <= remaining) { remaining -= Buffer.byteLength(line) + 1; candidateLine = line; }
|
|
@@ -453,15 +462,20 @@ export async function sessionStartBrief(options: BriefOptions): Promise<BriefRes
|
|
|
453
462
|
}
|
|
454
463
|
}
|
|
455
464
|
guard(true);
|
|
456
|
-
|
|
465
|
+
const notices = () => [...(transitionLine ? [transitionLine] : []), ...(candidateLine ? [candidateLine] : [])];
|
|
466
|
+
let context = [header(coverage, reasons), ...notices(), ...lines].join("\n");
|
|
457
467
|
while (Buffer.byteLength(context) > maximum && lines.length) {
|
|
458
468
|
const repoIndex = lines.findLastIndex(line => line.startsWith('{"section":"repo",'));
|
|
459
469
|
const removed = JSON.parse(lines.splice(repoIndex >= 0 ? repoIndex : lines.length - 1, 1)[0]!) as { section?: Section };
|
|
460
470
|
if (removed.section && coverage[removed.section] === "complete") coverage[removed.section] = "partial";
|
|
461
|
-
context = [header(coverage, reasons), ...(
|
|
471
|
+
context = [header(coverage, reasons), ...notices(), ...lines].join("\n");
|
|
462
472
|
}
|
|
463
473
|
if (Buffer.byteLength(context) > maximum && candidateLine) {
|
|
464
474
|
candidateLine = undefined;
|
|
475
|
+
context = [header(coverage, reasons), ...notices(), ...lines].join("\n");
|
|
476
|
+
}
|
|
477
|
+
if (Buffer.byteLength(context) > maximum && transitionLine) {
|
|
478
|
+
transitionLine = undefined;
|
|
465
479
|
context = [header(coverage, reasons), ...lines].join("\n");
|
|
466
480
|
}
|
|
467
481
|
if (Buffer.byteLength(context) > maximum) result = unavailable();
|
package/src/setup-drift.ts
CHANGED
|
@@ -2,7 +2,7 @@ import { closeSync, constants, type Dir, existsSync, fstatSync, lstatSync, opend
|
|
|
2
2
|
import { dirname, isAbsolute, join, resolve } from "node:path";
|
|
3
3
|
import { createHash } from "node:crypto";
|
|
4
4
|
import { isDeepStrictEqual } from "node:util";
|
|
5
|
-
import { setupReceiptRemedy, type SetupTarget } from "./setup.ts";
|
|
5
|
+
import { setupReceiptRemedy, type SetupTarget } from "./setup-writer-roots.ts";
|
|
6
6
|
import { SETUP_CONFIG_BYTES } from "./setup-toml.ts";
|
|
7
7
|
import { amemCaptureCommand, amemCaptureHooks, managedAfter, managedHookEntries, mcpLauncher, mcpRecord, type ConfigImage } from "./setup-owned.ts";
|
|
8
8
|
import { resolveSetupPaths, type SetupEnvironment } from "./setup-paths.ts";
|