knowmind 0.1.9

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/LICENSE ADDED
@@ -0,0 +1,17 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ Copyright 2026 Schübeler Consulting
6
+
7
+ Licensed under the Apache License, Version 2.0 (the "License");
8
+ you may not use this file except in compliance with the License.
9
+ You may obtain a copy of the License at
10
+
11
+ http://www.apache.org/licenses/LICENSE-2.0
12
+
13
+ Unless required by applicable law or agreed to in writing, software
14
+ distributed under the License is distributed on an "AS IS" BASIS,
15
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
+ See the License for the specific language governing permissions and
17
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,70 @@
1
+ # knowmind
2
+
3
+ Kommandozeile und lokale MCP-Vermittlung für Knowmind — das Gedächtnis für Ihre KI.
4
+
5
+ ## Installation
6
+
7
+ ```
8
+ npm install -g https://knowmind.de/cli/knowmind-0.1.4.tgz
9
+ ```
10
+
11
+ Oder direkt aus dem Monorepo lokal:
12
+
13
+ ```
14
+ npm link
15
+ ```
16
+
17
+ ## Setup
18
+
19
+ 1. Token auf knowmind.de anlegen: Dashboard → API-Tokens
20
+ 2. Lokal speichern:
21
+
22
+ ```
23
+ knowmind login --token kmt_xxxxxxxx
24
+ ```
25
+
26
+ Alternativ über ENV:
27
+
28
+ ```
29
+ export KNOWMIND_TOKEN=kmt_xxxxxxxx
30
+ export KNOWMIND_API_URL=https://knowmind.de
31
+ ```
32
+
33
+ ## Befehle
34
+
35
+ ```
36
+ knowmind search "Wo läuft die OKR-App?"
37
+ knowmind upload notizen.md --title "Meeting Notizen 2026-05-12"
38
+ knowmind stats
39
+ knowmind health
40
+ knowmind config
41
+ ```
42
+
43
+ ## MCP-Stdio-Modus
44
+
45
+ Klassischer MCP-Server über stdin/stdout — bindet Knowmind in Claude Code, Claude Desktop, Cursor, ChatGPT-Desktop ein.
46
+
47
+ In `.claude/mcp-servers.json` oder `claude_desktop_config.json`:
48
+
49
+ ```json
50
+ {
51
+ "knowmind": {
52
+ "command": "knowmind",
53
+ "args": ["mcp"]
54
+ }
55
+ }
56
+ ```
57
+
58
+ Token kommt aus `~/.knowmind/config.json` oder `KNOWMIND_TOKEN`.
59
+
60
+ ## Tools (im MCP-Modus)
61
+
62
+ - `knowmind.recall` — Hybride Suche im Wissensspeicher des Mandanten
63
+ - `knowmind.store` — Neue Erinnerung anlegen (Titel + Inhalt)
64
+ - `knowmind.link` — Typisierte Beziehung zwischen zwei Erinnerungen anlegen (Inverse wird automatisch gesetzt)
65
+ - `knowmind.unlink` — Beziehung wieder entfernen (samt Inverse)
66
+ - `knowmind.relations` — Beziehungen einer Erinnerung auflisten
67
+ - `knowmind.stats` — Statistik über gespeicherte Erinnerungen und Beziehungen
68
+ - `knowmind.health` — Verfügbarkeits-Status der Plattform
69
+
70
+ Die zulässigen Beziehungstypen sind im Tool-Schema von `knowmind.link` als Enum hinterlegt — der Agent sieht sie direkt bei der Werkzeug-Auswahl. Inverse-Beziehungen (z. B. `IS_EMPLOYEE_OF` zu `HAS_EMPLOYEE`) werden serverseitig automatisch mit angelegt.
@@ -0,0 +1,224 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Knowmind CLI Entry-Point.
4
+ *
5
+ * Verfügbare Befehle:
6
+ * knowmind login [--token kmt_…] — API-Token speichern
7
+ * knowmind config — aktuelle Config anzeigen
8
+ * knowmind search "Frage" [-k 5] — Recall
9
+ * knowmind upload <file> [--title] — Dokument-Ingestion
10
+ * knowmind stats — Korpus-Statistik
11
+ * knowmind health — Service-Health
12
+ * knowmind mcp — Stdio-MCP-Server
13
+ */
14
+ import { readFileSync } from "node:fs";
15
+ import { basename } from "node:path";
16
+ import { stdin as input } from "node:process";
17
+ import {
18
+ recall,
19
+ uploadDocument,
20
+ stats,
21
+ health,
22
+ } from "../src/client.js";
23
+ import { loadConfig, saveConfig, configPath, VERSION } from "../src/config.js";
24
+ import { runStdioServer } from "../src/mcp-stdio.js";
25
+ import { syncDirectory } from "../src/sync.js";
26
+
27
+ const args = process.argv.slice(2);
28
+ const cmd = args[0];
29
+
30
+ function parseFlag(name, fallback) {
31
+ const i = args.indexOf(name);
32
+ if (i < 0) return fallback;
33
+ return args[i + 1] ?? fallback;
34
+ }
35
+
36
+ async function readStdin() {
37
+ return await new Promise((resolve) => {
38
+ let data = "";
39
+ input.setEncoding("utf-8");
40
+ input.on("data", (c) => (data += c));
41
+ input.on("end", () => resolve(data));
42
+ });
43
+ }
44
+
45
+ function help() {
46
+ console.log(`
47
+ Knowmind ${VERSION} — Das Gedächtnis für Ihre KI
48
+
49
+ Befehle:
50
+ knowmind login [--token kmt_TOKEN] [--api https://knowmind.de]
51
+ Token speichern
52
+ knowmind config Aktuelle Konfiguration anzeigen
53
+ knowmind search "Frage" [-k 5] [--hops 2]
54
+ Hybrid-Recall gegen den Tenant-Korpus
55
+ knowmind upload <file> [--title "..."]
56
+ Markdown-/Text-Datei indexieren (stdin: knowmind upload -)
57
+ knowmind sync <dir> [--ext .md,.txt] [--verbose] [--title-from-content]
58
+ Ordner mit dem Korpus abgleichen. Idempotent über
59
+ Content-Hash, Manifest in <dir>/.knowmind-manifest.json.
60
+ knowmind stats Memory- und Edge-Counter des Tenants
61
+ knowmind health Health-Check der Plattform
62
+ knowmind mcp Stdio-MCP-Server für lokale AI-Clients
63
+
64
+ ENV-Override:
65
+ KNOWMIND_API_URL z. B. https://knowmind.de
66
+ KNOWMIND_TOKEN Bearer-Token (überschreibt Config-File)
67
+ `);
68
+ }
69
+
70
+ async function runLogin() {
71
+ let token = parseFlag("--token", null);
72
+ const api = parseFlag("--api", null);
73
+ if (!token) {
74
+ // Interaktiv von stdin lesen
75
+ process.stdout.write("API-Token (kmt_…): ");
76
+ const line = await new Promise((resolve) => {
77
+ input.once("data", (d) => resolve(d.toString().trim()));
78
+ });
79
+ token = line;
80
+ }
81
+ if (!token || !token.startsWith("kmt_"))
82
+ throw new Error("Token muss mit kmt_ beginnen.");
83
+
84
+ // Vor dem Speichern: Token gegen Server verifizieren. Sonst wäre jeder
85
+ // Phantasie-String akzeptiert und alle späteren Aufrufe scheitern erst
86
+ // beim ersten echten Call — das ist verwirrend.
87
+ const apiUrl = api || process.env.KNOWMIND_API_URL || loadConfig().apiUrl;
88
+ process.stdout.write("Token wird gegen Server verifiziert … ");
89
+ const r = await fetch(`${apiUrl}/api/mcp/v1`, {
90
+ method: "POST",
91
+ headers: { "content-type": "application/json", authorization: `Bearer ${token}` },
92
+ body: JSON.stringify({
93
+ jsonrpc: "2.0",
94
+ id: 1,
95
+ method: "tools/call",
96
+ params: { name: "knowmind.health", arguments: {} },
97
+ }),
98
+ }).catch((e) => ({ ok: false, _netError: e.message }));
99
+ if (r._netError) {
100
+ process.stdout.write("FEHLER\n");
101
+ throw new Error(`Server nicht erreichbar (${apiUrl}): ${r._netError}`);
102
+ }
103
+ const data = await r.json().catch(() => ({}));
104
+ if (!r.ok || data.error) {
105
+ process.stdout.write("ABGELEHNT\n");
106
+ const code = data.error?.code ?? r.status;
107
+ const msg = data.error?.message ?? `HTTP ${r.status}`;
108
+ throw new Error(`Token ungültig: ${code} — ${msg}`);
109
+ }
110
+ process.stdout.write("ok\n");
111
+ const where = saveConfig({ token, ...(api ? { apiUrl: api } : {}) });
112
+ console.log(`Token gespeichert in ${where}.`);
113
+ }
114
+
115
+ async function runSearch() {
116
+ const query = args.slice(1).filter((a) => !a.startsWith("-")).join(" ");
117
+ if (!query) throw new Error('Usage: knowmind search "Ihre Frage"');
118
+ const k = Number(parseFlag("-k", parseFlag("--k", 5)));
119
+ const hops = Number(parseFlag("--hops", 2));
120
+ const result = await recall(query, { k, hops });
121
+ if (!result?.hits?.length) {
122
+ console.log("Keine Treffer.");
123
+ return;
124
+ }
125
+ for (const [i, hit] of result.hits.entries()) {
126
+ const src = hit.metadata?.source_id ?? hit.chunk_id;
127
+ const name = hit.metadata?.name ?? src;
128
+ console.log(`\n#${i + 1} ${name} (score ${hit.score.toFixed(3)})`);
129
+ console.log(" " + hit.content.slice(0, 280).replace(/\n/g, "\n "));
130
+ }
131
+ console.log(`\n${result.hits.length} Treffer in ${result.latency_ms} ms.`);
132
+ }
133
+
134
+ async function runUpload() {
135
+ const path = args[1];
136
+ if (!path) throw new Error("Usage: knowmind upload <file> (oder `-` für stdin)");
137
+ let content;
138
+ let title = parseFlag("--title", null);
139
+ if (path === "-") {
140
+ content = await readStdin();
141
+ title = title ?? "stdin";
142
+ } else {
143
+ content = readFileSync(path, "utf-8");
144
+ title = title ?? basename(path);
145
+ }
146
+ const data = await uploadDocument(title, content);
147
+ console.log(`Indexiert: ${data.chunksWritten} Chunks (Provider ${data.embeddingProvider}).`);
148
+ }
149
+
150
+ async function runSync() {
151
+ const dir = args[1];
152
+ if (!dir) throw new Error("Usage: knowmind sync <directory>");
153
+ const extFlag = parseFlag("--ext", null);
154
+ const options = {
155
+ extensions: extFlag ? extFlag.split(",").map((e) => (e.startsWith(".") ? e : `.${e}`)) : undefined,
156
+ verbose: args.includes("--verbose"),
157
+ titleFromContent: args.includes("--title-from-content"),
158
+ };
159
+ const result = await syncDirectory(dir, options);
160
+ if (result.failed > 0) process.exitCode = 3;
161
+ }
162
+
163
+
164
+ async function runStats() {
165
+ console.log(JSON.stringify(await stats(), null, 2));
166
+ }
167
+
168
+ async function runHealth() {
169
+ console.log(JSON.stringify(await health(), null, 2));
170
+ }
171
+
172
+ async function runConfig() {
173
+ const c = loadConfig();
174
+ console.log(`Config-Datei: ${configPath()}`);
175
+ console.log(`API-URL: ${c.apiUrl}`);
176
+ console.log(`Token: ${c.token ? c.token.slice(0, 12) + "…" : "(keiner)"}`);
177
+ }
178
+
179
+ // Wichtig: `process.exit(N)` reißt offene Sockets/fetch-Verbindungen mit
180
+ // rein und triggert auf Windows/Node 22 die libuv-Assertion
181
+ // `!(handle->flags & UV_HANDLE_CLOSING)`. Stattdessen `exitCode` setzen
182
+ // und sauber zurückkehren — Node beendet sich von selbst, sobald keine
183
+ // offenen Handles mehr da sind.
184
+ try {
185
+ switch (cmd) {
186
+ case "login":
187
+ await runLogin();
188
+ break;
189
+ case "config":
190
+ await runConfig();
191
+ break;
192
+ case "search":
193
+ await runSearch();
194
+ break;
195
+ case "upload":
196
+ await runUpload();
197
+ break;
198
+ case "sync":
199
+ await runSync();
200
+ break;
201
+ case "stats":
202
+ await runStats();
203
+ break;
204
+ case "health":
205
+ await runHealth();
206
+ break;
207
+ case "mcp":
208
+ await runStdioServer();
209
+ break;
210
+ case "--help":
211
+ case "-h":
212
+ case "help":
213
+ case undefined:
214
+ help();
215
+ break;
216
+ default:
217
+ console.error(`Unbekannter Befehl: ${cmd}`);
218
+ help();
219
+ process.exitCode = 1;
220
+ }
221
+ } catch (e) {
222
+ console.error(`Fehler: ${e.message}`);
223
+ process.exitCode = 2;
224
+ }
package/package.json ADDED
@@ -0,0 +1,51 @@
1
+ {
2
+ "name": "knowmind",
3
+ "version": "0.1.9",
4
+ "description": "Kommandozeile und lokale MCP-Vermittlung für Knowmind — das Gedächtnis für Ihre KI.",
5
+ "type": "module",
6
+ "license": "Apache-2.0",
7
+ "homepage": "https://knowmind.de",
8
+ "bugs": {
9
+ "url": "https://knowmind.de/support",
10
+ "email": "info@schuebeler-consulting.de"
11
+ },
12
+ "author": {
13
+ "name": "Knowmind",
14
+ "email": "info@schuebeler-consulting.de",
15
+ "url": "https://knowmind.de"
16
+ },
17
+ "engines": {
18
+ "node": ">=20"
19
+ },
20
+ "bin": {
21
+ "knowmind": "bin/knowmind.js"
22
+ },
23
+ "files": [
24
+ "bin",
25
+ "src",
26
+ "README.md",
27
+ "LICENSE"
28
+ ],
29
+ "scripts": {
30
+ "test": "node --test src/*.test.js"
31
+ },
32
+ "dependencies": {
33
+ "@huggingface/transformers": "^3.5.0"
34
+ },
35
+ "keywords": [
36
+ "knowmind",
37
+ "mcp",
38
+ "model-context-protocol",
39
+ "knowledge-graph",
40
+ "recall",
41
+ "memory",
42
+ "rag",
43
+ "claude",
44
+ "openai",
45
+ "anthropic",
46
+ "ai"
47
+ ],
48
+ "publishConfig": {
49
+ "access": "public"
50
+ }
51
+ }
package/src/client.js ADDED
@@ -0,0 +1,115 @@
1
+ /**
2
+ * Knowmind-API-Client.
3
+ *
4
+ * Spricht ausschließlich gegen den MCP-Endpoint /api/mcp/v1 (JSON-RPC),
5
+ * weil dieser bereits Bearer-Auth + Tools für recall/stats/health bietet.
6
+ * Document-Upload geht zusätzlich gegen die REST-API /api/documents.
7
+ */
8
+ import { loadConfig } from "./config.js";
9
+
10
+ let rpcId = 1;
11
+
12
+ async function rpc(method, params, options = {}) {
13
+ const { apiUrl, token } = loadConfig();
14
+ if (!token) throw new Error("Kein Token konfiguriert — bitte `knowmind login` ausführen.");
15
+ const r = await fetch(`${apiUrl}/api/mcp/v1`, {
16
+ method: "POST",
17
+ headers: {
18
+ "content-type": "application/json",
19
+ authorization: `Bearer ${token}`,
20
+ ...(options.headers ?? {}),
21
+ },
22
+ body: JSON.stringify({ jsonrpc: "2.0", id: rpcId++, method, params }),
23
+ signal: options.signal,
24
+ });
25
+ const data = await r.json();
26
+ if (data.error) throw new Error(`${data.error.code}: ${data.error.message}`);
27
+ return data.result;
28
+ }
29
+
30
+ export async function recall(query, { k = 5, hops = 2 } = {}) {
31
+ const res = await rpc("tools/call", {
32
+ name: "knowmind.recall",
33
+ arguments: { query, k, hops },
34
+ });
35
+ // MCP-Antwort: { content: [{ type: "text", text: "<JSON>" }] }
36
+ const text = res.content?.[0]?.text;
37
+ if (!text) return null;
38
+ return JSON.parse(text);
39
+ }
40
+
41
+ export async function stats() {
42
+ const res = await rpc("tools/call", { name: "knowmind.stats", arguments: {} });
43
+ return JSON.parse(res.content?.[0]?.text ?? "{}");
44
+ }
45
+
46
+ export async function health() {
47
+ const res = await rpc("tools/call", { name: "knowmind.health", arguments: {} });
48
+ return JSON.parse(res.content?.[0]?.text ?? "{}");
49
+ }
50
+
51
+ /**
52
+ * Lädt ein Dokument hoch. Default-Pfad: Client rechnet die Embeddings
53
+ * lokal und schickt sie mit — der Server speichert nur noch, ohne eigene
54
+ * Berechnung. Skaliert deutlich besser.
55
+ *
56
+ * Wird KNOWMIND_EMBED_MODE=server gesetzt, geht der alte Pfad: Server
57
+ * rechnet selbst. Sinnvoll als Fallback, wenn der Client kein Modell
58
+ * laden kann (z. B. RAM-knapp).
59
+ */
60
+ export async function uploadDocument(title, content) {
61
+ const { apiUrl, token } = loadConfig();
62
+ if (!token) throw new Error("Kein Token konfiguriert.");
63
+
64
+ const mode = (process.env.KNOWMIND_EMBED_MODE || "client").toLowerCase();
65
+ let body;
66
+ if (mode === "client") {
67
+ try {
68
+ const { prepareChunks, embedBatch, MODEL } = await import("./local-embedding.js");
69
+ // prepareChunks zerlegt Text in Standard-Chunks UND extrahiert
70
+ // Preference-/Fact-/Update-Statements als Zusatz-Chunks mit type-Tag.
71
+ // Recall-Server boostet die getaggten Chunks für passende Queries.
72
+ const prepared = await prepareChunks(content);
73
+ const vectors = await embedBatch(prepared.map((c) => c.content), "passage");
74
+ body = {
75
+ title,
76
+ content,
77
+ chunks: prepared.map((c, i) => ({
78
+ content: c.content,
79
+ embedding: vectors[i],
80
+ ...(c.metadata ? { metadata: c.metadata } : {}),
81
+ })),
82
+ embeddingModel: MODEL,
83
+ };
84
+ } catch (err) {
85
+ process.stderr.write(
86
+ `[knowmind] lokales Embedding fehlgeschlagen, fallback auf Server: ${err.message}\n`,
87
+ );
88
+ body = { title, content };
89
+ }
90
+ } else {
91
+ body = { title, content };
92
+ }
93
+
94
+ const r = await fetch(`${apiUrl}/api/documents`, {
95
+ method: "POST",
96
+ headers: { "content-type": "application/json", authorization: `Bearer ${token}` },
97
+ body: JSON.stringify(body),
98
+ });
99
+ const text = await r.text();
100
+ let data;
101
+ try {
102
+ data = text ? JSON.parse(text) : {};
103
+ } catch {
104
+ if (!r.ok) {
105
+ throw new Error(`HTTP ${r.status} ${r.statusText} — ${text.slice(0, 200)}`);
106
+ }
107
+ throw new Error(`HTTP ${r.status} lieferte ungültiges JSON: ${text.slice(0, 200)}`);
108
+ }
109
+ if (!r.ok) throw new Error(data.error ?? `HTTP ${r.status} ${r.statusText}`);
110
+ return data;
111
+ }
112
+
113
+ export async function listTools() {
114
+ return await rpc("tools/list", {});
115
+ }
package/src/config.js ADDED
@@ -0,0 +1,118 @@
1
+ /**
2
+ * Knowmind-CLI Konfiguration.
3
+ *
4
+ * Lese-Reihenfolge:
5
+ * 1. ENV (KNOWMIND_API_URL, KNOWMIND_TOKEN)
6
+ * 2. ~/.knowmind/config.json
7
+ * 3. Defaults
8
+ *
9
+ * Sicherheits-Garantien beim Schreiben:
10
+ * - Unix: chmod 600 auf config.json und 700 auf dem Ordner
11
+ * - Windows: aktive NTFS-ACL via icacls — nur der aktuelle User, SYSTEM
12
+ * und Administratoren behalten Zugriff. Das ist nötig, weil Node auf
13
+ * Windows `mode: 0o600` ignoriert.
14
+ * - Beim Start löschen wir Backup-Files (`config.json.bak*`,
15
+ * `config.json.sc-backup`), die frühere Versionen hinterlassen haben.
16
+ */
17
+ import { readFileSync, writeFileSync, mkdirSync, existsSync, readdirSync, unlinkSync } from "node:fs";
18
+ import { homedir, userInfo, platform } from "node:os";
19
+ import { join } from "node:path";
20
+ import { spawnSync } from "node:child_process";
21
+ import { fileURLToPath } from "node:url";
22
+
23
+ const DEFAULT_API = "https://knowmind.de";
24
+ const CONFIG_DIR = join(homedir(), ".knowmind");
25
+ const CONFIG_FILE = join(CONFIG_DIR, "config.json");
26
+
27
+ function _readPackageVersion() {
28
+ try {
29
+ const pkgUrl = new URL("../package.json", import.meta.url);
30
+ const pkg = JSON.parse(readFileSync(fileURLToPath(pkgUrl), "utf-8"));
31
+ return pkg.version || "0.0.0";
32
+ } catch {
33
+ return "0.0.0";
34
+ }
35
+ }
36
+
37
+ export const VERSION = _readPackageVersion();
38
+
39
+ /**
40
+ * Löscht alle `config.json.bak*`- und `config.json.sc-backup`-Files im
41
+ * Knowmind-Konfig-Ordner. Frühere CLI-Versionen haben solche Backups
42
+ * geschrieben, die den Token in Klartext-Kopien hinterlassen haben.
43
+ */
44
+ function _purgeStaleBackups() {
45
+ if (!existsSync(CONFIG_DIR)) return;
46
+ try {
47
+ for (const entry of readdirSync(CONFIG_DIR)) {
48
+ if (
49
+ entry.startsWith("config.json.bak") ||
50
+ entry === "config.json.sc-backup"
51
+ ) {
52
+ try {
53
+ unlinkSync(join(CONFIG_DIR, entry));
54
+ } catch {
55
+ // best effort
56
+ }
57
+ }
58
+ }
59
+ } catch {
60
+ // best effort
61
+ }
62
+ }
63
+
64
+ /**
65
+ * Windows: NTFS-ACL hart auf den aktuellen User + SYSTEM + Administratoren
66
+ * beschränken. Vererbung deaktiviert. Auf Unix ist `chmod` ausreichend.
67
+ */
68
+ function _lockdown(target) {
69
+ if (platform() !== "win32") return;
70
+ try {
71
+ const user = userInfo().username;
72
+ // /reset alleine reicht nicht — die geerbten Berechtigungen müssen weg.
73
+ spawnSync("icacls", [target, "/inheritance:r"], { stdio: "ignore" });
74
+ spawnSync("icacls", [target, "/grant:r", `${user}:(OI)(CI)F`], { stdio: "ignore" });
75
+ spawnSync("icacls", [target, "/grant:r", "SYSTEM:(OI)(CI)F"], { stdio: "ignore" });
76
+ spawnSync("icacls", [target, "/grant:r", "Administratoren:(OI)(CI)F"], {
77
+ stdio: "ignore",
78
+ });
79
+ // EN-Variante als Fallback (icacls akzeptiert beide nur in jeweiliger Locale)
80
+ spawnSync("icacls", [target, "/grant:r", "Administrators:(OI)(CI)F"], {
81
+ stdio: "ignore",
82
+ });
83
+ } catch {
84
+ // best effort — wenn icacls fehlt, fallen wir auf Standard-NTFS zurück
85
+ }
86
+ }
87
+
88
+ export function loadConfig() {
89
+ _purgeStaleBackups();
90
+ let fileConfig = {};
91
+ if (existsSync(CONFIG_FILE)) {
92
+ try {
93
+ fileConfig = JSON.parse(readFileSync(CONFIG_FILE, "utf-8"));
94
+ } catch {
95
+ /* corrupt — ignore */
96
+ }
97
+ }
98
+ return {
99
+ apiUrl: process.env.KNOWMIND_API_URL ?? fileConfig.apiUrl ?? DEFAULT_API,
100
+ token: process.env.KNOWMIND_TOKEN ?? fileConfig.token ?? null,
101
+ };
102
+ }
103
+
104
+ export function saveConfig(partial) {
105
+ const merged = { ...loadConfig(), ...partial };
106
+ if (!existsSync(CONFIG_DIR)) {
107
+ mkdirSync(CONFIG_DIR, { recursive: true, mode: 0o700 });
108
+ _lockdown(CONFIG_DIR);
109
+ }
110
+ writeFileSync(CONFIG_FILE, JSON.stringify(merged, null, 2), { mode: 0o600 });
111
+ _lockdown(CONFIG_DIR);
112
+ _lockdown(CONFIG_FILE);
113
+ return CONFIG_FILE;
114
+ }
115
+
116
+ export function configPath() {
117
+ return CONFIG_FILE;
118
+ }