@staix/agent-mem 0.37.0 → 0.38.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,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";
@@ -20,7 +21,7 @@ import { HOOK_EVENTS } from "./hook-contract.ts";
20
21
  import { readEffectiveSyncPlacementWriters } from "./memory/sync-placement-effective-writers.ts";
21
22
  import { placementMarkerState } from "./memory/sync-placement-guard.ts";
22
23
  import { memoryHome } from "./memory/home.ts";
23
- import { label, PLAIN, singleLine, type Style } from "./memory/style.ts";
24
+ import { PLAIN, singleLine, type Style } from "./memory/style.ts";
24
25
  import { canonicalPath, memoryGitEnv, memoryGitSync, processLiveness, processSignature, realPath } from "./memory/platform.ts";
25
26
 
26
27
  export const SETUP_TARGETS = ["claude", "codex", "kimi", "pi", "qwen", "jcode", "opencode", "gemini", "agy"] as const;
@@ -741,58 +742,133 @@ export function undoSetup(plan: SetupPlan, options: SetupContext = {}): { restor
741
742
  return withSetupLock(options, () => undoUnlocked(plan, options));
742
743
  }
743
744
 
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` : ""}`, ""];
745
+ interface SetupRenderOptions { columns?: number; verbose?: boolean; writerCommands?: readonly string[] }
746
+ type SetupResult = SetupApplyResult | { restored: SetupTarget[]; skills?: SetupSkillResult[] };
747
+
748
+ function setupHookSummary(hooks: SetupPlan["actions"][number]["hooks"]): string {
749
+ const events = hooks.map(hook => hook.event).join(", ");
750
+ if (hooks.length === 1) return `${events}: ${hooks[0]!.command} (timeout ${hooks[0]!.timeout})`;
751
+ const templates = hooks.map(hook => hook.command.endsWith(` ${hook.event}`) ? `${hook.command.slice(0, -hook.event.length)}<event>` : hook.command);
752
+ const first = templates[0];
753
+ return first !== undefined && templates.every(value => value === first) && hooks.every(hook => hook.timeout === hooks[0]!.timeout)
754
+ ? `${events}; ${first} (timeout ${hooks[0]!.timeout})` : `${events}; commands differ (see --verbose or --json)`;
755
+ }
756
+
757
+ /** Human-only shortening; --json retains the exact path and command bytes. */
758
+ function setupDisplay(value: string, columns?: number): string {
759
+ const limit = columns === undefined ? undefined : Math.max(12, columns - 30);
760
+ if (limit === undefined) return singleLine(value);
761
+ return singleLine(value).replace(/\S+/g, token => {
762
+ if (cellWidth(token) <= limit) return token;
763
+ const graphemes = [...new Intl.Segmenter(undefined, { granularity: "grapheme" }).segment(token)].map(item => item.segment);
764
+ let left = "", right = ""; const budget = limit - 3;
765
+ while (graphemes.length && cellWidth(left) < Math.floor(budget / 2)) left += graphemes.shift();
766
+ while (graphemes.length && cellWidth(left + "..." + graphemes.at(-1) + right) <= limit) right = graphemes.pop() + right;
767
+ return left + "..." + right;
768
+ });
769
+ }
770
+
771
+ function setupWriterCommands(plan: SetupPlan): string[] {
772
+ if (!plan.placementWriter) return [];
773
+ try {
774
+ // The plan's receipt uses the same resolved memory home as setup, including HOME-only contexts.
775
+ const receipt = plan.actions[0]?.receipt;
776
+ if (!receipt) return ["amem doctor"];
777
+ const home = dirname(dirname(receipt)), roots = readEffectiveSyncPlacementWriters(home).roots;
778
+ if (!roots) return ["amem doctor"];
779
+ const root = plan.root?.path ?? realPath(fileURLToPath(new URL("..", import.meta.url)));
780
+ const all = [...new Set([...roots, ...readSetupWriterRoots(home), root].map(realPath))].sort();
781
+ if (all.some(value => /[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u.test(value))) return ["amem doctor"];
782
+ const flags = all.map(value => `--writer-root ${quote(value)}`).join(" ");
783
+ return [`amem migrate --sync-placement --dry-run ${flags}`, `amem migrate --sync-placement --apply ${flags}`];
784
+ } catch { return ["amem doctor"]; }
785
+ }
786
+
787
+ function renderSetup(plan: SetupPlan, result: SetupResult | undefined, s: Style, options: SetupRenderOptions = {}): string {
788
+ const report = new Report(options.columns, s.ascii, { keepTokensWhole: true });
789
+ 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));
790
+ 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"]) : []);
791
+ 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);
792
+ let warningCount = 0;
793
+ const counts = { toChange: 0, applied: 0, unchanged: 0, skipped: 0, restored: 0, nothing: 0 };
794
+ report.header("amem", "Setup"); report.line(`${verb}: ${plan.targets.length} target${plan.targets.length === 1 ? "" : "s"}`);
795
+ if ((plan.mode !== "undo" && plan.placementWriter) || warnings.length) {
796
+ report.section("Attention");
797
+ if (plan.mode !== "undo" && plan.placementWriter) {
798
+ const writerCommands = options.writerCommands ?? ["amem doctor"];
799
+ 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.");
800
+ for (const command of writerCommands) report.next(command);
801
+ }
802
+ const versionWarnings = warnings.filter(note => /layout verified on/.test(note));
803
+ 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.`); }
804
+ for (const warning of [...new Set(warnings.filter(note => !versionWarnings.includes(note)))]) { warningCount++; report.bullet("warn", setupDisplay(warning.replace(/^WARNING:\s*/, ""), options.columns)); }
805
+ }
751
806
  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)"}`);
