diff --git a/docs/brain-synapse.md b/docs/brain-synapse.md index 37b14f5..9ea6ad6 100644 --- a/docs/brain-synapse.md +++ b/docs/brain-synapse.md @@ -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= 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 `. -- Нет токена → сервис отказывается биндиться на что-либо кроме 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= 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 должны существовать; MERGE идемпотентен) +# add a synapse (both leafs must exist; MERGE is idempotent) curl -s -X POST -H "$AUTH" -H "Content-Type: application/json" \ -d '{"from":"","to":"","type":"supports"}' \ "http://$HOST:$PORT/addedge" -# кратчайший путь a -> c +# shortest path a -> c curl -s -H "$AUTH" "http://$HOST:$PORT/path?from=&to=&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 diff --git a/docs/brain/contract.md b/docs/brain/contract.md index 6eb0324..c207172 100644 --- a/docs/brain/contract.md +++ b/docs/brain/contract.md @@ -1,71 +1,73 @@ -# Контракт записи в Ladybug (P-9.2 + P-9.3) +# Leaf write contract in Ladybug (P-9.2 + P-9.3) -Единый контракт записи leaf в Ladybug для всех источников корпуса (mail, -git, chats, docs, facts). Формализация по образцу gator `contract.Record` -(G-8.0, issue #73) — см. также общий ADR по версионности P-9.6 (#16). +Single contract for writing a leaf into Ladybug for all corpus sources (mail, +git, chats, docs, facts). Formalization following the gator `contract.Record` +model (G-8.0, issue #73) — see also the shared versioning ADR P-9.6 (#16). -Реализация: пакет `internal/contract` (cgo-free) + адаптеры корпуса -`internal/corpus` (cgo-free) + write-путь `internal/brain` (колонки +Implementation: package `internal/contract` (cgo-free) + corpus adapters +`internal/corpus` (cgo-free) + write path `internal/brain` (columns `observed_at`, `external_id`; id = `ContentHash`). -## Поля leaf +## Leaf fields -| Поле | Обязательно | Смысл | +| Field | Required | Meaning | |------|-------------|-------| -| `source` | да | корпус-источник: `mail` / `git` / `chats` / `docs` / `facts` (P-9.3: имя корпуса, не evidence pointer) | -| `external_id` | да | устойчивый ref внутри корпуса: message id / commit sha / chat message id / rel-путь файла | -| `kind` | да | тип leaf: `fact` / `mail` / `chat` / `commit` / `reference` / `seed` / … | -| `text` | да | содержимое leaf | -| `root` | нет | `facts` (утверждение, ≥2 источника) или `info` (нарратив); default `info` | -| `confidence` | нет | `confirmed` / `estimated` / `inferred` / …; default `confirmed` | -| `source_rev` | нет | ревизия источника: `working-tree` / sha; default `working-tree` | -| `how` | нет | как получено: `kb/index`, `mail/import`, `git-log`, `facts/extract`, `brain/add` | -| `loc` | нет | локальный контекст (путь/репо); default = `source` | -| `valid_from` / `valid_to` | нет | D24-день валидности (YYYY-MM-DD) — **ортогонально версии**: это про факт, а не про запись | -| `observed_at` | нет | когда контент **увиден** (RFC3339); пусто → штамп `now()` при записи; **не входит в dedup-ключ** | - -Проверка обязательных полей — `Leaf.Validate()`; невалидный leaf режется на -границе записи (до upsert). - -## Dedup (ContentHash) — id в БД - -Dedup-ключ версии **и id записи в БД** — `ContentHash()` = -`sha256(source|external_id|kind|text)[:32]` (P-9.3: runtime id переведён с -`LeafID(text, source)[:24]` на контрактный `ContentHash` — единый ключ, -dedup-ключ == id). Текст перед хэшем нормализуется `contract.NormalizeText` -(ToValidUTF8 → LF → trim): один контент из разных путей (CRLF vs LF, -хвостовые пробелы) даёт один id. `observed_at` намеренно вне хэша — семантика -gator (G-8.0 #73): тот же контент, записанный позже, дедуплицируется к той же -версии (сохраняется первый `observed_at`); изменился контент → новый ключ. - -## Версионирование - -Одна версия = один id. Изменение контента (text) или identity (source / -external_id / kind) → новый `ContentHash` → новый id, старая версия остаётся в -графе. Повторная запись той же версии — MERGE (upsert), без дубликата. - -`valid_from/valid_to` — валидность факта по дням (D24, `facts.NormalizeDay`), -используется в поиске `--as-of`. Это не версионирование записи: версия -определяется id/ContentHash, валидность — интервалом. - -## Формат ref (external_id) — P-9.3 - -`source` = имя корпуса; `external_id` = устойчивый ref; `loc` = evidence -pointer (путь/репо) для FROM_FILE и аудита. - -| Корпус | source | external_id | Пример loc | +| `source` | yes | corpus source: `mail` / `git` / `chats` / `docs` / `facts` (P-9.3: corpus name, not an evidence pointer) | +| `external_id` | yes | stable ref inside the corpus: message id / commit sha / chat message id / file rel-path | +| `kind` | yes | leaf type: `fact` / `mail` / `chat` / `commit` / `reference` / `seed` / … | +| `text` | yes | leaf content | +| `root` | no | `facts` (claim, ≥2 sources) or `info` (narrative); default `info` | +| `confidence` | no | `confirmed` / `estimated` / `inferred` / …; default `confirmed` | +| `source_rev` | no | source revision: `working-tree` / sha; default `working-tree` | +| `how` | no | how it was obtained: `kb/index`, `mail/import`, `git-log`, `facts/extract`, `brain/add` | +| `loc` | no | local context (path/repo); default = `source` | +| `valid_from` / `valid_to` | no | D24 validity day (YYYY-MM-DD) — **orthogonal to the version**: it is about the fact, not about the record | +| `observed_at` | no | when the content was **seen** (RFC3339); empty → stamped with `now()` on write; **not part of the dedup key** | + +Required-field validation — `Leaf.Validate()`; an invalid leaf is cut at the +write boundary (before upsert). + +## Dedup (ContentHash) — the DB id + +The dedup key of the version **and the id of the record in the DB** — +`ContentHash()` = `sha256(source|external_id|kind|text)[:32]` (P-9.3: the +runtime id moved from `LeafID(text, source)[:24]` to the contract +`ContentHash` — one key, dedup key == id). Before hashing, the text is +normalized by `contract.NormalizeText` (ToValidUTF8 → LF → trim): the same +content from different paths (CRLF vs LF, trailing spaces) yields one id. +`observed_at` is deliberately outside the hash — gator semantics (G-8.0 #73): +the same content written later dedups to the same version (the first +`observed_at` is kept); the content changed → new key. + +## Versioning + +One version = one id. A change of content (text) or identity (source / +external_id / kind) → new `ContentHash` → new id, the old version stays in the +graph. Rewriting the same version — MERGE (upsert), without a duplicate. + +`valid_from/valid_to` — validity of the fact by days (D24, `facts.NormalizeDay`), +used in `--as-of` search. This is not record versioning: the version is +determined by id/ContentHash, validity — by an interval. + +## Ref format (external_id) — P-9.3 + +`source` = corpus name; `external_id` = stable ref; `loc` = evidence pointer +(path/repo) for FROM_FILE and the audit. + +| Corpus | source | external_id | Example loc | |--------|--------|-------------|------------| -| mail | `mail` | content-address `sha256(NormalizeText(text))[:16]` — единая схема для live (OO numeric id) и legacy (sha256:16 dir), чтобы один message из обоих корпусов сливался по ContentHash (#5.2) | `/var/corpus/mail///message.md` | -| git | `git` | commit sha (полный) | путь репозитория | -| chats | `chats` | frontmatter `id` (первый message id); нет id → content-address | `.../var/corpus/chats/md///messages.md` | -| docs | `docs` | относительный путь в репо (стабилен между машинами) | абсолютный путь файла | +| mail | `mail` | content-address `sha256(NormalizeText(text))[:16]` — one scheme for live (OO numeric id) and legacy (sha256:16 dir), so that one message from both corpora merges by ContentHash (#5.2) | `/var/corpus/mail///message.md` | +| git | `git` | commit sha (full) | repository path | +| chats | `chats` | frontmatter `id` (first message id); no id → content-address | `.../var/corpus/chats/md///messages.md` | +| docs | `docs` | relative path in the repo (stable across machines) | absolute file path | -Текст лифа = `Heading + "\n\n" + body` во всех корпусах (git переведён с -одинарного `\n` на двойной, #5.3) — единообразие для ContentHash. +Leaf text = `Heading + "\n\n" + body` in all corpora (git moved from a single +`\n` to a double one, #5.3) — uniformity for ContentHash. -## Адаптеры корпуса (P-9.3) +## Corpus adapters (P-9.3) -Каждый корпус — адаптер по контракту gator `Source` (`internal/contract`): +Each corpus is an adapter following the gator `Source` contract +(`internal/contract`): ```go type Source interface { @@ -74,47 +76,49 @@ type Source interface { } ``` -Адаптеры в `internal/corpus` (cgo-free): `mail.go`, `git.go`, `chats.go`, -`docs.go`. Общий index-драйвер (`bin/brain/index.go`) собирает leafs через -`corpus.StreamAll` и пишет единым `brain.WriteCorpus([]contract.Leaf)`. -**Добавление/удаление корпуса = адаптер в `sources()` + `--rebuild`** -(детерминированные id = ContentHash → пересборка без ручной магии). -Флаги `--with-mail` / `--with-chats` / `--corpus` / `--git-root` включают -соответствующие адаптеры. facts остаются отдельным путём (не корпус, а -evidence gate) — семантика «facts = ≥2 независимых источника» не трогается. +Adapters live in `internal/corpus` (cgo-free): `mail.go`, `git.go`, `chats.go`, +`docs.go`. The common index driver (`bin/brain/index.go`) collects leafs via +`corpus.StreamAll` and writes them with a single `brain.WriteCorpus([]contract.Leaf)`. +**Adding/removing a corpus = an adapter in `sources()` + `--rebuild`** +(deterministic ids = ContentHash → rebuild without manual magic). +The flags `--with-mail` / `--with-chats` / `--corpus` / `--git-root` enable the +corresponding adapters. facts remain a separate path (not a corpus but an +evidence gate) — the semantics "facts = ≥2 independent sources" is untouched. -Дубль git устранён: git-история пишется только git-адаптером -(`var/corpus/git/*.md` и `2dph__corpus__git__*` в docs-корпусе исключаются -docs-адаптером). +The git duplicate is eliminated: git history is written only by the git adapter +(`var/corpus/git/*.md` and `2dph__corpus__git__*` in the docs corpus are excluded +by the docs adapter). -## Аудит соответствия +## Conformance audit -`bin/brain/audit-contract.go` — read-only аудит против живой kb.lbug -(открывает БД с `ReadOnly=true`, не держит файл, агрегаты одним проходом): +`bin/brain/audit-contract.go` — read-only audit against the live kb.lbug +(opens the DB with `ReadOnly=true`, does not hold the file, aggregates in a +single pass): ./bin/brain/audit-contract.go # summary - ./bin/brain/audit-contract.go --json # полные агрегаты - -Считает total, пропуски обязательных/рекомендуемых полей, распределение по -корпусам (группировка по полю `source` напрямую — P-9.3; на живой БД до -пересборки source ещё содержит старые evidence-указатели, такие строки -показываются как есть). Прогон на живой БД -(2026-09-01, 313817 leafs): `missing_external_id: 313817` (колонки ещё нет — -миграция применится при старте сервиса), `missing_valid_from: 10099`, + ./bin/brain/audit-contract.go --json # full aggregates + +Counts total, missing required/recommended fields, distribution by corpus +(grouping by the `source` field directly — P-9.3; on the live DB before the +rebuild source still contains old evidence pointers, such rows are shown as +they are). Run on the live DB +(2026-09-01, 313817 leafs): `missing_external_id: 313817` (the column does not +exist yet — the migration will be applied when the service starts), +`missing_valid_from: 10099`, `missing_how/loc/kind: 4`, `observed_at: 0`. -## Известные расхождения (на момент P-9.3) +## Known discrepancies (as of P-9.3) -- Живая `var/kb.lbug` (313k leafs) ещё не пересобрана: старые id - (`sha256(source\0text)[:24]`), старые source (evidence pointers), git-дубль. - Пересборка — отдельный шаг (devops, после merge): `index --rebuild - --with-mail --with-facts [--with-chats] [--git-root DIR]`, полный рехэш id. -- facts-путь (`factsFromJSON`) пишет напрямую `UpsertLeaf` без `FROM_FILE` — - оставлено как есть, фиксируется контрактом как допустимый путь записи. +- The live `var/kb.lbug` (313k leafs) has not been rebuilt yet: old ids + (`sha256(source\0text)[:24]`), old source (evidence pointers), git duplicate. + The rebuild is a separate step (devops, after merge): `index --rebuild + --with-mail --with-facts [--with-chats] [--git-root DIR]`, full id rehash. +- The facts path (`factsFromJSON`) writes directly via `UpsertLeaf` without + `FROM_FILE` — left as is, recorded by the contract as an allowed write path. ## Cross-ref -- G-8.0 контракт записи gator: `internal/contract` (gator), issue #73. -- Общий паттерн версионности / ADR: P-9.6, issue #16. -- Адаптеры корпуса + рехэш id: P-9.3, issue #13. -- Скилл `brain` (skills/brain) — как пользоваться поиском и как добавить источник. +- G-8.0 gator write contract: `internal/contract` (gator), issue #73. +- Shared versioning pattern / ADR: P-9.6, issue #16. +- Corpus adapters + id rehash: P-9.3, issue #13. +- Skill `brain` (skills/brain) — how to use search and how to add a source. diff --git a/docs/brain/crm-network-filter.md b/docs/brain/crm-network-filter.md index 5efa248..1504665 100644 --- a/docs/brain/crm-network-filter.md +++ b/docs/brain/crm-network-filter.md @@ -1,111 +1,113 @@ -# CRM-network filter: люди/компании vs сервис-аккаунты (N-1.1 #268) +# CRM-network filter: people/companies vs service accounts (N-1.1 #268) -Детерминированный классификатор адреса сети связей (L-9.5 #234): **какие -accept-связи — реальные деловые контакты (люди/компании), а какие — -сервис-аккаунты/подсистемы/рассылки**, чтобы в OnlyOffice CRM не попали -GitLab/PayPal/LinkedIn/markets-platform/chiliproject@trac и аналоги. +Deterministic classifier of the contact-network address (L-9.5 #234): **which +accept links are real business contacts (people/companies) and which are +service accounts/subsystems/mailing lists**, so that +GitLab/PayPal/LinkedIn/markets-platform/chiliproject@trac and the like do not +end up in OnlyOffice CRM. -Эпик N-1 #267 («граф → OO CRM»): N-1.1 (этот фильтр) → N-1.2 коннектор → -N-1.3 пилот гдеgroup → N-1.4 компания-группировка. +Epic N-1 #267 ("graph → OO CRM"): N-1.1 (this filter) → N-1.2 connector → +N-1.3 wheregroup pilot → N-1.4 company grouping. -## Классы +## Classes -| kind | Значение | В CRM | +| kind | Meaning | In CRM | |------|----------|-------| -| `person` | человек: личный адрес или display name = реальное имя | да | -| `company` | организация/роль-ящик (`info@`, `kundenservice@`, отдел, группа) | да (N-1.4 группирует по домену) | -| `service` | автомат/сервис-домен/подсистема/трекер/список рассылки | **нет** | +| `person` | human: personal address or display name = a real name | yes | +| `company` | organization/role mailbox (`info@`, `kundenservice@`, department, group) | yes (N-1.4 groups by domain) | +| `service` | automaton/service domain/subsystem/tracker/mailing list | **no** | -## Где живёт +## Where it lives - `internal/mailconv/classify.go` (cgo-free): `ClassifySender(ParsedAddress)` - → `person|company|service`. База — sender-эвристики mailconv + → `person|company|service`. The basis is mailconv sender heuristics (`IsMachineSender`, `junkDomains`/`junkLocalParts`, messages.go): - доменный junk-список переиспользуется через общий `isJunkDomain` (одна - реализация, правило #10). Сеть НЕ использует локальные junk-ПОДСТРОКИ - mailconv («info@», «reply», «news») намеренно — см. «Отличия от - IsMachineSender». -- `internal/network/network.go`: поле `Link.Kind` заполняется в `BuildLinks` - для каждой связи (обратная совместимость: поле аддитивно, старый вывод - не ломается). -- `bin/network/network.go`: `--exclude-services` (общий фильтр) и - `--accept-only` (CRM-экспорт) **исключают `kind=service`**; kind печатается - в YAML/JSON/text. + the domain junk list is reused through the shared `isJunkDomain` (one + implementation, rule #10). The network deliberately does NOT use mailconv's + local junk SUBSTRINGS ("info@", "reply", "news") — see "Differences from + IsMachineSender". +- `internal/network/network.go`: the `Link.Kind` field is filled in `BuildLinks` + for every link (backward compatible: the field is additive, the old output + does not break). +- `bin/network/network.go`: `--exclude-services` (shared filter) and + `--accept-only` (CRM export) **exclude `kind=service`**; kind is printed + in YAML/JSON/text. -## Каскад правил (первое совпадение) +## Rule cascade (first match) -1. Пустой email / без `@` → `service` (защита). -2. **Платформенные релеи людей** (LinkedIn InMail): `hit-reply` / - `inmail-hit-reply` @ `linkedin.com` → `person`. Display name — реальный - человек (Ruby Rodriguez, Johanna Eckerstorfer), письма идут через релей - платформы, а не с личного адреса. Стоит ДО junk-доменов (linkedin.com — - junk). Дайджест-релеи (`messaging-digest-noreply@…`) — `service`. -3. **Сервис**: - - junk-домен mailconv (`isJunkDomain`: linkedin.com, github.com, - google.com, facebook.com, amazon.com, slack.com и др.) или поддомен; - - сервис-домены сети `networkServiceDomains` (по реальным спискам #268 + - очевидные аккаунт-платформы): `gitlab.com`, `paypal.com`, `paypal.de`, +1. Empty email / no `@` → `service` (guard). +2. **Platform relays for people** (LinkedIn InMail): `hit-reply` / + `inmail-hit-reply` @ `linkedin.com` → `person`. The display name is a real + person (Ruby Rodriguez, Johanna Eckerstorfer), the messages go through the + platform relay, not from a personal address. It stands BEFORE junk domains + (linkedin.com is junk). Digest relays (`messaging-digest-noreply@…`) — `service`. +3. **Service**: + - mailconv junk domain (`isJunkDomain`: linkedin.com, github.com, + google.com, facebook.com, amazon.com, slack.com and others) or a subdomain; + - network service domains `networkServiceDomains` (from the real lists #268 + + obvious account platforms): `gitlab.com`, `paypal.com`, `paypal.de`, `markets-platform.com`, `xing.com`, `djinni.co`, `wellfound.com`, `workablemail.com`, `coinbase.com`, `dynadot.com`, `hetzner.com`, `netlify.com`, `letsencrypt.org`, `steampowered.com`, `instagram.com`, `discord.com`, `microsoft.com`, `apple.com`; - - локальная часть-автомат (суффиксы после снятия `._-`): `noreply`, + - local part automaton (suffixes after stripping `._-`): `noreply`, `donotreply`, `mailerdaemon`, `postmaster`, `mailrobot`, `mailer`, `robot`, `bounce(s)`, `newsletter`, `notifications`, `jobalert(s)`, - `security`, `digest`, `alerts`; токены: `news`, `marketing`, + `security`, `digest`, `alerts`; tokens: `news`, `marketing`, `subscribe`; - - подсистема/трекер: tool-имя в локальной части или левом лейбле домена - (`toolNames`: gitlab, projeqtor, chiliproject, trac, redmine, jira, + - subsystem/tracker: tool name in the local part or the left label of the + domain (`toolNames`: gitlab, projeqtor, chiliproject, trac, redmine, jira, confluence, wiki, mediawiki, apache, svn, jenkins, mailman, sympa, - nagios, zabbix) — ловит `gitlab@wheregroup.com`, `projeqtor@wheregroup.com`, + nagios, zabbix) — catches `gitlab@wheregroup.com`, `projeqtor@wheregroup.com`, `chiliproject@trac.wheregroup.com`, `apache@wiki.wheregroup.com`, `gitlab@gitlab`, `dev@trac.example.com`; - - списки рассылки: локальная часть на `-request`/`-owner`, левый лейбл + - mailing lists: local part on `-request`/`-owner`, left label `lists` (`mapbender_dev-request@lists.osgeo.org`). -4. **Person**: display name похож на имя человека — ≥2 токена после снятия - декораций (« (Орг)», « via X»): Title-case / ALLCAPS / инициалы / частицы - (van/von/de/of/…); без корпоративных маркеров (GmbH/AG/e.V./Ltd/Inc/…) и - ролевых слов (Team/Wartung/Neuigkeiten/Digest/…). -5. **Person**: локальная часть `firstname.lastname@домен` (инициал.фамилия - тоже), display name пуст/неинформативен. -6. Иначе → `company` (роль/организация). Консервативно: НЕ исключаем — - потеря реального контакта хуже, чем лишняя роль. +4. **Person**: the display name looks like a person's name — ≥2 tokens after + stripping decorations (" (Org)", " via X"): Title-case / ALLCAPS / initials / + particles (van/von/de/of/…); without corporate markers (GmbH/AG/e.V./Ltd/Inc/…) + and role words (Team/Wartung/Neuigkeiten/Digest/…). +5. **Person**: local part `firstname.lastname@domain` (initial.lastname + too), display name empty/uninformative. +6. Otherwise → `company` (role/organization). Conservative: we do NOT exclude — + losing a real contact is worse than an extra role. -## Спец-исключения и границы (OPEN) +## Special exceptions and boundaries (OPEN) -- **Домен компании-контекста ≠ сервис**: `wheregroup.com` НЕ входит в - сервис-домены — коллеги (`astrid.emde@wheregroup.com`) и роль-ящики - (`info@wheregroup.com` → company) проходят. Подсистемы компании на том же - домене ловятся tool-именами/лейблами (`gitlab@wheregroup.com`, +- **Company-context domain ≠ service**: `wheregroup.com` is NOT one of the + service domains — colleagues (`astrid.emde@wheregroup.com`) and role mailboxes + (`info@wheregroup.com` → company) pass. Company subsystems on the same + domain are caught by tool names/labels (`gitlab@wheregroup.com`, `trac.wheregroup.com`). -- **Отличия от `IsMachineSender`**: локальные junk-подстроки mailconv - («info@», «reply», «news» как подстрока) в сети не применяются — иначе - `info@компания` (роль-ящик) и релеи людей (`hit-reply@linkedin.com`) - терялись бы. IsMachineSender для reconcile-инструментов не изменён. -- **Торговые/потребительские компании** (amazon.de, ebay, банки, телекомы, - airbnb, opodo и т.п.) классифицируются `company` (у них товарно-денежные - отношения с пользователем, но это не «сервис-аккаунт»); отсев таких - доменов из CRM-импорта — отдельное решение владельца (N-1.2/N-1.4). -- **Корпоративные домены гигантов** (google.com, microsoft.com, apple.com и - др.) — `service`: если реальный человек с такого домена станет деловым - контактом — добавляется точечное исключение. -- **Люди через релеи**: адрес — релей платформы (`messenger@webex.com`, - `hit-reply@linkedin.com`), не личный; контакту присваивается класс по - display name. -- **Двухсловные бренды**, выглядящие как имена («BMW Deutschland») → person - по форме; точечные ошибки документируются в таблице на issue. -- **Алиасы самого пользователя** (eslider@gmail.com в сети гдеgroup-таргета) - — проблема алиасов, вне скоупа (#267 YAGNI). +- **Differences from `IsMachineSender`**: mailconv's local junk substrings + ("info@", "reply", "news" as a substring) are not applied in the network — + otherwise `info@company` (role mailbox) and people's relays + (`hit-reply@linkedin.com`) would be lost. IsMachineSender for reconcile tools + is unchanged. +- **Commercial/consumer companies** (amazon.de, ebay, banks, telecoms, + airbnb, opodo etc.) are classified `company` (they have goods-for-money + relationships with the user, but this is not a "service account"); filtering + such domains out of the CRM import is a separate owner decision (N-1.2/N-1.4). +- **Corporate domains of the giants** (google.com, microsoft.com, apple.com and + others) — `service`: if a real person from such a domain becomes a business + contact — a pinpoint exception is added. +- **People via relays**: the address is a platform relay (`messenger@webex.com`, + `hit-reply@linkedin.com`), not a personal one; the contact is assigned the + class by display name. +- **Two-word brands** that look like names ("BMW Deutschland") → person + by shape; pinpoint errors are documented in the table on the issue. +- **The user's own aliases** (eslider@gmail.com in the wheregroup-target + network) — an alias problem, out of scope (#267 YAGNI). -## Применение +## Usage ```bash -bin/network/network.go --person andriy.oblivantsev@wheregroup.com --accept-only # CRM YAML, без сервисов +bin/network/network.go --person andriy.oblivantsev@wheregroup.com --accept-only # CRM YAML, no services bin/network/network.go --person andriy.oblivantsev@wheregroup.com --exclude-services -bin/network/network.go --person eslider@gmail.com --json # полный аудит + kind +bin/network/network.go --person eslider@gmail.com --json # full audit + kind ``` -## Ссылки +## Links -- Epic N-1 #267; тело/приёмка N-1.1 #268; сеть L-9.5 #234 (docs/brain/graph-network.md). +- Epic N-1 #267; body/acceptance N-1.1 #268; network L-9.5 #234 (docs/brain/graph-network.md). - `mailconv.IsMachineSender` (internal/mailconv/messages.go), `mailconv.SplitPersonName`. diff --git a/docs/brain/graph-gator-mail.md b/docs/brain/graph-gator-mail.md index 5c6cfde..b24b053 100644 --- a/docs/brain/graph-gator-mail.md +++ b/docs/brain/graph-gator-mail.md @@ -1,107 +1,107 @@ # Graph: gator kind=mail → 2dph Message/Person (D-1, ADR-0013) -Дизайн-документ коннектора и переноса conversation-канона (#99) в Ladybug. -D-1.1 (#258). Цель: 2dph строит граф Message/Person/рёбра из канона gator -kind=mail, а не из сырого корпуса var/mail (ADR-0013). +Design document for the connector and the transfer of the conversation canon (#99) into Ladybug. +D-1.1 (#258). Goal: 2dph builds the Message/Person/edges graph from the gator +kind=mail canon, not from the raw var/mail corpus (ADR-0013). -## 1. Вход: gator kind=mail (канон почты) +## 1. Input: gator kind=mail (mail canon) -- **Где**: `/mnt/8TB/projects/produktor/gator/var/gator/parquet/mail/source=mail/channel={wheregroup,gmail}/dt=*/data_*.parquet` - (hive-каталог на том же хосте arc-01; 2dph и gator — общий /mnt/8TB). -- **Каналы живые**: `wheregroup` (3984 unique, andriy.oblivantsev@wheregroup.com), +- **Where**: `/mnt/8TB/projects/produktor/gator/var/gator/parquet/mail/source=mail/channel={wheregroup,gmail}/dt=*/data_*.parquet` + (hive directory on the same host arc-01; 2dph and gator share /mnt/8TB). +- **Live channels**: `wheregroup` (3984 unique, andriy.oblivantsev@wheregroup.com), `gmail` (18007, eslider@gmail.com). -- **Чтение**: `query.Mail` (gator internal/query/mail.go) — SQL над parquet - через `MailFilter` (latest per message_id по умолчанию; `History=true` все - версии; `Limit` default ~100 → нужна пагинация). Либо прямой - `read_parquet(glob, union_by_name=true)` — быстрее на полный канал, минуя - gator-пагинацию. Коннектор 2dph читает **только канон gator** (parquet/mail), - НЕ сырьё `var/mail`. -- **Tombstone**: `deleted=true` (G-9.3) — latest по умолчанию исключает - удалённое. 2dph при повторном sync должен учитывать: письмо удалённое в - Roundcube → исключается из графа (или помечается), History видит удалённое. +- **Reading**: `query.Mail` (gator internal/query/mail.go) — SQL over parquet + via `MailFilter` (latest per message_id by default; `History=true` all + versions; `Limit` default ~100 → pagination needed). Or directly + `read_parquet(glob, union_by_name=true)` — faster for the full channel, bypassing + gator pagination. The 2dph connector reads **only the gator canon** (parquet/mail), + NOT the raw `var/mail`. +- **Tombstone**: `deleted=true` (G-9.3) — latest by default excludes + deleted items. On re-sync 2dph must account for this: a mail deleted in + Roundcube → excluded from the graph (or marked), History sees the deleted one. -## 2. Маппинг row gator → canon.Message +## 2. Mapping gator row → canon.Message -Row gator kind=mail (колонки query.Mail, согласованы в G-9.2 #89): +gator row kind=mail (query.Mail columns, agreed in G-9.2 #89): -| gator row | canon.Message (internal/canon #99) | заметка | +| gator row | canon.Message (internal/canon #99) | note | |---|---|---| -| message_id | Message.ID | уже канон Message-ID (CanonMessageID/Fallback) | -| folder | — (атрибут) | поле на узле, не в рёбрах | -| from {name,email} | Message.From (Person) | gator уже разобрал — MIME-парсинг НЕ нужен | -| to/cc/bcc []{name,email} | Message.To/CC/BCC ([]Person) | как выше | -| in_reply_to [] | Message.ReplyTo / ThreadID | см. §3 | +| message_id | Message.ID | already the Message-ID canon (CanonMessageID/Fallback) | +| folder | — (attribute) | a field on the node, not in the edges | +| from {name,email} | Message.From (Person) | gator already parsed it — MIME parsing NOT needed | +| to/cc/bcc []{name,email} | Message.To/CC/BCC ([]Person) | as above | +| in_reply_to [] | Message.ReplyTo / ThreadID | see §3 | | date (RFC3339) | Message.SentAt | | -| subject | — (атрибут) | на узле, если нужен | -| body | Message.Body | переработанное тело (без цитат) | +| subject | — (attribute) | on the node, if needed | +| body | Message.Body | processed body (without quotes) | | content_hash | gator_ref | deeplink `kind=mail#v-` | -Person.ID для mail = lowercased email (как canon Person), Name — display name -из gator. +Person.ID for mail = lowercased email (like canon Person), Name — display name +from gator. ## 3. Thread_id / REPLY_TO -- gator read-схема не имеет References — только `in_reply_to` (список Message-ID, - на которые отвечает). -- Стратегия треда: узел Message несёт `thread_id`. Корень = письмо без - in_reply_to (или с пустым). REPLY_TO-ребро: `(m)-[:REPLY_TO]->(parent)` по - in_reply_to. Тред-группировка для Person↔Project↔Time (L-9.5 #234) строится - транзитивно по REPLY_TO (клиент сети связей), не материализуется отдельным - узлом Thread на первом этапе (YAGNI до запроса). -- fallback: письма без in_reply_to и без References → root-сообщение +- The gator read schema has no References — only `in_reply_to` (list of Message-IDs + that the mail replies to). +- Thread strategy: the Message node carries `thread_id`. Root = a mail without + in_reply_to (or with an empty one). REPLY_TO edge: `(m)-[:REPLY_TO]->(parent)` by + in_reply_to. Thread grouping for Person↔Project↔Time (L-9.5 #234) is built + transitively over REPLY_TO (contact network client), not materialized as a separate + Thread node in the first stage (YAGNI until requested). +- fallback: mails without in_reply_to and without References → root message (thread_id = message_id). -## 4. Перенос #99 в Ladybug-схему +## 4. Moving #99 into the Ladybug schema -- **Модель/рёбра**: `canon.Person`/`canon.Message`/`Message.Edges()` (SENT/TO/ - CC/BCC/REPLY_TO/PART_OF) — переиспользуются **as-is** (уже в main, golden-тест). -- **Ladybug-схема** (InitSchema, internal/brain/write.go) — аддитивно добавить: +- **Model/edges**: `canon.Person`/`canon.Message`/`Message.Edges()` (SENT/TO/ + CC/BCC/REPLY_TO/PART_OF) — reused **as-is** (already in main, golden test). +- **Ladybug schema** (InitSchema, internal/brain/write.go) — add additively: - `Message` node table (id STRING PK = message_id; thread_id, folder, subject, sent_at, gator_ref, body, ...); - rel tables `SENT (FROM Person TO Message)`, `TO/CC/BCC (FROM Message TO Person)`, `REPLY_TO (FROM Message TO Message)`; - - `Person` node table — УЖЕ ЕСТЬ (id/name/email), не создавать повторно; - заполнить из gator. - - Paragraph/PART_OF (из canon.Edges) — на первом этапе НЕ включать (AD-решение: - граф сопряжения Person/Message первичен; парсинг тел на Paragraph — позже - при запросе семантики, YAGNI). -- **Запись**: Ladybug `MERGE` по id (идемпотентно, как WriteCorpus). Не - store.go JSON-манифест #99 — роль берёт Ladybug. -- **Инкремент**: повторный sync идемпотентен (MERGE); tombstone → пометка - узла/исключение. - -## 5. Коннектор (архитектура) + - `Person` node table — ALREADY EXISTS (id/name/email), do not create it again; + fill it from gator. + - Paragraph/PART_OF (from canon.Edges) — do NOT include at the first stage (AD decision: + the Person/Message adjacency graph is primary; parsing bodies into Paragraph — later + when semantics are requested, YAGNI). +- **Write**: Ladybug `MERGE` by id (idempotent, like WriteCorpus). Not the + store.go JSON manifest #99 — that role is taken over by Ladybug. +- **Increment**: re-sync is idempotent (MERGE); tombstone → node marking + or exclusion. + +## 5. Connector (architecture) ``` gator parquet/mail (channel X) --read_parquet/query.Mail--> []canon.Message - └── canon.Message.Edges() ──► Ladybug MERGE (Person/Message + рёбра) + └── canon.Message.Edges() ──► Ladybug MERGE (Person/Message + edges) ``` -- Новый `bin/mail/graph.go` (или расширение существующего import-пути): - читает канал → canon.Message → MERGE в kb.lbug. -- Путь чтения: прямой `read_parquet` (полный канал без gator-пагинации) — - предпочтителен для 3984/18007; query.Mail — для точечных/инкрементальных. -- Конфиг: каналы из gator (как registry), hive-путь. +- New `bin/mail/graph.go` (or an extension of the existing import path): + reads a channel → canon.Message → MERGE into kb.lbug. +- Read path: direct `read_parquet` (full channel without gator pagination) — + preferable for 3984/18007; query.Mail — for pinpoint/incremental reads. +- Config: channels from gator (like registry), hive path. -## 6. Что из #99 НЕ переносится на gator-путь +## 6. What from #99 is NOT transferred to the gator path -- `frommail.go` (emersion/go-message MIME-парсинг) — gator уже разобрал from/ - to/cc/bcc/body; зависимость не тянуть, дубль не писать. -- `store.go` (JSON-манифест на диск) — заменён Ladybug MERGE. -- `fromchat.go` — чаты отдельным каналом позже (вне D-1), модель едина. +- `frommail.go` (emersion/go-message MIME parsing) — gator has already parsed from/ + to/cc/bcc/body; do not pull in the dependency, do not write a duplicate. +- `store.go` (JSON manifest on disk) — replaced by Ladybug MERGE. +- `fromchat.go` — chats as a separate channel later (outside D-1), the model is unified. -## 7. Deliverables / следующий шаг (D-1.2) +## 7. Deliverables / next step (D-1.2) -- Схема Message/рёбра в InitSchema + write-путь (MERGE) — TDD. -- Импортёр гдеgroup (3984) → пилот → gmail (18007). -- Оценка размера/времени: 18k писем ~ простой MERGE (секунды-минуты). +- Message/edges schema in InitSchema + write path (MERGE) — TDD. +- wheregroup importer (3984) → pilot → gmail (18007). +- Size/time estimate: 18k mails ~ a plain MERGE (seconds to minutes). -## 8. Реализация D-1.2 (#259) — схема и write-путь +## 8. D-1.2 implementation (#259) — schema and write path -Код-схема (не импорт; импорт — D-1.3 #260). +Code-only (not the import; the import is D-1.3 #260). -**InitSchema** (internal/brain/write.go) — аддитивно, только `IF NOT EXISTS`, -ничего не DROP: +**InitSchema** (internal/brain/write.go) — additive, `IF NOT EXISTS` only, +nothing is DROPped: ```cypher CREATE NODE TABLE IF NOT EXISTS Message ( @@ -115,34 +115,34 @@ CREATE REL TABLE IF NOT EXISTS BCC (FROM Message TO Person) CREATE REL TABLE IF NOT EXISTS REPLY_TO (FROM Message TO Message) ``` -`Person`-таблица уже была (id/name/email, PK id) — не пересоздаётся. +The `Person` table already existed (id/name/email, PK id) — it is not recreated. `Message.id` = message_id, `gator_ref` = deeplink `kind=mail#v-`. -Paragraph/PART_OF на этом этапе НЕ материализуются (решение D-1.1, YAGNI). - -**Write-путь** (internal/brain/graphplan.go — чистая деривация, cgo-free; -graph.go — исполнение через execParams, cgo): - -- Вход `MessageInput{ canon.Message; Folder; Subject; GatorRef }` — canon #99 - используется as-is, рёбра берутся из `canon.Message.Edges()`. -- `planGraph`: уникальные Person-узлы (порядок From → To → CC → BCC, name - первого вхождения; повторный sync перезаписывает name последним — SET в - MERGE) и рёбра `Edges()` минус PART_OF и само-REPLY_TO. -- Запись идемпотентна: `MERGE (n:Label {id:$id}) SET ...` для узлов и - `MATCH (a..), (b..) MERGE (a)-[:REL]->(b)` для рёбер — повторный прогон - даёт 0 новых узлов/рёбер. -- REPLY_TO на ещё не импортированного родителя молча пропускается (MATCH не - находит конец) — ребро появляется при повторном прогоне после импорта - родителя; импортёр D-1.3 упорядочивает по дате (родители раньше ответов). -- Транзакции: `UpsertMessages` пишет пачку в одном BEGIN/COMMIT (образец +Paragraph/PART_OF are NOT materialized at this stage (D-1.1 decision, YAGNI). + +**Write path** (internal/brain/graphplan.go — pure derivation, cgo-free; +graph.go — execution via execParams, cgo): + +- Input `MessageInput{ canon.Message; Folder; Subject; GatorRef }` — canon #99 + is used as-is, edges are taken from `canon.Message.Edges()`. +- `planGraph`: unique Person nodes (order From → To → CC → BCC, name of the + first occurrence; a repeated sync overwrites the name with the last one — SET in + MERGE) and `Edges()` minus PART_OF and self-REPLY_TO. +- The write is idempotent: `MERGE (n:Label {id:$id}) SET ...` for nodes and + `MATCH (a..), (b..) MERGE (a)-[:REL]->(b)` for edges — a repeated run + yields 0 new nodes/edges. +- REPLY_TO to a parent that is not imported yet is silently skipped (MATCH does not + find the end) — the edge appears on a repeated run after the parent is + imported; the D-1.3 importer orders by date (parents before replies). +- Transactions: `UpsertMessages` writes a batch in one BEGIN/COMMIT (pattern `AddLeafs`). -**Read**: read path (search/get/stats/audit, P-9.4 #240) не тронут; узлы -Message/Person читаются обычным Cypher (`MATCH (m:Message)-[:TO]->(p:Person)`), -клиенты P-9 (#241) работают поверх Leaf-контракта как раньше. +**Read**: the read path (search/get/stats/audit, P-9.4 #240) is untouched; Message/ +Person nodes are read with plain Cypher (`MATCH (m:Message)-[:TO]->(p:Person)`), +P-9 clients (#241) work on top of the Leaf contract as before. -## Ссылки +## Links -- ADR-0013 (mail canon → gator; 2dph = Message/Person/Leaf граф) -- ADR-0012 (§сеть связей), domain-model.md (Message/Person #99) -- gator: G-9 (#87), query.Mail (#89), tombstone (#90), каналы гдеgroup/gmail -- 2dph: P-9.6 #242 (ADR памяти — ссылается, не дублирует), L-9.4 #233 +- ADR-0013 (mail canon → gator; 2dph = Message/Person/Leaf graph) +- ADR-0012 (§contact network), domain-model.md (Message/Person #99) +- gator: G-9 (#87), query.Mail (#89), tombstone (#90), wheregroup/gmail channels +- 2dph: P-9.6 #242 (memory ADR — referenced, not duplicated), L-9.4 #233 diff --git a/docs/brain/graph-git-commits.md b/docs/brain/graph-git-commits.md index f9f9c3c..641a26e 100644 --- a/docs/brain/graph-git-commits.md +++ b/docs/brain/graph-git-commits.md @@ -1,138 +1,138 @@ # Graph: git-commits → 2dph Commit/Person/AUTHORED (L-9.4 #233) -Дизайн и реализация граф-заполнителя Commit/Person/AUTHORED из git-истории -репозиториев git.produktor.io (eSlider/*, produktor/*). Цель эпика L-9 (#229) — -дедукция «кто над чем работал, когда, что сделал»: источник фактов для аудита -и ось «проект/время» сети связей (L-9.5 #234, ADR-0012). +Design and implementation of the graph filler Commit/Person/AUTHORED from the git +history of the git.produktor.io repositories (eSlider/*, produktor/*). The goal of epic +L-9 (#229) — deduction "who worked on what, when, what they did": a source of facts for the +audit and the "project/time" axis of the contact network (L-9.5 #234, ADR-0012). -## 1. Место в графе: два слоя +## 1. Place in the graph: two layers -| Слой | Что | Путь | Узел | +| Layer | What | Path | Node | |------|-----|------|------| -| premises | git-история как Leaf-текст (kind=commit, source=git) | `internal/corpus/git.go` → `gitlog.Log`/`ToLeaf` → `bin/brain/import-git.go` | `Leaf` | -| граф | дедуктивный слой: Commit/Person/AUTHORED | `internal/gitgraph` → `bin/git/graph.go` → `brain.UpsertCommits` | `Commit`, `Person`, `AUTHORED` | - -Leaf и Commit-узел — разные граф-слои (ADR-0012): git — premises для -дедукции; Commit-узел — результат. Дубль-корпус (`var/corpus/git/*.md` + -`2dph__corpus__git__*`) устранён (#10/P-9.3), тексты старых тел #233 про него -устарели. - -## 2. Источник git-фактов - -- **Репозитории**: локальные клоны git.produktor.io. Скан `--root DIR` — - одноуровневый по каталогам с `.git` (алгоритм `corpus.Git.resolveRepos`), - либо явный `--repo path[,path]`. Имя репозитория = `gitlog.RepoName` - (base имени origin-remote; без origin — имя каталога): стабильно при - переезде клона. -- **Чтение истории**: `gitlog.Log` (go-git, без git-бинара) — тот же канон, - что premises-корпус: **merge-коммиты пропускаются**, `Subject` = первая - строка message, автор = `Author` (не committer), дата = `Author.When` - RFC3339. Дублирующего чтения нет — коннектор реиспользует gitlog. -- **Канон git-коммита**: уникальность по паре `(repo, sha)` — полный sha - уникален в репозитории; одинаковый sha в разных репо (форк/копия) — - разные узлы. `Commit.id = :` (формат FileID `repo:path`). - Неизменяемая история остаётся в git-репах; gator коммиты не выносит (P-9). - -## 3. Маппинг в схему +| premises | git history as Leaf text (kind=commit, source=git) | `internal/corpus/git.go` → `gitlog.Log`/`ToLeaf` → `bin/brain/import-git.go` | `Leaf` | +| graph | deductive layer: Commit/Person/AUTHORED | `internal/gitgraph` → `bin/git/graph.go` → `brain.UpsertCommits` | `Commit`, `Person`, `AUTHORED` | + +Leaf and the Commit node are different graph layers (ADR-0012): git — premises for +deduction; the Commit node — the result. The duplicate corpus (`var/corpus/git/*.md` + +`2dph__corpus__git__*`) is eliminated (#10/P-9.3), the texts of the old #233 bodies about it +are outdated. + +## 2. Source of git facts + +- **Repositories**: local clones of git.produktor.io. The `--root DIR` scan — + single-level over directories with `.git` (algorithm `corpus.Git.resolveRepos`), + or an explicit `--repo path[,path]`. Repository name = `gitlog.RepoName` + (base of the origin remote name; without origin — the directory name): stable when + the clone moves. +- **Reading history**: `gitlog.Log` (go-git, no git binary) — the same canon + as the premises corpus: **merge commits are skipped**, `Subject` = the first + line of the message, author = `Author` (not committer), date = `Author.When` + RFC3339. There is no duplicate reading — the connector reuses gitlog. +- **Git commit canon**: uniqueness by the pair `(repo, sha)` — a full sha + is unique within a repository; the same sha in different repos (fork/copy) — + different nodes. `Commit.id = :` (FileID format `repo:path`). + Immutable history stays in the git repos; gator does not export commits (P-9). + +## 3. Mapping into the schema `gitlog.Commit` → `brain.CommitInput` (`internal/gitgraph.ToInputs`): -| gitlog.Commit | CommitInput / узел | заметка | +| gitlog.Commit | CommitInput / node | note | |---|---|---| -| sha | `Commit.id = repo:sha` | канон | -| repo (RepoName) | `Commit.repo` | как leaf.Repo git-корпуса | -| subject (first line) | `Commit.subject` | «что сделал» — гипотеза из message | +| sha | `Commit.id = repo:sha` | canon | +| repo (RepoName) | `Commit.repo` | like leaf.Repo of the git corpus | +| subject (first line) | `Commit.subject` | "what they did" — a hypothesis from the message | | author name | `Commit.author` | display name | -| author email | `Commit.email`, `Person.id` | **lowercase** — Person.id канон mail (D-1 #257): тот же email в mail и git = один Person | +| author email | `Commit.email`, `Person.id` | **lowercase** — mail Person.id canon (D-1 #257): the same email in mail and git = one Person | | author date | `Commit.date` | RFC3339 | -Person без display name в mail-графе получает name из git-автора (name-мердж -«последний sync побеждает», SET в MERGE). Коммит без email автора остаётся -Commit-узлом без AUTHORED (сопряжение по email невозможно). +A Person without a display name in the mail graph gets the name from the git author +(name merge "last sync wins", SET in MERGE). A commit without an author email stays a +Commit node without AUTHORED (joining by email is impossible). -Рёбра: `(:Commit)-[:AUTHORED]->(:Person)`. Рёбер Commit→File/Leaf нет -(YAGNI, тело #233): область проекта на этом этапе = `Commit.repo`; Project- -таблица не заводится (выводится из repo/файлов — решает дизайн #234). -Сортировка записи — по дате ASC (родители раньше; flat commits — рёбер между -коммитами нет), tie-break по id. +Edges: `(:Commit)-[:AUTHORED]->(:Person)`. There are no Commit→File/Leaf edges +(YAGNI, body #233): the project area at this stage = `Commit.repo`; no Project +table is introduced (it is derived from repo/files — decided by the #234 design). +Write ordering — by date ASC (parents first; flat commits — there are no edges between +commits), tie-break by id. -## 4. Write-путь +## 4. Write path -- `internal/brain/commitplan.go` (cgo-free): `CommitInput`, SQL-формы - `commitUpsertQuery` (MERGE Commit по id + SET свойств), +- `internal/brain/commitplan.go` (cgo-free): `CommitInput`, SQL forms + `commitUpsertQuery` (MERGE Commit by id + SET properties), `authoredEdgeQuery` (MATCH Commit+Person + MERGE AUTHORED), `commitAuthor` (Person.id = email lowercase, name = author). -- `internal/brain/gitcommit.go` (cgo): `UpsertCommit`/`UpsertCommits` — пачка - одной транзакцией (образец `UpsertMessages` D-1.2 #259). Идемпотентность — - MERGE по id (repo:sha / email): повторный прогон 0 дублей. `InitSchema` - (write.go:130-133) уже создаёт Commit/Person/AUTHORED — схема не меняется. -- CLI `bin/git/graph.go` (образец `bin/mail/graph.go` D-1.3 #260): dry-run по - умолчанию (`--commit` пишет), `--repo`/`--root`, `--since`, `--limit`, - `--db`, `--skip-existing` (инкремент по имеющимся Commit.id), live-holder - guard (`--force`), `--json`, батчи 500. Отчёт: dry-run — commits per repo / +- `internal/brain/gitcommit.go` (cgo): `UpsertCommit`/`UpsertCommits` — a batch in + one transaction (pattern `UpsertMessages` D-1.2 #259). Idempotency — + MERGE by id (repo:sha / email): a repeated run gives 0 duplicates. `InitSchema` + (write.go:130-133) already creates Commit/Person/AUTHORED — the schema does not change. +- CLI `bin/git/graph.go` (pattern `bin/mail/graph.go` D-1.3 #260): dry-run by + default (`--commit` writes), `--repo`/`--root`, `--since`, `--limit`, + `--db`, `--skip-existing` (incremental over existing Commit.id), live-holder + guard (`--force`), `--json`, batches of 500. Report: dry-run — commits per repo / unique emails / weak subjects; commit — Commit/Person/AUTHORED before→after. -## 5. Дедукция (инструмент git-facts) +## 5. Deduction (git-facts tool) -`bin/git/facts.go` (read-only, RO-open параллельно живому сервису): читает -`(:Commit)-[:AUTHORED]->(:Person)` тройки и выдаёт факт-карточки -«кто работал над `` в ``» (внутренняя логика +`bin/git/facts.go` (read-only, RO-open in parallel with the live service): reads +`(:Commit)-[:AUTHORED]->(:Person)` triples and emits fact cards +"who worked on `` in ``" (internal logic `internal/gitgraph.GroupFacts`/`BuildFacts`). -Факт-карточка (Vinogradov, audit card): +Fact card (Vinogradov, audit card): ``` repo=2dph person=Ada Lovelace - claim: «Ada Lovelace» работал(а) над 2dph в 2026-08-10..2026-08-12 (3 коммитов) - gap: OPEN: 1 из 3 коммитов со служебным message — их «что именно» не выводится + claim: «Ada Lovelace» worked on 2dph in 2026-08-10..2026-08-12 (3 commits) + gap: OPEN: 1 of 3 commits has a service message — their "what exactly" is not derived inference: deduction; verdict: accept ``` -Границы дедукции (иначе fallacy, docs/audit-recipes.md): -- «что сделал» — гипотеза из subject коммита, НЕ факт о намерении; -- слабый/пустой subject («Update», WIP) → только «трогал файлы», карточка - weaken + gap OPEN (весь subject-набор слабый → verdict weaken); -- авторство по Author; merge-коммиты не импортируются (gitlog.Log), - co-author в теле сообщения невидим — ограничение (OPEN); -- 1 коммит ≠ «вся неделя на X» — поспешная индукция не строится (период — - от фактических дат коммитов). - -## 6. Сопряжение с mail-графом - -Person mail-графа (D-1 #257, id=email lowercase, ~3 064 узла) и git-авторы -с тем же email сливаются в один Person-узел (MERGE по id): git-коммит автора -получает AUTHORED к уже существующему Person из mail. Незнакомый email — -новый Person (name из git-автора). Итог: один Person-узел на email, рёбра -SENT/TO/CC/BCC/REPLY_TO (mail) + AUTHORED (git) сосуществуют. - -## 7. Тесты - -- юнит cgo-free (`internal/brain/commitplan_test.go`): формы MERGE-запросов, - деривация автора (email lowercase), no-email; -- юнит cgo-free (`internal/gitgraph`): канон repo:sha, маппинг - gitlog.Commit → CommitInput, dedup/сортировка (идемпотентность повтора), - Resolve (root-скан/явные), ReadAll (go-git fixture), WeakSubject, Stats, - GroupFacts/BuildFacts (фильтры, вердикты accept/weaken+OPEN, premises); -- cgo на живой Ladybug (`internal/brain/gitcommit_test.go`, temp DB): запись - Commit/Person/AUTHORED и перечитывание, повторный прогон = 0 дублей, - сопряжение mail↔git Person (SENT + AUTHORED на одном узле), no-email, - сосуществование с Leaf/Message + EnsureIndexes. - -## 8. Сеть связей (L-9.5 #234) — сделано - -Сетевой слой поверх графа (mail D-1 #257 + git L-9.4 #233): инструмент -`bin/network/network.go` «кто с кем и через кого» — Person↔Person по общим -письмам/тредам (SENT/TO/CC/BCC/REPLY_TO) и общим проектам (AUTHORED -Commit.repo — ось «проект/время»), premises (Message.id/Commit.id), verdict -accept/weaken, экспорт accept в CRM (ADR-0012 п.4). Дизайн и границы: -[docs/brain/graph-network.md](graph-network.md). Осталось после #234 (не -скоуп): группировка файлов → проектная область (сейчас область = repo), -алиасы email, транзитивные цепочки depth>1. - -## Ссылки - -- Epic L-9 #229, тело L-9.4 #233 (дедуктивный паттерн, границы). -- D-1 #257 (mail-граф, Person.id=email), D-1.2 #259 (write-путь/InitSchema), - D-1.3 #260 (CLI-импортёр, образец). -- ADR-0012 (§сеть связей), ADR-0013 (база графа); docs/facts/audit-recipes.md - (шаблон audit card). +Boundaries of deduction (otherwise fallacy, docs/audit-recipes.md): +- "what they did" — a hypothesis from the commit subject, NOT a fact about intent; +- weak/empty subject ("Update", WIP) → only "touched files", the card carries + weaken + gap OPEN (the whole subject set is weak → verdict weaken); +- authorship by Author; merge commits are not imported (gitlog.Log), + co-author in the message body is invisible — a limitation (OPEN); +- 1 commit ≠ "the whole week on X" — no hasty induction is built (the period is + from the actual commit dates). + +## 6. Joining with the mail graph + +Person of the mail graph (D-1 #257, id=email lowercase, ~3 064 nodes) and git authors +with the same email merge into one Person node (MERGE by id): the author's git commit +gets AUTHORED to the already existing Person from mail. An unknown email — +a new Person (name from the git author). Result: one Person node per email, edges +SENT/TO/CC/BCC/REPLY_TO (mail) + AUTHORED (git) coexist. + +## 7. Tests + +- cgo-free unit (`internal/brain/commitplan_test.go`): forms of the MERGE queries, + author derivation (email lowercase), no-email; +- cgo-free unit (`internal/gitgraph`): repo:sha canon, mapping + gitlog.Commit → CommitInput, dedup/sorting (idempotency of a repeat), + Resolve (root scan/explicit), ReadAll (go-git fixture), WeakSubject, Stats, + GroupFacts/BuildFacts (filters, accept/weaken+OPEN verdicts, premises); +- cgo on the live Ladybug (`internal/brain/gitcommit_test.go`, temp DB): writing + Commit/Person/AUTHORED and re-reading, a repeated run = 0 duplicates, + mail↔git Person joining (SENT + AUTHORED on one node), no-email, + coexistence with Leaf/Message + EnsureIndexes. + +## 8. Contact network (L-9.5 #234) — done + +Network layer on top of the graph (mail D-1 #257 + git L-9.4 #233): tool +`bin/network/network.go` "who with whom and through whom" — Person↔Person by shared +mails/threads (SENT/TO/CC/BCC/REPLY_TO) and shared projects (AUTHORED +Commit.repo — the "project/time" axis), premises (Message.id/Commit.id), verdict +accept/weaken, export of accept to CRM (ADR-0012 item 4). Design and boundaries: +[docs/brain/graph-network.md](graph-network.md). Remaining after #234 (not in +scope): grouping files → project area (currently the area = repo), +email aliases, transitive chains depth>1. + +## Links + +- Epic L-9 #229, body L-9.4 #233 (deductive pattern, boundaries). +- D-1 #257 (mail graph, Person.id=email), D-1.2 #259 (write path/InitSchema), + D-1.3 #260 (CLI importer, pattern). +- ADR-0012 (§contact network), ADR-0013 (graph base); docs/facts/audit-recipes.md + (audit card template). diff --git a/docs/brain/graph-network.md b/docs/brain/graph-network.md index 82f6529..8a3b8e7 100644 --- a/docs/brain/graph-network.md +++ b/docs/brain/graph-network.md @@ -1,99 +1,99 @@ -# Graph network: «кто с кем и через кого» из mail+commits (L-9.5 #234) +# Graph network: "who with whom and through whom" from mail+commits (L-9.5 #234) -Дизайн сетевого слоя поверх готового графа kb.lbug (mail D-1 #257: Message/ +Design of the network layer on top of the ready kb.lbug graph (mail D-1 #257: Message/ Person + SENT/TO/CC/BCC/REPLY_TO; git L-9.4 #233: Commit/Person/AUTHORED). -Цель эпика L-9 (#229, ADR-0012 §сеть связей): восстановление социально- -профессиональной сети — «с кем и через кого я работал, над чем, когда» — для -CRM/маркетинга. Инструмент read-only: граф не пишет, схему не меняет. +The goal of epic L-9 (#229, ADR-0012 §contact network): reconstruction of the social- +professional network — "who I worked with and through whom, on what, when" — for +CRM/marketing. The tool is read-only: it does not write the graph, does not change the schema. -## 1. Деривации (только из существующих узлов/рёбер) +## 1. Derivations (only from existing nodes/edges) -Для целевого Person (email) выводятся связи с другими Person: +For the target Person (email), links with other Persons are derived: -| Канал | Деривация | Из узлов/рёбер | Вес | +| Channel | Derivation | From nodes/edges | Weight | |-------|-----------|----------------|-----| -| mail direct | письмо, где target — sender и Q — получатель, или наоборот | SENT, TO/CC/BCC | TO 1.0 / CC 0.5 / BCC 0.25 | -| mail shared | письмо, где target и Q оба — получатели (sender — третий) | TO/CC/BCC | +0.25 | -| mail reply | письмо Q отвечает на письмо target (и наоборот) | REPLY_TO | +0.5 | -| mail thread | число thread_id, где оба участвуют | Message.thread_id | контекст | -| git project | target и Q оба AUTHORED коммиты в один repo | Commit.repo, AUTHORED | отдельный факт | +| mail direct | a mail where target is the sender and Q is the recipient, or vice versa | SENT, TO/CC/BCC | TO 1.0 / CC 0.5 / BCC 0.25 | +| mail shared | a mail where target and Q are both recipients (the sender is a third party) | TO/CC/BCC | +0.25 | +| mail reply | a mail where Q replies to target's mail (and vice versa) | REPLY_TO | +0.5 | +| mail thread | the number of thread_ids where both participate | Message.thread_id | context | +| git project | target and Q both AUTHORED commits in the same repo | Commit.repo, AUTHORED | separate fact | -Person.id = email lowercase (канон mail D-1 #257; git-авторы сопряжены по -email в L-9.4 #233) — тот же email в mail и git = один Person-узел. +Person.id = email lowercase (mail canon D-1 #257; git authors are joined by +email in L-9.4 #233) — the same email in mail and git = one Person node. -## 2. Premises и verdict (audit card по Vinogradov, ADR-0012) +## 2. Premises and verdict (audit card by Vinogradov, ADR-0012) -Каждый факт связи несёт: +Each link fact carries: -- **premises** — ссылки на Message.id (mail) / Commit.id `repo:sha` (git); - без premises связь не выводится (sufficient reason, ADR-0012 п.1); +- **premises** — references to Message.id (mail) / Commit.id `repo:sha` (git); + without premises the link is not derived (sufficient reason, ADR-0012 item 1); - **verdict**: - - `accept` — ≥2 прямых писем, или ≥1 REPLY_TO-диалог, или общий проект - (обе стороны AUTHORED в repo); экспортируется в CRM; - - `weaken` — одиночный контакт (1 письмо без ответа и без проекта) или - только общий получатель; gap `OPEN`, в CRM-экспорт НЕ идёт (ADR-0012 - п.4 «только проверенные связи»; п.2 «1 письмо ≠ устойчивая связь»); -- **inference** = `deduction`; **период** = min..max дат свидетельств. - -## 3. Код - -- `internal/network/network.go` (cgo-free): `BuildLinks(Rows, Filter)` — вся - деривация, детерминированная (сортировка по весу, tie-break email). -- `internal/network/query.go` (cgo, read-only): `LoadRows(conn)` — читает - Message/Person/рёбра + Commit/AUTHORED в строки сети. + - `accept` — ≥2 direct mails, or ≥1 REPLY_TO dialogue, or a shared project + (both sides AUTHORED in repo); exported to CRM; + - `weaken` — a single contact (1 mail without a reply and without a project) or + only a shared recipient; gap `OPEN`, does NOT go into the CRM export (ADR-0012 + item 4 "verified links only"; item 2 "1 mail ≠ a stable link"); +- **inference** = `deduction`; **period** = min..max of the evidence dates. + +## 3. Code + +- `internal/network/network.go` (cgo-free): `BuildLinks(Rows, Filter)` — all the + derivation, deterministic (sorted by weight, tie-break email). +- `internal/network/query.go` (cgo, read-only): `LoadRows(conn)` — reads + Message/Person/edges + Commit/AUTHORED into network rows. - `bin/network/network.go` (cgo, read-only): CLI. ```bash bin/network/network.go --person eslider@gmail.com bin/network/network.go --person eslider@gmail.com --json bin/network/network.go --person alice@x --project demo --since 2026-01-01 -bin/network/network.go --person alice@x --accept-only # CRM-экспорт YAML +bin/network/network.go --person alice@x --accept-only # CRM export YAML ``` -Флаги: `--person EMAIL` (обязателен), `--project REPO` (git-ось: только -связи с общим проектом), `--since/--until`, `--limit`, `--json`, -`--accept-only` (YAML только accept, без дублей — одна запись на связь, -агрегат mail+git каналов), `--exclude-services` (без сервис-аккаунтов, -kind=service, N-1.1 #268), `--db PATH` (default `/var/kb.lbug`). -`--depth` зарезервирован (пилот #234 — только прямые связи, depth=1). - -## 3a. Классификация связей: люди/компании vs сервисы (N-1.1 #268) - -Каждая связь получает поле `kind`: `person` | `company` | `service` -(классификатор `mailconv.ClassifySender`, правила — в -[docs/brain/crm-network-filter.md](crm-network-filter.md)). Сервис-аккаунты/ -подсистемы/рассылки (GitLab, PayPal, LinkedIn, markets-platform, -chiliproject@trac и т.п.) в CRM-экспорт не попадают: `--accept-only` -исключает `kind=service` (раньше они попадали в экспорт по verdict accept). - -## 4. Экспорт в CRM - -`--accept-only` → YAML: target + список accept-связей (person, name, kind, -msgs, threads, replies, period, projects[], premises[] — первые 5 + -extraPremises счётчик; полный список в `--json`). Дублей нет: каждая связь -один раз со всеми каналами. Сервисные связи (kind=service) исключены -(N-1.1 #268). Источник помечен `source: 2dph graph mail+git (L-9.5 #234)`. -Формат — тип `network.Manifest` (`internal/network/manifest.go`), общий -контракт с коннектором. - -**Write в CRM (N-1.2 #269):** `bin/onlyoffice/import-network.go` читает этот -манифест и пишет каждую не-сервисную связь как контакт Person -(email/имя/тег `2dph:network:`/about со сводкой и premises), -идемпотентно по email. Маппинг и команды — [docs/brain/oo-network-import.md](oo-network-import.md). - -## 5. Границы (что НЕ выводится) - -- «что именно обсуждали» — по телу письма (Paragraph/PART_OF не - материализованы, D-1.1 YAGNI); -- транзитивные цепочки «знакомые знакомых» — depth>1 вне пилота #234; -- алиасы email (один человек, разные адреса) — граф сопрягает строго по - email (L-9.4 #233), alias-резолв — отдельная задача; -- mail ↔ repo привязка (письмо «о проекте X») — в графе нет такого ребра, - не выдумывается. - -## Ссылки - -- Epic L-9 #229; тело L-9.5 #234 (пилот/приёмка). -- D-1 #257 (mail-граф), L-9.4 #233 (Commit/Person/AUTHORED, git-facts). -- ADR-0012 §сеть связей (premises/verdict/экспорт accept), ADR-0013. -- docs/facts/audit-recipes.md (шаблон audit card). +Flags: `--person EMAIL` (required), `--project REPO` (git axis: only links +with a shared project), `--since/--until`, `--limit`, `--json`, +`--accept-only` (YAML accept only, without duplicates — one record per link, +aggregate of the mail+git channels), `--exclude-services` (without service +accounts, kind=service, N-1.1 #268), `--db PATH` (default `/var/kb.lbug`). +`--depth` is reserved (pilot #234 — only direct links, depth=1). + +## 3a. Link classification: people/companies vs services (N-1.1 #268) + +Each link gets a `kind` field: `person` | `company` | `service` +(classifier `mailconv.ClassifySender`, rules — in +[docs/brain/crm-network-filter.md](crm-network-filter.md)). Service accounts/ +subsystems/mailing lists (GitLab, PayPal, LinkedIn, markets-platform, +chiliproject@trac and the like) do not get into the CRM export: `--accept-only` +excludes `kind=service` (previously they got into the export by verdict accept). + +## 4. Export to CRM + +`--accept-only` → YAML: target + list of accept links (person, name, kind, +msgs, threads, replies, period, projects[], premises[] — the first 5 + +extraPremises counter; the full list in `--json`). No duplicates: each link +appears once with all channels. Service links (kind=service) are excluded +(N-1.1 #268). The source is marked `source: 2dph graph mail+git (L-9.5 #234)`. +The format — type `network.Manifest` (`internal/network/manifest.go`), a shared +contract with the connector. + +**Write to CRM (N-1.2 #269):** `bin/onlyoffice/import-network.go` reads this +manifest and writes each non-service link as a Person contact +(email/name/tag `2dph:network:`/about with a summary and premises), +idempotently by email. Mapping and commands — [docs/brain/oo-network-import.md](oo-network-import.md). + +## 5. Boundaries (what is NOT derived) + +- "what exactly was discussed" — from the mail body (Paragraph/PART_OF are + not materialized, D-1.1 YAGNI); +- transitive chains "friends of friends" — depth>1 outside pilot #234; +- email aliases (one person, different addresses) — the graph joins strictly by + email (L-9.4 #233), alias resolution is a separate task; +- mail ↔ repo binding (a mail "about project X") — the graph has no such edge, + it is not invented. + +## Links + +- Epic L-9 #229; body L-9.5 #234 (pilot/acceptance). +- D-1 #257 (mail graph), L-9.4 #233 (Commit/Person/AUTHORED, git-facts). +- ADR-0012 §contact network (premises/verdict/accept export), ADR-0013. +- docs/facts/audit-recipes.md (audit card template). diff --git a/docs/brain/memory-adr.md b/docs/brain/memory-adr.md index 8dcea15..a8ca83a 100644 --- a/docs/brain/memory-adr.md +++ b/docs/brain/memory-adr.md @@ -1,136 +1,136 @@ -# ADR P-9.6: память 2dph — единая модель фактов, аудита и хранения +# ADR P-9.6: 2dph memory — a single model of facts, audit and storage -> Статус: **Accepted** (2026-09-03). Документ не вводит новых механизмов: он -> сводит уже принятые и работающие решения (P-9.2/#235, P-9.3/#13, -> P-9.4/#240, L-9/#229–234) в одну модель для клиентов. Изменение модели — -> через новый issue; эпик P-9 (#239). +> Status: **Accepted** (2026-09-03). The document introduces no new mechanisms: it +> consolidates the already accepted and working decisions (P-9.2/#235, P-9.3/#13, +> P-9.4/#240, L-9/#229–234) into one model for clients. A change of the model — +> through a new issue; epic P-9 (#239). -## 1. Цель и место документа +## 1. Purpose and place of the document -2dph («память», префронтальная кора по ADR-0012) держит **факты и выводы**: -leafs (утверждения) + связи + аудит. Разрозненные документы описывали части -модели; этот ADR — единая точка входа для клиентов (агенты/MCP, gator, cv, -скрипты), чтобы все опирались на одну модель фактов/аудита/хранения. +2dph ("memory", the prefrontal cortex per ADR-0012) holds **facts and conclusions**: +leafs (statements) + links + audit. Scattered documents described parts of the +model; this ADR — a single entry point for clients (agents/MCP, gator, cv, +scripts), so that everyone relies on one model of facts/audit/storage. -Что он делает и чего не делает: +What it does and what it does not do: -- **сводит** уже существующее: write-контракт (`docs/brain/contract.md`, - P-9.2/P-9.3), read-контракт (`docs/brain/read-contract.md`, P-9.4), - эмпирику аудита (`docs/facts/audit-recipes.md`, #52/#56) и формальную - логику L-9 (issues #229–234), факт-слой (`bin/facts/extract.go`, +- **consolidates** what already exists: the write contract (`docs/brain/contract.md`, + P-9.2/P-9.3), the read contract (`docs/brain/read-contract.md`, P-9.4), + the audit empirics (`docs/facts/audit-recipes.md`, #52/#56) and the formal + logic of L-9 (issues #229–234), the facts layer (`bin/facts/extract.go`, `docs/facts/ingest.md`); -- **не дублирует код и не заменяет** контракты: здесь — модель и ссылки, - норматив — в перечисленных файлах (пересечение с L-9 файловое минимальное: - ADR отдельный файл, L-9 пишет в `docs/facts/audit-recipes.md` и +- **does not duplicate code and does not replace** the contracts: here — the model and references, + the normative part — in the listed files (the overlap with L-9 is minimal at the file level: + the ADR is a separate file, L-9 writes to `docs/facts/audit-recipes.md` and `var/audit/source-of-truth.yml`); -- **не описывает** инструменты сбора/CRM/gator — их зоны фиксирует ADR-0012 - (ответственность зон, «один канон на тип данных»). +- **does not describe** the collection/CRM/gator tools — their zones are fixed by ADR-0012 + (zone responsibility, "one canon per data type"). -Карта зон (ADR-0012), где живёт 2dph: +Zone map (ADR-0012), where 2dph lives: -| Зона | Система | Канон | +| Zone | System | Canon | |------|---------|-------| -| сенсоры/сырьё | gator (`var/` raw/parquet) | **данные** (raw, версии, append-only) | -| кора/память | **2dph** (Ladybug `var/kb.lbug`) | **факты/выводы** (leafs) + связи | -| скелет | OnlyOffice CRM | структура бизнеса (сделки/контакты/задачи) | -| суперэго | skills/inventar | правила, контракты, ADR | +| sensors/raw | gator (`var/` raw/parquet) | **data** (raw, versions, append-only) | +| cortex/memory | **2dph** (Ladybug `var/kb.lbug`) | **facts/conclusions** (leafs) + links | +| skeleton | OnlyOffice CRM | business structure (deals/contacts/tasks) | +| superego | skills/inventar | rules, contracts, ADR | -2dph ссылается на каноны данных и CRM, не копирует их; свой канон (факты/ -выводы) держит сам. Детали — ADR-0012 (внешний документ fabric, inventar +2dph references the data and CRM canons, does not copy them; it keeps its own canon (facts/ +conclusions) itself. Details — ADR-0012 (external fabric document, inventar `docs/adr/ADR-0012-responsibility-zones.md`). -## 2. Модель фактов: термины +## 2. Fact model: terms -Единые термины (совпадают с write- и read-контрактами): +Unified terms (matching the write and read contracts): -| Термин | Определение | +| Term | Definition | |--------|-------------| -| **наблюдение** (leaf корпуса) | единичное свидетельство одного источника: корпусный лист (`root=info`, kind `mail`/`commit`/`chat`/`reference`/`seed`/…). Пишется адаптером корпуса из одного файла/коммита/сообщения — по построению **single-source**, само по себе ничего не утверждает. Момент «когда контент увиден» фиксирует `observed_at` (RFC3339). | -| **info** | корень нарративных/описательных листов корпуса (mail/git/chats/docs). Поисковый слой, `never asserted`. Один лист = одно наблюдение. | -| **факт** | утверждение под `root=facts`, подтверждённое **≥2 независимыми источниками**; `confidence: confirmed`. Единственный корень, ответ с которого можно выдавать как подтверждённое знание. | -| **независимость источников** | источники из разных классов свидетелей: runtime × declared (например `docker ps` × compose-файл; `~/.ssh/config` × README/PLAN/AGENTS). В листе пара пишется в `source` через `" x "` (нотация факт-слоя, `facts/extract`). | -| **версия** | одна версия = один id. id записи = `ContentHash(source\|external_id\|kind\|text)[:32]` (dedup-ключ == id). Изменение контента/identity → новый hash → новая версия; старая остаётся в графе. Повторная запись той же версии — MERGE (upsert). | -| **валидность** | `valid_from` / `valid_to` (`YYYY-MM-DD`, D24) — интервал истинности **факта по дням**, ортогонален версии (версия про запись, валидность про смысл). Пустой интервал = «всегда» (legacy); пустой `valid_to` = открытый конец; концы включительно. Фильтр — `--as-of YYYY-MM-DD`. | -| **confirmed** | `confidence: confirmed`; пустое значение confidence (legacy leafs) трактуется как `confirmed`. | -| **(not confirmed)** | любой ответ, который **не сошёл с facts-корня**: info-хит, hypothesis/partial, единственный источник, противоречие 2v2 без сработавшего правила. Агент обязан помечать такой ответ `(not confirmed)`, а не выдавать за факт. | -| **stale** | `valid_to` в прошлом, либо факт отсутствует в сегодняшнем `--as-of`-виде (D24). Не путать с D16 `temporal_freshness` (свежесть источника против HEAD). | - -Один лист в БД — контрактные поля против runtime-схемы Ladybug: - -| Контракт (`internal/contract.Leaf`) | Колонка/смысл в БД | +| **observation** (corpus leaf) | a single piece of evidence from one source: a corpus sheet (`root=info`, kind `mail`/`commit`/`chat`/`reference`/`seed`/…). Written by a corpus adapter from one file/commit/message — by construction **single-source**, on its own it asserts nothing. The moment "when the content was seen" is recorded by `observed_at` (RFC3339). | +| **info** | the root of narrative/descriptive corpus sheets (mail/git/chats/docs). The search layer, `never asserted`. One sheet = one observation. | +| **fact** | a claim under `root=facts`, confirmed by **≥2 independent sources**; `confidence: confirmed`. The only root whose answer can be given as confirmed knowledge. | +| **source independence** | sources from different witness classes: runtime × declared (e.g. `docker ps` × compose file; `~/.ssh/config` × README/PLAN/AGENTS). In the sheet the pair is written to `source` via `" x "` (fact-layer notation, `facts/extract`). | +| **version** | one version = one id. Record id = `ContentHash(source\|external_id\|kind\|text)[:32]` (dedup key == id). A change of content/identity → new hash → new version; the old one stays in the graph. Rewriting the same version — MERGE (upsert). | +| **validity** | `valid_from` / `valid_to` (`YYYY-MM-DD`, D24) — the interval of truthfulness **of the fact by days**, orthogonal to the version (the version is about the record, validity about the meaning). An empty interval = "always" (legacy); an empty `valid_to` = an open end; the ends are inclusive. Filter — `--as-of YYYY-MM-DD`. | +| **confirmed** | `confidence: confirmed`; an empty confidence value (legacy leafs) is treated as `confirmed`. | +| **(not confirmed)** | any answer that **did not come from the facts root**: an info hit, hypothesis/partial, a single source, a 2v2 contradiction with no rule triggered. The agent must mark such an answer `(not confirmed)` and not present it as a fact. | +| **stale** | `valid_to` in the past, or the fact is absent in today's `--as-of` view (D24). Not to be confused with D16 `temporal_freshness` (source freshness against HEAD). | + +One sheet in the DB — contract fields against the Ladybug runtime schema: + +| Contract (`internal/contract.Leaf`) | Column/meaning in the DB | |-------------------------------------|--------------------| -| `source` | имя корпуса-источника: `mail`/`git`/`chats`/`docs`; у фактов — пара источников `"S1 x S2"` | -| `external_id` | устойчивый ref внутри корпуса (message id / commit sha / chat id / rel-путь; у mail — content-address `sha256(text)[:16]`) | -| `kind` | тип листа (в БД колонка `type`): `fact`/`mail`/`chat`/`commit`/`reference`/`seed`/… | -| `text` | содержимое (Heading + body, единообразно во всех корпусах) | -| `root` | `facts` (утверждение, ≥2 источника) или `info` (нарратив); default `info` | -| `confidence` | открытый домен: `confirmed`/`estimated`/`inferred`/`hypothesis`/`partial`/… | -| `valid_from`/`valid_to` | D24-день валидности (см. выше) | -| `observed_at` | когда контент увиден (RFC3339); **вне** dedup-ключа | - -Норматив записи — [`docs/brain/contract.md`](contract.md) (Leaf.Validate(), -`NormalizeText`, ContentHash, `observed_at` вне хэша, адаптеры корпуса). - -## 3. Модель аудита - -### 3.1 Как факт подтверждается - -1. **Наблюдения** приходят из корпусов (адаптеры `internal/corpus`) и пишутся - всегда как `root=info` (`internal/brain/corpus.go`, `WriteCorpus`) — один - лист происходит из одного файла/коммита, сам по себе фактом быть не может. -2. **Факт-слой** — отдельный evidence gate (`bin/facts/extract.go`), не корпус: - сопоставляет два независимых класса источников — +| `source` | name of the corpus source: `mail`/`git`/`chats`/`docs`; for facts — a pair of sources `"S1 x S2"` | +| `external_id` | stable ref inside the corpus (message id / commit sha / chat id / rel-path; for mail — content-address `sha256(text)[:16]`) | +| `kind` | sheet type (in the DB the column is `type`): `fact`/`mail`/`chat`/`commit`/`reference`/`seed`/… | +| `text` | content (Heading + body, uniform across all corpora) | +| `root` | `facts` (claim, ≥2 sources) or `info` (narrative); default `info` | +| `confidence` | open domain: `confirmed`/`estimated`/`inferred`/`hypothesis`/`partial`/… | +| `valid_from`/`valid_to` | D24 validity day (see above) | +| `observed_at` | when the content was seen (RFC3339); **outside** the dedup key | + +The write norm — [`docs/brain/contract.md`](contract.md) (Leaf.Validate(), +`NormalizeText`, ContentHash, `observed_at` outside the hash, corpus adapters). + +## 3. Audit model + +### 3.1 How a fact is confirmed + +1. **Observations** come from corpora (adapters `internal/corpus`) and are written + always as `root=info` (`internal/brain/corpus.go`, `WriteCorpus`) — one + sheet originates from one file/commit and on its own cannot be a fact. +2. The **facts layer** — a separate evidence gate (`bin/facts/extract.go`), not a corpus: + it matches two independent classes of sources — S1 runtime (`docker ps` / `~/.ssh/config`) × S2 declared - (compose-файл / README+PLAN+AGENTS) — и пишет совпадение как + (compose file / README+PLAN+AGENTS) — and writes the match as `root=facts`, `confidence: confirmed`, `source: "S1 x S2"`. -3. **Promote** (`bin/facts/promote.go`): уже подтверждённые `info`-листы, - чей `source` содержит ≥2 различных источника, перекореняются в `facts` - (идемпотентно). -4. При **rebuild** факт-слой включается только флагом `--with-facts` - (`bin/brain/index.go`); без него facts-корень пуст (#181) — см. +3. **Promote** (`bin/facts/promote.go`): already confirmed `info` sheets + whose `source` contains ≥2 distinct sources are re-rooted into `facts` + (idempotently). +4. On **rebuild** the facts layer is enabled only by the `--with-facts` flag + (`bin/brain/index.go`); without it the facts root is empty (#181) — see `docs/facts/ingest.md`. -Проверка двух-источниковости по живой БД — `bin/facts/audit.go db` (каждый -`root=facts` лист); корень правила «≥2 источника» — evidence-first (AGENTS.md), -эмпирика — `docs/facts/audit-recipes.md` (#52/#56). +Two-source verification against the live DB — `bin/facts/audit.go db` (every +`root=facts` sheet); the root of the "≥2 sources" rule — evidence-first (AGENTS.md), +the empirics — `docs/facts/audit-recipes.md` (#52/#56). -### 3.2 Когда ответ (not confirmed) +### 3.2 When an answer is (not confirmed) -- ответ сошёл с `info`-корня (нарратив, даже если `confidence: confirmed`); -- у утверждения один источник (hypothesis/partial); -- **противоречие 2v2**: `a x b` против `c x d`, обе стороны с ≥2 источниками, - но ни одно правило не сработало (`temporal_freshness` / `authority_pairing`, - D16) — остаётся hypothesis, пока не расследовано (`bin/facts/audit.go +- the answer came from the `info` root (narrative, even if `confidence: confirmed`); +- the claim has one source (hypothesis/partial); +- **2v2 contradiction**: `a x b` against `c x d`, both sides with ≥2 sources, + but no rule triggered (`temporal_freshness` / `authority_pairing`, + D16) — it stays a hypothesis until investigated (`bin/facts/audit.go contradict`); -- stale (valid_to в прошлом или нет в сегодняшнем `--as-of`). +- stale (valid_to in the past or absent in today's `--as-of`). -Дедукционный порядок поиска: **facts → info → web** (`web` — SearXNG, второй -независимый источник, держится отдельным блоком; `throttled`/`refused` — не -доказательство отсутствия). +The deductive search order: **facts → info → web** (`web` — SearXNG, the second +independent source, kept in a separate block; `throttled`/`refused` — not +proof of absence). -### 3.3 Формальная логика L-9 (Vinogradov) +### 3.3 Formal logic L-9 (Vinogradov) -Эмпирика рецептов (#52/#56) дополнена формальными законами на уровне -суждений/URL (L-9, issues #229–234; ядро `internal/facts`, cgo-free): +The empirics of the recipes (#52/#56) is complemented by formal laws at the level of +judgments/URLs (L-9, issues #229–234; the core `internal/facts`, cgo-free): -| Закон | Правило | Вердикт | +| Law | Rule | Verdict | |-------|---------|---------| -| identity (тождество) | один канонический URL в разных написаниях → merge/flag | `weaken` | -| contradiction (противоречие) | подтверждённые `P` и `¬P` об одном предикате одного URL с пересекающимися D24-интервалами | `reject` | -| excluded middle | hypothesis/partial или claim без предиката — не FACT, кандидат в `open_questions[]` | `weaken` | -| sufficient reason | verdict `accept` только с FACT-/OPEN- premises | `reject`/`weaken` | +| identity (sameness) | one canonical URL in different spellings → merge/flag | `weaken` | +| contradiction | confirmed `P` and `¬P` about one predicate of one URL with overlapping D24 intervals | `reject` | +| excluded middle | hypothesis/partial or a claim without a predicate — not FACT, a candidate for `open_questions[]` | `weaken` | +| sufficient reason | verdict `accept` only with FACT-/OPEN- premises | `reject`/`weaken` | -Суждение = факт о ресурсе URL: `{id, url, claim, attr, neg, conf, from, to}` -(`attr` — предикат, `neg` — знак P/¬P). Машинные проверки — -`bin/facts/audit.go formal` (stdin JSON). Канонизация URL — -`facts.CanonicalURL` (конвенция gator G-8.1). Полные рецепты — -`docs/facts/audit-recipes.md` (§Формальные проверки URL, L-9.3). +A judgment = a fact about a URL resource: `{id, url, claim, attr, neg, conf, from, to}` +(`attr` — the predicate, `neg` — the P/¬P sign). Machine checks — +`bin/facts/audit.go formal` (stdin JSON). URL canonicalization — +`facts.CanonicalURL` (gator convention G-8.1). Full recipes — +`docs/facts/audit-recipes.md` (§Formal URL checks, L-9.3). -### 3.4 Аудит-карточки и source-of-truth +### 3.4 Audit cards and source-of-truth -Каждый вердикт фиксируется **карточкой Vinogradov** в логическом SoT +Every verdict is recorded by a **Vinogradov card** in the logical SoT (`var/audit/source-of-truth.yml`, `audits[]`, L-9.1 #230 / L-9.2 #231): -рекомендация без карточки = нарушение. Карточка обязана опираться на +a recommendation without a card = a violation. The card must rely on FACT-/OPEN- premises: ```bash @@ -138,153 +138,153 @@ bin/facts/audit-card.go --claim "…" --premises FACT-9002,FACT-9001 \ --inference deduction --gaps OPEN-0001 --counter none --verdict weaken ``` -- CLI валидирует карточку (verdict `accept|reject|weaken`, inference - `deduction|induction|analogy|other`, обязательные claim/premises/counter), - присваивает `AUD-NNNN`, дописывает в `audits[]` (yaml-дерево, остальные - секции не трогает). -- SoT хранит только индексированные факты `{id, claim, source}` — срезы из - `root=facts` Ladybug; сырьё остаётся в `var/`; секретов нет (ASR-0006); - файл gitignored, живёт локально как артефакт контура. -- В `root=facts` **нет** фактов-вакансий (truth-gate #52) — см. OPEN-0001 в - SoT: не выдуманы. +- The CLI validates the card (verdict `accept|reject|weaken`, inference + `deduction|induction|analogy|other`, mandatory claim/premises/counter), + assigns `AUD-NNNN`, appends to `audits[]` (yaml tree, does not touch the other + sections). +- The SoT stores only indexed facts `{id, claim, source}` — slices from + `root=facts` Ladybug; the raw material stays in `var/`; no secrets (ASR-0006); + the file is gitignored, lives locally as a circuit artifact. +- In `root=facts` there are **no** vacancy facts (truth-gate #52) — see OPEN-0001 in + the SoT: not invented. -### 3.5 Read-аудит (форматы ответа) +### 3.5 Read audit (response formats) -- `/audit` (HTTP/MCP) и `bin/facts/audit.go db` — гистограмма `root × - confidence` (формат — read-контракт, поле `by_confidence`); -- `bin/brain/audit-contract.go` — read-only аудит **соответствия write- - контракту** (пропуски обязательных полей, распределение по корпусам); -- `bin/brain/read-contract.go` / `read-contract-db.go` — гейты форматов - read-контракта (живой сервис и живая БД, read-only). +- `/audit` (HTTP/MCP) and `bin/facts/audit.go db` — a `root × + confidence` histogram (format — the read contract, field `by_confidence`); +- `bin/brain/audit-contract.go` — a read-only audit of **conformance to the write + contract** (missing required fields, distribution by corpus); +- `bin/brain/read-contract.go` / `read-contract-db.go` — format gates of the + read contract (live service and live DB, read-only). -## 4. Модель хранения +## 4. Storage model -### 4.1 Ladybug, один файл, два корня +### 4.1 Ladybug, one file, two roots -Вся память — один встроенный граф Ladybug: `var/kb.lbug`. `facts` и `info` — -колонка `root` на каждом листе, **семантическое, не физическое** разделение: -оба корня живут в одном файле и пишутся в одной транзакции (D12, ACID — аудит -видит согласованный снимок). +All memory — one embedded Ladybug graph: `var/kb.lbug`. `facts` and `info` — +the `root` column on each sheet, a **semantic, not physical** separation: +both roots live in one file and are written in one transaction (D12, ACID — the audit +sees a consistent snapshot). -Схема (`internal/brain` `InitSchema`, идемпотентна): узлы -`Leaf`/`File`/`Host`/`Commit`/`Person`/`Message` + рёбра +The schema (`internal/brain` `InitSchema`, idempotent): nodes +`Leaf`/`File`/`Host`/`Commit`/`Person`/`Message` + edges `FROM_FILE`, `RUNS_ON`, `AUTHORED`, `SENT`, `TO`, `CC`, `BCC`, `REPLY_TO`, -`SYNAPTIC` (пользовательские связи leaf↔leaf, #82). Лист несёт embedding -`FLOAT[256]`; ANN-индекс — `var/state/vector.ann` (dim=256, nlist=2000, -nprobe=2000, #206). Схема Ladybug — внутренняя, меняется без предупреждения; -**клиенты никогда не парсят `var/kb.lbug` напрямую**, только read-контракт. +`SYNAPTIC` (user leaf↔leaf links, #82). A sheet carries an embedding +`FLOAT[256]`; the ANN index — `var/state/vector.ann` (dim=256, nlist=2000, +nprobe=2000, #206). The Ladybug schema is internal, changes without notice; +**clients never parse `var/kb.lbug` directly**, only the read contract. -### 4.2 Запись: контракт + адаптеры корпуса + факт-слой +### 4.2 Write: contract + corpus adapters + facts layer -| Путь записи | Инструмент | Что пишет | +| Write path | Tool | What it writes | |-------------|------------|-----------| -| корпуса (docs/mail/chats/git) | адаптеры `internal/corpus` (`contract.Source`: `Name()` + `Stream(ctx, emit(Leaf))`) → драйвер `bin/brain/index.go` → `brain.WriteCorpus` | `root=info`, по одному наблюдению на файл/commit/сообщение | -| факты | `bin/facts/extract.go` → `UpsertLeaf` (напрямую, без `FROM_FILE`) | `root=facts`, `kind=fact`, пара источников в `source` | -| ручное добавление | `bin/brain/add.go` (`--root facts --source "a.md x b.md"`) | лист по контракту | -| rebuild | `bin/brain/index.go --rebuild --with-mail --with-facts [--with-chats] [--git-root DIR]` | полный рехэш id = ContentHash, детерминированно | +| corpora (docs/mail/chats/git) | adapters `internal/corpus` (`contract.Source`: `Name()` + `Stream(ctx, emit(Leaf))`) → driver `bin/brain/index.go` → `brain.WriteCorpus` | `root=info`, one observation per file/commit/message | +| facts | `bin/facts/extract.go` → `UpsertLeaf` (directly, without `FROM_FILE`) | `root=facts`, `kind=fact`, a pair of sources in `source` | +| manual addition | `bin/brain/add.go` (`--root facts --source "a.md x b.md"`) | a sheet per the contract | +| rebuild | `bin/brain/index.go --rebuild --with-mail --with-facts [--with-chats] [--git-root DIR]` | full id rehash = ContentHash, deterministically | -Факты пишутся **без `external_id`** (21 лист на живой БД) — прямой путь -`UpsertLeaf` зафиксирован контрактом как допустимый (P-9.3, расхождение -описано в `docs/brain/contract.md`). `observed_at` штампуется при записи, -если пуст. +Facts are written **without `external_id`** (21 sheets on the live DB) — the direct +`UpsertLeaf` path is recorded by the contract as allowed (P-9.3, the discrepancy is +described in `docs/brain/contract.md`). `observed_at` is stamped on write +if empty. -### 4.3 Чтение: read-контракт (один формат на всех поверхностях) +### 4.3 Read: the read contract (one format on all surfaces) -Read-контракт (`internal/contract/read.go`, версия **`1.0`**, MAJOR.MINOR): -каждый ответ несёт `contract_version`; additive-правки — MINOR, breaking — -MAJOR. Клиенты обязаны принимать любой ответ с тем же MAJOR, игнорировать -неизвестные поля, отсутствие `contract_version` (сервис до контракта) -пропускать через `--relax-version`. +Read contract (`internal/contract/read.go`, version **`1.0`**, MAJOR.MINOR): +every response carries `contract_version`; additive edits — MINOR, breaking — +MAJOR. Clients must accept any response with the same MAJOR, ignore +unknown fields, and pass the absence of `contract_version` (a service predating the contract) +with `--relax-version`. -| Поверхность | Команда / путь | Формат | +| Surface | Command / path | Format | |-------------|----------------|--------| -| CLI | `bin/brain/search.go "q" --json`, `get.go --body --json`, `stats.go --json` | read-контракт | -| HTTP (:8630) | `GET /search?q=`, `GET /get?id=`, `GET /stats`, `GET /audit`, `GET /openapi.json` | read-контракт (+ raw-граф: `/leafs`, `/edges`, `/path`) | -| MCP | `POST /mcp`: tools `search` / `get` / `audit` (минимальная поверхность, D20; `stats`/`ingest` — HTTP-only) | read-контракт | -| гейты | `bin/brain/read-contract.go`, `read-contract-db.go` (read-only) | валидация схемы | +| CLI | `bin/brain/search.go "q" --json`, `get.go --body --json`, `stats.go --json` | read contract | +| HTTP (:8630) | `GET /search?q=`, `GET /get?id=`, `GET /stats`, `GET /audit`, `GET /openapi.json` | read contract (+ raw graph: `/leafs`, `/edges`, `/path`) | +| MCP | `POST /mcp`: tools `search` / `get` / `audit` (minimal surface, D20; `stats`/`ingest` — HTTP-only) | read contract | +| gates | `bin/brain/read-contract.go`, `read-contract-db.go` (read-only) | schema validation | -Норматив форматов (search/get/stats/audit, отсутствие → отсутствие, -`results` всегда массив) — [`docs/brain/read-contract.md`](read-contract.md). +The normative formats (search/get/stats/audit, absence → absence, +`results` always an array) — [`docs/brain/read-contract.md`](read-contract.md). -### 4.4 Актуальное состояние БД (после полного rebuild, 2026-09-03) +### 4.4 Current DB state (after a full rebuild, 2026-09-03) -Замеры на живой БД (`/stats`, `/audit` сервиса :8630 и read-only +Measurements on the live DB (`/stats`, `/audit` of the :8630 service and the read-only `bin/brain/audit-contract.go`): -| Метрика | Значение | +| Metric | Value | |---------|----------| | total leafs | **105,220** | | info | **105,199** = mail 105,027 + docs 172 | -| facts | **21** = 19 docker/compose + 2 ssh-host (все `confidence: confirmed`, двух-источниковые) | +| facts | **21** = 19 docker/compose + 2 ssh-host (all `confidence: confirmed`, two-source) | | root × confidence | facts 21 confirmed; info 105,199 confirmed | | ANN | 105,220 (loaded, `var/state/vector.ann`, dim=256) | -| соответствие контракту | observed_at/how/loc/kind: 0 пропусков; `external_id` отсутствует ровно у 21 facts-листа (легальный путь записи фактов) | - -Контекст цифр: полный rebuild 2026-09-02 (P-9.3 content-address dedup) сжал -307,431 стримнутых mail-листов → 105,027 уникальных (live `var/corpus/mail` + -legacy `var/mail` схлопнулись по ContentHash, #248). Ранее -задокументированные ориентиры **сняты**: «info ≥ ~200k» и «~313k leafs» -(см. §7). Между гейтом read-контракта 2026-09-02 (105,210) и замером -2026-09-03 БД выросла на 10 docs-листов; нормативны актуальные цифры выше. - -## 5. Границы: что brain НЕ делает - -- **Inspector/auditor, не executor** (#52): 2dph не пишет состояние - job-пайплайна/cv/CRM, не отправляет сообщения, не меняет источники. Он - фильтрует, ищет, аудирует; единственная его запись — собственный канон - (leafs/факты/выводы) в `var/kb.lbug` (+ граф-слои Commit/Person/Message). -- **Канон один на тип данных** (ADR-0012): данные → gator, структура бизнеса - → OnlyOffice CRM, правила → inventar/skills. 2dph **ссылается**, не - копирует; импорт в граф (mail/git) — premises/связи, не дубль канона. -- **Дедукция не выходит за посылки** (границы рецептов L-9.4/L-9.5): - «что сделал» по message/files — гипотеза, не факт о намерении; 1 коммит ≠ - «вся неделя на X»; алиасы email не склеиваются (сопряжение строго по - email); транзитивные цепочки «знакомые знакомых» — вне пилота (depth=1); - mail↔repo привязка не выдумывается. -- **facts без выдумок**: в `root=facts` только двух-источниковые утверждения; - фактов-вакансий нет (SoT OPEN-0001), пока их не подтвердят ≥2 источника. -- **Ответственность за подтверждение**: агент не выдаёт info/одиночный - источник за факт — обязателен маркер `(not confirmed)`; `web`-блок не - смешивается с графовыми hits. - -## 6. Карта потребителей - -| Потребитель | Поверхность | Контракт / инструмент | +| contract conformance | observed_at/how/loc/kind: 0 gaps; `external_id` is absent from exactly 21 facts sheets (the legal facts write path) | + +Context for the numbers: the full rebuild on 2026-09-02 (P-9.3 content-address dedup) collapsed +307,431 streamed mail sheets → 105,027 unique (live `var/corpus/mail` + +legacy `var/mail` collapsed by ContentHash, #248). The previously +documented reference points are **withdrawn**: "info ≥ ~200k" and "~313k leafs" +(see §7). Between the read-contract gate on 2026-09-02 (105,210) and the measurement +on 2026-09-03 the DB grew by 10 docs sheets; the current numbers above are normative. + +## 5. Boundaries: what the brain does NOT do + +- **Inspector/auditor, not executor** (#52): 2dph does not write the state of the + job pipeline/cv/CRM, does not send messages, does not change sources. It + filters, searches, audits; its only write is its own canon + (leafs/facts/conclusions) in `var/kb.lbug` (+ graph layers Commit/Person/Message). +- **One canon per data type** (ADR-0012): data → gator, business structure + → OnlyOffice CRM, rules → inventar/skills. 2dph **references**, does not + copy; import into the graph (mail/git) — premises/links, not a canon duplicate. +- **Deduction does not go beyond the premises** (boundaries of the L-9.4/L-9.5 recipes): + "what they did" by message/files — a hypothesis, not a fact about intent; 1 commit ≠ + "the whole week on X"; email aliases are not merged (joining strictly by + email); transitive chains "friends of friends" — outside the pilot (depth=1); + the mail↔repo binding is not invented. +- **facts without inventions**: in `root=facts` only two-source claims; + there are no vacancy facts (SoT OPEN-0001) until ≥2 sources confirm them. +- **Responsibility for confirmation**: the agent does not present info/a single + source as a fact — the `(not confirmed)` marker is mandatory; the `web` block is not + mixed with graph hits. + +## 6. Consumer map + +| Consumer | Surface | Contract / tool | |-------------|-------------|----------------------| -| агенты (PicoClaw gateway, `cv/ai-bot`) | MCP `search → get → audit` (`POST /mcp`, :8630) | read-контракт (P-9.4); скилл `picoclaw`, `brain` | -| gator и будущие сервисные клиенты | HTTP/CLI `--json` | read-контракт; P-9.5 (#241) клиенты поверх него; запись gator — свой контракт `contract.Record` (G-8.0, #73) | -| cv / job-пайплайн | `search → get → audit`, `/stats` | read-контракт + аудит-рецепты (#52) | -| скрипты стека | CLI `bin/brain/*.go --json` | read-контракт (версия `1.0`); гейты — `read-contract*.go` | -| оператор/аудитор | `bin/brain/*`, `bin/facts/*`, `audit-card.go` | write-контракт (запись), read-контракт, SoT, L-9 | - -Все клиенты обязаны: принимать MAJOR-совместимые ответы, игнорировать -неизвестные поля, помечать не-facts ответы `(not confirmed)` и не парсить -`var/kb.lbug` напрямую. - -## 7. Что изменено против ранее задокументированного - -- **Снято правило «info ≥ ~200k»** (было в `skills/brain/SKILL.md`): после - полного rebuild 2026-09-02 актуальный ориентир — **total 105,220** = - info 105,199 + facts 21 (см. §4.4). Меньше → корпус недозаписан. -- **Снят ориентир «~313k leafs»**: P-9.3 content-address dedup схлопнул - дубликаты mail (307k → 105k). Исторические 313k остаются только как - контекст в runbook (замеры ANN-параметров #192/#206). -- Старые снапшоты в `docs/brain/contract.md` («на момент P-9.3», 313,817 - leafs, «ещё не пересобрана») описывают состояние **до** rebuild; актуальные - цифры — §4.4 этого ADR. +| agents (PicoClaw gateway, `cv/ai-bot`) | MCP `search → get → audit` (`POST /mcp`, :8630) | read contract (P-9.4); skills `picoclaw`, `brain` | +| gator and future service clients | HTTP/CLI `--json` | read contract; P-9.5 (#241) clients on top of it; gator's write — its own contract `contract.Record` (G-8.0, #73) | +| cv / job pipeline | `search → get → audit`, `/stats` | read contract + audit recipes (#52) | +| stack scripts | CLI `bin/brain/*.go --json` | read contract (version `1.0`); gates — `read-contract*.go` | +| operator/auditor | `bin/brain/*`, `bin/facts/*`, `audit-card.go` | write contract (writing), read contract, SoT, L-9 | + +All clients must: accept MAJOR-compatible responses, ignore +unknown fields, mark non-facts answers `(not confirmed)` and not parse +`var/kb.lbug` directly. + +## 7. What changed against what was documented earlier + +- **The "info ≥ ~200k" rule is withdrawn** (it was in `skills/brain/SKILL.md`): after + the full rebuild on 2026-09-02 the current reference point is — **total 105,220** = + info 105,199 + facts 21 (see §4.4). Less → the corpus is under-written. +- **The "~313k leafs" reference point is withdrawn**: the P-9.3 content-address dedup collapsed + mail duplicates (307k → 105k). The historical 313k remain only as + context in the runbook (ANN parameter measurements #192/#206). +- Old snapshots in `docs/brain/contract.md` ("as of P-9.3", 313,817 + leafs, "not rebuilt yet") describe the state **before** the rebuild; the current + numbers are §4.4 of this ADR. ## 8. Cross-ref -- Write-контракт: [`docs/brain/contract.md`](contract.md) (P-9.2/#235, - P-9.3/#13) + `internal/contract` (Leaf, ContentHash, адаптеры). -- Read-контракт: [`docs/brain/read-contract.md`](read-contract.md) +- Write contract: [`docs/brain/contract.md`](contract.md) (P-9.2/#235, + P-9.3/#13) + `internal/contract` (Leaf, ContentHash, adapters). +- Read contract: [`docs/brain/read-contract.md`](read-contract.md) (P-9.4/#240) + `internal/contract/read.go` (`contract_version 1.0`). -- Аудит: [`docs/facts/audit-recipes.md`](../facts/audit-recipes.md) (#52/#56), +- Audit: [`docs/facts/audit-recipes.md`](../facts/audit-recipes.md) (#52/#56), L-9 (#229–234), SoT `var/audit/source-of-truth.yml` (L-9.1 #230), - `bin/facts/audit-card.go` (#231), формальные проверки (#232). -- Факт-слой: `bin/facts/extract.go`, `docs/facts/ingest.md`, rebuild — + `bin/facts/audit-card.go` (#231), formal checks (#232). +- Facts layer: `bin/facts/extract.go`, `docs/facts/ingest.md`, rebuild — `docs/brain/rebuild.md`. -- Дизайн/дедукция: `docs/design.md` (D12/D16/D20/D24), скилл `brain` - (`skills/brain/SKILL.md`), `docs/picoclaw.md` (агентский профиль). -- Зоны/каноны: ADR-0012 (ответственность зон), gator G-8.0 (#73) — - контракт записи данных; P-9.5 (#241) — сервисные клиенты. +- Design/deduction: `docs/design.md` (D12/D16/D20/D24), skill `brain` + (`skills/brain/SKILL.md`), `docs/picoclaw.md` (agent profile). +- Zones/canons: ADR-0012 (zone responsibility), gator G-8.0 (#73) — + data write contract; P-9.5 (#241) — service clients. diff --git a/docs/brain/oo-network-import.md b/docs/brain/oo-network-import.md index 366c8bd..047ab75 100644 --- a/docs/brain/oo-network-import.md +++ b/docs/brain/oo-network-import.md @@ -1,136 +1,135 @@ -# OO CRM: коннектор accept-связей сети (N-1.2 #269) +# OO CRM: connector for network accept links (N-1.2 #269) -Перенос accept-связей сети связей (L-9.5 #234, выход -`bin/network --accept-only`) в OnlyOffice CRM как **деловых контактов** — -чтобы маркетинг/продажи работали из графа: каждый контакт с premises- -ссылкой (проверяемой в графе через `bin/network`) и без дублей -(ADR-0012 §сеть связей п.4). Пилот — top-60 accept +Transfer of the contact-network accept links (L-9.5 #234, output +`bin/network --accept-only`) into OnlyOffice CRM as **business contacts** — +so that marketing/sales work from the graph: each contact with a premises +reference (verifiable in the graph via `bin/network`) and without duplicates +(ADR-0012 §contact network item 4). Pilot — top-60 accept of andriy.oblivantsev@wheregroup.com (N-1.3 #270). -## Инструмент +## Tool ```bash -bin/network/network.go --person X --accept-only > /tmp/net.yml # манифест (read-only) +bin/network/network.go --person X --accept-only > /tmp/net.yml # manifest (read-only) ONLYOFFICE_URL/USER/PASS ./bin/onlyoffice/import-network.go --manifest /tmp/net.yml # report only -./bin/onlyoffice/import-network.go --manifest /tmp/net.yml --dry-run # preview: lookups, ничего не пишет -./bin/onlyoffice/import-network.go --manifest /tmp/net.yml --write --limit 60 # создать до 60 -./bin/onlyoffice/import-network.go --manifest /tmp/net.yml --write --backfill # + дописать тег/about matched (N-1.4) -./bin/onlyoffice/import-network.go --manifest /tmp/net.yml --write --companies c.yml # + role-ящики на компанию по домену (N-1.4) +./bin/onlyoffice/import-network.go --manifest /tmp/net.yml --dry-run # preview: lookups, writes nothing +./bin/onlyoffice/import-network.go --manifest /tmp/net.yml --write --limit 60 # create up to 60 +./bin/onlyoffice/import-network.go --manifest /tmp/net.yml --write --backfill # + backfill tag/about for matched (N-1.4) +./bin/onlyoffice/import-network.go --manifest /tmp/net.yml --write --companies c.yml # + role mailboxes onto a company by domain (N-1.4) cat /tmp/net.yml | ./bin/onlyoffice/import-network.go --manifest - --write # stdin ``` -Флаги: `--manifest ` (обязателен), `--dry-run` (preview, ничего не -пишет), `--write` (создавать; по умолчанию report-only), `--limit N` -(макс. новых за прогон), `--tag` (default `2dph:network:`), -`--backfill`, `--companies ` (оба — N-1.4 #271, идемпотентны). -Отчёт: `created / matched / skipped / failed / pending`; сбои — списком -(`failed` возвращает exit 1). Creds — `ONLYOFFICE_URL/USER/PASS` -(go-onlyoffice `GetEnvironmentCredentials`), не логируются. +Flags: `--manifest ` (required), `--dry-run` (preview, writes nothing), +`--write` (create; report-only by default), `--limit N` +(max new per run), `--tag` (default `2dph:network:`), +`--backfill`, `--companies ` (both — N-1.4 #271, idempotent). +Report: `created / matched / skipped / failed / pending`; failures — as a list +(`failed` returns exit 1). Creds — `ONLYOFFICE_URL/USER/PASS` +(go-onlyoffice `GetEnvironmentCredentials`), not logged. -## Маппинг (связь → контакт) +## Mapping (link → contact) -| Что в манифесте | Что в OO CRM | +| What in the manifest | What in OO CRM | |---|---| -| accept-связь (kind person/company) | контакт **Person**: `firstName/lastName` из `name` (fallback — локальная часть email, `mailconv.SplitPersonName`); `about` — сводка | -| email связи | `AddContactInfo` infoType email, category Work, **primary** (ключ идемпотентности, lowercase) | -| источник | тег контакта `2dph:network:` (создаётся, если нет) | -| сила связи | `about`: `{msgs} писем / {threads} тредов / {replies} ответов, период {period}` | -| premises (первые 5 + extraPremises) | `about`: `premises: mail ; commit ; … (+N ещё)` — стабильный ключ в kb.lbug | -| источник манифеста | `about`: `source: ` (текст из манифеста) | - -«Деловая связь» в OO = существование контакта с email + тегом источника -(нативной записи Person↔Person в OO нет — не выдумываем). Полный манифест -(все premises, projects) — артефакт вне CRM (`--json` у bin/network). - -## Границы классов (по N-1.1 #268) - -- **kind=service** (GitLab/PayPal/LinkedIn-служебные/markets-platform/ - трекеры/рассылки) — пропускаются (`skipped`), в CRM не идут; -- **linkedin-релеи людей** (`hit-reply@linkedin.com` с реальным display - name: Ruby Rodriguez и т.п.) — Person как есть: email = релей платформы, - имя = реальный человек (классификатор N-1.1: person); -- **роль-ящики/компании** (`info@`/`alle@`, организации) — тоже контакт - Person (fallback-имя из локальной части): компания-группировка по домену - (`--companies`, N-1.4 #271) линкует их на компанию; matched-существующие - получают тег/about аддитивно (`--backfill`, N-1.4 #271). - -## Идемпотентность - -Ключ = email (lowercase). Один проход по CRM (`BuildContactEmailIndex`); -существующий по email (включая импортированных из VCF/MAB #85) — **skip** -(`matched`), не перезаписывается (ручные правки не трогаем). Повторный -прогон = 0 созданий / 0 изменений. При сбое email/тег-прикрепления только -что созданный контакт удаляется (rollback) — «created» = полностью -созданный контакт, повтор не заводит дубль. - -## N-1.4 #271: дописывание matched (--backfill) и компания-группировка (--companies) - -Шаги N-1.4 выполняются тем же инструментом ПОСЛЕ создания (см. примеры -выше); каждый шаг идемпотентен, report-only/dry-run по умолчанию ничего не -пишет. - -### Дописывание существующим matched (`--backfill`) - -Решение владельца (#267, вопрос 3): существующий по email контакт (в т.ч. -импорт VCF/MAB #85) **не пропускается молча**, а получает аддитивно: - -- тег `2dph:network:` — если у контакта его нет; -- about-premises-сводку из манифеста — **только если about пуст** (ручные - правки, в т.ч. Org из #85 в about, не перезаписываются). - -Механизм по email-ключу от манифеста (не хардкод под id); переиспользуется -N-1.5 #275 для eslider@. Состояние тега — множество id под тегом -(`ListContactsByTag`), about/имена — `GetContact`. Повтор = 0 изменений -(`updated=0 unchanged=N`). Отчёт: `updated / would (dry-run) / unchanged / +| accept link (kind person/company) | **Person** contact: `firstName/lastName` from `name` (fallback — the local part of the email, `mailconv.SplitPersonName`); `about` — summary | +| link email | `AddContactInfo` infoType email, category Work, **primary** (idempotency key, lowercase) | +| source | contact tag `2dph:network:` (created if missing) | +| link strength | `about`: `{msgs} mails / {threads} threads / {replies} replies, period {period}` | +| premises (first 5 + extraPremises) | `about`: `premises: mail ; commit ; … (+N more)` — stable key in kb.lbug | +| manifest source | `about`: `source: ` (text from the manifest) | + +A "business link" in OO = the existence of a contact with the email + the source tag +(OO has no native Person↔Person record — we do not invent one). The full manifest +(all premises, projects) — an artifact outside CRM (`--json` in bin/network). + +## Class boundaries (per N-1.1 #268) + +- **kind=service** (GitLab/PayPal/LinkedIn service/markets-platform/ + trackers/mailing lists) — skipped (`skipped`), do not go into CRM; +- **linkedin relays of people** (`hit-reply@linkedin.com` with a real display + name: Ruby Rodriguez etc.) — Person as is: email = platform relay, + name = real person (N-1.1 classifier: person); +- **role mailboxes/companies** (`info@`/`alle@`, organizations) — also a Person + contact (fallback name from the local part): company grouping by domain + (`--companies`, N-1.4 #271) links them to a company; matched existing ones + get the tag/about additively (`--backfill`, N-1.4 #271). + +## Idempotency + +Key = email (lowercase). One pass over CRM (`BuildContactEmailIndex`); +an existing contact by email (including those imported from VCF/MAB #85) — **skip** +(`matched`), not overwritten (we do not touch manual edits). A repeated +run = 0 creations / 0 changes. If attaching the email/tag fails, the +just-created contact is deleted (rollback) — "created" = a fully +created contact, a repeat does not create a duplicate. + +## N-1.4 #271: backfilling matched (--backfill) and company grouping (--companies) + +N-1.4 steps are performed by the same tool AFTER creation (see the examples +above); each step is idempotent, report-only/dry-run writes nothing by default. + +### Backfilling existing matched (`--backfill`) + +Owner decision (#267, question 3): an existing contact by email (incl. the +VCF/MAB #85 import) is **not silently skipped**, but gets additively: + +- the tag `2dph:network:` — if the contact does not have it; +- the about-premises summary from the manifest — **only if about is empty** (manual + edits, incl. Org from #85 in about, are not overwritten). + +The mechanism is by the email key from the manifest (no hardcoding to +ids); reused by N-1.5 #275 for eslider@. Tag state — a set of ids under the tag +(`ListContactsByTag`), about/names — `GetContact`. Repeat = 0 changes +(`updated=0 unchanged=N`). Report: `updated / would (dry-run) / unchanged / missing / failed`. -### Компания-группировка role-ящиков (`--companies`) +### Company grouping of role mailboxes (`--companies`) -Маппинг «домен email → компания» — YAML-файл, напр. `companies-wheregroup.yml`: +The "email domain → company" mapping — a YAML file, e.g. `companies-wheregroup.yml`: ```yaml wheregroup.com: WhereGroup ``` -Линкуются **только role-ящики/организации манифеста** (`kind=company`: -alle@, info@, wartung@…), чей домен есть в маппинге: `FindCompany` → если -нет, `CreateCompany` (оба идемпотентны по нормализованному имени) → -`UpdatePerson` с `companyId`. **person-kind не трогаем** (реальные люди — не -«роль-ящик»); company-kind без правила остаётся Person-контактом как есть -(`unmapped`, в пилоте #270 — events@suse). Повтор = 0 изменений (`found`, -`already`, `unmapped`). Отчёт: `found / created / linked / already / -notfound / unmapped / failed` (+ `missing / wouldlink` в dry-run). - -Компания ищется по нормализованному display name (без GmbH-суффиксов и -слоганов, go-onlyoffice `CompanyGroupingKey`) — **значение Name в маппинге -должно совпадать с реальной компанией CRM** (анализ — dry-run: found vs -missing); при несовпадении имени dry-run покажет `missing`, и маппинг -правится до `--write` (иначе CreateCompany заведёт дубль юрлица). - -## Код и тесты - -- `internal/network/manifest.go` — контракт манифеста `network.Manifest` - (общий у продюсера `bin/network` и коннектора; раньше — crmDoc/crmLink в +Only **role mailboxes/organizations of the manifest** are linked (`kind=company`: +alle@, info@, wartung@…), whose domain is in the mapping: `FindCompany` → if +absent, `CreateCompany` (both idempotent by normalized name) → +`UpdatePerson` with `companyId`. **We do not touch person-kind** (real people are not a +"role mailbox"); company-kind without a rule remains a Person contact as is +(`unmapped`, in pilot #270 — events@suse). Repeat = 0 changes (`found`, +`already`, `unmapped`). Report: `found / created / linked / already / +notfound / unmapped / failed` (+ `missing / wouldlink` in dry-run). + +The company is looked up by the normalized display name (without GmbH suffixes and +slogans, go-onlyoffice `CompanyGroupingKey`) — **the Name value in the mapping +must match the real company in CRM** (analysis — dry-run: found vs +missing); if the name does not match, the dry-run will show `missing`, and the mapping +is fixed before `--write` (otherwise CreateCompany will create a duplicate legal entity). + +## Code and tests + +- `internal/network/manifest.go` — the `network.Manifest` contract + (shared by the producer `bin/network` and the connector; previously — crmDoc/crmLink in bin/network); -- `internal/ooimport` (cgo-free): `ParseManifest` → `BuildPlan` (маппинг, - фильтр сервисов, тег, about, kind связи) → `Run` (lookups + создание, - dry-run/limit); N-1.4: `RunBackfill` (дописывание matched, аддитивно) + - `RunCompanies` (`ParseCompanies`/`GroupCompanyLinks`, линковка role-ящиков - на компанию по домену); +- `internal/ooimport` (cgo-free): `ParseManifest` → `BuildPlan` (mapping, + service filter, tag, about, link kind) → `Run` (lookups + creation, + dry-run/limit); N-1.4: `RunBackfill` (backfilling matched, additively) + + `RunCompanies` (`ParseCompanies`/`GroupCompanyLinks`, linking role mailboxes + to a company by domain); - CLI `bin/onlyoffice/import-network.go` (shebang, tag `onlyoffice_import_network`); -- тесты: офлайн (`internal/ooimport/*_test.go` — план/маппинг/roundtrip - продюсер-консьюмер, split по existing: повтор = 0 новых; ParseCompanies, - GroupCompanyLinks, BackfillChanges аддитивность) + интеграция - (`//go:build integration`, живой OO, creds из окружения, без creds — - skip; созданные тестовые контакты удаляются в конце; тег остаётся - 0-count — API клиента не удаляет теги); SplitPersonName-косметика - (mailconv) — трейлинговая « (Org)»-декорация снимается до разбора имени. - -## Ссылки - -- Epic N-1 #267; дети: N-1.1 #268 (фильтр), N-1.3 #270 (пилот), N-1.4 #271 - (компании). -- Сеть: docs/brain/graph-network.md; фильтр: docs/brain/crm-network-filter.md. -- go-onlyoffice: примитивы FindPersonByEmail/BuildContactEmailIndex/ +- tests: offline (`internal/ooimport/*_test.go` — plan/mapping/roundtrip + producer-consumer, split by existing: repeat = 0 new; ParseCompanies, + GroupCompanyLinks, BackfillChanges additivity) + integration + (`//go:build integration`, live OO, creds from the environment, without creds — + skip; created test contacts are deleted at the end; the tag stays + 0-count — the client API does not delete tags); SplitPersonName cosmetics + (mailconv) — the trailing " (Org)" decoration is stripped before parsing the name. + +## Links + +- Epic N-1 #267; children: N-1.1 #268 (filter), N-1.3 #270 (pilot), N-1.4 #271 + (companies). +- Network: docs/brain/graph-network.md; filter: docs/brain/crm-network-filter.md. +- go-onlyoffice: primitives FindPersonByEmail/BuildContactEmailIndex/ CreatePerson/AddContactInfo/CreateContactTag/AddContactTag. diff --git a/docs/brain/read-contract.md b/docs/brain/read-contract.md index 3315bb7..208cdd7 100644 --- a/docs/brain/read-contract.md +++ b/docs/brain/read-contract.md @@ -1,188 +1,188 @@ -# Контракт чтения brain (P-9.4) +# Brain read contract (P-9.4) -Нормативный формат ответов `search` / `get` / `stats` / `audit` — как клиенты -и агенты читают факты, info и аудит из Ladybug. Зеркало write-контракта -[`docs/brain/contract.md`](contract.md) (P-9.2/P-9.3): там — как писать leaf -(source/external_id/kind/text, ContentHash, observed_at), здесь — как читать. +Normative response format of `search` / `get` / `stats` / `audit` — how clients +and agents read facts, info and audit from Ladybug. A mirror of the write contract +[`docs/brain/contract.md`](contract.md) (P-9.2/P-9.3): there — how to write a leaf +(source/external_id/kind/text, ContentHash, observed_at), here — how to read. -Реализация схемы: `internal/contract/read.go` (cgo-free, версия -`contract.ReadContractVersion`); продьюсеры ответов — `internal/brain` -(search/get/stats/audit), HTTP-поверхность — `pkg/httpapi` +Schema implementation: `internal/contract/read.go` (cgo-free, version +`contract.ReadContractVersion`); response producers — `internal/brain` +(search/get/stats/audit), HTTP surface — `pkg/httpapi` (`bin/brain/serve.go`, :8630) + MCP (`POST /mcp`), CLI — `bin/brain/*.go --json`; -сервисный клиент для потребителей — `pkg/brainclient` (P-9.5, раздел -[«Как клиенту читать brain»](#клиентский-слой-p-95)). +the service client for consumers — `pkg/brainclient` (P-9.5, section +["How a client reads the brain"](#client-layer-p-95)). -## Поверхности чтения (один формат) +## Read surfaces (one format) -| Поверхность | Команда / путь | +| Surface | Command / path | |-------------|----------------| | CLI | `bin/brain/search.go "q" --json`, `bin/brain/get.go --json`, `bin/brain/stats.go --json` | | HTTP | `GET /search?q=`, `GET /get?id=`, `GET /stats`, `GET /audit` (:8630) | -| MCP | tools `search` / `get` / `audit` (`POST /mcp`; `stats` — HTTP-only, минимальная MCP-поверхность D20) | -| Клиент | SDK `pkg/brainclient`, CLI `bin/brain/client.go search|get|stats|audit` (P-9.5, раздел «Клиентский слой») | +| MCP | tools `search` / `get` / `audit` (`POST /mcp`; `stats` — HTTP-only, minimal MCP surface D20) | +| Client | SDK `pkg/brainclient`, CLI `bin/brain/client.go search|get|stats|audit` (P-9.5, section "Client layer") | -Все поверхности отдают один и тот же JSON (схемы ниже); HTTP/MCP — тонкий -транспорт над теми же структурами. **Клиенты читают brain только через эти -форматы — никогда не парсят `var/kb.lbug` напрямую** (схема Ladybug — -внутренняя, меняется без предупреждения). +All surfaces return the same JSON (schemas below); HTTP/MCP — a thin +transport over the same structures. **Clients read the brain only through these +formats — never parse `var/kb.lbug` directly** (the Ladybug schema is +internal, changes without notice). -## Версионность контракта +## Contract versioning -Каждый ответ несёт поле **`contract_version`** (semver `MAJOR.MINOR`, -сейчас `1.0`). Правки контракта: +Every response carries the field **`contract_version`** (semver `MAJOR.MINOR`, +currently `1.0`). Contract edits: -- **additive** (minor bump): новое опциональное поле, уточнение доков, новый - домен значения. Обратно совместимо — старые клиенты работают без изменений. -- **breaking** (major bump): удаление/переименование обязательного поля, смена - типа или семантики. Требует миграции всех клиентов. +- **additive** (minor bump): a new optional field, a doc clarification, a new + value domain. Backward compatible — old clients work unchanged. +- **breaking** (major bump): removal/renaming of a required field, a change of + type or semantics. Requires migration of all clients. -Правила клиентов: +Client rules: -- Принимать **любой** ответ с совместимым MAJOR; не требовать точного MINOR. -- Игнорировать неизвестные поля (additive evolution) — не валиться на них. -- Отсутствие `contract_version` = ответ сформирован **до** контракта - (старый сервис); формат полей при этом тот же — гейт допускает такой ответ - через `--relax-version` (warning, не failure). +- Accept **any** response with a compatible MAJOR; do not require an exact MINOR. +- Ignore unknown fields (additive evolution) — do not fail on them. +- The absence of `contract_version` = the response was formed **before** the + contract (an old service); the field format is the same — the gate admits such a response + via `--relax-version` (warning, not failure). -Потребители контракта: агенты (PicoClaw gateway — `search → get → audit`), -`gator`/`cv`-клиенты, `bin/brain`-инструменты, скрипты стека. +Contract consumers: agents (PicoClaw gateway — `search → get → audit`), +`gator`/`cv` clients, `bin/brain` tools, stack scripts. -## Форматы ответов (JSON-схемы) +## Response formats (JSON schemas) -Общие правила: **отсутствие → отсутствие** — опциональное поле, которого нет, -просто отсутствует в JSON (`omitempty`), не `null` и не пустая строка. -Обязательные поля всегда присутствуют. `results`/`by_confidence` — всегда -массив (может быть пустым), не `null`. +Common rules: **absence → absence** — an optional field that is missing is +simply absent from the JSON (`omitempty`), not `null` and not an empty string. +Required fields are always present. `results`/`by_confidence` are always an +array (may be empty), not `null`. ### search — `GET /search?q=…` / CLI `--json` -| Поле | Тип | Обязательно | Смысл | +| Field | Type | Required | Meaning | |------|-----|-------------|-------| -| `contract_version` | string | да | версия контракта, `MAJOR.MINOR` | -| `query` | string | да | переданный запрос | -| `root_filter` | string | да | `facts` / `info`; `""` = все корни | -| `as_of` | string | нет | `YYYY-MM-DD` (D24), фильтр валидности | -| `count` | int | да | число результатов (`>= 0`) | -| `results` | array | да | хиты (пусто, если нет совпадений) | -| `web` | object | нет | второй независимый источник (SearXNG) | +| `contract_version` | string | yes | contract version, `MAJOR.MINOR` | +| `query` | string | yes | the submitted query | +| `root_filter` | string | yes | `facts` / `info`; `""` = all roots | +| `as_of` | string | no | `YYYY-MM-DD` (D24), validity filter | +| `count` | int | yes | number of results (`>= 0`) | +| `results` | array | yes | hits (empty if there are no matches) | +| `web` | object | no | the second independent source (SearXNG) | -Хит (`results[]`): +Hit (`results[]`): -| Поле | Тип | Обязательно | Смысл | +| Field | Type | Required | Meaning | |------|-----|-------------|-------| -| `id` | string | да | id листа | -| `text` | string | да | полный текст листа | -| `root` | string | да | `facts` / `info` | -| `confidence` | string | нет | `confirmed` / `estimated` / `inferred` / … | -| `score` | float | да | оценка релевантности (RRF/косинус) | -| `snippet` | string | нет | до 280 рун текста | -| `valid_from` / `valid_to` | string | нет | `YYYY-MM-DD` (D24) | -| `hops` | array | нет | обход `--hop N` (`id`/`label`/`name`/`depth`) | - -`web` блок: `status` (обязательно: `ok`/`throttled`/`skipped`/`refused`/…), +| `id` | string | yes | sheet id | +| `text` | string | yes | full sheet text | +| `root` | string | yes | `facts` / `info` | +| `confidence` | string | no | `confirmed` / `estimated` / `inferred` / … | +| `score` | float | yes | relevance score (RRF/cosine) | +| `snippet` | string | no | up to 280 runes of text | +| `valid_from` / `valid_to` | string | no | `YYYY-MM-DD` (D24) | +| `hops` | array | no | `--hop N` traversal (`id`/`label`/`name`/`depth`) | + +`web` block: `status` (required: `ok`/`throttled`/`skipped`/`refused`/…), `note`, `cached`, `results[]` (`rank`/`title`/`url`/`snippet`/`engine`). ### get — `GET /get?id=…` / CLI `--json` -| Поле | Тип | Обязательно | Смысл | +| Field | Type | Required | Meaning | |------|-----|-------------|-------| -| `contract_version` | string | да | версия контракта | -| `id` | string | да | id листа | -| `root` | string | да | `facts` / `info` | -| `confidence` | string | да | `confirmed` / `estimated` / `inferred` / … | -| `source` | string | да | корпус: `mail` / `git` / `chats` / `docs` / `facts` | -| `type` | string | да | kind листа (`fact` / `mail` / `chat` / `commit` / …) | -| `valid_from` / `valid_to` | string | нет | `YYYY-MM-DD` (D24) | -| `snippet` | string | нет | без `--body` (до 280 рун) | -| `text` | string | нет | только с `--body` (полный текст) | - -`text` и `snippet` взаимоисключающие: `--body` → `text`, иначе `snippet`. +| `contract_version` | string | yes | contract version | +| `id` | string | yes | sheet id | +| `root` | string | yes | `facts` / `info` | +| `confidence` | string | yes | `confirmed` / `estimated` / `inferred` / … | +| `source` | string | yes | corpus: `mail` / `git` / `chats` / `docs` / `facts` | +| `type` | string | yes | sheet kind (`fact` / `mail` / `chat` / `commit` / …) | +| `valid_from` / `valid_to` | string | no | `YYYY-MM-DD` (D24) | +| `snippet` | string | no | without `--body` (up to 280 runes) | +| `text` | string | no | only with `--body` (full text) | + +`text` and `snippet` are mutually exclusive: `--body` → `text`, otherwise `snippet`. ### stats — `GET /stats` / CLI `--json` -| Поле | Тип | Обязательно | Смысл | +| Field | Type | Required | Meaning | |------|-----|-------------|-------| -| `contract_version` | string | да | версия контракта | -| `total` | int | да | всего leafs (`>= 0`) | -| `by_root` | object | да | `{"facts": N, "info": N}` — фактические корни | -| `db` | string | да | путь к kb.lbug | -| `model` | string | нет | CLI-расширение: id embedding-модели | -| `ann` | object | нет | HTTP-расширение: статус ANN-индекса | +| `contract_version` | string | yes | contract version | +| `total` | int | yes | total leafs (`>= 0`) | +| `by_root` | object | yes | `{"facts": N, "info": N}` — actual roots | +| `db` | string | yes | path to kb.lbug | +| `model` | string | no | CLI extension: embedding model id | +| `ann` | object | no | HTTP extension: ANN index status | -Required-ядро едино для CLI и HTTP; `model` и `ann` — аддитивные расширения -поверхностей (клиент не должен на них полагаться). +The required core is the same for CLI and HTTP; `model` and `ann` are additive +surface extensions (a client must not rely on them). ### audit — `GET /audit` / MCP `audit` -| Поле | Тип | Обязательно | Смысл | +| Field | Type | Required | Meaning | |------|-----|-------------|-------| -| `contract_version` | string | да | версия контракта | -| `status` | string | да | `"ok"` | -| `by_confidence` | array | да | гистограмма root × confidence | - -Строка `by_confidence[]`: `root` (`facts`/`info`), `confidence`, `count` -(`>= 0`). Это **формат ответа** чтения аудита; сами аудит-карточки -Vinogradov (L-9, issues #229–234) — отдельный домен (`docs/facts/`, -`bin/facts/audit.go`), в этот контракт не входят. Аудит соответствия -write-контракту — `bin/brain/audit-contract.go` (своя схема отчёта, P-9.2). - -## Семантика: root, confidence, (not confirmed) - -Единые термины с write-контрактом (contract.md): - -- **`root=facts`** — утверждение, подтверждённое **≥2 независимыми - источниками**, `confidence: confirmed`. Это единственный корень, с которого - ответ считается фактом. -- **`root=info`** — описательный/нарративный leaf корпуса (mail/git/chats/docs), - поисковый, никогда не утверждается. -- **`confidence`** — домен открыт: `confirmed` / `estimated` / `inferred` / - `hypothesis` / `partial` / …. Пустое значение (legacy leafs) трактуется - как `confirmed`. -- **`(not confirmed)`** — ответ не сходит с facts-корня: info-хит, - hypothesis/partial, либо только один независимый источник. Агент обязан - помечать такой ответ `(not confirmed)`, а не выдавать за факт. -- Дедuction-порядок поиска: facts → info → web. `--root facts` возвращает - только подтверждённые; без фильтра info-хиты помечаются `(not confirmed)`. -- `web`-блок держится отдельно от графовых hits: «наши» vs «не наши». - `throttled`/`skipped`/`refused` — не доказательство отсутствия. - -## Время: `--as-of` (valid_from/valid_to) и observed_at - -- **`valid_from` / `valid_to`** — валидность факта **по дням** (D24, - `YYYY-MM-DD`), **ортогональна версии** (версия = id/ContentHash). - `--as-of YYYY-MM-DD` оставляет hits, чей интервал покрывает день: пустой - интервал = «всегда» (legacy), пустой `valid_to` = открытый конец, оба конца - включительно. Это фильтр по смыслу факта, не по дате записи. -- **`observed_at`** — когда контент **увиден** (RFC3339), часть write- - контракта, **не входит в dedup-ключ** (ContentHash): тот же контент, - записанный позже, дедуплицируется к той же версии. В read-ответах поле - сейчас **не экспонируется** (аддитивное будущее); читается через аудит - write-контракта (`bin/brain/audit-contract.go`). - -## Гейт соответствия (read-only) - -Контракт проверяется скриптом, а не только текстом. Оба гейта read-only, -работают параллельно с живым сервисом (Ladybug: второй RW-open невозможен, -RO-open разрешён). +| `contract_version` | string | yes | contract version | +| `status` | string | yes | `"ok"` | +| `by_confidence` | array | yes | root × confidence histogram | + +The `by_confidence[]` row: `root` (`facts`/`info`), `confidence`, `count` +(`>= 0`). This is the **read response format** of the audit; the Vinogradov +audit cards themselves (L-9, issues #229–234) are a separate domain (`docs/facts/`, +`bin/facts/audit.go`) and are not part of this contract. The conformance audit against the +write contract — `bin/brain/audit-contract.go` (its own report schema, P-9.2). + +## Semantics: root, confidence, (not confirmed) + +Terms shared with the write contract (contract.md): + +- **`root=facts`** — a claim confirmed by **≥2 independent + sources**, `confidence: confirmed`. This is the only root from which an + answer counts as a fact. +- **`root=info`** — a descriptive/narrative corpus leaf (mail/git/chats/docs), + searchable, never asserted. +- **`confidence`** — an open domain: `confirmed` / `estimated` / `inferred` / + `hypothesis` / `partial` / …. An empty value (legacy leafs) is treated + as `confirmed`. +- **`(not confirmed)`** — the answer does not come from the facts root: an info hit, + hypothesis/partial, or only one independent source. The agent must + mark such an answer `(not confirmed)` and not present it as a fact. +- Deduction search order: facts → info → web. `--root facts` returns + only confirmed ones; without the filter info hits are marked `(not confirmed)`. +- The `web` block is kept separate from the graph hits: "ours" vs "not ours". + `throttled`/`skipped`/`refused` — not proof of absence. + +## Time: `--as-of` (valid_from/valid_to) and observed_at + +- **`valid_from` / `valid_to`** — validity of the fact **by days** (D24, + `YYYY-MM-DD`), **orthogonal to the version** (version = id/ContentHash). + `--as-of YYYY-MM-DD` keeps hits whose interval covers the day: an empty + interval = "always" (legacy), an empty `valid_to` = an open end, both ends + inclusive. This is a filter by the meaning of the fact, not by the write date. +- **`observed_at`** — when the content was **seen** (RFC3339), part of the write + contract, **not part of the dedup key** (ContentHash): the same content + written later dedups to the same version. In read responses the field is + currently **not exposed** (additive future); it is read via the write-contract + audit (`bin/brain/audit-contract.go`). + +## Conformance gate (read-only) + +The contract is checked by a script, not only by text. Both gates are read-only, +work in parallel with the live service (Ladybug: a second RW-open is impossible, +RO-open is allowed). ```bash -# Формат ответов живого сервиса (HTTP :8630): -./bin/brain/read-contract.go # строго (требует contract_version) -./bin/brain/read-contract.go --relax-version # сервис до контракта: формат проверяется, версия — warning -./bin/brain/read-contract.go --base URL --token T # другой сервис -./bin/brain/read-contract.go --json # машиночитаемый отчёт +# Response format of the live service (HTTP :8630): +./bin/brain/read-contract.go # strict (requires contract_version) +./bin/brain/read-contract.go --relax-version # service predating the contract: format is checked, version — warning +./bin/brain/read-contract.go --base URL --token T # another service +./bin/brain/read-contract.go --json # machine-readable report -# Инварианты данных на живой kb.lbug (не нужен поднятый сервис): +# Data invariants on the live kb.lbug (no running service needed): bin/cgo/zig go run -tags=system_ladybug,brain_readcontract_db bin/brain/read-contract-db.go bin/cgo/zig go run -tags=system_ladybug,brain_readcontract_db bin/brain/read-contract-db.go --json ``` -Что проверяет HTTP-гейт: search (общий + `root=facts` + `as_of`), get (с телом -и без), stats, audit — обязательные поля, типы, домены (`root` ∈ facts|info, -даты `YYYY-MM-DD`), отсутствие → отсутствие. DB-гейт воспроизводит формы -ответов из живых данных и прогоняет те же валидаторы (выборка 200 leafs). +What the HTTP gate checks: search (general + `root=facts` + `as_of`), get (with and +without a body), stats, audit — required fields, types, domains (`root` ∈ facts|info, +dates `YYYY-MM-DD`), absence → absence. The DB gate reproduces the response +shapes from live data and runs the same validators (sample of 200 leafs). -Прогон 2026-09-02 на живой kb.lbug (105210 leafs, сервис :8630): +Run on 2026-09-02 against the live kb.lbug (105210 leafs, service :8630): ``` $ bin/cgo/zig go run -tags=system_ladybug,brain_readcontract_db bin/brain/read-contract-db.go @@ -192,69 +192,70 @@ read contract gate: db (contract_version=1.0) PASS sample search/get fields ok (sample=200) gate: PASS -$ ./bin/brain/read-contract.go --relax-version # live :8630 до редеплоя +$ ./bin/brain/read-contract.go --relax-version # live :8630 before redeploy read contract gate: http:http://127.0.0.1:8630 (contract_version=1.0) PASS* search ok (warnings) # warning: service predates read-contract … gate: PASS ``` -## Клиентский слой (P-9.5) +## Client layer (P-9.5) -Единый клиентский слой поверх read-контракта, чтобы gator/cv/агенты/скрипты -не звали HTTP/MCP/CLI каждый по-своему и не открывали `var/kb.lbug`: +A single client layer on top of the read contract, so that gator/cv/agents/scripts +do not call HTTP/MCP/CLI each in their own way and do not open `var/kb.lbug`: -| Слой | Где | Что | +| Layer | Where | What | |------|-----|-----| -| SDK | `pkg/brainclient` (cgo-free) | typed-клиент: `Search`/`Get`/`Stats`/`Audit` → `internal/contract`-ответы; ответы валидируются контрактными валидаторами (формат + `contract_version`, несовместимый сервис — ошибка); «гейт facts» (`Gate`, `Facts`, `GateAudit`) | -| CLI | `bin/brain/client.go` (shebang, `brain_client`) | подкоманды `search`/`get`/`stats`/`audit`, `--json`, `--root facts|info`, `--as-of`, `-n`, `--no-web`, `--base URL`, `--token T`; base по умолчанию из `internal/config` (host/port), иначе `127.0.0.1:8630` | +| SDK | `pkg/brainclient` (cgo-free) | typed client: `Search`/`Get`/`Stats`/`Audit` → `internal/contract` responses; responses are validated by the contract validators (format + `contract_version`, an incompatible service — an error); the "facts gate" (`Gate`, `Facts`, `GateAudit`) | +| CLI | `bin/brain/client.go` (shebang, `brain_client`) | subcommands `search`/`get`/`stats`/`audit`, `--json`, `--root facts|info`, `--as-of`, `-n`, `--no-web`, `--base URL`, `--token T`; base by default from `internal/config` (host/port), otherwise `127.0.0.1:8630` | -Клиент ходит только через контракт (HTTP :8630, `bin/brain/serve.go`) — в -коде клиента нет ни одного открытия kb.lbug, парсинга Ladybug-файла или -запросов к внутренней схеме БД. Пакет cgo-free: тесты на httptest-фикстурах -входят в обычный `go test ./...`. +The client goes only through the contract (HTTP :8630, `bin/brain/serve.go`) — the +client code contains not a single opening of kb.lbug, parsing of the Ladybug file, or +query against the internal DB schema. The package is cgo-free: tests on httptest +fixtures are part of the regular `go test ./...`. ```bash -# CLI-примеры +# CLI examples ./bin/brain/client.go search "onlyoffice postgres" --root facts --json ./bin/brain/client.go get --body ./bin/brain/client.go stats ./bin/brain/client.go audit ``` -SDK-пример (агент/скрипт/сервис на Go): +SDK example (an agent/script/service in Go): ```go import "github.com/eSlider/2dph/pkg/brainclient" cl := brainclient.New(brainclient.Config{Base: "http://127.0.0.1:8630"}) facts, err := cl.Facts(ctx, "where is the lexicon", brainclient.SearchOptions{}) -for _, f := range facts.Confirmed { /* безопасно цитировать как факт */ } -for _, nf := range facts.NotConfirmed { /* (not confirmed): только с пометкой */ } +for _, f := range facts.Confirmed { /* safe to quote as a fact */ } +for _, nf := range facts.NotConfirmed { /* (not confirmed): only with a marker */ } ``` -### Гейт facts +### Facts gate -Сервер отдаёт листья как они лежат в БД; за то, что **не подтверждённое не -выдаётся за факт**, отвечает клиентский гейт (`pkg/brainclient`): +The server returns sheets as they lie in the DB; the client-side gate +(`pkg/brainclient`) is responsible for **what is not confirmed not being +presented as a fact**: -- `Gate(root, confidence)` — вердикт для одного хита: `true` только для - `root=facts` с `confidence=confirmed` (пустое = legacy, по семантике выше). +- `Gate(root, confidence)` — the verdict for a single hit: `true` only for + `root=facts` with `confidence=confirmed` (empty = legacy, per the semantics above). `info`, `hypothesis`/`partial`/`estimated`/`inferred` → `false`. -- `Client.Facts` = `search --root facts` + гейт: ответ разделяется на - `confirmed[]` (подтверждённые факты) и `not_confirmed[]` (отклонённое, с - полем `reason` — пометка `(not confirmed)`). 2v2-противоречия (D16) лежат - как `hypothesis` и в `confirmed` не попадают никогда. -- `GateAudit` — гейт поверх `audit`-гистограммы: `confirmed_facts` vs - `not_confirmed_facts` на facts-корне. `not_confirmed_facts > 0` значит: на - facts-корне есть hypothesis/partial — такие листы нельзя подавать как - факты, пока их не разберёт `bin/facts/audit.go contradict` / audit-card - (L-9, #229–234). CLI `audit` в этом случае выходит с кодом 1. -- Гейт — оборона на чтении; запись по-прежнему требует ≥2 независимых - источников (promote, `docs/brain/contract.md`). Клиент не «доверяет» - серверу: несовместимый формат/версия — ошибка, отклонённое — помечается. - -### Пример 1: search-факт через клиент +- `Client.Facts` = `search --root facts` + the gate: the response is split into + `confirmed[]` (confirmed facts) and `not_confirmed[]` (rejected, with a + `reason` field — the `(not confirmed)` marker). 2v2 contradictions (D16) lie + as `hypothesis` and never get into `confirmed`. +- `GateAudit` — a gate over the `audit` histogram: `confirmed_facts` vs + `not_confirmed_facts` on the facts root. `not_confirmed_facts > 0` means: there are + hypothesis/partial sheets on the facts root — such sheets cannot be served as + facts until `bin/facts/audit.go contradict` / audit-card sorts them out + (L-9, #229–234). In this case the CLI `audit` exits with code 1. +- The gate is a defense on read; writing still requires ≥2 independent + sources (promote, `docs/brain/contract.md`). The client does not "trust" the + server: an incompatible format/version — an error, a rejected one — is marked. + +### Example 1: a search fact through the client ```bash ./bin/brain/client.go search "onlyoffice postgres" --root facts --json @@ -279,13 +280,13 @@ for _, nf := range facts.NotConfirmed { /* (not confirmed): только с по } ``` -Если на facts-корне встретится hypothesis/partial (например 2v2-лист до -аудита), он уйдёт в `not_confirmed[]` с `reason`, а не в `confirmed[]` — -агент не сможет процитировать его как факт. `get --body` показывает -двухисточниковый `source` («docker ps x compose:docker-compose.yml») — -доказательство по write-контракту. +If a hypothesis/partial appears on the facts root (e.g. a 2v2 sheet before the +audit), it goes into `not_confirmed[]` with a `reason`, not into `confirmed[]` — +the agent will not be able to quote it as a fact. `get --body` shows the +two-source `source` ("docker ps x compose:docker-compose.yml") — +evidence per the write contract. -### Пример 2: audit-карточка (гигиена facts-корня) +### Example 2: audit card (facts-root hygiene) ```bash ./bin/brain/client.go audit @@ -294,27 +295,27 @@ info confirmed 105199 facts gate: confirmed=21 not_confirmed=0 ``` -`facts gate: not_confirmed=0` — facts-корень чист: все 21 факта confirmed. -Если гейт покажет `not_confirmed > 0`, это сигнал для L-9-карточки: -`bin/facts/audit.go contradict` (2v2-разбор) или `bin/facts/audit-card.go` -(вердикт в `var/audit/source-of-truth.yml`) — до разбора такие листы остаются -`(not confirmed)` и в ответах клиента фактами не считаются. +`facts gate: not_confirmed=0` — the facts root is clean: all 21 facts are confirmed. +If the gate shows `not_confirmed > 0`, this is a signal for an L-9 card: +`bin/facts/audit.go contradict` (2v2 analysis) or `bin/facts/audit-card.go` +(a verdict into `var/audit/source-of-truth.yml`) — until the analysis such sheets remain +`(not confirmed)` and are not counted as facts in client responses. -### Кросс-репо потребители (gator/cv) +### Cross-repo consumers (gator/cv) -`internal/contract` — внутренний пакет модуля, поэтому сегодня клиент -импортируют 2dph-инструменты и скиллы. Чтобы gator/cv импортировали -клиент как внешний go-модуль, нужен вынос типов read-контракта и клиента в -публичный `go-*` модуль — это решает P-9.6 (общий ADR модели -фактов/аудита/памяти, эпик #239); до него внешние потребители читают brain по -этому документу (форматы) и через HTTP/MCP/CLI без дублирования логики. +`internal/contract` is an internal package of the module, so today the client is +imported by 2dph tools and skills. For gator/cv to import the +client as an external go module, the read-contract types and the client need to be moved into a +public `go-*` module — this is decided by P-9.6 (the shared ADR of the +facts/audit/memory model, epic #239); before that, external consumers read the brain by +this document (formats) and via HTTP/MCP/CLI without duplicating logic. ## Cross-ref -- Write-контракт: [`docs/brain/contract.md`](contract.md) (P-9.2/P-9.3, - issues #235/#13) — Leaf, ContentHash, observed_at, адаптеры корпуса. -- Общий паттерн версионности / ADR: P-9.6, issue #16. -- Аудит-карточки Vinogradov: L-9, issues #229–234 — отдельный домен +- Write contract: [`docs/brain/contract.md`](contract.md) (P-9.2/P-9.3, + issues #235/#13) — Leaf, ContentHash, observed_at, corpus adapters. +- Shared versioning pattern / ADR: P-9.6, issue #16. +- Vinogradov audit cards: L-9, issues #229–234 — a separate domain (`docs/facts/audit-recipes.md`, `bin/facts/audit.go`). -- Скилл `brain` (skills/brain) — как пользоваться поиском и добавлять корпус. -- HTTP/MCP поверхность: `pkg/httpapi` (OpenAPI `GET /openapi.json`). +- Skill `brain` (skills/brain) — how to use search and add a corpus. +- HTTP/MCP surface: `pkg/httpapi` (OpenAPI `GET /openapi.json`). diff --git a/docs/brain/rebuild.md b/docs/brain/rebuild.md index 568aa54..48a6f14 100644 --- a/docs/brain/rebuild.md +++ b/docs/brain/rebuild.md @@ -9,17 +9,17 @@ Build the native binaries (also runs the cgo brain tests): scripts/stack/serve-brain --build # or ./bin/cgo/zig go build ... -Fresh rebuild of info + mail + facts with control flags (одна команда, без -двухфазного workaround-а — пул для FTS-фазы подбирается автоматически, #244): +Fresh rebuild of info + mail + facts with control flags (one command, without the +two-phase workaround — the pool for the FTS phase is picked automatically, #244): bin-build/brain-index \ --rebuild --with-mail --with-facts \ --workers 12 --batch 256 --progress 5 --skip -Corpus adapters (P-9.3): `--with-mail` → mail-адаптер, `--with-chats` → -chats-адаптер, `--corpus DIR` → docs-адаптер (доп. пути), `--git-root DIR` → -git-адаптер (история репозиториев). Каждый корпус — `contract.Source` -(`internal/corpus`); index пишет их единым `WriteCorpus`. +Corpus adapters (P-9.3): `--with-mail` → mail adapter, `--with-chats` → +chats adapter, `--corpus DIR` → docs adapter (additional paths), `--git-root DIR` → +git adapter (repository history). Each corpus is a `contract.Source` +(`internal/corpus`); index writes them with a single `WriteCorpus`. > Facts require `--with-facts` (or `--facts-json`). Corpus leafs are always > written as `root=info` (single file source each); the facts layer @@ -34,41 +34,41 @@ git-адаптер (история репозиториев). Каждый ко - `--progress N` print rate + ETA every N seconds to stderr - `--skip` resume: skip leafs whose id is already in the db -### Dedup перед записью (issue #248 A1) +### Dedup before write (issue #248 A1) -`WriteCorpusChunked` дедуплицирует **кросс-чанково и всегда** (не только при -`--skip`): leaf с контрактным `ContentHash` (source|external_id|kind|text), -уже виденным в этом прогоне, не эмбеддится и не пишется. Это убирает двойной -стрим одной почты (live `var/corpus/mail` + legacy `var/mail`, #199/#184): -полный rebuild — 307k streamed → ~105k unique, C-сторона делает 3× меньше -MERGE/undo-работы. Детерминизм id/порядка финальных leafs не меняется -(дубликаты схлопывались бы к тому же id и на C-стороне — теперь раньше). +`WriteCorpusChunked` dedups **cross-chunk and always** (not only with +`--skip`): a leaf with a contract `ContentHash` (source|external_id|kind|text) +already seen in this run is neither embedded nor written. This removes the double +stream of the same mail (live `var/corpus/mail` + legacy `var/mail`, #199/#184): +a full rebuild — 307k streamed → ~105k unique, the C side does 3× less +MERGE/undo work. The determinism of the id/order of the final leafs does not change +(duplicates would collapse to the same id on the C side too — now earlier). -Pass 1 (`CountCorpus`, dry-run) считает так же: `info` = уникальных -(сколько ляжет в БД), `streamed` = сырой стрим с дублями. `--limit` считается -по стримнутым leafs, поэтому dry-run и фактическая запись при том же limit -дают одно число. +Pass 1 (`CountCorpus`, dry-run) counts the same way: `info` = the number of unique +leafs (how many will land in the DB), `streamed` = the raw stream with duplicates. +`--limit` counts streamed leafs, so a dry-run and the actual write with the same limit +give the same number. Because leaf ids are deterministic (`contract.ContentHash`, P-9.3), `--skip` makes a re-run cheap: it filters existing ids before embedding, so it embeds only new leafs. After a partial/aborted run, re-running with `--skip` skips the already-written corpus and goes straight to index build. -### Embedding-колонка и ANN (issue #248 B3) +### Embedding column and ANN (issue #248 B3) -Когда `vector.ann.enabled=true` (прод-дефолт #206), rebuild **не пишет -embedding-колонку**: модель не грузится вовсе (минус ~1.5GB RSS write-фазы), -leafs и facts пишутся текстом. Векторный индекс строит шаг волны `ann-build` -(`bin/brain/ann.go ensure`) из текста напрямую — `extractRows` эмбеддит -column-less leafs моделью (legacy-БД с колонкой идут старым путём, без -модели). Колонка пишется только когда ANN **выключен** — тогда векторный -путь поиска это linear-scan по `l.embedding` (search.go `vecScanStmt`). +When `vector.ann.enabled=true` (prod default #206), rebuild **does not write the +embedding column**: the model is not loaded at all (minus ~1.5GB RSS of the write phase), +leafs and facts are written as text. The vector index is built by the `ann-build` +wave step (`bin/brain/ann.go ensure`) from the text directly — `extractRows` embeds +column-less leafs with the model (legacy DBs with the column go the old way, without the +model). The column is written only when ANN is **disabled** — then the vector +search path is a linear scan over `l.embedding` (search.go `vecScanStmt`). > Note: `--rebuild` deletes the db, so `--skip` + `--rebuild` always restarts > fresh. To resume a crashed build (leafs already written, indexes missing), > run `--skip` **without** `--rebuild` so the db is preserved and only missing -> indexes are built — фаза индексов в обоих случаях одна и та же -> (`BuildIndexes`, автопул): +> indexes are built — the index phase is the same in both cases +> (`BuildIndexes`, auto pool): > > bin-build/brain-index --skip \ > --with-mail --with-facts --workers 12 --batch 256 --progress 5 @@ -89,72 +89,72 @@ Before a fresh rebuild, remove the old db (daemons must be down first): scripts/stack/serve-brain --stop # or pkill bin-build/brain-* rm -f var/kb.lbug var/kb.lbug.wal -## Buffer pool (память, issue #244) - -Две фазы прогона живут на разных пулах: - -- **write-фаза** (запись leafs) — на конфигурированном `KB_BUFFER_POOL` - (default 1 GB). Явный `KB_BUFFER_POOL` остаётся нижней границей для обеих фаз. -- **FTS-фаза** (`CREATE_FTS_INDEX`, после записи leafs) — хэндл закрывается, - БД переоткрывается с автоподобранным пулом `max(1GB, chars×32)`, где chars — - суммарный размер текста корпуса (`MATCH (l:Leaf) RETURN sum(size(l.text))`). - Замеры порога «buffer pool full»: реальные mail-лифы 10.3 MB текста → - 64 MB падает / 128 MB проходит; синтетика 10.8 MB → 192 MB / 256 MB; - продакшн 105k лифов (280 MB текста) → 1 GB падает / 10 GB проходит. - Коэффициент ×32 даёт ~9 GB на полном корпусе. - -Пул — это page cache, а не преаллокация: RSS растёт только под реальный -working set, поэтому завышение пула безопасно (память не резервируется). - -### C-потолок: write-фаза ~140 KB/leaf (замер #244) - -Помимо пула, C-сторона Ladybug держит ~135-145 KB на каждый записанный лиф -(независимо от пула: при 1 GB пуле и 30k лифов RSS вырос до ~6.3 GB; -эмбеддинг не влияет — замер без `embedding` дал те же 141 KB/leaf). -Рост линейный и **не освобождается при закрытии хэндла в том же процессе** -(malloc-арены): полный корпус 105k → ~14-15 GB C-side + модель ~1.5 GB. -CHECKPOINT каждые 1024 лифа не влияет. Это внутренности liblbug 0.19.1 -(undo/версионные структуры узла), вне Go-контроля. - -> Checkpoint (issue #248 B1, замерено): liblbug 0.19.1 включает -> `auto_checkpoint` по умолчанию с порогом WAL 16MB — и go-ladybug v0.17.0 -> пробрасывает это как есть (поля `auto_checkpoint`/`checkpoint_threshold` в -> Go-`SystemConfig` отсутствуют, toC стартует от C-дефолта). В write-фазе WAL -> растёт до ~16MB и циклически чекпойнтится в основную БД (наблюдалось на -> 15k leafs: wal 0→16.6MB → сброс в 2.2MB, db растёт порциями). Явный -> `CHECKPOINT` как Cypher-стейтмент тоже принимается. На RSS это не влияет -> (рост дают undo-структуры, не WAL) — главный рычаг пика это dedup (A1): -> 3× меньше MERGE/undo на C-стороне. - -Следствие для пикового RSS: фаза индексов стартует после закрытия write-хэндла -(тот же процесс — память удержана), поэтому пик ≈ C-накопление write-фазы + -working set FTS-фазы. Раньше (до #244) runbook предписывал -`KB_BUFFER_POOL=10GB` на весь прогон — write-фаза дополнительно раздувала -dirty-страницы к 10 GB и FTS строился на том же хэндле поверх накопленного: -это и давало наблюдаемые 39-41 GB. Теперь write-фаза идёт на 1 GB пуле, FTS — -на автопуле после закрытия хэндла. - -Если нужен пик ниже (отдельные процессы для фаз полностью освобождают C-память -между прогонами — двухфазный workaround) — это контроль DevOps на полном -прогоне; код даёт корректный результат и в одном процессе. - -### C-потолок: орфан-таблица (почему автопул) - -При падении `CREATE_FTS_INDEX` (нехватка пула) Ladybug оставляет частичную -внутреннюю таблицу `0_id_appears_info` (строки токенов до точки отказа). -Она недостижима через `DROP TABLE`/`DROP_FTS_INDEX` (каталог скрывает -внутренние таблицы; проверено на liblbug 0.19.1 и в исходниках Kuzu FTS: -`appears_info` создаётся первой, дропается в конце rewrite-запроса) и -навсегда блокирует повторный `CREATE_FTS_INDEX` на этой БД. Поэтому пул -фазы индексов подбирается заранее; если FTS всё же упал (хосту не хватает -RAM), ошибка явно называет орфан и recovery: удалить БД и пересобрать или -восстановить бэкап. Критерий #237 «пик RSS ≤ 2-4 GB» формально относится к -Go-части (чанкинг, выполнено); C-сторона требует мультигигабайты и на write -(~140 KB/leaf), и на FTS (пул ~9 GB на полном корпусе) — это осознанные -C-ограничения Ladybug (issue #244). - -`--skip-indexes` по-прежнему пишет только leafs (первая фаза workaround-а -для отладки/внешних индексов); в обычном прогоне он не нужен. +## Buffer pool (memory, issue #244) + +The two phases of a run live on different pools: + +- **write phase** (writing leafs) — on the configured `KB_BUFFER_POOL` + (default 1 GB). An explicit `KB_BUFFER_POOL` remains the lower bound for both phases. +- **FTS phase** (`CREATE_FTS_INDEX`, after writing the leafs) — the handle is closed, + the DB is reopened with an auto-picked pool `max(1GB, chars×32)`, where chars is + the total size of the corpus text (`MATCH (l:Leaf) RETURN sum(size(l.text))`). + Measurements of the "buffer pool full" threshold: real mail leafs 10.3 MB of text → + 64 MB fails / 128 MB passes; synthetic 10.8 MB → 192 MB / 256 MB; + production 105k leafs (280 MB of text) → 1 GB fails / 10 GB passes. + The ×32 coefficient gives ~9 GB on the full corpus. + +The pool is a page cache, not a preallocation: RSS grows only for the real +working set, so over-provisioning the pool is safe (memory is not reserved). + +### C ceiling: write phase ~140 KB/leaf (measurement #244) + +Besides the pool, the C side of Ladybug holds ~135-145 KB per written leaf +(independently of the pool: with a 1 GB pool and 30k leafs RSS grew to ~6.3 GB; +embedding does not matter — a measurement without `embedding` gave the same 141 KB/leaf). +The growth is linear and is **not released when the handle is closed in the same process** +(malloc arenas): the full corpus of 105k → ~14-15 GB C-side + the model ~1.5 GB. +A CHECKPOINT every 1024 leafs does not matter. This is liblbug 0.19.1 internals +(undo/version structures of the node), outside Go control. + +> Checkpoint (issue #248 B1, measured): liblbug 0.19.1 enables +> `auto_checkpoint` by default with a WAL threshold of 16MB — and go-ladybug v0.17.0 +> passes this through as is (the fields `auto_checkpoint`/`checkpoint_threshold` are +> absent in the Go `SystemConfig`, toC starts from the C default). In the write phase WAL +> grows to ~16MB and is checkpointed cyclically into the main DB (observed on +> 15k leafs: wal 0→16.6MB → reset to 2.2MB, the db grows in chunks). An explicit +> `CHECKPOINT` as a Cypher statement is also accepted. It does not affect RSS +> (the growth comes from undo structures, not from WAL) — the main lever of the peak is dedup (A1): +> 3× less MERGE/undo on the C side. + +Consequence for the peak RSS: the index phase starts after the write handle is closed +(same process — the memory is retained), so the peak ≈ the C accumulation of the write phase + +the working set of the FTS phase. Earlier (before #244) the runbook prescribed +`KB_BUFFER_POOL=10GB` for the whole run — the write phase additionally inflated +dirty pages towards 10 GB and FTS was built on the same handle on top of the accumulation: +that is what gave the observed 39-41 GB. Now the write phase runs on a 1 GB pool, FTS — +on the auto pool after the handle is closed. + +If a lower peak is needed (separate processes for the phases free the C memory +between runs — the two-phase workaround) — that is DevOps control on a full +run; the code gives a correct result in one process as well. + +### C ceiling: the orphan table (why the auto pool) + +When `CREATE_FTS_INDEX` fails (insufficient pool) Ladybug leaves a partial +internal table `0_id_appears_info` (token rows up to the point of failure). +It is unreachable via `DROP TABLE`/`DROP_FTS_INDEX` (the catalog hides +internal tables; verified on liblbug 0.19.1 and in the Kuzu FTS sources: +`appears_info` is created first, dropped at the end of the rewrite query) and +permanently blocks a repeated `CREATE_FTS_INDEX` on this DB. That is why the pool +of the index phase is picked in advance; if FTS still fails (the host lacks +RAM), the error explicitly names the orphan and the recovery: delete the DB and rebuild or +restore a backup. Criterion #237 "peak RSS ≤ 2-4 GB" formally refers to the +Go part (chunking, done); the C side requires multiple gigabytes both on write +(~140 KB/leaf) and on FTS (a pool of ~9 GB on the full corpus) — these are deliberate +C limitations of Ladybug (issue #244). + +`--skip-indexes` still writes only leafs (the first phase of the workaround +for debugging/external indexes); it is not needed in a normal run. ## Control / monitoring