@staix/vault-mem 0.5.0 → 0.6.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.
Files changed (49) hide show
  1. package/CHANGELOG.md +66 -0
  2. package/README.md +140 -23
  3. package/package.json +5 -4
  4. package/src/amem/seam.ts +15 -6
  5. package/src/analysis-commands.ts +1 -1
  6. package/src/analysis-input.ts +24 -3
  7. package/src/analysis-reports.ts +1 -1
  8. package/src/analysis-types.ts +13 -1
  9. package/src/canon-tables.ts +190 -0
  10. package/src/cli-output.ts +15 -1
  11. package/src/cli.ts +1 -1
  12. package/src/commands-table.ts +6 -2
  13. package/src/config.ts +31 -3
  14. package/src/frontmatter.ts +10 -3
  15. package/src/links.ts +13 -1
  16. package/src/mcp-spec.ts +19 -11
  17. package/src/mcp-vault.ts +14 -9
  18. package/src/mcp.ts +4 -2
  19. package/src/org-promote.ts +29 -12
  20. package/src/promote.ts +24 -12
  21. package/src/read-commands.ts +1 -2
  22. package/src/read-output.ts +7 -5
  23. package/src/registry.ts +1 -0
  24. package/src/skills-mine.ts +5 -4
  25. package/src/spec-command-table.ts +10 -1
  26. package/src/spec-commands.ts +7 -3
  27. package/src/spec-gitlinks.ts +106 -0
  28. package/src/spec-output.ts +30 -0
  29. package/src/spec-source.ts +9 -3
  30. package/src/spec-validate.ts +6 -3
  31. package/src/spec-write.ts +469 -0
  32. package/src/ui/inbox-source.ts +46 -0
  33. package/src/ui/inbox-worker.ts +8 -0
  34. package/src/ui/inbox.ts +152 -0
  35. package/src/ui/panel.js +26 -5
  36. package/src/ui/plugin.ts +42 -65
  37. package/src/ui/snapshot-cache.ts +123 -0
  38. package/src/vault-index.ts +109 -19
  39. package/src/vault-lint.ts +53 -5
  40. package/src/vault-log.ts +3 -2
  41. package/src/vault-stats.ts +110 -5
  42. package/src/write-commands.ts +4 -3
  43. package/src/write-files.ts +63 -0
  44. package/src/write-operations.ts +175 -25
  45. package/src/write-output.ts +20 -9
  46. package/src/write-types.ts +8 -1
  47. package/src/write-validation.ts +46 -17
  48. package/src/writer.ts +137 -41
  49. package/src/yaml-quoted.ts +12 -2
