@staix/agent-mem 0.37.0 → 0.39.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.
Files changed (49) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/README.md +1 -1
  3. package/package.json +1 -1
  4. package/src/brief-curated.ts +8 -4
  5. package/src/cli-agent-reads.ts +55 -4
  6. package/src/cli.ts +222 -93
  7. package/src/commands-table.ts +332 -171
  8. package/src/index.ts +5 -0
  9. package/src/memory/capacity-text.ts +100 -0
  10. package/src/memory/capacity.ts +1 -57
  11. package/src/memory/commands.ts +45 -9
  12. package/src/memory/curated-cache-state.ts +22 -3
  13. package/src/memory/doctor-text.ts +144 -0
  14. package/src/memory/doctor.ts +9 -86
  15. package/src/memory/eval-audit-text.ts +62 -0
  16. package/src/memory/eval-audit.ts +1 -34
  17. package/src/memory/eval-text.ts +32 -0
  18. package/src/memory/eval.ts +1 -14
  19. package/src/memory/formats.ts +2 -0
  20. package/src/memory/gc-text.ts +22 -0
  21. package/src/memory/gc.ts +0 -6
  22. package/src/memory/generation-index.ts +1 -1
  23. package/src/memory/index-file.ts +1 -1
  24. package/src/memory/metrics.ts +18 -10
  25. package/src/memory/migrate-text.ts +32 -0
  26. package/src/memory/migrate.ts +0 -29
  27. package/src/memory/prune-text.ts +29 -0
  28. package/src/memory/prune.ts +0 -26
  29. package/src/memory/report-text.ts +233 -0
  30. package/src/memory/shard-migration-text.ts +40 -0
  31. package/src/memory/shard-migration.ts +0 -37
  32. package/src/memory/status-text.ts +72 -29
  33. package/src/memory/store.ts +112 -17
  34. package/src/memory/style.ts +98 -1
  35. package/src/memory/sync-placement-bound.ts +2 -2
  36. package/src/memory/sync-placement-checkpoint-person.ts +1 -1
  37. package/src/memory/sync-placement-noop-cache.ts +93 -0
  38. package/src/memory/sync-placement-refusal-category.ts +18 -0
  39. package/src/memory/sync-placement-transport.ts +43 -7
  40. package/src/memory/sync-progress-text.ts +7 -0
  41. package/src/memory/sync-progress.ts +21 -7
  42. package/src/memory/sync-screen.ts +13 -0
  43. package/src/memory/work-lists.ts +6 -4
  44. package/src/setup-drift.ts +1 -1
  45. package/src/setup-writer-roots.ts +136 -0
  46. package/src/setup.ts +122 -159
  47. package/src/sync-placement-writer-context.ts +8 -3
  48. package/src/ui/plugin.ts +4 -2
  49. package/src/work-brief-preparation.ts +28 -0
package/src/setup.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { installSkills, skillRoot, type SkillInstallReport } from "./skills-install.ts";
2
+ import { Report, cellWidth } from "@staix/cli-output";
2
3
  import { cliAttribution } from "./memory/cli-attribution.ts";
3
4
  import { configuredPolicy } from "./memory/config.ts";
4
5
  import { SETUP_CONFIG_BYTES, updateTomlArray } from "./setup-toml.ts";
@@ -17,16 +18,16 @@ import { dirname, isAbsolute, join, relative, resolve } from "node:path";
17
18
  import { fileURLToPath } from "node:url";
18
19
  import { isDeepStrictEqual, types } from "node:util";
19
20
  import { HOOK_EVENTS } from "./hook-contract.ts";
21
+ import { decodeReceipt, JOURNAL_MAX, readSetupWriterRoots, setupReceiptRemedy, SetupWriterRootsError, SETUP_TARGETS, type Receipt, type SetupTarget } from "./setup-writer-roots.ts";
22
+ export { readSetupWriterRoots, setupReceiptRemedy, SetupWriterRootsError, SETUP_TARGETS, type SetupTarget };
20
23
  import { readEffectiveSyncPlacementWriters } from "./memory/sync-placement-effective-writers.ts";
21
24
  import { placementMarkerState } from "./memory/sync-placement-guard.ts";
22
25
  import { memoryHome } from "./memory/home.ts";
23
- import { label, PLAIN, singleLine, type Style } from "./memory/style.ts";
26
+ import { PLAIN, singleLine, type Style } from "./memory/style.ts";
24
27
  import { canonicalPath, memoryGitEnv, memoryGitSync, processLiveness, processSignature, realPath } from "./memory/platform.ts";
25
28
 
26
- export const SETUP_TARGETS = ["claude", "codex", "kimi", "pi", "qwen", "jcode", "opencode", "gemini", "agy"] as const;
27
29
  /** Workspace-scoped Antigravity setup is always selected explicitly. */
28
30
  export const SETUP_ALL_TARGETS = SETUP_TARGETS.filter(target => target !== "agy");
29
- export type SetupTarget = typeof SETUP_TARGETS[number];
30
31
  // Only recorded layout verification versions belong here; null means no version was recorded.
