knowmind 0.1.19 → 0.1.21

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 CHANGED
@@ -1,5 +1,53 @@
1
1
  # Knowmind CLI — Änderungen
2
2
 
3
+ ## 0.1.21 (2026-06-10)
4
+
5
+ **Bugfix: `knowmind init`-Recall-Hook funktioniert jetzt auf Windows**
6
+ - Der von `knowmind init --client claude-code` erzeugte Recall-Hook rief die Plattform
7
+ bisher über einen Subprozess auf (`spawnSync("npx.cmd", …)`). Auf Windows mit Node
8
+ ≥ 18.20.2/20.12/21.6/22 wirft das `EINVAL` (Node-Härtung CVE-2024-27980 gegen das
9
+ direkte Spawnen von `.cmd`/`.bat` ohne Shell) — der Hook feuerte dort nie. Gefunden im
10
+ echten Claude-Code-Realtest.
11
+ - Fix: Der Hook ruft die Plattform jetzt per **direktem HTTPS-Call** (`fetch` gegen
12
+ `/api/mcp/v1`, `tools/call knowmind_recall`) auf — kein Subprozess, kein npx-Kaltstart
13
+ (Timeout 6 s, schneller), und **keine Command-Injection** mehr, weil die Nutzer-Frage
14
+ als JSON-Body statt als Shell-Argument übergeben wird. Token/apiUrl aus ENV oder
15
+ `~/.knowmind/config.json`. Treffer werden lesbar verdichtet ausgegeben (Titel + Score +
16
+ Auszug). Weiterhin fail-open (jeder Fehler/kein Token → exit 0). SSE- und Plain-JSON-
17
+ Antworten werden robust geparst.
18
+
19
+ ## 0.1.20 (2026-06-10)
20
+
21
+ **MCP-`instructions` erreichen jetzt den Client (initialize wird durchgereicht)**
22
+ - `knowmind mcp` beantwortete `initialize` bisher lokal und unterschlug damit das
23
+ serverseitige `instructions`-Feld. Der Proxy fragt `initialize` nun beim Server an und
24
+ übernimmt `serverInfo` (Name/Version aus zentraler Quelle), `capabilities` und
25
+ `instructions` aus der Server-Antwort. Damit liest jeder MCP-Client beim Verbinden die
26
+ Memory-First-Betriebsanweisung des Servers — der client-übergreifende Pflege-Hebel
27
+ OHNE manuelles Setup. Bei Server-Fehler/Offline fällt der Proxy auf den lokalen Default
28
+ zurück (Proxy-Charakter + Offline-Robustheit bleiben).
29
+ - Serverseitig (knowmind.de) liefert das `initialize`-Result jetzt ein `instructions`-Feld
30
+ (Recall-First + proaktives Speichern) sowie `serverInfo.version` aus einer einzigen Quelle.
31
+
32
+ **Neuer Befehl: `knowmind init` — automatische Gedächtnis-Pflege einrichten**
33
+ - `knowmind init [--client claude-code|cursor|auto] [--dry-run]` richtet die
34
+ Memory-First-Automatik im KI-Client des Nutzers ein, ohne manuelles Hook-Gefrickel.
35
+ Client wird am Projekt-/Home-Verzeichnis erkannt (`.claude/`, `.cursor/`, `~/.codex/`)
36
+ oder explizit gewählt.
37
+ - **Claude Code:** schreibt projektlokale Hooks (`UserPromptSubmit` → `knowmind_recall`
38
+ vor jeder Frage; `Stop` → Capture-Reminder, der an `knowmind_store_memory` erinnert,
39
+ wenn die Runde Sicherungswürdiges enthielt) + einen Memory-First-Block in `./CLAUDE.md`.
40
+ Die Hooks reden gegen die Plattform (`npx knowmind search` / die MCP-Tools), nicht
41
+ gegen lokale `.md`-Dateien.
42
+ - **Cursor:** schreibt `.cursor/rules/knowmind.mdc` (Memory-First-Regel, `alwaysApply`).
43
+ - **Claude Desktop / Codex / generisch:** kein Hook-Mechanismus — zeigt den
44
+ Memory-First-Text zum manuellen Einfügen und benennt die ehrliche Grenze (nur
45
+ MCP-instructions + MCP-prompts wirken, keine harte Erzwingung).
46
+ - **Idempotent & nicht-destruktiv:** marker-/befehls-basierte Ersetzung
47
+ (`<!-- BEGIN/END knowmind -->`); zweiter Lauf erzeugt keine Duplikate, fremde Dateien
48
+ und Hooks bleiben unangetastet. `--dry-run` zeigt jede Aktion ohne zu schreiben.
49
+ - Tests in `src/init.test.js` (Idempotenz, Client-Erkennung, dry-run, Marker-Upsert).
50
+
3
51
  ## 0.1.19 (2026-06-10)
4
52
 
5
53
  **CLI-Befehle repariert (search/stats/health/login)**
package/README.md CHANGED
@@ -34,6 +34,7 @@ export KNOWMIND_API_URL=https://knowmind.de
34
34
  ## Befehle
35
35
 
36
36
  ```
37
+ knowmind init Automatische Gedächtnis-Pflege im KI-Client einrichten
37
38
  knowmind search "Wo läuft die OKR-App?"
38
39
  knowmind upload notizen.md --title "Meeting Notizen 2026-05-12"
39
40
  knowmind stats
@@ -41,6 +42,43 @@ knowmind health
41
42
  knowmind config
42
43
  ```
43
44
 
