knowmind 0.3.2 → 0.3.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/package.json +61 -61
- package/src/init.js +831 -702
package/src/init.js
CHANGED
|
@@ -1,702 +1,831 @@
|
|
|
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, writeFileSync, mkdirSync, readdirSync, statSync, unlinkSync } from "node:fs";
|
|
158
|
-
import { homedir } from "node:os";
|
|
159
|
-
import { join } from "node:path";
|
|
160
|
-
|
|
161
|
-
// Stempelt den Aktivitäts-Zeitpunkt für die knowmind-Statusline (grüne
|
|
162
|
-
// HDD-LED). Best-effort, darf den Recall nie brechen.
|
|
163
|
-
function markActivity() {
|
|
164
|
-
try {
|
|
165
|
-
mkdirSync(join(homedir(), ".knowmind"), { recursive: true });
|
|
166
|
-
writeFileSync(join(homedir(), ".knowmind", "activity"), String(Date.now()));
|
|
167
|
-
} catch {}
|
|
168
|
-
}
|
|
169
|
-
|
|
170
|
-
// Zählt pro Claude-Code-Session die abgerufenen Erinnerungen. Die Statusline
|
|
171
|
-
// zeigt „N abgerufen" für die laufende Sitzung. Best-effort.
|
|
172
|
-
function bumpSessionRecalls(sessionId, hits) {
|
|
173
|
-
if (!sessionId || !(hits > 0)) return;
|
|
174
|
-
try {
|
|
175
|
-
const d = join(homedir(), ".knowmind", "sessions");
|
|
176
|
-
mkdirSync(d, { recursive: true });
|
|
177
|
-
const now = Date.now();
|
|
178
|
-
for (const fn of readdirSync(d)) {
|
|
179
|
-
try {
|
|
180
|
-
if (now - statSync(join(d, fn)).mtimeMs > 86400000) unlinkSync(join(d, fn));
|
|
181
|
-
} catch {}
|
|
182
|
-
}
|
|
183
|
-
const safe = String(sessionId).replace(/[^a-zA-Z0-9_-]/g, "").slice(0, 80);
|
|
184
|
-
const p = join(d, safe + ".json");
|
|
185
|
-
let cur = {};
|
|
186
|
-
try { cur = JSON.parse(readFileSync(p, "utf-8")); } catch {}
|
|
187
|
-
cur.recalls = (cur.recalls || 0) + 1;
|
|
188
|
-
cur.memories = (cur.memories || 0) + hits;
|
|
189
|
-
cur.updated = now;
|
|
190
|
-
writeFileSync(p, JSON.stringify(cur));
|
|
191
|
-
} catch {}
|
|
192
|
-
}
|
|
193
|
-
|
|
194
|
-
const TRIVIAL = new Set([
|
|
195
|
-
"ok","okay","go","ja","nein","weiter","stop","danke","thanks","thx",
|
|
196
|
-
"yes","no","yep","nope","perfekt","passt","super","gut",
|
|
197
|
-
]);
|
|
198
|
-
const TRIGGER = [
|
|
199
|
-
"kunde","kunden","projekt","tool","server","domain","wer ist","was ist",
|
|
200
|
-
"welche","liste","übersicht","status","wo ","wann","wieso","warum",
|
|
201
|
-
"recherche","research","info zu","infos zu","memory","graph","datenbank",
|
|
202
|
-
];
|
|
203
|
-
|
|
204
|
-
function shouldRecall(p) {
|
|
205
|
-
const s = (p || "").trim().toLowerCase();
|
|
206
|
-
if (s.length < 8) return false;
|
|
207
|
-
if (TRIVIAL.has(s)) return false;
|
|
208
|
-
if (s.startsWith("/")) return false;
|
|
209
|
-
if (TRIGGER.some((k) => s.includes(k))) return true;
|
|
210
|
-
if (s.endsWith("?")) return true;
|
|
211
|
-
return s.length >= 40;
|
|
212
|
-
}
|
|
213
|
-
|
|
214
|
-
// Token + apiUrl: ENV hat Vorrang, sonst ~/.knowmind/config.json (gleiche
|
|
215
|
-
// Reihenfolge wie die CLI). Kein Token -> kein Recall (fail-open).
|
|
216
|
-
function loadCreds() {
|
|
217
|
-
let file = {};
|
|
218
|
-
try {
|
|
219
|
-
file = JSON.parse(readFileSync(join(homedir(), ".knowmind", "config.json"), "utf-8"));
|
|
220
|
-
} catch { /* keine/kaputte Config -> ENV/Default */ }
|
|
221
|
-
let apiUrl = process.env.KNOWMIND_API_URL || file.apiUrl || "https://knowmind.de";
|
|
222
|
-
if (apiUrl.endsWith("/")) apiUrl = apiUrl.slice(0, -1);
|
|
223
|
-
return { apiUrl, token: process.env.KNOWMIND_TOKEN || file.token || null };
|
|
224
|
-
}
|
|
225
|
-
|
|
226
|
-
// Antwort von /api/mcp/v1 ist Standard-SSE (data:-Frames) ODER plain JSON.
|
|
227
|
-
// Beides robust auf das JSON-RPC-Objekt mit result/error reduzieren.
|
|
228
|
-
function parseBody(raw) {
|
|
229
|
-
raw = (raw || "").trim();
|
|
230
|
-
if (!raw) return null;
|
|
231
|
-
if (raw.startsWith("{")) { try { return JSON.parse(raw); } catch { return null; } }
|
|
232
|
-
let found = null;
|
|
233
|
-
for (const lineRaw of raw.split("\\n")) {
|
|
234
|
-
const line = lineRaw.trim();
|
|
235
|
-
if (line.indexOf("data:") !== 0) continue;
|
|
236
|
-
try {
|
|
237
|
-
const obj = JSON.parse(line.slice(5).trim());
|
|
238
|
-
if (obj && (obj.result || obj.error)) found = obj;
|
|
239
|
-
} catch { /* nicht-JSON data-Zeile überspringen */ }
|
|
240
|
-
}
|
|
241
|
-
return found;
|
|
242
|
-
}
|
|
243
|
-
|
|
244
|
-
// knowmind_recall liefert result.content[].text = JSON-String mit hits[].
|
|
245
|
-
// Lesbar verdichten; bei Parse-Fehler den Rohtext durchreichen.
|
|
246
|
-
function formatHits(rpc) {
|
|
247
|
-
const c = rpc && rpc.result && rpc.result.content;
|
|
248
|
-
const text = Array.isArray(c)
|
|
249
|
-
? c.filter((b) => b && b.type === "text" && b.text).map((b) => b.text).join("\\n").trim()
|
|
250
|
-
: "";
|
|
251
|
-
if (!text) return "";
|
|
252
|
-
try {
|
|
253
|
-
const o = JSON.parse(text);
|
|
254
|
-
if (Array.isArray(o.hits)) {
|
|
255
|
-
if (o.hits.length === 0) return "";
|
|
256
|
-
return o.hits.slice(0, 5).map((h, i) => {
|
|
257
|
-
const m = h.metadata || {};
|
|
258
|
-
const title = m.title || m.name || h.source || ("Treffer " + (i + 1));
|
|
259
|
-
const score = typeof h.score === "number" ? " (" + h.score.toFixed(2) + ")" : "";
|
|
260
|
-
const snip = String(h.content || "").replace(/\\s+/g, " ").trim().slice(0, 280);
|
|
261
|
-
return "• " + title + score + ": " + snip;
|
|
262
|
-
}).join("\\n");
|
|
263
|
-
}
|
|
264
|
-
} catch { /* kein hits-JSON -> Rohtext */ }
|
|
265
|
-
return text;
|
|
266
|
-
}
|
|
267
|
-
|
|
268
|
-
async function main() {
|
|
269
|
-
let raw = "";
|
|
270
|
-
process.stdin.setEncoding("utf-8");
|
|
271
|
-
for await (const c of process.stdin) raw += c;
|
|
272
|
-
let prompt = "";
|
|
273
|
-
let sessionId = "";
|
|
274
|
-
try {
|
|
275
|
-
const data = raw ? JSON.parse(raw) : {};
|
|
276
|
-
prompt = data.prompt || data.user_prompt || data.user_message || "";
|
|
277
|
-
sessionId = data.session_id || data.sessionId || "";
|
|
278
|
-
} catch { return; }
|
|
279
|
-
if (!shouldRecall(prompt)) return;
|
|
280
|
-
|
|
281
|
-
const { apiUrl, token } = loadCreds();
|
|
282
|
-
if (!token) return;
|
|
283
|
-
markActivity();
|
|
284
|
-
const query = prompt.trim().slice(0, 500);
|
|
285
|
-
|
|
286
|
-
const ctrl = new AbortController();
|
|
287
|
-
const timer = setTimeout(() => ctrl.abort(), 6000);
|
|
288
|
-
let rpc = null;
|
|
289
|
-
try {
|
|
290
|
-
const res = await fetch(apiUrl + "/api/mcp/v1", {
|
|
291
|
-
method: "POST",
|
|
292
|
-
headers: {
|
|
293
|
-
"Authorization": "Bearer " + token,
|
|
294
|
-
"Content-Type": "application/json",
|
|
295
|
-
"Accept": "application/json, text/event-stream",
|
|
296
|
-
},
|
|
297
|
-
body: JSON.stringify({
|
|
298
|
-
jsonrpc: "2.0", id: 1, method: "tools/call",
|
|
299
|
-
params: { name: "knowmind_recall", arguments: { query, k: 5, hops: 2 } },
|
|
300
|
-
}),
|
|
301
|
-
signal: ctrl.signal,
|
|
302
|
-
});
|
|
303
|
-
rpc = parseBody(await res.text());
|
|
304
|
-
} catch { return; } finally { clearTimeout(timer); }
|
|
305
|
-
|
|
306
|
-
const hits = formatHits(rpc);
|
|
307
|
-
if (!hits) return;
|
|
308
|
-
bumpSessionRecalls(sessionId, (hits.match(/^• /gm) || []).length);
|
|
309
|
-
|
|
310
|
-
process.stdout.write(
|
|
311
|
-
"═════════ knowmind RECALL (auto) ═════════\\n" +
|
|
312
|
-
hits + "\\n" +
|
|
313
|
-
"Diese Treffer wurden automatisch vor deiner Antwort abgerufen.\\n" +
|
|
314
|
-
"Erst hier prüfen, dann Dateien lesen / Web suchen.\\n" +
|
|
315
|
-
"══════════════════════════════════════════\\n"
|
|
316
|
-
);
|
|
317
|
-
}
|
|
318
|
-
|
|
319
|
-
main().catch(() => process.exit(0));
|
|
320
|
-
// <<< knowmind auto-recall hook
|
|
321
|
-
`;
|
|
322
|
-
}
|
|
323
|
-
|
|
324
|
-
function captureGateHookSource() {
|
|
325
|
-
return `#!/usr/bin/env node
|
|
326
|
-
// >>> knowmind capture-gate hook (Stop)
|
|
327
|
-
// Erzeugt von: knowmind init. Idempotent ersetzbar (trägt diesen Marker).
|
|
328
|
-
//
|
|
329
|
-
// Prüft nach jeder Antwort, ob die Runde Sicherungswürdiges enthielt
|
|
330
|
-
// (Code-/Config-Änderung, Deploy/Commit, neue Regel/Entscheidung) UND ob ein
|
|
331
|
-
// knowmind_store_memory aufgerufen wurde. Wenn nicht -> {"decision":"block"},
|
|
332
|
-
// damit die KI vor dem Stoppen eine Erinnerung ablegt.
|
|
333
|
-
// Rein heuristisch (kein LLM). Loop-Schutz via stop_hook_active. Fail-open.
|
|
334
|
-
import { readFileSync } from "node:fs";
|
|
335
|
-
|
|
336
|
-
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;
|
|
337
|
-
const RULE = /(ab sofort|ab jetzt|von nun an|merk(e)? dir|neue regel|regel:|harte regel|standing order|niemals wieder|nie wieder)/i;
|
|
338
|
-
const ARCH = /(architektur-?entscheid|\\bADR\\b|wir stellen um|grundsatzentscheidung|wir migrieren auf|umstellung auf|wir setzen auf)/i;
|
|
339
|
-
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"];
|
|
340
|
-
const STORE_HINTS = ["knowmind_store","store_memory","update_fact","knowmind_update_fact"];
|
|
341
|
-
|
|
342
|
-
function isUserMsg(e) {
|
|
343
|
-
if (e.type !== "user") return false;
|
|
344
|
-
const c = e.message?.content;
|
|
345
|
-
if (typeof c === "string") return !!c.trim();
|
|
346
|
-
if (Array.isArray(c)) {
|
|
347
|
-
const text = c.some((b) => b?.type === "text");
|
|
348
|
-
const tr = c.some((b) => b?.type === "tool_result");
|
|
349
|
-
return text && !tr;
|
|
350
|
-
}
|
|
351
|
-
return false;
|
|
352
|
-
}
|
|
353
|
-
function userText(e) {
|
|
354
|
-
const c = e.message?.content;
|
|
355
|
-
if (typeof c === "string") return c;
|
|
356
|
-
if (Array.isArray(c)) return c.filter((b) => b?.type === "text").map((b) => b.text || "").join(" ");
|
|
357
|
-
return "";
|
|
358
|
-
}
|
|
359
|
-
function collectRound(path) {
|
|
360
|
-
const lines = readFileSync(path, "utf-8").split(/\\r?\\n/).filter(Boolean).map((l) => { try { return JSON.parse(l); } catch { return null; } }).filter(Boolean);
|
|
361
|
-
let start = 0;
|
|
362
|
-
for (let i = lines.length - 1; i >= 0; i--) if (isUserMsg(lines[i])) { start = i; break; }
|
|
363
|
-
const utext = lines.length ? userText(lines[start]) : "";
|
|
364
|
-
const tools = [];
|
|
365
|
-
for (const e of lines.slice(start)) {
|
|
366
|
-
if (e.type !== "assistant") continue;
|
|
367
|
-
const c = e.message?.content;
|
|
368
|
-
if (Array.isArray(c)) for (const b of c) if (b?.type === "tool_use") tools.push(b);
|
|
369
|
-
}
|
|
370
|
-
return { utext, tools };
|
|
371
|
-
}
|
|
372
|
-
function hasStore(tools) {
|
|
373
|
-
for (const t of tools) {
|
|
374
|
-
const n = (t.name || "").toLowerCase();
|
|
375
|
-
if (STORE_HINTS.some((h) => n.includes(h))) return true;
|
|
376
|
-
}
|
|
377
|
-
return false;
|
|
378
|
-
}
|
|
379
|
-
function detect(utext, tools) {
|
|
380
|
-
const sig = [];
|
|
381
|
-
for (const t of tools) if (t.name === "Bash" && DEPLOY.test((t.input?.command) || "")) { sig.push("Deploy/Commit"); break; }
|
|
382
|
-
for (const t of tools) {
|
|
383
|
-
if (["Write","Edit","MultiEdit"].includes(t.name)) {
|
|
384
|
-
const fp = (t.input?.file_path || "").toLowerCase();
|
|
385
|
-
if (fp && CODE_EXT.some((x) => fp.endsWith(x))) { sig.push("Code-/Config-Änderung"); break; }
|
|
386
|
-
}
|
|
387
|
-
}
|
|
388
|
-
if (RULE.test(utext)) sig.push("neue Regel/Standing Order");
|
|
389
|
-
if (ARCH.test(utext)) sig.push("Architektur-Entscheidung");
|
|
390
|
-
return [...new Set(sig)];
|
|
391
|
-
}
|
|
392
|
-
|
|
393
|
-
async function main() {
|
|
394
|
-
let raw = "";
|
|
395
|
-
process.stdin.setEncoding("utf-8");
|
|
396
|
-
for await (const c of process.stdin) raw += c;
|
|
397
|
-
let data = {};
|
|
398
|
-
try { data = raw ? JSON.parse(raw) : {}; } catch { return; }
|
|
399
|
-
if (data.stop_hook_active) return; // Loop-Schutz
|
|
400
|
-
const tp = data.transcript_path;
|
|
401
|
-
if (!tp) return;
|
|
402
|
-
let round;
|
|
403
|
-
try { round = collectRound(tp); } catch { return; }
|
|
404
|
-
if (hasStore(round.tools)) return; // schon gesichert
|
|
405
|
-
const sig = detect(round.utext, round.tools);
|
|
406
|
-
if (!sig.length) return; // nichts Sicherungswürdiges
|
|
407
|
-
|
|
408
|
-
const reason =
|
|
409
|
-
"STOP-GATE (knowmind): Diese Runde enthielt Sicherungswürdiges (" + sig.join(", ") + "), " +
|
|
410
|
-
"aber es wurde kein knowmind_store_memory aufgerufen.\\n" +
|
|
411
|
-
"Bevor du stoppst: lege das Ergebnis mit knowmind_store_memory ab (Titel + Inhalt) " +
|
|
412
|
-
"und verknüpfe es ggf. mit knowmind_link. Ist der Vorgang wirklich nicht " +
|
|
413
|
-
"sicherungswürdig (reine Recherche, Wegwerf-Test), begründe es in einem Satz, dann stoppe.";
|
|
414
|
-
process.stdout.write(JSON.stringify({ decision: "block", reason }));
|
|
415
|
-
}
|
|
416
|
-
|
|
417
|
-
main().catch(() => process.exit(0));
|
|
418
|
-
// <<< knowmind capture-gate hook
|
|
419
|
-
`;
|
|
420
|
-
}
|
|
421
|
-
|
|
422
|
-
// ─── Cursor-Rule (.mdc) ──────────────────────────────────────────────
|
|
423
|
-
function cursorRuleSource() {
|
|
424
|
-
return `---
|
|
425
|
-
description: knowmind — Memory-First-Regel (automatisches Langzeitgedächtnis)
|
|
426
|
-
alwaysApply: true
|
|
427
|
-
---
|
|
428
|
-
${BEGIN}
|
|
429
|
-
# knowmind — automatische Gedächtnis-Pflege
|
|
430
|
-
|
|
431
|
-
Dieses Projekt nutzt **knowmind** (Langzeitgedächtnis & Wissensgraph) als MCP-Server.
|
|
432
|
-
|
|
433
|
-
1. **Recall zuerst.** Bevor du eine inhaltliche Frage beantwortest oder eine Aufgabe
|
|
434
|
-
planst, rufe \`knowmind_recall\` auf und prüfe, ob bereits relevantes Wissen vorliegt.
|
|
435
|
-
Erst danach Dateien lesen / Web suchen.
|
|
436
|
-
2. **Wissen sichern.** Bringt eine Runde Sicherungswürdiges hervor (Entscheidung, neue
|
|
437
|
-
Regel, Ergebnis, Fakt über Personen/Projekte/Systeme), lege es mit
|
|
438
|
-
\`knowmind_store_memory\` ab, bevor du fortfährst.
|
|
439
|
-
3. **Beziehungen pflegen.** Verknüpfe zusammengehörige Erinnerungen mit \`knowmind_link\`.
|
|
440
|
-
|
|
441
|
-
Das Gedächtnis lebt auf der knowmind-Plattform (Server in Deutschland), nicht in lokalen
|
|
442
|
-
Dateien — über Sessions und Clients hinweg dasselbe Gehirn.
|
|
443
|
-
${END}
|
|
444
|
-
`;
|
|
445
|
-
}
|
|
446
|
-
|
|
447
|
-
// ─── Claude-settings.json: Hook-Registrierung (idempotent) ───────────
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
}
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
if (
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
}
|
|
640
|
-
}
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
if (
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
}
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
};
|
|
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, writeFileSync, mkdirSync, readdirSync, statSync, unlinkSync } from "node:fs";
|
|
158
|
+
import { homedir } from "node:os";
|
|
159
|
+
import { join } from "node:path";
|
|
160
|
+
|
|
161
|
+
// Stempelt den Aktivitäts-Zeitpunkt für die knowmind-Statusline (grüne
|
|
162
|
+
// HDD-LED). Best-effort, darf den Recall nie brechen.
|
|
163
|
+
function markActivity() {
|
|
164
|
+
try {
|
|
165
|
+
mkdirSync(join(homedir(), ".knowmind"), { recursive: true });
|
|
166
|
+
writeFileSync(join(homedir(), ".knowmind", "activity"), String(Date.now()));
|
|
167
|
+
} catch {}
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
// Zählt pro Claude-Code-Session die abgerufenen Erinnerungen. Die Statusline
|
|
171
|
+
// zeigt „N abgerufen" für die laufende Sitzung. Best-effort.
|
|
172
|
+
function bumpSessionRecalls(sessionId, hits) {
|
|
173
|
+
if (!sessionId || !(hits > 0)) return;
|
|
174
|
+
try {
|
|
175
|
+
const d = join(homedir(), ".knowmind", "sessions");
|
|
176
|
+
mkdirSync(d, { recursive: true });
|
|
177
|
+
const now = Date.now();
|
|
178
|
+
for (const fn of readdirSync(d)) {
|
|
179
|
+
try {
|
|
180
|
+
if (now - statSync(join(d, fn)).mtimeMs > 86400000) unlinkSync(join(d, fn));
|
|
181
|
+
} catch {}
|
|
182
|
+
}
|
|
183
|
+
const safe = String(sessionId).replace(/[^a-zA-Z0-9_-]/g, "").slice(0, 80);
|
|
184
|
+
const p = join(d, safe + ".json");
|
|
185
|
+
let cur = {};
|
|
186
|
+
try { cur = JSON.parse(readFileSync(p, "utf-8")); } catch {}
|
|
187
|
+
cur.recalls = (cur.recalls || 0) + 1;
|
|
188
|
+
cur.memories = (cur.memories || 0) + hits;
|
|
189
|
+
cur.updated = now;
|
|
190
|
+
writeFileSync(p, JSON.stringify(cur));
|
|
191
|
+
} catch {}
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
const TRIVIAL = new Set([
|
|
195
|
+
"ok","okay","go","ja","nein","weiter","stop","danke","thanks","thx",
|
|
196
|
+
"yes","no","yep","nope","perfekt","passt","super","gut",
|
|
197
|
+
]);
|
|
198
|
+
const TRIGGER = [
|
|
199
|
+
"kunde","kunden","projekt","tool","server","domain","wer ist","was ist",
|
|
200
|
+
"welche","liste","übersicht","status","wo ","wann","wieso","warum",
|
|
201
|
+
"recherche","research","info zu","infos zu","memory","graph","datenbank",
|
|
202
|
+
];
|
|
203
|
+
|
|
204
|
+
function shouldRecall(p) {
|
|
205
|
+
const s = (p || "").trim().toLowerCase();
|
|
206
|
+
if (s.length < 8) return false;
|
|
207
|
+
if (TRIVIAL.has(s)) return false;
|
|
208
|
+
if (s.startsWith("/")) return false;
|
|
209
|
+
if (TRIGGER.some((k) => s.includes(k))) return true;
|
|
210
|
+
if (s.endsWith("?")) return true;
|
|
211
|
+
return s.length >= 40;
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
// Token + apiUrl: ENV hat Vorrang, sonst ~/.knowmind/config.json (gleiche
|
|
215
|
+
// Reihenfolge wie die CLI). Kein Token -> kein Recall (fail-open).
|
|
216
|
+
function loadCreds() {
|
|
217
|
+
let file = {};
|
|
218
|
+
try {
|
|
219
|
+
file = JSON.parse(readFileSync(join(homedir(), ".knowmind", "config.json"), "utf-8"));
|
|
220
|
+
} catch { /* keine/kaputte Config -> ENV/Default */ }
|
|
221
|
+
let apiUrl = process.env.KNOWMIND_API_URL || file.apiUrl || "https://knowmind.de";
|
|
222
|
+
if (apiUrl.endsWith("/")) apiUrl = apiUrl.slice(0, -1);
|
|
223
|
+
return { apiUrl, token: process.env.KNOWMIND_TOKEN || file.token || null };
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
// Antwort von /api/mcp/v1 ist Standard-SSE (data:-Frames) ODER plain JSON.
|
|
227
|
+
// Beides robust auf das JSON-RPC-Objekt mit result/error reduzieren.
|
|
228
|
+
function parseBody(raw) {
|
|
229
|
+
raw = (raw || "").trim();
|
|
230
|
+
if (!raw) return null;
|
|
231
|
+
if (raw.startsWith("{")) { try { return JSON.parse(raw); } catch { return null; } }
|
|
232
|
+
let found = null;
|
|
233
|
+
for (const lineRaw of raw.split("\\n")) {
|
|
234
|
+
const line = lineRaw.trim();
|
|
235
|
+
if (line.indexOf("data:") !== 0) continue;
|
|
236
|
+
try {
|
|
237
|
+
const obj = JSON.parse(line.slice(5).trim());
|
|
238
|
+
if (obj && (obj.result || obj.error)) found = obj;
|
|
239
|
+
} catch { /* nicht-JSON data-Zeile überspringen */ }
|
|
240
|
+
}
|
|
241
|
+
return found;
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
// knowmind_recall liefert result.content[].text = JSON-String mit hits[].
|
|
245
|
+
// Lesbar verdichten; bei Parse-Fehler den Rohtext durchreichen.
|
|
246
|
+
function formatHits(rpc) {
|
|
247
|
+
const c = rpc && rpc.result && rpc.result.content;
|
|
248
|
+
const text = Array.isArray(c)
|
|
249
|
+
? c.filter((b) => b && b.type === "text" && b.text).map((b) => b.text).join("\\n").trim()
|
|
250
|
+
: "";
|
|
251
|
+
if (!text) return "";
|
|
252
|
+
try {
|
|
253
|
+
const o = JSON.parse(text);
|
|
254
|
+
if (Array.isArray(o.hits)) {
|
|
255
|
+
if (o.hits.length === 0) return "";
|
|
256
|
+
return o.hits.slice(0, 5).map((h, i) => {
|
|
257
|
+
const m = h.metadata || {};
|
|
258
|
+
const title = m.title || m.name || h.source || ("Treffer " + (i + 1));
|
|
259
|
+
const score = typeof h.score === "number" ? " (" + h.score.toFixed(2) + ")" : "";
|
|
260
|
+
const snip = String(h.content || "").replace(/\\s+/g, " ").trim().slice(0, 280);
|
|
261
|
+
return "• " + title + score + ": " + snip;
|
|
262
|
+
}).join("\\n");
|
|
263
|
+
}
|
|
264
|
+
} catch { /* kein hits-JSON -> Rohtext */ }
|
|
265
|
+
return text;
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
async function main() {
|
|
269
|
+
let raw = "";
|
|
270
|
+
process.stdin.setEncoding("utf-8");
|
|
271
|
+
for await (const c of process.stdin) raw += c;
|
|
272
|
+
let prompt = "";
|
|
273
|
+
let sessionId = "";
|
|
274
|
+
try {
|
|
275
|
+
const data = raw ? JSON.parse(raw) : {};
|
|
276
|
+
prompt = data.prompt || data.user_prompt || data.user_message || "";
|
|
277
|
+
sessionId = data.session_id || data.sessionId || "";
|
|
278
|
+
} catch { return; }
|
|
279
|
+
if (!shouldRecall(prompt)) return;
|
|
280
|
+
|
|
281
|
+
const { apiUrl, token } = loadCreds();
|
|
282
|
+
if (!token) return;
|
|
283
|
+
markActivity();
|
|
284
|
+
const query = prompt.trim().slice(0, 500);
|
|
285
|
+
|
|
286
|
+
const ctrl = new AbortController();
|
|
287
|
+
const timer = setTimeout(() => ctrl.abort(), 6000);
|
|
288
|
+
let rpc = null;
|
|
289
|
+
try {
|
|
290
|
+
const res = await fetch(apiUrl + "/api/mcp/v1", {
|
|
291
|
+
method: "POST",
|
|
292
|
+
headers: {
|
|
293
|
+
"Authorization": "Bearer " + token,
|
|
294
|
+
"Content-Type": "application/json",
|
|
295
|
+
"Accept": "application/json, text/event-stream",
|
|
296
|
+
},
|
|
297
|
+
body: JSON.stringify({
|
|
298
|
+
jsonrpc: "2.0", id: 1, method: "tools/call",
|
|
299
|
+
params: { name: "knowmind_recall", arguments: { query, k: 5, hops: 2 } },
|
|
300
|
+
}),
|
|
301
|
+
signal: ctrl.signal,
|
|
302
|
+
});
|
|
303
|
+
rpc = parseBody(await res.text());
|
|
304
|
+
} catch { return; } finally { clearTimeout(timer); }
|
|
305
|
+
|
|
306
|
+
const hits = formatHits(rpc);
|
|
307
|
+
if (!hits) return;
|
|
308
|
+
bumpSessionRecalls(sessionId, (hits.match(/^• /gm) || []).length);
|
|
309
|
+
|
|
310
|
+
process.stdout.write(
|
|
311
|
+
"═════════ knowmind RECALL (auto) ═════════\\n" +
|
|
312
|
+
hits + "\\n" +
|
|
313
|
+
"Diese Treffer wurden automatisch vor deiner Antwort abgerufen.\\n" +
|
|
314
|
+
"Erst hier prüfen, dann Dateien lesen / Web suchen.\\n" +
|
|
315
|
+
"══════════════════════════════════════════\\n"
|
|
316
|
+
);
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
main().catch(() => process.exit(0));
|
|
320
|
+
// <<< knowmind auto-recall hook
|
|
321
|
+
`;
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
function captureGateHookSource() {
|
|
325
|
+
return `#!/usr/bin/env node
|
|
326
|
+
// >>> knowmind capture-gate hook (Stop)
|
|
327
|
+
// Erzeugt von: knowmind init. Idempotent ersetzbar (trägt diesen Marker).
|
|
328
|
+
//
|
|
329
|
+
// Prüft nach jeder Antwort, ob die Runde Sicherungswürdiges enthielt
|
|
330
|
+
// (Code-/Config-Änderung, Deploy/Commit, neue Regel/Entscheidung) UND ob ein
|
|
331
|
+
// knowmind_store_memory aufgerufen wurde. Wenn nicht -> {"decision":"block"},
|
|
332
|
+
// damit die KI vor dem Stoppen eine Erinnerung ablegt.
|
|
333
|
+
// Rein heuristisch (kein LLM). Loop-Schutz via stop_hook_active. Fail-open.
|
|
334
|
+
import { readFileSync } from "node:fs";
|
|
335
|
+
|
|
336
|
+
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;
|
|
337
|
+
const RULE = /(ab sofort|ab jetzt|von nun an|merk(e)? dir|neue regel|regel:|harte regel|standing order|niemals wieder|nie wieder)/i;
|
|
338
|
+
const ARCH = /(architektur-?entscheid|\\bADR\\b|wir stellen um|grundsatzentscheidung|wir migrieren auf|umstellung auf|wir setzen auf)/i;
|
|
339
|
+
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"];
|
|
340
|
+
const STORE_HINTS = ["knowmind_store","store_memory","update_fact","knowmind_update_fact"];
|
|
341
|
+
|
|
342
|
+
function isUserMsg(e) {
|
|
343
|
+
if (e.type !== "user") return false;
|
|
344
|
+
const c = e.message?.content;
|
|
345
|
+
if (typeof c === "string") return !!c.trim();
|
|
346
|
+
if (Array.isArray(c)) {
|
|
347
|
+
const text = c.some((b) => b?.type === "text");
|
|
348
|
+
const tr = c.some((b) => b?.type === "tool_result");
|
|
349
|
+
return text && !tr;
|
|
350
|
+
}
|
|
351
|
+
return false;
|
|
352
|
+
}
|
|
353
|
+
function userText(e) {
|
|
354
|
+
const c = e.message?.content;
|
|
355
|
+
if (typeof c === "string") return c;
|
|
356
|
+
if (Array.isArray(c)) return c.filter((b) => b?.type === "text").map((b) => b.text || "").join(" ");
|
|
357
|
+
return "";
|
|
358
|
+
}
|
|
359
|
+
function collectRound(path) {
|
|
360
|
+
const lines = readFileSync(path, "utf-8").split(/\\r?\\n/).filter(Boolean).map((l) => { try { return JSON.parse(l); } catch { return null; } }).filter(Boolean);
|
|
361
|
+
let start = 0;
|
|
362
|
+
for (let i = lines.length - 1; i >= 0; i--) if (isUserMsg(lines[i])) { start = i; break; }
|
|
363
|
+
const utext = lines.length ? userText(lines[start]) : "";
|
|
364
|
+
const tools = [];
|
|
365
|
+
for (const e of lines.slice(start)) {
|
|
366
|
+
if (e.type !== "assistant") continue;
|
|
367
|
+
const c = e.message?.content;
|
|
368
|
+
if (Array.isArray(c)) for (const b of c) if (b?.type === "tool_use") tools.push(b);
|
|
369
|
+
}
|
|
370
|
+
return { utext, tools };
|
|
371
|
+
}
|
|
372
|
+
function hasStore(tools) {
|
|
373
|
+
for (const t of tools) {
|
|
374
|
+
const n = (t.name || "").toLowerCase();
|
|
375
|
+
if (STORE_HINTS.some((h) => n.includes(h))) return true;
|
|
376
|
+
}
|
|
377
|
+
return false;
|
|
378
|
+
}
|
|
379
|
+
function detect(utext, tools) {
|
|
380
|
+
const sig = [];
|
|
381
|
+
for (const t of tools) if (t.name === "Bash" && DEPLOY.test((t.input?.command) || "")) { sig.push("Deploy/Commit"); break; }
|
|
382
|
+
for (const t of tools) {
|
|
383
|
+
if (["Write","Edit","MultiEdit"].includes(t.name)) {
|
|
384
|
+
const fp = (t.input?.file_path || "").toLowerCase();
|
|
385
|
+
if (fp && CODE_EXT.some((x) => fp.endsWith(x))) { sig.push("Code-/Config-Änderung"); break; }
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
if (RULE.test(utext)) sig.push("neue Regel/Standing Order");
|
|
389
|
+
if (ARCH.test(utext)) sig.push("Architektur-Entscheidung");
|
|
390
|
+
return [...new Set(sig)];
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
async function main() {
|
|
394
|
+
let raw = "";
|
|
395
|
+
process.stdin.setEncoding("utf-8");
|
|
396
|
+
for await (const c of process.stdin) raw += c;
|
|
397
|
+
let data = {};
|
|
398
|
+
try { data = raw ? JSON.parse(raw) : {}; } catch { return; }
|
|
399
|
+
if (data.stop_hook_active) return; // Loop-Schutz
|
|
400
|
+
const tp = data.transcript_path;
|
|
401
|
+
if (!tp) return;
|
|
402
|
+
let round;
|
|
403
|
+
try { round = collectRound(tp); } catch { return; }
|
|
404
|
+
if (hasStore(round.tools)) return; // schon gesichert
|
|
405
|
+
const sig = detect(round.utext, round.tools);
|
|
406
|
+
if (!sig.length) return; // nichts Sicherungswürdiges
|
|
407
|
+
|
|
408
|
+
const reason =
|
|
409
|
+
"STOP-GATE (knowmind): Diese Runde enthielt Sicherungswürdiges (" + sig.join(", ") + "), " +
|
|
410
|
+
"aber es wurde kein knowmind_store_memory aufgerufen.\\n" +
|
|
411
|
+
"Bevor du stoppst: lege das Ergebnis mit knowmind_store_memory ab (Titel + Inhalt) " +
|
|
412
|
+
"und verknüpfe es ggf. mit knowmind_link. Ist der Vorgang wirklich nicht " +
|
|
413
|
+
"sicherungswürdig (reine Recherche, Wegwerf-Test), begründe es in einem Satz, dann stoppe.";
|
|
414
|
+
process.stdout.write(JSON.stringify({ decision: "block", reason }));
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
main().catch(() => process.exit(0));
|
|
418
|
+
// <<< knowmind capture-gate hook
|
|
419
|
+
`;
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
// ─── Cursor-Rule (.mdc) ──────────────────────────────────────────────
|
|
423
|
+
function cursorRuleSource() {
|
|
424
|
+
return `---
|
|
425
|
+
description: knowmind — Memory-First-Regel (automatisches Langzeitgedächtnis)
|
|
426
|
+
alwaysApply: true
|
|
427
|
+
---
|
|
428
|
+
${BEGIN}
|
|
429
|
+
# knowmind — automatische Gedächtnis-Pflege
|
|
430
|
+
|
|
431
|
+
Dieses Projekt nutzt **knowmind** (Langzeitgedächtnis & Wissensgraph) als MCP-Server.
|
|
432
|
+
|
|
433
|
+
1. **Recall zuerst.** Bevor du eine inhaltliche Frage beantwortest oder eine Aufgabe
|
|
434
|
+
planst, rufe \`knowmind_recall\` auf und prüfe, ob bereits relevantes Wissen vorliegt.
|
|
435
|
+
Erst danach Dateien lesen / Web suchen.
|
|
436
|
+
2. **Wissen sichern.** Bringt eine Runde Sicherungswürdiges hervor (Entscheidung, neue
|
|
437
|
+
Regel, Ergebnis, Fakt über Personen/Projekte/Systeme), lege es mit
|
|
438
|
+
\`knowmind_store_memory\` ab, bevor du fortfährst.
|
|
439
|
+
3. **Beziehungen pflegen.** Verknüpfe zusammengehörige Erinnerungen mit \`knowmind_link\`.
|
|
440
|
+
|
|
441
|
+
Das Gedächtnis lebt auf der knowmind-Plattform (Server in Deutschland), nicht in lokalen
|
|
442
|
+
Dateien — über Sessions und Clients hinweg dasselbe Gehirn.
|
|
443
|
+
${END}
|
|
444
|
+
`;
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
// ─── Claude-settings.json: Hook-Registrierung (idempotent) ───────────
|
|
448
|
+
|
|
449
|
+
/**
|
|
450
|
+
* Fensterloser Starter für Windows.
|
|
451
|
+
*
|
|
452
|
+
* Gemessen am 08.08.2026: Startet ein Prozess OHNE eigene Konsole ein
|
|
453
|
+
* Konsolenprogramm, gibt Windows dem Kind ein eigenes Fenster
|
|
454
|
+
* (`GetConsoleWindow() != 0`). Läuft der KI-Client also nicht im Terminal —
|
|
455
|
+
* Desktop-Anwendung, IDE-Erweiterung —, blitzt bei JEDEM Hook-Aufruf ein
|
|
456
|
+
* Fenster auf. Bei mehreren Hooks je Runde wird das unerträglich.
|
|
457
|
+
*
|
|
458
|
+
* `node.exe` hat kein fensterloses Gegenstück (kein „nodew.exe"). Deshalb
|
|
459
|
+
* dieser Umweg: `pythonw.exe` ist ein GUI-Programm und öffnet selbst kein
|
|
460
|
+
* Fenster; es startet node mit CREATE_NO_WINDOW und reicht die Datenströme
|
|
461
|
+
* unverändert durch. Der Hook selbst bleibt unverändert in Node — eine
|
|
462
|
+
* Wahrheit, kein zweiter Pflegezweig.
|
|
463
|
+
*
|
|
464
|
+
* Ohne Python auf dem Rechner bleibt es beim direkten node-Aufruf; dann blitzt
|
|
465
|
+
* es, wie es das vorher auch tat. Das ist ehrlicher als eine halbe Lösung.
|
|
466
|
+
*/
|
|
467
|
+
function windowsStarterSource() {
|
|
468
|
+
return `# >>> knowmind windows starter >>>
|
|
469
|
+
# Erzeugt von: knowmind init. Startet den Node-Hook ohne Konsolenfenster.
|
|
470
|
+
# Hintergrund: siehe windowsStarterSource() in knowmind/src/init.js.
|
|
471
|
+
import os, subprocess, sys
|
|
472
|
+
|
|
473
|
+
CREATE_NO_WINDOW = 0x08000000
|
|
474
|
+
skript = os.path.join(os.path.dirname(os.path.abspath(__file__)), sys.argv[1])
|
|
475
|
+
try:
|
|
476
|
+
fertig = subprocess.run(
|
|
477
|
+
["node", skript],
|
|
478
|
+
input=sys.stdin.buffer.read(),
|
|
479
|
+
capture_output=True,
|
|
480
|
+
creationflags=CREATE_NO_WINDOW,
|
|
481
|
+
)
|
|
482
|
+
sys.stdout.buffer.write(fertig.stdout)
|
|
483
|
+
sys.stdout.flush()
|
|
484
|
+
sys.exit(fertig.returncode)
|
|
485
|
+
except Exception:
|
|
486
|
+
# Fail-open wie der Hook selbst: nie blockieren.
|
|
487
|
+
sys.exit(0)
|
|
488
|
+
# <<< knowmind windows starter <<<
|
|
489
|
+
`;
|
|
490
|
+
}
|
|
491
|
+
|
|
492
|
+
/** Vollständiger Pfad zu pythonw.exe, oder null wenn nicht auffindbar. */
|
|
493
|
+
function findePythonw() {
|
|
494
|
+
if (platform() !== "win32") return null;
|
|
495
|
+
const kandidaten = [];
|
|
496
|
+
const lokal = process.env.LOCALAPPDATA;
|
|
497
|
+
if (lokal) {
|
|
498
|
+
for (const v of ["313", "312", "311", "310"]) {
|
|
499
|
+
kandidaten.push(join(lokal, "Programs", "Python", `Python${v}`, "pythonw.exe"));
|
|
500
|
+
}
|
|
501
|
+
}
|
|
502
|
+
for (const v of ["313", "312", "311", "310"]) {
|
|
503
|
+
kandidaten.push(join("C:\\", `Python${v}`, "pythonw.exe"));
|
|
504
|
+
}
|
|
505
|
+
return kandidaten.find((p) => existsSync(p)) ?? null;
|
|
506
|
+
}
|
|
507
|
+
|
|
508
|
+
function ensureClaudeHookEntry(settings, eventName, scriptRel, pythonw) {
|
|
509
|
+
// settings.hooks[eventName] ist ein Array von { matcher?, hooks: [{type,command}] }.
|
|
510
|
+
// Wir registrieren genau EINEN knowmind-Eintrag pro Event, marker-erkennbar am command.
|
|
511
|
+
const skriptName = scriptRel.split(/[\\/]/).pop();
|
|
512
|
+
const cmd = pythonw
|
|
513
|
+
? `"${pythonw}" ".claude/hooks/knowmind_start.py" "${skriptName}"`
|
|
514
|
+
: `node "${scriptRel}"`;
|
|
515
|
+
settings.hooks = settings.hooks || {};
|
|
516
|
+
const arr = settings.hooks[eventName] || [];
|
|
517
|
+
// Existierenden knowmind-Eintrag finden (command enthält den Skriptnamen).
|
|
518
|
+
// Greift für beide Formen: direkter node-Aufruf und Windows-Starter, weil in
|
|
519
|
+
// beiden der Skriptname vorkommt. So wird ein Eintrag beim Wechsel zwischen
|
|
520
|
+
// den Formen ersetzt statt verdoppelt.
|
|
521
|
+
const scriptName = skriptName;
|
|
522
|
+
let mutated = false;
|
|
523
|
+
let present = false;
|
|
524
|
+
for (const group of arr) {
|
|
525
|
+
for (const h of group.hooks || []) {
|
|
526
|
+
if (typeof h.command === "string" && h.command.includes(scriptName)) {
|
|
527
|
+
present = true;
|
|
528
|
+
if (h.command !== cmd) {
|
|
529
|
+
h.command = cmd;
|
|
530
|
+
mutated = true;
|
|
531
|
+
}
|
|
532
|
+
}
|
|
533
|
+
}
|
|
534
|
+
}
|
|
535
|
+
if (!present) {
|
|
536
|
+
arr.push({ hooks: [{ type: "command", command: cmd }] });
|
|
537
|
+
mutated = true;
|
|
538
|
+
}
|
|
539
|
+
settings.hooks[eventName] = arr;
|
|
540
|
+
return mutated;
|
|
541
|
+
}
|
|
542
|
+
|
|
543
|
+
// ─── Plan-Bauer pro Client ───────────────────────────────────────────
|
|
544
|
+
// Jeder Eintrag: { path, kind, render() -> {action, content?} oder Info }
|
|
545
|
+
|
|
546
|
+
function planClaudeCode(cwd) {
|
|
547
|
+
const actions = [];
|
|
548
|
+
const hooksDir = join(cwd, ".claude", "hooks");
|
|
549
|
+
const recallPath = join(hooksDir, "knowmind_recall.mjs");
|
|
550
|
+
const capturePath = join(hooksDir, "knowmind_capture.mjs");
|
|
551
|
+
const settingsPath = join(cwd, ".claude", "settings.json");
|
|
552
|
+
const claudeMdPath = join(cwd, "CLAUDE.md");
|
|
553
|
+
|
|
554
|
+
// 1) Recall-Hook
|
|
555
|
+
const recallSrc = autoRecallHookSource();
|
|
556
|
+
actions.push({
|
|
557
|
+
label: "Claude-Code Recall-Hook",
|
|
558
|
+
path: recallPath,
|
|
559
|
+
...writeOwnFile(recallPath, recallSrc, ">>> knowmind auto-recall hook"),
|
|
560
|
+
content: recallSrc,
|
|
561
|
+
_own: true,
|
|
562
|
+
_exec: true,
|
|
563
|
+
});
|
|
564
|
+
|
|
565
|
+
// 2) Capture-Gate-Hook
|
|
566
|
+
const captureSrc = captureGateHookSource();
|
|
567
|
+
actions.push({
|
|
568
|
+
label: "Claude-Code Capture-Gate-Hook",
|
|
569
|
+
path: capturePath,
|
|
570
|
+
...writeOwnFile(capturePath, captureSrc, ">>> knowmind capture-gate hook"),
|
|
571
|
+
content: captureSrc,
|
|
572
|
+
_own: true,
|
|
573
|
+
_exec: true,
|
|
574
|
+
});
|
|
575
|
+
|
|
576
|
+
// 2b) Windows-Starter — nur dort, wo er gebraucht wird und wirken kann.
|
|
577
|
+
const pythonwPfad = findePythonw();
|
|
578
|
+
if (pythonwPfad) {
|
|
579
|
+
const starterPfad = join(hooksDir, "knowmind_start.py");
|
|
580
|
+
const starterSrc = windowsStarterSource();
|
|
581
|
+
actions.push({
|
|
582
|
+
label: "Windows-Starter (Hooks ohne Konsolenfenster)",
|
|
583
|
+
path: starterPfad,
|
|
584
|
+
...writeOwnFile(starterPfad, starterSrc, ">>> knowmind windows starter"),
|
|
585
|
+
content: starterSrc,
|
|
586
|
+
_own: true,
|
|
587
|
+
});
|
|
588
|
+
}
|
|
589
|
+
|
|
590
|
+
// 3) settings.json — Hooks registrieren
|
|
591
|
+
let settings = {};
|
|
592
|
+
if (existsSync(settingsPath)) {
|
|
593
|
+
try {
|
|
594
|
+
settings = JSON.parse(readFileSync(settingsPath, "utf-8"));
|
|
595
|
+
} catch {
|
|
596
|
+
settings = { _parseError: true };
|
|
597
|
+
}
|
|
598
|
+
}
|
|
599
|
+
if (settings._parseError) {
|
|
600
|
+
actions.push({
|
|
601
|
+
label: "Claude-Code settings.json",
|
|
602
|
+
path: settingsPath,
|
|
603
|
+
action: "skip-foreign",
|
|
604
|
+
reason: "settings.json ist kein gültiges JSON — bitte Hooks manuell eintragen",
|
|
605
|
+
});
|
|
606
|
+
} else {
|
|
607
|
+
const relRecall = ".claude/hooks/knowmind_recall.mjs";
|
|
608
|
+
const relCapture = ".claude/hooks/knowmind_capture.mjs";
|
|
609
|
+
const pythonw = findePythonw();
|
|
610
|
+
const m1 = ensureClaudeHookEntry(settings, "UserPromptSubmit", relRecall, pythonw);
|
|
611
|
+
const m2 = ensureClaudeHookEntry(settings, "Stop", relCapture, pythonw);
|
|
612
|
+
// Statusline: knowmind-Lebenszeichen (grüne HDD-LED). NUR setzen, wenn
|
|
613
|
+
// keine existiert oder sie bereits auf knowmind zeigt — eine fremde
|
|
614
|
+
// Statusline des Nutzers wird NIE gekapert.
|
|
615
|
+
// refreshInterval: Claude Code rendert die Statusline sonst nur bei
|
|
616
|
+
// Ereignissen — damit die grüne LED bei Aktivität sichtbar flackert, muss
|
|
617
|
+
// sie periodisch neu gezeichnet werden (Claude Code >= 2.1.97, Min. 500 ms).
|
|
618
|
+
const km = { type: "command", command: "knowmind status --line", refreshInterval: 500 };
|
|
619
|
+
let m3 = false;
|
|
620
|
+
const existing = settings.statusLine;
|
|
621
|
+
const isKnowmind =
|
|
622
|
+
existing && typeof existing.command === "string" && existing.command.includes("knowmind status");
|
|
623
|
+
if (!existing) {
|
|
624
|
+
settings.statusLine = km;
|
|
625
|
+
m3 = true;
|
|
626
|
+
} else if (isKnowmind && (existing.command !== km.command || existing.refreshInterval !== 500)) {
|
|
627
|
+
settings.statusLine = km;
|
|
628
|
+
m3 = true;
|
|
629
|
+
}
|
|
630
|
+
actions.push({
|
|
631
|
+
label: "Claude-Code settings.json (Hooks + Statusline)",
|
|
632
|
+
path: settingsPath,
|
|
633
|
+
action: m1 || m2 || m3 ? (existsSync(settingsPath) ? "patch" : "create") : "unchanged",
|
|
634
|
+
content: JSON.stringify(settings, null, 2) + "\n",
|
|
635
|
+
_note:
|
|
636
|
+
existing && !isKnowmind
|
|
637
|
+
? "Eigene Statusline erkannt — nicht überschrieben. Manuell einbinden: knowmind status --line"
|
|
638
|
+
: undefined,
|
|
639
|
+
});
|
|
640
|
+
}
|
|
641
|
+
|
|
642
|
+
// 4) CLAUDE.md — Memory-First-Block
|
|
643
|
+
const md = upsertMarkedBlock(claudeMdPath, memoryFirstBlock());
|
|
644
|
+
actions.push({
|
|
645
|
+
label: "CLAUDE.md (Memory-First-Block)",
|
|
646
|
+
path: claudeMdPath,
|
|
647
|
+
action: md.action,
|
|
648
|
+
content: md.content,
|
|
649
|
+
});
|
|
650
|
+
|
|
651
|
+
return actions;
|
|
652
|
+
}
|
|
653
|
+
|
|
654
|
+
function planCursor(cwd) {
|
|
655
|
+
const rulePath = join(cwd, ".cursor", "rules", "knowmind.mdc");
|
|
656
|
+
const src = cursorRuleSource();
|
|
657
|
+
return [
|
|
658
|
+
{
|
|
659
|
+
label: "Cursor-Rule .cursor/rules/knowmind.mdc",
|
|
660
|
+
path: rulePath,
|
|
661
|
+
...writeOwnFile(rulePath, src, BEGIN),
|
|
662
|
+
content: src,
|
|
663
|
+
_own: true,
|
|
664
|
+
},
|
|
665
|
+
];
|
|
666
|
+
}
|
|
667
|
+
|
|
668
|
+
// ─── Ausführung ──────────────────────────────────────────────────────
|
|
669
|
+
|
|
670
|
+
function applyAction(a) {
|
|
671
|
+
if (!a.action || ["unchanged", "skip-foreign"].includes(a.action)) return;
|
|
672
|
+
if (a.content == null) return;
|
|
673
|
+
mkdirSync(dirname(a.path), { recursive: true });
|
|
674
|
+
writeFileSync(a.path, a.content, "utf-8");
|
|
675
|
+
if (a._exec && platform() !== "win32") {
|
|
676
|
+
try {
|
|
677
|
+
chmodSync(a.path, 0o755);
|
|
678
|
+
} catch {
|
|
679
|
+
/* best effort */
|
|
680
|
+
}
|
|
681
|
+
}
|
|
682
|
+
}
|
|
683
|
+
|
|
684
|
+
const ICON = {
|
|
685
|
+
create: "+",
|
|
686
|
+
replace: "~",
|
|
687
|
+
overwrite: "~",
|
|
688
|
+
patch: "~",
|
|
689
|
+
append: "~",
|
|
690
|
+
unchanged: "=",
|
|
691
|
+
"skip-foreign": "!",
|
|
692
|
+
};
|
|
693
|
+
|
|
694
|
+
/**
|
|
695
|
+
* Haupteinstieg. options: { client, dryRun, cwd, home }
|
|
696
|
+
*/
|
|
697
|
+
export async function runInit({ client = "auto", dryRun = false, cwd = process.cwd(), home = homedir() } = {}) {
|
|
698
|
+
const cfg = loadConfig();
|
|
699
|
+
const lines = [];
|
|
700
|
+
lines.push(`knowmind init ${VERSION}${dryRun ? " (dry-run — es wird NICHTS geschrieben)" : ""}`);
|
|
701
|
+
lines.push(`Projekt: ${resolve(cwd)}`);
|
|
702
|
+
lines.push(`Plattform: ${cfg.apiUrl}${cfg.token ? " (Token konfiguriert)" : " (KEIN Token — `knowmind login` zuerst!)"}`);
|
|
703
|
+
lines.push("");
|
|
704
|
+
|
|
705
|
+
// Client wählen
|
|
706
|
+
let target = client;
|
|
707
|
+
if (client === "auto") {
|
|
708
|
+
const detected = detectClients(cwd, home);
|
|
709
|
+
if (detected.length === 0) {
|
|
710
|
+
target = "generic";
|
|
711
|
+
lines.push("Kein Client automatisch erkannt — generische Anleitung.");
|
|
712
|
+
} else if (detected.length === 1) {
|
|
713
|
+
target = detected[0];
|
|
714
|
+
lines.push(`Erkannter Client: ${target}`);
|
|
715
|
+
} else {
|
|
716
|
+
// Mehrere -> alle einrichten, klar ausweisen.
|
|
717
|
+
target = detected;
|
|
718
|
+
lines.push(`Erkannte Clients: ${detected.join(", ")} — alle werden eingerichtet.`);
|
|
719
|
+
}
|
|
720
|
+
} else {
|
|
721
|
+
lines.push(`Client (explizit): ${client}`);
|
|
722
|
+
}
|
|
723
|
+
lines.push("");
|
|
724
|
+
|
|
725
|
+
const targets = Array.isArray(target) ? target : [target];
|
|
726
|
+
const allActions = [];
|
|
727
|
+
for (const t of targets) {
|
|
728
|
+
if (t === "claude-code") allActions.push(...planClaudeCode(cwd));
|
|
729
|
+
else if (t === "cursor") allActions.push(...planCursor(cwd));
|
|
730
|
+
else {
|
|
731
|
+
// generic / claude-desktop / codex und alles ohne Hook-Mechanismus.
|
|
732
|
+
const heading =
|
|
733
|
+
t === "codex"
|
|
734
|
+
? "Codex CLI:"
|
|
735
|
+
: t === "claude-desktop"
|
|
736
|
+
? "Claude Desktop:"
|
|
737
|
+
: "Generischer Client:";
|
|
738
|
+
lines.push(heading);
|
|
739
|
+
lines.push(" Dieser Client kennt keinen Hook-Mechanismus, der die Pflege HART erzwingt.");
|
|
740
|
+
lines.push(" Es wirken automatisch: die MCP-instructions (werden beim Verbinden gelesen)");
|
|
741
|
+
lines.push(" und die MCP-prompts. Für eine zusätzliche, weiche Memory-First-Regel den");
|
|
742
|
+
lines.push(" folgenden Block in deine System-/Projekt-Anweisung (z. B. AGENTS.md, CLAUDE.md,");
|
|
743
|
+
lines.push(" Custom Instructions) einfügen:");
|
|
744
|
+
lines.push("");
|
|
745
|
+
lines.push(manualSnippet().split("\n").map((l) => " " + l).join("\n"));
|
|
746
|
+
lines.push("");
|
|
747
|
+
}
|
|
748
|
+
}
|
|
749
|
+
|
|
750
|
+
// Plan ausgeben + ggf. anwenden
|
|
751
|
+
if (allActions.length) {
|
|
752
|
+
lines.push("Aktionen:");
|
|
753
|
+
for (const a of allActions) {
|
|
754
|
+
const icon = ICON[a.action] || "?";
|
|
755
|
+
let note = "";
|
|
756
|
+
if (a.action === "skip-foreign") note = ` (übersprungen: ${a.reason})`;
|
|
757
|
+
if (a.action === "unchanged") note = " (bereits aktuell)";
|
|
758
|
+
lines.push(` [${icon}] ${a.label}`);
|
|
759
|
+
lines.push(` ${a.path}${note}`);
|
|
760
|
+
}
|
|
761
|
+
lines.push("");
|
|
762
|
+
if (!dryRun) {
|
|
763
|
+
for (const a of allActions) applyAction(a);
|
|
764
|
+
lines.push("Eingerichtet. Starte deinen KI-Client neu, damit Hooks/Regeln greifen.");
|
|
765
|
+
lines.push(...(await naechsterSchritt()));
|
|
766
|
+
} else {
|
|
767
|
+
lines.push("Dry-Run: keine Datei wurde geändert. Ohne --dry-run erneut ausführen.");
|
|
768
|
+
}
|
|
769
|
+
}
|
|
770
|
+
|
|
771
|
+
return lines.join("\n");
|
|
772
|
+
}
|
|
773
|
+
|
|
774
|
+
/**
|
|
775
|
+
* Der Schritt nach dem Einrichten: Wissen hineinbringen.
|
|
776
|
+
*
|
|
777
|
+
* WARUM (09.08.2026): Bis hierher endete `init` mit „Eingerichtet." — und der
|
|
778
|
+
* Nutzer stand vor einem LEEREN Gedächtnis. Die Technik lief, der erste Recall
|
|
779
|
+
* lieferte nichts, und ohne Treffer sieht niemand einen Nutzen. Genau so verlief
|
|
780
|
+
* die erste externe Anmeldung: Konto angelegt, zwei Minuten geblieben, nie
|
|
781
|
+
* wiedergekommen.
|
|
782
|
+
*
|
|
783
|
+
* Eine Einrichtung, die den Bestand nicht anspricht, ist auf halbem Weg stehen
|
|
784
|
+
* geblieben. Deshalb prüft init jetzt den Füllstand und nennt bei leerem
|
|
785
|
+
* Arbeitsbereich den einen Befehl, der ihn in Minuten füllt.
|
|
786
|
+
*
|
|
787
|
+
* Best-effort: Ist die Plattform nicht erreichbar oder fehlt der Token, bleibt
|
|
788
|
+
* der Hinweis allgemein. Die Einrichtung selbst darf daran nie scheitern.
|
|
789
|
+
*/
|
|
790
|
+
async function naechsterSchritt(statsFn) {
|
|
791
|
+
const zeilen = ["", "Nächster Schritt — Wissen hineinbringen:"];
|
|
792
|
+
let leer = true;
|
|
793
|
+
try {
|
|
794
|
+
const hole = statsFn ?? (await import("./client.js")).stats;
|
|
795
|
+
const s = await hole();
|
|
796
|
+
const anzahl = Number(s?.memories ?? s?.documents ?? 0);
|
|
797
|
+
leer = !(anzahl > 0);
|
|
798
|
+
if (!leer) {
|
|
799
|
+
zeilen.push(` Ihr Arbeitsbereich enthält bereits ${anzahl} Einträge — Sie sind startklar.`);
|
|
800
|
+
zeilen.push(" Neue Ordner jederzeit nachziehen: knowmind sync <ordner>");
|
|
801
|
+
return zeilen;
|
|
802
|
+
}
|
|
803
|
+
} catch {
|
|
804
|
+
// Plattform nicht erreichbar: Hinweis trotzdem geben, er schadet nie.
|
|
805
|
+
}
|
|
806
|
+
|
|
807
|
+
zeilen.push(" Ihr Gedächtnis ist noch leer. Ohne Inhalt findet die KI nichts,");
|
|
808
|
+
zeilen.push(" und der erste Versuch endet enttäuschend. Zwei Wege, beide dauern Minuten:");
|
|
809
|
+
zeilen.push("");
|
|
810
|
+
zeilen.push(" 1. Vorhandene Unterlagen einlesen (Markdown, Text):");
|
|
811
|
+
zeilen.push(" knowmind sync ./docs");
|
|
812
|
+
zeilen.push(" Wiederholtes Einlesen ändert nichts doppelt — erkannt über den Inhalt.");
|
|
813
|
+
zeilen.push("");
|
|
814
|
+
zeilen.push(" 2. Der KI im Gespräch etwas zum Behalten geben, zum Beispiel:");
|
|
815
|
+
zeilen.push(" „Merk dir in knowmind: Unsere Berichte prüft das Qualitätsmanagement,");
|
|
816
|
+
zeilen.push(" bevor sie an Kunden gehen.“");
|
|
817
|
+
zeilen.push(" Danach in einer neuen Sitzung danach fragen — die Antwort kommt aus dem Gedächtnis.");
|
|
818
|
+
return zeilen;
|
|
819
|
+
}
|
|
820
|
+
|
|
821
|
+
// Für Tests exportiert.
|
|
822
|
+
export const _internals = {
|
|
823
|
+
naechsterSchritt,
|
|
824
|
+
upsertMarkedBlock,
|
|
825
|
+
writeOwnFile,
|
|
826
|
+
ensureClaudeHookEntry,
|
|
827
|
+
detectClients,
|
|
828
|
+
memoryFirstBlock,
|
|
829
|
+
BEGIN,
|
|
830
|
+
END,
|
|
831
|
+
};
|