@staix/agent-mem 0.28.0 → 0.28.2
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/cli.ts +13 -3
- package/src/memory/home-identity.ts +26 -0
- package/src/memory/public-prune-advance.ts +2 -1
- package/src/memory/shard-sync-applications.ts +1 -1
- package/src/memory/shard.ts +11 -4
- package/src/memory/sync-placement-activation-proof.ts +3 -2
- package/src/memory/sync-placement-activation-storage.ts +2 -1
- package/src/memory/sync-placement-active.ts +2 -1
- package/src/memory/sync-placement-capture.ts +13 -3
- package/src/memory/sync-placement-transport.ts +2 -1
- package/src/memory/sync-placement-writer-history.ts +3 -2
package/README.md
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
Curated memory with append-only JSONL logs, a derived SQLite index, short- and long-term tiers, a typed graph, goals with leases, and git sync between machines. Extracted from [agent-hub](https://github.com/STAIxBWLB/agent-hub), with compatible storage and entry IDs.
|
|
4
4
|
|
|
5
5
|
<!-- facts:version -->
|
|
6
|
-
Version: 0.28.
|
|
6
|
+
Version: 0.28.2. Requires Bun 1.4.2 or later; no runtime dependencies.
|
|
7
7
|
<!-- /facts:version -->
|
|
8
8
|
|
|
9
9
|
## Quick start
|
package/package.json
CHANGED
package/src/cli.ts
CHANGED
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
import { parseRecordLines } from "./hook-record.ts";
|
|
2
2
|
import { assertFormatFloor } from "./memory/formats.ts";
|
|
3
3
|
import { placementRuntimeRefusal, readPlacementRuntimeMarkers } from "./memory/sync-placement-guard.ts";
|
|
4
|
+
import { readActivePlacementBinding } from "./memory/sync-placement-active.ts";
|
|
4
5
|
import { activatePublicPruneView } from "./memory/public-prune-activation.ts";
|
|
5
6
|
import { AgentUsageError, agentCliRead } from "./cli-agent-reads.ts";
|
|
6
7
|
import { cliAttribution, withCliAttribution } from "./memory/cli-attribution.ts";
|
|
7
|
-
import { randomUUID } from "node:crypto";
|
|
8
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
8
9
|
import type { Writable } from "node:stream";
|
|
9
10
|
import { buildIntentBrief } from "./memory/intent-brief.ts";
|
|
10
11
|
import { proposeConsolidation } from "./memory/consolidate.ts";
|
|
@@ -32,7 +33,7 @@ import { memoryProjectKey } from "./memory/project.ts";
|
|
|
32
33
|
import { CandidateStore, candidateTargetRevision, type CandidateFilter } from "./memory/candidates.ts";
|
|
33
34
|
import { candidateOverlaps, candidateOverlapsBatch } from "./memory/candidate-overlaps.ts";
|
|
34
35
|
import { openCuratedForRead } from "./memory/curated-read.ts";
|
|
35
|
-
import { aliasedKeys, appendAlias, appendUnalias, listAliases, readShardedSelection, resolveAlias } from "./memory/shard.ts";
|
|
36
|
+
import { aliasedKeys, appendAlias, appendUnalias, assertCuratedShardPaths, listAliases, readShardedSelection, resolveAlias } from "./memory/shard.ts";
|
|
36
37
|
import { capacityReport, capacityText, capacityApplyText, capacitySplitText } from "./memory/capacity.ts";
|
|
37
38
|
import { CaptureStore, readCaptureConfigFile, writeCaptureConfigFile, type CaptureConfig } from "./memory/capture.ts";
|
|
38
39
|
|
|
@@ -1207,18 +1208,27 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
1207
1208
|
let output: string;
|
|
1208
1209
|
let placementWriters: import("./sync-placement-writer-context.ts").PlacementWriterContext | undefined;
|
|
1209
1210
|
let progress: import("./memory/sync-progress.ts").SyncProgress | undefined;
|
|
1211
|
+
let skippedCwdProject = false;
|
|
1210
1212
|
const stop = ifDue ? stopSignal(context.syncDeadlineMs ?? SYNC_IF_DUE_DEADLINE_MS, process) : undefined;
|
|
1211
1213
|
try {
|
|
1212
1214
|
if (sub === "sync" && (readPlacementRuntimeMarkers(syncHome).profile as { publicationFormat?:string } | undefined)?.publicationFormat === "agent-mem.sync-placement/v1") {
|
|
1213
1215
|
const { activePlacementWriterContext } = await import("./sync-placement-writer-context.ts");
|
|
1214
1216
|
progress = await placementProgress(syncHome, typeof options["--progress"] === "string" ? options["--progress"] as string : "auto", context);
|
|
1215
1217
|
placementWriters = activePlacementWriterContext(syncHome,fileURLToPath(new URL("..",import.meta.url)));
|
|
1218
|
+
const markers = readPlacementRuntimeMarkers(syncHome);
|
|
1219
|
+
const active = readActivePlacementBinding(syncHome, markers.profile, markers.shards);
|
|
1220
|
+
if (!active) throw Error("sync placement activation metadata unavailable or changed; inspect the retained activation before continuing");
|
|
1221
|
+
skippedCwdProject = !active.activation.realms.some(realm => realm.scope === "project" && realm.keyHash === createHash("sha256").update(boundProject()).digest("hex"));
|
|
1216
1222
|
}
|
|
1217
|
-
output = await withRepoRows(await rawMemoryCommand(memoryArgs, cwd, { person: true, rankedSearch: !legacySearch, ...(identity.actor === "agent" ? { screenGraph: true } : {}), ...(explainSearch ? { explainSearch: true } : {}), project: boundProject(), open, readable: notes => identity.actor === "person" ? notes : notes.filter(view => view.project === boundProject() && policyOf().screenStandalone(view)), stale: createRecallStalenessProbe({ cwd: recallRoot ?? cwd, rootConfirmed, policy: () => configured }), outputReady: notes => outputReady(notes.map(view => view.id)), importPolicy: () => text => configured.declinesPersonal(text),
|
|
1223
|
+
output = await withRepoRows(await rawMemoryCommand(memoryArgs, cwd, { person: true, rankedSearch: !legacySearch, ...(identity.actor === "agent" ? { screenGraph: true } : {}), ...(explainSearch ? { explainSearch: true } : {}), project: boundProject(), open: skippedCwdProject ? () => openShardStore({ memoryDir: syncHome, user: true, deferPromotions: true }) : sub === "sync" && placementWriters ? () => { assertCuratedShardPaths(syncHome, { project: boundProject() }, "cwd binding"); return open(); } : open, readable: notes => identity.actor === "person" ? notes : notes.filter(view => view.project === boundProject() && policyOf().screenStandalone(view)), stale: createRecallStalenessProbe({ cwd: recallRoot ?? cwd, rootConfirmed, policy: () => configured }), outputReady: notes => outputReady(notes.map(view => view.id)), importPolicy: () => text => configured.declinesPersonal(text),
|
|
1218
1224
|
sync: { ...(placementWriters ? { placementAttestation:placementWriters.attest } : {}), ...(progress ? { progress } : {}), screen: row => configured.screenStandalone(row), policyVersion: () => JSON.stringify(configuredPolicyOptions(memoryHome(), policyCwd)), ...(stop ? { signal: stop.signal } : {}) }, // the repository-narrowed policy binds what sync publishes too
|
|
1219
1225
|
onBridgeStatus: status => { receipt.bridgeStatus = status; },
|
|
1220
1226
|
// #188: ids-only listing of nearby machine-local rows; policy-refused rows are neither listed nor counted.
|
|
1221
1227
|
forgetNearby: note => forgetNearby({ base: memoryHome(), project: note.project, text: note.text, title: note.title, screen: value => configured.screenStandalone(value) }) }));
|
|
1228
|
+
if (skippedCwdProject) {
|
|
1229
|
+
const notice = "cwd project is not in the activated inventory and was skipped";
|
|
1230
|
+
output = options["--json"] ? JSON.stringify({ ...JSON.parse(output), skippedCwdProject: notice }, null, 2) : `${output}\n${notice}`;
|
|
1231
|
+
}
|
|
1222
1232
|
} catch (error) {
|
|
1223
1233
|
if (sub === "sync") progress?.finish(stop?.cause() ? "cancelled" : "failed", stop?.cause() ? "cancelled" : "unavailable");
|
|
1224
1234
|
if (sub === "sync") stampSync((error as Error).message, stop?.cause());
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/** Memory home identity bound into sync-placement epochs (#444). */
|
|
2
|
+
import type { BigIntStats } from "node:fs";
|
|
3
|
+
import { hashJSON } from "./generation.ts";
|
|
4
|
+
|
|
5
|
+
type HomeStat = Pick<BigIntStats, "dev" | "ino" | "uid">;
|
|
6
|
+
const hashFor = (home: string, dev: bigint, stat: HomeStat) => hashJSON([home, String(dev), String(stat.ino), String(stat.uid)]);
|
|
7
|
+
const resolved = new Map<string, string>();
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Hash of the home's path, device, inode and uid. Epochs persist this value, and a macOS reboot can renumber the volume's
|
|
11
|
+
* `st.dev` while the directory stays the same. When `pinned` reproduces from the current path, inode and uid with another
|
|
12
|
+
* device number, it is returned unchanged, so a retained epoch keeps binding; a replaced or copied home still differs by inode.
|
|
13
|
+
* ponytail: only device numbers that differ in the low 16 bits are tried (65536 hashes, about 30 ms, memoized per process);
|
|
14
|
+
* widen the window or bind a stored volume UUID if a platform renumbers higher bits.
|
|
15
|
+
*/
|
|
16
|
+
export function homeIdentityHash(home: string, stat: HomeStat, pinned?: string): string {
|
|
17
|
+
const current = hashFor(home, stat.dev, stat);
|
|
18
|
+
if (pinned === undefined || pinned === current) return current;
|
|
19
|
+
const key = JSON.stringify([pinned, home, String(stat.dev), String(stat.ino), String(stat.uid)]);
|
|
20
|
+
const known = resolved.get(key); if (known !== undefined) return known;
|
|
21
|
+
let result = current;
|
|
22
|
+
const base = stat.dev & ~0xffffn;
|
|
23
|
+
for (let low = 0n; low <= 0xffffn; low++) if (hashFor(home, base | low, stat) === pinned) { result = pinned; break; }
|
|
24
|
+
resolved.set(key, result); return result;
|
|
25
|
+
}
|
|
26
|
+
export const homeIdentityMatches = (expected: string, home: string, stat: HomeStat): boolean => homeIdentityHash(home, stat, expected) === expected;
|
|
@@ -14,6 +14,7 @@ import { invalidateCuratedCaches } from "./curated-cache-state.ts";
|
|
|
14
14
|
export type PublicPruneAdvanceStage = "after-intent" | "after-shards" | "after-profile" | "after-remove";
|
|
15
15
|
export interface PublicPruneAdvanceOptions {
|
|
16
16
|
memoryDir: string; view: PublicPruneViewV1; expectedRevision: string; mutations?: readonly MutationHandle[];
|
|
17
|
+
origin?: "remote";
|
|
17
18
|
checkpoint?: (stage: PublicPruneAdvanceStage) => void | Promise<void>;
|
|
18
19
|
}
|
|
19
20
|
export interface PublicPruneAdvanceResult { revision: string; viewHash: string }
|
|
@@ -141,7 +142,7 @@ export async function advancePublicPruneView(options: PublicPruneAdvanceOptions)
|
|
|
141
142
|
const previousProfile=raw(join(home,"profile.json")),previousShards=raw(join(home,"shards.json")),old=readPublicPruneViewForActivation(home,profile.pruneInputSetHash,profile.generation);
|
|
142
143
|
const bindings:Binding[]=[];
|
|
143
144
|
for(const key of Object.keys(view.realms).sort())if(old.realms[key]!==view.realms[key]){
|
|
144
|
-
const bound=resolveShardProfile(home,key==="user"?{user:true}:{project:key.slice(8)}),stat=owned(bound.dir,true);
|
|
145
|
+
const bound=resolveShardProfile(home,key==="user"?{user:true}:{project:key.slice(8)}, options.origin),stat=owned(bound.dir,true);
|
|
145
146
|
bindings.push({key,dir:bound.dir,dev:stat.dev,ino:stat.ino,metadata:metadata(bound.dir)});
|
|
146
147
|
}
|
|
147
148
|
const final={...profile,pruneInputSetHash:publicPruneViewHash(view)},shards={...JSON.parse(previousShards),selectorRevision:hashJSON(final)};
|
|
@@ -141,7 +141,7 @@ export class ShardSyncApplications {
|
|
|
141
141
|
const view: PublicPruneViewV1 = { ...this.#boundView, realms };
|
|
142
142
|
if (canonicalJSON(view) !== canonicalJSON(this.#boundView)) {
|
|
143
143
|
for (const target of o.targets) shardSelectorRetention(target, true, true);
|
|
144
|
-
const result = await advancePublicPruneView({ memoryDir: o.home, view, expectedRevision: o.getRevision(), mutations: [o.homeMutation, ...o.targets.map(target => target.mutation!)] });
|
|
144
|
+
const result = await advancePublicPruneView({ memoryDir: o.home, view, expectedRevision: o.getRevision(), origin: "remote", mutations: [o.homeMutation, ...o.targets.map(target => target.mutation!)] });
|
|
145
145
|
o.setRevision(result.revision); this.#boundView = view;
|
|
146
146
|
for (const target of o.targets) target.store.refresh();
|
|
147
147
|
await o.afterAdvance();
|
package/src/memory/shard.ts
CHANGED
|
@@ -153,17 +153,24 @@ export function readShardedSelection(memoryDir: string): ShardedSelection {
|
|
|
153
153
|
}catch(error){if(safeProfileLockMessage(error))throw error;throw profileLockRecoveryError(memoryDir)??error;}
|
|
154
154
|
}
|
|
155
155
|
|
|
156
|
+
/** Bounded identifiers only, safe to surface without exposing a project key or row. */
|
|
157
|
+
export class PlacementRealmRefusal extends Error {
|
|
158
|
+
constructor(readonly scope: "user" | "project", readonly keyHash: string | undefined, readonly origin: "cwd binding" | "remote" | "local binding") {
|
|
159
|
+
super(`sync placement realm is outside the activated inventory: scope=${scope}${keyHash ? ` keyHash=${keyHash}` : ""}; origin=${origin}; review its activation before opening it`);
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
|
|
156
163
|
/** Fixed curated paths cannot redirect writes into legacy inputs or another shard.
|
|
157
164
|
* ponytail: same-user concurrent parent replacement needs descriptor-relative opens; fixed preflight does not claim that fence.
|
|
158
165
|
*/
|
|
159
|
-
export function assertCuratedShardPaths(memoryDir: string, opts: { project?: string; user?: boolean }): void {
|
|
166
|
+
export function assertCuratedShardPaths(memoryDir: string, opts: { project?: string; user?: boolean }, origin: "cwd binding" | "remote" | "local binding" = "local binding"): void {
|
|
160
167
|
assertPlacementRuntime(memoryDir);
|
|
161
168
|
const selector = readProfileJSON(join(memoryDir, "profile.json")) as {schema?:unknown} | undefined;
|
|
162
169
|
if (selector?.schema === "agent-mem.profile/v3") {
|
|
163
170
|
const active = readActivePlacementBinding(memoryDir, selector, readProfileJSON(join(memoryDir, "shards.json")));
|
|
164
171
|
const keyHash = opts.user ? undefined : createHash("sha256").update(opts.project!).digest("hex");
|
|
165
172
|
if (!active || !active.activation.realms.some(realm => opts.user ? realm.scope === "user" : realm.scope === "project" && realm.keyHash === keyHash))
|
|
166
|
-
throw new
|
|
173
|
+
throw new PlacementRealmRefusal(opts.user ? "user" : "project", keyHash, origin);
|
|
167
174
|
}
|
|
168
175
|
const dir = opts.user === true ? userShardDir(memoryDir) : shardDir(memoryDir, opts.project!);
|
|
169
176
|
const check = (path: string, directory: boolean) => {
|
|
@@ -180,9 +187,9 @@ export function assertCuratedShardPaths(memoryDir: string, opts: { project?: str
|
|
|
180
187
|
}
|
|
181
188
|
|
|
182
189
|
/** Open one already-sealed shard without consulting the legacy home or the catalog. */
|
|
183
|
-
export function resolveShardProfile(memoryDir: string, opts: { project?: string; user?: boolean }): BoundProfile {
|
|
190
|
+
export function resolveShardProfile(memoryDir: string, opts: { project?: string; user?: boolean }, origin?: "cwd binding" | "remote" | "local binding"): BoundProfile {
|
|
184
191
|
if (opts.user === true && opts.project !== undefined || opts.user !== true && !opts.project) throw new Error("choose exactly one project or the user shard");
|
|
185
|
-
assertCuratedShardPaths(memoryDir, opts);
|
|
192
|
+
assertCuratedShardPaths(memoryDir, opts, origin);
|
|
186
193
|
const deadline = Date.now() + PROFILE_LOCK_TIMEOUT_MS, initial = shardSnapshot(memoryDir, deadline), generation = initial.journal.generation;
|
|
187
194
|
const dir = opts.user === true ? userShardDir(memoryDir) : shardDir(memoryDir, opts.project!);
|
|
188
195
|
if (opts.project !== undefined && readShardDescriptor(memoryDir, shardKeyHash(opts.project))?.key !== opts.project) throw new Error("curated shard project identity mismatch");
|
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
/** Internal activation-owner proof. No serialized object or boolean grants lock bypass authority. */
|
|
2
2
|
import { closeSync, constants, fstatSync, lstatSync, openSync, readSync, type BigIntStats } from "node:fs";
|
|
3
3
|
import { join } from "node:path";
|
|
4
|
-
import { canonicalJSON
|
|
4
|
+
import { canonicalJSON } from "./generation.ts";
|
|
5
|
+
import { homeIdentityMatches } from "./home-identity.ts";
|
|
5
6
|
import { assertMutationHandle, type MutationHandle } from "./mutation.ts";
|
|
6
7
|
import { processSignature, realPath } from "./platform.ts";
|
|
7
8
|
import type { PlacementActivationMarkerSnapshot } from "./sync-placement-capture.ts";
|
|
@@ -53,7 +54,7 @@ export function createPlacementActivationCaptureProof(owner: PlacementActivation
|
|
|
53
54
|
const state = owners.get(owner)!;
|
|
54
55
|
const intent = validatePlacementActivationIntent(input), actual = readPlacementActivationIntent(state.home);
|
|
55
56
|
if (!intent || !actual || canonicalJSON(intent) !== canonicalJSON(actual)
|
|
56
|
-
|| actual.home !== state.home || actual.epoch.homeHash
|
|
57
|
+
|| actual.home !== state.home || !homeIdentityMatches(actual.epoch.homeHash,state.home,state.root)) fail();
|
|
57
58
|
const token = Object.freeze({}) as PlacementActivationCaptureProof; captures.set(token,{owner,intent:actual}); return token;
|
|
58
59
|
}
|
|
59
60
|
export function activationSourceMarkers(token: PlacementActivationCaptureProof, home: string, markers: { profileText: string; shardsText: string; profileStamp: readonly string[]; shardsStamp: readonly string[] }): PlacementActivationMarkerSnapshot {
|
|
@@ -5,6 +5,7 @@ import { isAbsolute, join, resolve } from "node:path";
|
|
|
5
5
|
import { types } from "node:util";
|
|
6
6
|
import { canonicalJSON, hashJSON } from "./generation.ts";
|
|
7
7
|
import { realPath } from "./platform.ts";
|
|
8
|
+
import { homeIdentityMatches } from "./home-identity.ts";
|
|
8
9
|
import { assertMutationHandle, type MutationHandle } from "./mutation.ts";
|
|
9
10
|
import { validatePlacementBaseV2, validatePlacementShards, validatePlacementMarkerTransition, PLACEMENT_FORMAT, PLACEMENT_SHARDS_SCHEMA } from "./sync-placement-format.ts";
|
|
10
11
|
import { validatePlacementPlan, type SyncPlacementActivationPlan } from "./sync-placement-plan.ts";
|
|
@@ -104,7 +105,7 @@ function root(home: string): { home: string; stat: BigIntStats; file: string } {
|
|
|
104
105
|
if (stat.dev !== current.dev || stat.ino !== current.ino) fail("changed"); return { home: canonical, stat, file: join(canonical, PLACEMENT_ACTIVATION_INTENT_FILE) };
|
|
105
106
|
}
|
|
106
107
|
function bindHome(intent: PlacementActivationIntent, current: ReturnType<typeof root>): void {
|
|
107
|
-
if (intent.home !== current.home || intent.epoch.homeHash
|
|
108
|
+
if (intent.home !== current.home || !homeIdentityMatches(intent.epoch.homeHash, current.home, current.stat)) fail("changed");
|
|
108
109
|
}
|
|
109
110
|
interface Read { intent: PlacementActivationIntent; text: string; stat: BigIntStats }
|
|
110
111
|
function read(current: ReturnType<typeof root>): Read | undefined {
|
|
@@ -3,6 +3,7 @@ import { closeSync, constants, fstatSync, lstatSync, openSync, readSync, type Bi
|
|
|
3
3
|
import { join } from "node:path";
|
|
4
4
|
import { canonicalJSON, hashJSON } from "./generation.ts";
|
|
5
5
|
import { realPath } from "./platform.ts";
|
|
6
|
+
import { homeIdentityHash } from "./home-identity.ts";
|
|
6
7
|
import { validatePlacementProfile, validatePlacementShards, type PlacementProfile, type PlacementShards } from "./sync-placement-format.ts";
|
|
7
8
|
import { validatePlacementPlan, type SyncPlacementActivationPlan } from "./sync-placement-plan.ts";
|
|
8
9
|
import { placementEpochHash, validatePlacementEpoch, validatePlacementActiveFence, type PlacementEpoch } from "./sync-placement-journal-format.ts";
|
|
@@ -84,7 +85,7 @@ export function readActivePlacementBinding(homeInput: string, profileInput: unkn
|
|
|
84
85
|
const epochFile = read(join(dir, "epoch.json")), activationFile = read(join(dir, "activation.json")), fenceFile = read(join(home, "sync-placement", "active.json"));
|
|
85
86
|
if (!epochFile || !activationFile || !fenceFile) return undefined;
|
|
86
87
|
const epoch = validatePlacementEpoch(epochFile.value), activation = validatePlacementPlan(activationFile.value), fence = validatePlacementActiveFence(fenceFile.value);
|
|
87
|
-
const homeHash =
|
|
88
|
+
const homeHash = homeIdentityHash(home, root, epoch.homeHash);
|
|
88
89
|
if (epoch.homeHash !== homeHash || epoch.generation !== profile.generation || placementEpochHash(epoch) !== profile.placementHead
|
|
89
90
|
|| activation.contextHash !== epoch.contextHash || activation.generation !== epoch.generation || activation.targetProfile.placementHead !== profile.placementHead
|
|
90
91
|
|| fence.epochHash !== profile.placementHead || fence.homeHash !== homeHash || fence.generation !== profile.generation) fail();
|
|
@@ -2,7 +2,7 @@ import type { PlacementPublicationSource } from "./sync-placement-publication-pl
|
|
|
2
2
|
import { validatePlacementKey, type PlacementRealm } from "./sync-placement-journal-format.ts";
|
|
3
3
|
import { types } from "node:util";
|
|
4
4
|
import { createHash } from "node:crypto";
|
|
5
|
-
import { closeSync, constants, fstatSync, lstatSync, openSync, opendirSync, readSync, type BigIntStats } from "node:fs";
|
|
5
|
+
import { closeSync, constants, fstatSync, lstatSync, openSync, opendirSync, readFileSync, readSync, type BigIntStats } from "node:fs";
|
|
6
6
|
import { join } from "node:path";
|
|
7
7
|
import { canonicalJSON, generationDescriptor, hashJSON, validateVaultLinkRow, type BoundProfile, type VaultLinkRow } from "./generation.ts";
|
|
8
8
|
import { validatePlacementBaseV2, validatePlacementProfile, validatePlacementShards, PLACEMENT_PROFILE_SCHEMA } from "./sync-placement-format.ts";
|
|
@@ -16,7 +16,9 @@ import { readShardLegacySnapshot } from "./shard-bridge.ts";
|
|
|
16
16
|
import { coalesceGenerationSource } from "./generation-index.ts";
|
|
17
17
|
import { validatePruneRow, type PruneSourceRow, type PruneRow } from "./prune.ts";
|
|
18
18
|
import { shardKeyHash, SHARD_SCHEMA } from "./shard.ts";
|
|
19
|
-
import { SyncPlacementJournalError, placementKeyId, type PlacementKey } from "./sync-placement-journal-format.ts";
|
|
19
|
+
import { SyncPlacementJournalError, placementKeyId, validatePlacementActiveFence, type PlacementKey } from "./sync-placement-journal-format.ts";
|
|
20
|
+
import { readPlacementActivationIntent } from "./sync-placement-activation-storage.ts";
|
|
21
|
+
import { homeIdentityHash } from "./home-identity.ts";
|
|
20
22
|
import type { Entry } from "./store.ts";
|
|
21
23
|
import { assertPlacementRuntime } from "./sync-placement-guard.ts";
|
|
22
24
|
import { activationSourceMarkers, assertPlacementActivationOwner, type PlacementActivationOwner, type PlacementActivationCaptureProof } from "./sync-placement-activation-proof.ts";
|
|
@@ -288,7 +290,7 @@ function sourcePreview(homeInput: string, selected?: readonly PlacementRealm[],
|
|
|
288
290
|
const defaults = memoryPolicySnapshot({ names: DENY_NAMES, segments: DENY_SEGMENTS }); if (!defaults) fail();
|
|
289
291
|
const configuration = loadAmemConfig(home).config;
|
|
290
292
|
const contextBase: PlacementSourcePreview["base"] = { ...base,
|
|
291
|
-
homeHash:
|
|
293
|
+
homeHash: homeIdentityHash(home, root, pinnedHomeHash(home, activeHead, !!ownerProof)), sourceHash: hashJSON(facts),
|
|
292
294
|
aliasesHash: digest(aliases ?? Buffer.alloc(0)), policyHash: hashJSON({ config: configuration, defaults, policyVersion }), realms };
|
|
293
295
|
// ponytail: passive checks rely on native inode/size/ctime identity for the hashed prefixes.
|
|
294
296
|
// Immutable descriptor-bound source blocks are the upgrade path for hostile same-user raw writers.
|
|
@@ -305,6 +307,14 @@ function sourcePreview(homeInput: string, selected?: readonly PlacementRealm[],
|
|
|
305
307
|
return { home, base: contextBase, assertSourcesUnchanged, ...(activeHead ? { activeHead } : {}), markerHash, markers,
|
|
306
308
|
directories: directories.sort(), prefixes, rows, specialRows, sourceRowsByRealm };
|
|
307
309
|
}
|
|
310
|
+
/** The homeHash a retained epoch (or an in-flight activation) already committed to, so a reboot-renumbered device keeps binding (#444). */
|
|
311
|
+
function pinnedHomeHash(home: string, activeHead: string | undefined, activating: boolean): string | undefined {
|
|
312
|
+
try {
|
|
313
|
+
if (activeHead) return validatePlacementActiveFence(JSON.parse(readFileSync(join(home, "sync-placement", "active.json"), "utf8"))).homeHash;
|
|
314
|
+
if (activating) return readPlacementActivationIntent(home)?.epoch.homeHash;
|
|
315
|
+
} catch { /* unreadable metadata stays refused by the binding checks */ }
|
|
316
|
+
return undefined;
|
|
317
|
+
}
|
|
308
318
|
/** Read-only preview shares the source collector, without fabricating a quiescence attestation. */
|
|
309
319
|
export function previewSyncPlacementSources(home: string): PlacementSourcePreview {
|
|
310
320
|
return previewSources(home);
|
|
@@ -6,7 +6,7 @@ import { canonicalJSON, hashJSON, readSelector } from "./generation.ts";
|
|
|
6
6
|
import { generationSyncLock } from "./generation-sync.ts";
|
|
7
7
|
import { generationSyncGit, generationSyncGitBytes, remoteVisibility, type SyncOptions, type SyncResult } from "./sync.ts";
|
|
8
8
|
import { acquireMutation, assertMutationHandle, type MutationHandle } from "./mutation.ts";
|
|
9
|
-
import { isLocalKey, resolveShardProfile } from "./shard.ts";
|
|
9
|
+
import { isLocalKey, PlacementRealmRefusal, resolveShardProfile } from "./shard.ts";
|
|
10
10
|
import { memoryPolicySnapshot } from "./policy.ts";
|
|
11
11
|
import { outboundPolicyEvaluator } from "./sync-screen.ts";
|
|
12
12
|
import { readActivePlacementBinding } from "./sync-placement-active.ts";
|
|
@@ -580,6 +580,7 @@ class PlacementTransport {
|
|
|
580
580
|
const bound=this.attemptHash||this.journal?.publicationReservation?undefined:placementSyncBoundReceipt(error);
|
|
581
581
|
if(bound){this.bound=bound;return this.result(false,"not-needed",placementSyncBoundMessage(bound));}
|
|
582
582
|
if(this.attemptHash)return this.result(false,"unknown","Placement sync stopped with a retained attempt that may have published; recheck its exact receipts before another publication.");
|
|
583
|
+
if (error && typeof error === "object" && !types.isProxy(error) && error instanceof PlacementRealmRefusal && error.origin === "remote") return this.result(false, "not-needed", error.message);
|
|
583
584
|
// #426: name the failing check by a fixed category and the phase; never the error's own text, which may carry a path.
|
|
584
585
|
this.refusal=placementRefusalCategoryOf(error)??classifyPlacementError(error)??"other";
|
|
585
586
|
return this.result(false,"not-needed",placementRefusalMessage(this.refusal,this.phaseNow));
|
|
@@ -3,7 +3,8 @@ import { createHash } from "node:crypto";
|
|
|
3
3
|
import { closeSync, constants, fstatSync, fsyncSync, linkSync, lstatSync, openSync, opendirSync, readSync, unlinkSync, writeSync, type BigIntStats } from "node:fs";
|
|
4
4
|
import { dirname, join } from "node:path";
|
|
5
5
|
import { types } from "node:util";
|
|
6
|
-
import { canonicalJSON
|
|
6
|
+
import { canonicalJSON } from "./generation.ts";
|
|
7
|
+
import { homeIdentityMatches } from "./home-identity.ts";
|
|
7
8
|
import { realPath } from "./platform.ts";
|
|
8
9
|
import { assertMutationHandle, type MutationHandle } from "./mutation.ts";
|
|
9
10
|
import {
|
|
@@ -70,7 +71,7 @@ function binding(value: WriterHistoryBinding): WriterHistoryBinding {
|
|
|
70
71
|
interface Paths { home: string; epoch: string; intent: string; log: string; dirs: [string,BigIntStats][] }
|
|
71
72
|
function paths(homeInput: string, input: WriterHistoryBinding): Paths {
|
|
72
73
|
const home=realPath(homeInput), original=checkedDir(homeInput), root=checkedDir(home);
|
|
73
|
-
if(identity(original)!==identity(root)
|
|
74
|
+
if(identity(original)!==identity(root)||!homeIdentityMatches(input.homeHash,home,root))fail("changed");
|
|
74
75
|
const dirs:[string,BigIntStats][]=[[home,root]];
|
|
75
76
|
let current=home;for(const part of ["sync-placement","epochs",input.epochHash]){current=join(current,part);dirs.push([current,checkedDir(current)]);}
|
|
76
77
|
return {home,epoch:current,intent:join(home,WRITER_RENEWAL_INTENT_FILE),log:join(current,WRITER_COMMIT_LOG),dirs};
|