807
+ report.section(action.target);
808
+ const reason = skipped.get(action.target) ?? (!result && plan.mode !== "undo" && !action.available ? "CLI not installed" : undefined);
809
+ 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}`;
810
+ const rows: [string, string][] = [["MCP", state]];
811
+ if (!reason) {
812
+ 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"}`]);
813
+ if (plan.root) rows.push(["Install", setupDisplay(`${plan.root.path} (amem ${plan.root.version})`, options.columns)]);
814
+ if (action.files.length) rows.push(["Files", action.files.map(file => setupDisplay(file, options.columns)).join(", ")]);
815
+ if (action.cwd) rows.push(["Directory", setupDisplay(action.cwd, options.columns)]);
816
+ rows.push(["Receipt", setupDisplay(action.receipt, options.columns)]);
817
+ if (!result && action.available && action.registration) rows.push(["Command", setupDisplay(action.registration.map(quote).join(" "), options.columns)]);
818
+ if (action.hooks.length) rows.push(["Hooks", setupDisplay(setupHookSummary(action.hooks), options.columns)]);
819
+ for (const removal of action.removes ?? []) rows.push(["Remove", setupDisplay(`${removal.event}: ${removal.command} (in ${removal.file})`, options.columns)]);
759
820
  }
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)}`);
821
+ const skill = skills.find(row => row.target === action.target);
822
+ const skillChanged = skill?.report?.actions.some(item => ["install", "replace", "remove"].includes(item.change)) === true;
823
+ if (reason) counts.skipped++;
824
+ else if (plan.mode === "undo") { if (changed.has(action.target) || skillChanged) counts.restored++; else counts.nothing++; }
825
+ else if (result) { if (changed.has(action.target) || skillChanged) counts.applied++; else counts.unchanged++; }
826
+ else if (changed.has(action.target) || skillChanged) counts.toChange++; else counts.unchanged++;
827
+ if (skill?.report) {
828
+ const changedSkills = skill.report.actions.filter(item => item.change !== "unchanged" && item.change !== "absent");
829
+ const unchanged = skill.report.actions.filter(item => item.change === "unchanged").length;
830
+ 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)})`] : [])];
831
+ rows.push(["Skills", summary.join(", ") || "no changes"]);
832
+ } else if (skill?.reason) rows.push(["Skills", skill.refused ? "refused" : "unavailable"]);
833
+ report.kv(rows);
834
+ if (options.verbose) for (const hook of action.hooks) report.note(singleLine(`${hook.event}: ${hook.command} (timeout ${hook.timeout})`));
835
+ if (skill?.reason) { warningCount++; report.bullet("warn", singleLine(skill.reason)); }
836
+ for (const item of skill?.report?.actions ?? []) if (item.reason) { warningCount++; report.bullet("warn", singleLine(`${item.name}: ${item.reason}`)); }
768
837
  }
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");
838
+ const actionable = plan.actions.some(action => changed.has(action.target) && (plan.mode === "undo" || action.available))
839
+ || skills.some(row => row.report?.actions.some(item => ["install", "replace", "remove"].includes(item.change)));
840
+ const notes = plan.notes.filter(note => note !== plan.placementWriter && !warnings.includes(note));
841
+ 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"]];
842
+ 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")));
843
+ if (visibleNotes.length) { report.section("Notes"); for (const note of [...new Set(visibleNotes)]) report.note(setupDisplay(note, options.columns)); }
844
+ if (!result && plan.mode === "preview" && actionable) {
845
+ if (plan.root && /[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u.test(plan.root.path)) {
846
+ warningCount++; report.bullet("warn", "The install root contains control characters; inspect it with --json before rerunning setup.");
847
+ } 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)}` : ""}`);
848
+ }
849
+ const outcomes = plan.mode === "undo" ? `${counts.restored} restored, ${counts.nothing} nothing to restore`
850
+ : result ? `${counts.applied} applied, ${counts.unchanged} unchanged, ${counts.skipped} skipped`
851
+ : `${counts.toChange} to change, ${counts.unchanged} unchanged, ${counts.skipped} skipped`;
852
+ report.line("");
853
+ report.line(`Summary: ${outcomes}${warningCount ? `, ${warningCount} warning${warningCount === 1 ? "" : "s"}` : ""}`);
854
+ return report.render(s.color).join("\n");
785
855
  }
