knowmind 0.4.2 → 0.4.4

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,13 @@
1
1
  # Knowmind CLI — Änderungen
2
2
 
3
+ ## 0.4.4 (2026-10-16)
4
+
5
+ - Verbesserungen der Stabilität.
6
+
7
+ ## 0.4.3 (2026-10-16)
8
+
9
+ - Verbesserungen der Stabilität.
10
+
3
11
  ## 0.4.2 (2026-10-16)
4
12
 
5
13
  - Liegt ein Ordner im Open Knowledge Format mit Belegen unter `.claims/` in
package/README.de.md CHANGED
@@ -40,14 +40,15 @@ export KNOWMIND_API_URL=https://knowmind.de
40
40
  ## Befehle
41
41
 
42
42
  ```
43
- npx -y knowmind install <ide> MCP-Server im KI-Client verdrahten (claude, cursor, vscode …)
44
- knowmind init Automatische Gedächtnis-Pflege im KI-Client einrichten
43
+ npx -y knowmind install <ide> # MCP-Server im KI-Client eintragen (install list zeigt alle Clients)
44
+ knowmind init # automatische Gedächtnis-Pflege im KI-Client einrichten
45
45
  knowmind search "Wo läuft die OKR-App?"
46
46
  knowmind upload notizen.md --title "Meeting Notizen 2026-05-12"
47
+ knowmind sync ./openwiki # Ordner abgleichen, auch im Open Knowledge Format
47
48
  knowmind stats
48
49
  knowmind health
49
- knowmind status Lebenszeichen des Gedächtnisses (Report)
50
- knowmind status --line Einzeilige Statusline für Ihr KI-Werkzeug
50
+ knowmind status # Lebenszeichen des Gedächtnisses als Bericht
51
+ knowmind status --line # einzeilige Statusline für Ihr KI-Werkzeug
51
52
  knowmind config
52
53
  ```
53
54
 
@@ -58,40 +59,51 @@ automatisch ein (eine bereits vorhandene eigene Statusline bleibt unangetastet).
58
59
 
59
60
  ## Automatische Pflege einrichten (`knowmind init`)
60
61
 
61
- Damit Ihre KI knowmind selbsttätig pflegt — **Recall vor jeder Aufgabe**, **Sichern nach
62
- jeder sicherungswürdigen Runde** — richtet `knowmind init` die passenden Mechanismen für
63
- Ihren Client ein. Der Befehl erkennt den Client am Projekt- und Home-Verzeichnis
64
- (`.claude/`, `.cursor/`, `~/.codex/`) oder Sie wählen ihn explizit.
62
+ Damit Ihre KI knowmind selbsttätig pflegt — in Claude Code **Recall vor jeder Aufgabe** und
63
+ **Sichern nach jeder sicherungswürdigen Runde**, in Cursor und Codex als Regel für das Modell —
64
+ richtet `knowmind init` die passenden Mechanismen für
65
+ Ihren Client ein. Der Befehl erkennt den Client an `.claude/` im Projekt, `~/.claude.json` oder
66
+ `~/.claude` (Claude Code), an `.cursor/` im Projekt oder `~/.cursor` (Cursor) und an
67
+ `~/.codex/config.toml` (Codex), oder Sie wählen ihn explizit.
65
68
 
66
69
  ```
67
70
  knowmind init # Client automatisch erkennen
68
71
  knowmind init --client claude-code # gezielt für Claude Code
69
72
  knowmind init --client cursor # gezielt für Cursor
73
+ knowmind init --client codex # gezielt für Codex
70
74
  knowmind init --dry-run # zeigt nur, was geschähe (schreibt nichts)
71
75
  ```
72
76
 
73
77
  **Was eingerichtet wird:**
74
78
 
75
79
  - **Claude Code** — projektlokale Hooks in `.claude/`:
76
- - *UserPromptSubmit* → ruft vor jeder inhaltlichen Frage `knowmind_recall_memories` auf und reicht die
77
- Top-Treffer als Kontext nach (Memory-First, automatisch).
78
- - *Stop* → erinnert die KI daran, mit `knowmind_store_memory` zu sichern, wenn die Runde
79
- Sicherungswürdiges enthielt (Deploy/Commit, neue Regel, Entscheidung) und noch nichts
80
- gespeichert wurde.
80
+ - *UserPromptSubmit* → fragt vor jeder inhaltlichen Frage knowmind ab und reicht die
81
+ besten Treffer als Kontext nach (Memory-First, automatisch).
82
+ - *Stop* → hält das Ende der Runde an und fordert die KI auf, mit `knowmind_store_memory` zu
83
+ sichern, wenn die Runde Sicherungswürdiges enthielt und noch nichts gespeichert wurde. Als
84
+ sicherungswürdig gelten Deploy oder Commit, eine neue Regel, eine Architekturentscheidung und
85
+ geänderter Code oder geänderte Konfiguration.
81
86
  - ein **Memory-First-Block** in `./CLAUDE.md` (mit `<!-- BEGIN/END knowmind -->`-Markern).
82
87
  - **Cursor** — `.cursor/rules/knowmind.mdc` mit der Memory-First-Regel (`alwaysApply`).
83
- - **Claude Desktop / Codex / generisch** — kein automatischer Hook-Mechanismus vorhanden;
84
- der Befehl zeigt den Memory-First-Text zum manuellen Einfügen (siehe Grenze unten).
88
+ - **Codex** — ein Block in `AGENTS.md` (mit Markern wie bei `CLAUDE.md`): knowmind fragen, wenn
89
+ eine Aufgabe von Entscheidungen, Absprachen oder Wissen außerhalb des Codes abhängt; Quellcode
90
+ und Tests bleiben maßgeblich; was über die Sitzung hinaus gilt, mit `knowmind_store_memory`
91
+ festhalten.
92
+ - **Claude Desktop / generisch** — kein Hook-Mechanismus, der die Pflege erzwingt; es wirken die
93
+ MCP-instructions und die MCP-prompts, und der Befehl zeigt den Memory-First-Text zum manuellen
94
+ Einfügen (siehe Grenze unten).
85
95
 
86
96
  **Idempotent & nicht-destruktiv:** Ein zweiter Lauf erzeugt keine Duplikate
87
- (marker-/befehls-basierte Ersetzung); bestehende fremde Dateien und Hooks bleiben
88
- unangetastet. Mit `--dry-run` sehen Sie jede Aktion vorab.
97
+ (marker-/befehls-basierte Ersetzung). Vorhandene fremde Hooks ändert init nicht. Eine vorhandene
98
+ `CLAUDE.md` oder `AGENTS.md` bekommt den markierten Block angehängt, eine vorhandene
99
+ `.claude/settings.json` die Hooks und die Statusline dazu. Trägt eine Datei den Namen einer
100
+ knowmind-Datei, aber keinen Marker, wird sie übersprungen. Mit `--dry-run` sehen Sie jede Aktion vorab.
89
101
 
90
- > **Grenze der Automatik:** Eine *harte* Erzwingung der Pflege gibt es nur in Clients mit
91
- > Hook-/Rule-Mechanismus (Claude Code, Cursor). In Clients ohne solchen Mechanismus
92
- > (z. B. Claude Desktop, Codex CLI) greifen die **MCP-instructions** (werden beim
93
- > Verbinden gelesen) und die **MCP-prompts** — eine modellabhängige Steuerung ohne
94
- > technische Garantie.
102
+ > **Grenze der Automatik:** Eine *harte* Erzwingung der Pflege gibt es nur in Claude Code,
103
+ > dessen Hooks unabhängig vom Modell laufen. Die Regeldatei in Cursor und der Block in
104
+ > `AGENTS.md` für Codex sind Anweisungen an das Modell, ebenso in allen übrigen Clients die
105
+ > **MCP-instructions** (werden beim Verbinden gelesen) und die **MCP-prompts** — eine
106
+ > modellabhängige Steuerung ohne technische Garantie.
95
107
 
96
108
  ## MCP-Server einrichten
97
109
 
