kongbrain 0.3.8 → 0.3.10

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/README.npm.md ADDED
@@ -0,0 +1,400 @@
1
+ # KongBrain
2
+
3
+ [![npm](https://img.shields.io/npm/v/kongbrain?style=for-the-badge&logo=npm&color=cb3837)](https://www.npmjs.com/package/kongbrain)
4
+ [![ClawHub](https://img.shields.io/badge/ClawHub-kongbrain-ff6b35?style=for-the-badge)](https://clawhub.ai/packages/kongbrain)
5
+ [![GitHub Stars](https://img.shields.io/github/stars/42U/kongbrain?style=for-the-badge&logo=github&color=gold)](https://github.com/42U/kongbrain)
6
+ [![License: MIT](https://img.shields.io/github/license/42U/kongbrain?style=for-the-badge&logo=opensourceinitiative&color=blue)](https://opensource.org/licenses/MIT)
7
+ [![Node.js](https://img.shields.io/badge/Node.js-20+-339933?style=for-the-badge&logo=node.js&logoColor=white)](https://nodejs.org)
8
+ [![SurrealDB](https://img.shields.io/badge/SurrealDB-3.0-ff00a0?style=for-the-badge&logo=surrealdb&logoColor=white)](https://surrealdb.com)
9
+ [![OpenClaw](https://img.shields.io/badge/OpenClaw-Plugin-ff6b35?style=for-the-badge)](https://github.com/openclaw/openclaw)
10
+ [![Tests](https://img.shields.io/badge/Tests-88_passing-brightgreen?style=for-the-badge&logo=vitest&logoColor=white)](https://vitest.dev)
11
+
12
+ **A graph-backed cognitive engine for [OpenClaw](https://github.com/openclaw/openclaw).**
13
+
14
+ > *OpenClaw ships with a lobster brain. It works — lobsters have survived 350 million years — but they also solve problems by walking backwards and occasionally eating each other.*
15
+ >
16
+ > *When a conversation gets too long, the lobster brain does what lobsters do best: it panics, truncates everything before message 47, and carries on like nothing happened. Your carefully explained architecture? Gone. That bug you described in detail twenty minutes ago? Never heard of it.*
17
+ >
18
+ > *KongBrain is a brain transplant. You're replacing that crustacean context window with a primate cortex — backed by a graph database, vector embeddings, and the kind of persistent memory that lets your AI remember what you said last Tuesday — and judge you for it.*
19
+
20
+ Persistent memory graph. Vector-embedded, self-scoring, wired to learn across sessions. It extracts skills from what worked, traces causal chains through what broke, reflects on its own failures, and earns an identity through real experience. Every session compounds on the last.
21
+
22
+ Your assistant stops forgetting. Then it starts getting smarter.
23
+
24
+ [Quick Start](#quick-start) | [Architecture](#architecture) | [How It Works](#how-it-works) | [Tools](#tools) | [Development](#development)
25
+
26
+ ---
27
+
28
+ ## What Changes
29
+
30
+ | | Lobster Brain (default) | Ape Brain (KongBrain) |
31
+ |---|---|---|
32
+ | **Memory** | Sliding window. Old messages fall off a cliff. | Graph-persistent. Every turn, concept, skill, and causal chain stored with vector embeddings. |
33
+ | **Recall** | Whatever fits in the context window right now. | Cosine similarity + graph expansion + learned attention scoring across your entire history. |
34
+ | **Adaptation** | Same retrieval budget every turn, regardless of intent. | 10 intent categories. Simple question? Minimal retrieval. Complex debugging? Full graph search + elevated thinking. |
35
+ | **Learning** | None. Every session starts from zero. | Skills extracted from successful workflows, causal chains graduated into reusable procedures, corrections remembered permanently. |
36
+ | **Self-awareness** | Thermostat-level. | Periodic cognitive checks grade its own retrieval quality, detect contradictions, suppress noise, and extract your preferences. Eventually graduates a soul document. |
37
+ | **Compaction** | LLM-summarizes your conversation mid-flow (disruptive). | Graph retrieval IS the compaction. No interruptions, no lossy summaries. |
38
+
39
+ ## Quick Start
40
+
41
+ From zero to ape brain in under 5 minutes.
42
+
43
+ ### 1. Install OpenClaw (if you haven't already)
44
+
45
+ ```bash
46
+ npm install -g openclaw
47
+ ```
48
+
49
+ ### 2. Start SurrealDB
50
+
51
+ Install SurrealDB via your platform's package manager (see [surrealdb.com/install](https://surrealdb.com/docs/surrealdb/installation)):
52
+
53
+ ```bash
54
+ # macOS
55
+ brew install surrealdb/tap/surreal
56
+
57
+ # Linux (Debian/Ubuntu)
58
+ curl -sSf https://install.surrealdb.com | sh
59
+ export PATH="$HOME/.surrealdb:$PATH"
60
+ ```
61
+
62
+ Then start it locally — **change the credentials before use**:
63
+
64
+ ```bash
65
+ surreal start --user youruser --pass yourpass --bind 127.0.0.1:8042 surrealkv:~/.kongbrain/surreal.db
66
+ ```
67
+
68
+ Or with Docker:
69
+
70
+ ```bash
71
+ docker run -d --name surrealdb -p 127.0.0.1:8042:8000 \
72
+ -v ~/.kongbrain/surreal-data:/data \
73
+ surrealdb/surrealdb:latest start \
74
+ --user youruser --pass yourpass surrealkv:/data/surreal.db
75
+ ```
76
+
77
+ > **Security note:** Always bind to `127.0.0.1` (not `0.0.0.0`) unless you need remote access. Never use default credentials in production.
78
+
79
+ ### 3. Install KongBrain
80
+
81
+ ```bash
82
+ # From ClawHub (recommended)
83
+ openclaw plugins install clawhub:kongbrain
84
+
85
+ # From npm (fallback)
86
+ openclaw plugins install kongbrain
87
+ ```
88
+
89
+ > **Note:** Bare `openclaw plugins install kongbrain` checks ClawHub first, then falls back to npm. Use the `clawhub:` prefix to install from ClawHub explicitly.
90
+
91
+ ### 4. Activate
92
+
93
+ Add to your OpenClaw config (`~/.openclaw/openclaw.json`):
94
+
95
+ ```json
96
+ {
97
+ "plugins": {
98
+ "allow": ["kongbrain"],
99
+ "slots": {
100
+ "contextEngine": "kongbrain"
101
+ }
102
+ }
103
+ }
104
+ ```
105
+
106
+ ### 5. Talk to your ape
107
+
108
+ ```bash
109
+ openclaw tui
110
+ ```
111
+
112
+ That's it. KongBrain uses whatever LLM provider and model you already have configured in OpenClaw (Anthropic, OpenAI, Google, Ollama, whatever). No separate API keys needed for the brain itself.
113
+
114
+ The BGE-M3 embedding model (~420MB) downloads automatically on first startup from [Hugging Face](https://huggingface.co/BAAI/bge-m3). All database tables and indexes are created automatically on first run. No manual setup required.
115
+
116
+ <details>
117
+ <summary><strong>Configuration Options</strong></summary>
118
+
119
+ All options have sensible defaults. Override via plugin config or environment variables:
120
+
121
+ | Option | Env Var | Default |
122
+ |--------|---------|---------|
123
+ | `surreal.url` | `SURREAL_URL` | `ws://127.0.0.1:8042/rpc` |
124
+ | `surreal.user` | `SURREAL_USER` | (required) |
125
+ | `surreal.pass` | `SURREAL_PASS` | (required) |
126
+ | `surreal.ns` | `SURREAL_NS` | `kong` |
127
+ | `surreal.db` | `SURREAL_DB` | `memory` |
128
+ | `embedding.modelPath` | `KONGBRAIN_EMBEDDING_MODEL` | Auto-downloaded BGE-M3 Q4_K_M |
129
+ | `embedding.dimensions` | - | `1024` |
130
+
131
+ Full config example:
132
+
133
+ ```json
134
+ {
135
+ "plugins": {
136
+ "allow": ["kongbrain"],
137
+ "slots": {
138
+ "contextEngine": "kongbrain"
139
+ },
140
+ "entries": {
141
+ "kongbrain": {
142
+ "config": {
143
+ "surreal": {
144
+ "url": "ws://127.0.0.1:8042/rpc",
145
+ "user": "youruser",
146
+ "pass": "yourpass",
147
+ "ns": "kong",
148
+ "db": "memory"
149
+ }
150
+ }
151
+ }
152
+ }
153
+ }
154
+ }
155
+ ```
156
+
157
+ </details>
158
+
159
+ ---
160
+
161
+ ## Architecture
162
+
163
+ ### The IKONG Pillars
164
+
165
+ KongBrain's cognitive architecture follows five functional pillars:
166
+
167
+ | Pillar | Role | What it does |
168
+ |--------|------|-------------|
169
+ | **I**ntelligence | Adaptive reasoning | Intent classification, complexity estimation, thinking depth, orchestrator preflight |
170
+ | **K**nowledge | Persistent memory | Memory graph, concepts, skills, reflections, identity chunks, core memory tiers |
171
+ | **O**peration | Execution | Tool orchestration, skill procedures, causal chain tracking, artifact management |
172
+ | **N**etwork | Graph traversal | Cross-pillar edge following, neighbor expansion, causal path walking |
173
+ | **G**raph | Persistence | SurrealDB storage, BGE-M3 vector search, HNSW indexes, embedding pipeline |
174
+
175
+ A 6th pillar, **Persona**, is unlocked at soul graduation: *"You have a Soul, an identity grounded in real experience. Be unique, be genuine, be yourself."*
176
+
177
+ ### Structural Pillars
178
+
179
+ The graph entity model in SurrealDB:
180
+
181
+ | Pillar | Table | What it anchors |
182
+ |--------|-------|-----------------|
183
+ | 1. Agent | `agent` | Who is operating (name, model) |
184
+ | 2. Project | `project` | What we're working on (status, tags) |
185
+ | 3. Task | `task` | Individual sessions as units of work |
186
+ | 4. Artifact | `artifact` | Files and outputs tracked across sessions |
187
+ | 5. Concept | `concept` | Semantic knowledge nodes extracted from sessions |
188
+
189
+ On startup, the agent bootstraps the full chain: `Agent → owns → Project`, `Agent → performed → Task`, `Task → task_part_of → Project`, `Session → session_task → Task`. Graph expansion traverses these edges during retrieval.
190
+
191
+ ### The Knowledge Graph
192
+
193
+ SurrealDB with HNSW vector indexes (1024-dim cosine). Everything is embedded and queryable.
194
+
195
+ | Table | What it stores |
196
+ |-------|---------------|
197
+ | `turn` | Every conversation message (role, text, embedding, token count, model, usage) |
198
+ | `memory` | Compacted episodic knowledge (importance 0-10, confidence, access tracking) |
199
+ | `skill` | Learned procedures with steps, preconditions, success/failure counts |
200
+ | `reflection` | Metacognitive lessons (efficiency, failure patterns, approach strategy) |
201
+ | `causal_chain` | Cause-effect patterns (trigger, outcome, chain type, success, confidence) |
202
+ | `identity_chunk` | Agent self-knowledge fragments (source, importance, embedding) |
203
+ | `monologue` | Thinking traces preserved across sessions |
204
+ | `core_memory` | Tier 0 (always loaded) + Tier 1 (session-pinned) directives |
205
+ | `soul` | Emergent identity document, earned through graduation |
206
+
207
+ <details>
208
+ <summary><strong>Adaptive Reasoning</strong>: per-turn intent classification and budget allocation</summary>
209
+
210
+ Every turn gets classified by intent and assigned an adaptive config:
211
+
212
+ | Intent | Thinking | Tool Limit | Token Budget | Retrieval Share |
213
+ |--------|----------|------------|--------------|-----------------|
214
+ | `simple-question` | low | 3 | 4K | 10% |
215
+ | `code-read` | medium | 5 | 6K | 15% |
216
+ | `code-write` | high | 8 | 8K | 20% |
217
+ | `code-debug` | high | 10 | 8K | 20% |
218
+ | `deep-explore` | medium | 15 | 6K | 15% |
219
+ | `reference-prior` | medium | 5 | 10K | 25% |
220
+ | `meta-session` | low | 2 | 3K | 7% (skip retrieval) |
221
+ | `multi-step` | high | 12 | 8K | 20% |
222
+ | `continuation` | low | 8 | 4K | skip retrieval |
223
+
224
+ **Fast path:** Short inputs (<20 chars, no `?`) skip classification entirely.
225
+ **Confidence gate:** Below 0.40 confidence, falls back to conservative config.
226
+
227
+ </details>
228
+
229
+ <details>
230
+ <summary><strong>Context Injection Pipeline</strong></summary>
231
+
232
+ 1. **Embed** user input via BGE-M3 (or hit prefetch cache at 0.85 cosine threshold)
233
+ 2. **Vector search** across 6 tables (turn, identity_chunk, concept, memory, artifact, monologue)
234
+ 3. **Graph expand**: fetch neighbors via structural + semantic edges, compute cosine similarity
235
+ 4. **Score** all candidates with WMR (Working Memory Ranker):
236
+ ```
237
+ score = W * [similarity, recency, importance, access, neighbor_bonus, utility, reflection_boost]
238
+ ```
239
+ 5. **Budget trim**: inject Tier 0/1 core memory first (15% of context), then ranked results up to 21% retrieval budget
240
+ 6. **Stage** retrieval snapshot for post-hoc quality evaluation
241
+
242
+ </details>
243
+
244
+ <details>
245
+ <summary><strong>ACAN</strong>: learned cross-attention scorer</summary>
246
+
247
+ A ~130K-parameter cross-attention network that replaces the fixed WMR weights once enough data accumulates.
248
+
249
+ - **Activation:** 5,000+ labeled retrieval outcomes
250
+ - **Training:** Pure TypeScript SGD with manual backprop, 80 epochs
251
+ - **Staleness:** Retrains when data grows 50%+ or weights age > 7 days
252
+
253
+ </details>
254
+
255
+ <details>
256
+ <summary><strong>Soul & Graduation</strong>: earned identity, not assigned</summary>
257
+
258
+ The agent earns an identity document through accumulated experience. Graduation requires **all 7 thresholds met** AND a **quality score >= 0.6**:
259
+
260
+ | Signal | Threshold |
261
+ |--------|-----------|
262
+ | Sessions completed | 15 |
263
+ | Reflections stored | 10 |
264
+ | Causal chains traced | 5 |
265
+ | Concepts extracted | 30 |
266
+ | Memory compactions | 5 |
267
+ | Monologue traces | 5 |
268
+ | Time span | 3 days |
269
+
270
+ **Quality scoring** from 4 real performance signals: retrieval utilization (30%), skill success rate (25%), critical reflection rate (25%), tool failure rate (20%).
271
+
272
+ **Maturity stages:** nascent (0-3/7) → developing (4/7) → emerging (5/7) → maturing (6/7) → ready (7/7 + quality gate). The agent and user are notified at each stage transition.
273
+
274
+ **Soul evolution:** Every 10 sessions after graduation, the soul is re-evaluated against new experience and revised if the agent has meaningfully changed.
275
+
276
+ **Soul document structure:** Working style, self-observations, earned values (grounded in specific evidence), revision history. Seeded as Tier 0 core memory, loaded every single turn.
277
+
278
+ </details>
279
+
280
+ <details>
281
+ <summary><strong>Reflection System</strong>: metacognitive self-correction</summary>
282
+
283
+ Triggers at session end when metrics indicate problems:
284
+
285
+ | Condition | Threshold |
286
+ |-----------|-----------|
287
+ | Retrieval utilization | < 20% average |
288
+ | Tool failure rate | > 20% |
289
+ | Steering candidates | any detected |
290
+ | Context waste | > 0.5% of context window |
291
+
292
+ The LLM generates a 2-4 sentence reflection: root cause, error pattern, what to do differently. Stored with importance 7.0, deduped at 0.85 cosine similarity.
293
+
294
+ </details>
295
+
296
+ ---
297
+
298
+ ## How It Works
299
+
300
+ ### Every Turn
301
+
302
+ ```
303
+ User Input
304
+ |
305
+ v
306
+ Preflight ──────── Intent classification (25ms, zero-shot BGE-M3 cosine)
307
+ | 10 categories: simple-question, code-read, code-write,
308
+ | code-debug, deep-explore, reference-prior, meta-session,
309
+ | multi-step, continuation, unknown
310
+ v
311
+ Prefetch ────────── Predictive background vector searches (LRU cache, 5-min TTL)
312
+ |
313
+ v
314
+ Context Injection ─ Vector search -> graph expand -> 6-signal scoring -> budget trim
315
+ | Searches: turns, concepts, memories, artifacts, identity, monologues
316
+ | Scores: similarity, recency, importance, access, neighbor, utility
317
+ | Budget: 21% of context window reserved for retrieval
318
+ v
319
+ Agent Loop ──────── LLM + tool execution
320
+ | Planning gate: announces plan before touching tools
321
+ | Smart truncation: preserves tail of large tool outputs
322
+ v
323
+ Turn Storage ────── Every message embedded + stored + linked via graph edges
324
+ | responds_to, part_of, mentions, produced
325
+ v
326
+ Quality Eval ────── Measures retrieval utilization (text overlap, trigrams, unigrams)
327
+ | Tracks tool success, context waste, feeds ACAN training
328
+ v
329
+ Memory Daemon ───── Worker thread extracts 9 knowledge types via LLM:
330
+ | causal chains, monologues, concepts, corrections,
331
+ | preferences, artifacts, decisions, skills, resolved memories
332
+ v
333
+ Postflight ──────── Records orchestrator metrics (non-blocking)
334
+ ```
335
+
336
+ ### Between Sessions
337
+
338
+ At session end, KongBrain runs a combined extraction pass: skill graduation, metacognitive reflection, causal chain consolidation, soul graduation check, and soul evolution. A handoff note is written so the next session wakes up knowing what happened.
339
+
340
+ At session start, a wake-up briefing is synthesized from the handoff, recent monologues, soul content (if graduated), and identity state, then injected as inner speech so the agent knows who it is and what it was doing.
341
+
342
+ <details>
343
+ <summary><strong>Memory Daemon</strong>: background knowledge extraction</summary>
344
+
345
+ A worker thread running throughout the session. Batches turns every ~12K tokens, calls the configured LLM to extract:
346
+
347
+ - **Causal chains**: trigger/outcome sequences with success/confidence
348
+ - **Monologue traces**: thinking blocks that reveal problem-solving approach
349
+ - **Concepts**: semantic nodes (architecture patterns, domain terms)
350
+ - **Corrections**: user-provided fixes (importance: 9)
351
+ - **Preferences**: behavioral rules learned from feedback
352
+ - **Artifacts**: file paths created or modified
353
+ - **Decisions**: important conclusions reached
354
+ - **Skills**: multi-step procedures (if 5+ tool calls in session)
355
+ - **Resolved memories**: completed tasks and confirmed facts
356
+
357
+ </details>
358
+
359
+ ---
360
+
361
+ ## Tools
362
+
363
+ Three tools are registered for the LLM:
364
+
365
+ - **`recall`**: Search graph memory by query
366
+ - **`core_memory`**: Read/write persistent core directives (tiered: always-loaded vs session-pinned)
367
+ - **`introspect`**: Inspect database state, verify memory counts, run diagnostics, check graduation status, migrate workspace files
368
+
369
+ ---
370
+
371
+ ## Development
372
+
373
+ ```bash
374
+ git clone https://github.com/42U/kongbrain.git
375
+ cd kongbrain
376
+ pnpm install
377
+ pnpm build
378
+ pnpm test
379
+ ```
380
+
381
+ Link your local build to OpenClaw:
382
+
383
+ ```bash
384
+ openclaw plugins install . --link
385
+ ```
386
+
387
+ Then set `plugins.slots.contextEngine` to `"kongbrain"` in `~/.openclaw/openclaw.json` and run `openclaw`.
388
+
389
+ ## Contributing
390
+
391
+ 1. Clone the repo and install dependencies (`pnpm install`)
392
+ 2. Make your changes
393
+ 3. Build (`pnpm build`) and run tests (`pnpm test`)
394
+ 4. Open a PR against `master`
395
+
396
+ The lobster doesn't accept contributions. The ape does.
397
+
398
+ ---
399
+
400
+ MIT License | Built by [42U](https://github.com/42U)
package/SKILL.md CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  name: kongbrain
3
3
  description: Graph-backed persistent memory engine for OpenClaw. Replaces the default context window with SurrealDB + vector embeddings that learn across sessions.
4
- version: 0.3.8
4
+ version: 0.3.10
5
5
  homepage: https://github.com/42U/kongbrain
6
6
  metadata:
7
7
  openclaw:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "kongbrain",
3
- "version": "0.3.8",
3
+ "version": "0.3.10",
4
4
  "description": "Graph-backed persistent memory engine for OpenClaw. Replaces the default context window with SurrealDB + vector embeddings that learn across sessions.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -41,6 +41,8 @@
41
41
  }
42
42
  },
43
43
  "scripts": {
44
+ "prepack": "cp README.md README.github.md && cp README.npm.md README.md",
45
+ "postpack": "cp README.github.md README.md && rm README.github.md",
44
46
  "test": "vitest run",
45
47
  "test:watch": "vitest",
46
48
  "build": "tsc --noEmit",
@@ -0,0 +1,155 @@
1
+ /**
2
+ * Shared concept-extraction helpers.
3
+ *
4
+ * Regex-based extraction of concept names from text, plus helpers to
5
+ * upsert extracted concepts and link them via arbitrary edge types.
6
+ */
7
+
8
+ import type { SurrealStore } from "./surreal.js";
9
+ import type { EmbeddingService } from "./embeddings.js";
10
+ import { swallow } from "./errors.js";
11
+
12
+ // Same regexes used by the original extractAndLinkConcepts in context-engine.
13
+ export const CONCEPT_RE = /\b(?:(?:use|using|implement|create|add|configure|setup|install|import)\s+)([A-Z][a-zA-Z0-9_-]+(?:\s+[A-Z][a-zA-Z0-9_-]+)?)/g;
14
+ export const TECH_TERMS = /\b(api|database|schema|migration|endpoint|middleware|component|service|module|handler|controller|model|interface|type|class|function|method|hook|plugin|extension|config|cache|queue|worker|daemon)\b/gi;
15
+
16
+ /** Extract concept name strings from free text using regex heuristics. */
17
+ export function extractConceptNames(text: string): string[] {
18
+ const concepts = new Set<string>();
19
+
20
+ let match: RegExpExecArray | null;
21
+ const re1 = new RegExp(CONCEPT_RE.source, CONCEPT_RE.flags);
22
+ while ((match = re1.exec(text)) !== null) {
23
+ concepts.add(match[1].trim());
24
+ }
25
+
26
+ const re2 = new RegExp(TECH_TERMS.source, TECH_TERMS.flags);
27
+ while ((match = re2.exec(text)) !== null) {
28
+ concepts.add(match[1].toLowerCase());
29
+ }
30
+
31
+ return [...concepts].slice(0, 10);
32
+ }
33
+
34
+ /**
35
+ * Upsert concepts from text and link them to a source node via the given edge.
36
+ *
37
+ * Used for:
38
+ * - turn → "mentions" → concept (existing behaviour)
39
+ * - memory → "about_concept" → concept (Fix 1)
40
+ * - artifact → "artifact_mentions" → concept (Fix 2)
41
+ */
42
+ export async function upsertAndLinkConcepts(
43
+ sourceId: string,
44
+ edgeName: string,
45
+ text: string,
46
+ store: SurrealStore,
47
+ embeddings: EmbeddingService,
48
+ logTag: string,
49
+ opts?: { taskId?: string; projectId?: string },
50
+ ): Promise<void> {
51
+ const names = extractConceptNames(text);
52
+ if (names.length === 0) return;
53
+
54
+ for (const name of names) {
55
+ try {
56
+ let embedding: number[] | null = null;
57
+ if (embeddings.isAvailable()) {
58
+ try { embedding = await embeddings.embed(name); } catch { /* ok */ }
59
+ }
60
+ const conceptId = await store.upsertConcept(name, embedding);
61
+ if (conceptId) {
62
+ await store.relate(sourceId, edgeName, conceptId)
63
+ .catch(e => swallow(`${logTag}:relate`, e));
64
+
65
+ // derived_from: concept → task
66
+ if (opts?.taskId) {
67
+ await store.relate(conceptId, "derived_from", opts.taskId)
68
+ .catch(e => swallow(`${logTag}:derived_from`, e));
69
+ }
70
+ // relevant_to: concept → project
71
+ if (opts?.projectId) {
72
+ await store.relate(conceptId, "relevant_to", opts.projectId)
73
+ .catch(e => swallow(`${logTag}:relevant_to`, e));
74
+ }
75
+ }
76
+ } catch (e) {
77
+ swallow(`${logTag}:upsert`, e);
78
+ }
79
+ }
80
+ }
81
+
82
+ /**
83
+ * Link a newly-upserted concept to existing concepts via narrower/broader
84
+ * edges when one concept's name is a substring of the other (indicating a
85
+ * parent-child hierarchy, e.g. "React" → "React hooks").
86
+ */
87
+ export async function linkConceptHierarchy(
88
+ conceptId: string,
89
+ conceptName: string,
90
+ store: SurrealStore,
91
+ embeddings: EmbeddingService,
92
+ logTag: string,
93
+ ): Promise<void> {
94
+ try {
95
+ const existing = await store.queryFirst<{ id: string; content: string }>(
96
+ `SELECT id, content FROM concept WHERE id != $cid LIMIT 50`,
97
+ { cid: conceptId },
98
+ );
99
+ if (existing.length === 0) return;
100
+
101
+ const lowerName = conceptName.toLowerCase();
102
+ let relatedCount = 0;
103
+
104
+ for (const other of existing) {
105
+ const otherLower = (other.content ?? "").toLowerCase();
106
+ if (!otherLower || otherLower === lowerName) continue;
107
+
108
+ const otherId = String(other.id);
109
+
110
+ if (lowerName.includes(otherLower) && lowerName !== otherLower) {
111
+ // New concept is more specific (e.g. "React hooks" contains "React")
112
+ await store.relate(conceptId, "narrower", otherId)
113
+ .catch(e => swallow(`${logTag}:narrower`, e));
114
+ await store.relate(otherId, "broader", conceptId)
115
+ .catch(e => swallow(`${logTag}:broader`, e));
116
+ } else if (otherLower.includes(lowerName) && otherLower !== lowerName) {
117
+ // New concept is more general (e.g. "React" contained in "React hooks")
118
+ await store.relate(conceptId, "broader", otherId)
119
+ .catch(e => swallow(`${logTag}:broader`, e));
120
+ await store.relate(otherId, "narrower", conceptId)
121
+ .catch(e => swallow(`${logTag}:narrower`, e));
122
+ }
123
+ }
124
+
125
+ // related_to: peer-level semantic association via embedding similarity
126
+ if (embeddings.isAvailable()) {
127
+ try {
128
+ const conceptEmb = await embeddings.embed(conceptName);
129
+ if (conceptEmb?.length) {
130
+ const similar = await store.queryFirst<{ id: string; score: number }>(
131
+ `SELECT id, vector::similarity::cosine(embedding, $vec) AS score
132
+ FROM concept
133
+ WHERE id != $cid
134
+ AND embedding != NONE AND array::len(embedding) > 0
135
+ ORDER BY score DESC
136
+ LIMIT 3`,
137
+ { vec: conceptEmb, cid: conceptId },
138
+ );
139
+ for (const s of similar) {
140
+ if (s.score < 0.75) break;
141
+ const simId = String(s.id);
142
+ await store.relate(conceptId, "related_to", simId)
143
+ .catch(e => swallow(`${logTag}:related_to`, e));
144
+ await store.relate(simId, "related_to", conceptId)
145
+ .catch(e => swallow(`${logTag}:related_to`, e));
146
+ }
147
+ }
148
+ } catch (e) {
149
+ swallow(`${logTag}:related_to_search`, e);
150
+ }
151
+ }
152
+ } catch (e) {
153
+ swallow(`${logTag}:hierarchy`, e);
154
+ }
155
+ }