@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.
Files changed (54) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/LICENSE +21 -0
  3. package/README.md +78 -2
  4. package/docs/README.md +33 -0
  5. package/docs/assets/mnemos-readme.svg +13 -0
  6. package/docs/assets/mnemos-social-preview.png +0 -0
  7. package/docs/branding.md +19 -0
  8. package/docs/cli.md +144 -0
  9. package/docs/development.md +29 -0
  10. package/docs/getting-started.md +127 -0
  11. package/docs/mcp.md +105 -0
  12. package/docs/ontology.md +233 -0
  13. package/docs/operations.md +130 -0
  14. package/docs/refresh.md +79 -0
  15. package/docs/release.md +68 -0
  16. package/docs/relocation.md +22 -0
  17. package/examples/ontology.extended.yaml +64 -0
  18. package/package.json +91 -4
  19. package/scripts/check-docs.mjs +23 -0
  20. package/scripts/cli.mjs +9 -0
  21. package/scripts/mcp.mjs +3 -0
  22. package/scripts/package-smoke-worker.mjs +63 -0
  23. package/scripts/package-smoke.mjs +49 -0
  24. package/scripts/refresh.config.example.json +8 -0
  25. package/scripts/refresh.mjs +10 -0
  26. package/src/api.ts +39 -0
  27. package/src/cli.ts +111 -0
  28. package/src/config.ts +124 -0
  29. package/src/core-bootstrap.mjs +3 -0
  30. package/src/explorer.ts +106 -0
  31. package/src/index.ts +88 -0
  32. package/src/legacy-v5.json +22 -0
  33. package/src/mcp.ts +31 -0
  34. package/src/ontology-editor.ts +115 -0
  35. package/src/ontology.ts +50 -0
  36. package/src/ontology.yaml +60 -0
  37. package/src/opencode-bootstrap.mjs +2 -0
  38. package/src/opencode.ts +28 -0
  39. package/src/paths.ts +8 -0
  40. package/src/refresh/cli.ts +121 -0
  41. package/src/refresh/inventory.ts +259 -0
  42. package/src/refresh/refresh.ts +112 -0
  43. package/src/service-bootstrap.mjs +11 -0
  44. package/src/service-protocol.ts +94 -0
  45. package/src/service.ts +138 -0
  46. package/src/shared-store.ts +125 -0
  47. package/src/store.ts +385 -0
  48. package/src/tool-contract.ts +45 -0
  49. package/src/web/app.js +241 -0
  50. package/src/web/index.html +56 -0
  51. package/src/web/mnemos-icon-32.png +0 -0
  52. package/src/web/mnemos-icon.svg +9 -0
  53. package/src/web/mnemos-logo.svg +10 -0
  54. package/src/web/style.css +57 -0
