Compare commits
24
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
54cb901f84 | ||
|
|
5d4b3427a4 | ||
|
|
1c7db6d499 | ||
|
|
0786ddcb06 | ||
|
|
eeb5b79cf2 | ||
|
|
5990feb1f6 | ||
|
|
d27a738fee | ||
|
|
669e184cf6 | ||
|
|
ebc3f948c1 | ||
|
|
fe6a02024c | ||
|
|
4a065d9838 | ||
|
|
e3c6ef5684 | ||
|
|
98c14e23f1 | ||
|
|
ff1716de40 | ||
|
|
fec5325c7a | ||
|
|
27d9521e7f | ||
|
|
a7cb8d4c76 | ||
|
|
53cd00284d | ||
|
|
b73b4d4f97 | ||
|
|
1d1f6a90ff | ||
|
|
f220bcd95a | ||
|
|
678a1d1dba | ||
|
|
8781c0c3eb | ||
|
|
d6b17e8819 |
@@ -29,7 +29,7 @@ detective method: **a fact needs ≥2 independent sources or it is
|
|||||||
| D3 | web search | Vendored client; SearXNG URL is config. Optional Compose instance (sanitized settings). Do not run a second copy on a host that already has one. Empty/`throttled` ≠ “nothing exists”. |
|
| D3 | web search | Vendored client; SearXNG URL is config. Optional Compose instance (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`); Python remains for index/write until the Go write path is safe. |
|
| D6 | graph engine | **LadybugDB**. Go is the service (`bin/brain/search.go`, `internal/brain`); Python remains for index/write 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)`. 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. |
|
||||||
@@ -49,7 +49,7 @@ detective method: **a fact needs ≥2 independent sources or it is
|
|||||||
2dph/
|
2dph/
|
||||||
PLAN.md / AGENTS.md
|
PLAN.md / AGENTS.md
|
||||||
docs/ published docs (this conversation → docs/ as md)
|
docs/ published docs (this conversation → docs/ as md)
|
||||||
skills/ in-project skills (web-search, db-yaml, brain, diataxis-docs)
|
skills/ in-project skills (web-search, db-yaml, kb-search, agent-cost, diataxis-docs, …)
|
||||||
bin/
|
bin/
|
||||||
facts/extract auto-pair 2 sources → lexicon yaml + graph
|
facts/extract auto-pair 2 sources → lexicon yaml + graph
|
||||||
facts/audit ["self"|"facts"|"info"|"stale"] 2-source + staleness gate
|
facts/audit ["self"|"facts"|"info"|"stale"] 2-source + staleness gate
|
||||||
@@ -57,7 +57,7 @@ detective method: **a fact needs ≥2 independent sources or it is
|
|||||||
brain/index.go rebuild FTS + HNSW (incl. --with-mail)
|
brain/index.go rebuild FTS + HNSW (incl. --with-mail)
|
||||||
brain/get.go stats.go eval.go watch.go
|
brain/get.go stats.go eval.go watch.go
|
||||||
brain/search.go deduction: facts → info → web-search
|
brain/search.go deduction: facts → info → web-search
|
||||||
brain/serve.go HTTP API in-process (internal/httpapi + internal/brain)
|
brain/serve.go HTTP API (internal/httpapi)
|
||||||
mail/import.go JSON → markdown (no brain write)
|
mail/import.go JSON → markdown (no brain write)
|
||||||
markdown/import.go mistune leaves
|
markdown/import.go mistune leaves
|
||||||
postgres/query.go read-only YAML (wraps bin/db/psql-yq)
|
postgres/query.go read-only YAML (wraps bin/db/psql-yq)
|
||||||
@@ -140,7 +140,7 @@ Feedback loop: every commit → PR → CI → green/gate → merge. Same discipl
|
|||||||
|
|
||||||
1. scaffold repo (:done after this file + AGENTS.md + .gitignore + ci)
|
1. scaffold repo (:done after this file + AGENTS.md + .gitignore + ci)
|
||||||
2. gh repo create eSlider/2dph --private + initial commit + CI
|
2. gh repo create eSlider/2dph --private + initial commit + CI
|
||||||
3. vendored skill integration (web-search, db-yaml, brain, diataxis-docs) — no remote links
|
3. vendored skill integration (web-search, db-yaml, kb-search, agent-cost, diataxis-docs) — no remote links
|
||||||
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
|
||||||
|
|||||||
@@ -121,8 +121,8 @@ bin/brain/search.go "invoice from last week" # same s
|
|||||||
|
|
||||||
`bin/{subject}/{method}.go` — self-describing: shebang on line 1, usage comment
|
`bin/{subject}/{method}.go` — self-describing: shebang on line 1, usage comment
|
||||||
from line 2. Shared code in `internal/`. YAML default output, `--json` for
|
from line 2. Shared code in `internal/`. YAML default output, `--json` for
|
||||||
machines. Tests gate every commit. HTTP: `bin/brain/serve.go` calls
|
machines. Tests gate every commit. HTTP: `bin/brain/serve.go` (default search
|
||||||
`internal/brain` in-process (`/health` `/search` `/get` `/stats` `/audit` `/ingest`).
|
binary `var/bin/brain-search`, not Python).
|
||||||
|
|
||||||
## Development
|
## Development
|
||||||
|
|
||||||
|
|||||||
+6
-11
@@ -1,20 +1,18 @@
|
|||||||
//usr/bin/env go run -tags=brain_serve,system_ladybug "$0" "$@"; exit
|
//usr/bin/env go run -tags=brain_serve "$0" "$@"; exit
|
||||||
//go:build brain_serve && cgo && system_ladybug
|
//go:build brain_serve
|
||||||
//
|
//
|
||||||
// bin/brain/serve.go - HTTP API (in-process ladybug search).
|
// bin/brain/serve.go - HTTP API for the 2dph brain.
|
||||||
//
|
//
|
||||||
// KB_ROOT=/path/to/2dph ./bin/brain/serve.go
|
// KB_ROOT=/path/to/2dph ./bin/brain/serve.go
|
||||||
// KB_WORKERS=4 KB_PORT=8630 ./bin/brain/serve.go
|
// KB_SEARCH_CMD=... KB_WORKERS=4 KB_PORT=8630 ./bin/brain/serve.go
|
||||||
//
|
//
|
||||||
// Needs CGO + libladybug (same as bin/brain/search.go).
|
// Default search backend is var/bin/brain-search (Go), not Python.
|
||||||
// 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
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"log"
|
|
||||||
"os"
|
"os"
|
||||||
|
|
||||||
"github.com/eSlider/2dph/internal/brain"
|
|
||||||
"github.com/eSlider/2dph/internal/httpapi"
|
"github.com/eSlider/2dph/internal/httpapi"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -24,8 +22,5 @@ func main() {
|
|||||||
os.Setenv("KB_ROOT", wd)
|
os.Setenv("KB_ROOT", wd)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if err := brain.Ready(); err != nil {
|
httpapi.Run()
|
||||||
log.Fatal(err)
|
|
||||||
}
|
|
||||||
httpapi.Run(brain.HTTP{})
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,20 +0,0 @@
|
|||||||
//go:build brain_serve && !system_ladybug
|
|
||||||
//
|
|
||||||
// Fallback serve when ladybug cgo is not in the build (CI / tags=brain_serve).
|
|
||||||
// Production shebang is serve.go (in-process).
|
|
||||||
package main
|
|
||||||
|
|
||||||
import (
|
|
||||||
"os"
|
|
||||||
|
|
||||||
"github.com/eSlider/2dph/internal/httpapi"
|
|
||||||
)
|
|
||||||
|
|
||||||
func main() {
|
|
||||||
if os.Getenv("KB_ROOT") == "" {
|
|
||||||
if wd, err := os.Getwd(); err == nil {
|
|
||||||
os.Setenv("KB_ROOT", wd)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
httpapi.Run(nil)
|
|
||||||
}
|
|
||||||
+1
-1
@@ -18,5 +18,5 @@ func main() {
|
|||||||
os.Setenv("KB_ROOT", wd)
|
os.Setenv("KB_ROOT", wd)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
httpapi.Run(nil)
|
httpapi.Run()
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -43,7 +43,7 @@ class PublishedDocsTest(unittest.TestCase):
|
|||||||
paths = [
|
paths = [
|
||||||
ROOT / "README.md",
|
ROOT / "README.md",
|
||||||
ROOT / "docs" / "design.md",
|
ROOT / "docs" / "design.md",
|
||||||
ROOT / "skills" / "brain" / "SKILL.md",
|
ROOT / "skills" / "kb-search" / "SKILL.md",
|
||||||
ROOT / "skills" / "diataxis-docs" / "SKILL.md",
|
ROOT / "skills" / "diataxis-docs" / "SKILL.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.
|
||||||
|
|||||||
@@ -1,33 +0,0 @@
|
|||||||
"""Every bin/ path named in skills/ must exist on disk."""
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import re
|
|
||||||
import unittest
|
|
||||||
from pathlib import Path
|
|
||||||
|
|
||||||
ROOT = Path(__file__).resolve().parents[2]
|
|
||||||
BIN_PATH = re.compile(r"\b(bin/[A-Za-z0-9_./-]+)")
|
|
||||||
|
|
||||||
|
|
||||||
class SkillsBinPathsTest(unittest.TestCase):
|
|
||||||
def test_agent_cost_skill_is_gone(self) -> None:
|
|
||||||
self.assertFalse(
|
|
||||||
(ROOT / "skills" / "agent-cost").exists(),
|
|
||||||
"skills/agent-cost documents bin/agents/cost which does not exist",
|
|
||||||
)
|
|
||||||
|
|
||||||
def test_brain_skill_replaces_kb_search(self) -> None:
|
|
||||||
self.assertTrue((ROOT / "skills" / "brain" / "SKILL.md").is_file())
|
|
||||||
self.assertFalse((ROOT / "skills" / "kb-search").exists())
|
|
||||||
|
|
||||||
def test_skill_bin_paths_exist(self) -> None:
|
|
||||||
missing: list[str] = []
|
|
||||||
for skill in sorted((ROOT / "skills").rglob("SKILL.md")):
|
|
||||||
text = skill.read_text()
|
|
||||||
for match in BIN_PATH.findall(text):
|
|
||||||
rel = match.rstrip("`'.,")
|
|
||||||
if rel.endswith(".go") or Path(rel).suffix == "" or Path(rel).suffix in {".go", ".py"}:
|
|
||||||
p = ROOT / rel
|
|
||||||
if not p.exists():
|
|
||||||
missing.append(f"{skill.relative_to(ROOT)}: {rel}")
|
|
||||||
self.assertEqual(missing, [], "SKILL.md names bin/ paths that do not exist")
|
|
||||||
+1
-2
@@ -8,8 +8,7 @@ Brain/ops/eSlider stack. Facts need proof or they are
|
|||||||
- [design](design.md) — schema, deduction model, sources
|
- [design](design.md) — schema, deduction model, sources
|
||||||
- [Gitea issues](https://git.produktor.io/eSlider/2dph/issues) — work board (origin)
|
- [Gitea issues](https://git.produktor.io/eSlider/2dph/issues) — work board (origin)
|
||||||
|
|
||||||
Search: `bin/brain/search.go "query"` (HTTP: `bin/brain/serve.go` —
|
Search: `bin/brain/search.go "query"` (HTTP: `bin/brain/serve.go`). `--hop` is
|
||||||
`/health` `/search` `/get` `/stats` `/audit` `/ingest`). `--hop` is
|
|
||||||
not a walk; the flag errors until File/FROM_FILE edges exist.
|
not a walk; the flag errors until File/FROM_FILE edges exist.
|
||||||
|
|
||||||
Published docs live here and mirror the project state.
|
Published docs live here and mirror the project state.
|
||||||
|
|||||||
@@ -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
|
||||||
@@ -1,154 +0,0 @@
|
|||||||
//go:build cgo && system_ladybug
|
|
||||||
|
|
||||||
package brain
|
|
||||||
|
|
||||||
import (
|
|
||||||
"bytes"
|
|
||||||
"context"
|
|
||||||
"encoding/json"
|
|
||||||
"fmt"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Ready opens the Ladybug file for the life of the serve process.
|
|
||||||
func Ready() error {
|
|
||||||
return openBrain()
|
|
||||||
}
|
|
||||||
|
|
||||||
// HTTP is the in-process API used by bin/brain/serve.go.
|
|
||||||
type HTTP struct{}
|
|
||||||
|
|
||||||
func (HTTP) Search(_ context.Context, query string, limit int) ([]byte, error) {
|
|
||||||
hits, err := searchHits(query, "", "", limit)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
for i := range hits {
|
|
||||||
if hits[i].Text != "" {
|
|
||||||
runes := []rune(hits[i].Text)
|
|
||||||
if len(runes) > 280 {
|
|
||||||
runes = runes[:280]
|
|
||||||
}
|
|
||||||
hits[i].Snippet = string(runes)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
var buf bytes.Buffer
|
|
||||||
enc := json.NewEncoder(&buf)
|
|
||||||
enc.SetEscapeHTML(false)
|
|
||||||
if err := enc.Encode(toJSONOut(hits, query, "")); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return buf.Bytes(), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (HTTP) Get(_ context.Context, id string, body bool) ([]byte, error) {
|
|
||||||
if conn == nil {
|
|
||||||
return nil, fmt.Errorf("brain not open")
|
|
||||||
}
|
|
||||||
stmt, err := conn.Prepare(
|
|
||||||
"MATCH (l:Leaf {id:$id}) RETURN l.id, l.text, l.root, l.confidence, l.source, l.type",
|
|
||||||
)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
defer stmt.Close()
|
|
||||||
res, err := conn.Execute(stmt, map[string]any{"id": id})
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
if !res.HasNext() {
|
|
||||||
return nil, fmt.Errorf("no leaf %s", id)
|
|
||||||
}
|
|
||||||
row, err := res.Next()
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
vals, err := row.GetAsSlice()
|
|
||||||
if err != nil || len(vals) < 6 {
|
|
||||||
return nil, fmt.Errorf("leaf row")
|
|
||||||
}
|
|
||||||
out := map[string]any{
|
|
||||||
"id": fmt.Sprint(vals[0]),
|
|
||||||
"root": fmt.Sprint(vals[2]),
|
|
||||||
"confidence": fmt.Sprint(vals[3]),
|
|
||||||
"source": fmt.Sprint(vals[4]),
|
|
||||||
"type": fmt.Sprint(vals[5]),
|
|
||||||
}
|
|
||||||
if body {
|
|
||||||
out["text"] = fmt.Sprint(vals[1])
|
|
||||||
}
|
|
||||||
return json.Marshal(out)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (HTTP) Stats(context.Context) ([]byte, error) {
|
|
||||||
if conn == nil {
|
|
||||||
return nil, fmt.Errorf("brain not open")
|
|
||||||
}
|
|
||||||
res, err := conn.Query("MATCH (l:Leaf) RETURN l.root, count(*)")
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
byRoot := map[string]int{}
|
|
||||||
total := 0
|
|
||||||
for res.HasNext() {
|
|
||||||
row, err := res.Next()
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
vals, err := row.GetAsSlice()
|
|
||||||
if err != nil || len(vals) < 2 {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
n := int(asInt(vals[1]))
|
|
||||||
byRoot[fmt.Sprint(vals[0])] = n
|
|
||||||
total += n
|
|
||||||
}
|
|
||||||
return json.Marshal(map[string]any{"total": total, "by_root": byRoot, "db": dbPath()})
|
|
||||||
}
|
|
||||||
|
|
||||||
func (HTTP) Audit(context.Context) ([]byte, error) {
|
|
||||||
if conn == nil {
|
|
||||||
return nil, fmt.Errorf("brain not open")
|
|
||||||
}
|
|
||||||
res, err := conn.Query("MATCH (l:Leaf) RETURN l.root, l.confidence, count(*)")
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
var rows []map[string]any
|
|
||||||
for res.HasNext() {
|
|
||||||
row, err := res.Next()
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
vals, err := row.GetAsSlice()
|
|
||||||
if err != nil || len(vals) < 3 {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
rows = append(rows, map[string]any{
|
|
||||||
"root": fmt.Sprint(vals[0]),
|
|
||||||
"confidence": fmt.Sprint(vals[1]),
|
|
||||||
"count": asInt(vals[2]),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
return json.Marshal(map[string]any{"status": "ok", "by_confidence": rows})
|
|
||||||
}
|
|
||||||
|
|
||||||
func (HTTP) Ingest(context.Context) ([]byte, error) {
|
|
||||||
return json.Marshal(map[string]any{
|
|
||||||
"mode": "rebuild",
|
|
||||||
"command": "bin/brain/index.go --rebuild",
|
|
||||||
"add": "v2",
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
func asInt(v any) int64 {
|
|
||||||
switch n := v.(type) {
|
|
||||||
case int64:
|
|
||||||
return n
|
|
||||||
case int:
|
|
||||||
return int64(n)
|
|
||||||
case float64:
|
|
||||||
return int64(n)
|
|
||||||
default:
|
|
||||||
return 0
|
|
||||||
}
|
|
||||||
}
|
|
||||||
+15
-19
@@ -51,13 +51,25 @@ func runSearch(args []string) int {
|
|||||||
}
|
}
|
||||||
defer closeBrain()
|
defer closeBrain()
|
||||||
|
|
||||||
hits, err := searchHits(query, root, repo, limit)
|
emb, err := embedQuery(query)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Fprintf(os.Stderr, "search: %v\n", err)
|
fmt.Fprintf(os.Stderr, "embed: %v\n", err)
|
||||||
return 1
|
return 1
|
||||||
}
|
}
|
||||||
|
|
||||||
results := hits
|
fts, err := queryFTS(query, limit*3)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintf(os.Stderr, "fts: %v\n", err)
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
|
||||||
|
var vec []Hit
|
||||||
|
if vec, err = queryVector(emb, limit*3); err != nil {
|
||||||
|
fmt.Fprintf(os.Stderr, "vec: %v\n", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
results := rank.RankAndFilter(fts, vec, root, repo, limit)
|
||||||
|
|
||||||
for i := range results {
|
for i := range results {
|
||||||
if results[i].Text != "" {
|
if results[i].Text != "" {
|
||||||
runes := []rune(results[i].Text)
|
runes := []rune(results[i].Text)
|
||||||
@@ -85,22 +97,6 @@ func runSearch(args []string) int {
|
|||||||
return 0
|
return 0
|
||||||
}
|
}
|
||||||
|
|
||||||
func searchHits(query, root, repo string, limit int) ([]Hit, error) {
|
|
||||||
emb, err := embedQuery(query)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("embed: %w", err)
|
|
||||||
}
|
|
||||||
fts, err := queryFTS(query, limit*3)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("fts: %w", err)
|
|
||||||
}
|
|
||||||
var vec []Hit
|
|
||||||
if vec, err = queryVector(emb, limit*3); err != nil {
|
|
||||||
fmt.Fprintf(os.Stderr, "vec: %v\n", err)
|
|
||||||
}
|
|
||||||
return rank.RankAndFilter(fts, vec, root, repo, limit), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func b2i(err error) int {
|
func b2i(err error) int {
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return 1
|
return 1
|
||||||
|
|||||||
+33
-104
@@ -1,10 +1,10 @@
|
|||||||
// Package httpapi serves the 2dph brain over HTTP.
|
// Package server serves the 2dph brain over HTTP.
|
||||||
//
|
//
|
||||||
// Async by design: every request runs on its own goroutine, and CPU-heavy
|
// Async by design: every request runs on its own goroutine, and CPU-heavy
|
||||||
// searches are serialized through a bounded worker pool so N requests can't
|
// searches are serialized through a bounded worker pool (a counting
|
||||||
// spawn N backends at once.
|
// semaphore) so N requests can't spawn N search processes at once.
|
||||||
//
|
//
|
||||||
// Used by bin/brain/serve.go. Tests inject a fake API (no exec, no ladybug).
|
// Used by bin/brain/serve.go.
|
||||||
package httpapi
|
package httpapi
|
||||||
|
|
||||||
import (
|
import (
|
||||||
@@ -21,45 +21,30 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
// API is the in-process brain surface. Production serve.go wires internal/brain.
|
type Searcher interface {
|
||||||
type API interface {
|
|
||||||
Search(ctx context.Context, query string, limit int) ([]byte, error)
|
Search(ctx context.Context, query string, limit int) ([]byte, error)
|
||||||
Get(ctx context.Context, id string, body bool) ([]byte, error)
|
|
||||||
Stats(ctx context.Context) ([]byte, error)
|
|
||||||
Audit(ctx context.Context) ([]byte, error)
|
|
||||||
Ingest(ctx context.Context) ([]byte, error)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type Server struct {
|
type Server struct {
|
||||||
api API
|
searcher Searcher
|
||||||
semaphore chan struct{}
|
semaphore chan struct{}
|
||||||
}
|
}
|
||||||
|
|
||||||
const defaultPort = 8630
|
const defaultPort = 8630
|
||||||
|
|
||||||
var errUnimplemented = errors.New("not implemented")
|
func NewServer(searcher Searcher, workers int) http.Handler {
|
||||||
|
|
||||||
func NewServer(api API, workers int) http.Handler {
|
|
||||||
return &Server{
|
return &Server{
|
||||||
api: api,
|
searcher: searcher,
|
||||||
semaphore: make(chan struct{}, workers),
|
semaphore: make(chan struct{}, workers),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||||
switch r.URL.Path {
|
switch {
|
||||||
case "/health":
|
case r.URL.Path == "/health":
|
||||||
writeJSON(w, http.StatusOK, map[string]any{"status": "ok"})
|
writeJSON(w, http.StatusOK, map[string]any{"status": "ok"})
|
||||||
case "/search":
|
case r.URL.Path == "/search":
|
||||||
s.handleSearch(w, r)
|
s.handleSearch(w, r)
|
||||||
case "/get":
|
|
||||||
s.handleGet(w, r)
|
|
||||||
case "/stats":
|
|
||||||
s.handleJSON(w, r, s.api.Stats)
|
|
||||||
case "/audit":
|
|
||||||
s.handleJSON(w, r, s.api.Audit)
|
|
||||||
case "/ingest":
|
|
||||||
s.handleJSON(w, r, s.api.Ingest)
|
|
||||||
default:
|
default:
|
||||||
writeJSON(w, http.StatusNotFound, map[string]any{"error": "not found"})
|
writeJSON(w, http.StatusNotFound, map[string]any{"error": "not found"})
|
||||||
}
|
}
|
||||||
@@ -80,56 +65,19 @@ func (s *Server) handleSearch(w http.ResponseWriter, r *http.Request) {
|
|||||||
}
|
}
|
||||||
limit = n
|
limit = n
|
||||||
}
|
}
|
||||||
if !s.acquire(w, r) {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
defer s.release()
|
|
||||||
body, err := s.api.Search(r.Context(), q, limit)
|
|
||||||
writeAPI(w, body, err)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *Server) handleGet(w http.ResponseWriter, r *http.Request) {
|
// Worker pool: block until a slot frees, so burst concurrency still
|
||||||
id := strings.TrimSpace(r.URL.Query().Get("id"))
|
// bounds memory (no unbounded python processes).
|
||||||
if id == "" {
|
|
||||||
writeJSON(w, http.StatusBadRequest, map[string]any{"error": "id required"})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
body := r.URL.Query().Get("body") == "1" || r.URL.Query().Get("body") == "true"
|
|
||||||
if !s.acquire(w, r) {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
defer s.release()
|
|
||||||
out, err := s.api.Get(r.Context(), id, body)
|
|
||||||
writeAPI(w, out, err)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *Server) handleJSON(w http.ResponseWriter, r *http.Request, fn func(context.Context) ([]byte, error)) {
|
|
||||||
if !s.acquire(w, r) {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
defer s.release()
|
|
||||||
body, err := fn(r.Context())
|
|
||||||
writeAPI(w, body, err)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *Server) acquire(w http.ResponseWriter, r *http.Request) bool {
|
|
||||||
select {
|
select {
|
||||||
case s.semaphore <- struct{}{}:
|
case s.semaphore <- struct{}{}:
|
||||||
return true
|
defer func() { <-s.semaphore }()
|
||||||
case <-r.Context().Done():
|
case <-r.Context().Done():
|
||||||
return false
|
return
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
func (s *Server) release() { <-s.semaphore }
|
body, err := s.searcher.Search(r.Context(), q, limit)
|
||||||
|
|
||||||
func writeAPI(w http.ResponseWriter, body []byte, err error) {
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
code := http.StatusBadGateway
|
writeJSON(w, http.StatusGatewayTimeout, map[string]any{"error": err.Error()})
|
||||||
if errors.Is(err, errUnimplemented) {
|
|
||||||
code = http.StatusNotImplemented
|
|
||||||
}
|
|
||||||
writeJSON(w, code, map[string]any{"error": err.Error()})
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
writeRaw(w, http.StatusOK, body)
|
writeRaw(w, http.StatusOK, body)
|
||||||
@@ -147,20 +95,17 @@ func writeRaw(w http.ResponseWriter, code int, body []byte) {
|
|||||||
w.Write(body)
|
w.Write(body)
|
||||||
}
|
}
|
||||||
|
|
||||||
// ExecSearcher shells out to var/bin/brain-search. Fallback when the serve
|
// brainSearcher shells out to the Go brain-search binary (not Python).
|
||||||
// binary is built without ladybug cgo (CI / tags=brain_serve only).
|
// A single search is bounded and short-lived; the worker pool keeps at most N live.
|
||||||
type ExecSearcher struct {
|
type brainSearcher struct {
|
||||||
CmdPath string
|
cmdPath string
|
||||||
Timeout time.Duration
|
timeout time.Duration
|
||||||
}
|
}
|
||||||
|
|
||||||
func (b ExecSearcher) Search(ctx context.Context, query string, limit int) ([]byte, error) {
|
func (b *brainSearcher) Search(ctx context.Context, query string, limit int) ([]byte, error) {
|
||||||
if b.Timeout == 0 {
|
ctx, cancel := context.WithTimeout(ctx, b.timeout)
|
||||||
b.Timeout = 60 * time.Second
|
|
||||||
}
|
|
||||||
ctx, cancel := context.WithTimeout(ctx, b.Timeout)
|
|
||||||
defer cancel()
|
defer cancel()
|
||||||
cmd := exec.CommandContext(ctx, b.CmdPath, "--json", "-n", strconv.Itoa(limit), query)
|
cmd := exec.CommandContext(ctx, b.cmdPath, "--json", "-n", strconv.Itoa(limit), query)
|
||||||
out, err := cmd.Output()
|
out, err := cmd.Output()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
var exitErr *exec.ExitError
|
var exitErr *exec.ExitError
|
||||||
@@ -172,18 +117,6 @@ func (b ExecSearcher) Search(ctx context.Context, query string, limit int) ([]by
|
|||||||
return out, nil
|
return out, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (ExecSearcher) Get(context.Context, string, bool) ([]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) Ingest(context.Context) ([]byte, error) {
|
|
||||||
return json.Marshal(map[string]any{
|
|
||||||
"mode": "rebuild",
|
|
||||||
"command": "bin/brain/index.go --rebuild",
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
func defaultSearchCmd(root string) string {
|
func defaultSearchCmd(root string) string {
|
||||||
if env := os.Getenv("KB_SEARCH_CMD"); env != "" {
|
if env := os.Getenv("KB_SEARCH_CMD"); env != "" {
|
||||||
return env
|
return env
|
||||||
@@ -191,7 +124,11 @@ func defaultSearchCmd(root string) string {
|
|||||||
return filepath.Join(root, "var", "bin", "brain-search")
|
return filepath.Join(root, "var", "bin", "brain-search")
|
||||||
}
|
}
|
||||||
|
|
||||||
func workersAndPort() (int, int) {
|
// Run starts the HTTP server. Reads env: KB_SEARCH_CMD (default
|
||||||
|
// $KB_ROOT/var/bin/brain-search), KB_WORKERS (default 4), KB_PORT (default 8630).
|
||||||
|
func Run() {
|
||||||
|
root := os.Getenv("KB_ROOT")
|
||||||
|
searchPath := defaultSearchCmd(root)
|
||||||
workers := 4
|
workers := 4
|
||||||
if raw := os.Getenv("KB_WORKERS"); raw != "" {
|
if raw := os.Getenv("KB_WORKERS"); raw != "" {
|
||||||
if n, err := strconv.Atoi(raw); err == nil && n > 0 {
|
if n, err := strconv.Atoi(raw); err == nil && n > 0 {
|
||||||
@@ -204,19 +141,11 @@ func workersAndPort() (int, int) {
|
|||||||
port = n
|
port = n
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return workers, port
|
|
||||||
}
|
|
||||||
|
|
||||||
// Run starts the HTTP server with an injected API (in-process brain, or ExecSearcher).
|
searcher := &brainSearcher{cmdPath: searchPath, timeout: 60 * time.Second}
|
||||||
func Run(api API) {
|
handler := NewServer(searcher, workers)
|
||||||
if api == nil {
|
|
||||||
root := os.Getenv("KB_ROOT")
|
|
||||||
api = ExecSearcher{CmdPath: defaultSearchCmd(root), Timeout: 60 * time.Second}
|
|
||||||
}
|
|
||||||
workers, port := workersAndPort()
|
|
||||||
handler := NewServer(api, workers)
|
|
||||||
addr := "127.0.0.1:" + strconv.Itoa(port)
|
addr := "127.0.0.1:" + strconv.Itoa(port)
|
||||||
log.Printf("serve: %s (workers=%d)", addr, workers)
|
log.Printf("serve: %s (workers=%d cmd=%s)", addr, workers, searchPath)
|
||||||
if err := http.ListenAndServe(addr, handler); err != nil {
|
if err := http.ListenAndServe(addr, handler); err != nil {
|
||||||
log.Fatal(err)
|
log.Fatal(err)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,7 +5,6 @@ import (
|
|||||||
"encoding/json"
|
"encoding/json"
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/http/httptest"
|
"net/http/httptest"
|
||||||
"os"
|
|
||||||
"strings"
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
"sync/atomic"
|
"sync/atomic"
|
||||||
@@ -48,26 +47,6 @@ func (f *fakeSearcher) Search(ctx context.Context, query string, limit int) ([]b
|
|||||||
return []byte(`{"query":"` + query + `","count":0,"results":[]}`), nil
|
return []byte(`{"query":"` + query + `","count":0,"results":[]}`), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (f *fakeSearcher) Get(_ context.Context, id string, body bool) ([]byte, error) {
|
|
||||||
out := map[string]any{"id": id, "root": "info"}
|
|
||||||
if body {
|
|
||||||
out["text"] = "fake body"
|
|
||||||
}
|
|
||||||
return json.Marshal(out)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (f *fakeSearcher) Stats(context.Context) ([]byte, error) {
|
|
||||||
return []byte(`{"total":0,"by_root":{}}`), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (f *fakeSearcher) Audit(context.Context) ([]byte, error) {
|
|
||||||
return []byte(`{"status":"ok"}`), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (f *fakeSearcher) Ingest(context.Context) ([]byte, error) {
|
|
||||||
return []byte(`{"mode":"rebuild","command":"bin/brain/index.go --rebuild"}`), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (f *fakeSearcher) count() int {
|
func (f *fakeSearcher) count() int {
|
||||||
f.mu.Lock()
|
f.mu.Lock()
|
||||||
defer f.mu.Unlock()
|
defer f.mu.Unlock()
|
||||||
@@ -163,47 +142,6 @@ func TestSearchRejectsBadLimit(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestGetLeaf(t *testing.T) {
|
|
||||||
fs := &fakeSearcher{callback: func(q string, limit int) ([]byte, error) {
|
|
||||||
return []byte(`{}`), nil
|
|
||||||
}}
|
|
||||||
h := NewServer(fs, 1)
|
|
||||||
if code, _ := get(t, h, "/get"); code != http.StatusBadRequest {
|
|
||||||
t.Fatalf("missing id code = %d, want 400", code)
|
|
||||||
}
|
|
||||||
code, body := get(t, h, "/get?id=leaf-1&body=1")
|
|
||||||
if code != http.StatusOK {
|
|
||||||
t.Fatalf("get code = %d, want 200 body=%s", code, body)
|
|
||||||
}
|
|
||||||
if !strings.Contains(string(body), "leaf-1") {
|
|
||||||
t.Fatalf("get body %s missing id", body)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestStatsAuditIngest(t *testing.T) {
|
|
||||||
h := NewServer(&fakeSearcher{}, 1)
|
|
||||||
for _, path := range []string{"/stats", "/audit", "/ingest"} {
|
|
||||||
code, body := get(t, h, path)
|
|
||||||
if code != http.StatusOK {
|
|
||||||
t.Fatalf("%s code = %d, want 200 (%s)", path, code, body)
|
|
||||||
}
|
|
||||||
if !json.Valid(body) {
|
|
||||||
t.Fatalf("%s body not json: %s", path, body)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestHTTPPackageDoesNotExecPython(t *testing.T) {
|
|
||||||
raw, err := os.ReadFile("server.go")
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
lower := strings.ToLower(string(raw))
|
|
||||||
if strings.Contains(lower, "python3") || strings.Contains(lower, "bin/kb/search") {
|
|
||||||
t.Fatal("httpapi must not exec Python or bin/kb/search")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestDefaultSearchCmdIsBrainNotPython(t *testing.T) {
|
func TestDefaultSearchCmdIsBrainNotPython(t *testing.T) {
|
||||||
t.Setenv("KB_SEARCH_CMD", "")
|
t.Setenv("KB_SEARCH_CMD", "")
|
||||||
cmd := defaultSearchCmd("/repo")
|
cmd := defaultSearchCmd("/repo")
|
||||||
|
|||||||
@@ -0,0 +1,34 @@
|
|||||||
|
---
|
||||||
|
name: agent-cost
|
||||||
|
description: >-
|
||||||
|
Measure what an agent session actually costs in tokens using bin/agents/cost.
|
||||||
|
Use before and after changing documentation, skills or context layout, and when
|
||||||
|
a session feels unexpectedly expensive.
|
||||||
|
---
|
||||||
|
|
||||||
|
# agent-cost
|
||||||
|
|
||||||
|
```bash
|
||||||
|
bin/agents/cost # every project, YAML
|
||||||
|
bin/agents/cost --repo 2dph # only sessions whose cwd matches
|
||||||
|
bin/agents/cost --json | jq .cursor.by_tool
|
||||||
|
bin/agents/cost --snapshot after-x --repo 2dph # append a row to docs/CONTEXT-BUDGET.md
|
||||||
|
```
|
||||||
|
|
||||||
|
Reads local session storage from OpenCode and Cursor transcripts. Reports the
|
||||||
|
always-loaded baseline, cache hit/miss/thrash, and which tools moved the most
|
||||||
|
bytes.
|
||||||
|
|
||||||
|
## How to read it
|
||||||
|
|
||||||
|
- **Baseline** is what every single message pays for: `AGENTS.md` plus anything
|
||||||
|
eagerly linked from it. Keep it small; it multiplies by message count.
|
||||||
|
- **Cache thrash** matters more than raw size. Editing a file that sits early in
|
||||||
|
the context invalidates the prompt cache for the whole session.
|
||||||
|
- **by_tool bytes** shows where the real spend is. Usually it is unfiltered
|
||||||
|
command output, not documentation.
|
||||||
|
|
||||||
|
## Rule
|
||||||
|
|
||||||
|
Measure before and after. A claim that something "reduces tokens" without a
|
||||||
|
before and an after number is an opinion, not a result.
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
---
|
---
|
||||||
name: brain
|
name: kb-search
|
||||||
description: >-
|
description: >-
|
||||||
Deduction search over the 2dph brain (Ladybug graph: ops corpus, portfolio,
|
Deduction search over the 2dph brain (Ladybug graph: ops corpus, portfolio,
|
||||||
ssh hosts) with bin/brain/search.go instead of reading files or grepping
|
ssh hosts) with bin/brain/search.go instead of reading files or grepping
|
||||||
@@ -8,7 +8,7 @@ description: >-
|
|||||||
documentation.
|
documentation.
|
||||||
---
|
---
|
||||||
|
|
||||||
# brain — deduction over facts and info
|
# kb-search — deduction over facts and info
|
||||||
|
|
||||||
One embedded Ladybug graph (`var/kb.lbug`, read-only when queried) holding two
|
One embedded Ladybug graph (`var/kb.lbug`, read-only when queried) holding two
|
||||||
roots:
|
roots:
|
||||||
Reference in New Issue
Block a user