@andespindola/brainlink 0.1.0-beta.14 → 0.1.0-beta.141

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.
Files changed (55) hide show
  1. package/AGENTS.md +8 -5
  2. package/CHANGELOG.md +26 -2
  3. package/CONTRIBUTING.md +2 -2
  4. package/COPYRIGHT.md +5 -0
  5. package/README.md +144 -22
  6. package/SECURITY.md +1 -1
  7. package/dist/application/analyze-vault.js +1 -15
  8. package/dist/application/build-context.js +64 -3
  9. package/dist/application/dedupe-notes.js +226 -0
  10. package/dist/application/frontend/client-css.js +110 -45
  11. package/dist/application/frontend/client-html.js +35 -26
  12. package/dist/application/frontend/client-js.js +2990 -161
  13. package/dist/application/frontend/client-worker-js.js +66 -0
  14. package/dist/application/get-graph-layout.js +39 -6
  15. package/dist/application/get-graph-node.js +3 -3
  16. package/dist/application/get-graph-summary.js +3 -3
  17. package/dist/application/get-graph-view.js +243 -0
  18. package/dist/application/get-graph.js +3 -3
  19. package/dist/application/import-legacy-sqlite.js +296 -0
  20. package/dist/application/index-vault.js +253 -25
  21. package/dist/application/list-agents.js +3 -3
  22. package/dist/application/list-links.js +5 -5
  23. package/dist/application/offline-pack-backup.js +44 -0
  24. package/dist/application/search-graph-node-ids.js +3 -3
  25. package/dist/application/search-knowledge.js +4 -5
  26. package/dist/application/server/routes.js +156 -5
  27. package/dist/application/start-server.js +75 -4
  28. package/dist/application/watch-vault.js +23 -2
  29. package/dist/benchmarks/large-vault.js +1 -1
  30. package/dist/cli/commands/agent-commands.js +7 -0
  31. package/dist/cli/commands/write-commands.js +842 -8
  32. package/dist/domain/context.js +54 -11
  33. package/dist/domain/graph-layout.js +181 -3
  34. package/dist/domain/markdown.js +29 -9
  35. package/dist/domain/middle-out.js +18 -0
  36. package/dist/infrastructure/config.js +38 -0
  37. package/dist/infrastructure/file-index.js +358 -0
  38. package/dist/infrastructure/file-system-vault.js +15 -0
  39. package/dist/infrastructure/index-state.js +58 -0
  40. package/dist/infrastructure/private-pack-codec.js +71 -10
  41. package/dist/infrastructure/search-packs.js +276 -87
  42. package/dist/infrastructure/volatile-memory.js +100 -0
  43. package/dist/mcp/server.js +21 -1
  44. package/dist/mcp/tools.js +96 -0
  45. package/docs/AGENT_USAGE.md +101 -19
  46. package/docs/ARCHITECTURE.md +23 -28
  47. package/docs/QUICKSTART.md +7 -0
  48. package/package.json +6 -4
  49. package/dist/infrastructure/sqlite/document-writer.js +0 -51
  50. package/dist/infrastructure/sqlite/graph-reader.js +0 -267
  51. package/dist/infrastructure/sqlite/recovery.js +0 -163
  52. package/dist/infrastructure/sqlite/schema.js +0 -114
  53. package/dist/infrastructure/sqlite/search-reader.js +0 -188
  54. package/dist/infrastructure/sqlite/types.js +0 -1
  55. package/dist/infrastructure/sqlite-index.js +0 -38
package/AGENTS.md CHANGED
@@ -6,19 +6,19 @@ This file tells coding agents and AI assistants how to use this repository.
6
6
 
7
7
  Brainlink is a local-first knowledge memory for agents.
8
8
 
9
- It reads a Markdown vault, extracts `[[wiki links]]` and `#tags`, builds a local SQLite full-text index, and returns compact context packages that agents can inject into prompts.
9
+ It reads a Markdown vault, extracts `[[wiki links]]` and `#tags`, builds a local file index at `.brainlink/index.json`, and returns compact context packages that agents can inject into prompts.
10
10
 
11
11
  ## Source Of Truth
12
12
 
13
13
  Markdown files are the source of truth.
14
14
 
15
- The SQLite database at `.brainlink/brainlink.db` is a derived index. It can be deleted and rebuilt with:
15
+ The JSON index at `.brainlink/index.json` is derived. It can be deleted and rebuilt with:
16
16
 
17
17
  ```bash
18
18
  npm run dev -- index --vault ./vault
19
19
  ```
20
20
 
21
- Do not store permanent knowledge only in SQLite.
21
+ Do not store permanent knowledge only in index artifacts.
22
22
 
23
23
  By default, the installed Brainlink CLI uses `$HOME/.brainlink/vault` as its vault. Passing `--vault` or setting `vault` in `brainlink.config.json` intentionally selects a custom vault such as `./vault`.
24
24
 
@@ -83,6 +83,9 @@ Use watch mode while editing notes:
83
83
  ```bash
84
84
  npm run dev -- server --vault ./vault --watch
85
85
  npm run dev -- watch --vault ./vault
86
+ npm run dev -- bench --vault ./vault
87
+ npm run dev -- bench --vault ./vault --watch
88
+ npm run dev -- pack-backup --vault ./vault
86
89
  ```
87
90
 
88
91
  Start MCP over stdio:
