knowmind 0.4.4 → 0.4.6

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.6 (2026-11-01)
4
+
5
+ - Verbesserungen der Stabilität.
6
+
7
+ ## 0.4.5 (2026-10-16)
8
+
9
+ - Verbesserungen der Stabilität.
10
+
3
11
  ## 0.4.4 (2026-10-16)
4
12
 
5
13
  - Verbesserungen der Stabilität.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "knowmind",
3
- "version": "0.4.4",
3
+ "version": "0.4.6",
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",
@@ -44,7 +44,26 @@ async function registryLatest() {
44
44
  const cmp = (a, b) => a.localeCompare(b, undefined, { numeric: true });
45
45
 
46
46
  const npmV = await npmLatest();
47
- const regV = await registryLatest();
47
+ let regV = await registryLatest();
48
+
49
+ // Warten auf die Registry (REGISTRY_WARTEN_S, nur Endkontrolle in CI).
50
+ //
51
+ // WARUM (16.10.2026, CRM 99c79e7d): Jeder rote Lauf seit dem 09.10. hatte
52
+ // denselben Ablauf. Der Publish meldete „Successfully published“, und die
53
+ // Endkontrolle eine halbe Sekunde später las aus der Liste der Registry noch
54
+ // die alte Fassung als neueste. Ein bis zwei Minuten später war der Lauf grün.
55
+ // Die Liste zieht nach dem Publish verzögert nach; das ist eine Reihenfolge,
56
+ // keine Drift. Gewartet wird nur, wenn alles andere stimmt und allein die
57
+ // Registry eine ältere Fassung meldet, und nur bis zur Frist.
58
+ const wartenS = Number(process.env.REGISTRY_WARTEN_S || 0);
59
+ if (wartenS > 0 && regV !== npmV && sj.version === npmV) {
60
+ const ende = Date.now() + wartenS * 1000;
61
+ while (regV !== npmV && Date.now() < ende) {
62
+ console.log(` … MCP-Registry meldet ${regV ?? "nichts"}, warte auf ${npmV}`);
63
+ await new Promise((r) => setTimeout(r, 10000));
64
+ regV = await registryLatest();
65
+ }
66
+ }
48
67
 
49
68
  const fehler = [];
50
69
  const warnung = [];
package/src/install.js CHANGED
@@ -274,21 +274,30 @@ function meldung(ide, path, { ergebnis, sicherung }) {
274
274
  return `✓ ${ide.label}: knowmind-Eintrag in ${path} aktualisiert (Sicherung: ${sicherung})`;
275
275
  }
276
276
 
277
- function printClaudeCodeCommand(opts) {
277
+ // Der Name steht vor den --env-Angaben. `-e, --env <env...>` nimmt beliebig
278
+ // viele Werte; stand der Name dahinter (bis 0.4.4), las Claude Code ihn als
279
+ // weitere Variable und brach ab: „Invalid environment variable format:
280
+ // knowmind“ (gemessen 16.10.2026 mit Claude Code 2.1.301). So steht es auch im
281
+ // Beispiel von `claude mcp add --help`: Name, dann -e, dann `--` und der Befehl.
282
+ function claudeCodeBefehl(opts) {
278
283
  const tokenArg = opts.literalToken ? opts.literalToken : "$KNOWMIND_TOKEN";
279
- console.log("Claude Code (User-Scope, alle Projekte) — diesen Befehl ausführen:\n");
280
- console.log(
281
- ` claude mcp add --scope user --transport stdio \\\n` +
282
- ` --env KNOWMIND_TOKEN=${tokenArg} \\\n` +
283
- ` --env KNOWMIND_API_URL=${opts.apiUrl} \\\n` +
284
- ` knowmind -- npx -y knowmind mcp\n`,
284
+ return (
285
+ ` claude mcp add --scope user --transport stdio knowmind \\\n` +
286
+ ` --env KNOWMIND_TOKEN=${tokenArg} \\\n` +
287
+ ` --env KNOWMIND_API_URL=${opts.apiUrl} \\\n` +
288
+ ` -- npx -y knowmind mcp\n`
285
289
  );
290
+ }
291
+
292
+ function printClaudeCodeCommand(opts) {
293
+ console.log("Claude Code (User-Scope, alle Projekte) — diesen Befehl ausführen:\n");
294
+ console.log(claudeCodeBefehl(opts));
286
295
  console.log("Für ein einzelnes Projekt stattdessen: knowmind install claude-code --project\n");
287
296
  }
288
297
 
289
298
  // Für die Prüffälle (src/starterpfad.test.js, src/install.test.js): Sie decken
290
299
  // jeden Client ab, den diese Liste kennt, auch einen, der später dazukommt.
291
- export const _internals = { IDES, serverEntry, mergeInto, mergeToml, startBefehl, findePythonwFuerMcp };
300
+ export const _internals = { IDES, serverEntry, mergeInto, mergeToml, startBefehl, findePythonwFuerMcp, claudeCodeBefehl };
292
301
 
293
302
  // ── Hauptbefehl ─────────────────────────────────────────────────────────────
294
303
  // `cwd` und `umgebung` nur für Prüffälle.
@@ -16,6 +16,7 @@
16
16
  import { homedir } from "node:os";
17
17
  import { join } from "node:path";
18
18
  import { mkdirSync, existsSync } from "node:fs";
19
+ import { zerlegen } from "./ueberschriftenschnitt.js";
19
20
 
20
21
  const MODEL_ID = process.env.KNOWMIND_EMBED_MODEL || "Xenova/multilingual-e5-large";
21
22
  const TARGET_DIM = 1024;
@@ -52,14 +53,12 @@ export async function warmup() {
52
53
  }
53
54
 
54
55
  /**
55
- * Zerlegt Text in Chunks identisch zum Server-Default (1200 Zeichen).
56
+ * Zerlegt Text in Chunks wie der Server: Markdown ein Ausschnitt je
57
+ * Abschnitt, anderer Text alle 1200 Zeichen (./ueberschriftenschnitt.js).
58
+ * Leerer Text ergibt wie bisher einen leeren Ausschnitt.
56
59
  */
57
60
  export function chunkText(text, size = CHUNK_TARGET) {
58
- const out = [];
59
- for (let i = 0; i < text.length; i += size) {
60
- const seg = text.slice(i, i + size);
61
- if (seg.trim()) out.push(seg);
62
- }
61
+ const out = zerlegen(text, size);
63
62
  return out.length > 0 ? out : [""];
64
63
  }
65
64
 
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "_hinweis": "Rückfall für tools/list, wenn die Discovery nicht erreichbar ist. Erzeugt aus https://knowmind.de/api/mcp/v1. Abgleich: npm run tools:abgleich",
3
- "stand": "2026-10-16",
3
+ "stand": "2026-11-01",
4
4
  "quelle": "https://knowmind.de/api/mcp/v1",
5
5
  "protocolVersion": "2025-06-18",
6
6
  "tools": [
@@ -13,7 +13,7 @@
13
13
  "idempotentHint": true,
14
14
  "openWorldHint": false
15
15
  },
16
- "description": "Retrieve relevant knowledge before answering anything that benefits from prior context - decisions, preferences, project state, people, deadlines, past conversations. Hybrid recall (BM25 + pgvector + knowledge graph) over the tenant corpus; returns the top-k memory chunks, each with a relevance score and source reference. Suitable whenever earlier context would improve the answer; use knowmind_recall_at_time when you need what was valid at a past point in time. Passages from pages in Open Knowledge Format carry metadata.review_flags: stale once stale_after is reached, unverified when no verification is recorded, superseded when the page's status is deprecated or superseded or its valid_to is reached, drifted when code cited by the page's claims changed or was removed since the page was written; an empty list means none applies. Read scope suffices.",
16
+ "description": "Retrieve relevant knowledge before answering anything that benefits from prior context - decisions, preferences, project state, people, deadlines, past conversations. Hybrid recall (BM25 + pgvector + knowledge graph) over the tenant corpus; returns the top-k memory chunks, each with a relevance score and source reference. Suitable whenever earlier context would improve the answer; use knowmind_recall_at_time when you need what was valid at a past point in time. Passages from pages in Open Knowledge Format carry metadata.review_flags: stale once stale_after is reached, unverified when no verification is recorded, superseded when the page's status is deprecated or superseded or its valid_to is reached, drifted when code cited by the page's claims changed or was removed since the page was written; an empty list means none applies. When kein_belastbarer_treffer is true, the corpus most likely holds no answer; unless the hits clearly answer the question, say so. Read scope suffices.",
17
17
  "inputSchema": {
18
18
  "type": "object",
19
19
  "properties": {
@@ -103,7 +103,7 @@
103
103
  "idempotentHint": false,
104
104
  "openWorldHint": false
105
105
  },
106
- "description": "Store durable insights the moment they arise - decisions, preferences, facts, results, appointments. Persists one memory entry in the tenant corpus (Postgres + vector index + graph node), afterwards findable via knowmind_recall and knowmind_list_recent. Append-only: the same title replaces nothing (use knowmind_update_fact to supersede); sha-identical content is detected as idempotent (unchanged). Returns the new memory id. Use for a single short fact; for long or multi-fact text use knowmind_upload_document. GIVE THE EDGES ALONG: whatever the text says about people, organisations, projects, hosts or technologies belongs into `relations` in THIS call - name the counterpart, the server creates its node and the edge, no second call needed. A memory without edges is a note; with edges it becomes a graph that answers questions nobody wrote down. Use knowmind_link separately only to connect two entries that already exist. ENTRIES ARE NEVER HARD-DELETED, they are superseded: correct a fact with knowmind_update_fact, remove an edge with knowmind_unlink_entities. Both keep the history auditable, which is the point of this store - what was true when, and when that changed. Requires write scope.",
106
+ "description": "Store durable insights the moment they arise - decisions, preferences, facts, results, appointments. Persists one memory entry in the tenant corpus (Postgres + vector index + graph node), afterwards findable via knowmind_recall and knowmind_list_recent. Always creates a new entry; an earlier entry with the same title stays valid, because titles do not identify entries here (to supersede, use knowmind_update_fact, or knowmind_upload_document, which replaces by title); sha-identical content is detected as idempotent (unchanged). Returns the new memory id. Use for a single short fact; for long or multi-fact text use knowmind_upload_document. GIVE THE EDGES ALONG: whatever the text says about people, organisations, projects, hosts or technologies belongs into `relations` in THIS call - name the counterpart, the server creates its node and the edge, no second call needed. A memory without edges is a note; with edges it becomes a graph that answers questions nobody wrote down. Use knowmind_link separately only to connect two entries that already exist. ENTRIES ARE NEVER HARD-DELETED, they are superseded: correct a fact with knowmind_update_fact, remove an edge with knowmind_unlink_entities. Both keep the history auditable, which is the point of this store - what was true when, and when that changed. Requires write scope.",
107
107
  "inputSchema": {
108
108
  "type": "object",
109
109
  "properties": {
@@ -189,13 +189,13 @@
189
189
  "idempotentHint": false,
190
190
  "openWorldHint": false
191
191
  },
192
- "description": "Ingest a longer text as one document into the tenant corpus: chunk splitting, embeddings, vector chunks and graph nodes. Upsert-by-title: if a document with the same title exists, the new version replaces the old one (server default). Use for long-form or multi-fact content (a report, a page, a doc); for a single short fact use knowmind_store_memory. Returns the document id and the number of chunks written. AFTER INGESTING: extract the facts the text states about people, organisations, projects, products, technologies and hosts, and create the corresponding edges via knowmind_link. Requires write scope.",
192
+ "description": "Ingest a longer text as one document into the tenant corpus: chunk splitting, embeddings, vector chunks and graph nodes. Upsert-by-title (server default): if a valid document with the same title exists in the same domain, the new version supersedes it; the old version stays retrievable via knowmind_recall_at_time, and the superseded ids come back in replaced_document_ids. If the same text already exists in another valid document of the same domain, no new document is created and the response carries deduplicated. Use for long-form or multi-fact content (a report, a page, a doc); for a single short fact use knowmind_store_memory. Returns the document id and the number of chunks written. AFTER INGESTING: extract the facts the text states about people, organisations, projects, products, technologies and hosts, and create the corresponding edges via knowmind_link. Requires write scope.",
193
193
  "inputSchema": {
194
194
  "type": "object",
195
195
  "properties": {
196
196
  "title": {
197
197
  "type": "string",
198
- "description": "Document title. Acts as the upsert key - an existing document with the same title is replaced."
198
+ "description": "Document title. Unless replace is false, it identifies the document: a valid document with the same title in the same domain is superseded and stays retrievable via knowmind_recall_at_time."
199
199
  },
200
200
  "content": {
201
201
  "type": "string",
@@ -203,7 +203,11 @@
203
203
  },
204
204
  "source": {
205
205
  "type": "string",
206
- "description": "Origin - URL or file path. Free text, stored for provenance."
206
+ "description": "Origin, a URL or file path. Free text appended to the content for provenance; it does not decide which document is superseded."
207
+ },
208
+ "replace": {
209
+ "type": "boolean",
210
+ "description": "Default on knowmind.de: true, supersede the valid document with the same title in the same domain. false: store as a new document next to it."
207
211
  },
208
212
  "relations": {
209
213
  "type": "array",
@@ -281,6 +285,37 @@
281
285
  ]
282
286
  }
283
287
  },
288
+ {
289
+ "name": "knowmind_end_fact",
290
+ "annotations": {
291
+ "title": "End fact",
292
+ "readOnlyHint": false,
293
+ "destructiveHint": false,
294
+ "idempotentHint": true,
295
+ "openWorldHint": false
296
+ },
297
+ "description": "End an entry that no longer applies and that nothing replaces (a project closed, a source withdrawn): the entry gets valid_to (now, or the given time) and drops out of knowmind_recall, while knowmind_recall_at_time before that time still finds it. Nothing is deleted and no new entry is created. When a newer statement replaces the entry, use knowmind_update_fact instead. Calling it again changes nothing. Requires write scope.",
298
+ "inputSchema": {
299
+ "type": "object",
300
+ "properties": {
301
+ "target_id": {
302
+ "type": "string",
303
+ "description": "ID of the entry to end; get it via knowmind_recall - never invent it."
304
+ },
305
+ "valid_to": {
306
+ "type": "string",
307
+ "description": "ISO-8601 time with time zone from which the entry no longer applies; defaults to now. Example: '2026-10-11T22:10:00+02:00'."
308
+ },
309
+ "reason": {
310
+ "type": "string",
311
+ "description": "Why it ends (e.g. 'source withdrawn'); stored with the entry."
312
+ }
313
+ },
314
+ "required": [
315
+ "target_id"
316
+ ]
317
+ }
318
+ },
284
319
  {
285
320
  "name": "knowmind_recall_at_time",
286
321
  "annotations": {
@@ -290,7 +325,7 @@
290
325
  "idempotentHint": true,
291
326
  "openWorldHint": false
292
327
  },
293
- "description": "Time-travel recall: return only memories that were valid at a given instant (valid_from <= as_of <= valid_to, or still open). Answers 'what did the agent know on March 14?'. Use instead of knowmind_recall when the point in time matters; otherwise use knowmind_recall for the current truth. Passages from pages in Open Knowledge Format carry metadata.review_flags (stale, unverified, superseded, drifted); stale and superseded are judged against as_of. Read scope suffices.",
328
+ "description": "Time-travel recall: return only memories that were valid at a given instant (valid_from <= as_of <= valid_to, or still open). Answers 'what did the agent know on March 14?'. Use instead of knowmind_recall when the point in time matters; otherwise use knowmind_recall for the current truth. Passages from pages in Open Knowledge Format carry metadata.review_flags (stale, unverified, superseded, drifted); stale and superseded are judged against as_of. When kein_belastbarer_treffer is true, the corpus as of as_of most likely holds no answer; it is judged on the hits visible at as_of. Unless they clearly answer the question, say so. Read scope suffices.",
294
329
  "inputSchema": {
295
330
  "type": "object",
296
331
  "properties": {
@@ -414,13 +449,13 @@
414
449
  {
415
450
  "name": "knowmind_unlink_entities",
416
451
  "annotations": {
417
- "title": "Remove relation",
452
+ "title": "End relation",
418
453
  "readOnlyHint": false,
419
454
  "destructiveHint": true,
420
455
  "idempotentHint": true,
421
456
  "openWorldHint": false
422
457
  },
423
- "description": "Delete a typed relation between two memory nodes; the inverse edge is removed with it. Idempotent - deleting a non-existent edge is a no-op. Use to correct a wrong link created via knowmind_link. Requires write scope.",
458
+ "description": "End a relation between two memories; inverse and inferred edges end with it. It stays in history, where knowmind_recall_at_time finds it. Repeating it does nothing. Fixes a wrong knowmind_link. Requires write scope.",
424
459
  "inputSchema": {
425
460
  "type": "object",
426
461
  "properties": {
@@ -551,7 +586,7 @@
551
586
  "idempotentHint": true,
552
587
  "openWorldHint": false
553
588
  },
554
- "description": "DEPRECATED, removed on 2027-03-31: use knowmind_recall_memories. This name keeps answering unchanged until then. Retrieve relevant knowledge before answering anything that benefits from prior context - decisions, preferences, project state, people, deadlines, past conversations. Hybrid recall (BM25 + pgvector + knowledge graph) over the tenant corpus; returns the top-k memory chunks, each with a relevance score and source reference. Suitable whenever earlier context would improve the answer; use knowmind_recall_at_time when you need what was valid at a past point in time. Passages from pages in Open Knowledge Format carry metadata.review_flags: stale once stale_after is reached, unverified when no verification is recorded, superseded when the page's status is deprecated or superseded or its valid_to is reached, drifted when code cited by the page's claims changed or was removed since the page was written; an empty list means none applies. Read scope suffices.",
589
+ "description": "DEPRECATED, removed on 2027-03-31: use knowmind_recall_memories. This name keeps answering unchanged until then. Retrieve relevant knowledge before answering anything that benefits from prior context - decisions, preferences, project state, people, deadlines, past conversations. Hybrid recall (BM25 + pgvector + knowledge graph) over the tenant corpus; returns the top-k memory chunks, each with a relevance score and source reference. Suitable whenever earlier context would improve the answer; use knowmind_recall_at_time when you need what was valid at a past point in time. Passages from pages in Open Knowledge Format carry metadata.review_flags: stale once stale_after is reached, unverified when no verification is recorded, superseded when the page's status is deprecated or superseded or its valid_to is reached, drifted when code cited by the page's claims changed or was removed since the page was written; an empty list means none applies. When kein_belastbarer_treffer is true, the corpus most likely holds no answer; unless the hits clearly answer the question, say so. Read scope suffices.",
555
590
  "inputSchema": {
556
591
  "type": "object",
557
592
  "properties": {
@@ -708,13 +743,13 @@
708
743
  {
709
744
  "name": "knowmind_unlink",
710
745
  "annotations": {
711
- "title": "Remove relation (deprecated)",
746
+ "title": "End relation (deprecated)",
712
747
  "readOnlyHint": false,
713
748
  "destructiveHint": true,
714
749
  "idempotentHint": true,
715
750
  "openWorldHint": false
716
751
  },
717
- "description": "DEPRECATED, removed on 2027-03-31: use knowmind_unlink_entities. This name keeps answering unchanged until then. Delete a typed relation between two memory nodes; the inverse edge is removed with it. Idempotent - deleting a non-existent edge is a no-op. Use to correct a wrong link created via knowmind_link. Requires write scope.",
752
+ "description": "DEPRECATED, removed on 2027-03-31: use knowmind_unlink_entities. This name keeps answering unchanged until then. End a relation between two memories; inverse and inferred edges end with it. It stays in history, where knowmind_recall_at_time finds it. Repeating it does nothing. Fixes a wrong knowmind_link. Requires write scope.",
718
753
  "inputSchema": {
719
754
  "type": "object",
720
755
  "properties": {
@@ -0,0 +1,155 @@
1
+ /**
2
+ * Schneidet Markdown an Überschriften: ein Ausschnitt je Abschnitt.
3
+ *
4
+ * Gleiche Regel wie im Dienst (`services/memory/app/ueberschriftenschnitt.py`
5
+ * in soviq-platform); beide prüfen sich gegen
6
+ * `test/fixtures/ueberschriftenschnitt_faelle.json`. Bis 0.4.5 schnitt die
7
+ * Kommandozeile alle 1.200 Zeichen. In den Kompendien begann der Ausschnitt
8
+ * einer Regel dadurch mitten in der Regel davor, und die Nachsortierung, die
9
+ * nur die ersten 500 Zeichen liest, sah sie nicht.
10
+ *
11
+ * - Jede Überschrift (# bis ######, außerhalb von Codeblöcken) beginnt einen
12
+ * eigenen Ausschnitt; benachbarte Abschnitte werden nicht zusammengelegt.
13
+ * - Ein Abschnitt unter MINDEST Zeichen wandert zum folgenden.
14
+ * - Lange Abschnitte werden an Leerzeilen geteilt, dann an Zeilenenden, zuletzt hart.
15
+ * - Kopfdaten (--- … ---) bleiben mit dem Vorspann vorn.
16
+ * - Die Ausschnitte hintereinander ergeben den Text Zeichen für Zeichen.
17
+ * - Text ohne Überschrift und ohne Kopfdaten schneidet fest wie bisher.
18
+ *
19
+ * Längen zählen Unicode-Zeichen wie Python, nicht UTF-16-Einheiten: Sonst
20
+ * schnitte ein Emoji die Grenze anders als der Dienst und könnte ein
21
+ * Ersatzzeichenpaar zerreißen.
22
+ */
23
+ export const ZIEL = 1200;
24
+ export const MINDEST = 200;
25
+
26
+ const UEBERSCHRIFT = /^#{1,6}[ \t]+[^ \t\r\n\f\v]/;
27
+ const ZAUN = /^[ \t]*(```|~~~)/;
28
+ const KOPFDATEN = /^---[ \t]*\r?\n[\s\S]*?\r?\n---[ \t]*(?:\r?\n|$)/;
29
+ const LEERZEILE = /\n[ \t\r]*\n/g;
30
+ // Leerraum ausdrücklich, wie im Dienst: trim() zählt andere Zeichen dazu als Pythons strip().
31
+ const RAND = /^[ \t\n\r\f\v]+|[ \t\n\r\f\v]+$/g;
32
+
33
+ const rumpf = (s) => s.replace(RAND, "");
34
+ const laenge = (s) => {
35
+ let n = 0;
36
+ for (const _ of s) n++;
37
+ return n;
38
+ };
39
+
40
+ /** Der bisherige Schnitt: alle `groesse` Zeichen, leere Stücke fallen weg. */
41
+ export function fest(text, groesse = ZIEL) {
42
+ const z = Array.from(text);
43
+ const aus = [];
44
+ for (let i = 0; i < z.length; i += groesse) {
45
+ const seg = z.slice(i, i + groesse).join("");
46
+ if (rumpf(seg)) aus.push(seg);
47
+ }
48
+ return aus;
49
+ }
50
+
51
+ function zeilen(text) {
52
+ return text.split(/(?<=\n)/).filter((z) => z);
53
+ }
54
+
55
+ /** Kopfdaten am Anfang oder eine Überschrift außerhalb eines Codeblocks. */
56
+ export function istMarkdown(text) {
57
+ if (KOPFDATEN.test(text)) return true;
58
+ let zaun = false;
59
+ for (const zeile of zeilen(text)) {
60
+ if (ZAUN.test(zeile)) zaun = !zaun;
61
+ else if (!zaun && UEBERSCHRIFT.test(zeile)) return true;
62
+ }
63
+ return false;
64
+ }
65
+
66
+ function abschnitte(text) {
67
+ const teile = [];
68
+ let aktuell = "";
69
+ let zaun = false;
70
+ for (const zeile of zeilen(text)) {
71
+ if (ZAUN.test(zeile)) zaun = !zaun;
72
+ else if (!zaun && UEBERSCHRIFT.test(zeile) && aktuell) {
73
+ teile.push(aktuell);
74
+ aktuell = "";
75
+ }
76
+ aktuell += zeile;
77
+ }
78
+ if (aktuell) teile.push(aktuell);
79
+ return teile;
80
+ }
81
+
82
+ function hart(text, groesse) {
83
+ let z = Array.from(text);
84
+ const stuecke = [];
85
+ while (z.length > groesse) {
86
+ let schnitt = z.lastIndexOf("\n", groesse - 1) + 1;
87
+ if (schnitt <= Math.floor(groesse / 3)) schnitt = groesse;
88
+ stuecke.push(z.slice(0, schnitt).join(""));
89
+ z = z.slice(schnitt);
90
+ }
91
+ if (z.length) stuecke.push(z.join(""));
92
+ return stuecke;
93
+ }
94
+
95
+ function langTeilen(text, groesse) {
96
+ if (laenge(text) <= groesse) return [text];
97
+ const grenzen = [0];
98
+ for (const m of text.matchAll(LEERZEILE)) grenzen.push(m.index + m[0].length);
99
+ grenzen.push(text.length);
100
+ const absaetze = [];
101
+ for (let i = 0; i + 1 < grenzen.length; i++) {
102
+ if (grenzen[i + 1] > grenzen[i]) absaetze.push(text.slice(grenzen[i], grenzen[i + 1]));
103
+ }
104
+ const stuecke = [];
105
+ let puffer = "";
106
+ for (const absatz of absaetze) {
107
+ // Ein kurzer Puffer (etwa die Überschrift allein) bleibt beim folgenden Absatz.
108
+ if (puffer && laenge(puffer) + laenge(absatz) > groesse && laenge(rumpf(puffer)) >= MINDEST) {
109
+ stuecke.push(puffer);
110
+ puffer = "";
111
+ }
112
+ puffer += absatz;
113
+ if (laenge(puffer) > groesse) {
114
+ const teile = hart(puffer, groesse);
115
+ puffer = teile.pop();
116
+ stuecke.push(...teile);
117
+ }
118
+ }
119
+ if (puffer) stuecke.push(puffer);
120
+ return stuecke;
121
+ }
122
+
123
+ /** Die Ausschnitte eines Textes für das Hochladen. Leerer Text ergibt keinen. */
124
+ export function zerlegen(text, groesse = ZIEL) {
125
+ if (!text || !rumpf(text)) return [];
126
+ if (!istMarkdown(text)) return fest(text, groesse);
127
+
128
+ const m = text.match(KOPFDATEN);
129
+ const kopf = m ? m[0] : "";
130
+ const teile = abschnitte(m ? text.slice(m[0].length) : text);
131
+ const roh = [];
132
+ let offen = kopf;
133
+ teile.forEach((t, i) => {
134
+ const abschnitt = offen + t;
135
+ offen = "";
136
+ if (laenge(rumpf(abschnitt)) < MINDEST && i + 1 < teile.length) {
137
+ offen = abschnitt;
138
+ return;
139
+ }
140
+ roh.push(...langTeilen(abschnitt, groesse));
141
+ });
142
+ if (offen) roh.push(offen);
143
+
144
+ // Reiner Leerraum hängt am Ausschnitt davor, damit der Wortlaut vollständig bleibt.
145
+ let aus = [];
146
+ for (const stueck of roh) {
147
+ if (!rumpf(stueck) && aus.length) aus[aus.length - 1] += stueck;
148
+ else if (rumpf(stueck) || !aus.length) aus.push(stueck);
149
+ }
150
+ if (aus.length && !rumpf(aus[0])) {
151
+ if (aus.length > 1) aus[1] = aus[0] + aus[1];
152
+ aus = aus.slice(1);
153
+ }
154
+ return aus;
155
+ }