@staix/agent-mem 0.34.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/src/setup.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { installSkills, skillRoot, type SkillInstallReport } from "./skills-install.ts";
1
2
  import { cliAttribution } from "./memory/cli-attribution.ts";
2
3
  import { configuredPolicy } from "./memory/config.ts";
3
4
  import { SETUP_CONFIG_BYTES, updateTomlArray } from "./setup-toml.ts";
@@ -50,7 +51,9 @@ export interface SetupContext {
50
51
  /** Trusted test seam; production always runs the named native CLI in a private staging HOME. */
51
52
  native?: (argv: readonly string[], env: Env, cwd: string) => void;
52
53
  }
54
+ export type SetupSkillResult = { target: SetupTarget; report?: SkillInstallReport; reason?: string; refused?: boolean };
53
55
  export interface SetupPlan {
56
+ skills?: SetupSkillResult[];
54
57
  targets: SetupTarget[]; mode: "preview" | "apply" | "undo"; root?: InstallRoot;
55
58
  actions: { target: SetupTarget; version?: ClientVersion; files: string[]; receipt: string; cwd?: string; registration: string[] | null; lifecycle: string; available: boolean; hooks: PlannedHook[]; removes?: { file: string; event: string; command: string }[]; mcpChange: "add" | "replace" | "restore" | "unchanged"; commands: string[][]; state: string }[];
56
59
  notes: string[];
@@ -319,7 +322,8 @@ export function planSetup(target: string, mode: SetupPlan["mode"] = "preview", o
319
322
  if (placementWriter) pluginNotes.push(placementWriter);
320
323
  if (target === "all") pluginNotes.push("Antigravity is repository-scoped and excluded from all; run amem setup agy explicitly inside its repository.");
321
324
  if (targets.includes("jcode")) pluginNotes.push("Launch Jcode with JCODE_DISABLE_CLAUDE_MCP=1 and without a same-name project override: imported Claude stdio entries can replace this private amem binding with a shared daemon-cwd server. Use a new workspace-bound session when changing projects.");
322
- return { targets, mode, ...(c.root ? { root: c.root } : {}), ...(placementWriter ? { placementWriter } : {}), actions: targets.map(target => {
325
+ const skills = mode === "undo" ? [] : skillResults(c, targets.filter(target => available(c, target, options)), "preview", mode);
326
+ return { targets, mode, ...(skills.length ? { skills } : {}), ...(c.root ? { root: c.root } : {}), ...(placementWriter ? { placementWriter } : {}), actions: targets.map(target => {
323
327
  const receipted = receipt(c, target, false), files = mode === "undo" && receipted ? receipted.changes.map(change => change.path) : c.paths[target];
324
328
  for (const file of files) read(file);
325
329
  const stale = mode !== "undo" && !!receipted && staleReceipt(target, receipted);
@@ -628,7 +632,21 @@ function prepare(c: ReturnType<typeof context>, target: SetupTarget, options: Se
628
632
  }
629
633
  function save(c: ReturnType<typeof context>, value: Receipt): void { write(journal(c, value.target), image(JSON.stringify(value) + "\n")); }
630
634
  function available(c: ReturnType<typeof context>, target: SetupTarget, options: SetupContext): boolean { return target === "agy" || !!options.native || Bun.which(target, { PATH: c.env.PATH ?? process.env.PATH }) !== null; }
631
- export interface SetupApplyResult { applied: SetupTarget[]; unchanged: SetupTarget[]; skipped?: { target: SetupTarget; reason: string }[]; warnings?: string[] }
635
+ export interface SetupApplyResult { skills?: SetupSkillResult[]; applied: SetupTarget[]; unchanged: SetupTarget[]; skipped?: { target: SetupTarget; reason: string }[]; warnings?: string[] }
636
+ function skillResults(c: ReturnType<typeof context>, targets: SetupTarget[], mode: "preview" | "apply" | "undo", requested: SetupPlan["mode"] = mode, prior?: SetupSkillResult[]): SetupSkillResult[] {
637
+ return targets.flatMap((target): SetupSkillResult[] => {
638
+ const retry = `amem setup ${target} ${requested === "undo" ? "--undo" : "--apply"}${requested !== "undo" && c.root ? ` --root ${quote(c.root.path)}` : ""}`;
639
+ try {
640
+ const root = skillRoot(target, c.env, c.home);
641
+ if (!root) return [];
642
+ const planned = prior?.find(row => row.target === target)?.report;
643
+ if (mode === "apply" && planned?.actions.every(action => action.change === "refused")) return [{ target, report: planned }];
644
+ const expected = mode === "apply" && planned ? { root: planned.root, ...(planned.linkedFrom ? { linkedFrom: planned.linkedFrom } : {}) } : undefined;
645
+ return [{ target, report: installSkills(root, mode, c.root?.path, c.root?.version, retry, c.env, expected) }];
646
+ }
647
+ catch (error) { return [{ target, refused: true, reason: `${error instanceof Error ? error.message : String(error)}; inspect and retry ${retry}` }]; }
648
+ });
649
+ }
632
650
  /** Claim only a directory this invocation actually created, never one merely absent at preview. */
633
651
  function prepareCreatedDirectory(c: ReturnType<typeof context>, value: Receipt): void {
634
652
  if (value.target !== "agy") return;
@@ -677,15 +695,17 @@ function applyUnlocked(plan: SetupPlan, options: SetupContext = {}): SetupApplyR
677
695
  for (let i = 0; i < value.changes.length; i++) { const change = value.changes[i]!; if (!sameImage(item.expected[i]!, change.after)) write(change.path, change.after, item.expected[i]!, publishGuard(c, value.target, options)); }
678
696
  value.phase = "applied"; save(c, value); applied.push(value.target);
679
697
  }
680
- return { applied, unchanged, ...(skipped.length ? { skipped } : {}) };
698
+ const skills = skillResults(c, targets, "apply", "apply", plan.skills);
699
+ return { applied, unchanged, ...(skills.length ? { skills } : {}), ...(skipped.length ? { skipped } : {}) };
681
700
  }
682
701
  /** Byte-exact for untouched files, otherwise remove/restore only this installer's owned entries. */
683
- function undoUnlocked(plan: SetupPlan, options: SetupContext = {}): { restored: SetupTarget[] } {
702
+ function undoUnlocked(plan: SetupPlan, options: SetupContext = {}): { restored: SetupTarget[]; skills?: SetupSkillResult[] } {
684
703
  const c = contextForPlan(plan, options), receipts = plan.targets.map(target => receipt(c, target, false)).filter((value): value is Receipt => !!value);
685
704
  const pending = receipts.map(value => ({ value, files: value.changes.map((change, index) => { const expected = read(change.path); return { change, expected, restored: restoreChange(value, change, index, expected) }; }) }));
686
705
  for (const item of pending) for (const file of item.files) if (!sameImage(read(file.change.path), file.expected)) throw Error("setup configuration changed during undo preparation");
687
706
  for (const item of pending) { if (item.value.target === "agy") c.workspace!.assertCurrent(); for (const file of item.files) if (!sameImage(file.expected, file.restored)) write(file.change.path, file.restored, file.expected, publishGuard(c, item.value.target, options)); removeCreatedDirectory(c, item.value); rmSync(journal(c, item.value.target)); }
688
- return { restored: receipts.map(value => value.target) };
707
+ const skills = skillResults(c, plan.targets, "undo");
708
+ return { restored: receipts.map(value => value.target), ...(skills.length ? { skills } : {}) };
689
709
  }
690
710
 
691
711
  function withSetupLock<T>(options: SetupContext, run: () => T): T {
@@ -715,7 +735,7 @@ export function applySetup(plan: SetupPlan, options: SetupContext = {}): SetupAp
715
735
  // #551 AC2: `--apply` prints only this result, so the plan's placement warning is repeated on the receipt.
716
736
  return plan.placementWriter ? { ...result, warnings: [plan.placementWriter] } : result;
717
737
  }
718
- export function undoSetup(plan: SetupPlan, options: SetupContext = {}): { restored: SetupTarget[] } {
738
+ export function undoSetup(plan: SetupPlan, options: SetupContext = {}): { restored: SetupTarget[]; skills?: SetupSkillResult[] } {
719
739
  if (plan.targets.includes("jcode")) assertJcodeHome(options.env ?? process.env);
720
740
  if (plan.targets.includes("agy")) contextForPlan(plan, options);
721
741
  return withSetupLock(options, () => undoUnlocked(plan, options));
@@ -746,6 +766,8 @@ export function setupPlanText(plan: SetupPlan, s: Style = PLAIN): string {
746
766
  if (action.available && !action.hooks.length && plan.mode !== "undo") lines.push(` hook ${s.dim("none")}`);
747
767
  lines.push(` ${s.dim(action.lifecycle)}`);
748
768
  }
769
+ for (const row of plan.skills ?? []) for (const action of row.report?.actions ?? []) lines.push(` skill ${row.target}: ${action.name} ${action.change} ${action.path}${row.report?.linkedFrom ? ` (linked from ${row.report.linkedFrom})` : ""}${action.reason ? `: ${action.reason}` : ""}`);
770
+ for (const row of plan.skills ?? []) if (row.reason) lines.push(` skill ${row.target}: ${row.reason}`);
749
771
  const warnings = plan.notes.filter(note => /^WARNING|detected|version-specific/.test(note)), notes = plan.notes.filter(note => !warnings.includes(note));
750
772
  if (skipped.length) lines.push("", `Skipped clients: ${skipped.map(action => action.target).join(", ")} (not installed)`);
751
773
  if (warnings.length) lines.push("", "Warnings:", ...warnings.map(note => ` - ${s.attention(note)}`));
@@ -754,11 +776,12 @@ export function setupPlanText(plan: SetupPlan, s: Style = PLAIN): string {
754
776
  return lines.join("\n");
755
777
  }
756
778
 
757
- function setupResultText(result: SetupApplyResult | { restored: SetupTarget[] }, s: Style): string {
758
- if ("restored" in result) return `${label(s, "ok")} restored: ${result.restored.join(", ") || "none"}`;
779
+ function setupResultText(result: SetupApplyResult | { restored: SetupTarget[]; skills?: SetupSkillResult[] }, s: Style): string {
780
+ const skills = (result.skills ?? []).flatMap(row => [...(row.reason ? [`skill ${row.target}: ${row.reason}`] : []), ...(row.report?.actions ?? []).map(a => `skill ${row.target}: ${a.name} ${a.change} ${a.path}${row.report?.linkedFrom ? ` (linked from ${row.report.linkedFrom})` : ""}${a.reason ? `: ${a.reason}` : ""}`)]);
781
+ if ("restored" in result) return [`${label(s, "ok")} restored: ${result.restored.join(", ") || "none"}`, ...skills].join("\n");
759
782
  return [`${label(s, "ok")} applied: ${result.applied.join(", ") || "none"}`, `${label(s, "ok")} unchanged: ${result.unchanged.join(", ") || "none"}`,
760
783
  ...(result.skipped ?? []).map(item => `${label(s, "skipped")} ${item.target}: ${item.reason}`),
761
- ...(result.warnings ?? []).map(warning => `${label(s, "attention")} ${warning}`)].join("\n");
784
+ ...(result.warnings ?? []).map(warning => `${label(s, "attention")} ${warning}`), ...skills].join("\n");
762
785
  }
763
786
 
764
787
  /** Compatibility formatter for confirmation-style callers: the raw plan under `--json`, the readable plan otherwise. */
@@ -790,7 +813,7 @@ export class SetupWriterRootsError extends Error {
790
813
  constructor(readonly category: "unsafe" | "changed" | "bound" | "unsupported" | "pending" | "unavailable", readonly target?: SetupTarget) {
791
814
  super(target
792
815
  ? `Setup writer inventory: ${setupReceiptRemedy(target, true)}.`
793
- : `Setup writer inventory ${category}; have the person inspect setup receipts and rerun setup before activation.`);
816
+ : `Setup writer inventory ${category}; inspect setup receipts and rerun setup before activation.`);
794
817
  this.name = "SetupWriterRootsError";
795
818
  }
796
819
  }
@@ -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
+ }
@@ -23,8 +23,8 @@ function writerContextMessage(category:PlacementWriterRootCategory,causeClass:"m
23
23
  // #551 AC1: the shared revision text names neither this category nor its cause class, so both are printed here and the
24
24
  // shared text (which carries its own remedy) follows. The checkpoint message is still reproduced verbatim, never replaced.
25
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); have the person 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); have the person inspect formats.json and use a reader compatible with its recorded floor, then run amem migrate --sync-placement --dry-run.`;
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.`;
28
28
  const cause=detail?`; ${failureDetails[detail]}`:"";
29
29
  // #520: a receipt whose recorded install root is gone names its target and remedy, never the recorded path. #551 keeps that
30
30
  // sentence - its cause marker, its remedy and its next step - behind the fixed category and cause class, so both surfaces
@@ -32,7 +32,7 @@ function writerContextMessage(category:PlacementWriterRootCategory,causeClass:"m
32
32
  const receipt=category==="setup receipt"&&setupTarget?setupReceiptRemedy(setupTarget):undefined;
33
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.`;
34
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 have the person run amem migrate --sync-placement --dry-run and --apply with the complete --writer-root inventory after installing the required 0.22.0 home floor.`;
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.`;
36
36
  }
37
37
  export class PlacementWriterContextError extends Error {
38
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) {
@@ -95,7 +95,7 @@ function placementWriterRefusal(error: unknown): PlacementWriterContextError | u
95
95
  typeof target === "string" && (SETUP_TARGETS as readonly string[]).includes(target) ? target as SetupTarget : undefined);
96
96
  }
97
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; have the person inspect the home with a compatible release, then run amem migrate --sync-placement --dry-run.";
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
99
  /** An inventory state that could not be proven: never reported as a missing root, and never given an invented category. */
100
100
  class UnprovenWriterInventory extends Error { constructor(){ super(PLACEMENT_WRITER_UNVERIFIED_TEXT); this.name="UnprovenWriterInventory"; } }
101
101
  /** A shared writer-history code outside the three renewal states: `safeRefusal` would otherwise assert the locator category for it. */
@@ -262,6 +262,9 @@ export function previewActivePlacementWriters(home: string, ownRoot: string, req
262
262
  for (const row of measurement.writers) if (!expected.some(value=>value.writerId===row.writerId)) differences.push({writerId:row.writerId,state:"added"});
263
263
  const matches=missingCategories.length===0&&differences.every(row=>row.state==="unchanged");
264
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;});
265
- const refusalCategory:PlacementWriterRootCategory=missingCategories[0]??(changed?.root===needed.own?"running CLI":changed&&needed.receipt.includes(changed.root)?"setup receipt":"declared writer");
266
- return {complete:true,matches,roots:measurement.roots,expected,missingCategories,differences,refusalCategory};
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}:{})};
267
270
  }