@@ -107,10 +110,10 @@ npm run dev -- doctor --vault ./vault
107
110
 
108
111
  - Keep domain rules in `src/domain`.
109
112
  - Keep use cases in `src/application`.
110
- - Keep filesystem and SQLite details in `src/infrastructure`.
113
+ - Keep filesystem and index details in `src/infrastructure`.
111
114
  - Keep CLI concerns in `src/cli`.
112
115
  - Prefer pure functions for parsing, ranking, formatting, and transformation.
113
- - Do not make SQLite the canonical storage layer.
116
+ - Do not make index artifacts the canonical storage layer.
114
117
  - Do not add comments with emojis.
115
118
  - Keep JSON output backwards compatible where possible.
116
119
 
package/CHANGELOG.md CHANGED
@@ -22,6 +22,30 @@
22
22
  - Added short-lived hybrid search cache with automatic invalidation on index changes.
23
23
  - Added `stats --extended` observability output with storage, quality and latency probes.
24
24
  - Added `docs/QUICKSTART.md` and aligned README/agent docs with the latest CLI/MCP flows.
25
+ - Added middle-out context assembly so chunk selection expands around the strongest note chunk.
26
+ - Added compressed-space pack prefiltering (token bloom index) before `.blpk` decryption and scan.
27
+ - Improved graph UI auto-fit and viewport recovery so loaded nodes are re-centered when zoom/pan drifts to empty canvas.
28
+ - Added cross-platform native desktop GUI auto-open for `blink server` (macOS Swift/WebKit, Windows PowerShell WinForms, Linux Python GTK/WebKit2), with app-window/browser fallback.
29
+ - Changed Linux default UI launch to app-window/browser for lighter startup; Linux native GUI is now opt-in via `BRAINLINK_LINUX_NATIVE_GUI=1`.
30
+ - Added native GUI parent-process monitoring so GUI windows close automatically when `blink server` stops.
31
+ - Improved non-mac browser detection fallback to try installed Edge/Chrome/Firefox/Chromium candidates before system default open.
32
+ - Improved graph filter rendering to keep hub anchor nodes visible (`Memory Hub`/`MOC`/high-degree fallback) for coherent relationship context.
33
+ - Fixed graph modal content loading by correcting agent query parameter composition for `/api/graph-node` and `/api/graph-filter` requests.
34
+ - Improved 50k+ graph rendering performance with viewport-aware spatial node culling, cached render visibility, and node-adjacent edge selection to avoid full graph scans every frame.
35
+ - Added incremental vault indexing with file snapshots to reuse unchanged documents/chunks/embeddings, plus adaptive search-pack rebuild thresholds to avoid full re-compression on small edits.
36
+ - Reduced large-graph HTTP payload size with compact `/api/graph-layout` encoding for high-node vaults and capped transmitted edges to improve UI load responsiveness.
37
+ - Added aggressive graph LOD clustering when zoomed out, dynamic per-zoom edge render budgets, and a dedicated frontend worker for off-main-thread graph filter matching.
38
+ - Improved Linux browser fallback launch stability by auto-applying Chromium compatibility flags (`--ozone-platform=x11`, `--disable-gpu`, `--disable-features=Vulkan,VaapiVideoDecoder`, `--disable-background-networking`) for app-window/browser modes.
39
+ - Improved massive-graph UI responsiveness with stricter render budgets, adaptive heavy-graph frame throttling, reduced interaction hit-test frequency, and URL-first agent selection on initial graph load.
40
+ - Improved 50k+ graph LOD behavior so zoomed-out views render lightweight cluster overviews and progressively reveal nodes/edges only as zoom increases.
41
+ - Added `blink bench` with realtime index phase telemetry and per-run compressed-pack analysis (input/output bytes, ratio, saved space, rebuild reason and duration), including continuous watch mode.
42
+ - Added tunable single-stage search-pack compression settings (`searchPack.rowChunkSize`, `searchPack.compressionLevel`, `searchPack.useDictionary`).
43
+ - Added benchmark guardrails for compression savings and latency regression (`searchPack.guardrailMinSavingsPercent`, `searchPack.guardrailMaxLatencyRegressionPercent`), reported in `blink bench`.
44
+ - Added `blink pack-backup` for offline second-stage compression backups of encrypted `.blpk` packs, outside the online query path.
45
+ - Hardened Linux browser launch flags for Ubuntu 26 Chromium/Wayland compatibility (`--disable-vulkan`, `--use-gl=swiftshader`, `--ozone-platform-hint=x11`).
46
+ - Improved pack resilience by auto-repairing missing search-pack manifests from existing `.blpk` files, avoiding unnecessary full repacks on small incremental updates.
47
+ - Updated Linux graph auto-open behavior to prioritize the system default browser (`xdg-open`) before explicit browser fallbacks.
48
+ - Removed implicit Chromium dependency in Linux auto-open flow; app-window launch is now opt-in (`BRAINLINK_LINUX_APP_WINDOW=1`).
25
49
 
26
50
  ## 0.1.0-beta.3
27
51
 
@@ -49,8 +73,8 @@
49
73
  ## 0.1.0-alpha.0
50
74
 
51
75
  - Added local-first Markdown vault indexing.
52
- - Added SQLite FTS, local semantic retrieval, wiki links, backlinks and graph retrieval.
53
- - Added SQLite semantic bucket indexing to narrow vector candidates for larger vaults.
76
+ - Added local full-text indexing, local semantic retrieval, wiki links, backlinks and graph retrieval.
77
+ - Added semantic candidate bucket indexing to narrow vector candidates for larger vaults.
54
78
  - Optimized title/link resolution with precomputed agent-scoped title maps.
