@staix/agent-mem 0.36.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 +4 -1
- package/src/cli-agent-reads.ts +54 -4
- package/src/cli.ts +172 -72
- 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 -50
- 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 -28
- package/src/memory/style.ts +107 -55
- 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,7 +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,
|
|
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";
|
|
73
76
|
import { endLikeSignal, nextSyncAt, readSyncState, recordSyncAttempt, remoteConfigured, syncDue, stopSignal, syncOutcome, usableState, SYNC_IF_DUE_DEADLINE_MS, type StopCause } from "./memory/sync-cadence.ts";
|
|
74
77
|
|
|
75
78
|
const VERSION = (JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")) as { version: string }).version;
|
|
@@ -312,6 +315,18 @@ class ReadPolicyWithheld extends Error {
|
|
|
312
315
|
constructor() { super("Memory read withheld [cause: policy_withheld]; no partial result is shown. Ask the person to check the configured policy."); }
|
|
313
316
|
}
|
|
314
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
|
+
|
|
315
330
|
/** #326: a marked score read the policy refuses names its cause class and where to check it, never the matched value. */
|
|
316
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.";
|
|
317
332
|
|
|
@@ -356,7 +371,7 @@ export async function runCli(argv: readonly string[], context: CliContext = {}):
|
|
|
356
371
|
// The command returned successfully: withholding its receipt cannot undo its effects.
|
|
357
372
|
const failed = receipt !== null && typeof receipt === "object" && "ok" in receipt && receipt.ok === false;
|
|
358
373
|
return parsed.options["--json"] === true ? JSON.stringify({ ok: !failed, completed: !failed, receiptWithheld: true })
|
|
359
|
-
: 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.";
|
|
360
375
|
}
|
|
361
376
|
}
|
|
362
377
|
}
|
|
@@ -370,7 +385,8 @@ export async function runCli(argv: readonly string[], context: CliContext = {}):
|
|
|
370
385
|
const safe = new DecayApplyError(error.report, undefined); safe.jsonOutput = error.jsonOutput; throw safe;
|
|
371
386
|
}
|
|
372
387
|
// Data-free errors (decided before any store or file is opened) keep their own message.
|
|
373
|
-
|
|
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;
|
|
374
390
|
if (marked && error instanceof RemoteRealmRefusal) throw error;
|
|
375
391
|
// The checkpoint pending message is a fixed data-free remedy shared by journal and writer guards.
|
|
376
392
|
if (marked && error instanceof Error && error.message === PLACEMENT_CHECKPOINT_PENDING_MESSAGE) throw new Error(PLACEMENT_CHECKPOINT_PENDING_MESSAGE);
|
|
@@ -408,8 +424,12 @@ export async function runCli(argv: readonly string[], context: CliContext = {}):
|
|
|
408
424
|
// Preserve the value and the policy-screened result; only the JSON presentation changes.
|
|
409
425
|
try {
|
|
410
426
|
const parsed = parseCommand(argv);
|
|
427
|
+
if (parsed.options["--help"] === true || argv.includes("--help")) return output;
|
|
411
428
|
if (parsed.options["--json"] === true) return JSON.stringify(JSON.parse(output), null, 2);
|
|
412
|
-
|
|
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;
|
|
413
433
|
} catch { /* Help and non-JSON special commands keep their existing output. */ }
|
|
414
434
|
return output;
|
|
415
435
|
});
|
|
@@ -456,17 +476,24 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
456
476
|
cwd: context.cwd ?? process.cwd(), base: memoryHome(context.env ?? process.env),
|
|
457
477
|
...(typeof parsed.options["--since"] === "string" ? { since: parsed.options["--since"] as string } : {}),
|
|
458
478
|
});
|
|
459
|
-
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));
|
|
460
480
|
}
|
|
461
481
|
// Help and version carry no memory data.
|
|
462
482
|
if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "version")) return `amem ${VERSION}`;
|
|
463
483
|
if (argv.length === 1 && (argv[0] === "--help" || argv[0] === "help")) return commandHelp();
|
|
464
484
|
if (argv[0] === "--version" || argv[0] === "version") return `amem ${VERSION}`;
|
|
465
|
-
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
|
+
}
|
|
466
491
|
if (argv[0] === "--help" || argv.includes("--help")) return commandHelp(argv);
|
|
467
492
|
let parsed;
|
|
468
493
|
try {
|
|
469
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`);
|
|
470
497
|
if (parsed.path[0] === "version") return `amem ${VERSION}`;
|
|
471
498
|
if (parsed.path[0] === "manifest") return JSON.stringify(manifest(), null, parsed.options["--json"] === true ? undefined : 2);
|
|
472
499
|
if (parsed.path[0] === "completion") {
|
|
@@ -531,11 +558,11 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
531
558
|
env: context.env ?? process.env, stdinTTY: context.stdinTTY ?? process.stdin.isTTY, cwd: context.cwd ?? process.cwd(),
|
|
532
559
|
...(typeof options["--root"] === "string" ? { root: options["--root"] } : {}),
|
|
533
560
|
...(options["--adopt-current"] === true ? { adoptCurrent: true } : {}),
|
|
534
|
-
...(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,
|
|
535
562
|
});
|
|
536
563
|
}
|
|
537
564
|
if (identity.actor === "agent") {
|
|
538
|
-
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) });
|
|
539
566
|
if (read !== undefined) return read;
|
|
540
567
|
}
|
|
541
568
|
const goal = parsed.path[0] === "goal", review = parsed.path[0] === "review", sub = goal || review ? parsed.path[1]! : parsed.path[0]!;
|
|
@@ -547,6 +574,15 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
547
574
|
const policyCwd = context.cwd ?? process.cwd();
|
|
548
575
|
const policyOf = () => configuredPolicy(memoryHome(), policyCwd); // the same home every other command here resolves
|
|
549
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
|
+
};
|
|
550
586
|
let canonicalProject: string | undefined;
|
|
551
587
|
const boundProject = () => canonicalProject ??= resolveAlias(memoryHome(), memoryProjectKey(context.cwd ?? process.cwd()));
|
|
552
588
|
const commandBinding = (home: string, project: string): (() => void) => {
|
|
@@ -705,12 +741,12 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
705
741
|
if (mode === "deactivate") throw new Error("--deactivate is not a shard migration mode");
|
|
706
742
|
if (actor === "agent" && mode !== "dry-run") administrative(await migrateShards({ ...common, mode: "dry-run" }));
|
|
707
743
|
const result = await migrateShards({ ...common, mode });
|
|
708
|
-
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() } : {}) }));
|
|
709
745
|
}
|
|
710
746
|
if (actor === "agent" && mode === "deactivate") administrative({ target: common.memoryDir, selector: readSelector(common.memoryDir), mode });
|
|
711
747
|
else if (actor === "agent" && mode !== "dry-run") administrative(await migrate({ ...common, mode: "dry-run" }));
|
|
712
748
|
const result = await migrate({ ...common, mode });
|
|
713
|
-
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() } : {}) }));
|
|
714
750
|
}
|
|
715
751
|
if (sub === "status") {
|
|
716
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.
|
|
@@ -725,7 +761,7 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
725
761
|
if (summary === null) return { unavailable: "candidates.db exists but cannot be read" };
|
|
726
762
|
return { ...summary, ...(summary.dueWithin7Days ? { warning: `${summary.dueWithin7Days} candidate${summary.dueWithin7Days === 1 ? "" : "s"} within 7 days of expiry: run \`amem review walk\`` } : {}) }; })(),
|
|
727
763
|
...shardMigrationStatus(where.home) };
|
|
728
|
-
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));
|
|
729
765
|
}
|
|
730
766
|
if (parsed.path[0] === "formats" && parsed.path[1] === "raise") {
|
|
731
767
|
const { planFormatRaise, applyFormatRaise, formatRaiseRefusal, installVersion, runningAmemRoots } = await import("./memory/formats-raise.ts");
|
|
@@ -756,19 +792,29 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
756
792
|
if (options["--confirm"] !== true) {
|
|
757
793
|
const refusal = formatRaiseRefusal(plan);
|
|
758
794
|
if (options["--json"] === true) return JSON.stringify({ ...plan, refusal: refusal ?? null }, null, 2);
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
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"));
|
|
762
805
|
}
|
|
763
806
|
const record = applyFormatRaise(plan, () => planFormatRaise(home, surface, minReader, inventory(), now));
|
|
764
|
-
|
|
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"));
|
|
765
811
|
}
|
|
766
812
|
if (sub === "doctor") {
|
|
767
813
|
// F15: one read-only report; see src/memory/doctor.ts for exactly what "read-only" covers.
|
|
768
814
|
const where = resolveMemoryHome(), project = boundProject();
|
|
769
815
|
const report = await doctorReport({ home: where.home, homeSource: where.source, cwd: policyCwd, project, aliases: aliasedKeys(where.home, project), now: Date.now(),
|
|
770
816
|
openCurated: base => curatedStoreAt(base, project, { deferPromotions: true }) });
|
|
771
|
-
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));
|
|
772
818
|
}
|
|
773
819
|
if (sub === "prune") {
|
|
774
820
|
const applying = options["--apply"] === true;
|
|
@@ -797,7 +843,7 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
797
843
|
administrative(port.snapshot().rows.filter(source => ids.has(source.row.id)).map(source => source.row));
|
|
798
844
|
}
|
|
799
845
|
const result = applying ? applyPrune(port, input, auth) : plan;
|
|
800
|
-
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() } : {}) }));
|
|
801
847
|
} finally { store.close(); }
|
|
802
848
|
}
|
|
803
849
|
if (sub === "decay") {
|
|
@@ -829,12 +875,12 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
829
875
|
const preview = administrative(decayPreview(store, project, current)), action = options["--forget"] === true ? "FORGET" : "demote";
|
|
830
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" : ""}`,
|
|
831
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");
|
|
832
|
-
if (!applying) return options["--json"] ? JSON.stringify(preview, null, 2) : display;
|
|
833
|
-
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() } : {}) }));
|
|
834
880
|
if (options["--forget"] === true) assertExactDecayForget(store, preview.entries.map(entry => entry.target.id), project);
|
|
835
881
|
assertCurrent();
|
|
836
882
|
const result = applyDecay(store, preview, { ...current, actor, confirmed: true, forget: options["--forget"] === true });
|
|
837
|
-
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() } : {}) }));
|
|
838
884
|
} catch (error) { if (error instanceof DecayApplyError) error.jsonOutput = options["--json"] === true; throw error; }
|
|
839
885
|
finally { store.close(); }
|
|
840
886
|
}
|
|
@@ -873,14 +919,25 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
873
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");
|
|
874
920
|
const aliases = aliasedKeys(base, project), snapshot = readReviewSnapshot(base, [project, ...aliases]);
|
|
875
921
|
const store = openCuratedForRead(base, project);
|
|
876
|
-
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
|
+
}
|
|
877
928
|
try {
|
|
878
929
|
const policy = policyOf(), root = boundRepoRoot(policyCwd, base, project), stale = createRecallStalenessProbe({ cwd: root ?? policyCwd, rootConfirmed: root !== undefined, policy: () => policy });
|
|
879
930
|
const settings = loadAmemConfig(base, repoConfigRoot(policyCwd)).config.review;
|
|
880
931
|
const rows = store.withDeferredPromotions(() => store.list({ project, limit: 5000 })).filter(row => actor !== "agent" || policy.screenStandalone(row));
|
|
881
932
|
const result = reviewTargets(rows, { now: store.readNow(), recheckDays: settings?.recheck_days ?? REVIEW_DEFAULTS.recheck_days, limit: Number(rawLimit), stale,
|
|
882
933
|
use: row => reviewUse(snapshot, [project, ...aliases], row.id), eligibleForRecheck: (row, cutoff) => noRecentReview(snapshot, row.id, cutoff) });
|
|
883
|
-
|
|
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"));
|
|
884
941
|
} finally { store.close(); }
|
|
885
942
|
}
|
|
886
943
|
const id = parsed.positionals[0];
|
|
@@ -1072,13 +1129,13 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
1072
1129
|
if (sub === "vault-candidates" && (options["--all-projects"] === true || options["--project"] !== undefined)) {
|
|
1073
1130
|
if (options["--all-projects"] === true && options["--project"] !== undefined) throw new Error("choose either --all-projects or --project <key>, not both");
|
|
1074
1131
|
const result = await vaultCandidatesAll(memoryHome(), { policy: policyOf(), ...(options["--project"] !== undefined ? { project: resolveAlias(memoryHome(), String(options["--project"])) } : {}), ...(options["--limit"] ? { limit: Number(options["--limit"]) } : {}) });
|
|
1075
|
-
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() } : {}) }));
|
|
1076
1133
|
}
|
|
1077
1134
|
if (sub === "vault-candidates") {
|
|
1078
1135
|
const project = boundProject(), store = curatedStore(project, { deferPromotions: true });
|
|
1079
1136
|
try {
|
|
1080
1137
|
const result = await vaultCandidates(store, { project, policy: policyOf(), ...(options["--limit"] ? { limit: Number(options["--limit"]) } : {}) });
|
|
1081
|
-
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() } : {}) }));
|
|
1082
1139
|
} finally { store.close(); }
|
|
1083
1140
|
}
|
|
1084
1141
|
if (sub === "eval") {
|
|
@@ -1107,13 +1164,13 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
1107
1164
|
try { sheet = audit.auditSample({ store, project, n, seed, root, asOf, screen: view => screen.screenStandalone(view) }); } finally { store.close(); }
|
|
1108
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`);
|
|
1109
1166
|
const file = audit.writeAuditSheet(out, sheet);
|
|
1110
|
-
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() } : {}) }));
|
|
1111
1168
|
}
|
|
1112
1169
|
if (parsed.path[2] === "score") {
|
|
1113
1170
|
const [sheet] = parsed.positionals;
|
|
1114
1171
|
if (!sheet) throw new Error("usage: amem eval audit score <sheet> (the file `amem eval audit sample` wrote)");
|
|
1115
1172
|
const score = audit.auditScore(audit.readAuditSheet(sheet));
|
|
1116
|
-
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() } : {}) }));
|
|
1117
1174
|
}
|
|
1118
1175
|
throw new Error("usage: amem eval audit sample --seed <s> [--n <n>] [--project <key>] | amem eval audit score <sheet>");
|
|
1119
1176
|
}
|
|
@@ -1127,7 +1184,7 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
1127
1184
|
const project = boundProject(), store = curatedStore(project, { deferPromotions: true });
|
|
1128
1185
|
try { report = evalStore(store, project, set, ks); } finally { store.close(); }
|
|
1129
1186
|
}
|
|
1130
|
-
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) });
|
|
1131
1188
|
}
|
|
1132
1189
|
if (sub === "spool") {
|
|
1133
1190
|
// #217 PR2. Every argument refusal runs before any home, source or store access; both actors take this guarded
|
|
@@ -1137,7 +1194,7 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
1137
1194
|
const replay = await import("./hook-spool-replay.ts");
|
|
1138
1195
|
if (!apply) {
|
|
1139
1196
|
const plan = administrative(await replay.planHookSpoolReplay({ base: memoryHome(), ...(typeof source === "string" ? { source } : {}) }));
|
|
1140
|
-
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() } : {}) }));
|
|
1141
1198
|
}
|
|
1142
1199
|
let saved: unknown;
|
|
1143
1200
|
try { saved = JSON.parse(readFileSync(planFile as string, "utf8")); }
|
|
@@ -1151,13 +1208,15 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
1151
1208
|
const share = options["--disk-share"];
|
|
1152
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]");
|
|
1153
1210
|
const report = administrative(capacityReport({ ...(share !== undefined ? { diskShare: Number(share) } : {}) }));
|
|
1154
|
-
|
|
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(" ");
|
|
1155
1214
|
if (options["--split"] === true) {
|
|
1156
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.
|
|
1157
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");
|
|
1158
1217
|
const diskShare = share !== undefined ? { diskShare: Number(share) } : {};
|
|
1159
1218
|
const result = options["--confirm"] === true ? applySplit(memoryHome(), diskShare) : previewSplit(memoryHome(), diskShare);
|
|
1160
|
-
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 });
|
|
1161
1220
|
}
|
|
1162
1221
|
// Preview first; --confirm writes the bound home default config.
|
|
1163
1222
|
const file = join(memoryHome(), "capture-config.json");
|
|
@@ -1171,7 +1230,7 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
1171
1230
|
if (options["--confirm"] !== true) {
|
|
1172
1231
|
writeFileSync(previewFile, JSON.stringify(preview) + "\n", { mode: 0o600 });
|
|
1173
1232
|
const result = { preview, confirm: "re-run with --confirm to write" };
|
|
1174
|
-
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 });
|
|
1175
1234
|
}
|
|
1176
1235
|
let approved: { file?: string; current?: unknown; target?: CaptureConfig };
|
|
1177
1236
|
try { approved = JSON.parse(readFileSync(previewFile, "utf8")) as typeof approved; }
|
|
@@ -1183,29 +1242,30 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
1183
1242
|
const written = writeCaptureConfigFile(file, target);
|
|
1184
1243
|
rmSync(previewFile, { force: true });
|
|
1185
1244
|
const result = { preview, written: { cap_mb: written.capMb, retention_days: written.retentionDays } };
|
|
1186
|
-
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 });
|
|
1187
1246
|
}
|
|
1188
1247
|
if (sub === "projects") {
|
|
1189
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.
|
|
1190
1249
|
const rows = readCatalogFresh(memoryHome()).filter(project => options["--all"] === true || project.state !== "forgotten");
|
|
1191
1250
|
if (options["--json"]) return JSON.stringify(rows, null, 2);
|
|
1192
|
-
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() } : {}) }));
|
|
1193
1252
|
const mb = (n: number) => `${(n / 1048576).toFixed(1)} MB`;
|
|
1194
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.
|
|
1195
1254
|
const split = shardStatePresent();
|
|
1196
|
-
|
|
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() } : {}) }));
|
|
1197
1257
|
}
|
|
1198
1258
|
if (sub === "usage") {
|
|
1199
1259
|
const limit = options["--limit"] === undefined ? undefined : Number(options["--limit"]);
|
|
1200
1260
|
const report = usageReport(memoryHome(), { ...(limit !== undefined ? { limit } : {}), includeForgotten: options["--all"] === true });
|
|
1201
|
-
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() } : {}) }));
|
|
1202
1262
|
}
|
|
1203
1263
|
if (sub === "gc") {
|
|
1204
1264
|
// A preview reads; only explicit --confirm evicts, after the administrative preflight.
|
|
1205
1265
|
const batches = options["--batches"] === undefined ? undefined : Number(options["--batches"]);
|
|
1206
1266
|
if (actor === "agent") administrative(runGc(memoryHome(), { dryRun: true, ...(batches !== undefined ? { maxBatchesPerShard: batches } : {}) }));
|
|
1207
1267
|
const result = runGc(memoryHome(), { dryRun: options["--confirm"] !== true, ...(batches !== undefined ? { maxBatchesPerShard: batches } : {}) });
|
|
1208
|
-
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}`}` }));
|
|
1209
1269
|
}
|
|
1210
1270
|
if (sub === "import" && ["claude-auto", "codex"].includes(parsed.path[1] ?? "")) {
|
|
1211
1271
|
for (const flag of ["--db", "--limit", "--restart", "--capture-days"]) if (options[flag] !== undefined) throw new Error(`${flag} only applies to import claude-mem`);
|
|
@@ -1233,11 +1293,14 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
1233
1293
|
try {
|
|
1234
1294
|
const result = await importProject(store, { from: options["--from"], project: key, confirm: options["--confirm"] === true,
|
|
1235
1295
|
allowShared: options["--allow-shared"] === true, policy: note => policy.screenStandalone(note) });
|
|
1236
|
-
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)}`;
|
|
1237
1298
|
const summary = result.applied ? `imported ${result.added} of ${result.read} curated notes into ${result.project} with their original ids`
|
|
1238
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)`;
|
|
1239
|
-
|
|
1240
|
-
|
|
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);
|
|
1241
1304
|
} finally { store.close(); }
|
|
1242
1305
|
}
|
|
1243
1306
|
const key = administrative(requireShard(memoryHome(), requested));
|
|
@@ -1250,7 +1313,7 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
1250
1313
|
}
|
|
1251
1314
|
// Only the existing cross-project capture renderer uses this; project search and agent MCP routing stay unchanged.
|
|
1252
1315
|
const captureSearchText = (capture: { event: string; excerpt: string; paths: string[] }): string => {
|
|
1253
|
-
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) ? "..." : "");
|
|
1254
1317
|
const parsed = parseRecordLines(capture.excerpt), record = parsed.records[0];
|
|
1255
1318
|
// Historical capture can contain arbitrary event text. Never render it as a canonical Record or inject another display line.
|
|
1256
1319
|
return record && parsed.records.length === 1 && Object.keys(parsed.drops).length === 0 && record.line === capture.excerpt
|
|
@@ -1263,8 +1326,12 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
1263
1326
|
if (!words.trim()) throw new Error("usage: amem search --all-projects <words> [--limit N] [--include-archived] [--json]");
|
|
1264
1327
|
const result = searchAllProjects(memoryHome(), words, { ...(options["--limit"] !== undefined ? { limit: Number(options["--limit"]) } : {}), includeArchived: options["--include-archived"] === true });
|
|
1265
1328
|
if (options["--json"]) return JSON.stringify(result, null, 2);
|
|
1266
|
-
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!)}`;
|
|
1267
|
-
|
|
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")}`);
|
|
1268
1335
|
}
|
|
1269
1336
|
if (sub === "search" && options["--include-archived"] === true) throw new Error("--include-archived only applies with --all-projects");
|
|
1270
1337
|
if (sub === "search" && options["--explain"] === true) {
|
|
@@ -1307,8 +1374,9 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
1307
1374
|
const scoped = repoReadPolicy(root);
|
|
1308
1375
|
const read = "reason" in scoped ? undefined : await readRepoScope(root, scoped.policy);
|
|
1309
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 } : {}) };
|
|
1310
|
-
|
|
1311
|
-
|
|
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() } : {}) }));
|
|
1312
1380
|
}
|
|
1313
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");
|
|
1314
1382
|
if (sub === "promote" && options["--to"] !== undefined) {
|
|
@@ -1341,9 +1409,17 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
1341
1409
|
administrative({ path: plan.path, line: plan.line });
|
|
1342
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(", ")})`] : []),
|
|
1343
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)"}`];
|
|
1344
|
-
if (plan.alreadyPresent) return [...preview, "already in the file: nothing to write"].join("\n");
|
|
1345
1412
|
const entryPrefix = plan.line.id.slice(0, 8);
|
|
1346
|
-
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
|
+
}
|
|
1347
1423
|
if (seen.state !== "private") {
|
|
1348
1424
|
const given = options["--confirm-public"];
|
|
1349
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)`);
|
|
@@ -1360,8 +1436,7 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
1360
1436
|
const shown = await memory.tools.amem_show({ id: parsed.positionals[0]! }) as { capture?: import("./memory/capture.ts").CaptureRow } | null;
|
|
1361
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)`);
|
|
1362
1438
|
return options["--json"] === true ? JSON.stringify(row, null, 2)
|
|
1363
|
-
:
|
|
1364
|
-
...(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]] : [])]);
|
|
1365
1440
|
} finally { memory.close(); }
|
|
1366
1441
|
}
|
|
1367
1442
|
if (sub === "show" && /^repo:/.test(parsed.positionals[0] ?? "")) {
|
|
@@ -1370,8 +1445,10 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
1370
1445
|
const wanted = parsed.positionals[0]!.slice(5), hit = rows.filter(row => row.id === wanted || wanted.length >= 6 && row.id.startsWith(wanted));
|
|
1371
1446
|
if (hit.length !== 1) throw new Error(`no repo entry ${parsed.positionals[0]} in this repository's .amem/log.jsonl`);
|
|
1372
1447
|
const row = hit[0]!;
|
|
1373
|
-
|
|
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]] : [])]);
|
|
1374
1450
|
}
|
|
1451
|
+
let priorRead: string | undefined;
|
|
1375
1452
|
// Recall (D4): the current project plus, when the repository IS this project, that repository's `.amem/`. Never another project's.
|
|
1376
1453
|
const withRepoRows = async (output: string): Promise<string> => {
|
|
1377
1454
|
if (options["--history"] === true || options["--as-of"] !== undefined) return output;
|
|
@@ -1388,10 +1465,14 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
1388
1465
|
&& words.every(word => `${row.title ?? ""}\n${row.text}\n${row.about.join(" ")}`.toLowerCase().includes(word))).slice(0, limit);
|
|
1389
1466
|
const repoDetails = explainSearch ? rows.map(row => ({ ...row, scoreDetails: unrankedScoreDetails("repo", null) })) : rows;
|
|
1390
1467
|
if (options["--json"]) { try { const base = JSON.parse(output) as unknown[]; return JSON.stringify([...base, ...repoDetails], null, 2); } catch { return output; } }
|
|
1391
|
-
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)}`;
|
|
1392
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)}`;
|
|
1393
1470
|
const lines = explainSearch ? rows.flatMap(row => [line(row), `score: ${JSON.stringify(unrankedScoreDetails("repo", null))}`]) : rows.map(line);
|
|
1394
|
-
|
|
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"));
|
|
1395
1476
|
};
|
|
1396
1477
|
const crosses = definition.policyFree === true;
|
|
1397
1478
|
const cwd = context.cwd ?? process.cwd();
|
|
@@ -1428,7 +1509,7 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
1428
1509
|
// #418: read-only status from the telemetry sidecars; no realm, lock, proof, journal or schedule is touched.
|
|
1429
1510
|
if (Object.keys(options).some(name => name !== "--status" && name !== "--json")) throw new Error("sync --status takes only --json");
|
|
1430
1511
|
const { readSyncStatus, renderSyncStatus } = await import("./memory/sync-progress.ts"), report = readSyncStatus(syncHome);
|
|
1431
|
-
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() } : {}) }));
|
|
1432
1513
|
}
|
|
1433
1514
|
if (sub === "sync") { assertFormatFloor(syncHome, "sync"); const refusal = placementRuntimeRefusal(syncHome); if (refusal) throw new Error("amem sync: " + refusal); }
|
|
1434
1515
|
if (ifDue) {
|
|
@@ -1479,7 +1560,7 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
1479
1560
|
const markers = readPlacementRuntimeMarkers(syncHome);
|
|
1480
1561
|
if (!readActivePlacementBinding(syncHome, markers.profile, markers.shards)) throw Error("sync placement activation metadata unavailable or changed; inspect the retained activation before continuing");
|
|
1481
1562
|
}
|
|
1482
|
-
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),
|
|
1483
1564
|
// #578 Q2: the CLI sync (also --if-due) is eligible; the home opt-in still decides whether a checkpoint can run.
|
|
1484
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
|
|
1485
1566
|
onBridgeStatus: status => { receipt.bridgeStatus = status; },
|
|
@@ -1515,8 +1596,11 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
1515
1596
|
const policy = configured, db = options["--db"] ? { db: String(options["--db"]) } : {}, limit = options["--limit"] ? { limit: Number(options["--limit"]) } : {}, restart = options["--restart"] === true;
|
|
1516
1597
|
const work = await importClaudeMemWorkState({ base: memoryHome(), project: boundProject(), policy: row => policy.screen(row), ...db, ...limit, restart });
|
|
1517
1598
|
const capture = captureDays === undefined ? undefined : await importClaudeMemCapture({ base: memoryHome(), project: boundProject(), cwd, days: captureDays, ...db, ...limit, restart, policy: { host: policy } });
|
|
1518
|
-
|
|
1519
|
-
|
|
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 } : {}) }));
|
|
1520
1604
|
}
|
|
1521
1605
|
return !options["--json"] && receipt.bridgeStatus
|
|
1522
1606
|
? `${output}\n(legacy malformed lines skipped: ${receipt.bridgeStatus.skippedRows})` : output;
|
|
@@ -1536,10 +1620,14 @@ async function placementProgress(home: string, mode: string, context: CliContext
|
|
|
1536
1620
|
return new SyncProgress({ sink: snapshot => { for (const index of live) try { parts[index]!(snapshot); } catch { live.delete(index); } } });
|
|
1537
1621
|
}
|
|
1538
1622
|
function outputStyle(context: CliContext, options: Record<string, string | boolean>): Style {
|
|
1539
|
-
const color = resolveColor(typeof options["--color"] === "string" ? options["--color"] : undefined, streamEnv((context.stdoutTTY ?? process.stdout.isTTY) === true, context.env ?? process.env));
|
|
1623
|
+
const color = resolveColor(typeof options["--color"] === "string" ? options["--color"] : undefined, streamEnv((context.stdoutTTY ?? process.stdout.isTTY) === true, context.env ?? process.env), "amem");
|
|
1540
1624
|
if (color instanceof Error) throw color;
|
|
1541
1625
|
return style(options["--json"] !== true && color, asciiMarkers(context.env ?? process.env, options["--ascii"] === true));
|
|
1542
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
|
+
}
|
|
1543
1631
|
function reportWidth(context: CliContext): number | undefined {
|
|
1544
1632
|
const env = context.env ?? process.env, configured = Number(env.COLUMNS);
|
|
1545
1633
|
if (Number.isSafeInteger(configured) && configured >= 20) return configured;
|
|
@@ -1547,7 +1635,7 @@ function reportWidth(context: CliContext): number | undefined {
|
|
|
1547
1635
|
}
|
|
1548
1636
|
|
|
1549
1637
|
/** Native ingest remains capture-only and agent-reachable; this formats only its returned receipt. */
|
|
1550
|
-
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 {
|
|
1551
1639
|
const state = result.errors || result.remaining || result.spooled ? "attention" : result.files || result.read ? "complete" : "skipped";
|
|
1552
1640
|
const reason: string | undefined = result.reason;
|
|
1553
1641
|
const actions: Record<string, string> = {
|
|
@@ -1563,18 +1651,28 @@ export function ingestText(kind: IngestKind, result: IngestReceipt, s: Style = P
|
|
|
1563
1651
|
: result.errors ? "review the ingest errors and supported native source contract before retrying"
|
|
1564
1652
|
: result.remaining ? "run the same ingest command again to continue"
|
|
1565
1653
|
: result.spooled ? "the next capture write replays rows spooled while the store was busy"
|
|
1566
|
-
: state === "skipped" ? "open a native session in this repository before ingesting its transcript" :
|
|
1567
|
-
|
|
1568
|
-
|
|
1569
|
-
|
|
1570
|
-
|
|
1571
|
-
|
|
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");
|
|
1572
1663
|
}
|
|
1573
1664
|
|
|
1574
|
-
|
|
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 {
|
|
1575
1670
|
if (error instanceof DecayApplyError || error instanceof CliPartialApplyError) return error.render();
|
|
1576
|
-
const
|
|
1577
|
-
|
|
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}`;
|
|
1578
1676
|
}
|
|
1579
1677
|
|
|
1580
1678
|
/** A completed write means rendered output, never evidence of host delivery or citation. */
|
|
@@ -1589,12 +1687,14 @@ export async function main(argv = process.argv.slice(2)): Promise<void> {
|
|
|
1589
1687
|
if (process.stderr.isTTY) {
|
|
1590
1688
|
let options: Record<string, string | boolean> = {};
|
|
1591
1689
|
try { options = parseCommand(argv).options; } catch { /* Invalid options still report their usage error. */ }
|
|
1592
|
-
const color = resolveColor(typeof options["--color"] === "string" ? options["--color"] : undefined, streamEnv(true, process.env));
|
|
1690
|
+
const color = resolveColor(typeof options["--color"] === "string" ? options["--color"] : undefined, streamEnv(true, process.env), "amem");
|
|
1593
1691
|
const ascii = asciiMarkers(process.env, options["--ascii"] === true);
|
|
1594
|
-
|
|
1692
|
+
// ponytail: amem keeps the two-cell marker column; upgrade when errorSpans exposes that padding.
|
|
1693
|
+
const marker = errorSpans("amem", "", "", { tty: true, ascii })[0]![0]!;
|
|
1694
|
+
prefix = `${paint([{ ...marker, text: markerCell("fail", ascii) }], !argv.includes("--json") && color === true)} `;
|
|
1595
1695
|
}
|
|
1596
|
-
const code = (error as { exitCode?: number }).exitCode ?? ((error as Error).message.startsWith("usage:") ?
|
|
1597
|
-
console.error(prefix + formatCliError(error, code === 2)); process.exitCode = code;
|
|
1696
|
+
const code = (error as { exitCode?: number }).exitCode ?? ((error as Error).message.startsWith("usage:") ? EXIT.usage : EXIT.fail);
|
|
1697
|
+
console.error(prefix + formatCliError(error, code === 2, argv)); process.exitCode = code;
|
|
1598
1698
|
}
|
|
1599
1699
|
if (personStop !== undefined) endLikeSignal(personStop); // after the report, with amem's own handlers already removed
|
|
1600
1700
|
}
|