@staix/agent-mem 0.41.0 → 0.42.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 +2 -2
- package/package.json +4 -3
- package/src/cli.ts +129 -24
- package/src/commands-table.ts +11 -4
- package/src/index.ts +2 -1
- package/src/mcp-bounds.ts +3 -0
- package/src/mcp-memory.ts +64 -10
- package/src/mcp.ts +36 -121
- package/src/memory/candidates.ts +21 -5
- package/src/memory/commands.ts +6 -3
- package/src/memory/config.ts +26 -0
- package/src/memory/consolidation-clusters.ts +13 -2
- package/src/memory/doctor-text.ts +4 -1
- package/src/memory/formats-raise.ts +36 -15
- package/src/memory/formats.ts +26 -10
- package/src/memory/profile-marker-cache.ts +45 -0
- package/src/memory/search-fts.ts +55 -27
- package/src/memory/shard.ts +17 -14
- package/src/memory/store.ts +5 -3
- package/src/memory/sync-cadence.ts +8 -4
- package/src/memory/sync-placement-activation-locks.ts +27 -19
- package/src/memory/sync-placement-active.ts +67 -19
- package/src/memory/sync-placement-advertisement.ts +25 -3
- package/src/memory/sync-placement-checkpoint-person.ts +8 -14
- package/src/memory/sync-placement-effective-writers.ts +4 -3
- package/src/memory/sync-placement-guard.ts +29 -11
- package/src/memory/sync-placement-inventory.ts +20 -4
- package/src/memory/sync-placement-realm-admission.ts +16 -11
- package/src/memory/sync-placement-refusal.ts +7 -0
- package/src/memory/sync-placement-remote-admission.ts +31 -13
- package/src/memory/sync-placement-remote-refusal.ts +1 -1
- package/src/memory/sync-placement-remote-stage.ts +1 -1
- package/src/memory/sync-placement-transport.ts +28 -12
- package/src/memory/sync-placement-writer-listing.ts +38 -13
- package/src/memory/sync-placement-writer-renewal.ts +5 -7
- package/src/memory/topic.ts +14 -0
- package/src/setup-console.ts +49 -23
- package/src/setup-drift.ts +31 -1
- package/src/setup-writer-roots.ts +1 -1
- package/src/setup.ts +66 -10
- package/src/sync-placement-writer-context.ts +1 -1
|
@@ -16,7 +16,9 @@ import { resolvePlacementWindow } from "./sync-placement-checkpoint-storage.ts";
|
|
|
16
16
|
import { SyncPlacementJournalError } from "./sync-placement-journal-format.ts";
|
|
17
17
|
import { readEffectiveSyncPlacementWriters } from "./sync-placement-effective-writers.ts";
|
|
18
18
|
import { pendingRealmInventory } from "./sync-placement-realm-pending.ts";
|
|
19
|
-
import {
|
|
19
|
+
import { placementFenceDirectories } from "./sync-placement-writer-renewal.ts";
|
|
20
|
+
import { assertNoLiveReaders } from "./reader-lease.ts";
|
|
21
|
+
import { PlacementInventoryFenceError, withPlacementMutationFences } from "./sync-placement-activation-locks.ts";
|
|
20
22
|
import { assertPlacementActivationOwner } from "./sync-placement-activation-proof.ts";
|
|
21
23
|
import { previewOwnedSyncPlacementSources } from "./sync-placement-capture.ts";
|
|
22
24
|
import { activePlacementWriterContext } from "../sync-placement-writer-context.ts";
|
|
@@ -56,7 +58,13 @@ function assertCheckpointClear(home: string): void {
|
|
|
56
58
|
catch (error) { if (error instanceof SyncPlacementJournalError && error.code === "pending") throw new SyncPlacementJournalError("checkpoint-pending"); throw error; }
|
|
57
59
|
}
|
|
58
60
|
function dirs(home: string, project: string): string[] {
|
|
59
|
-
const
|
|
61
|
+
const markers = readPlacementRuntimeMarkers(home);
|
|
62
|
+
const binding = readActivePlacementBinding(home, markers.profile, markers.shards);
|
|
63
|
+
if (!binding) return unavailable("epoch");
|
|
64
|
+
const directories = placementFenceDirectories(home, binding);
|
|
65
|
+
const target = shardDir(home, project);
|
|
66
|
+
if (lstatSync(target, { throwIfNoEntry: false })) directories.push(target);
|
|
67
|
+
return directories;
|
|
60
68
|
}
|
|
61
69
|
const nextSync = "amem sync";
|
|
62
70
|
|
|
@@ -72,6 +80,13 @@ async function remoteRealmAdmissionInner(homeInput: string, project: string, opt
|
|
|
72
80
|
// A private stage without any companion cannot be attributed to this operation or silently abandoned.
|
|
73
81
|
if (!plan && !staged.length && pending.hashes.includes(realm)) return unavailable("staging");
|
|
74
82
|
const admitted = () => active(home, realm);
|
|
83
|
+
const assertTargetIdle = () => {
|
|
84
|
+
if (admitted()) return;
|
|
85
|
+
const target = shardDir(home, project);
|
|
86
|
+
if (!lstatSync(target, { throwIfNoEntry: false })) return;
|
|
87
|
+
try { assertNoLiveReaders(target, { includeShards: true }); }
|
|
88
|
+
catch { unavailable("lock"); }
|
|
89
|
+
};
|
|
75
90
|
if (options.mode === "dry-run") {
|
|
76
91
|
if (plan || staged.length) return { state: "retained", realm, staged: staged.length, nextStep: "resume or review abandon" };
|
|
77
92
|
if (admitted()) return { state: "already-admitted", realm, nextStep: nextSync };
|
|
@@ -81,19 +96,19 @@ async function remoteRealmAdmissionInner(homeInput: string, project: string, opt
|
|
|
81
96
|
}
|
|
82
97
|
if (options.mode === "abandon" && staged.length) {
|
|
83
98
|
if (!options.confirm) return { state: "retained", realm, staged: staged.length, nextStep: "confirm abandon" };
|
|
84
|
-
await
|
|
99
|
+
await withPlacementMutationFences(home, dirs(home, project), async (mutation, owner) => {
|
|
85
100
|
const proof = { mutation, assertCurrent: () => { assertPlacementActivationOwner(owner, home); assertMutationHandle(mutation, home); assertCheckpointClear(home); } };
|
|
86
101
|
clearRemoteAdoptionPending(home, realm, staged, proof);
|
|
87
|
-
});
|
|
102
|
+
}, { surface: "admit" });
|
|
88
103
|
return { state: "abandoned", realm, staged: staged.length, nextStep: plan ? "resume or review abandon" : "preview admission" };
|
|
89
104
|
}
|
|
90
105
|
if (options.mode === "abandon" && !plan) return { state: admitted() ? "already-admitted" : "abandoned", realm, nextStep: admitted() ? nextSync : "preview admission" };
|
|
91
106
|
if (options.mode === "abandon" && plan && !options.confirm) return { state: "retained", realm, nextStep: "confirm abandon" };
|
|
92
107
|
if (options.mode === "apply" && (plan || staged.length) && !admitted()) return unavailable("pending");
|
|
93
108
|
if (!plan && admitted()) {
|
|
94
|
-
if (staged.length) await
|
|
109
|
+
if (staged.length) await withPlacementMutationFences(home, dirs(home, project), async (mutation, owner) => {
|
|
95
110
|
clearRemoteAdoptionPending(home, realm, staged, { mutation, assertCurrent: () => { assertPlacementActivationOwner(owner, home); assertMutationHandle(mutation, home); assertCheckpointClear(home); } });
|
|
96
|
-
});
|
|
111
|
+
}, { surface: "admit" });
|
|
97
112
|
return { state: "already-admitted", realm, nextStep: nextSync };
|
|
98
113
|
}
|
|
99
114
|
if (options.mode === "resume" && !plan && !staged.length) return admitted() ? { state: "already-admitted", realm, nextStep: nextSync } : unavailable();
|
|
@@ -105,11 +120,11 @@ async function remoteRealmAdmissionInner(homeInput: string, project: string, opt
|
|
|
105
120
|
}
|
|
106
121
|
const frozen: RemoteAdoption = plan, files = packs!;
|
|
107
122
|
const clearOwn = async () => {
|
|
108
|
-
await
|
|
123
|
+
await withPlacementMutationFences(home, dirs(home, project), async (mutation, owner) => {
|
|
109
124
|
const current = readRemoteAdoption(home, realm); if (!current) return;
|
|
110
125
|
if (current.seal !== frozen.seal) return unavailable("staging");
|
|
111
126
|
clearRemoteAdoption(home, frozen, files, { mutation, assertCurrent: () => { assertPlacementActivationOwner(owner, home); assertMutationHandle(mutation, home); assertCheckpointClear(home); } });
|
|
112
|
-
});
|
|
127
|
+
}, { surface: "admit" });
|
|
113
128
|
};
|
|
114
129
|
if (options.mode === "abandon") {
|
|
115
130
|
const oldIntent = readRealmIntent(home, realm);
|
|
@@ -120,13 +135,15 @@ async function remoteRealmAdmissionInner(homeInput: string, project: string, opt
|
|
|
120
135
|
await applyRealmAdmission(home, project, { mode: "abandon", confirm: true });
|
|
121
136
|
}
|
|
122
137
|
}
|
|
123
|
-
await
|
|
138
|
+
await withPlacementMutationFences(home, dirs(home, project), async (mutation, owner) => {
|
|
124
139
|
const current = () => { assertPlacementActivationOwner(owner, home); assertMutationHandle(mutation, home); assertCheckpointClear(home); };
|
|
125
140
|
const proof = { mutation, assertCurrent: current };
|
|
126
|
-
if (!admitted() && remoteAdoptionLogMayBeInstalled(home, project, frozen))
|
|
141
|
+
if (!admitted() && remoteAdoptionLogMayBeInstalled(home, project, frozen)) {
|
|
142
|
+
assertTargetIdle();
|
|
127
143
|
discardRemoteInstalledLog(home, project, frozen, { mutation, assertCurrent: () => { current(); if (admitted()) unavailable(); } });
|
|
144
|
+
}
|
|
128
145
|
clearRemoteAdoption(home, frozen, files, proof);
|
|
129
|
-
});
|
|
146
|
+
}, { surface: "admit" });
|
|
130
147
|
return { state: admitted() ? "already-admitted" : "abandoned", realm, nextStep: admitted() ? nextSync : "preview admission" };
|
|
131
148
|
}
|
|
132
149
|
if (admitted()) {
|
|
@@ -134,8 +151,9 @@ async function remoteRealmAdmissionInner(homeInput: string, project: string, opt
|
|
|
134
151
|
await clearOwn();
|
|
135
152
|
return { state: "already-admitted", realm, nextStep: nextSync };
|
|
136
153
|
}
|
|
137
|
-
await
|
|
154
|
+
await withPlacementMutationFences(home, dirs(home, project), async (mutation, owner) => {
|
|
138
155
|
if (admitted()) return;
|
|
156
|
+
assertTargetIdle();
|
|
139
157
|
const remotePending = pendingRemoteAdoptions(home); if (remotePending.unknown) return unavailable("staging"); if (remotePending.hashes.some(hash => hash !== realm)) return unavailable("pending");
|
|
140
158
|
const pending = pendingRealmInventory(home); if (pending.unknown) return unavailable("staging"); if (pending.hashes.some(hash => hash !== realm)) return unavailable("pending");
|
|
141
159
|
const markers = readPlacementRuntimeMarkers(home), binding = readActivePlacementBinding(home, markers.profile, markers.shards);
|
|
@@ -162,7 +180,7 @@ async function remoteRealmAdmissionInner(homeInput: string, project: string, opt
|
|
|
162
180
|
const retained = readRealmIntent(home, realm);
|
|
163
181
|
const completeMetadata = source.base.realms.some(item => item.scope === "project" && item.keyHash === realm);
|
|
164
182
|
installRemoteAdoptionLog(home, project, frozen, proof, !!retained || completeMetadata); await options.checkpoint?.("after-install");
|
|
165
|
-
});
|
|
183
|
+
}, { surface: "admit" });
|
|
166
184
|
if (admitted()) {
|
|
167
185
|
await clearOwn();
|
|
168
186
|
return { state: "already-admitted", realm, nextStep: nextSync };
|
|
@@ -15,7 +15,7 @@ const messages: Record<RemoteRealmCause, string> = {
|
|
|
15
15
|
};
|
|
16
16
|
export class RemoteRealmRefusal extends Error {
|
|
17
17
|
constructor(readonly causeClass: RemoteRealmCause, subpath?: string) {
|
|
18
|
-
const safeName = subpath && subpath.length <= 128 && !/[\r\n]/.test(subpath) && /^(?:log|local|legacy|legacy-main|generation\.json|generation-seal\.json|migration-sources\.json|machine\.json|prune-translations\.jsonl|prune-plans|public-prune-objects|public-prune-inputs|public-prune-input-sets|index(?:-v[0-9]+(?:-i[0-9]+)?)?\.db(?:-wal|-shm|-journal)?|search
|
|
18
|
+
const safeName = subpath && subpath.length <= 128 && !/[\r\n]/.test(subpath) && /^(?:log|local|legacy|legacy-main|generation\.json|generation-seal\.json|migration-sources\.json|machine\.json|prune-translations\.jsonl|prune-plans|public-prune-objects|public-prune-inputs|public-prune-input-sets|index(?:-v[0-9]+(?:-i[0-9]+)?)?\.db(?:-wal|-shm|-journal)?|search(?:-s[0-9]+)?\.db(?:-wal|-shm|-journal)?)$/.test(subpath) ? subpath : undefined;
|
|
19
19
|
super(`Remote realm unavailable (${causeClass}): ${safeName ? `existing curated subpath: ${safeName}. ` : ""}${messages[causeClass]}`); this.name = "RemoteRealmRefusal";
|
|
20
20
|
}
|
|
21
21
|
}
|
|
@@ -30,7 +30,7 @@ function rejectExistingCurated(dir: string): void {
|
|
|
30
30
|
"prune-translations.jsonl", "prune-plans", "public-prune-objects", "public-prune-inputs", "public-prune-input-sets"]);
|
|
31
31
|
for (const name of readdirSync(dir)) {
|
|
32
32
|
if (fixed.has(name) || /^index(?:-v[0-9]+(?:-i[0-9]+)?)?\.db(?:-wal|-shm|-journal)?$/.test(name)
|
|
33
|
-
|| /^search
|
|
33
|
+
|| /^search(?:-s[0-9]+)?\.db(?:-wal|-shm|-journal)?$/.test(name))
|
|
34
34
|
throw new RemoteRealmRefusal("existing", name);
|
|
35
35
|
}
|
|
36
36
|
}
|
|
@@ -4,14 +4,14 @@ 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
|
+
import { placementAdvertisement, placementStorageCacheScope, placementVisibility } from "./sync-placement-advertisement.ts";
|
|
8
8
|
import { generationSyncGit, generationSyncGitBytes, remoteVisibility, type SyncFailureCause, type SyncOptions, type SyncResult } from "./sync.ts";
|
|
9
9
|
import { acquireMutation, assertMutationHandle, type MutationHandle } from "./mutation.ts";
|
|
10
10
|
import { isLocalKey, localKeyOptInMessage, PlacementRealmRefusal, resolveShardProfile } from "./shard.ts";
|
|
11
11
|
import { memoryPolicySnapshot } from "./policy.ts";
|
|
12
12
|
import { outboundPolicyEvaluator, rowScreenIdentity } from "./sync-screen.ts";
|
|
13
|
-
import { readActivePlacementBinding } from "./sync-placement-active.ts";
|
|
14
|
-
import { readPlacementRuntimeMarkers } from "./sync-placement-guard.ts";
|
|
13
|
+
import { readActivePlacementBinding, withPlacementFenceMemo } from "./sync-placement-active.ts";
|
|
14
|
+
import { readPlacementRuntimeMarkers, readPlacementRuntimeMarkerSnapshots } from "./sync-placement-guard.ts";
|
|
15
15
|
import { captureSyncPlacementContextAsync, placementCaptureContextHash, previewSyncPlacementSources, type PlacementCapture, type PlacementPendingSource } from "./sync-placement-capture.ts";
|
|
16
16
|
import { readEffectiveSyncPlacementWriters, type EffectiveSyncPlacementWriters } from "./sync-placement-effective-writers.ts";
|
|
17
17
|
import { SharedWriterRevisionError } from "./sync-placement-writer-revision-format.ts";
|
|
@@ -40,7 +40,7 @@ import { placementCacheConfigStamp, placementCacheRootStamp, placementCacheTreeP
|
|
|
40
40
|
import { PlacementSyncBoundError, placementSyncBoundDetail, placementSyncBoundMessage, placementSyncBoundReceipt, type PlacementSyncBound } from "./sync-placement-bound.ts";
|
|
41
41
|
import { PLACEMENT_CHECKPOINT_PENDING_MESSAGE, placementCheckpointPending } from "./sync-placement-checkpoint-storage.ts";
|
|
42
42
|
import type { SyncProgress, SyncProgressPhase } from "./sync-progress.ts";
|
|
43
|
-
import { PlacementSyncRefusal, placementRefusalCategoryOf, placementRefusalMessage, type PlacementRefusalCategory } from "./sync-placement-refusal.ts";
|
|
43
|
+
import { PlacementSyncRefusal, placementRefusalCategoryOf, placementRefusalMessage, placementStoppedMessage, PLACEMENT_RETAINED_STOP_MESSAGE, type PlacementRefusalCategory } from "./sync-placement-refusal.ts";
|
|
44
44
|
import { SyncPlacementJournalError } from "./sync-placement-journal-format.ts";
|
|
45
45
|
import { readEffectiveRealmInventory } from "./sync-placement-realm-effective.ts";
|
|
46
46
|
import { listRemotePlacementRealms, REMOTE_REALM_ADVERTISEMENT_BYTES, type RemoteOnlyRealm } from "./sync-placement-realm-discovery.ts";
|
|
@@ -265,14 +265,16 @@ class PlacementTransport {
|
|
|
265
265
|
}
|
|
266
266
|
if (this.homeMutation) assertMutationHandle(this.homeMutation, this.home);
|
|
267
267
|
for (const target of this.targets) if (target.mutation) assertMutationHandle(target.mutation, target.store.dir);
|
|
268
|
-
|
|
268
|
+
// #656: the reader's frozen snapshots, so the binding memo hits while the markers are unchanged; nothing here mutates them.
|
|
269
|
+
const markers = readPlacementRuntimeMarkerSnapshots(this.home), active = readActivePlacementBinding(this.home, markers.profile, markers.shards);
|
|
269
270
|
if (!active || active.profile.placementHead !== this.epochHash || active.epoch.homeHash !== this.journal.epoch.homeHash) refuse("epoch");
|
|
270
271
|
}
|
|
271
272
|
verify(fresh: boolean): void {
|
|
272
|
-
this.
|
|
273
|
+
const complete = fresh || this.provedAt === undefined || this.clock() - this.provedAt >= PLACEMENT_PROOF_REUSE_MS;
|
|
274
|
+
// #656: a reused-proof check may reuse the prune-advance answer while its files keep their stamps; a complete proof reads in full.
|
|
275
|
+
if (complete) this.metadata(); else withPlacementFenceMemo(() => this.metadata());
|
|
273
276
|
if (this.factual) { this.progress?.alive(); return; }
|
|
274
277
|
if (this.opts.signal?.aborted) refuse();
|
|
275
|
-
const complete = fresh || this.provedAt === undefined || this.clock() - this.provedAt >= PLACEMENT_PROOF_REUSE_MS;
|
|
276
278
|
if (complete) {
|
|
277
279
|
this.provedAt = undefined; this.attest(); this.capture?.assertUnchanged(); this.provedAt = this.clock();
|
|
278
280
|
if(this.capture){this.lastPolicyHash=this.capture.context.policyHash;this.lastPolicyCheckUnixMs=Date.now();this.policyCheckSource="live";}
|
|
@@ -281,7 +283,8 @@ class PlacementTransport {
|
|
|
281
283
|
if (!complete && this.capture && this.opts.policyVersion && this.opts.policyVersion() !== this.capturedPolicyVersion) refuse("policy");
|
|
282
284
|
this.progress?.proof(complete);
|
|
283
285
|
for (const target of this.targets) for (const check of target.selectorChecks ?? []) check();
|
|
284
|
-
|
|
286
|
+
// #656: a reused proof runs no file or host callout between the two reads, so the opening metadata() covers it.
|
|
287
|
+
if (complete) this.metadata();
|
|
285
288
|
}
|
|
286
289
|
/** Fence check inside a proof scope: reuses a complete proof no older than PLACEMENT_PROOF_REUSE_MS. */
|
|
287
290
|
check = (): void => this.verify(false);
|
|
@@ -358,7 +361,7 @@ class PlacementTransport {
|
|
|
358
361
|
if (!existing && !this.opts.remote) refuse("remote");
|
|
359
362
|
this.url = this.opts.remote ?? await this.required(["remote", "get-url", "origin"]);
|
|
360
363
|
if (!this.url || this.url.length > 4096 || this.url.startsWith("-") || /[\r\n\0]/.test(this.url)) refuse("remote");
|
|
361
|
-
if (await this.call(() => (this.opts.visibility ?? remoteVisibility)
|
|
364
|
+
if (await this.call(() => placementVisibility(this.opts, this.url, this.opts.visibility ?? remoteVisibility)) !== "private") refuse("remote");
|
|
362
365
|
await yieldTurn(); this.prove(); // a host callout ends any reusable proof
|
|
363
366
|
if (!existsSync(this.root)) mkdirSync(this.root, { mode: 0o700 });
|
|
364
367
|
const transport = acquireMutation(this.root); if (!transport) refuse("lock"); this.rootMutation=transport; this.releases.push(transport);
|
|
@@ -478,8 +481,16 @@ class PlacementTransport {
|
|
|
478
481
|
evaluate(value: unknown) {
|
|
479
482
|
// The configured policy is read once; complete proofs on both sides bind that read to the captured policy hash.
|
|
480
483
|
if (!this.evaluator) { this.prove(); this.evaluator = outboundPolicyEvaluator(this.home, this.opts.screen); this.prove(); }
|
|
481
|
-
|
|
484
|
+
const evaluate = this.evaluator;
|
|
485
|
+
// #656: no screen or a package-owned deterministic screen is pure and in memory, so the fence is checked once per 64-row
|
|
486
|
+
// slice; the closing prove() in materialize still binds every verdict before planning. A host callback keeps the per-row pair.
|
|
487
|
+
if (this.opts.screen === undefined || rowScreenIdentity(this.opts.screen) !== undefined) {
|
|
488
|
+
if (this.evaluated++ % 64 === 0) this.check();
|
|
489
|
+
return evaluate(structuredClone(value) as Record<string, unknown>);
|
|
490
|
+
}
|
|
491
|
+
this.check(); const verdict = evaluate(structuredClone(value) as Record<string, unknown>); this.check(); return verdict;
|
|
482
492
|
}
|
|
493
|
+
evaluated = 0;
|
|
483
494
|
nativeProofs(): Set<string> {
|
|
484
495
|
const verified=new Set<string>();
|
|
485
496
|
for(const target of this.targets){
|
|
@@ -734,7 +745,7 @@ class PlacementTransport {
|
|
|
734
745
|
}
|
|
735
746
|
async run():Promise<SyncResult>{
|
|
736
747
|
let result:SyncResult;
|
|
737
|
-
try{result=await this.execute();}finally{releasePlacementStorageCaches();} // #420 memos live for one sync only
|
|
748
|
+
try{result=await this.execute();}finally{if(!placementStorageCacheScope(this.opts))releasePlacementStorageCaches();} // #420 memos live for one sync only; #656: an inventory run releases them itself
|
|
738
749
|
// Success is reported only from the real receipt; a failed or stopped run can never leave a successful status.
|
|
739
750
|
if(result.ok)this.progress?.finish("succeeded");
|
|
740
751
|
else if(this.opts.signal?.aborted)this.progress?.finish("cancelled","cancelled");
|
|
@@ -847,7 +858,12 @@ class PlacementTransport {
|
|
|
847
858
|
// #288 step 1: the bound's own numbers-only clause is rebuilt from the receipt for the receipt's fields, so the
|
|
848
859
|
// thrown error's detail is carried over explicitly; the result's error is what the person reads.
|
|
849
860
|
if(bound){this.bound=bound;const detail=placementSyncBoundDetail(error);return this.result(false,"not-needed",placementSyncBoundMessage(bound)+(detail?` ${detail}`:""));}
|
|
850
|
-
if(this.attemptHash)return this.result(false,"unknown",
|
|
861
|
+
if(this.attemptHash)return this.result(false,"unknown",PLACEMENT_RETAINED_STOP_MESSAGE);
|
|
862
|
+
// #657: a stop before any attempt exists published nothing; it is reported as stopped in its phase, never as a refusal.
|
|
863
|
+
if(this.opts.signal?.aborted)return this.journal?.publicationReservation
|
|
864
|
+
// A reservation from an earlier run may have published even before this run read its attempt: keep it as unknown.
|
|
865
|
+
?this.result(false,"unknown",PLACEMENT_RETAINED_STOP_MESSAGE)
|
|
866
|
+
:this.result(false,"not-needed",placementStoppedMessage(this.phaseNow.replaceAll("-"," ")));
|
|
851
867
|
if (error && typeof error === "object" && !types.isProxy(error) && error instanceof PlacementRealmRefusal && error.origin === "remote") { this.failureCause = "remote"; return this.result(false, "not-needed", error.message); }
|
|
852
868
|
if (error instanceof LocalKeyOptInRefusal) { this.failureCause = "unavailable"; return this.result(false, "not-needed", error.message); }
|
|
853
869
|
// #426: name the failing check by a fixed category and the phase; never the error's own text, which may carry a path.
|
|
@@ -1,53 +1,75 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* #639: a read-only listing of the placement writer inventory and the install roots a renewal must declare. It writes
|
|
3
3
|
* nothing, takes no lock and never searches the filesystem for installs; it only reads the active inventory, the running
|
|
4
|
-
* install
|
|
4
|
+
* install, the setup receipts and (#660) library hosts found from the process table or as ahub/vmem on PATH, then suggests
|
|
5
|
+
* the present roots and the saving-preview command built from them.
|
|
5
6
|
*/
|
|
6
|
-
import { lstatSync } from "node:fs";
|
|
7
7
|
import { realPath } from "./platform.ts";
|
|
8
|
-
import {
|
|
8
|
+
import { join } from "node:path";
|
|
9
|
+
import { embeddedAmemRoot, installAbsent, installVersion, runningAmemRoots } from "./formats-raise.ts";
|
|
9
10
|
import { readEffectiveSyncPlacementWriters } from "./sync-placement-effective-writers.ts";
|
|
10
11
|
import { readSetupWriterLaunchers, type SetupTarget } from "../setup-writer-roots.ts";
|
|
11
12
|
|
|
12
13
|
export const PLACEMENT_WRITERS_LISTING = "amem migrate --sync-placement --writers";
|
|
13
14
|
export const PLACEMENT_WRITERS_SCHEMA = "amem.placement-writers/v1";
|
|
14
|
-
export const PLACEMENT_WRITERS_NOTE = "Installs bundled inside other tools (agent-hub, vault-mem) appear here
|
|
15
|
+
export const PLACEMENT_WRITERS_NOTE = "Installs bundled inside other tools (agent-hub, vault-mem) appear here when they are in the inventory or a setup receipt, run in a live process, or sit behind ahub or vmem on PATH; add any other host bundle with another --writer-root.";
|
|
15
16
|
|
|
16
17
|
export interface PlacementWriterListing {
|
|
17
18
|
schema: typeof PLACEMENT_WRITERS_SCHEMA;
|
|
18
19
|
inventory: { root: string; version: string | null; state: "present" | "missing" }[];
|
|
19
20
|
running: { root: string; version: string | null; inInventory: boolean };
|
|
20
21
|
receipts: { target: SetupTarget; root: string; state: "present" | "missing" }[];
|
|
22
|
+
/** #660, additive: amem roots loaded by a live process (`pid`) or behind ahub/vmem on PATH (`host` is the entry script). */
|
|
23
|
+
runningHosts?: { pid?: number; root: string; version: string | null; host?: string }[];
|
|
21
24
|
suggestedRoots: string[];
|
|
22
25
|
command: string;
|
|
23
26
|
note: string;
|
|
24
27
|
}
|
|
25
28
|
|
|
26
|
-
// ponytail: the same ENOENT/ENOTDIR test as the checkpoint's installAbsent (#634); one shared helper once #448 settles that file.
|
|
27
|
-
function absent(root: string): boolean {
|
|
28
|
-
try { lstatSync(root); return false; } catch (error) { const code = (error as NodeJS.ErrnoException).code; return code === "ENOENT" || code === "ENOTDIR"; }
|
|
29
|
-
}
|
|
30
29
|
/** POSIX single-quote shell quoting: the printed command is pasted into a shell as is. */
|
|
31
30
|
export function shellQuote(value: string): string {
|
|
32
31
|
return `'${value.replaceAll("'", `'\\''`)}'`;
|
|
33
32
|
}
|
|
34
33
|
export function placementWriterCommand(roots: readonly string[]): string {
|
|
35
34
|
const flags = roots.map(root => `--writer-root ${shellQuote(root)}`).join(" ");
|
|
36
|
-
return `
|
|
35
|
+
return `amem migrate --sync-placement --checkpoint ${flags} --out checkpoint-plan.json, then amem migrate --sync-placement --checkpoint --confirm --plan checkpoint-plan.json`;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** #660 discovery seams: the `pid args` process table, the embedded-package probe and the PATH to resolve ahub/vmem on. */
|
|
39
|
+
export interface PlacementWriterDiscovery { table?: () => string; embedded?: (dir: string) => boolean; path?: string }
|
|
40
|
+
function discoverHosts(own: string, discovery: PlacementWriterDiscovery): NonNullable<PlacementWriterListing["runningHosts"]> {
|
|
41
|
+
const out: NonNullable<PlacementWriterListing["runningHosts"]> = [], seen = new Set<string>();
|
|
42
|
+
const add = (root: string, extra: { pid?: number; host?: string }) => {
|
|
43
|
+
let canonical: string; try { canonical = realPath(root); } catch { return; }
|
|
44
|
+
if (canonical === own || seen.has(`${canonical}\0${extra.pid ?? ""}`)) return; seen.add(`${canonical}\0${extra.pid ?? ""}`);
|
|
45
|
+
out.push({ ...(extra.pid !== undefined ? { pid: extra.pid } : {}), root: canonical, version: installVersion(canonical), ...(extra.host ? { host: extra.host } : {}) });
|
|
46
|
+
};
|
|
47
|
+
// ponytail: a failed process listing finds no live hosts, and runningAmemRoots splits `ps` args on whitespace, so a script path
|
|
48
|
+
// with a space is missed; the PATH check and an explicit --writer-root still cover them. Upgrade: read argv per pid.
|
|
49
|
+
if (discovery.table) try { for (const row of runningAmemRoots(discovery.table, discovery.embedded)) add(row.root, { pid: row.pid, ...(row.host ? { host: row.host } : {}) }); } catch { /* no live hosts */ }
|
|
50
|
+
for (const dir of (discovery.path ?? "").split(":")) {
|
|
51
|
+
if (!dir.startsWith("/")) continue;
|
|
52
|
+
for (const name of ["ahub", "vmem"]) {
|
|
53
|
+
let script: string; try { script = realPath(join(dir, name)); } catch { continue; }
|
|
54
|
+
const root = embeddedAmemRoot(script, discovery.embedded); if (root) add(root, { host: script });
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
return out;
|
|
37
58
|
}
|
|
38
59
|
|
|
39
|
-
export function listPlacementWriters(home: string, ownRoot: string): PlacementWriterListing {
|
|
60
|
+
export function listPlacementWriters(home: string, ownRoot: string, discovery: PlacementWriterDiscovery = {}): PlacementWriterListing {
|
|
40
61
|
const inventory = (readEffectiveSyncPlacementWriters(home).roots ?? []).map(root => {
|
|
41
|
-
const state =
|
|
62
|
+
const state = installAbsent(root) ? "missing" as const : "present" as const;
|
|
42
63
|
return { root, version: state === "present" ? installVersion(root) : null, state };
|
|
43
64
|
});
|
|
44
65
|
const own = realPath(ownRoot);
|
|
45
66
|
const running = { root: own, version: installVersion(own), inInventory: inventory.some(row => row.root === own) };
|
|
46
|
-
const receipts = readSetupWriterLaunchers(home);
|
|
67
|
+
const receipts = readSetupWriterLaunchers(home), runningHosts = discoverHosts(own, discovery);
|
|
47
68
|
const present = new Set<string>([own]);
|
|
48
69
|
for (const row of [...inventory, ...receipts]) if (row.state === "present") present.add(realPath(row.root));
|
|
70
|
+
for (const row of runningHosts) if (row.version !== null && !installAbsent(row.root)) present.add(row.root);
|
|
49
71
|
const suggestedRoots = [...present].sort();
|
|
50
|
-
return { schema: PLACEMENT_WRITERS_SCHEMA, inventory, running, receipts, suggestedRoots, command: placementWriterCommand(suggestedRoots), note: PLACEMENT_WRITERS_NOTE };
|
|
72
|
+
return { schema: PLACEMENT_WRITERS_SCHEMA, inventory, running, receipts, runningHosts, suggestedRoots, command: placementWriterCommand(suggestedRoots), note: PLACEMENT_WRITERS_NOTE };
|
|
51
73
|
}
|
|
52
74
|
|
|
53
75
|
export function placementWritersText(listing: PlacementWriterListing): string {
|
|
@@ -58,6 +80,9 @@ export function placementWritersText(listing: PlacementWriterListing): string {
|
|
|
58
80
|
lines.push("setup receipts:");
|
|
59
81
|
for (const row of listing.receipts) lines.push(` ${row.target} ${row.state} ${row.root}`);
|
|
60
82
|
if (!listing.receipts.length) lines.push(" (none)");
|
|
83
|
+
lines.push("library hosts:");
|
|
84
|
+
for (const row of listing.runningHosts ?? []) lines.push(` ${row.version ?? "unknown"} ${row.root}${row.pid !== undefined ? ` (pid ${row.pid})` : " (on PATH)"}`);
|
|
85
|
+
if (!listing.runningHosts?.length) lines.push(" (none found)");
|
|
61
86
|
lines.push("roots to declare:");
|
|
62
87
|
for (const root of listing.suggestedRoots) lines.push(` ${root}`);
|
|
63
88
|
lines.push(`next: ${listing.command}`, `note: ${listing.note}`);
|
|
@@ -15,9 +15,7 @@ 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 {
|
|
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 });
|
|
18
|
+
import { withPlacementMutationFences } from "./sync-placement-activation-locks.ts";
|
|
21
19
|
import { assertPlacementActivationOwner, type PlacementActivationOwner } from "./sync-placement-activation-proof.ts";
|
|
22
20
|
import { previewSyncPlacementSources, previewOwnedSyncPlacementSources } from "./sync-placement-capture.ts";
|
|
23
21
|
import { captureInspectionPendingPrunes } from "./sync-placement-inspection-pending.ts";
|
|
@@ -95,7 +93,7 @@ export async function renewSyncPlacementWriters(options:PlacementActivationOptio
|
|
|
95
93
|
try{history=readWriterHistory(home,b,{allowPending:true});}catch(error){
|
|
96
94
|
if(options.mode!=="abandon"||!error||typeof error!=="object"||types.isProxy(error)||!(error instanceof SharedWriterRevisionError)||Object.getOwnPropertyDescriptor(error,"code")?.value!=="staging")throw error;
|
|
97
95
|
requireWriterRenewalHomeFloor(home);
|
|
98
|
-
return
|
|
96
|
+
return withPlacementMutationFences(home,directories(home,initial),async(mutation,owner)=>{
|
|
99
97
|
const locator=readInitialSyncPlacementWriterLocator(home),seal=hashJSON({action:"abandon-unpublished-writer-staging",...b,initialLocatorHash:locator.seal});
|
|
100
98
|
let authorized=false;try{authorized=options.authorize(Object.freeze({seal,generation:b.generation,homeHash:b.homeHash}))===true;}catch{}
|
|
101
99
|
if(!authorized)throw new WriterRenewalError("authorization");
|
|
@@ -106,7 +104,7 @@ export async function renewSyncPlacementWriters(options:PlacementActivationOptio
|
|
|
106
104
|
};
|
|
107
105
|
const cleared=abandonUnpublishedWriterStaging(home,{...b,initialLocatorHash:locator.seal},{mutation,assertCurrent,assertCommittedHistory});
|
|
108
106
|
return{mode:options.mode,active:true,abandoned:true,unpublishedStagingRemoved:cleared.removed,nextStep:"amem migrate --sync-placement --dry-run"};
|
|
109
|
-
});
|
|
107
|
+
}, { surface: "renewal" });
|
|
110
108
|
}
|
|
111
109
|
if(!history.pending&&(options.mode==="resume"||options.mode==="abandon")&&history.sequence===0)return undefined;
|
|
112
110
|
if(options.mode==="dry-run"){
|
|
@@ -132,7 +130,7 @@ export async function renewSyncPlacementWriters(options:PlacementActivationOptio
|
|
|
132
130
|
// An unlocked refusal stays entirely passive; crashed owners must first be reclaimed by the real fences below.
|
|
133
131
|
const passivePreflight=options.mode==="apply"||options.mode==="resume"&&history.pending&&!history.appendStarted&&!lstatSync(join(home,"profile.lock"),{throwIfNoEntry:false});
|
|
134
132
|
let sourceCheck=passivePreflight?(journalClear(home,b.epochHash),pendingSources(home)):undefined;
|
|
135
|
-
return
|
|
133
|
+
return withPlacementMutationFences(home,directories(home,initial),async(mutation,owner)=>{
|
|
136
134
|
if(options.mode==="resume"&&history.pending&&!history.appendStarted){journalClear(home,b.epochHash);sourceCheck=pendingSources(home,owner);}
|
|
137
135
|
let intent=history.pending;
|
|
138
136
|
const cleanupOnly=!intent&&options.mode==="resume"&&!!history.current;
|
|
@@ -185,5 +183,5 @@ export async function renewSyncPlacementWriters(options:PlacementActivationOptio
|
|
|
185
183
|
check();writeWriterRenewalIntent(home,fixed,storage);writeWriterRevision(home,fixed,storage);appendWriterCommit(home,fixed,storage);
|
|
186
184
|
clearWriterRenewalIntent(home,fixed,{...storage,assertCurrent:metadata});
|
|
187
185
|
return{mode:options.mode,active:true,renewed:true,epochHash:b.epochHash,sequence:fixed.revision.sequence,revisionHash:fixed.commit.seal,remainingRevisions:WRITER_REVISION_LIMIT-fixed.revision.sequence};
|
|
188
|
-
});
|
|
186
|
+
}, { surface: "renewal" });
|
|
189
187
|
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* #580: a caller-chosen key naming the subject a note states, carried as the `about` node `topic:<key>` (owner ruling
|
|
3
|
+
* 2026-11-28: no NoteEntry field and no format floor, since every reader already keeps and indexes `about` nodes).
|
|
4
|
+
*/
|
|
5
|
+
export const TOPIC_FORM = "[a-z0-9][a-z0-9/-]{0,63}";
|
|
6
|
+
const TOPIC = new RegExp(`^${TOPIC_FORM}$`);
|
|
7
|
+
export const TOPIC_PREFIX = "topic:";
|
|
8
|
+
export const validTopic = (value: unknown): value is string => typeof value === "string" && TOPIC.test(value);
|
|
9
|
+
export const topicNode = (topic: string): string => `${TOPIC_PREFIX}${topic}`;
|
|
10
|
+
/** The note's topic, or null. A note carries at most one when written through amem; the first valid one wins otherwise. */
|
|
11
|
+
export function topicOf(view: { about: readonly string[] }): string | null {
|
|
12
|
+
for (const node of view.about) if (node.startsWith(TOPIC_PREFIX) && validTopic(node.slice(TOPIC_PREFIX.length))) return node.slice(TOPIC_PREFIX.length);
|
|
13
|
+
return null;
|
|
14
|
+
}
|
package/src/setup-console.ts
CHANGED
|
@@ -1,20 +1,29 @@
|
|
|
1
1
|
import { createHash } from "node:crypto";
|
|
2
2
|
import { chmodSync, lstatSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
|
|
3
3
|
import { homedir } from "node:os";
|
|
4
|
-
import { join, resolve } from "node:path";
|
|
4
|
+
import { dirname, join, resolve } from "node:path";
|
|
5
5
|
import { fileURLToPath } from "node:url";
|
|
6
6
|
import { isDeepStrictEqual } from "node:util";
|
|
7
|
+
import { acquireMutation } from "./memory/mutation.ts";
|
|
7
8
|
|
|
8
9
|
export interface ConsoleSetup { file: string; module: string; change: "add" | "replace" | "unchanged" | "remove" | "none"; reason?: string }
|
|
9
10
|
|
|
11
|
+
/** `$AGENTHUB_HOME/console/plugins/amem.json`, the acon plugin manifest; doctor and `setup all` read the same path. */
|
|
12
|
+
export function consoleManifestFile(env: Readonly<Record<string, string | undefined>> = process.env): string {
|
|
13
|
+
const configured = env.AGENTHUB_HOME;
|
|
14
|
+
const family = configured?.trim() ? resolve(configured) : join(env.HOME?.trim() || homedir(), ".agenthub");
|
|
15
|
+
return join(family, "console", "plugins", "amem.json");
|
|
16
|
+
}
|
|
17
|
+
|
|
10
18
|
/**
|
|
11
19
|
* `amem setup console`: the acon plugin manifest `{api, tool, module, sha256}` at `$AGENTHUB_HOME/console/plugins/amem.json`, in a 0700 directory
|
|
12
20
|
* and a 0600 file, which is what agent-console's scanPlugins accepts. Preview writes nothing; undo removes only a manifest that points at this install.
|
|
13
21
|
*/
|
|
14
22
|
export function consoleSetup(mode: "preview" | "apply" | "undo", env: Readonly<Record<string, string | undefined>> = process.env,
|
|
15
|
-
module = fileURLToPath(new URL("./ui/plugin.ts", import.meta.url))): ConsoleSetup {
|
|
16
|
-
const
|
|
17
|
-
|
|
23
|
+
module = fileURLToPath(new URL("./ui/plugin.ts", import.meta.url)), opts: { existingOnly?: boolean } = {}): ConsoleSetup {
|
|
24
|
+
const file = consoleManifestFile(env), dir = dirname(file);
|
|
25
|
+
// #659: `setup all` only refreshes a manifest the person installed; an absent one (also one removed since the caller looked) is never created.
|
|
26
|
+
if ((opts.existingOnly || mode === "undo") && !lstatSync(file, { throwIfNoEntry: false })) return { file, module, change: "none", reason: "no console manifest" };
|
|
18
27
|
// acon refuses a manifest directory or file that is a link, another kind of entry or another user's; so does setup, before writing anything.
|
|
19
28
|
for (const [path, kind] of [[dir, "directory"], [file, "file"]] as const) {
|
|
20
29
|
const info = lstatSync(path, { throwIfNoEntry: false });
|
|
@@ -22,27 +31,44 @@ export function consoleSetup(mode: "preview" | "apply" | "undo", env: Readonly<R
|
|
|
22
31
|
if (kind === "directory" ? !info.isDirectory() : !info.isFile()) throw Error(`${path}: acon needs a real ${kind}, not a link or another entry`);
|
|
23
32
|
if (typeof process.getuid === "function" && info.uid !== process.getuid()) throw Error(`${path} is owned by another user; acon would refuse it`);
|
|
24
33
|
}
|
|
25
|
-
const
|
|
26
|
-
if (mode === "
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
34
|
+
const next = mode === "undo" ? undefined : { api: 1, tool: "amem", module, sha256: createHash("sha256").update(readFileSync(module)).digest("hex") };
|
|
35
|
+
if (mode === "preview") return inspectAndUpdate();
|
|
36
|
+
if (mode === "apply" && !opts.existingOnly) mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
37
|
+
const directory = lstatSync(dir, { throwIfNoEntry: false });
|
|
38
|
+
if (!directory) return { file, module, change: "none", reason: "no console manifest" };
|
|
39
|
+
for (const suffix of ["", "-journal", "-wal", "-shm"]) {
|
|
40
|
+
const lock = lstatSync(join(dir, `mutation-lock.db${suffix}`), { throwIfNoEntry: false });
|
|
41
|
+
if (lock && (!lock.isFile() || lock.nlink !== 1 || lock.uid !== directory.uid || (lock.mode & 0o022) !== 0))
|
|
42
|
+
throw Error("console setup lock is unsafe; inspect the plugin directory before retrying");
|
|
31
43
|
}
|
|
32
|
-
const
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
+
const release = acquireMutation(dir);
|
|
45
|
+
if (!release) throw Error("console setup is busy; retry after the active console setup exits");
|
|
46
|
+
try { return inspectAndUpdate(); }
|
|
47
|
+
finally { release(); }
|
|
48
|
+
|
|
49
|
+
function inspectAndUpdate(): ConsoleSetup {
|
|
50
|
+
const before = lstatSync(file, { throwIfNoEntry: false }) ? JSON.parse(readFileSync(file, "utf8")) as Record<string, unknown> : undefined;
|
|
51
|
+
// ponytail: external or older writers bypass the console lock. A replace-only filesystem primitive would also exclude their unlink race.
|
|
52
|
+
if (opts.existingOnly && !before) return { file, module, change: "none", reason: "no console manifest" };
|
|
53
|
+
if (mode === "undo") {
|
|
54
|
+
if (!before) return { file, module, change: "none", reason: "no console manifest" };
|
|
55
|
+
if (before.module !== module) throw Error(`${file} points at another amem install (${String(before.module)}); left as is`);
|
|
56
|
+
unlinkSync(file);
|
|
57
|
+
return { file, module, change: "remove" };
|
|
58
|
+
}
|
|
59
|
+
const mode7 = (path: string, want: number) => (lstatSync(path, { throwIfNoEntry: false })?.mode ?? want) & 0o777;
|
|
60
|
+
const modesOk = mode7(dir, 0o700) === 0o700 && mode7(file, 0o600) === 0o600;
|
|
61
|
+
if (isDeepStrictEqual(before, next) && modesOk) return { file, module, change: "unchanged" };
|
|
62
|
+
const change = before ? "replace" : "add";
|
|
63
|
+
if (mode === "apply") {
|
|
64
|
+
chmodSync(dir, 0o700);
|
|
65
|
+
const temp = `${file}.${process.pid}.tmp`;
|
|
66
|
+
writeFileSync(temp, `${JSON.stringify(next, null, 2)}\n`, { mode: 0o600 });
|
|
67
|
+
renameSync(temp, file);
|
|
68
|
+
chmodSync(file, 0o600);
|
|
69
|
+
}
|
|
70
|
+
return { file, module, change, ...(modesOk ? {} : { reason: "permissions: plugin directory 0700, manifest 0600" }) };
|
|
44
71
|
}
|
|
45
|
-
return { file, module, change, ...(modesOk ? {} : { reason: "permissions: plugin directory 0700, manifest 0600" }) };
|
|
46
72
|
}
|
|
47
73
|
|
|
48
74
|
export const consoleSetupText = (result: ConsoleSetup, mode: "preview" | "apply" | "undo"): string =>
|
package/src/setup-drift.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { closeSync, constants, type Dir, existsSync, fstatSync, lstatSync, opendirSync, openSync, readSync } from "node:fs";
|
|
2
2
|
import { dirname, isAbsolute, join, resolve } from "node:path";
|
|
3
|
+
import { fileURLToPath } from "node:url";
|
|
3
4
|
import { createHash } from "node:crypto";
|
|
4
5
|
import { isDeepStrictEqual } from "node:util";
|
|
5
6
|
import { decodeReceipt, setupReceiptRemedy, type SetupTarget } from "./setup-writer-roots.ts";
|
|
@@ -8,10 +9,13 @@ import { amemCaptureCommand, amemCaptureHooks, managedAfter, managedHookEntries,
|
|
|
8
9
|
import { resolveSetupPaths, type SetupEnvironment } from "./setup-paths.ts";
|
|
9
10
|
import { HOOK_EVENTS } from "./hook-contract.ts";
|
|
10
11
|
import { realPath } from "./memory/platform.ts";
|
|
12
|
+
import { consoleManifestFile } from "./setup-console.ts";
|
|
13
|
+
import { installVersion, versionBelow } from "./memory/formats-raise.ts";
|
|
11
14
|
|
|
12
15
|
export type SetupDriftStatus = "ok" | "attention" | "skipped" | "unavailable";
|
|
13
16
|
export interface SetupDriftEntry {
|
|
14
|
-
|
|
17
|
+
/** `console` is the acon plugin manifest (#659), which has no setup receipt. */
|
|
18
|
+
target: SetupTarget | "console";
|
|
15
19
|
file: string;
|
|
16
20
|
entry: string;
|
|
17
21
|
reason: string;
|
|
@@ -204,6 +208,28 @@ export function listAgyReceiptLocations(home: string): { receipts: AgyReceiptLoc
|
|
|
204
208
|
return { receipts, incomplete };
|
|
205
209
|
}
|
|
206
210
|
|
|
211
|
+
export const CONSOLE_DRIFT_REASON = "the acon console plugin manifest names a missing module or one whose hash changed; run amem setup console --apply to refresh it or amem setup console --undo to remove it";
|
|
212
|
+
/** The manifest and its module, read without following links and bounded. */
|
|
213
|
+
function consoleDrift(env: SetupEnvironment, budget: { remaining: number }): SetupDriftEntry | "absent" | "current" {
|
|
214
|
+
const file = consoleManifestFile(env), finding = (kind: SetupDriftEntry["kind"], reason: string): SetupDriftEntry => ({ target: "console", file, entry: "plugin manifest", reason, kind });
|
|
215
|
+
let manifest: Record<string, unknown>;
|
|
216
|
+
try {
|
|
217
|
+
const raw = safeImage(file, 64 * 1024, budget);
|
|
218
|
+
if (raw.bytes === null) return "absent";
|
|
219
|
+
const value: unknown = JSON.parse(Buffer.from(raw.bytes, "base64").toString("utf8"));
|
|
220
|
+
if (!plain(value) || typeof value.module !== "string" || !isAbsolute(value.module) || typeof value.sha256 !== "string") return finding("drift", CONSOLE_DRIFT_REASON);
|
|
221
|
+
manifest = value;
|
|
222
|
+
} catch { return finding("unavailable", "the acon console plugin manifest cannot be read safely; inspect it or run amem setup console --apply"); }
|
|
223
|
+
try {
|
|
224
|
+
const module = safeImage(String(manifest.module), SETUP_CONFIG_BYTES, budget);
|
|
225
|
+
if (module.bytes === null || createHash("sha256").update(Buffer.from(module.bytes, "base64")).digest("hex") !== manifest.sha256) return finding("drift", CONSOLE_DRIFT_REASON);
|
|
226
|
+
} catch { return finding("unavailable", "the acon console plugin module cannot be read safely; run amem setup console --apply"); }
|
|
227
|
+
// An intact module from an older install still loads, but it serves that release's panels: refresh it to this one.
|
|
228
|
+
const theirs = installVersion(dirname(dirname(dirname(String(manifest.module))))), ours = installVersion(fileURLToPath(new URL("..", import.meta.url)));
|
|
229
|
+
if (theirs !== null && ours !== null && versionBelow(theirs, ours)) return finding("drift", `the acon console plugin manifest names amem ${theirs}, older than this amem ${ours}; run amem setup console --apply to refresh it`);
|
|
230
|
+
return "current";
|
|
231
|
+
}
|
|
232
|
+
|
|
207
233
|
/** Read setup receipts and only the resolver-selected native config files. This function never writes. */
|
|
208
234
|
export function readSetupDrift(options: { home: string; env?: SetupEnvironment; cwd?: string }): SetupDriftReport {
|
|
209
235
|
const env = options.env ?? process.env;
|
|
@@ -327,6 +353,10 @@ export function readSetupDrift(options: { home: string; env?: SetupEnvironment;
|
|
|
327
353
|
const install = installMissing("agy", receipt.changes[0]!.after);
|
|
328
354
|
if (install) { entries.push(installEntry("agy", "setup receipt of another workspace", install)); if (install === "unavailable") unavailable = true; }
|
|
329
355
|
}
|
|
356
|
+
// #659: an acon plugin manifest goes stale when amem moves or its UI module changes; only an existing manifest is checked.
|
|
357
|
+
const plugin = consoleDrift(env, budget);
|
|
358
|
+
if (plugin !== "absent") { anyReceipt = true; checked++; }
|
|
359
|
+
if (typeof plugin === "object") { if (plugin.kind === "unavailable") unavailable = true; entries.push(plugin); }
|
|
330
360
|
const status: SetupDriftStatus = entries.some(value => value.kind === "drift" || value.kind === "review-needed") ? "attention"
|
|
331
361
|
: unavailable ? "unavailable" : anyReceipt ? "ok" : "skipped";
|
|
332
362
|
return { status, checked, entries, ...(!anyReceipt && !entries.length ? { reason: "no applied setup receipts found" } : {}) };
|
|
@@ -45,7 +45,7 @@ export function decodeReceipt(value: Record<string, unknown>, target: SetupTarge
|
|
|
45
45
|
* sync refusal, doctor and the marked diagnostic. It names the target and both commands, never the recorded path.
|
|
46
46
|
*/
|
|
47
47
|
export function setupReceiptRemedy(target: SetupTarget, applied = false): string {
|
|
48
|
-
if (target === "agy") return `the ${applied ? "applied " : ""}agy setup receipt names an amem install that no longer exists; run amem setup agy --list, then from each listed stale repository run amem setup agy --apply to refresh its receipt or amem setup agy --undo to remove it`;
|
|
48
|
+
if (target === "agy") return `the ${applied ? "applied " : ""}agy setup receipt names an amem install that no longer exists; run amem setup agy --refresh --apply to refresh every receipted repository, or amem setup agy --list, then from each listed stale repository run amem setup agy --apply to refresh its receipt or amem setup agy --undo to remove it`;
|
|
49
49
|
return `the ${applied ? "applied " : ""}${target} setup receipt names an amem install that no longer exists; run amem setup ${target} --apply to refresh the receipt or amem setup ${target} --undo to remove it`;
|
|
50
50
|
}
|
|
51
51
|
/**
|