55
79
  - Added CLI, JSON output, HTTP API and graph UI.
56
80
  - Added vault diagnostics: stats, broken links, orphans, validation and doctor.
package/CONTRIBUTING.md CHANGED
@@ -22,7 +22,7 @@ npm run pack:smoke
22
22
  ## Design Rules
23
23
 
24
24
  - Markdown files are the source of truth.
25
- - SQLite is a derived index and must remain rebuildable.
25
+ - Local index artifacts are derived and must remain rebuildable.
26
26
  - Domain parsing, graph analysis and layout should stay pure and testable.
27
- - CLI, HTTP, filesystem and SQLite code are adapters around application use cases.
27
+ - CLI, HTTP, filesystem and index code are adapters around application use cases.
28
28
  - MCP integration should live outside this package by wrapping the CLI with `--json`.
package/COPYRIGHT.md ADDED
@@ -0,0 +1,5 @@
1
+ Copyright (c) 2026 Substructa
2
+
3
+ This project is licensed under the MIT License.
4
+
5
+ See [LICENSE](./LICENSE) for full terms.
package/README.md CHANGED
@@ -52,15 +52,15 @@ LLMs do not have infinite context. Brainlink gives agents an external memory lay
52
52
  1. Durable knowledge is written as Markdown.
53
53
  2. Notes are connected with `[[wiki links]]`.
54
54
  3. Concepts are classified with `#tags`.
55
- 4. Brainlink builds a local SQLite index with FTS records and local embeddings.
55
+ 4. Brainlink builds a local JSON index (`.brainlink/index.json`) and private encrypted search packs.
56
56
  5. Agents query the index before responding.
57
57
  6. Brainlink returns compact, source-backed context.
58
58
 
59
- Markdown is the source of truth. `.brainlink/brainlink.db` is only a rebuildable index.
60
- Brainlink now keeps an automatic rollback snapshot at `.brainlink/brainlink.db.backup` plus rotating snapshots in `.brainlink/brainlink.db.backup.snapshots/`. If the main SQLite file is corrupted, Brainlink automatically restores the newest valid snapshot (or recreates a clean index when no snapshot exists).
61
- After each index run, Brainlink also writes private encrypted search packs at `.brainlink/search-packs/*.blpk`. If SQLite is unavailable, search falls back to these packs automatically.
59
+ Markdown is the source of truth. `.brainlink/index.json` is a rebuildable index artifact.
60
+ After each index run, Brainlink also writes private encrypted search packs at `.brainlink/search-packs/*.blpk` to preserve fast retrieval and portable recovery.
61
+ Online retrieval always uses a single compression stage per pack; optional second-stage compression is reserved for offline backup artifacts only.
62
62
  Pack decryption uses a Brainlink key from `$BRAINLINK_HOME/keys` or from `BRAINLINK_SEARCH_PACK_KEY` when explicitly configured.
63
- On upgrade, if a legacy SQLite index exists without private packs, Brainlink imports index rows into `.blpk` automatically on first search/context access.
63
+ Legacy `.jsonl.gz` packs are upgraded to `.blpk` automatically on first search/context access.
64
64
 
65
65
  ## Features
66
66
 
@@ -68,8 +68,13 @@ On upgrade, if a legacy SQLite index exists without private packs, Brainlink imp
68
68
  - Obsidian-compatible `[[wiki links]]` and `#tags`.
69
69
  - Weighted graph edges so agents can rank relationship importance and priority.
70
70
  - Backlinks, broken-link reports, orphan detection and validation.
71
- - Full-text, semantic and hybrid retrieval modes.
72
- - SQLite-backed semantic candidate buckets for larger vaults.
71
+ - Full-text, semantic and hybrid retrieval on a local file index.
72
+ - Middle-out context assembly around the strongest chunk per document.
73
+ - In-process index and context caching with automatic invalidation on index updates.
74
+ - HTTP graph server caches generated frontend assets and graph-layout JSON payloads by signature, and skips layout serialization when ETag returns `304`.
75
+ - Compressed-space prefiltering for `.blpk` packs before decryption and scan.
76
+ - Incremental indexing that reprocesses only changed markdown files and reuses existing chunks/embeddings for unchanged notes.
77
+ - Adaptive compressed-pack rebuild policy to keep indexing fast during small edit batches.
73
78
  - Agent namespaces under `agents/<agent-id>/`.
74
79
  - S3-compatible bucket vaults through `s3://bucket/prefix` URIs.
75
80
  - CLI with machine-readable `--json` output.
@@ -77,6 +82,16 @@ On upgrade, if a legacy SQLite index exists without private packs, Brainlink imp
77
82
  - Built-in MCP stdio server for agent tool integration.
78
83
  - Local HTTP API.
79
84
  - Realtime graph UI with agent selector and colored knowledge groups.