45
+ ## Automatische Pflege einrichten (`knowmind init`)
46
+
47
+ Damit Ihre KI knowmind selbsttätig pflegt — **Recall vor jeder Aufgabe**, **Sichern nach
48
+ jeder sicherungswürdigen Runde** — richtet `knowmind init` die passenden Mechanismen für
49
+ Ihren Client ein. Der Befehl erkennt den Client am Projekt- und Home-Verzeichnis
50
+ (`.claude/`, `.cursor/`, `~/.codex/`) oder Sie wählen ihn explizit.
51
+
52
+ ```
53
+ knowmind init # Client automatisch erkennen
54
+ knowmind init --client claude-code # gezielt für Claude Code
55
+ knowmind init --client cursor # gezielt für Cursor
56
+ knowmind init --dry-run # zeigt nur, was geschähe (schreibt nichts)
57
+ ```
58
+
59
+ **Was eingerichtet wird:**
60
+
61
+ - **Claude Code** — projektlokale Hooks in `.claude/`:
62
+ - *UserPromptSubmit* → ruft vor jeder echten Frage `knowmind_recall` auf und reicht die
63
+ Top-Treffer als Kontext nach (Memory-First, automatisch).
64
+ - *Stop* → erinnert die KI daran, mit `knowmind_store_memory` zu sichern, wenn die Runde
65
+ Sicherungswürdiges enthielt (Deploy/Commit, neue Regel, Entscheidung) und noch nichts
66
+ gespeichert wurde.
67
+ - ein **Memory-First-Block** in `./CLAUDE.md` (mit `<!-- BEGIN/END knowmind -->`-Markern).
68
+ - **Cursor** — `.cursor/rules/knowmind.mdc` mit der Memory-First-Regel (`alwaysApply`).
69
+ - **Claude Desktop / Codex / generisch** — kein automatischer Hook-Mechanismus vorhanden;
70
+ der Befehl zeigt den Memory-First-Text zum manuellen Einfügen (siehe Grenze unten).
71
+
72
+ **Idempotent & nicht-destruktiv:** Ein zweiter Lauf erzeugt keine Duplikate
73
+ (marker-/befehls-basierte Ersetzung); bestehende fremde Dateien und Hooks bleiben
74
+ unangetastet. Mit `--dry-run` sehen Sie jede Aktion vorab.
75
+
76
+ > **Ehrliche Grenze:** Eine *harte* Erzwingung der Pflege gibt es nur in Clients mit
77
+ > Hook-/Rule-Mechanismus (Claude Code, Cursor). In Clients ohne solchen Mechanismus
78
+ > (z. B. Claude Desktop, Codex CLI) wirken nur die **MCP-instructions** (werden beim
79
+ > Verbinden gelesen) und die **MCP-prompts** — das ist eine weiche, modellabhängige
80
+ > Steuerung, keine technische Garantie.
81
+
44
82
  ## MCP-Server einrichten
45
83
 
46
84
  knowmind ist ein MCP-Server (`npx -y knowmind mcp`, stdio). Token aus dem knowmind.de-Dashboard