@@ -103,7 +115,7 @@ knowmind ist ein MCP-Server (`npx -y knowmind mcp`, stdio). Token aus dem knowmi
103
115
  claude mcp add knowmind --env KNOWMIND_TOKEN=kmt_xxx --env KNOWMIND_API_URL=https://knowmind.de -- npx -y knowmind mcp
104
116
  ```
105
117
 
106
- **Claude Desktop / Cursor / Windsurf / Cline / Continue / Goose / Zed** (`claude_desktop_config.json`, `~/.cursor/mcp.json`, …)
118
+ **Claude Desktop / Cursor / Windsurf / Gemini CLI** (`claude_desktop_config.json`, `~/.cursor/mcp.json`, …; Zed erwartet denselben Eintrag unter `context_servers`)
107
119
  ```json
108
120
  {
109
121
  "mcpServers": {
@@ -115,17 +127,23 @@ claude mcp add knowmind --env KNOWMIND_TOKEN=kmt_xxx --env KNOWMIND_API_URL=http
115
127
  }
116
128
  }
117
129
  ```
118
- > Windows-Hinweis: falls `npx` nicht direkt startet, `"command": "cmd"`, `"args": ["/c", "npx", "-y", "knowmind", "mcp"]`.
130
+ > Windows-Hinweis: Besser `npx -y knowmind install <ide>`. Liegt `pythonw.exe` von Python 3.10 bis
131
+ > 3.14 am üblichen Ort (`%LOCALAPPDATA%\Programs\Python\Python3…` oder `C:\Python3…`), starten die
132
+ > eingetragenen Server ohne Konsolenfenster; Codex und der ausgegebene Befehl für Claude Code
133
+ > nutzen `npx` direkt. Wer von Hand einträgt und `npx` nicht direkt startet,
134
+ > nimmt `"command": "cmd"`, `"args": ["/c", "npx", "-y", "knowmind", "mcp"]`; Clients ohne eigene
135
+ > Konsole öffnen dann bei jedem Werkzeugaufruf ein Fenster.
119
136
 
120
137
  **VS Code / GitHub Copilot** (`.vscode/mcp.json` — Top-Level `servers` + `inputs`)
121
138
  ```json
122
139
  {
123
- "inputs": [{ "id": "knowmind_token", "type": "promptString", "description": "Knowmind API token", "password": true }],
140
+ "inputs": [{ "type": "promptString", "id": "knowmind-token", "description": "KNOWMIND_TOKEN", "password": true }],
124
141
  "servers": {
125
142
  "knowmind": {
143
+ "type": "stdio",
126
144
  "command": "npx",
127
145
  "args": ["-y", "knowmind", "mcp"],
128
- "env": { "KNOWMIND_TOKEN": "${input:knowmind_token}", "KNOWMIND_API_URL": "https://knowmind.de" }
146
+ "env": { "KNOWMIND_TOKEN": "${input:knowmind-token}", "KNOWMIND_API_URL": "https://knowmind.de" }
129
147
  }
130
148
  }
131
149
  }
@@ -167,6 +185,8 @@ identisch mit dem Remote-Connector (`https://knowmind.de/api/mcp/v1`).
167
185
  - `knowmind_get_health` — Verfügbarkeits-Status der Plattform
168
186
  - `knowmind_upsert_entity` — Knoten für eine Sache anlegen (Person, Firma, Anwendung, Rechner, Technik) oder den vorhandenen zurückgeben
169
187
  - `knowmind_get_schema` — Welche Entitätsklassen und Beziehungstypen dieser Arbeitsbereich kennt
188
+ - `knowmind_list_inferred` — Beziehungen, die auf eine Entscheidung warten (aus Text erschlossen oder von einem Dokument ausgehend), mit Prüfstand, Herkunft und Beleg
189
+ - `knowmind_review_inferred` — Entscheidung zu einer solchen Beziehung festhalten: bestätigen, verwerfen (`valid_to` wird gesetzt, nichts gelöscht) oder Verwerfen zurücknehmen
170
190
 
171
191
  Inverse-Beziehungen (z. B. `IS_EMPLOYEE_OF` zu `HAS_EMPLOYEE`) werden
172
192
  serverseitig automatisch mit angelegt. Hinweis: `knowmind upload` als
@@ -206,11 +226,11 @@ ein Drittlandtransfer stattfinden, für den Sie als Verantwortlicher zuständig
206
226
 
207
227
  ## Haftung & Nutzung (Disclaimer)
208
228
 
209
- - **Software:** Dieses Paket steht unter der **Apache-Lizenz 2.0** und wird „AS IS" ohne jegliche
229
+ - **Software:** Dieses Paket steht unter der **Apache-Lizenz 2.0** und wird „AS IS“ ohne jegliche
210
230
  Gewährleistung bereitgestellt; die Haftung ist im Rahmen der Lizenz (Abschnitte 7 und 8)
211
231
  ausgeschlossen bzw. beschränkt. Siehe `LICENSE`.
212
232
  - **Eigenes Konto, eigener Token:** knowmind bündelt keine Zugangsdaten. Sie nutzen Ihren eigenen
213
- knowmind.de-Account und API-Token. Anlegen: https://knowmind.de/dashboard/api-tokens
233
+ knowmind.de-Account und API-Token. Anlegen: https://knowmind.de/dashboard/tokens
214
234
  - **Eigene Kosten/Verbrauch:** Jede Nutzung (API-Anfragen, Token-/Kontingentverbrauch, ggf.
215
235
  modellbezogene Kosten) erfolgt über Ihren eigenen Account und auf Ihre Verantwortung. Verbrauch
216
236
  und Kosten sind im knowmind.de-Dashboard transparent einsehbar.
package/README.md CHANGED
@@ -25,7 +25,7 @@ npx -y knowmind login --token kmt_xxxxxxxx
25
25
  claude mcp add knowmind --env KNOWMIND_TOKEN=kmt_xxx -- npx -y knowmind mcp
26
26
  ```
27
27
 
28
- **Cursor** (`~/.cursor/mcp.json`) — also works for Claude Desktop, Windsurf, Cline, Continue, Goose, and Zed with their respective config files:
28
+ **Cursor** (`~/.cursor/mcp.json`) — the same `mcpServers` block works for Claude Desktop, Windsurf and Gemini CLI in their config files; Zed expects it under `context_servers`:
29
29
  ```json