85
+ - Graph renderer keeps the full filtered graph visible during zoom/pan, rendering every visible node and edge without viewport culling or edge caps in the main view.
86
+ - Canvas graph rendering uses the same batched node and edge pipeline for every graph size, reducing per-frame draw calls while keeping selected and hovered items highlighted.
87
+ - WebGL acceleration is used when available for dense node and edge drawing, with Canvas 2D preserved as the interaction and fallback layer.
88
+ - Large graph layout API automatically uses compact payload encoding with link-coverage-aware edge selection to reduce initial client load without hiding major relationships.
89
+ - Large-segment layout spacing now grows logarithmically to keep initial visual density consistent between medium and very large vaults (for example, ~1k vs ~50k notes).
90
+ - Graph coordinates are visually compacted across graph sizes so reset starts from a stable fitted scene and zoom-in progressively reveals local detail.
91
+ - Zoomed-out graph keeps the same flat graph scene and preserves complete filtered relationships without switching to nested subgraphs.
92
+ - Graph reset fits the full graph scene instead of starting in a separate macro overview mode.
93
+ - Graph filtering runs in a dedicated browser worker to keep the UI thread responsive during heavy datasets.
94
+ - Node titles are shown as the user zooms closer, while labels remain bounded to visible on-screen nodes in very large graphs.
80
95
 
81
96
  ## Install
82
97
 
@@ -286,7 +301,7 @@ export BRAINLINK_S3_FORCE_PATH_STYLE=1
286
301
 
287
302
  Bucket vaults mirror Markdown into a local cache under
288
303
  `$BRAINLINK_HOME/bucket-cache`. The bucket remains canonical; the local
289
- `.brainlink/brainlink.db` stays a disposable index. Run `index` after remote
304
+ `.brainlink/index.json` stays a disposable index artifact. Run `index` after remote
290
305
  bucket changes before relying on `search`, `context`, graph or validation
291
306
  commands. Watch mode is only supported for local filesystem vaults.
292
307
 
@@ -302,7 +317,7 @@ vault/
302
317
  research-agent/
303
318
  source-review-policy.md
304
319
  .brainlink/
305
- brainlink.db
320
+ index.json
306
321
  ```
307
322
 
308
323
  Permanent data:
@@ -312,7 +327,7 @@ Permanent data:
312
327
 
313
328
  Rebuildable data:
314
329
 
315
- - `.brainlink/brainlink.db`
330
+ - `.brainlink/index.json`
316
331
  - full-text records
317
332
  - local embedding vectors
318
333
  - local embedding buckets
@@ -396,6 +411,7 @@ blink agent upgrade
396
411
  ```
397
412
 
398
413
  This configures `~/.codex/config.toml` with Brainlink MCP (`brainlink-mcp`) so Brainlink is available by default in agent sessions.
414
+ `agent install` and `agent upgrade` also apply the MCP `fully-auto` bootstrap policy by default (`enforceBootstrap`, `enforceContextFirst`, `autoBootstrapOnRead`, `autoBootstrapOnStartup` all enabled).
399
415
 
400
416
  If you are inside this repository and want plugin gallery setup too:
401
417
 
@@ -515,8 +531,12 @@ Available tools:
515
531
  - `brainlink_recommendations`: return an automatic action plan so agents can run Brainlink in the recommended order.
516
532
  - `brainlink_context`: read indexed context for a task or question.
517
533
  - `brainlink_search`: search indexed notes.
534
+ - `brainlink_dedupe`: detect duplicate candidates using exact hash + semantic similarity scores.
535
+ - `brainlink_resolve_duplicate`: resolve duplicate pairs (`merge`, `link`, `ignore`) with connectivity-safe fallback edges.
518
536
  - `brainlink_add_note`: write durable Markdown memory and reindex.
519
537
  - `brainlink_add_file`: ingest a local file as a note and reindex.
538
+ - `brainlink_volatile_add`: write temporary agent-decided memory with TTL; volatile sections are included in context and never create durable graph edges.
539
+ - `brainlink_volatile_clear`: clear temporary memory for the current vault/agent namespace.
520
540
  - `brainlink_index`: rebuild the vault index.
521
541
  - `brainlink_stats`: read indexed vault statistics.
522
542
  - `brainlink_validate`: validate broken links and orphan notes.
@@ -542,7 +562,7 @@ Agents can raise the importance of a relationship by putting priority markers on
542
562
  Related: [[Incident Runbook]] #critical
543
563
  ```
544
564
 
545
- Indexed edges expose `weight` and `priority` (`low`, `normal`, `high`, `critical`) through CLI JSON, HTTP graph APIs and `brainlink_graph`.
565
+ Indexed edges expose `weight` and `priority` (`low`, `normal`, `high`, `critical`) through CLI JSON, HTTP graph APIs and `brainlink_graph`. Brainlink promotes only representative graph links per note: high-priority and high-weight links win, structural hub links such as `Memory Hub`, `Knowledge Root`, `MOC` and map notes are suppressed when stronger direct links exist, and old indexes are rebuilt automatically when their graph link model version is missing or stale.
546
566
 
547
567
  ## Graph UI
548
568
 
@@ -553,20 +573,40 @@ blink server --host 127.0.0.1 --port 4321 --watch
553
573
  ```
554
574
 
555
575
  By default, the server uses `$HOME/.brainlink/vault`. Pass `--vault ./vault` only when you want to inspect a custom vault.
