@staix/vault-mem 0.9.1 → 0.10.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 +27 -0
- package/README.md +19 -6
- package/bin/vmem.js +2 -2
- package/package.json +2 -2
- package/src/analysis-commands.ts +24 -14
- package/src/analysis-input.ts +12 -0
- package/src/analysis-types.ts +5 -1
- package/src/assert-command.ts +48 -0
- package/src/assertion-exposure.ts +367 -0
- package/src/assertion-index.ts +86 -0
- package/src/assertion-policy.ts +63 -0
- package/src/assertion-read.ts +170 -0
- package/src/assertions-command.ts +123 -0
- package/src/assertions.ts +1013 -0
- package/src/cli-output.ts +9 -3
- package/src/cli.ts +44 -23
- package/src/commands-table.ts +16 -2
- package/src/evidence.ts +222 -0
- package/src/graph-evidence.ts +169 -0
- package/src/index.ts +14 -0
- package/src/links.ts +18 -0
- package/src/log-commands.ts +7 -7
- package/src/mcp-spec.ts +11 -11
- package/src/mcp-vault.ts +105 -6
- package/src/mcp.ts +4 -0
- package/src/org-commands.ts +5 -5
- package/src/org-promote.ts +9 -0
- package/src/promote-command.ts +6 -6
- package/src/proposal-commands.ts +100 -0
- package/src/proposal-provider.ts +335 -0
- package/src/proposal-storage.ts +334 -0
- package/src/proposals.ts +170 -0
- package/src/read-commands.ts +44 -12
- package/src/read-output.ts +42 -14
- package/src/skills-mine.ts +12 -7
- package/src/source-age.ts +131 -0
- package/src/spec-output.ts +14 -13
- package/src/sync.ts +14 -7
- package/src/text-output.ts +86 -21
- package/src/vault-brief.ts +8 -4
- package/src/vault-graph.ts +12 -3
- package/src/vault-history.ts +662 -0
- package/src/vault-index.ts +2 -0
- package/src/vault-lint.ts +15 -4
- package/src/write-commands.ts +18 -17
- package/src/write-output.ts +6 -6
- package/src/write-types.ts +1 -0
- package/src/write-validation.ts +3 -1
- package/src/writer.ts +257 -11
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
/** Verified, policy-screened assertion journal reads. */
|
|
2
|
+
import { spawnSync } from "node:child_process";
|
|
3
|
+
import { createHash } from "node:crypto";
|
|
4
|
+
import { closeSync, constants, fstatSync, lstatSync, openSync, readSync, realpathSync } from "node:fs";
|
|
5
|
+
import { join, resolve } from "node:path";
|
|
6
|
+
import { evaluateAssertions, readJournal, type AssertionQuery, type VerifiedJournal } from "./assertions.ts";
|
|
7
|
+
import { indexedJournal, rebuildAssertionIndex } from "./assertion-index.ts";
|
|
8
|
+
import { screenAssertion, type ScreenedAssertion } from "./assertion-policy.ts";
|
|
9
|
+
import { parseFrontmatter } from "./frontmatter.ts";
|
|
10
|
+
import { canonicalPath, isDenied, memoryGitArgv, memoryGitEnv } from "./platform.ts";
|
|
11
|
+
import { loadRegistry } from "./registry.ts";
|
|
12
|
+
import { MAX_NOTE_BYTES } from "./vault-index.ts";
|
|
13
|
+
import type { VaultSpec, VmemConfig } from "./config.ts";
|
|
14
|
+
import type { EvidenceReadBudget, EvidenceReads } from "./evidence.ts";
|
|
15
|
+
import { screenContent } from "./write-validation.ts";
|
|
16
|
+
|
|
17
|
+
export const ASSERTIONS_PAGE_LIMIT = 100;
|
|
18
|
+
// The transport refuses request IDs over 200 UTF-16 units; even JSON's six-byte escapes fit in this reserve.
|
|
19
|
+
const FRAME_LIMIT = 48 * 1024, FRAME_RESERVE = 2048;
|
|
20
|
+
export interface AssertionsReadRequest extends AssertionQuery { vault: string; limit?: number; cursor?: string }
|
|
21
|
+
export interface AssertionsReadOptions { env?: NodeJS.ProcessEnv }
|
|
22
|
+
export interface AssertionsReadResult {
|
|
23
|
+
schemaVersion: 1; basis: "assertion_journal"; vault: string; at: string | null;
|
|
24
|
+
asOf: ReturnType<typeof evaluateAssertions>["asOf"]; pin: ReturnType<typeof evaluateAssertions>["pin"];
|
|
25
|
+
coverage: ReturnType<typeof evaluateAssertions>["coverage"] & { unsynced: number | null; indexIssue?: string };
|
|
26
|
+
items: (ScreenedAssertion & { subjectNote?: { path?: string; status: "present" | "missing" | "superseded"; supersededBy?: unknown } })[];
|
|
27
|
+
overlaps?: (ReturnType<typeof evaluateAssertions>["overlaps"][number] & { size: number })[]; truncated: boolean; continuation?: string;
|
|
28
|
+
}
|
|
29
|
+
const fail = (message: string, code = "V04"): never => { throw Object.assign(new Error(message), { code }); };
|
|
30
|
+
const fits = (value: unknown) => Buffer.byteLength(JSON.stringify(JSON.stringify(value))) <= FRAME_LIMIT - FRAME_RESERVE;
|
|
31
|
+
|
|
32
|
+
/** A bounded Git status over assertion files only, after checking that Git will not run a clean filter. */
|
|
33
|
+
function unsynced(root: string, env: NodeJS.ProcessEnv): number | null {
|
|
34
|
+
const git = (args: string[], input?: Buffer) => {
|
|
35
|
+
const argv = memoryGitArgv(["-C", root, ...args]);
|
|
36
|
+
const safeEnv = memoryGitEnv({ ...env, GIT_OPTIONAL_LOCKS: "0", LC_ALL: "C" }, { repositoryIsolation: true, readOnlyDiagnostic: true });
|
|
37
|
+
safeEnv.GIT_LITERAL_PATHSPECS = "1";
|
|
38
|
+
return spawnSync(argv[0]!, argv.slice(1), { env: safeEnv, timeout: 5000, maxBuffer: 4 * 1024 * 1024, ...(input ? { input } : {}) });
|
|
39
|
+
};
|
|
40
|
+
const top = git(["rev-parse", "--show-toplevel"]);
|
|
41
|
+
if (top.status !== 0 || top.stdout.toString().trim() !== root) return null;
|
|
42
|
+
const listed = git(["ls-files", "-z", "--", "assertions"]);
|
|
43
|
+
if (listed.status !== 0) return null;
|
|
44
|
+
if (listed.stdout.length) {
|
|
45
|
+
const attrs = git(["check-attr", "-z", "--stdin", "filter"], listed.stdout);
|
|
46
|
+
if (attrs.status !== 0) return null;
|
|
47
|
+
const fields = attrs.stdout.toString().split("\0");
|
|
48
|
+
for (let i = 2; i < fields.length; i += 3) if (fields[i] && fields[i] !== "unspecified") return null;
|
|
49
|
+
}
|
|
50
|
+
const status = git(["status", "--porcelain=v1", "-z", "--untracked-files=all", "--", "assertions"]);
|
|
51
|
+
if (status.status !== 0) return null;
|
|
52
|
+
const records = status.stdout.toString().split("\0").filter(Boolean);
|
|
53
|
+
const changed = new Set<string>();
|
|
54
|
+
for (let i = 0; i < records.length; i++) {
|
|
55
|
+
const record = records[i]!, name = record.slice(3);
|
|
56
|
+
if (/^assertions\/[0-9a-f]{16}\.jsonl$/.test(name)) changed.add(name);
|
|
57
|
+
if (/[RC]/.test(record.slice(0, 2))) {
|
|
58
|
+
const prior = records[++i];
|
|
59
|
+
if (prior && /^assertions\/[0-9a-f]{16}\.jsonl$/.test(prior)) changed.add(prior);
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
return changed.size;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function noteStatus(vault: VaultSpec, note: string, config: VmemConfig, budget: EvidenceReadBudget): NonNullable<AssertionsReadResult["items"][number]["subjectNote"]> {
|
|
66
|
+
if (!/^notes\/[^/\\]+\.md$/.test(note) || note.includes("\0")) return { status: "missing" };
|
|
67
|
+
const deny = config.denyPaths ?? [];
|
|
68
|
+
const root = realpathSync(vault.path), dir = join(root, "notes"), file = join(root, note);
|
|
69
|
+
if (isDenied(canonicalPath(file), [...deny]) || isDenied(note, [...deny]) || screenContent(note, vault, config).some(issue => issue.severity === "error")) return { status: "missing" };
|
|
70
|
+
if (budget.remainingFiles <= 0 || budget.remainingBytes <= 0) fail("assertions: subject note read budget exceeded; lower the page limit", "V09");
|
|
71
|
+
budget.remainingFiles--;
|
|
72
|
+
try {
|
|
73
|
+
if (lstatSync(dir).isSymbolicLink() || !lstatSync(dir).isDirectory()) return { path: note, status: "missing" };
|
|
74
|
+
const fd = openSync(file, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
|
|
75
|
+
try {
|
|
76
|
+
const stat = fstatSync(fd);
|
|
77
|
+
if (!stat.isFile() || stat.size > MAX_NOTE_BYTES) return { path: note, status: "missing" };
|
|
78
|
+
if (stat.size > budget.remainingBytes) fail("assertions: subject note read budget exceeded; lower the page limit", "V09");
|
|
79
|
+
budget.remainingBytes -= stat.size;
|
|
80
|
+
const data = Buffer.alloc(stat.size); let offset = 0;
|
|
81
|
+
while (offset < data.length) { const n = readSync(fd, data, offset, data.length - offset, null); if (!n) break; offset += n; }
|
|
82
|
+
if (offset !== stat.size || fstatSync(fd).size !== stat.size) return { path: note, status: "missing" };
|
|
83
|
+
const frontmatter = parseFrontmatter(new TextDecoder("utf-8", { fatal: true }).decode(data)).data;
|
|
84
|
+
if (frontmatter.status !== "superseded") return { path: note, status: "present" };
|
|
85
|
+
const target = frontmatter.superseded_by;
|
|
86
|
+
if (typeof target !== "string" || Buffer.byteLength(target) > 1024 || screenContent(target, vault, config).some(issue => issue.severity === "error")) return { path: note, status: "superseded" };
|
|
87
|
+
const stem = target.replace(/^\[\[/, "").replace(/\]\]$/, "").replace(/^notes\//, "").replace(/\.md$/, "");
|
|
88
|
+
if (!stem || /[/\\|#\0]/.test(stem) || isDenied(target, [...deny]) || isDenied(canonicalPath(join(dir, `${stem}.md`)), [...deny])) return { path: note, status: "superseded" };
|
|
89
|
+
return { path: note, status: "superseded", supersededBy: target };
|
|
90
|
+
} finally { closeSync(fd); }
|
|
91
|
+
} catch (error) { if ((error as { code?: string }).code === "V09") throw error; return { path: note, status: "missing" }; }
|
|
92
|
+
}
|
|
93
|
+
function declaredNotes(journal: VerifiedJournal, cutoff: ReturnType<typeof evaluateAssertions>["asOf"]): Map<string, string | null> {
|
|
94
|
+
const result = new Map<string, string | null>();
|
|
95
|
+
const entries = journal.segments.flatMap(segment => segment.entries.filter(entry => entry.op === "subject"));
|
|
96
|
+
entries.sort((a, b) => a.recorded_at < b.recorded_at ? -1 : a.recorded_at > b.recorded_at ? 1 : a.seg < b.seg ? -1 : a.seg > b.seg ? 1 : a.seq - b.seq);
|
|
97
|
+
for (const entry of entries) {
|
|
98
|
+
if (cutoff && (cutoff.cutoffInclusive ? entry.recorded_at > cutoff.cutoff : entry.recorded_at >= cutoff.cutoff)) continue;
|
|
99
|
+
const subject = entry.payload?.subject;
|
|
100
|
+
if (typeof subject === "string") result.set(subject, typeof entry.payload?.note === "string" ? entry.payload.note : null);
|
|
101
|
+
}
|
|
102
|
+
return result;
|
|
103
|
+
}
|
|
104
|
+
function fingerprint(value: unknown): string { return createHash("sha256").update(JSON.stringify(value)).digest("hex"); }
|
|
105
|
+
|
|
106
|
+
/** Freshly verifies the journal and applies current policy. The cache is disposable and is never a trust source. */
|
|
107
|
+
export function readAssertions(home: string, request: AssertionsReadRequest, options: AssertionsReadOptions = {}): AssertionsReadResult {
|
|
108
|
+
const config = loadRegistry(home), vault = config.vaults.find(value => value.id === request.vault) ?? fail("assertions: unknown vault id; list registered vaults with vmem status");
|
|
109
|
+
const root = realpathSync(vault.path);
|
|
110
|
+
if (root !== resolve(vault.path)) fail("assertions: registered vault root changed; re-register the vault with vmem vaults add");
|
|
111
|
+
const limit = request.limit ?? 50;
|
|
112
|
+
if (!Number.isSafeInteger(limit) || limit < 1 || limit > ASSERTIONS_PAGE_LIMIT) fail("assertions: limit must be 1..100; choose a smaller page");
|
|
113
|
+
const journal = readJournal(root, config.denyPaths ?? []);
|
|
114
|
+
let indexed = journal, indexIssue: string | undefined;
|
|
115
|
+
try {
|
|
116
|
+
const index = rebuildAssertionIndex(home, root, journal, config.vaults.map(value => value.path));
|
|
117
|
+
indexed = indexedJournal(index, journal);
|
|
118
|
+
if (indexed === journal) indexIssue = "assertion index could not be read or verified; check VMEM_HOME/indexes and retry";
|
|
119
|
+
} catch (error) {
|
|
120
|
+
const code = (error as NodeJS.ErrnoException)?.code;
|
|
121
|
+
const cause = typeof code === "string" && /^[A-Z0-9_]{1,24}$/.test(code) ? code : error instanceof Error && error.message.startsWith("assertion index: ") ? error.message.slice("assertion index: ".length).split(";")[0] : "cache unavailable";
|
|
122
|
+
indexIssue = `assertion index not refreshed (${cause}); check VMEM_HOME/indexes permissions and location`;
|
|
123
|
+
}
|
|
124
|
+
const query: AssertionQuery = { ...(request.subject !== undefined ? { subject: request.subject } : {}), ...(request.relation !== undefined ? { relation: request.relation } : {}), ...(request.at !== undefined ? { at: request.at } : {}), ...(request.asOf !== undefined ? { asOf: request.asOf } : {}), ...(request.history !== undefined ? { history: request.history } : {}) };
|
|
125
|
+
const answer = evaluateAssertions(indexed, query), binding = fingerprint({ root, query, pin: answer.pin, coverage: answer.coverage });
|
|
126
|
+
let offset = 0;
|
|
127
|
+
if (request.cursor !== undefined) {
|
|
128
|
+
try {
|
|
129
|
+
if (request.cursor.length > 512) throw new Error();
|
|
130
|
+
const cursor = JSON.parse(Buffer.from(request.cursor, "base64url").toString("utf8")) as { v: number; binding: string; offset: number };
|
|
131
|
+
if (cursor.v !== 1 || cursor.binding !== binding || !Number.isSafeInteger(cursor.offset) || cursor.offset < 0 || cursor.offset >= answer.items.length) throw new Error();
|
|
132
|
+
offset = cursor.offset;
|
|
133
|
+
} catch { fail("assertions: cursor is invalid or the journal changed; restart without --cursor"); }
|
|
134
|
+
}
|
|
135
|
+
const budget: EvidenceReadBudget = { remainingBytes: 64 * 1024 * 1024, remainingFiles: 1000 }, reads: EvidenceReads = new Map();
|
|
136
|
+
const subjectNotes = declaredNotes(journal, answer.asOf), notes = new Map<string, ReturnType<typeof noteStatus>>();
|
|
137
|
+
const output: AssertionsReadResult = { schemaVersion: 1, basis: "assertion_journal", vault: vault.id, at: answer.at, asOf: answer.asOf, pin: answer.pin,
|
|
138
|
+
coverage: { ...answer.coverage, unsynced: unsynced(root, options.env ?? process.env), ...(indexIssue ? { indexIssue } : {}) }, items: [], ...(request.at ? { overlaps: [] } : {}), truncated: false };
|
|
139
|
+
const overlapById = new Map<string, typeof answer.overlaps[number]>();
|
|
140
|
+
for (const group of answer.overlaps) for (const id of group.ids) overlapById.set(id, group);
|
|
141
|
+
const pageOverlaps = () => {
|
|
142
|
+
const groups = new Map<typeof answer.overlaps[number], string[]>();
|
|
143
|
+
for (const item of output.items) {
|
|
144
|
+
const group = overlapById.get(item.id);
|
|
145
|
+
if (!group) continue;
|
|
146
|
+
const ids = groups.get(group) ?? [];
|
|
147
|
+
if (!ids.includes(item.id)) ids.push(item.id);
|
|
148
|
+
groups.set(group, ids);
|
|
149
|
+
}
|
|
150
|
+
return [...groups].map(([group, ids]) => ({ subject: group.subject, relation: group.relation, ids, size: group.ids.length, ...(group.possible ? { possible: true as const } : {}) }));
|
|
151
|
+
};
|
|
152
|
+
const continuation = (next: number) => Buffer.from(JSON.stringify({ v: 1, binding, offset: next })).toString("base64url");
|
|
153
|
+
if (!fits(output)) fail("assertions: journal coverage exceeds the 48 KiB response bound; narrow the journal or inspect its segments", "V09");
|
|
154
|
+
for (let i = offset; i < answer.items.length && output.items.length < limit; i++) {
|
|
155
|
+
const item = answer.items[i]!, note = subjectNotes.get(item.subject);
|
|
156
|
+
let subjectNote: ReturnType<typeof noteStatus> | undefined;
|
|
157
|
+
if (note) { subjectNote = notes.get(note); if (!subjectNote) { subjectNote = noteStatus(vault, note, config, budget); notes.set(note, subjectNote); } }
|
|
158
|
+
output.items.push({ ...screenAssertion(item, vault, config, reads, budget), ...(subjectNote ? { subjectNote } : {}) });
|
|
159
|
+
if (output.overlaps) output.overlaps = pageOverlaps();
|
|
160
|
+
const hasMore = i + 1 < answer.items.length;
|
|
161
|
+
output.truncated = hasMore; if (hasMore) output.continuation = continuation(i + 1); else delete output.continuation;
|
|
162
|
+
if (!fits(output)) {
|
|
163
|
+
output.items.pop();
|
|
164
|
+
if (output.overlaps) output.overlaps = pageOverlaps();
|
|
165
|
+
if (!output.items.length) fail("assertions: one result exceeds the 48 KiB response bound; narrow its evidence or query", "V09");
|
|
166
|
+
output.truncated = true; output.continuation = continuation(i); break;
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
return output;
|
|
170
|
+
}
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
/** CLI surface for the shared assertion read provider. */
|
|
2
|
+
import { readAssertions } from "./assertion-read.ts";
|
|
3
|
+
import { scanAssertionExposure, writeReplaceFile, type ExposureReceipt } from "./assertion-exposure.ts";
|
|
4
|
+
import { purgeAssertions, type PurgeReceipt } from "./assertions.ts";
|
|
5
|
+
import { blocks, clean, heading, issueTable, nextCommand, paragraph, plural, status, table, PLAIN, UsageError, type TextOptions } from "./text-output.ts";
|
|
6
|
+
import { confirmCommand } from "./write-output.ts";
|
|
7
|
+
|
|
8
|
+
export function runAssertionsCommand(args: string[], home: string, env: NodeJS.ProcessEnv, text: TextOptions): { text: string; code: number } {
|
|
9
|
+
if (args[0] === "purge") return runPurgeCommand(args.slice(1), home, env, text);
|
|
10
|
+
if (args[0] === "exposure") return runExposureCommand(args.slice(1), home, env, text);
|
|
11
|
+
const positional: string[] = [], flags: Record<string, string | boolean> = {};
|
|
12
|
+
const values = ["--subject", "--relation", "--at", "--as-of", "--limit", "--cursor"];
|
|
13
|
+
for (let i = 0; i < args.length; i++) {
|
|
14
|
+
const word = args[i]!;
|
|
15
|
+
if (!word.startsWith("-")) { positional.push(word); continue; }
|
|
16
|
+
if (Object.hasOwn(flags, word) || ![...values, "--history", "--json"].includes(word)) throw new UsageError(`assertions: unknown or repeated option: ${word}`);
|
|
17
|
+
if (!values.includes(word)) { flags[word] = true; continue; }
|
|
18
|
+
const value = args[++i];
|
|
19
|
+
if (!value || value.startsWith("--")) throw new UsageError(`${word}: value required`);
|
|
20
|
+
flags[word] = value;
|
|
21
|
+
}
|
|
22
|
+
if (positional.length !== 1) throw new UsageError("assertions: requires one vault id; run vmem help assertions");
|
|
23
|
+
const limit = flags["--limit"];
|
|
24
|
+
if (typeof limit === "string" && !/^[1-9][0-9]*$/.test(limit)) throw new UsageError("--limit: expected an integer from 1 to 100");
|
|
25
|
+
const result = readAssertions(home, { vault: positional[0]!,
|
|
26
|
+
...(typeof flags["--subject"] === "string" ? { subject: flags["--subject"] } : {}),
|
|
27
|
+
...(typeof flags["--relation"] === "string" ? { relation: flags["--relation"] } : {}),
|
|
28
|
+
...(typeof flags["--at"] === "string" ? { at: flags["--at"] } : {}),
|
|
29
|
+
...(typeof flags["--as-of"] === "string" ? { asOf: flags["--as-of"] } : {}),
|
|
30
|
+
...(typeof limit === "string" ? { limit: Number(limit) } : {}),
|
|
31
|
+
...(typeof flags["--cursor"] === "string" ? { cursor: flags["--cursor"] } : {}),
|
|
32
|
+
...(flags["--history"] === true ? { history: true } : {}) }, { env });
|
|
33
|
+
if (flags["--json"]) return { text: JSON.stringify(result), code: 0 };
|
|
34
|
+
const rows = result.items.map(item => [clean(item.subject), clean(item.relation), item.answer ?? "-", typeof item.value === "string" ? clean(item.value) : item.value ? "withheld" : "-", item.id]);
|
|
35
|
+
return { text: blocks(heading(`Assertions in ${clean(result.vault)}`, text), table(["SUBJECT", "RELATION", "ANSWER", "VALUE", "ID"], rows, text),
|
|
36
|
+
result.truncated ? status("pending", `more results: rerun with --cursor ${result.continuation}`, text) : status("ok", `${result.items.length} assertion(s) shown`, text),
|
|
37
|
+
result.coverage.untrusted.length ? status("warn", `${result.coverage.untrusted.length} untrusted journal segment(s); inspect assertions/`, text) : undefined,
|
|
38
|
+
result.coverage.indexIssue ? status("warn", result.coverage.indexIssue, text) : undefined), code: 0 };
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** What a purge receipt means in words; `argv` is the command without `vmem`, so the confirm line is pasteable. */
|
|
42
|
+
export function purgeText(r: PurgeReceipt, o: TextOptions, c: { argv: string[]; vault: string }): string {
|
|
43
|
+
const entries = plural(r.entries.length, "entry", "entries"), segments = plural(r.segments.length, "segment");
|
|
44
|
+
const verdict = r.preview
|
|
45
|
+
? (r.ok ? status("ok", `purge preview for ${clean(r.assertion)} in ${clean(c.vault)}: ${entries} in ${segments} would keep their hashes and lose their payloads; nothing written`, o)
|
|
46
|
+
: status("fail", `purge refused for ${clean(c.vault)}; nothing written`, o))
|
|
47
|
+
: r.applied
|
|
48
|
+
? (r.ok ? status("ok", `purged ${clean(r.assertion)} in ${clean(c.vault)} at ${r.at}: ${entries} rewritten in ${segments}; payloads removed, chain unchanged`, o)
|
|
49
|
+
: status("fail", `${clean(r.assertion)} was rewritten in ${clean(c.vault)} but a later step failed; request a fresh preview and confirm again`, o))
|
|
50
|
+
: status("fail", `purge refused for ${clean(c.vault)}; nothing written`, o);
|
|
51
|
+
const rows = r.entries.length ? table(["SEGMENT", "SEQ", "OP", "HASH"], r.entries.map(e => [e.segment, e.seq, e.op, e.hash.slice(0, 12)]), o) : undefined;
|
|
52
|
+
const already = r.alreadyPurged ? paragraph(`${plural(r.alreadyPurged, "entry", "entries")} already carried a purge marker and were left as they are.`, o, "muted") : undefined;
|
|
53
|
+
const omitted = r.omitted ? paragraph(`${r.omitted} more ${r.omitted === 1 ? "entry is" : "entries are"} affected but not listed; confirm rewrites all of them.`, o, "muted") : undefined;
|
|
54
|
+
const recovery = r.recovery.length ? ["recovery:", ...r.recovery.map(note => ` - ${clean(note)}`)].join("\n") : undefined;
|
|
55
|
+
const confirm = r.preview && r.ok ? nextCommand("confirm", confirmCommand(["assertions", ...c.argv], r.fingerprint), o) : undefined;
|
|
56
|
+
const scope = r.applied ? paragraph("bytes in Git history, other clones or remotes are unchanged; erasing them needs a history rewrite outside vmem", o, "muted") : undefined;
|
|
57
|
+
return blocks(verdict, rows, already, omitted, recovery, issueTable(r.issues, o), scope, confirm);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** `vmem assertions purge <vault> <id> --reason TEXT [--confirm --fingerprint SHA] [--json]`. */
|
|
61
|
+
export function runPurgeCommand(args: string[], home: string, env: NodeJS.ProcessEnv = process.env, text: TextOptions = PLAIN): { text: string; code: number } {
|
|
62
|
+
const positional: string[] = [], flags: Record<string, string | boolean> = {};
|
|
63
|
+
const values = ["--reason", "--fingerprint"];
|
|
64
|
+
for (let i = 0; i < args.length; i++) {
|
|
65
|
+
const word = args[i]!;
|
|
66
|
+
if (!word.startsWith("-")) { positional.push(word); continue; }
|
|
67
|
+
if (Object.hasOwn(flags, word) || ![...values, "--confirm", "--json"].includes(word)) throw new UsageError(`assertions purge: unknown or repeated option: ${word}`);
|
|
68
|
+
if (!values.includes(word)) { flags[word] = true; continue; }
|
|
69
|
+
const value = args[++i];
|
|
70
|
+
if (value === undefined || value.startsWith("--")) throw new UsageError(`${word}: value required`);
|
|
71
|
+
flags[word] = value;
|
|
72
|
+
}
|
|
73
|
+
if (positional.length !== 2) throw new UsageError("assertions purge: requires a vault id and an assertion id; run vmem help assertions purge");
|
|
74
|
+
if (typeof flags["--reason"] !== "string") throw new UsageError("assertions purge: --reason TEXT is required; it stays in the journal, so keep it free of sensitive content");
|
|
75
|
+
if (flags["--confirm"] === true && typeof flags["--fingerprint"] !== "string") throw new UsageError("assertions purge: --confirm needs --fingerprint SHA from the preview");
|
|
76
|
+
if (flags["--confirm"] !== true && flags["--fingerprint"] !== undefined) throw new UsageError("assertions purge: --fingerprint applies only with --confirm; run the preview first");
|
|
77
|
+
const vault = positional[0]!, id = positional[1]!;
|
|
78
|
+
const receipt = purgeAssertions(home, { vault, id, reason: flags["--reason"], channel: "cli", ...(flags["--confirm"] === true ? { confirm: true } : {}), ...(typeof flags["--fingerprint"] === "string" ? { fingerprint: flags["--fingerprint"] } : {}) }, { env });
|
|
79
|
+
return { text: flags["--json"] ? JSON.stringify(receipt) : purgeText(receipt, text, { argv: ["purge", ...args.filter(word => word !== "--json")], vault }), code: receipt.ok ? 0 : 1 };
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** What an exposure receipt means in words; the scan prints position and hash, never payload text. */
|
|
83
|
+
export function exposureText(r: ExposureReceipt, o: TextOptions): string {
|
|
84
|
+
const scanned = `${plural(r.scanned.commits, "commit")}, ${plural(r.scanned.blobs, "blob")}, ${r.scanned.bytes} bytes`;
|
|
85
|
+
const verdict = r.clean === true ? status("ok", `${clean(r.vault)}: no purged payload is reachable in this repository's history (${scanned})`, o)
|
|
86
|
+
: r.clean === false ? status(r.exposed.length ? "fail" : "warn", r.exposed.length
|
|
87
|
+
? `${clean(r.vault)}: ${plural(r.exposed.length, "purged entry", "purged entries")} still hold a payload in reachable history (${scanned})`
|
|
88
|
+
: `${clean(r.vault)}: the scan is incomplete, so it is not reported clean (${scanned})`, o)
|
|
89
|
+
: status("unknown", `${clean(r.vault)}: the history scan could not run`, o);
|
|
90
|
+
const rows = r.exposed.length
|
|
91
|
+
? table(["ASSERTION", "SEGMENT", "SEQ", "COMMITS", "REFS", "HASH"], r.exposed.map(row => [row.assertion, row.segment, row.seq, row.commits.count, row.refs.length, row.hash.slice(0, 12)]), o)
|
|
92
|
+
: undefined;
|
|
93
|
+
const refs = r.refsOmitted ? paragraph("refs are omitted from this reply to stay inside the 48 KiB bound", o, "muted") : undefined;
|
|
94
|
+
const held = r.refsOmitted ? undefined : r.exposed.filter(row => row.refs.length);
|
|
95
|
+
const heldText = held && held.length ? ["held by:", ...held.map(row => ` - ${row.assertion} ${row.segment}:${row.seq}: ${row.refs.join(", ")}`)].join("\n") : undefined;
|
|
96
|
+
const omitted = r.omitted ? paragraph(`${r.omitted} more exposed ${r.omitted === 1 ? "entry is" : "entries are"} omitted from this reply to stay inside the 48 KiB bound`, o, "muted") : undefined;
|
|
97
|
+
const truncated = r.truncated ? status("warn", `partial scan: stopped at the ${r.truncated}; a partial scan is never reported clean`, o) : undefined;
|
|
98
|
+
const manual = r.exposed.filter(row => row.manual !== undefined);
|
|
99
|
+
const manualText = manual.length ? ["manual step:", ...manual.map(row => ` - ${row.assertion} ${row.segment}:${row.seq}: ${row.manual}`)].join("\n") : undefined;
|
|
100
|
+
const file = r.replaceFile ? paragraph(`replace file ${clean(r.replaceFile.path)}: ${plural(r.replaceFile.lines, "expression")}, ${r.replaceFile.unreplaceable} unreplaceable. ${r.replaceFile.delete}`, o, "warn") : undefined;
|
|
101
|
+
const issues = r.issues.length ? ["issues:", ...r.issues.map(item => ` - ${clean(item)}`)].join("\n") : undefined;
|
|
102
|
+
const scope = r.clean === false ? paragraph("vmem never runs the rewrite: git-filter-repo, the force push, reflog expire and gc stay with you; see docs/reference/writes.md", o, "muted") : undefined;
|
|
103
|
+
return blocks(verdict, rows, heldText, omitted, refs, truncated, manualText, file, issues, scope);
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** `vmem assertions exposure <vault> [<assertion-id>] [--replace-file PATH] [--json]`. */
|
|
107
|
+
export function runExposureCommand(args: string[], home: string, env: NodeJS.ProcessEnv = process.env, text: TextOptions = PLAIN): { text: string; code: number } {
|
|
108
|
+
const positional: string[] = [], flags: Record<string, string | boolean> = {};
|
|
109
|
+
const values = ["--replace-file"];
|
|
110
|
+
for (let i = 0; i < args.length; i++) {
|
|
111
|
+
const word = args[i]!;
|
|
112
|
+
if (!word.startsWith("-")) { positional.push(word); continue; }
|
|
113
|
+
if (Object.hasOwn(flags, word) || ![...values, "--json"].includes(word)) throw new UsageError(`assertions exposure: unknown or repeated option: ${word}`);
|
|
114
|
+
if (!values.includes(word)) { flags[word] = true; continue; }
|
|
115
|
+
const value = args[++i];
|
|
116
|
+
if (value === undefined || value.startsWith("--")) throw new UsageError(`${word}: value required`);
|
|
117
|
+
flags[word] = value;
|
|
118
|
+
}
|
|
119
|
+
if (positional.length < 1 || positional.length > 2) throw new UsageError("assertions exposure: requires a vault id and at most one assertion id; run vmem help assertions exposure");
|
|
120
|
+
const scan = scanAssertionExposure(home, { vault: positional[0]!, ...(positional[1] !== undefined ? { assertion: positional[1]! } : {}) }, { env });
|
|
121
|
+
if (typeof flags["--replace-file"] === "string") scan.receipt.replaceFile = writeReplaceFile(scan, flags["--replace-file"]);
|
|
122
|
+
return { text: flags["--json"] ? JSON.stringify(scan.receipt) : exposureText(scan.receipt, text), code: scan.receipt.clean === true ? 0 : 1 };
|
|
123
|
+
}
|