@staix/agent-mem 0.33.0 → 0.35.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 +4 -2
- package/package.json +2 -1
- package/skills/_shared/amem-adapter.md +10 -0
- package/skills/amem-ops/SKILL.md +15 -0
- package/skills/amem-recall/SKILL.md +13 -0
- package/skills/amem-remember/SKILL.md +13 -0
- package/skills/amem-review/SKILL.md +14 -0
- package/skills/amem-status/SKILL.md +12 -0
- package/src/amem-read-tools.ts +20 -0
- package/src/cli.ts +50 -12
- package/src/commands-table.ts +3 -2
- package/src/hook-jcode-journal.ts +8 -2
- package/src/hook-spool.ts +5 -0
- package/src/hooks.ts +16 -3
- package/src/index.ts +2 -0
- package/src/mcp-memory.ts +73 -15
- package/src/mcp.ts +2 -2
- package/src/memory/binding-read-set.ts +18 -0
- package/src/memory/capacity.ts +7 -3
- package/src/memory/commands.ts +19 -7
- package/src/memory/doctor.ts +26 -2
- package/src/memory/home-binding-fence.ts +97 -0
- package/src/memory/intent-brief.ts +26 -11
- package/src/memory/intent-node-matcher.ts +62 -0
- package/src/memory/metrics.ts +75 -28
- package/src/memory/profile-lock-diagnostic.ts +5 -5
- package/src/memory/public-prune-input-chain.ts +4 -1
- package/src/memory/public-prune-view.ts +6 -1
- package/src/memory/recall-staleness.ts +18 -7
- package/src/memory/shard-sync-history.ts +27 -6
- package/src/memory/shard.ts +1 -1
- package/src/memory/sync-placement-activation.ts +2 -2
- package/src/memory/sync-placement-active.ts +4 -1
- package/src/memory/sync-placement-bound.ts +1 -1
- package/src/memory/sync-placement-capture.ts +17 -6
- package/src/memory/sync-placement-checkpoint-person.ts +26 -4
- package/src/memory/sync-placement-checkpoint-prospective.ts +5 -1
- package/src/memory/sync-placement-guard.ts +17 -2
- package/src/memory/sync-placement-inspection-evidence.ts +17 -6
- package/src/memory/sync-placement-inspection.ts +2 -2
- package/src/memory/sync-placement-prerequisites.ts +1 -1
- package/src/memory/sync-placement-refusal.ts +1 -1
- package/src/memory/sync-placement-writer-renewal.ts +1 -1
- package/src/memory/sync-placement-writer-revision-format.ts +3 -3
- package/src/session-brief.ts +47 -7
- package/src/setup.ts +62 -11
- package/src/skills-install.ts +241 -0
- package/src/sync-placement-writer-context.ts +94 -19
- package/src/ui/plugin.ts +1 -1
|
@@ -0,0 +1,241 @@
|
|
|
1
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
2
|
+
import { lstatSync, mkdirSync, readFileSync, readdirSync, readlinkSync, renameSync, rmSync, writeFileSync } from "node:fs";
|
|
3
|
+
import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
|
|
4
|
+
import { fileURLToPath } from "node:url";
|
|
5
|
+
import { canonicalPath, realPath } from "./memory/platform.ts";
|
|
6
|
+
import { memoryHome } from "./memory/home.ts";
|
|
7
|
+
import { resolveSetupPaths, type SetupEnvironment } from "./setup-paths.ts";
|
|
8
|
+
import type { SetupTarget } from "./setup.ts";
|
|
9
|
+
|
|
10
|
+
export const SKILL_NAMES = ["amem-status", "amem-recall", "amem-remember", "amem-review", "amem-ops"] as const;
|
|
11
|
+
export type SkillAction = { name: string; path: string; change: "install" | "replace" | "remove" | "unchanged" | "absent" | "modified" | "foreign" | "refused"; reason?: string };
|
|
12
|
+
export type SkillInstallReport = { root: string; linkedFrom?: string; actions: SkillAction[] };
|
|
13
|
+
type RootBinding = { root: string; linkedFrom?: string };
|
|
14
|
+
type Marker = { tool: "amem"; version: string; sha256: string };
|
|
15
|
+
type Tree = Map<string, Buffer>;
|
|
16
|
+
const markerName = ".amem-skill.json";
|
|
17
|
+
// ponytail: Limit each skill to 256 files and 1 MiB per file; make these configurable if larger packaged skills are needed.
|
|
18
|
+
const maxFiles = 256, maxBytes = 1024 * 1024;
|
|
19
|
+
const defaultRoot = fileURLToPath(new URL("..", import.meta.url));
|
|
20
|
+
|
|
21
|
+
export function skillRoot(target: SetupTarget, env: SetupEnvironment, givenHome?: string): string | undefined {
|
|
22
|
+
const paths = resolveSetupPaths(env, givenHome).paths;
|
|
23
|
+
if (target === "claude") return join(dirname(paths.claude[1]!), "skills");
|
|
24
|
+
if (target === "codex" || target === "kimi" || target === "qwen") return join(dirname(paths[target][0]!), "skills");
|
|
25
|
+
return undefined;
|
|
26
|
+
}
|
|
27
|
+
function exists(path: string): boolean { try { lstatSync(path); return true; } catch (e) { if ((e as NodeJS.ErrnoException).code === "ENOENT") return false; throw e; } }
|
|
28
|
+
class SkillTreeError extends Error {}
|
|
29
|
+
function tree(root: string, skipMarker = false): Tree {
|
|
30
|
+
const result: Tree = new Map();
|
|
31
|
+
function visit(dir: string, prefix: string): void {
|
|
32
|
+
const stat = lstatSync(dir);
|
|
33
|
+
if (!stat.isDirectory() || stat.isSymbolicLink()) throw new SkillTreeError(`not a real directory: ${prefix || "."}`);
|
|
34
|
+
const entries = readdirSync(dir).sort();
|
|
35
|
+
if (!entries.length && prefix) throw new SkillTreeError(`empty directory: ${prefix}`);
|
|
36
|
+
for (const name of entries) {
|
|
37
|
+
if (!prefix && skipMarker && name === markerName) continue;
|
|
38
|
+
const rel = prefix ? `${prefix}/${name}` : name, path = join(dir, name), st = lstatSync(path);
|
|
39
|
+
if (st.isSymbolicLink()) throw new SkillTreeError(`symlink refused: ${rel}`);
|
|
40
|
+
if (st.isDirectory()) visit(path, rel);
|
|
41
|
+
else if (st.isFile()) {
|
|
42
|
+
if (st.size > maxBytes) throw new SkillTreeError(`skill file size limit ${maxBytes} bytes exceeded: ${rel}`);
|
|
43
|
+
if (result.size >= maxFiles) throw new SkillTreeError(`skill file count limit ${maxFiles} exceeded: ${rel}`);
|
|
44
|
+
const data = readFileSync(path);
|
|
45
|
+
if (data.length > maxBytes) throw new SkillTreeError(`skill file size limit ${maxBytes} bytes exceeded: ${rel}`);
|
|
46
|
+
result.set(rel, data);
|
|
47
|
+
} else throw new SkillTreeError(`non-regular file refused: ${rel}`);
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
visit(root, "");
|
|
51
|
+
return result;
|
|
52
|
+
}
|
|
53
|
+
function digest(files: Tree): string {
|
|
54
|
+
const hash = createHash("sha256");
|
|
55
|
+
// Contract: sorted UTF-8 slash-separated paths, each framed as decimal byte length, colon, bytes; then the file bytes framed identically.
|
|
56
|
+
for (const [name, data] of [...files].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)) {
|
|
57
|
+
const pathBytes = Buffer.from(name, "utf8");
|
|
58
|
+
hash.update(`${pathBytes.length}:`).update(pathBytes).update(`${data.length}:`).update(data);
|
|
59
|
+
}
|
|
60
|
+
return hash.digest("hex");
|
|
61
|
+
}
|
|
62
|
+
function marker(dir: string): Marker | undefined {
|
|
63
|
+
try {
|
|
64
|
+
const path = join(dir, markerName), st = lstatSync(path);
|
|
65
|
+
if (!st.isFile() || st.isSymbolicLink() || st.size > 4096) return undefined;
|
|
66
|
+
const value: unknown = JSON.parse(readFileSync(path, "utf8"));
|
|
67
|
+
if (typeof value !== "object" || value === null) return undefined;
|
|
68
|
+
const m = value as Record<string, unknown>;
|
|
69
|
+
if (m.tool !== "amem" || typeof m.version !== "string" || typeof m.sha256 !== "string" || !/^[a-f0-9]{64}$/.test(m.sha256)) return undefined;
|
|
70
|
+
return m as Marker;
|
|
71
|
+
} catch { return undefined; }
|
|
72
|
+
}
|
|
73
|
+
function owned(dir: string): Marker | undefined {
|
|
74
|
+
const m = marker(dir);
|
|
75
|
+
if (!m || digest(tree(dir, true)) !== m.sha256) return undefined;
|
|
76
|
+
return m;
|
|
77
|
+
}
|
|
78
|
+
function matches(dir: string, expected: Marker): boolean {
|
|
79
|
+
const current = owned(dir);
|
|
80
|
+
return !!current && current.sha256 === expected.sha256 && current.version === expected.version;
|
|
81
|
+
}
|
|
82
|
+
function packageTree(packageRoot: string, name: string): Tree {
|
|
83
|
+
safeInput(join(packageRoot, "skills", name));
|
|
84
|
+
safeInput(join(packageRoot, "skills", "_shared", "amem-adapter.md"));
|
|
85
|
+
const files = tree(join(packageRoot, "skills", name));
|
|
86
|
+
if (files.has(markerName) || files.has("references/amem-adapter.md")) throw new Error("reserved packaged file");
|
|
87
|
+
const adapter = join(packageRoot, "skills", "_shared", "amem-adapter.md"), st = lstatSync(adapter);
|
|
88
|
+
if (!st.isFile() || st.isSymbolicLink() || st.size > maxBytes || files.size >= maxFiles) throw new Error("invalid adapter");
|
|
89
|
+
files.set("references/amem-adapter.md", readFileSync(adapter));
|
|
90
|
+
return files;
|
|
91
|
+
}
|
|
92
|
+
function writeTree(dir: string, files: Tree, version: string): void {
|
|
93
|
+
mkdirSync(dir);
|
|
94
|
+
for (const [name, data] of files) { const path = join(dir, ...name.split("/")); mkdirSync(dirname(path), { recursive: true }); writeFileSync(path, data, { flag: "wx" }); }
|
|
95
|
+
writeFileSync(join(dir, markerName), JSON.stringify({ tool: "amem", version, sha256: digest(files) }) + "\n", { flag: "wx" });
|
|
96
|
+
}
|
|
97
|
+
function safeInput(path: string): void {
|
|
98
|
+
if (exists(path) && lstatSync(path).isSymbolicLink()) throw new Error(`Package input ${path} is a symlink`);
|
|
99
|
+
}
|
|
100
|
+
function within(child: string, parent: string): boolean {
|
|
101
|
+
const part = relative(parent, child);
|
|
102
|
+
return part === "" || (part !== ".." && !part.startsWith(`..${sep}`) && !isAbsolute(part));
|
|
103
|
+
}
|
|
104
|
+
function safeRoot(root: string, packageRoot: string, env: SetupEnvironment): RootBinding {
|
|
105
|
+
const absolute = resolve(root);
|
|
106
|
+
if (exists(absolute) && lstatSync(absolute).isSymbolicLink()) {
|
|
107
|
+
const target = resolve(dirname(absolute), readlinkSync(absolute));
|
|
108
|
+
let physical: string;
|
|
109
|
+
try { physical = realPath(absolute); }
|
|
110
|
+
catch { throw new Error(`Skill root link ${absolute} targets ${target}, which is unavailable; repair the link and retry`); }
|
|
111
|
+
if (!lstatSync(physical).isDirectory()) throw new Error(`Skill root link ${absolute} targets ${physical}, which is not a directory; choose a directory and retry`);
|
|
112
|
+
const home = canonicalPath(memoryHome(env)), source = canonicalPath(join(packageRoot, "skills"));
|
|
113
|
+
if (within(physical, home) || within(physical, source)) throw new Error(`Skill root link ${absolute} targets ${physical}, inside the memory home or package skills; choose another directory and retry`);
|
|
114
|
+
return { root: physical, linkedFrom: absolute };
|
|
115
|
+
}
|
|
116
|
+
function parentPath(path: string): string {
|
|
117
|
+
if (exists(path)) return realPath(path);
|
|
118
|
+
const parent = dirname(path);
|
|
119
|
+
if (parent === path) throw new Error(`Cannot resolve ${path}`);
|
|
120
|
+
return join(parentPath(parent), basename(path));
|
|
121
|
+
}
|
|
122
|
+
return { root: join(parentPath(dirname(absolute)), basename(absolute)) };
|
|
123
|
+
}
|
|
124
|
+
function message(error: unknown): string { return error instanceof Error ? error.message : String(error); }
|
|
125
|
+
function leftovers(root: string, name: string): string[] {
|
|
126
|
+
if (!exists(root)) return [];
|
|
127
|
+
return readdirSync(root).filter(x => x.startsWith(`.amem-skill-${name}-`)).map(x => join(root, x));
|
|
128
|
+
}
|
|
129
|
+
export function installSkills(root: string, mode: "preview" | "apply" | "undo", packageRoot = defaultRoot, packageVersion?: string, retryCommand = "amem setup --apply", env: SetupEnvironment = process.env, expectedBinding?: RootBinding): SkillInstallReport {
|
|
130
|
+
root = resolve(root);
|
|
131
|
+
const actions: SkillAction[] = [];
|
|
132
|
+
const requested = root;
|
|
133
|
+
let rootError: string | undefined, binding: RootBinding = { root };
|
|
134
|
+
let identity: { dev: number; ino: number } | undefined;
|
|
135
|
+
try {
|
|
136
|
+
binding = safeRoot(root, packageRoot, env); root = binding.root;
|
|
137
|
+
if (expectedBinding && (expectedBinding.root !== root || expectedBinding.linkedFrom !== binding.linkedFrom)) throw new Error(`Skill root ${requested} changed since preview (target ${root}); inspect it and rerun ${retryCommand}`);
|
|
138
|
+
if (exists(root)) { const st = lstatSync(root); if (!st.isDirectory() || st.isSymbolicLink()) throw new Error(`${root} is not a real directory; choose a directory`); identity = { dev: st.dev, ino: st.ino }; }
|
|
139
|
+
} catch (e) { rootError = message(e); }
|
|
140
|
+
const checkRoot = () => {
|
|
141
|
+
if (binding.linkedFrom) {
|
|
142
|
+
const current = safeRoot(binding.linkedFrom, packageRoot, env);
|
|
143
|
+
if (current.root !== root || current.linkedFrom !== binding.linkedFrom) throw new Error(`Skill root link ${binding.linkedFrom} changed from ${root}; inspect the link and rerun ${retryCommand}`);
|
|
144
|
+
}
|
|
145
|
+
const st = lstatSync(root);
|
|
146
|
+
if (!st.isDirectory() || st.isSymbolicLink() || identity && (st.dev !== identity.dev || st.ino !== identity.ino)) throw new Error(`Skill root ${root} changed; inspect it and rerun ${retryCommand}`);
|
|
147
|
+
};
|
|
148
|
+
let version = packageVersion;
|
|
149
|
+
if (mode !== "undo" && version === undefined) { try { version = JSON.parse(readFileSync(join(packageRoot, "package.json"), "utf8")).version; if (typeof version !== "string") throw new Error("invalid version"); } catch (e) { rootError = `${message(e)}; check the package and rerun ${retryCommand}`; } }
|
|
150
|
+
for (const name of SKILL_NAMES) {
|
|
151
|
+
const path = join(root, name);
|
|
152
|
+
const action = (change: SkillAction["change"], reason?: string) => actions.push({ name, path, change, ...(reason ? { reason: change === "foreign" || change === "modified" ? `${reason} at ${path}; keep it, or move it aside and rerun ${retryCommand}` : reason } : {}) });
|
|
153
|
+
if (rootError) { action("refused", rootError); continue; }
|
|
154
|
+
try {
|
|
155
|
+
const pending = leftovers(root, name);
|
|
156
|
+
// Recover only verified leftovers. A backup is restored if the destination is absent; verified stages and obsolete backups can then be removed.
|
|
157
|
+
if (pending.length) {
|
|
158
|
+
const backups = pending.filter(p => basename(p).startsWith(`.amem-skill-${name}-backup-`));
|
|
159
|
+
const stages = pending.filter(p => basename(p).startsWith(`.amem-skill-${name}-stage-`));
|
|
160
|
+
const verified = pending.every(p => { try { return !!owned(p); } catch { return false; } });
|
|
161
|
+
if (!verified || backups.length > 1 || stages.length > 1 || backups.length + stages.length !== pending.length) { action("refused", `Unverified or ambiguous interrupted swap: ${pending.join(", ")}; inspect and remove the leftovers if no longer needed, then rerun ${retryCommand}`); continue; }
|
|
162
|
+
if (mode === "preview") { action("refused", `Interrupted swap requires recovery; run ${retryCommand}`); continue; }
|
|
163
|
+
checkRoot();
|
|
164
|
+
if (!exists(path) && backups.length === 1) renameSync(backups[0]!, path);
|
|
165
|
+
if (exists(path) && !owned(path)) { action("refused", `Interrupted swap destination ${path} is not verified; keep it, or move it aside and rerun ${retryCommand}`); continue; }
|
|
166
|
+
for (const item of pending) if (exists(item)) { if (!owned(item)) throw new Error("Interrupted swap changed during recovery"); rmSync(item, { recursive: true }); }
|
|
167
|
+
}
|
|
168
|
+
let old: Marker | undefined;
|
|
169
|
+
if (exists(path)) {
|
|
170
|
+
const st = lstatSync(path);
|
|
171
|
+
if (st.isSymbolicLink()) { action("foreign", "Skill target is a symlink"); continue; }
|
|
172
|
+
if (!st.isDirectory()) { action("foreign", "Skill target is not a directory"); continue; }
|
|
173
|
+
if (!(old = marker(path))) { action("foreign", "Skill directory lacks a valid amem ownership marker"); continue; }
|
|
174
|
+
try { if (!owned(path)) { action("modified", "Owned skill changed; preserve it"); continue; } } catch (error) { action("modified", error instanceof SkillTreeError ? `Owned skill contains unsafe files (${error.message})` : "Owned skill contains unsafe or changed files"); continue; }
|
|
175
|
+
}
|
|
176
|
+
if (mode === "undo") {
|
|
177
|
+
if (!old) { action("absent"); continue; }
|
|
178
|
+
if (!matches(path, old)) { action("modified", "Skill changed before removal"); continue; }
|
|
179
|
+
const backup = join(root, `.amem-skill-${name}-backup-${randomUUID()}`);
|
|
180
|
+
checkRoot(); renameSync(path, backup);
|
|
181
|
+
if (!matches(backup, old)) { renameSync(backup, path); action("modified", "Skill changed before removal"); continue; }
|
|
182
|
+
rmSync(backup, { recursive: true }); action("remove"); continue;
|
|
183
|
+
}
|
|
184
|
+
const files = packageTree(packageRoot, name), expected = digest(files);
|
|
185
|
+
if (old && old.sha256 === expected && old.version === version) { action("unchanged"); continue; }
|
|
186
|
+
if (mode === "preview") { action(old ? "replace" : "install"); continue; }
|
|
187
|
+
if (exists(root)) checkRoot();
|
|
188
|
+
mkdirSync(root, { recursive: true });
|
|
189
|
+
if (!identity) { const st = lstatSync(root); identity = { dev: st.dev, ino: st.ino }; }
|
|
190
|
+
checkRoot();
|
|
191
|
+
const stage = join(root, `.amem-skill-${name}-stage-${randomUUID()}`), backup = join(root, `.amem-skill-${name}-backup-${randomUUID()}`);
|
|
192
|
+
writeTree(stage, files, version!);
|
|
193
|
+
if (!owned(stage)) throw new Error("staged verification failed");
|
|
194
|
+
checkRoot();
|
|
195
|
+
if (old) {
|
|
196
|
+
if (!matches(path, old)) { if (owned(stage)) rmSync(stage, { recursive: true }); action("modified", "Skill changed before swap"); continue; }
|
|
197
|
+
renameSync(path, backup);
|
|
198
|
+
if (!matches(backup, old)) { renameSync(backup, path); if (owned(stage)) rmSync(stage, { recursive: true }); action("modified", "Skill changed before swap"); continue; }
|
|
199
|
+
} else if (exists(path)) { if (owned(stage)) rmSync(stage, { recursive: true }); action("foreign", "Destination appeared before install"); continue; }
|
|
200
|
+
try {
|
|
201
|
+
renameSync(stage, path);
|
|
202
|
+
if (!owned(path) || marker(path)?.sha256 !== expected) throw new Error("post-swap verification failed");
|
|
203
|
+
if (old && !matches(backup, old)) throw new Error("backup changed before removal");
|
|
204
|
+
} catch (e) {
|
|
205
|
+
if (exists(path) && matches(path, { tool: "amem", version: version!, sha256: expected })) rmSync(path, { recursive: true });
|
|
206
|
+
if (old && !exists(path) && exists(backup)) renameSync(backup, path);
|
|
207
|
+
if (exists(stage) && owned(stage)) rmSync(stage, { recursive: true });
|
|
208
|
+
action("refused", `${message(e)}; inspect the affected files and rerun ${retryCommand}`);
|
|
209
|
+
continue;
|
|
210
|
+
}
|
|
211
|
+
if (old) {
|
|
212
|
+
try { rmSync(backup, { recursive: true }); }
|
|
213
|
+
catch (e) { action("refused", `Installed skill is verified but backup removal failed at ${backup}: ${message(e)}; inspect and remove the leftover, then rerun ${retryCommand}`); continue; }
|
|
214
|
+
}
|
|
215
|
+
action(old ? "replace" : "install");
|
|
216
|
+
} catch (e) { action("refused", `${message(e)}; inspect the affected files and rerun ${retryCommand}`); }
|
|
217
|
+
}
|
|
218
|
+
return { root, ...(binding.linkedFrom ? { linkedFrom: binding.linkedFrom } : {}), actions };
|
|
219
|
+
}
|
|
220
|
+
export function exportSkills(destination: string, options: { packageRoot?: string; packageVersion?: string; env?: SetupEnvironment } = {}): SkillInstallReport {
|
|
221
|
+
let root = resolve(destination || ".");
|
|
222
|
+
let binding: RootBinding = { root };
|
|
223
|
+
const retry = `amem skills export '${destination.replace(/'/g, "'\\''")}'`;
|
|
224
|
+
const refuse = (reason: string): SkillInstallReport => ({ root, ...(binding.linkedFrom ? { linkedFrom: binding.linkedFrom } : {}), actions: SKILL_NAMES.map(name => ({ name, path: join(root, name), change: "refused", reason })) });
|
|
225
|
+
if (!destination.trim() || [...destination].some(c => c.charCodeAt(0) < 32 || c.charCodeAt(0) === 127)) return refuse("Destination is empty or contains control characters; choose a valid directory and rerun amem skills export <dir>");
|
|
226
|
+
try {
|
|
227
|
+
binding = safeRoot(root, options.packageRoot ?? defaultRoot, options.env ?? process.env); root = binding.root;
|
|
228
|
+
if (exists(root)) {
|
|
229
|
+
if (!lstatSync(root).isDirectory()) return refuse(`Destination ${root} is not a directory; choose a directory and rerun ${retry}`);
|
|
230
|
+
for (const entry of readdirSync(root)) {
|
|
231
|
+
if ((SKILL_NAMES as readonly string[]).includes(entry)) continue;
|
|
232
|
+
const recognized = SKILL_NAMES.some(name => entry.startsWith(`.amem-skill-${name}-`));
|
|
233
|
+
if (!recognized) return refuse(`Foreign destination entry ${join(root, entry)}; keep it or move it aside, then rerun ${retry}`);
|
|
234
|
+
let valid = false;
|
|
235
|
+
try { valid = !!owned(join(root, entry)); } catch { /* preserve unverified leftovers */ }
|
|
236
|
+
if (!valid) return refuse(`Unverified interrupted swap ${join(root, entry)}; inspect and remove it if no longer needed, then rerun ${retry}`);
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
} catch (e) { return refuse(`${message(e)}; inspect the destination and rerun ${retry}`); }
|
|
240
|
+
return installSkills(destination, "apply", options.packageRoot, options.packageVersion, retry, options.env, binding);
|
|
241
|
+
}
|
|
@@ -4,6 +4,7 @@ import { fileURLToPath } from "node:url";
|
|
|
4
4
|
import { canonicalPath, realPath } from "./memory/platform.ts";
|
|
5
5
|
import { canonicalJSON } from "./memory/generation.ts";
|
|
6
6
|
import { readSetupWriterRoots, SETUP_TARGETS, setupReceiptRemedy, SetupWriterRootsError, type SetupTarget } from "./setup.ts";
|
|
7
|
+
import { placementMarkerState } from "./memory/sync-placement-guard.ts";
|
|
7
8
|
import { measureSyncPlacementWriters, extractSyncPlacementWriterFailure, type SyncPlacementWriterFailureDetail, type SyncPlacementWriterMeasurement } from "./memory/sync-placement-writers.ts";
|
|
8
9
|
import { readEffectiveSyncPlacementWriters } from "./memory/sync-placement-effective-writers.ts";
|
|
9
10
|
import { PlacementHomeFloorError, requirePlacementHomeFloor } from "./memory/sync-placement-prerequisites.ts";
|
|
@@ -19,15 +20,19 @@ const failureDetails:Record<SyncPlacementWriterFailureDetail,string>={
|
|
|
19
20
|
"missing-runtime":"required bin/amem.js or src/index.ts is missing",bound:"inventory exceeds a supported bound",changed:"install changed during measurement",
|
|
20
21
|
};
|
|
21
22
|
function writerContextMessage(category:PlacementWriterRootCategory,causeClass:"missing"|"changed"|"unavailable",phase:PlacementWriterContextPhase,detail?:SyncPlacementWriterFailureDetail,renewalState?:"pending"|"staging"|"checkpoint-pending",setupTarget?:SetupTarget):string {
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
if(category==="
|
|
23
|
+
// #551 AC1: the shared revision text names neither this category nor its cause class, so both are printed here and the
|
|
24
|
+
// shared text (which carries its own remedy) follows. The checkpoint message is still reproduced verbatim, never replaced.
|
|
25
|
+
if(category==="writer renewal")return `Sync placement ${phase==="initial"?"initial ":""}writer proof is ${causeClass} (writer renewal category); ${new SharedWriterRevisionError(renewalState==="staging"?"staging":renewalState==="checkpoint-pending"?"checkpoint-pending":"pending").message}`;
|
|
26
|
+
if(category==="active locator") return `Sync placement initial root locator is ${causeClass} (active locator category); inspect sync-placement-writer-roots.json and the matching activation metadata with a compatible recovery release, then run amem migrate --sync-placement --dry-run.`;
|
|
27
|
+
if(category==="home floor") return `Sync placement reader-floor proof is ${causeClass} (home floor category); inspect formats.json and use a reader compatible with its recorded floor, then run amem migrate --sync-placement --dry-run.`;
|
|
25
28
|
const cause=detail?`; ${failureDetails[detail]}`:"";
|
|
26
|
-
// #520: a receipt whose recorded install root is gone names its target and remedy, never the recorded path.
|
|
29
|
+
// #520: a receipt whose recorded install root is gone names its target and remedy, never the recorded path. #551 keeps that
|
|
30
|
+
// sentence - its cause marker, its remedy and its next step - behind the fixed category and cause class, so both surfaces
|
|
31
|
+
// print one sentence and neither loses the established remedy.
|
|
27
32
|
const receipt=category==="setup receipt"&&setupTarget?setupReceiptRemedy(setupTarget):undefined;
|
|
28
33
|
if(phase==="initial")return `Sync placement initial writer proof is ${causeClass} (${category} category${cause}); ${receipt??(category==="setup receipt"?"upgrade or repair the managed amem install and its host exact pin, then rerun amem setup <target> --apply":"upgrade or repair the amem install and its host exact pin")}. Declare the complete writer roots and rerun amem migrate --sync-placement --dry-run.`;
|
|
29
|
-
if(receipt)return `Sync placement writer proof is ${causeClass} (${category} category${cause}); ${receipt}; then rerun the sync.`;
|
|
30
|
-
return `Sync placement writer proof is ${causeClass} (${category} category${cause}); restore the inventoried install, or
|
|
34
|
+
if(receipt)return `Sync placement writer proof is ${causeClass} (${category} category${cause}); Placement sync refused [cause: setup_receipt_missing_install]: ${receipt}; then rerun the sync.`;
|
|
35
|
+
return `Sync placement writer proof is ${causeClass} (${category} category${cause}); restore the inventoried install, or renew it: if needed, preview amem formats raise home 0.22.0 and add --confirm after the exact command is approved; then run amem migrate --sync-placement --dry-run with the complete --writer-root inventory, and run --apply after the exact apply command is approved.`;
|
|
31
36
|
}
|
|
32
37
|
export class PlacementWriterContextError extends Error {
|
|
33
38
|
constructor(readonly category: PlacementWriterRootCategory, readonly causeClass: "missing" | "changed" | "unavailable",readonly phase:PlacementWriterContextPhase="active",readonly detail?:SyncPlacementWriterFailureDetail,readonly renewalState?:"pending"|"staging"|"checkpoint-pending",readonly setupTarget?:SetupTarget) {
|
|
@@ -46,20 +51,85 @@ export function placementSyncFailure(refusal: PlacementWriterContextError, failu
|
|
|
46
51
|
* #520: the fixed-data text a marked session gets when a placement refusal comes from an applied setup receipt whose
|
|
47
52
|
* recorded amem install no longer exists. Fields are read as own properties and validated against closed sets, so a
|
|
48
53
|
* caught message, a recorded path or a forged target never reaches the text; every other failure returns undefined and
|
|
49
|
-
* keeps the generic masked refusal.
|
|
54
|
+
* keeps the generic masked refusal. #551 AC1: the sentence is the shared one, so it carries the fixed category and cause
|
|
55
|
+
* class in front of #520's marker, remedy and next step.
|
|
50
56
|
*/
|
|
51
57
|
export function markedSetupReceiptRefusal(error: unknown): string | undefined {
|
|
52
|
-
const
|
|
53
|
-
return
|
|
58
|
+
const receipt = setupReceiptRefusal(error);
|
|
59
|
+
return receipt === undefined ? undefined : writerContextMessage("setup receipt","unavailable",receipt.phase,receipt.detail,undefined,receipt.target);
|
|
54
60
|
}
|
|
55
|
-
function
|
|
61
|
+
function setupReceiptRefusal(error: unknown): { target: SetupTarget; phase: PlacementWriterContextPhase; detail?: SyncPlacementWriterFailureDetail } | undefined {
|
|
56
62
|
if (!error || typeof error !== "object" || types.isProxy(error)) return undefined;
|
|
57
|
-
const carried = Object.getOwnPropertyDescriptor(error, "placementRefusal")?.value;
|
|
63
|
+
const carried: unknown = Object.getOwnPropertyDescriptor(error, "placementRefusal")?.value;
|
|
58
64
|
const refusal: unknown = carried && typeof carried === "object" && !types.isProxy(carried) ? carried : error;
|
|
59
65
|
if (refusal === null || typeof refusal !== "object") return undefined;
|
|
60
|
-
const fields = Object.getOwnPropertyDescriptors(refusal), target: unknown = fields.setupTarget?.value;
|
|
61
|
-
|
|
62
|
-
|
|
66
|
+
const fields = Object.getOwnPropertyDescriptors(refusal), target: unknown = fields.setupTarget?.value, detail: unknown = fields.detail?.value;
|
|
67
|
+
if (fields.category?.value !== "setup receipt" || fields.causeClass?.value !== "unavailable") return undefined;
|
|
68
|
+
if (typeof target !== "string" || !(SETUP_TARGETS as readonly string[]).includes(target)) return undefined;
|
|
69
|
+
return { target: target as SetupTarget, phase: fields.phase?.value === "initial" ? "initial" : "active",
|
|
70
|
+
...(typeof detail === "string" && Object.hasOwn(failureDetails, detail) ? { detail: detail as SyncPlacementWriterFailureDetail } : {}) };
|
|
71
|
+
}
|
|
72
|
+
const WRITER_ROOT_CATEGORIES=["running CLI","host package","setup receipt","declared writer","active locator","home floor","writer renewal"] as const satisfies readonly PlacementWriterRootCategory[];
|
|
73
|
+
const WRITER_CAUSE_CLASSES=["missing","changed","unavailable"] as const;
|
|
74
|
+
/**
|
|
75
|
+
* #551 AC1: the refusal as fixed own data for a person-facing surface. A real PlacementWriterContextError - or the one a
|
|
76
|
+
* later sync failure carries as `placementRefusal` - is rebuilt from its own validated fields, so a tampered message, a
|
|
77
|
+
* forged category or a recorded path never reaches the text; anything else returns undefined and keeps its own handling.
|
|
78
|
+
* A proxy is refused before any instanceof, prototype or property inspection, including a proxy carried as
|
|
79
|
+
* `placementRefusal`, so a throwing trap can never run here.
|
|
80
|
+
* Module-internal: the two surfaces reach it through `placementWriterRefusalText` and `placementWriterVerification` only.
|
|
81
|
+
*/
|
|
82
|
+
function placementWriterRefusal(error: unknown): PlacementWriterContextError | undefined {
|
|
83
|
+
if (!error || typeof error !== "object" || types.isProxy(error)) return undefined;
|
|
84
|
+
const carried: unknown = Object.getOwnPropertyDescriptor(error, "placementRefusal")?.value;
|
|
85
|
+
const candidate: unknown = carried !== null && typeof carried === "object" && !types.isProxy(carried) && carried instanceof PlacementWriterContextError ? carried : error;
|
|
86
|
+
if (!(candidate instanceof PlacementWriterContextError)) return undefined;
|
|
87
|
+
const fields = Object.getOwnPropertyDescriptors(candidate), category = fields.category?.value, causeClass = fields.causeClass?.value;
|
|
88
|
+
if (typeof category !== "string" || !(WRITER_ROOT_CATEGORIES as readonly string[]).includes(category)) return undefined;
|
|
89
|
+
if (typeof causeClass !== "string" || !(WRITER_CAUSE_CLASSES as readonly string[]).includes(causeClass)) return undefined;
|
|
90
|
+
const detail = fields.detail?.value, state = fields.renewalState?.value, target = fields.setupTarget?.value;
|
|
91
|
+
return new PlacementWriterContextError(category as PlacementWriterRootCategory, causeClass as PlacementWriterContextError["causeClass"],
|
|
92
|
+
fields.phase?.value === "initial" ? "initial" : "active",
|
|
93
|
+
typeof detail === "string" && Object.hasOwn(failureDetails, detail) ? detail as SyncPlacementWriterFailureDetail : undefined,
|
|
94
|
+
state === "staging" || state === "pending" || state === "checkpoint-pending" ? state : undefined,
|
|
95
|
+
typeof target === "string" && (SETUP_TARGETS as readonly string[]).includes(target) ? target as SetupTarget : undefined);
|
|
96
|
+
}
|
|
97
|
+
/** #551: no category is claimed here, because the state could not be read far enough to name one. */
|
|
98
|
+
const PLACEMENT_WRITER_UNVERIFIED_TEXT = "Placement writer verification could not establish a category: the retained writer inventory or its history could not be read far enough to name one; inspect the home with a compatible release, then run amem migrate --sync-placement --dry-run.";
|
|
99
|
+
/** An inventory state that could not be proven: never reported as a missing root, and never given an invented category. */
|
|
100
|
+
class UnprovenWriterInventory extends Error { constructor(){ super(PLACEMENT_WRITER_UNVERIFIED_TEXT); this.name="UnprovenWriterInventory"; } }
|
|
101
|
+
/** A shared writer-history code outside the three renewal states: `safeRefusal` would otherwise assert the locator category for it. */
|
|
102
|
+
function unprovenWriterHistory(error: unknown): boolean {
|
|
103
|
+
if (!error || typeof error !== "object" || types.isProxy(error) || !(error instanceof SharedWriterRevisionError)) return false;
|
|
104
|
+
const code = Object.getOwnPropertyDescriptor(error, "code")?.value;
|
|
105
|
+
return code !== "pending" && code !== "staging" && code !== "checkpoint-pending";
|
|
106
|
+
}
|
|
107
|
+
/**
|
|
108
|
+
* #551 AC1: the fixed text `amem sync` and `amem doctor` report, one sentence per category, rebuilt rather than echoed.
|
|
109
|
+
* #520's receipt case rides inside that same sentence - its cause marker, its target's remedy and its next step - so a
|
|
110
|
+
* marked and an unmarked run print one text instead of two, and its shape-only entry point stays the fallback for a
|
|
111
|
+
* refusal built by another copy of this module.
|
|
112
|
+
*/
|
|
113
|
+
export function placementWriterRefusalText(error: unknown): string | undefined {
|
|
114
|
+
if (!types.isProxy(error) && error instanceof UnprovenWriterInventory) return PLACEMENT_WRITER_UNVERIFIED_TEXT;
|
|
115
|
+
return placementWriterRefusal(error)?.message ?? markedSetupReceiptRefusal(error);
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* #551: the writer verification a sync on this home would perform, as data. `missing` is reported only after the inventory
|
|
119
|
+
* was read and compared, so an unreadable one never claims a root is absent; an unproven state asserts no category at all.
|
|
120
|
+
*/
|
|
121
|
+
export function placementWriterVerification(home: string, ownRoot: string):
|
|
122
|
+
{ writers: number; refusal?: undefined; unverified?: undefined }
|
|
123
|
+
| { writers?: undefined; refusal: PlacementWriterContextError; unverified?: undefined }
|
|
124
|
+
| { writers?: undefined; refusal?: undefined; unverified: string } {
|
|
125
|
+
// #551: a marker this home cannot prove proves no category either, so it is unverified before any measurement is attempted.
|
|
126
|
+
if (placementMarkerState(home) === "unverified") return { unverified: PLACEMENT_WRITER_UNVERIFIED_TEXT };
|
|
127
|
+
try { return { writers: activePlacementWriterContext(home, ownRoot).measurement.writers.length }; }
|
|
128
|
+
catch (error) {
|
|
129
|
+
if (!types.isProxy(error) && error instanceof UnprovenWriterInventory) return { unverified: PLACEMENT_WRITER_UNVERIFIED_TEXT };
|
|
130
|
+
const refusal = placementWriterRefusal(error);
|
|
131
|
+
return refusal ? { refusal } : { unverified: PLACEMENT_WRITER_UNVERIFIED_TEXT };
|
|
132
|
+
}
|
|
63
133
|
}
|
|
64
134
|
function safeRefusal(error: unknown, category: PlacementWriterRootCategory,phase:PlacementWriterContextPhase="active"): PlacementWriterContextError {
|
|
65
135
|
if (error && typeof error === "object" && !types.isProxy(error) && (error instanceof PlacementHomeFloorError || error instanceof FormatFloorError)) return new PlacementWriterContextError("home floor","unavailable",phase);
|
|
@@ -67,8 +137,8 @@ function safeRefusal(error: unknown, category: PlacementWriterRootCategory,phase
|
|
|
67
137
|
if (error && typeof error === "object" && !types.isProxy(error) && error instanceof PlacementWriterContextError) {
|
|
68
138
|
const fields=Object.getOwnPropertyDescriptors(error),root=fields.category,cause=fields.causeClass,detail=fields.detail;
|
|
69
139
|
const category:unknown=root&&"value"in root?root.value:undefined,causeClass:unknown=cause&&"value"in cause?cause.value:undefined;
|
|
70
|
-
if (typeof category==="string" &&
|
|
71
|
-
&& typeof causeClass==="string" && [
|
|
140
|
+
if (typeof category==="string" && (WRITER_ROOT_CATEGORIES as readonly string[]).includes(category)
|
|
141
|
+
&& typeof causeClass==="string" && (WRITER_CAUSE_CLASSES as readonly string[]).includes(causeClass)) {
|
|
72
142
|
const ownDetail=detail&&"value"in detail&&typeof detail.value==="string"&&Object.hasOwn(failureDetails,detail.value)?detail.value as SyncPlacementWriterFailureDetail:undefined;
|
|
73
143
|
const state=fields.renewalState?.value,target=fields.setupTarget?.value;
|
|
74
144
|
return new PlacementWriterContextError(category as PlacementWriterRootCategory,causeClass as PlacementWriterContextError["causeClass"],phase,ownDetail,state==="staging"||state==="pending"||state==="checkpoint-pending"?state:undefined,
|
|
@@ -133,7 +203,9 @@ export function activePlacementWriterContext(home: string, ownRoot: string): Pla
|
|
|
133
203
|
const read = () => {
|
|
134
204
|
try { requirePlacementHomeFloor(home); } catch (error) { throw safeRefusal(error,"home floor"); }
|
|
135
205
|
let effective: ReturnType<typeof readEffectiveSyncPlacementWriters>;
|
|
136
|
-
try { effective=readEffectiveSyncPlacementWriters(home); }
|
|
206
|
+
try { effective=readEffectiveSyncPlacementWriters(home); }
|
|
207
|
+
// #551: an unreadable writer history proves no category, so it is never reported as a missing or unreadable locator.
|
|
208
|
+
catch (error) { if (unprovenWriterHistory(error)) throw new UnprovenWriterInventory(); throw safeRefusal(error,"active locator"); }
|
|
137
209
|
const roots=effective.roots;if(!roots)return fail("active locator","unavailable");
|
|
138
210
|
const needed = required(home,ownRoot);
|
|
139
211
|
if(!roots.includes(needed.own))return fail("running CLI","missing");
|
|
@@ -190,6 +262,9 @@ export function previewActivePlacementWriters(home: string, ownRoot: string, req
|
|
|
190
262
|
for (const row of measurement.writers) if (!expected.some(value=>value.writerId===row.writerId)) differences.push({writerId:row.writerId,state:"added"});
|
|
191
263
|
const matches=missingCategories.length===0&&differences.every(row=>row.state==="unchanged");
|
|
192
264
|
const changed=measurement.roots.find(row=>{const old=expected.find(value=>value.writerId===row.writerId);return !old||old.pin!==row.pin||old.version!==row.version;});
|
|
193
|
-
const
|
|
194
|
-
|
|
265
|
+
const changedCategory:PlacementWriterRootCategory|undefined=changed?(changed.root===needed.own?"running CLI":needed.receipt.includes(changed.root)?"setup receipt":"declared writer"):undefined;
|
|
266
|
+
// #567 AC4: a complete inventory with no missing category is not a refusal; the first changed root's category is
|
|
267
|
+
// informational `changedCategory`. `refusalCategory` keeps its meaning and appears only when a category is missing.
|
|
268
|
+
return {complete:true,matches,roots:measurement.roots,expected,missingCategories,differences,
|
|
269
|
+
...(missingCategories[0]?{refusalCategory:missingCategories[0]}:{}),...(changedCategory?{changedCategory}:{})};
|
|
195
270
|
}
|
package/src/ui/plugin.ts
CHANGED
|
@@ -282,7 +282,7 @@ export const plugin = {
|
|
|
282
282
|
if (!q) return { q: "", hits: [] };
|
|
283
283
|
return { q, ...(await read(project, "amem_search", { ...args, query: q }) as Args) };
|
|
284
284
|
}
|
|
285
|
-
case "timeline": return { entries: await read(project, "amem_timeline", args) };
|
|
285
|
+
case "timeline": return { entries: await read(project, "amem_timeline", { ...args, expand: true }) }; // #544: the panel lists raw rows; capture-run summaries are for MCP and agent reads.
|
|
286
286
|
case "work": return { lists: await read(project, "amem_work_state_read", args) };
|
|
287
287
|
case "goals": {
|
|
288
288
|
const store = openCuratedForRead(base, project), p = policy();
|