786
856
 
857
+ export function setupPlanText(plan: SetupPlan, s: Style = PLAIN, options: SetupRenderOptions = {}): string { return renderSetup(plan, undefined, s, options); }
858
+ function setupResultText(result: SetupResult, s: Style, plan: SetupPlan, options: SetupRenderOptions = {}): string { return renderSetup(plan, result, s, options); }
787
859
  /** Compatibility formatter for confirmation-style callers: the raw plan under `--json`, the readable plan otherwise. */
788
860
  export function setupConfirmationText(plan: SetupPlan, json: boolean, s: Style = PLAIN): string { return json ? JSON.stringify(plan, null, 2) : setupPlanText(plan, s); }
789
861
 
790
- export async function runSetup(target: string, mode: SetupPlan["mode"], options: SetupContext & { json?: boolean; style?: Style } = {}): Promise<string> {
862
+ export async function runSetup(target: string, mode: SetupPlan["mode"], options: SetupContext & { json?: boolean; style?: Style; columns?: number; verbose?: boolean } = {}): Promise<string> {
791
863
  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);
864
+ const renderOptions: SetupRenderOptions = { columns: options.columns, verbose: options.verbose, ...(!options.json && mode !== "undo" && plan.placementWriter ? { writerCommands: setupWriterCommands(plan) } : {}) };
865
+ if (cliAttribution()?.actor === "agent") {
866
+ const policy = configuredPolicy(memoryHome(options.env ?? process.env), options.cwd ?? process.cwd());
867
+ 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.");
868
+ }
869
+ if (mode === "preview") return options.json ? JSON.stringify(plan, null, 2) : setupPlanText(plan, s, renderOptions);
794
870
  const result = mode === "apply" ? applySetup(plan, options) : undoSetup(plan, options);
795
- return options.json ? JSON.stringify(result, null, 2) : setupResultText(result, s);
871
+ return options.json ? JSON.stringify(result, null, 2) : setupResultText(result, s, plan, renderOptions);
796
872
  }
797
873
 
798
874