31
32
  const SETUP_VERIFIED_VERSIONS: Readonly<Record<SetupTarget, string | null>> = {
32
33
  claude: null, codex: "0.165.0", kimi: null, pi: null, qwen: "0.26.1", jcode: "0.99.1", opencode: "1.18.35", gemini: "0.61.0", agy: null,
@@ -37,7 +38,6 @@ type Image = ConfigImage;
37
38
  interface PlannedHook { event: string; command: string; timeout: number }
38
39
  interface Change { key: string; path: string; before: Image; after: Image; start?: Image }
39
40
  interface DirectoryIdentity { dev: number; ino: number }
40
- interface Receipt { createdDirectory?: DirectoryIdentity; version: 1 | 2; target: SetupTarget; intent: string; phase: "prepared" | "applied"; changes: Change[] }
41
41
  export interface SetupContext {
42
42
  env?: Env; bun?: string; entry?: string; stdinTTY?: boolean; cwd?: string;
43
43
  /** `--root`: an absolute amem install root to register instead of the running one (#199). Ignored when `entry` is given. */
@@ -60,7 +60,7 @@ export interface SetupPlan {
60
60
  /** #551, additive: the placement-inventory warning, repeated on the apply receipt so `--apply` shows it too. */
61
61
  placementWriter?: string;
62
62
  }
63
- const MAX = SETUP_CONFIG_BYTES, JOURNAL_MAX = 12 * MAX;
63
+ const MAX = SETUP_CONFIG_BYTES;
64
64
  const digest = (value: unknown) => createHash("sha256").update(JSON.stringify(value)).digest("hex");
65
65
  const quote = (value: string) => "'" + value.replaceAll("'", "'\\''") + "'";
66
66
  function record(value: unknown): Record<string, unknown> {
@@ -216,24 +216,6 @@ function assertOpencodeLayout(c: ReturnType<typeof context>, mode: SetupPlan["mo
216
216
  }
217
217
  function intent(c: ReturnType<typeof context>, target: SetupTarget): string { return digest([1, target, c.paths[target], c.bun, c.entry, ...(["codex", "kimi", "qwen"].includes(target) ? ["capture-json-v1"] : []), ...(target === "jcode" ? ["jcode-hooks-v1"] : []), ...(["claude", "codex", "kimi", "pi", "qwen", "jcode"].includes(target) ? ["root-hooks-v2"] : []), ...(target === "agy" ? [c.workspace!.root] : [])]); }
218
218
  function journal(c: ReturnType<typeof context>, target: SetupTarget): string { return join(c.state, target === "agy" ? `agy-${digest(c.workspace!.root)}.json` : `${target}.json`); }
219
- function decodeReceipt(value: Record<string, unknown>, target: SetupTarget, count: number, strict = false): Receipt {
220
- if (strict && Object.keys(value).some(key => !["version", "target", "intent", "phase", "changes", "createdDirectory"].includes(key))) throw Error("setup receipt invalid");
221
- if (value.version !== 1 && value.version !== 2) throw Error("setup receipt version is unsupported; run setup or undo with the release that wrote it");
222
- if (value.target !== target || typeof value.intent !== "string" || !/^[a-f0-9]{64}$/.test(value.intent) || strict && value.intent.length !== 64 || !["prepared", "applied"].includes(String(value.phase)) || !Array.isArray(value.changes) || value.changes.length !== count && !(target === "jcode" && value.changes.length === 1)) throw Error("setup receipt does not match this installation");
223
- for (let i = 0; i < value.changes.length; i++) {
224
- const change = record(value.changes[i]);
225
- if (change.key !== `${target}:${i}` || strict && (Object.keys(change).some(key => !["key", "path", "before", "after", "start"].includes(key)) || typeof change.path !== "string" || !isAbsolute(change.path) || change.path.length > 4096 || change.path.includes("\0"))) throw Error("setup receipt target mismatch");
226
- for (const key of ["before", "after", ...(change.start !== undefined ? ["start"] : [])]) {
227
- const v = record(change[key]);
228
- if (strict && Object.keys(v).sort().join() !== "bytes,mode" || !Number.isInteger(v.mode) || Number(v.mode) < 0 || Number(v.mode) > 0o777 || v.bytes !== null && (typeof v.bytes !== "string" || v.bytes.length > 2 * MAX || strict && (v.bytes.length > Math.ceil(MAX / 3) * 4 || v.bytes.length / 4 * 3 - (v.bytes.endsWith("==") ? 2 : v.bytes.endsWith("=") ? 1 : 0) > MAX) || Buffer.from(v.bytes, "base64").toString("base64") !== v.bytes)) throw Error("setup receipt invalid");
229
- }
230
- }
231
- if (value.createdDirectory !== undefined) {
232
- const created = record(value.createdDirectory);
233
- if (target !== "agy" || Object.keys(created).sort().join() !== "dev,ino" || !Number.isSafeInteger(created.dev) || Number(created.dev) < 0 || !Number.isSafeInteger(created.ino) || Number(created.ino) <= 0) throw Error("setup receipt directory ownership invalid");
234
- }
235
- return value as unknown as Receipt;
236
- }
237
219
  function receipt(c: ReturnType<typeof context>, target: SetupTarget, requireRuntime = false): Receipt | undefined {
238
220
  const raw = read(journal(c, target), JOURNAL_MAX); if (raw.bytes === null) return;
239
221
  const value = decodeReceipt(record(JSON.parse(Buffer.from(raw.bytes, "base64").toString("utf8"))), target, c.paths[target].length);
@@ -741,152 +723,133 @@ export function undoSetup(plan: SetupPlan, options: SetupContext = {}): { restor
741
723
  return withSetupLock(options, () => undoUnlocked(plan, options));
742
724
  }
743
725
 
744
- /** Person-facing setup plan (#125): each target once, with its effective files, MCP and hook changes, then skipped clients and notes. `--json` keeps the raw plan. */
745
- export function setupPlanText(plan: SetupPlan, s: Style = PLAIN): string {
746
- const verb = plan.mode === "undo" ? "undo" : plan.mode === "apply" ? "apply" : "preview";
747
- // Undo restores every target with a receipt whether or not its CLI is still installed (undoUnlocked), so undo never collapses an action.
748
- const full = (action: SetupPlan["actions"][number]) => plan.mode === "undo" || action.available;
749
- const skipped = plan.actions.filter(action => !full(action)), changing = plan.actions.filter(action => full(action) && action.mcpChange !== "unchanged");
750
- const lines = [`${s.bold(`amem setup ${verb}:`)} ${plan.targets.length} target${plan.targets.length === 1 ? "" : "s"}, ${changing.length} with ${plan.mode === "undo" ? "restores" : "MCP changes"}${skipped.length ? `, ${skipped.length} skipped` : ""}`, ""];
726
+ interface SetupRenderOptions { columns?: number; verbose?: boolean; writerCommands?: readonly string[] }
727
+ type SetupResult = SetupApplyResult | { restored: SetupTarget[]; skills?: SetupSkillResult[] };
728
+
729
+ function setupHookSummary(hooks: SetupPlan["actions"][number]["hooks"]): string {
730
+ const events = hooks.map(hook => hook.event).join(", ");
731
+ if (hooks.length === 1) return `${events}: ${hooks[0]!.command} (timeout ${hooks[0]!.timeout})`;
732
+ const templates = hooks.map(hook => hook.command.endsWith(` ${hook.event}`) ? `${hook.command.slice(0, -hook.event.length)}<event>` : hook.command);
733
+ const first = templates[0];
734
+ return first !== undefined && templates.every(value => value === first) && hooks.every(hook => hook.timeout === hooks[0]!.timeout)
735
+ ? `${events}; ${first} (timeout ${hooks[0]!.timeout})` : `${events}; commands differ (see --verbose or --json)`;
736
+ }
737
+
738
+ /** Human-only shortening; --json retains the exact path and command bytes. */
739
+ function setupDisplay(value: string, columns?: number): string {
740
+ const limit = columns === undefined ? undefined : Math.max(12, columns - 30);
741
+ if (limit === undefined) return singleLine(value);
742
+ return singleLine(value).replace(/\S+/g, token => {
743
+ if (cellWidth(token) <= limit) return token;
744
+ const graphemes = [...new Intl.Segmenter(undefined, { granularity: "grapheme" }).segment(token)].map(item => item.segment);
745
+ let left = "", right = ""; const budget = limit - 3;
746
+ while (graphemes.length && cellWidth(left) < Math.floor(budget / 2)) left += graphemes.shift();
747
+ while (graphemes.length && cellWidth(left + "..." + graphemes.at(-1) + right) <= limit) right = graphemes.pop() + right;
748
+ return left + "..." + right;
749
+ });
750
+ }
751
+
752
+ function setupWriterCommands(plan: SetupPlan): string[] {
753
+ if (!plan.placementWriter) return [];
754
+ try {
755
+ // The plan's receipt uses the same resolved memory home as setup, including HOME-only contexts.
756
+ const receipt = plan.actions[0]?.receipt;
757
+ if (!receipt) return ["amem doctor"];
758
+ const home = dirname(dirname(receipt)), roots = readEffectiveSyncPlacementWriters(home).roots;
759
+ if (!roots) return ["amem doctor"];
760
+ const root = plan.root?.path ?? realPath(fileURLToPath(new URL("..", import.meta.url)));
761
+ const all = [...new Set([...roots, ...readSetupWriterRoots(home), root].map(realPath))].sort();
762
+ if (all.some(value => /[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u.test(value))) return ["amem doctor"];
763
+ const flags = all.map(value => `--writer-root ${quote(value)}`).join(" ");
764
+ return [`amem migrate --sync-placement --dry-run ${flags}`, `amem migrate --sync-placement --apply ${flags}`];
765
+ } catch { return ["amem doctor"]; }
766
+ }
767
+
768
+ function renderSetup(plan: SetupPlan, result: SetupResult | undefined, s: Style, options: SetupRenderOptions = {}): string {
769
+ const report = new Report(options.columns, s.ascii, { keepTokensWhole: true });
770
+ const verb = plan.mode, changed = new Set(result && "applied" in result ? result.applied : result && "restored" in result ? result.restored : plan.actions.filter(action => action.mcpChange !== "unchanged").map(action => action.target));
771
+ const skipped = new Map<SetupTarget, string>(result && "skipped" in result ? result.skipped?.map(row => [row.target, row.reason]) : !result && plan.mode !== "undo" ? plan.actions.filter(action => !action.available).map(action => [action.target, "CLI not installed"]) : []);
772
+ const skills = result?.skills ?? plan.skills ?? [], warnings = plan.notes.filter(note => (note.startsWith("WARNING:") || note.includes("detected:") || note.includes("version-specific") && changed.size > 0) && note !== plan.placementWriter);
773
+ let warningCount = 0;
774
+ const counts = { toChange: 0, applied: 0, unchanged: 0, skipped: 0, restored: 0, nothing: 0 };
775
+ report.header("amem", "Setup"); report.line(`${verb}: ${plan.targets.length} target${plan.targets.length === 1 ? "" : "s"}`);
776
+ if ((plan.mode !== "undo" && plan.placementWriter) || warnings.length) {
777
+ report.section("Attention");
778
+ if (plan.mode !== "undo" && plan.placementWriter) {
779
+ const writerCommands = options.writerCommands ?? ["amem doctor"];
780
+ warningCount++; report.bullet("warn", writerCommands[0] === "amem doctor" ? "The placement writer inventory or its roots could not be verified; check them before renewal." : plan.placementWriter.includes("outside the active") ? "This install root is outside the active placement writer inventory; sync may refuse until it is renewed." : "The active placement writer inventory could not be verified.");
781
+ for (const command of writerCommands) report.next(command);
782
+ }
783
+ const versionWarnings = warnings.filter(note => /layout verified on/.test(note));
784
+ if (versionWarnings.length) { warningCount++; report.bullet("warn", `${versionWarnings.length} client version${versionWarnings.length === 1 ? " differs" : "s differ"} from a verified layout; native validation remains enabled.`); }
785
+ for (const warning of [...new Set(warnings.filter(note => !versionWarnings.includes(note)))]) { warningCount++; report.bullet("warn", setupDisplay(warning.replace(/^WARNING:\s*/, ""), options.columns)); }
786
+ }
751
787
  for (const action of plan.actions) {
752
- if (!full(action)) { lines.push(`${label(s, "skipped")} ${s.bold(action.target)}: CLI not installed`); continue; }
753
- const state = action.mcpChange === "unchanged" ? "ok" : "attention";
754
- const what = action.mcpChange === "unchanged" ? plan.mode === "undo" ? "no setup receipt; nothing to restore" : "already set up; no change" : action.mcpChange === "restore" ? `restore original MCP/hook files${action.available ? "" : " (CLI not installed)"}` : `MCP ${action.mcpChange}`;
755
- lines.push(`${label(s, state)} ${s.bold(action.target)}: ${what} ${s.dim(`(${action.state})`)}`);
756
- if (action.version) {
757
- const reported = action.version.output === null ? "unknown" : action.version.verified && action.version.matches === null ? `unrecognised (${action.version.output})` : action.version.output;
758
- lines.push(` version ${reported}; ${action.version.verified ? `verified ${action.version.verified}` : "unverified (no verified version recorded)"}`);
788
+ report.section(action.target);
789
+ const reason = skipped.get(action.target) ?? (!result && plan.mode !== "undo" && !action.available ? "CLI not installed" : undefined);
790
+ const state = reason ? `skipped: ${reason}` : plan.mode === "undo" && action.mcpChange === "unchanged" ? "no setup receipt; nothing to restore" : result ? changed.has(action.target) ? plan.mode === "undo" ? "restored" : "applied" : "unchanged" : action.mcpChange === "unchanged" ? "unchanged" : `${action.mcpChange}: ${action.state}`;
791
+ const rows: [string, string][] = [["MCP", state]];
792
+ if (!reason) {
793
+ if (action.version) rows.push(["Version", `${action.version.output === null ? "unknown" : action.version.verified && action.version.matches === null ? `unrecognised (${action.version.output})` : action.version.output}; ${action.version.verified ? `verified ${action.version.verified}` : "unverified"}`]);
794
+ if (plan.root) rows.push(["Install", setupDisplay(`${plan.root.path} (amem ${plan.root.version})`, options.columns)]);
795
+ if (action.files.length) rows.push(["Files", action.files.map(file => setupDisplay(file, options.columns)).join(", ")]);
796
+ if (action.cwd) rows.push(["Directory", setupDisplay(action.cwd, options.columns)]);
797
+ rows.push(["Receipt", setupDisplay(action.receipt, options.columns)]);
798
+ if (!result && action.available && action.registration) rows.push(["Command", setupDisplay(action.registration.map(quote).join(" "), options.columns)]);
799
+ if (action.hooks.length) rows.push(["Hooks", setupDisplay(setupHookSummary(action.hooks), options.columns)]);
800
+ for (const removal of action.removes ?? []) rows.push(["Remove", setupDisplay(`${removal.event}: ${removal.command} (in ${removal.file})`, options.columns)]);
759
801
  }
760
- for (const file of action.files) lines.push(` file ${file}`);
761
- if (action.cwd) lines.push(` cwd ${action.cwd}`);
762
- lines.push(` receipt ${action.receipt}`);
763
- if (action.available && action.registration) lines.push(` command ${action.registration.map(quote).join(" ")}`);
764
- for (const hook of action.hooks) lines.push(` hook ${hook.event}: ${hook.command} (timeout ${hook.timeout})`);
765
- for (const row of action.removes ?? []) lines.push(` remove ${row.event}: ${row.command} (an earlier amem install, in ${row.file})`);
766
- if (action.available && !action.hooks.length && plan.mode !== "undo") lines.push(` hook ${s.dim("none")}`);
767
- lines.push(` ${s.dim(action.lifecycle)}`);
802
+ const skill = skills.find(row => row.target === action.target);
803
+ const skillChanged = skill?.report?.actions.some(item => ["install", "replace", "remove"].includes(item.change)) === true;
804
+ if (reason) counts.skipped++;
805
+ else if (plan.mode === "undo") { if (changed.has(action.target) || skillChanged) counts.restored++; else counts.nothing++; }
806
+ else if (result) { if (changed.has(action.target) || skillChanged) counts.applied++; else counts.unchanged++; }
807
+ else if (changed.has(action.target) || skillChanged) counts.toChange++; else counts.unchanged++;
808
+ if (skill?.report) {
809
+ const changedSkills = skill.report.actions.filter(item => item.change !== "unchanged" && item.change !== "absent");
810
+ const unchanged = skill.report.actions.filter(item => item.change === "unchanged").length;
811
+ const summary = [...changedSkills.map(item => `${item.name} ${item.change}`), ...(unchanged ? [`${unchanged} unchanged`] : []), ...(skill.report.linkedFrom ? [`root ${setupDisplay(skill.report.root, options.columns)} (linked from ${setupDisplay(skill.report.linkedFrom, options.columns)})`] : [])];
812
+ rows.push(["Skills", summary.join(", ") || "no changes"]);
813
+ } else if (skill?.reason) rows.push(["Skills", skill.refused ? "refused" : "unavailable"]);
814
+ report.kv(rows);
815
+ if (options.verbose) for (const hook of action.hooks) report.note(singleLine(`${hook.event}: ${hook.command} (timeout ${hook.timeout})`));
816
+ if (skill?.reason) { warningCount++; report.bullet("warn", singleLine(skill.reason)); }
817
+ for (const item of skill?.report?.actions ?? []) if (item.reason) { warningCount++; report.bullet("warn", singleLine(`${item.name}: ${item.reason}`)); }
768
818
  }
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}`);
771
- const warnings = plan.notes.filter(note => /^WARNING|detected|version-specific/.test(note)), notes = plan.notes.filter(note => !warnings.includes(note));
772
- if (skipped.length) lines.push("", `Skipped clients: ${skipped.map(action => action.target).join(", ")} (not installed)`);
773
- if (warnings.length) lines.push("", "Warnings:", ...warnings.map(note => ` - ${s.attention(note)}`));
774
- lines.push("", "Notes:", ...notes.map(note => ` - ${note}`));
775
- if (plan.mode === "preview") lines.push("", `Next: amem setup ${plan.targets.length === 1 ? plan.targets[0] : "all"} --apply writes without a prompt; --json prints the full plan`);
776
- return lines.join("\n");
777
- }
778
-
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");
782
- return [`${label(s, "ok")} applied: ${result.applied.join(", ") || "none"}`, `${label(s, "ok")} unchanged: ${result.unchanged.join(", ") || "none"}`,
783
- ...(result.skipped ?? []).map(item => `${label(s, "skipped")} ${item.target}: ${item.reason}`),
784
- ...(result.warnings ?? []).map(warning => `${label(s, "attention")} ${warning}`), ...skills].join("\n");
819
+ const actionable = plan.actions.some(action => changed.has(action.target) && (plan.mode === "undo" || action.available))
820
+ || skills.some(row => row.report?.actions.some(item => ["install", "replace", "remove"].includes(item.change)));
821
+ const notes = plan.notes.filter(note => note !== plan.placementWriter && !warnings.includes(note));
822
+ const noteTargets: [RegExp, SetupTarget][] = [[/^Codex requires/, "codex"], [/^Qwen capture/, "qwen"], [/^(Jcode setup|Launch Jcode)/, "jcode"], [/^Gemini CLI setup/, "gemini"], [/^OpenCode setup/, "opencode"], [/^Antigravity MCP/, "agy"]];
823
+ const visibleNotes = options.verbose ? notes : notes.filter(note => (plan.mode !== "undo" && noteTargets.some(([pattern, target]) => pattern.test(note) && changed.has(target) && plan.actions.some(action => action.target === target && action.available))) || plan.actions.some(action => changed.has(action.target) && note.startsWith(`${action.target}: `)) || (plan.mode !== "undo" && actionable && note.startsWith("Antigravity is repository-scoped")));
824
+ if (visibleNotes.length) { report.section("Notes"); for (const note of [...new Set(visibleNotes)]) report.note(setupDisplay(note, options.columns)); }
825
+ if (!result && plan.mode === "preview" && actionable) {
826
+ if (plan.root && /[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u.test(plan.root.path)) {
827
+ warningCount++; report.bullet("warn", "The install root contains control characters; inspect it with --json before rerunning setup.");
828
+ } else report.next(`amem setup ${plan.targets.length === 1 ? plan.targets[0] : "all"} --apply${plan.actions.some(action => action.state.includes("apply needs --adopt-current")) ? " --adopt-current" : ""}${plan.root ? ` --root ${quote(plan.root.path)}` : ""}`);
829
+ }
830
+ const outcomes = plan.mode === "undo" ? `${counts.restored} restored, ${counts.nothing} nothing to restore`
831
+ : result ? `${counts.applied} applied, ${counts.unchanged} unchanged, ${counts.skipped} skipped`
832
+ : `${counts.toChange} to change, ${counts.unchanged} unchanged, ${counts.skipped} skipped`;
833
+ report.line("");
834
+ report.line(`Summary: ${outcomes}${warningCount ? `, ${warningCount} warning${warningCount === 1 ? "" : "s"}` : ""}`);
835
+ return report.render(s.color).join("\n");
785
836
  }
786
837
 
838
+ export function setupPlanText(plan: SetupPlan, s: Style = PLAIN, options: SetupRenderOptions = {}): string { return renderSetup(plan, undefined, s, options); }
839
+ function setupResultText(result: SetupResult, s: Style, plan: SetupPlan, options: SetupRenderOptions = {}): string { return renderSetup(plan, result, s, options); }
787
840
  /** Compatibility formatter for confirmation-style callers: the raw plan under `--json`, the readable plan otherwise. */
788
841
  export function setupConfirmationText(plan: SetupPlan, json: boolean, s: Style = PLAIN): string { return json ? JSON.stringify(plan, null, 2) : setupPlanText(plan, s); }
789
842
 
790
- export async function runSetup(target: string, mode: SetupPlan["mode"], options: SetupContext & { json?: boolean; style?: Style } = {}): Promise<string> {
843
+ export async function runSetup(target: string, mode: SetupPlan["mode"], options: SetupContext & { json?: boolean; style?: Style; columns?: number; verbose?: boolean } = {}): Promise<string> {
791
844
  const plan = planSetup(target, mode, options), s = options.json ? PLAIN : options.style ?? PLAIN;
792
- if (cliAttribution()?.actor === "agent" && !configuredPolicy(memoryHome(options.env ?? process.env), options.cwd ?? process.cwd()).screenStandalone(JSON.parse(JSON.stringify(plan)))) throw Error("Memory operation unavailable or refused; no partial result is shown.");
793
- if (mode === "preview") return options.json ? JSON.stringify(plan, null, 2) : setupPlanText(plan, s);
845
+ const renderOptions: SetupRenderOptions = { columns: options.columns, verbose: options.verbose, ...(!options.json && mode !== "undo" && plan.placementWriter ? { writerCommands: setupWriterCommands(plan) } : {}) };
846
+ if (cliAttribution()?.actor === "agent") {
847
+ const policy = configuredPolicy(memoryHome(options.env ?? process.env), options.cwd ?? process.cwd());
848
+ if (!policy.screenStandalone(JSON.parse(JSON.stringify(plan))) || (renderOptions.writerCommands && !policy.screenStandalone(renderOptions.writerCommands))) throw Error("Memory operation unavailable or refused; no partial result is shown.");
849
+ }
850
+ if (mode === "preview") return options.json ? JSON.stringify(plan, null, 2) : setupPlanText(plan, s, renderOptions);
794
851
  const result = mode === "apply" ? applySetup(plan, options) : undoSetup(plan, options);
795
- return options.json ? JSON.stringify(result, null, 2) : setupResultText(result, s);
852
+ return options.json ? JSON.stringify(result, null, 2) : setupResultText(result, s, plan, renderOptions);
796
853
  }
797
854
 
798
855
 
799
- /**
800
- * #520: the fixed remedy for a receipt whose recorded amem install no longer exists, shared by setup, the placement
801
- * sync refusal, doctor and the marked diagnostic. It names the target and both commands, never the recorded path.
802
- */
803
- export function setupReceiptRemedy(target: SetupTarget, applied = false): string {
804
- return `the ${applied ? "applied " : ""}${target} setup receipt names an amem install that no longer exists; run amem setup ${target} --apply to refresh the receipt or amem setup ${target} --undo to remove it`;
805
- }
806
- /**
807
- * Fixed safe category only; receipt text, native paths and external error messages are never diagnostics.
808
- * `target` is set only when an applied receipt names a runtime root whose absence was positively identified, so the
809
- * refusal can name the setup target and its remedy without exposing the recorded path (#520).
810
- */
811
- export class SetupWriterRootsError extends Error {
812
- readonly code = "setup_writer_roots_unavailable";
813
- constructor(readonly category: "unsafe" | "changed" | "bound" | "unsupported" | "pending" | "unavailable", readonly target?: SetupTarget) {
814
- super(target
815
- ? `Setup writer inventory: ${setupReceiptRemedy(target, true)}.`
816
- : `Setup writer inventory ${category}; inspect setup receipts and rerun setup before activation.`);
817
- this.name = "SetupWriterRootsError";
818
- }
819
- }
820
- /** Current managed MCP AFTER images only. Native configuration paths and historical BEFORE/START images are never opened. */
821
- export function readSetupWriterRoots(home: string): string[] {
822
- function fail(category: SetupWriterRootsError["category"], target?: SetupTarget): never { throw new SetupWriterRootsError(category, target); }
823
- try {
824
- const owned = (stat: BigIntStats) => { if (stat.isSymbolicLink() || stat.uid !== BigInt(process.getuid?.() ?? -1) || (stat.mode & 0o077n) !== 0n) fail("unsafe"); };
825
- const stamp = (stat: BigIntStats) => JSON.stringify([stat.dev, stat.ino, stat.uid, stat.mode, stat.nlink, stat.size, stat.mtimeNs, stat.ctimeNs].map(String));
826
- const base = lstatSync(home, { bigint: true, throwIfNoEntry: false }); if (!base) return []; owned(base); if (!base.isDirectory()) fail("unsafe");
827
- const directory = join(home, "setup"), initial = lstatSync(directory, { bigint: true, throwIfNoEntry: false });
828
- if (!initial) return [];
829
- owned(initial); if (!initial.isDirectory()) fail("unsafe");
830
- // ponytail:256 setup namespace entries and doctor's existing32MiB aggregate receipt-byte ceiling.
831
- // A reviewed metadata-only setup inventory is required before increasing either ceiling.
832
- const files: { name: string; stat: BigIntStats }[] = [], namespace: string[] = [], iterator = opendirSync(directory);
833
- let entries = 0, totalBytes = 0;
834
- try { for (;;) {
835
- const entry = iterator.readSync(); if (!entry) break;
836
- namespace.push(entry.name);
837
- if (++entries > 256) fail("bound"); if (entry.name === "setup.lock") fail("pending");
838
- if (!entry.name.endsWith(".json")) continue; // Retained .json.stale-* and unregistered temps are historical, never current authority.
839
- const stat = lstatSync(join(directory, entry.name), { bigint: true }); owned(stat); if (!stat.isFile() || stat.nlink !== 1n) fail("unsafe");
840
- if (stat.size > BigInt(JOURNAL_MAX) || totalBytes + Number(stat.size) > 32 * 1024 * 1024) fail("bound");
841
- totalBytes += Number(stat.size); files.push({ name: entry.name, stat });
842
- } } finally { iterator.closeSync(); }
843
- const roots = new Set<string>(), launchers: { entry: string; root: string }[] = [];
844
- for (const file of files.sort((a, b) => a.name.localeCompare(b.name))) {
845
- const target = (file.name.startsWith("agy-") && /^agy-[a-f0-9]{64}\.json$/.test(file.name) ? "agy" : file.name.slice(0, -5)) as SetupTarget;
846
- if (!SETUP_TARGETS.includes(target) || target === "agy" && !/^agy-[a-f0-9]{64}\.json$/.test(file.name)) fail("unsupported");
847
- const path = join(directory, file.name), fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
848
- let text: string;
849
- try {
850
- const opened = fstatSync(fd, { bigint: true }); owned(opened); if (!opened.isFile() || opened.nlink !== 1n || stamp(opened) !== stamp(file.stat)) fail("changed");
851
- const data = Buffer.alloc(Number(opened.size) + 1); let count = 0;
852
- while (count < data.length) { const n = readSync(fd, data, count, data.length - count, count); if (!n) break; count += n; }
853
- if (count !== Number(opened.size) || stamp(fstatSync(fd, { bigint: true })) !== stamp(opened) || stamp(lstatSync(path, { bigint: true })) !== stamp(opened)) fail("changed");
854
- text = new TextDecoder("utf-8", { fatal: true }).decode(data.subarray(0, count));
855
- } finally { closeSync(fd); }
856
- const counts: Record<SetupTarget, number> = { claude: 2, codex: 2, kimi: 2, pi: 2, qwen: 1, jcode: 2, opencode: 1, gemini: 1, agy: 1 };
857
- let value: Receipt;
858
- try { value = decodeReceipt(record(JSON.parse(text)), target, counts[target], true); } catch { return fail("unsupported"); }
859
- if (value.phase !== "applied") fail("pending");
860
- const runtime = mcpLauncher(mcpRecord(target, value.changes[0]!.after), target);
861
- if (!runtime || runtime.bun.includes("\0") || runtime.entry.length > 4096 || runtime.entry.includes("\0") || !["/bin/amem.js", "/src/cli.ts"].some(suffix => runtime.entry.endsWith(suffix))
862
- || target === "opencode" && [runtime.bun, runtime.entry].some(value => /\{(?:env|file):/.test(value))) fail("unsupported");
863
- // #520: only a positively identified ENOENT/ENOTDIR for the recorded root names its setup target; a non-directory,
864
- // a permission error and every other unreadable state stay anonymous.
865
- let root: string;
866
- try { root = realPath(dirname(dirname(runtime.entry))); }
867
- catch (error) {
868
- const code = (error as NodeJS.ErrnoException).code;
869
- if (code === "ENOENT" || code === "ENOTDIR") fail("unavailable", target);
870
- fail("unavailable");
871
- }
872
- if (!lstatSync(root, { throwIfNoEntry: false })?.isDirectory()) fail("unavailable");
873
- roots.add(root); launchers.push({ entry: runtime.entry, root });
874
- }
875
- const finalHome = lstatSync(home, { bigint: true }); owned(finalHome);
876
- if (!finalHome.isDirectory() || stamp(lstatSync(directory, { bigint: true })) !== stamp(initial) || finalHome.dev !== base.dev || finalHome.ino !== base.ino) fail("changed");
877
- const finalNames: string[] = [], finalDirectory = opendirSync(directory);
878
- try { for (;;) { const entry = finalDirectory.readSync(); if (!entry) break; if (finalNames.length >= namespace.length) fail("changed"); finalNames.push(entry.name); } }
879
- finally { finalDirectory.closeSync(); }
880
- if (JSON.stringify(finalNames.sort()) !== JSON.stringify(namespace.sort())) fail("changed");
881
- for (const file of files) if (stamp(lstatSync(join(directory, file.name), { bigint: true })) !== stamp(file.stat)) fail("changed");
882
- for (const runtime of launchers) if (realPath(dirname(dirname(runtime.entry))) !== runtime.root) fail("changed");
883
- return [...roots].sort();
884
- } catch (error) {
885
- if (error && typeof error === "object" && !types.isProxy(error) && error instanceof SetupWriterRootsError) {
886
- const category = Object.getOwnPropertyDescriptor(error, "category"), target = Object.getOwnPropertyDescriptor(error, "target")?.value;
887
- if (category && "value" in category && ["unsafe", "changed", "bound", "unsupported", "pending", "unavailable"].includes(category.value))
888
- throw new SetupWriterRootsError(category.value, typeof target === "string" && (SETUP_TARGETS as readonly string[]).includes(target) ? target as SetupTarget : undefined);
889
- }
890
- throw new SetupWriterRootsError("unavailable");
891
- }
892
- }
@@ -3,7 +3,7 @@ import { types } from "node:util";
3
3
  import { fileURLToPath } from "node:url";
4
4
  import { canonicalPath, realPath } from "./memory/platform.ts";
5
5
  import { canonicalJSON } from "./memory/generation.ts";
6
- import { readSetupWriterRoots, SETUP_TARGETS, setupReceiptRemedy, SetupWriterRootsError, type SetupTarget } from "./setup.ts";
6
+ import { readSetupWriterRoots, SETUP_TARGETS, setupReceiptRemedy, SetupWriterRootsError, type SetupTarget } from "./setup-writer-roots.ts";
7
7
  import { placementMarkerState } from "./memory/sync-placement-guard.ts";
8
8
  import { measureSyncPlacementWriters, extractSyncPlacementWriterFailure, type SyncPlacementWriterFailureDetail, type SyncPlacementWriterMeasurement } from "./memory/sync-placement-writers.ts";
9
9
  import { readEffectiveSyncPlacementWriters } from "./memory/sync-placement-effective-writers.ts";
@@ -12,6 +12,7 @@ import { FormatFloorError } from "./memory/formats.ts";
12
12
  import type { PlacementCapturePort } from "./memory/sync-placement-capture.ts";
13
13
  import { SharedWriterRevisionError } from "./memory/sync-placement-writer-revision-format.ts";
14
14
 
15
+ import { WRITER_CAUSE_CLASSES, WRITER_ROOT_CATEGORIES, type PlacementWriterRefusal } from "./memory/sync-placement-refusal-category.ts";
15
16
  export type PlacementWriterRootCategory = "running CLI" | "host package" | "setup receipt" | "declared writer" | "active locator" | "home floor" | "writer renewal";
16
17
  export type PlacementWriterContextPhase = "initial" | "active";
17
18
  const failureDetails:Record<SyncPlacementWriterFailureDetail,string>={
@@ -69,8 +70,6 @@ function setupReceiptRefusal(error: unknown): { target: SetupTarget; phase: Plac
69
70
  return { target: target as SetupTarget, phase: fields.phase?.value === "initial" ? "initial" : "active",
70
71
  ...(typeof detail === "string" && Object.hasOwn(failureDetails, detail) ? { detail: detail as SyncPlacementWriterFailureDetail } : {}) };
71
72
  }
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
73
  /**
75
74
  * #551 AC1: the refusal as fixed own data for a person-facing surface. A real PlacementWriterContextError - or the one a
76
75
  * later sync failure carries as `placementRefusal` - is rebuilt from its own validated fields, so a tampered message, a
@@ -94,6 +93,12 @@ function placementWriterRefusal(error: unknown): PlacementWriterContextError | u
94
93
  state === "staging" || state === "pending" || state === "checkpoint-pending" ? state : undefined,
95
94
  typeof target === "string" && (SETUP_TARGETS as readonly string[]).includes(target) ? target as SetupTarget : undefined);
96
95
  }
96
+ /** Closed data projection for progress telemetry. Shaped errors from other module copies do not qualify. */
97
+ export function placementWriterRefusalDetail(error: unknown): PlacementWriterRefusal | undefined {
98
+ const refusal = placementWriterRefusal(error);
99
+ return refusal && { causeClass: refusal.causeClass, rootCategory: refusal.category };
100
+ }
101
+
97
102
  /** #551: no category is claimed here, because the state could not be read far enough to name one. */
98
103
  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
104
  /** An inventory state that could not be proven: never reported as a missing root, and never given an invented category. */
package/src/ui/plugin.ts CHANGED
@@ -25,12 +25,14 @@ import { catalogKeys, readCatalogFresh } from "../memory/catalog.ts";
25
25
  import { configuredPolicy, configuredPolicyOptions } from "../memory/config.ts";
26
26
  import { openCuratedForRead, requireShard } from "../memory/curated-read.ts";
27
27
  import { applyDecay, assertExactDecayForget, decayPreview, DECAY_DEFAULT_DAYS, readDecayCounters } from "../memory/decay-review.ts";
28
- import { gcText, planGc, runGc } from "../memory/gc.ts";
28
+ import { planGc, runGc } from "../memory/gc.ts";
29
+ import { gcText } from "../memory/gc-text.ts";
29
30
  import { memoryHome } from "../memory/home.ts";
30
31
  import { appendLifecycle, assertProjectActive, projectState } from "../memory/lifecycle.ts";
31
32
  import { hasFailLabel, noteAdd, parseFailTemplate } from "../memory/note-add.ts";
32
33
  import type { StandalonePolicy } from "../memory/policy.ts";
33
- import { applyPrune, planPrune, pruneText } from "../memory/prune.ts";
34
+ import { applyPrune, planPrune } from "../memory/prune.ts";
35
+ import { pruneText } from "../memory/prune-text.ts";
34
36
  import { aliasedKeys, PlacementRealmRefusal, placementRealmGap, placementRealmView, readShardedSelection, resolveAlias, type PlacementRealmGap, type PlacementRealmView } from "../memory/shard.ts";
35
37
  import { machineId, MemoryStore, openShardStore, type StoreOptions, type View } from "../memory/store.ts";
36
38
 
@@ -0,0 +1,28 @@
1
+ import { existsSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { readWorkBrief, workLogSegments, workPolicyRevision } from "./brief-work.ts";
4
+ import { configuredPolicyOptions } from "./memory/config.ts";
5
+ import { machineId } from "./memory/machine.ts";
6
+ import { recordBriefPublicationFailure } from "./memory/metrics.ts";
7
+ import { aliasedKeys, resolveAlias, shardDir } from "./memory/shard.ts";
8
+ import { WorkListStore } from "./memory/work-lists.ts";
9
+
10
+ /** Explicit off-hook preparation for existing work logs, including logs written before snapshots existed. */
11
+ export async function prepareWorkBriefCache(base: string, project: string, cwd: string): Promise<void> {
12
+ try {
13
+ const canonical = resolveAlias(base, project), aliases = aliasedKeys(base, canonical);
14
+ if (![canonical, ...aliases].some(key => existsSync(join(shardDir(base, key), "work", "log")))) return;
15
+ const segments = workLogSegments(base, canonical, aliases);
16
+ if (!segments) return recordBriefPublicationFailure(base, "work", "source_unavailable");
17
+ const machine = machineId(base).id, policyOptions = () => configuredPolicyOptions(base, cwd);
18
+ const homeRevision = workPolicyRevision(configuredPolicyOptions(base)), effectiveRevision = workPolicyRevision(policyOptions());
19
+ const current = (policy: string, revision?: string) => {
20
+ const brief = readWorkBrief({ base, project: canonical, machine, revision });
21
+ return brief?.policy === policy && JSON.stringify(brief.segments) === JSON.stringify(segments);
22
+ };
23
+ if (current(homeRevision) && (homeRevision === effectiveRevision || current(effectiveRevision, effectiveRevision))) return;
24
+ const store = new WorkListStore({ base, project: canonical, aliases, policy: () => false, briefPolicyOptions: policyOptions });
25
+ try { await store.publishBrief(); }
26
+ finally { store.close(); }
27
+ } catch { recordBriefPublicationFailure(base, "work", "source_unavailable"); }
28
+ }