576
+ By default, `blink server` tries to open the graph in a native desktop GUI window:
577
+ - macOS: Swift + WebKit
578
+ - Windows: PowerShell WinForms WebBrowser
579
+ - Linux: optional Python GTK + WebKit2 (requires `python3` + `gi` + `WebKit2`)
580
+
581
+ On Linux, native GUI is disabled by default for better startup performance. Enable it with `BRAINLINK_LINUX_NATIVE_GUI=1`.
582
+ If native GUI launch is unavailable on your system, it falls back to dedicated app-window mode and then to the default browser.
583
+ For Chromium-family browsers on Linux (`chromium`, `chromium-browser`, `google-chrome`, `microsoft-edge`, `brave-browser`), Brainlink now auto-applies compatibility flags during launch (`--ozone-platform=x11`, `--ozone-platform-hint=x11`, `--disable-gpu`, `--disable-vulkan`, `--use-gl=swiftshader`, `--disable-features=Vulkan,VaapiVideoDecoder`, `--disable-background-networking`) to avoid common Wayland/Vulkan/VAAPI startup issues.
584
+ On Linux, Brainlink opens the graph through the system default browser first (`xdg-open`), then `$BROWSER`/detected browsers as fallback. Chromium-family app-window mode is optional via `BRAINLINK_LINUX_APP_WINDOW=1`.
585
+ Use `--no-open` to keep it headless.
586
+ When native GUI is used, the GUI window automatically closes when the `blink server` process stops.
556
587
 
557
588
  The graph UI shows:
558
589
 
559
590
  - notes as nodes
560
- - `[[wiki links]]` as weighted edges
561
- - details opened on node click (tags, outgoing links, backlinks, full Markdown content)
591
+ - representative `[[wiki links]]` as weighted edges
592
+ - details opened in a non-modal side panel (tags, outgoing links, backlinks, full Markdown content), so zoom and pan remain available while inspecting data
562
593
  - neutral graph nodes with segment/group metadata
563
- - agent selector for isolated views
594
+ - agent selector (id-only labels) for isolated views
564
595
  - graph filter matches title, path, tags and note content
596
+ - graph filter keeps hub context nodes visible (`Memory Hub`/`MOC`/high-degree fallback) to preserve relationship readability
565
597
  - realtime refresh while `--watch` is enabled
566
598
  - graph controls for zoom in, zoom out, fit visible nodes and reset-to-fit-all
567
- - wheel zoom anchored to cursor position for faster navigation in large graphs
599
+ - wheel zoom (including `cmd+scroll` and `ctrl+scroll`) anchored to cursor position for faster navigation in large graphs
600
+ - wheel/button zoom updates immediately at the cursor anchor without delayed focus-transition interpolation
601
+ - Bloom-like scene navigation: reset fits the current graph scene, wheel zoom stays anchored to the cursor, and WebGL acceleration draws the dense node and edge layer faster
602
+ - zoom-out floor for large and massive graphs to keep the scene reachable without switching into a separate macro graph mode
603
+ - keyboard shortcuts: `+` zoom in, `-` zoom out, `0` reset fit
604
+ - click on a node opens its details panel; double-click on empty canvas zooms in at cursor position
568
605
  - floating graph totals (notes, links, tags) below the Brainlink title
569
- - large-graph rendering safeguards (edge draw caps, lower redraw rate, zoom-aware interaction)
606
+ - graph rendering safeguards (batched canvas drawing across graph sizes, lower redraw rate, zoom-aware interaction)
607
+ - adaptive CPU safeguards for large graphs: idle frame pacing, throttled background physics updates and cached viewport dimensions to reduce redraw/layout overhead while preserving interaction responsiveness
608
+ - WebGL node and edge acceleration when supported, falling back to Canvas 2D without changing graph behavior
609
+ - large graph view keeps a single-level graph model across zoom levels, renders the full filtered scene instead of viewport-sampled subsets, and shows node titles as zoom approaches readable scale
570
610
 
571
611
  The server indexes before starting by default. Use `--no-index` to skip that step:
572
612
 
@@ -585,6 +625,7 @@ Routes:
585
625
  - `GET /api/agents`
586
626
  - `GET /api/graph`
587
627
  - `GET /api/graph-layout`
628
+ - `GET /api/graph-view?x=<x>&y=<y>&w=<width>&h=<height>&scale=<scale>`
588
629
  - `GET /api/graph-node?id=<node-id>`
589
630
  - `GET /api/search?q=<query>&limit=10&mode=hybrid`
590
631
  - `GET /api/context?q=<query>&limit=12&tokens=2000&mode=hybrid`
@@ -668,6 +709,18 @@ blink migrate-vault --from ~/.brainlink/vault --to ./team-vault --report ./migra
668
709
  Runs explicit markdown migration between vaults while preserving conflicts as `.conflict-<timestamp>` files.
669
710
  Use `--dry-run` to preview `copied`, `conflicted` and `unchanged` counts before writing.
670
711
 
712
+ ### `db-import`
713
+
714
+ ```bash
715
+ blink db-import --vault ./team-vault
716
+ blink db-import --vault ./team-vault --db ./legacy/brainlink.db
717
+ blink db-import --vault ./team-vault --db ./legacy/brainlink.db --table legacy_notes --dry-run
718
+ ```
719
+
720
+ Imports durable memory from a legacy SQLite database into Markdown notes (`agents/<agent-id>/*.md`) and reindexes by default.
721
+ When `--db` is omitted, Brainlink auto-detects common legacy paths such as `<vault>/.brainlink/brainlink.db`.
722
+ Use `--agent <id>` to force all imported rows into one namespace, `--limit` for incremental imports, `--dry-run` to preview without writing files, and `--no-index` to defer reindexing.
723
+
671
724
  ### `init`