30
30
  {
31
31
  "mcpServers": {
@@ -38,9 +38,13 @@ claude mcp add knowmind --env KNOWMIND_TOKEN=kmt_xxx -- npx -y knowmind mcp
38
38
  }
39
39
  ```
40
40
 
41
- **Any other MCP client**: knowmind is a standard MCP server over stdio (`npx -y knowmind mcp`). On Windows, if `npx` does not start directly, use `"command": "cmd"`, `"args": ["/c", "npx", "-y", "knowmind", "mcp"]`.
41
+ **Any other MCP client**: knowmind is a standard MCP server over stdio (`npx -y knowmind mcp`). On Windows, `npx -y knowmind install <ide>` is the better way: if `pythonw.exe` from Python 3.10 to 3.14 sits in its default location (`%LOCALAPPDATA%\Programs\Python\Python3…` or `C:\Python3…`), the entries it writes start the server without a console window; Codex and the printed Claude Code command use `npx` directly. If you configure by hand and `npx` does not start directly, use `"command": "cmd"`, `"args": ["/c", "npx", "-y", "knowmind", "mcp"]`; clients without a console of their own then open a window with each tool call.
42
42
 
43
- `npx -y knowmind install <ide>` writes this configuration for you (e.g. `claude`, `cursor`, `vscode`), and `npx -y knowmind init` sets up automatic memory hygiene — recall before each task, store after each meaningful change — for clients with a hook or rule mechanism (Claude Code, Cursor).
43
+ `npx -y knowmind install <ide>` writes this configuration for you, for example `cursor`, `vscode`, `windsurf`, `zed`, `claude-desktop`, `gemini` or `codex`; `npx -y knowmind install list` shows all clients. For Claude Code it prints the `claude mcp add` command instead, and `--project` writes `.mcp.json` in the current folder.
44
+
45
+ Clients that cannot read the token from the environment get a placeholder to replace with your token. Running `install` again updates only the knowmind entry and keeps a token you entered; before it changes a file, it saves a copy next to it.
46
+
47
+ `npx -y knowmind init` sets up memory hygiene in your client: hooks in Claude Code that recall before each task and, when a turn contained something worth keeping (a deploy or commit, a new rule, an architecture decision, changed code or configuration) and nothing was stored yet, ask the model to store it before the turn ends, a rule file in Cursor, and a block in `AGENTS.md` that tells Codex when to ask knowmind and what to keep.
44
48
 
45
49
  ## How knowmind stores facts
46
50
 
@@ -107,7 +111,7 @@ sync as a bundle.
107
111
 
108
112
  ## Available Tools
109
113
 
110
- Thirteen tools over MCP. Every one works against your own workspace; the server
114
+ Fifteen tools over MCP. Every one works against your own workspace; the server
111
115
  never sees another tenant's data.
112
116
 
113
117
  ### Reading
@@ -148,6 +152,15 @@ accepts. No parameters.
148
152
  *Usage:* call it before `knowmind_upsert_entity` or `knowmind_link_entities` to use a type the
149
153
  server will accept, rather than inventing one.
150
154
 
155
+ **`knowmind_list_inferred`** — Relations that wait for a human decision: relations knowmind
156
+ inferred from a text, and relations that start from a document although their type needs a
157
+ person, organisation or similar. Each comes with its review state, both connected entries, its
158
+ source and the entry that supports it.
159
+ `status` (`open`, `confirmed` or `rejected`, optional) · `limit` (integer, default 50, max 200) ·
160
+ `offset` (integer, default 0)
161
+ *Usage:* review what the graph learned on its own. Open relations do not feed the derivation
162
+ rules until someone confirms them.
163
+
151
164
  **`knowmind_get_stats`** — Size of the corpus: documents, chunks, entities, edges.
152
165
  No parameters.
153
166
 
@@ -201,6 +214,15 @@ created for you.
201
214
  `from_id`, `to_id`, `rel_type` (all required)
202
215
  *Usage:* an edge created in error. The entries themselves stay.
203
216
 
217
+ **`knowmind_review_inferred`** — Record a decision on one relation from
218
+ `knowmind_list_inferred`. `confirm` lets it feed the derivation rules; `reject` ends the
219
+ relation, its reverse and every relation derived from it (`valid_to` is set, nothing is
220
+ deleted); `undo` takes a rejection back.
221
+ `edge_id` (string, required) · `decision` (`confirm`, `reject` or `undo`, required) ·
222
+ `evidence` (string, optional — id of the entry that supports the decision)
223
+ *Usage:* after reviewing the list. Returns the state before and after and how many reverse and
224
+ derived relations were affected.
225
+
204
226
  ### On deleting
205
227
 
206
228
  There is no delete tool, and that is deliberate. Facts are superseded
package/bin/knowmind.js CHANGED
@@ -76,7 +76,7 @@ Befehle:
76
76
  bei Aktivität, rot bei Ausfall) — für die Statusline
77
77
  eines KI-Werkzeugs, z. B. Claude Code.
78
78
  knowmind mcp Stdio-MCP-Server für lokale AI-Clients
79
- knowmind install <ide> [--project] [--print] [--token T] [--api URL]
79
+ knowmind install <ide> [--project] [--print] [--dry-run] [--token T] [--api URL]
80
80
  knowmind als MCP-Server in eine IDE eintragen
81
81
  (cursor, vscode, windsurf, antigravity, zed, jetbrains, gemini,
82
82
  codex, claude-code, claude-desktop, all). 'install list' zeigt alle.
@@ -0,0 +1,24 @@
1
+ # -*- coding: utf-8 -*-
2
+ """Übergang: Starter am alten Ort bin/, der Starter selbst liegt unter src/.
3
+
4
+ WARUM (16.10.2026): Am 13.10.2026 fiel der knowmind-MCP-Server in einer
5
+ Claude-Code-Einrichtung aus („Connection closed“). Ihr Eintrag zeigte auf
6
+ `node_modules/knowmind/bin/mcp-starter.py`. Diese Datei war von Hand dorthin
7
+ kopiert worden; kein veröffentlichtes Paket hat sie je enthalten (geprüft an
8
+ allen 33 Fassungen auf npm, 0.1.9 bis 0.4.2). Beim Update ersetzt npm das ganze
9
+ Paketverzeichnis, und die Kopie war weg.
10
+
11
+ Diese Datei hält den alten Pfad am Leben, ohne dass jemand eine
12
+ Konfigurationsdatei anfassen muss. Sie führt `src/mcp-starter.py` aus, mit
13
+ denselben Argumenten und demselben Rückgabewert. Sie bleibt im Paket, solange
14
+ ein Eintrag auf sie zeigen kann; `src/starterpfad.test.js` hält das fest.
15
+ """
16
+ import os
17
+ import runpy
18
+ import sys
19
+
20
+ ZIEL = os.path.join(os.path.dirname(os.path.abspath(__file__)), os.pardir, "src", "mcp-starter.py")
21
+
22
+ if __name__ == "__main__":
23
+ sys.argv[0] = ZIEL
24
+ runpy.run_path(ZIEL, run_name="__main__")
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "knowmind",
3
- "version": "0.4.2",
3
+ "version": "0.4.4",
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",
package/src/install.js CHANGED
@@ -11,11 +11,19 @@
11
11
  // (`${env:KNOWMIND_TOKEN}` / `${input:…}` / `${KNOWMIND_TOKEN}`); wo nicht, steht
12
12
  // ein Platzhalter mit Warnung. Nur mit ausdrücklichem `--token <wert>` wird ein
13
13
  // literaler Wert geschrieben (dann mit Klartext-Warnung).
14
+ //
15
+ // Erneuter Aufruf (seit 0.4.4): install ersetzt nur den eigenen Eintrag und
16
+ // lässt jedes andere Byte der Datei stehen (src/konfig-text.js). Ein Token, das
17
+ // der Nutzer schon eingetragen hat, bleibt ohne --token erhalten, ebenso eigene
18
+ // Umgebungsvariablen, eigene Felder und eigene Argumente nach `mcp`. Ändert sich
19
+ // die Datei, liegt vorher eine Sicherung daneben. Ändert sich nichts, wird
20
+ // nichts geschrieben.
14
21
 
15
- import { mkdirSync, readFileSync, writeFileSync, existsSync } from "node:fs";
22
+ import { copyFileSync, existsSync, readFileSync, writeFileSync, mkdirSync } from "node:fs";
16
23
  import { homedir, platform } from "node:os";
17
24
  import { dirname, join } from "node:path";
18
- import { fileURLToPath } from "node:url";
25
+ import { jsonEintragSetzen, tomlEintragSetzen } from "./konfig-text.js";
26
+ import { starterAblegen, starterOrt } from "./starter.js";
19
27
 
20
28
  const DEFAULT_API = "https://knowmind.de";
21
29
  const NPX = "npx";
@@ -37,7 +45,7 @@ function appData(...p) {
37
45
  }
38
46
 
39
47
  // ── IDE-Registry ──────────────────────────────────────────────────────────
40
- // family: "mcpServers" | "servers" | "context_servers" | "command"
48
+ // family: "mcpServers" | "servers" | "context_servers" | "toml"
41
49
  // secret: "env" | "input" | "shell" | "literal-only" (Default-Referenzstil)
42
50
  const IDES = {
43
51
  cursor: {
@@ -137,41 +145,57 @@ function tokenRef(secretStyle, literalToken) {
137
145
  * 10.08.2026: „Viele werden es deshalb deinstallieren." — und er hat recht.
138
146
  *
139
147
  * Deshalb dazwischen `pythonw.exe` (GUI-Programm, öffnet selbst kein Fenster),
140
- * das npx mit CREATE_NO_WINDOW startet und die Datenströme durchreicht. Ohne
141
- * Python auf dem Rechner bleibt es beim direkten npx-Aufruf — eine ehrliche
142
- * Grenze ist besser als eine halbe Lösung.
148
+ * das npx in einer versteckten Konsole startet und die Datenströme durchreicht.
149
+ * Ohne Python auf dem Rechner bleibt es beim direkten npx-Aufruf — eine
150
+ * ehrliche Grenze ist besser als eine halbe Lösung.
151
+ *
152
+ * Der Starter liegt seit 0.4.4 unter ~/.knowmind/ (src/starter.js), nicht mehr
153
+ * im Paketverzeichnis: Das liegt nach `npx -y knowmind install` im
154
+ * npx-Zwischenspeicher und verschwindet, wenn der geleert wird.
155
+ *
156
+ * `umgebung` (nur für Prüffälle): plattform, pythonw (Pfad oder null), heim.
143
157
  */
144
- function startBefehl() {
145
- const pythonw = findePythonwFuerMcp();
146
- if (!pythonw) return { command: NPX, args: NPX_ARGS };
147
- const starter = join(dirname(fileURLToPath(import.meta.url)), "mcp-starter.py");
148
- return { command: pythonw, args: [starter, NPX, ...NPX_ARGS] };
158
+ function startBefehl(umgebung = {}) {
159
+ const pythonw = "pythonw" in umgebung ? umgebung.pythonw : findePythonwFuerMcp(umgebung.plattform);
160
+ if (!pythonw) return { command: NPX, args: [...NPX_ARGS], starter: false };
161
+ return { command: pythonw, args: [starterOrt(umgebung.heim), NPX, ...NPX_ARGS], starter: true };
149
162
  }
150
163
 
151
164
  /** Vollständiger Pfad zu pythonw.exe, oder null. */
152
- function findePythonwFuerMcp() {
153
- if (platform() !== "win32") return null;
165
+ function findePythonwFuerMcp(plattform = platform()) {
166
+ if (plattform !== "win32") return null;
154
167
  const kandidaten = [];
155
168
  const lokal = process.env.LOCALAPPDATA;
156
- for (const v of ["313", "312", "311", "310"]) {
169
+ for (const v of ["314", "313", "312", "311", "310"]) {
157
170
  if (lokal) kandidaten.push(join(lokal, "Programs", "Python", `Python${v}`, "pythonw.exe"));
158
171
  kandidaten.push(join("C:\\", `Python${v}`, "pythonw.exe"));
159
172
  }
160
173
  return kandidaten.find((p) => existsSync(p)) ?? null;
161
174
  }
162
175
 
163
- // Server-Eintrag im Schema der Familie.
164
- function serverEntry(ide, { apiUrl, literalToken }) {
165
- const env = {
166
- KNOWMIND_TOKEN: tokenRef(ide.secret, literalToken),
167
- KNOWMIND_API_URL: apiUrl,
168
- };
169
- const { command, args } = startBefehl();
170
- if (ide.family === "servers") {
171
- // VS Code verlangt einen Transport-Typ.
172
- return { type: "stdio", command, args, env };
173
- }
174
- return { command, args, env };
176
+ /** Argumente, die der Nutzer hinter `mcp` angehängt hat. */
177
+ function eigeneArgumente(alt) {
178
+ const args = Array.isArray(alt?.args) ? alt.args : [];
179
+ const stelle = args.lastIndexOf("mcp");
180
+ return stelle >= 0 ? args.slice(stelle + 1) : [];
181
+ }
182
+
183
+ // Server-Eintrag im Schema der Familie. `alt` ist der bisherige Eintrag (oder
184
+ // null): eigene Felder, Umgebungsvariablen, ein eingetragenes Token und eigene
185
+ // Argumente nach `mcp` bleiben erhalten.
186
+ function serverEntry(ide, { apiUrl, apiGegeben, literalToken, umgebung }, alt = null) {
187
+ // Nur ein lokaler Eintrag (mit command) wird fortgeschrieben. Ein Eintrag
188
+ // anderer Art unter dem Namen knowmind (etwa url für einen Fernzugang) wird
189
+ // ganz ersetzt, sonst entstünde eine Mischung, die kein Client versteht.
190
+ const lokal = alt && typeof alt === "object" && typeof alt.command === "string" ? alt : null;
191
+ const altEnv = lokal && typeof lokal.env === "object" && lokal.env ? lokal.env : {};
192
+ const env = { ...altEnv };
193
+ if (literalToken || !("KNOWMIND_TOKEN" in env)) env.KNOWMIND_TOKEN = tokenRef(ide.secret, literalToken);
194
+ if (apiGegeben || !("KNOWMIND_API_URL" in env)) env.KNOWMIND_API_URL = apiUrl;
195
+ const { command, args } = startBefehl(umgebung);
196
+ const eintrag = { ...(lokal || {}), command, args: [...args, ...eigeneArgumente(lokal)], env };
197
+ if (ide.family === "servers") return { type: "stdio", ...eintrag };
198
+ return eintrag;
175
199
  }
176
200
 
177
201
  // Vollständiges Snippet (für --print / GUI-IDEs).
@@ -187,10 +211,7 @@ function snippet(ide, opts) {
187
211
  }
188
212
 
189
213
  // ── TOML (Codex CLI) ────────────────────────────────────────────────────────
190
- // Codex liest ~/.codex/config.toml. Es gibt keinen TOML-Parser als Abhängigkeit
191
- // und es soll keiner dazukommen — der knowmind-Block wird zeilenbasiert ersetzt:
192
- // Abschnittskopf [mcp_servers.knowmind] (und Unterabschnitte) samt Folgezeilen
193
- // bis zum nächsten Abschnittskopf entfernen, dann den frischen Block anhängen.
214
+ // Codex läuft im Terminal und hat eine Konsole: npx direkt, ohne Starter.
194
215
  function tomlBlock(opts) {
195
216
  const token = tokenRef("literal-only", opts.literalToken);
196
217
  return [
@@ -205,45 +226,52 @@ function tomlBlock(opts) {
205
226
  }
206
227
 
207
228
  function mergeToml(text, opts) {
208
- // Erst Zeilenenden vereinheitlichen: `.` matcht kein \r, mit CRLF-Dateien
209
- // bräche die Abschnitts-Entfernung sonst mitten im Block ab (Test 04.08.).
210
- const quelltext = (text || "").replace(/\r\n/g, "\n");
211
- // Kopfzeile + alle Folgezeilen, die keinen neuen Abschnitt beginnen.
212
- const alt = /(^|\n)\[mcp_servers\.knowmind(\.[^\]]+)?\](?:\n(?!\[).*)*/g;
213
- let neu = quelltext.replace(alt, "$1");
214
- neu = neu.replace(/\n{3,}/g, "\n\n").trimEnd();
215
- return (neu ? neu + "\n\n" : "") + tomlBlock(opts) + "\n";
229
+ const token = tokenRef("literal-only", opts.literalToken);
230
+ const env = {};
231
+ const envFallsFehlt = {};
232
+ (opts.literalToken ? env : envFallsFehlt).KNOWMIND_TOKEN = token;
233
+ (opts.apiGegeben ? env : envFallsFehlt).KNOWMIND_API_URL = opts.apiUrl;
234
+ return tomlEintragSetzen(text, { command: NPX, args: NPX_ARGS, env, envFallsFehlt });
216
235
  }
217
236
 
218
- function readJsonSafe(path) {
219
- if (!existsSync(path)) return {};
220
- try {
221
- return JSON.parse(readFileSync(path, "utf-8"));
222
- } catch {
223
- return null; // signalisiert: vorhandene Datei ist kaputt → nicht blind überschreiben
224
- }
237
+ // Setzt den knowmind-Eintrag in den JSON-Text, ohne den Rest anzufassen.
238
+ function mergeInto(text, ide, opts) {
239
+ const fach = ide.family === "servers" ? "servers" : ide.family;
240
+ const zusatzListe = ide.family === "servers"
241
+ ? {
242
+ fach: "inputs",
243
+ element: { type: "promptString", id: "knowmind-token", description: "KNOWMIND_TOKEN", password: true },
244
+ gleich: (i) => i && i.id === "knowmind-token",
245
+ }
246
+ : undefined;
247
+ return jsonEintragSetzen(text, fach, "knowmind", (alt) => serverEntry(ide, opts, alt), { zusatzListe }).text;
225
248
  }
226
249
 
227
- function writeJson(path, obj) {
228
- mkdirSync(dirname(path), { recursive: true });
229
- writeFileSync(path, JSON.stringify(obj, null, 2) + "\n", "utf-8");
250
+ function stempel(d = new Date()) {
251
+ const z = (n) => String(n).padStart(2, "0");
252
+ return `${d.getFullYear()}${z(d.getMonth() + 1)}${z(d.getDate())}-${z(d.getHours())}${z(d.getMinutes())}${z(d.getSeconds())}`;
230
253
  }
231
254
 
232
- // Merged knowmind in eine bestehende Config, ohne Fremd-Server zu verlieren.
233
- function mergeInto(existing, ide, opts) {
234
- const cfg = existing && typeof existing === "object" ? { ...existing } : {};
235
- const entry = serverEntry(ide, opts);
236
- if (ide.family === "servers") {
237
- cfg.servers = { ...(cfg.servers || {}), knowmind: entry };
238
- const inputs = Array.isArray(cfg.inputs) ? cfg.inputs.slice() : [];
239
- if (!inputs.some((i) => i && i.id === "knowmind-token")) {
240
- inputs.push({ type: "promptString", id: "knowmind-token", description: "KNOWMIND_TOKEN", password: true });
241
- }
242
- cfg.inputs = inputs;
243
- } else {
244
- cfg[ide.family] = { ...(cfg[ide.family] || {}), knowmind: entry };
255
+ /**
256
+ * Schreibt `neu` nach `path`, wenn es sich vom Bestand unterscheidet. Vorher
257
+ * liegt eine Sicherung daneben. Rückgabe: "neu", "geändert" oder "unverändert".
258
+ */
259
+ function schreibenMitSicherung(path, alt, neu) {
260
+ if (alt === neu) return { ergebnis: "unverändert" };
261
+ mkdirSync(dirname(path), { recursive: true });
262
+ let sicherung = null;
263
+ if (alt !== null) {
264
+ sicherung = `${path}.knowmind-sicherung-${stempel()}`;
265
+ copyFileSync(path, sicherung);
245
266
  }
246
- return cfg;
267
+ writeFileSync(path, neu, "utf-8");
268
+ return { ergebnis: alt === null ? "neu" : "geändert", sicherung };
269
+ }
270
+
271
+ function meldung(ide, path, { ergebnis, sicherung }) {
272
+ if (ergebnis === "unverändert") return `✓ ${ide.label}: Eintrag in ${path} ist aktuell, nichts geschrieben`;
273
+ if (ergebnis === "neu") return `✓ ${ide.label}: knowmind eingetragen in ${path}`;
274
+ return `✓ ${ide.label}: knowmind-Eintrag in ${path} aktualisiert (Sicherung: ${sicherung})`;
247
275
  }
248
276
 
249
277
  function printClaudeCodeCommand(opts) {
@@ -258,7 +286,12 @@ function printClaudeCodeCommand(opts) {
258
286
  console.log("Für ein einzelnes Projekt stattdessen: knowmind install claude-code --project\n");
259
287
  }
260
288
 
289
+ // Für die Prüffälle (src/starterpfad.test.js, src/install.test.js): Sie decken
290
+ // jeden Client ab, den diese Liste kennt, auch einen, der später dazukommt.
291
+ export const _internals = { IDES, serverEntry, mergeInto, mergeToml, startBefehl, findePythonwFuerMcp };
292
+
261
293
  // ── Hauptbefehl ─────────────────────────────────────────────────────────────
294
+ // `cwd` und `umgebung` nur für Prüffälle.
262
295
  export function runInstall(opts) {
263
296
  const { ideKey, project, dryRun, printOnly, apiUrl, literalToken } = opts;
264
297
 
@@ -279,8 +312,15 @@ export function runInstall(opts) {
279
312
  console.warn("WARNUNG: --token schreibt das Token im KLARTEXT in die Config-Datei(en).\n");
280
313
  }
281
314
 
282
- const cwd = process.cwd();
283
- const entryOpts = { apiUrl: apiUrl || DEFAULT_API, literalToken };
315
+ const cwd = opts.cwd || process.cwd();
316
+ const entryOpts = { apiUrl: apiUrl || DEFAULT_API, apiGegeben: Boolean(apiUrl), literalToken, umgebung: opts.umgebung };
317
+ let starterBereit = false;
318
+ const starterSicherstellen = () => {
319
+ if (starterBereit || dryRun || !startBefehl(opts.umgebung).starter) return;
320
+ const ergebnis = starterAblegen({ ziel: starterOrt(opts.umgebung?.heim) });
321
+ if (ergebnis !== "aktuell") console.log(`✓ Starter ${ergebnis}: ${starterOrt(opts.umgebung?.heim)}`);
322
+ starterBereit = true;
323
+ };
284
324
 
285
325
  for (const key of targets) {
286
326
  const ide = IDES[key];
@@ -291,8 +331,13 @@ export function runInstall(opts) {
291
331
  printClaudeCodeCommand(entryOpts);
292
332
  continue;
293
333
  }
334
+ if (!printOnly && ide.family !== "toml") starterSicherstellen();
294
335
  console.log(`# ${ide.label} — Snippet (manuell einfügen):`);
295
336
  console.log(ide.family === "toml" ? tomlBlock(entryOpts) : JSON.stringify(snippet(ide, entryOpts), null, 2));
337
+ if (printOnly && ide.family !== "toml" && startBefehl(opts.umgebung).starter && !existsSync(starterOrt(opts.umgebung?.heim))) {
338
+ console.log(`# Der Eintrag startet über ${starterOrt(opts.umgebung?.heim)}; die Datei fehlt noch.`);
339
+ console.log(`# \`knowmind install ${key}\` ohne --print legt sie ab.`);
340
+ }
296
341
  console.log("");
297
342
  continue;
298
343
  }