package/bin/knowmind.js CHANGED
@@ -23,6 +23,7 @@ import {
23
23
  import { loadConfig, saveConfig, configPath, VERSION } from "../src/config.js";
24
24
  import { runStdioServer } from "../src/mcp-stdio.js";
25
25
  import { syncDirectory } from "../src/sync.js";
26
+ import { runInit } from "../src/init.js";
26
27
 
27
28
  const args = process.argv.slice(2);
28
29
  const cmd = args[0];
@@ -49,6 +50,9 @@ Knowmind ${VERSION} — Das Gedächtnis für Ihre KI
49
50
  Befehle:
50
51
  knowmind login [--token kmt_TOKEN] [--api https://knowmind.de]
51
52
  Token speichern
53
+ knowmind init [--client claude-code|cursor|auto] [--dry-run]
54
+ Automatische Gedächtnis-Pflege im KI-Client einrichten
55
+ (Hooks/Regeln + Memory-First-Block). Idempotent.
52
56
  knowmind config Aktuelle Konfiguration anzeigen
53
57
  knowmind search "Frage" [-k 5] [--hops 2]
54
58
  Hybrid-Recall gegen den Tenant-Korpus
@@ -180,6 +184,12 @@ async function runConfig() {
180
184
  console.log(`Token: ${c.token ? c.token.slice(0, 12) + "…" : "(keiner)"}`);
181
185
  }
182
186
 
187
+ async function runInitCmd() {
188
+ const client = parseFlag("--client", "auto");
189
+ const dryRun = args.includes("--dry-run");
190
+ console.log(await runInit({ client, dryRun }));
191
+ }
192
+
183
193
  // Wichtig: `process.exit(N)` reißt offene Sockets/fetch-Verbindungen mit
184
194
  // rein und triggert auf Windows/Node 22 die libuv-Assertion
185
195
  // `!(handle->flags & UV_HANDLE_CLOSING)`. Stattdessen `exitCode` setzen
@@ -211,6 +221,9 @@ try {
211
221
  case "mcp":
212
222
  await runStdioServer();
213
223
  break;
224
+ case "init":
225
+ await runInitCmd();
226
+ break;
214
227
  case "--help":
215
228
  case "-h":
216
229
  case "help":
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "knowmind",
3
- "version": "0.1.19",
3
+ "version": "0.1.21",
4
4
  "mcpName": "io.github.Schubeler-Consulting/knowmind",
5
5
  "description": "Knowmind — das Agentengehirn aus Deutschland: CLI + MCP-Server (Langzeitgedächtnis & Wissensgraph für Ihre KI, Server in Deutschland).",
6
6
  "type": "module",
@@ -28,6 +28,7 @@
28
28
  "files": [
29
29
  "bin",
30
30
  "src",
31
+ "!src/*.test.js",
31
32
  "README.md",
32
33
  "CHANGELOG.md",
33
34
  "LICENSE"
package/src/init.js ADDED
@@ -0,0 +1,643 @@
1
+ /**
2
+ * `knowmind init` — client-aware Onboarding.
3
+ *
4
+ * Richtet die AUTOMATISCHE Gedächtnis-Pflege im erkannten KI-Client ein, damit
5
+ * die Kunden-KI knowmind ohne manuelles Hook-Gefrickel pflegt:
6
+ *
7
+ * - Claude Code: schreibt projektlokale Hooks (UserPromptSubmit -> Recall-Hint
8
+ * via knowmind_recall; Stop -> Capture-Reminder, der an knowmind_store_memory
9
+ * erinnert, wenn die Runde Sicherungswürdiges enthielt) und einen
10
+ * Memory-First-Block in ./CLAUDE.md (idempotent, BEGIN/END-Marker).
11
+ * - Cursor: schreibt .cursor/rules/knowmind.mdc mit der Memory-First-Regel.
12
+ * - generisch / Claude Desktop: erklärt, dass die MCP-instructions automatisch
13
+ * wirken, und zeigt den manuellen Memory-First-Text zum Einfügen.
14
+ *
15
+ * Garantien:
16
+ * - IDEMPOTENT: zweiter Lauf erzeugt keine Duplikate. Eingefügte Blöcke werden
17
+ * mit BEGIN/END-knowmind-Markern umschlossen und beim erneuten Lauf ersetzt,
18
+ * nie ein zweites Mal angehängt.
19
+ * - NICHT-DESTRUKTIV: ohne Marker wird keine fremde Datei überschrieben; eigene
20
+ * Dateien (Hook-Skripte, .mdc) werden nur ge-/überschrieben, wenn sie einen
21
+ * knowmind-Marker tragen ODER neu sind.
22
+ * - --dry-run zeigt jede Aktion, schreibt aber nichts.
23
+ *
24
+ * Die Hooks rufen NICHT lokale .md-Dateien an (das ist der interne SC-Weg),
25
+ * sondern reden gegen die Plattform: `npx knowmind search` für Recall.
26
+ * Token/apiUrl kommen aus der knowmind-Config (~/.knowmind/config.json) bzw. ENV.
27
+ */
28
+ import {
29
+ existsSync,
30
+ readFileSync,
31
+ writeFileSync,
32
+ mkdirSync,
33
+ chmodSync,
34
+ } from "node:fs";
35
+ import { homedir, platform } from "node:os";
36
+ import { join, resolve, dirname } from "node:path";
37
+ import { loadConfig, VERSION } from "./config.js";
38
+
39
+ // ─── Marker (für idempotente Block-Ersetzung) ────────────────────────
40
+ const BEGIN = "<!-- BEGIN knowmind -->";
41
+ const END = "<!-- END knowmind -->";
42
+ const BEGIN_HASH = "# >>> BEGIN knowmind >>>";
43
+ const END_HASH = "# <<< END knowmind <<<";
44
+
45
+ // ─── Memory-First-Text (Kunden-Variante, gegen die Plattform) ────────
46
+ // Bewusst kurz und client-neutral. Verweist auf die MCP-Tools, die der
47
+ // knowmind-MCP-Server bereitstellt (knowmind_recall / knowmind_store_memory).
48
+ function memoryFirstBlock() {
49
+ return [
50
+ BEGIN,
51
+ "## knowmind — automatische Gedächtnis-Pflege",
52
+ "",
53
+ "Dieses Projekt nutzt **knowmind** (Langzeitgedächtnis & Wissensgraph) als MCP-Server.",
54
+ "Halte dich an die Memory-First-Regel:",
55
+ "",
56
+ "1. **Recall zuerst.** Bevor du eine inhaltliche Frage beantwortest oder eine",
57
+ " Aufgabe planst, rufe `knowmind_recall` (oder `knowmind search`) auf und prüfe,",
58
+ " ob es bereits relevantes Wissen gibt. Erst danach Dateien lesen/Web suchen.",
59
+ "2. **Wissen sichern.** Wenn eine Runde etwas Sicherungswürdiges hervorbringt —",
60
+ " eine Entscheidung, eine neue Regel, ein Ergebnis, ein Fakt über Personen/",
61
+ " Projekte/Systeme — lege es mit `knowmind_store_memory` (Titel + Inhalt) ab,",
62
+ " bevor du fortfährst. Reine Recherche oder Wegwerf-Tests müssen nicht gesichert werden.",
63
+ "3. **Beziehungen pflegen.** Verknüpfe zusammengehörige Erinnerungen mit",
64
+ " `knowmind_link`, damit der Graph nutzbar bleibt.",
65
+ "",
66
+ "Das Gedächtnis lebt auf der knowmind-Plattform (Server in Deutschland), nicht in",
67
+ "lokalen Dateien. Es ist über Sessions und Clients hinweg dasselbe Gehirn.",
68
+ END,
69
+ ].join("\n");
70
+ }
71
+
72
+ // ─── Generischer Hinweis-Text (manuell einfügbar) ────────────────────
73
+ function manualSnippet() {
74
+ return memoryFirstBlock();
75
+ }
76
+
77
+ // ─── Datei-Helfer ────────────────────────────────────────────────────
78
+
79
+ /**
80
+ * Fügt einen marker-umschlossenen Block in eine Textdatei ein bzw. ersetzt
81
+ * einen bereits vorhandenen. Liefert { action, content } ohne zu schreiben.
82
+ * action: "create" | "replace" | "append" | "unchanged"
83
+ */
84
+ function upsertMarkedBlock(filePath, block, { begin = BEGIN, end = END } = {}) {
85
+ const existed = existsSync(filePath);
86
+ const current = existed ? readFileSync(filePath, "utf-8") : "";
87
+
88
+ // Bereits ein Block vorhanden? -> ersetzen.
89
+ const bi = current.indexOf(begin);
90
+ const ei = current.indexOf(end);
91
+ if (bi !== -1 && ei !== -1 && ei > bi) {
92
+ const before = current.slice(0, bi);
93
+ const after = current.slice(ei + end.length);
94
+ const next = (before + block + after).replace(/\n{3,}/g, "\n\n");
95
+ if (next === current) return { action: "unchanged", content: current };
96
+ return { action: "replace", content: next };
97
+ }
98
+
99
+ // Kein Block -> anhängen (oder Datei neu).
100
+ if (!existed) {
101
+ return { action: "create", content: block + "\n" };
102
+ }
103
+ const sep = current.endsWith("\n") ? "\n" : "\n\n";
104
+ return { action: "append", content: current + sep + block + "\n" };
105
+ }
106
+
107
+ /** Schreibt eine eigene knowmind-Datei nur, wenn neu ODER marker-getragen. */
108
+ function writeOwnFile(filePath, content, marker) {
109
+ if (existsSync(filePath)) {
110
+ const cur = readFileSync(filePath, "utf-8");
111
+ if (!cur.includes(marker)) {
112
+ return { action: "skip-foreign", reason: "Datei existiert ohne knowmind-Marker" };
113
+ }
114
+ if (cur === content) return { action: "unchanged" };
115
+ return { action: "overwrite", content };
116
+ }
117
+ return { action: "create", content };
118
+ }
119
+
120
+ // ─── Client-Erkennung ────────────────────────────────────────────────
121
+
122
+ /**
123
+ * Erkennt den/die wahrscheinlichen Client(s) anhand von Projekt- und
124
+ * Home-Verzeichnis. Liefert eine Liste, weil mehrere zugleich plausibel sind.
125
+ */
126
+ export function detectClients(cwd, home) {
127
+ const found = new Set();
128
+ // Claude Code: projektlokales .claude/ ODER globale ~/.claude.json / ~/.claude
129
+ if (existsSync(join(cwd, ".claude"))) found.add("claude-code");
130
+ if (existsSync(join(home, ".claude.json")) || existsSync(join(home, ".claude")))
131
+ found.add("claude-code");
132
+ // Cursor: projektlokales .cursor/ ODER globale ~/.cursor
133
+ if (existsSync(join(cwd, ".cursor"))) found.add("cursor");
134
+ if (existsSync(join(home, ".cursor"))) found.add("cursor");
135
+ // Codex CLI
136
+ if (existsSync(join(home, ".codex", "config.toml"))) found.add("codex");
137
+ return [...found];
138
+ }
139
+
140
+ // ─── Hook-Skripte (Claude-Code-Vorlage, gegen die Plattform) ─────────
141
+ // Reines Node, keine externen Deps — laufen über `node`. Sie rufen die CLI
142
+ // per `npx -y knowmind ...` bzw. direkt die Bearer-API, ohne SC-spezifische
143
+ // Pfade. Token/apiUrl über ENV oder ~/.knowmind/config.json.
144
+
145
+ function autoRecallHookSource() {
146
+ return `#!/usr/bin/env node
147
+ // >>> knowmind auto-recall hook (UserPromptSubmit)
148
+ // Erzeugt von: knowmind init. Idempotent ersetzbar (trägt diesen Marker).
149
+ //
150
+ // Ruft vor jeder echten Frage knowmind_recall auf und injiziert die Top-Treffer
151
+ // als zusätzlichen Kontext (stdout). Direkter HTTPS-Call gegen die Plattform —
152
+ // KEIN Subprozess/npx: das vermeidet den Windows-.cmd-Spawn-Fehler (EINVAL bei
153
+ // spawn von npx.cmd ohne Shell, Node-Härtung CVE-2024-27980) und den langsamen
154
+ // npx-Kaltstart; und es gibt KEINE Command-Injection, weil die Nutzer-Frage als
155
+ // JSON-Body und nicht als Shell-Argument übergeben wird. Fail-open: jeder
156
+ // Fehler / fehlendes Token -> exit 0 ohne Ausgabe, blockiert nie.
157
+ import { readFileSync } from "node:fs";
158
+ import { homedir } from "node:os";
159
+ import { join } from "node:path";
160
+
161
+ const TRIVIAL = new Set([
162
+ "ok","okay","go","ja","nein","weiter","stop","danke","thanks","thx",
163
+ "yes","no","yep","nope","perfekt","passt","super","gut",
164
+ ]);
165
+ const TRIGGER = [
166
+ "kunde","kunden","projekt","tool","server","domain","wer ist","was ist",
167
+ "welche","liste","übersicht","status","wo ","wann","wieso","warum",
168
+ "recherche","research","info zu","infos zu","memory","graph","datenbank",
169
+ ];
170
+
171
+ function shouldRecall(p) {
172
+ const s = (p || "").trim().toLowerCase();
173
+ if (s.length < 8) return false;
174
+ if (TRIVIAL.has(s)) return false;
175
+ if (s.startsWith("/")) return false;
176
+ if (TRIGGER.some((k) => s.includes(k))) return true;
177
+ if (s.endsWith("?")) return true;
178
+ return s.length >= 40;
179
+ }
180
+
181
+ // Token + apiUrl: ENV hat Vorrang, sonst ~/.knowmind/config.json (gleiche
182
+ // Reihenfolge wie die CLI). Kein Token -> kein Recall (fail-open).
183
+ function loadCreds() {
184
+ let file = {};
185
+ try {
186
+ file = JSON.parse(readFileSync(join(homedir(), ".knowmind", "config.json"), "utf-8"));
187
+ } catch { /* keine/kaputte Config -> ENV/Default */ }
188
+ let apiUrl = process.env.KNOWMIND_API_URL || file.apiUrl || "https://knowmind.de";
189
+ if (apiUrl.endsWith("/")) apiUrl = apiUrl.slice(0, -1);
190
+ return { apiUrl, token: process.env.KNOWMIND_TOKEN || file.token || null };
191
+ }
192
+
193
+ // Antwort von /api/mcp/v1 ist Standard-SSE (data:-Frames) ODER plain JSON.
194
+ // Beides robust auf das JSON-RPC-Objekt mit result/error reduzieren.
195
+ function parseBody(raw) {
196
+ raw = (raw || "").trim();
197
+ if (!raw) return null;
198
+ if (raw.startsWith("{")) { try { return JSON.parse(raw); } catch { return null; } }
199
+ let found = null;
200
+ for (const lineRaw of raw.split("\\n")) {
201
+ const line = lineRaw.trim();
202
+ if (line.indexOf("data:") !== 0) continue;
203
+ try {
204
+ const obj = JSON.parse(line.slice(5).trim());
205
+ if (obj && (obj.result || obj.error)) found = obj;
206
+ } catch { /* nicht-JSON data-Zeile überspringen */ }
207
+ }
208
+ return found;
209
+ }
210
+
211
+ // knowmind_recall liefert result.content[].text = JSON-String mit hits[].
212
+ // Lesbar verdichten; bei Parse-Fehler den Rohtext durchreichen.
213
+ function formatHits(rpc) {
214
+ const c = rpc && rpc.result && rpc.result.content;
215
+ const text = Array.isArray(c)
216
+ ? c.filter((b) => b && b.type === "text" && b.text).map((b) => b.text).join("\\n").trim()
217
+ : "";
218
+ if (!text) return "";
219
+ try {
220
+ const o = JSON.parse(text);
221
+ if (Array.isArray(o.hits)) {
222
+ if (o.hits.length === 0) return "";
223
+ return o.hits.slice(0, 5).map((h, i) => {
224
+ const m = h.metadata || {};
225
+ const title = m.title || m.name || h.source || ("Treffer " + (i + 1));
226
+ const score = typeof h.score === "number" ? " (" + h.score.toFixed(2) + ")" : "";
227
+ const snip = String(h.content || "").replace(/\\s+/g, " ").trim().slice(0, 280);
228
+ return "• " + title + score + ": " + snip;
229
+ }).join("\\n");
230
+ }
231
+ } catch { /* kein hits-JSON -> Rohtext */ }
232
+ return text;
233
+ }
234
+
235
+ async function main() {
236
+ let raw = "";
237
+ process.stdin.setEncoding("utf-8");
238
+ for await (const c of process.stdin) raw += c;
239
+ let prompt = "";
240
+ try {
241
+ const data = raw ? JSON.parse(raw) : {};
242
+ prompt = data.prompt || data.user_prompt || data.user_message || "";
243
+ } catch { return; }
244
+ if (!shouldRecall(prompt)) return;
245
+
246
+ const { apiUrl, token } = loadCreds();
247
+ if (!token) return;
248
+ const query = prompt.trim().slice(0, 500);
249
+
250
+ const ctrl = new AbortController();
251
+ const timer = setTimeout(() => ctrl.abort(), 6000);
252
+ let rpc = null;
253
+ try {
254
+ const res = await fetch(apiUrl + "/api/mcp/v1", {
255
+ method: "POST",
256
+ headers: {
257
+ "Authorization": "Bearer " + token,
258
+ "Content-Type": "application/json",
259
+ "Accept": "application/json, text/event-stream",
260
+ },
261
+ body: JSON.stringify({
262
+ jsonrpc: "2.0", id: 1, method: "tools/call",
263
+ params: { name: "knowmind_recall", arguments: { query, k: 5, hops: 2 } },
264
+ }),
265
+ signal: ctrl.signal,
266
+ });
267
+ rpc = parseBody(await res.text());
268
+ } catch { return; } finally { clearTimeout(timer); }
269
+
270
+ const hits = formatHits(rpc);
271
+ if (!hits) return;
272
+
273
+ process.stdout.write(
274
+ "═════════ knowmind RECALL (auto) ═════════\\n" +
275
+ hits + "\\n" +
276
+ "Diese Treffer wurden automatisch vor deiner Antwort abgerufen.\\n" +
277
+ "Erst hier prüfen, dann Dateien lesen / Web suchen.\\n" +
278
+ "══════════════════════════════════════════\\n"
279
+ );
280
+ }
281
+
282
+ main().catch(() => process.exit(0));
283
+ // <<< knowmind auto-recall hook
284
+ `;
285
+ }
286
+
287
+ function captureGateHookSource() {
288
+ return `#!/usr/bin/env node
289
+ // >>> knowmind capture-gate hook (Stop)
290
+ // Erzeugt von: knowmind init. Idempotent ersetzbar (trägt diesen Marker).
291
+ //
292
+ // Prüft nach jeder Antwort, ob die Runde Sicherungswürdiges enthielt
293
+ // (Code-/Config-Änderung, Deploy/Commit, neue Regel/Entscheidung) UND ob ein
294
+ // knowmind_store_memory aufgerufen wurde. Wenn nicht -> {"decision":"block"},
295
+ // damit die KI vor dem Stoppen eine Erinnerung ablegt.
296
+ // Rein heuristisch (kein LLM). Loop-Schutz via stop_hook_active. Fail-open.
297
+ import { readFileSync } from "node:fs";
298
+
299
+ const DEPLOY = /\\b(git\\s+commit|git\\s+push|docker\\s+compose[^\\n]*\\bup\\b|docker\\s+build|deploy|scp|rsync|npm\\s+publish|kubectl\\s+apply)\\b/i;
300
+ const RULE = /(ab sofort|ab jetzt|von nun an|merk(e)? dir|neue regel|regel:|harte regel|standing order|niemals wieder|nie wieder)/i;
301
+ const ARCH = /(architektur-?entscheid|\\bADR\\b|wir stellen um|grundsatzentscheidung|wir migrieren auf|umstellung auf|wir setzen auf)/i;
302
+ const CODE_EXT = [".ts",".tsx",".js",".jsx",".mjs",".cjs",".py",".php",".go",".rs",".java",".rb",".css",".scss",".html",".vue",".svelte",".json",".yml",".yaml",".toml",".prisma",".sql",".sh",".ps1"];
303
+ const STORE_HINTS = ["knowmind_store","store_memory","update_fact","knowmind_update_fact"];
304
+
305
+ function isUserMsg(e) {
306
+ if (e.type !== "user") return false;
307
+ const c = e.message?.content;
308
+ if (typeof c === "string") return !!c.trim();
309
+ if (Array.isArray(c)) {
310
+ const text = c.some((b) => b?.type === "text");
311
+ const tr = c.some((b) => b?.type === "tool_result");
312
+ return text && !tr;
313
+ }
314
+ return false;
315
+ }
316
+ function userText(e) {
317
+ const c = e.message?.content;
318
+ if (typeof c === "string") return c;
319
+ if (Array.isArray(c)) return c.filter((b) => b?.type === "text").map((b) => b.text || "").join(" ");
320
+ return "";
321
+ }
322
+ function collectRound(path) {
323
+ const lines = readFileSync(path, "utf-8").split(/\\r?\\n/).filter(Boolean).map((l) => { try { return JSON.parse(l); } catch { return null; } }).filter(Boolean);
324
+ let start = 0;
325
+ for (let i = lines.length - 1; i >= 0; i--) if (isUserMsg(lines[i])) { start = i; break; }
326
+ const utext = lines.length ? userText(lines[start]) : "";
327
+ const tools = [];
328
+ for (const e of lines.slice(start)) {
329
+ if (e.type !== "assistant") continue;
330
+ const c = e.message?.content;
331
+ if (Array.isArray(c)) for (const b of c) if (b?.type === "tool_use") tools.push(b);
332
+ }
333
+ return { utext, tools };
334
+ }
335
+ function hasStore(tools) {
336
+ for (const t of tools) {
337
+ const n = (t.name || "").toLowerCase();
338
+ if (STORE_HINTS.some((h) => n.includes(h))) return true;
339
+ }
340
+ return false;
341
+ }
342
+ function detect(utext, tools) {
343
+ const sig = [];
344
+ for (const t of tools) if (t.name === "Bash" && DEPLOY.test((t.input?.command) || "")) { sig.push("Deploy/Commit"); break; }
345
+ for (const t of tools) {
346
+ if (["Write","Edit","MultiEdit"].includes(t.name)) {
347
+ const fp = (t.input?.file_path || "").toLowerCase();
348
+ if (fp && CODE_EXT.some((x) => fp.endsWith(x))) { sig.push("Code-/Config-Änderung"); break; }
349
+ }
350
+ }
351
+ if (RULE.test(utext)) sig.push("neue Regel/Standing Order");
352
+ if (ARCH.test(utext)) sig.push("Architektur-Entscheidung");
353
+ return [...new Set(sig)];
354
+ }
355
+
356
+ async function main() {
357
+ let raw = "";
358
+ process.stdin.setEncoding("utf-8");
359
+ for await (const c of process.stdin) raw += c;
360
+ let data = {};
361
+ try { data = raw ? JSON.parse(raw) : {}; } catch { return; }
362
+ if (data.stop_hook_active) return; // Loop-Schutz
363
+ const tp = data.transcript_path;
364
+ if (!tp) return;
365
+ let round;
366
+ try { round = collectRound(tp); } catch { return; }
367
+ if (hasStore(round.tools)) return; // schon gesichert
368
+ const sig = detect(round.utext, round.tools);
369
+ if (!sig.length) return; // nichts Sicherungswürdiges
370
+
371
+ const reason =
372
+ "STOP-GATE (knowmind): Diese Runde enthielt Sicherungswürdiges (" + sig.join(", ") + "), " +
373
+ "aber es wurde kein knowmind_store_memory aufgerufen.\\n" +
374
+ "Bevor du stoppst: lege das Ergebnis mit knowmind_store_memory ab (Titel + Inhalt) " +
375
+ "und verknüpfe es ggf. mit knowmind_link. Ist der Vorgang wirklich nicht " +
376
+ "sicherungswürdig (reine Recherche, Wegwerf-Test), begründe es in einem Satz, dann stoppe.";
377
+ process.stdout.write(JSON.stringify({ decision: "block", reason }));
378
+ }
379
+
380
+ main().catch(() => process.exit(0));
381
+ // <<< knowmind capture-gate hook
382
+ `;
383
+ }
384
+
385
+ // ─── Cursor-Rule (.mdc) ──────────────────────────────────────────────
386
+ function cursorRuleSource() {
387
+ return `---
388
+ description: knowmind — Memory-First-Regel (automatisches Langzeitgedächtnis)
389
+ alwaysApply: true
390
+ ---
391
+ ${BEGIN}
392
+ # knowmind — automatische Gedächtnis-Pflege
393
+
394
+ Dieses Projekt nutzt **knowmind** (Langzeitgedächtnis & Wissensgraph) als MCP-Server.
395
+
396
+ 1. **Recall zuerst.** Bevor du eine inhaltliche Frage beantwortest oder eine Aufgabe
397
+ planst, rufe \`knowmind_recall\` auf und prüfe, ob bereits relevantes Wissen vorliegt.
398
+ Erst danach Dateien lesen / Web suchen.
399
+ 2. **Wissen sichern.** Bringt eine Runde Sicherungswürdiges hervor (Entscheidung, neue
400
+ Regel, Ergebnis, Fakt über Personen/Projekte/Systeme), lege es mit
401
+ \`knowmind_store_memory\` ab, bevor du fortfährst.
402
+ 3. **Beziehungen pflegen.** Verknüpfe zusammengehörige Erinnerungen mit \`knowmind_link\`.
403
+
404
+ Das Gedächtnis lebt auf der knowmind-Plattform (Server in Deutschland), nicht in lokalen
405
+ Dateien — über Sessions und Clients hinweg dasselbe Gehirn.
406
+ ${END}
407
+ `;
408
+ }
409
+
410
+ // ─── Claude-settings.json: Hook-Registrierung (idempotent) ───────────
411
+
412
+ function ensureClaudeHookEntry(settings, eventName, scriptRel) {
413
+ // settings.hooks[eventName] ist ein Array von { matcher?, hooks: [{type,command}] }.
414
+ // Wir registrieren genau EINEN knowmind-Eintrag pro Event, marker-erkennbar am command.
415
+ const cmd = `node "${scriptRel}"`;
416
+ settings.hooks = settings.hooks || {};
417
+ const arr = settings.hooks[eventName] || [];
418
+ // Existierenden knowmind-Eintrag finden (command enthält den Skriptnamen).
419
+ const scriptName = scriptRel.split(/[\\/]/).pop();
420
+ let mutated = false;
421
+ let present = false;
422
+ for (const group of arr) {
423
+ for (const h of group.hooks || []) {
424
+ if (typeof h.command === "string" && h.command.includes(scriptName)) {
425
+ present = true;
426
+ if (h.command !== cmd) {
427
+ h.command = cmd;
428
+ mutated = true;
429
+ }
430
+ }
431
+ }
432
+ }
433
+ if (!present) {
434
+ arr.push({ hooks: [{ type: "command", command: cmd }] });
435
+ mutated = true;
436
+ }
437
+ settings.hooks[eventName] = arr;
438
+ return mutated;
439
+ }
440
+
441
+ // ─── Plan-Bauer pro Client ───────────────────────────────────────────
442
+ // Jeder Eintrag: { path, kind, render() -> {action, content?} oder Info }
443
+
444
+ function planClaudeCode(cwd) {
445
+ const actions = [];
446
+ const hooksDir = join(cwd, ".claude", "hooks");
447
+ const recallPath = join(hooksDir, "knowmind_recall.mjs");
448
+ const capturePath = join(hooksDir, "knowmind_capture.mjs");
449
+ const settingsPath = join(cwd, ".claude", "settings.json");
450
+ const claudeMdPath = join(cwd, "CLAUDE.md");
451
+
452
+ // 1) Recall-Hook
453
+ const recallSrc = autoRecallHookSource();
454
+ actions.push({
455
+ label: "Claude-Code Recall-Hook",
456
+ path: recallPath,
457
+ ...writeOwnFile(recallPath, recallSrc, ">>> knowmind auto-recall hook"),
458
+ content: recallSrc,
459
+ _own: true,
460
+ _exec: true,
461
+ });
462
+
463
+ // 2) Capture-Gate-Hook
464
+ const captureSrc = captureGateHookSource();
465
+ actions.push({
466
+ label: "Claude-Code Capture-Gate-Hook",
467
+ path: capturePath,
468
+ ...writeOwnFile(capturePath, captureSrc, ">>> knowmind capture-gate hook"),
469
+ content: captureSrc,
470
+ _own: true,
471
+ _exec: true,
472
+ });
473
+
474
+ // 3) settings.json — Hooks registrieren
475
+ let settings = {};
476
+ if (existsSync(settingsPath)) {
477
+ try {
478
+ settings = JSON.parse(readFileSync(settingsPath, "utf-8"));
479
+ } catch {
480
+ settings = { _parseError: true };
481
+ }
482
+ }
483
+ if (settings._parseError) {
484
+ actions.push({
485
+ label: "Claude-Code settings.json",
486
+ path: settingsPath,
487
+ action: "skip-foreign",
488
+ reason: "settings.json ist kein gültiges JSON — bitte Hooks manuell eintragen",
489
+ });
490
+ } else {
491
+ const relRecall = ".claude/hooks/knowmind_recall.mjs";
492
+ const relCapture = ".claude/hooks/knowmind_capture.mjs";
493
+ const m1 = ensureClaudeHookEntry(settings, "UserPromptSubmit", relRecall);
494
+ const m2 = ensureClaudeHookEntry(settings, "Stop", relCapture);
495
+ actions.push({
496
+ label: "Claude-Code settings.json (Hook-Registrierung)",
497
+ path: settingsPath,
498
+ action: m1 || m2 ? (existsSync(settingsPath) ? "patch" : "create") : "unchanged",
499
+ content: JSON.stringify(settings, null, 2) + "\n",
500
+ });
501
+ }
502
+
503
+ // 4) CLAUDE.md — Memory-First-Block
504
+ const md = upsertMarkedBlock(claudeMdPath, memoryFirstBlock());
505
+ actions.push({
506
+ label: "CLAUDE.md (Memory-First-Block)",
507
+ path: claudeMdPath,
508
+ action: md.action,
509
+ content: md.content,
510
+ });
511
+
512
+ return actions;
513
+ }
514
+
515
+ function planCursor(cwd) {
516
+ const rulePath = join(cwd, ".cursor", "rules", "knowmind.mdc");
517
+ const src = cursorRuleSource();
518
+ return [
519
+ {
520
+ label: "Cursor-Rule .cursor/rules/knowmind.mdc",
521
+ path: rulePath,
522
+ ...writeOwnFile(rulePath, src, BEGIN),
523
+ content: src,
524
+ _own: true,
525
+ },
526
+ ];
527
+ }
528
+
529
+ // ─── Ausführung ──────────────────────────────────────────────────────
530
+
531
+ function applyAction(a) {
532
+ if (!a.action || ["unchanged", "skip-foreign"].includes(a.action)) return;
533
+ if (a.content == null) return;
534
+ mkdirSync(dirname(a.path), { recursive: true });
535
+ writeFileSync(a.path, a.content, "utf-8");
536
+ if (a._exec && platform() !== "win32") {
537
+ try {
538
+ chmodSync(a.path, 0o755);
539
+ } catch {
540
+ /* best effort */
541
+ }
542
+ }
543
+ }
544
+
545
+ const ICON = {
546
+ create: "+",
547
+ replace: "~",
548
+ overwrite: "~",
549
+ patch: "~",
550
+ append: "~",
551
+ unchanged: "=",
552
+ "skip-foreign": "!",
553
+ };
554
+
555
+ /**
556
+ * Haupteinstieg. options: { client, dryRun, cwd, home }
557
+ */
558
+ export async function runInit({ client = "auto", dryRun = false, cwd = process.cwd(), home = homedir() } = {}) {
559
+ const cfg = loadConfig();
560
+ const lines = [];
561
+ lines.push(`knowmind init ${VERSION}${dryRun ? " (dry-run — es wird NICHTS geschrieben)" : ""}`);
562
+ lines.push(`Projekt: ${resolve(cwd)}`);
563
+ lines.push(`Plattform: ${cfg.apiUrl}${cfg.token ? " (Token konfiguriert)" : " (KEIN Token — `knowmind login` zuerst!)"}`);
564
+ lines.push("");
565
+
566
+ // Client wählen
567
+ let target = client;
568
+ if (client === "auto") {
569
+ const detected = detectClients(cwd, home);
570
+ if (detected.length === 0) {
571
+ target = "generic";
572
+ lines.push("Kein Client automatisch erkannt — generische Anleitung.");
573
+ } else if (detected.length === 1) {
574
+ target = detected[0];
575
+ lines.push(`Erkannter Client: ${target}`);
576
+ } else {
577
+ // Mehrere -> alle einrichten, klar ausweisen.
578
+ target = detected;
579
+ lines.push(`Erkannte Clients: ${detected.join(", ")} — alle werden eingerichtet.`);
580
+ }
581
+ } else {
582
+ lines.push(`Client (explizit): ${client}`);
583
+ }
584
+ lines.push("");
585
+
586
+ const targets = Array.isArray(target) ? target : [target];
587
+ const allActions = [];
588
+ for (const t of targets) {
589
+ if (t === "claude-code") allActions.push(...planClaudeCode(cwd));
590
+ else if (t === "cursor") allActions.push(...planCursor(cwd));
591
+ else {
592
+ // generic / claude-desktop / codex und alles ohne Hook-Mechanismus.
593
+ const heading =
594
+ t === "codex"
595
+ ? "Codex CLI:"
596
+ : t === "claude-desktop"
597
+ ? "Claude Desktop:"
598
+ : "Generischer Client:";
599
+ lines.push(heading);
600
+ lines.push(" Dieser Client kennt keinen Hook-Mechanismus, der die Pflege HART erzwingt.");
601
+ lines.push(" Es wirken automatisch: die MCP-instructions (werden beim Verbinden gelesen)");
602
+ lines.push(" und die MCP-prompts. Für eine zusätzliche, weiche Memory-First-Regel den");
603
+ lines.push(" folgenden Block in deine System-/Projekt-Anweisung (z. B. AGENTS.md, CLAUDE.md,");
604
+ lines.push(" Custom Instructions) einfügen:");
605
+ lines.push("");
606
+ lines.push(manualSnippet().split("\n").map((l) => " " + l).join("\n"));
607
+ lines.push("");
608
+ }
609
+ }
610
+
611
+ // Plan ausgeben + ggf. anwenden
612
+ if (allActions.length) {
613
+ lines.push("Aktionen:");
614
+ for (const a of allActions) {
615
+ const icon = ICON[a.action] || "?";
616
+ let note = "";
617
+ if (a.action === "skip-foreign") note = ` (übersprungen: ${a.reason})`;
618
+ if (a.action === "unchanged") note = " (bereits aktuell)";
619
+ lines.push(` [${icon}] ${a.label}`);
620
+ lines.push(` ${a.path}${note}`);
621
+ }
622
+ lines.push("");
623
+ if (!dryRun) {
624
+ for (const a of allActions) applyAction(a);
625
+ lines.push("Eingerichtet. Starte deinen KI-Client neu, damit Hooks/Regeln greifen.");
626
+ } else {
627
+ lines.push("Dry-Run: keine Datei wurde geändert. Ohne --dry-run erneut ausführen.");
628
+ }
629
+ }
630
+
631
+ return lines.join("\n");
632
+ }
633
+
634
+ // Für Tests exportiert.
635
+ export const _internals = {
636
+ upsertMarkedBlock,
637
+ writeOwnFile,
638
+ ensureClaudeHookEntry,
639
+ detectClients,
640
+ memoryFirstBlock,
641
+ BEGIN,
642
+ END,
643
+ };
package/src/mcp-stdio.js CHANGED
@@ -14,6 +14,11 @@
14
14
  * genau diese Abweichung (Punkt- vs. Unterstrich-Namen) hatte 0.1.17 unbrauchbar
15
15
  * gemacht, nachdem die Plattform auf das MCP-Namensschema umgestellt wurde.
16
16
  *
17
+ * Seit 0.1.20 wird auch `initialize` an den Server durchgereicht, damit die
18
+ * serverseitigen `instructions` (der client-übergreifende Pflege-Hebel) und die
19
+ * tatsächlichen serverInfo/capabilities den Client erreichen. Bei Server-
20
+ * Fehler/Offline fällt der Proxy auf einen lokalen Default zurück.
21
+ *
17
22
  * Protokoll: stdio mit zeilenweise JSON (NDJSON-Style). Jedes Frame ist ein
18
23
  * vollständiges JSON-RPC-Objekt.
19
24
  */
@@ -23,6 +28,19 @@ import { createInterface } from "node:readline";
23
28
  /** Methoden, die lokal beantwortet werden (alles andere geht an den Server). */
24
29
  const LOCAL_METHODS = new Set(["initialize", "ping"]);
25
30
 
31
+ /**
32
+ * Lokaler Fallback-result für `initialize`, falls der Server nicht erreichbar
33
+ * ist oder keine verwertbare Antwort liefert. Hält den Proxy offline-robust.
34
+ * Die serverInfo.version stammt aus der package.json (VERSION).
35
+ */
36
+ function localInitializeResult() {
37
+ return {
38
+ protocolVersion: "2025-06-18",
39
+ serverInfo: { name: "knowmind", version: VERSION },
40
+ capabilities: { tools: {}, prompts: {} },
41
+ };
42
+ }
43
+
26
44
  async function forwardToServer(method, params) {
27
45
  const { apiUrl, token } = loadConfig();
28
46
  if (!token)
@@ -171,16 +189,40 @@ export async function runStdioServer() {
171
189
  write({ jsonrpc: "2.0", id: req.id ?? null, result: {} });
172
190
  continue;
173
191
  }
174
- // initialize
175
- write({
176
- jsonrpc: "2.0",
177
- id: req.id ?? null,
178
- result: {
179
- protocolVersion: "2025-06-18",
180
- serverInfo: { name: "knowmind", version: VERSION },
181
- capabilities: { tools: {}, prompts: {} },
182
- },
183
- });
192
+ // initialize: An den Server durchreichen und serverInfo / instructions /
193
+ // capabilities aus der Server-Antwort übernehmen. Nur so erreichen die
194
+ // serverseitigen `instructions` (der automatische Pflege-Hebel) den
195
+ // MCP-Client. Bei Server-Fehler/Offline auf den lokalen Default
196
+ // zurückfallen — Proxy-Charakter und Offline-Robustheit bleiben.
197
+ let initResult = localInitializeResult();
198
+ try {
199
+ const upstreamInit = await forwardToServer("initialize", req.params);
200
+ const serverResult =
201
+ upstreamInit && typeof upstreamInit === "object" && "result" in upstreamInit
202
+ ? upstreamInit.result
203
+ : null;
204
+ if (serverResult && typeof serverResult === "object") {
205
+ initResult = {
206
+ // protocolVersion vom Server, sonst lokaler Default.
207
+ protocolVersion: serverResult.protocolVersion ?? initResult.protocolVersion,
208
+ // serverInfo vom Server (Name/Version aus zentraler Quelle), sonst lokal.
209
+ serverInfo: serverResult.serverInfo ?? initResult.serverInfo,
210
+ // capabilities vom Server, sonst lokal.
211
+ capabilities: serverResult.capabilities ?? initResult.capabilities,
212
+ // instructions NUR übernehmen, wenn der Server sie liefert.
213
+ ...(typeof serverResult.instructions === "string"
214
+ ? { instructions: serverResult.instructions }
215
+ : {}),
216
+ };
217
+ }
218
+ } catch (e) {
219
+ // Server nicht erreichbar o.Ä. → lokaler Default. Der Client soll trotzdem
220
+ // initialisieren können; Tool-Calls scheitern dann ohnehin mit klarer Meldung.
221
+ process.stderr.write(
222
+ `[knowmind] initialize-Forward fehlgeschlagen, lokaler Default: ${e instanceof Error ? e.message : String(e)}\n`,
223
+ );
224
+ }
225
+ write({ jsonrpc: "2.0", id: req.id ?? null, result: initResult });
184
226
  continue;
185
227
  }
186
228