672
725
 
673
726
  ```bash
@@ -692,6 +745,28 @@ blink add "Note Title" --vault ./vault --content-file ./notes.md --no-auto-index
692
745
 
693
746
  Creates a Markdown note under `agents/<agent-id>/`. Common secret patterns are blocked by default; use `--allow-sensitive` only for an intentionally protected vault.
694
747
  To avoid disconnected memory, Brainlink auto-adds a fallback wiki edge when a note is written without links, creating agent hub notes when needed.
748
+ `add` also returns `possibleDuplicates` (exact hash + semantic candidates) so agents can resolve duplicate memory right after writes.
749
+
750
+ ### `dedupe`
751
+
752
+ ```bash
753
+ blink dedupe --vault ./vault --json
754
+ blink dedupe --vault ./vault --agent coding-agent --limit 20 --min-score 0.92 --json
755
+ blink dedupe --vault ./vault --no-semantic --json
756
+ ```
757
+
758
+ Detects `possibleDuplicate` pairs using exact content hashes and optional semantic similarity.
759
+
760
+ ### `dedupe-resolve`
761
+
762
+ ```bash
763
+ blink dedupe-resolve --vault ./vault --left agents/shared/a.md --right agents/shared/b.md --action merge --json
764
+ blink dedupe-resolve --vault ./vault --left agents/shared/a.md --right agents/shared/b.md --action link --json
765
+ blink dedupe-resolve --vault ./vault --left agents/shared/a.md --right agents/shared/b.md --action ignore --json
766
+ ```
767
+
768
+ Resolves a duplicate pair with `merge`, `link` or `ignore`.
769
+ When action is not `merge`, Brainlink still creates a low-priority related edge (`#related-to`) so notes remain connected.
695
770
 
696
771
  ### `index`
697
772
 
@@ -702,6 +777,38 @@ blink index --vault ./vault
702
777
 
703
778
  Rebuilds the local index from Markdown files.
704
779
 
780
+ ### `bench`
781
+
782
+ ```bash
783
+ blink bench --vault ./vault
784
+ blink bench --vault ./vault --watch
785
+ blink bench --vault ./vault --watch --debounce 500
786
+ blink bench --vault ./vault --json
787
+ ```
788
+
789
+ Runs indexing with realtime phase telemetry (`start`, `scan`, `parse`, `embed`, `persist`, `packs`, `complete`) and prints a benchmark summary at the end of each run.
790
+
791
+ Summary includes compression behavior for `.blpk` packs when rebuild happens:
792
+ - pack rebuild reason
793
+ - pack count and pack build duration
794
+ - uncompressed input bytes vs compressed output bytes
795
+ - saved percentage
796
+ - objective guardrails (minimum savings and maximum latency regression thresholds)
797
+
798
+ Use `--watch` to keep benchmarking incremental reindex runs after Markdown changes (local filesystem vaults only).
799
+ When `.brainlink/search-packs/manifest.json` is missing but `.blpk` files exist, Brainlink repairs the manifest first and avoids unnecessary full pack rebuild on small edits.
800
+
801
+ ### `pack-backup`
802
+
803
+ ```bash
804
+ blink pack-backup --vault ./vault
805
+ blink pack-backup --vault ./vault --output ./vault/.brainlink/backups/custom.blpkbak.gz
806
+ blink pack-backup --vault ./vault --json
807
+ ```
808
+
809
+ Creates an offline backup artifact of encrypted search packs with a second compression pass.
810
+ This is intentionally outside the online retrieval path (`index`, `search`, `context`).
811
+
705
812
  ### `agents`
706
813
 
707
814
  ```bash
@@ -724,11 +831,12 @@ If `--mode` or `--limit` is omitted, Brainlink resolves values from the current
724
831
 
725
832
  Modes:
726
833
 
727
- - `hybrid`: default; combines SQLite FTS with local embedding similarity.
728
- - `fts`: exact lexical retrieval through SQLite FTS.
834
+ - `hybrid`: default; combines lexical matching with local embedding similarity.
835
+ - `fts`: exact lexical retrieval from the file index.
729
836
  - `semantic`: local deterministic embedding similarity only.
730
837
 
731
838
  Hybrid results are cached in-memory for a short TTL and invalidated automatically when the local index file changes.
839
+ Context selection uses a middle-out strategy: it starts from the strongest chunk in a note and expands to neighboring chunks while respecting token budget.
732
840
 
733
841
  ### `context`
734
842
 
@@ -739,6 +847,7 @@ blink context "question" --vault ./vault --agent coding-agent --mode hybrid --js
739
847
  ```
740
848
 
741
849
  Builds a compact context package for an agent.
850
+ Repeated calls with the same vault, agent, query, mode and token/limit settings are served from a short in-memory cache while the index is unchanged.
742
851
 
743
852
  ### `links`
744
853
 
@@ -823,9 +932,15 @@ Watches Markdown files and rebuilds the index when notes change.
823
932
  ```bash
824
933
  blink server --watch
825
934
  blink server --vault ./vault --watch
935
+ blink server --vault ./vault --watch --no-open
826
936
  ```
827
937
 
828
938
  Starts the local read-only graph UI and HTTP API.
