@staix/vault-mem 0.3.3 → 0.5.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/CHANGELOG.md +56 -0
- package/README.md +45 -20
- package/bin/vmem.js +9 -3
- package/package.json +2 -2
- package/src/analysis-commands.ts +22 -13
- package/src/analysis-input.ts +2 -2
- package/src/analysis-types.ts +2 -0
- package/src/cli-output.ts +140 -0
- package/src/cli.ts +91 -45
- package/src/commands-table.ts +85 -43
- package/src/config.ts +22 -3
- package/src/links.ts +2 -0
- package/src/log-commands.ts +10 -5
- package/src/log-format.ts +3 -0
- package/src/log-types.ts +5 -1
- package/src/mcp-spec.ts +10 -4
- package/src/mcp-vault.ts +27 -15
- package/src/org-commands.ts +5 -3
- package/src/org-promote.ts +3 -0
- package/src/promote-command.ts +6 -4
- package/src/read-commands.ts +12 -2
- package/src/read-output.ts +99 -0
- package/src/registry.ts +3 -2
- package/src/setup.ts +58 -12
- package/src/skills-mine.ts +3 -2
- package/src/spec-git.ts +7 -4
- package/src/spec-output.ts +119 -0
- package/src/sync.ts +62 -18
- package/src/text-output.ts +120 -0
- package/src/ui/panel.css +1 -5
- package/src/ui/panel.js +60 -70
- package/src/ui/plugin.ts +33 -2
- package/src/vault-files.ts +74 -0
- package/src/vault-graph.ts +21 -2
- package/src/vault-index.ts +121 -19
- package/src/vault-lint.ts +8 -2
- package/src/vault-log.ts +109 -1
- package/src/vault-stats.ts +50 -0
- package/src/workspace-graph.ts +9 -1
- package/src/write-commands.ts +32 -9
- package/src/write-operations.ts +48 -8
- package/src/write-output.ts +151 -0
- package/src/write-types.ts +3 -1
- package/src/write-validation.ts +30 -8
- package/src/writer.ts +19 -7
package/src/setup.ts
CHANGED
|
@@ -76,24 +76,58 @@ const record = (value: unknown, label: string): Record<string, unknown> => {
|
|
|
76
76
|
};
|
|
77
77
|
|
|
78
78
|
// TOML: edit only the `[mcp_servers.vmem]` table (and its subtables) textually so unrelated bytes stay identical.
|
|
79
|
-
|
|
79
|
+
/**
|
|
80
|
+
* The key of a `[table]` or `[[array]]` header line, or undefined for any other line. Quote-aware like `tomlKey`:
|
|
81
|
+
* a `]` inside a "basic" or 'literal' quoted part does not end the header; a trailing `# comment` is allowed.
|
|
82
|
+
*/
|
|
83
|
+
function tomlHeaderName(line: string): string | undefined {
|
|
84
|
+
const m = /^\s*(\[\[?)/.exec(line);
|
|
85
|
+
if (!m) return undefined;
|
|
86
|
+
const close = m[1] === "[[" ? "]]" : "]";
|
|
87
|
+
let i = m[0].length, quote: '"' | "'" | undefined;
|
|
88
|
+
for (; i < line.length; i++) {
|
|
89
|
+
const c = line[i]!;
|
|
90
|
+
if (quote) { if (c === "\\" && quote === '"') i++; else if (c === quote) quote = undefined; continue; }
|
|
91
|
+
if (c === '"' || c === "'") { quote = c; continue; }
|
|
92
|
+
if (c === "]") break;
|
|
93
|
+
}
|
|
94
|
+
if (quote || !line.startsWith(close, i)) return undefined;
|
|
95
|
+
const name = line.slice(m[0].length, i).trim();
|
|
96
|
+
return name && /^\s*(?:#.*)?$/.test(line.slice(i + close.length)) ? name : undefined;
|
|
97
|
+
}
|
|
98
|
+
/** A dotted TOML key as its parts: bare, "basic" or 'literal', with spaces around dots; undefined when malformed. */
|
|
99
|
+
function tomlKey(name: string): string[] | undefined {
|
|
100
|
+
const part = /\s*(?:([A-Za-z0-9_-]+)|"((?:[^"\\]|\\.)*)"|'([^']*)')\s*(?:\.|$)/y, parts: string[] = [];
|
|
101
|
+
while (part.lastIndex < name.length) {
|
|
102
|
+
const m = part.exec(name);
|
|
103
|
+
if (!m) return undefined;
|
|
104
|
+
try { parts.push(m[1] ?? m[3] ?? tomlUnescape(m[2]!)); } catch { return undefined; }
|
|
105
|
+
}
|
|
106
|
+
return parts;
|
|
107
|
+
}
|
|
108
|
+
const TOML_ESCAPES: Record<string, string> = { b: "\b", t: "\t", n: "\n", f: "\f", r: "\r", e: "\x1b", '"': '"', "\\": "\\" };
|
|
109
|
+
/** A TOML basic-string body decoded: `\uXXXX`, `\UXXXXXXXX`, `\xHH` and the short escapes; any other escape throws. */
|
|
110
|
+
function tomlUnescape(body: string): string {
|
|
111
|
+
return body.replace(/\\(?:u([0-9A-Fa-f]{4})|U([0-9A-Fa-f]{8})|x([0-9A-Fa-f]{2})|(.))/g, (_, u, U, x, c) => {
|
|
112
|
+
if (u ?? U ?? x) return String.fromCodePoint(parseInt(u ?? U ?? x, 16));
|
|
113
|
+
if (c in TOML_ESCAPES) return TOML_ESCAPES[c]!;
|
|
114
|
+
throw new Error("invalid TOML escape");
|
|
115
|
+
});
|
|
116
|
+
}
|
|
80
117
|
/** Every table owned by the entry (`[mcp_servers.vmem]` and any `[mcp_servers.vmem.*]`), wherever it appears. */
|
|
81
118
|
function tomlSpans(lines: string[]): [number, number][] {
|
|
82
|
-
const own = (name: string) => {
|
|
83
|
-
const key = name.replace(/\s*\.\s*/g, ".").replace(/"vmem"/g, SERVER_NAME);
|
|
84
|
-
return key === `mcp_servers.${SERVER_NAME}` || key.startsWith(`mcp_servers.${SERVER_NAME}.`);
|
|
85
|
-
};
|
|
119
|
+
const own = (name: string) => { const key = tomlKey(name); return key?.[0] === "mcp_servers" && key[1] === SERVER_NAME; };
|
|
86
120
|
const spans: [number, number][] = [];
|
|
87
121
|
let start = -1;
|
|
88
122
|
for (let i = 0; i <= lines.length; i++) {
|
|
89
|
-
const header = i < lines.length ?
|
|
90
|
-
if (i < lines.length &&
|
|
123
|
+
const header = i < lines.length ? tomlHeaderName(lines[i]!) : undefined;
|
|
124
|
+
if (i < lines.length && header === undefined) continue;
|
|
91
125
|
if (start >= 0) {
|
|
92
126
|
let stop = i;
|
|
93
127
|
while (stop > start && lines[stop - 1]!.trim() === "") stop--;
|
|
94
128
|
spans.push([start, stop]); start = -1;
|
|
95
129
|
}
|
|
96
|
-
if (header && own(header
|
|
130
|
+
if (header !== undefined && own(header)) start = i;
|
|
97
131
|
}
|
|
98
132
|
return spans;
|
|
99
133
|
}
|
|
@@ -114,7 +148,7 @@ function tomlBlock(text: string | null): string[] | undefined {
|
|
|
114
148
|
return spans.length ? spans.flatMap(([start, stop]) => lines.slice(start, stop)) : undefined;
|
|
115
149
|
}
|
|
116
150
|
/** Replace the vmem entry. TOML takes either an entry value or the exact prior block lines to restore. */
|
|
117
|
-
function putEntry(host: HostFile, text: string | null, value: unknown, rawToml?: string[], keepKey = false): string | null {
|
|
151
|
+
function putEntry(host: HostFile, text: string | null, value: unknown, rawToml?: string[], keepKey = false, mode: "apply" | "undo" = "apply"): string | null {
|
|
118
152
|
if (host.format === "toml") {
|
|
119
153
|
const source = text ?? "", newline = source.includes("\r\n") ? "\r\n" : "\n";
|
|
120
154
|
const lines = source.length ? source.split(/\r?\n/) : [];
|
|
@@ -140,7 +174,18 @@ function putEntry(host: HostFile, text: string | null, value: unknown, rawToml?:
|
|
|
140
174
|
}
|
|
141
175
|
while (lines.length && lines[lines.length - 1] === "") lines.pop();
|
|
142
176
|
const out = lines.length ? lines.join(newline) + newline : "";
|
|
143
|
-
|
|
177
|
+
// Never publish a file the host cannot parse.
|
|
178
|
+
try { Bun.TOML.parse(out); }
|
|
179
|
+
catch (error) {
|
|
180
|
+
const reason = error instanceof Error ? error.message : "TOML parse error";
|
|
181
|
+
// A root `mcp_servers = { ... }` cannot take an appended [mcp_servers.vmem] table: there is no entry to rewrite.
|
|
182
|
+
// Only root lines count: those before the first table header. A dotted `mcp_servers.<x> = {` fails the same way.
|
|
183
|
+
const firstHeader = lines.findIndex(line => tomlHeaderName(line) !== undefined);
|
|
184
|
+
const root = firstHeader < 0 ? lines : lines.slice(0, firstHeader);
|
|
185
|
+
const inline = root.some(line => /^\s*(?:mcp_servers|"mcp_servers"|'mcp_servers')\s*(?:\.[^=]*)?=\s*\{/.test(line));
|
|
186
|
+
const fix = inline ? `convert the inline mcp_servers value to [mcp_servers.<name>] tables` : `rewrite the vmem entry by hand as a [mcp_servers.${SERVER_NAME}] table`;
|
|
187
|
+
throw new Error(`${host.file}: the updated file would not parse (${reason}); ${fix}, then ${mode === "undo" ? `rerun \`vmem setup ${host.target} --undo\`` : "rerun setup"}`);
|
|
188
|
+
}
|
|
144
189
|
return out;
|
|
145
190
|
}
|
|
146
191
|
const doc = text === null ? {} : record(JSON.parse(text), host.file);
|
|
@@ -224,7 +269,7 @@ export function runSetup(target: string, mode: SetupMode, options: { home: strin
|
|
|
224
269
|
if (current === undefined) { action.change = "none"; action.reason = "vmem entry already absent; nothing restored"; unlinkSync(receiptPath); continue; }
|
|
225
270
|
action.change = receipt.prior === undefined || receipt.prior === null ? "remove" : "restore";
|
|
226
271
|
{
|
|
227
|
-
let next = current === undefined ? text : putEntry(host, text, receipt.prior ?? undefined, receipt.priorToml, receipt.keyExisted === true);
|
|
272
|
+
let next = current === undefined ? text : putEntry(host, text, receipt.prior ?? undefined, receipt.priorToml, receipt.keyExisted === true, "undo");
|
|
228
273
|
// A file setup created is removed again only when nothing else was added to it.
|
|
229
274
|
if (!receipt.existed && next !== null && readEntry(host, next) === undefined && isDeepStrictEqual(host.format === "toml" ? Bun.TOML.parse(next) : JSON.parse(next), {})) next = null;
|
|
230
275
|
if (next !== text && (next !== null || text !== null)) atomicWrite(host.file, next);
|
|
@@ -234,8 +279,9 @@ export function runSetup(target: string, mode: SetupMode, options: { home: strin
|
|
|
234
279
|
}
|
|
235
280
|
if (isDeepStrictEqual(current, entry)) { action.change = "unchanged"; continue; }
|
|
236
281
|
action.change = current === undefined ? "add" : "replace";
|
|
282
|
+
// The dry run renders and parses the planned file too, so a refusal shows in the preview.
|
|
283
|
+
const next = putEntry(host, text, entry);
|
|
237
284
|
if (mode === "apply") {
|
|
238
|
-
const next = putEntry(host, text, entry);
|
|
239
285
|
// Keep the original prior value across repeated applies.
|
|
240
286
|
const prior: Receipt = receipt ?? { version: 1, target: name, file: host.file, existed: text !== null, keyExisted: hasKey(host, text), prior: current ?? null, ...(host.format === "toml" && current !== undefined ? { priorToml: tomlBlock(text) } : {}), installed: entry };
|
|
241
287
|
// The receipt is durable before the host file changes; a failed host write rolls the receipt back.
|
package/src/skills-mine.ts
CHANGED
|
@@ -8,6 +8,7 @@ import { parseFrontmatter } from "./frontmatter.ts";
|
|
|
8
8
|
import { canonicalPath, isDenied } from "./platform.ts";
|
|
9
9
|
import { codePointCompare as compare, labelCommunities } from "./vault-graph.ts";
|
|
10
10
|
import { SECRET_PATTERNS } from "./write-validation.ts";
|
|
11
|
+
import { PLAIN, stripTerminal, type TextOptions } from "./text-output.ts";
|
|
11
12
|
|
|
12
13
|
/**
|
|
13
14
|
* `vmem skills mine`: read-only skill-candidate mining over amem memory and vault notes, a port of the skill-mine
|
|
@@ -455,7 +456,7 @@ export async function mineSkills(home: string, options: MineOptions): Promise<Mi
|
|
|
455
456
|
const VALUES = ["--days", "--project", "--vocab", "--skills", "--min-size", "--min-novelty"];
|
|
456
457
|
const BOOLEANS = ["--all-projects", "--json"];
|
|
457
458
|
/** `vmem skills mine <vault> ...`. Prints the JSON result, or the markdown report without --json. */
|
|
458
|
-
export async function runSkillsCommand(args: string[], home: string, env: NodeJS.ProcessEnv): Promise<{ text: string; code: number }> {
|
|
459
|
+
export async function runSkillsCommand(args: string[], home: string, env: NodeJS.ProcessEnv, text: TextOptions = PLAIN): Promise<{ text: string; code: number }> {
|
|
459
460
|
if (args[0] !== "mine") throw new Error("skills: use `vmem skills mine <vault>`");
|
|
460
461
|
const flags: Record<string, string | boolean> = {}, skills: string[] = [], positional: string[] = [];
|
|
461
462
|
for (let i = 1; i < args.length; i++) {
|
|
@@ -483,5 +484,5 @@ export async function runSkillsCommand(args: string[], home: string, env: NodeJS
|
|
|
483
484
|
...(number("--min-size") !== undefined ? { minSize: number("--min-size") } : {}),
|
|
484
485
|
...(number("--min-novelty") !== undefined ? { minNovelty: number("--min-novelty") } : {}),
|
|
485
486
|
});
|
|
486
|
-
return { text: flags["--json"] ? JSON.stringify(result) : result.report.trimEnd(), code: 0 };
|
|
487
|
+
return { text: flags["--json"] ? JSON.stringify(result) : stripTerminal(result.report).trimEnd(), code: 0 };
|
|
487
488
|
}
|
package/src/spec-git.ts
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import { spawnSync } from "node:child_process";
|
|
2
2
|
import { memoryGitArgv, memoryGitEnv } from "./platform.ts";
|
|
3
3
|
|
|
4
|
+
const SPEC_GIT_TIMEOUT_MS = 10000;
|
|
5
|
+
|
|
4
6
|
export interface SpecGitOptions {
|
|
5
7
|
env?: NodeJS.ProcessEnv;
|
|
6
8
|
maxBuffer?: number;
|
|
@@ -13,10 +15,10 @@ export function specGit(root: string, args: string[], options: SpecGitOptions =
|
|
|
13
15
|
const argv = memoryGitArgv(["-C", root, ...args]), maxBuffer = options.maxBuffer ?? 65536;
|
|
14
16
|
const env = memoryGitEnv({ ...(options.env ?? process.env), GIT_OPTIONAL_LOCKS: "0", LC_ALL: "C" }, { repositoryIsolation: true });
|
|
15
17
|
for (const key of ["GIT_LITERAL_PATHSPECS", "GIT_GLOB_PATHSPECS", "GIT_NOGLOB_PATHSPECS", "GIT_ICASE_PATHSPECS"]) delete env[key];
|
|
16
|
-
const result = spawnSync(argv[0]!, argv.slice(1), { env, timeout:
|
|
18
|
+
const result = spawnSync(argv[0]!, argv.slice(1), { env, timeout: SPEC_GIT_TIMEOUT_MS, maxBuffer, stdio: ["ignore", "pipe", "pipe"] });
|
|
17
19
|
if (result.error) {
|
|
18
20
|
const code = (result.error as NodeJS.ErrnoException).code;
|
|
19
|
-
if (code === "ETIMEDOUT") throw new Error(
|
|
21
|
+
if (code === "ETIMEDOUT") throw new Error(`spec source: git inspection timed out after ${SPEC_GIT_TIMEOUT_MS} ms${result.signal ? ` (signal ${result.signal})` : ""}; retry and check for a locked repository or slow mount`, { cause: result.error });
|
|
20
22
|
if (code === "ENOBUFS") {
|
|
21
23
|
const advice = options.discovery ? "ignore large or vendored Markdown via .gitignore and untrack already-tracked excluded files with git rm --cached before retrying" : "make SPEC.md paths more specific, or inspect the failed Git command if its output is unexpected, before retrying";
|
|
22
24
|
throw new Error(`spec source: git output exceeded ${maxBuffer} bytes; ${advice}`, { cause: result.error });
|
|
@@ -25,9 +27,10 @@ export function specGit(root: string, args: string[], options: SpecGitOptions =
|
|
|
25
27
|
throw new Error(`spec source: git could not run (${code ?? "spawn failure"}); install git or fix PATH before retrying`, { cause: result.error });
|
|
26
28
|
}
|
|
27
29
|
const status = result.status;
|
|
28
|
-
if (status === null
|
|
30
|
+
if (status === null) throw new Error(`spec source: git inspection timed out or was interrupted (signal ${result.signal ?? "unavailable"}; inspection timeout ${SPEC_GIT_TIMEOUT_MS} ms, parent/test timeout may be shorter); inspect git -C <path> rev-parse --show-toplevel and repair the repository or ownership configuration`);
|
|
31
|
+
if (!(options.allowedExitCodes ?? [0]).includes(status)) {
|
|
29
32
|
const first = result.stderr.toString("utf8").split(/\r?\n/, 1)[0]?.split(root).join("<path>").slice(0, 240) || "no diagnostic";
|
|
30
|
-
throw new Error(`spec source: git refused inspection (exit ${status
|
|
33
|
+
throw new Error(`spec source: git refused inspection (exit ${status}): ${first}; inspect git -C <path> rev-parse --show-toplevel and repair the repository or ownership configuration`);
|
|
31
34
|
}
|
|
32
35
|
return { status, stdout: result.stdout, stderr: result.stderr };
|
|
33
36
|
}
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Text renderers for `vmem spec get|graph|grep|validate` (#114). Each one reads the same result object `--json` prints
|
|
3
|
+
* and never adds content to it; data goes through `clean()` in tables and fields, and bodies keep their lines with
|
|
4
|
+
* terminal escape sequences stripped.
|
|
5
|
+
*/
|
|
6
|
+
import type { SpecCommand } from "./spec-command-table.ts";
|
|
7
|
+
import type { SpecEdge, SpecNode } from "./spec-graph.ts";
|
|
8
|
+
import type { SpecFreshnessEntry } from "./spec-freshness.ts";
|
|
9
|
+
import type { SpecValidationIssue, SpecValidationReport } from "./spec-validate.ts";
|
|
10
|
+
import type { SpecDiagnostic } from "./spec-source.ts";
|
|
11
|
+
import { blocks, fields, heading, issueTable, nextCommand, paint, paragraph, plural, shellWord, table, tone, type CellInput, type TextOptions, stripTerminal } from "./text-output.ts";
|
|
12
|
+
|
|
13
|
+
/** What the renderers need from the command line: the spec arguments (`get root --body`) and their parsed values. */
|
|
14
|
+
export interface SpecTextContext { args: readonly string[]; values: Record<string, unknown>; repo?: string }
|
|
15
|
+
export interface SpecGetResult {
|
|
16
|
+
source: string; worktree: string; id: string; path: string; sha256: string; frontmatter: Record<string, unknown>;
|
|
17
|
+
links: SpecEdge[]; backlinks: SpecEdge[]; children: SpecNode[]; freshness: SpecFreshnessEntry | null; freshnessIssues: SpecValidationIssue[];
|
|
18
|
+
truncated: boolean; totals: { links: number; backlinks: number; children: number };
|
|
19
|
+
body?: string; bodyTruncated?: boolean; nextOffset?: number; headings?: string[]; headingsTruncated?: boolean; section?: string; offset?: number;
|
|
20
|
+
}
|
|
21
|
+
export interface SpecGraphResult { source: string; worktree: string; nodes: SpecNode[]; edges: SpecEdge[]; truncated: boolean }
|
|
22
|
+
export interface SpecGrepHit { id: string; path: string; title: string; type: string; status?: string; snippet: string; score?: number }
|
|
23
|
+
export interface SpecGrepResult { source: string; worktree: string; hits: SpecGrepHit[]; offset: number; truncated: boolean; nextOffset?: number }
|
|
24
|
+
export type SpecValidateResult = SpecValidationReport & { source?: string; worktree?: string };
|
|
25
|
+
|
|
26
|
+
const value = (data: unknown): string => typeof data === "string" ? data : Array.isArray(data) ? data.map(value).join(", ") : data === undefined || data === null ? "" : JSON.stringify(data);
|
|
27
|
+
const statusTone = (status: string | undefined): CellInput => status === "active" ? tone(status, "ok") : status === "deprecated" ? tone(status, "warn") : status ?? "-";
|
|
28
|
+
const counted = (shown: number, total: number) => shown < total ? ` (${shown} of ${total})` : "";
|
|
29
|
+
/** The same command with `--offset` set, inserted before a `--` separator so it stays an option. */
|
|
30
|
+
export function offsetCommand(args: readonly string[], offset: number): string {
|
|
31
|
+
const end = args.includes("--") ? args.indexOf("--") : args.length;
|
|
32
|
+
const head = args.slice(0, end).filter((arg, i, all) => arg !== "--offset" && all[i - 1] !== "--offset");
|
|
33
|
+
return ["vmem", "spec", ...head, "--offset", String(offset), ...args.slice(end)].map(shellWord).join(" ");
|
|
34
|
+
}
|
|
35
|
+
function freshnessText(entry: SpecFreshnessEntry | null): CellInput {
|
|
36
|
+
if (!entry) return undefined;
|
|
37
|
+
if (entry.state === "fresh") return tone(entry.dirty ? "fresh, uncommitted changes" : "fresh", entry.dirty ? "warn" : "ok");
|
|
38
|
+
return tone(`stale: ${staleText(entry)}`, "warn");
|
|
39
|
+
}
|
|
40
|
+
const staleText = (entry: SpecFreshnessEntry) => [entry.commits > 0 && `${plural(entry.commits, "commit")} since verified-against`, entry.dirty && "uncommitted changes"].filter(Boolean).join(", ") || "source scope changed";
|
|
41
|
+
|
|
42
|
+
export function renderSpecGet(r: SpecGetResult, o: TextOptions, context: SpecTextContext): string {
|
|
43
|
+
const data = r.frontmatter, title = typeof data.title === "string" ? data.title : "";
|
|
44
|
+
const info = fields([
|
|
45
|
+
["type", value(data.type)], ["status", typeof data.status === "string" ? statusTone(data.status) : value(data.status)],
|
|
46
|
+
["parent", value(data.parent)], ["depends-on", value(data["depends-on"])], ["covers", value(data.covers)], ["paths", value(data.paths)],
|
|
47
|
+
["path", r.path], ["source", r.source], ["freshness", freshnessText(r.freshness)],
|
|
48
|
+
["links", r.links.map(edge => `${edge.kind} ${edge.target}`).join(", ") + counted(r.links.length, r.totals.links)],
|
|
49
|
+
["backlinks", r.backlinks.map(edge => `${edge.kind} ${edge.source}`).join(", ") + counted(r.backlinks.length, r.totals.backlinks)],
|
|
50
|
+
["children", r.children.map(node => node.id).join(", ") + counted(r.children.length, r.totals.children)],
|
|
51
|
+
["section", r.section], ["offset", r.offset],
|
|
52
|
+
["sections", r.headings?.length ? r.headings.join(", ") + (r.headingsTruncated ? ", ..." : "") : undefined],
|
|
53
|
+
], o);
|
|
54
|
+
const body = r.body === undefined ? undefined : stripTerminal(r.body).replace(/\n+$/, "");
|
|
55
|
+
return blocks(heading(`spec ${r.id}${title ? `: ${title}` : ""}`, o), info, issueTable(r.freshnessIssues, o), body,
|
|
56
|
+
r.bodyTruncated && r.nextOffset !== undefined && nextCommand("next", offsetCommand(context.args, r.nextOffset), o));
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** The slice as a table in breadth-first order from the root: DEPTH and EDGE say how each node was reached. */
|
|
60
|
+
export function renderSpecGraph(r: SpecGraphResult, o: TextOptions, context: SpecTextContext): string {
|
|
61
|
+
const root = r.nodes[0], direction = typeof context.values.direction === "string" ? context.values.direction : "subtree";
|
|
62
|
+
if (!root) return paragraph("spec graph: no nodes", o);
|
|
63
|
+
const reached = new Map<string, { depth: number; edge?: SpecEdge }>([[root.id, { depth: 0 }]]), queue = [root.id];
|
|
64
|
+
for (let i = 0; i < queue.length; i++) {
|
|
65
|
+
const at = queue[i]!, depth = reached.get(at)!.depth + 1;
|
|
66
|
+
for (const edge of r.edges) {
|
|
67
|
+
const next = direction !== "subtree" && edge.source === at ? edge.target : direction !== "ancestors" && edge.target === at ? edge.source : undefined;
|
|
68
|
+
if (next === undefined || reached.has(next)) continue;
|
|
69
|
+
reached.set(next, { depth, edge }); queue.push(next);
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
const order = (node: SpecNode) => reached.get(node.id)?.depth ?? 9;
|
|
73
|
+
const nodes = [...r.nodes].sort((a, b) => order(a) - order(b));
|
|
74
|
+
const rows = nodes.map(node => { const how = reached.get(node.id); return [tone(node.id, "info"), node.type || "-", statusTone(node.status), how?.edge?.kind ?? "-", how ? how.depth : "-", node.title]; });
|
|
75
|
+
const tree = new Set([...reached.values()].flatMap(how => how.edge ? [how.edge] : []));
|
|
76
|
+
const other = r.edges.filter(edge => !tree.has(edge));
|
|
77
|
+
const edge = typeof context.values.edge === "string" ? `${context.values.edge} edges` : direction === "neighbors" ? "all edges" : "parent edges";
|
|
78
|
+
return blocks(heading(`spec graph ${root.id}: ${direction}, ${edge}, depth ${typeof context.values.depth === "number" ? context.values.depth : 1}`, o),
|
|
79
|
+
table(["ID", "TYPE", "STATUS", "EDGE", "DEPTH", "TITLE"], rows, o),
|
|
80
|
+
other.length > 0 && table(["SOURCE", "EDGE", "TARGET"], other.map(item => [item.source, item.kind, item.target]), o),
|
|
81
|
+
[paragraph(`${plural(r.nodes.length, "node")}, ${plural(r.edges.length, "edge")}`, o),
|
|
82
|
+
r.truncated && paragraph("truncated: more specs lie beyond this slice; raise --depth (up to 3) or --limit (up to 500)", o, "warn")].filter(Boolean).join("\n"));
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** One hit per row, its snippet on the next line; rows never wrap so each snippet stays under its row. */
|
|
86
|
+
export function renderSpecGrep(r: SpecGrepResult, o: TextOptions, context: SpecTextContext): string {
|
|
87
|
+
if (!r.hits.length) return paragraph(r.offset ? `no more hits after offset ${r.offset}` : "no specs matched", o);
|
|
88
|
+
const lines = table(["ID", "TYPE", "STATUS", "TITLE"], r.hits.map(hit => [tone(hit.id, "info"), hit.type || "-", statusTone(hit.status), hit.title]), { color: o.color }).split("\n");
|
|
89
|
+
const body = [lines[0]!, ...r.hits.flatMap((hit, i) => [lines[i + 1]!, paragraph(stripTerminal(hit.snippet).replace(/\s+/g, " ").trim(), o, "muted", " ")])].join("\n");
|
|
90
|
+
const range = r.offset || r.truncated ? `hits ${r.offset + 1}-${r.offset + r.hits.length}` : plural(r.hits.length, "hit");
|
|
91
|
+
return blocks(body, [paragraph(range + (r.truncated ? ", more remain" : ""), o),
|
|
92
|
+
r.truncated && r.nextOffset !== undefined && nextCommand("next", offsetCommand(context.args, r.nextOffset), o)].filter(Boolean).join("\n"));
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
const finding = (item: { path: string; field?: string; target?: string; firstPath?: string; message: string }) =>
|
|
96
|
+
`${item.path}${item.field ? ` ${item.field}` : ""}${item.target ?? item.firstPath ? ` -> ${item.target ?? item.firstPath}` : ""}: ${item.message}`;
|
|
97
|
+
const levelCell = (severity: SpecValidationIssue["severity"]) => tone(severity, severity === "error" ? "fail" : "warn");
|
|
98
|
+
|
|
99
|
+
/** LEVEL/CHECK/FINDING rows per section, then a verdict line. Stale scopes are their own section unless --require-fresh made them errors. */
|
|
100
|
+
export function renderSpecValidate(r: SpecValidateResult, o: TextOptions, context: SpecTextContext): string {
|
|
101
|
+
const section = (title: string, rows: CellInput[][]) => rows.length > 0 && `${heading(title, o)}\n${table(["LEVEL", "CHECK", "FINDING"], rows, o)}`;
|
|
102
|
+
const stale = r.freshness.filter(entry => entry.state === "stale");
|
|
103
|
+
const target = context.repo !== undefined ? `--repo ${context.repo}` : r.source ?? "";
|
|
104
|
+
const verdict = `${r.ok ? "ok" : "fail"}: ${plural(r.errors, "error")}, ${plural(r.warnings, "warning")}, ${plural(stale.length, "stale scope")}`;
|
|
105
|
+
return blocks(heading(`spec validate ${target}`.trim(), o),
|
|
106
|
+
section("Findings", r.items.map(item => [levelCell(item.severity), item.code, finding(item)])),
|
|
107
|
+
section("Discovery", r.diagnostics.map((item: SpecDiagnostic) => [tone("note", "muted"), item.code, finding(item)])),
|
|
108
|
+
context.values.requireFresh !== true && section("Freshness", stale.map(entry => [tone("warning", "warn"), "stale",
|
|
109
|
+
`${entry.path}${entry.id ? ` (${entry.id})` : ""}: ${staleText(entry)}; review the scope and refresh verified-against`])),
|
|
110
|
+
[r.truncated && paragraph(`truncated: ${r.items.length} of ${r.errors + r.warnings} findings shown; raise --limit (up to 500) or fix the listed findings and rerun`, o, "warn"),
|
|
111
|
+
paint(verdict, r.ok ? "ok" : "fail", o)].filter(Boolean).join("\n"));
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
export function renderSpec(command: SpecCommand, result: unknown, o: TextOptions, context: SpecTextContext): string {
|
|
115
|
+
if (command === "get") return renderSpecGet(result as SpecGetResult, o, context);
|
|
116
|
+
if (command === "graph") return renderSpecGraph(result as SpecGraphResult, o, context);
|
|
117
|
+
if (command === "grep") return renderSpecGrep(result as SpecGrepResult, o, context);
|
|
118
|
+
return renderSpecValidate(result as SpecValidateResult, o, context);
|
|
119
|
+
}
|
package/src/sync.ts
CHANGED
|
@@ -19,7 +19,7 @@ export interface SyncResult {
|
|
|
19
19
|
branch: string | null;
|
|
20
20
|
/** Planned changed paths that will be staged and committed. */
|
|
21
21
|
paths: string[];
|
|
22
|
-
/** Changed paths outside
|
|
22
|
+
/** Changed paths outside STAGE_PREFIXES and STAGE_FILES: never staged. */
|
|
23
23
|
ignored: string[];
|
|
24
24
|
ahead: number;
|
|
25
25
|
behind: number;
|
|
@@ -28,7 +28,8 @@ export interface SyncResult {
|
|
|
28
28
|
pushed?: boolean;
|
|
29
29
|
issues: WriteIssue[];
|
|
30
30
|
}
|
|
31
|
-
|
|
31
|
+
/** A git call; `cause` names why a failed call failed (timeout, signal or the last stderr line). */
|
|
32
|
+
type Git = (args: string[], options?: { allowFail?: boolean }) => SpawnSyncReturns<string> & { cause: string };
|
|
32
33
|
const issue = (code: string, message: string): WriteIssue => ({ code, severity: "error", message });
|
|
33
34
|
/** Compare remotes after removing transport noise: scheme, credentials, trailing .git and slash. Host remotes compare case-insensitively without a trailing .git; local and file: paths keep their case and their .git suffix. */
|
|
34
35
|
export function sameRemote(a: string, b: string): boolean {
|
|
@@ -43,12 +44,28 @@ export function sameRemote(a: string, b: string): boolean {
|
|
|
43
44
|
};
|
|
44
45
|
return norm(a) === norm(b);
|
|
45
46
|
}
|
|
46
|
-
|
|
47
|
+
/** Time budget of the console's local sync check. */
|
|
48
|
+
const GIT_TIMEOUT_BUDGET_MS = 1000;
|
|
49
|
+
/** The paths `vmem sync` stages (STAGE_PREFIXES, then STAGE_FILES), as people read them. */
|
|
50
|
+
export const STAGED_DESCRIPTION = ((items: string[]) => items.length > 1 ? `${items.slice(0, -1).join(", ")} and ${items.at(-1)}` : items.join(""))([...STAGE_PREFIXES, ...STAGE_FILES]);
|
|
51
|
+
type SpawnResult = { exitCode: number | null; signalCode?: string | number | null; exitedDueToTimeout?: boolean; stderr: { toString(): string } };
|
|
52
|
+
/** Why a git call failed: its timeout or signal when it left no exit code, else the last stderr line. */
|
|
53
|
+
function failureCause(result: SpawnResult, budgetMs: number): string {
|
|
54
|
+
if (result.exitedDueToTimeout) return `timed out after ${budgetMs / 1000} s`;
|
|
55
|
+
if (result.exitCode === null) return `killed by ${result.signalCode ?? "a signal"}`;
|
|
56
|
+
return result.stderr.toString().trim().split("\n").at(-1)?.slice(0, 300) || "error";
|
|
57
|
+
}
|
|
58
|
+
const NEXT_STEP = { console: "inspect the vault Git state in System and retry", sync: "check `git -C <vault> status`, then rerun vmem sync", doctor: "check `git -C <vault> status`, then rerun vmem doctor" } as const;
|
|
59
|
+
function gitIn(cwd: string, env: NodeJS.ProcessEnv, deadline?: number, context: keyof typeof NEXT_STEP = "sync"): Git {
|
|
47
60
|
return (args, options = {}) => {
|
|
61
|
+
const timeout = deadline === undefined ? GIT_TIMEOUT_MS : deadline - Date.now();
|
|
62
|
+
if (timeout <= 0) throw new Error(`git ${args[0]} not started: the ${GIT_TIMEOUT_BUDGET_MS / 1000} s budget is used up; ${NEXT_STEP[context]}`);
|
|
48
63
|
const argv = memoryGitArgv(["-C", cwd, ...args]);
|
|
49
|
-
const result = Bun.spawnSync(argv, { env: memoryGitEnv({ ...env, GIT_OPTIONAL_LOCKS: "0", LC_ALL: "C" }, { repositoryIsolation: true }), stdin: "ignore", stdout: "pipe", stderr: "pipe", timeout
|
|
50
|
-
|
|
51
|
-
|
|
64
|
+
const result = Bun.spawnSync(argv, { env: memoryGitEnv({ ...env, GIT_OPTIONAL_LOCKS: "0", LC_ALL: "C" }, { repositoryIsolation: true }), stdin: "ignore", stdout: "pipe", stderr: "pipe", timeout });
|
|
65
|
+
// A timeout or signal leaves no exit code and usually no stderr, so `cause` names it instead.
|
|
66
|
+
const cause = result.exitCode === 0 ? "" : failureCause(result, deadline === undefined ? GIT_TIMEOUT_MS : GIT_TIMEOUT_BUDGET_MS);
|
|
67
|
+
const out = { status: result.exitCode, stdout: result.stdout.toString(), stderr: result.stderr.toString(), pid: result.pid, output: [], signal: null, cause } as unknown as ReturnType<Git>;
|
|
68
|
+
if (!options.allowFail && result.exitCode !== 0) throw Object.assign(new Error(`git ${args[0]} failed: ${cause}${result.exitCode === null ? `; ${NEXT_STEP[context]}` : ""}`), { git: true });
|
|
52
69
|
return out;
|
|
53
70
|
};
|
|
54
71
|
}
|
|
@@ -65,8 +82,8 @@ function applicableRewrites(lines: (args: string[]) => string[], urls: string[])
|
|
|
65
82
|
});
|
|
66
83
|
}
|
|
67
84
|
/** Local-only origin validation shared by doctor and sync; never fetches or pushes. */
|
|
68
|
-
export function originCheck(root: string, remote: string, env: NodeJS.ProcessEnv = process.env): { ok: boolean; origin: string | null; fetchUrls: string[]; pushUrls: string[]; issue?: string } {
|
|
69
|
-
const git = gitIn(root, env);
|
|
85
|
+
export function originCheck(root: string, remote: string, env: NodeJS.ProcessEnv = process.env, context: "sync" | "doctor" = "sync"): { ok: boolean; origin: string | null; fetchUrls: string[]; pushUrls: string[]; issue?: string } {
|
|
86
|
+
const git = gitIn(root, env, undefined, context);
|
|
70
87
|
if (realpathSync(git(["rev-parse", "--show-toplevel"]).stdout.trim()) !== root) throw new Error("vault path is not the root of its git repository");
|
|
71
88
|
const origin = git(["remote", "get-url", "origin"], { allowFail: true });
|
|
72
89
|
const originUrl = origin.status === 0 ? origin.stdout.trim() : null;
|
|
@@ -78,15 +95,42 @@ export function originCheck(root: string, remote: string, env: NodeJS.ProcessEnv
|
|
|
78
95
|
return { ok, origin: originUrl, fetchUrls, pushUrls, ...(!ok ? { issue: originUrl === null ? "repository has no origin remote" : rewrites.length ? `git url rewrite ${rewrites[0]} applies to the vault remote; refusing because the push destination cannot be verified` : "an origin fetch or push URL does not match the configured remote; nothing was fetched or pushed" } : {}) };
|
|
79
96
|
}
|
|
80
97
|
function planned(path: string): boolean { return STAGE_FILES.includes(path) || STAGE_PREFIXES.some(prefix => path.startsWith(prefix)); }
|
|
81
|
-
/** Parse `status --porcelain=v1 -z` into
|
|
82
|
-
function
|
|
83
|
-
const parts = git(["status", "--porcelain=v1", "-z", "--untracked-files=all"]).stdout.split("\0").filter(Boolean),
|
|
98
|
+
/** Parse `status --porcelain=v1 -z` into one entry per change; a rename or copy is one entry with both sides. */
|
|
99
|
+
function changedEntries(git: Git): string[][] {
|
|
100
|
+
const parts = git(["status", "--porcelain=v1", "-z", "--untracked-files=all"]).stdout.split("\0").filter(Boolean), entries: string[][] = [];
|
|
84
101
|
for (let i = 0; i < parts.length; i++) {
|
|
85
102
|
const entry = parts[i]!, code = entry.slice(0, 2);
|
|
86
|
-
|
|
87
|
-
if (code.includes("R") || code.includes("C")) paths.push(parts[++i]!);
|
|
103
|
+
entries.push(code.includes("R") || code.includes("C") ? [entry.slice(3), parts[++i]!] : [entry.slice(3)]);
|
|
88
104
|
}
|
|
89
|
-
return
|
|
105
|
+
return entries;
|
|
106
|
+
}
|
|
107
|
+
/** Changed paths, both sides of a rename included, sorted and unique. */
|
|
108
|
+
function changed(git: Git): string[] { return [...new Set(changedEntries(git).flat())].sort(); }
|
|
109
|
+
|
|
110
|
+
/** Shared local history counts; no fetch is needed to compare stored refs. */
|
|
111
|
+
function aheadBehind(git: Git, upstream: string): { behind: number; ahead: number } {
|
|
112
|
+
const [behind, ahead] = git(["rev-list", "--left-right", "--count", `${upstream}...HEAD`]).stdout.trim().split(/\s+/).map(Number);
|
|
113
|
+
if (!Number.isSafeInteger(behind) || !Number.isSafeInteger(ahead) || behind! < 0 || ahead! < 0) throw new Error("git rev-list returned invalid counts; inspect the vault Git state in System and retry");
|
|
114
|
+
return { behind: behind!, ahead: ahead! };
|
|
115
|
+
}
|
|
116
|
+
/** Local-only inbox state: dirty paths plus commits ahead of the configured tracking ref. */
|
|
117
|
+
export function localSyncPending(root: string, env: NodeJS.ProcessEnv = process.env): { changed: number; ignored: number; ahead: number; upstream: boolean } {
|
|
118
|
+
const git = gitIn(root, { ...env, GIT_TERMINAL_PROMPT: "0", GCM_INTERACTIVE: "Never", GIT_NO_LAZY_FETCH: "1" }, Date.now() + GIT_TIMEOUT_BUDGET_MS, "console");
|
|
119
|
+
if (realpathSync(root) !== root || realpathSync(git(["rev-parse", "--show-toplevel"]).stdout.trim()) !== root) throw new Error("sync pending requires the registered Git worktree root; check the vault path in System");
|
|
120
|
+
// Only changes sync would stage count; a rename counts once. Other dirty paths are reported separately.
|
|
121
|
+
const entries = changedEntries(git), dirty = entries.filter(paths => paths.some(planned)).length, ignored = entries.length - dirty;
|
|
122
|
+
const none = { changed: dirty, ignored, ahead: 0, upstream: false };
|
|
123
|
+
// `symbolic-ref` exits 1 only for a detached HEAD, which has no branch and so no upstream. An unborn branch
|
|
124
|
+
// passes here, but its branch ref does not exist yet, so `for-each-ref` below finds no upstream.
|
|
125
|
+
const branch = git(["symbolic-ref", "--quiet", "HEAD"], { allowFail: true });
|
|
126
|
+
if (branch.status === 1) return none;
|
|
127
|
+
if (branch.status !== 0) throw new Error("sync pending cannot read the current branch; inspect the vault Git state in System and retry");
|
|
128
|
+
const upstream = git(["for-each-ref", "--format=%(upstream)", branch.stdout.trim()]).stdout.trim();
|
|
129
|
+
if (!upstream) return none;
|
|
130
|
+
const tracking = git(["rev-parse", "--verify", "--quiet", upstream], { allowFail: true });
|
|
131
|
+
if (tracking.status === 1) return none;
|
|
132
|
+
if (tracking.status !== 0) throw new Error("sync pending cannot verify the tracking ref; inspect the vault Git state in System and retry");
|
|
133
|
+
return { changed: dirty, ignored, ahead: aheadBehind(git, upstream).ahead, upstream: true };
|
|
90
134
|
}
|
|
91
135
|
|
|
92
136
|
/**
|
|
@@ -120,12 +164,12 @@ export function syncVault(home: string, request: { vault: string; confirm?: bool
|
|
|
120
164
|
result.branch = branch.stdout.trim();
|
|
121
165
|
if (git(["rev-parse", "--verify", "--quiet", "REBASE_HEAD"], { allowFail: true }).status === 0 || git(["rev-parse", "--verify", "--quiet", "MERGE_HEAD"], { allowFail: true }).status === 0) return { ...result, issues: [issue("SYNC", "a rebase or merge is in progress; resolve it first")] };
|
|
122
166
|
const fetch = git(["fetch", "--quiet", "--no-tags", "origin", result.branch], { allowFail: true });
|
|
123
|
-
if (fetch.status !== 0) return { ...result, issues: [issue("FETCH", `fetch failed: ${fetch.
|
|
167
|
+
if (fetch.status !== 0) return { ...result, issues: [issue("FETCH", `fetch failed: ${fetch.cause}; check the network and credentials for origin, then rerun vmem sync`)] };
|
|
124
168
|
const upstream = `origin/${result.branch}`;
|
|
125
169
|
const hasUpstream = git(["rev-parse", "--verify", "--quiet", `refs/remotes/${upstream}`], { allowFail: true }).status === 0;
|
|
126
170
|
if (hasUpstream) {
|
|
127
|
-
const
|
|
128
|
-
result.behind = behind
|
|
171
|
+
const counts = aheadBehind(git, upstream);
|
|
172
|
+
result.behind = counts.behind; result.ahead = counts.ahead;
|
|
129
173
|
}
|
|
130
174
|
const all = changed(git);
|
|
131
175
|
result.paths = all.filter(planned); result.ignored = all.filter(path => !planned(path));
|
|
@@ -155,7 +199,7 @@ export function syncVault(home: string, request: { vault: string; confirm?: bool
|
|
|
155
199
|
const pushNow = lines(["remote", "get-url", "--push", "--all", "origin"]);
|
|
156
200
|
if (pushNow.some(url => !sameRemote(url, spec.remote!)) || applicableRewrites(lines, [spec.remote, ...fetchUrls, ...pushNow]).length) return { ...result, applied: Boolean(result.commit), pushed: false, issues: [issue("REMOTE", "push destination changed before push; nothing was pushed")] };
|
|
157
201
|
const push = git(["push", "--quiet", "--porcelain", "origin", `HEAD:refs/heads/${result.branch}`], { allowFail: true });
|
|
158
|
-
if (push.status !== 0) return { ...result, applied: Boolean(result.commit), pushed: false, issues: [issue("PUSH", `push failed: ${push.
|
|
202
|
+
if (push.status !== 0) return { ...result, applied: Boolean(result.commit), pushed: false, issues: [issue("PUSH", `push failed: ${push.cause}; the local commit was kept; check the network and push access for origin, then rerun vmem sync`)] };
|
|
159
203
|
// Verify the remote really has our head before reporting success.
|
|
160
204
|
git(["fetch", "--quiet", "--no-tags", "origin", result.branch]);
|
|
161
205
|
const pushedHead = git(["rev-parse", upstream]).stdout.trim(), localHead = git(["rev-parse", "HEAD"]).stdout.trim();
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Text output for people (#114), after agent-hub's CLI conventions: uppercase-header tables sized by display width,
|
|
3
|
+
* aligned field blocks, a wrapped description column and `--color=auto|always|never`. `--json` output never comes
|
|
4
|
+
* through here, and color only adds emphasis: every renderer's text is complete without it.
|
|
5
|
+
*/
|
|
6
|
+
import type { WriteIssue } from "./write-types.ts";
|
|
7
|
+
|
|
8
|
+
export type Tone = "ok" | "warn" | "fail" | "muted" | "info" | "accent" | "bold";
|
|
9
|
+
export interface TextOptions { color: boolean; columns?: number }
|
|
10
|
+
export interface Cell { text: string; tone?: Tone }
|
|
11
|
+
export type CellInput = string | number | boolean | null | undefined | Cell;
|
|
12
|
+
|
|
13
|
+
/** Plain text, no wrapping: the default for library callers and tests. */
|
|
14
|
+
export const PLAIN: TextOptions = { color: false };
|
|
15
|
+
const CODES: Record<Tone, string> = { ok: "32", warn: "33", fail: "31", muted: "2", info: "36", accent: "35", bold: "1" };
|
|
16
|
+
const COLOR_USAGE = "--color: expected --color=auto, --color=always or --color=never";
|
|
17
|
+
|
|
18
|
+
/** Removes the one allowed `--color=` flag from args. It may appear anywhere before a `--` separator. */
|
|
19
|
+
export function takeColorFlag(args: string[]): { args: string[]; color?: string } {
|
|
20
|
+
const end = args.includes("--") ? args.indexOf("--") : args.length;
|
|
21
|
+
const found = args.slice(0, end).filter(arg => arg === "--color" || arg.startsWith("--color="));
|
|
22
|
+
if (!found.length) return { args };
|
|
23
|
+
if (found.length > 1 || found[0] === "--color") throw new Error(`${COLOR_USAGE}, given once`);
|
|
24
|
+
return { args: args.filter((arg, i) => i >= end || arg !== found[0]), color: found[0]!.slice("--color=".length) };
|
|
25
|
+
}
|
|
26
|
+
export function resolveColor(flag: string | undefined, env: { isTTY: boolean; TERM?: string; NO_COLOR?: string }): boolean {
|
|
27
|
+
if (flag === "always") return true;
|
|
28
|
+
if (flag === "never") return false;
|
|
29
|
+
if (flag === undefined || flag === "auto") return env.isTTY && env.TERM !== "dumb" && !env.NO_COLOR;
|
|
30
|
+
throw new Error(COLOR_USAGE);
|
|
31
|
+
}
|
|
32
|
+
/** Terminal width on a TTY (at least 80), else `COLUMNS` when set, else no wrapping. */
|
|
33
|
+
export function outputWidth(env: { isTTY: boolean; columns?: number; COLUMNS?: string }): number | undefined {
|
|
34
|
+
if (env.isTTY) return Math.max(80, env.columns && Number.isFinite(env.columns) ? env.columns : 80);
|
|
35
|
+
return env.COLUMNS && /^[1-9][0-9]*$/.test(env.COLUMNS) ? Number(env.COLUMNS) : undefined;
|
|
36
|
+
}
|
|
37
|
+
/** Options for a stdout; the default is a non-terminal, so library calls and tests get the same text everywhere. */
|
|
38
|
+
export function textOptions(flag: string | undefined, env: NodeJS.ProcessEnv = process.env, stdout: { isTTY?: boolean; columns?: number } = {}): TextOptions {
|
|
39
|
+
const isTTY = stdout.isTTY === true, color = resolveColor(flag, { isTTY, TERM: env.TERM, NO_COLOR: env.NO_COLOR });
|
|
40
|
+
const columns = outputWidth({ isTTY, columns: stdout.columns, COLUMNS: env.COLUMNS });
|
|
41
|
+
return { color, ...(columns !== undefined ? { columns } : {}) };
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
const cell = (value: CellInput): Cell => typeof value === "object" && value !== null ? value : { text: value === null || value === undefined ? "" : String(value) };
|
|
45
|
+
/** Control characters (terminal escapes, tabs, newlines) never reach the terminal from data. */
|
|
46
|
+
export const clean = (text: string) => text.replace(/[\u0000-\u001f\u007f-\u009f]/g, " ");
|
|
47
|
+
export const width = (text: string) => Bun.stringWidth(text);
|
|
48
|
+
/** Note and spec bodies printed as is, minus terminal escape sequences (OSC, CSI, C1) and control characters other than tab and newline. */
|
|
49
|
+
export const stripTerminal = (text: string) => text
|
|
50
|
+
.replace(/\u001b\][^\u0007\u001b]*(?:\u0007|\u001b\\)?|\u001b\[[0-?]*[ -/]*[@-~]?|\u009b[0-?]*[ -/]*[@-~]?|\u001b[^[\]]?/g, "")
|
|
51
|
+
.replace(/\r\n?/g, "\n").replace(/[\u0000-\u0008\u000b-\u001f\u007f-\u009f]/g, "");
|
|
52
|
+
export function paint(text: string, tone: Tone | undefined, o: TextOptions): string {
|
|
53
|
+
return o.color && tone && text ? `\u001b[${CODES[tone]}m${text}\u001b[0m` : text;
|
|
54
|
+
}
|
|
55
|
+
export const tone = (text: CellInput, t: Tone): Cell => ({ text: cell(text).text, tone: t });
|
|
56
|
+
const graphemes = new Intl.Segmenter(undefined, { granularity: "grapheme" });
|
|
57
|
+
|
|
58
|
+
/** Word wrap by display width; a word longer than the width is split by grapheme. */
|
|
59
|
+
export function wrap(text: string, columns: number | undefined, indent = ""): string[] {
|
|
60
|
+
const flat = clean(text);
|
|
61
|
+
if (columns === undefined) return [indent + flat];
|
|
62
|
+
const room = Math.max(10, columns - width(indent)), lines: string[] = [];
|
|
63
|
+
let line = "";
|
|
64
|
+
for (const word of flat.split(/ +/).filter(Boolean)) {
|
|
65
|
+
const pieces: string[] = [];
|
|
66
|
+
if (width(word) <= room) pieces.push(word);
|
|
67
|
+
else { let piece = ""; for (const { segment } of graphemes.segment(word)) { if (width(piece + segment) > room) { pieces.push(piece); piece = ""; } piece += segment; } if (piece) pieces.push(piece); }
|
|
68
|
+
for (const piece of pieces) {
|
|
69
|
+
if (line && width(line + " " + piece) > room) { lines.push(line); line = ""; }
|
|
70
|
+
line = line ? `${line} ${piece}` : piece;
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
if (line || !lines.length) lines.push(line);
|
|
74
|
+
return lines.map(value => indent + value);
|
|
75
|
+
}
|
|
76
|
+
const pad = (text: string, size: number) => text + " ".repeat(Math.max(0, size - width(text)));
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* Table with uppercase headers and two-space gaps. When a width is known and the row is too wide, the last column
|
|
80
|
+
* wraps under itself; with no width (pipes, tests) rows stay on one line.
|
|
81
|
+
*/
|
|
82
|
+
export function table(headers: string[], rows: CellInput[][], o: TextOptions): string {
|
|
83
|
+
const data = rows.map(row => headers.map((_, i) => { const c = cell(row[i]); return { ...c, text: clean(c.text) }; }));
|
|
84
|
+
const sizes = headers.map((header, i) => Math.max(width(header), ...data.map(row => width(row[i]!.text))));
|
|
85
|
+
const last = headers.length - 1, lead = sizes.slice(0, last).reduce((sum, size) => sum + size + 2, 0);
|
|
86
|
+
const lastRoom = o.columns !== undefined && lead + sizes[last]! > o.columns ? Math.max(20, o.columns - lead) : undefined;
|
|
87
|
+
const line = (cells: Cell[], bold = false) => {
|
|
88
|
+
const tail = wrap(cells[last]!.text, lastRoom);
|
|
89
|
+
const head = cells.slice(0, last).map((c, i) => paint(pad(c.text, sizes[i]!), bold ? "bold" : c.tone, o)).join(" ");
|
|
90
|
+
return tail.map((part, i) => (i ? " ".repeat(lead) : head + (last ? " " : "")) + paint(part, bold ? "bold" : cells[last]!.tone, o)).join("\n").replace(/ +$/gm, "");
|
|
91
|
+
};
|
|
92
|
+
return [line(headers.map(text => ({ text })), true), ...data.map(row => line(row))].join("\n");
|
|
93
|
+
}
|
|
94
|
+
/** `label value` lines with aligned values, indented by two spaces. Empty values are left out. */
|
|
95
|
+
export function fields(pairs: [label: string, value: CellInput][], o: TextOptions, indent = " "): string {
|
|
96
|
+
const shown = pairs.map(([label, value]) => [label, cell(value)] as const).filter(([, value]) => value.text !== "");
|
|
97
|
+
const size = Math.max(0, ...shown.map(([label]) => width(label)));
|
|
98
|
+
const hang = indent + " ".repeat(size + 2);
|
|
99
|
+
return shown.map(([label, value]) => {
|
|
100
|
+
const lines = wrap(value.text, o.columns === undefined ? undefined : o.columns - width(hang));
|
|
101
|
+
return lines.map((text, i) => (i ? hang : indent + pad(label, size) + " ") + paint(text, value.tone, o)).join("\n");
|
|
102
|
+
}).join("\n");
|
|
103
|
+
}
|
|
104
|
+
export const heading = (text: string, o: TextOptions) => paint(clean(text), "bold", o);
|
|
105
|
+
/** Paragraph wrapped to the width, for hints and verdicts. */
|
|
106
|
+
export const paragraph = (text: string, o: TextOptions, t?: Tone, indent = "") => wrap(text, o.columns, indent).map(line => paint(line, t, o)).join("\n");
|
|
107
|
+
/** Joins the non-empty blocks with one blank line. */
|
|
108
|
+
export const blocks = (...parts: (string | undefined | false)[]) => parts.filter((part): part is string => !!part).join("\n\n");
|
|
109
|
+
export const plural = (count: number, one: string, many = `${one}s`) => `${count} ${count === 1 ? one : many}`;
|
|
110
|
+
|
|
111
|
+
/** Write and validation issues: LEVEL, CODE, PATH and MESSAGE, errors first. */
|
|
112
|
+
export function issueTable(issues: readonly WriteIssue[], o: TextOptions): string | undefined {
|
|
113
|
+
if (!issues.length) return undefined;
|
|
114
|
+
const sorted = [...issues].sort((a, b) => (a.severity === b.severity ? 0 : a.severity === "error" ? -1 : 1));
|
|
115
|
+
return table(["LEVEL", "CODE", "PATH", "MESSAGE"], sorted.map(issue => [tone(issue.severity, issue.severity === "error" ? "fail" : "warn"), issue.code, issue.path ?? "-", issue.message]), o);
|
|
116
|
+
}
|
|
117
|
+
/** The command a person runs next, for example to confirm a preview or read the next page. */
|
|
118
|
+
export const nextCommand = (label: string, command: string, o: TextOptions) => `${label}: ${paint(clean(command), "info", o)}`;
|
|
119
|
+
/** Quotes one shell word only when it needs it, so a printed command can be pasted. */
|
|
120
|
+
export const shellWord = (word: string) => /^[\p{L}\p{N}_./:=@%+,-]+$/u.test(word) ? word : `'${word.replace(/'/g, `'"'"'`)}'`;
|
package/src/ui/panel.css
CHANGED
|
@@ -1,16 +1,12 @@
|
|
|
1
|
+
.vmem-cards { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(300px, 100%), 1fr)); gap: var(--acon-space-4); }
|
|
1
2
|
.vmem { display: flex; flex-direction: column; gap: var(--acon-space-3); word-break: keep-all; }
|
|
2
3
|
.vmem-bar { display: flex; flex-wrap: wrap; align-items: center; gap: var(--acon-space-2); }
|
|
3
4
|
.vmem-inline { display: inline-flex; gap: var(--acon-space-2); }
|
|
4
5
|
.vmem-input { min-height: 32px; min-width: 0; padding: 0 10px; border: 1px solid var(--acon-line-2); border-radius: var(--acon-radius-2); background: var(--acon-surface); color: var(--acon-text); font: inherit; }
|
|
5
6
|
.vmem-bar input[type="search"] { flex: 1; max-width: 480px; }
|
|
6
|
-
.vmem-head { display: flex; flex-wrap: wrap; align-items: center; gap: var(--acon-space-2); }
|
|
7
|
-
.vmem-head h2 { margin: 0; font-size: 17px; }
|
|
8
7
|
.vmem-sub { margin: 0; color: var(--acon-text-2); }
|
|
9
8
|
.vmem-body { margin: var(--acon-space-2) 0 0; padding: var(--acon-space-3); max-height: 60vh; overflow: auto; white-space: pre-wrap; word-break: break-word; background: var(--acon-surface); border: 1px solid var(--acon-line); border-radius: var(--acon-radius-2); font: 13px/1.5 var(--acon-font-mono); }
|
|
10
|
-
.vmem-mono { margin: 0; color: var(--acon-text-2); font: 12px var(--acon-font-mono); word-break: break-all; }
|
|
11
|
-
.vmem details > summary { cursor: pointer; font-weight: 600; padding: var(--acon-space-1) 0; }
|
|
12
9
|
@media (max-width: 600px) { .vmem-inline { width: 100%; } .vmem-inline .vmem-input { flex: 1; } }
|
|
13
10
|
.vmem-form { display: flex; flex-direction: column; gap: var(--acon-space-2); max-width: 560px; }
|
|
14
11
|
.vmem-form h2 { margin: 0; font-size: 15px; }
|
|
15
|
-
.vmem-form .btn { align-self: flex-start; }
|
|
16
12
|
.vmem-check { display: inline-flex; align-items: center; gap: 4px; color: var(--acon-text-2); }
|