@staix/agent-mem 0.40.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 +172 -30
- package/src/commands-table.ts +16 -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 +7 -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/reader-lease.ts +37 -1
- 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 +35 -13
- 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 +90 -0
- 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 +92 -21
- package/src/setup-writer-roots.ts +17 -3
- package/src/setup.ts +71 -11
- package/src/sync-placement-writer-context.ts +1 -1
|
@@ -20,7 +20,8 @@ import { assertMutationHandle, type MutationHandle } from "./mutation.ts";
|
|
|
20
20
|
import { realPath } from "./platform.ts";
|
|
21
21
|
import { readShardDescriptor, assertCuratedShardLayout, shardDir } from "./shard.ts";
|
|
22
22
|
import { assertPlacementActivationOwner, type PlacementActivationOwner } from "./sync-placement-activation-proof.ts";
|
|
23
|
-
import {
|
|
23
|
+
import { placementFenceDirectories } from "./sync-placement-writer-renewal.ts";
|
|
24
|
+
import { withPlacementMutationFences, PlacementInventoryFenceError } from "./sync-placement-activation-locks.ts";
|
|
24
25
|
import { readActivePlacementBinding, type ActivePlacementBinding } from "./sync-placement-active.ts";
|
|
25
26
|
import { previewOwnedSyncPlacementSources, previewSyncPlacementSources } from "./sync-placement-capture.ts";
|
|
26
27
|
import { readPlacementRuntimeMarkers } from "./sync-placement-guard.ts";
|
|
@@ -74,7 +75,7 @@ export interface RealmAdmissionResult {
|
|
|
74
75
|
}
|
|
75
76
|
export class RealmAdmissionError extends Error {
|
|
76
77
|
constructor(readonly causeClass: "readers" | "busy" | "changed" | "pending" | "committed" | "metadata", readonly retainedRealm?: string) {
|
|
77
|
-
super(`Sync placement realm admission is ${causeClass}${retainedRealm ? `; retained realm keyHash=${retainedRealm}` : ""}; the existing activated realms keep syncing. ${action(causeClass)}`);
|
|
78
|
+
super(`Sync placement realm admission is ${causeClass === "readers" ? "blocked by live readers" : causeClass}${retainedRealm ? `; retained realm keyHash=${retainedRealm}` : ""}; the existing activated realms keep syncing. ${action(causeClass)}`);
|
|
78
79
|
this.name = "RealmAdmissionError";
|
|
79
80
|
}
|
|
80
81
|
}
|
|
@@ -83,6 +84,7 @@ function action(causeClass: RealmAdmissionError["causeClass"]): string {
|
|
|
83
84
|
if (causeClass === "committed") return "The extension chain no longer matches the frozen intent: run amem migrate --sync-placement --admit <project> --resume to complete or clean up the retained attempt, and keep --abandon --confirm for an append that never committed.";
|
|
84
85
|
if (causeClass === "changed") return "Re-read the home with amem migrate --sync-placement --admit <project> --dry-run and apply the reviewed append.";
|
|
85
86
|
if (causeClass === "metadata") return "Inspect the local placement and curated metadata it names, then run amem migrate --sync-placement --admit <project> --dry-run.";
|
|
87
|
+
if (causeClass === "busy") return "Wait for the operation holding the lock (amem sync --status), then run amem migrate --sync-placement --admit <project> --dry-run.";
|
|
86
88
|
return "Close cooperating readers and writers, then run amem migrate --sync-placement --admit <project> --dry-run.";
|
|
87
89
|
}
|
|
88
90
|
function fail(causeClass: RealmAdmissionError["causeClass"]): never { throw new RealmAdmissionError(causeClass); }
|
|
@@ -95,6 +97,7 @@ function assertNoPendingAdmission(home: string, ownRealm?: string): void {
|
|
|
95
97
|
function rethrow(error: unknown): never {
|
|
96
98
|
if (error instanceof RealmAdmissionError || error instanceof RealmExtensionFormatError || error instanceof SyncPlacementJournalError && error.code === "checkpoint-pending") throw error;
|
|
97
99
|
if (error instanceof PlacementInventoryFenceError) fail(error.causeClass);
|
|
100
|
+
if (error instanceof Error && error.message === "profile lock held by a live or unknown owner") fail("busy");
|
|
98
101
|
return fail("metadata");
|
|
99
102
|
}
|
|
100
103
|
|
|
@@ -246,8 +249,8 @@ export async function applyRealmAdmission(homeInput: string, project: string, op
|
|
|
246
249
|
...(plan.staged ? { staged: plan.staged } : {}), nextStep: "confirm amem migrate --sync-placement --admit <project> --abandon --confirm" };
|
|
247
250
|
const stages = plan.staged ? inspectRealmIntentStages(home, realm) : undefined;
|
|
248
251
|
if (plan.staged && stages?.length !== plan.staged) fail("changed");
|
|
249
|
-
|
|
250
|
-
|
|
252
|
+
try {
|
|
253
|
+
return await withPlacementMutationFences(home, directories(home, projectPrefix), async (mutation, owner) => {
|
|
251
254
|
assertCheckpointClear(home);
|
|
252
255
|
const binding = realmBinding(activeBinding(home)), intent = readRealmIntent(home, realm);
|
|
253
256
|
const check = () => { assertPlacementActivationOwner(owner, home); assertMutationHandle(mutation, home); assertCheckpointClear(home); }, proof = { mutation, assertCurrent: check };
|
|
@@ -264,8 +267,8 @@ export async function applyRealmAdmission(homeInput: string, project: string, op
|
|
|
264
267
|
clearRealmIntent(home, intent, proof);
|
|
265
268
|
return { mode: "abandon" as const, state: "abandoned" as const, realm, sequence: intent.sequence, discarded,
|
|
266
269
|
nextStep: "amem migrate --sync-placement --admit <project> --dry-run" };
|
|
267
|
-
}
|
|
268
|
-
});
|
|
270
|
+
}, { surface: "admit" });
|
|
271
|
+
} catch (error) { return rethrow(error); }
|
|
269
272
|
}
|
|
270
273
|
if (options.mode === "apply") assertNoPendingAdmission(home);
|
|
271
274
|
const planned = options.mode === "apply" ? inspectRealmAdmission(home, project) : undefined;
|
|
@@ -275,8 +278,8 @@ export async function applyRealmAdmission(homeInput: string, project: string, op
|
|
|
275
278
|
if (inForce(home, realm)) return { mode: options.mode, state: "already-admitted", realm };
|
|
276
279
|
throw Error("No retained admission intent exists for this realm; run amem migrate --sync-placement --admit <project> --dry-run.");
|
|
277
280
|
}
|
|
278
|
-
|
|
279
|
-
|
|
281
|
+
try {
|
|
282
|
+
return await withPlacementMutationFences(home, directories(home, projectPrefix), async (mutation, owner) => {
|
|
280
283
|
assertCheckpointClear(home);
|
|
281
284
|
if (options.mode === "apply") assertNoPendingAdmission(home);
|
|
282
285
|
if (options.mode === "resume") assertNoPendingAdmission(home, realm);
|
|
@@ -343,10 +346,12 @@ export async function applyRealmAdmission(homeInput: string, project: string, op
|
|
|
343
346
|
await options.checkpoint?.("after-append");
|
|
344
347
|
clearRealmIntent(home, frozen, proof);
|
|
345
348
|
return { mode: options.mode, state: "admitted" as const, realm, sequence: frozen.sequence, headHash: record.seal, created };
|
|
346
|
-
}
|
|
347
|
-
});
|
|
349
|
+
}, { surface: "admit" });
|
|
350
|
+
} catch (error) { return rethrow(error); }
|
|
348
351
|
}
|
|
349
352
|
function directories(home: string, projectPrefix: string): string[] {
|
|
350
353
|
const realmDir = join(home, "projects", projectPrefix);
|
|
351
|
-
|
|
354
|
+
const active = placementFenceDirectories(home, activeBinding(home));
|
|
355
|
+
if (existsSync(realmDir)) active.push(realmDir);
|
|
356
|
+
return active;
|
|
352
357
|
}
|
|
@@ -40,6 +40,13 @@ export function placementRefusalCategoryOf(error: unknown): PlacementRefusalCate
|
|
|
40
40
|
|
|
41
41
|
export function placementRefusalNextStep(category: PlacementRefusalCategory): string { return NEXT[category]; }
|
|
42
42
|
|
|
43
|
+
/** A stop while a retained attempt may already have published: its outcome stays unknown until its receipts are rechecked. */
|
|
44
|
+
export const PLACEMENT_RETAINED_STOP_MESSAGE = "Placement sync stopped with a retained attempt that may have published; recheck its exact receipts before another publication.";
|
|
45
|
+
/** #657: a stop before any publication attempt existed; it published nothing and names the command that finishes the run. */
|
|
46
|
+
export function placementStoppedMessage(phase: string): string {
|
|
47
|
+
return `Placement sync stopped before publication (phase ${phase}); nothing was published for this batch. Run amem sync to finish it.`;
|
|
48
|
+
}
|
|
49
|
+
|
|
43
50
|
/** AC1/AC4: the person-facing refusal. `other` keeps the generic wording and still names the phase. */
|
|
44
51
|
export function placementRefusalMessage(category: PlacementRefusalCategory, phase: SyncProgressPhase): string {
|
|
45
52
|
const where = phase.replaceAll("-", " ");
|
|
@@ -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.
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* #639: a read-only listing of the placement writer inventory and the install roots a renewal must declare. It writes
|
|
3
|
+
* nothing, takes no lock and never searches the filesystem for installs; it only reads the active inventory, the running
|
|
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.
|
|
6
|
+
*/
|
|
7
|
+
import { realPath } from "./platform.ts";
|
|
8
|
+
import { join } from "node:path";
|
|
9
|
+
import { embeddedAmemRoot, installAbsent, installVersion, runningAmemRoots } from "./formats-raise.ts";
|
|
10
|
+
import { readEffectiveSyncPlacementWriters } from "./sync-placement-effective-writers.ts";
|
|
11
|
+
import { readSetupWriterLaunchers, type SetupTarget } from "../setup-writer-roots.ts";
|
|
12
|
+
|
|
13
|
+
export const PLACEMENT_WRITERS_LISTING = "amem migrate --sync-placement --writers";
|
|
14
|
+
export const PLACEMENT_WRITERS_SCHEMA = "amem.placement-writers/v1";
|
|
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.";
|
|
16
|
+
|
|
17
|
+
export interface PlacementWriterListing {
|
|
18
|
+
schema: typeof PLACEMENT_WRITERS_SCHEMA;
|
|
19
|
+
inventory: { root: string; version: string | null; state: "present" | "missing" }[];
|
|
20
|
+
running: { root: string; version: string | null; inInventory: boolean };
|
|
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 }[];
|
|
24
|
+
suggestedRoots: string[];
|
|
25
|
+
command: string;
|
|
26
|
+
note: string;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** POSIX single-quote shell quoting: the printed command is pasted into a shell as is. */
|
|
30
|
+
export function shellQuote(value: string): string {
|
|
31
|
+
return `'${value.replaceAll("'", `'\\''`)}'`;
|
|
32
|
+
}
|
|
33
|
+
export function placementWriterCommand(roots: readonly string[]): string {
|
|
34
|
+
const flags = roots.map(root => `--writer-root ${shellQuote(root)}`).join(" ");
|
|
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;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export function listPlacementWriters(home: string, ownRoot: string, discovery: PlacementWriterDiscovery = {}): PlacementWriterListing {
|
|
61
|
+
const inventory = (readEffectiveSyncPlacementWriters(home).roots ?? []).map(root => {
|
|
62
|
+
const state = installAbsent(root) ? "missing" as const : "present" as const;
|
|
63
|
+
return { root, version: state === "present" ? installVersion(root) : null, state };
|
|
64
|
+
});
|
|
65
|
+
const own = realPath(ownRoot);
|
|
66
|
+
const running = { root: own, version: installVersion(own), inInventory: inventory.some(row => row.root === own) };
|
|
67
|
+
const receipts = readSetupWriterLaunchers(home), runningHosts = discoverHosts(own, discovery);
|
|
68
|
+
const present = new Set<string>([own]);
|
|
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);
|
|
71
|
+
const suggestedRoots = [...present].sort();
|
|
72
|
+
return { schema: PLACEMENT_WRITERS_SCHEMA, inventory, running, receipts, runningHosts, suggestedRoots, command: placementWriterCommand(suggestedRoots), note: PLACEMENT_WRITERS_NOTE };
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export function placementWritersText(listing: PlacementWriterListing): string {
|
|
76
|
+
const lines = ["sync placement writer inventory:"];
|
|
77
|
+
for (const row of listing.inventory) lines.push(` ${row.state} ${row.version ?? "unknown"} ${row.root}`);
|
|
78
|
+
if (!listing.inventory.length) lines.push(" (no inventory roots recorded)");
|
|
79
|
+
lines.push(`running install: ${listing.running.version ?? "unknown"} ${listing.running.root} (${listing.running.inInventory ? "in the inventory" : "not in the inventory"})`);
|
|
80
|
+
lines.push("setup receipts:");
|
|
81
|
+
for (const row of listing.receipts) lines.push(` ${row.target} ${row.state} ${row.root}`);
|
|
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)");
|
|
86
|
+
lines.push("roots to declare:");
|
|
87
|
+
for (const root of listing.suggestedRoots) lines.push(` ${root}`);
|
|
88
|
+
lines.push(`next: ${listing.command}`, `note: ${listing.note}`);
|
|
89
|
+
return lines.join("\n");
|
|
90
|
+
}
|
|
@@ -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 =>
|