@staix/agent-mem 0.31.0 → 0.32.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/plugin.json +1 -1
- package/README.md +1 -1
- package/package.json +1 -1
- package/src/cli-agent-reads.ts +2 -1
- package/src/cli.ts +74 -23
- package/src/commands-table.ts +27 -12
- package/src/mcp-memory.ts +21 -2
- package/src/memory/catalog.ts +29 -2
- package/src/memory/curated-read.ts +5 -3
- package/src/memory/decay-review.ts +1 -1
- package/src/memory/doctor.ts +27 -13
- package/src/memory/public-prune-view.ts +8 -3
- package/src/memory/recap-scratch.ts +2 -0
- package/src/memory/recap-telemetry.ts +5 -0
- package/src/memory/search-fts.ts +1 -1
- package/src/memory/shard.ts +137 -5
- package/src/memory/status-text.ts +6 -6
- package/src/memory/store.ts +9 -2
- package/src/memory/style.ts +84 -6
- package/src/setup-drift.ts +71 -6
- package/src/setup-owned.ts +14 -0
- package/src/setup.ts +34 -23
- package/src/sync-placement-writer-context.ts +44 -9
- package/src/ui/panel.js +15 -3
- package/src/ui/plugin.ts +53 -20
- package/src/ui/snapshot-revision.ts +2 -0
package/src/memory/doctor.ts
CHANGED
|
@@ -7,16 +7,18 @@ import { basename, join } from "node:path";
|
|
|
7
7
|
import { Database } from "bun:sqlite";
|
|
8
8
|
import { sessionStartBrief, type BriefOptions } from "../session-brief.ts";
|
|
9
9
|
import { openCuratedForRead } from "./curated-read.ts";
|
|
10
|
+
import { RECAP_SCRATCH } from "./recap-scratch.ts";
|
|
10
11
|
import { pendingSummary } from "./candidate-pending.ts";
|
|
11
12
|
import { inspectNativeRoot, nativeRoots, type NativeRootKind } from "./native-roots.ts";
|
|
12
13
|
import { readCaptureDrops } from "./metrics.ts";
|
|
14
|
+
import { isRecapTelemetry } from "./recap-telemetry.ts";
|
|
13
15
|
import { walkShards } from "./catalog.ts";
|
|
14
16
|
import { loadAmemConfig, repoConfigRoot } from "./config.ts";
|
|
15
17
|
import { readSelector } from "./generation.ts";
|
|
16
18
|
import { processLiveness, withGitTimeout } from "./platform.ts";
|
|
17
19
|
import { endLikeSignal, STOP_SIGNALS } from "./sync-cadence.ts";
|
|
18
20
|
import { boundRepoRoot } from "./repo-scope.ts";
|
|
19
|
-
import { facts, label, PLAIN, singleLine, type Style } from "./style.ts";
|
|
21
|
+
import { facts, label, paint, section, markerCell, PLAIN, singleLine, type Style } from "./style.ts";
|
|
20
22
|
import { aliasedKeys, shardDir } from "./shard.ts";
|
|
21
23
|
import type { MemoryStore, View } from "./store.ts";
|
|
22
24
|
import { nextSyncAt, readSyncState, remoteConfigured, syncDue, usableState } from "./sync-cadence.ts";
|
|
@@ -153,11 +155,11 @@ function copyTree(from: string, to: string, budget: CopyBudget, skipNames: Reado
|
|
|
153
155
|
}
|
|
154
156
|
|
|
155
157
|
/** The curated side of the home, without any database: the logs of this project (and its aliases), and the small files that bind them. */
|
|
156
|
-
function copyCurated(options: Pick<DoctorOptions, "home" | "project" | "aliases">, layout: Layout, scratch: string, budget: CopyBudget): void {
|
|
158
|
+
function copyCurated(options: Pick<DoctorOptions, "home" | "project" | "aliases">, layout: Layout, scratch: string, budget: CopyBudget, recap = false): void {
|
|
157
159
|
const home = options.home;
|
|
158
|
-
observeDirectory(home, budget, name => !SKIP.test(name) && regularFile(join(home, name)));
|
|
160
|
+
observeDirectory(home, budget, name => !SKIP.test(name) && !(recap && isRecapTelemetry(name)) && regularFile(join(home, name)));
|
|
159
161
|
for (const name of readdirSync(home)) { // top-level plain files: machine.json, shards.json, profile.json, aliases.jsonl, lifecycle.jsonl, the configuration
|
|
160
|
-
if (SKIP.test(name) || !regularFile(join(home, name))) continue;
|
|
162
|
+
if (SKIP.test(name) || recap && isRecapTelemetry(name) || !regularFile(join(home, name))) continue;
|
|
161
163
|
observedCopy(join(home, name), join(scratch, name), budget);
|
|
162
164
|
}
|
|
163
165
|
const selected = readSelector(home).selector;
|
|
@@ -218,8 +220,8 @@ export async function withBriefSnapshot<T>(home: string, project: string, read:
|
|
|
218
220
|
const options = { home, project, aliases }, workBase = join(scratch, "work-base"); mkdirSync(workBase, { mode: 0o700 });
|
|
219
221
|
copyWork(options, workBase, budget);
|
|
220
222
|
if (curatedPresent(home, project, layout)) {
|
|
221
|
-
const copy = join(scratch, "home"); copyCurated(options, layout, copy, budget);
|
|
222
|
-
curated = openCuratedForRead(copy, project);
|
|
223
|
+
const copy = join(scratch, "home"); copyCurated(options, layout, copy, budget, true);
|
|
224
|
+
curated = openCuratedForRead(copy, project, RECAP_SCRATCH);
|
|
223
225
|
if (!curated) throw Error("recap curated snapshot unavailable");
|
|
224
226
|
}
|
|
225
227
|
check(budget);
|
|
@@ -648,8 +650,8 @@ function sectionDetail(name: string, detail: Record<string, unknown>, s: Style):
|
|
|
648
650
|
`native ${kinds.native}, summaries ${kinds.summaries}, unclassified ${kinds.unclassified}; classification ${detail.classificationCoverage}${kinds.complete ? "" : " (native and summary counts are lower bounds)"}`];
|
|
649
651
|
}
|
|
650
652
|
if (name === "setup" && Array.isArray(detail.entries)) {
|
|
651
|
-
return (detail.entries as { target?: unknown; file?: unknown; entry?: unknown; reason?: unknown; expectedFile?: unknown }[]).map(item =>
|
|
652
|
-
singleLine(`${item.target} ${item.file}${item.expectedFile ? ` -> ${item.expectedFile}` : ""} ${item.entry}: ${item.reason}`));
|
|
653
|
+
return (detail.entries as { target?: unknown; file?: unknown; entry?: unknown; reason?: unknown; expectedFile?: unknown; phase?: unknown }[]).map(item =>
|
|
654
|
+
singleLine(`${item.target}${item.phase ? ` (${item.phase})` : ""} ${item.file}${item.expectedFile ? ` -> ${item.expectedFile}` : ""} ${item.entry}: ${item.reason}`));
|
|
653
655
|
}
|
|
654
656
|
if (name === "brief" && typeof detail.tokens === "number") return [`${detail.tokens} of ${detail.budget} tokens${detail.coverage ? `, coverage ${facts(detail.coverage as Record<string, unknown>) || "complete"}` : ""}`];
|
|
655
657
|
const { examples, ...rest } = detail;
|
|
@@ -662,17 +664,29 @@ export function doctorText(report: DoctorReport, s: Style = PLAIN): string {
|
|
|
662
664
|
const entries = Object.entries(report.sections) as [keyof DoctorReport["sections"], Section & { hint?: string; reason?: string }][];
|
|
663
665
|
const count = (status: SectionStatus) => entries.filter(([, section]) => section.status === status).length;
|
|
664
666
|
const summary = facts({ attention: count("attention"), unavailable: count("unavailable"), skipped: count("skipped") });
|
|
665
|
-
const lines = [`${s.bold("amem doctor:")} ${report.status === "ok" ? s.ok(report.status) : report.status === "attention" ? s.attention(report.status) : s.error(report.status)}${summary ? ` (${summary})` : ` (all ${entries.length} checks ok)`}`,
|
|
666
|
-
`home ${report.home.path} ${s.dim(`(${report.home.source})`)}`, `project ${report.project}`, ""];
|
|
667
667
|
const actions: string[] = [];
|
|
668
|
+
for (const [name, item] of entries) {
|
|
669
|
+
if (item.hint) actions.push(`${name}: ${item.hint}`);
|
|
670
|
+
if (name === "capture" && item.clis) for (const [cli, row] of Object.entries(item.clis as Record<string, { hint?: string }>)) if (row.hint) actions.push(`capture ${cli}: ${row.hint}`);
|
|
671
|
+
}
|
|
672
|
+
const lines = [`${paint("header", " amem Doctor", s.color)}: ${report.status === "ok" ? s.ok(report.status) : report.status === "attention" ? s.attention(report.status) : s.error(report.status)}${summary ? ` (${summary})` : ` (all ${entries.length} checks ok)`}`,
|
|
673
|
+
...(actions.length ? ["", section(s, "Attention"), ...actions.map(action => ` ${paint("accent", markerCell("next", s.ascii), s.color)} ${action}`)] : []),
|
|
674
|
+
"", section(s, "Checks"), ` home: ${report.home.path} ${s.dim(`(${report.home.source})`)}`, ` project: ${report.project}`];
|
|
675
|
+
const order: Record<SectionStatus, number> = { attention: 0, unavailable: 1, skipped: 2, ok: 3 };
|
|
676
|
+
entries.sort((a, b) => order[a[1].status] - order[b[1].status]);
|
|
668
677
|
for (const [name, section] of entries) {
|
|
669
678
|
const { status, hint, reason, ...detail } = section;
|
|
670
679
|
lines.push(`${label(s, status)} ${name}: ${s.dim(SECTION_TITLE[name])}`);
|
|
671
680
|
for (const line of sectionDetail(name, detail, s)) lines.push(` ${line}`);
|
|
672
681
|
if (reason) lines.push(` ${s.dim(`reason: ${reason}`)}`);
|
|
673
|
-
if (hint) actions.push(`${name}: ${hint}`);
|
|
674
|
-
if (name === "capture" && detail.clis) for (const [cli, row] of Object.entries(detail.clis as Record<string, { hint?: string }>)) if (row.hint) actions.push(`capture ${cli}: ${row.hint}`);
|
|
675
682
|
}
|
|
676
|
-
lines.push("", actions.length ? "Next actions:" : "Next actions: none"
|
|
683
|
+
lines.push("", actions.length ? "Next actions: see Attention" : "Next actions: none");
|
|
684
|
+
const counts = [
|
|
685
|
+
...(count("attention") ? [`${paint("warning", markerCell("warn", s.ascii), s.color)} ${count("attention")} warnings`] : []),
|
|
686
|
+
...(count("unavailable") ? [`${paint("hint", markerCell("unknown", s.ascii), s.color)} ${count("unavailable")} unknown`] : []),
|
|
687
|
+
...(count("skipped") ? [`${paint("hint", markerCell("absent", s.ascii), s.color)} ${count("skipped")} skipped`] : []),
|
|
688
|
+
...(count("ok") ? [`${paint("success", markerCell("ok", s.ascii), s.color)} ${count("ok")} ok`] : []),
|
|
689
|
+
];
|
|
690
|
+
if (counts.length) lines.push(counts.join(" "));
|
|
677
691
|
return lines.join("\n");
|
|
678
692
|
}
|
|
@@ -14,6 +14,10 @@ export interface PublicPruneViewV1 {
|
|
|
14
14
|
const unavailable = (): never => { throw new Error("public prune view unavailable"); };
|
|
15
15
|
function guard(ok: unknown): asserts ok { if (!ok) unavailable(); }
|
|
16
16
|
function protectedCall<T>(work: () => T): T { try { return work(); } catch { return unavailable(); } }
|
|
17
|
+
/** #225/#302: a stat of an inode whose last link is already gone reports nlink 0, not ENOENT. On a path that is the
|
|
18
|
+
* same normal disappearance as an absent one: treat the path as gone and keep waiting or re-read. Any other count,
|
|
19
|
+
* owner or mode still refuses, and a zero-link profile.json still ends as unavailable. */
|
|
20
|
+
const gone = (stat: Stats | undefined): Stats | undefined => (stat && stat.nlink === 0 ? undefined : stat);
|
|
17
21
|
const object = (value: unknown): value is Record<string, unknown> => !!value && typeof value === "object" && !Array.isArray(value)
|
|
18
22
|
&& (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null);
|
|
19
23
|
const hex = (value: unknown, size: number): value is string => typeof value === "string" && value.length === size && /^[a-f0-9]+$/.test(value);
|
|
@@ -52,9 +56,10 @@ export function waitForPublicPruneWriter(home: string, absoluteDeadline?: number
|
|
|
52
56
|
// #225: a cooperating writer that finishes unlinks its intent, then its lock. If that lands between this reader's
|
|
53
57
|
// open and fstat, the fd's link count is 0. Only that is the normal disappearance (ENOENT): bytes read through the fd
|
|
54
58
|
// are discarded and the bounded loop re-resolves the path from scratch. Any other link count still refuses.
|
|
59
|
+
// #302: the same count seen by a path lstat here is `gone`, which yields the same ENOENT-or-absent behavior.
|
|
55
60
|
const unlinked = (stat: Stats): void => { if (stat.nlink === 0) throw Object.assign(new Error("publication unlinked while open"), { code: "ENOENT" }); };
|
|
56
61
|
const small = (file: string, limit: number): Record<string, unknown> => {
|
|
57
|
-
const before = lstatSync(file); privateStat(before); guard(before.size > 0 && before.size <= limit);
|
|
62
|
+
const before = lstatSync(file); unlinked(before); privateStat(before); guard(before.size > 0 && before.size <= limit);
|
|
58
63
|
const fd = openSync(file, constants.O_RDONLY | constants.O_NOFOLLOW);
|
|
59
64
|
try {
|
|
60
65
|
const opened = fstatSync(fd); unlinked(opened); privateStat(opened); guard(opened.size > 0 && opened.size <= limit);
|
|
@@ -70,7 +75,7 @@ export function waitForPublicPruneWriter(home: string, absoluteDeadline?: number
|
|
|
70
75
|
if (profile.schema !== "agent-mem.profile/v2") return; // v1 admission/intent behavior is unchanged.
|
|
71
76
|
for (;;) {
|
|
72
77
|
try {
|
|
73
|
-
const intent = lstatSync(intentFile, { throwIfNoEntry: false }), lock = lstatSync(lockFile, { throwIfNoEntry: false });
|
|
78
|
+
const intent = gone(lstatSync(intentFile, { throwIfNoEntry: false })), lock = gone(lstatSync(lockFile, { throwIfNoEntry: false }));
|
|
74
79
|
if (!intent && !lock) return;
|
|
75
80
|
if (lock) {
|
|
76
81
|
privateStat(lock);
|
|
@@ -99,7 +104,7 @@ export function waitForPublicPruneWriter(home: string, absoluteDeadline?: number
|
|
|
99
104
|
}
|
|
100
105
|
/** Any unresolved intent blocks reads. Never remove it, including malformed bytes. */
|
|
101
106
|
export function assertNoPublicPruneIntent(home: string, absoluteDeadline?: number): void {
|
|
102
|
-
protectedCall(() => { waitForPublicPruneWriter(home, absoluteDeadline); guard(!lstatSync(join(home, PUBLIC_PRUNE_INTENT), { throwIfNoEntry: false })); });
|
|
107
|
+
protectedCall(() => { waitForPublicPruneWriter(home, absoluteDeadline); guard(!gone(lstatSync(join(home, PUBLIC_PRUNE_INTENT), { throwIfNoEntry: false }))); });
|
|
103
108
|
}
|
|
104
109
|
function privateStat(stat: Stats, directory = false): void {
|
|
105
110
|
guard(!stat.isSymbolicLink() && (directory ? stat.isDirectory() : stat.isFile() && stat.nlink === 1));
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
/** Observation journals are not inputs to Recap or its reusable panel projections. */
|
|
2
|
+
export function isRecapTelemetry(name: string): boolean {
|
|
3
|
+
return name === "metrics.jsonl" || name === "record-variants.jsonl"
|
|
4
|
+
|| /^record-variants\.jsonl\.tmp-[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(name);
|
|
5
|
+
}
|
package/src/memory/search-fts.ts
CHANGED
|
@@ -87,7 +87,7 @@ export class SearchIndex {
|
|
|
87
87
|
db.run("CREATE VIRTUAL TABLE IF NOT EXISTS docs USING fts5(body, ref UNINDEXED, project UNINDEXED, tier UNINDEXED, at UNINDEXED, scope UNINDEXED)");
|
|
88
88
|
// FTS5 has no unique constraint: refs remembers what is indexed, so a repeated or rebuilt row is never doubled.
|
|
89
89
|
db.run("CREATE TABLE IF NOT EXISTS refs (ref TEXT PRIMARY KEY)");
|
|
90
|
-
try { chmodSync(file, 0o600); } catch { /* best effort */ }
|
|
90
|
+
if (file !== ":memory:") try { chmodSync(file, 0o600); } catch { /* best effort */ }
|
|
91
91
|
this.db = db;
|
|
92
92
|
this.available = true;
|
|
93
93
|
} catch { this.available = false; }
|
package/src/memory/shard.ts
CHANGED
|
@@ -5,7 +5,7 @@ import { assertPlacementRuntime, doctorScratchBinding, doctorScratchInventory, S
|
|
|
5
5
|
import { assertNoPublicPruneIntent, readPublicPruneView } from "./public-prune-view.ts";
|
|
6
6
|
import { indexFileName } from "./index-file.ts";
|
|
7
7
|
import { createHash, randomBytes } from "node:crypto";
|
|
8
|
-
import { existsSync, linkSync, lstatSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
|
8
|
+
import { existsSync, linkSync, lstatSync, mkdirSync, opendirSync, readFileSync, rmSync, writeFileSync, type Dir } from "node:fs";
|
|
9
9
|
import { join } from "node:path";
|
|
10
10
|
import { canonicalJSON, generationDescriptor, hashJSON, readProfileJSON, readSelector, validGeneration, PROFILE_LOCK_TIMEOUT_MS, type BoundProfile, type GenerationSeal } from "./generation.ts";
|
|
11
11
|
import { SHARD_SCHEMA, resolveAlias } from "./aliases.ts";
|
|
@@ -35,6 +35,13 @@ export function shardKeyHash(key: string): string {
|
|
|
35
35
|
/** A key in the no-remote path-hash form (`chain@hash8`) is this machine's only; the catalog flags it. */
|
|
36
36
|
export const isLocalKey = (key: string): boolean => /.+@[0-9a-f]{8}$/.test(key);
|
|
37
37
|
|
|
38
|
+
/**
|
|
39
|
+
* #525: why a project realm is outside the activated inventory. The class comes from the realm's own evidence, never
|
|
40
|
+
* from its key form alone: a restored curated realm can be GitHub-keyed and unadmitted, and an absent curated marker
|
|
41
|
+
* only means capture *might* be the case. `unverified` answers whenever a check could not run safely.
|
|
42
|
+
*/
|
|
43
|
+
export type PlacementRealmGap = "local-key" | "capture-only" | "no-memory" | "curated-unadmitted" | "unverified";
|
|
44
|
+
|
|
38
45
|
export function localKeyOptInMessage(key: string): string {
|
|
39
46
|
return `Local project ${JSON.stringify(key)} requires an explicit amem sync --remote <url> opt-in, or run amem project archive with that project key.`;
|
|
40
47
|
}
|
|
@@ -158,12 +165,25 @@ export function readShardedSelection(memoryDir: string): ShardedSelection {
|
|
|
158
165
|
}catch(error){if(safeProfileLockMessage(error))throw error;throw profileLockRecoveryError(memoryDir)??error;}
|
|
159
166
|
}
|
|
160
167
|
|
|
168
|
+
/** #525: each class carries its own next step. No path, project name or key appears here; the key hash stays the identifier. */
|
|
169
|
+
function realmGapRemedy(gap: PlacementRealmGap | undefined): string {
|
|
170
|
+
const admit = "admit it with amem migrate --sync-placement --admit <project> --dry-run, then --apply";
|
|
171
|
+
switch (gap) {
|
|
172
|
+
// Admission alone does not publish a local-key realm: sync needs an explicit remote opt-in per invocation.
|
|
173
|
+
case "local-key": return `class=local-key; to keep it, ${admit} when you want curated memory, then give sync an explicit remote opt-in with amem sync --remote <url>; otherwise remove it with amem project archive <project>`;
|
|
174
|
+
case "capture-only": return `class=capture-only; it holds capture rows and no curated memory, so capture stays readable; ${admit} if you want curated memory for it`;
|
|
175
|
+
case "no-memory": return `class=no-memory; it holds no captured rows and no curated notes yet; ${admit} if you want curated memory for it, or remove it with amem project archive <project>`;
|
|
176
|
+
case "curated-unadmitted": return `class=curated-unadmitted; it holds curated notes that are not part of the activated inventory, and ${admit} opens them`;
|
|
177
|
+
case "unverified": return "class=unverified; neither its curated state nor the activated inventory could be verified safely; have the person inspect the home before changing anything";
|
|
178
|
+
default: return admit;
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
|
|
161
182
|
/** Bounded identifiers only, safe to surface without exposing a project key or row. */
|
|
162
183
|
export class PlacementRealmRefusal extends Error {
|
|
163
|
-
constructor(readonly scope: "user" | "project", readonly keyHash: string | undefined, readonly origin: "cwd binding" | "remote" | "local binding") {
|
|
184
|
+
constructor(readonly scope: "user" | "project", readonly keyHash: string | undefined, readonly origin: "cwd binding" | "remote" | "local binding", readonly gap?: PlacementRealmGap) {
|
|
164
185
|
// A same-epoch extension record describes a project realm only, so the user realm is fixed by activation and has no admission command.
|
|
165
|
-
const next = scope === "user" ? "the user realm is fixed at activation; review it with amem migrate --sync-placement --dry-run"
|
|
166
|
-
: "admit it with amem migrate --sync-placement --admit <project> --dry-run, then --apply";
|
|
186
|
+
const next = scope === "user" ? "the user realm is fixed at activation; review it with amem migrate --sync-placement --dry-run" : realmGapRemedy(gap);
|
|
167
187
|
super(`sync placement realm is outside the activated inventory: scope=${scope}${keyHash ? ` keyHash=${keyHash}` : ""}; origin=${origin}; ${next}`);
|
|
168
188
|
}
|
|
169
189
|
}
|
|
@@ -202,7 +222,7 @@ export function assertCuratedShardPaths(memoryDir: string, opts: { project?: str
|
|
|
202
222
|
// An appended same-epoch extension is part of the inventory a curated write may open (#448); a realm it does not name stays refused.
|
|
203
223
|
const inventory = scratch ? doctorScratchInventory(memoryDir) : active ? readEffectiveRealmInventory(memoryDir, active) : undefined;
|
|
204
224
|
if (!inventory?.realms.some(realm => opts.user ? realm.scope === "user" : realm.scope === "project" && realm.keyHash === keyHash))
|
|
205
|
-
throw new PlacementRealmRefusal(opts.user ? "user" : "project", keyHash, origin);
|
|
225
|
+
throw new PlacementRealmRefusal(opts.user ? "user" : "project", keyHash, origin, opts.user ? undefined : placementRealmGap(memoryDir, opts.project!, inventoryView(inventory)));
|
|
206
226
|
inventory.assertCurrent();
|
|
207
227
|
recheckInventory = inventory.assertCurrent;
|
|
208
228
|
}
|
|
@@ -210,6 +230,118 @@ export function assertCuratedShardPaths(memoryDir: string, opts: { project?: str
|
|
|
210
230
|
recheckInventory?.();
|
|
211
231
|
}
|
|
212
232
|
|
|
233
|
+
type RealmInventory = ReturnType<typeof readEffectiveRealmInventory>;
|
|
234
|
+
|
|
235
|
+
function inventoryView(inventory: RealmInventory | undefined): PlacementRealmView | undefined {
|
|
236
|
+
return inventory
|
|
237
|
+
? { kind: "inventory", admitted: keyHash => inventory.realms.some(realm => realm.scope === "project" && realm.keyHash === keyHash), assertCurrent: inventory.assertCurrent }
|
|
238
|
+
: undefined;
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
/**
|
|
242
|
+
* #525: the activated inventory as the console sees it, built the way the curated preflight builds it. `undefined` means a
|
|
243
|
+
* placement-v3 home whose proof could not be established, where no class may be claimed. A home that is not placement-v3
|
|
244
|
+
* gates no curated open, so it answers `none` and nothing is marked.
|
|
245
|
+
*/
|
|
246
|
+
export type PlacementRealmView = { readonly kind: "none" } | { readonly kind: "inventory"; admitted(keyHash: string): boolean; assertCurrent(): void };
|
|
247
|
+
|
|
248
|
+
export function placementRealmView(base: string): PlacementRealmView | undefined {
|
|
249
|
+
let selector: { schema?: unknown } | undefined;
|
|
250
|
+
try { selector = readProfileJSON(join(base, "profile.json")) as { schema?: unknown } | undefined; } catch { return undefined; }
|
|
251
|
+
if (selector?.schema !== "agent-mem.profile/v3") return { kind: "none" };
|
|
252
|
+
// No fallback to `none` here: a malformed v3 home is unproved, not ungated.
|
|
253
|
+
try {
|
|
254
|
+
const scratch = doctorScratchBinding(base);
|
|
255
|
+
const active = scratch ?? readActivePlacementBinding(base, selector, readProfileJSON(join(base, "shards.json")));
|
|
256
|
+
return inventoryView(scratch ? doctorScratchInventory(base) : active ? readEffectiveRealmInventory(base, active) : undefined);
|
|
257
|
+
} catch { return undefined; }
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
/**
|
|
261
|
+
* #525: why this project realm is outside the activated inventory, from the realm's own evidence. The key form decides only
|
|
262
|
+
* the local-key class; capture is proved by a machine-scope capture store and curated memory by its seal or generation record,
|
|
263
|
+
* so an absent curated marker never implies capture. Anything unreadable or incompletely scanned stays `unverified` rather
|
|
264
|
+
* than guessed.
|
|
265
|
+
*/
|
|
266
|
+
export function placementRealmGap(base: string, key: string, view: PlacementRealmView | undefined): PlacementRealmGap | undefined {
|
|
267
|
+
if (view?.kind === "none") return undefined;
|
|
268
|
+
if (!view) return "unverified";
|
|
269
|
+
if (view.admitted(createHash("sha256").update(key).digest("hex"))) return undefined;
|
|
270
|
+
if (isLocalKey(key)) return "local-key";
|
|
271
|
+
// Never follow a linked projects/ or shard directory while deriving a class: evidence behind a link is not this home's.
|
|
272
|
+
// ponytail: a same-user parent replacement between this lstat and the marker reads is not fenced; descriptor-relative opens are the upgrade.
|
|
273
|
+
for (const dir of [join(base, "projects"), shardDir(base, key)]) {
|
|
274
|
+
try { const stat = lstatSync(dir); if (stat.isSymbolicLink() || !stat.isDirectory()) return "unverified"; }
|
|
275
|
+
catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") break; return "unverified"; }
|
|
276
|
+
}
|
|
277
|
+
const curated = curatedMarker(base, key);
|
|
278
|
+
if (curated === "present") return "curated-unadmitted";
|
|
279
|
+
if (curated === "unreadable") return "unverified";
|
|
280
|
+
const capture = captureMarker(base, key);
|
|
281
|
+
if (capture === "unreadable" || capture === "incomplete") return "unverified";
|
|
282
|
+
return capture === "present" ? "capture-only" : "no-memory";
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
/**
|
|
286
|
+
* One owned regular file, never followed: `present` only for a regular file of this user without group or world write, and
|
|
287
|
+
* `unreadable` for a link, a foreign or loosened file, a platform that cannot name the owner, and any error but a missing one.
|
|
288
|
+
*/
|
|
289
|
+
function ownedFileState(path: string): "present" | "absent" | "unreadable" {
|
|
290
|
+
try {
|
|
291
|
+
const stat = lstatSync(path), uid = process.getuid?.();
|
|
292
|
+
return uid !== undefined && !stat.isSymbolicLink() && stat.isFile() && stat.uid === uid && (stat.mode & 0o022) === 0 ? "present" : "unreadable";
|
|
293
|
+
} catch (error) { return (error as NodeJS.ErrnoException).code === "ENOENT" ? "absent" : "unreadable"; }
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
/** The curated marker is the seal or the generation record. Neither is opened, so a malformed one still reads as presence. */
|
|
297
|
+
function curatedMarker(base: string, key: string): "present" | "absent" | "unreadable" {
|
|
298
|
+
const dir = shardDir(base, key);
|
|
299
|
+
const states = ["generation.json", "generation-seal.json"].map(name => ownedFileState(join(dir, name)));
|
|
300
|
+
if (states.includes("present")) return "present";
|
|
301
|
+
return states.includes("unreadable") ? "unreadable" : "absent";
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
/** Machine-scope entries one shard may hold and still be scanned completely; at most one more entry than this is read. */
|
|
305
|
+
// ponytail: ceiling is 64 machine entries; a shard with more and no store in the scanned prefix reads unverified. Upgrade: a full streaming scan or a per-shard capture index.
|
|
306
|
+
const MACHINE_SCAN_LIMIT = 64;
|
|
307
|
+
|
|
308
|
+
/**
|
|
309
|
+
* #525: capture is proved by a machine-scope capture store, never inferred from an absent curated marker. Every entry the
|
|
310
|
+
* listing yields counts toward the bound, so a directory full of stray names cannot make the scan unbounded; a shard with
|
|
311
|
+
* more entries, or with an entry that is not a plain directory (a link could hold the store elsewhere), cannot establish
|
|
312
|
+
* absence and answers `incomplete` or `unreadable`. A store found inside the scanned prefix still proves capture.
|
|
313
|
+
*/
|
|
314
|
+
function captureMarker(base: string, key: string): "present" | "absent" | "unreadable" | "incomplete" {
|
|
315
|
+
const root = join(shardDir(base, key), "machine");
|
|
316
|
+
try { const stat = lstatSync(root); if (stat.isSymbolicLink() || !stat.isDirectory()) return "unreadable"; }
|
|
317
|
+
catch (error) { return (error as NodeJS.ErrnoException).code === "ENOENT" ? "absent" : "unreadable"; }
|
|
318
|
+
let handle: Dir;
|
|
319
|
+
try { handle = opendirSync(root); } catch { return "unreadable"; }
|
|
320
|
+
const names: string[] = [];
|
|
321
|
+
let seen = 0, unsafe = false, overflow = false;
|
|
322
|
+
try {
|
|
323
|
+
for (;;) {
|
|
324
|
+
if (seen > MACHINE_SCAN_LIMIT) { overflow = true; break; }
|
|
325
|
+
const entry = handle.readSync();
|
|
326
|
+
if (!entry) break;
|
|
327
|
+
seen++;
|
|
328
|
+
// Only a plain directory is a machine scope; a link or any other entry leaves the store unproved.
|
|
329
|
+
if (!entry.isDirectory()) { unsafe = true; continue; }
|
|
330
|
+
names.push(entry.name);
|
|
331
|
+
}
|
|
332
|
+
} catch { return "unreadable"; }
|
|
333
|
+
finally { try { handle.closeSync(); } catch { /* already closed */ } }
|
|
334
|
+
// Sorted, so "the scanned prefix" is a fact about the names rather than the filesystem's listing order.
|
|
335
|
+
let unreadable = unsafe;
|
|
336
|
+
for (const name of names.sort().slice(0, MACHINE_SCAN_LIMIT)) {
|
|
337
|
+
const state = ownedFileState(join(root, name, "capture.db"));
|
|
338
|
+
if (state === "present") return "present";
|
|
339
|
+
if (state === "unreadable") unreadable = true;
|
|
340
|
+
}
|
|
341
|
+
if (unreadable) return "unreadable";
|
|
342
|
+
return overflow ? "incomplete" : "absent";
|
|
343
|
+
}
|
|
344
|
+
|
|
213
345
|
/** Open one already-sealed shard without consulting the legacy home or the catalog. */
|
|
214
346
|
export function resolveShardProfile(memoryDir: string, opts: { project?: string; user?: boolean }, origin?: "cwd binding" | "remote" | "local binding"): BoundProfile {
|
|
215
347
|
if (opts.user === true && opts.project !== undefined || opts.user !== true && !opts.project) throw new Error("choose exactly one project or the user shard");
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { facts, label, PLAIN, type Style } from "./style.ts";
|
|
1
|
+
import { facts, label, markerCell, paint, section, PLAIN, type Style } from "./style.ts";
|
|
2
2
|
|
|
3
3
|
/** The `amem status` object as the CLI builds it; `amem status --json` prints it unchanged. */
|
|
4
4
|
export interface StatusView {
|
|
@@ -32,15 +32,15 @@ export function statusText(status: StatusView, s: Style = PLAIN): string {
|
|
|
32
32
|
const { machine, repo, denyPaths, piiPatterns, ...limits } = status.config;
|
|
33
33
|
const pendingCounts = facts(Object.fromEntries(Object.entries(status.pending).filter(([key]) => !key.endsWith("Ids"))));
|
|
34
34
|
const lines = [
|
|
35
|
-
`${
|
|
36
|
-
`
|
|
37
|
-
"",
|
|
35
|
+
`${paint("header", " amem Status", s.color)}: ${overall === "ok" ? s.ok(overall) : overall === "attention" ? s.attention(overall) : s.error(overall)}`,
|
|
36
|
+
...(warnings.length || actions.length ? ["", section(s, "Attention"), ...warnings.map(warning => ` ${s.attention(markerCell("warn", s.ascii))} ${warning}`), ...actions.map(action => ` ${paint("accent", markerCell("next", s.ascii), s.color)} ${action}`)] : []),
|
|
37
|
+
"", section(s, "Memory"),
|
|
38
|
+
` home: ${status.home.path} ${s.dim(`(${status.home.source})`)}`,
|
|
38
39
|
`${label(s, "ok")} policy: machine ${machine ?? "none (defaults)"}, repo ${repo ?? "none"}; ${denyPaths} deny paths, ${piiPatterns} PII patterns${facts(limits) ? `; ${facts(limits)}` : ""}`,
|
|
39
40
|
`${label(s, candidateState)} candidates: ${candidateLine}`,
|
|
40
41
|
`${label(s, migrationState)} layout: ${status.active ? `shards active${status.generation ? ` (generation ${status.generation.slice(0, 8)})` : ""}` : status.phase ? `shard migration ${status.phase}${interrupted ? ", not active" : ""}` : "single home"}; ${pendingCounts ? `pending ${pendingCounts}` : "no pending old-layout appends"}`,
|
|
41
42
|
...(status.deadLeasesRemoved?.length ? [` ${s.dim(`${status.deadLeasesRemoved.length} dead reader leases removed`)}`] : []),
|
|
42
|
-
|
|
43
|
-
"", actions.length ? "Next actions:" : "Next actions: none", ...actions.map(action => ` - ${action}`),
|
|
43
|
+
"", actions.length ? "Next actions: see Attention" : "Next actions: none",
|
|
44
44
|
s.dim("Full report: amem status --json; health checks: amem doctor"),
|
|
45
45
|
];
|
|
46
46
|
return lines.join("\n");
|
package/src/memory/store.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { RECAP_SCRATCH } from "./recap-scratch.ts";
|
|
1
2
|
import { buildCuratedBriefCache, buildPreferenceBriefCache } from "../brief-curated.ts";
|
|
2
3
|
import { PREFERENCE_SLOT } from "./preference-brief.ts";
|
|
3
4
|
import { curatedProfileBinding, invalidateCuratedCaches } from "./curated-cache-state.ts";
|
|
@@ -250,8 +251,10 @@ export class MemoryStore {
|
|
|
250
251
|
private readonly reconcile?: { canonical: string; aliases: readonly string[] };
|
|
251
252
|
/** A full rebuild refills FTS in one resync instead of one derived transaction per entry. */
|
|
252
253
|
private rebuildingSearch = false;
|
|
254
|
+
private readonly recapScratch: boolean;
|
|
253
255
|
|
|
254
256
|
constructor(opts: StoreOptions = {}, bootstrap?: BootstrapBinding) {
|
|
257
|
+
this.recapScratch = (opts as StoreOptions & { [RECAP_SCRATCH]?: true })[RECAP_SCRATCH] === true;
|
|
255
258
|
if (bootstrap && bootstrap.token !== MIGRATION_BOOTSTRAP) throw new Error("invalid migration bootstrap");
|
|
256
259
|
this.bootstrapOnly = bootstrap ? bootstrap.authoring !== true : false;
|
|
257
260
|
this.userOverlay = bootstrap?.userOverlay;
|
|
@@ -309,7 +312,7 @@ export class MemoryStore {
|
|
|
309
312
|
this.db = db;
|
|
310
313
|
this.mutationDb = openedMutation = mutationDatabase(this.dir);
|
|
311
314
|
// One derived FTS copy per profile: a generation handle and a shared-v1 handle on one home never resync-fight.
|
|
312
|
-
this.searchIndex = openedSearch = new SearchIndex(this.profile.sharded ? join(this.dir, "search.db") : join(home, this.profile.kind === "generation" ? `search-${this.profile.generation}.db` : "search.db"));
|
|
315
|
+
this.searchIndex = openedSearch = new SearchIndex(this.recapScratch ? ":memory:" : this.profile.sharded ? join(this.dir, "search.db") : join(home, this.profile.kind === "generation" ? `search-${this.profile.generation}.db` : "search.db"));
|
|
313
316
|
this.memoryBaseDir = home;
|
|
314
317
|
try { chmodSync(indexFile, 0o600); } catch { /* best effort */ }
|
|
315
318
|
if (this.profile.kind === "generation") this.generationIndex = new GenerationIndex({ profile: this.profile, db, now: this.now,
|
|
@@ -1054,7 +1057,7 @@ export class MemoryStore {
|
|
|
1054
1057
|
// The FTS copy follows the committed row. `changes` is only a hint here (bun:sqlite misreports it for ignored
|
|
1055
1058
|
// inserts inside a transaction): addCurated is idempotent by entry id, and a missed hint becomes a count drift
|
|
1056
1059
|
// the next search resyncs.
|
|
1057
|
-
if (inserted && !this.rebuildingSearch) this.searchIndex.addCurated({ id, at: e.at, project: e.project, tier: e.tier === "long" ? "long" : "short", scope: e.scope === "shared" ? "shared" : "project", body: `${e.title ?? ""}\n${e.text}\n${e.about.map(String).join(" ")}` });
|
|
1060
|
+
if (inserted && !this.rebuildingSearch && !this.recapScratch) this.searchIndex.addCurated({ id, at: e.at, project: e.project, tier: e.tier === "long" ? "long" : "short", scope: e.scope === "shared" ? "shared" : "project", body: `${e.title ?? ""}\n${e.text}\n${e.about.map(String).join(" ")}` });
|
|
1058
1061
|
for (const node of e.about) this.db.query("INSERT OR IGNORE INTO edges (src, dst) VALUES (?, ?)").run(id, String(node));
|
|
1059
1062
|
} else if (e.op === "goal") {
|
|
1060
1063
|
if (!str(e.title, 400) || !Array.isArray(e.milestones) || !Array.isArray(e.dependsOn) || !str(e.project, 400) || !opt(e.actor) || !opt(e.scope)) { this.log(`memory segment ${segment}: a malformed entry was skipped`); return; }
|
|
@@ -1295,6 +1298,7 @@ export class MemoryStore {
|
|
|
1295
1298
|
|
|
1296
1299
|
/** Entries visible from `project` (its own, and `shared` ones of any project), newest first, filtered. */
|
|
1297
1300
|
list(f: Filter = {}): View[] {
|
|
1301
|
+
if (this.recapScratch && f.q !== undefined) throw new Error("search unavailable for a Recap scratch store; open a normal store to search");
|
|
1298
1302
|
const q = f.q?.toLowerCase().split(/\s+/).filter(Boolean) ?? [];
|
|
1299
1303
|
return this.live(f).filter((v) => (!f.project || this.inScope(v.project, f.project) || v.scope === "shared") && (!f.tier || v.tier === f.tier) && (!f.kind || v.kind === f.kind)
|
|
1300
1304
|
&& (!f.peer || v.peer === f.peer) && (!f.machine || v.machine === f.machine) && (!f.since || Date.parse(v.at) >= Date.parse(f.since)) && (f.includeSuperseded || !v.supersededBy)
|
|
@@ -1352,6 +1356,7 @@ export class MemoryStore {
|
|
|
1352
1356
|
|
|
1353
1357
|
/** Exact-project body pages for policy-aware callers. Relations still fold over complete metadata. */
|
|
1354
1358
|
readPage(window: ReadWindow & { query?: string; includeSuperseded?: boolean }): { rows: View[]; next?: ReadRef } {
|
|
1359
|
+
if (this.recapScratch && window.query !== undefined) throw new Error("search unavailable for a Recap scratch store; open a normal store to search");
|
|
1355
1360
|
this.ensureFresh(); this.prune();
|
|
1356
1361
|
const refs: ReadRef[] = [];
|
|
1357
1362
|
for (const store of this.readStores()) {
|
|
@@ -1378,6 +1383,7 @@ export class MemoryStore {
|
|
|
1378
1383
|
* R3 cost of the fallback is the pre-#13 behavior: same scan, same memory).
|
|
1379
1384
|
*/
|
|
1380
1385
|
search(q: string, f: SearchFilter = {}): SearchResult {
|
|
1386
|
+
if (this.recapScratch) throw new Error("search unavailable for a Recap scratch store; open a normal store to search");
|
|
1381
1387
|
const limit = f.limit ?? 200;
|
|
1382
1388
|
if (!this.searchIndex.available) {
|
|
1383
1389
|
const listed = this.list({ ...f, q, limit: f.groupTasks === false ? f.limit : Number.MAX_SAFE_INTEGER });
|
|
@@ -1473,6 +1479,7 @@ export class MemoryStore {
|
|
|
1473
1479
|
|
|
1474
1480
|
/** Bring the derived FTS copy level with the curated rows when a prune, a crash, a lock or a rebuild drifted them apart. */
|
|
1475
1481
|
private syncSearchIndex(): void {
|
|
1482
|
+
if (this.recapScratch) return; // This disposable store never exposes its unpopulated search index.
|
|
1476
1483
|
if (!this.searchIndex.available) return;
|
|
1477
1484
|
const curated = (this.db.query("SELECT COUNT(*) AS n FROM entries").get() as { n: number }).n;
|
|
1478
1485
|
if (!this.searchIndex.needsResync(curated)) return;
|
package/src/memory/style.ts
CHANGED
|
@@ -5,6 +5,7 @@
|
|
|
5
5
|
*/
|
|
6
6
|
export interface Style {
|
|
7
7
|
readonly color: boolean;
|
|
8
|
+
readonly ascii: boolean;
|
|
8
9
|
ok(text: string): string;
|
|
9
10
|
attention(text: string): string;
|
|
10
11
|
error(text: string): string;
|
|
@@ -12,14 +13,89 @@ export interface Style {
|
|
|
12
13
|
bold(text: string): string;
|
|
13
14
|
}
|
|
14
15
|
|
|
15
|
-
/**
|
|
16
|
+
/** Portable CLI output standard v1 vocabulary. */
|
|
17
|
+
export type Role = "header" | "section" | "key" | "value" | "success" | "warning" | "error" | "hint" | "accent";
|
|
18
|
+
const ESC = String.fromCharCode(27);
|
|
19
|
+
export const SGR_RESET = `${ESC}[0m`;
|
|
20
|
+
export const ROLE_SGR: Readonly<Record<Role, string>> = Object.freeze({
|
|
21
|
+
header: `${ESC}[1;34m`, section: `${ESC}[1;35m`, key: `${ESC}[34m`, value: "",
|
|
22
|
+
success: `${ESC}[1;32m`, warning: `${ESC}[1;33m`, error: `${ESC}[1;31m`,
|
|
23
|
+
hint: `${ESC}[90m`, accent: `${ESC}[36m`,
|
|
24
|
+
});
|
|
25
|
+
export const MARKER_NAMES = ["ok", "fail", "warn", "absent", "unknown", "pending", "active", "next"] as const;
|
|
26
|
+
export type MarkerName = (typeof MARKER_NAMES)[number];
|
|
27
|
+
export const MARKERS: Readonly<Record<MarkerName, { glyph: string; ascii: string; role: Role }>> = Object.freeze({
|
|
28
|
+
ok: { glyph: "✓", ascii: "ok", role: "success" }, fail: { glyph: "✗", ascii: "x", role: "error" },
|
|
29
|
+
warn: { glyph: "⚠", ascii: "!", role: "warning" }, absent: { glyph: "-", ascii: "-", role: "hint" },
|
|
30
|
+
unknown: { glyph: "?", ascii: "?", role: "hint" }, pending: { glyph: "~", ascii: "~", role: "hint" },
|
|
31
|
+
active: { glyph: "*", ascii: "*", role: "success" }, next: { glyph: "→", ascii: "->", role: "accent" },
|
|
32
|
+
});
|
|
33
|
+
export const SECTION_MARKER = { glyph: "▸", ascii: ">" } as const;
|
|
34
|
+
export const MARKER_COLUMN = 2;
|
|
35
|
+
export const cellWidth = (text: string): number => Bun.stringWidth(text, { ambiguousIsNarrow: true });
|
|
36
|
+
export function markerCell(name: MarkerName, ascii: boolean): string {
|
|
37
|
+
const text = ascii ? MARKERS[name].ascii : MARKERS[name].glyph;
|
|
38
|
+
return text + " ".repeat(Math.max(0, MARKER_COLUMN - cellWidth(text)));
|
|
39
|
+
}
|
|
40
|
+
export interface ColorEnv { isTTY: boolean; TERM?: string; NO_COLOR?: string; FORCE_COLOR?: string; CLICOLOR?: string; CLICOLOR_FORCE?: string }
|
|
41
|
+
export function streamEnv(isTTY: boolean, env: Readonly<Record<string, string | undefined>> = process.env): ColorEnv {
|
|
42
|
+
return { isTTY, TERM: env.TERM, NO_COLOR: env.NO_COLOR, FORCE_COLOR: env.FORCE_COLOR, CLICOLOR: env.CLICOLOR, CLICOLOR_FORCE: env.CLICOLOR_FORCE };
|
|
43
|
+
}
|
|
44
|
+
export function resolveColor(flag: string | undefined, env: ColorEnv): boolean | Error {
|
|
45
|
+
if (flag === "always") return true;
|
|
46
|
+
if (flag === "never") return false;
|
|
47
|
+
if (flag !== undefined && flag !== "auto") return new Error("usage: amem <command> [--color=auto|always|never]");
|
|
48
|
+
if (env.NO_COLOR) return false;
|
|
49
|
+
if ((env.FORCE_COLOR && env.FORCE_COLOR !== "0") || (env.CLICOLOR_FORCE && env.CLICOLOR_FORCE !== "0")) return true;
|
|
50
|
+
if (env.FORCE_COLOR === "0" || env.CLICOLOR === "0") return false;
|
|
51
|
+
return env.isTTY && env.TERM !== "dumb";
|
|
52
|
+
}
|
|
53
|
+
export function asciiMarkers(env: Readonly<Record<string, string | undefined>> = process.env, flag = false): boolean {
|
|
54
|
+
return flag || !/utf-?8/i.test(env.LC_ALL || env.LC_CTYPE || env.LANG || "");
|
|
55
|
+
}
|
|
56
|
+
export function paint(role: Role, text: string, color: boolean): string {
|
|
57
|
+
return color && ROLE_SGR[role] ? `${ROLE_SGR[role]}${text}${SGR_RESET}` : text;
|
|
58
|
+
}
|
|
59
|
+
export function section(s: Style, name: string): string {
|
|
60
|
+
return paint("section", `${s.ascii ? SECTION_MARKER.ascii : SECTION_MARKER.glyph} ${name}`, s.color);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** Wrap report prose at a stream's requested width; a pipe without COLUMNS remains unwrapped. */
|
|
64
|
+
export function wrapReport(text: string, width: number | undefined): string {
|
|
65
|
+
if (!Number.isSafeInteger(width) || width === undefined || width < 20) return text;
|
|
66
|
+
const ansi = new RegExp(`${ESC}\\[[0-9;]*m`, "g");
|
|
67
|
+
const measure = (value: string) => cellWidth(value.replace(ansi, ""));
|
|
68
|
+
return text.split("\n").flatMap(line => {
|
|
69
|
+
if (measure(line) <= width) return [line];
|
|
70
|
+
const indent = line.match(/^ */)?.[0] ?? "", continuation = " ";
|
|
71
|
+
const words = line.slice(indent.length).match(/\S+|\s+/g) ?? [];
|
|
72
|
+
const result: string[] = [];
|
|
73
|
+
let row = indent;
|
|
74
|
+
let spacing = "";
|
|
75
|
+
for (const word of words) {
|
|
76
|
+
if (/^\s+$/.test(word)) { spacing = word; continue; }
|
|
77
|
+
if (measure(row + spacing + word) > width && row.trim()) { result.push(row); row = continuation; spacing = ""; }
|
|
78
|
+
if (measure(row + spacing + word) <= width) { row += spacing + word; spacing = ""; continue; }
|
|
79
|
+
row += spacing; spacing = "";
|
|
80
|
+
// Long unbroken values are continued without truncation; --json retains their exact bytes.
|
|
81
|
+
for (const part of word.match(new RegExp(`${ESC}\\[[0-9;]*m|.`, "gu")) ?? []) {
|
|
82
|
+
if (measure(row + part) > width) { result.push(row); row = continuation; }
|
|
83
|
+
row += part;
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
if (row.trim()) result.push(row);
|
|
87
|
+
return result;
|
|
88
|
+
}).join("\n");
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** Default color decision for one stream, following the shared precedence table. */
|
|
16
92
|
export function colorEnabled(env: Readonly<Record<string, string | undefined>>, isTTY: boolean | undefined): boolean {
|
|
17
|
-
return isTTY === true
|
|
93
|
+
return resolveColor("auto", streamEnv(isTTY === true, env)) === true;
|
|
18
94
|
}
|
|
19
95
|
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
96
|
+
export function style(color: boolean, ascii = true): Style {
|
|
97
|
+
return { color, ascii, ok: text => paint("success", text, color), attention: text => paint("warning", text, color),
|
|
98
|
+
error: text => paint("error", text, color), dim: text => paint("hint", text, color), bold: text => paint("value", text, color) };
|
|
23
99
|
}
|
|
24
100
|
export const PLAIN: Style = style(false);
|
|
25
101
|
|
|
@@ -29,7 +105,9 @@ export const singleLine = (text: string): string => text.replace(/[\p{Cc}\p{Cf}\
|
|
|
29
105
|
/** Status label, padded so the columns line up; the word is always present. */
|
|
30
106
|
export function label(s: Style, state: "ok" | "attention" | "skipped" | "unavailable" | "error"): string {
|
|
31
107
|
const word = { ok: "OK", attention: "ATTENTION", skipped: "SKIPPED", unavailable: "UNAVAILABLE", error: "ERROR" }[state].padEnd(11);
|
|
32
|
-
|
|
108
|
+
const marker: MarkerName = state === "ok" ? "ok" : state === "attention" ? "warn" : state === "skipped" ? "absent" : state === "unavailable" ? "unknown" : "fail";
|
|
109
|
+
const text = `${markerCell(marker, s.ascii)} ${word}`;
|
|
110
|
+
return ` ${paint(MARKERS[marker].role, text, s.color)}`;
|
|
33
111
|
}
|
|
34
112
|
|
|
35
113
|
/** "key value" pairs, leaving out zero, empty and null values; returns "" when nothing material is left. */
|