@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,125 @@
|
|
|
1
|
+
import { fork } from "node:child_process";
|
|
2
|
+
import { fileURLToPath } from "node:url";
|
|
3
|
+
import { resolve } from "node:path";
|
|
4
|
+
import { renderedSchema, type GraphInput } from "./ontology.js";
|
|
5
|
+
import { defaultOntologyPath, fingerprint, loadOntology } from "./config.js";
|
|
6
|
+
import type { ConditionalResult, GraphSnapshot, GraphState } from "./store.js";
|
|
7
|
+
import { canonicalDatabase, explorerEnabled, processAlive, readEndpoint, SERVICE_VERSION, servicePort, serviceRequest, startupLock, type ServiceEndpoint } from "./service-protocol.js";
|
|
8
|
+
|
|
9
|
+
async function launch(path: string, ontologyPath: string, expectedOntology: string): Promise<ServiceEndpoint> {
|
|
10
|
+
const child = fork(fileURLToPath(new URL("./service-bootstrap.mjs", import.meta.url)), [path, expectedOntology], {
|
|
11
|
+
detached: true, stdio: ["ignore", "ignore", "ignore", "ipc"], execArgv: [],
|
|
12
|
+
// Bun hosts must never load Ladybug's Node native binding in-process.
|
|
13
|
+
execPath: process.env.PI_KNOWLEDGE_GRAPH_NODE ?? ((process.versions as Record<string, string>).bun ? "node" : process.execPath),
|
|
14
|
+
env: {...process.env, PI_KNOWLEDGE_GRAPH_ONTOLOGY: ontologyPath},
|
|
15
|
+
});
|
|
16
|
+
try {
|
|
17
|
+
return await new Promise<ServiceEndpoint>((resolve, reject) => {
|
|
18
|
+
const timer = setTimeout(() => {
|
|
19
|
+
child.kill("SIGTERM");
|
|
20
|
+
reject(new Error("Knowledge graph service startup timed out"));
|
|
21
|
+
}, 20_000);
|
|
22
|
+
const finish = (error?: Error, endpoint?: ServiceEndpoint) => {
|
|
23
|
+
clearTimeout(timer);
|
|
24
|
+
child.removeAllListeners();
|
|
25
|
+
if (error) reject(error); else resolve(endpoint!);
|
|
26
|
+
};
|
|
27
|
+
child.once("error", (error) => finish(error));
|
|
28
|
+
child.once("exit", (code, signal) => finish(new Error(`Knowledge graph service exited during startup (${signal ?? code})`)));
|
|
29
|
+
child.once("message", (message: any) => {
|
|
30
|
+
if (message.error) finish(new Error(message.error));
|
|
31
|
+
else finish(undefined, message.endpoint);
|
|
32
|
+
});
|
|
33
|
+
});
|
|
34
|
+
} finally {
|
|
35
|
+
if (child.connected) child.disconnect();
|
|
36
|
+
child.unref();
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** Lazy client. The service, not a Pi session, owns the native database connection. */
|
|
41
|
+
export class SharedGraphStore {
|
|
42
|
+
readonly path: string;
|
|
43
|
+
private closed = false;
|
|
44
|
+
private canonical?: Promise<string>;
|
|
45
|
+
private controllers = new Set<AbortController>();
|
|
46
|
+
|
|
47
|
+
readonly ontology;
|
|
48
|
+
readonly ontologyPath: string;
|
|
49
|
+
constructor(path: string, ontologyPath = process.env.PI_KNOWLEDGE_GRAPH_ONTOLOGY ?? defaultOntologyPath) {
|
|
50
|
+
this.path = resolve(path); this.ontologyPath = resolve(ontologyPath); this.ontology = loadOntology(this.ontologyPath);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
private async endpoint(signal: AbortSignal, requireRefresh = false): Promise<ServiceEndpoint> {
|
|
54
|
+
const port = servicePort();
|
|
55
|
+
const path = await (this.canonical ??= canonicalDatabase(this.path));
|
|
56
|
+
signal.throwIfAborted();
|
|
57
|
+
const release = await startupLock(path);
|
|
58
|
+
try {
|
|
59
|
+
signal.throwIfAborted();
|
|
60
|
+
const existing = await readEndpoint(path);
|
|
61
|
+
if (existing && processAlive(existing.pid)) {
|
|
62
|
+
if (existing.version !== SERVICE_VERSION) throw new Error("Knowledge graph service version changed; stop the old service before restarting");
|
|
63
|
+
if (port !== 0 && existing.port !== port) throw new Error(`Knowledge graph service is running on port ${existing.port}, but port ${port} is configured. Stop the old service before restarting, or set PI_KNOWLEDGE_GRAPH_PORT=${existing.port}.`);
|
|
64
|
+
// Never replace a live but unresponsive process or bypass its database writer lock.
|
|
65
|
+
const health = await serviceRequest(existing, "/health", undefined, signal, 2_000) as { capabilities?: string[]; ontology?: string; explorer?: boolean };
|
|
66
|
+
if (Boolean(health.explorer) !== explorerEnabled()) {
|
|
67
|
+
throw new Error("Knowledge graph explorer setting differs from the running owner; stop it and restart all clients with matching PI_KNOWLEDGE_GRAPH_EXPLORER settings");
|
|
68
|
+
}
|
|
69
|
+
if (requireRefresh && !health.capabilities?.includes("conditional-refresh")) throw new Error("Shared owner predates conditional refresh; stop the old owner and restart it before applying updates");
|
|
70
|
+
if (health.ontology !== fingerprint(this.ontology)) throw new Error("Knowledge graph ontology differs from shared daemon; stop the owner and reload all clients with matching configuration");
|
|
71
|
+
return existing;
|
|
72
|
+
}
|
|
73
|
+
const endpoint = await launch(path, this.ontologyPath, fingerprint(this.ontology));
|
|
74
|
+
const health = await serviceRequest(endpoint, "/health", undefined, signal) as {ontology?: string};
|
|
75
|
+
if (health.ontology !== fingerprint(this.ontology)) throw new Error("Knowledge graph ontology changed during daemon startup; reload");
|
|
76
|
+
return endpoint;
|
|
77
|
+
} finally { await release(); }
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
private async request(route: string, input?: GraphInput | { input: GraphInput; expected: GraphState }, signal?: AbortSignal): Promise<unknown> {
|
|
81
|
+
if (this.closed) throw new Error("Knowledge graph is closed");
|
|
82
|
+
const controller = new AbortController();
|
|
83
|
+
this.controllers.add(controller);
|
|
84
|
+
const combined = signal ? AbortSignal.any([signal, controller.signal]) : controller.signal;
|
|
85
|
+
try {
|
|
86
|
+
combined.throwIfAborted();
|
|
87
|
+
const endpoint = await this.endpoint(combined, route === "/refresh");
|
|
88
|
+
combined.throwIfAborted();
|
|
89
|
+
return await serviceRequest(endpoint, route, input, combined);
|
|
90
|
+
} finally { this.controllers.delete(controller); }
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
execute(input: GraphInput, signal?: AbortSignal): Promise<unknown> {
|
|
94
|
+
if (this.closed) return Promise.reject(new Error("Knowledge graph is closed"));
|
|
95
|
+
signal?.throwIfAborted();
|
|
96
|
+
// Schema inspection does not create directories or start a process.
|
|
97
|
+
if (input.action === "schema") return Promise.resolve(renderedSchema(this.ontology));
|
|
98
|
+
return this.request("/execute", input, signal);
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
executeConditional(input: GraphInput, expected: GraphState, signal?: AbortSignal): Promise<ConditionalResult> {
|
|
102
|
+
return this.request("/refresh", { input, expected }, signal) as Promise<ConditionalResult>;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
snapshot(): Promise<GraphSnapshot> { return this.request("/snapshot") as Promise<GraphSnapshot>; }
|
|
106
|
+
|
|
107
|
+
/** Ensure the service is running and return its plain shared browser URL. */
|
|
108
|
+
async url(): Promise<string> {
|
|
109
|
+
if (this.closed) throw new Error("Knowledge graph is closed");
|
|
110
|
+
if (!explorerEnabled()) throw new Error("Graph explorer is disabled. Set PI_KNOWLEDGE_GRAPH_EXPLORER=1 before starting the graph owner.");
|
|
111
|
+
const controller = new AbortController();
|
|
112
|
+
this.controllers.add(controller);
|
|
113
|
+
try {
|
|
114
|
+
const endpoint = await this.endpoint(controller.signal);
|
|
115
|
+
controller.signal.throwIfAborted();
|
|
116
|
+
return `http://127.0.0.1:${endpoint.port}/`;
|
|
117
|
+
} finally { this.controllers.delete(controller); }
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
async close(): Promise<void> {
|
|
121
|
+
this.closed = true;
|
|
122
|
+
for (const controller of this.controllers) controller.abort();
|
|
123
|
+
// Do not terminate the shared service: other sessions may be using it.
|
|
124
|
+
}
|
|
125
|
+
}
|
package/src/store.ts
ADDED
|
@@ -0,0 +1,385 @@
|
|
|
1
|
+
import { mkdir, readFile, writeFile, rename } from "node:fs/promises";
|
|
2
|
+
import { ONTOLOGY, edgeRules, endpointTypes, renderedSchema } from "./ontology.js";
|
|
3
|
+
import { assertCompatible, columns, loadOntology, legacyOntologyPath, sqlType, validateValue, validateOntology, deepFreeze, type Ontology, type Attribute } from "./config.js";
|
|
4
|
+
import { isDeepStrictEqual } from "node:util";
|
|
5
|
+
import { dirname, resolve } from "node:path";
|
|
6
|
+
import lbug, { type LbugValue } from "@ladybugdb/core";
|
|
7
|
+
import {
|
|
8
|
+
ACTIONS, GRAPH_SCHEMA,
|
|
9
|
+
optionalText, text, type EntityType, type GraphInput, type RepoKind, type EnvironmentStage,
|
|
10
|
+
} from "./ontology.js";
|
|
11
|
+
|
|
12
|
+
export interface Entity {
|
|
13
|
+
[attribute: string]: unknown;
|
|
14
|
+
id: string;
|
|
15
|
+
entity_type: EntityType;
|
|
16
|
+
name: string;
|
|
17
|
+
kind: RepoKind | null;
|
|
18
|
+
stage: EnvironmentStage | null;
|
|
19
|
+
localPath: string | null;
|
|
20
|
+
gitlabUrl: string | null;
|
|
21
|
+
description: string;
|
|
22
|
+
source: string;
|
|
23
|
+
created_at: string;
|
|
24
|
+
updated_at: string;
|
|
25
|
+
}
|
|
26
|
+
export interface GraphEdge {
|
|
27
|
+
[attribute: string]: unknown;
|
|
28
|
+
from: string;
|
|
29
|
+
to: string;
|
|
30
|
+
edge_type: string;
|
|
31
|
+
description: string;
|
|
32
|
+
source: string;
|
|
33
|
+
created_at: string;
|
|
34
|
+
updated_at: string;
|
|
35
|
+
}
|
|
36
|
+
export type GraphState = Entity | GraphEdge | null;
|
|
37
|
+
export interface ConditionalResult { applied: boolean; state: GraphState; reason?: string }
|
|
38
|
+
export interface GraphSnapshot {
|
|
39
|
+
database: string;
|
|
40
|
+
nodes: Entity[];
|
|
41
|
+
edges: GraphEdge[];
|
|
42
|
+
totalNodes: number;
|
|
43
|
+
totalEdges: number;
|
|
44
|
+
truncated: boolean;
|
|
45
|
+
schema: typeof GRAPH_SCHEMA;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
const baseColumns: Record<string, Attribute> = { id: {type: "string"}, name: {type: "string"}, created_at: {type: "string"}, updated_at: {type: "string"}, kind: {type: "string"}, stage: {type: "string"}, localPath: {type: "string"}, gitlabUrl: {type: "string"} };
|
|
49
|
+
const entityColumns = (alias: string, config: Ontology) => `label(${alias}) AS entity_type, ` + Object.keys({...baseColumns, ...columns(config)}).map(k => `${alias}.${k} AS ${k}`).join(", ");
|
|
50
|
+
|
|
51
|
+
/** One queued native connection in the shared owner. Handles open on the first operation. */
|
|
52
|
+
export class GraphStore {
|
|
53
|
+
readonly path: string;
|
|
54
|
+
private db?: InstanceType<typeof lbug.Database>;
|
|
55
|
+
private conn?: InstanceType<typeof lbug.Connection>;
|
|
56
|
+
private tail: Promise<unknown> = Promise.resolve();
|
|
57
|
+
private closed = false;
|
|
58
|
+
|
|
59
|
+
readonly ontology: Ontology;
|
|
60
|
+
constructor(path: string, ontology: Ontology = ONTOLOGY) { this.path = resolve(path); this.ontology = deepFreeze(validateOntology(structuredClone(ontology))); }
|
|
61
|
+
|
|
62
|
+
private assertType(type: unknown) { if (typeof type !== "string" || !Object.hasOwn(this.ontology.entities, type)) throw new Error(`Unknown entity type: ${type}`); }
|
|
63
|
+
private assertEdge(type: unknown) { if (typeof type !== "string" || !Object.hasOwn(this.ontology.relationships, type)) throw new Error(`Unknown edge type: ${type}`); }
|
|
64
|
+
private endpoints(edge: string, from: Entity, to: Entity, constraints = false) {
|
|
65
|
+
const rel = this.ontology.relationships[edge];
|
|
66
|
+
if (!endpointTypes(rel.from).includes(from.entity_type) || !endpointTypes(rel.to).includes(to.entity_type)) throw new Error(`${edge} does not allow ${from.entity_type} -> ${to.entity_type}`);
|
|
67
|
+
if (constraints) for (const [ep, node] of [[rel.from, from], [rel.to, to]] as const) for (const [key, value] of Object.entries(ep)) if (key !== "entity_type" && (node as any)[key] !== value) throw new Error(`${edge} requires ${String(rel.from.kind ?? JSON.stringify(rel.from))} -> ${String(rel.to.kind ?? JSON.stringify(rel.to))}`);
|
|
68
|
+
}
|
|
69
|
+
private values(p: GraphInput, defs: Record<string, Attribute>, existing?: Record<string, unknown>) {
|
|
70
|
+
const values: Record<string, string | number | boolean> = {...p.attributes};
|
|
71
|
+
for (const key of ["kind", "stage", "localPath", "gitlabUrl", "description", "source"] as const) if (p[key] !== undefined) {
|
|
72
|
+
if (Object.hasOwn(values, key)) throw new Error(`Duplicate attribute ${key}`);
|
|
73
|
+
values[key] = p[key]!;
|
|
74
|
+
}
|
|
75
|
+
for (const [key, value] of Object.entries(values)) {
|
|
76
|
+
if (!Object.hasOwn(defs, key)) throw new Error(`${key} is not allowed here${["kind", "localPath", "gitlabUrl"].includes(key) ? "; Repo-only attributes" : key === "stage" ? "; Environment-only attribute" : ""}`);
|
|
77
|
+
if (key === "kind" && defs[key].enum && !defs[key].enum.includes(value as string)) throw new Error(`Unknown repo kind: ${value}`);
|
|
78
|
+
if (key === "stage" && defs[key].enum && !defs[key].enum.includes(value as string)) throw new Error(`Unknown environment stage: ${value}`);
|
|
79
|
+
validateValue(value, key, defs[key]);
|
|
80
|
+
if (existing && defs[key].immutable && existing[key] !== value) throw new Error(`${key} cannot change`);
|
|
81
|
+
}
|
|
82
|
+
for (const [key, a] of Object.entries(defs)) if (a.required && values[key] === undefined && existing?.[key] == null) throw new Error(key === "kind" ? "Unknown repo kind: required on creation" : `${key} required on creation`);
|
|
83
|
+
return values;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
private queue<T>(fn: () => Promise<T>): Promise<T> {
|
|
87
|
+
const next = this.tail.then(fn);
|
|
88
|
+
this.tail = next.catch(() => undefined);
|
|
89
|
+
return next;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
private async rows(query: string, params?: Record<string, LbugValue>) {
|
|
93
|
+
const conn = this.conn!;
|
|
94
|
+
const statement = params ? await conn.prepare(query) : undefined;
|
|
95
|
+
if (statement && !statement.isSuccess()) throw new Error(statement.getErrorMessage());
|
|
96
|
+
const result = statement ? await conn.execute(statement, params) : await conn.query(query);
|
|
97
|
+
const results = Array.isArray(result) ? result : [result];
|
|
98
|
+
try { return await results[0]!.getAll(); }
|
|
99
|
+
finally { for (const item of results) item.close(); }
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
private async open() {
|
|
103
|
+
if (this.conn) return;
|
|
104
|
+
await mkdir(dirname(this.path), { recursive: true, mode: 0o700 });
|
|
105
|
+
// Bound memory and CPU use inside the Pi process.
|
|
106
|
+
this.db = new lbug.Database(this.path, 256 * 1024 * 1024);
|
|
107
|
+
try {
|
|
108
|
+
await this.db.init();
|
|
109
|
+
this.conn = new lbug.Connection(this.db, 2);
|
|
110
|
+
await this.conn.init();
|
|
111
|
+
this.conn.setQueryTimeout(5_000);
|
|
112
|
+
const tables = await this.rows("CALL show_tables() RETURN name");
|
|
113
|
+
const allowedNames = new Set([...Object.keys(this.ontology.entities), ...Object.keys(this.ontology.relationships)]);
|
|
114
|
+
if (tables.some(t => !allowedNames.has(String(t.name)))) throw new Error("Incompatible knowledge graph schema: unknown tables");
|
|
115
|
+
const types = Object.keys(this.ontology.entities);
|
|
116
|
+
const rules = edgeRules(this.ontology);
|
|
117
|
+
const allowedTables: readonly string[] = [...types, ...Object.keys(rules)];
|
|
118
|
+
let prior: Ontology;
|
|
119
|
+
let manifested = true;
|
|
120
|
+
try { prior = JSON.parse(await readFile(`${this.path}.ontology.json`, "utf8")); }
|
|
121
|
+
catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; prior = loadOntology(legacyOntologyPath); manifested = false; }
|
|
122
|
+
// Old manifests included non-executable prose; discard it for compatibility.
|
|
123
|
+
delete (prior as Ontology & { rules?: unknown }).rules;
|
|
124
|
+
validateOntology(prior);
|
|
125
|
+
if (tables.length) assertCompatible(prior, this.ontology);
|
|
126
|
+
const nodeCols = {...baseColumns, ...columns(this.ontology)};
|
|
127
|
+
const edgeCols: Record<string, Attribute> = {created_at: {type: "string"} as Attribute, updated_at: {type: "string"} as Attribute, ...columns(this.ontology, true)};
|
|
128
|
+
// Validate every existing column before any DDL. Unmanifested custom schemas are not adopted.
|
|
129
|
+
for (const table of tables) {
|
|
130
|
+
const name = String(table.name);
|
|
131
|
+
const expected = manifested ? (Object.hasOwn(this.ontology.entities, name) ? nodeCols : edgeCols) : (Object.hasOwn(prior.entities, name) ? {...baseColumns, ...columns(prior)} : {created_at: {type: "string"} as Attribute, updated_at: {type: "string"} as Attribute, ...columns(prior, true)});
|
|
132
|
+
const info = await this.rows(`CALL table_info('${name}') RETURN *`);
|
|
133
|
+
for (const col of info) if (!expected[String(col.name)] || sqlType(expected[String(col.name)]) !== col.type) throw new Error(`Incompatible knowledge graph schema: column ${name}.${col.name}`);
|
|
134
|
+
if (Object.hasOwn(this.ontology.entities, name)) {
|
|
135
|
+
if (!["id", "name", "description", "source", "created_at", "updated_at"].every(k => info.some(c => c.name === k))) throw new Error(`Incompatible knowledge graph schema: missing core columns ${name}`);
|
|
136
|
+
if (!info.some(c => c.name === 'id' && c['primary key'] === true)) throw new Error(`Incompatible knowledge graph schema: primary key ${name}`);
|
|
137
|
+
} else {
|
|
138
|
+
const actual = (await this.rows(`CALL show_connection('${name}') RETURN *`)).map(c => `${c['source table name']}->${c['destination table name']}`).sort();
|
|
139
|
+
const expectedPairs = rules[name]?.map(([a,b]) => `${a}->${b}`).sort();
|
|
140
|
+
if (!isDeepStrictEqual(actual, expectedPairs)) throw new Error(`Incompatible knowledge graph schema: endpoints ${name}`);
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
if (tables.some((table) => !allowedTables.includes(String(table.name)))) {
|
|
144
|
+
throw new Error("Incompatible knowledge graph schema. Keep the existing database as a backup and select a fresh path with PI_KNOWLEDGE_GRAPH_DB; only additive migration of the repo-level schema is supported.");
|
|
145
|
+
}
|
|
146
|
+
await this.rows("BEGIN TRANSACTION");
|
|
147
|
+
try {
|
|
148
|
+
for (const type of types) {
|
|
149
|
+
await this.rows(`CREATE NODE TABLE IF NOT EXISTS ${type}(${Object.entries(nodeCols).map(([k,a]) => `${k} ${sqlType(a)}`).join(", ")}, PRIMARY KEY(id))`);
|
|
150
|
+
const existing = await this.rows(`CALL table_info('${type}') RETURN name`);
|
|
151
|
+
for (const [key, a] of Object.entries(nodeCols)) if (!existing.some(c => c.name === key)) await this.rows(`ALTER TABLE ${type} ADD ${key} ${sqlType(a)}`);
|
|
152
|
+
}
|
|
153
|
+
for (const [edge, pairs] of Object.entries(rules)) {
|
|
154
|
+
await this.rows(`CREATE REL TABLE GROUP IF NOT EXISTS ${edge}(${pairs.map(([from,to]) => `FROM ${from} TO ${to}`).join(", ")}, ${Object.entries(edgeCols).map(([k,a]) => `${k} ${sqlType(a)}`).join(", ")})`);
|
|
155
|
+
const existing = await this.rows(`CALL table_info('${edge}') RETURN name`);
|
|
156
|
+
for (const [key, a] of Object.entries(edgeCols)) if (!existing.some(c => c.name === key)) await this.rows(`ALTER TABLE ${edge} ADD ${key} ${sqlType(a)}`);
|
|
157
|
+
}
|
|
158
|
+
await this.rows("COMMIT");
|
|
159
|
+
const manifest = `${this.path}.ontology.json`;
|
|
160
|
+
await writeFile(`${manifest}.tmp`, JSON.stringify(this.ontology), {mode: 0o600});
|
|
161
|
+
await rename(`${manifest}.tmp`, manifest);
|
|
162
|
+
} catch (error) {
|
|
163
|
+
await this.rows("ROLLBACK").catch(() => undefined);
|
|
164
|
+
throw error;
|
|
165
|
+
}
|
|
166
|
+
} catch (error) {
|
|
167
|
+
await this.release();
|
|
168
|
+
throw new Error(`Cannot open LadybugDB at ${this.path}. Another process may hold its writer lock; reload old Pi sessions or close external database clients. ${error instanceof Error ? error.message : error}`);
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
private async release() {
|
|
173
|
+
const conn = this.conn;
|
|
174
|
+
const db = this.db;
|
|
175
|
+
this.conn = undefined;
|
|
176
|
+
this.db = undefined;
|
|
177
|
+
try { await conn?.close(); } finally { await db?.close(); }
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
close(): Promise<void> {
|
|
181
|
+
this.closed = true;
|
|
182
|
+
return this.queue(() => this.release());
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/** Read-only, bounded browser snapshot. Uses the same queue/connection as model tools. */
|
|
186
|
+
snapshot(): Promise<GraphSnapshot> {
|
|
187
|
+
if (this.closed) return Promise.reject(new Error("Knowledge graph is closed"));
|
|
188
|
+
return this.queue(async () => {
|
|
189
|
+
await this.open();
|
|
190
|
+
const totalNodes = Number((await this.rows("MATCH (n) RETURN count(*) AS count"))[0]!.count);
|
|
191
|
+
const totalEdges = Number((await this.rows("MATCH ()-[r]->() RETURN count(*) AS count"))[0]!.count);
|
|
192
|
+
const nodes = await this.rows(`MATCH (n) RETURN ${entityColumns("n", this.ontology)} ORDER BY id LIMIT 1000`) as unknown as Entity[];
|
|
193
|
+
const edges = nodes.length ? await this.rows(`MATCH (a)-[r]->(b)
|
|
194
|
+
WHERE a.id IN $ids AND b.id IN $ids
|
|
195
|
+
RETURN a.id AS from, b.id AS to, label(r) AS edge_type,
|
|
196
|
+
${this.edgeColumns()}
|
|
197
|
+
ORDER BY from, edge_type, to LIMIT 4000`, { ids: nodes.map((node) => node.id) }) as unknown as GraphEdge[] : [];
|
|
198
|
+
return { database: this.path, nodes, edges, totalNodes, totalEdges,
|
|
199
|
+
truncated: nodes.length < totalNodes || edges.length < totalEdges, schema: renderedSchema(this.ontology) };
|
|
200
|
+
});
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
private async entity(id: string): Promise<Entity> {
|
|
204
|
+
const rows = await this.rows(`MATCH (n) WHERE n.id = $id RETURN ${entityColumns("n", this.ontology)} LIMIT 2`, { id });
|
|
205
|
+
if (rows.length === 0) throw new Error(`Entity not found: ${id}`);
|
|
206
|
+
if (rows.length !== 1) throw new Error(`Duplicate entity ID in database: ${id}`);
|
|
207
|
+
return rows[0] as unknown as Entity;
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
execute(input: GraphInput, signal?: AbortSignal): Promise<unknown> {
|
|
211
|
+
if (this.closed) return Promise.reject(new Error("Knowledge graph is closed"));
|
|
212
|
+
return this.queue(async () => {
|
|
213
|
+
signal?.throwIfAborted();
|
|
214
|
+
if (!ACTIONS.includes(input.action)) throw new Error(`Unknown action: ${input.action}`);
|
|
215
|
+
if (input.action === "schema") return renderedSchema(this.ontology);
|
|
216
|
+
await this.open();
|
|
217
|
+
signal?.throwIfAborted();
|
|
218
|
+
const writes = ["upsert_entity", "upsert_edge", "delete_entity", "delete_edge"].includes(input.action);
|
|
219
|
+
if (writes) await this.rows("BEGIN TRANSACTION");
|
|
220
|
+
try {
|
|
221
|
+
const result = await this.dispatch(input);
|
|
222
|
+
// Cancellation before commit rolls back mutations; native queries also have a 5s timeout.
|
|
223
|
+
signal?.throwIfAborted();
|
|
224
|
+
if (writes) await this.rows("COMMIT");
|
|
225
|
+
return result;
|
|
226
|
+
} catch (error) {
|
|
227
|
+
if (writes) await this.rows("ROLLBACK").catch(() => undefined);
|
|
228
|
+
throw error;
|
|
229
|
+
}
|
|
230
|
+
});
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
/** Refresh-only compare-and-write: checks and mutation share one queue entry/transaction. */
|
|
234
|
+
executeConditional(input: GraphInput, expected: GraphState, signal?: AbortSignal): Promise<ConditionalResult> {
|
|
235
|
+
if (this.closed) return Promise.reject(new Error("Knowledge graph is closed"));
|
|
236
|
+
return this.queue(async () => {
|
|
237
|
+
signal?.throwIfAborted();
|
|
238
|
+
if (!["upsert_entity", "upsert_edge", "delete_entity", "delete_edge"].includes(input.action)) throw new Error("Refresh supports mutations only");
|
|
239
|
+
if (expected !== null && (!expected || typeof expected !== "object" || Array.isArray(expected))) throw new Error("Refresh requires an explicit expected state or null");
|
|
240
|
+
await this.open();
|
|
241
|
+
await this.rows("BEGIN TRANSACTION");
|
|
242
|
+
try {
|
|
243
|
+
const state = await this.mutationState(input);
|
|
244
|
+
if (!isDeepStrictEqual(state, expected)) {
|
|
245
|
+
await this.rows("ROLLBACK");
|
|
246
|
+
return { applied: false, state, reason: "Fact changed since inventory" };
|
|
247
|
+
}
|
|
248
|
+
if (input.action === "delete_entity") {
|
|
249
|
+
const edges = await this.rows("MATCH (n)-[r]-() WHERE n.id = $id RETURN count(r) AS count", { id: text(input.id, "id") });
|
|
250
|
+
if (Number(edges[0]!.count) > 0) {
|
|
251
|
+
await this.rows("ROLLBACK");
|
|
252
|
+
return { applied: false, state, reason: "Entity still has relationships; refusing detach deletion" };
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
await this.dispatch(input);
|
|
256
|
+
const updated = await this.mutationState(input);
|
|
257
|
+
signal?.throwIfAborted();
|
|
258
|
+
await this.rows("COMMIT");
|
|
259
|
+
return { applied: true, state: updated };
|
|
260
|
+
} catch (error) {
|
|
261
|
+
await this.rows("ROLLBACK").catch(() => undefined);
|
|
262
|
+
throw error;
|
|
263
|
+
}
|
|
264
|
+
});
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
private async mutationState(input: GraphInput): Promise<GraphState> {
|
|
268
|
+
if (input.action.endsWith("entity")) {
|
|
269
|
+
const rows = await this.rows(`MATCH (n) WHERE n.id = $id RETURN ${entityColumns("n", this.ontology)} LIMIT 2`, { id: text(input.id, "id") });
|
|
270
|
+
if (rows.length > 1) throw new Error("Duplicate entity ID");
|
|
271
|
+
return (rows[0] as unknown as Entity) ?? null;
|
|
272
|
+
}
|
|
273
|
+
this.assertEdge(input.edge_type);
|
|
274
|
+
const from = await this.entity(text(input.from, "from"));
|
|
275
|
+
const to = await this.entity(text(input.to, "to"));
|
|
276
|
+
this.endpoints(input.edge_type!, from, to);
|
|
277
|
+
const rows = await this.rows(`MATCH (a:${from.entity_type})-[r:${input.edge_type}]->(b:${to.entity_type})
|
|
278
|
+
WHERE a.id = $from AND b.id = $to RETURN a.id AS from, b.id AS to, label(r) AS edge_type,
|
|
279
|
+
${this.edgeColumns()} LIMIT 2`, { from: from.id, to: to.id });
|
|
280
|
+
if (rows.length > 1) throw new Error("Duplicate relationship");
|
|
281
|
+
return (rows[0] as unknown as GraphEdge) ?? null;
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
private edgeColumns() { return Object.keys({...columns(this.ontology, true), created_at: {}, updated_at: {}}).map(k => `r.${k} AS ${k}`).join(", "); }
|
|
285
|
+
|
|
286
|
+
private async edgeState(edge: string, from: Entity, to: Entity) {
|
|
287
|
+
return (await this.rows(`MATCH (a:${from.entity_type})-[r:${edge}]->(b:${to.entity_type}) WHERE a.id = $from AND b.id = $to RETURN ${this.edgeColumns()} LIMIT 2`, {from: from.id, to: to.id}))[0] ?? null;
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
private async dispatch(p: GraphInput): Promise<unknown> {
|
|
291
|
+
if (Object.keys(p).some(k => !["action", "id", "entity_type", "name", "kind", "stage", "localPath", "gitlabUrl", "description", "source", "from", "to", "edge_type", "query", "limit", "direction", "attributes", "filters"].includes(k))) throw new Error("Unknown graph input field; use attributes/filters for custom fields");
|
|
292
|
+
for (const v of [p.attributes, p.filters]) if (v !== undefined && (!v || typeof v !== "object" || Array.isArray(v))) throw new Error("attributes/filters must be mappings");
|
|
293
|
+
const limit = p.limit ?? 20;
|
|
294
|
+
if (!Number.isInteger(limit) || limit < 1 || limit > 100) throw new Error("limit must be an integer from 1 to 100");
|
|
295
|
+
switch (p.action) {
|
|
296
|
+
case "upsert_entity": {
|
|
297
|
+
const id = text(p.id, "id");
|
|
298
|
+
this.assertType(p.entity_type);
|
|
299
|
+
const name = text(p.name, "name");
|
|
300
|
+
const existing = await this.rows(`MATCH (n) WHERE n.id = $id RETURN ${entityColumns("n", this.ontology)}`, {id});
|
|
301
|
+
if (existing.length > 1 || existing.some(n => n.entity_type !== p.entity_type)) throw new Error("Entity IDs are globally unique; entity_type cannot change");
|
|
302
|
+
const defs = {...this.ontology.shared_attributes, ...this.ontology.entities[p.entity_type!].attributes};
|
|
303
|
+
const values = this.values(p, defs, existing[0]);
|
|
304
|
+
const defaults = Object.entries(defs).filter(([,a]) => a.type === "string" && !a.enum && !a.required).map(([k]) => `n.${k} = ''`);
|
|
305
|
+
await this.rows(`MERGE (n:${p.entity_type} {id: $id}) ON CREATE SET n.created_at = $now${defaults.length ? ", " + defaults.join(", ") : ""}
|
|
306
|
+
SET n.name = $name, n.updated_at = $now${Object.keys(values).map(k => `, n.${k} = $v_${k}`).join("")}`,
|
|
307
|
+
{id, name, now: new Date().toISOString(), ...Object.fromEntries(Object.entries(values).map(([k,v]) => [`v_${k}`,v]))});
|
|
308
|
+
return this.entity(id);
|
|
309
|
+
}
|
|
310
|
+
case "get": return this.entity(text(p.id, "id"));
|
|
311
|
+
case "search": {
|
|
312
|
+
if (p.entity_type !== undefined) this.assertType(p.entity_type);
|
|
313
|
+
const defs = columns(this.ontology);
|
|
314
|
+
const selected = {...p.filters, ...(p.kind !== undefined ? {kind: p.kind} : {}), ...(p.stage !== undefined ? {stage: p.stage} : {})};
|
|
315
|
+
for (const [key,value] of Object.entries(selected)) {
|
|
316
|
+
if (!Object.hasOwn(defs, key)) throw new Error(`Unknown filter ${key}`);
|
|
317
|
+
if (key === "kind" && defs[key].enum && !defs[key].enum.includes(value as string)) throw new Error(`Unknown repo kind: ${value}`);
|
|
318
|
+
if (key === "stage" && defs[key].enum && !defs[key].enum.includes(value as string)) throw new Error(`Unknown environment stage: ${value}`);
|
|
319
|
+
validateValue(value, key, defs[key]);
|
|
320
|
+
}
|
|
321
|
+
const query = optionalText(p.query, "query", 512) ?? "";
|
|
322
|
+
const filters: string[] = [];
|
|
323
|
+
const params: Record<string, LbugValue> = {};
|
|
324
|
+
if (query) {
|
|
325
|
+
filters.push("(" + Object.entries({...baseColumns, ...defs}).filter(([,a]) => a.type === "string").map(([k]) => `lower(n.${k}) CONTAINS $query`).join(" OR ") + ")");
|
|
326
|
+
params.query = query.toLowerCase();
|
|
327
|
+
}
|
|
328
|
+
for (const [key,value] of Object.entries(selected)) { filters.push(`n.${key} = $f_${key}`); params[`f_${key}`] = value; }
|
|
329
|
+
return { entities: await this.rows(`MATCH (n${p.entity_type ? `:${p.entity_type}` : ""})
|
|
330
|
+
${filters.length ? `WHERE ${filters.join(" AND ")}` : ""}
|
|
331
|
+
RETURN ${entityColumns("n", this.ontology)} ORDER BY id LIMIT ${limit}`,
|
|
332
|
+
filters.length ? params : undefined), limit };
|
|
333
|
+
}
|
|
334
|
+
case "neighbors": {
|
|
335
|
+
const node = await this.entity(text(p.id, "id"));
|
|
336
|
+
const direction = p.direction ?? "both";
|
|
337
|
+
if (!["in", "out", "both"].includes(direction)) throw new Error("direction must be in, out, or both");
|
|
338
|
+
if (p.edge_type !== undefined) this.assertEdge(p.edge_type);
|
|
339
|
+
const rel = `[r${p.edge_type ? `:${p.edge_type}` : ""}]`;
|
|
340
|
+
const where = direction === "in" ? "b.id = $id" : direction === "out" ? "a.id = $id" : "a.id = $id OR b.id = $id";
|
|
341
|
+
const edges = await this.rows(`MATCH (a)-${rel}->(b) WHERE ${where}
|
|
342
|
+
RETURN CASE WHEN a.id = $id THEN b.id ELSE a.id END AS neighbor_id,
|
|
343
|
+
CASE WHEN a.id = $id THEN label(b) ELSE label(a) END AS neighbor_type,
|
|
344
|
+
CASE WHEN a.id = $id THEN b.name ELSE a.name END AS neighbor_name,
|
|
345
|
+
CASE WHEN a.id = $id THEN b.kind ELSE a.kind END AS neighbor_kind,
|
|
346
|
+
CASE WHEN a.id = $id THEN b.stage ELSE a.stage END AS neighbor_stage,
|
|
347
|
+
CASE WHEN a.id = $id THEN b.localPath ELSE a.localPath END AS neighbor_localPath,
|
|
348
|
+
CASE WHEN a.id = $id THEN b.gitlabUrl ELSE a.gitlabUrl END AS neighbor_gitlabUrl,
|
|
349
|
+
label(r) AS edge_type, a.id AS from_id, b.id AS to_id,
|
|
350
|
+
${Object.keys(columns(this.ontology, true)).map(k => `r.${k} AS ${k}`).join(", ")}${Object.keys(columns(this.ontology)).filter(k => !["kind", "stage", "localPath", "gitlabUrl"].includes(k)).map(k => `, CASE WHEN a.id = $id THEN b.${k} ELSE a.${k} END AS neighbor_${k}`).join("")}
|
|
351
|
+
ORDER BY edge_type, from_id, to_id LIMIT ${limit}`, { id: node.id });
|
|
352
|
+
return { entity: node, edges, limit };
|
|
353
|
+
}
|
|
354
|
+
case "upsert_edge":
|
|
355
|
+
case "delete_edge": {
|
|
356
|
+
this.assertEdge(p.edge_type);
|
|
357
|
+
const from = await this.entity(text(p.from, "from"));
|
|
358
|
+
const to = await this.entity(text(p.to, "to"));
|
|
359
|
+
this.endpoints(p.edge_type!, from, to, p.action === "upsert_edge");
|
|
360
|
+
const match = `MATCH (a:${from.entity_type} {id: $from}), (b:${to.entity_type} {id: $to})`;
|
|
361
|
+
const params = { from: from.id, to: to.id };
|
|
362
|
+
if (p.action === "delete_edge") {
|
|
363
|
+
const rows = await this.rows(`${match} MATCH (a)-[r:${p.edge_type}]->(b) RETURN count(r) AS count`, params);
|
|
364
|
+
await this.rows(`${match} MATCH (a)-[r:${p.edge_type}]->(b) DELETE r`, params);
|
|
365
|
+
return { deleted: Number(rows[0]!.count) };
|
|
366
|
+
}
|
|
367
|
+
const defs = {...this.ontology.shared_attributes, ...this.ontology.relationships[p.edge_type!].attributes};
|
|
368
|
+
const old = await this.edgeState(p.edge_type!, from, to);
|
|
369
|
+
const values = this.values(p, defs, old ?? undefined);
|
|
370
|
+
const defaults = Object.entries(defs).filter(([,a]) => a.type === "string" && !a.enum && !a.required).map(([k]) => `r.${k} = ''`);
|
|
371
|
+
await this.rows(`${match} MERGE (a)-[r:${p.edge_type}]->(b)
|
|
372
|
+
ON CREATE SET r.created_at = $now${defaults.length ? ", " + defaults.join(", ") : ""}
|
|
373
|
+
SET r.updated_at = $now${Object.keys(values).map(k => `, r.${k} = $v_${k}`).join("")}`,
|
|
374
|
+
{...params, now: new Date().toISOString(), ...Object.fromEntries(Object.entries(values).map(([k,v]) => [`v_${k}`,v]))});
|
|
375
|
+
return { from: from.id, to: to.id, edge_type: p.edge_type };
|
|
376
|
+
}
|
|
377
|
+
case "delete_entity": {
|
|
378
|
+
const node = await this.entity(text(p.id, "id"));
|
|
379
|
+
await this.rows(`MATCH (n:${node.entity_type} {id: $id}) DETACH DELETE n`, { id: node.id });
|
|
380
|
+
return { deleted: node.id, incident_edges_deleted: true };
|
|
381
|
+
}
|
|
382
|
+
default: throw new Error(`Unsupported action: ${p.action}`);
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { Ajv } from "ajv";
|
|
2
|
+
import { ACTIONS, EDGE_TYPES, ENTITY_TYPES, ONTOLOGY, type GraphInput } from "./ontology.js";
|
|
3
|
+
import { columns, type Attribute } from "./config.js";
|
|
4
|
+
|
|
5
|
+
const attributeSchema = (a: Attribute) => ({type: a.type, ...(a.enum ? {enum: a.enum} : {}), ...(a.maxLength ? {maxLength: a.maxLength} : {}), ...(a.description ? {description: a.description} : {})});
|
|
6
|
+
const entityColumns = columns(ONTOLOGY);
|
|
7
|
+
const allColumns = { ...entityColumns, ...columns(ONTOLOGY, true) };
|
|
8
|
+
const attributes = (entries: Record<string, Attribute>) => ({
|
|
9
|
+
type: "object" as const,
|
|
10
|
+
properties: Object.fromEntries(Object.entries(entries).map(([key, attribute]) => [key, attributeSchema(attribute)])),
|
|
11
|
+
additionalProperties: false,
|
|
12
|
+
});
|
|
13
|
+
const stringEnum = (values: readonly string[]) => values.length
|
|
14
|
+
? { type: "string" as const, enum: [...values] }
|
|
15
|
+
: { type: "string" as const, not: {} };
|
|
16
|
+
const string = (maxLength: number, description?: string) => ({ type: "string" as const, maxLength, ...(description ? { description } : {}) });
|
|
17
|
+
|
|
18
|
+
export const toolDescription = `Persistent LadybugDB graph, shared by concurrent Pi, OpenCode and MCP clients. User-wide by default; explicit database and YAML ontology paths are supported.
|
|
19
|
+
Configured entities: ${Object.keys(ONTOLOGY.entities).join(", ")}. Relationships: ${Object.keys(ONTOLOGY.relationships).join(", ")}.
|
|
20
|
+
Call schema for attribute applicability, required fields, enums and directed endpoint constraints. Graph writes change facts, not ontology configuration. This tool cannot edit ontology YAML; use mnemos_edit_ontology only when the user explicitly requests an ontology edit. Use attributes for entity/edge writes, filters for exact entity attribute search. Legacy top-level attributes remain accepted when configured.
|
|
21
|
+
upsert_entity requires id, entity_type, name and all configured required attributes on creation. upsert_edge/delete_edge require from, to, edge_type. get/delete_entity/neighbors require id.
|
|
22
|
+
IDs are globally unique; types and configured immutable attributes cannot change. Omitted attributes are preserved; empty strings clear optional non-enum text. Relationships are directed and unique per (from, type, to); both endpoints must exist. Entity deletion removes incident edges.
|
|
23
|
+
Search is case-insensitive substring matching across string attributes, not semantic search. Search/neighbors limit defaults to 20, maximum 100. Text output is capped at 40KB/1500 lines; narrow queries if truncated. Writes persist across sessions and are NOT undone by /tree or /fork.`;
|
|
24
|
+
export const toolParameters = {
|
|
25
|
+
type: "object" as const,
|
|
26
|
+
properties: {
|
|
27
|
+
action: stringEnum(ACTIONS),
|
|
28
|
+
attributes: attributes(allColumns),
|
|
29
|
+
filters: attributes(entityColumns),
|
|
30
|
+
id: string(512, "Stable entity ID; required for entity upsert/get/delete/neighbors"),
|
|
31
|
+
entity_type: stringEnum(ENTITY_TYPES),
|
|
32
|
+
name: string(512),
|
|
33
|
+
...Object.fromEntries(Object.entries(allColumns).filter(([key]) => ["kind", "stage", "localPath", "gitlabUrl", "description", "source"].includes(key)).map(([key, attribute]) => [key, attributeSchema(attribute)])),
|
|
34
|
+
from: string(512),
|
|
35
|
+
to: string(512),
|
|
36
|
+
edge_type: stringEnum(EDGE_TYPES),
|
|
37
|
+
query: string(512, "Search substring; omit to list entities"),
|
|
38
|
+
limit: { type: "integer" as const, minimum: 1, maximum: 100 },
|
|
39
|
+
direction: stringEnum(["in", "out", "both"]),
|
|
40
|
+
},
|
|
41
|
+
required: ["action"],
|
|
42
|
+
additionalProperties: false,
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
export const validToolInput = new Ajv({ ownProperties: true }).compile<GraphInput>(toolParameters);
|