@laurindustries/mnemos 0.0.0-stage → 0.2.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 +21 -0
- package/LICENSE +21 -0
- package/README.md +78 -2
- package/docs/README.md +33 -0
- package/docs/assets/mnemos-readme.svg +13 -0
- package/docs/assets/mnemos-social-preview.png +0 -0
- package/docs/branding.md +19 -0
- package/docs/cli.md +144 -0
- package/docs/development.md +29 -0
- package/docs/getting-started.md +127 -0
- package/docs/mcp.md +105 -0
- package/docs/ontology.md +233 -0
- package/docs/operations.md +130 -0
- package/docs/refresh.md +79 -0
- package/docs/release.md +68 -0
- package/docs/relocation.md +22 -0
- package/examples/ontology.extended.yaml +64 -0
- package/package.json +91 -4
- package/scripts/check-docs.mjs +23 -0
- package/scripts/cli.mjs +9 -0
- package/scripts/mcp.mjs +3 -0
- package/scripts/package-smoke-worker.mjs +63 -0
- package/scripts/package-smoke.mjs +49 -0
- package/scripts/refresh.config.example.json +8 -0
- package/scripts/refresh.mjs +10 -0
- package/src/api.ts +39 -0
- package/src/cli.ts +111 -0
- package/src/config.ts +124 -0
- package/src/core-bootstrap.mjs +3 -0
- package/src/explorer.ts +106 -0
- package/src/index.ts +88 -0
- package/src/legacy-v5.json +22 -0
- package/src/mcp.ts +31 -0
- package/src/ontology-editor.ts +115 -0
- package/src/ontology.ts +50 -0
- package/src/ontology.yaml +60 -0
- package/src/opencode-bootstrap.mjs +2 -0
- package/src/opencode.ts +28 -0
- package/src/paths.ts +8 -0
- package/src/refresh/cli.ts +121 -0
- package/src/refresh/inventory.ts +259 -0
- package/src/refresh/refresh.ts +112 -0
- package/src/service-bootstrap.mjs +11 -0
- package/src/service-protocol.ts +94 -0
- package/src/service.ts +138 -0
- package/src/shared-store.ts +125 -0
- package/src/store.ts +385 -0
- package/src/tool-contract.ts +45 -0
- package/src/web/app.js +241 -0
- package/src/web/index.html +56 -0
- package/src/web/mnemos-icon-32.png +0 -0
- package/src/web/mnemos-icon.svg +9 -0
- package/src/web/mnemos-logo.svg +10 -0
- package/src/web/style.css +57 -0
|
@@ -0,0 +1,259 @@
|
|
|
1
|
+
import { readdir, readFile, realpath, stat } from "node:fs/promises";
|
|
2
|
+
import { basename, delimiter, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
|
|
3
|
+
import { execFile } from "node:child_process";
|
|
4
|
+
import { promisify } from "node:util";
|
|
5
|
+
import type { Entity, GraphSnapshot } from "../store.js";
|
|
6
|
+
import type { GraphInput, RepoKind } from "../ontology.js";
|
|
7
|
+
import { assertCompatible, legacyOntologyPath, loadOntology } from "../config.js";
|
|
8
|
+
|
|
9
|
+
export type Domain = "repos" | "contexts" | "subscriptions";
|
|
10
|
+
export interface RefreshConfig {
|
|
11
|
+
repoRoots: string[];
|
|
12
|
+
kubeconfigDirectories: string[];
|
|
13
|
+
kubeconfigFiles?: string[];
|
|
14
|
+
azureSubscriptions: boolean;
|
|
15
|
+
contextEnvironments: Record<string, string[]>;
|
|
16
|
+
repoKinds?: Record<string, RepoKind>;
|
|
17
|
+
}
|
|
18
|
+
export interface Fact { input: GraphInput; domains: Domain[] }
|
|
19
|
+
export interface Inventory {
|
|
20
|
+
nodes: Map<string, Fact>;
|
|
21
|
+
edges: Map<string, Fact>;
|
|
22
|
+
complete: Record<Domain, boolean>;
|
|
23
|
+
issues: string[];
|
|
24
|
+
protectedEdgesFrom: Set<string>;
|
|
25
|
+
}
|
|
26
|
+
export const edgeKey = (from: string, type: string, to: string) => JSON.stringify([from, type, to]);
|
|
27
|
+
const exec = promisify(execFile);
|
|
28
|
+
export type Command = (name: string, args: string[]) => Promise<string>;
|
|
29
|
+
export const command: Command = async (name, args) => {
|
|
30
|
+
try { return (await exec(name, args, { timeout: 30_000, maxBuffer: 4 * 1024 * 1024, encoding: "utf8" })).stdout; }
|
|
31
|
+
catch { throw new Error(`${name} metadata command failed (stderr suppressed to avoid credential leakage)`); }
|
|
32
|
+
};
|
|
33
|
+
const excluded = new Set([".git", ".pi", ".terraform", ".terragrunt-cache", "node_modules", ".venv", "vendor", "dist", "build"]);
|
|
34
|
+
const within = (path: string, root: string) => path === root || path.startsWith(root + sep);
|
|
35
|
+
const evidence = (values: string[]) => [...new Set(values)].join("\n").slice(0, 2000);
|
|
36
|
+
const uuid = /^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i;
|
|
37
|
+
|
|
38
|
+
/** Strip comments without stripping URL fragments/slashes inside quoted strings; preserve line numbers. */
|
|
39
|
+
export function literals(content: string): { key: string; value: string; line: number }[] {
|
|
40
|
+
let clean = "", quoted = false, block = false, lineComment = false;
|
|
41
|
+
for (let i = 0; i < content.length; i++) {
|
|
42
|
+
const c = content[i]!, next = content[i + 1];
|
|
43
|
+
if (c === "\n") { clean += c; lineComment = false; continue; }
|
|
44
|
+
if (lineComment) { clean += " "; continue; }
|
|
45
|
+
if (block) { if (c === "*" && next === "/") { block = false; i++; clean += " "; } else clean += " "; continue; }
|
|
46
|
+
if (quoted && c === "\\") { clean += c + (next ?? ""); i++; continue; }
|
|
47
|
+
if (c === '"') quoted = !quoted;
|
|
48
|
+
if (!quoted && c === "/" && next === "*") { block = true; i++; clean += " "; continue; }
|
|
49
|
+
if (!quoted && (c === "#" || c === "/" && next === "/")) { lineComment = true; clean += " "; continue; }
|
|
50
|
+
clean += c;
|
|
51
|
+
}
|
|
52
|
+
return clean.split("\n").flatMap((line, index) => {
|
|
53
|
+
const match = /^\s*([A-Za-z_][\w-]*)\s*=\s*"((?:[^"\\]|\\.)*)"\s*[,}]?\s*$/.exec(line);
|
|
54
|
+
if (!match || /\$\{|%\{/.test(match[2]!)) return [];
|
|
55
|
+
try { return [{ key: match[1]!, value: JSON.parse(`"${match[2]}"`), line: index + 1 }]; } catch { return []; }
|
|
56
|
+
});
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** Normalize identity only; discard credentials, query tokens, refs, and subdirectory suffixes. */
|
|
60
|
+
export function gitIdentity(value: string): string | undefined {
|
|
61
|
+
value = value.trim().replace(/^git::/, "");
|
|
62
|
+
const scp = /^(?:[^@/:]+@)?([^/:]+):(.+)$/.exec(value);
|
|
63
|
+
if (scp && !value.includes("://") && !isAbsolute(value)) value = `ssh://${scp[1]}/${scp[2]}`;
|
|
64
|
+
try {
|
|
65
|
+
const url = new URL(value);
|
|
66
|
+
if (!["ssh:", "https:", "http:", "git:"].includes(url.protocol)) return undefined;
|
|
67
|
+
let path = url.pathname.replace(/^\/+|\/+$/g, "");
|
|
68
|
+
path = path.split(/\.git(?:\/|$)/)[0]!;
|
|
69
|
+
return `${url.hostname.toLowerCase()}/${path}`;
|
|
70
|
+
} catch { return undefined; }
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export async function collectInventory(config: RefreshConfig, snapshot: GraphSnapshot, configPath: string, run: Command = command): Promise<Inventory> {
|
|
74
|
+
// This scanner has default-model semantics; replacement ontologies must fail before discovery.
|
|
75
|
+
assertCompatible(loadOntology(legacyOntologyPath), {
|
|
76
|
+
version: snapshot.schema.version,
|
|
77
|
+
entities: Object.fromEntries(Object.entries(snapshot.schema.entities).map(([name,e]) => [name, {description: e.description, attributes: e.attribute_definitions}])),
|
|
78
|
+
relationships: snapshot.schema.relationships,
|
|
79
|
+
shared_attributes: snapshot.schema.shared_attribute_definitions,
|
|
80
|
+
});
|
|
81
|
+
const result: Inventory = { nodes: new Map(), edges: new Map(), complete: { repos: config.repoRoots.length > 0, contexts: true, subscriptions: config.azureSubscriptions }, issues: [], protectedEdgesFrom: new Set() };
|
|
82
|
+
const issue = (domain: Domain, message: string, incomplete = false) => { result.issues.push(message); if (incomplete) result.complete[domain] = false; };
|
|
83
|
+
const addNode = (input: GraphInput, domains: Domain[]) => {
|
|
84
|
+
const prior = result.nodes.get(input.id!);
|
|
85
|
+
result.nodes.set(input.id!, { input: prior ? { ...prior.input, ...input, source: evidence([prior.input.source ?? "", input.source ?? ""]) } : input,
|
|
86
|
+
domains: [...new Set([...(prior?.domains ?? []), ...domains])] });
|
|
87
|
+
};
|
|
88
|
+
const addEdge = (input: GraphInput, domains: Domain[]) => {
|
|
89
|
+
const key = edgeKey(input.from!, input.edge_type!, input.to!);
|
|
90
|
+
const prior = result.edges.get(key);
|
|
91
|
+
result.edges.set(key, { input: { ...input, source: evidence([prior?.input.source ?? "", input.source ?? ""].filter(Boolean)) }, domains });
|
|
92
|
+
};
|
|
93
|
+
const existingRepos = snapshot.nodes.filter((n) => n.entity_type === "Repo");
|
|
94
|
+
const byPath = new Map(existingRepos.filter((n) => n.localPath).map((n) => [resolve(n.localPath!), n]));
|
|
95
|
+
const environments = new Map<string, string>();
|
|
96
|
+
for (const node of snapshot.nodes.filter((n) => n.entity_type === "Environment")) {
|
|
97
|
+
if (environments.has(node.name)) throw new Error(`Ambiguous environment name: ${node.name}; use unique names before refreshing`);
|
|
98
|
+
environments.set(node.name, node.id);
|
|
99
|
+
}
|
|
100
|
+
const env = (name: string, source: string, domain: Domain) => {
|
|
101
|
+
const id = environments.get(name) ?? `environment:${name}`;
|
|
102
|
+
environments.set(name, id);
|
|
103
|
+
addNode({ action: "upsert_entity", id, entity_type: "Environment", name,
|
|
104
|
+
description: "Explicitly declared environment; no stage or live deployment is inferred.", source }, [domain]);
|
|
105
|
+
return id;
|
|
106
|
+
};
|
|
107
|
+
const repos: { path: string; root: string; node: Entity | GraphInput; files: { path: string; data: ReturnType<typeof literals>; uncertainSources: boolean }[] }[] = [];
|
|
108
|
+
const discovered = new Set<string>();
|
|
109
|
+
async function discover(directory: string, root: string): Promise<void> {
|
|
110
|
+
const entries = await readdir(directory, { withFileTypes: true });
|
|
111
|
+
if (entries.some((e) => e.name === ".git")) {
|
|
112
|
+
const path = await realpath(directory);
|
|
113
|
+
if (!discovered.has(path)) { discovered.add(path); await scanRepo(path, root); }
|
|
114
|
+
return;
|
|
115
|
+
}
|
|
116
|
+
for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {
|
|
117
|
+
if (entry.isDirectory() && !excluded.has(entry.name)) await discover(join(directory, entry.name), root);
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
async function scanRepo(path: string, root: string) {
|
|
121
|
+
const files: { path: string; data: ReturnType<typeof literals>; uncertainSources: boolean }[] = [];
|
|
122
|
+
let hasTf = false;
|
|
123
|
+
async function walk(directory: string) {
|
|
124
|
+
for (const entry of (await readdir(directory, { withFileTypes: true })).sort((a, b) => a.name.localeCompare(b.name))) {
|
|
125
|
+
if (excluded.has(entry.name)) continue;
|
|
126
|
+
const file = join(directory, entry.name);
|
|
127
|
+
if (entry.isDirectory()) await walk(file);
|
|
128
|
+
else if (entry.isFile() && entry.name.endsWith(".tf")) hasTf = true;
|
|
129
|
+
else if (entry.isFile() && entry.name.endsWith(".hcl")) {
|
|
130
|
+
if ((await stat(file)).size > 2 * 1024 * 1024) { issue("repos", `HCL exceeds scan limit: ${file}`, true); continue; }
|
|
131
|
+
const content = await readFile(file, "utf8");
|
|
132
|
+
const data = literals(content);
|
|
133
|
+
files.push({ path: file, data, uncertainSources: content.split("\n").filter((line) => /^\s*source\s*=/.test(line)).length > data.filter((d) => d.key === "source").length });
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
await walk(path);
|
|
138
|
+
const existing = byPath.get(path);
|
|
139
|
+
const hasSource = files.some((f) => f.uncertainSources || f.data.some((d) => d.key === "source"));
|
|
140
|
+
const override = config.repoKinds?.[path] ?? config.repoKinds?.[relative(root, path)];
|
|
141
|
+
if (!existing && !override && hasTf && hasSource) { issue("repos", `Ambiguous new repo kind (set repoKinds; not imported): ${path}`); return; }
|
|
142
|
+
const kind = existing?.kind ?? override ?? (hasTf ? "terraform-module" : hasSource ? "terragrunt" : "generic");
|
|
143
|
+
let origin = existing?.gitlabUrl ? gitIdentity(existing.gitlabUrl) : undefined;
|
|
144
|
+
try { origin = gitIdentity(await run("git", ["-C", path, "config", "--get", "remote.origin.url"])) ?? origin; }
|
|
145
|
+
catch { issue("repos", `Origin metadata unavailable (preserving known URL): ${path}`); }
|
|
146
|
+
const id = existing?.id ?? `repo:local:${basename(root)}:${relative(root, path) || basename(path)}`;
|
|
147
|
+
const node: GraphInput = { action: "upsert_entity", id, entity_type: "Repo", name: relative(root, path) || basename(path), kind: kind as RepoKind,
|
|
148
|
+
localPath: path, ...(origin ? { gitlabUrl: `https://${origin}` } : {}), description: "Local repository inventory; kind describes repository configuration, not deployment.", source: `${path}/.git; local repository scan` };
|
|
149
|
+
addNode(node, ["repos"]);
|
|
150
|
+
repos.push({ path, root, node, files });
|
|
151
|
+
}
|
|
152
|
+
for (const root of config.repoRoots) {
|
|
153
|
+
try { const path = await realpath(root); await discover(path, path); }
|
|
154
|
+
catch { issue("repos", `Repository root could not be completely scanned: ${root}`, true); }
|
|
155
|
+
}
|
|
156
|
+
const candidates = new Map(existingRepos.map((n) => [n.id, n] as const));
|
|
157
|
+
for (const repo of repos) candidates.set(repo.node.id!, { ...repo.node, entity_type: "Repo" } as Entity);
|
|
158
|
+
const targets = [...candidates.values()].sort((a, b) => (b.localPath?.length ?? 0) - (a.localPath?.length ?? 0));
|
|
159
|
+
const subscriptionDeclarations: { id: string; environment: string; source: string }[] = [];
|
|
160
|
+
for (const repo of repos) {
|
|
161
|
+
if (repo.node.kind !== "terragrunt") continue; // Terraform module examples are not environment inventories.
|
|
162
|
+
for (const file of repo.files) {
|
|
163
|
+
const envValues = file.data.filter((d) => d.key === "env" || d.key === "environment" && environments.has(d.value));
|
|
164
|
+
const direct = envValues.filter((d) => d.key === "env");
|
|
165
|
+
const selected = direct.length ? direct : envValues;
|
|
166
|
+
const names = [...new Set(selected.map((d) => d.value))];
|
|
167
|
+
if (names.length === 1) {
|
|
168
|
+
const declaration = evidence(selected.map((d) => `${file.path}:${d.line} (explicit ${d.key}=${d.value})`));
|
|
169
|
+
const environment = env(names[0]!, declaration, "repos");
|
|
170
|
+
if (repo.node.kind === "terragrunt") addEdge({ action: "upsert_edge", from: repo.node.id, to: environment, edge_type: "TARGETS",
|
|
171
|
+
description: "Configuration explicitly targets this environment; not proof of live deployment.", source: declaration }, ["repos"]);
|
|
172
|
+
const subs = file.data.filter((d) => d.key === "subscription_id" && uuid.test(d.value));
|
|
173
|
+
if (new Set(subs.map((d) => d.value.toLowerCase())).size === 1) subscriptionDeclarations.push({ id: subs[0]!.value.toLowerCase(), environment,
|
|
174
|
+
source: evidence([...subs.map((d) => `${file.path}:${d.line} (subscription_id)`), declaration]) });
|
|
175
|
+
} else if (names.length > 1) issue("repos", `Ambiguous environment declarations: ${file.path}`, true);
|
|
176
|
+
if (repo.node.kind !== "terragrunt") continue;
|
|
177
|
+
if (file.uncertainSources) {
|
|
178
|
+
result.protectedEdgesFrom.add(repo.node.id!);
|
|
179
|
+
issue("repos", `Dynamic or unsupported source; preserving owned edges from this repo: ${file.path}`);
|
|
180
|
+
}
|
|
181
|
+
for (const source of file.data.filter((d) => d.key === "source")) {
|
|
182
|
+
const identity = gitIdentity(source.value);
|
|
183
|
+
const local = source.value.startsWith(".") || isAbsolute(source.value) ? resolve(dirname(file.path), source.value.split("//")[0]!) : undefined;
|
|
184
|
+
let target: Entity | undefined;
|
|
185
|
+
if (identity) {
|
|
186
|
+
const matches = targets.filter((n) => {
|
|
187
|
+
const url = gitIdentity(n.gitlabUrl ?? ""); return url && (identity === url || identity.startsWith(url + "/"));
|
|
188
|
+
});
|
|
189
|
+
const longest = Math.max(0, ...matches.map((n) => gitIdentity(n.gitlabUrl!)!.length));
|
|
190
|
+
const exact = matches.filter((n) => gitIdentity(n.gitlabUrl!)!.length === longest);
|
|
191
|
+
// Multiple origins can mean separate checkouts/branches. Prefer the canonical path,
|
|
192
|
+
// never arbitrarily pick a feature checkout merely because its path is longer.
|
|
193
|
+
const canonical = exact.filter((n) => n.localPath?.endsWith("/" + gitIdentity(n.gitlabUrl!)!.split("/").slice(1).join("/")));
|
|
194
|
+
target = canonical.length === 1 ? canonical[0] : exact.length === 1 ? exact[0] : undefined;
|
|
195
|
+
} else if (local) {
|
|
196
|
+
target = targets.find((n) => n.localPath && within(local, n.localPath));
|
|
197
|
+
}
|
|
198
|
+
if (!target || target.kind !== "terraform-module") {
|
|
199
|
+
result.protectedEdgesFrom.add(repo.node.id!);
|
|
200
|
+
issue("repos", `Unresolved module reference; preserving owned edges from this repo: ${file.path}:${source.line}`); continue;
|
|
201
|
+
}
|
|
202
|
+
addEdge({ action: "upsert_edge", from: repo.node.id, to: target.id, edge_type: "CALLS", description: "Verified static Terragrunt source reference (including local checkouts); not proof of deployment.",
|
|
203
|
+
source: `${file.path}:${source.line}` }, ["repos"]);
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
const contextFiles = new Set(config.kubeconfigFiles ?? []);
|
|
208
|
+
for (const file of (process.env.KUBECONFIG ?? "").split(delimiter).filter(Boolean)) contextFiles.add(resolve(file));
|
|
209
|
+
for (const directory of config.kubeconfigDirectories) {
|
|
210
|
+
try { for (const file of await readdir(directory, { withFileTypes: true })) if (file.isFile() && (file.name === "config" || /\.ya?ml$/.test(file.name))) contextFiles.add(join(directory, file.name)); }
|
|
211
|
+
catch { issue("contexts", `Kubeconfig directory unavailable: ${directory}`, true); }
|
|
212
|
+
}
|
|
213
|
+
if (!contextFiles.size && !config.kubeconfigDirectories.length) result.complete.contexts = false;
|
|
214
|
+
const contexts = new Map<string, { cluster: string; sources: string[]; ambiguous?: boolean }>();
|
|
215
|
+
for (const file of [...contextFiles].sort()) {
|
|
216
|
+
try {
|
|
217
|
+
const output = await run("kubectl", ["--kubeconfig", file, "config", "view", "-o", 'jsonpath={range .contexts[*]}{.name}{"\\t"}{.context.cluster}{"\\n"}{end}']);
|
|
218
|
+
for (const line of output.trim().split("\n").filter(Boolean)) {
|
|
219
|
+
const [name, cluster] = line.split("\t");
|
|
220
|
+
if (!name || !cluster) throw new Error("Malformed context metadata");
|
|
221
|
+
const prior = contexts.get(name);
|
|
222
|
+
contexts.set(name, { cluster, sources: [...(prior?.sources ?? []), `${file}:contexts[name=${name}]`], ambiguous: prior?.ambiguous || !!prior && prior.cluster !== cluster });
|
|
223
|
+
}
|
|
224
|
+
} catch { issue("contexts", `Context metadata unavailable: ${file}`, true); }
|
|
225
|
+
}
|
|
226
|
+
for (const [name, context] of contexts) {
|
|
227
|
+
const existing = snapshot.nodes.filter((n) => n.entity_type === "K8sContext" &&
|
|
228
|
+
(n.name === name || context.sources.some((source) => n.source.includes(source))));
|
|
229
|
+
if (context.ambiguous || existing.length > 1) { issue("contexts", `Ambiguous context name: ${name}`, true); continue; }
|
|
230
|
+
const id = existing[0]?.id ?? `k8s-context:${name}`;
|
|
231
|
+
addNode({ action: "upsert_entity", id, entity_type: "K8sContext", name, description: `Configured Kubernetes context referencing cluster entry ${context.cluster}; reachability is not verified. No credentials are recorded.`, source: evidence(context.sources) }, ["contexts"]);
|
|
232
|
+
for (const nameEnv of config.contextEnvironments[name] ?? []) {
|
|
233
|
+
const source = `${configPath}:contextEnvironments[${name}] (explicit operator-approved mapping)`;
|
|
234
|
+
addEdge({ action: "upsert_edge", from: id, to: env(nameEnv, source, "contexts"), edge_type: "IN_ENVIRONMENT", description: "Explicit operator-approved context/environment association; not proof of live deployment.", source: evidence([...context.sources, source]) }, ["contexts"]);
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
const subscriptions = new Map<string, { name: string; source: string }>();
|
|
238
|
+
if (config.azureSubscriptions) {
|
|
239
|
+
try {
|
|
240
|
+
const records: unknown = JSON.parse(await run("az", ["account", "list", "--query", "[].{id:id,name:name,state:state}", "--output", "json"]));
|
|
241
|
+
if (!Array.isArray(records)) throw new Error("Malformed account metadata");
|
|
242
|
+
for (const record of records) {
|
|
243
|
+
if (!uuid.test(record.id ?? "") || typeof record.name !== "string") throw new Error("Malformed subscription metadata");
|
|
244
|
+
if (record.state === "Enabled") subscriptions.set(record.id.toLowerCase(), { name: record.name, source: "az account list (cached id/name/state metadata only; Enabled)" });
|
|
245
|
+
}
|
|
246
|
+
} catch { issue("subscriptions", "Azure account metadata unavailable; no subscription pruning", true); }
|
|
247
|
+
}
|
|
248
|
+
for (const [sid, subscription] of subscriptions) addNode({ action: "upsert_entity", id: `azure-subscription:${sid}`, entity_type: "AzureSubscription", name: subscription.name,
|
|
249
|
+
description: `Azure subscription UUID ${sid}, present in the Enabled account cache; not proof of live deployment.`, source: subscription.source }, ["subscriptions"]);
|
|
250
|
+
for (const declaration of subscriptionDeclarations) {
|
|
251
|
+
const id = `azure-subscription:${declaration.id}`;
|
|
252
|
+
const cached = subscriptions.get(declaration.id);
|
|
253
|
+
const existing = snapshot.nodes.find((n) => n.id === id);
|
|
254
|
+
addNode({ action: "upsert_entity", id, entity_type: "AzureSubscription", name: cached?.name ?? existing?.name ?? declaration.id,
|
|
255
|
+
description: `Azure subscription UUID ${declaration.id}, explicitly referenced in configuration; not proof of live deployment.`, source: declaration.source }, ["repos", ...(cached ? ["subscriptions" as const] : [])]);
|
|
256
|
+
addEdge({ action: "upsert_edge", from: id, to: declaration.environment, edge_type: "IN_ENVIRONMENT", description: "Subscription ID and environment are explicitly declared together in configuration; not proof of live deployment.", source: declaration.source }, ["repos"]);
|
|
257
|
+
}
|
|
258
|
+
return result;
|
|
259
|
+
}
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
import { isDeepStrictEqual } from "node:util";
|
|
2
|
+
import type { ConditionalResult, Entity, GraphEdge, GraphSnapshot, GraphState } from "../store.js";
|
|
3
|
+
import type { GraphInput } from "../ontology.js";
|
|
4
|
+
import { edgeKey, type Domain, type Inventory } from "./inventory.js";
|
|
5
|
+
|
|
6
|
+
export interface Owned<T> { state: T; domains: Domain[] }
|
|
7
|
+
export interface Manifest {
|
|
8
|
+
version: 1;
|
|
9
|
+
database: string;
|
|
10
|
+
nodes: Record<string, Owned<Entity>>;
|
|
11
|
+
edges: Record<string, Owned<GraphEdge>>;
|
|
12
|
+
}
|
|
13
|
+
export interface Operation { input: GraphInput; expected: GraphState; own: boolean; domains: Domain[] }
|
|
14
|
+
export interface RefreshPlan {
|
|
15
|
+
operations: Operation[];
|
|
16
|
+
manifest: Manifest;
|
|
17
|
+
issues: string[];
|
|
18
|
+
missingUnmanagedNodes: string[];
|
|
19
|
+
missingUnmanagedEdges: string[];
|
|
20
|
+
}
|
|
21
|
+
export interface RefreshClient { executeConditional(input: GraphInput, expected: GraphState, signal?: AbortSignal): Promise<ConditionalResult> }
|
|
22
|
+
export const emptyManifest = (database: string): Manifest => ({ version: 1, database, nodes: {}, edges: {} });
|
|
23
|
+
const same = (current: GraphState, owned?: Owned<GraphState>) => !!owned && isDeepStrictEqual(current, owned.state);
|
|
24
|
+
const changedFields = (input: GraphInput, current: Entity) => Object.entries(input).some(([key, value]) => key !== "action" && value !== undefined && !isDeepStrictEqual(value, current[key as keyof Entity]));
|
|
25
|
+
|
|
26
|
+
/** Legacy/manual facts are never adopted. Edited owned facts lose ownership rather than being clobbered. */
|
|
27
|
+
export function buildPlan(snapshot: GraphSnapshot, inventory: Inventory, prior: Manifest): RefreshPlan {
|
|
28
|
+
if (snapshot.truncated) throw new Error("Refresh requires a complete snapshot; graph exceeds the 1000-node/4000-edge API cap. No pruning or writes were attempted.");
|
|
29
|
+
if (prior.version !== 1 || prior.database !== snapshot.database) throw new Error("Ownership manifest belongs to a different database/version");
|
|
30
|
+
const manifest: Manifest = structuredClone(prior);
|
|
31
|
+
const operations: Operation[] = [];
|
|
32
|
+
const issues = [...inventory.issues];
|
|
33
|
+
const nodes = new Map(snapshot.nodes.map((n) => [n.id, n]));
|
|
34
|
+
const edges = new Map(snapshot.edges.map((e) => [edgeKey(e.from, e.edge_type, e.to), e]));
|
|
35
|
+
for (const [id, owned] of Object.entries(manifest.nodes)) {
|
|
36
|
+
const current = nodes.get(id);
|
|
37
|
+
if (current && !same(current, owned)) { delete manifest.nodes[id]; issues.push(`Released ownership of edited entity: ${id}`); }
|
|
38
|
+
}
|
|
39
|
+
for (const [key, owned] of Object.entries(manifest.edges)) {
|
|
40
|
+
const current = edges.get(key);
|
|
41
|
+
if (current && !same(current, owned)) { delete manifest.edges[key]; issues.push(`Released ownership of edited relationship: ${key}`); }
|
|
42
|
+
}
|
|
43
|
+
const domains = (fresh: Domain[], old?: Owned<GraphState>) => [...new Set([...fresh, ...(old?.domains.filter((d) => !inventory.complete[d]) ?? [])])];
|
|
44
|
+
for (const [id, fact] of inventory.nodes) {
|
|
45
|
+
const current = nodes.get(id) ?? null;
|
|
46
|
+
if (current && current.entity_type !== fact.input.entity_type) { issues.push(`Entity ID/type conflict: ${id}`); continue; }
|
|
47
|
+
const owned = manifest.nodes[id];
|
|
48
|
+
const input = { ...fact.input };
|
|
49
|
+
if (current && !owned) {
|
|
50
|
+
// Preserve manual labels, descriptions, evidence, stage, and immutable kinds.
|
|
51
|
+
input.name = current.name;
|
|
52
|
+
delete input.description; delete input.source; delete input.stage;
|
|
53
|
+
if (input.entity_type === "Repo") input.kind = current.kind!;
|
|
54
|
+
}
|
|
55
|
+
const scope = domains(fact.domains, owned);
|
|
56
|
+
if (owned) owned.domains = scope;
|
|
57
|
+
if (!current || changedFields(input, current)) operations.push({ input, expected: current, own: !current || !!owned, domains: scope });
|
|
58
|
+
}
|
|
59
|
+
for (const [key, fact] of inventory.edges) {
|
|
60
|
+
const current = edges.get(key) ?? null;
|
|
61
|
+
const owned = manifest.edges[key];
|
|
62
|
+
if (current && !owned) continue; // Preserve all manual edge evidence/labels.
|
|
63
|
+
const scope = domains(fact.domains, owned);
|
|
64
|
+
if (owned) owned.domains = scope;
|
|
65
|
+
if (!current || current.description !== fact.input.description || current.source !== fact.input.source) {
|
|
66
|
+
operations.push({ input: fact.input, expected: current, own: true, domains: scope });
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
// Remove owned relationships first. Entity CAS refuses deletion if ANY relationship remains.
|
|
70
|
+
for (const [key, owned] of Object.entries(manifest.edges)) {
|
|
71
|
+
if (inventory.edges.has(key) || inventory.protectedEdgesFrom.has(owned.state.from) || owned.domains.some((d) => !inventory.complete[d])) continue;
|
|
72
|
+
const state = edges.get(key);
|
|
73
|
+
if (!state) { delete manifest.edges[key]; continue; }
|
|
74
|
+
operations.push({ input: { action: "delete_edge", from: state.from, to: state.to, edge_type: state.edge_type as GraphInput["edge_type"] }, expected: state, own: true, domains: owned.domains });
|
|
75
|
+
}
|
|
76
|
+
for (const [id, owned] of Object.entries(manifest.nodes)) {
|
|
77
|
+
if (inventory.nodes.has(id) || owned.domains.some((d) => !inventory.complete[d])) continue;
|
|
78
|
+
const state = nodes.get(id);
|
|
79
|
+
if (!state) { delete manifest.nodes[id]; continue; }
|
|
80
|
+
operations.push({ input: { action: "delete_entity", id }, expected: state, own: true, domains: owned.domains });
|
|
81
|
+
}
|
|
82
|
+
return { operations, manifest, issues,
|
|
83
|
+
missingUnmanagedNodes: snapshot.nodes.filter((n) => !inventory.nodes.has(n.id) && !prior.nodes[n.id]).map((n) => n.id),
|
|
84
|
+
missingUnmanagedEdges: snapshot.edges.filter((e) => { const key = edgeKey(e.from, e.edge_type, e.to); return !inventory.edges.has(key) && !prior.edges[key]; }).map((e) => edgeKey(e.from, e.edge_type, e.to)) };
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
export async function applyPlan(client: RefreshClient, plan: RefreshPlan, persist: (manifest: Manifest, pending?: Operation) => Promise<void>, signal?: AbortSignal) {
|
|
88
|
+
let applied = 0;
|
|
89
|
+
const conflicts: { input: GraphInput; reason: string }[] = [];
|
|
90
|
+
await persist(plan.manifest);
|
|
91
|
+
for (const op of plan.operations) {
|
|
92
|
+
signal?.throwIfAborted();
|
|
93
|
+
await persist(plan.manifest, op); // Durable pending marker before the request (no blind retries).
|
|
94
|
+
const result = await client.executeConditional(op.input, op.expected, signal);
|
|
95
|
+
const entity = op.input.action.endsWith("entity");
|
|
96
|
+
const key = entity ? op.input.id! : edgeKey(op.input.from!, op.input.edge_type!, op.input.to!);
|
|
97
|
+
const collection = entity ? plan.manifest.nodes : plan.manifest.edges;
|
|
98
|
+
if (!result.applied) {
|
|
99
|
+
conflicts.push({ input: op.input, reason: result.reason ?? "Concurrent change" });
|
|
100
|
+
if (result.reason !== "Entity still has relationships; refusing detach deletion") delete collection[key];
|
|
101
|
+
} else {
|
|
102
|
+
applied++;
|
|
103
|
+
if (op.input.action.startsWith("delete")) delete collection[key];
|
|
104
|
+
else if (op.own && result.state) {
|
|
105
|
+
if (entity) plan.manifest.nodes[key] = { state: result.state as Entity, domains: op.domains };
|
|
106
|
+
else plan.manifest.edges[key] = { state: result.state as GraphEdge, domains: op.domains };
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
await persist(plan.manifest); // Clears pending only after ownership is durable.
|
|
110
|
+
}
|
|
111
|
+
return { applied, conflicts };
|
|
112
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
// Runtime dependency, independent of Pi's loader and development-only tsx.
|
|
2
|
+
import { createJiti } from "jiti";
|
|
3
|
+
const jiti = createJiti(import.meta.url);
|
|
4
|
+
try {
|
|
5
|
+
const { runService } = await jiti.import("./service.ts");
|
|
6
|
+
await runService(process.argv[2], process.argv[3]);
|
|
7
|
+
} catch (error) {
|
|
8
|
+
process.send?.({ error: error instanceof Error ? error.message : String(error) });
|
|
9
|
+
process.exitCode = 1;
|
|
10
|
+
if (process.connected) process.disconnect();
|
|
11
|
+
}
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
import { mkdir, readFile, realpath } from "node:fs/promises";
|
|
2
|
+
import { basename, dirname, join, resolve } from "node:path";
|
|
3
|
+
import { request } from "node:http";
|
|
4
|
+
import lockfile from "proper-lockfile";
|
|
5
|
+
|
|
6
|
+
// v5 requires an explicit opt-in before serving the unauthenticated explorer.
|
|
7
|
+
export const SERVICE_VERSION = 5;
|
|
8
|
+
export const explorerEnabled = () => process.env.PI_KNOWLEDGE_GRAPH_EXPLORER === "1";
|
|
9
|
+
// Keep the shared browser URL available; explicit positive values are used by idle tests.
|
|
10
|
+
export const IDLE_MS = 0;
|
|
11
|
+
// 7432 is reserved for pi-extensible-workflows' trajectory server.
|
|
12
|
+
export const DEFAULT_SERVICE_PORT = 7450;
|
|
13
|
+
|
|
14
|
+
/** Zero explicitly requests an ephemeral port (useful for isolated tests/services). */
|
|
15
|
+
export function servicePort(value = process.env.PI_KNOWLEDGE_GRAPH_PORT): number {
|
|
16
|
+
if (value === undefined) return DEFAULT_SERVICE_PORT;
|
|
17
|
+
if (!/^\d+$/.test(value) || !Number.isInteger(Number(value)) || Number(value) > 65535) {
|
|
18
|
+
throw new Error("PI_KNOWLEDGE_GRAPH_PORT must be an integer from 0 to 65535 (default 7450)");
|
|
19
|
+
}
|
|
20
|
+
return Number(value);
|
|
21
|
+
}
|
|
22
|
+
export interface ServiceEndpoint { version: number; database: string; pid: number; port: number; token: string }
|
|
23
|
+
export const descriptorPath = (path: string) => `${path}.service.json`;
|
|
24
|
+
|
|
25
|
+
/** Resolve aliases before choosing the service identity, including new databases. */
|
|
26
|
+
export async function canonicalDatabase(path: string): Promise<string> {
|
|
27
|
+
path = resolve(path);
|
|
28
|
+
await mkdir(dirname(path), { recursive: true, mode: 0o700 });
|
|
29
|
+
try { return await realpath(path); }
|
|
30
|
+
catch (error) {
|
|
31
|
+
if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
|
|
32
|
+
return join(await realpath(dirname(path)), basename(path));
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export async function readEndpoint(path: string): Promise<ServiceEndpoint | undefined> {
|
|
37
|
+
try {
|
|
38
|
+
const value = JSON.parse(await readFile(descriptorPath(path), "utf8")) as ServiceEndpoint;
|
|
39
|
+
if (value.database !== path || !Number.isInteger(value.pid) || value.pid < 1 ||
|
|
40
|
+
!Number.isInteger(value.port) || value.port < 1 || value.port > 65535 ||
|
|
41
|
+
!/^[a-f0-9]{48}$/.test(value.token)) throw new Error("Invalid knowledge graph service descriptor");
|
|
42
|
+
return value;
|
|
43
|
+
} catch (error) {
|
|
44
|
+
if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined;
|
|
45
|
+
throw error;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export function processAlive(pid: number): boolean {
|
|
50
|
+
try { process.kill(pid, 0); return true; }
|
|
51
|
+
catch (error) { return (error as NodeJS.ErrnoException).code !== "ESRCH"; }
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** Atomic mkdir lock with heartbeat/stale recovery; shared by startup and idle shutdown. */
|
|
55
|
+
export function startupLock(path: string): Promise<() => Promise<void>> {
|
|
56
|
+
return lockfile.lock(`${path}.service-start`, {
|
|
57
|
+
realpath: false, stale: 30_000, update: 10_000,
|
|
58
|
+
retries: { retries: 150, minTimeout: 100, maxTimeout: 200, randomize: true },
|
|
59
|
+
});
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** No automatic retries: a lost response may already represent a committed mutation. */
|
|
63
|
+
export function serviceRequest(endpoint: ServiceEndpoint, route: string, input?: unknown, signal?: AbortSignal, timeout = 30_000): Promise<unknown> {
|
|
64
|
+
signal?.throwIfAborted();
|
|
65
|
+
return new Promise((resolve, reject) => {
|
|
66
|
+
const body = input === undefined ? undefined : JSON.stringify(input);
|
|
67
|
+
const req = request({
|
|
68
|
+
hostname: "127.0.0.1", port: endpoint.port, path: route,
|
|
69
|
+
method: body === undefined ? "GET" : "POST", signal,
|
|
70
|
+
headers: { Authorization: `Bearer ${endpoint.token}`, Connection: "close",
|
|
71
|
+
...(body === undefined ? {} : { "Content-Type": "application/json", "Content-Length": Buffer.byteLength(body) }) },
|
|
72
|
+
}, (res) => {
|
|
73
|
+
const chunks: Buffer[] = [];
|
|
74
|
+
let size = 0;
|
|
75
|
+
res.on("data", (chunk: Buffer) => {
|
|
76
|
+
size += chunk.length;
|
|
77
|
+
if (size > 64 * 1024 * 1024) { res.destroy(new Error("Knowledge graph service response exceeds 64 MiB")); return; }
|
|
78
|
+
chunks.push(chunk);
|
|
79
|
+
});
|
|
80
|
+
res.on("error", reject);
|
|
81
|
+
res.on("end", () => {
|
|
82
|
+
try {
|
|
83
|
+
const value = JSON.parse(Buffer.concat(chunks).toString("utf8"));
|
|
84
|
+
if (res.statusCode !== 200) reject(new Error(value.error ?? `Knowledge graph service HTTP ${res.statusCode}`));
|
|
85
|
+
else resolve(value);
|
|
86
|
+
} catch (error) { reject(error); }
|
|
87
|
+
});
|
|
88
|
+
});
|
|
89
|
+
const timer = setTimeout(() => req.destroy(new Error("Knowledge graph service request timed out; mutation outcome may be unknown")), timeout);
|
|
90
|
+
req.on("close", () => clearTimeout(timer));
|
|
91
|
+
req.on("error", reject);
|
|
92
|
+
req.end(body);
|
|
93
|
+
});
|
|
94
|
+
}
|
package/src/service.ts
ADDED
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
import { createServer } from "node:http";
|
|
2
|
+
import { randomBytes } from "node:crypto";
|
|
3
|
+
import { rename, rm, writeFile } from "node:fs/promises";
|
|
4
|
+
import { GraphStore, type GraphState } from "./store.js";
|
|
5
|
+
import { ACTIONS, ONTOLOGY, type GraphInput } from "./ontology.js";
|
|
6
|
+
import { fingerprint } from "./config.js";
|
|
7
|
+
import { createExplorerHandler, explorerPaths } from "./explorer.js";
|
|
8
|
+
import { descriptorPath, explorerEnabled, IDLE_MS, readEndpoint, SERVICE_VERSION, servicePort, startupLock, type ServiceEndpoint } from "./service-protocol.js";
|
|
9
|
+
|
|
10
|
+
/** Shared read-only browser UI plus token-protected fixed-action API, all loopback-only. */
|
|
11
|
+
export async function startService(path: string, idleMs = IDLE_MS, port = servicePort()) {
|
|
12
|
+
if (!Number.isInteger(port) || port < 0 || port > 65535) throw new Error("Invalid knowledge graph service port");
|
|
13
|
+
const graph = new GraphStore(path);
|
|
14
|
+
const token = randomBytes(24).toString("hex");
|
|
15
|
+
let active = 0;
|
|
16
|
+
let lastUse = Date.now();
|
|
17
|
+
let stopping = false;
|
|
18
|
+
let shutdown: Promise<void> | undefined;
|
|
19
|
+
const browser = explorerEnabled() ? await createExplorerHandler(() => graph.snapshot(), "/", () => `http://127.0.0.1:${endpoint.port}`) : undefined;
|
|
20
|
+
const server = createServer(async (req, res) => {
|
|
21
|
+
const reply = (status: number, data: unknown) => {
|
|
22
|
+
if (res.destroyed) return;
|
|
23
|
+
res.writeHead(status, { "Content-Type": "application/json", "Cache-Control": "no-store" });
|
|
24
|
+
res.end(JSON.stringify(data, (_key, value) => typeof value === "bigint" ? Number(value) : value));
|
|
25
|
+
};
|
|
26
|
+
if (stopping) { reply(503, { error: "Knowledge graph service is stopping" }); return; }
|
|
27
|
+
if (explorerPaths.has((req.url ?? "/").split("?")[0]!)) {
|
|
28
|
+
if (!browser) { reply(404, { error: "Not found" }); return; }
|
|
29
|
+
if (active >= 128) { reply(503, { error: "Knowledge graph service queue is full" }); return; }
|
|
30
|
+
active++;
|
|
31
|
+
try { await browser(req, res); }
|
|
32
|
+
finally { active--; lastUse = Date.now(); }
|
|
33
|
+
return;
|
|
34
|
+
}
|
|
35
|
+
if (req.headers.host !== `127.0.0.1:${endpoint.port}` || req.headers.origin ||
|
|
36
|
+
req.headers.authorization !== `Bearer ${token}`) { reply(403, { error: "Forbidden" }); return; }
|
|
37
|
+
if (req.url === "/health" && req.method === "GET") {
|
|
38
|
+
lastUse = Date.now(); reply(200, { version: SERVICE_VERSION, database: path, pid: process.pid, capabilities: ["conditional-refresh"], explorer: !!browser, ontology: fingerprint(graph.ontology) }); return;
|
|
39
|
+
}
|
|
40
|
+
if (!((["/execute", "/refresh"].includes(req.url ?? "") && req.method === "POST") || (req.url === "/snapshot" && req.method === "GET"))) {
|
|
41
|
+
reply(404, { error: "Not found" }); return;
|
|
42
|
+
}
|
|
43
|
+
if (active >= 128) { reply(503, { error: "Knowledge graph service queue is full" }); return; }
|
|
44
|
+
active++;
|
|
45
|
+
const controller = new AbortController();
|
|
46
|
+
const onClose = () => { if (!res.writableEnded) controller.abort(); };
|
|
47
|
+
res.on("close", onClose);
|
|
48
|
+
try {
|
|
49
|
+
let input: GraphInput | undefined;
|
|
50
|
+
let expected: GraphState | undefined;
|
|
51
|
+
if (req.method === "POST") {
|
|
52
|
+
if (req.headers["content-type"] !== "application/json") { reply(415, { error: "Expected JSON" }); return; }
|
|
53
|
+
const chunks: Buffer[] = [];
|
|
54
|
+
let size = 0;
|
|
55
|
+
for await (const chunk of req) {
|
|
56
|
+
size += chunk.length;
|
|
57
|
+
if (size > 128 * 1024) { reply(413, { error: "Request exceeds 128 KiB" }); return; }
|
|
58
|
+
chunks.push(chunk);
|
|
59
|
+
}
|
|
60
|
+
const payload = JSON.parse(Buffer.concat(chunks).toString("utf8"));
|
|
61
|
+
input = req.url === "/refresh" ? payload?.input : payload;
|
|
62
|
+
expected = req.url === "/refresh" ? payload?.expected : undefined;
|
|
63
|
+
if (!input || typeof input !== "object" || !ACTIONS.includes(input.action)) throw new Error("Invalid graph action");
|
|
64
|
+
}
|
|
65
|
+
controller.signal.throwIfAborted();
|
|
66
|
+
const data = req.url === "/refresh"
|
|
67
|
+
? await graph.executeConditional(input!, expected!, controller.signal)
|
|
68
|
+
: input ? await graph.execute(input, controller.signal) : await graph.snapshot();
|
|
69
|
+
reply(200, data);
|
|
70
|
+
} catch (error) { reply(400, { error: error instanceof Error ? error.message : String(error) }); }
|
|
71
|
+
finally { active--; lastUse = Date.now(); res.removeListener("close", onClose); }
|
|
72
|
+
});
|
|
73
|
+
server.requestTimeout = 30_000;
|
|
74
|
+
server.headersTimeout = 10_000;
|
|
75
|
+
server.timeout = 30_000;
|
|
76
|
+
const endpoint: ServiceEndpoint = { version: SERVICE_VERSION, database: path, pid: process.pid, port: 0, token };
|
|
77
|
+
const temporary = `${descriptorPath(path)}.${process.pid}.tmp`;
|
|
78
|
+
try {
|
|
79
|
+
// Open and validate before announcing readiness. Keep LadybugDB's native writer lock intact.
|
|
80
|
+
await graph.execute({ action: "search", limit: 1 });
|
|
81
|
+
await new Promise<void>((resolve, reject) => {
|
|
82
|
+
const onError = (error: NodeJS.ErrnoException) => reject(error.code === "EADDRINUSE"
|
|
83
|
+
? new Error(`Knowledge graph HTTP port ${port} is already in use. Set PI_KNOWLEDGE_GRAPH_PORT to a different port for this database; no random-port fallback is performed.`)
|
|
84
|
+
: error);
|
|
85
|
+
server.once("error", onError);
|
|
86
|
+
server.listen(port, "127.0.0.1", () => { server.removeListener("error", onError); resolve(); });
|
|
87
|
+
});
|
|
88
|
+
endpoint.port = (server.address() as import("node:net").AddressInfo).port;
|
|
89
|
+
await writeFile(temporary, JSON.stringify(endpoint), { mode: 0o600, flag: "wx" });
|
|
90
|
+
await rename(temporary, descriptorPath(path));
|
|
91
|
+
} catch (error) {
|
|
92
|
+
server.close();
|
|
93
|
+
await graph.close();
|
|
94
|
+
await rm(temporary, { force: true });
|
|
95
|
+
throw error;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
const stop = (idleOnly = false): Promise<void> => {
|
|
99
|
+
if (shutdown) return shutdown;
|
|
100
|
+
shutdown = (async () => {
|
|
101
|
+
const release = await startupLock(path);
|
|
102
|
+
try {
|
|
103
|
+
if (idleOnly && (active || Date.now() - lastUse < idleMs)) { shutdown = undefined; return; }
|
|
104
|
+
stopping = true;
|
|
105
|
+
clearInterval(timer);
|
|
106
|
+
await new Promise<void>((resolve, reject) => server.close((error) => error ? reject(error) : resolve()));
|
|
107
|
+
await graph.close();
|
|
108
|
+
if ((await readEndpoint(path))?.token === token) await rm(descriptorPath(path), { force: true });
|
|
109
|
+
} finally { await release(); }
|
|
110
|
+
})();
|
|
111
|
+
return shutdown;
|
|
112
|
+
};
|
|
113
|
+
// Production stays available for direct browser visits even when Pi sessions are idle/closed.
|
|
114
|
+
const timer = idleMs > 0 ? setInterval(() => {
|
|
115
|
+
if (!active && Date.now() - lastUse >= idleMs) void stop(true).catch(() => process.exit(1));
|
|
116
|
+
}, Math.min(idleMs, 5_000)) : undefined;
|
|
117
|
+
return { endpoint, close: () => stop() };
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
export async function runService(path: string, expectedOntology: string | undefined) {
|
|
121
|
+
process.umask(0o077);
|
|
122
|
+
try {
|
|
123
|
+
// Validate the daemon's loaded configuration before GraphStore can open storage or run DDL.
|
|
124
|
+
if (fingerprint(ONTOLOGY) !== expectedOntology) {
|
|
125
|
+
throw new Error("Knowledge graph ontology changed since the client loaded it; reload before starting the service");
|
|
126
|
+
}
|
|
127
|
+
const service = await startService(path);
|
|
128
|
+
const stop = () => { void service.close().then(() => process.exit(0), () => process.exit(1)); };
|
|
129
|
+
process.on("SIGTERM", stop);
|
|
130
|
+
process.on("SIGINT", stop);
|
|
131
|
+
process.send?.({ endpoint: service.endpoint });
|
|
132
|
+
process.disconnect?.();
|
|
133
|
+
} catch (error) {
|
|
134
|
+
process.send?.({ error: error instanceof Error ? error.message : String(error) });
|
|
135
|
+
process.exitCode = 1;
|
|
136
|
+
if (process.connected) process.disconnect();
|
|
137
|
+
}
|
|
138
|
+
}
|