Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
84 changes: 42 additions & 42 deletions docs/brain-synapse.md
Original file line number Diff line number Diff line change
@@ -1,106 +1,106 @@
# Brain Synapse Matrix — сервис для pc-agent (issue #82)
# Brain Synapse Matrix — service for pc-agent (issue #82)

Мозг 2dph (`internal/brain`: leafs + edges) как HTTP-сервис. Метафора:
**leafs = нейроны**, **SYNAPTIC edges = синапсы**. pc-agent читает граф и
пишет новые наблюдения как leafs с `source=pc-agent`.
The 2dph brain (`internal/brain`: leafs + edges) as an HTTP service. Metaphor:
**leafs = neurons**, **SYNAPTIC edges = synapses**. pc-agent reads the graph and
writes new observations as leafs with `source=pc-agent`.

## Запуск
## Startup

```bash
# loopback only, порт 8632 (по умолчанию)
# loopback only, port 8632 (default)
scripts/stack/synapse-matrix

# с токеном и доступом снаружи (0.0.0.0 требует токен!)
# with a token and outside access (0.0.0.0 requires a token!)
KB_SYNAPSE_HOST=0.0.0.0 KB_SYNAPSE_TOKEN=<token> scripts/stack/synapse-matrix

# напрямую (shebang-тулза, Zig CGO)
# directly (shebang tool, Zig CGO)
./bin/brain/synapse-matrix.go
```

Конфиг — стек go-config (`etc/brain/config.yml → config.local.yml → .env →
env`), секция `synapse` (legacy `KB_SYNAPSE_*`):
Config — the go-config stack (`etc/brain/config.yml → config.local.yml → .env →
env`), section `synapse` (legacy `KB_SYNAPSE_*`):

```yaml
synapse:
host: "127.0.0.1" # 0.0.0.0 требует token
host: "127.0.0.1" # 0.0.0.0 requires a token
port: 8632
token: "" # пусто = только loopback bind
token: "" # empty = loopback bind only
```

## Auth

Политика (#82): **token ИЛИ bind 127.0.0.1**.
Policy (#82): **token OR bind 127.0.0.1**.

- Есть `synapse.token` → каждый маршрут кроме `/health` требует
- If `synapse.token` is set → every route except `/health` requires
`Authorization: Bearer <token>`.
- Нет токена → сервис отказывается биндиться на что-либо кроме loopback.
- `/health` всегда открыт (для оркестраторов).
- No token → the service refuses to bind to anything but loopback.
- `/health` is always open (for orchestrators).

## Endpoints

| Метод | Путь | Что |
| Method | Path | What |
|-------|------|-----|
| GET | `/health` | liveness |
| GET | `/leafs?root=&type=&source=&q=&n=` | выборка leafs по фильтрам/тексту |
| GET | `/edges?id=` | adjacency (входящие+исходящие синапсы) |
| POST | `/addedge` | добавить синапс `{from,to,type}` |
| GET | `/path?from=&to=&max=` | кратчайший путь между leafs |
| GET | `/leafs?root=&type=&source=&q=&n=` | selection of leafs by filters/text |
| GET | `/edges?id=` | adjacency (incoming+outgoing synapses) |
| POST | `/addedge` | add a synapse `{from,to,type}` |
| GET | `/path?from=&to=&max=` | shortest path between leafs |
| GET | `/openapi.json` | OpenAPI 3 |
| POST | `/mcp` | JSON-RPC MCP (tools: search, get, audit, leafs, edges, addedge, path) |

Полное описание — `GET /openapi.json` (генерируется из `pkg/httpapi.Ops`).
The full description — `GET /openapi.json` (generated from `pkg/httpapi.Ops`).

## Примеры curl
## curl examples

```bash
HOST=127.0.0.1; PORT=8632; TOKEN=<token>
AUTH="Authorization: Bearer $TOKEN"

# leafs по root
# leafs by root
curl -s -H "$AUTH" "http://$HOST:$PORT/leafs?root=facts&n=10"

# leafs по источнику (наблюдения pc-agent)
# leafs by source (pc-agent observations)
curl -s -H "$AUTH" "http://$HOST:$PORT/leafs?source=pc-agent&n=50"

# leafs по типу
# leafs by type
curl -s -H "$AUTH" "http://$HOST:$PORT/leafs?type=fact&root=facts"

# full-text по тексту leaf
# full-text over the leaf text
curl -s -H "$AUTH" "http://$HOST:$PORT/leafs?q=container&n=5"

# adjacency одной leaf (входящие+исходящие синапсы)
# adjacency of one leaf (incoming+outgoing synapses)
curl -s -H "$AUTH" "http://$HOST:$PORT/edges?id=<leaf-id>"

# добавить синапс (оба leaf должны существовать; MERGE идемпотентен)
# add a synapse (both leafs must exist; MERGE is idempotent)
curl -s -X POST -H "$AUTH" -H "Content-Type: application/json" \
-d '{"from":"<id-a>","to":"<id-b>","type":"supports"}' \
"http://$HOST:$PORT/addedge"

# кратчайший путь a -> c
# shortest path a -> c
curl -s -H "$AUTH" "http://$HOST:$PORT/path?from=<id-a>&to=<id-c>&max=6"
```

Без токена: 401 на всех маршрутах кроме `/health`.
Without a token: 401 on all routes except `/health`.

## Контракт для pc-agent
## Contract for pc-agent

1. **Читает** граф: `GET /leafs` (выборка по root/type/source/тексту),
`GET /edges` (adjacency), `GET /path` (связность).
2. **Пишет** новые наблюдения как leafs с `source=pc-agent` через
`POST /ingest` (существующий endpoint; режим add, без rebuild):
1. **Reads** the graph: `GET /leafs` (selection by root/type/source/text),
`GET /edges` (adjacency), `GET /path` (connectivity).
2. **Writes** new observations as leafs with `source=pc-agent` via
`POST /ingest` (an existing endpoint; add mode, without rebuild):
```bash
curl -s -X POST -H "$AUTH" -H "Content-Type: application/json" \
-d '{"text":"наблюдение pc-agent","root":"info","source":"pc-agent","type":"fact"}' \
-d '{"text":"pc-agent observation","root":"info","source":"pc-agent","type":"fact"}' \
"http://$HOST:$PORT/ingest"
```
3. **Связывает** наблюдения синапсами через `POST /addedge`.
3. **Links** observations with synapses via `POST /addedge`.

MCP-альтернатива: `POST /mcp` JSON-RPC `tools/call` c именами `leafs`,
`edges`, `addedge`, `path` — те же параметры, что в OpenAPI.
MCP alternative: `POST /mcp` JSON-RPC `tools/call` with the names `leafs`,
`edges`, `addedge`, `path` — the same parameters as in OpenAPI.

## Тесты
## Tests

- `internal/brain/synapse_test.go` (cgo+system_ladybug, temp-DB фикстуры):
- `internal/brain/synapse_test.go` (cgo+system_ladybug, temp-DB fixtures):
`TestQueryLeafsByFilters`, `TestAddEdgeAndAdjacency`, `TestPathBetween`,
`TestHTTPLeafsEdgesPathJSON`, `TestSynapseHTTPServerEndToEnd`.
- `pkg/httpapi/server_test.go` (offline, fake API): leafs/edges/addedge/path
Expand Down
Loading