@staix/agent-mem 0.38.0 → 0.40.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/brief-curated.ts +8 -4
- package/src/cli-agent-reads.ts +2 -1
- package/src/cli.ts +82 -32
- package/src/commands-table.ts +6 -3
- package/src/hooks.ts +4 -0
- package/src/index.ts +5 -0
- package/src/memory/capacity-text.ts +100 -0
- package/src/memory/capacity.ts +0 -92
- package/src/memory/commands.ts +6 -1
- package/src/memory/curated-cache-state.ts +22 -3
- package/src/memory/doctor-text.ts +148 -0
- package/src/memory/doctor.ts +19 -141
- package/src/memory/eval-audit-text.ts +62 -0
- package/src/memory/eval-audit.ts +0 -57
- package/src/memory/eval-text.ts +32 -0
- package/src/memory/eval.ts +0 -28
- package/src/memory/formats.ts +2 -0
- package/src/memory/gc-text.ts +22 -0
- package/src/memory/gc.ts +0 -19
- package/src/memory/generation-index.ts +1 -1
- package/src/memory/index-file.ts +1 -1
- package/src/memory/metrics.ts +18 -10
- package/src/memory/migrate-text.ts +32 -0
- package/src/memory/migrate.ts +0 -29
- package/src/memory/project-export.ts +9 -4
- package/src/memory/prune-text.ts +29 -0
- package/src/memory/prune.ts +0 -26
- package/src/memory/report-text.ts +2 -0
- package/src/memory/roots.ts +145 -0
- package/src/memory/shard-migration-text.ts +40 -0
- package/src/memory/shard-migration.ts +0 -37
- package/src/memory/status-text.ts +5 -1
- package/src/memory/store.ts +112 -17
- package/src/memory/sync-placement-activation-locks.ts +7 -5
- package/src/memory/sync-placement-advertisement.ts +18 -0
- package/src/memory/sync-placement-bound.ts +2 -2
- package/src/memory/sync-placement-checkpoint-person.ts +2 -2
- package/src/memory/sync-placement-inventory.ts +4 -1
- package/src/memory/sync-placement-noop-cache.ts +93 -0
- package/src/memory/sync-placement-refusal-category.ts +18 -0
- package/src/memory/sync-placement-transport.ts +80 -13
- package/src/memory/sync-placement-writer-renewal.ts +3 -1
- package/src/memory/sync-progress-text.ts +7 -0
- package/src/memory/sync-progress.ts +21 -7
- package/src/memory/sync-screen.ts +13 -0
- package/src/memory/work-lists.ts +6 -4
- package/src/session-brief.ts +16 -2
- package/src/setup-drift.ts +1 -1
- package/src/setup-writer-roots.ts +136 -0
- package/src/setup.ts +8 -118
- package/src/sync-placement-writer-context.ts +9 -4
- package/src/ui/inbox.ts +1 -1
- package/src/ui/plugin.ts +4 -2
- package/src/work-brief-preparation.ts +28 -0
package/README.md
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
Curated memory with append-only JSONL logs, a derived SQLite index, short- and long-term tiers, a typed graph, goals with leases, and git sync between machines. Extracted from [agent-hub](https://github.com/STAIxBWLB/agent-hub), with compatible storage and entry IDs.
|
|
4
4
|
|
|
5
5
|
<!-- facts:version -->
|
|
6
|
-
Version: 0.
|
|
6
|
+
Version: 0.40.0. Requires Bun 1.4.2 or later; runtime dependencies: @staix/cli-output.
|
|
7
7
|
<!-- /facts:version -->
|
|
8
8
|
|
|
9
9
|
## Quick start
|
package/package.json
CHANGED
package/src/brief-curated.ts
CHANGED
|
@@ -6,6 +6,8 @@ import { BRIEF_CACHE_BYTES, writeBriefCache, type BriefCacheRow } from "./brief-
|
|
|
6
6
|
import { PREFERENCE_SLOT } from "./memory/preference-brief.ts";
|
|
7
7
|
import { taskGroupKey } from "./memory/task-group.ts";
|
|
8
8
|
|
|
9
|
+
// The longest serialized Date.parse result (or null) fits this reservation.
|
|
10
|
+
const EXPIRY_RESERVATION = -8_640_000_000_000_000;
|
|
9
11
|
const PAGE_ROWS = 32, MAX_PAGES = 4, SECTION_RECORDS = 4, RECORD_BYTES = 768, MAX_AGE = 24 * 60 * 60 * 1000;
|
|
10
12
|
|
|
11
13
|
/** Canonical curated display shared by the library brief and snapshot writer. */
|
|
@@ -54,8 +56,9 @@ export function buildPreferenceBriefCache(store: Pick<MemoryStore, "readPreferen
|
|
|
54
56
|
options: { base: string; project: string; directory: string; binding: string; cwd?: string; now?: () => number; policy?: StandalonePolicyOptions }): void {
|
|
55
57
|
if (options.policy?.host) throw new Error("prebuilt preference brief requires synchronous standalone policy; remove host policy or use the async session brief");
|
|
56
58
|
const now = (options.now ?? Date.now)(), policy = createStandalonePolicy(configuredPolicyOptions(options.base, options.cwd, options.policy));
|
|
59
|
+
const builtThrough = Math.max(1, now);
|
|
57
60
|
const rows: BriefCacheRow[] = [], expires: number[] = [];
|
|
58
|
-
let partial = false, bytes = Buffer.byteLength(JSON.stringify({ schema: "agent-mem.brief-cache/v1", project: options.project, section: "preferences", builtThrough
|
|
61
|
+
let partial = false, bytes = Buffer.byteLength(JSON.stringify({ schema: "agent-mem.brief-cache/v1", project: options.project, section: "preferences", builtThrough, partial: false, rows: [], preferences: { builtAt: now, binding: options.binding, expiresAt: EXPIRY_RESERVATION } })) + 1;
|
|
59
62
|
store.withDeferredPromotions(() => {
|
|
60
63
|
// Newest first with no paging: the slot must not hide an old preference behind newer notes of other kinds.
|
|
61
64
|
const page = store.readPreferences(options.project, PREFERENCE_SLOT);
|
|
@@ -76,7 +79,7 @@ export function buildPreferenceBriefCache(store: Pick<MemoryStore, "readPreferen
|
|
|
76
79
|
});
|
|
77
80
|
const expiresAt = expires.length ? Math.min(...expires) : null;
|
|
78
81
|
writeBriefCache({ directory: options.directory, project: options.project, section: "preferences" }, {
|
|
79
|
-
schema: "agent-mem.brief-cache/v1", project: options.project, section: "preferences", builtThrough
|
|
82
|
+
schema: "agent-mem.brief-cache/v1", project: options.project, section: "preferences", builtThrough, partial, rows,
|
|
80
83
|
preferences: { builtAt: now, binding: options.binding, expiresAt },
|
|
81
84
|
});
|
|
82
85
|
}
|
|
@@ -85,10 +88,11 @@ export function buildCuratedBriefCache(store: Pick<MemoryStore, "readPage" | "wi
|
|
|
85
88
|
options: { base: string; project: string; directory: string; binding: string; cwd?: string; now?: () => number; policy?: StandalonePolicyOptions }): void {
|
|
86
89
|
if (options.policy?.host) throw new Error("prebuilt curated brief requires synchronous standalone policy; remove host policy or use the async session brief");
|
|
87
90
|
const now = (options.now ?? Date.now)(), policy = createStandalonePolicy(configuredPolicyOptions(options.base, options.cwd, options.policy));
|
|
91
|
+
const builtThrough = Math.max(1, now);
|
|
88
92
|
const rows: BriefCacheRow[] = [], expires: number[] = [];
|
|
89
93
|
let partial = false, after: { position: number; id: string } | undefined, complete = false;
|
|
90
94
|
const tasks = new Set<string>(); // #423: one row per task, the first in page order; later same-task rows take no slot
|
|
91
|
-
let bytes = Buffer.byteLength(JSON.stringify({ schema: "agent-mem.brief-cache/v1", project: options.project, section: "curated", builtThrough
|
|
95
|
+
let bytes = Buffer.byteLength(JSON.stringify({ schema: "agent-mem.brief-cache/v1", project: options.project, section: "curated", builtThrough, partial: false, rows: [], curated: { builtAt: now, binding: options.binding, expiresAt: EXPIRY_RESERVATION } })) + 1;
|
|
92
96
|
store.withDeferredPromotions(() => {
|
|
93
97
|
for (let pageNo = 0; pageNo < MAX_PAGES; pageNo++) {
|
|
94
98
|
const page = store.readPage({ project: options.project, limit: PAGE_ROWS, after });
|
|
@@ -117,7 +121,7 @@ export function buildCuratedBriefCache(store: Pick<MemoryStore, "readPage" | "wi
|
|
|
117
121
|
});
|
|
118
122
|
const expiresAt = expires.length ? Math.min(...expires) : null;
|
|
119
123
|
writeBriefCache({ directory: options.directory, project: options.project, section: "curated" }, {
|
|
120
|
-
schema: "agent-mem.brief-cache/v1", project: options.project, section: "curated", builtThrough
|
|
124
|
+
schema: "agent-mem.brief-cache/v1", project: options.project, section: "curated", builtThrough, partial, rows,
|
|
121
125
|
curated: { builtAt: now, binding: options.binding, expiresAt },
|
|
122
126
|
});
|
|
123
127
|
}
|
package/src/cli-agent-reads.ts
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import { noteDisplayActor } from "./memory/cli-attribution.ts";
|
|
2
2
|
import { memoryDetailText, memoryRecordText, memoryScoresText, memoryTableText, PLAIN, type HumanMemoryRow, type Style } from "./memory/style.ts";
|
|
3
3
|
import type { View } from "./memory/store.ts";
|
|
4
|
-
import {
|
|
4
|
+
import { type CapacityReport } from "./memory/capacity.ts";
|
|
5
|
+
import { capacityText } from "./memory/capacity-text.ts";
|
|
5
6
|
import { createMemoryMcp } from "./mcp-memory.ts";
|
|
6
7
|
import { safeProfileLockMessage } from "./memory/profile-lock-diagnostic.ts";
|
|
7
8
|
import { memoryHome } from "./memory/home.ts";
|
package/src/cli.ts
CHANGED
|
@@ -9,6 +9,7 @@ import { cliAttribution, withCliAttribution } from "./memory/cli-attribution.ts"
|
|
|
9
9
|
import { createHash, randomUUID } from "node:crypto";
|
|
10
10
|
import type { Writable } from "node:stream";
|
|
11
11
|
import { buildIntentBrief } from "./memory/intent-brief.ts";
|
|
12
|
+
import { prepareWorkBriefCache } from "./work-brief-preparation.ts";
|
|
12
13
|
import { proposeConsolidation } from "./memory/consolidate.ts";
|
|
13
14
|
import { recordCaptureLookup, recordSourceCheck, recordWindow } from "./memory/record-candidates.ts";
|
|
14
15
|
import { createIntentBriefSource, recallViewIsLive } from "./memory/recall.ts";
|
|
@@ -21,6 +22,7 @@ import { PLACEMENT_CHECKPOINT_PENDING_MESSAGE } from "./memory/sync-placement-jo
|
|
|
21
22
|
import { MCP_TOOLS, serveMcp, writeConfirmed } from "./mcp.ts";
|
|
22
23
|
import { createStandalonePolicy } from "./memory/policy.ts";
|
|
23
24
|
import { configuredPolicy, configuredPolicyOptions, loadAmemConfig, repoConfigRoot } from "./memory/config.ts";
|
|
25
|
+
import { deterministicRowScreen } from "./memory/sync-screen.ts";
|
|
24
26
|
import { vaultCandidates, vaultCandidatesText, vaultCandidatesAllText } from "./memory/vault.ts";
|
|
25
27
|
import type { IngestKind, IngestReceipt } from "./ingest.ts";
|
|
26
28
|
import { importClaudeMemCapture, importClaudeMemWorkState } from "./memory/import.ts";
|
|
@@ -36,8 +38,10 @@ import { memoryProjectKey } from "./memory/project.ts";
|
|
|
36
38
|
import { CandidateStore, candidateInputId, candidateTargetRevision, type CandidateFilter } from "./memory/candidates.ts";
|
|
37
39
|
import { candidateOverlaps, candidateOverlapsBatch } from "./memory/candidate-overlaps.ts";
|
|
38
40
|
import { openCuratedForRead } from "./memory/curated-read.ts";
|
|
39
|
-
import { aliasedKeys, appendAlias, appendUnalias, listAliases, readShardedSelection, resolveAlias } from "./memory/shard.ts";
|
|
40
|
-
import {
|
|
41
|
+
import { aliasedKeys, appendAlias, appendUnalias, listAliases, readShardedSelection, resolveAlias, shardDir } from "./memory/shard.ts";
|
|
42
|
+
import { curatedCount, projectTransition, recordKeepSeparate, rootsLogPath, transitionKey } from "./memory/roots.ts";
|
|
43
|
+
import { capacityReport } from "./memory/capacity.ts";
|
|
44
|
+
import { capacityText, capacityApplyText, capacitySplitText } from "./memory/capacity-text.ts";
|
|
41
45
|
import { CaptureStore, readCaptureConfigFile, writeCaptureConfigFile, type CaptureConfig } from "./memory/capture.ts";
|
|
42
46
|
|
|
43
47
|
import { COMMANDS, CommandUsageError, commandHelp, commandPath, parseCommand, usageLine } from "./commands-table.ts";
|
|
@@ -45,13 +49,18 @@ import { completionScript } from "./completion.ts";
|
|
|
45
49
|
import { memoryHome, resolveMemoryHome } from "./memory/home.ts";
|
|
46
50
|
import { realPath } from "./memory/platform.ts";
|
|
47
51
|
import { RemoteRealmRefusal } from "./memory/sync-placement-remote-refusal.ts";
|
|
52
|
+
import { placementSyncBoundMessage, placementSyncBoundReceipt } from "./memory/sync-placement-bound.ts";
|
|
48
53
|
import { hashJSON, readSelector, resolveProfile } from "./memory/generation.ts";
|
|
49
|
-
import { migrate
|
|
50
|
-
import {
|
|
51
|
-
import {
|
|
54
|
+
import { migrate } from "./memory/migrate.ts";
|
|
55
|
+
import { migrationText } from "./memory/migrate-text.ts";
|
|
56
|
+
import { migrateShards, shardMigrationStatus } from "./memory/shard-migration.ts";
|
|
57
|
+
import { shardMigrationText } from "./memory/shard-migration-text.ts";
|
|
58
|
+
import { applyPrune, planPrune, PRUNE_PLAN_MAX_BYTES } from "./memory/prune.ts";
|
|
59
|
+
import { pruneText } from "./memory/prune-text.ts";
|
|
52
60
|
import { readCatalogFresh } from "./memory/catalog.ts";
|
|
53
61
|
import { appendLifecycle, assertProjectActive, projectState } from "./memory/lifecycle.ts";
|
|
54
|
-
import {
|
|
62
|
+
import { runGc } from "./memory/gc.ts";
|
|
63
|
+
import { gcText } from "./memory/gc-text.ts";
|
|
55
64
|
import { usageReport, usageText } from "./memory/usage.ts";
|
|
56
65
|
import * as reports from "./memory/report-text.ts";
|
|
57
66
|
import { exportProject, type ProjectExportFormat } from "./memory/project-export.ts";
|
|
@@ -63,13 +72,15 @@ import { requireShard } from "./memory/curated-read.ts";
|
|
|
63
72
|
import { appendGitattributes, appendRepoLine, boundRepoRoot, planGitattributes, planRepoPromotion, readRepoScope, repoLogIgnored, repoLogPath, repoReadPolicy, repoVisibility } from "./memory/repo-scope.ts";
|
|
64
73
|
import type { Visibility } from "./memory/sync.ts";
|
|
65
74
|
import { applySplit, previewSplit } from "./memory/capacity-split.ts";
|
|
66
|
-
import {
|
|
75
|
+
import { parseKs } from "./memory/eval.ts";
|
|
76
|
+
import { evalText } from "./memory/eval-text.ts";
|
|
67
77
|
import { unrankedScoreDetails } from "./memory/search-score.ts";
|
|
68
78
|
import { builtinSet, evalSeeded, evalStore, FIXTURE_PATH, readEvalSet } from "./memory/eval-fixture.ts";
|
|
69
79
|
import { markShown, pendingSummary } from "./memory/candidate-pending.ts";
|
|
70
80
|
import { buildNote, FAIL_TEMPLATE, hasFailLabel, noteAdd, parseFailTemplate, type FailFields } from "./memory/note-add.ts";
|
|
71
81
|
import { runEditor } from "./memory/editor.ts";
|
|
72
|
-
import { doctorReport
|
|
82
|
+
import { doctorReport } from "./memory/doctor.ts";
|
|
83
|
+
import { doctorText } from "./memory/doctor-text.ts";
|
|
73
84
|
import { statusText, type StatusView } from "./memory/status-text.ts";
|
|
74
85
|
import { asciiMarkers, errorLine, errorSpans, EXIT, markerCell, paint, Report, resolveColor, streamEnv } from "@staix/cli-output";
|
|
75
86
|
import { style, facts, label, memoryRecordText, memoryScoresText, memoryTableText, PLAIN, singleLine, wordedKey, type Style } from "./memory/style.ts";
|
|
@@ -409,6 +420,10 @@ export async function runCli(argv: readonly string[], context: CliContext = {}):
|
|
|
409
420
|
let usage: Error | undefined, parsed: ReturnType<typeof parseCommand> | undefined;
|
|
410
421
|
try { parsed = parseCommand(argv); } catch (parseError) { usage = parseError as Error; }
|
|
411
422
|
if (usage) throw Object.assign(new Error(usage.message), (error as { exitCode?: number }).exitCode === undefined ? {} : { exitCode: (error as { exitCode?: number }).exitCode });
|
|
423
|
+
if (parsed?.path[0] === "sync") {
|
|
424
|
+
const bound = placementSyncBoundReceipt(error);
|
|
425
|
+
if (bound) throw new Error(placementSyncBoundMessage(bound));
|
|
426
|
+
}
|
|
412
427
|
const setupError = parsed && markedSetupApplyError(parsed, error);
|
|
413
428
|
if (setupError) throw setupError;
|
|
414
429
|
if (parsed && markedReadOnly(parsed)) {
|
|
@@ -497,7 +512,7 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
497
512
|
if (parsed.path[0] === "version") return `amem ${VERSION}`;
|
|
498
513
|
if (parsed.path[0] === "manifest") return JSON.stringify(manifest(), null, parsed.options["--json"] === true ? undefined : 2);
|
|
499
514
|
if (parsed.path[0] === "completion") {
|
|
500
|
-
if (parsed.positionals.length !== 1) throw new
|
|
515
|
+
if (parsed.positionals.length !== 1) throw new CommandUsageError("usage: amem completion zsh|bash|fish");
|
|
501
516
|
return completionScript(parsed.positionals[0]!);
|
|
502
517
|
}
|
|
503
518
|
} catch (error) {
|
|
@@ -522,7 +537,7 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
522
537
|
const chosen = [options["--confirm"] === true, options["--resume"] === true, options["--abandon"] === true].filter(Boolean).length;
|
|
523
538
|
if (options["--admit"] !== undefined || options["--list-remote"] === true || options["--from-remote"] === true || options["--apply"] === true || options["--dry-run"] === true || chosen > 1 || (options["--confirm"] === true) !== (options["--plan"] !== undefined)
|
|
524
539
|
|| (options["--resume"] === true || options["--abandon"] === true) && options["--writer-root"] !== undefined)
|
|
525
|
-
throw new AgentUsageError("A placement checkpoint
|
|
540
|
+
throw new AgentUsageError("A placement checkpoint previews with --sync-placement --checkpoint --writer-root <install root> (repeat), saves the plan with (umask 077; set -C; amem migrate --sync-placement --checkpoint --writer-root <install root> --json > checkpoint-plan.json), then confirms with amem migrate --sync-placement --checkpoint --confirm --plan checkpoint-plan.json and the same writer roots, or uses --resume / --abandon alone.");
|
|
526
541
|
} else if (options["--plan"] !== undefined) {
|
|
527
542
|
throw new AgentUsageError("--plan applies only to --sync-placement --checkpoint --confirm.");
|
|
528
543
|
} else if (options["--admit"] !== undefined) {
|
|
@@ -535,7 +550,7 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
535
550
|
throw new AgentUsageError("--writer-root, --abandon, --admit, --list-remote, --from-remote, --checkpoint and --plan apply only to --sync-placement; run amem migrate --sync-placement --dry-run to review the inventory.");
|
|
536
551
|
}
|
|
537
552
|
if (parsed.path[0] === "skills" && parsed.path[1] === "export") {
|
|
538
|
-
if (parsed.positionals.length !== 1) throw new
|
|
553
|
+
if (parsed.positionals.length !== 1) throw new CommandUsageError("usage: amem skills export <dir> [--json]");
|
|
539
554
|
const { exportSkills } = await import("./skills-install.ts");
|
|
540
555
|
const destination = parsed.positionals[0]!;
|
|
541
556
|
const report = exportSkills(destination.trim() ? resolve(context.cwd ?? process.cwd(), destination) : destination, { env: context.env ?? process.env });
|
|
@@ -545,7 +560,7 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
545
560
|
}
|
|
546
561
|
if (parsed.path[0] === "setup") {
|
|
547
562
|
if (parsed.positionals.length !== 1 || options["--apply"] === true && options["--undo"] === true
|
|
548
|
-
|| options["--adopt-current"] === true && (options["--apply"] !== true || parsed.positionals[0] === "console")) throw new
|
|
563
|
+
|| options["--adopt-current"] === true && (options["--apply"] !== true || parsed.positionals[0] === "console")) throw new CommandUsageError("usage: amem setup claude|codex|kimi|pi|qwen|jcode|opencode|gemini|agy|all|console [--root <abs path>] [--apply [--adopt-current]|--undo]");
|
|
549
564
|
if (parsed.positionals[0] === "console") {
|
|
550
565
|
const { consoleSetup, consoleSetupText } = await import("./setup-console.ts");
|
|
551
566
|
const mode = options["--apply"] === true ? "apply" : options["--undo"] === true ? "undo" : "preview";
|
|
@@ -627,7 +642,7 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
627
642
|
} finally { candidates?.close(); store.close(); }
|
|
628
643
|
}
|
|
629
644
|
if (sub === "brief") {
|
|
630
|
-
const intent = options["--for"]; if (typeof intent !== "string" || !intent.trim() || intent.length > 1000 || parsed.positionals.length) throw
|
|
645
|
+
const intent = options["--for"]; if (typeof intent !== "string" || !intent.trim() || intent.length > 1000 || parsed.positionals.length) throw new CommandUsageError("usage: amem brief --for <intent> [--paths <path>] [--symbols <symbol>] [--bytes N] [--json]");
|
|
631
646
|
const rawBytes = options["--bytes"];
|
|
632
647
|
if (rawBytes !== undefined && !/^[1-9][0-9]*$/.test(String(rawBytes))) throw Error("brief bytes must be a positive decimal integer");
|
|
633
648
|
const maxBytes = rawBytes === undefined ? 2048 : Number(rawBytes); if (!Number.isSafeInteger(maxBytes) || maxBytes > 8192) throw Error("brief bytes must be 1..8192");
|
|
@@ -640,6 +655,7 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
640
655
|
const settings = () => configuredPolicyOptions(base, policyCwd), policyKey = () => hashJSON(settings()), revision = policyKey(), snapshot = createStandalonePolicy(settings());
|
|
641
656
|
const policy = () => snapshot, policyVersion = () => policyKey();
|
|
642
657
|
if (policyVersion() !== revision) throw Error("brief policy changed before read");
|
|
658
|
+
await prepareWorkBriefCache(base, project, policyCwd);
|
|
643
659
|
const result = await buildIntentBrief(createIntentBriefSource(store, project),
|
|
644
660
|
{ project, cwd: root, repo: project, intent, paths, symbols, maxBytes, policy, policyVersion, assertCurrent, now: () => store.readNow(), stale: createRecallStalenessProbe({ cwd: root, rootConfirmed, policy }) });
|
|
645
661
|
assertCurrent(); outputReady(result.items.map(view => view.id), project);
|
|
@@ -695,7 +711,7 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
695
711
|
+ `completed plan: ${h.completedPlan.slots} slots + ${h.completedPlan.reservedJournalChunks} reserved journal chunks; prospective plan: ${h.prospectivePlan.state === "cache-only" ? `${h.prospectivePlan.slots} slots + ${h.prospectivePlan.reservedJournalChunks} reserved journal chunks (cache-only; remote may have changed)` : h.prospectivePlan.state === "none" ? "none" : "unavailable without current remote evidence; using completed history"}\n`
|
|
696
712
|
+ `headroom after checkpoint: ${h.remaining} of ${h.limit} (live ${h.liveAfter}, next renewal ${h.nextRenewal}, largest plan ${h.largestPlan.slots} + ${h.largestPlan.reservedJournalChunks} reserved journal chunks)\n`
|
|
697
713
|
+ `home floor ${preview.requiredHomeFloor}: ${preview.floorReady ? "ready" : `missing; preview amem formats raise home ${preview.requiredHomeFloor}, then --confirm it`}; writers ${preview.writers}; plan ${preview.planHash}\n`
|
|
698
|
-
+ `next:
|
|
714
|
+
+ `next: ${preview.nextStep}\n`;
|
|
699
715
|
}
|
|
700
716
|
if (options["--admit"] !== undefined) {
|
|
701
717
|
const { previewRealmAdmission, planRealmAbandon, applyRealmAdmission } = await import("./memory/sync-placement-realm-admission.ts");
|
|
@@ -760,14 +776,17 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
760
776
|
candidates: (() => { const bound = boundProject(), summary = pendingSummary(where.home, [bound, ...aliasedKeys(where.home, bound)], Date.now(), true);
|
|
761
777
|
if (summary === null) return { unavailable: "candidates.db exists but cannot be read" };
|
|
762
778
|
return { ...summary, ...(summary.dueWithin7Days ? { warning: `${summary.dueWithin7Days} candidate${summary.dueWithin7Days === 1 ? "" : "s"} within 7 days of expiry: run \`amem review walk\`` } : {}) }; })(),
|
|
763
|
-
...shardMigrationStatus(where.home)
|
|
779
|
+
...shardMigrationStatus(where.home),
|
|
780
|
+
// #581: read-only (the SessionStart hook is the only writer of roots.jsonl); present only during a transition, so the default shape is unchanged.
|
|
781
|
+
...(() => { try { const t = projectTransition(where.home, policyCwd, transitionKey(policyCwd), key => curatedCount(where.home, key, shardDir));
|
|
782
|
+
return t ? { projectTransition: { previousKey: t.previousKey, key: t.key, previousCuratedNotes: t.previousCuratedNotes, aliasCommand: t.aliasCommand, keepCommand: t.keepCommand } } : {}; } catch { return {}; } })() };
|
|
764
783
|
return options["--json"] ? JSON.stringify(status, null, 2) : statusText(status as unknown as StatusView, outputStyle(context, options), reportOptions(context, options));
|
|
765
784
|
}
|
|
766
785
|
if (parsed.path[0] === "formats" && parsed.path[1] === "raise") {
|
|
767
786
|
const { planFormatRaise, applyFormatRaise, formatRaiseRefusal, installVersion, runningAmemRoots } = await import("./memory/formats-raise.ts");
|
|
768
787
|
const { readSetupWriterRoots } = await import("./setup.ts"), { readEffectiveSyncPlacementWriterRoots } = await import("./memory/sync-placement-effective-writers.ts");
|
|
769
788
|
const [surface, minReader] = parsed.positionals;
|
|
770
|
-
if (!surface || !minReader || parsed.positionals.length !== 2) throw new
|
|
789
|
+
if (!surface || !minReader || parsed.positionals.length !== 2) throw new CommandUsageError("formats raise requires a surface and minimum reader version");
|
|
771
790
|
const home = realPath(memoryHome()), own = realPath(fileURLToPath(new URL("..", import.meta.url)));
|
|
772
791
|
const inventory = (): import("./memory/formats-raise.ts").FormatWriterInventory => {
|
|
773
792
|
const writers: import("./memory/formats-raise.ts").FormatWriter[] = [], incomplete: string[] = [], seen = new Set<string>();
|
|
@@ -1142,7 +1161,7 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
1142
1161
|
// F13: read-only. A set with entries is scored against a throwaway store seeded with them (touches no memory home); one without scores the bound project's real entries.
|
|
1143
1162
|
if (parsed.path[1] === "audit") {
|
|
1144
1163
|
// #326: a private local sheet plus a content-free score. Judging happens outside amem, so nothing on this path calls a model or the network.
|
|
1145
|
-
const audit = await import("./memory/eval-audit.ts"), { MAX_AUDIT_NOTES } = await import("./memory/eval.ts");
|
|
1164
|
+
const audit = await import("./memory/eval-audit.ts"), auditText = await import("./memory/eval-audit-text.ts"), { MAX_AUDIT_NOTES } = await import("./memory/eval.ts");
|
|
1146
1165
|
if (parsed.path[2] === "sample") {
|
|
1147
1166
|
const n = options["--n"] === undefined ? 40 : Number(options["--n"]), seed = typeof options["--seed"] === "string" ? options["--seed"] : "";
|
|
1148
1167
|
if (!Number.isInteger(n) || n < 1 || n > MAX_AUDIT_NOTES) throw new Error(`--n must be an integer from 1 to ${MAX_AUDIT_NOTES}`);
|
|
@@ -1164,15 +1183,15 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
1164
1183
|
try { sheet = audit.auditSample({ store, project, n, seed, root, asOf, screen: view => screen.screenStandalone(view) }); } finally { store.close(); }
|
|
1165
1184
|
const out = typeof options["--out"] === "string" ? options["--out"] : join(memoryHome(), "eval", `audit-${project.replace(/[^A-Za-z0-9._-]+/g, "-").slice(0, 80)}-${seed}.json`);
|
|
1166
1185
|
const file = audit.writeAuditSheet(out, sheet);
|
|
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(
|
|
1186
|
+
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(auditText.auditSheetText(sheet, file), auditText.auditSheetText(sheet, file, { columns: reportWidth(context) ?? 80, style: outputStyle(context, options), ...(context.now ? { now: context.now() } : {}) }));
|
|
1168
1187
|
}
|
|
1169
1188
|
if (parsed.path[2] === "score") {
|
|
1170
1189
|
const [sheet] = parsed.positionals;
|
|
1171
|
-
if (!sheet) throw new
|
|
1190
|
+
if (!sheet) throw new CommandUsageError("usage: amem eval audit score <sheet> (the file `amem eval audit sample` wrote)");
|
|
1172
1191
|
const score = audit.auditScore(audit.readAuditSheet(sheet));
|
|
1173
|
-
return options["--json"] === true ? JSON.stringify(score, null, 2) : screenedLegacy(
|
|
1192
|
+
return options["--json"] === true ? JSON.stringify(score, null, 2) : screenedLegacy(auditText.auditScoreText(score), auditText.auditScoreText(score, { columns: reportWidth(context) ?? 80, style: outputStyle(context, options), ...(context.now ? { now: context.now() } : {}) }));
|
|
1174
1193
|
}
|
|
1175
|
-
throw new
|
|
1194
|
+
throw new CommandUsageError("usage: amem eval audit sample --seed <s> [--n <n>] [--project <key>] | amem eval audit score <sheet>");
|
|
1176
1195
|
}
|
|
1177
1196
|
const ks = parseKs(typeof options["--k"] === "string" ? options["--k"] : undefined);
|
|
1178
1197
|
const file = typeof options["--set"] === "string" ? options["--set"] : undefined;
|
|
@@ -1276,6 +1295,20 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
1276
1295
|
: result.checked ? `no ${source} memory found; checked ${result.checked.join(" and ")}`
|
|
1277
1296
|
: `imported ${result.added} ${source} candidates from ${result.files} files (${result.read} records, ${result.pending.count} pending); skipped ${result.skipped.rules} rule files, ${result.skipped.policy} policy/secret records, ${result.skipped.invalid} invalid records and ${result.skipped.truncated} oversized inputs${result.queueFull ? "; candidate queue is full" : result.limitReached ? "; per-run candidate cap reached" : ""}`;
|
|
1278
1297
|
}
|
|
1298
|
+
if (sub === "project" && parsed.path[1] === "keep-separate") {
|
|
1299
|
+
// #581: end a project-key transition for this directory without joining the keys. Preview without --confirm.
|
|
1300
|
+
const home = memoryHome(), key = transitionKey(policyCwd);
|
|
1301
|
+
const transition = projectTransition(home, policyCwd, key, previous => curatedCount(home, previous, shardDir));
|
|
1302
|
+
if (!transition) throw Object.assign(new Error("no project key transition for this directory: nothing to keep apart. Run amem status to see the bound project."), { exitCode: 2 });
|
|
1303
|
+
if (options["--confirm"] !== true) {
|
|
1304
|
+
const preview = { preview: true, previousKey: transition.previousKey, key: transition.key, previousCuratedNotes: transition.previousCuratedNotes, file: rootsLogPath(home), confirmCommand: "amem project keep-separate --confirm" };
|
|
1305
|
+
return options["--json"] ? JSON.stringify(preview, null, 2)
|
|
1306
|
+
: `preview: keep ${transition.key} apart from ${transition.previousKey} for this directory. Appends one keep line to ${rootsLogPath(home)}; no key is joined and no note moves. Run: amem project keep-separate --confirm`;
|
|
1307
|
+
}
|
|
1308
|
+
const line = recordKeepSeparate(home, policyCwd, transition);
|
|
1309
|
+
return options["--json"] ? JSON.stringify({ kept: { previousKey: line.prev, key: line.key, at: line.at }, file: rootsLogPath(home) }, null, 2)
|
|
1310
|
+
: `kept ${line.key} apart from ${line.prev} for this directory; the notice stops. To join them later: ${transition.aliasCommand}`;
|
|
1311
|
+
}
|
|
1279
1312
|
if (sub === "project") {
|
|
1280
1313
|
const op = parsed.path[1]!, [requested] = parsed.positionals;
|
|
1281
1314
|
if (!requested) throw new Error(`usage: amem project ${op} <key>`);
|
|
@@ -1283,8 +1316,8 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
1283
1316
|
if (typeof options["--to"] !== "string") throw new Error("usage: amem project export <key> --to <file>");
|
|
1284
1317
|
const format = (options["--format"] ?? "json") as ProjectExportFormat;
|
|
1285
1318
|
// The bundle leaves the home, so it is screened by the configured policy (secrets, personal data, the configured patterns and deny paths).
|
|
1286
|
-
const result = await exportProject(memoryHome(), requested, { to: options["--to"], policy: policyOf(), format });
|
|
1287
|
-
return options["--json"] ? JSON.stringify(result, null, 2) : `exported ${result.project} to ${result.file} as ${result.format}: ${result.counts.
|
|
1319
|
+
const result = await exportProject(memoryHome(), requested, { to: options["--to"], policy: policyOf(), format, includeCapture: options["--include-capture"] === true });
|
|
1320
|
+
return options["--json"] ? JSON.stringify(result, null, 2) : `exported ${result.project} to ${result.file} as ${result.format}: ${result.counts.curated} notes, ${result.counts.goals} goals, ${result.counts.workLists} work lists, ${result.counts.capture} capture rows (${result.capture === "included" ? "included" : "excluded; add --include-capture"}); ${result.withheld} withheld by the screen`;
|
|
1288
1321
|
}
|
|
1289
1322
|
if (op === "import") {
|
|
1290
1323
|
if (typeof options["--from"] !== "string") throw new Error("usage: amem project import <key> --from <file.jsonl> [--confirm] [--allow-shared]");
|
|
@@ -1323,7 +1356,7 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
1323
1356
|
if (options["--explain"] === true) throw new Error("--explain applies to current-project ranked search, not --all-projects");
|
|
1324
1357
|
if (options["--filter"] === true) throw new Error("--filter applies to project-local search, not --all-projects");
|
|
1325
1358
|
const words = parsed.positionals.join(" ");
|
|
1326
|
-
if (!words.trim()) throw new
|
|
1359
|
+
if (!words.trim()) throw new CommandUsageError("usage: amem search --all-projects <words> [--limit N] [--include-archived] [--json]");
|
|
1327
1360
|
const result = searchAllProjects(memoryHome(), words, { ...(options["--limit"] !== undefined ? { limit: Number(options["--limit"]) } : {}), includeArchived: options["--include-archived"] === true });
|
|
1328
1361
|
if (options["--json"]) return JSON.stringify(result, null, 2);
|
|
1329
1362
|
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)}`;
|
|
@@ -1381,7 +1414,7 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
1381
1414
|
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");
|
|
1382
1415
|
if (sub === "promote" && options["--to"] !== undefined) {
|
|
1383
1416
|
const idText = parsed.positionals[0];
|
|
1384
|
-
if (!idText || parsed.positionals.length !== 1) throw new
|
|
1417
|
+
if (!idText || parsed.positionals.length !== 1) throw new CommandUsageError("usage: amem promote <id> --to repo --policy-free [--confirm [--confirm-public <entry id prefix>]]");
|
|
1385
1418
|
const project = boundProject(), root = boundRepoRoot(repoCwd, memoryHome(), project);
|
|
1386
1419
|
if (!root) throw new Error("repo scope needs the working tree of the repository that is this project: run it from inside that repository");
|
|
1387
1420
|
const store = curatedStore(project, { deferPromotions: true, screen: () => "skip" });
|
|
@@ -1543,26 +1576,40 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
1543
1576
|
let output: string;
|
|
1544
1577
|
let placementWriters: import("./sync-placement-writer-context.ts").PlacementWriterContext | undefined;
|
|
1545
1578
|
let progress: import("./memory/sync-progress.ts").SyncProgress | undefined;
|
|
1579
|
+
let writerRefusal: import("./memory/sync-placement-refusal-category.ts").PlacementWriterRefusal | undefined;
|
|
1580
|
+
let attestPlacement: import("./sync-placement-writer-context.ts").PlacementWriterContext["attest"] | undefined;
|
|
1546
1581
|
const stop = ifDue ? stopSignal(context.syncDeadlineMs ?? SYNC_IF_DUE_DEADLINE_MS, process) : undefined;
|
|
1547
1582
|
try {
|
|
1548
1583
|
if (sub === "sync" && (readPlacementRuntimeMarkers(syncHome).profile as { publicationFormat?:string } | undefined)?.publicationFormat === "agent-mem.sync-placement/v1") {
|
|
1549
|
-
const { activePlacementWriterContext } = await import("./sync-placement-writer-context.ts");
|
|
1550
|
-
progress = await placementProgress(syncHome, typeof options["--progress"] === "string" ? options["--progress"] as string : "auto", context);
|
|
1584
|
+
const { activePlacementWriterContext, placementWriterRefusalDetail, placementWriterRefusalText } = await import("./sync-placement-writer-context.ts");
|
|
1585
|
+
progress = await placementProgress(syncHome, typeof options["--progress"] === "string" ? options["--progress"] as string : "auto", context, () => writerRefusal);
|
|
1551
1586
|
try { placementWriters = activePlacementWriterContext(syncHome,fileURLToPath(new URL("..",import.meta.url))); }
|
|
1552
1587
|
catch (error) {
|
|
1588
|
+
writerRefusal = placementWriterRefusalDetail(error);
|
|
1553
1589
|
// #551 AC1: a writer-context refusal is this run's own failed result, so --json reports it instead of printing one
|
|
1554
1590
|
// masked line; a human run keeps the refusal's fixed text and exit 1, and every other refusal keeps its own path.
|
|
1555
|
-
const refusal =
|
|
1591
|
+
const refusal = placementWriterRefusalText(error);
|
|
1556
1592
|
if (refusal === undefined || !options["--json"]) throw error;
|
|
1557
1593
|
stampSync(refusal, stop?.cause());
|
|
1558
1594
|
return JSON.stringify({ ok: false, pushed: false, entries: 0, failure: { cause: "refusal" }, error: refusal }, null, 2);
|
|
1559
1595
|
}
|
|
1596
|
+
const attest = placementWriters.attest;
|
|
1597
|
+
attestPlacement = () => {
|
|
1598
|
+
try {
|
|
1599
|
+
const proof = attest();
|
|
1600
|
+
writerRefusal = undefined;
|
|
1601
|
+
return proof;
|
|
1602
|
+
} catch (error) {
|
|
1603
|
+
writerRefusal = placementWriterRefusalDetail(error);
|
|
1604
|
+
throw error;
|
|
1605
|
+
}
|
|
1606
|
+
};
|
|
1560
1607
|
const markers = readPlacementRuntimeMarkers(syncHome);
|
|
1561
1608
|
if (!readActivePlacementBinding(syncHome, markers.profile, markers.shards)) throw Error("sync placement activation metadata unavailable or changed; inspect the retained activation before continuing");
|
|
1562
1609
|
}
|
|
1563
1610
|
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),
|
|
1564
1611
|
// #578 Q2: the CLI sync (also --if-due) is eligible; the home opt-in still decides whether a checkpoint can run.
|
|
1565
|
-
sync: { ...(
|
|
1612
|
+
sync: { ...(attestPlacement ? { placementAttestation: attestPlacement, placementCheckpoint: true } : {}), ...(progress ? { progress } : {}), screen: deterministicRowScreen(configuredPolicyOptions(memoryHome(), policyCwd)), policyVersion: () => JSON.stringify(configuredPolicyOptions(memoryHome(), policyCwd)), ...(stop ? { signal: stop.signal } : {}) }, // the repository-narrowed policy binds what sync publishes too
|
|
1566
1613
|
onBridgeStatus: status => { receipt.bridgeStatus = status; },
|
|
1567
1614
|
// #188: ids-only listing of nearby machine-local rows; policy-refused rows are neither listed nor counted.
|
|
1568
1615
|
forgetNearby: note => forgetNearby({ base: memoryHome(), project: note.project, text: note.text, title: note.title, screen: value => configured.screenStandalone(value) }) }));
|
|
@@ -1611,13 +1658,16 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
1611
1658
|
* #418: one reporter per placement sync. The private sidecar backs `sync --status` in every mode; stderr gets human
|
|
1612
1659
|
* lines or versioned JSON events. Each part fails alone and silently: telemetry never fails or alters the sync.
|
|
1613
1660
|
*/
|
|
1614
|
-
async function placementProgress(home: string, mode: string, context: CliContext): Promise<import("./memory/sync-progress.ts").SyncProgress> {
|
|
1615
|
-
const { SyncProgress, renderSyncProgress, syncProgressSidecar } = await import("./memory/sync-progress.ts");
|
|
1661
|
+
async function placementProgress(home: string, mode: string, context: CliContext, writerRefusal: () => import("./memory/sync-placement-refusal-category.ts").PlacementWriterRefusal | undefined): Promise<import("./memory/sync-progress.ts").SyncProgress> {
|
|
1662
|
+
const { SyncProgress, renderSyncProgress, syncProgressSidecar, syncStatusSnapshot } = await import("./memory/sync-progress.ts");
|
|
1616
1663
|
const write = context.stderr ?? ((text: string) => { process.stderr.write(text); });
|
|
1617
1664
|
const render = mode === "json" ? "json" : mode === "human" || mode === "auto" && (context.stderrTTY ?? process.stderr.isTTY) ? "human" : undefined;
|
|
1618
1665
|
const parts = [syncProgressSidecar(home), ...(render ? [(snapshot: import("./memory/sync-progress.ts").SyncProgressSnapshot) => write((render === "json" ? JSON.stringify(snapshot) : renderSyncProgress(snapshot)) + "\n")] : [])];
|
|
1619
1666
|
const live = new Set(parts.keys());
|
|
1620
|
-
return new SyncProgress({ sink: snapshot => {
|
|
1667
|
+
return new SyncProgress({ sink: snapshot => {
|
|
1668
|
+
const status = syncStatusSnapshot(snapshot, writerRefusal());
|
|
1669
|
+
for (const index of live) try { parts[index]!(status); } catch { live.delete(index); }
|
|
1670
|
+
} });
|
|
1621
1671
|
}
|
|
1622
1672
|
function outputStyle(context: CliContext, options: Record<string, string | boolean>): Style {
|
|
1623
1673
|
const color = resolveColor(typeof options["--color"] === "string" ? options["--color"] : undefined, streamEnv((context.stdoutTTY ?? process.stdout.isTTY) === true, context.env ?? process.env), "amem");
|
package/src/commands-table.ts
CHANGED
|
@@ -121,9 +121,9 @@ export const COMMANDS: Record<string, CommandDefinition> = {
|
|
|
121
121
|
options: { ...json("the gc result"), "--confirm": flag("Evict now; without it, preview only"), "--batches": number("Evict windows per shard (1..1000, default 1)") } },
|
|
122
122
|
project: { group: "maintenance", description: "Export, import, archive or forget one project", options: json("the project receipt"), commands: {
|
|
123
123
|
export: { description: "Write one project's memory to a new export file",
|
|
124
|
-
details: "
|
|
125
|
-
examples: ["amem project export repo@1234abcd --to ./repo.json"],
|
|
126
|
-
options: { ...json("the export receipt"), "--to": path("Destination file, outside the memory home"), "--format": { description: "Portable format (default json)", value: ["json", "jsonl", "markdown"] }, ...policy },
|
|
124
|
+
details: "Curated notes, goals and work lists, as JSON, JSONL or Markdown; capture only with --include-capture. Never overwrites.",
|
|
125
|
+
examples: ["amem project export repo@1234abcd --to ./repo.json", "amem project export repo@1234abcd --to ./repo.json --include-capture"],
|
|
126
|
+
options: { ...json("the export receipt"), "--to": path("Destination file, outside the memory home"), "--include-capture": flag("Also export capture rows, screened"), "--format": { description: "Portable format (default json)", value: ["json", "jsonl", "markdown"] }, ...policy },
|
|
127
127
|
args: [{ name: "key" }] },
|
|
128
128
|
import: { description: "Preview or re-import notes from a JSONL export", details: "Keeps the original entry ids.",
|
|
129
129
|
examples: ["amem project import repo@1234abcd --from ./repo.jsonl", "amem project import repo@1234abcd --from ./repo.jsonl --confirm"],
|
|
@@ -135,6 +135,9 @@ export const COMMANDS: Record<string, CommandDefinition> = {
|
|
|
135
135
|
options: json("the unarchive receipt"), args: [{ name: "key" }], mutates: true },
|
|
136
136
|
forget: { description: "Forget one project for good", details: "An append-only op; previews without --confirm.", examples: ["amem project forget repo@1234abcd", "amem project forget repo@1234abcd --confirm"],
|
|
137
137
|
options: { ...json("the forget receipt"), "--confirm": flag("Record the forget after the preview") }, args: [{ name: "key" }], mutates: "confirm" },
|
|
138
|
+
"keep-separate": { description: "Keep this directory's new project key apart", details: "Ends a project key transition without joining; previews without --confirm.",
|
|
139
|
+
examples: ["amem project keep-separate", "amem project keep-separate --confirm"],
|
|
140
|
+
options: { ...json("the keep-separate preview or receipt"), "--confirm": flag("Record the choice after the preview") }, mutates: "confirm" },
|
|
138
141
|
} },
|
|
139
142
|
show: { group: "read", description: "Show a note", examples: ["amem show abcdef12", "amem show abcdef12 --history"], options: { ...json("the note"), ...history }, args: [{ name: "id" }] },
|
|
140
143
|
graph: { group: "read", description: "Show the graph around a note or node", examples: ["amem graph abcdef12", "amem graph abcdef12 --hops 2"],
|
package/src/hooks.ts
CHANGED
|
@@ -18,6 +18,7 @@ import { canonicalPath, realPath } from "./memory/platform.ts";
|
|
|
18
18
|
import { createStandalonePolicy, type MemoryPolicy, type StandalonePolicyOptions } from "./memory/policy.ts";
|
|
19
19
|
import { configuredPolicyOptions, loadAmemConfig, recordsEnabled, repoConfigRoot } from "./memory/config.ts";
|
|
20
20
|
|
|
21
|
+
import { observeRoot } from "./memory/roots.ts";
|
|
21
22
|
import { HOOK_EVENTS, HOOK_INPUT_BYTES, HOOK_CONTEXT_BYTES, HOOK_OUTPUT_BYTES, isHookTranscriptProgress, type HookTranscriptProgress } from "./hook-contract.ts";
|
|
22
23
|
export { HOOK_EVENTS, HOOK_INPUT_BYTES, HOOK_CONTEXT_BYTES, HOOK_OUTPUT_BYTES, type HookEvent } from "./hook-contract.ts";
|
|
23
24
|
// Leave 10ms of the external 150ms R2 budget for teardown and the metrics write.
|
|
@@ -333,6 +334,9 @@ async function sessionInParent(input: unknown, options: HookOptions, base: strin
|
|
|
333
334
|
const [identity, owner, briefModule] = metadata;
|
|
334
335
|
if (identity.status !== "fulfilled" || owner.status !== "fulfilled" || briefModule.status !== "fulfilled") throw new Error("hook metadata unavailable");
|
|
335
336
|
const project = resolveAlias(base, identity.value);
|
|
337
|
+
// #581: the one writer of roots.jsonl lines: first sight of this working root, or a re-bind once an alias joined
|
|
338
|
+
// its recorded key. One bounded read and at most one 0600 append; observeRoot never throws, so it cannot fail the hook.
|
|
339
|
+
observeRoot(base, cwd, identity.value);
|
|
336
340
|
const signature = owner.value;
|
|
337
341
|
const { sessionStartBrief } = briefModule.value;
|
|
338
342
|
if (remaining() <= 0) return result;
|
package/src/index.ts
CHANGED
|
@@ -9,9 +9,11 @@ export type { CuratedDoc, RankedRef } from "./memory/search-fts.ts";
|
|
|
9
9
|
export * from "./memory/shard.ts";
|
|
10
10
|
export * from "./memory/catalog.ts";
|
|
11
11
|
export * from "./memory/capacity.ts";
|
|
12
|
+
export { capacityApplyText, capacitySplitText, capacityText } from "./memory/capacity-text.ts";
|
|
12
13
|
export * from "./memory/lifecycle.ts";
|
|
13
14
|
export * from "./memory/usage.ts";
|
|
14
15
|
export * from "./memory/gc.ts";
|
|
16
|
+
export { gcText } from "./memory/gc-text.ts";
|
|
15
17
|
export * from "./memory/project-export.ts";
|
|
16
18
|
export * from "./memory/project-import.ts";
|
|
17
19
|
export * from "./memory/external-import.ts";
|
|
@@ -38,8 +40,11 @@ export type {
|
|
|
38
40
|
export * from "./memory/ops-contract.ts";
|
|
39
41
|
export * from "./memory/generation.ts";
|
|
40
42
|
export * from "./memory/migrate.ts";
|
|
43
|
+
export { migrationText } from "./memory/migrate-text.ts";
|
|
41
44
|
export * from "./memory/prune.ts";
|
|
45
|
+
export { pruneText } from "./memory/prune-text.ts";
|
|
42
46
|
export * from "./memory/shard-migration.ts";
|
|
47
|
+
export { shardMigrationText } from "./memory/shard-migration-text.ts";
|
|
43
48
|
|
|
44
49
|
export * from "./mcp.ts";
|
|
45
50
|
export * from "./mcp-memory.ts";
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
import { Report } from "@staix/cli-output";
|
|
2
|
+
import { facts, humanBytes, label, PLAIN, singleLine, type Style } from "./style.ts";
|
|
3
|
+
import type { CapacityReport } from "./capacity.ts";
|
|
4
|
+
import type { CaptureConfig } from "./capture.ts";
|
|
5
|
+
|
|
6
|
+
const MB = 1048576;
|
|
7
|
+
|
|
8
|
+
/** #592: the human capacity output, kept out of capacity.ts so the write path never imports the output package. */
|
|
9
|
+
interface CapacityRender { columns?: number; style?: Style; next?: string }
|
|
10
|
+
/** The non-JSON rendering of `amem capacity`. */
|
|
11
|
+
export function capacityText(report: CapacityReport, render?: CapacityRender): string {
|
|
12
|
+
if (render) {
|
|
13
|
+
const s = render.style ?? PLAIN, out = new Report(render.columns ?? 80, s.ascii, { sanitize: singleLine, keepTokensWhole: true });
|
|
14
|
+
out.header("amem", "Capacity"); out.section("Capture");
|
|
15
|
+
out.kv([["Rows", String(report.capture.rows)], ["Size", humanBytes(report.capture.bytes)], ["Shards", String(report.capture.shards)], ["Growth", `${report.capture.rowsPerDay.toFixed(1)} rows/day, ${humanBytes(report.capture.bytesPerDay)}/day`]]);
|
|
16
|
+
out.section("Resources"); out.kv([["Disk", `${humanBytes(report.disk.freeBytes)} free of ${humanBytes(report.disk.totalBytes)}`], ["Memory", `${humanBytes(report.memory.totalBytes)} total${report.memory.pressure ? `, pressure ${report.memory.pressure}` : ""}`], ["Samples", String(report.metrics.samples)], ["Hook p95", report.metrics.hookP95Ms === null ? "?" : `${report.metrics.hookP95Ms.toFixed(1)} ms`], ["Search peak", report.metrics.searchRssMB === null ? "?" : `${report.metrics.searchRssMB.toFixed(1)} MiB`], ...(report.metrics.mcpPhasePeak ? [["MCP phase peak", `${report.metrics.mcpPhasePeak.phase}: ${report.metrics.mcpPhasePeak.rssMB.toFixed(1)} MiB (${report.metrics.mcpPhasePeak.shared ? "shared peak" : report.metrics.mcpPhasePeak.peakRaised ? "peak raised" : "not attributed"})`] as [string, string]] : [])]);
|
|
17
|
+
out.section("Proposal"); out.kv([["Projected", `${humanBytes(report.projected.bytes)} in ${report.projected.days} days`], ["Current", `${report.current.capMb} MiB, ${report.current.retentionDays} days`], ["Proposed", `${report.proposal.capMb} MiB, ${report.proposal.retentionDays} days`], ["Reason", report.proposal.reason]]);
|
|
18
|
+
if (report.splitRefused) out.bullet("warn", `Split unavailable: ${report.splitRefused}`);
|
|
19
|
+
if (report.split.length) { out.section("Shard proposals", String(report.split.length)); out.table(["PROJECT", "CAP", "RETENTION", "REASON"], report.split.map(row => [row.key, `${row.capMb} MiB`, `${row.retentionDays} days`, row.reason]), 3); out.next("amem capacity apply --split"); }
|
|
20
|
+
out.line(""); out.line(`Summary: 1 capacity proposal, ${report.split.length} shard proposals`);
|
|
21
|
+
return out.render(s.color).join("\n");
|
|
22
|
+
}
|
|
23
|
+
const mb = (n: number): string => `${(n / MB).toFixed(1)} MB`;
|
|
24
|
+
return [
|
|
25
|
+
`capture: ${report.capture.rows} rows, ${mb(report.capture.bytes)} in ${report.capture.shards} shard(s), +${report.capture.rowsPerDay.toFixed(1)} rows/day, +${mb(report.capture.bytesPerDay)}/day`,
|
|
26
|
+
`disk: ${mb(report.disk.freeBytes)} free of ${mb(report.disk.totalBytes)}; memory: ${mb(report.memory.totalBytes)} total${report.memory.pressure ? `, pressure ${report.memory.pressure}` : ""}`,
|
|
27
|
+
`metrics: ${report.metrics.samples} samples (hook p95 ${report.metrics.hookP95Ms?.toFixed(1) ?? "?"} ms, search peak ${report.metrics.searchRssMB?.toFixed(1) ?? "?"} MB)`,
|
|
28
|
+
...(report.metrics.mcpPhasePeak ? [`MCP phase peak: ${report.metrics.mcpPhasePeak.phase} ${report.metrics.mcpPhasePeak.rssMB.toFixed(1)} MB (${report.metrics.mcpPhasePeak.shared ? "shared peak" : report.metrics.mcpPhasePeak.peakRaised ? "peak raised" : "not attributed"})`] : []),
|
|
29
|
+
`projected capture in ${report.projected.days} days: ${mb(report.projected.bytes)}`,
|
|
30
|
+
`current: cap ${report.current.capMb} MB, retention ${report.current.retentionDays} days`,
|
|
31
|
+
`proposal: cap ${report.proposal.capMb} MB, retention ${report.proposal.retentionDays} days (${report.proposal.reason})`,
|
|
32
|
+
...(report.splitRefused ? [`split: none proposed (${report.splitRefused})`] : []),
|
|
33
|
+
...(report.split.length ? ["split of the global budget per shard (a proposal: amem capacity apply --split):", ...report.split.map(row => ` ${row.key}: cap ${row.capMb} MB, retention ${row.retentionDays} days (${row.reason})`)] : []),
|
|
34
|
+
].join("\n");
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** Human-readable `capacity apply` result. JSON output remains the caller's responsibility. */
|
|
38
|
+
export function capacityApplyText(result: {
|
|
39
|
+
preview: { file: string; current: Partial<CaptureConfig>; target: CaptureConfig; reason: string };
|
|
40
|
+
confirm?: string;
|
|
41
|
+
written?: { cap_mb?: number; retention_days?: number };
|
|
42
|
+
}, s: Style = PLAIN, render?: CapacityRender): string {
|
|
43
|
+
const applied = result.written !== undefined;
|
|
44
|
+
if (render) {
|
|
45
|
+
const out = new Report(render.columns ?? 80, s.ascii, { sanitize: singleLine, keepTokensWhole: true });
|
|
46
|
+
out.header("amem", "Capacity apply"); out.section(applied ? "Applied" : "Preview");
|
|
47
|
+
out.bullet(applied ? "ok" : "pending", applied ? "Capacity settings written." : "Capacity settings are ready for review.");
|
|
48
|
+
out.kv([["File", result.preview.file], ["Current", result.preview.current.capMb === undefined && result.preview.current.retentionDays === undefined ? "defaults" : `${result.preview.current.capMb ?? "?"} MiB, ${result.preview.current.retentionDays ?? "?"} days`], ["Proposed", `${result.preview.target.capMb} MiB, ${result.preview.target.retentionDays} days`], ["Reason", result.preview.reason], ...(result.written ? [["Written", `${result.written.cap_mb ?? "?"} MiB, ${result.written.retention_days ?? "?"} days`] as [string, string]] : [])]);
|
|
49
|
+
if (!applied && render.next) out.next(render.next);
|
|
50
|
+
return out.render(s.color).join("\n");
|
|
51
|
+
}
|
|
52
|
+
return [
|
|
53
|
+
`amem capacity apply: ${applied ? s.ok("complete") : s.attention("preview")}`,
|
|
54
|
+
`${label(s, applied ? "ok" : "attention")} target: ${singleLine(result.preview.file)}`,
|
|
55
|
+
`${label(s, "ok")} current: ${facts({ cap_mb: result.preview.current.capMb, retention_days: result.preview.current.retentionDays }) || "defaults"}`,
|
|
56
|
+
`${label(s, "attention")} proposed: ${facts({ cap_mb: result.preview.target.capMb, retention_days: result.preview.target.retentionDays })}`,
|
|
57
|
+
`${label(s, "ok")} reason: ${singleLine(result.preview.reason)}`,
|
|
58
|
+
...(applied ? [`${label(s, "ok")} written: ${facts(result.written!) || "no settings reported"}`] : []),
|
|
59
|
+
`Next action: ${applied ? "none" : "re-run the same capacity apply command with --confirm, keeping all other arguments"}`,
|
|
60
|
+
].join("\n");
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** Human-readable `capacity apply --split` result, retaining skipped shard identities. */
|
|
64
|
+
export function capacitySplitText(result:
|
|
65
|
+
| { at: number; split: { key: string; dir: string; current: Partial<CaptureConfig>; target: CaptureConfig; reason: string }[]; skipped: string[]; confirm: string }
|
|
66
|
+
| { split: { key: string; dir: string; current: Partial<CaptureConfig>; target: CaptureConfig; reason: string }[]; written: { key: string; cap_mb: number; retention_days: number }[] },
|
|
67
|
+
s: Style = PLAIN, render?: CapacityRender,
|
|
68
|
+
): string {
|
|
69
|
+
const applied = "written" in result;
|
|
70
|
+
if (render) {
|
|
71
|
+
const out = new Report(render.columns ?? 80, s.ascii, { sanitize: singleLine, keepTokensWhole: true });
|
|
72
|
+
out.header("amem", "Capacity split"); out.section(applied ? "Applied" : "Preview");
|
|
73
|
+
out.bullet(applied ? "ok" : "pending", applied ? "Shard settings written." : "Shard settings are ready for review.");
|
|
74
|
+
if (!result.split.length) out.note("No shard settings to change.");
|
|
75
|
+
for (const row of result.split) {
|
|
76
|
+
const written = "written" in result ? result.written.find(item => item.key === row.key) : undefined;
|
|
77
|
+
out.section("Shard");
|
|
78
|
+
out.kv([["Project", row.key], ["File", row.dir], ["Current", row.current.capMb === undefined && row.current.retentionDays === undefined ? "defaults" : `${row.current.capMb ?? "?"} MiB, ${row.current.retentionDays ?? "?"} days`], ["Proposed", `${row.target.capMb} MiB, ${row.target.retentionDays} days`], ["Reason", row.reason], ...(written ? [["Written", `${written.cap_mb ?? "?"} MiB, ${written.retention_days ?? "?"} days`] as [string, string]] : [])]);
|
|
79
|
+
}
|
|
80
|
+
if ("skipped" in result) for (const key of result.skipped) out.bullet("absent", `${key}: no local shard config to write`);
|
|
81
|
+
if (!applied && result.split.length && render.next) out.next(render.next);
|
|
82
|
+
return out.render(s.color).join("\n");
|
|
83
|
+
}
|
|
84
|
+
const rows = result.split.map(row => [
|
|
85
|
+
`${label(s, applied ? "ok" : "attention")} shard: ${singleLine(row.key)}`,
|
|
86
|
+
`${label(s, applied ? "ok" : "attention")} target: ${singleLine(row.dir)}`,
|
|
87
|
+
`${label(s, "ok")} current: ${facts({ cap_mb: row.current.capMb, retention_days: row.current.retentionDays }) || "defaults"}`,
|
|
88
|
+
`${label(s, applied ? "ok" : "attention")} proposed: ${facts({ cap_mb: row.target.capMb, retention_days: row.target.retentionDays })}`,
|
|
89
|
+
`${label(s, "ok")} reason: ${singleLine(row.reason)}`,
|
|
90
|
+
].join("\n"));
|
|
91
|
+
const skipped = "skipped" in result ? result.skipped : [];
|
|
92
|
+
return [
|
|
93
|
+
`amem capacity apply --split: ${applied ? s.ok("complete") : s.attention("preview")}`,
|
|
94
|
+
...(result.split.length ? [] : [`${label(s, "skipped")} targets: none`]),
|
|
95
|
+
...rows,
|
|
96
|
+
...skipped.map(key => `${label(s, "skipped")} skipped shard: ${singleLine(key)} (no local shard config to write)`),
|
|
97
|
+
...(applied ? result.written.map(row => `${label(s, "ok")} written ${singleLine(row.key)}: ${facts({ cap_mb: row.cap_mb, retention_days: row.retention_days })}`) : []),
|
|
98
|
+
`Next action: ${applied || !result.split.length ? "none" : "re-run the same capacity apply --split command with --confirm, keeping all other arguments"}`,
|
|
99
|
+
].join("\n");
|
|
100
|
+
}
|