@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
|
@@ -9,10 +9,19 @@ export function curatedProfileBinding(base: string, project: string): string {
|
|
|
9
9
|
shards: existsSync(join(base, "shards.json")) ? readShardedSelection(base) : null,
|
|
10
10
|
aliases: aliasedKeys(base, project) });
|
|
11
11
|
}
|
|
12
|
+
export interface CuratedCacheCandidate { project: string; activity: number; warm: boolean }
|
|
13
|
+
|
|
14
|
+
function fileActivity(file: string): number | undefined {
|
|
15
|
+
try {
|
|
16
|
+
const stat = lstatSync(file, { throwIfNoEntry: false });
|
|
17
|
+
if (stat?.isFile()) return stat.mtimeMs;
|
|
18
|
+
} catch { /* An unreadable derived file gives no activity signal. */ }
|
|
19
|
+
}
|
|
20
|
+
|
|
12
21
|
/** Off-hook conservative invalidation: derived directories only, never enumerate authoritative logs.
|
|
13
22
|
* #424: `projects` limits removal to those projects' cache directories (an alias resolves to its canonical directory),
|
|
14
23
|
* so one project's write keeps every other project's prebuilt brief. Omitted, every project is invalidated. */
|
|
15
|
-
export function invalidateCuratedCaches(base: string, projects?: readonly string[]): string[] {
|
|
24
|
+
export function invalidateCuratedCaches(base: string, projects?: readonly string[], observe?: { machine: string; now: number; candidate: (candidate: CuratedCacheCandidate) => void }): string[] {
|
|
16
25
|
const invalidated = new Set<string>(), root = join(base, "projects");
|
|
17
26
|
if (!existsSync(root)) return [];
|
|
18
27
|
const only = projects && new Set(projects.flatMap(project => [shardKeyHash(project), shardKeyHash(resolveAlias(base, project))]));
|
|
@@ -22,8 +31,18 @@ export function invalidateCuratedCaches(base: string, projects?: readonly string
|
|
|
22
31
|
if (!stat.isDirectory() || stat.isSymbolicLink()) continue;
|
|
23
32
|
const descriptor = readShardDescriptor(base, hash);
|
|
24
33
|
const machines = join(directory, "machine");
|
|
25
|
-
|
|
26
|
-
|
|
34
|
+
const parent = lstatSync(machines, { throwIfNoEntry: false });
|
|
35
|
+
if (parent && !parent.isDirectory()) continue;
|
|
36
|
+
if (observe && descriptor && shardKeyHash(descriptor.key) === hash && fileActivity(join(directory, "generation.json")) !== undefined) {
|
|
37
|
+
const scope = join(machines, observe.machine);
|
|
38
|
+
const local = lstatSync(scope, { throwIfNoEntry: false });
|
|
39
|
+
if (!local || local.isDirectory()) {
|
|
40
|
+
const lastCurated = fileActivity(join(scope, "brief-curated.json"));
|
|
41
|
+
observe.candidate({ project: descriptor.key, activity: fileActivity(join(scope, "brief-capture.json")) ?? 0,
|
|
42
|
+
warm: lastCurated !== undefined && observe.now - lastCurated < 24 * 60 * 60 * 1000 });
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
if (!parent) continue;
|
|
27
46
|
for (const machine of readdirSync(machines)) {
|
|
28
47
|
if (!/^[a-f0-9]{16}$/.test(machine)) continue;
|
|
29
48
|
const scope = join(machines, machine), info = lstatSync(scope);
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
import { CLIS, type DoctorReport, type Section, type SectionStatus } from "./doctor.ts";
|
|
2
|
+
import { humanBytes, relativeTime, singleLine, wordedFacts, wordedKey, PLAIN, type Style } from "./style.ts";
|
|
3
|
+
import { validPlacementWriterRefusal } from "./sync-placement-refusal-category.ts";
|
|
4
|
+
import { writerRefusalText } from "./sync-progress-text.ts";
|
|
5
|
+
import { attention, reportFrame, stateRows, STATE_WORD, type Finding, type ReportTextOptions } from "./status-text.ts";
|
|
6
|
+
|
|
7
|
+
/** #592: the human doctor report, kept out of doctor.ts so the doctor's checks never import the output package. */
|
|
8
|
+
/** Section order and one-line names for the person-facing report (#125). */
|
|
9
|
+
const SECTION_TITLE: Record<keyof DoctorReport["sections"], string> = {
|
|
10
|
+
duplicates: "duplicate notes", stale: "stale path references", candidates: "review candidates", capture: "capture per CLI", brief: "session brief",
|
|
11
|
+
index: "index equals rebuild", readers: "reader leases", policy: "policy in effect", cadence: "ingest and sync cadence", drops: "recent capture drops",
|
|
12
|
+
writers: "placement writers",
|
|
13
|
+
spool: "pending hook spool",
|
|
14
|
+
setup: "native setup registrations",
|
|
15
|
+
masked: "forgotten or pruned entries (informational)",
|
|
16
|
+
};
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* #590 C4: every hint a section emits, as one finding and the complete commands that act on it. `--json` keeps the hint text unchanged;
|
|
20
|
+
* only the human report reads this table. A hint missing from it renders as a finding with no `→`, never as text with an embedded command.
|
|
21
|
+
* `test/status-doctor-layout.test.ts` checks every hint producer against this table.
|
|
22
|
+
*/
|
|
23
|
+
export const DOCTOR_HINTS: Readonly<Record<string, (section: Record<string, unknown>) => Finding>> = {
|
|
24
|
+
"amem dedupe previews the imported duplicates; amem dedupe --apply reconciles them": () =>
|
|
25
|
+
({ text: "imported duplicate notes can be reconciled", next: ["amem dedupe", "amem dedupe --apply"] }),
|
|
26
|
+
"The person can inspect these examples with amem show <id> from their own shell.": section => {
|
|
27
|
+
const first = Array.isArray(section.examples) ? String(section.examples[0] ?? "") : "";
|
|
28
|
+
// #511 AC3: an agent-marked `show` may withhold these ids, so the finding says where they open.
|
|
29
|
+
return { text: `${section.missingReferences} notes reference paths that no longer exist; open the examples from your own shell`, next: first ? [`amem show ${first}`] : [] };
|
|
30
|
+
},
|
|
31
|
+
"the index differs from a rebuild of the logs: run amem rebuild": () => ({ text: "the index differs from a rebuild of the logs", next: ["amem rebuild"] }),
|
|
32
|
+
"a section is partial or unavailable in the brief: see coverage": () => ({ text: "a brief section is partial or unavailable", next: [] }),
|
|
33
|
+
"the brief uses over 90% of its budget": () => ({ text: "the session brief uses over 90% of its budget", next: [] }),
|
|
34
|
+
"a reader lease of a process that is gone is cleared by the next reader; an unreadable one needs a look": () =>
|
|
35
|
+
({ text: "a reader lease is stale or unreadable; the next reader clears a stale one", next: [] }),
|
|
36
|
+
"capture rows were dropped recently (see counts by reason); amem doctor --json keeps the numbers": () =>
|
|
37
|
+
({ text: "capture rows were dropped recently", next: ["amem doctor --json"] }),
|
|
38
|
+
"pending hook spool needs attention: capture can be dropped when both tiers fill; supported orphan recovery is pending": () =>
|
|
39
|
+
({ text: "the hook spool is nearly full; capture is dropped when both tiers fill", next: [] }),
|
|
40
|
+
"sync has failed repeatedly; amem sync --force shows why": () => ({ text: "sync has failed 3 or more times in a row", next: ["amem sync --force"] }),
|
|
41
|
+
"no recent successful sync: run amem sync": () => ({ text: "no recent successful sync", next: ["amem sync"] }),
|
|
42
|
+
"run amem review walk": section => ({ text: `${section.dueWithin7Days} candidates expire within 7 days`, next: ["amem review walk"] }),
|
|
43
|
+
};
|
|
44
|
+
/** Capture hints name a CLI; each maps to a finding and the commands for that CLI. */
|
|
45
|
+
export function captureFinding(cli: string, hint: string): Finding {
|
|
46
|
+
const known = new Set<string>(CLIS);
|
|
47
|
+
const ingest = known.has(cli) && cli !== "claude" ? [`amem ingest ${cli}`] : [];
|
|
48
|
+
if (hint.startsWith(`the ${cli} `) && hint.includes("unsafe symlink")) return { text: `${cli}: a native session root is an unsafe symlink and was skipped`, next: ingest };
|
|
49
|
+
if (hint.startsWith("run amem setup")) return { text: `${cli}: capture is not set up`, next: known.has(cli) ? [`amem setup ${cli} --apply`, ...ingest] : [] };
|
|
50
|
+
if (hint.includes("/hooks trust review")) return { text: "codex: the hook is registered but has never captured; approve it in the Codex /hooks trust review", next: [] };
|
|
51
|
+
const state = /capture is (\w+)/.exec(hint)?.[1] ?? "not fresh", where = hint.includes("on this machine") ? "on this machine" : "in this project";
|
|
52
|
+
return { text: `${cli}: capture is ${state} ${where}; open a session`, next: ingest };
|
|
53
|
+
}
|
|
54
|
+
export function hintFinding(name: string, hint: string, section: Record<string, unknown>): Finding {
|
|
55
|
+
const mapped = DOCTOR_HINTS[hint];
|
|
56
|
+
return mapped ? mapped(section) : { text: `${SECTION_TITLE[name as keyof typeof SECTION_TITLE] ?? name}: ${hint.replace(/[:;,]?\s*(?:run |see |use )?\bamem [a-z].*$/, "").replace(/[:;,]\s*$/, "").trim() || "needs a look"}`, next: [] };
|
|
57
|
+
}
|
|
58
|
+
/** #590 C6: a writer refusal is one finding; each command it names is one `→` line. The fixed refusal text stays in `--json`. */
|
|
59
|
+
export function writerFinding(section: Record<string, unknown>): Finding {
|
|
60
|
+
const reason = String(section.reason ?? "");
|
|
61
|
+
const commands = [...reason.matchAll(/amem (?:migrate --sync-placement --(?:dry-run|resume|abandon)|formats raise home [0-9.]+|setup [a-z]+ --(?:apply|undo))/g)].map(match => match[0]);
|
|
62
|
+
return { text: `placement writer proof is ${section.cause ?? "unverified"} (${section.category ?? "unknown"} category)`, next: [...new Set(commands)] };
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function sectionFact(name: string, detail: Record<string, unknown>, now: number): string[] {
|
|
66
|
+
if (name === "capture" && detail.clis && typeof detail.clis === "object") {
|
|
67
|
+
return Object.entries(detail.clis as Record<string, Record<string, unknown>>).map(([cli, row]) =>
|
|
68
|
+
`${cli} hook ${row.hook}${row.setup ? ` (${row.setup})` : ""}, capture ${row.capture}${row.lastCaptureAt ? ` ${relativeTime(String(row.lastCaptureAt), now)}` : ""}, ${row.rows} rows; machine-wide ${row.machineCapture ?? "unknown"}${row.machineLastCaptureAt ? ` ${relativeTime(String(row.machineLastCaptureAt), now)}` : ""}${row.note ? `, ${row.note}` : ""}`);
|
|
69
|
+
}
|
|
70
|
+
if (name === "cadence") {
|
|
71
|
+
const sync = (detail.sync ?? {}) as Record<string, unknown>, ingest = (detail.ingest ?? {}) as Record<string, string>;
|
|
72
|
+
return [`ingest ${Object.entries(ingest).map(([cli, how]) => `${cli} ${how}`).join(", ")}`,
|
|
73
|
+
`sync remote ${sync.remote}${sync.remote === "configured" ? `, last ok ${relativeTime(sync.lastOkAt as string | null, now)}, ${sync.failures} failures${sync.due ? ", due" : ""}` : ""}`,
|
|
74
|
+
...(validPlacementWriterRefusal(sync.writerRefusal) ? [`last failure: ${writerRefusalText(sync.writerRefusal)}`] : [])];
|
|
75
|
+
}
|
|
76
|
+
if (name === "drops") {
|
|
77
|
+
if (detail.counts === undefined) return [];
|
|
78
|
+
const counts = Object.entries((detail.counts ?? {}) as Record<string, number>);
|
|
79
|
+
return [`${counts.length ? counts.map(([reason, n]) => `${reason.replaceAll("_", " ")} ${n}`).join(", ") : "none"} in the recent metrics tail${detail.malformedLines ? `, ${detail.malformedLines} malformed lines skipped` : ""}`];
|
|
80
|
+
}
|
|
81
|
+
if (name === "spool") {
|
|
82
|
+
if (!detail.active || !detail.reserve) return [];
|
|
83
|
+
const tiers = ["active", "reserve"].map(tierName => {
|
|
84
|
+
const tier = detail[tierName] as { files: number; bytes: number; maxFiles: number; maxBytes: number };
|
|
85
|
+
return `${tierName} ${tier.files} of ${tier.maxFiles} files, ${humanBytes(tier.bytes)} of ${humanBytes(tier.maxBytes)}`;
|
|
86
|
+
});
|
|
87
|
+
const kinds = detail.kinds as { native: number; summaries: number; unclassified: number; complete: boolean };
|
|
88
|
+
return [`${String(detail.fill).replaceAll("_", " ")}; ${tiers.join("; ")}; ${detail.claimed} claimed${detail.oldestAt ? `, oldest ${relativeTime(String(detail.oldestAt), now)}` : ""}${detail.complete ? "" : " (counts are lower bounds)"}`,
|
|
89
|
+
`native ${kinds.native}, summaries ${kinds.summaries}, unclassified ${kinds.unclassified}; classification ${detail.classificationCoverage}${kinds.complete ? "" : " (native and summary counts are lower bounds)"}`];
|
|
90
|
+
}
|
|
91
|
+
if (name === "setup" && Array.isArray(detail.entries)) {
|
|
92
|
+
const entries = detail.entries as { target?: unknown; file?: unknown; entry?: unknown; reason?: unknown; expectedFile?: unknown; phase?: unknown }[];
|
|
93
|
+
if (!entries.length) return [`${detail.checked ?? 0} registrations match their receipts`];
|
|
94
|
+
return entries.map(item => singleLine(`${item.target}${item.phase ? ` (${item.phase})` : ""} ${item.file}${item.expectedFile ? `, expected ${item.expectedFile}` : ""} ${item.entry}: ${item.reason}`));
|
|
95
|
+
}
|
|
96
|
+
if (name === "writers") return typeof detail.writers === "number" ? [`${detail.writers} writers match the active inventory`] : [];
|
|
97
|
+
if (name === "brief" && typeof detail.tokens === "number") {
|
|
98
|
+
const missing = Object.entries((detail.coverage ?? {}) as Record<string, unknown>).filter(([, value]) => value && value !== "complete").map(([key, value]) => `${wordedKey(key)} ${value}`);
|
|
99
|
+
return [`${detail.tokens} of ${detail.budget} tokens${missing.length ? `, coverage: ${missing.join(", ")}` : ""}`];
|
|
100
|
+
}
|
|
101
|
+
if (name === "policy") return [`machine ${detail.machine ?? "none (defaults)"}, repo ${detail.repo ?? "none"}, ${detail.denyPaths} deny paths, ${detail.piiPatterns} PII patterns`];
|
|
102
|
+
if (name === "index") return detail.liveIndex ? [`live index ${detail.liveIndex}, equal to a rebuild`] : [];
|
|
103
|
+
if (name === "readers") return [`${detail.live ?? 0} live, ${detail.stale ?? 0} stale, ${detail.unreadable ?? 0} unreadable`];
|
|
104
|
+
if (name === "duplicates" && typeof detail.notes === "number") return [`${detail.notes} notes, ${detail.identicalGroups ?? 0} identical groups, ${detail.importedGroups ?? 0} imported groups${detail.truncated ? `, ${detail.truncated}` : ""}`,
|
|
105
|
+
...(Array.isArray(detail.examples) && detail.examples.length ? [`examples ${(detail.examples as unknown[]).map(item => Array.isArray(item) ? item.join(" = ") : String(item)).join(", ")}`] : [])];
|
|
106
|
+
if (name === "stale" && typeof detail.checked === "number") return [`${detail.checked} checked, ${detail.missingReferences ?? 0} missing`,
|
|
107
|
+
...(Array.isArray(detail.examples) && detail.examples.length ? [`examples ${(detail.examples as unknown[]).join(", ")}`] : [])];
|
|
108
|
+
if (name === "masked") return [`${detail.forgets ?? 0} forgotten, ${detail.prunes ?? 0} pruned; see docs/purge.md`];
|
|
109
|
+
if (name === "candidates") return [`${detail.count ?? 0} pending${detail.unshown ? `, ${detail.unshown} never shown` : ""}${detail.oldestExpiresInDays !== null && detail.oldestExpiresInDays !== undefined ? `, oldest expires in ${detail.oldestExpiresInDays} d` : ""}`];
|
|
110
|
+
const { examples, note: _note, ...rest } = detail;
|
|
111
|
+
const line = wordedFacts(rest);
|
|
112
|
+
return [...(line ? [line] : []), ...(Array.isArray(examples) && examples.length ? [`examples ${examples.map(item => Array.isArray(item) ? item.join(" = ") : String(item)).join(", ")}`] : [])];
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** The person-facing report (#125, #590): state, findings with their commands, one row per check, then the summary. `amem doctor --json` keeps the full report. */
|
|
116
|
+
export function doctorText(report: DoctorReport, s: Style = PLAIN, opts: ReportTextOptions & { now?: number } = {}): string {
|
|
117
|
+
const now = opts.now ?? Date.now();
|
|
118
|
+
const entries = Object.entries(report.sections) as [keyof DoctorReport["sections"], Section & { hint?: string; reason?: string }][];
|
|
119
|
+
const count = (status: SectionStatus) => entries.filter(([, section]) => section.status === status).length;
|
|
120
|
+
const findings: Finding[] = [];
|
|
121
|
+
for (const [name, item] of entries) {
|
|
122
|
+
if (name === "writers" && item.status === "attention") findings.push(writerFinding(item));
|
|
123
|
+
if (item.hint) findings.push(hintFinding(name, item.hint, item));
|
|
124
|
+
if (name === "capture" && item.clis) for (const [cli, row] of Object.entries(item.clis as Record<string, { hint?: string }>)) if (row.hint) findings.push(captureFinding(cli, row.hint));
|
|
125
|
+
}
|
|
126
|
+
const out = reportFrame(s, "doctor", report.status === "skipped" ? "ok" : STATE_WORD[report.status], opts, report.home);
|
|
127
|
+
out.note(`project ${report.project}`);
|
|
128
|
+
attention(out, findings);
|
|
129
|
+
out.section("Checks", String(entries.length));
|
|
130
|
+
const order: Record<SectionStatus, number> = { attention: 0, unavailable: 1, skipped: 2, ok: 3 };
|
|
131
|
+
entries.sort((a, b) => order[a[1].status] - order[b[1].status]);
|
|
132
|
+
const rows = entries.flatMap(([name, section]) => {
|
|
133
|
+
const { status, hint: _hint, reason, ...detail } = section;
|
|
134
|
+
const facts = name === "writers" && status === "attention" ? [] : sectionFact(name, detail, now);
|
|
135
|
+
const writerRefusal = name === "writers" && status === "attention";
|
|
136
|
+
const fact = writerRefusal ? `${section.cause} (${section.category} category); see Attention`
|
|
137
|
+
: [...facts, ...(reason ? [singleLine(reason)] : [])].join("; ") || (status === "ok" ? "nothing to report" : SECTION_TITLE[name]);
|
|
138
|
+
return [{ state: status, name, fact }];
|
|
139
|
+
});
|
|
140
|
+
stateRows(out, rows, s);
|
|
141
|
+
if (count("skipped")) { out.line(""); out.note(`${count("skipped")} skipped: nothing to check here`); }
|
|
142
|
+
out.summary({ warnings: count("attention"), unknown: count("unavailable"), ok: count("ok") });
|
|
143
|
+
return out.render(s.color).join("\n");
|
|
144
|
+
}
|
package/src/memory/doctor.ts
CHANGED
|
@@ -19,11 +19,10 @@ import { readSelector } from "./generation.ts";
|
|
|
19
19
|
import { processLiveness, withGitTimeout } from "./platform.ts";
|
|
20
20
|
import { endLikeSignal, STOP_SIGNALS } from "./sync-cadence.ts";
|
|
21
21
|
import { boundRepoRoot } from "./repo-scope.ts";
|
|
22
|
-
import { humanBytes, relativeTime, singleLine, wordedFacts, wordedKey, PLAIN, type Style } from "./style.ts";
|
|
23
|
-
import { attention, reportFrame, stateRows, STATE_WORD, type Finding, type ReportTextOptions } from "./status-text.ts";
|
|
24
22
|
import { aliasedKeys, shardDir } from "./shard.ts";
|
|
25
23
|
import type { MemoryStore, View } from "./store.ts";
|
|
26
24
|
import { nextSyncAt, readSyncState, remoteConfigured, syncDue, usableState } from "./sync-cadence.ts";
|
|
25
|
+
import { readSyncStatus } from "./sync-progress.ts";
|
|
27
26
|
import { readSetupDrift } from "../setup-drift.ts";
|
|
28
27
|
import { readHookSpoolStatus } from "../hook-spool.ts";
|
|
29
28
|
|
|
@@ -498,13 +497,19 @@ function cadenceSection(options: DoctorOptions): Section {
|
|
|
498
497
|
const ingest: Record<string, string> = {};
|
|
499
498
|
for (const cli of CLIS) ingest[cli] = receiptPhase(options.home, cli) === "applied" ? (cli === "claude" ? "hooks" : "session end") : "manual";
|
|
500
499
|
const remote = remoteConfigured(options.home), state = usableState(readSyncState(options.home), options.now), next = nextSyncAt(state);
|
|
500
|
+
const latest = readSyncStatus(options.home, options.now).operations
|
|
501
|
+
.filter(op => op.state !== "running" && op.state !== "interrupted" && op.lastAliveUnixMs <= options.now)
|
|
502
|
+
.sort((a, b) => b.lastAliveUnixMs - a.lastAliveUnixMs)[0];
|
|
503
|
+
const lastOk = state.lastOkAt === null ? -Infinity : Date.parse(state.lastOkAt);
|
|
504
|
+
const writerRefusal = latest?.state === "failed" && latest.lastAliveUnixMs > lastOk ? latest.writerRefusal : undefined;
|
|
501
505
|
const command = options.syncCommand ?? "amem sync --if-due";
|
|
502
506
|
const stale = remote && (state.lastOkAt === null || options.now - Date.parse(state.lastOkAt) > SYNC_STALE_MS || state.failures >= 3);
|
|
503
507
|
const sync = { remote: remote ? "configured" : "none", lastAttemptAt: state.lastAttemptAt, lastOkAt: state.lastOkAt, failures: state.failures,
|
|
504
508
|
nextAttemptAt: next === null ? null : new Date(next).toISOString(), due: remote ? syncDue(state, options.now) : false,
|
|
509
|
+
...(writerRefusal ? { writerRefusal } : {}),
|
|
505
510
|
...(remote ? { schedule: `run \`${command}\` from your own shell (for example a zshexit or bash EXIT trap): it needs a terminal like every mutating command; amem registers no sync hook and runs nothing between sessions` } : {}) };
|
|
506
511
|
const manual = CLIS.filter(cli => ingest[cli] === "manual");
|
|
507
|
-
return { status: stale ? "attention" : "ok", ingest, ...(manual.length ? { manual } : {}), sync,
|
|
512
|
+
return { status: stale || writerRefusal ? "attention" : "ok", ingest, ...(manual.length ? { manual } : {}), sync,
|
|
508
513
|
...(stale ? { hint: state.failures >= 3 ? "sync has failed repeatedly; amem sync --force shows why" : "no recent successful sync: run amem sync" } : {}) };
|
|
509
514
|
}
|
|
510
515
|
|
|
@@ -633,140 +638,3 @@ async function runDoctor(options: DoctorOptions, scratch: string): Promise<Docto
|
|
|
633
638
|
} finally { curated?.close(); }
|
|
634
639
|
return { schema: DOCTOR_SCHEMA, status: worst(Object.values(sections).map(section => section.status)), home: { path: options.home, source: options.homeSource }, project: options.project, sections };
|
|
635
640
|
}
|
|
636
|
-
|
|
637
|
-
/** Section order and one-line names for the person-facing report (#125). */
|
|
638
|
-
const SECTION_TITLE: Record<keyof DoctorReport["sections"], string> = {
|
|
639
|
-
duplicates: "duplicate notes", stale: "stale path references", candidates: "review candidates", capture: "capture per CLI", brief: "session brief",
|
|
640
|
-
index: "index equals rebuild", readers: "reader leases", policy: "policy in effect", cadence: "ingest and sync cadence", drops: "recent capture drops",
|
|
641
|
-
writers: "placement writers",
|
|
642
|
-
spool: "pending hook spool",
|
|
643
|
-
setup: "native setup registrations",
|
|
644
|
-
masked: "forgotten or pruned entries (informational)",
|
|
645
|
-
};
|
|
646
|
-
|
|
647
|
-
/**
|
|
648
|
-
* #590 C4: every hint a section emits, as one finding and the complete commands that act on it. `--json` keeps the hint text unchanged;
|
|
649
|
-
* only the human report reads this table. A hint missing from it renders as a finding with no `→`, never as text with an embedded command.
|
|
650
|
-
* `test/status-doctor-layout.test.ts` checks every hint producer against this table.
|
|
651
|
-
*/
|
|
652
|
-
export const DOCTOR_HINTS: Readonly<Record<string, (section: Record<string, unknown>) => Finding>> = {
|
|
653
|
-
"amem dedupe previews the imported duplicates; amem dedupe --apply reconciles them": () =>
|
|
654
|
-
({ text: "imported duplicate notes can be reconciled", next: ["amem dedupe", "amem dedupe --apply"] }),
|
|
655
|
-
"The person can inspect these examples with amem show <id> from their own shell.": section => {
|
|
656
|
-
const first = Array.isArray(section.examples) ? String(section.examples[0] ?? "") : "";
|
|
657
|
-
// #511 AC3: an agent-marked `show` may withhold these ids, so the finding says where they open.
|
|
658
|
-
return { text: `${section.missingReferences} notes reference paths that no longer exist; open the examples from your own shell`, next: first ? [`amem show ${first}`] : [] };
|
|
659
|
-
},
|
|
660
|
-
"the index differs from a rebuild of the logs: run amem rebuild": () => ({ text: "the index differs from a rebuild of the logs", next: ["amem rebuild"] }),
|
|
661
|
-
"a section is partial or unavailable in the brief: see coverage": () => ({ text: "a brief section is partial or unavailable", next: [] }),
|
|
662
|
-
"the brief uses over 90% of its budget": () => ({ text: "the session brief uses over 90% of its budget", next: [] }),
|
|
663
|
-
"a reader lease of a process that is gone is cleared by the next reader; an unreadable one needs a look": () =>
|
|
664
|
-
({ text: "a reader lease is stale or unreadable; the next reader clears a stale one", next: [] }),
|
|
665
|
-
"capture rows were dropped recently (see counts by reason); amem doctor --json keeps the numbers": () =>
|
|
666
|
-
({ text: "capture rows were dropped recently", next: ["amem doctor --json"] }),
|
|
667
|
-
"pending hook spool needs attention: capture can be dropped when both tiers fill; supported orphan recovery is pending": () =>
|
|
668
|
-
({ text: "the hook spool is nearly full; capture is dropped when both tiers fill", next: [] }),
|
|
669
|
-
"sync has failed repeatedly; amem sync --force shows why": () => ({ text: "sync has failed 3 or more times in a row", next: ["amem sync --force"] }),
|
|
670
|
-
"no recent successful sync: run amem sync": () => ({ text: "no recent successful sync", next: ["amem sync"] }),
|
|
671
|
-
"run amem review walk": section => ({ text: `${section.dueWithin7Days} candidates expire within 7 days`, next: ["amem review walk"] }),
|
|
672
|
-
};
|
|
673
|
-
/** Capture hints name a CLI; each maps to a finding and the commands for that CLI. */
|
|
674
|
-
export function captureFinding(cli: string, hint: string): Finding {
|
|
675
|
-
const known = new Set<string>(CLIS);
|
|
676
|
-
const ingest = known.has(cli) && cli !== "claude" ? [`amem ingest ${cli}`] : [];
|
|
677
|
-
if (hint.startsWith(`the ${cli} `) && hint.includes("unsafe symlink")) return { text: `${cli}: a native session root is an unsafe symlink and was skipped`, next: ingest };
|
|
678
|
-
if (hint.startsWith("run amem setup")) return { text: `${cli}: capture is not set up`, next: known.has(cli) ? [`amem setup ${cli} --apply`, ...ingest] : [] };
|
|
679
|
-
if (hint.includes("/hooks trust review")) return { text: "codex: the hook is registered but has never captured; approve it in the Codex /hooks trust review", next: [] };
|
|
680
|
-
const state = /capture is (\w+)/.exec(hint)?.[1] ?? "not fresh", where = hint.includes("on this machine") ? "on this machine" : "in this project";
|
|
681
|
-
return { text: `${cli}: capture is ${state} ${where}; open a session`, next: ingest };
|
|
682
|
-
}
|
|
683
|
-
export function hintFinding(name: string, hint: string, section: Record<string, unknown>): Finding {
|
|
684
|
-
const mapped = DOCTOR_HINTS[hint];
|
|
685
|
-
return mapped ? mapped(section) : { text: `${SECTION_TITLE[name as keyof typeof SECTION_TITLE] ?? name}: ${hint.replace(/[:;,]?\s*(?:run |see |use )?\bamem [a-z].*$/, "").replace(/[:;,]\s*$/, "").trim() || "needs a look"}`, next: [] };
|
|
686
|
-
}
|
|
687
|
-
/** #590 C6: a writer refusal is one finding; each command it names is one `→` line. The fixed refusal text stays in `--json`. */
|
|
688
|
-
export function writerFinding(section: Record<string, unknown>): Finding {
|
|
689
|
-
const reason = String(section.reason ?? "");
|
|
690
|
-
const commands = [...reason.matchAll(/amem (?:migrate --sync-placement --(?:dry-run|resume|abandon)|formats raise home [0-9.]+|setup [a-z]+ --(?:apply|undo))/g)].map(match => match[0]);
|
|
691
|
-
return { text: `placement writer proof is ${section.cause ?? "unverified"} (${section.category ?? "unknown"} category)`, next: [...new Set(commands)] };
|
|
692
|
-
}
|
|
693
|
-
|
|
694
|
-
function sectionFact(name: string, detail: Record<string, unknown>, now: number): string[] {
|
|
695
|
-
if (name === "capture" && detail.clis && typeof detail.clis === "object") {
|
|
696
|
-
return Object.entries(detail.clis as Record<string, Record<string, unknown>>).map(([cli, row]) =>
|
|
697
|
-
`${cli} hook ${row.hook}${row.setup ? ` (${row.setup})` : ""}, capture ${row.capture}${row.lastCaptureAt ? ` ${relativeTime(String(row.lastCaptureAt), now)}` : ""}, ${row.rows} rows; machine-wide ${row.machineCapture ?? "unknown"}${row.machineLastCaptureAt ? ` ${relativeTime(String(row.machineLastCaptureAt), now)}` : ""}${row.note ? `, ${row.note}` : ""}`);
|
|
698
|
-
}
|
|
699
|
-
if (name === "cadence") {
|
|
700
|
-
const sync = (detail.sync ?? {}) as Record<string, unknown>, ingest = (detail.ingest ?? {}) as Record<string, string>;
|
|
701
|
-
return [`ingest ${Object.entries(ingest).map(([cli, how]) => `${cli} ${how}`).join(", ")}`,
|
|
702
|
-
`sync remote ${sync.remote}${sync.remote === "configured" ? `, last ok ${relativeTime(sync.lastOkAt as string | null, now)}, ${sync.failures} failures${sync.due ? ", due" : ""}` : ""}`];
|
|
703
|
-
}
|
|
704
|
-
if (name === "drops") {
|
|
705
|
-
if (detail.counts === undefined) return [];
|
|
706
|
-
const counts = Object.entries((detail.counts ?? {}) as Record<string, number>);
|
|
707
|
-
return [`${counts.length ? counts.map(([reason, n]) => `${reason.replaceAll("_", " ")} ${n}`).join(", ") : "none"} in the recent metrics tail${detail.malformedLines ? `, ${detail.malformedLines} malformed lines skipped` : ""}`];
|
|
708
|
-
}
|
|
709
|
-
if (name === "spool") {
|
|
710
|
-
if (!detail.active || !detail.reserve) return [];
|
|
711
|
-
const tiers = ["active", "reserve"].map(tierName => {
|
|
712
|
-
const tier = detail[tierName] as { files: number; bytes: number; maxFiles: number; maxBytes: number };
|
|
713
|
-
return `${tierName} ${tier.files} of ${tier.maxFiles} files, ${humanBytes(tier.bytes)} of ${humanBytes(tier.maxBytes)}`;
|
|
714
|
-
});
|
|
715
|
-
const kinds = detail.kinds as { native: number; summaries: number; unclassified: number; complete: boolean };
|
|
716
|
-
return [`${String(detail.fill).replaceAll("_", " ")}; ${tiers.join("; ")}; ${detail.claimed} claimed${detail.oldestAt ? `, oldest ${relativeTime(String(detail.oldestAt), now)}` : ""}${detail.complete ? "" : " (counts are lower bounds)"}`,
|
|
717
|
-
`native ${kinds.native}, summaries ${kinds.summaries}, unclassified ${kinds.unclassified}; classification ${detail.classificationCoverage}${kinds.complete ? "" : " (native and summary counts are lower bounds)"}`];
|
|
718
|
-
}
|
|
719
|
-
if (name === "setup" && Array.isArray(detail.entries)) {
|
|
720
|
-
const entries = detail.entries as { target?: unknown; file?: unknown; entry?: unknown; reason?: unknown; expectedFile?: unknown; phase?: unknown }[];
|
|
721
|
-
if (!entries.length) return [`${detail.checked ?? 0} registrations match their receipts`];
|
|
722
|
-
return entries.map(item => singleLine(`${item.target}${item.phase ? ` (${item.phase})` : ""} ${item.file}${item.expectedFile ? `, expected ${item.expectedFile}` : ""} ${item.entry}: ${item.reason}`));
|
|
723
|
-
}
|
|
724
|
-
if (name === "writers") return typeof detail.writers === "number" ? [`${detail.writers} writers match the active inventory`] : [];
|
|
725
|
-
if (name === "brief" && typeof detail.tokens === "number") {
|
|
726
|
-
const missing = Object.entries((detail.coverage ?? {}) as Record<string, unknown>).filter(([, value]) => value && value !== "complete").map(([key, value]) => `${wordedKey(key)} ${value}`);
|
|
727
|
-
return [`${detail.tokens} of ${detail.budget} tokens${missing.length ? `, coverage: ${missing.join(", ")}` : ""}`];
|
|
728
|
-
}
|
|
729
|
-
if (name === "policy") return [`machine ${detail.machine ?? "none (defaults)"}, repo ${detail.repo ?? "none"}, ${detail.denyPaths} deny paths, ${detail.piiPatterns} PII patterns`];
|
|
730
|
-
if (name === "index") return detail.liveIndex ? [`live index ${detail.liveIndex}, equal to a rebuild`] : [];
|
|
731
|
-
if (name === "readers") return [`${detail.live ?? 0} live, ${detail.stale ?? 0} stale, ${detail.unreadable ?? 0} unreadable`];
|
|
732
|
-
if (name === "duplicates" && typeof detail.notes === "number") return [`${detail.notes} notes, ${detail.identicalGroups ?? 0} identical groups, ${detail.importedGroups ?? 0} imported groups${detail.truncated ? `, ${detail.truncated}` : ""}`,
|
|
733
|
-
...(Array.isArray(detail.examples) && detail.examples.length ? [`examples ${(detail.examples as unknown[]).map(item => Array.isArray(item) ? item.join(" = ") : String(item)).join(", ")}`] : [])];
|
|
734
|
-
if (name === "stale" && typeof detail.checked === "number") return [`${detail.checked} checked, ${detail.missingReferences ?? 0} missing`,
|
|
735
|
-
...(Array.isArray(detail.examples) && detail.examples.length ? [`examples ${(detail.examples as unknown[]).join(", ")}`] : [])];
|
|
736
|
-
if (name === "masked") return [`${detail.forgets ?? 0} forgotten, ${detail.prunes ?? 0} pruned; see docs/purge.md`];
|
|
737
|
-
if (name === "candidates") return [`${detail.count ?? 0} pending${detail.unshown ? `, ${detail.unshown} never shown` : ""}${detail.oldestExpiresInDays !== null && detail.oldestExpiresInDays !== undefined ? `, oldest expires in ${detail.oldestExpiresInDays} d` : ""}`];
|
|
738
|
-
const { examples, note: _note, ...rest } = detail;
|
|
739
|
-
const line = wordedFacts(rest);
|
|
740
|
-
return [...(line ? [line] : []), ...(Array.isArray(examples) && examples.length ? [`examples ${examples.map(item => Array.isArray(item) ? item.join(" = ") : String(item)).join(", ")}`] : [])];
|
|
741
|
-
}
|
|
742
|
-
|
|
743
|
-
/** The person-facing report (#125, #590): state, findings with their commands, one row per check, then the summary. `amem doctor --json` keeps the full report. */
|
|
744
|
-
export function doctorText(report: DoctorReport, s: Style = PLAIN, opts: ReportTextOptions & { now?: number } = {}): string {
|
|
745
|
-
const now = opts.now ?? Date.now();
|
|
746
|
-
const entries = Object.entries(report.sections) as [keyof DoctorReport["sections"], Section & { hint?: string; reason?: string }][];
|
|
747
|
-
const count = (status: SectionStatus) => entries.filter(([, section]) => section.status === status).length;
|
|
748
|
-
const findings: Finding[] = [];
|
|
749
|
-
for (const [name, item] of entries) {
|
|
750
|
-
if (name === "writers" && item.status === "attention") findings.push(writerFinding(item));
|
|
751
|
-
if (item.hint) findings.push(hintFinding(name, item.hint, item));
|
|
752
|
-
if (name === "capture" && item.clis) for (const [cli, row] of Object.entries(item.clis as Record<string, { hint?: string }>)) if (row.hint) findings.push(captureFinding(cli, row.hint));
|
|
753
|
-
}
|
|
754
|
-
const out = reportFrame(s, "doctor", report.status === "skipped" ? "ok" : STATE_WORD[report.status], opts, report.home);
|
|
755
|
-
out.note(`project ${report.project}`);
|
|
756
|
-
attention(out, findings);
|
|
757
|
-
out.section("Checks", String(entries.length));
|
|
758
|
-
const order: Record<SectionStatus, number> = { attention: 0, unavailable: 1, skipped: 2, ok: 3 };
|
|
759
|
-
entries.sort((a, b) => order[a[1].status] - order[b[1].status]);
|
|
760
|
-
const rows = entries.flatMap(([name, section]) => {
|
|
761
|
-
const { status, hint: _hint, reason, ...detail } = section;
|
|
762
|
-
const facts = name === "writers" && status === "attention" ? [] : sectionFact(name, detail, now);
|
|
763
|
-
const writerRefusal = name === "writers" && status === "attention";
|
|
764
|
-
const fact = writerRefusal ? `${section.cause} (${section.category} category); see Attention`
|
|
765
|
-
: [...facts, ...(reason ? [singleLine(reason)] : [])].join("; ") || (status === "ok" ? "nothing to report" : SECTION_TITLE[name]);
|
|
766
|
-
return [{ state: status, name, fact }];
|
|
767
|
-
});
|
|
768
|
-
stateRows(out, rows, s);
|
|
769
|
-
if (count("skipped")) { out.line(""); out.note(`${count("skipped")} skipped: nothing to check here`); }
|
|
770
|
-
out.summary({ warnings: count("attention"), unknown: count("unavailable"), ok: count("ok") });
|
|
771
|
-
return out.render(s.color).join("\n");
|
|
772
|
-
}
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { Report } from "@staix/cli-output";
|
|
2
|
+
import { PLAIN, relativeTime, singleLine, type Style } from "./style.ts";
|
|
3
|
+
import { AUDIT_LABELS, type AuditLabel } from "./eval.ts";
|
|
4
|
+
import type { AuditSheet, AuditScore } from "./eval-audit.ts";
|
|
5
|
+
|
|
6
|
+
/** #592: the human eval-audit output, kept out of eval-audit.ts so the write path never imports the output package. */
|
|
7
|
+
interface AuditRender { columns?: number; style?: Style; now?: number }
|
|
8
|
+
/** Human text for `amem eval audit sample`: where the sheet is, and what filling it costs. Content-free, like the score. */
|
|
9
|
+
export function auditSheetText(sheet: AuditSheet, file: string, render?: AuditRender): string {
|
|
10
|
+
const cells = new Set(sheet.notes.map(note => `${note.kind}/${note.age}`));
|
|
11
|
+
const frame = `${sheet.frame}${sheet.truncated ? "+ (the store listing hit its cap, so the frame is a floor)" : ""}`;
|
|
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", "Audit sample"); out.section("Sheet");
|
|
15
|
+
out.kv([["Project", sheet.project], ["Drawn", `${sheet.drawn} of ${frame}`], ["Seed", sheet.seed], ["Measured", relativeTime(sheet.asOf, render.now ?? Date.now())], ["Groups", String(cells.size)], ["Root", sheet.root], ["File", file], ["Withheld", String(sheet.withheld)]]);
|
|
16
|
+
out.note("The sheet is mode 0600, local only; never synced or committed.");
|
|
17
|
+
out.note(`Fill both judge columns using ${AUDIT_LABELS.join(", ")}; the rubric is in the sheet.`);
|
|
18
|
+
if (/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u.test(file)) out.bullet("warn", "The sheet path contains control characters; inspect --json and pass the exact path to the score command.");
|
|
19
|
+
else out.next(`amem eval audit score '${file.replaceAll("'", "'\\''")}'`);
|
|
20
|
+
return out.render(s.color).join("\n");
|
|
21
|
+
}
|
|
22
|
+
return [
|
|
23
|
+
`audit sample: ${sheet.drawn} of ${frame} ${sheet.project} notes, seed "${sheet.seed}" as of ${sheet.asOf}, ${cells.size} kind/age cells, anchors checked in ${sheet.root}${sheet.withheld ? `, ${sheet.withheld} withheld by the configured policy` : ""}`,
|
|
24
|
+
`sheet: ${file} (0600, local only; never synced and never committed)`,
|
|
25
|
+
`fill judge_a and judge_b with ${AUDIT_LABELS.join(", ")} (rubric in the sheet header), then run \`amem eval audit score ${file}\``,
|
|
26
|
+
].join("\n");
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** Human text for `amem eval audit score`; the JSON is the machine form. */
|
|
30
|
+
export function auditScoreText(score: AuditScore, render?: AuditRender): string {
|
|
31
|
+
const row = (label: string, counts: Partial<Record<AuditLabel, number>>) => `${label.padEnd(10)} ${AUDIT_LABELS.map(name => String(counts[name] ?? 0).padStart(4)).join(" ")}`;
|
|
32
|
+
const frame = `${score.frame}${score.truncated ? "+ (the store listing hit its cap, so the frame is a floor)" : ""}`;
|
|
33
|
+
const withheld = score.withheld ? `, ${score.withheld} withheld by the configured policy` : "";
|
|
34
|
+
const head = `audit score: project ${score.project}, ${score.drawn} of ${frame} notes, seed "${score.seed}" as of ${score.asOf}, ${score.labelled} labelled, ${score.unlabelled} not${withheld}`;
|
|
35
|
+
// The joint cells are printed as one line per kind/age/anchor stratum, so a reader sees which label fills each intersection instead of three marginals.
|
|
36
|
+
const strata = new Map<string, Partial<Record<AuditLabel, number>>>();
|
|
37
|
+
for (const cell of score.cells) {
|
|
38
|
+
const key = `${cell.kind}/${cell.age}/${cell.anchor}`, counts = strata.get(key) ?? {};
|
|
39
|
+
counts[cell.label] = cell.count;
|
|
40
|
+
strata.set(key, counts);
|
|
41
|
+
}
|
|
42
|
+
if (render) {
|
|
43
|
+
const s = render.style ?? PLAIN, out = new Report(render.columns ?? 80, s.ascii, { sanitize: singleLine });
|
|
44
|
+
out.header("amem", "Audit score"); out.section("Summary");
|
|
45
|
+
out.kv([["Project", score.project], ["Drawn", `${score.drawn} of ${frame}`], ["Seed", score.seed], ["Measured", relativeTime(score.asOf, render.now ?? Date.now())], ["Labelled", String(score.labelled)], ["Unlabelled", String(score.unlabelled)], ["Withheld", String(score.withheld)], ["Kappa", score.agreement.kappa === null ? "? (needs both judges and more than one label)" : score.agreement.kappa.toFixed(3)], ["Judge pairs", String(score.agreement.pairs)]]);
|
|
46
|
+
out.section("Labels");
|
|
47
|
+
const rows: [string, Partial<Record<AuditLabel, number>>][] = [["all", score.byLabel], ...Object.entries(score.byKind).map(([kind, counts]): [string, Partial<Record<AuditLabel, number>>] => [`kind ${kind}`, counts]), ...Object.entries(score.byAge).map(([age, counts]): [string, Partial<Record<AuditLabel, number>>] => [`age ${age}`, counts]), ...Object.entries(score.byAnchor).map(([anchor, counts]): [string, Partial<Record<AuditLabel, number>>] => [`anchor ${anchor}`, counts]), ...[...strata.entries()].map(([key, counts]): [string, Partial<Record<AuditLabel, number>>] => [`cross ${key}`, counts])];
|
|
48
|
+
out.table(["GROUP", ...AUDIT_LABELS], rows.map(([name, counts]) => [name, ...AUDIT_LABELS.map(label => String(counts[label] ?? 0))]), 0);
|
|
49
|
+
out.line(""); out.line(`Summary: ${score.labelled} labelled, ${score.unlabelled} unlabelled`);
|
|
50
|
+
return out.render(s.color).join("\n");
|
|
51
|
+
}
|
|
52
|
+
return [
|
|
53
|
+
head,
|
|
54
|
+
`${"".padEnd(10)} ${AUDIT_LABELS.map(name => name.slice(0, 4).padStart(4)).join(" ")}`,
|
|
55
|
+
row("all", score.byLabel),
|
|
56
|
+
...Object.entries(score.byKind).map(([kind, counts]) => row(`kind ${kind}`, counts)),
|
|
57
|
+
...Object.entries(score.byAge).map(([age, counts]) => row(`age ${age}`, counts)),
|
|
58
|
+
...Object.entries(score.byAnchor).map(([anchor, counts]) => row(`anchor ${anchor}`, counts)),
|
|
59
|
+
...strata.entries().map(([key, counts]) => row(`cross ${key}`, counts)),
|
|
60
|
+
`kappa ${score.agreement.kappa === null ? "n/a (needs both judge columns, and more than one label between them)" : score.agreement.kappa.toFixed(3)} over ${score.agreement.pairs} doubly labelled note(s)`,
|
|
61
|
+
].join("\n");
|
|
62
|
+
}
|
package/src/memory/eval-audit.ts
CHANGED
|
@@ -15,10 +15,7 @@ import {
|
|
|
15
15
|
} from "./eval.ts";
|
|
16
16
|
import { memoryGitEnv, memoryGitSync, realPath } from "./platform.ts";
|
|
17
17
|
import type { MemoryStore, View } from "./store.ts";
|
|
18
|
-
import { Report } from "@staix/cli-output";
|
|
19
|
-
import { PLAIN, relativeTime, singleLine, type Style } from "./style.ts";
|
|
20
18
|
|
|
21
|
-
interface AuditRender { columns?: number; style?: Style; now?: number }
|
|
22
19
|
|
|
23
20
|
export interface AuditAnchor { path: string; status: Exclude<AuditAnchorStatus, "none"> }
|
|
24
21
|
export interface AuditNote {
|
|
@@ -409,58 +406,4 @@ export function auditScore(sheet: AuditSheet): AuditScore {
|
|
|
409
406
|
return score;
|
|
410
407
|
}
|
|
411
408
|
|
|
412
|
-
/** Human text for `amem eval audit sample`: where the sheet is, and what filling it costs. Content-free, like the score. */
|
|
413
|
-
export function auditSheetText(sheet: AuditSheet, file: string, render?: AuditRender): string {
|
|
414
|
-
const cells = new Set(sheet.notes.map(note => `${note.kind}/${note.age}`));
|
|
415
|
-
const frame = `${sheet.frame}${sheet.truncated ? "+ (the store listing hit its cap, so the frame is a floor)" : ""}`;
|
|
416
|
-
if (render) {
|
|
417
|
-
const s = render.style ?? PLAIN, out = new Report(render.columns ?? 80, s.ascii, { sanitize: singleLine, keepTokensWhole: true });
|
|
418
|
-
out.header("amem", "Audit sample"); out.section("Sheet");
|
|
419
|
-
out.kv([["Project", sheet.project], ["Drawn", `${sheet.drawn} of ${frame}`], ["Seed", sheet.seed], ["Measured", relativeTime(sheet.asOf, render.now ?? Date.now())], ["Groups", String(cells.size)], ["Root", sheet.root], ["File", file], ["Withheld", String(sheet.withheld)]]);
|
|
420
|
-
out.note("The sheet is mode 0600, local only; never synced or committed.");
|
|
421
|
-
out.note(`Fill both judge columns using ${AUDIT_LABELS.join(", ")}; the rubric is in the sheet.`);
|
|
422
|
-
if (/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u.test(file)) out.bullet("warn", "The sheet path contains control characters; inspect --json and pass the exact path to the score command.");
|
|
423
|
-
else out.next(`amem eval audit score '${file.replaceAll("'", "'\\''")}'`);
|
|
424
|
-
return out.render(s.color).join("\n");
|
|
425
|
-
}
|
|
426
|
-
return [
|
|
427
|
-
`audit sample: ${sheet.drawn} of ${frame} ${sheet.project} notes, seed "${sheet.seed}" as of ${sheet.asOf}, ${cells.size} kind/age cells, anchors checked in ${sheet.root}${sheet.withheld ? `, ${sheet.withheld} withheld by the configured policy` : ""}`,
|
|
428
|
-
`sheet: ${file} (0600, local only; never synced and never committed)`,
|
|
429
|
-
`fill judge_a and judge_b with ${AUDIT_LABELS.join(", ")} (rubric in the sheet header), then run \`amem eval audit score ${file}\``,
|
|
430
|
-
].join("\n");
|
|
431
|
-
}
|
|
432
409
|
|
|
433
|
-
/** Human text for `amem eval audit score`; the JSON is the machine form. */
|
|
434
|
-
export function auditScoreText(score: AuditScore, render?: AuditRender): string {
|
|
435
|
-
const row = (label: string, counts: Partial<Record<AuditLabel, number>>) => `${label.padEnd(10)} ${AUDIT_LABELS.map(name => String(counts[name] ?? 0).padStart(4)).join(" ")}`;
|
|
436
|
-
const frame = `${score.frame}${score.truncated ? "+ (the store listing hit its cap, so the frame is a floor)" : ""}`;
|
|
437
|
-
const withheld = score.withheld ? `, ${score.withheld} withheld by the configured policy` : "";
|
|
438
|
-
const head = `audit score: project ${score.project}, ${score.drawn} of ${frame} notes, seed "${score.seed}" as of ${score.asOf}, ${score.labelled} labelled, ${score.unlabelled} not${withheld}`;
|
|
439
|
-
// The joint cells are printed as one line per kind/age/anchor stratum, so a reader sees which label fills each intersection instead of three marginals.
|
|
440
|
-
const strata = new Map<string, Partial<Record<AuditLabel, number>>>();
|
|
441
|
-
for (const cell of score.cells) {
|
|
442
|
-
const key = `${cell.kind}/${cell.age}/${cell.anchor}`, counts = strata.get(key) ?? {};
|
|
443
|
-
counts[cell.label] = cell.count;
|
|
444
|
-
strata.set(key, counts);
|
|
445
|
-
}
|
|
446
|
-
if (render) {
|
|
447
|
-
const s = render.style ?? PLAIN, out = new Report(render.columns ?? 80, s.ascii, { sanitize: singleLine });
|
|
448
|
-
out.header("amem", "Audit score"); out.section("Summary");
|
|
449
|
-
out.kv([["Project", score.project], ["Drawn", `${score.drawn} of ${frame}`], ["Seed", score.seed], ["Measured", relativeTime(score.asOf, render.now ?? Date.now())], ["Labelled", String(score.labelled)], ["Unlabelled", String(score.unlabelled)], ["Withheld", String(score.withheld)], ["Kappa", score.agreement.kappa === null ? "? (needs both judges and more than one label)" : score.agreement.kappa.toFixed(3)], ["Judge pairs", String(score.agreement.pairs)]]);
|
|
450
|
-
out.section("Labels");
|
|
451
|
-
const rows: [string, Partial<Record<AuditLabel, number>>][] = [["all", score.byLabel], ...Object.entries(score.byKind).map(([kind, counts]): [string, Partial<Record<AuditLabel, number>>] => [`kind ${kind}`, counts]), ...Object.entries(score.byAge).map(([age, counts]): [string, Partial<Record<AuditLabel, number>>] => [`age ${age}`, counts]), ...Object.entries(score.byAnchor).map(([anchor, counts]): [string, Partial<Record<AuditLabel, number>>] => [`anchor ${anchor}`, counts]), ...[...strata.entries()].map(([key, counts]): [string, Partial<Record<AuditLabel, number>>] => [`cross ${key}`, counts])];
|
|
452
|
-
out.table(["GROUP", ...AUDIT_LABELS], rows.map(([name, counts]) => [name, ...AUDIT_LABELS.map(label => String(counts[label] ?? 0))]), 0);
|
|
453
|
-
out.line(""); out.line(`Summary: ${score.labelled} labelled, ${score.unlabelled} unlabelled`);
|
|
454
|
-
return out.render(s.color).join("\n");
|
|
455
|
-
}
|
|
456
|
-
return [
|
|
457
|
-
head,
|
|
458
|
-
`${"".padEnd(10)} ${AUDIT_LABELS.map(name => name.slice(0, 4).padStart(4)).join(" ")}`,
|
|
459
|
-
row("all", score.byLabel),
|
|
460
|
-
...Object.entries(score.byKind).map(([kind, counts]) => row(`kind ${kind}`, counts)),
|
|
461
|
-
...Object.entries(score.byAge).map(([age, counts]) => row(`age ${age}`, counts)),
|
|
462
|
-
...Object.entries(score.byAnchor).map(([anchor, counts]) => row(`anchor ${anchor}`, counts)),
|
|
463
|
-
...strata.entries().map(([key, counts]) => row(`cross ${key}`, counts)),
|
|
464
|
-
`kappa ${score.agreement.kappa === null ? "n/a (needs both judge columns, and more than one label between them)" : score.agreement.kappa.toFixed(3)} over ${score.agreement.pairs} doubly labelled note(s)`,
|
|
465
|
-
].join("\n");
|
|
466
|
-
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { Report } from "@staix/cli-output";
|
|
2
|
+
import { PLAIN, singleLine, type Style } from "./style.ts";
|
|
3
|
+
import type { EvalAggregate, EvalReport } from "./eval.ts";
|
|
4
|
+
const pct = (value: number | null): string => value === null ? " n/a" : value.toFixed(3);
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
/** #592: the human eval output, kept out of eval.ts so the write path never imports the output package. */
|
|
8
|
+
/** Human text for `amem eval`; the JSON report is the machine form. */
|
|
9
|
+
export function evalText(report: EvalReport, label: string, render?: { columns?: number; style?: Style }): string {
|
|
10
|
+
if (render) {
|
|
11
|
+
const s = render.style ?? PLAIN, out = new Report(render.columns ?? 80, s.ascii, { sanitize: singleLine });
|
|
12
|
+
out.header("amem", "Evaluation"); out.section("Results");
|
|
13
|
+
out.kv([["Set", label], ["Engine", report.engine], ["Questions", String(report.all.questions)], ["Answerable", String(report.answerable.questions)], ["All MRR", report.all.mrr === null ? "?" : report.all.mrr.toFixed(3)], ["Answerable MRR", report.answerable.mrr === null ? "?" : report.answerable.mrr.toFixed(3)]]);
|
|
14
|
+
if (report.answerable.questions < report.all.questions) out.note(`${report.all.questions - report.answerable.questions} questions name entries this store does not hold; they score zero in all.`);
|
|
15
|
+
out.section("Cutoffs", String(report.ks.length));
|
|
16
|
+
const number = (value: number | null | undefined) => value == null ? "?" : value.toFixed(3);
|
|
17
|
+
out.table(["K", "ALL RECALL", "ALL HIT", "ANSWERABLE RECALL", "ANSWERABLE HIT"], report.ks.map(k => [String(k), number(report.all.recall[k]), number(report.all.hit[k]), number(report.answerable.recall[k]), number(report.answerable.hit[k])]), 0);
|
|
18
|
+
const missed = report.perQuestion.filter(row => row.rank === null || row.rank > Math.min(...report.ks));
|
|
19
|
+
if (missed.length) { out.section("Questions to review", String(missed.length)); out.table(["RESULT", "QUESTION"], missed.map(row => [row.rank === null ? "miss" : `rank ${row.rank}`, `${row.answerable ? "" : "not in store: "}${row.q}`]), 1); }
|
|
20
|
+
out.line(""); out.line(`Summary: ${report.all.questions} questions, ${report.answerable.questions} answerable`);
|
|
21
|
+
return out.render(s.color).join("\n");
|
|
22
|
+
}
|
|
23
|
+
const head = (name: string, row: EvalAggregate) => `${name.padEnd(11)} ${String(row.questions).padStart(4)} ${report.ks.map(k => `${pct(row.recall[k] ?? null)}/${pct(row.hit[k] ?? null)}`.padStart(13)).join(" ")} ${pct(row.mrr).padStart(6)}`;
|
|
24
|
+
return [
|
|
25
|
+
`eval: ${label} (${report.engine === "substring" ? "substring fallback" : "ranked store.search, engine " + report.engine}; same ranked search path as default \`amem search\`; \`--filter\` keeps legacy substring matching)`,
|
|
26
|
+
`${"".padEnd(11)} ${"n".padStart(4)} ${report.ks.map(k => `@${k} recall/hit`.padStart(13)).join(" ")} ${"MRR".padStart(6)}`,
|
|
27
|
+
head("all", report.all),
|
|
28
|
+
head("answerable", report.answerable),
|
|
29
|
+
...(report.answerable.questions < report.all.questions ? [`${report.all.questions - report.answerable.questions} question(s) name an entry this store does not hold (they score 0 in "all")`] : []),
|
|
30
|
+
...report.perQuestion.filter(row => row.rank === null || row.rank > Math.min(...report.ks)).map(row => ` ${row.rank === null ? "miss" : `rank ${row.rank}`}${row.answerable ? "" : " (not in store)"}: ${row.q.slice(0, 100)}`),
|
|
31
|
+
].join("\n");
|
|
32
|
+
}
|
package/src/memory/eval.ts
CHANGED
|
@@ -7,8 +7,6 @@
|
|
|
7
7
|
* - self-contained: `entries` are synthetic notes seeded into a throwaway store, and `expect` names them by `key` (the committed fixture is one);
|
|
8
8
|
* - the person's own: no `entries`, `expect` holds real entry ids (or `mem:<id>`, or a prefix of 8 or more hex characters) and the bound project's store is searched.
|
|
9
9
|
*/
|
|
10
|
-
import { Report } from "@staix/cli-output";
|
|
11
|
-
import { PLAIN, singleLine, type Style } from "./style.ts";
|
|
12
10
|
export const EVAL_SCHEMA = "amem.eval/v1";
|
|
13
11
|
export const MAX_QUESTIONS = 500, MAX_ENTRIES = 200, MAX_QUESTION_CHARS = 500, MAX_EXPECT = 20, MAX_ENTRY_CHARS = 4000, MAX_SET_BYTES = 1024 * 1024, MAX_K = 100;
|
|
14
12
|
export const DEFAULT_KS: readonly number[] = [1, 5, 10];
|
|
@@ -214,29 +212,3 @@ export function runEval(rank: (question: string) => readonly string[], resolve:
|
|
|
214
212
|
return { engine, ks: [...ks], all: aggregate(perQuestion, ks, true), answerable: aggregate(perQuestion.filter(row => row.answerable), ks, false), perQuestion };
|
|
215
213
|
}
|
|
216
214
|
|
|
217
|
-
const pct = (value: number | null): string => value === null ? " n/a" : value.toFixed(3);
|
|
218
|
-
/** Human text for `amem eval`; the JSON report is the machine form. */
|
|
219
|
-
export function evalText(report: EvalReport, label: string, render?: { columns?: number; style?: Style }): string {
|
|
220
|
-
if (render) {
|
|
221
|
-
const s = render.style ?? PLAIN, out = new Report(render.columns ?? 80, s.ascii, { sanitize: singleLine });
|
|
222
|
-
out.header("amem", "Evaluation"); out.section("Results");
|
|
223
|
-
out.kv([["Set", label], ["Engine", report.engine], ["Questions", String(report.all.questions)], ["Answerable", String(report.answerable.questions)], ["All MRR", report.all.mrr === null ? "?" : report.all.mrr.toFixed(3)], ["Answerable MRR", report.answerable.mrr === null ? "?" : report.answerable.mrr.toFixed(3)]]);
|
|
224
|
-
if (report.answerable.questions < report.all.questions) out.note(`${report.all.questions - report.answerable.questions} questions name entries this store does not hold; they score zero in all.`);
|
|
225
|
-
out.section("Cutoffs", String(report.ks.length));
|
|
226
|
-
const number = (value: number | null | undefined) => value == null ? "?" : value.toFixed(3);
|
|
227
|
-
out.table(["K", "ALL RECALL", "ALL HIT", "ANSWERABLE RECALL", "ANSWERABLE HIT"], report.ks.map(k => [String(k), number(report.all.recall[k]), number(report.all.hit[k]), number(report.answerable.recall[k]), number(report.answerable.hit[k])]), 0);
|
|
228
|
-
const missed = report.perQuestion.filter(row => row.rank === null || row.rank > Math.min(...report.ks));
|
|
229
|
-
if (missed.length) { out.section("Questions to review", String(missed.length)); out.table(["RESULT", "QUESTION"], missed.map(row => [row.rank === null ? "miss" : `rank ${row.rank}`, `${row.answerable ? "" : "not in store: "}${row.q}`]), 1); }
|
|
230
|
-
out.line(""); out.line(`Summary: ${report.all.questions} questions, ${report.answerable.questions} answerable`);
|
|
231
|
-
return out.render(s.color).join("\n");
|
|
232
|
-
}
|
|
233
|
-
const head = (name: string, row: EvalAggregate) => `${name.padEnd(11)} ${String(row.questions).padStart(4)} ${report.ks.map(k => `${pct(row.recall[k] ?? null)}/${pct(row.hit[k] ?? null)}`.padStart(13)).join(" ")} ${pct(row.mrr).padStart(6)}`;
|
|
234
|
-
return [
|
|
235
|
-
`eval: ${label} (${report.engine === "substring" ? "substring fallback" : "ranked store.search, engine " + report.engine}; same ranked search path as default \`amem search\`; \`--filter\` keeps legacy substring matching)`,
|
|
236
|
-
`${"".padEnd(11)} ${"n".padStart(4)} ${report.ks.map(k => `@${k} recall/hit`.padStart(13)).join(" ")} ${"MRR".padStart(6)}`,
|
|
237
|
-
head("all", report.all),
|
|
238
|
-
head("answerable", report.answerable),
|
|
239
|
-
...(report.answerable.questions < report.all.questions ? [`${report.all.questions - report.answerable.questions} question(s) name an entry this store does not hold (they score 0 in "all")`] : []),
|
|
240
|
-
...report.perQuestion.filter(row => row.rank === null || row.rank > Math.min(...report.ks)).map(row => ` ${row.rank === null ? "miss" : `rank ${row.rank}`}${row.answerable ? "" : " (not in store)"}: ${row.q.slice(0, 100)}`),
|
|
241
|
-
].join("\n");
|
|
242
|
-
}
|
package/src/memory/formats.ts
CHANGED
|
@@ -31,6 +31,8 @@ const READER_VERSION: string | undefined = (() => {
|
|
|
31
31
|
try { const { version } = JSON.parse(readFileSync(new URL("../../package.json", import.meta.url), "utf8")) as { version?: unknown }; return typeof version === "string" && SEMVER.test(version) ? version : undefined; }
|
|
32
32
|
catch { return undefined; }
|
|
33
33
|
})();
|
|
34
|
+
/** This release's plain version as read at load, or undefined when unreadable. */
|
|
35
|
+
export function amemReaderVersion(): string | undefined { return READER_VERSION; }
|
|
34
36
|
const parts = (version: string) => SEMVER.exec(version)!.slice(1, 4).map(Number);
|
|
35
37
|
/** Compare versions accepted by format-floor records, using their numeric release components. */
|
|
36
38
|
export function formatVersionBelow(reader: string, floor: string): boolean {
|