939
+ By default, it tries to open a native desktop GUI window for the graph URL.
940
+ On Linux, native GUI is disabled by default; enable it with `BRAINLINK_LINUX_NATIVE_GUI=1`.
941
+ If native GUI launch is unavailable, it falls back to dedicated app-window mode and then browser open.
942
+ When fallback opens Chromium-family browsers on Linux, Brainlink automatically uses compatibility launch flags for stable rendering on Ubuntu/Wayland setups.
943
+ Use `--no-open` to skip that behavior.
829
944
 
830
945
  The HTTP server only binds to loopback hosts such as `127.0.0.1`, `localhost` or `::1`.
831
946
 
@@ -866,6 +981,13 @@ If no `vault` is configured and no `--vault` flag is passed, Brainlink uses `$HO
866
981
  "embeddingProvider": "local",
867
982
  "defaultSearchMode": "hybrid",
868
983
  "chunkSize": 1200,
984
+ "searchPack": {
985
+ "rowChunkSize": 5000,
986
+ "compressionLevel": 5,
987
+ "useDictionary": true,
988
+ "guardrailMinSavingsPercent": 8,
989
+ "guardrailMaxLatencyRegressionPercent": 5
990
+ },
869
991
  "agentProfiles": {
870
992
  "coding-agent": {
871
993
  "defaultSearchMode": "semantic",
@@ -977,7 +1099,7 @@ src/
977
1099
  application/ use cases
978
1100
  cli/ command-line adapter
979
1101
  domain/ pure knowledge rules
980
- infrastructure/ filesystem and SQLite adapters
1102
+ infrastructure/ filesystem and index adapters
981
1103
  ```
982
1104
 
983
1105
  Detailed notes:
@@ -989,7 +1111,6 @@ Detailed notes:
989
1111
  ## Current Limits
990
1112
 
991
1113
  - Semantic search uses deterministic local embeddings, not a remote model provider.
992
- - Semantic search uses SQLite embedding buckets to narrow candidates before cosine scoring.
993
1114
  - `embeddingProvider` currently supports `local` and `none`.
994
1115
  - Link resolution is title-based inside each agent namespace, with `shared` as fallback.
995
1116
  - HTTP API is local and unauthenticated.
@@ -1000,7 +1121,7 @@ Detailed notes:
1000
1121
  The `0.1.0-beta` line is intended to stabilize the local-first memory loop:
1001
1122
 
1002
1123
  - Markdown as durable memory.
1003
- - SQLite FTS plus local embeddings and semantic buckets as rebuildable retrieval index.
1124
+ - Rebuildable file index plus local embeddings and encrypted pack exports.
1004
1125
  - CLI as the primary agent interface.
1005
1126
  - HTTP graph API and frontend as inspection tools.
1006
1127
  - Agent namespaces to avoid context mixing.
@@ -1016,7 +1137,7 @@ Brainlink is local-first by default.
1016
1137
  - Brainlink HTTP is localhost-only and refuses non-loopback hosts.
1017
1138
  - Brainlink blocks common secret patterns by default when adding notes. Use `--allow-sensitive` only for intentional, protected vaults.
1018
1139
  - Do not store secrets, credentials, API keys or regulated personal data unless the vault is protected by your own storage controls.
1019
- - Treat `.brainlink/brainlink.db` as disposable derived data.
1140
+ - Treat `.brainlink/index.json` and `.brainlink/search-packs/` as disposable derived artifacts.
1020
1141
 
1021
1142
  See [SECURITY.md](SECURITY.md).
1022
1143
 
@@ -1027,6 +1148,7 @@ See [CONTRIBUTING.md](CONTRIBUTING.md).
1027
1148
  ## License
1028
1149
 
1029
1150
  MIT. See [LICENSE](LICENSE).
1151
+ Copyright (c) 2026 Substructa. See [COPYRIGHT.md](COPYRIGHT.md).
1030
1152
 
1031
1153
  ### Memory Optimization Loop (1-7)
1032
1154
 
package/SECURITY.md CHANGED
@@ -7,7 +7,7 @@ Brainlink is local-first.
7
7
  - The HTTP server binds to `127.0.0.1` by default.
8
8
  - The HTTP server always refuses non-loopback hosts.
9
9
  - The HTTP server is read-only and does not expose note creation, indexing or update routes.
10
- - The SQLite database is a derived local index.
10
+ - Local index artifacts (`.brainlink/index.json` and `.brainlink/search-packs/`) are derived data.
11
11
  - Markdown files are user-owned source data.
12
12
  - Brainlink-created Markdown files use `0600` permissions.
13
13
  - Brainlink-created directories and `.brainlink` use `0700` permissions.
@@ -1,7 +1,5 @@
1
1
  import { stat } from 'node:fs/promises';
2
- import { existsSync, readdirSync } from 'node:fs';
3
2
  import { performance } from 'node:perf_hooks';
4
- import { join } from 'node:path';
5
3
  import { validateGraph, getBrokenLinks, getOrphanNodes, getVaultStats } from '../domain/graph-analysis.js';
6
4
  import { ensureVault, listVaultFiles, readMarkdownFiles } from '../infrastructure/file-system-vault.js';
7
5
  import { resolveAgentRuntimeDefaults } from '../infrastructure/config.js';
