@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/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, `'"'"'`)}'`;
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
/** One read-only inbox source. Runs off the request thread, with a parent-enforced deadline. */
|
|
2
|
+
import type { InboxItem } from "@staix/agent-console/contract";
|
|
3
|
+
import { analysisInput } from "../analysis-input.ts";
|
|
4
|
+
import { listPromotionCandidates } from "../promote.ts";
|
|
5
|
+
import { loadRegistry } from "../registry.ts";
|
|
6
|
+
import type { VaultSpec } from "../config.ts";
|
|
7
|
+
import { isDenied } from "../platform.ts";
|
|
8
|
+
import { localSyncPending, STAGED_DESCRIPTION } from "../sync.ts";
|
|
9
|
+
import { boundInbox, type InboxRows } from "./inbox.ts";
|
|
10
|
+
import { lintVault } from "../vault-lint.ts";
|
|
11
|
+
|
|
12
|
+
export type InboxSource = { kind: "candidates" } | { kind: "lint" | "sync"; vault: VaultSpec };
|
|
13
|
+
export async function collectInboxSource(home: string, source: InboxSource): Promise<InboxRows> {
|
|
14
|
+
const at = new Date().toISOString();
|
|
15
|
+
if (source.kind === "candidates") {
|
|
16
|
+
// Fetch one beyond the payload cap. The API limits per project and has no cheap total.
|
|
17
|
+
// `more` is "at least N more" when any project saturates: it cannot fall as candidates
|
|
18
|
+
// are added to the same population, and a single overflowing project never reports zero.
|
|
19
|
+
const { projects } = await listPromotionCandidates({ allProjects: true, limit: 51, piiPatterns: loadRegistry(home).piiPatterns });
|
|
20
|
+
const items: InboxItem[] = projects.flatMap(p => p.candidates.map(c => ({
|
|
21
|
+
id: `mem:${c.id}`, group: "candidate" as const, kind: "promotion", title: c.title ?? c.kind, detail: `${c.kind} memory to promote into a vault note`,
|
|
22
|
+
project: c.project, at: new Date(c.at).toISOString(), verbs: [],
|
|
23
|
+
link: { panel: "promote", params: { id: c.id, project: c.project } },
|
|
24
|
+
})));
|
|
25
|
+
return boundInbox(items, 0, projects.some(p => p.candidates.length === 51));
|
|
26
|
+
}
|
|
27
|
+
const v = source.vault;
|
|
28
|
+
if (source.kind === "lint") {
|
|
29
|
+
const report = lintVault(analysisInput(home, v.id, { expectedVault: v }).snapshot);
|
|
30
|
+
const items: InboxItem[] = [];
|
|
31
|
+
if (report.errors > 0) items.push({ id: `lint:${v.id}`, group: "alert", kind: "lint", title: `${report.errors} lint errors in ${v.id}`,
|
|
32
|
+
detail: report.summary, at, chip: { text: `${report.errors} errors`, tone: "err" }, verbs: [], link: { panel: "lint", params: { vault: v.id } } });
|
|
33
|
+
if (report.findings.L11?.length) items.push({ id: `stale:${v.id}`, group: "alert", kind: "lint", title: `Graph report is stale in ${v.id}`,
|
|
34
|
+
detail: report.findings.L11[0]!, at, chip: { text: "stale", tone: "warn" }, verbs: [], link: { panel: "lint", params: { vault: v.id } } });
|
|
35
|
+
return boundInbox(items);
|
|
36
|
+
}
|
|
37
|
+
const config = loadRegistry(home), spec = config.vaults.find(x => x.id === v.id);
|
|
38
|
+
if (!spec || JSON.stringify(spec) !== JSON.stringify(v)) throw new Error("vault binding changed; restart the console provider");
|
|
39
|
+
if (isDenied(spec.path, config.denyPaths)) throw new Error("vault path is denied; check its path policy in System");
|
|
40
|
+
const pending = localSyncPending(spec.path), count = pending.changed + pending.ahead;
|
|
41
|
+
return boundInbox(count > 0 ? [{ id: `sync:${v.id}`, group: "alert", kind: "sync", title: `${count} unsynced change${count === 1 ? "" : "s"} in ${v.id}`,
|
|
42
|
+
detail: [`${pending.changed} uncommitted path${pending.changed === 1 ? "" : "s"} to sync`,
|
|
43
|
+
...(pending.ignored ? [`${pending.ignored} other path${pending.ignored === 1 ? "" : "s"} outside ${STAGED_DESCRIPTION} not counted`] : []),
|
|
44
|
+
...(pending.upstream ? [`${pending.ahead} local commit${pending.ahead === 1 ? "" : "s"} ahead of upstream`] : [])].join("; "),
|
|
45
|
+
at, chip: { text: "sync pending", tone: "warn" }, verbs: [], link: { panel: "overview", params: { vault: v.id } } }] : []);
|
|
46
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { parentPort, workerData } from "node:worker_threads";
|
|
2
|
+
import { collectInboxSource } from "./inbox-source.ts";
|
|
3
|
+
|
|
4
|
+
try {
|
|
5
|
+
parentPort!.postMessage({ result: await collectInboxSource(workerData.home, workerData.source) });
|
|
6
|
+
} catch (error) {
|
|
7
|
+
parentPort!.postMessage({ error: error instanceof Error ? error.message : String(error) });
|
|
8
|
+
}
|
package/src/ui/inbox.ts
ADDED
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
import { Worker } from "node:worker_threads";
|
|
2
|
+
import type { InboxItem } from "@staix/agent-console/contract";
|
|
3
|
+
import type { VaultSpec } from "../config.ts";
|
|
4
|
+
import type { InboxSource } from "./inbox-source.ts";
|
|
5
|
+
|
|
6
|
+
const CACHE_MS = 60_000;
|
|
7
|
+
const FIRST_WAIT_MS = 700;
|
|
8
|
+
const SOURCE_MS = 30_000;
|
|
9
|
+
// agent-mem has no total-count API; a saturated candidate source can only report a lower bound.
|
|
10
|
+
export type InboxRows = { items: InboxItem[]; more: number; moreIsLowerBound?: boolean };
|
|
11
|
+
|
|
12
|
+
function readInboxRows(value: unknown): InboxRows {
|
|
13
|
+
if (!value || typeof value !== "object" || !("items" in value) || !Array.isArray(value.items)
|
|
14
|
+
|| !("more" in value) || typeof value.more !== "number" || !Number.isSafeInteger(value.more) || value.more < 0) {
|
|
15
|
+
throw new Error("inbox source returned no valid result; inspect System and restart the console provider");
|
|
16
|
+
}
|
|
17
|
+
return value as InboxRows;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** An explicit error is a failure even when its message is empty. */
|
|
21
|
+
export function readInboxWorkerMessage(message: unknown): InboxRows {
|
|
22
|
+
if (message && typeof message === "object" && "error" in message) {
|
|
23
|
+
throw new Error(typeof message.error === "string" && message.error ? message.error
|
|
24
|
+
: "inbox source failed without an error message; inspect System and retry");
|
|
25
|
+
}
|
|
26
|
+
return readInboxRows(message && typeof message === "object" && "result" in message ? message.result : undefined);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** Urgent rows precede candidates; newest candidates first. Never ship full lint reports or memory bodies. */
|
|
30
|
+
export function boundInbox(items: InboxItem[], more = 0, moreIsLowerBound = false): InboxRows {
|
|
31
|
+
const rank = (i: InboxItem) => {
|
|
32
|
+
if (i.chip?.tone === "err") return 0;
|
|
33
|
+
if (i.group === "alert") return 1;
|
|
34
|
+
return 2;
|
|
35
|
+
};
|
|
36
|
+
const clip = (value: string, limit: number) => {
|
|
37
|
+
let out = "", count = 0;
|
|
38
|
+
for (const point of value) { if (count++ === limit) break; out += point; }
|
|
39
|
+
return out;
|
|
40
|
+
};
|
|
41
|
+
const sorted = [...items].sort((a, b) => rank(a) - rank(b) || b.at.localeCompare(a.at) || a.id.localeCompare(b.id));
|
|
42
|
+
return { items: sorted.slice(0, 50).map(i => ({ ...i, title: clip(i.title, 160), ...(i.detail ? { detail: clip(i.detail, 240) } : {}) })),
|
|
43
|
+
more: more + Math.max(0, items.length - 50), ...(moreIsLowerBound ? { moreIsLowerBound: true } : {}) };
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** Workers isolate synchronous lint, SQLite and Git from requests. The deadline initiates termination;
|
|
47
|
+
* shutdown can still wait for a blocking native call, so the queue waits before starting another worker. */
|
|
48
|
+
export function runInboxSource(home: string, source: InboxSource): { result: Promise<InboxRows>; cancel: () => void } {
|
|
49
|
+
const panel = { candidates: "Promote", lint: "Lint", sync: "Overview" }[source.kind];
|
|
50
|
+
const worker = new Worker(new URL("./inbox-worker.ts", import.meta.url), { workerData: { home, source }, env: { ...process.env } });
|
|
51
|
+
let cancel = () => {};
|
|
52
|
+
const result = new Promise<InboxRows>((resolve, reject) => {
|
|
53
|
+
let settled = false;
|
|
54
|
+
const finish = (error?: Error, rows?: InboxRows) => {
|
|
55
|
+
if (settled) return;
|
|
56
|
+
settled = true; clearTimeout(timer);
|
|
57
|
+
void worker.terminate().then(() => {
|
|
58
|
+
if (error) reject(error); else resolve(rows!);
|
|
59
|
+
}, failure => reject(failure));
|
|
60
|
+
};
|
|
61
|
+
const timer = setTimeout(() => finish(new Error(`inbox ${source.kind} timed out after 30 s; inspect ${panel} and System, then retry`)), SOURCE_MS);
|
|
62
|
+
cancel = () => finish(new Error("inbox closed"));
|
|
63
|
+
worker.once("message", (message: unknown) => {
|
|
64
|
+
try { finish(undefined, readInboxWorkerMessage(message)); }
|
|
65
|
+
catch (error) { finish(error instanceof Error ? error : new Error(String(error))); }
|
|
66
|
+
});
|
|
67
|
+
worker.once("error", error => finish(error instanceof Error ? error : new Error(String(error))));
|
|
68
|
+
worker.once("exit", code => finish(new Error(`inbox worker exited (${code}); inspect System and restart the console provider`)));
|
|
69
|
+
});
|
|
70
|
+
return { result, cancel: () => cancel() };
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
type Runner = typeof runInboxSource;
|
|
74
|
+
export function createInboxSnapshot(home: string, vaults: VaultSpec[], log: (message: string) => void, run: Runner = runInboxSource) {
|
|
75
|
+
const sources: InboxSource[] = [...vaults.filter(v => v.kind === "org").map(vault => ({ kind: "sync" as const, vault })),
|
|
76
|
+
...vaults.filter(v => v.kind === "personal").map(vault => ({ kind: "lint" as const, vault })), { kind: "candidates" }];
|
|
77
|
+
const rows = new Map<number, InboxRows>(), firstSeen = new Map<string, string>();
|
|
78
|
+
let cached: InboxRows | undefined, flight: Promise<void> | undefined, at = -Infinity, revision = 0, closed = false;
|
|
79
|
+
let cancel: (() => void) | undefined;
|
|
80
|
+
const statusAt = new Date().toISOString();
|
|
81
|
+
const status = (unavailable: boolean): InboxRows => ({ items: [{
|
|
82
|
+
id: unavailable ? "inbox:unavailable" : "inbox:refresh", group: "alert", kind: "status",
|
|
83
|
+
title: unavailable ? "Vault inbox is unavailable" : "Vault inbox is refreshing",
|
|
84
|
+
detail: unavailable ? "Inspect System, then retry." : "The first collection is running; check again shortly.",
|
|
85
|
+
at: statusAt, verbs: [], link: { panel: "overview" },
|
|
86
|
+
}], more: 0 });
|
|
87
|
+
function refresh() {
|
|
88
|
+
if (closed || flight || Date.now() - at < CACHE_MS) return;
|
|
89
|
+
const started = revision;
|
|
90
|
+
flight = (async () => {
|
|
91
|
+
// One worker at a time, including failed sources. A source's deadline covers its entire expensive step.
|
|
92
|
+
for (const [index, source] of sources.entries()) {
|
|
93
|
+
if (closed) return;
|
|
94
|
+
try {
|
|
95
|
+
const job = run(home, source); cancel = job.cancel;
|
|
96
|
+
rows.set(index, readInboxRows(await job.result));
|
|
97
|
+
} catch (error) {
|
|
98
|
+
if (!closed) log(`vmem: ${source.kind === "sync" ? "sync pending" : source.kind}${"vault" in source ? ` ${source.vault.id}` : ""} failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
99
|
+
} finally { cancel = undefined; }
|
|
100
|
+
}
|
|
101
|
+
if (closed) return;
|
|
102
|
+
const all = [...rows.values()].flatMap(r => r.items);
|
|
103
|
+
for (const item of all) if (item.group === "alert") {
|
|
104
|
+
item.at = firstSeen.get(item.id) ?? item.at; firstSeen.set(item.id, item.at);
|
|
105
|
+
}
|
|
106
|
+
const ids = new Set(all.map(i => i.id));
|
|
107
|
+
for (const id of firstSeen.keys()) if (!ids.has(id)) firstSeen.delete(id);
|
|
108
|
+
cached = rows.size === 0 ? status(true) : boundInbox(all, [...rows.values()].reduce((n, r) => n + r.more, 0), [...rows.values()].some(r => r.moreIsLowerBound));
|
|
109
|
+
// An action during collection makes the next poll refresh again, without erasing the last rows.
|
|
110
|
+
at = started === revision ? Date.now() : -Infinity;
|
|
111
|
+
})().catch(error => {
|
|
112
|
+
// Warm snapshots do not await this promise. Never let a refresh failure escape to the console.
|
|
113
|
+
if (!closed) {
|
|
114
|
+
cached ??= status(true);
|
|
115
|
+
at = started === revision ? Date.now() : -Infinity;
|
|
116
|
+
try { log(`vmem: inbox refresh failed: ${error instanceof Error ? error.message : String(error)}; inspect System and retry`); }
|
|
117
|
+
catch { /* A failed log sink must not create another unhandled rejection. */ }
|
|
118
|
+
}
|
|
119
|
+
}).finally(() => { flight = undefined; });
|
|
120
|
+
}
|
|
121
|
+
return {
|
|
122
|
+
async snapshot(): Promise<InboxRows & { refreshing?: boolean }> {
|
|
123
|
+
refresh();
|
|
124
|
+
if (!cached && flight) {
|
|
125
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
126
|
+
await Promise.race([flight, new Promise<void>(resolve => { timer = setTimeout(resolve, FIRST_WAIT_MS); })]);
|
|
127
|
+
clearTimeout(timer);
|
|
128
|
+
}
|
|
129
|
+
return { ...(cached ?? status(false)), ...(flight ? { refreshing: true } : {}) };
|
|
130
|
+
},
|
|
131
|
+
invalidate() { revision++; at = -Infinity; },
|
|
132
|
+
async close() { closed = true; cancel?.(); await flight; },
|
|
133
|
+
};
|
|
134
|
+
}
|
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); }
|