@@ -0,0 +1,469 @@
1
+ import { capturePublicationPath, publishFile, cleanupOwnedFile, PublicationDrift } from "./write-files.ts";
2
+ import { createHash, randomUUID } from "node:crypto";
3
+ import { closeSync, constants, fstatSync, fchmodSync, fsyncSync, lstatSync, mkdirSync, openSync, readSync, realpathSync, rmdirSync, writeFileSync } from "node:fs";
4
+ import { basename, dirname, isAbsolute, join, relative, sep } from "node:path";
5
+ import { isDeepStrictEqual } from "node:util";
6
+ import type { SpecSourceSpec, VmemConfig } from "./config.ts";
7
+ import { emitFrontmatter, parseFrontmatter } from "./frontmatter.ts";
8
+ import { AGENT_MARKERS } from "./log-format.ts";
9
+ import { canonicalPath, isDenied } from "./platform.ts";
10
+ import { loadRegistry, syncDirectory } from "./registry.ts";
11
+ import { discoverSpecs, resolveSpecWorktree, MAX_SPEC_MARKDOWN_PATHS, type SpecCandidate, type SpecDocument, type SpecSnapshot } from "./spec-source.ts";
12
+ import { introducedSpecErrors, type SpecValidationIssue } from "./spec-validate.ts";
13
+ import { MAX_NOTE_BYTES } from "./vault-index.ts";
14
+ import { screenContent, screenMetadata } from "./write-validation.ts";
15
+ import { specGit } from "./spec-git.ts";
16
+ import { specGitlinkAncestors } from "./spec-gitlinks.ts";
17
+ import { buildSpecGraph, type SpecEdge, type SpecNode } from "./spec-graph.ts";
18
+
19
+ export const SPEC_UPDATE_SCALAR_FIELDS = ["title", "type", "status", "parent", "superseded-by", "verified-against"] as const;
20
+ export const SPEC_UPDATE_LIST_FIELDS = ["depends-on", "references", "implements", "covers", "tags", "paths"] as const;
21
+ export const SPEC_UPDATE_OPTIONAL_FIELDS = ["status", "parent", "superseded-by", "verified-against", ...SPEC_UPDATE_LIST_FIELDS] as const;
22
+ export interface SpecUpdateRequest {
23
+ id: string; source?: string; worktree?: string; expectedSha?: string;
24
+ set?: Record<string, string>; unset?: string[]; add?: Record<string, string[]>; remove?: Record<string, string[]>;
25
+ }
26
+ export interface SpecCreateRequest {
27
+ path: string; id: string; type: string; title: string; source?: string; worktree?: string;
28
+ status?: string; parent?: string; "superseded-by"?: string; "verified-against"?: string;
29
+ "depends-on"?: string[]; references?: string[]; implements?: string[]; covers?: string[]; tags?: string[]; paths?: string[];
30
+ }
31
+ export interface SpecDeleteRequest { id: string; source?: string; worktree?: string; confirm?: boolean; fingerprint?: string }
32
+ export interface SpecDeleteResult extends SpecWriteResult { preview?: boolean; fingerprint?: string; backlinks?: SpecEdge[]; children?: SpecNode[] }
33
+ interface SpecDeletePreview { preview: boolean; fingerprint: string; sha256: string; backlinks: SpecEdge[]; children: SpecNode[] }
34
+ export interface SpecWriteIssue { code: string; severity: "error" | "warning"; message: string; path?: string; target?: string; originalTarget?: string; field?: string }
35
+ export interface SpecWriteResult {
36
+ ok: boolean; changed: boolean; actor: "agent" | "person"; source?: string; worktree?: string; id?: string; path?: string; sha256?: string; issues: SpecWriteIssue[];
37
+ }
38
+ export interface SpecWriteOptions { env?: NodeJS.ProcessEnv; channel?: "cli" | "mcp"; binding?: SpecSourceSpec }
39
+ export interface SpecMutation { path: string; before: string | null; after: string | null; deletion?: SpecDeletePreview; expectedFingerprint?: string }
40
+ type SpecWriteOperation = "create" | "update" | "delete";
41
+ function retrySpecOperation(operation: SpecWriteOperation): string {
42
+ if (operation === "delete") return "request a fresh preview with vmem spec delete, review its backlinks and children, then confirm the delete with that fingerprint";
43
+ return operation === "create" ? "reread the source tree and retry the create" : "reread vmem spec get and retry the update with its sha256 (--expected-sha)";
44
+ }
45
+ const deletedSpecInspection = "inspect the deleted file's parent directory, and inspect the lock state under VMEM_HOME";
46
+ const createdSpecInspection = "inspect the created file and its parent directories, and inspect the lock state under VMEM_HOME";
47
+ function publishedSpecInspection(operation: SpecWriteOperation, changed: boolean): string | undefined {
48
+ if (!changed) return undefined;
49
+ return operation === "create" ? createdSpecInspection : operation === "delete" ? deletedSpecInspection : undefined;
50
+ }
51
+ const compare = (a: string, b: string) => a < b ? -1 : a > b ? 1 : 0;
52
+ const hash = (value: string) => createHash("sha256").update(value).digest("hex");
53
+ class Refusal extends Error {
54
+ constructor(readonly issues: SpecWriteIssue[]) { super(issues[0]?.message ?? "spec mutation refused; inspect the write issues before retrying"); }
55
+ }
56
+ function refuse(code: string, message: string, path?: string): never { throw new Refusal([{ code, severity: "error", message, ...(path === undefined ? {} : { path }) }]); }
57
+ function writeErrorCause(error: unknown): string {
58
+ const code = (error as NodeJS.ErrnoException | undefined)?.code;
59
+ return `${typeof code === "string" ? `${code}: ` : ""}${error instanceof Error ? error.message : String(error)}`;
60
+ }
61
+ const record = (value: unknown): value is Record<string, unknown> => !!value && typeof value === "object" && !Array.isArray(value) && [null, Object.prototype].includes(Object.getPrototypeOf(value));
62
+ const within = (root: string, file: string) => { const path = relative(root, file); return path === "" || !isAbsolute(path) && path !== ".." && !path.startsWith(`..${sep}`); };
63
+ const identity = (file: string) => { const stat = lstatSync(file, { bigint: true }); return `${stat.dev}:${stat.ino}`; };
64
+ function deniedSpecPath(file: string, denyPaths: string[]): boolean {
65
+ return isDenied(canonicalPath(file), denyPaths) || isDenied(file, denyPaths);
66
+ }
67
+
68
+ function pathParts(path: string, operation: SpecWriteOperation = "create"): string[] {
69
+ if (typeof path !== "string" || isAbsolute(path) || !path.endsWith(".md") || path.includes("\\") || /[\p{Cc}]/u.test(path) || path.split("/").some(part => !part || part === "." || part === ".." || part.toLowerCase() === ".git")) refuse("PATH", `spec path is not contained Markdown; use a relative .md path outside Git administrative directories${operation === "delete" ? `, then ${retrySpecOperation(operation)}` : ""}`, typeof path === "string" ? path : undefined);
70
+ return path.split("/");
71
+ }
72
+
73
+ /** Read without following links or accepting a torn/oversized file. Parent paths are checked before every write stage. */
74
+ function plainPath(root: string, path: string, denyPaths: string[] = [], operation: SpecWriteOperation = "update"): string {
75
+ pathParts(path, operation);
76
+ const next = operation === "delete" ? `, then ${retrySpecOperation(operation)}` : " and retry";
77
+ let file = root;
78
+ if (lstatSync(root).isSymbolicLink() || !lstatSync(root).isDirectory()) refuse("PATH", `worktree root changed; restore the original plain root${next}`, path);
79
+ for (const [index, part] of path.split("/").entries()) {
80
+ file = join(file, part); const stat = lstatSync(file);
81
+ if (stat.isSymbolicLink() || (index === path.split("/").length - 1 ? !stat.isFile() : !stat.isDirectory())) refuse("PATH", `spec path has a symlink or non-plain component; restore the plain in-worktree file${next}`, path);
82
+ }
83
+ if (!within(root, realpathSync(file)) || deniedSpecPath(file, denyPaths)) refuse("PATH", `spec path is denied or leaves the worktree; choose an allowed plain spec file${operation === "delete" ? next : ""}`, path);
84
+ return file;
85
+ }
86
+ function readBounded(file: string, path: string, operation: SpecWriteOperation): { source: string; mode: number; identity: string } {
87
+ const fd = openSync(file, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
88
+ try {
89
+ const before = fstatSync(fd, { bigint: true });
90
+ if (!before.isFile() || before.size > BigInt(MAX_NOTE_BYTES)) refuse("SIZE", `spec ${operation} input is not a bounded plain file; ${operation === "create" ? "reduce the metadata" : "split the file below the read limit"}, then ${retrySpecOperation(operation)}`, path);
91
+ const bytes = Buffer.alloc(Number(before.size) + 1); let size = 0;
92
+ while (size < bytes.length) { const n = readSync(fd, bytes, size, bytes.length - size, null); if (!n) break; size += n; }
93
+ const after = fstatSync(fd, { bigint: true }), named = lstatSync(file, { bigint: true });
94
+ if (named.dev !== after.dev || named.ino !== after.ino || before.dev !== after.dev || before.ino !== after.ino || before.size !== after.size || before.mtimeNs !== after.mtimeNs || before.ctimeNs !== after.ctimeNs || size !== Number(before.size)) refuse("DRIFT", `spec ${operation} input changed during its read; ${retrySpecOperation(operation)}`, path);
95
+ const buffer = bytes.subarray(0, size), source = buffer.toString("utf8");
96
+ if (!Buffer.from(source).equals(buffer)) refuse("ENCODING", `spec ${operation} input is not valid UTF-8; ${operation === "create" ? retrySpecOperation(operation) : `re-encode the file, then ${retrySpecOperation(operation)}`}`, path);
97
+ return { source, mode: Number(before.mode & 0o777n), identity: `${before.dev}:${before.ino}` };
98
+ } finally { closeSync(fd); }
99
+ }
100
+
101
+ function readPlain(root: string, path: string, denyPaths: string[], operation: SpecWriteOperation) { return readBounded(plainPath(root, path, denyPaths, operation), path, operation); }
102
+
103
+ /** Once per create stage; filesystem-only checks remain safe to repeat during mkdir. */
104
+ function guardCreateRepository(root: string, change: SpecMutation, denyPaths: string[], env: NodeJS.ProcessEnv): void {
105
+ if (change.before !== null) return;
106
+ const path = change.path, { deepest, parts } = createPath(root, path, denyPaths);
107
+ const ancestors = parts.slice(0, -1).map((_, index) => parts.slice(0, index + 1).join("/"));
108
+ if (ancestors.length) {
109
+ try {
110
+ if (specGitlinkAncestors(root, ancestors, env).matched) refuse("PATH", "spec path crosses or aliases a submodule gitlink; create the spec in that repository's own source", path);
111
+ } catch (error) {
112
+ if ((error as { code?: unknown })?.code === "LIMIT") refuse("LIMIT", (error as Error).message, path);
113
+ throw error;
114
+ }
115
+ }
116
+ const top = specGit(canonicalPath(deepest), ["rev-parse", "--show-toplevel"], { env }).stdout.toString("utf8").replace(/\r?\n$/, "");
117
+ if (canonicalPath(top) !== root) refuse("PATH", "spec path crosses into a nested repository; create the spec in that repository's own source", path);
118
+ if (specGit(root, ["check-ignore", "--quiet", "--no-index", "--", `./${path}`], { env, allowedExitCodes: [0, 1] }).status === 0) refuse("PATH", "spec path is git-ignored; choose a non-ignored path or adjust the ignore policy before retrying the create", path);
119
+ }
120
+
121
+ /** Missing parent directories are allowed; every existing component must be plain. Never follows a dangling link. */
122
+ function createPath(root: string, path: string, denyPaths: string[]): { file: string; deepest: string; parts: string[] } {
123
+ const parts = pathParts(path);
124
+ if (lstatSync(root).isSymbolicLink() || !lstatSync(root).isDirectory()) refuse("PATH", "worktree root changed; restore the original plain root and retry", path);
125
+ let file = root, deepest = root;
126
+ for (const [index, part] of parts.entries()) {
127
+ file = join(file, part);
128
+ let stat;
129
+ try { stat = lstatSync(file); }
130
+ catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; continue; }
131
+ if (stat.isSymbolicLink() || !stat.isDirectory() || index === parts.length - 1) refuse("PATH", "create requires an absent target and plain directory components; choose a new in-worktree path", path);
132
+ if (!within(root, realpathSync(file))) refuse("PATH", "spec parent leaves the worktree; choose a contained plain path", path);
133
+ deepest = file;
134
+ }
135
+ if (deniedSpecPath(file, denyPaths)) refuse("PATH", "spec create path is denied; choose an allowed path and retry the create", path);
136
+ return { file, deepest, parts };
137
+ }
138
+ function readMutation(root: string, change: SpecMutation, denyPaths: string[], operation: SpecWriteOperation): { source: string | null; mode: number; identity: string | null } {
139
+ if (change.before !== null) return readPlain(root, change.path, denyPaths, operation);
140
+ createPath(root, change.path, denyPaths);
141
+ return { source: null, mode: 0o666 & ~process.umask(), identity: null };
142
+ }
143
+ function ensureCreateParents(root: string, path: string, denyPaths: string[], owned: Map<string, string>): void {
144
+ let parent = root;
145
+ for (const part of pathParts(path).slice(0, -1)) {
146
+ createPath(root, path, denyPaths);
147
+ parent = join(parent, part);
148
+ try { mkdirSync(parent, { mode: 0o777 & ~process.umask() }); owned.set(parent, identity(parent)); }
149
+ catch (error) { if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error; }
150
+ }
151
+ createPath(root, path, denyPaths);
152
+ }
153
+ function prepareMutationTarget(root: string, change: SpecMutation, denyPaths: string[], owned: Map<string, string>): string {
154
+ if (change.before !== null) return plainPath(root, change.path, denyPaths);
155
+ ensureCreateParents(root, change.path, denyPaths, owned);
156
+ return createPath(root, change.path, denyPaths).file;
157
+ }
158
+ function checkExpectedSha(change: SpecMutation, expectedSha: string | undefined): void {
159
+ if (expectedSha !== undefined && (change.before === null || !/^[a-f0-9]{64}$/.test(expectedSha) || hash(change.before) !== expectedSha)) refuse("EXPECTED_SHA", "expectedSha does not match the spec; reread vmem spec get and retry with its sha256", change.path);
160
+ }
161
+ function createdDirectoryCleanupIssue(error: unknown, race: boolean, directory: string): SpecWriteIssue {
162
+ if ((error as NodeJS.ErrnoException | undefined)?.code === "ENOTEMPTY") return { code: "CLEANUP", severity: "warning", message: `created parent directory was kept (${directory}, ENOTEMPTY) because it now contains another file or directory; ${race ? "this is expected after a refused create race; " : ""}inspect the preserved contents and choose an absent target before retrying the create` };
163
+ return { code: "CLEANUP", severity: "error", message: `owned parent directory cleanup failed for ${directory} (${writeErrorCause(error)}); inspect its ownership and access, preserve unrelated contents and repair the reported cause before retrying the create` };
164
+ }
165
+ function cleanupCreatedDirs(owned: Map<string, string>, result: SpecWriteResult): void {
166
+ if (result.changed) return;
167
+ const race = result.issues.some(issue => issue.code === "EEXIST");
168
+ for (const [dir, stamp] of [...owned].reverse()) {
169
+ try { if (identity(dir) !== stamp) throw new Error("directory ownership changed"); rmdirSync(dir); }
170
+ catch (error) {
171
+ const item = createdDirectoryCleanupIssue(error, race, dir);
172
+ if (item.severity === "error") result.ok = false;
173
+ result.issues.push({ ...item, ...(result.path ? { path: result.path } : {}) });
174
+ }
175
+ }
176
+ }
177
+ function syncCreatedParents(owned: ReadonlyMap<string, string>): void {
178
+ for (const dir of [...owned.keys()].reverse()) syncDirectory(dirname(dir));
179
+ }
180
+
181
+ /** Pure prospective tree, shared by frontmatter update and future create/delete operations. No prospective file is read from disk. */
182
+ export function prospectiveSpecSnapshot(current: SpecSnapshot, edits: ReadonlyMap<string, string | null>): SpecSnapshot {
183
+ const byPath = new Map((current.candidates ?? current.specs).map(candidate => [candidate.path, candidate]));
184
+ for (const [path, source] of edits) {
185
+ if (source === null) { byPath.delete(path); continue; }
186
+ const document = parseFrontmatter(source);
187
+ if (basename(path) !== "SPEC.md" && !Object.hasOwn(document.data, "id") && !Object.hasOwn(document.data, "type")) byPath.delete(path);
188
+ else byPath.set(path, { path, hash: hash(source), source, frontmatter: document.data, body: document.body });
189
+ }
190
+ const candidates = [...byPath.values()].sort((a, b) => compare(a.path.normalize("NFC"), b.path.normalize("NFC")) || (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));
191
+ const specs: SpecDocument[] = [], seen = new Set<string>();
192
+ for (const candidate of candidates) {
193
+ const { id, type } = candidate.frontmatter;
194
+ if (typeof id === "string" && id.trim() && typeof type === "string" && type.trim() && !seen.has(id)) { specs.push({ ...candidate, id }); seen.add(id); }
195
+ }
196
+ // The validation API recomputes id/shape/duplicate errors from complete candidates.
197
+ const diagnostics = current.diagnostics.filter(item => !edits.has(item.path) && item.code !== "duplicate_id");
198
+ return { ...current, candidates, specs, diagnostics };
199
+ }
200
+ /** Validation can blame a related file (for example a later duplicate). The mutation receipt always names the written file. */
201
+ export function attributeSpecErrors(issues: SpecValidationIssue[], path: string, operation: SpecWriteOperation = "update"): SpecWriteIssue[] {
202
+ const correction = operation === "delete" ? `repair the source tree error before deleting ${path}` : `correct the ${operation} metadata for ${path}`;
203
+ return issues.map(issue => ({ ...issue, path, ...(issue.path !== path ? { target: issue.path, ...(issue.target !== undefined ? { originalTarget: issue.target } : {}) } : {}), message: `${issue.message}; ${correction}; ${retrySpecOperation(operation)}` }));
204
+ }
205
+ function screen(after: string, source: SpecSourceSpec, config: VmemConfig, path: string, operation: SpecWriteOperation): void {
206
+ if (Buffer.byteLength(after) > MAX_NOTE_BYTES) refuse("SIZE", `spec ${operation} exceeds the read limit; ${operation === "create" ? "reduce the metadata" : "reduce its frontmatter or split the file"} before retrying the ${operation}`, path);
207
+ const vault = { ...source, kind: "personal" as const };
208
+ const issues = [...screenContent(after, vault, config), ...screenMetadata(parseFrontmatter(after).data, { vault, config }, path)]
209
+ .filter(issue => issue.severity === "error").map(issue => ({ ...issue, path, message: `${issue.message}; remove the content matched by ${issue.code} from ${path} and retry the ${operation}` }));
210
+ if (issues.length) throw new Refusal([...new Map(issues.map(issue => [`${issue.code}:${issue.message}`, issue])).values()]);
211
+ }
212
+ function screenMutation(change: SpecMutation, source: SpecSourceSpec, config: VmemConfig, operation: SpecWriteOperation): void {
213
+ if (change.after !== null) screen(change.after, source, config, change.path, operation);
214
+ }
215
+ function allowedDeleteLinks(snapshot: SpecSnapshot, change: SpecMutation): { path: string; field: string; target: string }[] {
216
+ if (!change.deletion) return [];
217
+ const paths = new Map(snapshot.specs.map(document => [document.id, document.path]));
218
+ return (change.deletion?.backlinks ?? []).filter(edge => edge.kind !== "body_link").map(edge => ({ path: paths.get(edge.source)!, field: edge.kind, target: edge.target }));
219
+ }
220
+ function checkDeletionConfirmation(change: SpecMutation): void {
221
+ if (change.deletion?.preview === false && change.expectedFingerprint !== change.deletion.fingerprint) refuse("FINGERPRINT", "delete preview is missing or stale; request a fresh preview and acknowledge its listed backlinks and children before confirming", change.path);
222
+ }
223
+
224
+ interface SpecWriteGuard { config: VmemConfig; source: SpecSourceSpec; root: string; homeRoot: string; bindings: readonly (readonly [string, string])[]; path?: string }
225
+ /** Every authorization check uses the fresh registry, both at startup and immediately before publication. */
226
+ function guardSpecWrite(home: string, request: Pick<SpecUpdateRequest, "source" | "worktree">, options: SpecWriteOptions & { operation: SpecWriteOperation }, previous?: SpecWriteGuard, prepare?: (guard: SpecWriteGuard) => string): SpecWriteGuard {
227
+ const config = loadRegistry(home), sources = config.specs ?? [], source = request.source === undefined ? sources[0] : sources.find(value => value.id === request.source);
228
+ const path = previous?.path, env = options.env ?? process.env, channel = options.channel ?? "cli";
229
+ if (!source) refuse(previous ? "REGISTRY_DRIFT" : "SOURCE", `spec source is not registered; use vmem specs list and select a registered source, then ${retrySpecOperation(options.operation)}`, path);
230
+ if (options.binding && !isDeepStrictEqual(source, options.binding)) refuse("REGISTRY_DRIFT", `spec ${options.operation} source changed since MCP startup; restart the server, then ${retrySpecOperation(options.operation)}`, path);
231
+ if (previous && (!isDeepStrictEqual(source, previous.source) || !isDeepStrictEqual(config.denyPaths, previous.config.denyPaths) || !isDeepStrictEqual(config.piiPatterns, previous.config.piiPatterns))) refuse("REGISTRY_DRIFT", `spec registry or screening policy changed during the ${options.operation}; reread the source policy, then ${retrySpecOperation(options.operation)}`, path);
232
+ if (!["mcp", "cli"].includes(channel)) refuse("POLICY", "unknown spec write channel; use CLI or MCP", path);
233
+ const root = resolveSpecWorktree(source, request.worktree, env), homeRoot = canonicalPath(home);
234
+ if (deniedSpecPath(root, config.denyPaths ?? [])) refuse("PATH", `spec worktree is denied; select an allowed registered source, then ${retrySpecOperation(options.operation)}`, path);
235
+ const roots = [root, source.path, ...config.vaults.map(value => value.path), ...sources.map(value => value.path)];
236
+ if (roots.some(value => within(value, homeRoot))) refuse("HOME", `VMEM_HOME is inside a registered source/worktree; select a home outside repositories, then ${retrySpecOperation(options.operation)}`, path);
237
+ const bindings = [...new Set([root, source.path])].map(value => [value, identity(value)] as const);
238
+ if (previous && (root !== previous.root || !isDeepStrictEqual(bindings, previous.bindings))) refuse("DRIFT", `spec worktree identity changed; restore the registered worktree, then ${retrySpecOperation(options.operation)}`, path);
239
+ const guard = { config, source, root, homeRoot, bindings, path };
240
+ // Resolve the written path once so startup policy refusals retain path attribution.
241
+ if (prepare) guard.path = prepare(guard);
242
+ if (source.write === "none" || channel === "mcp" && source.write !== "mcp") refuse("POLICY", `spec write policy ${source.write} refuses channel ${channel}; select an allowed channel or have the owner update the source policy, then ${retrySpecOperation(options.operation)}`, guard.path);
243
+ return guard;
244
+ }
245
+
246
+ /** Spec state always participates in drift checks; only create depends on discovery occupancy. */
247
+ function sameMutationSnapshot(before: SpecSnapshot, after: SpecSnapshot, operation: SpecWriteOperation, target: string): boolean {
248
+ const { markdownPaths: beforePaths, ...beforeTree } = before, { markdownPaths: afterPaths, ...afterTree } = after;
249
+ return isDeepStrictEqual(beforeTree, afterTree) && (operation !== "create" ||
250
+ (beforePaths?.length === afterPaths?.length && beforePaths?.includes(target) === afterPaths?.includes(target)));
251
+ }
252
+ /** Count every Git-listed input, not only admitted spec candidates. */
253
+ function guardCreateDiscoveryBudget(snapshot: SpecSnapshot, change: SpecMutation): void {
254
+ if (change.before !== null) return;
255
+ const paths = snapshot.markdownPaths;
256
+ if (!paths) refuse("LIMIT", "spec create discovery budget is unavailable; rescan the source with the current vmem install before retrying the create", change.path);
257
+ if (!paths.includes(change.path) && paths.length >= MAX_SPEC_MARKDOWN_PATHS) refuse("LIMIT", `spec create would exceed the ${MAX_SPEC_MARKDOWN_PATHS}-Markdown discovery cap; remove or ignore Markdown files (untrack tracked exclusions with git rm --cached), then retry the create`, change.path);
258
+ }
259
+ /** Shared authorization, lock, validation and publication path for spec mutations. */
260
+ export function mutateSpec(home: string, request: Pick<SpecUpdateRequest, "id" | "source" | "worktree" | "expectedSha">, plan: (snapshot: SpecSnapshot) => SpecMutation, options: SpecWriteOptions = {}, operation: SpecWriteOperation = "update"): SpecWriteResult {
261
+ const env = options.env ?? process.env, channel = options.channel ?? "cli";
262
+ const context = { ...options, operation };
263
+ const result: SpecWriteResult = { ok: false, changed: false, actor: channel === "mcp" || AGENT_MARKERS.some(key => !!env[key]) ? "agent" : "person", id: request.id, issues: [] };
264
+ const createdDirs = new Map<string, string>();
265
+ let lockFd: number | undefined, lockFile: string | undefined, lockIdentity: string | undefined, temp: string | undefined, tempIdentity: string | undefined, tempFd: number | undefined;
266
+ try {
267
+ let initial!: SpecSnapshot, first!: SpecMutation, commonIdentity!: string;
268
+ const startup = guardSpecWrite(home, request, context, undefined, guard => {
269
+ result.source = guard.source.id; result.worktree = guard.root;
270
+ initial = discoverSpecs(guard.source, { worktree: guard.root, env }); commonIdentity = identity(initial.commonDir); first = plan(initial);
271
+ result.path = first.path; const firstRead = readMutation(guard.root, first, guard.config.denyPaths ?? [], operation);
272
+ if (firstRead.source !== first.before) refuse("DRIFT", `spec ${operation} changed during its initial read; ${retrySpecOperation(operation)}`, first.path);
273
+ return first.path;
274
+ });
275
+ const { config, source, root, homeRoot } = startup;
276
+ guardCreateDiscoveryBudget(initial, first);
277
+ guardCreateRepository(root, first, config.denyPaths ?? [], env);
278
+ const assertBinding = () => {
279
+ if (lockFile && lockIdentity !== undefined && identity(lockFile) !== lockIdentity) refuse("LOCKED", `spec mutation lock changed ownership; inspect the lock under VMEM_HOME and wait for the other writer, then ${retrySpecOperation(operation)}`, result.path);
280
+ guardSpecWrite(home, request, context, startup);
281
+ };
282
+ checkDeletionConfirmation(first);
283
+ checkExpectedSha(first, request.expectedSha);
284
+ screenMutation(first, source, config, operation);
285
+ if (first.deletion) Object.assign(result, first.deletion);
286
+ if (first.deletion?.preview) { assertBinding(); result.ok = true; return result; }
287
+ if (first.before === first.after && first.after !== null) { assertBinding(); result.ok = true; result.sha256 = hash(first.after); return result; }
288
+ mkdirSync(homeRoot, { recursive: true, mode: 0o700 });
289
+ const lockDir = join(homeRoot, "spec-mutations"); mkdirSync(lockDir, { recursive: true, mode: 0o700 });
290
+ if (lstatSync(lockDir).isSymbolicLink() || realpathSync(lockDir) !== lockDir) refuse("LOCKED", `spec lock directory is not plain; restore a private lock directory under VMEM_HOME, then ${retrySpecOperation(operation)}`, first.path);
291
+ lockFile = join(lockDir, `${hash(root)}.lock`);
292
+ try { lockFd = openSync(lockFile, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600); }
293
+ catch (error) {
294
+ lockFile = undefined;
295
+ if ((error as NodeJS.ErrnoException | undefined)?.code === "EEXIST") refuse("LOCKED", `spec mutation lock already exists; wait for the other mutation or inspect the interrupted writer's owned lock under VMEM_HOME, then ${retrySpecOperation(operation)}`, first.path);
296
+ refuse("IO", `spec mutation lock open failed (${writeErrorCause(error)}); check permissions and free space for the lock directory under VMEM_HOME, then ${retrySpecOperation(operation)}`, first.path);
297
+ }
298
+ const ownedLock = fstatSync(lockFd, { bigint: true }); lockIdentity = `${ownedLock.dev}:${ownedLock.ino}`;
299
+ writeFileSync(lockFd, JSON.stringify({ pid: process.pid, token: randomUUID() }) + "\n"); fsyncSync(lockFd);
300
+ assertBinding();
301
+ const current = discoverSpecs(source, { worktree: root, env }), change = plan(current);
302
+ checkDeletionConfirmation(change);
303
+ if (current.commonDir !== initial.commonDir || identity(initial.commonDir) !== commonIdentity || change.path !== first.path || change.before !== first.before) refuse("DRIFT", `spec ${operation} changed since the request read; ${retrySpecOperation(operation)}`, first.path);
304
+ const original = readMutation(root, change, config.denyPaths ?? [], operation);
305
+ if (original.source !== change.before) refuse("DRIFT", `spec ${operation} changed under the mutation lock; ${retrySpecOperation(operation)}`, change.path);
306
+ guardCreateDiscoveryBudget(current, change);
307
+ guardCreateRepository(root, change, config.denyPaths ?? [], env);
308
+ const prospective = prospectiveSpecSnapshot(current, new Map([[change.path, change.after]]));
309
+ screenMutation(change, source, config, operation);
310
+ const introduced = introducedSpecErrors(current, prospective, { env }, allowedDeleteLinks(current, change));
311
+ if (introduced.length) throw new Refusal(attributeSpecErrors(introduced, change.path, operation));
312
+ if (change.after === null) {
313
+ assertBinding();
314
+ if (!sameMutationSnapshot(current, discoverSpecs(source, { worktree: root, env }), operation, change.path)) refuse("DRIFT", `spec tree changed while validating deletion; ${retrySpecOperation(operation)}`, change.path);
315
+ const latest = readMutation(root, change, config.denyPaths ?? [], operation);
316
+ if (latest.source !== change.before || latest.identity !== original.identity) refuse("DRIFT", `spec changed before deletion; ${retrySpecOperation(operation)}`, change.path);
317
+ const file = plainPath(root, change.path, config.denyPaths ?? [], operation), publication = capturePublicationPath(root, file);
318
+ assertBinding();
319
+ publishFile(publication, { kind: "unlink" }, () => { result.changed = true; });
320
+ syncDirectory(dirname(file)); result.ok = true; return result;
321
+ }
322
+ const file = prepareMutationTarget(root, change, config.denyPaths ?? [], createdDirs), parent = dirname(file), parentIdentity = identity(parent);
323
+ const publication = capturePublicationPath(root, file);
324
+ const candidateTemp = join(parent, `.spec-${randomUUID()}.tmp`);
325
+ const fd = openSync(candidateTemp, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, original.mode);
326
+ temp = candidateTemp; tempFd = fd;
327
+ const stat = fstatSync(fd, { bigint: true }); tempIdentity = `${stat.dev}:${stat.ino}`;
328
+ fchmodSync(fd, original.mode); writeFileSync(fd, change.after); fsyncSync(fd);
329
+ assertBinding();
330
+ if (identity(parent) !== parentIdentity || !sameMutationSnapshot(current, discoverSpecs(source, { worktree: root, env }), operation, change.path)) refuse("DRIFT", `spec tree changed while validating the ${operation}; ${retrySpecOperation(operation)}`, change.path);
331
+ guardCreateRepository(root, change, config.denyPaths ?? [], env);
332
+ const latest = readMutation(root, change, config.denyPaths ?? [], operation), staged = readBounded(temp, change.path, operation);
333
+ if (latest.source !== change.before || latest.identity !== original.identity || staged.source !== change.after || staged.identity !== tempIdentity) refuse("DRIFT", `spec ${operation} target or staged file changed before publication; ${retrySpecOperation(operation)}`, change.path);
334
+ assertBinding();
335
+ const afterSha = hash(change.after);
336
+ try {
337
+ publishFile(publication, { kind: change.before === null ? "link" : "rename", temp }, () => {
338
+ result.changed = true; result.sha256 = afterSha;
339
+ if (change.before !== null) temp = undefined;
340
+ });
341
+ } catch (error) {
342
+ if (change.before === null && !result.changed && error instanceof PublicationDrift && error.targetExists) {
343
+ refuse("EEXIST", "create target appeared before publication; inspect the existing target and choose an absent path before retrying", change.path);
344
+ }
345
+ if (change.before !== null || error instanceof PublicationDrift || result.changed) throw error;
346
+ if ((error as NodeJS.ErrnoException).code === "EEXIST") refuse("EEXIST", "create target appeared before publication; inspect the existing file and choose an absent path before retrying", change.path);
347
+ refuse("LINK", `create hard-link publication failed (${writeErrorCause(error)}); check filesystem hard-link support and permissions and free space, then choose a writable worktree on a filesystem supporting same-directory hard links; create never falls back to rename`, change.path);
348
+ }
349
+ if (change.before === null) { cleanupOwnedFile(temp!, tempFd!); temp = undefined; }
350
+ syncDirectory(parent); syncCreatedParents(createdDirs); result.ok = true;
351
+ } catch (error) {
352
+ const inspection = publishedSpecInspection(operation, result.changed);
353
+ result.issues = error instanceof Refusal ? error.issues : error instanceof PublicationDrift ? [{ code: "DRIFT", severity: "error", message: error.message, ...(result.path ? { path: result.path } : {}) }] : [{ code: "IO", severity: "error", message: `spec ${operation} failed (${writeErrorCause(error)}); ${inspection ? `${inspection}, check permissions and free space, and repair the reported cause` : `inspect the source tree and target directory, check permissions and free space for the target and VMEM_HOME lock directory, repair the reported cause, then ${retrySpecOperation(operation)}`}`, ...(result.path ? { path: result.path } : {}) }];
354
+ result.path ??= result.issues.find(issue => issue.path)?.path;
355
+ } finally {
356
+ if (temp) {
357
+ try { cleanupOwnedFile(temp, tempFd!); }
358
+ catch (error) {
359
+ const inspection = publishedSpecInspection(operation, result.changed);
360
+ result.ok = false; result.issues.push({ code: "CLEANUP", severity: "error", message: `spec temporary cleanup could not prove owned-file removal (${writeErrorCause(error)}); ${inspection ? `${inspection}; inspect any .spec-*.tmp file in the target directory and preserve replacements` : "inspect the .spec-*.tmp file in the target directory before retrying (a replacement is preserved)"}`, ...(result.path ? { path: result.path } : {}) });
361
+ }
362
+ }
363
+ if (tempFd !== undefined) {
364
+ try { closeSync(tempFd); }
365
+ catch (error) { result.ok = false; result.issues.push({ code: "CLEANUP", severity: "error", message: `spec temporary descriptor close failed (${writeErrorCause(error)}); inspect the write receipt and temporary files before recovery` }); }
366
+ }
367
+ if (lockFd !== undefined) {
368
+ try { cleanupOwnedFile(lockFile!, lockFd); }
369
+ catch (error) { result.ok = false; result.issues.push({ code: "CLEANUP", severity: "error", message: `spec lock cleanup failed (${writeErrorCause(error)}); ${publishedSpecInspection(operation, result.changed) ?? "inspect the owned lock under VMEM_HOME before retrying"}`, ...(result.path ? { path: result.path } : {}) }); }
370
+ finally {
371
+ try { closeSync(lockFd); }
372
+ catch (error) { result.ok = false; result.issues.push({ code: "CLEANUP", severity: "error", message: `spec lock descriptor close failed (${writeErrorCause(error)}); ${publishedSpecInspection(operation, result.changed) ?? "inspect the write receipt and lock state before retrying"}`, ...(result.path ? { path: result.path } : {}) }); }
373
+ }
374
+ }
375
+ cleanupCreatedDirs(createdDirs, result);
376
+ }
377
+ return result;
378
+ }
379
+
380
+ function validSpecTitle(value: string): boolean { return !/[\p{Cc}\p{Zl}\p{Zp}]/u.test(value); }
381
+ function updateFrontmatter(document: SpecCandidate, request: SpecUpdateRequest): string {
382
+ const path = document.path, changes: Record<string, unknown> = {};
383
+ const invalid = (message: string): never => refuse("INPUT", `${message}; use only the documented spec update set/unset/add/remove fields`, path);
384
+ if (Object.keys(request).some(key => !["id", "source", "worktree", "expectedSha", "set", "unset", "add", "remove"].includes(key))) invalid("unknown update option");
385
+ for (const field of ["set", "add", "remove"] as const) if (request[field] !== undefined && !record(request[field])) invalid(`${field} must be an object`);
386
+ if (request.unset !== undefined && (!Array.isArray(request.unset) || request.unset.some(key => typeof key !== "string" || !(SPEC_UPDATE_OPTIONAL_FIELDS as readonly string[]).includes(key)))) invalid("unset accepts optional fields only; id, type and title are required");
387
+ for (const [key, value] of Object.entries(request.set ?? {})) {
388
+ if (!(SPEC_UPDATE_SCALAR_FIELDS as readonly string[]).includes(key) || typeof value !== "string" || !value.trim()) invalid("set accepts known nonempty scalar fields only; id is immutable");
389
+ if (key === "title" && !validSpecTitle(value)) invalid("title must be one line without control or line-separator characters; use plain single-line text");
390
+ if (key === "type" && !["goal", "architecture", "module", "submodule"].includes(value) || key === "status" && !["draft", "active", "deprecated"].includes(value)) invalid("unknown type or status vocabulary");
391
+ if (request.unset?.includes(key)) invalid("a field cannot be set and unset together");
392
+ changes[key] = value;
393
+ }
394
+ for (const key of request.unset ?? []) changes[key] = undefined;
395
+ for (const field of ["remove", "add"] as const) for (const [key, values] of Object.entries(request[field] ?? {})) {
396
+ if (!(SPEC_UPDATE_LIST_FIELDS as readonly string[]).includes(key) || !Array.isArray(values) || values.some(value => typeof value !== "string" || !value.trim())) invalid(`${field} accepts known lists of nonempty strings only`);
397
+ if (request.unset?.includes(key)) invalid("a list cannot be unset and edited together");
398
+ const current = Object.hasOwn(changes, key) ? changes[key] : document.frontmatter[key];
399
+ if (current !== undefined && (!Array.isArray(current) || current.some(value => typeof value !== "string"))) invalid("existing list has the wrong shape; unset it before adding or removing entries");
400
+ if (field === "add" && values.some(value => request.remove?.[key]?.includes(value))) invalid("a value cannot be added and removed together");
401
+ const previous = (current ?? []) as string[];
402
+ const next = field === "remove" ? previous.filter(value => !values.includes(value)) : [...previous, ...values.filter((value, index) => !previous.includes(value) && values.indexOf(value) === index)];
403
+ if (current !== undefined || next.length) changes[key] = next;
404
+ }
405
+ try { return emitFrontmatter(parseFrontmatter(document.source), changes); }
406
+ catch (error) { refuse("FRONTMATTER", `frontmatter cannot be edited losslessly (${writeErrorCause(error)}); repair its block mapping and retry`, path); }
407
+ }
408
+ export function updateSpec(home: string, request: SpecUpdateRequest, options: SpecWriteOptions = {}): SpecWriteResult {
409
+ return mutateSpec(home, request, snapshot => {
410
+ let document: SpecCandidate | undefined = snapshot.specs.find(candidate => candidate.id === request.id);
411
+ if (!document) {
412
+ const candidates = (snapshot.candidates ?? []).filter(candidate => candidate.frontmatter.id === request.id);
413
+ if (candidates.length > 1) refuse("AMBIGUOUS", "multiple candidates share this id and none is an admitted spec; make the ids unique with an editor before retrying");
414
+ document = candidates[0];
415
+ }
416
+ if (!document) refuse("TARGET", "spec id was not found; choose an id from vmem spec grep in the selected source");
417
+ return { path: document.path, before: document.source, after: updateFrontmatter(document, request) };
418
+ }, options);
419
+ }
420
+
421
+ /** Create structural prose only; body editing remains with the caller's normal file tools. */
422
+ export function createSpec(home: string, request: SpecCreateRequest, options: SpecWriteOptions = {}): SpecWriteResult {
423
+ return mutateSpec(home, request, () => {
424
+ const fields = ["id", "type", "title", "status", "parent", "superseded-by", "depends-on", "references", "implements", "covers", "tags", "paths", "verified-against"] as const;
425
+ const invalid = (message: string): never => refuse("INPUT", `${message}; supply the documented spec create metadata fields`, request.path);
426
+ if (Object.keys(request).some(key => !["path", "source", "worktree", ...fields].includes(key))) invalid("unknown create option");
427
+ for (const field of ["path", "id", "type", "title"] as const) if (typeof request[field] !== "string" || !request[field].trim()) invalid(`${field} must be a nonempty string`);
428
+ if (!Object.hasOwn(SPEC_HEADINGS, request.type)) invalid("unknown type vocabulary");
429
+ if (request.status !== undefined && !["draft", "active", "deprecated"].includes(request.status)) invalid("unknown status vocabulary");
430
+ if (!validSpecTitle(request.title)) invalid("title must be one line without control or line-separator characters; use plain single-line text");
431
+ const data: Record<string, unknown> = {};
432
+ for (const field of fields) {
433
+ const value = field === "status" ? request.status ?? "draft" : request[field];
434
+ if (value === undefined) continue;
435
+ if ((SPEC_UPDATE_LIST_FIELDS as readonly string[]).includes(field)) {
436
+ if (!Array.isArray(value) || value.some(item => typeof item !== "string" || !item.trim())) invalid(`${field} must be a list of nonempty strings`);
437
+ } else if (typeof value !== "string" || !value.trim()) invalid(`${field} must be a nonempty string`);
438
+ data[field] = value;
439
+ }
440
+ const body = `# ${request.title}\n\n` + SPEC_HEADINGS[request.type]!.map(heading => `## ${heading}\n\n`).join("");
441
+ return { path: request.path, before: null, after: emitFrontmatter(parseFrontmatter(body), data) };
442
+ }, options, "create");
443
+ }
444
+ const SPEC_HEADINGS: Readonly<Record<string, readonly string[]>> = {
445
+ goal: ["Scope", "Decisions", "Success and evidence"], architecture: ["Boundaries", "Decisions"],
446
+ module: ["Responsibility", "Interfaces", "Decisions"], submodule: ["Responsibility", "Interfaces", "Decisions"],
447
+ };
448
+
449
+ /** Complete acknowledgements, not a paged read: oversize previews refuse rather than omit a backlink. */
450
+ function deletionPreview(snapshot: SpecSnapshot, document: SpecCandidate, preview: boolean): SpecDeletePreview {
451
+ const graph = buildSpecGraph(snapshot), id = String(document.frontmatter.id);
452
+ const backlinks = graph.edges.filter(edge => edge.target === id).sort((a, b) => compare(a.source, b.source) || compare(a.kind, b.kind) || compare(a.target, b.target));
453
+ const childIds = new Set(backlinks.filter(edge => edge.kind === "parent").map(edge => edge.source));
454
+ const children = graph.nodes.filter(node => childIds.has(node.id)).sort((a, b) => compare(a.id, b.id) || compare(a.path, b.path));
455
+ const sha256 = hash(document.source), fingerprint = hash(JSON.stringify({ worktree: snapshot.root, path: document.path, sha256, backlinks, children }));
456
+ const acknowledgement = { fingerprint, sha256, backlinks, children };
457
+ if (Buffer.byteLength(JSON.stringify(acknowledgement)) > 224 * 1024) refuse("LIMIT", "complete delete acknowledgement exceeds the response budget; repair or remove backlinks before requesting a fresh preview", document.path);
458
+ return { preview, ...acknowledgement };
459
+ }
460
+ export function deleteSpec(home: string, request: SpecDeleteRequest, options: SpecWriteOptions = {}): SpecDeleteResult {
461
+ return mutateSpec(home, request, snapshot => {
462
+ if (Object.keys(request).some(key => !["id", "source", "worktree", "confirm", "fingerprint"].includes(key)) || typeof request.id !== "string" || !request.id.trim() || request.confirm !== undefined && typeof request.confirm !== "boolean") refuse("INPUT", "invalid spec delete request; use a spec id, optional source/worktree and boolean confirm with a fresh preview fingerprint");
463
+ if (request.fingerprint !== undefined && (typeof request.fingerprint !== "string" || !/^[a-f0-9]{64}$/.test(request.fingerprint))) refuse("FINGERPRINT", "invalid delete fingerprint; request a fresh delete preview before confirming");
464
+ const document = snapshot.specs.find(candidate => candidate.id === request.id);
465
+ if (!document) refuse("TARGET", "spec delete id was not found; choose an id from vmem spec grep in the selected source, then request a fresh preview with vmem spec delete");
466
+ const deletion = deletionPreview(snapshot, document, request.confirm !== true);
467
+ return { path: document.path, before: document.source, after: null, deletion, expectedFingerprint: request.fingerprint };
468
+ }, options, "delete");
469
+ }
@@ -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
+ }