@@ -305,17 +350,22 @@ export function runInstall(opts) {
305
350
  console.log(tomlBlock(entryOpts));
306
351
  continue;
307
352
  }
308
- const alterText = existsSync(tomlPath) ? readFileSync(tomlPath, "utf-8") : "";
309
- const neuerText = mergeToml(alterText, entryOpts);
353
+ const alterText = existsSync(tomlPath) ? readFileSync(tomlPath, "utf-8") : null;
354
+ let neuerText;
355
+ try {
356
+ neuerText = mergeToml(alterText ?? "", entryOpts);
357
+ } catch (fehler) {
358
+ console.error(`! ${ide.label}: ${tomlPath} — ${fehler.message}. Übersprungen, nichts geschrieben.`);
359
+ continue;
360
+ }
310
361
  if (dryRun) {
311
362
  console.log(`# ${ide.label} — DRY RUN → ${tomlPath}`);
312
363
  console.log(neuerText);
313
364
  continue;
314
365
  }
315
- mkdirSync(dirname(tomlPath), { recursive: true });
316
- writeFileSync(tomlPath, neuerText, "utf-8");
317
- console.log(`✓ ${ide.label}: knowmind eingetragen in ${tomlPath}`);
318
- if (!literalToken) {
366
+ const ergebnis = schreibenMitSicherung(tomlPath, alterText, neuerText);
367
+ console.log(meldung(ide, tomlPath, ergebnis));
368
+ if (!literalToken && ergebnis.ergebnis === "neu") {
319
369
  console.log(` → Platzhalter gesetzt: KNOWMIND_TOKEN in ${tomlPath} durch dein Token ersetzen.`);
320
370
  }
321
371
  continue;
@@ -324,33 +374,38 @@ export function runInstall(opts) {
324
374
  const path = project ? (ide.projectPath && ide.projectPath(cwd)) : (ide.globalPath && ide.globalPath());
325
375
  if (!path) {
326
376
  // Kein Datei-Ziel für diesen Scope → Snippet zeigen.
377
+ starterSicherstellen();
327
378
  console.log(`# ${ide.label}: kein ${project ? "Projekt" : "globaler"}-Dateipfad bekannt — Snippet:`);
328
379
  console.log(JSON.stringify(snippet(ide, entryOpts), null, 2));
329
380
  console.log("");
330
381
  continue;
331
382
  }
332
383
 
333
- const existing = readJsonSafe(path);
334
- if (existing === null) {
335
- console.error(`! ${ide.label}: ${path} ist kein gültiges JSON — übersprungen (nicht überschrieben).`);
384
+ const alterText = existsSync(path) ? readFileSync(path, "utf-8") : null;
385
+ let neuerText;
386
+ try {
387
+ neuerText = mergeInto(alterText ?? "", ide, entryOpts);
388
+ } catch (fehler) {
389
+ console.error(`! ${ide.label}: ${path} ist nicht lesbar (${fehler.message}) — übersprungen, nicht überschrieben.`);
336
390
  continue;
337
391
  }
338
- const merged = mergeInto(existing, ide, entryOpts);
339
392
 
340
393
  if (dryRun) {
341
394
  console.log(`# ${ide.label} — DRY RUN → ${path}`);
342
- console.log(JSON.stringify(merged, null, 2));
395
+ console.log(neuerText);
343
396
  console.log("");
344
397
  continue;
345
398
  }
346
399
 
347
- writeJson(path, merged);
348
- console.log(`✓ ${ide.label}: knowmind eingetragen in ${path}`);
400
+ starterSicherstellen();
401
+ const ergebnis = schreibenMitSicherung(path, alterText, neuerText);
402
+ console.log(meldung(ide, path, ergebnis));
403
+ if (ergebnis.ergebnis === "unverändert") continue;
349
404
  if (literalToken) {
350
405
  console.log(` → ${ide.label} neu starten — fertig.`);
351
406
  } else if (ide.secret === "env") {
352
407
  console.log(` → setze KNOWMIND_TOKEN in deiner Umgebung (oder nutze --token).`);
353
- } else if (ide.secret === "literal-only" && !literalToken) {
408
+ } else if (ide.secret === "literal-only" && ergebnis.ergebnis === "neu") {
354
409
  console.log(` → Platzhalter gesetzt: KNOWMIND_TOKEN in ${path} durch dein Token ersetzen.`);
355
410
  } else if (ide.secret === "shell") {
356
411
  console.log(` → ${path} nutzt \${KNOWMIND_TOKEN} aus der Umgebung (git-sicher).`);
@@ -0,0 +1,286 @@
1
+ // Gezieltes Umschreiben des knowmind-Eintrags in Konfigurationsdateien der
2
+ // KI-Clients, ohne den Rest der Datei anzufassen.
3
+ //
4
+ // WARUM (16.10.2026): install las die Datei mit JSON.parse und schrieb sie mit
5
+ // JSON.stringify zurück. Damit änderten sich Einrückung, Zeilenenden und
6
+ // Schreibweise aller fremden Einträge, und eine Datei mit Kommentaren (VS Code,
7
+ // Zed) wurde gar nicht erst gelesen. Hier wird nur der Textbereich des eigenen
8
+ // Eintrags ersetzt oder eingefügt; jedes andere Byte bleibt, wie es war.
9
+ //
10
+ // Gelesen wird JSON mit Kommentaren und Komma vor der schließenden Klammer
11
+ // (JSONC), wie VS Code und Zed es schreiben.
12
+
13
+ /** Liest JSONC und liefert einen Baum mit Textpositionen. Wirft bei Fehlern. */
14
+ export function jsoncLesen(text) {
15
+ let i = 0;
16
+ const fehler = (was) => {
17
+ throw new Error(`${was} an Stelle ${i}`);
18
+ };
19
+ const leer = () => {
20
+ for (;;) {
21
+ while (i < text.length && /\s/.test(text[i])) i++;
22
+ if (text.startsWith("//", i)) {
23
+ while (i < text.length && text[i] !== "\n") i++;
24
+ } else if (text.startsWith("/*", i)) {
25
+ const e = text.indexOf("*/", i + 2);
26
+ if (e < 0) fehler("Kommentar ohne Ende");
27
+ i = e + 2;
28
+ } else return;
29
+ }
30
+ };
31
+ const zeichenkette = () => {
32
+ if (text[i] !== '"') fehler("Zeichenkette erwartet");
33
+ const start = i++;
34
+ while (i < text.length && text[i] !== '"') i += text[i] === "\\" ? 2 : 1;
35
+ if (i >= text.length) fehler("Zeichenkette ohne Ende");
36
+ i++;
37
+ return JSON.parse(text.slice(start, i));
38
+ };
39
+ const wert = () => {
40
+ leer();
41
+ const start = i;
42
+ const c = text[i];
43
+ if (c === "{") {
44
+ i++;
45
+ const glieder = [];
46
+ for (;;) {
47
+ leer();
48
+ if (text[i] === "}") break;
49
+ const nameStart = i;
50
+ const name = zeichenkette();
51
+ leer();
52
+ if (text[i] !== ":") fehler("Doppelpunkt erwartet");
53
+ i++;
54
+ const w = wert();
55
+ glieder.push({ name, nameStart, wert: w });
56
+ leer();
57
+ if (text[i] === ",") {
58
+ i++;
59
+ continue;
60
+ }
61
+ if (text[i] !== "}") fehler("Komma oder } erwartet");
62
+ }
63
+ i++;
64
+ return { art: "objekt", start, ende: i, glieder };
65
+ }
66
+ if (c === "[") {
67
+ i++;
68
+ const elemente = [];
69
+ for (;;) {
70
+ leer();
71
+ if (text[i] === "]") break;
72
+ elemente.push(wert());
73
+ leer();
74
+ if (text[i] === ",") {
75
+ i++;
76
+ continue;
77
+ }
78
+ if (text[i] !== "]") fehler("Komma oder ] erwartet");
79
+ }
80
+ i++;
81
+ return { art: "liste", start, ende: i, elemente };
82
+ }
83
+ if (c === '"') {
84
+ zeichenkette();
85
+ return { art: "wert", start, ende: i };
86
+ }
87
+ const m = /^(?:-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?|true|false|null)/.exec(text.slice(i));
88
+ if (!m) fehler("Wert erwartet");
89
+ i += m[0].length;
90
+ return { art: "wert", start, ende: i };
91
+ };
92
+ const wurzel = wert();
93
+ leer();
94
+ if (i !== text.length) fehler("Text nach dem Ende");
95
+ return wurzel;
96
+ }
97
+
98
+ /** Wert eines Knotens als JavaScript-Wert (Kommentare entfernt). */
99
+ export function knotenWert(text, knoten) {
100
+ if (knoten.art === "objekt") {
101
+ return Object.fromEntries(knoten.glieder.map((g) => [g.name, knotenWert(text, g.wert)]));
102
+ }
103
+ if (knoten.art === "liste") return knoten.elemente.map((e) => knotenWert(text, e));
104
+ return JSON.parse(text.slice(knoten.start, knoten.ende));
105
+ }
106
+
107
+ const zeilenende = (text) => (text.includes("\r\n") ? "\r\n" : "\n");
108
+
109
+ function einzugVor(text, pos) {
110
+ const zeilenStart = text.lastIndexOf("\n", pos - 1) + 1;
111
+ const m = /^[ \t]*/.exec(text.slice(zeilenStart, pos));
112
+ return m ? m[0] : "";
113
+ }
114
+
115
+ function schreibweise(wert, basis, eol) {
116
+ return JSON.stringify(wert, null, 2).split("\n").join(eol + basis);
117
+ }
118
+
119
+ /** Fügt `"name": wert` als letztes Glied in ein Objekt ein. */
120
+ function gliedHinzu(text, objekt, name, wert, eol) {
121
+ const basis = einzugVor(text, objekt.start);
122
+ if (objekt.glieder.length === 0) {
123
+ const innen = basis + " ";
124
+ const neu = `{${eol}${innen}${JSON.stringify(name)}: ${schreibweise(wert, innen, eol)}${eol}${basis}}`;
125
+ return text.slice(0, objekt.start) + neu + text.slice(objekt.ende);
126
+ }
127
+ const letztes = objekt.glieder[objekt.glieder.length - 1];
128
+ const innen = einzugVor(text, letztes.nameStart);
129
+ const einschub = `,${eol}${innen}${JSON.stringify(name)}: ${schreibweise(wert, innen, eol)}`;
130
+ return text.slice(0, letztes.wert.ende) + einschub + text.slice(letztes.wert.ende);
131
+ }
132
+
133
+ /** Hängt ein Element an eine Liste an. */
134
+ function elementHinzu(text, liste, wert, eol) {
135
+ const basis = einzugVor(text, liste.start);
136
+ if (liste.elemente.length === 0) {
137
+ const innen = basis + " ";
138
+ return text.slice(0, liste.start) + `[${eol}${innen}${schreibweise(wert, innen, eol)}${eol}${basis}]` + text.slice(liste.ende);
139
+ }
140
+ const letztes = liste.elemente[liste.elemente.length - 1];
141
+ const innen = einzugVor(text, letztes.start);
142
+ return text.slice(0, letztes.ende) + `,${eol}${innen}${schreibweise(wert, innen, eol)}` + text.slice(letztes.ende);
143
+ }
144
+
145
+ /**
146
+ * Setzt `wurzel[fach][name] = bauen(alt)` im Text. Nur der Bereich des
147
+ * Eintrags ändert sich. `alt` im Ergebnis ist der bisherige Wert oder null.
148
+ * `zusatzListe` hängt bei Bedarf ein Element an eine Liste der Wurzel an
149
+ * (VS Code: inputs).
150
+ */
151
+ export function jsonEintragSetzen(text, fach, name, bauen, { zusatzListe } = {}) {
152
+ if (!text || !text.trim()) {
153
+ const neu = { [fach]: { [name]: bauen(null) } };
154
+ if (zusatzListe) neu[zusatzListe.fach] = [zusatzListe.element];
155
+ return { text: JSON.stringify(neu, null, 2) + "\n", alt: null };
156
+ }
157
+ const eol = zeilenende(text);
158
+ let wurzel = jsoncLesen(text);
159
+ if (wurzel.art !== "objekt") throw new Error("Die Datei ist kein JSON-Objekt");
160
+ let alt = null;
161
+ const fachKnoten = wurzel.glieder.find((g) => g.name === fach);
162
+ if (!fachKnoten) {
163
+ text = gliedHinzu(text, wurzel, fach, { [name]: bauen(null) }, eol);
164
+ } else {
165
+ if (fachKnoten.wert.art !== "objekt") throw new Error(`"${fach}" ist kein Objekt`);
166
+ const treffer = fachKnoten.wert.glieder.filter((g) => g.name === name);
167
+ if (treffer.length > 1) throw new Error(`"${name}" steht mehrfach in "${fach}"`);
168
+ if (treffer.length === 1) {
169
+ const e = treffer[0];
170
+ alt = knotenWert(text, e.wert);
171
+ const neu = schreibweise(bauen(alt), einzugVor(text, e.nameStart), eol);
172
+ text = text.slice(0, e.wert.start) + neu + text.slice(e.wert.ende);
173
+ } else {
174
+ text = gliedHinzu(text, fachKnoten.wert, name, bauen(null), eol);
175
+ }
176
+ }
177
+ if (zusatzListe) {
178
+ wurzel = jsoncLesen(text);
179
+ const listenKnoten = wurzel.glieder.find((g) => g.name === zusatzListe.fach);
180
+ if (!listenKnoten) {
181
+ text = gliedHinzu(text, wurzel, zusatzListe.fach, [zusatzListe.element], eol);
182
+ } else if (listenKnoten.wert.art === "liste") {
183
+ const da = knotenWert(text, listenKnoten.wert);
184
+ if (!da.some(zusatzListe.gleich)) text = elementHinzu(text, listenKnoten.wert, zusatzListe.element, eol);
185
+ }
186
+ }
187
+ jsoncLesen(text); // das Ergebnis muss lesbar bleiben
188
+ return { text, alt };
189
+ }
190
+
191
+ // ── TOML (Codex) ────────────────────────────────────────────────────────────
192
+ // Kein TOML-Parser als Abhängigkeit. Die Datei wird in Abschnitte zerlegt
193
+ // (Kopfzeile bis zur nächsten Kopfzeile); Abschnitte, die nicht zu knowmind
194
+ // gehören, bleiben Byte für Byte erhalten.
195
+
196
+ const KOPF = /^[ \t]*\[\[?[^\]\n]*\]\]?[ \t]*(?:#.*)?$/;
197
+ const EIGENER_KOPF = /^[ \t]*\[[ \t]*mcp_servers\.knowmind(?:\.([^\]\s]+))?[ \t]*\][ \t]*(?:#.*)?$/;
198
+
199
+ function abschnitte(text) {
200
+ const zeilen = text.split(/(?<=\n)/);
201
+ const teile = [{ kopf: null, zeilen: [] }];
202
+ for (const z of zeilen) {
203
+ const ohneEnde = z.replace(/\r?\n$/, "");
204
+ if (KOPF.test(ohneEnde)) teile.push({ kopf: ohneEnde, zeilen: [z] });
205
+ else teile[teile.length - 1].zeilen.push(z);
206
+ }
207
+ return teile;
208
+ }
209
+
210
+ const tomlString = (s) => JSON.stringify(s);
211
+
212
+ /**
213
+ * Setzt command, args und die eigenen env-Schlüssel des knowmind-Eintrags in
214
+ * einer Codex-config.toml. Weitere Zeilen und Unterabschnitte des Eintrags und
215
+ * alle fremden Abschnitte bleiben stehen. `env` wird gesetzt, `envFallsFehlt`
216
+ * kommt nur dazu, wo der Schlüssel noch fehlt.
217
+ */
218
+ export function tomlEintragSetzen(text, { command, args, env = {}, envFallsFehlt = {} }) {
219
+ text = text || "";
220
+ if (/^[ \t]*mcp_servers\.knowmind[ \t]*=/m.test(text) ||
221
+ abschnitte(text).some((t) => /^\[[ \t]*mcp_servers[ \t]*\]/.test(t.kopf || "") &&
222
+ t.zeilen.some((z) => /^[ \t]*knowmind[ \t]*=/.test(z)))) {
223
+ throw new Error("knowmind steht dort in Kurzform (knowmind = { … }); bitte von Hand umstellen");
224
+ }
225
+ const eol = text ? zeilenende(text) : "\n";
226
+ const teile = abschnitte(text);
227
+ const eigene = teile.filter((t) => t.kopf && EIGENER_KOPF.test(t.kopf));
228
+ const haupt = eigene.find((t) => !EIGENER_KOPF.exec(t.kopf)[1]);
229
+ const envTeil = eigene.find((t) => EIGENER_KOPF.exec(t.kopf)[1] === "env");
230
+ const zeileFuer = (k, v) => `${k} = ${v}${eol}`;
231
+ const befehl = zeileFuer("command", tomlString(command));
232
+ const argumente = zeileFuer("args", `[${args.map(tomlString).join(", ")}]`);
233
+ const alleEnv = { ...envFallsFehlt, ...env };
234
+
235
+ if (!haupt) {
236
+ const envZeilen = Object.entries(alleEnv).map(([k, v]) => zeileFuer(k, tomlString(v))).join("");
237
+ const block = `[mcp_servers.knowmind]${eol}${befehl}${argumente}${eol}[mcp_servers.knowmind.env]${eol}${envZeilen}`;
238
+ const trenner = !text ? "" : text.endsWith(eol + eol) ? "" : text.endsWith("\n") ? eol : eol + eol;
239
+ return text + trenner + block;
240
+ }
241
+
242
+ // Hauptabschnitt: command und args ersetzen, alles andere stehen lassen.
243
+ const rest = haupt.zeilen.slice(1).filter((z) => !/^[ \t]*(command|args)[ \t]*=/.test(z));
244
+ haupt.zeilen = [haupt.zeilen[0], befehl, argumente, ...rest];
245
+
246
+ if (envTeil) {
247
+ const da = new Set();
248
+ envTeil.zeilen = envTeil.zeilen.map((z, n) => {
249
+ if (n === 0) return z;
250
+ const m = /^([ \t]*)([A-Za-z0-9_]+)([ \t]*=[ \t]*)(.*?)(\r?\n)?$/.exec(z);
251
+ if (!m) return z;
252
+ da.add(m[2]);
253
+ return m[2] in env ? `${m[1]}${m[2]}${m[3]}${tomlString(env[m[2]])}${m[5] ?? eol}` : z;
254
+ });
255
+ const neu = Object.entries(alleEnv).filter(([k]) => !da.has(k));
256
+ if (neu.length) {
257
+ let ende = envTeil.zeilen.length;
258
+ while (ende > 1 && !envTeil.zeilen[ende - 1].trim()) ende--;
259
+ envTeil.zeilen.splice(ende, 0, ...neu.map(([k, v]) => zeileFuer(k, tomlString(v))));
260
+ }
261
+ } else if (Object.keys(alleEnv).length) {
262
+ const kopf = "[mcp_servers.knowmind.env]";
263
+ teile.splice(teile.indexOf(haupt) + 1, 0, {
264
+ kopf, zeilen: [kopf + eol, ...Object.entries(alleEnv).map(([k, v]) => zeileFuer(k, tomlString(v)))],
265
+ });
266
+ }
267
+ return teile.map((t) => t.zeilen.join("")).join("");
268
+ }
269
+
270
+ /** Liest command, args und env des knowmind-Eintrags aus einer config.toml. */
271
+ export function tomlEintragLesen(text) {
272
+ const teile = abschnitte(text || "");
273
+ const haupt = teile.find((t) => t.kopf && EIGENER_KOPF.test(t.kopf) && !EIGENER_KOPF.exec(t.kopf)[1]);
274
+ if (!haupt) return null;
275
+ const envTeil = teile.find((t) => t.kopf && EIGENER_KOPF.exec(t.kopf)?.[1] === "env");
276
+ const wert = (k) => {
277
+ const z = haupt.zeilen.find((x) => new RegExp(`^[ \\t]*${k}[ \\t]*=`).test(x));
278
+ return z ? JSON.parse(z.slice(z.indexOf("=") + 1).trim()) : undefined;
279
+ };
280
+ const env = {};
281
+ for (const z of envTeil?.zeilen.slice(1) ?? []) {
282
+ const m = /^[ \t]*([A-Za-z0-9_]+)[ \t]*=[ \t]*(".*")/.exec(z);
283
+ if (m) env[m[1]] = JSON.parse(m[2]);
284
+ }
285
+ return { command: wert("command"), args: wert("args"), env };
286
+ }
@@ -34,6 +34,10 @@ import subprocess
34
34
  import sys
35
35
  import threading
36
36
 
37
+ # Stand dieses Starters. Bei jeder Änderung an dieser Datei um eins erhöhen:
38
+ # install legt eine Kopie unter ~/.knowmind/ ab (src/starter.js), und nur ein
39
+ # höherer Stand ersetzt sie. src/starterpfad.test.js hält Stand und Inhalt fest.
40
+ STARTER_STAND = 3
37
41
 
38
42
 
39
43
  def pumpe(quelle, ziel) -> None:
@@ -98,7 +102,7 @@ def main() -> int:
98
102
  **_ohne_fenster(),
99
103
  )
100
104
  except FileNotFoundError:
101
- sys.stderr.write(f"node nicht gefunden: {node}\n")
105
+ sys.stderr.write(f"knowmind: Befehl nicht gefunden: {befehl[0]}\n")
102
106
  return 127
103
107
 
104
108
  faeden = [
package/src/mcp-stdio.js CHANGED
@@ -33,6 +33,7 @@
33
33
  */
34
34
  import { readFileSync } from "node:fs";
35
35
  import { loadConfig, VERSION } from "./config.js";
36
+ import { starterAblegen } from "./starter.js";
36
37
  import { createInterface } from "node:readline";
37
38
 
38
39
  /** Methoden, die lokal beantwortet werden (alles andere geht an den Server). */
@@ -192,6 +193,15 @@ function fallbackStand() {
192
193
  }
193
194
 
194
195
  export async function runStdioServer() {
196
+ // Der Starter unter ~/.knowmind/ (src/starter.js) bekommt den Stand dieser
197
+ // Fassung, falls er älter ist. Nur eine vorhandene Datei, nur nach oben, und
198
+ // ein Fehler hier hält den Server nicht auf.
199
+ try {
200
+ starterAblegen({ nurWennDa: true });
201
+ } catch {
202
+ // ohne Schreibrecht im Benutzerverzeichnis bleibt der alte Starter
203
+ }
204
+
195
205
  // Kein Token konfiguriert → Discovery-Modus: initialize/tools/list laufen
196
206
  // über die öffentliche Server-Discovery, tools/call verlangt Login.
197
207
  let discoveryMode = false;
package/src/starter.js ADDED
@@ -0,0 +1,58 @@
1
+ // Der MCP-Starter für Windows an einem festen Ort im Benutzerverzeichnis.
2
+ //
3
+ // WARUM (16.10.2026, CRM 4b33e6fe): install schrieb den Pfad des Starters
4
+ // dorthin, wo das Kommandozeilenwerkzeug gerade lief. Wer nach README
5
+ // `npx -y knowmind install <ide>` aufruft, bekommt einen Pfad in den
6
+ // npx-Zwischenspeicher (%LOCALAPPDATA%\npm-cache\_npx\…). Leert er den, gibt es
7
+ // die Datei nicht mehr, und der MCP-Server startet ohne Meldung nicht.
8
+ //
9
+ // Deshalb liegt der Starter in ~/.knowmind/mcp-starter.py. install legt ihn
10
+ // dort ab und trägt diesen Pfad ein. Der Starter ruft `npx -y knowmind mcp`
11
+ // auf; ist der Zwischenspeicher leer, holt npx das Paket neu.
12
+ //
13
+ // Den Starter gibt es wegen des Konsolenfensters (src/mcp-starter.py, Johann
14
+ // am 10.08.2026: „Viele werden es deshalb deinstallieren.“). Er bleibt also
15
+ // pythonw.exe plus Starter, nur an einem Ort, der nicht verschwindet.
16
+ //
17
+ // Auffrischen: Jede Fassung trägt `STARTER_STAND = <n>` im Starter. install und
18
+ // der Start des MCP-Servers ersetzen die abgelegte Datei, wenn die mitgelieferte
19
+ // einen höheren Stand hat. Eine ältere Fassung überschreibt nie eine neuere.
20
+
21
+ import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
22
+ import { homedir } from "node:os";
23
+ import { dirname, join } from "node:path";
24
+ import { fileURLToPath } from "node:url";
25
+
26
+ export const MITGELIEFERT = join(dirname(fileURLToPath(import.meta.url)), "mcp-starter.py");
27
+
28
+ export function starterOrt(heim = homedir()) {
29
+ return join(heim, ".knowmind", "mcp-starter.py");
30
+ }
31
+
32
+ export function starterStand(text) {
33
+ const m = /^STARTER_STAND = (\d+)/m.exec(text || "");
34
+ return m ? Number(m[1]) : 0;
35
+ }
36
+
37
+ /**
38
+ * Legt den Starter ab oder frischt ihn auf. `nurWennDa`: nichts anlegen, nur
39
+ * eine vorhandene Datei auffrischen (Start des MCP-Servers).
40
+ * Rückgabe: "angelegt", "aufgefrischt", "aktuell" oder "fehlt".
41
+ */
42
+ export function starterAblegen({ ziel = starterOrt(), nurWennDa = false, quelle = MITGELIEFERT } = {}) {
43
+ const neu = readFileSync(quelle, "utf-8");
44
+ if (existsSync(ziel)) {
45
+ const alt = readFileSync(ziel, "utf-8");
46
+ if (alt === neu || starterStand(alt) >= starterStand(neu)) return "aktuell";
47
+ } else if (nurWennDa) {
48
+ return "fehlt";
49
+ }
50
+ const da = existsSync(ziel);
51
+ mkdirSync(dirname(ziel), { recursive: true });
52
+ // Erst daneben schreiben, dann umbenennen: Ein Client, der in diesem Moment
53
+ // startet, liest die alte oder die neue Datei, nie eine halbe.
54
+ const zwischen = `${ziel}.${process.pid}.neu`;
55
+ writeFileSync(zwischen, neu, "utf-8");
56
+ renameSync(zwischen, ziel);
57
+ return da ? "aufgefrischt" : "angelegt";
58
+ }