@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/.claude-plugin/plugin.json +1 -1
- package/README.md +1 -1
- package/package.json +1 -1
- package/src/cli-agent-reads.ts +54 -4
- package/src/cli.ts +166 -69
- package/src/commands-table.ts +332 -171
- package/src/memory/capacity.ts +40 -4
- package/src/memory/commands.ts +39 -8
- package/src/memory/doctor.ts +106 -51
- package/src/memory/eval-audit.ts +26 -2
- package/src/memory/eval.ts +17 -2
- package/src/memory/gc.ts +14 -1
- package/src/memory/report-text.ts +231 -0
- package/src/memory/status-text.ts +72 -29
- package/src/memory/style.ts +98 -1
- package/src/setup.ts +119 -43
package/src/cli.ts
CHANGED
|
@@ -30,6 +30,7 @@ import { fileURLToPath } from "node:url";
|
|
|
30
30
|
import { captureSessionKey } from "./memory/capture-input.ts";
|
|
31
31
|
import { originLine, originRecheck } from "./memory/candidate-origin.ts";
|
|
32
32
|
import { MemoryStore, looksSecret, machineId, openShardStore, type StoreOptions } from "./memory/store.ts";
|
|
33
|
+
import { CLI_MEMORY_RENDER } from "./memory/style.ts";
|
|
33
34
|
import { rawMemoryCommand, rawGoalCommand, claudeMemImportText } from "./memory/commands.ts";
|
|
34
35
|
import { memoryProjectKey } from "./memory/project.ts";
|
|
35
36
|
import { CandidateStore, candidateInputId, candidateTargetRevision, type CandidateFilter } from "./memory/candidates.ts";
|
|
@@ -39,7 +40,7 @@ import { aliasedKeys, appendAlias, appendUnalias, listAliases, readShardedSelect
|
|
|
39
40
|
import { capacityReport, capacityText, capacityApplyText, capacitySplitText } from "./memory/capacity.ts";
|
|
40
41
|
import { CaptureStore, readCaptureConfigFile, writeCaptureConfigFile, type CaptureConfig } from "./memory/capture.ts";
|
|
41
42
|
|
|
42
|
-
import { COMMANDS, commandHelp, parseCommand } from "./commands-table.ts";
|
|
43
|
+
import { COMMANDS, CommandUsageError, commandHelp, commandPath, parseCommand, usageLine } from "./commands-table.ts";
|
|
43
44
|
import { completionScript } from "./completion.ts";
|
|
44
45
|
import { memoryHome, resolveMemoryHome } from "./memory/home.ts";
|
|
45
46
|
import { realPath } from "./memory/platform.ts";
|
|
@@ -52,13 +53,14 @@ import { readCatalogFresh } from "./memory/catalog.ts";
|
|
|
52
53
|
import { appendLifecycle, assertProjectActive, projectState } from "./memory/lifecycle.ts";
|
|
53
54
|
import { gcText, runGc } from "./memory/gc.ts";
|
|
54
55
|
import { usageReport, usageText } from "./memory/usage.ts";
|
|
56
|
+
import * as reports from "./memory/report-text.ts";
|
|
55
57
|
import { exportProject, type ProjectExportFormat } from "./memory/project-export.ts";
|
|
56
58
|
import { importProject } from "./memory/project-import.ts";
|
|
57
59
|
import { importExternalMemory, type ExternalMemorySource } from "./memory/external-import.ts";
|
|
58
60
|
import { forgetNearby } from "./memory/forget-nearby.ts";
|
|
59
61
|
import { searchAllProjects, vaultCandidatesAll } from "./memory/cross-project.ts";
|
|
60
62
|
import { requireShard } from "./memory/curated-read.ts";
|
|
61
|
-
import { appendGitattributes, appendRepoLine, boundRepoRoot, planGitattributes, planRepoPromotion, readRepoScope, repoLogIgnored, repoLogPath, repoReadPolicy, repoVisibility
|
|
63
|
+
import { appendGitattributes, appendRepoLine, boundRepoRoot, planGitattributes, planRepoPromotion, readRepoScope, repoLogIgnored, repoLogPath, repoReadPolicy, repoVisibility } from "./memory/repo-scope.ts";
|
|
62
64
|
import type { Visibility } from "./memory/sync.ts";
|
|
63
65
|
import { applySplit, previewSplit } from "./memory/capacity-split.ts";
|
|
64
66
|
import { evalText, parseKs } from "./memory/eval.ts";
|
|
@@ -69,8 +71,8 @@ import { buildNote, FAIL_TEMPLATE, hasFailLabel, noteAdd, parseFailTemplate, typ
|
|
|
69
71
|
import { runEditor } from "./memory/editor.ts";
|
|
70
72
|
import { doctorReport, doctorText } from "./memory/doctor.ts";
|
|
71
73
|
import { statusText, type StatusView } from "./memory/status-text.ts";
|
|
72
|
-
import { asciiMarkers, errorLine, errorSpans, EXIT, markerCell, paint, resolveColor, streamEnv } from "@staix/cli-output";
|
|
73
|
-
import { style,
|
|
74
|
+
import { asciiMarkers, errorLine, errorSpans, EXIT, markerCell, paint, Report, resolveColor, streamEnv } from "@staix/cli-output";
|
|
75
|
+
import { style, facts, label, memoryRecordText, memoryScoresText, memoryTableText, PLAIN, singleLine, wordedKey, type Style } from "./memory/style.ts";
|
|
74
76
|
import { endLikeSignal, nextSyncAt, readSyncState, recordSyncAttempt, remoteConfigured, syncDue, stopSignal, syncOutcome, usableState, SYNC_IF_DUE_DEADLINE_MS, type StopCause } from "./memory/sync-cadence.ts";
|
|
75
77
|
|
|
76
78
|
const VERSION = (JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")) as { version: string }).version;
|
|
@@ -313,6 +315,18 @@ class ReadPolicyWithheld extends Error {
|
|
|
313
315
|
constructor() { super("Memory read withheld [cause: policy_withheld]; no partial result is shown. Ask the person to check the configured policy."); }
|
|
314
316
|
}
|
|
315
317
|
|
|
318
|
+
/** Human-only receipts; host handlers and every JSON response retain their existing bytes. */
|
|
319
|
+
function receiptText(output: string, parsed: ReturnType<typeof parseCommand>, context: CliContext): string {
|
|
320
|
+
const command = parsed.path.join(" ");
|
|
321
|
+
const receipts = new Set(["note", "note add", "confirm", "reject", "promote", "demote", "forget", "supersede", "rebuild", "dedupe", "consolidate", "review accept", "review reject", "review decide", "project export", "project import", "project archive", "project unarchive", "project forget", "alias add", "alias remove", "goal new", "goal state", "goal done", "goal take", "import claude-mem", "import claude-auto", "import codex", "repo attributes"]);
|
|
322
|
+
if (!receipts.has(command) || !output || command === "import claude-mem" || output === "Operation completed; receipt withheld by policy. Run amem status to inspect state." || output === "Operation did not complete; receipt withheld by policy. Inspect state before retrying." || command === "promote" && parsed.options["--to"] === "repo") return output;
|
|
323
|
+
const preview = /^preview\b/i.test(output) || command === "review decide" && parsed.options["--confirm"] !== true || command === "dedupe" && parsed.options["--apply"] !== true;
|
|
324
|
+
const s = outputStyle(context, parsed.options), lines = (command === "alias add" && !s.ascii ? output.replace(" -> ", " → ") : output).split("\n"), out = new Report(reportWidth(context) ?? 80, s.ascii, { sanitize: singleLine, keepTokensWhole: true });
|
|
325
|
+
out.bullet(preview ? "pending" : "ok", lines[0]!);
|
|
326
|
+
for (const line of lines.slice(1)) if (line.trim()) out.note(line);
|
|
327
|
+
return out.render(s.color).join("\n");
|
|
328
|
+
}
|
|
329
|
+
|
|
316
330
|
/** #326: a marked score read the policy refuses names its cause class and where to check it, never the matched value. */
|
|
317
331
|
export const AUDIT_SCORE_REFUSED = "Audit score refused [cause: policy_denied]: the configured policy denies a value in the rendered score (its seed, as-of or project digest); no partial result is shown. Next step: check the policy (amem.config.json in the memory home, narrowed by the repository's .amem/config) against those values, or sample again with a different --seed.";
|
|
318
332
|
|
|
@@ -357,7 +371,7 @@ export async function runCli(argv: readonly string[], context: CliContext = {}):
|
|
|
357
371
|
// The command returned successfully: withholding its receipt cannot undo its effects.
|
|
358
372
|
const failed = receipt !== null && typeof receipt === "object" && "ok" in receipt && receipt.ok === false;
|
|
359
373
|
return parsed.options["--json"] === true ? JSON.stringify({ ok: !failed, completed: !failed, receiptWithheld: true })
|
|
360
|
-
: failed ? "Operation did not complete; receipt withheld by policy. Inspect state before retrying." : "Operation completed; receipt withheld by policy.";
|
|
374
|
+
: failed ? "Operation did not complete; receipt withheld by policy. Inspect state before retrying." : "Operation completed; receipt withheld by policy. Run amem status to inspect state.";
|
|
361
375
|
}
|
|
362
376
|
}
|
|
363
377
|
}
|
|
@@ -371,7 +385,8 @@ export async function runCli(argv: readonly string[], context: CliContext = {}):
|
|
|
371
385
|
const safe = new DecayApplyError(error.report, undefined); safe.jsonOutput = error.jsonOutput; throw safe;
|
|
372
386
|
}
|
|
373
387
|
// Data-free errors (decided before any store or file is opened) keep their own message.
|
|
374
|
-
|
|
388
|
+
// #590 H7: a CommandUsageError is decided from argv words before any store access, so it stays a usage error.
|
|
389
|
+
if (marked && (error instanceof AgentUsageError || error instanceof CommandUsageError || error instanceof AgentReadFailure || error instanceof AgentReadAmbiguous)) throw error;
|
|
375
390
|
if (marked && error instanceof RemoteRealmRefusal) throw error;
|
|
376
391
|
// The checkpoint pending message is a fixed data-free remedy shared by journal and writer guards.
|
|
377
392
|
if (marked && error instanceof Error && error.message === PLACEMENT_CHECKPOINT_PENDING_MESSAGE) throw new Error(PLACEMENT_CHECKPOINT_PENDING_MESSAGE);
|
|
@@ -409,8 +424,12 @@ export async function runCli(argv: readonly string[], context: CliContext = {}):
|
|
|
409
424
|
// Preserve the value and the policy-screened result; only the JSON presentation changes.
|
|
410
425
|
try {
|
|
411
426
|
const parsed = parseCommand(argv);
|
|
427
|
+
if (parsed.options["--help"] === true || argv.includes("--help")) return output;
|
|
412
428
|
if (parsed.options["--json"] === true) return JSON.stringify(JSON.parse(output), null, 2);
|
|
413
|
-
|
|
429
|
+
// #590: status and doctor wrap through the Report builder at the same width, so a continuation aligns under its value.
|
|
430
|
+
const rendered = receiptText(output, parsed, context);
|
|
431
|
+
if (marked && rendered !== output && !configuredPolicy(memoryHome(), context.cwd ?? process.cwd()).screenStandalone(rendered)) return "Operation completed; receipt withheld by policy. Run amem status to inspect state.";
|
|
432
|
+
return rendered;
|
|
414
433
|
} catch { /* Help and non-JSON special commands keep their existing output. */ }
|
|
415
434
|
return output;
|
|
416
435
|
});
|
|
@@ -457,17 +476,24 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
457
476
|
cwd: context.cwd ?? process.cwd(), base: memoryHome(context.env ?? process.env),
|
|
458
477
|
...(typeof parsed.options["--since"] === "string" ? { since: parsed.options["--since"] as string } : {}),
|
|
459
478
|
});
|
|
460
|
-
return parsed.options["--json"] === true ? JSON.stringify(result, null, 2) : ingestText(kind as IngestKind, result, outputStyle(context, parsed.options));
|
|
479
|
+
return parsed.options["--json"] === true ? JSON.stringify(result, null, 2) : ingestText(kind as IngestKind, result, outputStyle(context, parsed.options), reportWidth(context));
|
|
461
480
|
}
|
|
462
481
|
// Help and version carry no memory data.
|
|
463
482
|
if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "version")) return `amem ${VERSION}`;
|
|
464
483
|
if (argv.length === 1 && (argv[0] === "--help" || argv[0] === "help")) return commandHelp();
|
|
465
484
|
if (argv[0] === "--version" || argv[0] === "version") return `amem ${VERSION}`;
|
|
466
|
-
if (argv[0] === "help")
|
|
485
|
+
if (argv[0] === "help") {
|
|
486
|
+
// #590 H7: `help <unknown>` is a usage error, not the overview.
|
|
487
|
+
const words = argv.slice(1).filter(word => !word.startsWith("-"));
|
|
488
|
+
if (words.length && commandPath(argv.slice(1)).length < words.length) throw new CommandUsageError(`unknown command ${words.join(" ")}`);
|
|
489
|
+
return commandHelp(argv.slice(1));
|
|
490
|
+
}
|
|
467
491
|
if (argv[0] === "--help" || argv.includes("--help")) return commandHelp(argv);
|
|
468
492
|
let parsed;
|
|
469
493
|
try {
|
|
470
494
|
parsed = parseCommand(argv);
|
|
495
|
+
// #590 H7: these groups do nothing bare (eval and capacity run their own report; spool and eval audit name their usage themselves).
|
|
496
|
+
if (["project", "skills", "formats", "note", "import"].includes(parsed.path.join(" "))) throw new CommandUsageError(`amem ${parsed.path.join(" ")} needs a command`);
|
|
471
497
|
if (parsed.path[0] === "version") return `amem ${VERSION}`;
|
|
472
498
|
if (parsed.path[0] === "manifest") return JSON.stringify(manifest(), null, parsed.options["--json"] === true ? undefined : 2);
|
|
473
499
|
if (parsed.path[0] === "completion") {
|
|
@@ -532,11 +558,11 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
532
558
|
env: context.env ?? process.env, stdinTTY: context.stdinTTY ?? process.stdin.isTTY, cwd: context.cwd ?? process.cwd(),
|
|
533
559
|
...(typeof options["--root"] === "string" ? { root: options["--root"] } : {}),
|
|
534
560
|
...(options["--adopt-current"] === true ? { adoptCurrent: true } : {}),
|
|
535
|
-
...(context.setupConfirm ? { confirm: context.setupConfirm } : {}), json: options["--json"] === true, style: outputStyle(context, options),
|
|
561
|
+
...(context.setupConfirm ? { confirm: context.setupConfirm } : {}), json: options["--json"] === true, style: outputStyle(context, options), columns: reportWidth(context), verbose: options["--verbose"] === true,
|
|
536
562
|
});
|
|
537
563
|
}
|
|
538
564
|
if (identity.actor === "agent") {
|
|
539
|
-
const read = await agentCliRead(parsed, argv, context);
|
|
565
|
+
const read = await agentCliRead(parsed, argv, { ...context, columns: reportWidth(context) ?? 80, style: options["--json"] === true ? PLAIN : outputStyle(context, options) });
|
|
540
566
|
if (read !== undefined) return read;
|
|
541
567
|
}
|
|
542
568
|
const goal = parsed.path[0] === "goal", review = parsed.path[0] === "review", sub = goal || review ? parsed.path[1]! : parsed.path[0]!;
|
|
@@ -548,6 +574,15 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
548
574
|
const policyCwd = context.cwd ?? process.cwd();
|
|
549
575
|
const policyOf = () => configuredPolicy(memoryHome(), policyCwd); // the same home every other command here resolves
|
|
550
576
|
const administrative = <T>(value: T): T => { assertAgentAdministrative(value, policyOf()); return value; };
|
|
577
|
+
// Reformat only after the prior human receipt passes the same whole-output screen.
|
|
578
|
+
const screenedLegacy = (legacy: string, formatted: string): string => actor === "agent" && !policyOf().screenStandalone(legacy) ? legacy : formatted;
|
|
579
|
+
// #590 task 429: a mutating command's receipt in a marked session; a denial of either text keeps the existing withheld-receipt line.
|
|
580
|
+
const screenedReceipt = (legacy: string, formatted: string): string =>
|
|
581
|
+
actor === "agent" && (!policyOf().screenStandalone(legacy) || !policyOf().screenStandalone(formatted)) ? "Operation completed; receipt withheld by policy. Run amem status to inspect state." : formatted;
|
|
582
|
+
const screenedReadPair = (legacy: string, formatted: string): string => {
|
|
583
|
+
if (actor === "agent" && (!policyOf().screenStandalone(legacy) || !policyOf().screenStandalone(formatted))) throw new ReadPolicyWithheld();
|
|
584
|
+
return formatted;
|
|
585
|
+
};
|
|
551
586
|
let canonicalProject: string | undefined;
|
|
552
587
|
const boundProject = () => canonicalProject ??= resolveAlias(memoryHome(), memoryProjectKey(context.cwd ?? process.cwd()));
|
|
553
588
|
const commandBinding = (home: string, project: string): (() => void) => {
|
|
@@ -706,12 +741,12 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
706
741
|
if (mode === "deactivate") throw new Error("--deactivate is not a shard migration mode");
|
|
707
742
|
if (actor === "agent" && mode !== "dry-run") administrative(await migrateShards({ ...common, mode: "dry-run" }));
|
|
708
743
|
const result = await migrateShards({ ...common, mode });
|
|
709
|
-
return options["--json"] ? JSON.stringify(result, null, 2) : shardMigrationText(result, outputStyle(context, options));
|
|
744
|
+
return options["--json"] ? JSON.stringify(result, null, 2) : (mode === "dry-run" ? screenedReadPair : screenedReceipt)(shardMigrationText(result, outputStyle(context, options)), reports.shardMigrateReportText(result, outputStyle(context, options), { columns: reportWidth(context) ?? 80, ...(context.now ? { now: context.now() } : {}) }));
|
|
710
745
|
}
|
|
711
746
|
if (actor === "agent" && mode === "deactivate") administrative({ target: common.memoryDir, selector: readSelector(common.memoryDir), mode });
|
|
712
747
|
else if (actor === "agent" && mode !== "dry-run") administrative(await migrate({ ...common, mode: "dry-run" }));
|
|
713
748
|
const result = await migrate({ ...common, mode });
|
|
714
|
-
return options["--json"] ? JSON.stringify(result, null, 2) : migrationText(result, outputStyle(context, options));
|
|
749
|
+
return options["--json"] ? JSON.stringify(result, null, 2) : (mode === "dry-run" ? screenedReadPair : screenedReceipt)(migrationText(result, outputStyle(context, options)), reports.migrateReportText(result, outputStyle(context, options), { columns: reportWidth(context) ?? 80, ...(context.now ? { now: context.now() } : {}) }));
|
|
715
750
|
}
|
|
716
751
|
if (sub === "status") {
|
|
717
752
|
// F1: say where the memory lives and which configuration is in effect. The migration fields keep their names and shape; `home` and `config` are added.
|
|
@@ -726,7 +761,7 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
726
761
|
if (summary === null) return { unavailable: "candidates.db exists but cannot be read" };
|
|
727
762
|
return { ...summary, ...(summary.dueWithin7Days ? { warning: `${summary.dueWithin7Days} candidate${summary.dueWithin7Days === 1 ? "" : "s"} within 7 days of expiry: run \`amem review walk\`` } : {}) }; })(),
|
|
728
763
|
...shardMigrationStatus(where.home) };
|
|
729
|
-
return options["--json"] ? JSON.stringify(status, null, 2) : statusText(status as unknown as StatusView, outputStyle(context, options));
|
|
764
|
+
return options["--json"] ? JSON.stringify(status, null, 2) : statusText(status as unknown as StatusView, outputStyle(context, options), reportOptions(context, options));
|
|
730
765
|
}
|
|
731
766
|
if (parsed.path[0] === "formats" && parsed.path[1] === "raise") {
|
|
732
767
|
const { planFormatRaise, applyFormatRaise, formatRaiseRefusal, installVersion, runningAmemRoots } = await import("./memory/formats-raise.ts");
|
|
@@ -757,19 +792,29 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
757
792
|
if (options["--confirm"] !== true) {
|
|
758
793
|
const refusal = formatRaiseRefusal(plan);
|
|
759
794
|
if (options["--json"] === true) return JSON.stringify({ ...plan, refusal: refusal ?? null }, null, 2);
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
795
|
+
const s = outputStyle(context, options), out = new Report(reportWidth(context) ?? 80, s.ascii, { sanitize: singleLine, keepTokensWhole: true });
|
|
796
|
+
out.header("amem", "Format floor"); out.section("Preview"); out.bullet("pending", "Review the proposed floor before confirming.");
|
|
797
|
+
out.kv([["Surface", plan.record.surface], ["Minimum reader", plan.record.minReader], ["Since", plan.record.since], ["File", plan.file], ["Existing", plan.existing.length ? plan.existing.map(floor => `${floor.surface} >= ${floor.minReader}`).join(", ") : "none"]]);
|
|
798
|
+
out.section("Writers", String(plan.writers.length));
|
|
799
|
+
if (plan.writers.length) out.table(["SOURCE", "VERSION", "INSTALL"], plan.writers.map(writer => [writer.source, writer.version ?? "?", `${writer.root}${writer.pid ? ` (pid ${writer.pid}${writer.host ? `, ${writer.host}` : ""})` : ""}`]), 2);
|
|
800
|
+
else out.note("No writers found.");
|
|
801
|
+
if (refusal) { out.section("Attention"); out.bullet("warn", refusal); }
|
|
802
|
+
else out.next(`amem formats raise ${surface} ${minReader} --confirm`);
|
|
803
|
+
const legacy = [`preview: append ${JSON.stringify(plan.record)} to ${plan.file}`, `existing floors: ${plan.existing.length ? plan.existing.map(floor => `${floor.surface}>=${floor.minReader}`).join(", ") : "none"}`, `writers checked (${plan.writers.length}):`, ...plan.writers.map(writer => ` ${writer.source.padEnd(14)} ${writer.version ?? "unknown"} ${writer.root}${writer.pid ? ` (pid ${writer.pid}${writer.host ? `, ${writer.host}` : ""})` : ""}`), refusal ? `refused: ${refusal}` : `ready: rerun with --confirm to append the record`].join("\n");
|
|
804
|
+
return screenedLegacy(legacy, out.render(s.color).join("\n"));
|
|
763
805
|
}
|
|
764
806
|
const record = applyFormatRaise(plan, () => planFormatRaise(home, surface, minReader, inventory(), now));
|
|
765
|
-
|
|
807
|
+
if (options["--json"] === true) return JSON.stringify({ appended: record, file: plan.file }, null, 2);
|
|
808
|
+
const s = outputStyle(context, options), out = new Report(reportWidth(context) ?? 80, s.ascii, { sanitize: singleLine });
|
|
809
|
+
out.bullet("ok", `Appended ${record.surface} minimum reader ${record.minReader} to ${plan.file}.`);
|
|
810
|
+
return screenedLegacy(`appended ${JSON.stringify(record)} to ${plan.file}`, out.render(s.color).join("\n"));
|
|
766
811
|
}
|
|
767
812
|
if (sub === "doctor") {
|
|
768
813
|
// F15: one read-only report; see src/memory/doctor.ts for exactly what "read-only" covers.
|
|
769
814
|
const where = resolveMemoryHome(), project = boundProject();
|
|
770
815
|
const report = await doctorReport({ home: where.home, homeSource: where.source, cwd: policyCwd, project, aliases: aliasedKeys(where.home, project), now: Date.now(),
|
|
771
816
|
openCurated: base => curatedStoreAt(base, project, { deferPromotions: true }) });
|
|
772
|
-
return options["--json"] ? JSON.stringify(report, null, 2) : doctorText(report, outputStyle(context, options));
|
|
817
|
+
return options["--json"] ? JSON.stringify(report, null, 2) : doctorText(report, outputStyle(context, options), reportOptions(context, options));
|
|
773
818
|
}
|
|
774
819
|
if (sub === "prune") {
|
|
775
820
|
const applying = options["--apply"] === true;
|
|
@@ -798,7 +843,7 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
798
843
|
administrative(port.snapshot().rows.filter(source => ids.has(source.row.id)).map(source => source.row));
|
|
799
844
|
}
|
|
800
845
|
const result = applying ? applyPrune(port, input, auth) : plan;
|
|
801
|
-
return options["--json"] ? JSON.stringify(result, null, 2) : pruneText(result, outputStyle(context, options));
|
|
846
|
+
return options["--json"] ? JSON.stringify(result, null, 2) : (applying ? screenedReceipt : screenedReadPair)(pruneText(result, outputStyle(context, options)), reports.pruneReportText(result, outputStyle(context, options), { columns: reportWidth(context) ?? 80, ...(context.now ? { now: context.now() } : {}) }));
|
|
802
847
|
} finally { store.close(); }
|
|
803
848
|
}
|
|
804
849
|
if (sub === "decay") {
|
|
@@ -830,12 +875,12 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
830
875
|
const preview = administrative(decayPreview(store, project, current)), action = options["--forget"] === true ? "FORGET" : "demote";
|
|
831
876
|
const display = [`${action} preview: ${preview.entries.length} notes older than ${days} days; citation history unknown (${preview.citedExemptions ?? "unknown"} observed retained-positive exemptions)${preview.truncated ? "; truncated" : ""}`,
|
|
832
877
|
...preview.entries.map(entry => `${entry.target.id} revision ${entry.target.revision} ${entry.view.at} ${entry.view.kind}: ${terminalSafe(entry.view.title ?? entry.view.text)}`)].join("\n");
|
|
833
|
-
if (!applying) return options["--json"] ? JSON.stringify(preview, null, 2) : display;
|
|
834
|
-
if (!preview.entries.length) return options["--json"] ? JSON.stringify({ action, ids: [] }) : "no eligible notes to apply";
|
|
878
|
+
if (!applying) return options["--json"] ? JSON.stringify(preview, null, 2) : screenedReadPair(display, reports.decayReportText({ kind: "preview", plan: preview, action }, outputStyle(context, options), { columns: reportWidth(context) ?? 80, ...(context.now ? { now: context.now() } : {}) }));
|
|
879
|
+
if (!preview.entries.length) return options["--json"] ? JSON.stringify({ action, ids: [] }) : screenedReadPair("no eligible notes to apply", reports.decayReportText({ kind: "empty" }, outputStyle(context, options), { columns: reportWidth(context) ?? 80, ...(context.now ? { now: context.now() } : {}) }));
|
|
835
880
|
if (options["--forget"] === true) assertExactDecayForget(store, preview.entries.map(entry => entry.target.id), project);
|
|
836
881
|
assertCurrent();
|
|
837
882
|
const result = applyDecay(store, preview, { ...current, actor, confirmed: true, forget: options["--forget"] === true });
|
|
838
|
-
return options["--json"] ? JSON.stringify(result, null, 2) : `${result.action}: ${result.ids.length} entries${result.expiresAt ? `; expires ${result.expiresAt}` : ""}
|
|
883
|
+
return options["--json"] ? JSON.stringify(result, null, 2) : screenedReceipt(`${result.action}: ${result.ids.length} entries${result.expiresAt ? `; expires ${result.expiresAt}` : ""}`, reports.decayReportText({ kind: "applied", ...result }, outputStyle(context, options), { columns: reportWidth(context) ?? 80, ...(context.now ? { now: context.now() } : {}) }));
|
|
839
884
|
} catch (error) { if (error instanceof DecayApplyError) error.jsonOutput = options["--json"] === true; throw error; }
|
|
840
885
|
finally { store.close(); }
|
|
841
886
|
}
|
|
@@ -874,14 +919,25 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
874
919
|
if (!/^[1-9][0-9]*$/.test(rawLimit) || Number(rawLimit) > 500) throw Error("review targets --limit must be from 1 to 500; pass a limit in that range");
|
|
875
920
|
const aliases = aliasedKeys(base, project), snapshot = readReviewSnapshot(base, [project, ...aliases]);
|
|
876
921
|
const store = openCuratedForRead(base, project);
|
|
877
|
-
if (!store)
|
|
922
|
+
if (!store) {
|
|
923
|
+
if (options["--json"]) return "[]";
|
|
924
|
+
const s = outputStyle(context, options), out = new Report(reportWidth(context) ?? 80, s.ascii, { sanitize: singleLine });
|
|
925
|
+
out.header("amem", "Review targets"); out.section("Entries", "0"); out.line(" No review targets.");
|
|
926
|
+
return screenedLegacy("no review targets", out.render(s.color).join("\n"));
|
|
927
|
+
}
|
|
878
928
|
try {
|
|
879
929
|
const policy = policyOf(), root = boundRepoRoot(policyCwd, base, project), stale = createRecallStalenessProbe({ cwd: root ?? policyCwd, rootConfirmed: root !== undefined, policy: () => policy });
|
|
880
930
|
const settings = loadAmemConfig(base, repoConfigRoot(policyCwd)).config.review;
|
|
881
931
|
const rows = store.withDeferredPromotions(() => store.list({ project, limit: 5000 })).filter(row => actor !== "agent" || policy.screenStandalone(row));
|
|
882
932
|
const result = reviewTargets(rows, { now: store.readNow(), recheckDays: settings?.recheck_days ?? REVIEW_DEFAULTS.recheck_days, limit: Number(rawLimit), stale,
|
|
883
933
|
use: row => reviewUse(snapshot, [project, ...aliases], row.id), eligibleForRecheck: (row, cutoff) => noRecentReview(snapshot, row.id, cutoff) });
|
|
884
|
-
|
|
934
|
+
if (options["--json"]) return JSON.stringify(result, null, 2);
|
|
935
|
+
const s = outputStyle(context, options), out = new Report(reportWidth(context) ?? 80, s.ascii, { sanitize: singleLine });
|
|
936
|
+
out.header("amem", "Review targets"); out.section("Entries", String(result.length));
|
|
937
|
+
if (result.length) { out.table(["ID", "REASON", "AGE", "RENDERED", "DELIVERED", "CITED"], result.map(row => [row.id.slice(0, 16), row.reason, `${row.ageDays} d`, String(row.counts.rendered ?? "?"), String(row.counts.delivered ?? "?"), String(row.counts.cited ?? "?")]), 1); out.note("Full entries: amem show <id> or --json."); }
|
|
938
|
+
else out.line(" No review targets.");
|
|
939
|
+
const legacy = result.length ? result.map(row => `${row.id} ${row.reason} ${row.ageDays}d rendered ${row.counts.rendered ?? "unknown"} delivered ${row.counts.delivered ?? "unknown"} cited ${row.counts.cited ?? "unknown"}`).join("\n") : "no review targets";
|
|
940
|
+
return screenedLegacy(legacy, out.render(s.color).join("\n"));
|
|
885
941
|
} finally { store.close(); }
|
|
886
942
|
}
|
|
887
943
|
const id = parsed.positionals[0];
|
|
@@ -1073,13 +1129,13 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
1073
1129
|
if (sub === "vault-candidates" && (options["--all-projects"] === true || options["--project"] !== undefined)) {
|
|
1074
1130
|
if (options["--all-projects"] === true && options["--project"] !== undefined) throw new Error("choose either --all-projects or --project <key>, not both");
|
|
1075
1131
|
const result = await vaultCandidatesAll(memoryHome(), { policy: policyOf(), ...(options["--project"] !== undefined ? { project: resolveAlias(memoryHome(), String(options["--project"])) } : {}), ...(options["--limit"] ? { limit: Number(options["--limit"]) } : {}) });
|
|
1076
|
-
return options["--json"] ? JSON.stringify(result, null, 2) : vaultCandidatesAllText(result, outputStyle(context, options));
|
|
1132
|
+
return options["--json"] ? JSON.stringify(result, null, 2) : screenedReadPair(vaultCandidatesAllText(result, outputStyle(context, options)), reports.vaultReportText(result.projects, result.crossedProjects, outputStyle(context, options), { columns: reportWidth(context) ?? 80, ...(context.now ? { now: context.now() } : {}) }));
|
|
1077
1133
|
}
|
|
1078
1134
|
if (sub === "vault-candidates") {
|
|
1079
1135
|
const project = boundProject(), store = curatedStore(project, { deferPromotions: true });
|
|
1080
1136
|
try {
|
|
1081
1137
|
const result = await vaultCandidates(store, { project, policy: policyOf(), ...(options["--limit"] ? { limit: Number(options["--limit"]) } : {}) });
|
|
1082
|
-
return options["--json"] ? JSON.stringify(result, null, 2) : vaultCandidatesText(result, outputStyle(context, options));
|
|
1138
|
+
return options["--json"] ? JSON.stringify(result, null, 2) : screenedReadPair(vaultCandidatesText(result, outputStyle(context, options)), reports.vaultReportText(result.length ? [{ project: result[0]!.project, candidates: result }] : [], false, outputStyle(context, options), { columns: reportWidth(context) ?? 80, ...(context.now ? { now: context.now() } : {}) }));
|
|
1083
1139
|
} finally { store.close(); }
|
|
1084
1140
|
}
|
|
1085
1141
|
if (sub === "eval") {
|
|
@@ -1108,13 +1164,13 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
1108
1164
|
try { sheet = audit.auditSample({ store, project, n, seed, root, asOf, screen: view => screen.screenStandalone(view) }); } finally { store.close(); }
|
|
1109
1165
|
const out = typeof options["--out"] === "string" ? options["--out"] : join(memoryHome(), "eval", `audit-${project.replace(/[^A-Za-z0-9._-]+/g, "-").slice(0, 80)}-${seed}.json`);
|
|
1110
1166
|
const file = audit.writeAuditSheet(out, sheet);
|
|
1111
|
-
return options["--json"] === true ? JSON.stringify({ file, project: sheet.project, seed: sheet.seed, asOf: sheet.asOf, frame: sheet.frame, drawn: sheet.drawn, truncated: sheet.truncated, withheld: sheet.withheld }, null, 2) : audit.auditSheetText(sheet, file);
|
|
1167
|
+
return options["--json"] === true ? JSON.stringify({ file, project: sheet.project, seed: sheet.seed, asOf: sheet.asOf, frame: sheet.frame, drawn: sheet.drawn, truncated: sheet.truncated, withheld: sheet.withheld }, null, 2) : screenedLegacy(audit.auditSheetText(sheet, file), audit.auditSheetText(sheet, file, { columns: reportWidth(context) ?? 80, style: outputStyle(context, options), ...(context.now ? { now: context.now() } : {}) }));
|
|
1112
1168
|
}
|
|
1113
1169
|
if (parsed.path[2] === "score") {
|
|
1114
1170
|
const [sheet] = parsed.positionals;
|
|
1115
1171
|
if (!sheet) throw new Error("usage: amem eval audit score <sheet> (the file `amem eval audit sample` wrote)");
|
|
1116
1172
|
const score = audit.auditScore(audit.readAuditSheet(sheet));
|
|
1117
|
-
return options["--json"] === true ? JSON.stringify(score, null, 2) : audit.auditScoreText(score);
|
|
1173
|
+
return options["--json"] === true ? JSON.stringify(score, null, 2) : screenedLegacy(audit.auditScoreText(score), audit.auditScoreText(score, { columns: reportWidth(context) ?? 80, style: outputStyle(context, options), ...(context.now ? { now: context.now() } : {}) }));
|
|
1118
1174
|
}
|
|
1119
1175
|
throw new Error("usage: amem eval audit sample --seed <s> [--n <n>] [--project <key>] | amem eval audit score <sheet>");
|
|
1120
1176
|
}
|
|
@@ -1128,7 +1184,7 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
1128
1184
|
const project = boundProject(), store = curatedStore(project, { deferPromotions: true });
|
|
1129
1185
|
try { report = evalStore(store, project, set, ks); } finally { store.close(); }
|
|
1130
1186
|
}
|
|
1131
|
-
return options["--json"] ? JSON.stringify(report, null, 2) : evalText(report, builtin ? `built-in fixture ${file}` : file ?? "built-in fixture");
|
|
1187
|
+
return options["--json"] ? JSON.stringify(report, null, 2) : evalText(report, builtin ? `built-in fixture ${file}` : file ?? "built-in fixture", { columns: reportWidth(context) ?? 80, style: outputStyle(context, options) });
|
|
1132
1188
|
}
|
|
1133
1189
|
if (sub === "spool") {
|
|
1134
1190
|
// #217 PR2. Every argument refusal runs before any home, source or store access; both actors take this guarded
|
|
@@ -1138,7 +1194,7 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
1138
1194
|
const replay = await import("./hook-spool-replay.ts");
|
|
1139
1195
|
if (!apply) {
|
|
1140
1196
|
const plan = administrative(await replay.planHookSpoolReplay({ base: memoryHome(), ...(typeof source === "string" ? { source } : {}) }));
|
|
1141
|
-
return options["--json"] === true ? JSON.stringify(plan, null, 2) : replayPreviewText(plan);
|
|
1197
|
+
return options["--json"] === true ? JSON.stringify(plan, null, 2) : screenedReadPair(replayPreviewText(plan), reports.spoolReplayReportText(plan, outputStyle(context, options), { columns: reportWidth(context) ?? 80, ...(context.now ? { now: context.now() } : {}) }));
|
|
1142
1198
|
}
|
|
1143
1199
|
let saved: unknown;
|
|
1144
1200
|
try { saved = JSON.parse(readFileSync(planFile as string, "utf8")); }
|
|
@@ -1152,13 +1208,15 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
1152
1208
|
const share = options["--disk-share"];
|
|
1153
1209
|
if (share !== undefined && (!Number.isFinite(Number(share)) || Number(share) <= 0 || Number(share) > 1)) throw new Error("--disk-share must be a number in (0, 1]");
|
|
1154
1210
|
const report = administrative(capacityReport({ ...(share !== undefined ? { diskShare: Number(share) } : {}) }));
|
|
1155
|
-
|
|
1211
|
+
const capacityStyle = options["--json"] === true ? PLAIN : outputStyle(context, options), capacityRender = { columns: reportWidth(context) ?? 80, style: capacityStyle };
|
|
1212
|
+
if (parsed.path[1] !== "apply") return options["--json"] ? JSON.stringify(report, null, 2) : capacityText(report, capacityRender);
|
|
1213
|
+
const confirmation = ["amem", "capacity", "apply", ...(options["--split"] === true ? ["--split"] : []), ...(["--disk-share", "--cap-mb", "--retention-days"] as const).flatMap(flag => typeof options[flag] === "string" && options[flag] !== "" ? [flag, String(Number(options[flag]))] : []), "--confirm"].join(" ");
|
|
1156
1214
|
if (options["--split"] === true) {
|
|
1157
1215
|
// #15 D7: each shard's own share of the global budget, written to its own config. The same two steps as the home default below, bound to the shards it was made for.
|
|
1158
1216
|
if (options["--cap-mb"] !== undefined || options["--retention-days"] !== undefined) throw new Error("--split computes each shard's values; do not combine it with --cap-mb or --retention-days");
|
|
1159
1217
|
const diskShare = share !== undefined ? { diskShare: Number(share) } : {};
|
|
1160
1218
|
const result = options["--confirm"] === true ? applySplit(memoryHome(), diskShare) : previewSplit(memoryHome(), diskShare);
|
|
1161
|
-
return options["--json"] ? JSON.stringify(result, null, 2) : capacitySplitText(result,
|
|
1219
|
+
return options["--json"] ? JSON.stringify(result, null, 2) : capacitySplitText(result, capacityStyle, { ...capacityRender, next: confirmation });
|
|
1162
1220
|
}
|
|
1163
1221
|
// Preview first; --confirm writes the bound home default config.
|
|
1164
1222
|
const file = join(memoryHome(), "capture-config.json");
|
|
@@ -1172,7 +1230,7 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
1172
1230
|
if (options["--confirm"] !== true) {
|
|
1173
1231
|
writeFileSync(previewFile, JSON.stringify(preview) + "\n", { mode: 0o600 });
|
|
1174
1232
|
const result = { preview, confirm: "re-run with --confirm to write" };
|
|
1175
|
-
return options["--json"] ? JSON.stringify(result, null, 2) : capacityApplyText(result,
|
|
1233
|
+
return options["--json"] ? JSON.stringify(result, null, 2) : capacityApplyText(result, capacityStyle, { ...capacityRender, next: confirmation });
|
|
1176
1234
|
}
|
|
1177
1235
|
let approved: { file?: string; current?: unknown; target?: CaptureConfig };
|
|
1178
1236
|
try { approved = JSON.parse(readFileSync(previewFile, "utf8")) as typeof approved; }
|
|
@@ -1184,29 +1242,30 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
1184
1242
|
const written = writeCaptureConfigFile(file, target);
|
|
1185
1243
|
rmSync(previewFile, { force: true });
|
|
1186
1244
|
const result = { preview, written: { cap_mb: written.capMb, retention_days: written.retentionDays } };
|
|
1187
|
-
return options["--json"] ? JSON.stringify(result, null, 2) : capacityApplyText(result,
|
|
1245
|
+
return options["--json"] ? JSON.stringify(result, null, 2) : capacityApplyText(result, capacityStyle, { ...capacityRender, next: confirmation });
|
|
1188
1246
|
}
|
|
1189
1247
|
if (sub === "projects") {
|
|
1190
1248
|
// Archived projects stay listed (the person must see what is cold); a forgotten one is out of the default view, and --all brings it back with its state.
|
|
1191
1249
|
const rows = readCatalogFresh(memoryHome()).filter(project => options["--all"] === true || project.state !== "forgotten");
|
|
1192
1250
|
if (options["--json"]) return JSON.stringify(rows, null, 2);
|
|
1193
|
-
if (!rows.length) return "no project shards yet";
|
|
1251
|
+
if (!rows.length) return screenedReadPair("no project shards yet", reports.projectsReportText(rows, false, outputStyle(context, options), { columns: reportWidth(context) ?? 80, ...(context.now ? { now: context.now() } : {}) }));
|
|
1194
1252
|
const mb = (n: number) => `${(n / 1048576).toFixed(1)} MB`;
|
|
1195
1253
|
// Per-project curated counts exist only after the split; before it every note is in one shared store, so the honest figure is unavailable, never 0.
|
|
1196
1254
|
const split = shardStatePresent();
|
|
1197
|
-
|
|
1255
|
+
const legacy = rows.map(p => `${p.key} ${p.state}${p.local ? " local-only key" : ""}${p.aliases.length ? ` aliases: ${p.aliases.join(", ")}` : ""} capture ${p.captureRows} rows ${mb(p.captureBytes)} curated ${split ? p.curatedEntries ?? "unavailable" : "unavailable (home not split)"} disk ${mb(p.diskBytes)} last ${p.captureLastAt ?? "never"}`).join("\n");
|
|
1256
|
+
return screenedReadPair(legacy, reports.projectsReportText(rows, split, outputStyle(context, options), { columns: reportWidth(context) ?? 80, ...(context.now ? { now: context.now() } : {}) }));
|
|
1198
1257
|
}
|
|
1199
1258
|
if (sub === "usage") {
|
|
1200
1259
|
const limit = options["--limit"] === undefined ? undefined : Number(options["--limit"]);
|
|
1201
1260
|
const report = usageReport(memoryHome(), { ...(limit !== undefined ? { limit } : {}), includeForgotten: options["--all"] === true });
|
|
1202
|
-
return options["--json"] ? JSON.stringify(report, null, 2) : usageText(report);
|
|
1261
|
+
return options["--json"] ? JSON.stringify(report, null, 2) : screenedReadPair(usageText(report), reports.usageReportText(report, outputStyle(context, options), { columns: reportWidth(context) ?? 80, ...(context.now ? { now: context.now() } : {}) }));
|
|
1203
1262
|
}
|
|
1204
1263
|
if (sub === "gc") {
|
|
1205
1264
|
// A preview reads; only explicit --confirm evicts, after the administrative preflight.
|
|
1206
1265
|
const batches = options["--batches"] === undefined ? undefined : Number(options["--batches"]);
|
|
1207
1266
|
if (actor === "agent") administrative(runGc(memoryHome(), { dryRun: true, ...(batches !== undefined ? { maxBatchesPerShard: batches } : {}) }));
|
|
1208
1267
|
const result = runGc(memoryHome(), { dryRun: options["--confirm"] !== true, ...(batches !== undefined ? { maxBatchesPerShard: batches } : {}) });
|
|
1209
|
-
return options["--json"] ? JSON.stringify(result, null, 2) : `${result.dryRun ? "preview (nothing evicted; add --confirm):\n" : ""}${gcText(result)}
|
|
1268
|
+
return options["--json"] ? JSON.stringify(result, null, 2) : screenedLegacy(`${result.dryRun ? "preview (nothing evicted; add --confirm):\n" : ""}${gcText(result)}`, gcText(result, { columns: reportWidth(context) ?? 80, style: outputStyle(context, options), next: `amem gc --confirm${batches === undefined ? "" : ` --batches ${batches}`}` }));
|
|
1210
1269
|
}
|
|
1211
1270
|
if (sub === "import" && ["claude-auto", "codex"].includes(parsed.path[1] ?? "")) {
|
|
1212
1271
|
for (const flag of ["--db", "--limit", "--restart", "--capture-days"]) if (options[flag] !== undefined) throw new Error(`${flag} only applies to import claude-mem`);
|
|
@@ -1234,11 +1293,14 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
1234
1293
|
try {
|
|
1235
1294
|
const result = await importProject(store, { from: options["--from"], project: key, confirm: options["--confirm"] === true,
|
|
1236
1295
|
allowShared: options["--allow-shared"] === true, policy: note => policy.screenStandalone(note) });
|
|
1237
|
-
const
|
|
1296
|
+
const describe = (values: Record<string, number>) => Object.entries(values).map(([key, value]) => `${wordedKey(key)} ${value}`).join(", ") || "none";
|
|
1297
|
+
const counts = `sources ${describe(result.provenance.source)}, peers ${describe(result.provenance.peer)}, scopes ${describe(result.provenance.scope)}, machines ${describe(result.provenance.machine)}`;
|
|
1238
1298
|
const summary = result.applied ? `imported ${result.added} of ${result.read} curated notes into ${result.project} with their original ids`
|
|
1239
1299
|
: `preview: ${result.wouldAdd} of ${result.read} curated notes can be imported into ${result.project} with their original ids (re-run with --confirm to write)`;
|
|
1240
|
-
|
|
1241
|
-
|
|
1300
|
+
const formatted = `${summary}; ${counts}; skipped ${result.skipped.invalid} invalid, ${result.skipped.policy} policy/secret and ${result.skipped.other} non-curated records. ${result.warnings.join(" ")}`;
|
|
1301
|
+
const legacyCounts = `sources ${JSON.stringify(result.provenance.source)}, peers ${JSON.stringify(result.provenance.peer)}, scopes ${JSON.stringify(result.provenance.scope)}, machines ${JSON.stringify(result.provenance.machine)}`;
|
|
1302
|
+
const legacy = `${summary}; ${legacyCounts}; skipped ${result.skipped.invalid} invalid, ${result.skipped.policy} policy/secret and ${result.skipped.other} non-curated records. ${result.warnings.join(" ")}`;
|
|
1303
|
+
return options["--json"] ? JSON.stringify(result, null, 2) : screenedLegacy(legacy, formatted);
|
|
1242
1304
|
} finally { store.close(); }
|
|
1243
1305
|
}
|
|
1244
1306
|
const key = administrative(requireShard(memoryHome(), requested));
|
|
@@ -1251,7 +1313,7 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
1251
1313
|
}
|
|
1252
1314
|
// Only the existing cross-project capture renderer uses this; project search and agent MCP routing stay unchanged.
|
|
1253
1315
|
const captureSearchText = (capture: { event: string; excerpt: string; paths: string[] }): string => {
|
|
1254
|
-
if (capture.event !== "Record") return capture.excerpt.split(
|
|
1316
|
+
if (capture.event !== "Record") return capture.excerpt.split(/[\r\n]/, 1)[0]! + (/[\r\n]/.test(capture.excerpt) ? "..." : "");
|
|
1255
1317
|
const parsed = parseRecordLines(capture.excerpt), record = parsed.records[0];
|
|
1256
1318
|
// Historical capture can contain arbitrary event text. Never render it as a canonical Record or inject another display line.
|
|
1257
1319
|
return record && parsed.records.length === 1 && Object.keys(parsed.drops).length === 0 && record.line === capture.excerpt
|
|
@@ -1264,8 +1326,12 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
1264
1326
|
if (!words.trim()) throw new Error("usage: amem search --all-projects <words> [--limit N] [--include-archived] [--json]");
|
|
1265
1327
|
const result = searchAllProjects(memoryHome(), words, { ...(options["--limit"] !== undefined ? { limit: Number(options["--limit"]) } : {}), includeArchived: options["--include-archived"] === true });
|
|
1266
1328
|
if (options["--json"]) return JSON.stringify(result, null, 2);
|
|
1267
|
-
const one = (hit: (typeof result.hits)[number]) => hit.view ? `${hit.project} ${hit.view.id.slice(0, 8)} ${hit.view.kind} ${(hit.view.title ?? hit.view.text).split("\n")[0]!.slice(0, 100)}` : `${hit.project} capture ${hit.capture!.id} ${hit.capture!.event}${hit.capture!.subagent ? " subagent" : ""} ${captureSearchText(hit.capture!)}`;
|
|
1268
|
-
|
|
1329
|
+
const one = (hit: (typeof result.hits)[number]) => hit.view ? `${hit.project} ${hit.view.id.slice(0, 8)} ${hit.view.kind} ${(hit.view.title ?? hit.view.text).split("\n")[0]!.slice(0, 100)}` : `${hit.project} capture ${hit.capture!.id} ${hit.capture!.event}${hit.capture!.subagent ? " subagent" : ""} ${hit.capture!.event === "Record" ? captureSearchText(hit.capture!) : hit.capture!.excerpt.split("\n")[0]!.slice(0, 100)}`;
|
|
1330
|
+
const legacy = [`crossed projects: searched ${result.projects.length} (${result.projects.join(", ")})`, ...(result.hits.length ? result.hits.map(one) : ["(nothing)"])].join("\n");
|
|
1331
|
+
const rows = result.hits.map(hit => hit.view ? { project: hit.project, id: hit.view.id, kind: hit.view.kind, tier: hit.view.tier, peer: hit.view.peer, scope: hit.view.scope, at: hit.view.at, text: `${hit.view.title ? `${hit.view.title}: ` : ""}${hit.view.text}` } : { project: hit.project, id: `capture:${hit.capture!.id}`, kind: "capture", peer: hit.capture!.agent, at: hit.capture!.at, text: `${hit.capture!.event}${hit.capture!.subagent ? " subagent" : ""}: ${captureSearchText(hit.capture!)}` });
|
|
1332
|
+
const width = reportWidth(context) ?? 80, displayStyle = outputStyle(context, options), projects = new Report(width, displayStyle.ascii, { sanitize: singleLine });
|
|
1333
|
+
projects.section("Projects", String(result.projects.length)); projects.line(`Crossed projects: ${result.projects.join(", ") || "none"}.`);
|
|
1334
|
+
return screenedReadPair(legacy, `${memoryTableText(rows, "Cross-project search", { columns: width, style: displayStyle, ...(context.now ? { now: context.now() } : {}) })}\n\n${projects.render(displayStyle.color).join("\n")}`);
|
|
1269
1335
|
}
|
|
1270
1336
|
if (sub === "search" && options["--include-archived"] === true) throw new Error("--include-archived only applies with --all-projects");
|
|
1271
1337
|
if (sub === "search" && options["--explain"] === true) {
|
|
@@ -1308,8 +1374,9 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
1308
1374
|
const scoped = repoReadPolicy(root);
|
|
1309
1375
|
const read = "reason" in scoped ? undefined : await readRepoScope(root, scoped.policy);
|
|
1310
1376
|
const status = { root, file: repoLogPath(root), state: read?.state ?? "unavailable", entries: read?.views.length ?? 0, skipped: read?.skipped ?? null, ...(read?.reason ? { reason: read.reason } : {}), ...("reason" in scoped ? { reason: scoped.reason } : {}) };
|
|
1311
|
-
|
|
1312
|
-
|
|
1377
|
+
if (options["--json"]) return JSON.stringify(status, null, 2);
|
|
1378
|
+
return screenedReadPair([`repo scope of ${project}: ${status.state}`, `file: ${status.file}`, `entries: ${status.entries}${read ? ` (skipped: ${read.skipped.malformed} malformed, ${read.skipped.mismatched} id mismatch, ${read.skipped.duplicate} duplicate, ${read.skipped.withheld} withheld by the screen)` : ""}`,
|
|
1379
|
+
...(status.reason ? [`unavailable: ${status.reason}`] : [])].join("\n"), reports.repoStatusReportText(status, project, outputStyle(context, options), { columns: reportWidth(context) ?? 80, ...(context.now ? { now: context.now() } : {}) }));
|
|
1313
1380
|
}
|
|
1314
1381
|
if (sub === "promote" && options["--to"] === undefined && (options["--confirm"] !== undefined || options["--confirm-public"] !== undefined)) throw new Error("--confirm and --confirm-public only apply with --to repo");
|
|
1315
1382
|
if (sub === "promote" && options["--to"] !== undefined) {
|
|
@@ -1342,9 +1409,17 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
1342
1409
|
administrative({ path: plan.path, line: plan.line });
|
|
1343
1410
|
const preview = [`the exact line that would be appended to ${plan.path}:`, plan.text, ...(plan.droppedNodes.length ? [`(left out, private references: ${plan.droppedNodes.join(", ")})`] : []),
|
|
1344
1411
|
`repository visibility: ${seen.state}${seen.remotes.length ? ` (${[...new Set(seen.remotes.map(r => `${r.name}${r.kind === "push" ? " (push)" : ""} ${r.visibility}`))].join(", ")})` : " (no remote)"}`];
|
|
1345
|
-
if (plan.alreadyPresent) return [...preview, "already in the file: nothing to write"].join("\n");
|
|
1346
1412
|
const entryPrefix = plan.line.id.slice(0, 8);
|
|
1347
|
-
if (options["--confirm"] !== true)
|
|
1413
|
+
if (plan.alreadyPresent || options["--confirm"] !== true) {
|
|
1414
|
+
const s = outputStyle(context, options), report = new Report(reportWidth(context) ?? 80, s.ascii, { sanitize: singleLine, keepTokensWhole: true });
|
|
1415
|
+
report.header("amem", "Repository promotion"); report.section("Preview");
|
|
1416
|
+
const targetParts = Array.from(plan.path), target = targetParts.length > 25 ? `${targetParts.slice(0, 10).join("")}...${targetParts.slice(-12).join("")}` : plan.path;
|
|
1417
|
+
report.kv([["Scope", "repo"], ["Kind", plan.line.kind], ["Target", target], ["Visibility", seen.state]]);
|
|
1418
|
+
if (plan.droppedNodes.length) report.line(`Private references omitted: ${plan.droppedNodes.join(", ")}`);
|
|
1419
|
+
report.line(plan.alreadyPresent ? "already in the file: nothing to write" : seen.state === "private" ? "Nothing written; add --confirm to append it." : `NOT a verified private repository: add --confirm --confirm-public ${entryPrefix} to append this entry (per entry, never blanket).`);
|
|
1420
|
+
// AC8 exception: the canonical line must be shown verbatim before appending to a shared repository.
|
|
1421
|
+
return `${report.render(s.color).join("\n")}\nLine to append:\n${plan.text}`;
|
|
1422
|
+
}
|
|
1348
1423
|
if (seen.state !== "private") {
|
|
1349
1424
|
const given = options["--confirm-public"];
|
|
1350
1425
|
if (typeof given !== "string" || given.length < 8 || !/^[a-f0-9]+$/.test(given) || !plan.line.id.startsWith(given)) throw new Error(`the repository is ${seen.state === "public" ? "public" : "not verified private"}: repo scope needs your confirmation of this entry: --confirm-public ${entryPrefix} (the first 8 characters of the id in the line above)`);
|
|
@@ -1361,8 +1436,7 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
1361
1436
|
const shown = await memory.tools.amem_show({ id: parsed.positionals[0]! }) as { capture?: import("./memory/capture.ts").CaptureRow } | null;
|
|
1362
1437
|
const row = shown?.capture; if (!row) throw new Error(`no capture row ${parsed.positionals[0]} in this project (capture is machine-local and expires; inspect the current project timeline and retention)`);
|
|
1363
1438
|
return options["--json"] === true ? JSON.stringify(row, null, 2)
|
|
1364
|
-
:
|
|
1365
|
-
...(row.paths.length ? [`paths: ${row.paths.join(", ")}`] : []), "", terminalSafe(row.excerpt)].join("\n");
|
|
1439
|
+
: memoryRecordText({ id: `capture:${row.id}`, kind: row.event, at: row.at, text: row.excerpt }, { columns: reportWidth(context) ?? 80, style: outputStyle(context, options), ...(context.now ? { now: context.now() } : {}) }, [["Recorded at", row.at], ["Agent", row.agent], ["Session", row.session ?? "unavailable"], ...(row.tool ? [["Tool", row.tool] as [string, string]] : []), ...(row.paths.length ? [["Paths", row.paths.join(", ")] as [string, string]] : []), ...(row.subagent ? [["Subagent", "yes"] as [string, string]] : [])]);
|
|
1366
1440
|
} finally { memory.close(); }
|
|
1367
1441
|
}
|
|
1368
1442
|
if (sub === "show" && /^repo:/.test(parsed.positionals[0] ?? "")) {
|
|
@@ -1371,8 +1445,10 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
1371
1445
|
const wanted = parsed.positionals[0]!.slice(5), hit = rows.filter(row => row.id === wanted || wanted.length >= 6 && row.id.startsWith(wanted));
|
|
1372
1446
|
if (hit.length !== 1) throw new Error(`no repo entry ${parsed.positionals[0]} in this repository's .amem/log.jsonl`);
|
|
1373
1447
|
const row = hit[0]!;
|
|
1374
|
-
|
|
1448
|
+
if (actor === "agent" && options["--json"] !== true) return [`repo:${row.id} ${row.kind}, repo scope, ${row.at}`, ...(row.about.length ? [`about: ${row.about.join(", ")}`] : []), "", ...(row.title ? [row.title] : []), row.text].join("\n");
|
|
1449
|
+
return options["--json"] ? JSON.stringify(row, null, 2) : memoryRecordText({ id: `repo:${row.id}`, kind: row.kind, at: row.at, text: `${row.title ? `${row.title}\n` : ""}${row.text}` }, { columns: reportWidth(context) ?? 80, style: outputStyle(context, options), ...(context.now ? { now: context.now() } : {}) }, [["Scope", "repo"], ...(row.about.length ? [["About", row.about.join(", ")] as [string, string]] : [])]);
|
|
1375
1450
|
}
|
|
1451
|
+
let priorRead: string | undefined;
|
|
1376
1452
|
// Recall (D4): the current project plus, when the repository IS this project, that repository's `.amem/`. Never another project's.
|
|
1377
1453
|
const withRepoRows = async (output: string): Promise<string> => {
|
|
1378
1454
|
if (options["--history"] === true || options["--as-of"] !== undefined) return output;
|
|
@@ -1389,10 +1465,14 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
1389
1465
|
&& words.every(word => `${row.title ?? ""}\n${row.text}\n${row.about.join(" ")}`.toLowerCase().includes(word))).slice(0, limit);
|
|
1390
1466
|
const repoDetails = explainSearch ? rows.map(row => ({ ...row, scoreDetails: unrankedScoreDetails("repo", null) })) : rows;
|
|
1391
1467
|
if (options["--json"]) { try { const base = JSON.parse(output) as unknown[]; return JSON.stringify([...base, ...repoDetails], null, 2); } catch { return output; } }
|
|
1392
|
-
const line = (row: RepoView) => `repo:${row.id.slice(0, 8)} ${row.at.slice(0, 16).replace("T", " ")} repo ${row.kind.padEnd(8)} ${`${row.title ? `${row.title}: ` : ""}${row.text}`.replace(/\s+/g, " ").slice(0, 100)}`;
|
|
1393
1468
|
const note = read.state === "unsafe" ? [`(repo scope unavailable: ${read.reason})`] : read.skipped.malformed + read.skipped.mismatched + read.skipped.withheld ? [`(${read.skipped.malformed + read.skipped.mismatched} repo lines skipped as invalid, ${read.skipped.withheld} withheld by the screen)`] : [];
|
|
1469
|
+
const line = (row: (typeof rows)[number]) => `repo:${row.id.slice(0, 8)} ${row.at.slice(0, 16).replace("T", " ")} repo ${row.kind.padEnd(8)} ${`${row.title ? `${row.title}: ` : ""}${row.text}`.replace(/\s+/g, " ").slice(0, 100)}`;
|
|
1394
1470
|
const lines = explainSearch ? rows.flatMap(row => [line(row), `score: ${JSON.stringify(unrankedScoreDetails("repo", null))}`]) : rows.map(line);
|
|
1395
|
-
|
|
1471
|
+
const legacy = [priorRead ?? output, ...(rows.length ? ["repo scope (.amem/log.jsonl):", ...lines] : []), ...note].join("\n");
|
|
1472
|
+
const render = { columns: reportWidth(context) ?? 80, style: outputStyle(context, options), ...(context.now ? { now: context.now() } : {}) };
|
|
1473
|
+
const table = rows.length ? memoryTableText(rows.map(row => ({ id: `repo:${row.id}`, kind: row.kind, at: row.at, text: `${row.title ? `${row.title}: ` : ""}${row.text}` })), "Repository", render) : "";
|
|
1474
|
+
const scores = explainSearch ? memoryScoresText(rows.map(row => ({ id: `repo:${row.id}`, details: unrankedScoreDetails("repo", null) as unknown as Record<string, unknown> })), render) : "";
|
|
1475
|
+
return screenedReadPair(legacy, [output, ...(rows.length ? ["repo scope (.amem/log.jsonl):", table] : []), ...(scores ? ["", scores] : []), ...note].join("\n"));
|
|
1396
1476
|
};
|
|
1397
1477
|
const crosses = definition.policyFree === true;
|
|
1398
1478
|
const cwd = context.cwd ?? process.cwd();
|
|
@@ -1429,7 +1509,7 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
1429
1509
|
// #418: read-only status from the telemetry sidecars; no realm, lock, proof, journal or schedule is touched.
|
|
1430
1510
|
if (Object.keys(options).some(name => name !== "--status" && name !== "--json")) throw new Error("sync --status takes only --json");
|
|
1431
1511
|
const { readSyncStatus, renderSyncStatus } = await import("./memory/sync-progress.ts"), report = readSyncStatus(syncHome);
|
|
1432
|
-
return options["--json"] ? JSON.stringify(report, null, 2) : renderSyncStatus(report);
|
|
1512
|
+
return options["--json"] ? JSON.stringify(report, null, 2) : screenedReadPair(renderSyncStatus(report), reports.syncStatusReportText(report, context.now?.() ?? Date.now(), outputStyle(context, options), { columns: reportWidth(context) ?? 80, ...(context.now ? { now: context.now() } : {}) }));
|
|
1433
1513
|
}
|
|
1434
1514
|
if (sub === "sync") { assertFormatFloor(syncHome, "sync"); const refusal = placementRuntimeRefusal(syncHome); if (refusal) throw new Error("amem sync: " + refusal); }
|
|
1435
1515
|
if (ifDue) {
|
|
@@ -1480,7 +1560,7 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
1480
1560
|
const markers = readPlacementRuntimeMarkers(syncHome);
|
|
1481
1561
|
if (!readActivePlacementBinding(syncHome, markers.profile, markers.shards)) throw Error("sync placement activation metadata unavailable or changed; inspect the retained activation before continuing");
|
|
1482
1562
|
}
|
|
1483
|
-
output = await withRepoRows(await rawMemoryCommand(memoryArgs, cwd, { person: true, rankedSearch: !legacySearch, ...(identity.actor === "agent" ? { screenGraph: true } : {}), ...(explainSearch ? { explainSearch: true } : {}), project: boundProject(), open: sub === "sync" && placementWriters ? () => openShardStore({ memoryDir: syncHome, user: true, deferPromotions: true }) : open, readable: notes => identity.actor === "person" ? notes : notes.filter(view => view.project === boundProject() && policyOf().screenStandalone(view)), stale: createRecallStalenessProbe({ cwd: recallRoot ?? cwd, rootConfirmed, policy: () => configured }), outputReady: notes => outputReady(notes.map(view => view.id)), importPolicy: () => text => configured.declinesPersonal(text),
|
|
1563
|
+
output = await withRepoRows(await rawMemoryCommand(memoryArgs, cwd, { person: true, rankedSearch: !legacySearch, ...(identity.actor === "agent" ? { screenGraph: true } : {}), ...(explainSearch ? { explainSearch: true } : {}), ...(options["--json"] !== true ? { [CLI_MEMORY_RENDER]: { render: { columns: reportWidth(context) ?? 80, style: outputStyle(context, options), ...(context.now ? { now: context.now() } : {}) }, ...(actor === "agent" ? { renderLegacy: (legacy: string, formatted: string) => { priorRead = legacy; return sub === "sync" ? screenedReceipt(legacy, formatted) : screenedReadPair(legacy, formatted); } } : {}) } } : {}), project: boundProject(), open: sub === "sync" && placementWriters ? () => openShardStore({ memoryDir: syncHome, user: true, deferPromotions: true }) : open, readable: notes => identity.actor === "person" ? notes : notes.filter(view => view.project === boundProject() && policyOf().screenStandalone(view)), stale: createRecallStalenessProbe({ cwd: recallRoot ?? cwd, rootConfirmed, policy: () => configured }), outputReady: notes => outputReady(notes.map(view => view.id)), importPolicy: () => text => configured.declinesPersonal(text),
|
|
1484
1564
|
// #578 Q2: the CLI sync (also --if-due) is eligible; the home opt-in still decides whether a checkpoint can run.
|
|
1485
1565
|
sync: { ...(placementWriters ? { placementAttestation:placementWriters.attest, placementCheckpoint: true } : {}), ...(progress ? { progress } : {}), screen: row => configured.screenStandalone(row), policyVersion: () => JSON.stringify(configuredPolicyOptions(memoryHome(), policyCwd)), ...(stop ? { signal: stop.signal } : {}) }, // the repository-narrowed policy binds what sync publishes too
|
|
1486
1566
|
onBridgeStatus: status => { receipt.bridgeStatus = status; },
|
|
@@ -1516,8 +1596,11 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
1516
1596
|
const policy = configured, db = options["--db"] ? { db: String(options["--db"]) } : {}, limit = options["--limit"] ? { limit: Number(options["--limit"]) } : {}, restart = options["--restart"] === true;
|
|
1517
1597
|
const work = await importClaudeMemWorkState({ base: memoryHome(), project: boundProject(), policy: row => policy.screen(row), ...db, ...limit, restart });
|
|
1518
1598
|
const capture = captureDays === undefined ? undefined : await importClaudeMemCapture({ base: memoryHome(), project: boundProject(), cwd, days: captureDays, ...db, ...limit, restart, policy: { host: policy } });
|
|
1519
|
-
|
|
1520
|
-
|
|
1599
|
+
if (options["--json"]) return JSON.stringify({ ...JSON.parse(output), work, ...(capture ? { capture } : {}) }, null, 2);
|
|
1600
|
+
const s = outputStyle(context, options), notes = JSON.parse(output), source = typeof options["--db"] === "string" ? options["--db"] : undefined;
|
|
1601
|
+
const safe = source === undefined || !/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u.test(source);
|
|
1602
|
+
const next = safe ? ["amem import claude-mem", ...(source ? [`--db '${source.replaceAll("'", "'\\''")}'`] : []), ...(limit.limit !== undefined ? [`--limit ${limit.limit}`] : []), ...(captureDays !== undefined ? [`--capture-days ${captureDays}`] : [])].join(" ") : undefined;
|
|
1603
|
+
return screenedLegacy(claudeMemImportText(notes, work, capture, { captureDays, restart }, s), claudeMemImportText(notes, work, capture, { captureDays, restart }, s, { columns: reportWidth(context) ?? 80, ...(next ? { next } : {}) }));
|
|
1521
1604
|
}
|
|
1522
1605
|
return !options["--json"] && receipt.bridgeStatus
|
|
1523
1606
|
? `${output}\n(legacy malformed lines skipped: ${receipt.bridgeStatus.skippedRows})` : output;
|
|
@@ -1541,6 +1624,10 @@ function outputStyle(context: CliContext, options: Record<string, string | boole
|
|
|
1541
1624
|
if (color instanceof Error) throw color;
|
|
1542
1625
|
return style(options["--json"] !== true && color, asciiMarkers(context.env ?? process.env, options["--ascii"] === true));
|
|
1543
1626
|
}
|
|
1627
|
+
function reportOptions(context: CliContext, options: Record<string, string | boolean>): { verbose: boolean; version: string; columns?: number } {
|
|
1628
|
+
const columns = reportWidth(context);
|
|
1629
|
+
return { verbose: options["--verbose"] === true, version: VERSION, ...(columns !== undefined ? { columns } : {}) };
|
|
1630
|
+
}
|
|
1544
1631
|
function reportWidth(context: CliContext): number | undefined {
|
|
1545
1632
|
const env = context.env ?? process.env, configured = Number(env.COLUMNS);
|
|
1546
1633
|
if (Number.isSafeInteger(configured) && configured >= 20) return configured;
|
|
@@ -1548,7 +1635,7 @@ function reportWidth(context: CliContext): number | undefined {
|
|
|
1548
1635
|
}
|
|
1549
1636
|
|
|
1550
1637
|
/** Native ingest remains capture-only and agent-reachable; this formats only its returned receipt. */
|
|
1551
|
-
export function ingestText(kind: IngestKind, result: IngestReceipt, s: Style = PLAIN): string {
|
|
1638
|
+
export function ingestText(kind: IngestKind, result: IngestReceipt, s: Style = PLAIN, columns?: number): string {
|
|
1552
1639
|
const state = result.errors || result.remaining || result.spooled ? "attention" : result.files || result.read ? "complete" : "skipped";
|
|
1553
1640
|
const reason: string | undefined = result.reason;
|
|
1554
1641
|
const actions: Record<string, string> = {
|
|
@@ -1564,18 +1651,28 @@ export function ingestText(kind: IngestKind, result: IngestReceipt, s: Style = P
|
|
|
1564
1651
|
: result.errors ? "review the ingest errors and supported native source contract before retrying"
|
|
1565
1652
|
: result.remaining ? "run the same ingest command again to continue"
|
|
1566
1653
|
: result.spooled ? "the next capture write replays rows spooled while the store was busy"
|
|
1567
|
-
: state === "skipped" ? "open a native session in this repository before ingesting its transcript" :
|
|
1568
|
-
|
|
1569
|
-
|
|
1570
|
-
|
|
1571
|
-
|
|
1572
|
-
|
|
1654
|
+
: state === "skipped" ? "open a native session in this repository before ingesting its transcript" : undefined;
|
|
1655
|
+
const report = new Report(columns ?? 80, s.ascii, { sanitize: singleLine, keepTokensWhole: true });
|
|
1656
|
+
report.header("amem", `Ingest ${kind}`); report.section("Receipt");
|
|
1657
|
+
report.bullet(state === "complete" ? "ok" : state === "skipped" ? "absent" : "warn", state === "complete" ? "Ingest completed." : state === "skipped" ? "No transcript imported." : "Ingest needs attention.");
|
|
1658
|
+
report.kv([["State", state], ["Files", String(result.files)], ["Read", String(result.read)], ["Imported", String(result.imported)], ["Skipped", String(result.skipped)], ["Spooled", String(result.spooled)], ["Errors", String(result.errors)], ["Remaining", result.remaining ? "yes" : "no"], ...(reason ? [["Reason", reason.replace(/_/g, " ") + (version ? ` (version ${version})` : "")] as [string, string]] : [])]);
|
|
1659
|
+
if (action) { report.section("Attention"); report.bullet(state === "attention" ? "warn" : "absent", action); }
|
|
1660
|
+
if (result.remaining || reason === "cursor_busy" || reason === "scope_changed") report.next(`amem ingest ${kind}`);
|
|
1661
|
+
report.line(""); report.line(`Summary: ${result.imported} imported, ${result.skipped} skipped, ${result.errors} errors`);
|
|
1662
|
+
return report.render(s.color).join("\n");
|
|
1573
1663
|
}
|
|
1574
1664
|
|
|
1575
|
-
|
|
1665
|
+
/**
|
|
1666
|
+
* #590 H7: a usage error prints its message, one usage line and the help page that explains it. A message that already
|
|
1667
|
+
* is a `usage:` line stays the one usage line.
|
|
1668
|
+
*/
|
|
1669
|
+
export function formatCliError(error: unknown, usage = false, argv: readonly string[] = []): string {
|
|
1576
1670
|
if (error instanceof DecayApplyError || error instanceof CliPartialApplyError) return error.render();
|
|
1577
|
-
const
|
|
1578
|
-
|
|
1671
|
+
const raw = String((error as Error).message), message = errorLine("amem", raw, "", { tty: false })[0]!;
|
|
1672
|
+
if (!usage && (error as { exitCode?: number }).exitCode !== 2) return message;
|
|
1673
|
+
const path = commandPath(argv[0] === "help" ? [] : argv);
|
|
1674
|
+
const help = `Run 'amem help${path.length ? ` ${path.join(" ")}` : ""}' for details.`;
|
|
1675
|
+
return raw.startsWith("usage:") ? `${message}\n${help}` : `${message}\nUsage: ${usageLine(path)}\n${help}`;
|
|
1579
1676
|
}
|
|
1580
1677
|
|
|
1581
1678
|
/** A completed write means rendered output, never evidence of host delivery or citation. */
|
|
@@ -1597,7 +1694,7 @@ export async function main(argv = process.argv.slice(2)): Promise<void> {
|
|
|
1597
1694
|
prefix = `${paint([{ ...marker, text: markerCell("fail", ascii) }], !argv.includes("--json") && color === true)} `;
|
|
1598
1695
|
}
|
|
1599
1696
|
const code = (error as { exitCode?: number }).exitCode ?? ((error as Error).message.startsWith("usage:") ? EXIT.usage : EXIT.fail);
|
|
1600
|
-
console.error(prefix + formatCliError(error, code === 2)); process.exitCode = code;
|
|
1697
|
+
console.error(prefix + formatCliError(error, code === 2, argv)); process.exitCode = code;
|
|
1601
1698
|
}
|
|
1602
1699
|
if (personStop !== undefined) endLikeSignal(personStop); // after the report, with amem's own handlers already removed
|
|
1603
1700
|
}
|