Compare commits
38
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
638e84c324 | ||
|
|
bb272d7416 | ||
|
|
e393cc6a99 | ||
|
|
7fb51e9918 | ||
|
|
e5a982e99a | ||
|
|
6b680bdb90 | ||
|
|
77c635b16b | ||
|
|
2fede46dcd | ||
|
|
54201d8c22 | ||
|
|
a6dbe2f6da | ||
|
|
368a757612 | ||
|
|
a8675ac33b | ||
|
|
de632ba6cc | ||
|
|
66c87842e2 | ||
|
|
20b78a9a20 | ||
|
|
5d4b3427a4 | ||
|
|
1c7db6d499 | ||
|
|
0786ddcb06 | ||
|
|
eeb5b79cf2 | ||
|
|
5990feb1f6 | ||
|
|
d27a738fee | ||
|
|
669e184cf6 | ||
|
|
ebc3f948c1 | ||
|
|
fe6a02024c | ||
|
|
4a065d9838 | ||
|
|
e3c6ef5684 | ||
|
|
98c14e23f1 | ||
|
|
ff1716de40 | ||
|
|
fec5325c7a | ||
|
|
27d9521e7f | ||
|
|
a7cb8d4c76 | ||
|
|
53cd00284d | ||
|
|
b73b4d4f97 | ||
|
|
1d1f6a90ff | ||
|
|
f220bcd95a | ||
|
|
678a1d1dba | ||
|
|
8781c0c3eb | ||
|
|
d6b17e8819 |
@@ -3,8 +3,7 @@
|
|||||||
Evidence-first brain over the ops/eSlider stack. Facts need proof or they are
|
Evidence-first brain over the ops/eSlider stack. Facts need proof or they are
|
||||||
`(not confirmed)`.
|
`(not confirmed)`.
|
||||||
|
|
||||||
Read first: [PLAN](PLAN.md) → [docs](docs/) → [roadmap](docs/roadmap.md)
|
Read first: [PLAN](PLAN.md) → [docs](docs/).
|
||||||
(epic [#16](https://git.produktor.io/eSlider/2dph/issues/16)).
|
|
||||||
|
|
||||||
## Method (detective, no fork)
|
## Method (detective, no fork)
|
||||||
|
|
||||||
@@ -40,7 +39,7 @@ PLAN.md decisions + execution + open questions
|
|||||||
docs/ published docs
|
docs/ published docs
|
||||||
skills/ in-project agent skills (vendored, no external links)
|
skills/ in-project agent skills (vendored, no external links)
|
||||||
bin/ self-describing tools bin/{subject}/{method}.go (shebang)
|
bin/ self-describing tools bin/{subject}/{method}.go (shebang)
|
||||||
bin/brain/ search.go serve.go index.go add.go get.go stats.go eval.go watch.go
|
bin/brain/ search.go serve.go index.go get.go stats.go eval.go watch.go
|
||||||
bin/chats/ sync.go import.go facts.go apply.go; libs in internal/chats
|
bin/chats/ sync.go import.go facts.go apply.go; libs in internal/chats
|
||||||
bin/mail/ sync.go import.go (index_mail → brain/index.go)
|
bin/mail/ sync.go import.go (index_mail → brain/index.go)
|
||||||
bin/markdown/ import.go (H2 leaf split; Python bin/md/import fallback)
|
bin/markdown/ import.go (H2 leaf split; Python bin/md/import fallback)
|
||||||
@@ -74,9 +73,9 @@ bin/brain/index.go --rebuild # rebuil
|
|||||||
`pdftotext -layout` fast path (~15ms); textless/scanned PDFs fall back to
|
`pdftotext -layout` fast path (~15ms); textless/scanned PDFs fall back to
|
||||||
docling (isolated subprocess — its native onnx can segfault the parent).
|
docling (isolated subprocess — its native onnx can segfault the parent).
|
||||||
Conversion never touches the brain DB (crash safety).
|
Conversion never touches the brain DB (crash safety).
|
||||||
- `index_mail` is a deprecation shim for `bin/brain/index.go --rebuild`. Bulk
|
- `index_mail` is a deprecation shim for `bin/brain/index.go --rebuild`. Ladybug
|
||||||
rebuild still deletes `var/kb.lbug` and creates FTS/HNSW last. Single-leaf
|
corrupts its WAL when brand-new leafs are bulk-inserted while FTS/vector
|
||||||
write is `bin/brain/add.go` (safe while indexes exist; do not DROP INDEX).
|
indexes exist; a fresh DB with indexes created last is the only safe path.
|
||||||
Keep conversion + indexing separate so a conversion crash can't leave the
|
Keep conversion + indexing separate so a conversion crash can't leave the
|
||||||
DB mid-transaction.
|
DB mid-transaction.
|
||||||
|
|
||||||
@@ -89,8 +88,6 @@ bin/kb/search "query" [--repo X] # deprecated wrapper → bin/b
|
|||||||
bin/brain/search.go "query" [--root facts|info] # deduction search → YAML
|
bin/brain/search.go "query" [--root facts|info] # deduction search → YAML
|
||||||
bin/brain/search.go "query" --no-web # local graph only
|
bin/brain/search.go "query" --no-web # local graph only
|
||||||
eval "$(bin/cgo/zig env)" # Zig cc + liblbug (not gcc)
|
eval "$(bin/cgo/zig env)" # Zig cc + liblbug (not gcc)
|
||||||
bin/brain/add.go --text T --root facts --source "a.md x b.md" # incremental write
|
|
||||||
bin/brain/add.go --json # stdin leaf or {leafs:[...]}
|
|
||||||
bin/brain/get.go <id> [--body] [--json] # Go read; Python bin/kb/get CI fallback
|
bin/brain/get.go <id> [--body] [--json] # Go read; Python bin/kb/get CI fallback
|
||||||
bin/brain/stats.go [--json]
|
bin/brain/stats.go [--json]
|
||||||
bin/brain/eval.go [--json] # recall@5; questions in internal/brain/rank
|
bin/brain/eval.go [--json] # recall@5; questions in internal/brain/rank
|
||||||
|
|||||||
@@ -4,9 +4,7 @@ A brain that loves facts and deduction. Evidence-first knowledge graph + hybrid
|
|||||||
RAG over the operational Brain/ops/eSlider stack. Built like Sherlock
|
RAG over the operational Brain/ops/eSlider stack. Built like Sherlock
|
||||||
Holmes: nothing is asserted unless it has proof.
|
Holmes: nothing is asserted unless it has proof.
|
||||||
|
|
||||||
Status: **in progress** — read path + MCP work; v1 goal is [epic #16](https://git.produktor.io/eSlider/2dph/issues/16)
|
Status: **in progress** — this file is the plan and the record of decisions.
|
||||||
(milestone [v1 detective brain](https://git.produktor.io/eSlider/2dph/milestone/12)).
|
|
||||||
Gap: [docs/roadmap.md](docs/roadmap.md).
|
|
||||||
|
|
||||||
## What
|
## What
|
||||||
|
|
||||||
@@ -31,9 +29,9 @@ detective method: **a fact needs ≥2 independent sources or it is
|
|||||||
| D3 | web search | Go client `bin/web/search.go` (`internal/websearch`). SearXNG URL is config (`BRAIN_SEARCH_URL`). Optional Compose profile `searxng` (sanitized settings). Do not run a second copy on a host that already has one. Empty/`throttled` ≠ “nothing exists”. |
|
| D3 | web search | Go client `bin/web/search.go` (`internal/websearch`). SearXNG URL is config (`BRAIN_SEARCH_URL`). Optional Compose profile `searxng` (sanitized settings). Do not run a second copy on a host that already has one. Empty/`throttled` ≠ “nothing exists”. |
|
||||||
| D4 | embeddings | **model2vec** `minishlab/potion-multilingual-128M` instead of embeddinggemma. |
|
| D4 | embeddings | **model2vec** `minishlab/potion-multilingual-128M` instead of embeddinggemma. |
|
||||||
| D5 | parser | **mistune** for MD → leaf extraction (duckdb-md documented as future optional SQL/export layer, not v1). |
|
| D5 | parser | **mistune** for MD → leaf extraction (duckdb-md documented as future optional SQL/export layer, not v1). |
|
||||||
| D6 | graph engine | **LadybugDB**. Go is the service (`bin/brain/search.go`, `bin/brain/serve.go` in-process, `internal/brain`). Read path is Go + Zig CGO (D21). Python `bin/kb/{get,stats,eval}` is the CI fallback when Zig/libs are not fetched. Incremental write is Python `bin/kb/add` (`bin/brain/add.go`). Bulk rebuild stays `compose --profile index` until the Go write path is safe. |
|
| D6 | graph engine | **LadybugDB**. Go is the service (`bin/brain/search.go`, `bin/brain/serve.go` in-process, `internal/brain`). Read path is Go + Zig CGO (D21). Python `bin/kb/{get,stats,eval}` is the CI fallback when Zig/libs are not fetched. Index/write stays Python (`compose --profile index`) until the Go write path is safe. |
|
||||||
| D7 | db access | `db-yaml`/`psql-yq`-style, read-only, YAML out. OnlyOffice Postgres via SSH tunnel (`127.0.0.1:5433`). |
|
| D7 | db access | `db-yaml`/`psql-yq`-style, read-only, YAML out. OnlyOffice Postgres via SSH tunnel (`127.0.0.1:5433`). |
|
||||||
| D8 | evidence | detective method: ≥2 independent sources or `(not confirmed)`. 2-source auto-pair docker ps × compose × ssh-config × docs. |
|
| D8 | evidence | detective method: ≥2 independent sources or `(not confirmed)`. Auto-pair docker ps × compose × ssh-config × docs. |
|
||||||
| D9 | facts/goal model | Who / What / How / Where / When + evidence + confidence on every edge. |
|
| D9 | facts/goal model | Who / What / How / Where / When + evidence + confidence on every edge. |
|
||||||
| D10 | versioning | everything is a leaf with `sha256 + observed_at + source_rev`; `File-[:HAS_VERSION]->Commit-[:AUTHORED]->Person`. Stale = `source_rev` < git HEAD. |
|
| D10 | versioning | everything is a leaf with `sha256 + observed_at + source_rev`; `File-[:HAS_VERSION]->Commit-[:AUTHORED]->Person`. Stale = `source_rev` < git HEAD. |
|
||||||
| D11 | strong/weak | `root` column: `facts` (strong) vs `info` (weak). Answer is `confirmed` only from facts root. |
|
| D11 | strong/weak | `root` column: `facts` (strong) vs `info` (weak). Answer is `confirmed` only from facts root. |
|
||||||
@@ -43,9 +41,9 @@ detective method: **a fact needs ≥2 independent sources or it is
|
|||||||
| D15 | repo | Gitea [`eSlider/2dph`](https://git.produktor.io/eSlider/2dph) is origin + [issues](https://git.produktor.io/eSlider/2dph/issues). GitHub `eSlider/2dph` is the public clone (PRs + Actions CI). No direct `main` pushes. TDD → PR → CI green → merge. |
|
| D15 | repo | Gitea [`eSlider/2dph`](https://git.produktor.io/eSlider/2dph) is origin + [issues](https://git.produktor.io/eSlider/2dph/issues). GitHub `eSlider/2dph` is the public clone (PRs + Actions CI). No direct `main` pushes. TDD → PR → CI green → merge. |
|
||||||
| D16 | contradictions | ≥2 yes vs ≥2 no → unrelated sources conflict → hypothesis → `(not confirmed)`. Resolution (authority, staleness adjudication) = **v2**, tracked as open question. |
|
| D16 | contradictions | ≥2 yes vs ≥2 no → unrelated sources conflict → hypothesis → `(not confirmed)`. Resolution (authority, staleness adjudication) = **v2**, tracked as open question. |
|
||||||
| D17 | assertion gate | Fact-check every *claim* (facts → info → live → web), not every edit. `bin/brain/search.go` adds a `web` block when there is no facts hit (`throttled`/`skipped`/`refused` ≠ absence). `--root` and `--no-web` stay local. Missing graph ≠ “does not exist”. |
|
| D17 | assertion gate | Fact-check every *claim* (facts → info → live → web), not every edit. `bin/brain/search.go` adds a `web` block when there is no facts hit (`throttled`/`skipped`/`refused` ≠ absence). `--root` and `--no-web` stay local. Missing graph ≠ “does not exist”. |
|
||||||
| D18 | reasoner | Pluggable OpenAI-compatible URL (`REASONER_BASE_URL`). RAM: `Qwen/Qwen3.5-9B`. Quality: `prism-ml/Bonsai-27B-gguf` or `Qwen/Qwen3.6-27B`. No official Qwen3.6-9B. CPU bake-off: `bin/reasoner/bakeoff.go` + compose profile `reasoner` (`OLLAMA_NUM_GPU=0`, `:11435`). PicoClaw is compose profile `picoclaw`; tools are `search`/`get`/`audit`. Weights are not copied into the 2dph image. Agent lever/loop: [#15](https://git.produktor.io/eSlider/2dph/issues/15). |
|
| D18 | reasoner | Pluggable OpenAI-compatible URL (`REASONER_BASE_URL`). RAM: `Qwen/Qwen3.5-9B`. Quality: `prism-ml/Bonsai-27B-gguf` or `Qwen/Qwen3.6-27B`. No official Qwen3.6-9B. CPU bake-off: `bin/reasoner/bakeoff.go` + compose profile `reasoner` (`OLLAMA_NUM_GPU=0`, `:11435`). PicoClaw is not shipped; tools are `search`/`get`/`audit`. Weights are not copied into the 2dph image. |
|
||||||
| D19 | git history | [go-git](https://github.com/go-git/go-git) via `bin/git/import.go`. No subprocess of the git binary. Conversion prints commit leafs; brain write is `bin/brain/index.go`. |
|
| D19 | git history | [go-git](https://github.com/go-git/go-git) via `bin/git/import.go`. No subprocess of the git binary. Conversion prints commit leafs; brain write is `bin/brain/index.go`. |
|
||||||
| D20 | agent API | OpenAPI + MCP are generated from the same `internal/httpapi.Ops` table as `bin/brain/serve.go` handlers. `GET /openapi.json`, `POST /mcp` (JSON-RPC tools/list + tools/call). Tool names match OpenAPI paths (`search`/`get`/`stats`/`audit`/`ingest`). |
|
| D20 | agent API | OpenAPI + MCP are generated from the same `internal/httpapi.Ops` table as `bin/brain/serve.go` handlers. `GET /openapi.json`, `POST /mcp` (JSON-RPC tools/list + tools/call). Tool names match OpenAPI paths (`search`/`get`/`stats`/`audit`). |
|
||||||
| D21 | CGO | Ladybug/tokenizers CGO is compiled with **Zig** (`bin/cgo/zcc` → `zig cc -target …-linux-gnu`), not gcc. `bin/cgo/zig` pins Zig 0.14.1 + liblbug 0.19.1 + libtokenizers 1.27.0. Compose `target: api` has no CPython; write/rebuild is profile `index`. |
|
| D21 | CGO | Ladybug/tokenizers CGO is compiled with **Zig** (`bin/cgo/zcc` → `zig cc -target …-linux-gnu`), not gcc. `bin/cgo/zig` pins Zig 0.14.1 + liblbug 0.19.1 + libtokenizers 1.27.0. Compose `target: api` has no CPython; write/rebuild is profile `index`. |
|
||||||
|
|
||||||
## Architecture
|
## Architecture
|
||||||
@@ -57,10 +55,8 @@ detective method: **a fact needs ≥2 independent sources or it is
|
|||||||
skills/ in-project skills (web-search, postgres, brain, picoclaw, diataxis-docs)
|
skills/ in-project skills (web-search, postgres, brain, picoclaw, diataxis-docs)
|
||||||
bin/
|
bin/
|
||||||
facts/extract.go audit.go crm.go # D14 shebang; Python implementation
|
facts/extract.go audit.go crm.go # D14 shebang; Python implementation
|
||||||
kb/index Python bulk write (called by bin/brain/index.go)
|
kb/index Python write path (called by bin/brain/index.go)
|
||||||
kb/add Python incremental write (called by bin/brain/add.go)
|
|
||||||
brain/index.go rebuild FTS + HNSW (incl. --with-mail)
|
brain/index.go rebuild FTS + HNSW (incl. --with-mail)
|
||||||
brain/add.go incremental leaf write (no rebuild)
|
|
||||||
brain/get.go stats.go eval.go # Go read (cgo); Python bin/kb/* CI fallback
|
brain/get.go stats.go eval.go # Go read (cgo); Python bin/kb/* CI fallback
|
||||||
brain/watch.go
|
brain/watch.go
|
||||||
brain/search.go deduction: facts → info → web-search
|
brain/search.go deduction: facts → info → web-search
|
||||||
@@ -87,8 +83,7 @@ detective method: **a fact needs ≥2 independent sources or it is
|
|||||||
|
|
||||||
Node tables: `Person, Service, Host, Container, Repo, File, Commit, Leaf`.
|
Node tables: `Person, Service, Host, Container, Repo, File, Commit, Leaf`.
|
||||||
`Leaf(embedding FLOAT[N])` — FTS on `text`, HNSW vector index on `embedding`.
|
`Leaf(embedding FLOAT[N])` — FTS on `text`, HNSW vector index on `embedding`.
|
||||||
Edges: `RUNS / USES / FROM_FILE / HAS_VERSION / AUTHORED / ABOUT / ASSOCIATED / SIMILAR_0.85`.
|
Edges: `RUNS / USES / HAS_VERSION / AUTHORED / ABOUT / ASSOCIATED / SIMILAR_0.85`.
|
||||||
`FROM_FILE` / `HAS_VERSION` exist in schema; search `--hop` does not walk them yet ([#17](https://git.produktor.io/eSlider/2dph/issues/17)).
|
|
||||||
|
|
||||||
Common props on every node/edge: `root`, `confidence`, `evidence[]`, `how`,
|
Common props on every node/edge: `root`, `confidence`, `evidence[]`, `how`,
|
||||||
`where`, `when`, `source_rev`.
|
`where`, `when`, `source_rev`.
|
||||||
@@ -113,9 +108,9 @@ Common props on every node/edge: `root`, `confidence`, `evidence[]`, `how`,
|
|||||||
## Open questions (v2)
|
## Open questions (v2)
|
||||||
|
|
||||||
- OQ1: mutually-contradicting evidence — how to resolve (authority weighting,
|
- OQ1: mutually-contradicting evidence — how to resolve (authority weighting,
|
||||||
temporal freshness, audit adjudication). **v2**; does not block epic #16.
|
temporal freshness, audit adjudication).
|
||||||
- OQ2: OCR — poppler `pdftotext` fast-path exists; scans still docling.
|
- OQ2: OCR pipeline for pdfs/images/docs — mostly solved: poppler pdftotext
|
||||||
[#6](https://git.produktor.io/eSlider/2dph/issues/6) (v2, does not block #16).
|
fast-path for born-digital PDFs, docling fallback for the ~5% textless ones.
|
||||||
- OQ3: optional duckdb-md layer for `SELECT … FORMAT MARKDOWN` export/write-back.
|
- OQ3: optional duckdb-md layer for `SELECT … FORMAT MARKDOWN` export/write-back.
|
||||||
- OQ4: YAML-first storage for leafs — deferred: JSON is ~10x faster to
|
- OQ4: YAML-first storage for leafs — deferred: JSON is ~10x faster to
|
||||||
serialize and unambiguous; YAML only where humans edit files.
|
serialize and unambiguous; YAML only where humans edit files.
|
||||||
@@ -143,7 +138,6 @@ Common props on every node/edge: `root`, `confidence`, `evidence[]`, `how`,
|
|||||||
3. python -m unittest discover -s bin/tools (includes published-docs SoT)
|
3. python -m unittest discover -s bin/tools (includes published-docs SoT)
|
||||||
4. `bin/facts/audit self` (lexicon internal consistency; `bin/facts/audit.go` is the D14 wrapper)
|
4. `bin/facts/audit self` (lexicon internal consistency; `bin/facts/audit.go` is the D14 wrapper)
|
||||||
5. `bin/kb/eval` (recall@5 ≥ 0.95). Local SoT is `bin/brain/eval.go` via Zig CGO.
|
5. `bin/kb/eval` (recall@5 ≥ 0.95). Local SoT is `bin/brain/eval.go` via Zig CGO.
|
||||||
CI SoT switch: [#19](https://git.produktor.io/eSlider/2dph/issues/19).
|
|
||||||
6. `bin/cgo/zig go build -tags system_ladybug` (compile search with zig cc; fetches pinned zig+libs).
|
6. `bin/cgo/zig go build -tags system_ladybug` (compile search with zig cc; fetches pinned zig+libs).
|
||||||
|
|
||||||
Feedback loop: every commit → PR → CI → green/gate → merge. Same discipline as
|
Feedback loop: every commit → PR → CI → green/gate → merge. Same discipline as
|
||||||
@@ -157,24 +151,5 @@ Feedback loop: every commit → PR → CI → green/gate → merge. Same discipl
|
|||||||
4. .venv: ladybug + model2vec + mistune
|
4. .venv: ladybug + model2vec + mistune
|
||||||
5. schema + tools with TDD (kb + md + facts + brain)
|
5. schema + tools with TDD (kb + md + facts + brain)
|
||||||
6. ~/.config/brain config
|
6. ~/.config/brain config
|
||||||
7. corpus extraction (facts/info) — **open**: [#18](https://git.produktor.io/eSlider/2dph/issues/18)
|
7. corpus extraction (facts/info)
|
||||||
8. verify: web-search smoke, onlyoffice pg, md-db round-trip, eval, audit
|
8. verify: web-search smoke, onlyoffice pg, md-db round-trip, eval, audit
|
||||||
|
|
||||||
## Gap to v1 (epic #16)
|
|
||||||
|
|
||||||
Read path + MCP are in. Incremental `brain/add` is in. The detective brain is
|
|
||||||
not closed until search can **walk** the graph and the facts+chats corpus
|
|
||||||
lands on rebuild. Board:
|
|
||||||
[epic #16](https://git.produktor.io/eSlider/2dph/issues/16),
|
|
||||||
milestone [v1 detective brain](https://git.produktor.io/eSlider/2dph/milestone/12).
|
|
||||||
Narrative: [docs/roadmap.md](docs/roadmap.md).
|
|
||||||
|
|
||||||
| Order | Issue | Gap |
|
|
||||||
|-------|-------|-----|
|
|
||||||
| 1 | [#14](https://git.produktor.io/eSlider/2dph/issues/14) | **in** — `bin/brain/add.go` / `POST /ingest` write facts+info without deleting `kb.lbug`. Bulk corpus still `--rebuild`. Leftover Python (mail/facts) is not the living-graph blocker. |
|
|
||||||
| 2 | [#17](https://git.produktor.io/eSlider/2dph/issues/17) | `--hop` errors. `FROM_FILE` / `HAS_VERSION` are in schema; search does not walk them. |
|
|
||||||
| 3 | [#18](https://git.produktor.io/eSlider/2dph/issues/18) | Rebuild is mostly `info` (repo md + mail). `facts/extract` and chats are not a first-class index input. WhatsApp sync is a stub. |
|
|
||||||
| 4 | [#15](https://git.produktor.io/eSlider/2dph/issues/15) | **in** — lever/loop documented (`search` → `get` → `audit`). |
|
|
||||||
| 5 | [#19](https://git.produktor.io/eSlider/2dph/issues/19) | GitHub CI recall still runs Python `bin/kb/eval`. |
|
|
||||||
|
|
||||||
Does **not** block epic close: [#6](https://git.produktor.io/eSlider/2dph/issues/6) OCR, OQ1, OQ3, OQ4.
|
|
||||||
@@ -7,16 +7,14 @@
|
|||||||
[](https://github.com/eSlider/2dph/releases)
|
[](https://github.com/eSlider/2dph/releases)
|
||||||
[](https://github.com/eSlider/2dph/stargazers)
|
[](https://github.com/eSlider/2dph/stargazers)
|
||||||
|
|
||||||
An evidence-first brain. **Facts need two independent sources, or they are
|
An evidence-first brain over the operational eSlider stack. **Facts need two
|
||||||
`(not confirmed)`.** Cursor is not the runtime.
|
independent sources, or they are `(not confirmed)`.**
|
||||||
|
|
||||||
`2dph` is a single embedded knowledge graph (LadybugDB) with native **HNSW
|
`2dph` is a single embedded knowledge graph (LadybugDB = Kuzu successor) with
|
||||||
vector** + **BM25 full-text** indexes. Search is *deduction*: confirmed facts
|
native **HNSW vector** + **BM25 full-text** indexes, built from markdown,
|
||||||
first, supporting info second, `web-search` as the independent second source
|
compose files, ssh config, docker state, and git history. Search is
|
||||||
when the local graph cannot confirm.
|
*deduction*: confirmed facts first, supporting info second, `web-search` as
|
||||||
|
the independent second source when the local graph cannot confirm.
|
||||||
Run it: [docs/runbook.md](docs/runbook.md). Design: [docs/design.md](docs/design.md).
|
|
||||||
Docs index: [docs/README.md](docs/README.md).
|
|
||||||
|
|
||||||
## Architecture
|
## Architecture
|
||||||
|
|
||||||
@@ -76,7 +74,7 @@ graph TB
|
|||||||
## The method
|
## The method
|
||||||
|
|
||||||
Every assertion is `Who / What / How / Where / When + evidence + confidence`,
|
Every assertion is `Who / What / How / Where / When + evidence + confidence`,
|
||||||
mirroring the detective method: **≥2 independent sources confirm a
|
mirroring the detective detective skill: **≥2 independent sources confirm a
|
||||||
fact; conflicting sources or a single source → `hypothesis` → `(not confirmed)`.**
|
fact; conflicting sources or a single source → `hypothesis` → `(not confirmed)`.**
|
||||||
|
|
||||||
| root | meaning | used for answers |
|
| root | meaning | used for answers |
|
||||||
@@ -120,23 +118,23 @@ Mail is a first-class corpus (retrievable through the same search):
|
|||||||
```bash
|
```bash
|
||||||
bin/mail/sync.go --source onlyoffice,gmail --workers 8 --out var/mail # raw sync (Go)
|
bin/mail/sync.go --source onlyoffice,gmail --workers 8 --out var/mail # raw sync (Go)
|
||||||
bin/mail/import.go --from-raw var/mail # JSON → markdown
|
bin/mail/import.go --from-raw var/mail # JSON → markdown
|
||||||
bin/brain/add.go --text T --root facts --source "a.md x b.md"
|
|
||||||
bin/brain/index.go --rebuild # rebuild brain (incl. mail)
|
bin/brain/index.go --rebuild # rebuild brain (incl. mail)
|
||||||
bin/brain/search.go "invoice from last week" # same search over mail leafs
|
bin/brain/search.go "invoice from last week" # same search over mail leafs
|
||||||
```
|
```
|
||||||
|
|
||||||
## Storage
|
## Storage
|
||||||
|
|
||||||
- **LadybugDB** — single `var/kb.lbug`, Cypher + HNSW + BM25, embedded.
|
- **LadybugDB** — single `var/kb.lbug`, Cypher property graph, HNSW + BM25
|
||||||
Read tools (`get` / `stats` / `eval`) are Go + Zig CGO (`bin/cgo/zcc`).
|
in one engine, embedded (no server), ACID, read-only-safe for concurrent
|
||||||
Python fallbacks stay for CI until the runner fetches Zig. Incremental
|
readers. Read tools (`get` / `stats` / `eval`) are Go + Zig CGO (`bin/cgo/zcc`); Python
|
||||||
write is `bin/brain/add.go` (Python `kblib.add_leafs`). Bulk rebuild is
|
`bin/kb/{get,stats,eval}` is the CI fallback. **Never `DROP INDEX` FTS/VECTOR** on Ladybug 0.19: DROP leaves
|
||||||
Compose profile `index` (`bin/brain/index.go --rebuild`).
|
ghost catalog tables (`_0_Leaf_vec_UPPER`) so recreate fails while
|
||||||
- **model2vec** — `potion-multilingual-128M` (256-dim), CPU, no Ollama
|
`SHOW_INDEXES` omits HNSW. Fresh indexes = delete `var/kb.lbug` +
|
||||||
runtime dependency.
|
`bin/brain/index.go --rebuild`. Use `ensure_indexes()` after upserts.
|
||||||
- facts and info split by `root` but written in the same transaction.
|
- **model2vec** — `potion-multilingual-128M` static embeddings (256-dim),
|
||||||
|
CPU-fast, deterministic, no Ollama runtime dependency.
|
||||||
Ladybug 0.19 DROP INDEX warning: [docs/runbook.md](docs/runbook.md).
|
- facts and info split semantically by `root` column but written inside the
|
||||||
|
same transaction.
|
||||||
|
|
||||||
## Tooling conventions
|
## Tooling conventions
|
||||||
|
|
||||||
@@ -147,13 +145,11 @@ machines. Tests gate every commit. HTTP: `bin/brain/serve.go` calls
|
|||||||
|
|
||||||
## Development
|
## Development
|
||||||
|
|
||||||
See the portable runbook: [docs/runbook.md](docs/runbook.md).
|
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
uv venv .venv
|
uv venv .venv # Python 3.12, uv-managed
|
||||||
uv pip install -r requirements.lock.txt
|
uv pip install -r requirements.lock.txt # pinned toolchain
|
||||||
bin/facts/audit.go self
|
bin/facts/audit.go self # lexicon consistency gate
|
||||||
go test ./... && uv run python -m unittest discover -s bin/tools -t .
|
go test ./... && python -m unittest discover -s bin/tools -t .
|
||||||
```
|
```
|
||||||
|
|
||||||
Docker (optional, cached model + var volumes):
|
Docker (optional, cached model + var volumes):
|
||||||
@@ -174,9 +170,7 @@ docker compose up brain-watch # auto re-index on change
|
|||||||
skills (`web-search`, `postgres`, …) that 2dph integrates
|
skills (`web-search`, `postgres`, …) that 2dph integrates
|
||||||
- detective method — the two-source method
|
- detective method — the two-source method
|
||||||
|
|
||||||
Work board (issues): [epic #16](https://git.produktor.io/eSlider/2dph/issues/16)
|
Work board (issues): [git.produktor.io/eSlider/2dph/issues](https://git.produktor.io/eSlider/2dph/issues).
|
||||||
on [git.produktor.io/eSlider/2dph/issues](https://git.produktor.io/eSlider/2dph/issues).
|
|
||||||
PRs and CI: GitHub [`eSlider/2dph`](https://github.com/eSlider/2dph).
|
PRs and CI: GitHub [`eSlider/2dph`](https://github.com/eSlider/2dph).
|
||||||
|
|
||||||
See [PLAN.md](PLAN.md) for decisions, [docs/roadmap.md](docs/roadmap.md) for
|
See [PLAN.md](PLAN.md) for decisions, execution status, and v2 open questions.
|
||||||
the gap to v1, and v2 open questions.
|
|
||||||
|
|||||||
@@ -1,21 +0,0 @@
|
|||||||
//usr/bin/env go run -tags=brain_add "$0" "$@"; exit
|
|
||||||
//go:build brain_add
|
|
||||||
//
|
|
||||||
// bin/brain/add.go - incremental leaf write (Python kblib, no rebuild).
|
|
||||||
//
|
|
||||||
// ./bin/brain/add.go --text T --root facts --source "a.md x b.md"
|
|
||||||
// ./bin/brain/add.go --json
|
|
||||||
//
|
|
||||||
// D6: write stays Python. Does not delete var/kb.lbug.
|
|
||||||
// NOTE: never run `gofmt -w` on this file — it breaks the shebang.
|
|
||||||
package main
|
|
||||||
|
|
||||||
import (
|
|
||||||
"os"
|
|
||||||
|
|
||||||
"github.com/eSlider/2dph/internal/cmdbin"
|
|
||||||
)
|
|
||||||
|
|
||||||
func main() {
|
|
||||||
os.Exit(cmdbin.ExecFile("bin/kb/add", os.Args[1:]))
|
|
||||||
}
|
|
||||||
+2
-2
@@ -7,8 +7,8 @@
|
|||||||
// ./bin/brain/index.go --rebuild --with-mail
|
// ./bin/brain/index.go --rebuild --with-mail
|
||||||
// ./bin/brain/index.go --dry-run --with-mail
|
// ./bin/brain/index.go --dry-run --with-mail
|
||||||
//
|
//
|
||||||
// v1 write: bin/brain/add.go for one/few leafs (indexes may already exist).
|
// v1 write is always a rebuild when mail is included (live FTS/HNSW + bulk
|
||||||
// Bulk mail/corpus still --rebuild (fresh file, indexes last).
|
// insert corrupts Ladybug 0.19 WAL). `add` is v2.
|
||||||
// NOTE: never run `gofmt -w` on this file — it breaks the shebang.
|
// NOTE: never run `gofmt -w` on this file — it breaks the shebang.
|
||||||
package main
|
package main
|
||||||
|
|
||||||
|
|||||||
-114
@@ -1,114 +0,0 @@
|
|||||||
#!/usr/bin/env python3
|
|
||||||
"""kb/add - incremental leaf write (no rebuild).
|
|
||||||
|
|
||||||
bin/kb/add --text T --root facts|info --source S
|
|
||||||
bin/kb/add --json # stdin: one object or {"leafs":[...]}
|
|
||||||
bin/kb/add --db PATH --json
|
|
||||||
|
|
||||||
Writes facts+info in one Ladybug transaction. Does not delete kb.lbug.
|
|
||||||
Embedding is used when provided; otherwise model2vec encodes the text.
|
|
||||||
"""
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import json
|
|
||||||
import sys
|
|
||||||
from pathlib import Path
|
|
||||||
|
|
||||||
ROOT = Path(__file__).resolve().parents[2]
|
|
||||||
sys.path.insert(0, str(ROOT / "bin" / "tools"))
|
|
||||||
|
|
||||||
from kblib import ( # noqa: E402
|
|
||||||
EMBED_DIM,
|
|
||||||
add_leafs,
|
|
||||||
connect,
|
|
||||||
ensure_indexes,
|
|
||||||
init_schema,
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def _as_leafs(payload: object) -> list[dict]:
|
|
||||||
if isinstance(payload, list):
|
|
||||||
return [dict(x) for x in payload]
|
|
||||||
if isinstance(payload, dict):
|
|
||||||
if "leafs" in payload:
|
|
||||||
return [dict(x) for x in payload["leafs"]]
|
|
||||||
return [dict(payload)]
|
|
||||||
raise ValueError("json must be an object, a list, or {leafs:[...]}")
|
|
||||||
|
|
||||||
|
|
||||||
def _embed_missing(leafs: list[dict]) -> None:
|
|
||||||
missing = [lf for lf in leafs if not lf.get("embedding")]
|
|
||||||
if not missing:
|
|
||||||
return
|
|
||||||
from model2vec import StaticModel
|
|
||||||
|
|
||||||
model = StaticModel.from_pretrained("minishlab/potion-multilingual-128M")
|
|
||||||
for lf in missing:
|
|
||||||
text = str(lf.get("text") or "")
|
|
||||||
vec = model.encode([text])[0].astype(float).tolist()
|
|
||||||
if len(vec) != EMBED_DIM:
|
|
||||||
vec = (vec + [0.0] * EMBED_DIM)[:EMBED_DIM]
|
|
||||||
lf["embedding"] = vec
|
|
||||||
|
|
||||||
|
|
||||||
def main(argv: list[str]) -> int:
|
|
||||||
import argparse
|
|
||||||
|
|
||||||
p = argparse.ArgumentParser(description="add leafs without rebuilding the brain")
|
|
||||||
p.add_argument("--db", default="", help="path to kb.lbug (default var/kb.lbug)")
|
|
||||||
p.add_argument("--json", action="store_true", help="read leaf JSON from stdin")
|
|
||||||
p.add_argument("--text", default="", help="leaf text")
|
|
||||||
p.add_argument("--root", default="info", choices=("facts", "info"))
|
|
||||||
p.add_argument("--source", default="")
|
|
||||||
p.add_argument("--confidence", default="confirmed")
|
|
||||||
p.add_argument("--source-rev", default="working-tree")
|
|
||||||
p.add_argument("--how", default="brain/add")
|
|
||||||
p.add_argument("--loc", default="")
|
|
||||||
p.add_argument("--type", default="reference", dest="type_")
|
|
||||||
args = p.parse_args(argv)
|
|
||||||
|
|
||||||
if args.json:
|
|
||||||
raw = sys.stdin.read()
|
|
||||||
if not raw.strip():
|
|
||||||
print("kb/add: empty stdin", file=sys.stderr)
|
|
||||||
return 2
|
|
||||||
leafs = _as_leafs(json.loads(raw))
|
|
||||||
else:
|
|
||||||
if not args.text or not args.source:
|
|
||||||
print("kb/add: --text and --source are required (or --json)", file=sys.stderr)
|
|
||||||
return 2
|
|
||||||
leafs = [{
|
|
||||||
"text": args.text,
|
|
||||||
"root": args.root,
|
|
||||||
"source": args.source,
|
|
||||||
"confidence": args.confidence,
|
|
||||||
"source_rev": args.source_rev,
|
|
||||||
"how": args.how,
|
|
||||||
"loc": args.loc or args.source,
|
|
||||||
"type": args.type_,
|
|
||||||
}]
|
|
||||||
|
|
||||||
for lf in leafs:
|
|
||||||
if not lf.get("text") or not lf.get("source"):
|
|
||||||
print("kb/add: each leaf needs text and source", file=sys.stderr)
|
|
||||||
return 2
|
|
||||||
|
|
||||||
_embed_missing(leafs)
|
|
||||||
|
|
||||||
from kblib import DB_PATH, VAR
|
|
||||||
|
|
||||||
dbpath = Path(args.db) if args.db else DB_PATH
|
|
||||||
dbpath.parent.mkdir(parents=True, exist_ok=True)
|
|
||||||
VAR.mkdir(exist_ok=True)
|
|
||||||
db, conn = connect(dbpath, read_only=False)
|
|
||||||
init_schema(conn)
|
|
||||||
ids = add_leafs(conn, leafs)
|
|
||||||
ensure_indexes(conn)
|
|
||||||
conn.close()
|
|
||||||
db.close()
|
|
||||||
print(json.dumps({"mode": "add", "ids": ids, "db": str(dbpath)}))
|
|
||||||
return 0
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
sys.exit(main(sys.argv[1:]))
|
|
||||||
+1
-45
@@ -4,7 +4,7 @@ Single embedded graph `var/kb.lbug`. Two roots: facts (assertions backed by
|
|||||||
>=2 independent sources) and info (narrative leafs). Hybrid retrieval: BM25
|
>=2 independent sources) and info (narrative leafs). Hybrid retrieval: BM25
|
||||||
(FTS extension) + HNSW cosine (VECTOR extension) + Cypher graph hops.
|
(FTS extension) + HNSW cosine (VECTOR extension) + Cypher graph hops.
|
||||||
|
|
||||||
All access is read-only unless `--rebuild` (kb/index) or `kb/add`.
|
All access is read-only unless `--rebuild` is passed to kb/index.
|
||||||
"""
|
"""
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
@@ -118,50 +118,6 @@ def upsert_leaf(conn: ladybug.Connection, *, text: str, root: str, confidence: s
|
|||||||
return lid
|
return lid
|
||||||
|
|
||||||
|
|
||||||
def add_leafs(conn: ladybug.Connection, leafs: list[dict]) -> list[str]:
|
|
||||||
"""Write facts+info leafs in one transaction. Safe while FTS/HNSW exist.
|
|
||||||
|
|
||||||
Each leaf dict: text, source, optional root/confidence/source_rev/how/loc/type/embedding.
|
|
||||||
Does not delete the database file. Measured on Ladybug 0.19: MERGE of new
|
|
||||||
ids (and updates) stays FTS+HNSW queryable; DROP INDEX is the fatal path.
|
|
||||||
"""
|
|
||||||
if not leafs:
|
|
||||||
return []
|
|
||||||
started = False
|
|
||||||
try:
|
|
||||||
conn.execute("BEGIN TRANSACTION")
|
|
||||||
started = True
|
|
||||||
except Exception:
|
|
||||||
started = False
|
|
||||||
ids: list[str] = []
|
|
||||||
try:
|
|
||||||
for lf in leafs:
|
|
||||||
ids.append(
|
|
||||||
upsert_leaf(
|
|
||||||
conn,
|
|
||||||
text=str(lf["text"]),
|
|
||||||
root=str(lf.get("root") or ROOT_INFO),
|
|
||||||
confidence=str(lf.get("confidence") or CONF_CONFIRMED),
|
|
||||||
source=str(lf["source"]),
|
|
||||||
source_rev=str(lf.get("source_rev") or "working-tree"),
|
|
||||||
how=str(lf.get("how") or "brain/add"),
|
|
||||||
loc=str(lf.get("loc") or lf.get("source") or ""),
|
|
||||||
type_=str(lf.get("type") or lf.get("type_") or "reference"),
|
|
||||||
embedding=lf.get("embedding"),
|
|
||||||
)
|
|
||||||
)
|
|
||||||
if started:
|
|
||||||
conn.execute("COMMIT")
|
|
||||||
except Exception:
|
|
||||||
if started:
|
|
||||||
try:
|
|
||||||
conn.execute("ROLLBACK")
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
raise
|
|
||||||
return ids
|
|
||||||
|
|
||||||
|
|
||||||
def leaf_index_names(conn: ladybug.Connection) -> set[str]:
|
def leaf_index_names(conn: ladybug.Connection) -> set[str]:
|
||||||
"""Return index names on the Leaf table (e.g. {'id', 'Leaf_vec', '_PK'})."""
|
"""Return index names on the Leaf table (e.g. {'id', 'Leaf_vec', '_PK'})."""
|
||||||
rows = conn.execute("CALL SHOW_INDEXES() RETURN *").get_all()
|
rows = conn.execute("CALL SHOW_INDEXES() RETURN *").get_all()
|
||||||
|
|||||||
@@ -75,20 +75,9 @@ class BinLayoutTest(unittest.TestCase):
|
|||||||
)
|
)
|
||||||
|
|
||||||
def test_brain_methods_are_shebangs(self) -> None:
|
def test_brain_methods_are_shebangs(self) -> None:
|
||||||
for method in ("index.go", "add.go", "get.go", "stats.go", "eval.go", "watch.go"):
|
for method in ("index.go", "get.go", "stats.go", "eval.go", "watch.go"):
|
||||||
self._assert_shebang(f"bin/brain/{method}")
|
self._assert_shebang(f"bin/brain/{method}")
|
||||||
|
|
||||||
def test_brain_add_is_python_write_not_rebuild(self) -> None:
|
|
||||||
self._assert_shebang("bin/brain/add.go")
|
|
||||||
text = (ROOT / "bin" / "brain" / "add.go").read_text()
|
|
||||||
self.assertIn("cmdbin.ExecFile", text)
|
|
||||||
self.assertIn("bin/kb/add", text)
|
|
||||||
self.assertNotIn("--rebuild", text)
|
|
||||||
py = (ROOT / "bin" / "kb" / "add").read_text()
|
|
||||||
self.assertIn("add_leafs", py)
|
|
||||||
self.assertIn("--json", py)
|
|
||||||
self.assertNotIn("unlink", py.lower())
|
|
||||||
|
|
||||||
def test_brain_get_stats_eval_are_not_python_exec(self) -> None:
|
def test_brain_get_stats_eval_are_not_python_exec(self) -> None:
|
||||||
for method in ("get.go", "stats.go", "eval.go"):
|
for method in ("get.go", "stats.go", "eval.go"):
|
||||||
text = (ROOT / "bin" / "brain" / method).read_text()
|
text = (ROOT / "bin" / "brain" / method).read_text()
|
||||||
|
|||||||
@@ -1,69 +0,0 @@
|
|||||||
"""Incremental add writes leafs without deleting kb.lbug."""
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import json
|
|
||||||
import os
|
|
||||||
import subprocess
|
|
||||||
import sys
|
|
||||||
import tempfile
|
|
||||||
import unittest
|
|
||||||
from pathlib import Path
|
|
||||||
|
|
||||||
ROOT = Path(__file__).resolve().parents[2]
|
|
||||||
|
|
||||||
|
|
||||||
class KbAddCLITest(unittest.TestCase):
|
|
||||||
def test_json_add_does_not_delete_db(self) -> None:
|
|
||||||
tmp = Path(tempfile.mkdtemp())
|
|
||||||
dbpath = tmp / "kb.lbug"
|
|
||||||
py = sys.executable
|
|
||||||
venv_py = ROOT / ".venv" / "bin" / "python"
|
|
||||||
if venv_py.is_file():
|
|
||||||
py = str(venv_py)
|
|
||||||
payload = {
|
|
||||||
"text": "cli zebra leaf",
|
|
||||||
"root": "info",
|
|
||||||
"source": "cli-test",
|
|
||||||
"confidence": "confirmed",
|
|
||||||
"how": "test",
|
|
||||||
"loc": str(tmp),
|
|
||||||
"type": "reference",
|
|
||||||
"embedding": [0.0] * 256,
|
|
||||||
}
|
|
||||||
payload["embedding"][0] = 0.3
|
|
||||||
proc = subprocess.run(
|
|
||||||
[py, str(ROOT / "bin" / "kb" / "add"), "--db", str(dbpath), "--json"],
|
|
||||||
cwd=ROOT,
|
|
||||||
input=json.dumps(payload),
|
|
||||||
capture_output=True,
|
|
||||||
text=True,
|
|
||||||
env=os.environ.copy(),
|
|
||||||
check=False,
|
|
||||||
)
|
|
||||||
self.assertEqual(proc.returncode, 0, proc.stderr)
|
|
||||||
self.assertTrue(dbpath.exists(), "add must create the db, not skip write")
|
|
||||||
out = json.loads(proc.stdout)
|
|
||||||
self.assertEqual(out.get("mode"), "add")
|
|
||||||
self.assertEqual(len(out.get("ids") or []), 1)
|
|
||||||
again = subprocess.run(
|
|
||||||
[py, str(ROOT / "bin" / "kb" / "add"), "--db", str(dbpath), "--json"],
|
|
||||||
cwd=ROOT,
|
|
||||||
input=json.dumps({
|
|
||||||
**payload,
|
|
||||||
"text": "second moose leaf",
|
|
||||||
"source": "cli-test-2",
|
|
||||||
}),
|
|
||||||
capture_output=True,
|
|
||||||
text=True,
|
|
||||||
env=os.environ.copy(),
|
|
||||||
check=False,
|
|
||||||
)
|
|
||||||
self.assertEqual(again.returncode, 0, again.stderr)
|
|
||||||
self.assertTrue(dbpath.exists())
|
|
||||||
second = json.loads(again.stdout)
|
|
||||||
self.assertEqual(len(second.get("ids") or []), 1)
|
|
||||||
self.assertNotEqual(out["ids"][0], second["ids"][0])
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
unittest.main()
|
|
||||||
@@ -71,69 +71,6 @@ class KblibTest(unittest.TestCase):
|
|||||||
self.assertTrue(hits)
|
self.assertTrue(hits)
|
||||||
self.assertIn("Leaf_vec", kblib.leaf_index_names(self.conn))
|
self.assertIn("Leaf_vec", kblib.leaf_index_names(self.conn))
|
||||||
|
|
||||||
def test_add_after_indexes_keeps_fts_queryable(self):
|
|
||||||
"""Incremental add after FTS+HNSW must find the new leaf on both indexes."""
|
|
||||||
kblib.upsert_leaf(self.conn, text="seed fox leaf", root="info",
|
|
||||||
confidence="confirmed", source="s", source_rev="r1",
|
|
||||||
how="test", loc="/tmp", type_="reference",
|
|
||||||
embedding=make_emb(0.1))
|
|
||||||
kblib.ensure_indexes(self.conn)
|
|
||||||
ids = kblib.add_leafs(self.conn, [{
|
|
||||||
"text": "added zebra after index",
|
|
||||||
"root": "facts",
|
|
||||||
"confidence": "confirmed",
|
|
||||||
"source": "a.md x b.md",
|
|
||||||
"source_rev": "r1",
|
|
||||||
"how": "test",
|
|
||||||
"loc": "/tmp",
|
|
||||||
"type": "fact",
|
|
||||||
"embedding": make_emb(0.9),
|
|
||||||
}])
|
|
||||||
self.assertEqual(len(ids), 1)
|
|
||||||
fts = kblib.query_fts(self.conn, "zebra", 5)
|
|
||||||
self.assertTrue(fts)
|
|
||||||
self.assertIn("zebra", fts[0]["text"])
|
|
||||||
self.assertEqual(fts[0]["root"], "facts")
|
|
||||||
vec = kblib.query_vector(self.conn, make_emb(0.9), 5)
|
|
||||||
self.assertTrue(any("zebra" in h["text"] for h in vec))
|
|
||||||
fox = kblib.query_fts(self.conn, "fox", 5)
|
|
||||||
self.assertTrue(fox)
|
|
||||||
self.assertIn("fox", fox[0]["text"])
|
|
||||||
|
|
||||||
def test_add_facts_and_info_one_transaction(self):
|
|
||||||
"""D12: facts and info land in the same transaction."""
|
|
||||||
kblib.ensure_indexes(self.conn)
|
|
||||||
ids = kblib.add_leafs(self.conn, [
|
|
||||||
{
|
|
||||||
"text": "tx fact leaf two-source",
|
|
||||||
"root": "facts",
|
|
||||||
"confidence": "confirmed",
|
|
||||||
"source": "compose.yml x docker ps",
|
|
||||||
"source_rev": "r1",
|
|
||||||
"how": "test",
|
|
||||||
"loc": "/tmp",
|
|
||||||
"type": "fact",
|
|
||||||
"embedding": make_emb(0.4),
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"text": "tx info narrative",
|
|
||||||
"root": "info",
|
|
||||||
"confidence": "confirmed",
|
|
||||||
"source": "note.md",
|
|
||||||
"source_rev": "r1",
|
|
||||||
"how": "test",
|
|
||||||
"loc": "/tmp",
|
|
||||||
"type": "reference",
|
|
||||||
"embedding": make_emb(0.5),
|
|
||||||
},
|
|
||||||
])
|
|
||||||
self.assertEqual(len(ids), 2)
|
|
||||||
stats = kblib.stats(self.conn)
|
|
||||||
self.assertEqual(stats["by_root"].get("facts"), 1)
|
|
||||||
self.assertEqual(stats["by_root"].get("info"), 1)
|
|
||||||
self.assertTrue(kblib.query_fts(self.conn, "two-source", 5))
|
|
||||||
self.assertTrue(kblib.query_fts(self.conn, "narrative", 5))
|
|
||||||
|
|
||||||
def test_drop_vector_then_create_raises_clear_error(self):
|
def test_drop_vector_then_create_raises_clear_error(self):
|
||||||
"""DROP INDEX leaves ghost catalog; create_fts_and_vector must raise."""
|
"""DROP INDEX leaves ghost catalog; create_fts_and_vector must raise."""
|
||||||
kblib.upsert_leaf(self.conn, text="seed", root="info",
|
kblib.upsert_leaf(self.conn, text="seed", root="info",
|
||||||
|
|||||||
@@ -145,9 +145,6 @@ class PublishedDocsTest(unittest.TestCase):
|
|||||||
ROOT / "docs" / "design.md",
|
ROOT / "docs" / "design.md",
|
||||||
ROOT / "skills" / "brain" / "SKILL.md",
|
ROOT / "skills" / "brain" / "SKILL.md",
|
||||||
ROOT / "skills" / "diataxis-docs" / "SKILL.md",
|
ROOT / "skills" / "diataxis-docs" / "SKILL.md",
|
||||||
ROOT / "docs" / "runbook.md",
|
|
||||||
ROOT / "docs" / "README.md",
|
|
||||||
ROOT / "docs" / "roadmap.md",
|
|
||||||
]
|
]
|
||||||
# Command-style `--hop 1` / `--hop N` plus follow/walk = the old lie.
|
# Command-style `--hop 1` / `--hop N` plus follow/walk = the old lie.
|
||||||
# Honest "not implemented" notes must not match.
|
# Honest "not implemented" notes must not match.
|
||||||
@@ -158,35 +155,3 @@ class PublishedDocsTest(unittest.TestCase):
|
|||||||
lie.search(text),
|
lie.search(text),
|
||||||
f"{path.relative_to(ROOT)} still claims --hop walks the graph",
|
f"{path.relative_to(ROOT)} still claims --hop walks the graph",
|
||||||
)
|
)
|
||||||
|
|
||||||
def test_docs_are_portable_diataxis(self) -> None:
|
|
||||||
index = (ROOT / "docs" / "README.md").read_text()
|
|
||||||
self.assertIn("type: reference", index)
|
|
||||||
for d in ("D3", "D6", "D14", "D15", "D17", "D18"):
|
|
||||||
self.assertIn(d, index)
|
|
||||||
runbook = (ROOT / "docs" / "runbook.md").read_text()
|
|
||||||
self.assertIn("type: howto", runbook)
|
|
||||||
self.assertIn("bin/brain/search.go", runbook)
|
|
||||||
self.assertIn("bin/brain/index.go", runbook)
|
|
||||||
self.assertNotIn("search.ops.io", runbook)
|
|
||||||
self.assertNotIn("/mnt/", runbook)
|
|
||||||
self.assertNotIn("/home/", runbook)
|
|
||||||
readme = (ROOT / "README.md").read_text()
|
|
||||||
self.assertIn("docs/runbook.md", readme)
|
|
||||||
self.assertNotIn("search.ops.io", readme)
|
|
||||||
|
|
||||||
def test_v1_epic_is_named_in_docs(self) -> None:
|
|
||||||
plan = (ROOT / "PLAN.md").read_text()
|
|
||||||
self.assertIn("Gap to v1", plan)
|
|
||||||
self.assertIn("eSlider/2dph/issues/16", plan)
|
|
||||||
self.assertIn("eSlider/2dph/issues/17", plan)
|
|
||||||
self.assertIn("eSlider/2dph/milestone/12", plan)
|
|
||||||
road = (ROOT / "docs" / "roadmap.md").read_text()
|
|
||||||
self.assertIn("type: explanation", road)
|
|
||||||
self.assertIn("issues/16", road)
|
|
||||||
self.assertIn("issues/14", road)
|
|
||||||
index = (ROOT / "docs" / "README.md").read_text()
|
|
||||||
self.assertIn("roadmap.md", index)
|
|
||||||
self.assertIn("epic #16", index)
|
|
||||||
agents = (ROOT / "AGENTS.md").read_text()
|
|
||||||
self.assertIn("roadmap.md", agents)
|
|
||||||
|
|||||||
+9
-31
@@ -1,38 +1,16 @@
|
|||||||
---
|
# 2dph (deductionphile)
|
||||||
type: reference
|
|
||||||
status: current
|
|
||||||
related:
|
|
||||||
- docs/runbook.md
|
|
||||||
- docs/design.md
|
|
||||||
- PLAN.md
|
|
||||||
- docs/roadmap.md
|
|
||||||
---
|
|
||||||
|
|
||||||
# 2dph docs (Diataxis)
|
Evidence-first knowledge graph + hybrid RAG over the operational
|
||||||
|
Brain/ops/eSlider stack. Facts need proof or they are
|
||||||
Evidence-first knowledge graph. Facts need proof or they are
|
|
||||||
`(not confirmed)`.
|
`(not confirmed)`.
|
||||||
|
|
||||||
| Type | Doc |
|
- [PLAN.md](../PLAN.md) — decisions, execution order, open questions (v2)
|
||||||
|------|-----|
|
- [design](design.md) — schema, deduction model, sources
|
||||||
| tutorial / howto | [runbook](runbook.md) — run anywhere (uv, Go, Docker) |
|
- [reasoner](reasoner.md) — D18 CPU bake-off (Qwen3.5-9B vs Bonsai / Qwen3.6-27B)
|
||||||
| explanation | [design](design.md) — two roots, deduction, D17/D20/D18 |
|
- [Gitea issues](https://git.produktor.io/eSlider/2dph/issues) — work board (origin)
|
||||||
| explanation | [roadmap](roadmap.md) — gap to v1 (epic #16) |
|
|
||||||
| howto | [picoclaw](picoclaw.md) — MCP agent profile |
|
|
||||||
| howto | [reasoner](reasoner.md) — CPU bake-off (D18) |
|
|
||||||
| reference | [PLAN.md](../PLAN.md) — decisions D1–D21 |
|
|
||||||
|
|
||||||
Decisions the public face must name: **D3** SearXNG compose, **D6** Go service /
|
|
||||||
Python write sidecar, **D14** `bin/{subject}/{method}.go`, **D15** Gitea origin,
|
|
||||||
**D17** assertion gate (facts → info → web), **D18** pluggable reasoner.
|
|
||||||
|
|
||||||
Search: `bin/brain/search.go "query"` (HTTP: `bin/brain/serve.go` —
|
Search: `bin/brain/search.go "query"` (HTTP: `bin/brain/serve.go` —
|
||||||
`/health` `/search` `/get` `/stats` `/audit` `/ingest`). `--hop` is
|
`/health` `/search` `/get` `/stats` `/audit` `/ingest`). `--hop` is
|
||||||
not a walk; the flag errors. Schema has `FROM_FILE`; search does not
|
not a walk; the flag errors until File/FROM_FILE edges exist.
|
||||||
use it ([#17](https://git.produktor.io/eSlider/2dph/issues/17)).
|
|
||||||
|
|
||||||
Work board: [Gitea issues](https://git.produktor.io/eSlider/2dph/issues)
|
Published docs live here and mirror the project state.
|
||||||
([epic #16](https://git.produktor.io/eSlider/2dph/issues/16)).
|
|
||||||
PRs and CI: GitHub [`eSlider/2dph`](https://github.com/eSlider/2dph).
|
|
||||||
|
|
||||||
Published docs live here and match live commands.
|
|
||||||
|
|||||||
@@ -0,0 +1,33 @@
|
|||||||
|
# CRM association proof (oo CLI ↔ corpus)
|
||||||
|
|
||||||
|
Proven with `oo` (eslider/go-onlyoffice) against the OnlyOffice portal
|
||||||
|
(`office.produktor.io`). Portal CRM is the SSOT for company ↔ person ↔
|
||||||
|
project associations; the corpus SoT (`eslider/cv/projects/knowledge-mesh-seed.yaml`)
|
||||||
|
is the second, independent source. Facts that can be backed by both are
|
||||||
|
written to the brain under `root=facts` by `bin/facts/crm`.
|
||||||
|
|
||||||
|
## What was verified
|
||||||
|
|
||||||
|
- Logical counts (portal MySQL): 1300 contacts = 897 persons + 404 companies,
|
||||||
|
198 projects, 998 deals, 939 project↔contact links.
|
||||||
|
- Every client company linked to a project has ≥1 person underneath.
|
||||||
|
- Every person `company_id` resolves to an existing company.
|
||||||
|
- Corpus org list (9) maps 1:1 onto CRM companies:
|
||||||
|
ProProdukt SL / produktor.io, Dyvenia, Immowelt AG, WhereGroup,
|
||||||
|
Keynote SIGOS, D2S/SYSTEMS, GRID, Pack und Cup, Markets Platform.
|
||||||
|
- 78 person↔company association facts written to the brain
|
||||||
|
(`how=crm-crosscheck`, `type=association`). Recall@5 in `bin/kb/eval` = 1.0.
|
||||||
|
|
||||||
|
## Mistakes found
|
||||||
|
|
||||||
|
| # | Mistake | Fix |
|
||||||
|
|---|---------|-----|
|
||||||
|
| 1 | Duplicate legal entity `GoldenRatio.Exchange` (contact 759) vs `Golden Ratio Exchange` (763); 3 deals (211, 287, 559) were linked to 759 | `oo contacts merge 759 763` — 763 kept, 759 removed, deal links re-pointed to 763 |
|
||||||
|
| 2 | `env/`-wide: OnlyOffice creds file used wrong UX (user `eslider`, password with `$2` suffix) making `oo` auth fail | `.env` fixed to `eslider@gmail.com` + clean password; `.env` stays gitignored |
|
||||||
|
|
||||||
|
## Gates after fix
|
||||||
|
|
||||||
|
- `uv run python -m unittest discover -s bin/tools -t .` → 26 tests OK
|
||||||
|
- `bin/facts/audit self` + `bin/facts/audit db` → ok
|
||||||
|
- `bin/kb/eval` → recall@5 = 1.0
|
||||||
|
- `go test ./...` (bin/server + bin/watch) → ok
|
||||||
+4
-19
@@ -1,12 +1,3 @@
|
|||||||
---
|
|
||||||
type: explanation
|
|
||||||
status: current
|
|
||||||
related:
|
|
||||||
- docs/README.md
|
|
||||||
- docs/runbook.md
|
|
||||||
- docs/roadmap.md
|
|
||||||
---
|
|
||||||
|
|
||||||
# Design — facts, info, deduction
|
# Design — facts, info, deduction
|
||||||
|
|
||||||
## Two roots, one transaction
|
## Two roots, one transaction
|
||||||
@@ -34,9 +25,8 @@ bin/brain/search.go "question"
|
|||||||
is not evidence of absence; `--no-web` / `--root` skip it)
|
is not evidence of absence; `--no-web` / `--root` skip it)
|
||||||
```
|
```
|
||||||
|
|
||||||
`--hop` is not implemented. `FROM_FILE` / `HAS_VERSION` exist in schema;
|
`--hop` is not implemented yet (needs File/FROM_FILE edges). The flag is an
|
||||||
search does not walk them ([#17](https://git.produktor.io/eSlider/2dph/issues/17)).
|
error; it is not a graph walk.
|
||||||
The flag is an error; it is not a graph walk.
|
|
||||||
|
|
||||||
## Who / What / How / Where / When + evidence
|
## Who / What / How / Where / When + evidence
|
||||||
|
|
||||||
@@ -80,16 +70,14 @@ Conflicting pairings (≥2 yes vs ≥2 no) = hypothesis (OQ1 → v2 resolution).
|
|||||||
They do not exec Python. Control questions for recall@5 live in
|
They do not exec Python. Control questions for recall@5 live in
|
||||||
`internal/brain/rank` so CI can test the table without libladybug.
|
`internal/brain/rank` so CI can test the table without libladybug.
|
||||||
Python `bin/kb/{get,stats,eval}` remain for GitHub Actions until the runner
|
Python `bin/kb/{get,stats,eval}` remain for GitHub Actions until the runner
|
||||||
fetches Zig + libs (`bin/cgo/zig`). Incremental write is `bin/kb/add`
|
fetches Zig + libs (`bin/cgo/zig`). Index/write is still `bin/kb/index`
|
||||||
(`bin/brain/add.go`). Bulk index/write is still `bin/kb/index`
|
|
||||||
(`docker compose --profile index`).
|
(`docker compose --profile index`).
|
||||||
|
|
||||||
## Agent API (D20)
|
## Agent API (D20)
|
||||||
|
|
||||||
`bin/brain/serve.go` exposes the same `internal/httpapi.Ops` table as OpenAPI
|
`bin/brain/serve.go` exposes the same `internal/httpapi.Ops` table as OpenAPI
|
||||||
(`GET /openapi.json`) and MCP (`POST /mcp` JSON-RPC `tools/list` +
|
(`GET /openapi.json`) and MCP (`POST /mcp` JSON-RPC `tools/list` +
|
||||||
`tools/call`). Tool names match paths: `search`, `get`, `stats`, `audit`,
|
`tools/call`). Tool names match paths: `search`, `get`, `stats`, `audit`.
|
||||||
`ingest` (add a leaf; omit body for the CLI hint).
|
|
||||||
Agents should use these endpoints instead of shebang CLIs.
|
Agents should use these endpoints instead of shebang CLIs.
|
||||||
|
|
||||||
## Reasoner (D18)
|
## Reasoner (D18)
|
||||||
@@ -99,6 +87,3 @@ Pluggable OpenAI-compatible URL. RAM: `Qwen/Qwen3.5-9B`. Quality:
|
|||||||
CPU sidecar: compose profile `reasoner` (`OLLAMA_NUM_GPU=0`,
|
CPU sidecar: compose profile `reasoner` (`OLLAMA_NUM_GPU=0`,
|
||||||
`127.0.0.1:11435`). Bake-off: `bin/reasoner/bakeoff.go`. Weights stay out
|
`127.0.0.1:11435`). Bake-off: `bin/reasoner/bakeoff.go`. Weights stay out
|
||||||
of the 2dph image. See [docs/reasoner.md](reasoner.md).
|
of the 2dph image. See [docs/reasoner.md](reasoner.md).
|
||||||
|
|
||||||
Gap to v1 (hops, corpus, CI eval): [roadmap](roadmap.md),
|
|
||||||
[epic #16](https://git.produktor.io/eSlider/2dph/issues/16).
|
|
||||||
@@ -1,61 +0,0 @@
|
|||||||
---
|
|
||||||
type: explanation
|
|
||||||
status: current
|
|
||||||
related:
|
|
||||||
- PLAN.md
|
|
||||||
- docs/design.md
|
|
||||||
- docs/runbook.md
|
|
||||||
---
|
|
||||||
|
|
||||||
# Gap to v1 — detective brain
|
|
||||||
|
|
||||||
Goal: a brain that does not assert without proof. Search is deduction
|
|
||||||
(`facts` ≥2 sources → `info` → `web`). `confirmed` only from the facts root.
|
|
||||||
|
|
||||||
**v1 is a living graph the agent can write and walk**, not “more RAG”.
|
|
||||||
|
|
||||||
Epic: [Gitea #16](https://git.produktor.io/eSlider/2dph/issues/16).
|
|
||||||
Milestone: [v1 detective brain](https://git.produktor.io/eSlider/2dph/milestone/12).
|
|
||||||
Decisions: [PLAN.md](../PLAN.md).
|
|
||||||
|
|
||||||
## In (do not reopen)
|
|
||||||
|
|
||||||
Read path Go + Zig CGO (D21). HTTP + OpenAPI + MCP (D20). PicoClaw compose
|
|
||||||
profile + CPU reasoner (D18). Mail sync → import → rebuild. D14 shebangs.
|
|
||||||
Compose `api` (no CPython) / `index` (Python write). Issues #1–#5, #7–#13.
|
|
||||||
[#15](https://git.produktor.io/eSlider/2dph/issues/15) lever/loop.
|
|
||||||
[#14](https://git.produktor.io/eSlider/2dph/issues/14) `bin/brain/add.go` /
|
|
||||||
`POST /ingest` (Python `kblib.add_leafs`; no Go upsert port).
|
|
||||||
|
|
||||||
## Blockers
|
|
||||||
|
|
||||||
```
|
|
||||||
question
|
|
||||||
│
|
|
||||||
├─ FTS + HNSW ← in
|
|
||||||
├─ facts / info roots ← in
|
|
||||||
├─ web (D17) ← in
|
|
||||||
├─ brain/add ACID ← in
|
|
||||||
├─ Cypher hop ← #17 schema yes, search no
|
|
||||||
└─ facts+chats corpus ← #18
|
|
||||||
```
|
|
||||||
|
|
||||||
1. **[#17](https://git.produktor.io/eSlider/2dph/issues/17) hops** —
|
|
||||||
`Leaf-[:FROM_FILE]->File-[:HAS_VERSION]->Commit-[:AUTHORED]->Person`
|
|
||||||
exists; `--hop` still errors. Without a walk, D9/D10 are paper.
|
|
||||||
2. **[#18](https://git.produktor.io/eSlider/2dph/issues/18) corpus** —
|
|
||||||
rebuild loads repo markdown + mail as `info`. `facts/extract` pairing
|
|
||||||
and `bin/chats` are not indexed. WhatsApp is a stub. PII stays in `var/`.
|
|
||||||
3. **[#19](https://git.produktor.io/eSlider/2dph/issues/19) CI eval** —
|
|
||||||
recall SoT should be `bin/brain/eval.go` via Zig, not Python `bin/kb/eval`.
|
|
||||||
|
|
||||||
## Not v1
|
|
||||||
|
|
||||||
[#6](https://git.produktor.io/eSlider/2dph/issues/6) OCR (OQ2), OQ1
|
|
||||||
contradiction resolution, OQ3 duckdb-md export, OQ4 YAML-first leafs.
|
|
||||||
|
|
||||||
## Close epic #16 when
|
|
||||||
|
|
||||||
- `--hop` stops erroring and runs a Cypher path from search hits
|
|
||||||
- ops pairing + chat import land as leafs on rebuild
|
|
||||||
- MCP tool order is documented and still gated by tests
|
|
||||||
@@ -1,84 +0,0 @@
|
|||||||
---
|
|
||||||
type: howto
|
|
||||||
status: current
|
|
||||||
related:
|
|
||||||
- docs/README.md
|
|
||||||
- PLAN.md
|
|
||||||
---
|
|
||||||
|
|
||||||
# Run 2dph (portable)
|
|
||||||
|
|
||||||
No laptop-absolute paths. Config lives in env files under `$HOME/.config/brain/`
|
|
||||||
(mode 0600), not in git.
|
|
||||||
|
|
||||||
## Toolchain
|
|
||||||
|
|
||||||
- Go (see `go.mod`)
|
|
||||||
- Python 3.12 + [uv](https://docs.astral.sh/uv)
|
|
||||||
- Optional: Docker, Zig CGO via `bin/cgo/zig` (not gcc)
|
|
||||||
|
|
||||||
```bash
|
|
||||||
uv venv .venv
|
|
||||||
uv pip install -r requirements.lock.txt
|
|
||||||
eval "$(bin/cgo/zig env)" # when compiling Ladybug read tools
|
|
||||||
go test ./...
|
|
||||||
uv run python -m unittest discover -s bin/tools -t .
|
|
||||||
```
|
|
||||||
|
|
||||||
## Config
|
|
||||||
|
|
||||||
| File / env | Purpose |
|
|
||||||
|------------|---------|
|
|
||||||
| `$BRAIN_SEARCH_ENV` (default `$HOME/.config/brain/search.env`) | `BRAIN_SEARCH_URL` (SearXNG). Optional Basic Auth. |
|
|
||||||
| `$HOME/.config/brain/db-profiles.yml` | read-only Postgres profiles (OnlyOffice via tunnel) |
|
|
||||||
|
|
||||||
If the host already runs SearXNG, point `BRAIN_SEARCH_URL` at it. Do not start
|
|
||||||
a second copy (D3). Optional Compose instance:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
SEARXNG_SECRET=$(openssl rand -hex 32) docker compose --profile searxng up -d
|
|
||||||
```
|
|
||||||
|
|
||||||
That binds `127.0.0.1:8888`. JSON format must stay enabled.
|
|
||||||
|
|
||||||
## Index then search
|
|
||||||
|
|
||||||
Write path is `bin/brain/add.go` for a leaf (or `POST /ingest`). Bulk
|
|
||||||
corpus rebuild remains `bin/brain/index.go --rebuild` (Compose profile
|
|
||||||
`index`). Do not DROP INDEX on Ladybug 0.19.
|
|
||||||
|
|
||||||
```bash
|
|
||||||
bin/brain/add.go --text "arc-1 runs Matrix" --root facts --source "compose.yml x docker ps"
|
|
||||||
bin/brain/index.go --rebuild
|
|
||||||
bin/brain/search.go "LadybugDB vector index" # facts → info → web (D17)
|
|
||||||
bin/brain/search.go "upstream flag" --no-web
|
|
||||||
bin/brain/get.go <id> --body
|
|
||||||
bin/brain/stats.go
|
|
||||||
```
|
|
||||||
|
|
||||||
`--hop` is not implemented. Empty web results are `throttled`, not absence.
|
|
||||||
Gap to v1: [roadmap](roadmap.md) / [epic #16](https://git.produktor.io/eSlider/2dph/issues/16).
|
|
||||||
|
|
||||||
Ladybug 0.19: never `DROP INDEX` FTS/VECTOR (ghost catalog). Fresh indexes =
|
|
||||||
delete `var/kb.lbug` then `--rebuild`.
|
|
||||||
|
|
||||||
## HTTP / MCP
|
|
||||||
|
|
||||||
```bash
|
|
||||||
docker compose up -d brain # :8630 Zig CGO serve
|
|
||||||
docker compose --profile index run --rm index # rebuild
|
|
||||||
docker compose --profile picoclaw up brain-mcp # MCP 127.0.0.1:8630
|
|
||||||
```
|
|
||||||
|
|
||||||
`GET /openapi.json`, `POST /mcp`. Agent tool order: `search` → `get` → `audit`.
|
|
||||||
|
|
||||||
## Reasoner (optional, D18)
|
|
||||||
|
|
||||||
CPU sidecar on `127.0.0.1:11435`. Weights are not in the 2dph image.
|
|
||||||
|
|
||||||
```bash
|
|
||||||
docker compose --profile reasoner up -d reasoner
|
|
||||||
REASONER_BASE_URL=http://127.0.0.1:11435/v1 ./bin/reasoner/bakeoff.go --json
|
|
||||||
```
|
|
||||||
|
|
||||||
See [reasoner.md](reasoner.md).
|
|
||||||
+4
-16
@@ -7,8 +7,6 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
"os/exec"
|
|
||||||
"path/filepath"
|
|
||||||
|
|
||||||
"github.com/eSlider/2dph/internal/brain/rank"
|
"github.com/eSlider/2dph/internal/brain/rank"
|
||||||
)
|
)
|
||||||
@@ -139,22 +137,12 @@ func (HTTP) Audit(context.Context) ([]byte, error) {
|
|||||||
return json.Marshal(map[string]any{"status": "ok", "by_confidence": rows})
|
return json.Marshal(map[string]any{"status": "ok", "by_confidence": rows})
|
||||||
}
|
}
|
||||||
|
|
||||||
func (HTTP) Ingest(ctx context.Context, body []byte) ([]byte, error) {
|
func (HTTP) Ingest(context.Context) ([]byte, error) {
|
||||||
if len(bytes.TrimSpace(body)) == 0 {
|
|
||||||
return json.Marshal(map[string]any{
|
return json.Marshal(map[string]any{
|
||||||
"mode": "add",
|
"mode": "rebuild",
|
||||||
"command": "bin/brain/add.go",
|
"command": "bin/brain/index.go --rebuild",
|
||||||
"rebuild": "bin/brain/index.go --rebuild",
|
"add": "v2",
|
||||||
})
|
})
|
||||||
}
|
|
||||||
cmd := exec.CommandContext(ctx, filepath.Join(repoRoot(), "bin", "kb", "add"), "--json")
|
|
||||||
cmd.Stdin = bytes.NewReader(body)
|
|
||||||
cmd.Dir = repoRoot()
|
|
||||||
out, err := cmd.Output()
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("add: %w", err)
|
|
||||||
}
|
|
||||||
return out, nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func asInt(v any) int64 {
|
func asInt(v any) int64 {
|
||||||
|
|||||||
@@ -144,15 +144,7 @@ func (s *Server) mcpCall(r *http.Request, params json.RawMessage) (any, error) {
|
|||||||
return nil, fmt.Errorf("cancelled")
|
return nil, fmt.Errorf("cancelled")
|
||||||
}
|
}
|
||||||
defer s.release()
|
defer s.release()
|
||||||
var payload []byte
|
body, err = s.api.Ingest(r.Context())
|
||||||
text := strings.TrimSpace(fmt.Sprint(p.Arguments["text"]))
|
|
||||||
if text != "" && text != "<nil>" {
|
|
||||||
payload, err = json.Marshal(p.Arguments)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
body, err = s.api.Ingest(r.Context(), payload)
|
|
||||||
default:
|
default:
|
||||||
return nil, fmt.Errorf("unknown tool %s", p.Name)
|
return nil, fmt.Errorf("unknown tool %s", p.Name)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -11,7 +11,6 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
"io"
|
|
||||||
"log"
|
"log"
|
||||||
"net/http"
|
"net/http"
|
||||||
"os"
|
"os"
|
||||||
@@ -28,7 +27,7 @@ type API interface {
|
|||||||
Get(ctx context.Context, id string, body bool) ([]byte, error)
|
Get(ctx context.Context, id string, body bool) ([]byte, error)
|
||||||
Stats(ctx context.Context) ([]byte, error)
|
Stats(ctx context.Context) ([]byte, error)
|
||||||
Audit(ctx context.Context) ([]byte, error)
|
Audit(ctx context.Context) ([]byte, error)
|
||||||
Ingest(ctx context.Context, body []byte) ([]byte, error)
|
Ingest(ctx context.Context) ([]byte, error)
|
||||||
}
|
}
|
||||||
|
|
||||||
type Server struct {
|
type Server struct {
|
||||||
@@ -60,7 +59,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
|||||||
case PathAudit:
|
case PathAudit:
|
||||||
s.handleJSON(w, r, s.api.Audit)
|
s.handleJSON(w, r, s.api.Audit)
|
||||||
case PathIngest:
|
case PathIngest:
|
||||||
s.handleIngest(w, r)
|
s.handleJSON(w, r, s.api.Ingest)
|
||||||
case PathOpenAPI:
|
case PathOpenAPI:
|
||||||
s.handleOpenAPI(w, r)
|
s.handleOpenAPI(w, r)
|
||||||
case PathMCP:
|
case PathMCP:
|
||||||
@@ -117,24 +116,6 @@ func (s *Server) handleJSON(w http.ResponseWriter, r *http.Request, fn func(cont
|
|||||||
writeAPI(w, body, err)
|
writeAPI(w, body, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Server) handleIngest(w http.ResponseWriter, r *http.Request) {
|
|
||||||
var raw []byte
|
|
||||||
if r.Method == http.MethodPost {
|
|
||||||
b, err := io.ReadAll(io.LimitReader(r.Body, 1<<20))
|
|
||||||
if err != nil {
|
|
||||||
writeJSON(w, http.StatusBadRequest, map[string]any{"error": "read body"})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
raw = b
|
|
||||||
}
|
|
||||||
if !s.acquire(w, r) {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
defer s.release()
|
|
||||||
body, err := s.api.Ingest(r.Context(), raw)
|
|
||||||
writeAPI(w, body, err)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *Server) tryAcquire(r *http.Request) bool {
|
func (s *Server) tryAcquire(r *http.Request) bool {
|
||||||
return s.acquire(nopWriter{}, r)
|
return s.acquire(nopWriter{}, r)
|
||||||
}
|
}
|
||||||
@@ -210,30 +191,11 @@ func (ExecSearcher) Get(context.Context, string, bool) ([]byte, error) {
|
|||||||
}
|
}
|
||||||
func (ExecSearcher) Stats(context.Context) ([]byte, error) { return nil, errUnimplemented }
|
func (ExecSearcher) Stats(context.Context) ([]byte, error) { return nil, errUnimplemented }
|
||||||
func (ExecSearcher) Audit(context.Context) ([]byte, error) { return nil, errUnimplemented }
|
func (ExecSearcher) Audit(context.Context) ([]byte, error) { return nil, errUnimplemented }
|
||||||
func (b ExecSearcher) Ingest(ctx context.Context, body []byte) ([]byte, error) {
|
func (ExecSearcher) Ingest(context.Context) ([]byte, error) {
|
||||||
if len(strings.TrimSpace(string(body))) == 0 {
|
|
||||||
return json.Marshal(map[string]any{
|
return json.Marshal(map[string]any{
|
||||||
"mode": "add",
|
"mode": "rebuild",
|
||||||
"command": "bin/brain/add.go",
|
"command": "bin/brain/index.go --rebuild",
|
||||||
"rebuild": "bin/brain/index.go --rebuild",
|
|
||||||
})
|
})
|
||||||
}
|
|
||||||
root := os.Getenv("KB_ROOT")
|
|
||||||
if root == "" {
|
|
||||||
root = "."
|
|
||||||
}
|
|
||||||
cmd := exec.CommandContext(ctx, filepath.Join(root, "bin/kb/add"), "--json")
|
|
||||||
cmd.Stdin = strings.NewReader(string(body))
|
|
||||||
cmd.Dir = root
|
|
||||||
out, err := cmd.Output()
|
|
||||||
if err != nil {
|
|
||||||
var exitErr *exec.ExitError
|
|
||||||
if errors.As(err, &exitErr) {
|
|
||||||
return nil, errors.New("add failed: " + strings.TrimSpace(string(exitErr.Stderr)))
|
|
||||||
}
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return out, nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func defaultSearchCmd(root string) string {
|
func defaultSearchCmd(root string) string {
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
package httpapi
|
package httpapi
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"bytes"
|
|
||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"net/http"
|
"net/http"
|
||||||
@@ -65,11 +64,8 @@ func (f *fakeSearcher) Audit(context.Context) ([]byte, error) {
|
|||||||
return []byte(`{"status":"ok"}`), nil
|
return []byte(`{"status":"ok"}`), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (f *fakeSearcher) Ingest(_ context.Context, body []byte) ([]byte, error) {
|
func (f *fakeSearcher) Ingest(context.Context) ([]byte, error) {
|
||||||
if len(bytes.TrimSpace(body)) == 0 {
|
return []byte(`{"mode":"rebuild","command":"bin/brain/index.go --rebuild"}`), nil
|
||||||
return []byte(`{"mode":"add","command":"bin/brain/add.go"}`), nil
|
|
||||||
}
|
|
||||||
return []byte(`{"mode":"add","ids":["fake-leaf"]}`), nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (f *fakeSearcher) count() int {
|
func (f *fakeSearcher) count() int {
|
||||||
@@ -197,27 +193,6 @@ func TestStatsAuditIngest(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestIngestIsAddNotRebuildHint(t *testing.T) {
|
|
||||||
h := NewServer(&fakeSearcher{}, 1)
|
|
||||||
code, body := get(t, h, "/ingest")
|
|
||||||
if code != http.StatusOK {
|
|
||||||
t.Fatalf("GET /ingest code = %d body=%s", code, body)
|
|
||||||
}
|
|
||||||
if strings.Contains(string(body), `"add":"v2"`) || strings.Contains(string(body), "write is v2") {
|
|
||||||
t.Fatalf("GET /ingest still a v2 hint: %s", body)
|
|
||||||
}
|
|
||||||
if !strings.Contains(string(body), "bin/brain/add.go") {
|
|
||||||
t.Fatalf("GET /ingest should name add.go: %s", body)
|
|
||||||
}
|
|
||||||
code, body = postJSON(t, h, "/ingest", `{"text":"hello","root":"info","source":"t"}`)
|
|
||||||
if code != http.StatusOK {
|
|
||||||
t.Fatalf("POST /ingest code = %d body=%s", code, body)
|
|
||||||
}
|
|
||||||
if !strings.Contains(string(body), "fake-leaf") {
|
|
||||||
t.Fatalf("POST /ingest should add: %s", body)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestHTTPPackageDoesNotExecPython(t *testing.T) {
|
func TestHTTPPackageDoesNotExecPython(t *testing.T) {
|
||||||
raw, err := os.ReadFile("server.go")
|
raw, err := os.ReadFile("server.go")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|||||||
@@ -47,15 +47,7 @@ var Ops = []Op{
|
|||||||
},
|
},
|
||||||
{Path: PathStats, Method: "get", ID: "stats", Summary: "index health", MCP: true},
|
{Path: PathStats, Method: "get", ID: "stats", Summary: "index health", MCP: true},
|
||||||
{Path: PathAudit, Method: "get", ID: "audit", Summary: "facts confidence histogram", MCP: true},
|
{Path: PathAudit, Method: "get", ID: "audit", Summary: "facts confidence histogram", MCP: true},
|
||||||
{
|
{Path: PathIngest, Method: "get", ID: "ingest", Summary: "rebuild hint (write is v2)", MCP: true},
|
||||||
Path: PathIngest, Method: "post", ID: "ingest", Summary: "add a leaf without rebuild",
|
|
||||||
MCP: true,
|
|
||||||
Params: []Param{
|
|
||||||
{Name: "text", In: "query", Type: "string", Description: "leaf text (omit for CLI hint)"},
|
|
||||||
{Name: "root", In: "query", Type: "string", Description: "facts or info (default info)"},
|
|
||||||
{Name: "source", In: "query", Type: "string", Description: "evidence pointer; facts need two sources"},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{Path: PathOpenAPI, Method: "get", ID: "openapi", Summary: "OpenAPI 3 document for this server"},
|
{Path: PathOpenAPI, Method: "get", ID: "openapi", Summary: "OpenAPI 3 document for this server"},
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -38,24 +38,11 @@ func TestMCPToolsMatchOpenAPIPaths(t *testing.T) {
|
|||||||
t.Fatalf("MCP tool %s has no OpenAPI path %s", tool.Name, path)
|
t.Fatalf("MCP tool %s has no OpenAPI path %s", tool.Name, path)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
for _, need := range []string{"search", "get", "stats", "audit", "ingest"} {
|
for _, need := range []string{"search", "get", "stats", "audit"} {
|
||||||
if !names[need] {
|
if !names[need] {
|
||||||
t.Fatalf("MCP tools missing %s: %v", need, names)
|
t.Fatalf("MCP tools missing %s: %v", need, names)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
var ingest MCPTool
|
|
||||||
for _, tool := range tools {
|
|
||||||
if tool.Name == "ingest" {
|
|
||||||
ingest = tool
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if strings.Contains(ingest.Description, "v2") {
|
|
||||||
t.Fatalf("ingest still a v2 hint: %s", ingest.Description)
|
|
||||||
}
|
|
||||||
if !strings.Contains(ingest.Description, "add") {
|
|
||||||
t.Fatalf("ingest should describe add: %s", ingest.Description)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestOpenAPIHTTP(t *testing.T) {
|
func TestOpenAPIHTTP(t *testing.T) {
|
||||||
|
|||||||
@@ -26,15 +26,13 @@ second independent source when local roots cannot confirm. An answer is
|
|||||||
bin/brain/search.go "Matrix federation" # pointers + snippets, YAML
|
bin/brain/search.go "Matrix federation" # pointers + snippets, YAML
|
||||||
bin/brain/search.go "onlyoffice postgres" --root facts # restrict to confirmed
|
bin/brain/search.go "onlyoffice postgres" --root facts # restrict to confirmed
|
||||||
bin/brain/search.go "where is cs-lexicon" --json | yq '.[].ref'
|
bin/brain/search.go "where is cs-lexicon" --json | yq '.[].ref'
|
||||||
bin/brain/add.go --text T --root facts --source "a.md x b.md"
|
|
||||||
bin/brain/get.go <id> --body # full chunk only when needed
|
bin/brain/get.go <id> --body # full chunk only when needed
|
||||||
bin/brain/stats.go # index health
|
bin/brain/stats.go # index health
|
||||||
bin/brain/eval.go # recall@5 >= 0.95 gate (Go; Python bin/kb/eval is CI fallback)
|
bin/brain/eval.go # recall@5 >= 0.95 gate (Go; Python bin/kb/eval is CI fallback)
|
||||||
```
|
```
|
||||||
|
|
||||||
`bin/kb/search` is a deprecated wrapper. `--hop` errors (schema has
|
`bin/kb/search` is a deprecated wrapper. `--hop` errors (File/FROM_FILE edges
|
||||||
`FROM_FILE`; search does not walk it yet, [#17](https://git.produktor.io/eSlider/2dph/issues/17));
|
are not wired yet); do not treat it as a graph walk.
|
||||||
do not treat it as a graph walk.
|
|
||||||
|
|
||||||
## Rules
|
## Rules
|
||||||
|
|
||||||
|
|||||||
@@ -8,4 +8,4 @@ Serve: `bin/brain/serve.go` (`GET /openapi.json`, `POST /mcp`).
|
|||||||
- `get` — read one leaf by id
|
- `get` — read one leaf by id
|
||||||
- `stats` — index health
|
- `stats` — index health
|
||||||
- `audit` — facts confidence histogram
|
- `audit` — facts confidence histogram
|
||||||
- `ingest` — add a leaf without rebuild
|
- `ingest` — rebuild hint (write is v2)
|
||||||
|
|||||||
Reference in New Issue
Block a user