package/package.json CHANGED
@@ -1,6 +1,93 @@
1
1
  {
2
2
  "name": "@laurindustries/mnemos",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "description": "Mnemos: a shared LadybugDB knowledge graph for Pi, OpenCode, MCP, and the CLI",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/LaurIndustries/mnemos.git"
10
+ },
11
+ "homepage": "https://github.com/LaurIndustries/mnemos#readme",
12
+ "bugs": {
13
+ "url": "https://github.com/LaurIndustries/mnemos/issues"
14
+ },
15
+ "publishConfig": {
16
+ "access": "public"
17
+ },
18
+ "keywords": [
19
+ "mnemos",
20
+ "pi-package",
21
+ "knowledge-graph",
22
+ "ladybugdb",
23
+ "mcp",
24
+ "opencode",
25
+ "ontology"
26
+ ],
27
+ "files": [
28
+ "src",
29
+ "scripts",
30
+ "README.md",
31
+ "examples",
32
+ "docs",
33
+ "LICENSE",
34
+ "CHANGELOG.md"
35
+ ],
36
+ "pi": {
37
+ "extensions": [
38
+ "./src/index.ts"
39
+ ]
40
+ },
41
+ "scripts": {
42
+ "test": "tsx --test test/*.test.ts",
43
+ "test:browser": "tsx --test browser/*.test.ts",
44
+ "typecheck": "tsc --noEmit",
45
+ "refresh": "node scripts/refresh.mjs",
46
+ "cli": "node scripts/cli.mjs",
47
+ "build": "tsc --noEmit",
48
+ "test:package": "node scripts/package-smoke.mjs",
49
+ "check:docs": "node scripts/check-docs.mjs",
50
+ "validate:release": "npm run typecheck && npm test && npm run check:docs && npm run test:package",
51
+ "prepack": "npm run typecheck && npm run check:docs"
52
+ },
53
+ "dependencies": {
54
+ "@ladybugdb/core": "0.22.3",
55
+ "@modelcontextprotocol/sdk": "^1.32.2",
56
+ "ajv": "^8.20.0",
57
+ "cytoscape": "3.35.0",
58
+ "jiti": "^2.7.0",
59
+ "proper-lockfile": "^4.1.2",
60
+ "yaml": "^2.9.1"
61
+ },
62
+ "peerDependencies": {
63
+ "@earendil-works/pi-coding-agent": "*"
64
+ },
65
+ "devDependencies": {
66
+ "@earendil-works/pi-coding-agent": "1.6.1",
67
+ "@opencode/plugin": "2.4.3",
68
+ "@types/node": "^22.0.0",
69
+ "@types/proper-lockfile": "^4.1.4",
70
+ "playwright": "1.65.1",
71
+ "tsx": "^4.20.0",
72
+ "typescript": "^5.8.0"
73
+ },
74
+ "engines": {
75
+ "node": ">=22.19.0"
76
+ },
77
+ "exports": {
78
+ ".": "./src/opencode-bootstrap.mjs",
79
+ "./opencode": "./src/opencode-bootstrap.mjs",
80
+ "./pi": "./src/index.ts",
81
+ "./core": "./src/core-bootstrap.mjs"
82
+ },
83
+ "bin": {
84
+ "knowledge-graph": "scripts/cli.mjs",
85
+ "knowledge-graph-mcp": "scripts/mcp.mjs",
86
+ "knowledge-graph-refresh": "scripts/refresh.mjs"
87
+ },
88
+ "peerDependenciesMeta": {
89
+ "@earendil-works/pi-coding-agent": {
90
+ "optional": true
91
+ }
92
+ }
93
+ }
@@ -0,0 +1,23 @@
1
+ import { readFile, readdir, access } from 'node:fs/promises';
2
+ import { resolve, dirname } from 'node:path';
3
+ import { fileURLToPath } from 'node:url';
4
+ const root = resolve(dirname(fileURLToPath(import.meta.url)), '..');
5
+ const files = ['README.md', 'CHANGELOG.md', ...(await readdir(resolve(root, 'docs'))).filter(x => x.endsWith('.md')).map(x => `docs/${x}`)];
6
+ for (const file of files) {
7
+ const text = await readFile(resolve(root, file), 'utf8');
8
+ if (file === 'README.md' && text.split('\n').length > 160) throw new Error('README length exceeds 160 lines');
9
+ if (/\/home\/(?!me\/)[\w.-]+\//.test(text)) throw new Error(`Use a placeholder home path in ${file}`);
10
+ for (const match of text.matchAll(/\]\(([^)]+)\)/g)) {
11
+ const target = match[1];
12
+ if (/^(https?:|mailto:)/.test(target)) continue;
13
+ const [path, anchor] = target.split('#');
14
+ const destination = path ? resolve(dirname(resolve(root, file)), path) : resolve(root, file);
15
+ await access(destination);
16
+ if (anchor && destination.endsWith('.md')) {
17
+ const headings = (await readFile(destination, 'utf8')).matchAll(/^#{1,6}\s+(.+)$/gm);
18
+ const ids = [...headings].map(x => x[1].toLowerCase().replace(/[^\p{L}\p{N}_\-\s]/gu, '').replace(/\s/g, '-'));
19
+ if (!ids.includes(anchor)) throw new Error(`Missing anchor ${target} in ${file}`);
20
+ }
21
+ }
22
+ }
23
+ console.error(`Documentation links checked: ${files.length} files`);
@@ -0,0 +1,9 @@
1
+ #!/usr/bin/env node
2
+ import { createJiti } from "jiti";
3
+ try {
4
+ const { main } = await createJiti(import.meta.url).import("../src/cli.ts");
5
+ await main(process.argv.slice(2));
6
+ } catch (error) {
7
+ console.error(JSON.stringify({ error: error instanceof Error ? error.message : String(error) }));
8
+ process.exitCode = 1;
9
+ }
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env node
2
+ import { createJiti } from "jiti";
3
+ try { await (await createJiti(import.meta.url).import("../src/mcp.ts")).runMcp(); } catch(e) { console.error(e); process.exitCode=1; }
@@ -0,0 +1,63 @@
1
+ // Copied into an isolated consumer directory; imports resolve only its dependencies.
2
+ import assert from 'node:assert/strict';
3
+ import { readFile, access } from 'node:fs/promises';
4
+ import { spawnSync } from 'node:child_process';
5
+ import { setTimeout as delay } from 'node:timers/promises';
6
+ import { createRequire } from 'node:module';
7
+ import { Client } from '@modelcontextprotocol/sdk/client/index.js';
8
+ import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';
9
+ import plugin from '@laurindustries/mnemos';
10
+ import { GraphClient } from '@laurindustries/mnemos/core';
11
+ const require = createRequire(import.meta.url);
12
+ assert.throws(() => require.resolve('@earendil-works/pi-coding-agent'));
13
+ assert.equal(typeof GraphClient, 'function');
14
+ assert.throws(() => require.resolve('@opencode/plugin'));
15
+ assert.throws(() => require.resolve('typebox'));
16
+ const base = 'node_modules/@laurindustries/mnemos/';
17
+ for (const file of ['src/ontology.yaml', 'src/legacy-v5.json', 'src/web/app.js', 'src/web/index.html', 'src/web/style.css', 'src/web/mnemos-logo.svg', 'src/web/mnemos-icon.svg', 'src/web/mnemos-icon-32.png', 'docs/assets/mnemos-readme.svg', 'LICENSE', 'CHANGELOG.md', 'docs/release.md', 'examples/ontology.extended.yaml']) await access(base + file);
18
+ const meta = JSON.parse(await readFile(base + 'package.json', 'utf8'));
19
+ for (const [bin, args] of [['knowledge-graph', ['--help']], ['knowledge-graph', ['schema']], ['knowledge-graph-refresh', ['--help']]]) {
20
+ const result = spawnSync(process.execPath, [base + meta.bin[bin], ...args], { encoding: 'utf8', timeout: 30000 });
21
+ assert.equal(result.status, 0, result.stderr);
22
+ if (args[0] === 'schema') JSON.parse(result.stdout);
23
+ }
24
+ const registeredTools = new Map();
25
+ const cleanup = await plugin.setup({ location: { directory: process.cwd() }, tool: { transform(fn) { fn({ add(value) { registeredTools.set(value.name, value); } }); } } });
26
+ const registered = registeredTools.get('knowledge_graph');
27
+ const editor = registeredTools.get('mnemos_edit_ontology');
28
+ const transport = new StdioClientTransport({ command: process.execPath, args: [base + meta.bin['knowledge-graph-mcp']], env: { ...process.env }, stderr: 'pipe' });
29
+ const client = new Client({ name: 'package-smoke', version: '1' });
30
+ try {
31
+ const created = await registered.execute({ action: 'upsert_entity', id: 'smoke', entity_type: 'Project', name: 'Smoke' }, { signal: new AbortController().signal });
32
+ assert.equal(JSON.parse(created.content[0].text).name, 'Smoke');
33
+ await client.connect(transport);
34
+ const tools = await client.listTools();
35
+ assert.deepEqual(tools.tools.find(t => t.name === 'knowledge_graph').inputSchema, registered.input);
36
+ const mcpEditor = tools.tools.find(t => t.name === editor.name);
37
+ assert.deepEqual(mcpEditor.inputSchema, editor.input);
38
+ assert.equal(mcpEditor.description, editor.description);
39
+ const rejected = await client.callTool({ name: editor.name, arguments: { action: 'inspect' } });
40
+ assert.equal(rejected.isError, true); // The packaged ontology is never editable.
41
+ const result = await client.callTool({ name: 'knowledge_graph', arguments: { action: 'get', id: 'smoke' } });
42
+ assert.equal(JSON.parse(result.content[0].text).name, 'Smoke');
43
+ const endpoint = JSON.parse(await readFile(process.env.PI_KNOWLEDGE_GRAPH_DB + '.service.json', 'utf8'));
44
+ const page = await fetch(`http://127.0.0.1:${endpoint.port}/`);
45
+ assert.equal(page.status, 404);
46
+ assert.equal((await fetch(`http://127.0.0.1:${endpoint.port}/api/graph`)).status, 404);
47
+ } finally {
48
+ await client.close();
49
+ if (typeof cleanup === 'function') await cleanup();
50
+ const descriptor = process.env.PI_KNOWLEDGE_GRAPH_DB + '.service.json';
51
+ let endpoint;
52
+ try { endpoint = JSON.parse(await readFile(descriptor, 'utf8')); } catch (e) { if (e.code !== 'ENOENT') throw e; }
53
+ if (endpoint) {
54
+ process.kill(endpoint.pid, 'SIGTERM');
55
+ let stopped = false;
56
+ for (let i = 0; i < 200; i++) {
57
+ try { await access(descriptor); } catch { stopped = true; break; }
58
+ await delay(25);
59
+ }
60
+ assert.ok(stopped, 'isolated owner must stop before temporary files are removed');
61
+ }
62
+ }
63
+ console.log('Production tarball smoke passed: no host SDKs, core/OpenCode exports, all bins, MCP initialize/list/call, YAML/web assets and private-by-default service');
@@ -0,0 +1,49 @@
1
+ // Pack without lifecycle recursion; prepack is independently exercised by npm pack.
2
+ import { mkdtemp, rm, writeFile, readFile, access } from 'node:fs/promises';
3
+ import { setTimeout as delay } from 'node:timers/promises';
4
+ import { tmpdir } from 'node:os';
5
+ import { resolve, dirname, join } from 'node:path';
6
+ import { fileURLToPath } from 'node:url';
7
+ import { spawnSync } from 'node:child_process';
8
+ const root = resolve(dirname(fileURLToPath(import.meta.url)), '..');
9
+ const temp = await mkdtemp(join(tmpdir(), 'kg-package-'));
10
+ function npm(args, cwd) {
11
+ const cli = process.env.npm_execpath;
12
+ const command = cli ? process.execPath : (process.platform === 'win32' ? 'npm.cmd' : 'npm');
13
+ const result = spawnSync(command, cli ? [cli, ...args] : args, { cwd, encoding: 'utf8', timeout: 240000, maxBuffer: 16 * 1024 * 1024 });
14
+ if (result.status !== 0) throw new Error(result.stderr + result.stdout + (result.error ?? ''));
15
+ return result.stdout;
16
+ }
17
+ try {
18
+ const packed = JSON.parse(npm(['pack', '--ignore-scripts', '--json', '--pack-destination', temp], root));
19
+ await writeFile(join(temp, 'package.json'), JSON.stringify({ private: true, type: 'module' }));
20
+ npm(['install', '--omit=dev', '--include=optional', '--no-audit', '--no-fund', join(temp, packed[0].filename)], temp);
21
+ const source = await import('node:fs/promises').then(fs => fs.readFile(join(root, 'scripts/package-smoke-worker.mjs'), 'utf8'));
22
+ await writeFile(join(temp, 'smoke.mjs'), source);
23
+ const result = spawnSync(process.execPath, ['smoke.mjs'], { cwd: temp, encoding: 'utf8', timeout: 90000, env: { ...process.env, PI_KNOWLEDGE_GRAPH_DB: join(temp, 'graph.lbug'), PI_KNOWLEDGE_GRAPH_ONTOLOGY: join(temp, 'node_modules/@laurindustries/mnemos/src/ontology.yaml'), PI_KNOWLEDGE_GRAPH_PORT: '0', PI_KNOWLEDGE_GRAPH_EXPLORER: '0' } });
24
+ if (result.status !== 0) throw new Error(result.stdout + result.stderr + (result.error ?? ''));
25
+ console.log(result.stdout.trim());
26
+ const cli = process.env.npm_execpath;
27
+ const audit = spawnSync(cli ? process.execPath : (process.platform === 'win32' ? 'npm.cmd' : 'npm'), cli ? [cli, 'audit', '--json'] : ['audit', '--json'], { cwd: temp, encoding: 'utf8' });
28
+ const report = JSON.parse(audit.stdout);
29
+ console.log('Production audit:', JSON.stringify(report.metadata.vulnerabilities));
30
+ if (process.env.KG_PACKAGE_AUDIT_OUTPUT) await writeFile(process.env.KG_PACKAGE_AUDIT_OUTPUT, audit.stdout);
31
+ if (report.metadata.vulnerabilities.high || report.metadata.vulnerabilities.critical) throw new Error('High/critical production audit blocker');
32
+ } finally {
33
+ // Recover our isolated owner even if the worker timed out before its finally.
34
+ const descriptor = join(temp, 'graph.lbug.service.json');
35
+ let endpoint;
36
+ try { endpoint = JSON.parse(await readFile(descriptor, 'utf8')); }
37
+ catch (error) { if (error.code !== 'ENOENT') throw error; }
38
+ if (endpoint) {
39
+ try { process.kill(endpoint.pid, 'SIGTERM'); }
40
+ catch (error) { if (error.code !== 'ESRCH') throw error; }
41
+ let stopped = false;
42
+ for (let i = 0; i < 200; i++) {
43
+ try { await access(descriptor); } catch { stopped = true; break; }
44
+ await delay(25);
45
+ }
46
+ if (!stopped) throw new Error(`Isolated owner did not stop; retained files at ${temp}`);
47
+ }
48
+ await rm(temp, { recursive: true, force: true });
49
+ }
@@ -0,0 +1,8 @@
1
+ {
2
+ "repoRoots": ["~/git"],
3
+ "kubeconfigDirectories": ["~/.kube"],
4
+ "kubeconfigFiles": [],
5
+ "azureSubscriptions": false,
6
+ "contextEnvironments": {},
7
+ "repoKinds": {}
8
+ }
@@ -0,0 +1,10 @@
1
+ #!/usr/bin/env node
2
+ import { createJiti } from "jiti";
3
+ const jiti = createJiti(import.meta.url);
4
+ try {
5
+ const { main } = await jiti.import("../src/refresh/cli.ts");
6
+ await main(process.argv.slice(2));
7
+ } catch (error) {
8
+ console.error(error instanceof Error ? error.message : "Refresh failed");
9
+ process.exitCode = 1;
10
+ }
package/src/api.ts ADDED
@@ -0,0 +1,39 @@
1
+ import { validToolInput } from "./tool-contract.js";
2
+ import { SharedGraphStore } from "./shared-store.js";
3
+ import { databasePath } from "./paths.js";
4
+ import { ONTOLOGY } from "./ontology.js";
5
+ import { defaultOntologyPath, fingerprint } from "./config.js";
6
+ import { resolve } from "node:path";
7
+ export function boundedText(text: string) {
8
+ const lines = text.split("\n").slice(0, 1499).join("\n");
9
+ const clipped = Buffer.from(lines).subarray(0, 39 * 1024).toString("utf8");
10
+ return clipped === text ? text : clipped + "\n[Output truncated; narrow query or lower limit.]";
11
+ }
12
+ export class GraphClient {
13
+ private store?: SharedGraphStore;
14
+ getStore(cwd: string) {
15
+ const path = databasePath(cwd);
16
+ if (this.store && this.store.path !== path) throw new Error("Knowledge graph path changed; reload before using another database");
17
+ if (!this.store) {
18
+ const candidate = new SharedGraphStore(path, resolve(process.env.PI_KNOWLEDGE_GRAPH_ONTOLOGY ?? defaultOntologyPath));
19
+ if (fingerprint(candidate.ontology) !== fingerprint(ONTOLOGY)) throw new Error("Ontology changed since tool registration; reload");
20
+ this.store = candidate;
21
+ }
22
+ return this.store;
23
+ }
24
+ /** Unbounded structured result for machine adapters; shares validation and ownership. */
25
+ async executeData(input: unknown, cwd: string, signal?: AbortSignal) {
26
+ signal?.throwIfAborted();
27
+ if (!validToolInput(input)) throw new Error("Invalid knowledge_graph input: does not match tool JSON schema");
28
+ const store = this.getStore(cwd);
29
+ return store.execute(input, signal);
30
+ }
31
+ async execute(input: unknown, cwd: string, signal?: AbortSignal) {
32
+ const data = await this.executeData(input, cwd, signal);
33
+ const store = this.getStore(cwd);
34
+ const serialized = JSON.stringify(data, (_key, value) => typeof value === "bigint" ? Number(value) : value, 2);
35
+ const text = boundedText(serialized);
36
+ return { content: [{ type: "text" as const, text }], details: { database: store.path, truncated: text !== serialized } };
37
+ }
38
+ async close() { const store = this.store; this.store = undefined; await store?.close(); }
39
+ }
package/src/cli.ts ADDED
@@ -0,0 +1,111 @@
1
+ // Keep ontology-dependent modules behind the configuration/ help boundary.
2
+ const commands = ["schema", "get", "search", "neighbors", "upsert-entity", "upsert-edge", "delete-entity", "delete-edge"];
3
+ const flags: Record<string, string> = { id: "id", "entity-type": "entity_type", name: "name", from: "from", to: "to", "edge-type": "edge_type", query: "query", limit: "limit", direction: "direction", attributes: "attributes", filters: "filters", kind: "kind", stage: "stage", "local-path": "localPath", "gitlab-url": "gitlabUrl", description: "description", source: "source" };
4
+ const help = `Usage: knowledge-graph COMMAND [ID] [OPTIONS]
5
+ Commands: schema, get, search, neighbors, upsert-entity, upsert-edge,
6
+ delete-entity, delete-edge, request
7
+ get/neighbors/upsert-entity/delete-entity accept one positional ID.
8
+ Flags: --id --entity-type --name --from --to --edge-type --query --limit
9
+ --direction in|out|both --attributes JSON --filters JSON
10
+ --kind --stage --local-path --gitlab-url --description --source
11
+ Raw: knowledge-graph [COMMAND|request] --input JSON (use - for stdin)
12
+ knowledge-graph request (reads stdin); raw action uses underscores.
13
+ Raw input cannot be combined with field flags or positional IDs.
14
+ Output: JSON on stdout, no text cap. Errors: JSON on stderr.
15
+ schema --human prints formatSchema text; --json is accepted explicitly.
16
+ Config: --db FILE overrides PI_KNOWLEDGE_GRAPH_DB; relative paths use cwd.
17
+ Default: $PI_CODING_AGENT_DIR/knowledge-graph/graph.lbug
18
+ (PI_CODING_AGENT_DIR defaults to ~/.pi/agent).
19
+ --ontology FILE overrides PI_KNOWLEDGE_GRAPH_ONTOLOGY
20
+ (default: packaged src/ontology.yaml).
21
+ PI_KNOWLEDGE_GRAPH_PORT and PI_KNOWLEDGE_GRAPH_NODE retain shared service semantics.
22
+ --help / -h works without loading ontology or starting a service.
23
+ Exit: 0 success, 2 usage/input error, 1 configuration/store error,
24
+ 130 SIGINT, 143 SIGTERM. Mutations are never automatically retried.
25
+ Deletes are explicit, noninteractive, and persistent; deleting an entity removes its edges.
26
+ Client exit only closes this client, never the shared daemon.`;
27
+ class UsageError extends Error {}
28
+ const json = (value: unknown) => JSON.stringify(value, (_key, v) => typeof v === "bigint" ? Number(v) : v, 2);
29
+ function parseJson(text: string): unknown {
30
+ try { return JSON.parse(text); } catch { throw new UsageError("Invalid JSON input"); }
31
+ }
32
+ export async function main(argv: string[]) {
33
+ if (argv.includes("--help") || argv.includes("-h")) { console.log(help); return; }
34
+ let client: import("./api.js").GraphClient | undefined;
35
+ const controller = new AbortController();
36
+ let interrupted = 0;
37
+ const interrupt = () => { interrupted = 130; controller.abort(); };
38
+ const terminate = () => { interrupted = 143; controller.abort(); };
39
+ process.once("SIGINT", interrupt); process.once("SIGTERM", terminate);
40
+ try {
41
+ const options: Record<string, string> = {};
42
+ const positional: string[] = [];
43
+ let human = false;
44
+ for (let i = 0; i < argv.length; i++) {
45
+ const arg = argv[i]!;
46
+ if (arg === "--human") { human = true; continue; }
47
+ if (arg === "--json") continue;
48
+ if (!arg.startsWith("--")) { positional.push(arg); continue; }
49
+ const [key, ...rest] = arg.slice(2).split("=");
50
+ if (!key || !(key in flags || ["db", "ontology", "input"].includes(key))) throw new UsageError(`Unknown option: ${arg}`);
51
+ if (key in options) throw new UsageError(`Duplicate option: --${key}`);
52
+ const value = rest.length ? rest.join("=") : argv[++i];
53
+ if (value === undefined || value.startsWith("--")) throw new UsageError(`Missing value: --${key}`);
54
+ options[key] = value;
55
+ }
56
+ const command = positional.shift();
57
+ if (command && !commands.includes(command) && command !== "request") throw new UsageError(`Unknown command: ${command}`);
58
+ const fields = Object.keys(options).filter(k => k in flags);
59
+ let input: unknown;
60
+ if (options.input !== undefined || command === "request") {
61
+ if (fields.length || positional.length) throw new UsageError("Raw input cannot be mixed with fields or IDs");
62
+ const source = options.input ?? "-";
63
+ let text = source;
64
+ if (source === "-") {
65
+ text = "";
66
+ process.stdin.setEncoding("utf8");
67
+ const stop = () => process.stdin.destroy();
68
+ controller.signal.addEventListener("abort", stop, { once: true });
69
+ try { for await (const chunk of process.stdin) text += chunk; }
70
+ finally { controller.signal.removeEventListener("abort", stop); }
71
+ }
72
+ input = parseJson(text);
73
+ if (command && command !== "request" && (input as any)?.action !== command.replaceAll("-", "_")) throw new UsageError("Raw action does not match command");
74
+ } else {
75
+ if (!command) throw new UsageError("A command or --input is required; use --help");
76
+ const result: Record<string, unknown> = { action: command.replaceAll("-", "_") };
77
+ if (positional.length) {
78
+ if (positional.length !== 1 || !["get", "neighbors", "upsert-entity", "delete-entity"].includes(command) || options.id !== undefined) throw new UsageError("Unexpected or duplicate positional ID");
79
+ result.id = positional[0];
80
+ }
81
+ for (const k of fields) {
82
+ const v = options[k]!;
83
+ result[flags[k]!] = ["attributes", "filters"].includes(k) ? parseJson(v) : k === "limit" ? (/^\d+$/.test(v) ? Number(v) : NaN) : v;
84
+ }
85
+ input = result;
86
+ }
87
+ if (human && (input as any)?.action !== "schema") throw new UsageError("--human is only supported for schema");
88
+ if (options.db !== undefined) { if (!options.db) throw new UsageError("--db cannot be empty"); process.env.PI_KNOWLEDGE_GRAPH_DB = options.db; }
89
+ if (options.ontology !== undefined) { if (!options.ontology) throw new UsageError("--ontology cannot be empty"); process.env.PI_KNOWLEDGE_GRAPH_ONTOLOGY = options.ontology; }
90
+ controller.signal.throwIfAborted();
91
+ const { GraphClient } = await import("./api.js");
92
+ const { validToolInput } = await import("./tool-contract.js");
93
+ if (!validToolInput(input)) throw new UsageError("Invalid knowledge_graph input: does not match tool JSON schema");
94
+ // Required action fields are checked before opening a DB, as well as by the store.
95
+ const request = input;
96
+ const required = request.action === "upsert_entity" ? ["id", "entity_type", "name"] as const
97
+ : ["get", "neighbors", "delete_entity"].includes(request.action) ? ["id"] as const
98
+ : ["upsert_edge", "delete_edge"].includes(request.action) ? ["from", "to", "edge_type"] as const : [];
99
+ for (const key of required) if (typeof request[key] !== "string" || !String(request[key]).trim()) throw new UsageError(`Required nonblank field: ${key}`);
100
+ client = new GraphClient();
101
+ const data = await client.executeData(input, process.cwd(), controller.signal);
102
+ controller.signal.throwIfAborted();
103
+ console.log(human ? (await import("./ontology.js")).formatSchema() : json(data));
104
+ } catch (error) {
105
+ process.exitCode = interrupted || (error instanceof UsageError ? 2 : 1);
106
+ console.error(json({ error: error instanceof Error ? error.message : String(error) }));
107
+ } finally {
108
+ await client?.close();
109
+ process.removeListener("SIGINT", interrupt); process.removeListener("SIGTERM", terminate);
110
+ }
111
+ }
package/src/config.ts ADDED
@@ -0,0 +1,124 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { resolve } from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+ import { createHash } from "node:crypto";
5
+ import { parseDocument } from "yaml";
6
+
7
+ export interface Attribute { type: "string" | "number" | "boolean"; enum?: string[]; maxLength?: number; required?: boolean; immutable?: boolean; description?: string }
8
+ export interface Endpoint { entity_type: string | string[]; [attribute: string]: unknown }
9
+ export interface Ontology {
10
+ version: number;
11
+ entities: Record<string, { description: string; attributes: Record<string, Attribute> }>;
12
+ relationships: Record<string, { description: string; from: Endpoint; to: Endpoint; attributes: Record<string, Attribute> }>;
13
+ shared_attributes: Record<string, Attribute>;
14
+ }
15
+ const identifier = /^[A-Za-z][A-Za-z0-9_]{0,63}$/;
16
+ const cypherKeywords = new Set(["match", "create", "return", "where", "set", "delete", "merge", "from", "to", "table", "node", "rel", "group", "primary", "key", "call", "with", "as", "order", "by", "limit", "union", "alter", "drop", "and", "or", "not", "null", "true", "false"]);
17
+ const reserved = new Set(["action", "id", "name", "entity_type", "edge_type", "from", "to", "query", "limit", "direction", "attributes", "filters", "created_at", "updated_at", "KGSchema"]);
18
+ const fail = (message: string): never => { throw new Error(`Invalid ontology: ${message}`); };
19
+ function object(value: any, keys?: string[]) {
20
+ if (!value || typeof value !== "object" || Array.isArray(value)) fail("expected mapping");
21
+ if (keys && Object.keys(value).some((key) => !keys.includes(key))) fail("unknown configuration key");
22
+ }
23
+ export function validateOntology(value: any): Ontology {
24
+ object(value, ["version", "entities", "relationships", "shared_attributes"]);
25
+ if (!Number.isInteger(value.version) || value.version < 1) fail("version must be a positive integer");
26
+ object(value.entities); object(value.relationships); object(value.shared_attributes);
27
+ if (!Object.keys(value.entities).length) fail("entities required");
28
+ const labels = new Set<string>(); const columns = new Map<string, string>();
29
+ const attributes = (attrs: any) => {
30
+ object(attrs);
31
+ for (const [key, a] of Object.entries(attrs) as [string, Attribute][]) {
32
+ if (!identifier.test(key) || reserved.has(key) || reserved.has(key.toLowerCase()) || cypherKeywords.has(key.toLowerCase())) fail(`unsafe/reserved attribute ${key}`);
33
+ object(a, ["type", "enum", "maxLength", "required", "immutable", "description"]);
34
+ if (!["string", "number", "boolean"].includes(a.type)) fail(`unsupported type for ${key}`);
35
+ if (a.enum && (a.type !== "string" || !Array.isArray(a.enum) || !a.enum.length || a.enum.some(v => typeof v !== "string" || !v) || new Set(a.enum).size !== a.enum.length)) fail(`invalid enum ${key}`);
36
+ if (a.maxLength !== undefined && (a.type !== "string" || !Number.isInteger(a.maxLength) || a.maxLength < 1 || a.maxLength > 8000)) fail(`invalid maxLength ${key}`);
37
+ if (a.enum?.some(v => v.length > (a.maxLength ?? 8000))) fail(`enum exceeds maxLength ${key}`);
38
+ for (const flag of ["required", "immutable"] as const) if (a[flag] !== undefined && typeof a[flag] !== "boolean") fail(`invalid ${flag}`);
39
+ if (a.description !== undefined && typeof a.description !== "string") fail("description must be text");
40
+ const folded = key.toLowerCase(); const signature = JSON.stringify([key, a.type, a.enum ?? null, a.maxLength ?? null]);
41
+ if (columns.has(folded) && columns.get(folded) !== signature) fail(`conflicting column ${key}`);
42
+ columns.set(folded, signature);
43
+ }
44
+ };
45
+ attributes(value.shared_attributes);
46
+ for (const key of ["description", "source"]) if (value.shared_attributes[key]?.type !== "string") fail(`${key} must be a shared string attribute`);
47
+ for (const attrs of [value.shared_attributes, ...Object.values(value.entities).map((e: any) => e.attributes), ...Object.values(value.relationships).map((e: any) => e.attributes)]) {
48
+ for (const key of ["kind", "stage", "localPath", "gitlabUrl"]) if (attrs?.[key] && attrs[key].type !== "string") fail(`${key} is a legacy string column`);
49
+ }
50
+ for (const section of [value.entities, value.relationships]) for (const [name, def] of Object.entries(section) as [string, any][]) {
51
+ if (!identifier.test(name) || name.toLowerCase() === "kgschema" || cypherKeywords.has(name.toLowerCase()) || labels.has(name.toLowerCase())) fail(`unsafe/duplicate label ${name}`);
52
+ labels.add(name.toLowerCase());
53
+ object(def, section === value.entities ? ["description", "attributes"] : ["description", "attributes", "from", "to"]);
54
+ if (typeof def.description !== "string") fail(`description required for ${name}`);
55
+ attributes(def.attributes);
56
+ if (Object.keys(def.attributes).some(k => k in value.shared_attributes)) fail("shared attribute redefined");
57
+ }
58
+ for (const rel of Object.values(value.relationships) as any[]) for (const ep of [rel.from, rel.to]) {
59
+ object(ep);
60
+ const types = Array.isArray(ep.entity_type) ? ep.entity_type : [ep.entity_type];
61
+ if (!types.length || new Set(types).size !== types.length || types.some((t: string) => !Object.hasOwn(value.entities, t))) fail("unknown/duplicate endpoint type");
62
+ for (const [key, val] of Object.entries(ep)) if (key !== "entity_type") for (const type of types) {
63
+ const attr = value.entities[type].attributes[key] ?? value.shared_attributes[key];
64
+ if (!attr || !attr.immutable) fail(`endpoint constraint ${key} must reference an immutable attribute`);
65
+ validateValue(val, key, attr);
66
+ }
67
+ }
68
+ return value;
69
+ }
70
+ export function validateValue(value: unknown, key: string, attr: Attribute) {
71
+ if (typeof value !== attr.type || (typeof value === "number" && !Number.isFinite(value))) throw new Error(`${key} must be ${attr.type}`);
72
+ if (typeof value === "string" && (value.length > (attr.maxLength ?? 8000) || attr.required && !value.trim())) throw new Error(`Invalid ${key}`);
73
+ if (attr.enum && !attr.enum.includes(value as string)) throw new Error(`Invalid ${key}; expected ${attr.enum.join(" or ")}`);
74
+ }
75
+ export const legacyOntologyPath = fileURLToPath(new URL("./legacy-v5.json", import.meta.url));
76
+ export const defaultOntologyPath = fileURLToPath(new URL("./ontology.yaml", import.meta.url));
77
+ export const ONTOLOGY_MAX_BYTES = 128 * 1024;
78
+ function parseSource(source: string) {
79
+ if (Buffer.byteLength(source) > ONTOLOGY_MAX_BYTES) fail("configuration exceeds 128 KiB");
80
+ const doc = parseDocument(source, { uniqueKeys: true });
81
+ if (doc.errors.length || doc.warnings.length) fail([...doc.errors, ...doc.warnings].map(e => e.message).join("; "));
82
+ return doc.toJS({ maxAliasCount: 0 });
83
+ }
84
+ export function parseOntology(source: string): Ontology {
85
+ return deepFreeze(validateOntology(parseSource(source)));
86
+ }
87
+ export function loadOntology(path = process.env.PI_KNOWLEDGE_GRAPH_ONTOLOGY ?? defaultOntologyPath): Ontology {
88
+ const source = readFileSync(resolve(path), "utf8");
89
+ if (resolve(path) !== legacyOntologyPath) return parseOntology(source);
90
+ // Keep the immutable historical baseline readable, without exposing its old prose field.
91
+ const value = parseSource(source);
92
+ delete value.rules;
93
+ return deepFreeze(validateOntology(value));
94
+ }
95
+ export function deepFreeze<T>(value: T): T { if (value && typeof value === "object") { Object.values(value).forEach(deepFreeze); Object.freeze(value); } return value; }
96
+ function canonical(value: any): any { return Array.isArray(value) ? value.map(canonical) : value && typeof value === "object" ? Object.fromEntries(Object.keys(value).sort().map(k => [k, canonical(value[k])])) : value; }
97
+ export const fingerprint = (value: Ontology) => createHash("sha256").update(JSON.stringify(canonical(value))).digest("hex");
98
+ /** Only additive types/optional attributes; no reinterpretation of any existing definition. */
99
+ export function assertCompatible(old: Ontology, next: Ontology) {
100
+ for (const section of ["entities", "relationships", "shared_attributes"] as const) {
101
+ for (const [name, def] of Object.entries(old[section])) {
102
+ const candidate: any = next[section][name];
103
+ if (!candidate) throw new Error(`Incompatible ontology: removed ${name}`);
104
+ const before: any = structuredClone(def); const after: any = structuredClone(candidate);
105
+ delete before.description; delete after.description;
106
+ if (before.attributes) {
107
+ for (const [key, attr] of Object.entries(before.attributes)) {
108
+ const oldAttr: any = structuredClone(attr); const nextAttr: any = structuredClone(after.attributes[key]);
109
+ delete oldAttr.description; if (nextAttr) delete nextAttr.description;
110
+ if (JSON.stringify(canonical(oldAttr)) !== JSON.stringify(canonical(nextAttr))) throw new Error(`Incompatible ontology: changed ${name}.${key}`);
111
+ delete after.attributes[key];
112
+ }
113
+ if (Object.values(after.attributes).some((a: any) => a.required)) throw new Error(`Incompatible ontology: new required attribute on ${name}`);
114
+ delete before.attributes; delete after.attributes;
115
+ }
116
+ if (JSON.stringify(canonical(before)) !== JSON.stringify(canonical(after))) throw new Error(`Incompatible ontology: changed ${name}`);
117
+ }
118
+ }
119
+ for (const [key, attr] of Object.entries(next.shared_attributes)) if (!(key in old.shared_attributes) && attr.required) throw new Error(`Incompatible ontology: new required ${key}`);
120
+ }
121
+ export function columns(config: Ontology, edges = false): Record<string, Attribute> {
122
+ return Object.assign({}, config.shared_attributes, ...Object.values(edges ? config.relationships : config.entities).map(d => d.attributes));
123
+ }
124
+ export const sqlType = (a: Attribute) => ({ string: "STRING", number: "DOUBLE", boolean: "BOOL" })[a.type];
@@ -0,0 +1,3 @@
1
+ import { createJiti } from "jiti";
2
+ const core = await createJiti(import.meta.url).import("./api.ts");
3
+ export const GraphClient = core.GraphClient;