@staix/agent-mem 0.38.0 → 0.39.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- 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 +58 -26
- 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 +144 -0
- package/src/memory/doctor.ts +8 -140
- 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/prune-text.ts +29 -0
- package/src/memory/prune.ts +0 -26
- package/src/memory/report-text.ts +2 -0
- package/src/memory/shard-migration-text.ts +40 -0
- package/src/memory/shard-migration.ts +0 -37
- package/src/memory/store.ts +112 -17
- package/src/memory/sync-placement-bound.ts +2 -2
- package/src/memory/sync-placement-checkpoint-person.ts +1 -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 +43 -7
- 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/setup-drift.ts +1 -1
- package/src/setup-writer-roots.ts +136 -0
- package/src/setup.ts +3 -116
- package/src/sync-placement-writer-context.ts +8 -3
- 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.39.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";
|
|
@@ -37,7 +39,8 @@ import { CandidateStore, candidateInputId, candidateTargetRevision, type Candida
|
|
|
37
39
|
import { candidateOverlaps, candidateOverlapsBatch } from "./memory/candidate-overlaps.ts";
|
|
38
40
|
import { openCuratedForRead } from "./memory/curated-read.ts";
|
|
39
41
|
import { aliasedKeys, appendAlias, appendUnalias, listAliases, readShardedSelection, resolveAlias } from "./memory/shard.ts";
|
|
40
|
-
import { capacityReport
|
|
42
|
+
import { capacityReport } from "./memory/capacity.ts";
|
|
43
|
+
import { capacityText, capacityApplyText, capacitySplitText } from "./memory/capacity-text.ts";
|
|
41
44
|
import { CaptureStore, readCaptureConfigFile, writeCaptureConfigFile, type CaptureConfig } from "./memory/capture.ts";
|
|
42
45
|
|
|
43
46
|
import { COMMANDS, CommandUsageError, commandHelp, commandPath, parseCommand, usageLine } from "./commands-table.ts";
|
|
@@ -45,13 +48,18 @@ import { completionScript } from "./completion.ts";
|
|
|
45
48
|
import { memoryHome, resolveMemoryHome } from "./memory/home.ts";
|
|
46
49
|
import { realPath } from "./memory/platform.ts";
|
|
47
50
|
import { RemoteRealmRefusal } from "./memory/sync-placement-remote-refusal.ts";
|
|
51
|
+
import { placementSyncBoundMessage, placementSyncBoundReceipt } from "./memory/sync-placement-bound.ts";
|
|
48
52
|
import { hashJSON, readSelector, resolveProfile } from "./memory/generation.ts";
|
|
49
|
-
import { migrate
|
|
50
|
-
import {
|
|
51
|
-
import {
|
|
53
|
+
import { migrate } from "./memory/migrate.ts";
|
|
54
|
+
import { migrationText } from "./memory/migrate-text.ts";
|
|
55
|
+
import { migrateShards, shardMigrationStatus } from "./memory/shard-migration.ts";
|
|
56
|
+
import { shardMigrationText } from "./memory/shard-migration-text.ts";
|
|
57
|
+
import { applyPrune, planPrune, PRUNE_PLAN_MAX_BYTES } from "./memory/prune.ts";
|
|
58
|
+
import { pruneText } from "./memory/prune-text.ts";
|
|
52
59
|
import { readCatalogFresh } from "./memory/catalog.ts";
|
|
53
60
|
import { appendLifecycle, assertProjectActive, projectState } from "./memory/lifecycle.ts";
|
|
54
|
-
import {
|
|
61
|
+
import { runGc } from "./memory/gc.ts";
|
|
62
|
+
import { gcText } from "./memory/gc-text.ts";
|
|
55
63
|
import { usageReport, usageText } from "./memory/usage.ts";
|
|
56
64
|
import * as reports from "./memory/report-text.ts";
|
|
57
65
|
import { exportProject, type ProjectExportFormat } from "./memory/project-export.ts";
|
|
@@ -63,13 +71,15 @@ import { requireShard } from "./memory/curated-read.ts";
|
|
|
63
71
|
import { appendGitattributes, appendRepoLine, boundRepoRoot, planGitattributes, planRepoPromotion, readRepoScope, repoLogIgnored, repoLogPath, repoReadPolicy, repoVisibility } from "./memory/repo-scope.ts";
|
|
64
72
|
import type { Visibility } from "./memory/sync.ts";
|
|
65
73
|
import { applySplit, previewSplit } from "./memory/capacity-split.ts";
|
|
66
|
-
import {
|
|
74
|
+
import { parseKs } from "./memory/eval.ts";
|
|
75
|
+
import { evalText } from "./memory/eval-text.ts";
|
|
67
76
|
import { unrankedScoreDetails } from "./memory/search-score.ts";
|
|
68
77
|
import { builtinSet, evalSeeded, evalStore, FIXTURE_PATH, readEvalSet } from "./memory/eval-fixture.ts";
|
|
69
78
|
import { markShown, pendingSummary } from "./memory/candidate-pending.ts";
|
|
70
79
|
import { buildNote, FAIL_TEMPLATE, hasFailLabel, noteAdd, parseFailTemplate, type FailFields } from "./memory/note-add.ts";
|
|
71
80
|
import { runEditor } from "./memory/editor.ts";
|
|
72
|
-
import { doctorReport
|
|
81
|
+
import { doctorReport } from "./memory/doctor.ts";
|
|
82
|
+
import { doctorText } from "./memory/doctor-text.ts";
|
|
73
83
|
import { statusText, type StatusView } from "./memory/status-text.ts";
|
|
74
84
|
import { asciiMarkers, errorLine, errorSpans, EXIT, markerCell, paint, Report, resolveColor, streamEnv } from "@staix/cli-output";
|
|
75
85
|
import { style, facts, label, memoryRecordText, memoryScoresText, memoryTableText, PLAIN, singleLine, wordedKey, type Style } from "./memory/style.ts";
|
|
@@ -409,6 +419,10 @@ export async function runCli(argv: readonly string[], context: CliContext = {}):
|
|
|
409
419
|
let usage: Error | undefined, parsed: ReturnType<typeof parseCommand> | undefined;
|
|
410
420
|
try { parsed = parseCommand(argv); } catch (parseError) { usage = parseError as Error; }
|
|
411
421
|
if (usage) throw Object.assign(new Error(usage.message), (error as { exitCode?: number }).exitCode === undefined ? {} : { exitCode: (error as { exitCode?: number }).exitCode });
|
|
422
|
+
if (parsed?.path[0] === "sync") {
|
|
423
|
+
const bound = placementSyncBoundReceipt(error);
|
|
424
|
+
if (bound) throw new Error(placementSyncBoundMessage(bound));
|
|
425
|
+
}
|
|
412
426
|
const setupError = parsed && markedSetupApplyError(parsed, error);
|
|
413
427
|
if (setupError) throw setupError;
|
|
414
428
|
if (parsed && markedReadOnly(parsed)) {
|
|
@@ -497,7 +511,7 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
497
511
|
if (parsed.path[0] === "version") return `amem ${VERSION}`;
|
|
498
512
|
if (parsed.path[0] === "manifest") return JSON.stringify(manifest(), null, parsed.options["--json"] === true ? undefined : 2);
|
|
499
513
|
if (parsed.path[0] === "completion") {
|
|
500
|
-
if (parsed.positionals.length !== 1) throw new
|
|
514
|
+
if (parsed.positionals.length !== 1) throw new CommandUsageError("usage: amem completion zsh|bash|fish");
|
|
501
515
|
return completionScript(parsed.positionals[0]!);
|
|
502
516
|
}
|
|
503
517
|
} catch (error) {
|
|
@@ -535,7 +549,7 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
535
549
|
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
550
|
}
|
|
537
551
|
if (parsed.path[0] === "skills" && parsed.path[1] === "export") {
|
|
538
|
-
if (parsed.positionals.length !== 1) throw new
|
|
552
|
+
if (parsed.positionals.length !== 1) throw new CommandUsageError("usage: amem skills export <dir> [--json]");
|
|
539
553
|
const { exportSkills } = await import("./skills-install.ts");
|
|
540
554
|
const destination = parsed.positionals[0]!;
|
|
541
555
|
const report = exportSkills(destination.trim() ? resolve(context.cwd ?? process.cwd(), destination) : destination, { env: context.env ?? process.env });
|
|
@@ -545,7 +559,7 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
545
559
|
}
|
|
546
560
|
if (parsed.path[0] === "setup") {
|
|
547
561
|
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
|
|
562
|
+
|| 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
563
|
if (parsed.positionals[0] === "console") {
|
|
550
564
|
const { consoleSetup, consoleSetupText } = await import("./setup-console.ts");
|
|
551
565
|
const mode = options["--apply"] === true ? "apply" : options["--undo"] === true ? "undo" : "preview";
|
|
@@ -627,7 +641,7 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
627
641
|
} finally { candidates?.close(); store.close(); }
|
|
628
642
|
}
|
|
629
643
|
if (sub === "brief") {
|
|
630
|
-
const intent = options["--for"]; if (typeof intent !== "string" || !intent.trim() || intent.length > 1000 || parsed.positionals.length) throw
|
|
644
|
+
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
645
|
const rawBytes = options["--bytes"];
|
|
632
646
|
if (rawBytes !== undefined && !/^[1-9][0-9]*$/.test(String(rawBytes))) throw Error("brief bytes must be a positive decimal integer");
|
|
633
647
|
const maxBytes = rawBytes === undefined ? 2048 : Number(rawBytes); if (!Number.isSafeInteger(maxBytes) || maxBytes > 8192) throw Error("brief bytes must be 1..8192");
|
|
@@ -640,6 +654,7 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
640
654
|
const settings = () => configuredPolicyOptions(base, policyCwd), policyKey = () => hashJSON(settings()), revision = policyKey(), snapshot = createStandalonePolicy(settings());
|
|
641
655
|
const policy = () => snapshot, policyVersion = () => policyKey();
|
|
642
656
|
if (policyVersion() !== revision) throw Error("brief policy changed before read");
|
|
657
|
+
await prepareWorkBriefCache(base, project, policyCwd);
|
|
643
658
|
const result = await buildIntentBrief(createIntentBriefSource(store, project),
|
|
644
659
|
{ project, cwd: root, repo: project, intent, paths, symbols, maxBytes, policy, policyVersion, assertCurrent, now: () => store.readNow(), stale: createRecallStalenessProbe({ cwd: root, rootConfirmed, policy }) });
|
|
645
660
|
assertCurrent(); outputReady(result.items.map(view => view.id), project);
|
|
@@ -767,7 +782,7 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
767
782
|
const { planFormatRaise, applyFormatRaise, formatRaiseRefusal, installVersion, runningAmemRoots } = await import("./memory/formats-raise.ts");
|
|
768
783
|
const { readSetupWriterRoots } = await import("./setup.ts"), { readEffectiveSyncPlacementWriterRoots } = await import("./memory/sync-placement-effective-writers.ts");
|
|
769
784
|
const [surface, minReader] = parsed.positionals;
|
|
770
|
-
if (!surface || !minReader || parsed.positionals.length !== 2) throw new
|
|
785
|
+
if (!surface || !minReader || parsed.positionals.length !== 2) throw new CommandUsageError("formats raise requires a surface and minimum reader version");
|
|
771
786
|
const home = realPath(memoryHome()), own = realPath(fileURLToPath(new URL("..", import.meta.url)));
|
|
772
787
|
const inventory = (): import("./memory/formats-raise.ts").FormatWriterInventory => {
|
|
773
788
|
const writers: import("./memory/formats-raise.ts").FormatWriter[] = [], incomplete: string[] = [], seen = new Set<string>();
|
|
@@ -1142,7 +1157,7 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
1142
1157
|
// 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
1158
|
if (parsed.path[1] === "audit") {
|
|
1144
1159
|
// #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");
|
|
1160
|
+
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
1161
|
if (parsed.path[2] === "sample") {
|
|
1147
1162
|
const n = options["--n"] === undefined ? 40 : Number(options["--n"]), seed = typeof options["--seed"] === "string" ? options["--seed"] : "";
|
|
1148
1163
|
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 +1179,15 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
1164
1179
|
try { sheet = audit.auditSample({ store, project, n, seed, root, asOf, screen: view => screen.screenStandalone(view) }); } finally { store.close(); }
|
|
1165
1180
|
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
1181
|
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(
|
|
1182
|
+
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
1183
|
}
|
|
1169
1184
|
if (parsed.path[2] === "score") {
|
|
1170
1185
|
const [sheet] = parsed.positionals;
|
|
1171
|
-
if (!sheet) throw new
|
|
1186
|
+
if (!sheet) throw new CommandUsageError("usage: amem eval audit score <sheet> (the file `amem eval audit sample` wrote)");
|
|
1172
1187
|
const score = audit.auditScore(audit.readAuditSheet(sheet));
|
|
1173
|
-
return options["--json"] === true ? JSON.stringify(score, null, 2) : screenedLegacy(
|
|
1188
|
+
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
1189
|
}
|
|
1175
|
-
throw new
|
|
1190
|
+
throw new CommandUsageError("usage: amem eval audit sample --seed <s> [--n <n>] [--project <key>] | amem eval audit score <sheet>");
|
|
1176
1191
|
}
|
|
1177
1192
|
const ks = parseKs(typeof options["--k"] === "string" ? options["--k"] : undefined);
|
|
1178
1193
|
const file = typeof options["--set"] === "string" ? options["--set"] : undefined;
|
|
@@ -1323,7 +1338,7 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
1323
1338
|
if (options["--explain"] === true) throw new Error("--explain applies to current-project ranked search, not --all-projects");
|
|
1324
1339
|
if (options["--filter"] === true) throw new Error("--filter applies to project-local search, not --all-projects");
|
|
1325
1340
|
const words = parsed.positionals.join(" ");
|
|
1326
|
-
if (!words.trim()) throw new
|
|
1341
|
+
if (!words.trim()) throw new CommandUsageError("usage: amem search --all-projects <words> [--limit N] [--include-archived] [--json]");
|
|
1327
1342
|
const result = searchAllProjects(memoryHome(), words, { ...(options["--limit"] !== undefined ? { limit: Number(options["--limit"]) } : {}), includeArchived: options["--include-archived"] === true });
|
|
1328
1343
|
if (options["--json"]) return JSON.stringify(result, null, 2);
|
|
1329
1344
|
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 +1396,7 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
1381
1396
|
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
1397
|
if (sub === "promote" && options["--to"] !== undefined) {
|
|
1383
1398
|
const idText = parsed.positionals[0];
|
|
1384
|
-
if (!idText || parsed.positionals.length !== 1) throw new
|
|
1399
|
+
if (!idText || parsed.positionals.length !== 1) throw new CommandUsageError("usage: amem promote <id> --to repo --policy-free [--confirm [--confirm-public <entry id prefix>]]");
|
|
1385
1400
|
const project = boundProject(), root = boundRepoRoot(repoCwd, memoryHome(), project);
|
|
1386
1401
|
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
1402
|
const store = curatedStore(project, { deferPromotions: true, screen: () => "skip" });
|
|
@@ -1543,26 +1558,40 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
1543
1558
|
let output: string;
|
|
1544
1559
|
let placementWriters: import("./sync-placement-writer-context.ts").PlacementWriterContext | undefined;
|
|
1545
1560
|
let progress: import("./memory/sync-progress.ts").SyncProgress | undefined;
|
|
1561
|
+
let writerRefusal: import("./memory/sync-placement-refusal-category.ts").PlacementWriterRefusal | undefined;
|
|
1562
|
+
let attestPlacement: import("./sync-placement-writer-context.ts").PlacementWriterContext["attest"] | undefined;
|
|
1546
1563
|
const stop = ifDue ? stopSignal(context.syncDeadlineMs ?? SYNC_IF_DUE_DEADLINE_MS, process) : undefined;
|
|
1547
1564
|
try {
|
|
1548
1565
|
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);
|
|
1566
|
+
const { activePlacementWriterContext, placementWriterRefusalDetail, placementWriterRefusalText } = await import("./sync-placement-writer-context.ts");
|
|
1567
|
+
progress = await placementProgress(syncHome, typeof options["--progress"] === "string" ? options["--progress"] as string : "auto", context, () => writerRefusal);
|
|
1551
1568
|
try { placementWriters = activePlacementWriterContext(syncHome,fileURLToPath(new URL("..",import.meta.url))); }
|
|
1552
1569
|
catch (error) {
|
|
1570
|
+
writerRefusal = placementWriterRefusalDetail(error);
|
|
1553
1571
|
// #551 AC1: a writer-context refusal is this run's own failed result, so --json reports it instead of printing one
|
|
1554
1572
|
// 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 =
|
|
1573
|
+
const refusal = placementWriterRefusalText(error);
|
|
1556
1574
|
if (refusal === undefined || !options["--json"]) throw error;
|
|
1557
1575
|
stampSync(refusal, stop?.cause());
|
|
1558
1576
|
return JSON.stringify({ ok: false, pushed: false, entries: 0, failure: { cause: "refusal" }, error: refusal }, null, 2);
|
|
1559
1577
|
}
|
|
1578
|
+
const attest = placementWriters.attest;
|
|
1579
|
+
attestPlacement = () => {
|
|
1580
|
+
try {
|
|
1581
|
+
const proof = attest();
|
|
1582
|
+
writerRefusal = undefined;
|
|
1583
|
+
return proof;
|
|
1584
|
+
} catch (error) {
|
|
1585
|
+
writerRefusal = placementWriterRefusalDetail(error);
|
|
1586
|
+
throw error;
|
|
1587
|
+
}
|
|
1588
|
+
};
|
|
1560
1589
|
const markers = readPlacementRuntimeMarkers(syncHome);
|
|
1561
1590
|
if (!readActivePlacementBinding(syncHome, markers.profile, markers.shards)) throw Error("sync placement activation metadata unavailable or changed; inspect the retained activation before continuing");
|
|
1562
1591
|
}
|
|
1563
1592
|
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
1593
|
// #578 Q2: the CLI sync (also --if-due) is eligible; the home opt-in still decides whether a checkpoint can run.
|
|
1565
|
-
sync: { ...(
|
|
1594
|
+
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
1595
|
onBridgeStatus: status => { receipt.bridgeStatus = status; },
|
|
1567
1596
|
// #188: ids-only listing of nearby machine-local rows; policy-refused rows are neither listed nor counted.
|
|
1568
1597
|
forgetNearby: note => forgetNearby({ base: memoryHome(), project: note.project, text: note.text, title: note.title, screen: value => configured.screenStandalone(value) }) }));
|
|
@@ -1611,13 +1640,16 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
1611
1640
|
* #418: one reporter per placement sync. The private sidecar backs `sync --status` in every mode; stderr gets human
|
|
1612
1641
|
* lines or versioned JSON events. Each part fails alone and silently: telemetry never fails or alters the sync.
|
|
1613
1642
|
*/
|
|
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");
|
|
1643
|
+
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> {
|
|
1644
|
+
const { SyncProgress, renderSyncProgress, syncProgressSidecar, syncStatusSnapshot } = await import("./memory/sync-progress.ts");
|
|
1616
1645
|
const write = context.stderr ?? ((text: string) => { process.stderr.write(text); });
|
|
1617
1646
|
const render = mode === "json" ? "json" : mode === "human" || mode === "auto" && (context.stderrTTY ?? process.stderr.isTTY) ? "human" : undefined;
|
|
1618
1647
|
const parts = [syncProgressSidecar(home), ...(render ? [(snapshot: import("./memory/sync-progress.ts").SyncProgressSnapshot) => write((render === "json" ? JSON.stringify(snapshot) : renderSyncProgress(snapshot)) + "\n")] : [])];
|
|
1619
1648
|
const live = new Set(parts.keys());
|
|
1620
|
-
return new SyncProgress({ sink: snapshot => {
|
|
1649
|
+
return new SyncProgress({ sink: snapshot => {
|
|
1650
|
+
const status = syncStatusSnapshot(snapshot, writerRefusal());
|
|
1651
|
+
for (const index of live) try { parts[index]!(status); } catch { live.delete(index); }
|
|
1652
|
+
} });
|
|
1621
1653
|
}
|
|
1622
1654
|
function outputStyle(context: CliContext, options: Record<string, string | boolean>): Style {
|
|
1623
1655
|
const color = resolveColor(typeof options["--color"] === "string" ? options["--color"] : undefined, streamEnv((context.stdoutTTY ?? process.stdout.isTTY) === true, context.env ?? process.env), "amem");
|
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
|
+
}
|
package/src/memory/capacity.ts
CHANGED
|
@@ -8,10 +8,7 @@ export { appendMetrics, readMetrics, metricsPath, type MetricSample } from "./me
|
|
|
8
8
|
import { walkShards } from "./catalog.ts";
|
|
9
9
|
import { lifecycleResolver } from "./lifecycle.ts";
|
|
10
10
|
import { captureShardGrowth, captureShardStats, readCaptureConfigFile, CAPTURE_DEFAULT_CAP_MB, CAPTURE_DEFAULT_RETENTION_DAYS, type CaptureConfig } from "./capture.ts";
|
|
11
|
-
import { facts, humanBytes, label, PLAIN, singleLine, type Style } from "./style.ts";
|
|
12
|
-
import { Report } from "@staix/cli-output";
|
|
13
11
|
|
|
14
|
-
interface CapacityRender { columns?: number; style?: Style; next?: string }
|
|
15
12
|
|
|
16
13
|
/**
|
|
17
14
|
* #13 R7: the capacity advisor. `capacityReport()` reads this machine's load and proposes capture bounds; the
|
|
@@ -276,94 +273,5 @@ export function capacityReport(opts: {
|
|
|
276
273
|
};
|
|
277
274
|
}
|
|
278
275
|
|
|
279
|
-
/** The non-JSON rendering of `amem capacity`. */
|
|
280
|
-
export function capacityText(report: CapacityReport, render?: CapacityRender): string {
|
|
281
|
-
if (render) {
|
|
282
|
-
const s = render.style ?? PLAIN, out = new Report(render.columns ?? 80, s.ascii, { sanitize: singleLine, keepTokensWhole: true });
|
|
283
|
-
out.header("amem", "Capacity"); out.section("Capture");
|
|
284
|
-
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`]]);
|
|
285
|
-
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]] : [])]);
|
|
286
|
-
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]]);
|
|
287
|
-
if (report.splitRefused) out.bullet("warn", `Split unavailable: ${report.splitRefused}`);
|
|
288
|
-
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"); }
|
|
289
|
-
out.line(""); out.line(`Summary: 1 capacity proposal, ${report.split.length} shard proposals`);
|
|
290
|
-
return out.render(s.color).join("\n");
|
|
291
|
-
}
|
|
292
|
-
const mb = (n: number): string => `${(n / MB).toFixed(1)} MB`;
|
|
293
|
-
return [
|
|
294
|
-
`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`,
|
|
295
|
-
`disk: ${mb(report.disk.freeBytes)} free of ${mb(report.disk.totalBytes)}; memory: ${mb(report.memory.totalBytes)} total${report.memory.pressure ? `, pressure ${report.memory.pressure}` : ""}`,
|
|
296
|
-
`metrics: ${report.metrics.samples} samples (hook p95 ${report.metrics.hookP95Ms?.toFixed(1) ?? "?"} ms, search peak ${report.metrics.searchRssMB?.toFixed(1) ?? "?"} MB)`,
|
|
297
|
-
...(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"})`] : []),
|
|
298
|
-
`projected capture in ${report.projected.days} days: ${mb(report.projected.bytes)}`,
|
|
299
|
-
`current: cap ${report.current.capMb} MB, retention ${report.current.retentionDays} days`,
|
|
300
|
-
`proposal: cap ${report.proposal.capMb} MB, retention ${report.proposal.retentionDays} days (${report.proposal.reason})`,
|
|
301
|
-
...(report.splitRefused ? [`split: none proposed (${report.splitRefused})`] : []),
|
|
302
|
-
...(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})`)] : []),
|
|
303
|
-
].join("\n");
|
|
304
|
-
}
|
|
305
276
|
|
|
306
|
-
/** Human-readable `capacity apply` result. JSON output remains the caller's responsibility. */
|
|
307
|
-
export function capacityApplyText(result: {
|
|
308
|
-
preview: { file: string; current: Partial<CaptureConfig>; target: CaptureConfig; reason: string };
|
|
309
|
-
confirm?: string;
|
|
310
|
-
written?: { cap_mb?: number; retention_days?: number };
|
|
311
|
-
}, s: Style = PLAIN, render?: CapacityRender): string {
|
|
312
|
-
const applied = result.written !== undefined;
|
|
313
|
-
if (render) {
|
|
314
|
-
const out = new Report(render.columns ?? 80, s.ascii, { sanitize: singleLine, keepTokensWhole: true });
|
|
315
|
-
out.header("amem", "Capacity apply"); out.section(applied ? "Applied" : "Preview");
|
|
316
|
-
out.bullet(applied ? "ok" : "pending", applied ? "Capacity settings written." : "Capacity settings are ready for review.");
|
|
317
|
-
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]] : [])]);
|
|
318
|
-
if (!applied && render.next) out.next(render.next);
|
|
319
|
-
return out.render(s.color).join("\n");
|
|
320
|
-
}
|
|
321
|
-
return [
|
|
322
|
-
`amem capacity apply: ${applied ? s.ok("complete") : s.attention("preview")}`,
|
|
323
|
-
`${label(s, applied ? "ok" : "attention")} target: ${singleLine(result.preview.file)}`,
|
|
324
|
-
`${label(s, "ok")} current: ${facts({ cap_mb: result.preview.current.capMb, retention_days: result.preview.current.retentionDays }) || "defaults"}`,
|
|
325
|
-
`${label(s, "attention")} proposed: ${facts({ cap_mb: result.preview.target.capMb, retention_days: result.preview.target.retentionDays })}`,
|
|
326
|
-
`${label(s, "ok")} reason: ${singleLine(result.preview.reason)}`,
|
|
327
|
-
...(applied ? [`${label(s, "ok")} written: ${facts(result.written!) || "no settings reported"}`] : []),
|
|
328
|
-
`Next action: ${applied ? "none" : "re-run the same capacity apply command with --confirm, keeping all other arguments"}`,
|
|
329
|
-
].join("\n");
|
|
330
|
-
}
|
|
331
277
|
|
|
332
|
-
/** Human-readable `capacity apply --split` result, retaining skipped shard identities. */
|
|
333
|
-
export function capacitySplitText(result:
|
|
334
|
-
| { at: number; split: { key: string; dir: string; current: Partial<CaptureConfig>; target: CaptureConfig; reason: string }[]; skipped: string[]; confirm: string }
|
|
335
|
-
| { split: { key: string; dir: string; current: Partial<CaptureConfig>; target: CaptureConfig; reason: string }[]; written: { key: string; cap_mb: number; retention_days: number }[] },
|
|
336
|
-
s: Style = PLAIN, render?: CapacityRender,
|
|
337
|
-
): string {
|
|
338
|
-
const applied = "written" in result;
|
|
339
|
-
if (render) {
|
|
340
|
-
const out = new Report(render.columns ?? 80, s.ascii, { sanitize: singleLine, keepTokensWhole: true });
|
|
341
|
-
out.header("amem", "Capacity split"); out.section(applied ? "Applied" : "Preview");
|
|
342
|
-
out.bullet(applied ? "ok" : "pending", applied ? "Shard settings written." : "Shard settings are ready for review.");
|
|
343
|
-
if (!result.split.length) out.note("No shard settings to change.");
|
|
344
|
-
for (const row of result.split) {
|
|
345
|
-
const written = "written" in result ? result.written.find(item => item.key === row.key) : undefined;
|
|
346
|
-
out.section("Shard");
|
|
347
|
-
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]] : [])]);
|
|
348
|
-
}
|
|
349
|
-
if ("skipped" in result) for (const key of result.skipped) out.bullet("absent", `${key}: no local shard config to write`);
|
|
350
|
-
if (!applied && result.split.length && render.next) out.next(render.next);
|
|
351
|
-
return out.render(s.color).join("\n");
|
|
352
|
-
}
|
|
353
|
-
const rows = result.split.map(row => [
|
|
354
|
-
`${label(s, applied ? "ok" : "attention")} shard: ${singleLine(row.key)}`,
|
|
355
|
-
`${label(s, applied ? "ok" : "attention")} target: ${singleLine(row.dir)}`,
|
|
356
|
-
`${label(s, "ok")} current: ${facts({ cap_mb: row.current.capMb, retention_days: row.current.retentionDays }) || "defaults"}`,
|
|
357
|
-
`${label(s, applied ? "ok" : "attention")} proposed: ${facts({ cap_mb: row.target.capMb, retention_days: row.target.retentionDays })}`,
|
|
358
|
-
`${label(s, "ok")} reason: ${singleLine(row.reason)}`,
|
|
359
|
-
].join("\n"));
|
|
360
|
-
const skipped = "skipped" in result ? result.skipped : [];
|
|
361
|
-
return [
|
|
362
|
-
`amem capacity apply --split: ${applied ? s.ok("complete") : s.attention("preview")}`,
|
|
363
|
-
...(result.split.length ? [] : [`${label(s, "skipped")} targets: none`]),
|
|
364
|
-
...rows,
|
|
365
|
-
...skipped.map(key => `${label(s, "skipped")} skipped shard: ${singleLine(key)} (no local shard config to write)`),
|
|
366
|
-
...(applied ? result.written.map(row => `${label(s, "ok")} written ${singleLine(row.key)}: ${facts({ cap_mb: row.cap_mb, retention_days: row.retention_days })}`) : []),
|
|
367
|
-
`Next action: ${applied || !result.split.length ? "none" : "re-run the same capacity apply --split command with --confirm, keeping all other arguments"}`,
|
|
368
|
-
].join("\n");
|
|
369
|
-
}
|
package/src/memory/commands.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { PlacementSyncBoundError } from "./sync-placement-bound.ts";
|
|
1
2
|
import { cliAttribution, noteDisplayActor } from "./cli-attribution.ts";
|
|
2
3
|
import { extractNodes, GOAL_STATES, KINDS, MemoryStore, setMachineLabel, type GoalState, type GoalView, type Kind, type Tier, type View } from "./store.ts";
|
|
3
4
|
import { syncMemory, type SyncOptions } from "./sync.ts";
|
|
@@ -262,7 +263,11 @@ export async function rawMemoryCommand(args: string[], cwd: string, opts: Memory
|
|
|
262
263
|
const realmLines = r.placementRealms?.length ? `\n${r.placementRealms.map(item => `realm ${item.realm === "user" ? "user" : item.realm.slice(0, 16)}: ${item.outcome}${item.publication ? ` (publication ${item.publication})` : ""}`).join("\n")}` : "";
|
|
263
264
|
// #578 Q2: one counts-only line when this sync ran a placement checkpoint.
|
|
264
265
|
const checkpointLine = r.checkpoint ? `\nplacement checkpoint: window ${r.checkpoint.window}, objects ${r.checkpoint.objectsBefore} -> ${r.checkpoint.objectsAfter}` : "";
|
|
265
|
-
if (!r.ok)
|
|
266
|
+
if (!r.ok) {
|
|
267
|
+
const bound = placement?.bound;
|
|
268
|
+
if (internal && cliAttribution()?.actor === "agent" && bound && (r.failure?.cause === "bound" || r.failure?.cause === "checkpoint-refused")) throw new PlacementSyncBoundError(bound);
|
|
269
|
+
fail(`${names.memory} sync: ${r.error}${checkpointLine}${realmLines}`);
|
|
270
|
+
}
|
|
266
271
|
// #590 (task 429): the CLI renders the success report; hosts keep the legacy line below byte for byte.
|
|
267
272
|
const cliSync = (legacy: string) => internal ? rendered(legacy, syncReportText(r, internal.render.style ?? PLAIN, { columns: internal.render.columns ?? 80 })) : legacy;
|
|
268
273
|
if (r.pruneApplication) {
|