@staix/vault-mem 0.4.0 → 0.5.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/CHANGELOG.md +46 -0
- package/README.md +15 -7
- 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 +75 -42
- package/src/commands-table.ts +85 -44
- package/src/config.ts +22 -3
- package/src/links.ts +2 -0
- package/src/log-commands.ts +10 -5
- package/src/mcp-spec.ts +5 -2
- package/src/mcp-vault.ts +6 -5
- 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/inbox-source.ts +46 -0
- package/src/ui/inbox-worker.ts +8 -0
- package/src/ui/inbox.ts +134 -0
- package/src/ui/panel.css +1 -5
- package/src/ui/panel.js +60 -70
- package/src/ui/plugin.ts +12 -30
- package/src/vault-graph.ts +21 -2
- package/src/vault-index.ts +10 -4
- package/src/vault-lint.ts +8 -2
- package/src/vault-log.ts +97 -0
- package/src/workspace-graph.ts +9 -1
- package/src/write-commands.ts +5 -3
- package/src/write-operations.ts +25 -2
- package/src/write-output.ts +151 -0
- package/src/write-validation.ts +30 -8
package/src/org-commands.ts
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
import { promoteToOrg } from "./org-promote.ts";
|
|
2
2
|
import { syncVault } from "./sync.ts";
|
|
3
|
+
import { PLAIN, type TextOptions } from "./text-output.ts";
|
|
4
|
+
import { renderOrgPromote, renderSync } from "./write-output.ts";
|
|
3
5
|
|
|
4
6
|
function parse(command: string, args: string[], values: string[], booleans: string[]) {
|
|
5
7
|
const flags: Record<string, string | boolean> = {}, positional: string[] = [];
|
|
@@ -15,17 +17,17 @@ function parse(command: string, args: string[], values: string[], booleans: stri
|
|
|
15
17
|
return { flags, positional, value: (name: string) => typeof flags[name] === "string" ? flags[name] as string : undefined };
|
|
16
18
|
}
|
|
17
19
|
/** `vmem promote <vault> <note> --to <org>` and `vmem sync <vault>`: both preview unless `--confirm --fingerprint`. */
|
|
18
|
-
export function runOrgCommand(command: string, args: string[], home: string, env: NodeJS.ProcessEnv): { text: string; code: number } {
|
|
20
|
+
export function runOrgCommand(command: string, args: string[], home: string, env: NodeJS.ProcessEnv, text: TextOptions = PLAIN): { text: string; code: number } {
|
|
19
21
|
if (command === "promote") {
|
|
20
22
|
const { flags, positional, value } = parse(command, args, ["--to", "--topics", "--fingerprint", "--log-project"], ["--again", "--confirm", "--json"]);
|
|
21
23
|
if (positional.length !== 2 || !value("--to")) throw new Error("promote: requires personal vault id, note and --to <org vault>");
|
|
22
24
|
const result = promoteToOrg(home, { from: positional[0]!, note: positional[1]!, to: value("--to")!, again: flags["--again"] === true, confirm: flags["--confirm"] === true,
|
|
23
25
|
...(value("--topics") ? { topics: value("--topics")!.split(",").map(t => t.trim()).filter(Boolean) } : {}),
|
|
24
26
|
...(value("--fingerprint") ? { fingerprint: value("--fingerprint") } : {}), ...(value("--log-project") ? { logProject: value("--log-project") } : {}), channel: "cli" }, { env });
|
|
25
|
-
return { text: JSON.stringify(result,
|
|
27
|
+
return { text: flags["--json"] ? JSON.stringify(result) : renderOrgPromote(result, text, { argv: [command, ...args], positional }), code: result.ok ? 0 : 1 };
|
|
26
28
|
}
|
|
27
29
|
const { flags, positional, value } = parse(command, args, ["--fingerprint", "--message"], ["--confirm", "--json"]);
|
|
28
30
|
if (positional.length !== 1) throw new Error("sync: requires vault id");
|
|
29
31
|
const result = syncVault(home, { vault: positional[0]!, confirm: flags["--confirm"] === true, ...(value("--fingerprint") ? { fingerprint: value("--fingerprint") } : {}), ...(value("--message") ? { message: value("--message") } : {}) }, { env });
|
|
30
|
-
return { text: JSON.stringify(result,
|
|
32
|
+
return { text: flags["--json"] ? JSON.stringify(result) : renderSync(result, text, { argv: [command, ...args], positional }), code: result.ok ? 0 : 1 };
|
|
31
33
|
}
|
package/src/org-promote.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { domainProblem } from "./config.ts";
|
|
1
2
|
import { localDate } from "./local-date.ts";
|
|
2
3
|
import { createHash } from "node:crypto";
|
|
3
4
|
import { closeSync, constants, fstatSync, openSync, readSync, realpathSync } from "node:fs";
|
|
@@ -183,6 +184,8 @@ export function promoteToOrg(home: string, request: OrgPromoteRequest, options:
|
|
|
183
184
|
const original = readSource(source, path);
|
|
184
185
|
let parsed;
|
|
185
186
|
try { parsed = parseFrontmatter(original); } catch { return fail(issue("V01", "source frontmatter is not parseable", path)); }
|
|
187
|
+
const domain = parsed.data.type === "moc" && parsed.data.domain === undefined ? undefined : domainProblem(parsed.data.domain, target);
|
|
188
|
+
if (domain) return fail(issue("V01", domain, path));
|
|
186
189
|
const promotedTo = `${target.id}:${path}`;
|
|
187
190
|
const prior = strings(parsed.data.promoted_to);
|
|
188
191
|
if (prior.length && !request.again) return fail(issue("AGAIN", `already promoted to ${prior.join(", ")}; pass --again to promote again`, path));
|
package/src/promote-command.ts
CHANGED
|
@@ -6,6 +6,8 @@ import { loadRegistry } from "./registry.ts";
|
|
|
6
6
|
import { canonicalPath, isDenied } from "./platform.ts";
|
|
7
7
|
import { MAX_WRITE_BYTES } from "./writer.ts";
|
|
8
8
|
import { listPromotionCandidates, promoteFromAmem, type PromoteRequest } from "./promote.ts";
|
|
9
|
+
import { PLAIN, type TextOptions } from "./text-output.ts";
|
|
10
|
+
import { renderCandidates, renderPromote } from "./write-output.ts";
|
|
9
11
|
|
|
10
12
|
const VALUES = ["--project", "--limit", "--stem", "--type", "--domain", "--topics", "--description", "--title", "--body", "--link-to", "--log-project", "--fingerprint"];
|
|
11
13
|
const BOOLEANS = ["--all-projects", "--edit", "--confirm", "--json"];
|
|
@@ -35,7 +37,7 @@ function editBody(draft: string, env: NodeJS.ProcessEnv, stdinIsTTY: boolean): s
|
|
|
35
37
|
} finally { rmSync(dir, { recursive: true, force: true }); }
|
|
36
38
|
}
|
|
37
39
|
/** `vmem promote-from-amem <vault> [<mem-id>] ...`: lists candidates, previews, or confirms one promotion. */
|
|
38
|
-
export async function runPromoteCommand(args: string[], home: string, env: NodeJS.ProcessEnv, io: { stdinIsTTY?: boolean } = {}): Promise<{ text: string; code: number }> {
|
|
40
|
+
export async function runPromoteCommand(args: string[], home: string, env: NodeJS.ProcessEnv, io: { stdinIsTTY?: boolean } = {}, text: TextOptions = PLAIN): Promise<{ text: string; code: number }> {
|
|
39
41
|
const flags: Record<string, string | boolean> = {}, positional: string[] = [];
|
|
40
42
|
for (let i = 0; i < args.length; i++) {
|
|
41
43
|
const arg = args[i]!;
|
|
@@ -47,7 +49,7 @@ export async function runPromoteCommand(args: string[], home: string, env: NodeJ
|
|
|
47
49
|
flags[arg] = value;
|
|
48
50
|
}
|
|
49
51
|
const value = (name: string) => typeof flags[name] === "string" ? flags[name] as string : undefined;
|
|
50
|
-
const
|
|
52
|
+
const json = flags["--json"] === true, ctx = { argv: ["promote-from-amem", ...args], positional };
|
|
51
53
|
if (positional.length < 1 || positional.length > 2) throw new Error("promote-from-amem: requires vault id and optional mem id");
|
|
52
54
|
const [vault, rawId] = positional as [string, string | undefined];
|
|
53
55
|
if (!loadRegistry(home).vaults.some(v => v.id === vault)) throw new Error("promote-from-amem: unknown vault id");
|
|
@@ -55,7 +57,7 @@ export async function runPromoteCommand(args: string[], home: string, env: NodeJ
|
|
|
55
57
|
if (flags["--all-projects"] && value("--project")) throw new Error("choose either --all-projects or --project");
|
|
56
58
|
const limit = value("--limit") === undefined ? undefined : /^[0-9]+$/.test(value("--limit")!) ? Number(value("--limit")) : NaN;
|
|
57
59
|
const list = await listPromotionCandidates({ env, allProjects: flags["--all-projects"] === true, ...(value("--project") ? { project: value("--project") } : {}), ...(limit !== undefined ? { limit } : {}), piiPatterns: loadRegistry(home).piiPatterns });
|
|
58
|
-
return { text:
|
|
60
|
+
return { text: json ? JSON.stringify(list) : renderCandidates(list, text, ctx), code: 0 };
|
|
59
61
|
}
|
|
60
62
|
if (flags["--all-projects"]) throw new Error("--all-projects lists candidates only");
|
|
61
63
|
const request: PromoteRequest = { vault, id: rawId.replace(/^mem:/, ""), channel: "cli", confirm: flags["--confirm"] === true };
|
|
@@ -73,5 +75,5 @@ export async function runPromoteCommand(args: string[], home: string, env: NodeJ
|
|
|
73
75
|
}
|
|
74
76
|
const result = await promoteFromAmem(home, request, options);
|
|
75
77
|
const edited = flags["--edit"] && request.body !== undefined && value("--body") === undefined;
|
|
76
|
-
return { text:
|
|
78
|
+
return { text: json ? JSON.stringify(edited ? { ...result, hint: "edited text is only previewed: save it and confirm with --body <file> and this fingerprint" } : result) : renderPromote(result, text, ctx, !!edited), code: result.ok ? 0 : 1 };
|
|
77
79
|
}
|
package/src/read-commands.ts
CHANGED
|
@@ -1,8 +1,12 @@
|
|
|
1
1
|
import { loadRegistry } from "./registry.ts";
|
|
2
2
|
import { VaultIndex, MAX_NOTE_BYTES } from "./vault-index.ts";
|
|
3
|
+
import { PLAIN, type TextOptions } from "./text-output.ts";
|
|
4
|
+
import { linksText, rebuildText, searchText, showText } from "./read-output.ts";
|
|
5
|
+
import type { NoteReadResult, SearchResult } from "./vault-index.ts";
|
|
6
|
+
import type { ResolvedLink } from "./links.ts";
|
|
3
7
|
const READ_COMMANDS = new Set(["rebuild", "search", "show", "links"]);
|
|
4
8
|
export function isReadCommand(command: string): boolean { return READ_COMMANDS.has(command); }
|
|
5
|
-
export function runReadCommand(command: string, args: string[], home: string): { text: string; code: number } {
|
|
9
|
+
export function runReadCommand(command: string, args: string[], home: string, text: TextOptions = PLAIN): { text: string; code: number } {
|
|
6
10
|
const options: Record<string, string | boolean> = {}, positional: string[] = [];
|
|
7
11
|
const allowed = command === "search" ? ["--limit", "--type", "--domain"] : command === "show" ? ["--max-bytes", "--section", "--offset"] : command === "links" ? ["--limit"] : [];
|
|
8
12
|
for (let i = 0; i < args.length; i++) {
|
|
@@ -39,5 +43,11 @@ export function runReadCommand(command: string, args: string[], home: string): {
|
|
|
39
43
|
else if (command === "links") result = index.links(positional[1]!, limit);
|
|
40
44
|
else throw new Error("unknown read command");
|
|
41
45
|
} finally { index.close(); }
|
|
42
|
-
|
|
46
|
+
if (options["--json"]) return { text: JSON.stringify(result), code: 0 };
|
|
47
|
+
const vaultId = vault.id, target = positional[1]!;
|
|
48
|
+
const out = command === "rebuild" ? rebuildText(result as Parameters<typeof rebuildText>[0], text)
|
|
49
|
+
: command === "search" ? searchText(result as SearchResult[], text, { vault: vaultId, query: target, limit: limit ?? 50, type: options["--type"] as string | undefined, domain: options["--domain"] as string | undefined })
|
|
50
|
+
: command === "show" ? showText(result as NoteReadResult, text, { vault: vaultId, target, maxBytes })
|
|
51
|
+
: linksText(result as ResolvedLink[], text, { vault: vaultId, target, limit: limit ?? 50 });
|
|
52
|
+
return { text: out, code: 0 };
|
|
43
53
|
}
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Text views for the read, log and analysis commands (#114). Each renderer is pure, takes the same result the
|
|
3
|
+
* command prints with `--json`, and never shows more than that result carries.
|
|
4
|
+
*/
|
|
5
|
+
import type { SearchResult, NoteReadResult } from "./vault-index.ts";
|
|
6
|
+
import type { ResolvedLink } from "./links.ts";
|
|
7
|
+
import type { LogReadResult, LogReceipt } from "./log-types.ts";
|
|
8
|
+
import type { LintCode, LintReport } from "./analysis-types.ts";
|
|
9
|
+
import type { GraphNeighborhood } from "./vault-graph.ts";
|
|
10
|
+
import type { WriteIssue, WriteReceipt } from "./write-types.ts";
|
|
11
|
+
import { blocks, clean, fields, heading, issueTable, nextCommand, paint, paragraph, plural, shellWord, table, tone, type TextOptions, stripTerminal } from "./text-output.ts";
|
|
12
|
+
|
|
13
|
+
const command = (...words: string[]) => ["vmem", ...words].map(shellWord).join(" ");
|
|
14
|
+
|
|
15
|
+
export function searchText(hits: SearchResult[], o: TextOptions, c: { vault: string; query: string; limit: number; type?: string; domain?: string }): string {
|
|
16
|
+
const count = `${plural(hits.length, "result")} for ${JSON.stringify(clean(c.query))}`;
|
|
17
|
+
if (!hits.length) return count;
|
|
18
|
+
// Rows stay on one line so each snippet sits under its own hit.
|
|
19
|
+
const rows = table(["PATH", "TITLE", "TYPE"], hits.map(h => [h.path, h.title, h.type]), { ...o, columns: undefined }).split("\n");
|
|
20
|
+
const list = [rows[0]!, ...hits.flatMap((h, i) => [rows[i + 1]!, ...(stripTerminal(h.snippet).trim() ? [paragraph(stripTerminal(h.snippet).trim(), o, "muted", " ")] : [])])].join("\n");
|
|
21
|
+
const filters = [...(c.type ? ["--type", c.type] : []), ...(c.domain ? ["--domain", c.domain] : [])];
|
|
22
|
+
const more = hits.length >= c.limit && c.limit < 500 ? nextCommand("next", command("search", c.vault, c.query, ...filters, "--limit", String(Math.min(500, c.limit * 2))), o) : undefined;
|
|
23
|
+
return blocks(list, [count, more].filter(Boolean).join("\n"));
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export function showText(r: NoteReadResult, o: TextOptions, c: { vault: string; target: string; maxBytes?: number }): string {
|
|
27
|
+
const head = [heading(r.path, o), fields([["section", r.section], ["sha256", r.hash.slice(0, 12)], ["bytes", Buffer.byteLength(r.content)], ["offset", r.offset]], o)].join("\n");
|
|
28
|
+
if (!r.truncated) return blocks(head, stripTerminal(r.content).replace(/\n+$/, ""));
|
|
29
|
+
const words = ["show", c.vault, c.target, ...(r.section ? ["--section", r.section] : []), ...(c.maxBytes !== undefined ? ["--max-bytes", String(c.maxBytes)] : []), "--offset", String(r.nextOffset)];
|
|
30
|
+
const tail = [paint("truncated", "warn", o), ...(r.nextOffset !== undefined ? [nextCommand("next", command(...words), o)] : [])];
|
|
31
|
+
const headings = r.headings?.length ? ["H2 headings (read one with --section):", ...r.headings.map(h => ` ${clean(h)}`), ...(r.headingsTruncated ? [paint(" ... more headings", "muted", o)] : [])].join("\n") : undefined;
|
|
32
|
+
return blocks(head, stripTerminal(r.content).replace(/\n+$/, ""), tail.join("\n"), headings);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function linksText(links: ResolvedLink[], o: TextOptions, c: { vault: string; target: string; limit: number }): string {
|
|
36
|
+
const from = links[0]?.source ?? c.target;
|
|
37
|
+
const count = `${plural(links.length, "link")} from ${clean(from)}`;
|
|
38
|
+
if (!links.length) return count;
|
|
39
|
+
const target = (l: ResolvedLink) => l.target + (l.heading !== null ? `#${l.heading}` : "") + (l.block !== null ? `#^${l.block}` : "");
|
|
40
|
+
const rows = links.map(l => [target(l), l.resolved ?? tone(l.reason ?? "unresolved", "warn"), l.line]);
|
|
41
|
+
const more = links.length >= c.limit && c.limit < 500 ? nextCommand("next", command("links", c.vault, c.target, "--limit", String(Math.min(500, c.limit * 2))), o) : undefined;
|
|
42
|
+
return blocks(heading("OUT", o) + "\n" + table(["TARGET", "RESOLVED", "LINE"], rows, o), [count, more].filter(Boolean).join("\n"));
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export function rebuildText(r: { vault: string; notes: number; changed: number; removed: number; skipped?: string[] }, _o: TextOptions): string {
|
|
46
|
+
return `rebuilt ${clean(r.vault)}: ${plural(r.notes, "note")}, ${r.changed} changed, ${r.removed} removed${r.skipped?.length ? `, ${r.skipped.length} skipped` : ""}`;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
const warnings = (list: string[], o: TextOptions) => list.length ? list.map(w => paint(`warning: ${clean(w)}`, "warn", o)).join("\n") : undefined;
|
|
50
|
+
export function logReadText(r: LogReadResult, o: TextOptions, c: { command: "tail" | "grep"; vault: string; pattern?: string; limit: number; type?: string }): string {
|
|
51
|
+
if (!r.ok) return blocks(paint(`log ${c.command}: not read`, "fail", o), issueTable(r.issues, o), warnings(r.warnings, o));
|
|
52
|
+
const count = `${plural(r.lines.length, "line")}${r.dataLines !== null ? ` (log has ${r.dataLines})` : ""}`;
|
|
53
|
+
const words = ["log", c.command, c.vault, ...(c.pattern !== undefined ? [c.pattern] : []), ...(c.type ? ["--type", c.type] : []), "--limit", String(Math.min(200, c.limit * 2))];
|
|
54
|
+
const more = r.lines.length >= c.limit && c.limit < 200 ? nextCommand("next", command(...words), o) : undefined;
|
|
55
|
+
return blocks(r.lines.length ? r.lines.map(clean).join("\n") : undefined, [count, more].filter(Boolean).join("\n"), warnings(r.warnings, o), issueTable(r.issues, o));
|
|
56
|
+
}
|
|
57
|
+
export function logAppendText(r: LogReceipt, o: TextOptions, c: { vault: string; type: string }): string {
|
|
58
|
+
const line = r.ok && r.appended ? paint(`appended ${clean(c.type)} to the ${clean(c.vault)} log${r.bytesWritten ? ` (${plural(r.bytesWritten, "byte")})` : ""}`, "ok", o)
|
|
59
|
+
: paint(`log append: ${clean(c.type)} not appended${r.rolledBack ? " (rolled back)" : ""}`, "fail", o);
|
|
60
|
+
return blocks(line, issueTable(r.issues, o));
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
const LEVELS: Record<LintCode, "error" | "warn"> = { L01: "error", L02: "error", L03: "warn", L09: "warn", L10: "warn", L11: "warn", L12: "warn", L13: "error", L14: "warn" };
|
|
64
|
+
const verdict = (r: { errors: number; warnings: number; summary: string }, o: TextOptions) => paint(clean(r.summary), r.errors ? "fail" : r.warnings ? "warn" : "ok", o);
|
|
65
|
+
export function lintText(d: { report: LintReport; notes: number; titles: Record<LintCode, string>; info: Partial<Record<LintCode, string>> }, o: TextOptions, c: { vault: string; note?: string }): string {
|
|
66
|
+
const rows = (Object.keys(d.report.findings) as LintCode[]).flatMap(code => {
|
|
67
|
+
const check = d.titles[code].replace(" — ", " "), found = d.report.findings[code];
|
|
68
|
+
return [...(found.length ? found.map(f => [tone(LEVELS[code], LEVELS[code] === "error" ? "fail" : "warn"), check, f]) : [[tone("ok", "ok"), check, "위반 없음"]]),
|
|
69
|
+
...(d.info[code] ? [[tone("info", "muted"), check, d.info[code]]] : [])];
|
|
70
|
+
});
|
|
71
|
+
return blocks(heading(`lint ${c.vault}${c.note ? ` ${c.note}` : ""}: ${plural(d.notes, "note")}`, o), table(["LEVEL", "CHECK", "FINDING"], rows, o), verdict(d.report, o));
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** `lint --write` and `graph build`: what was written or would be, then issues and the log event. */
|
|
75
|
+
export function analysisWriteText(r: { ok: boolean; applied: boolean; summary: unknown; paths: string[]; receipts: WriteReceipt[]; log?: LogReceipt }, o: TextOptions, c: { kind: "lint" | "graph"; dryRun: boolean }): string {
|
|
76
|
+
const verb = c.dryRun && r.ok ? "would write" : r.applied ? "wrote" : "did not write";
|
|
77
|
+
const line = paint(`${c.kind === "lint" ? "lint" : "graph build"}: ${verb} ${plural(r.paths.length, "report")}`, r.ok ? "ok" : "fail", o);
|
|
78
|
+
const s = (r.summary ?? {}) as Record<string, unknown>;
|
|
79
|
+
const counts = c.kind === "lint" ? verdict(s as { errors: number; warnings: number; summary: string }, o)
|
|
80
|
+
: fields((["nodes", "edges", "communities", "work_docs"] as const).map(k => [k.replace("_", " "), typeof s[k] === "number" ? s[k] : undefined]), o);
|
|
81
|
+
const issues: WriteIssue[] = [...r.receipts.flatMap(x => x.issues), ...(r.log?.issues ?? [])];
|
|
82
|
+
const logged = r.log ? (r.log.ok ? `logged ${c.kind === "lint" ? "LINT" : "GRAPH"} event` : paint("log event not appended", "fail", o)) : undefined;
|
|
83
|
+
return blocks(line, r.paths.map(p => ` ${clean(p)}`).join("\n"), counts, issueTable(issues, o), logged);
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
export function neighborsText(r: GraphNeighborhood, o: TextOptions, c: { vault: string; limit: number; relation?: string }): string {
|
|
87
|
+
// Hops and relations follow from the returned edges: every selected node's nearer neighbour is selected too.
|
|
88
|
+
const hops = new Map([[r.start, 0]]), queue = [r.start];
|
|
89
|
+
for (let i = 0; i < queue.length; i++) for (const e of r.edges) {
|
|
90
|
+
const other = e.source === queue[i] ? e.target : e.target === queue[i] ? e.source : undefined;
|
|
91
|
+
if (other !== undefined && !hops.has(other)) { hops.set(other, hops.get(queue[i]!)! + 1); queue.push(other); }
|
|
92
|
+
}
|
|
93
|
+
const relation = (id: string) => [...new Set(r.edges.filter(e => (e.source === id && hops.get(e.target) === hops.get(id)! - 1) || (e.target === id && hops.get(e.source) === hops.get(id)! - 1)).map(e => e.relation === "wiki_link" ? e.rel ?? e.relation : e.relation))].join(",");
|
|
94
|
+
const nodes = r.nodes.filter(n => n.id !== r.start).sort((a, b) => (hops.get(a.id) ?? 9) - (hops.get(b.id) ?? 9));
|
|
95
|
+
const count = `${plural(nodes.length, "neighbour")} of ${clean(r.start)} within ${plural(r.hops, "hop")}`;
|
|
96
|
+
const more = r.truncated && c.limit < 500 ? nextCommand("next", command("graph", "neighbors", c.vault, r.start, "--hops", String(r.hops), "--limit", String(Math.min(500, c.limit * 2)), ...(c.relation ? ["--relation", c.relation] : [])), o) : undefined;
|
|
97
|
+
if (!nodes.length) return [count, more].filter(Boolean).join("\n");
|
|
98
|
+
return blocks(table(["NOTE", "HOPS", "RELATION", "TITLE"], nodes.map(n => [n.id, hops.get(n.id), relation(n.id), n.label]), o), [count, more].filter(Boolean).join("\n"));
|
|
99
|
+
}
|
package/src/registry.ts
CHANGED
|
@@ -4,7 +4,7 @@ import { realPath, memoryGitArgv, memoryGitEnv } from "./platform.ts";
|
|
|
4
4
|
import { hostname } from "node:os";
|
|
5
5
|
import { join } from "node:path";
|
|
6
6
|
import { randomUUID } from "node:crypto";
|
|
7
|
-
import { CONFIG_FILE, MAX_CONFIG_BYTES, parseConfig, parsePii, parseVault, parseSpec, piiExtensions, readConfig, type VaultSpec, type SpecSourceSpec, type VmemConfig } from "./config.ts";
|
|
7
|
+
import { CONFIG_FILE, MAX_CONFIG_BYTES, effectiveDomains, parseConfig, parsePii, parseVault, parseSpec, piiExtensions, readConfig, type VaultSpec, type SpecSourceSpec, type VmemConfig } from "./config.ts";
|
|
8
8
|
import { loosenedCells, piiPolicy, piiShorthand } from "./pii.ts";
|
|
9
9
|
export const LOCK_FILE = "config.lock";
|
|
10
10
|
const TEMP = /^\.config-[0-9a-f-]{36}\.tmp$/;
|
|
@@ -44,6 +44,7 @@ function mutate<T>(home: string, update: (config: VmemConfig) => T): T {
|
|
|
44
44
|
writeFileSync(lockFd, JSON.stringify(owner) + "\n");
|
|
45
45
|
const config = loadRegistry(home), result = update(config);
|
|
46
46
|
if (config.specs !== undefined) config.version = Math.max(config.version ?? 1, 2);
|
|
47
|
+
if (config.vaults.some(vault => vault.domains !== undefined)) config.version = Math.max(config.version ?? 1, 3);
|
|
47
48
|
parseConfig(config);
|
|
48
49
|
const text = JSON.stringify(config, null, 2) + "\n";
|
|
49
50
|
if (Buffer.byteLength(text) > MAX_CONFIG_BYTES) throw new Error(`${join(home, CONFIG_FILE)}: serialized config exceeds 64 KiB`);
|
|
@@ -194,7 +195,7 @@ export function setVaultPii(home: string, id: string, value: unknown, confirm =
|
|
|
194
195
|
export function registryStatus(home: string) {
|
|
195
196
|
const config = loadRegistry(home);
|
|
196
197
|
return config.vaults.map(vault => {
|
|
197
|
-
const base = { ...vault, pii: effectivePii(vault), piiPolicy: piiPolicy(vault) };
|
|
198
|
+
const base = { ...vault, domains: effectiveDomains(vault), pii: effectivePii(vault), piiPolicy: piiPolicy(vault) };
|
|
198
199
|
try {
|
|
199
200
|
const root = realpathSync(vault.path), notes = join(root, "notes");
|
|
200
201
|
if (root !== vault.path || realpathSync(notes) !== notes || !statSync(notes).isDirectory()) throw new Error("changed");
|
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
|
+
}
|