@@ -96,23 +94,11 @@ export const doctorVault = async (vaultPath) => {
96
94
  const files = await readMarkdownFiles(absoluteVaultPath);
97
95
  const graph = await getGraphSummary(absoluteVaultPath);
98
96
  const validation = validateGraph(graph);
99
- const backupPath = join(absoluteVaultPath, '.brainlink', 'brainlink.db.backup');
100
- const snapshotDirectory = join(absoluteVaultPath, '.brainlink', 'brainlink.db.backup.snapshots');
101
- const hasBackup = existsSync(backupPath);
102
- const snapshotCount = existsSync(snapshotDirectory)
103
- ? readdirSync(snapshotDirectory).filter((name) => name.endsWith('.db')).length
104
- : 0;
105
- const backupReady = graph.nodes.length === 0 || hasBackup;
106
97
  const checks = [
107
98
  createCheck('vault', true, `Vault ready at ${absoluteVaultPath}`),
108
99
  createCheck('markdown-files', files.length > 0, `${files.length} markdown files found`),
109
100
  createCheck('index', graph.nodes.length > 0, `${graph.nodes.length} indexed documents found`),
110
- createCheck('broken-links', validation.brokenLinks.length === 0, `${validation.brokenLinks.length} broken links found`),
111
- createCheck('index-backup', backupReady, backupReady
112
- ? (hasBackup
113
- ? `SQLite recovery snapshot is available (${snapshotCount} rotating snapshots)`
114
- : 'No index yet. Snapshot will be created after first indexing run')
115
- : 'Recovery snapshot missing. Run blink index to create a rollback snapshot')
101
+ createCheck('broken-links', validation.brokenLinks.length === 0, `${validation.brokenLinks.length} broken links found`)
116
102
  ];
117
103
  const recommendations = files.length === 0 && graph.nodes.length === 0
118
104
  ? [
@@ -1,13 +1,74 @@
1
+ import { stat } from 'node:fs/promises';
1
2
  import { formatContextPackage, selectContextSections } from '../domain/context.js';
3
+ import { indexStoragePath } from '../infrastructure/file-index.js';
4
+ import { searchVolatileMemory, volatileMemoryStoragePath } from '../infrastructure/volatile-memory.js';
2
5
  import { searchKnowledge } from './search-knowledge.js';
6
+ const contextCacheTtlMs = 45_000;
7
+ const contextCacheMaxEntries = 200;
8
+ const contextCache = new Map();
9
+ const readFileSignature = async (path) => {
10
+ try {
11
+ const info = await stat(path);
12
+ return `${Math.floor(info.mtimeMs)}:${info.size}`;
13
+ }
14
+ catch {
15
+ return '0:0';
16
+ }
17
+ };
18
+ const readContextDataSignature = async (vaultPath) => `${await readFileSignature(indexStoragePath(vaultPath))}|${await readFileSignature(volatileMemoryStoragePath(vaultPath))}`;
19
+ const toCacheKey = (vaultPath, query, limit, maxTokens, agentId, mode) => JSON.stringify({
20
+ vaultPath,
21
+ query: query.trim().toLowerCase(),
22
+ limit,
23
+ maxTokens,
24
+ agentId: agentId?.trim().toLowerCase() ?? '*',
25
+ mode: mode ?? 'default'
26
+ });
27
+ const contextCacheGet = (key, dataSignature) => {
28
+ const entry = contextCache.get(key);
29
+ if (!entry) {
30
+ return undefined;
31
+ }
32
+ const fresh = Date.now() - entry.createdAt <= contextCacheTtlMs && entry.dataSignature === dataSignature;
33
+ if (!fresh) {
34
+ contextCache.delete(key);
35
+ return undefined;
36
+ }
37
+ return entry.context;
38
+ };
39
+ const contextCacheSet = (entry) => {
40
+ contextCache.set(entry.key, entry);
41
+ if (contextCache.size <= contextCacheMaxEntries) {
42
+ return;
43
+ }
44
+ const overflow = contextCache.size - contextCacheMaxEntries;
45
+ const keys = Array.from(contextCache.keys()).slice(0, overflow);
46
+ keys.forEach((key) => contextCache.delete(key));
47
+ };
3
48
  export const buildContextPackage = async (vaultPath, query, limit, maxTokens, agentId, mode) => {
49
+ const cacheKey = toCacheKey(vaultPath, query, limit, maxTokens, agentId, mode);
50
+ const dataSignature = await readContextDataSignature(vaultPath);
51
+ const cached = contextCacheGet(cacheKey, dataSignature);
52
+ if (cached) {
53
+ return cached;
54
+ }
4
55
  const results = await searchKnowledge(vaultPath, query, limit, agentId, mode);
5
- const sections = selectContextSections(results, maxTokens);
6
- return {
56
+ const durableSections = selectContextSections(results, maxTokens);
57
+ const volatileSections = await searchVolatileMemory(vaultPath, query, Math.min(3, limit), agentId, mode ?? 'hybrid');
58
+ const sections = [...volatileSections, ...durableSections];
59
+ const context = {
7
60
  query,
8
61
  sections,
9
- content: formatContextPackage(query, sections)
62
+ content: formatContextPackage(query, sections),
63
+ ...(volatileSections.length > 0 ? { volatileSections } : {})
10
64
  };
65
+ contextCacheSet({
66
+ key: cacheKey,
67
+ createdAt: Date.now(),
68
+ dataSignature,
69
+ context
70
+ });
71
+ return context;
11
72
  };
12
73
  export const buildContext = async (vaultPath, query, limit, maxTokens, agentId, mode) => {
13
74
  const contextPackage = await buildContextPackage(vaultPath, query, limit, maxTokens, agentId, mode);