Compare commits
22
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c2e2409d71 | ||
|
|
568a6af888 | ||
|
|
eeb5b79cf2 | ||
|
|
5990feb1f6 | ||
|
|
d27a738fee | ||
|
|
669e184cf6 | ||
|
|
ebc3f948c1 | ||
|
|
fe6a02024c | ||
|
|
4a065d9838 | ||
|
|
e3c6ef5684 | ||
|
|
98c14e23f1 | ||
|
|
ff1716de40 | ||
|
|
fec5325c7a | ||
|
|
27d9521e7f | ||
|
|
a7cb8d4c76 | ||
|
|
53cd00284d | ||
|
|
b73b4d4f97 | ||
|
|
1d1f6a90ff | ||
|
|
f220bcd95a | ||
|
|
678a1d1dba | ||
|
|
8781c0c3eb | ||
|
|
d6b17e8819 |
@@ -36,13 +36,10 @@ PLAN.md decisions + execution + open questions
|
|||||||
docs/ published docs
|
docs/ published docs
|
||||||
skills/ in-project agent skills (vendored, no external links)
|
skills/ in-project agent skills (vendored, no external links)
|
||||||
bin/ self-describing tools bin/{subject}/{method}.go (shebang)
|
bin/ self-describing tools bin/{subject}/{method}.go (shebang)
|
||||||
bin/brain/ search.go serve.go index.go get.go stats.go eval.go watch.go
|
bin/brain/ search.go, serve.go; libs in internal/brain and internal/httpapi
|
||||||
bin/chats/ sync.go import.go facts.go apply.go; libs in internal/chats
|
internal/ shared Go (brain/rank is cgo-free)
|
||||||
bin/mail/ sync.go import.go (index_mail → brain/index.go)
|
bin/watch/ corpus watcher (internal via bin/brain/watch later)
|
||||||
bin/markdown/ import.go (mistune leafs)
|
bin/mail/ mail pipeline: sync (Go), import (md), index_mail (rebuild)
|
||||||
bin/postgres/ query.go (read-only YAML)
|
|
||||||
internal/ shared Go (brain/rank is cgo-free; chats parsers too)
|
|
||||||
bin/watch/ corpus watcher (used by bin/brain/watch.go)
|
|
||||||
bin/tools/ vendored python libs behind bin/* (kblib, yamlout, websearch)
|
bin/tools/ vendored python libs behind bin/* (kblib, yamlout, websearch)
|
||||||
bin/docker-entrypoint container entrypoint (brain index|search|serve|watch)
|
bin/docker-entrypoint container entrypoint (brain index|search|serve|watch)
|
||||||
compose.yaml docker composition (root level, not docker/)
|
compose.yaml docker composition (root level, not docker/)
|
||||||
@@ -56,8 +53,8 @@ var/ kb.lbug, var/mail/*, caches (gitignored)
|
|||||||
```bash
|
```bash
|
||||||
bin/mail/sync.go --source onlyoffice,gmail --workers 8 --out var/mail # raw message.json + attachments
|
bin/mail/sync.go --source onlyoffice,gmail --workers 8 --out var/mail # raw message.json + attachments
|
||||||
bin/mail/sync.go --source gmail --query 'from:example.com' --out var/mail # Gmail search (default in:inbox)
|
bin/mail/sync.go --source gmail --query 'from:example.com' --out var/mail # Gmail search (default in:inbox)
|
||||||
bin/mail/import.go --from-raw var/mail # message.json → message.md (convert only)
|
bin/mail/import --from-raw var/mail # message.json → message.md (convert only)
|
||||||
bin/brain/index.go --rebuild # rebuild brain incl. all mail (fresh DB)
|
bin/mail/index_mail # rebuild brain incl. all mail (fresh DB)
|
||||||
```
|
```
|
||||||
|
|
||||||
- `sync` (Go) downloads messages + attachments; Gmail uses paginated list +
|
- `sync` (Go) downloads messages + attachments; Gmail uses paginated list +
|
||||||
@@ -66,7 +63,7 @@ bin/brain/index.go --rebuild # rebuil
|
|||||||
`pdftotext -layout` fast path (~15ms); textless/scanned PDFs fall back to
|
`pdftotext -layout` fast path (~15ms); textless/scanned PDFs fall back to
|
||||||
docling (isolated subprocess — its native onnx can segfault the parent).
|
docling (isolated subprocess — its native onnx can segfault the parent).
|
||||||
Conversion never touches the brain DB (crash safety).
|
Conversion never touches the brain DB (crash safety).
|
||||||
- `index_mail` is a deprecation shim for `bin/brain/index.go --rebuild`. Ladybug
|
- `index_mail` always rebuilds from scratch (repo corpus + mail). Ladybug
|
||||||
corrupts its WAL when brand-new leafs are bulk-inserted while FTS/vector
|
corrupts its WAL when brand-new leafs are bulk-inserted while FTS/vector
|
||||||
indexes exist; a fresh DB with indexes created last is the only safe path.
|
indexes exist; a fresh DB with indexes created last is the only safe path.
|
||||||
Keep conversion + indexing separate so a conversion crash can't leave the
|
Keep conversion + indexing separate so a conversion crash can't leave the
|
||||||
@@ -79,9 +76,6 @@ bin/facts/audit ["self"|"facts"|"info"|"stale"] # 2-source + staleness gate
|
|||||||
bin/facts/crm [--dry-run] # proof person↔company/company↔project (ooCRM × corpus SoT)
|
bin/facts/crm [--dry-run] # proof person↔company/company↔project (ooCRM × corpus SoT)
|
||||||
bin/kb/search "query" [--repo X] # deprecated wrapper → bin/brain/search.go
|
bin/kb/search "query" [--repo X] # deprecated wrapper → bin/brain/search.go
|
||||||
bin/brain/search.go "query" [--root facts|info] # deduction search → YAML
|
bin/brain/search.go "query" [--root facts|info] # deduction search → YAML
|
||||||
bin/brain/get.go <id> [--body]
|
|
||||||
bin/markdown/import.go [dir] # mistune leaves → YAML
|
|
||||||
bin/postgres/query.go --profile onlyoffice -c 'SELECT 1'
|
|
||||||
bin/md/tables # what the graph holds → YAML
|
bin/md/tables # what the graph holds → YAML
|
||||||
bin/brain/deduce "question" # thinking wrapper
|
bin/brain/deduce "question" # thinking wrapper
|
||||||
```
|
```
|
||||||
|
|||||||
@@ -26,10 +26,10 @@ detective method: **a fact needs ≥2 independent sources or it is
|
|||||||
|---|----------|--------|
|
|---|----------|--------|
|
||||||
| D1 | RAG corpus | ops stack (chat, onlyoffice, gitea/NPM, searchxng, observability, ai-bot, mcp-servers, `~/.ssh/config`) + portfolio. Exclude `office.dev` + jobs/applications. |
|
| D1 | RAG corpus | ops stack (chat, onlyoffice, gitea/NPM, searchxng, observability, ai-bot, mcp-servers, `~/.ssh/config`) + portfolio. Exclude `office.dev` + jobs/applications. |
|
||||||
| D2 | skill merging | integrate skills **in this project** `skills/`; skip gitea / brain-dependent skills. |
|
| D2 | skill merging | integrate skills **in this project** `skills/`; skip gitea / brain-dependent skills. |
|
||||||
| D3 | web search | Vendored client; SearXNG URL is config. Optional Compose instance (sanitized settings). Do not run a second copy on a host that already has one. Empty/`throttled` ≠ “nothing exists”. |
|
| D3 | web search | import `web-search`, retire local `searxng-ops`. Vendored here, no remote link. |
|
||||||
| D4 | embeddings | **model2vec** `minishlab/potion-multilingual-128M` instead of embeddinggemma. |
|
| D4 | embeddings | **model2vec** `minishlab/potion-multilingual-128M` instead of embeddinggemma. |
|
||||||
| D5 | parser | **mistune** for MD → leaf extraction (duckdb-md documented as future optional SQL/export layer, not v1). |
|
| D5 | parser | **mistune** for MD → leaf extraction (duckdb-md documented as future optional SQL/export layer, not v1). |
|
||||||
| D6 | graph engine | **LadybugDB**. Go is the service (`bin/brain/search.go`, `internal/brain`); Python remains for index/write until the Go write path is safe. |
|
| D6 | graph engine | **LadybugDB** (Kuzu successor, MIT, embedded, native FTS+vector+Cypher). Python binding for `bin/*`; Go shebang for golang tools. |
|
||||||
| D7 | db access | `db-yaml`/`psql-yq`-style, read-only, YAML out. OnlyOffice Postgres via SSH tunnel (`127.0.0.1:5433`). |
|
| D7 | db access | `db-yaml`/`psql-yq`-style, read-only, YAML out. OnlyOffice Postgres via SSH tunnel (`127.0.0.1:5433`). |
|
||||||
| D8 | evidence | detective method: ≥2 independent sources or `(not confirmed)`. Auto-pair docker ps × compose × ssh-config × docs. |
|
| D8 | evidence | detective method: ≥2 independent sources or `(not confirmed)`. Auto-pair docker ps × compose × ssh-config × docs. |
|
||||||
| D9 | facts/goal model | Who / What / How / Where / When + evidence + confidence on every edge. |
|
| D9 | facts/goal model | Who / What / How / Where / When + evidence + confidence on every edge. |
|
||||||
@@ -40,8 +40,6 @@ detective method: **a fact needs ≥2 independent sources or it is
|
|||||||
| D14 | tooling style | `bin/{subject}/{method}.go` shebang (e.g. `bin/brain/search.go`). Shared code in `internal/`. One root `go.mod` + `go.work`. No `bin/*/main.go`, no nested modules. |
|
| D14 | tooling style | `bin/{subject}/{method}.go` shebang (e.g. `bin/brain/search.go`). Shared code in `internal/`. One root `go.mod` + `go.work`. No `bin/*/main.go`, no nested modules. |
|
||||||
| D15 | repo | Gitea [`eSlider/2dph`](https://git.produktor.io/eSlider/2dph) is origin + [issues](https://git.produktor.io/eSlider/2dph/issues). GitHub `eSlider/2dph` is the public clone (PRs + Actions CI). No direct `main` pushes. TDD → PR → CI green → merge. |
|
| D15 | repo | Gitea [`eSlider/2dph`](https://git.produktor.io/eSlider/2dph) is origin + [issues](https://git.produktor.io/eSlider/2dph/issues). GitHub `eSlider/2dph` is the public clone (PRs + Actions CI). No direct `main` pushes. TDD → PR → CI green → merge. |
|
||||||
| D16 | contradictions | ≥2 yes vs ≥2 no → unrelated sources conflict → hypothesis → `(not confirmed)`. Resolution (authority, staleness adjudication) = **v2**, tracked as open question. |
|
| D16 | contradictions | ≥2 yes vs ≥2 no → unrelated sources conflict → hypothesis → `(not confirmed)`. Resolution (authority, staleness adjudication) = **v2**, tracked as open question. |
|
||||||
| D17 | assertion gate | Fact-check every *claim* (facts → info → live sources → web), not every edit. Missing graph ≠ “does not exist”. |
|
|
||||||
| D18 | reasoner | Pluggable OpenAI-compatible URL. RAM: Qwen3.5-9B. Quality: Bonsai-27B or Qwen3.6-27B. No official Qwen3.6-9B. |
|
|
||||||
|
|
||||||
## Architecture
|
## Architecture
|
||||||
|
|
||||||
@@ -53,17 +51,10 @@ detective method: **a fact needs ≥2 independent sources or it is
|
|||||||
bin/
|
bin/
|
||||||
facts/extract auto-pair 2 sources → lexicon yaml + graph
|
facts/extract auto-pair 2 sources → lexicon yaml + graph
|
||||||
facts/audit ["self"|"facts"|"info"|"stale"] 2-source + staleness gate
|
facts/audit ["self"|"facts"|"info"|"stale"] 2-source + staleness gate
|
||||||
kb/index Python write path (called by bin/brain/index.go)
|
kb/index build FTS + HNSW from corpus
|
||||||
brain/index.go rebuild FTS + HNSW (incl. --with-mail)
|
kb/search deduction: facts → info → web-search; --hop N
|
||||||
brain/get.go stats.go eval.go watch.go
|
kb/get kb/stats kb/eval
|
||||||
brain/search.go deduction: facts → info → web-search
|
md/import md/select md/tables md/gaps (mistune)
|
||||||
brain/serve.go HTTP API (internal/httpapi)
|
|
||||||
mail/import.go JSON → markdown (no brain write)
|
|
||||||
markdown/import.go mistune leaves
|
|
||||||
postgres/query.go read-only YAML (wraps bin/db/psql-yq)
|
|
||||||
chats/sync.go import.go facts.go apply.go
|
|
||||||
(libs in internal/chats; no chats index)
|
|
||||||
md/import (deprecated; bin/markdown/import.go)
|
|
||||||
brain/extract brain/audit brain/deduce (thinking wrapper)
|
brain/extract brain/audit brain/deduce (thinking wrapper)
|
||||||
web/search (vendored)
|
web/search (vendored)
|
||||||
db/psql-yq (vendored)
|
db/psql-yq (vendored)
|
||||||
@@ -112,26 +103,26 @@ Common props on every node/edge: `root`, `confidence`, `evidence[]`, `how`,
|
|||||||
|
|
||||||
1. `bin/mail/sync.go` (Go, 8 workers) — paginated Gmail/OnlyOffice download.
|
1. `bin/mail/sync.go` (Go, 8 workers) — paginated Gmail/OnlyOffice download.
|
||||||
Gmail attachments key off `body.attachmentId`, not MIME `partId`.
|
Gmail attachments key off `body.attachmentId`, not MIME `partId`.
|
||||||
2. `bin/mail/import.go --from-raw` — message.json → message.md; PDFs via
|
2. `bin/mail/import --from-raw` — message.json → message.md; PDFs via
|
||||||
`pdftotext -layout` (~15ms) with docling subprocess fallback; ICS sidecars
|
`pdftotext -layout` (~15ms) with docling subprocess fallback; ICS sidecars
|
||||||
Latin-1→UTF-8 normalized.
|
Latin-1→UTF-8 normalized.
|
||||||
3. `bin/brain/index.go --rebuild` — fresh rebuild (repo corpus + mail) because ladybug
|
3. `bin/mail/index_mail` — fresh rebuild (repo corpus + mail) because ladybug
|
||||||
corrupts its WAL on bulk-insert into an already-indexed DB. Conversion and
|
corrupts its WAL on bulk-insert into an already-indexed DB. Conversion and
|
||||||
indexing stay separate for crash safety. `bin/mail/index_mail` is a
|
indexing stay separate for crash safety.
|
||||||
deprecation shim.
|
|
||||||
4. Result: 17,835 messages → 28,918 info leafs, FTS + HNSW healthy, searchable
|
4. Result: 17,835 messages → 28,918 info leafs, FTS + HNSW healthy, searchable
|
||||||
via `bin/brain/search.go`.
|
via `bin/kb/search`.
|
||||||
|
|
||||||
## CI/CD pipeline (D15)
|
## CI/CD pipeline (D15)
|
||||||
|
|
||||||
`.github/workflows/ci.yml`:
|
`.github/workflows/ci.yml`:
|
||||||
|
|
||||||
1. go vet + go test ./... (root module; packages without ladybug cgo)
|
1. go vet + go test ./... (Go tools; root module)
|
||||||
2. `go test ./internal/brain/rank` (cgo-free ranking + flag parser)
|
2. `go test ./rank` in `bin/kbsearch` (cgo-free ranking + flag parser; nested module still needs ladybug for the rest)
|
||||||
3. python -m unittest discover -s bin/tools (includes published-docs SoT)
|
3. `go test ./...` in `bin/chats` (Telegram + LinkedIn parsers; nested module)
|
||||||
4. bin/facts/audit self (lexicon internal consistency)
|
4. python -m unittest discover (Py tools)
|
||||||
5. bin/brain/eval.go (recall@5 ≥ 0.95, gates index regressions)
|
5. bin/facts/audit self (lexicon internal consistency)
|
||||||
6. md-docs build/lint if docs tooling arrives.
|
6. bin/kb/eval (recall@5 ≥ 0.95, gates index regressions)
|
||||||
|
7. md-docs build/lint if docs tooling arrives.
|
||||||
|
|
||||||
Feedback loop: every commit → PR → CI → green/gate → merge. Same discipline as
|
Feedback loop: every commit → PR → CI → green/gate → merge. Same discipline as
|
||||||
`db/tech-poc`: contract first where there is an OpenAPI/message shape.
|
`db/tech-poc`: contract first where there is an OpenAPI/message shape.
|
||||||
|
|||||||
@@ -30,9 +30,9 @@ graph TB
|
|||||||
subgraph dph["2dph tools"]
|
subgraph dph["2dph tools"]
|
||||||
EX["bin/facts/extract<br/>2-source pairing"]
|
EX["bin/facts/extract<br/>2-source pairing"]
|
||||||
AU["bin/facts/audit<br/>confidence + staleness"]
|
AU["bin/facts/audit<br/>confidence + staleness"]
|
||||||
IDX["bin/brain/index.go<br/>chunk + embed"]
|
IDX["bin/kb/index<br/>chunk + embed"]
|
||||||
MD["bin/markdown/import.go<br/>mistune leaves"]
|
MD["bin/md/import<br/>mistune leaves"]
|
||||||
SR["bin/brain/search.go<br/>deduction"]
|
SR["bin/kb/search<br/>deduction + --hop"]
|
||||||
end
|
end
|
||||||
|
|
||||||
subgraph store["Ladybug var/kb.lbug"]
|
subgraph store["Ladybug var/kb.lbug"]
|
||||||
@@ -85,23 +85,21 @@ fact; conflicting sources or a single source → `hypothesis` → `(not confirme
|
|||||||
## Deduction search
|
## Deduction search
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
bin/brain/search.go "Matrix federation over HTTPS" # facts → info → web-search
|
bin/kb/search "Matrix federation over HTTPS" # facts → info → web-search
|
||||||
bin/brain/search.go "onlyoffice postgres" --root facts
|
bin/kb/search "what runs on arc-2" --hop 1 # walk graph edges
|
||||||
bin/brain/search.go "where is cs-lexicon" --json | yq '.'
|
bin/kb/search "where is cs-lexicon" --json | yq '.' # YAML by default
|
||||||
bin/brain/get.go <id> --body # full chunk on demand
|
bin/kb/get <id> --body # full chunk on demand
|
||||||
bin/brain/stats.go # index health
|
bin/kb/stats # index health
|
||||||
bin/brain/eval.go # recall@5 gate
|
bin/kb/eval # recall@5 gate
|
||||||
```
|
```
|
||||||
|
|
||||||
`--hop` is not implemented (needs File/FROM_FILE edges); the flag errors instead of walking. `bin/kb/search` is a deprecated wrapper around `bin/brain/search.go`.
|
|
||||||
|
|
||||||
Mail is a first-class corpus (retrievable through the same search):
|
Mail is a first-class corpus (retrievable through the same search):
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
bin/mail/sync.go --source onlyoffice,gmail --workers 8 --out var/mail # raw sync (Go)
|
bin/mail/sync.go --source onlyoffice,gmail --workers 8 --out var/mail # raw sync (Go)
|
||||||
bin/mail/import.go --from-raw var/mail # JSON → markdown
|
bin/mail/import --from-raw var/mail # JSON → markdown
|
||||||
bin/brain/index.go --rebuild # rebuild brain (incl. mail)
|
bin/mail/index_mail # rebuild brain incl. mail
|
||||||
bin/brain/search.go "invoice from last week" # same search over mail leafs
|
bin/kb/search "Mietwagen Nürnberg invoice" # now answers from mail
|
||||||
```
|
```
|
||||||
|
|
||||||
## Storage
|
## Storage
|
||||||
@@ -111,7 +109,7 @@ bin/brain/search.go "invoice from last week" # same s
|
|||||||
readers. **Never `DROP INDEX` FTS/VECTOR** on Ladybug 0.19: DROP leaves
|
readers. **Never `DROP INDEX` FTS/VECTOR** on Ladybug 0.19: DROP leaves
|
||||||
ghost catalog tables (`_0_Leaf_vec_UPPER`) so recreate fails while
|
ghost catalog tables (`_0_Leaf_vec_UPPER`) so recreate fails while
|
||||||
`SHOW_INDEXES` omits HNSW. Fresh indexes = delete `var/kb.lbug` +
|
`SHOW_INDEXES` omits HNSW. Fresh indexes = delete `var/kb.lbug` +
|
||||||
`bin/brain/index.go --rebuild`. Use `ensure_indexes()` after upserts.
|
`bin/kb/index --rebuild`. Use `ensure_indexes()` after upserts.
|
||||||
- **model2vec** — `potion-multilingual-128M` static embeddings (256-dim),
|
- **model2vec** — `potion-multilingual-128M` static embeddings (256-dim),
|
||||||
CPU-fast, deterministic, no Ollama runtime dependency.
|
CPU-fast, deterministic, no Ollama runtime dependency.
|
||||||
- facts and info split semantically by `root` column but written inside the
|
- facts and info split semantically by `root` column but written inside the
|
||||||
@@ -119,10 +117,10 @@ bin/brain/search.go "invoice from last week" # same s
|
|||||||
|
|
||||||
## Tooling conventions
|
## Tooling conventions
|
||||||
|
|
||||||
`bin/{subject}/{method}.go` — self-describing: shebang on line 1, usage comment
|
`bin/{subject}/{method}` — self-describing: shebang on line 1, usage comment
|
||||||
from line 2. Shared code in `internal/`. YAML default output, `--json` for
|
from line 2. bash + python primary; golang via the Go shebang when a compiled
|
||||||
machines. Tests gate every commit. HTTP: `bin/brain/serve.go` (default search
|
helper is right. YAML default output, `--json` for machines. Everything that
|
||||||
binary `var/bin/brain-search`, not Python).
|
touches network/db is read-only, throttled, cached. Tests gate every commit.
|
||||||
|
|
||||||
## Development
|
## Development
|
||||||
|
|
||||||
@@ -138,7 +136,7 @@ Docker (optional, cached model + var volumes):
|
|||||||
```bash
|
```bash
|
||||||
docker compose run --rm brain index # (re)index corpus
|
docker compose run --rm brain index # (re)index corpus
|
||||||
docker compose run --rm brain search "query" # one-shot query
|
docker compose run --rm brain search "query" # one-shot query
|
||||||
docker compose run --rm brain serve # bin/brain/serve.go
|
docker compose run --rm brain serve # async Go HTTP server
|
||||||
docker compose up brain-watch # auto re-index on change
|
docker compose up brain-watch # auto re-index on change
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|||||||
+2
-2
@@ -1,3 +1,3 @@
|
|||||||
// Commands in this directory are shebang mains (search.go, serve.go, index.go,
|
// Commands in this directory are shebang mains (search.go).
|
||||||
// get.go, stats.go, eval.go, watch.go), each behind an exclusive build tag.
|
// search.go is behind the system_ladybug build tag (cgo).
|
||||||
package main
|
package main
|
||||||
|
|||||||
@@ -1,20 +0,0 @@
|
|||||||
//usr/bin/env go run -tags=brain_eval "$0" "$@"; exit
|
|
||||||
//go:build brain_eval
|
|
||||||
//
|
|
||||||
// bin/brain/eval.go - recall@5 gate.
|
|
||||||
//
|
|
||||||
// ./bin/brain/eval.go
|
|
||||||
// ./bin/brain/eval.go --json
|
|
||||||
//
|
|
||||||
// NOTE: never run `gofmt -w` on this file — it breaks the shebang.
|
|
||||||
package main
|
|
||||||
|
|
||||||
import (
|
|
||||||
"os"
|
|
||||||
|
|
||||||
"github.com/eSlider/2dph/internal/cmdbin"
|
|
||||||
)
|
|
||||||
|
|
||||||
func main() {
|
|
||||||
os.Exit(cmdbin.ExecFile("bin/kb/eval", os.Args[1:]))
|
|
||||||
}
|
|
||||||
@@ -1,20 +0,0 @@
|
|||||||
//usr/bin/env go run -tags=brain_get "$0" "$@"; exit
|
|
||||||
//go:build brain_get
|
|
||||||
//
|
|
||||||
// bin/brain/get.go - read one leaf by id.
|
|
||||||
//
|
|
||||||
// ./bin/brain/get.go <id>
|
|
||||||
// ./bin/brain/get.go <id> --body
|
|
||||||
//
|
|
||||||
// NOTE: never run `gofmt -w` on this file — it breaks the shebang.
|
|
||||||
package main
|
|
||||||
|
|
||||||
import (
|
|
||||||
"os"
|
|
||||||
|
|
||||||
"github.com/eSlider/2dph/internal/cmdbin"
|
|
||||||
)
|
|
||||||
|
|
||||||
func main() {
|
|
||||||
os.Exit(cmdbin.ExecFile("bin/kb/get", os.Args[1:]))
|
|
||||||
}
|
|
||||||
@@ -1,24 +0,0 @@
|
|||||||
//usr/bin/env go run -tags=brain_index "$0" "$@"; exit
|
|
||||||
//go:build brain_index
|
|
||||||
//
|
|
||||||
// bin/brain/index.go - rebuild the Ladybug graph (Python write path).
|
|
||||||
//
|
|
||||||
// ./bin/brain/index.go --rebuild
|
|
||||||
// ./bin/brain/index.go --rebuild --with-mail
|
|
||||||
// ./bin/brain/index.go --dry-run --with-mail
|
|
||||||
//
|
|
||||||
// v1 write is always a rebuild when mail is included (live FTS/HNSW + bulk
|
|
||||||
// insert corrupts Ladybug 0.19 WAL). `add` is v2.
|
|
||||||
// NOTE: never run `gofmt -w` on this file — it breaks the shebang.
|
|
||||||
package main
|
|
||||||
|
|
||||||
import (
|
|
||||||
"os"
|
|
||||||
|
|
||||||
"github.com/eSlider/2dph/internal/cmdbin"
|
|
||||||
)
|
|
||||||
|
|
||||||
func main() {
|
|
||||||
args := append([]string{"--with-mail"}, os.Args[1:]...)
|
|
||||||
os.Exit(cmdbin.ExecFile("bin/kb/index", args))
|
|
||||||
}
|
|
||||||
@@ -1,20 +0,0 @@
|
|||||||
//usr/bin/env go run -tags=brain_stats "$0" "$@"; exit
|
|
||||||
//go:build brain_stats
|
|
||||||
//
|
|
||||||
// bin/brain/stats.go - index health.
|
|
||||||
//
|
|
||||||
// ./bin/brain/stats.go
|
|
||||||
// ./bin/brain/stats.go --json
|
|
||||||
//
|
|
||||||
// NOTE: never run `gofmt -w` on this file — it breaks the shebang.
|
|
||||||
package main
|
|
||||||
|
|
||||||
import (
|
|
||||||
"os"
|
|
||||||
|
|
||||||
"github.com/eSlider/2dph/internal/cmdbin"
|
|
||||||
)
|
|
||||||
|
|
||||||
func main() {
|
|
||||||
os.Exit(cmdbin.ExecFile("bin/kb/stats", os.Args[1:]))
|
|
||||||
}
|
|
||||||
@@ -1,20 +0,0 @@
|
|||||||
//usr/bin/env go run -tags=brain_watch "$0" "$@"; exit
|
|
||||||
//go:build brain_watch
|
|
||||||
//
|
|
||||||
// bin/brain/watch.go - re-index when corpus files change.
|
|
||||||
//
|
|
||||||
// ./bin/brain/watch.go [dir...]
|
|
||||||
// KB_WATCH_INTERVAL=15 ./bin/brain/watch.go
|
|
||||||
//
|
|
||||||
// NOTE: never run `gofmt -w` on this file — it breaks the shebang.
|
|
||||||
package main
|
|
||||||
|
|
||||||
import (
|
|
||||||
"os"
|
|
||||||
|
|
||||||
"github.com/eSlider/2dph/bin/watch"
|
|
||||||
)
|
|
||||||
|
|
||||||
func main() {
|
|
||||||
watch.Run(os.Args[1:])
|
|
||||||
}
|
|
||||||
@@ -1,19 +0,0 @@
|
|||||||
//usr/bin/env go run -tags=chats_apply "$0" "$@"; exit
|
|
||||||
//go:build chats_apply
|
|
||||||
//
|
|
||||||
// bin/chats/apply.go - push extracted chat facts to OnlyOffice CRM.
|
|
||||||
//
|
|
||||||
// ./bin/chats/apply.go [--dry-run]
|
|
||||||
//
|
|
||||||
// NOTE: never run `gofmt -w` on this file — it breaks the shebang.
|
|
||||||
package main
|
|
||||||
|
|
||||||
import (
|
|
||||||
"os"
|
|
||||||
|
|
||||||
"github.com/eSlider/2dph/internal/chats"
|
|
||||||
)
|
|
||||||
|
|
||||||
func main() {
|
|
||||||
os.Exit(chats.RunApply(os.Args[1:]))
|
|
||||||
}
|
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
package chats
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"bytes"
|
"bytes"
|
||||||
@@ -24,7 +24,7 @@ type ooContact struct {
|
|||||||
} `json:"commonData"`
|
} `json:"commonData"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func RunApply(args []string) int {
|
func runApply(args []string) int {
|
||||||
fs := flag.NewFlagSet("chats apply", flag.ContinueOnError)
|
fs := flag.NewFlagSet("chats apply", flag.ContinueOnError)
|
||||||
dryRun := fs.Bool("dry-run", false, "show what would be done without writing")
|
dryRun := fs.Bool("dry-run", false, "show what would be done without writing")
|
||||||
help := fs.Bool("help", false, "")
|
help := fs.Bool("help", false, "")
|
||||||
@@ -176,7 +176,7 @@ func RunApply(args []string) int {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func loadFacts() ([]ExtractedFact, error) {
|
func loadFacts() ([]ExtractedFact, error) {
|
||||||
factsPath := filepath.Join(Dir(), "facts", "chat-facts.json")
|
factsPath := filepath.Join(chatsDir(), "facts", "chat-facts.json")
|
||||||
data, err := os.ReadFile(factsPath)
|
data, err := os.ReadFile(factsPath)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if os.IsNotExist(err) {
|
if os.IsNotExist(err) {
|
||||||
@@ -3,7 +3,7 @@
|
|||||||
// These are integration tests using real data and real Telegram API (when
|
// These are integration tests using real data and real Telegram API (when
|
||||||
// credentials are available). They follow the TDD workflow pattern:
|
// credentials are available). They follow the TDD workflow pattern:
|
||||||
// sync → import → facts → verify.
|
// sync → import → facts → verify.
|
||||||
package chats
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
@@ -48,7 +48,7 @@ func TestChatsImport(t *testing.T) {
|
|||||||
t.Cleanup(func() { os.Chdir(cwd) })
|
t.Cleanup(func() { os.Chdir(cwd) })
|
||||||
t.Setenv("KB_ROOT", dir)
|
t.Setenv("KB_ROOT", dir)
|
||||||
|
|
||||||
exitCode := RunImport([]string{})
|
exitCode := runImport([]string{})
|
||||||
if exitCode != 0 {
|
if exitCode != 0 {
|
||||||
t.Fatalf("import exit code %d", exitCode)
|
t.Fatalf("import exit code %d", exitCode)
|
||||||
}
|
}
|
||||||
@@ -140,7 +140,7 @@ func TestChatsImportEmpty(t *testing.T) {
|
|||||||
t.Cleanup(func() { os.Chdir(cwd) })
|
t.Cleanup(func() { os.Chdir(cwd) })
|
||||||
t.Setenv("KB_ROOT", dir)
|
t.Setenv("KB_ROOT", dir)
|
||||||
|
|
||||||
exitCode := RunImport([]string{})
|
exitCode := runImport([]string{})
|
||||||
if exitCode == 0 {
|
if exitCode == 0 {
|
||||||
t.Fatal("expected non-zero exit for empty data dir")
|
t.Fatal("expected non-zero exit for empty data dir")
|
||||||
}
|
}
|
||||||
@@ -171,7 +171,7 @@ func TestChatsRoundTrip(t *testing.T) {
|
|||||||
t.Cleanup(func() { os.Chdir(cwd) })
|
t.Cleanup(func() { os.Chdir(cwd) })
|
||||||
t.Setenv("KB_ROOT", dir)
|
t.Setenv("KB_ROOT", dir)
|
||||||
|
|
||||||
if code := RunImport([]string{}); code != 0 {
|
if code := runImport([]string{}); code != 0 {
|
||||||
t.Fatalf("import exit %d", code)
|
t.Fatalf("import exit %d", code)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1,4 +0,0 @@
|
|||||||
// Commands in this directory are shebang mains (sync.go, import.go, facts.go,
|
|
||||||
// apply.go), each behind an exclusive build tag so `go build ./bin/chats`
|
|
||||||
// does not see two mains. Shared code lives in internal/chats.
|
|
||||||
package main
|
|
||||||
@@ -1,20 +0,0 @@
|
|||||||
//usr/bin/env go run -tags=chats_facts "$0" "$@"; exit
|
|
||||||
//go:build chats_facts
|
|
||||||
//
|
|
||||||
// bin/chats/facts.go - extract phone/email/linkedin facts from JSONL.
|
|
||||||
//
|
|
||||||
// ./bin/chats/facts.go
|
|
||||||
//
|
|
||||||
// Writes var/chats/facts/. Does not index the brain.
|
|
||||||
// NOTE: never run `gofmt -w` on this file — it breaks the shebang.
|
|
||||||
package main
|
|
||||||
|
|
||||||
import (
|
|
||||||
"os"
|
|
||||||
|
|
||||||
"github.com/eSlider/2dph/internal/chats"
|
|
||||||
)
|
|
||||||
|
|
||||||
func main() {
|
|
||||||
os.Exit(chats.RunFacts(os.Args[1:]))
|
|
||||||
}
|
|
||||||
@@ -1,11 +1,13 @@
|
|||||||
package chats
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"bufio"
|
"bufio"
|
||||||
|
"bytes"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"flag"
|
"flag"
|
||||||
"fmt"
|
"fmt"
|
||||||
"os"
|
"os"
|
||||||
|
"os/exec"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"regexp"
|
"regexp"
|
||||||
"strings"
|
"strings"
|
||||||
@@ -75,7 +77,7 @@ type ExtractedFact struct {
|
|||||||
MessageID string `json:"message_id"`
|
MessageID string `json:"message_id"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func RunFacts(args []string) int {
|
func runFacts(args []string) int {
|
||||||
fs := flag.NewFlagSet("chats facts", flag.ContinueOnError)
|
fs := flag.NewFlagSet("chats facts", flag.ContinueOnError)
|
||||||
help := fs.Bool("help", false, "")
|
help := fs.Bool("help", false, "")
|
||||||
fs.SetOutput(os.Stderr)
|
fs.SetOutput(os.Stderr)
|
||||||
@@ -87,7 +89,7 @@ func RunFacts(args []string) int {
|
|||||||
return 0
|
return 0
|
||||||
}
|
}
|
||||||
|
|
||||||
root := Dir()
|
root := chatsDir()
|
||||||
telegramDir := filepath.Join(root, "telegram")
|
telegramDir := filepath.Join(root, "telegram")
|
||||||
|
|
||||||
entries, err := os.ReadDir(telegramDir)
|
entries, err := os.ReadDir(telegramDir)
|
||||||
@@ -147,7 +149,7 @@ func RunFacts(args []string) int {
|
|||||||
}
|
}
|
||||||
fmt.Printf("chats facts: saved to %s\n", factsPath)
|
fmt.Printf("chats facts: saved to %s\n", factsPath)
|
||||||
|
|
||||||
writeFactsMarkdown(allFacts)
|
writeFactsToBrain(root, allFacts)
|
||||||
|
|
||||||
return 0
|
return 0
|
||||||
}
|
}
|
||||||
@@ -271,10 +273,14 @@ func filterFacts(facts []ExtractedFact, factType string) []ExtractedFact {
|
|||||||
return result
|
return result
|
||||||
}
|
}
|
||||||
|
|
||||||
// writeFactsMarkdown stores a sidecar for humans. Brain ingest is
|
func writeFactsToBrain(root string, facts []ExtractedFact) {
|
||||||
// bin/brain/index.go (not this subject).
|
indexScript := filepath.Join(root, "bin", "kb", "index")
|
||||||
func writeFactsMarkdown(facts []ExtractedFact) {
|
if _, err := os.Stat(indexScript); os.IsNotExist(err) {
|
||||||
mdDir := filepath.Join(Dir(), "facts")
|
fmt.Fprintf(os.Stderr, "chats facts: kb/index not found, skipping brain write\n")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
mdDir := filepath.Join(chatsDir(), "facts")
|
||||||
if err := os.MkdirAll(mdDir, 0755); err != nil {
|
if err := os.MkdirAll(mdDir, 0755); err != nil {
|
||||||
fmt.Fprintf(os.Stderr, "chats facts: mkdir %s: %v\n", mdDir, err)
|
fmt.Fprintf(os.Stderr, "chats facts: mkdir %s: %v\n", mdDir, err)
|
||||||
return
|
return
|
||||||
@@ -282,7 +288,7 @@ func writeFactsMarkdown(facts []ExtractedFact) {
|
|||||||
|
|
||||||
var sb strings.Builder
|
var sb strings.Builder
|
||||||
sb.WriteString("---\n")
|
sb.WriteString("---\n")
|
||||||
sb.WriteString("root: info\n")
|
sb.WriteString("root: facts\n")
|
||||||
sb.WriteString("---\n\n")
|
sb.WriteString("---\n\n")
|
||||||
sb.WriteString("# Chat-Derived Facts\n\n")
|
sb.WriteString("# Chat-Derived Facts\n\n")
|
||||||
for _, f := range facts {
|
for _, f := range facts {
|
||||||
@@ -296,5 +302,15 @@ func writeFactsMarkdown(facts []ExtractedFact) {
|
|||||||
fmt.Fprintf(os.Stderr, "chats facts: write %s: %v\n", factsMD, err)
|
fmt.Fprintf(os.Stderr, "chats facts: write %s: %v\n", factsMD, err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
fmt.Printf("chats facts: markdown %s (index via brain, not chats)\n", factsMD)
|
|
||||||
|
cmd := exec.Command(indexScript, "--corpus", mdDir, "--skip-indexes")
|
||||||
|
var outBuf, errBuf bytes.Buffer
|
||||||
|
cmd.Stdout = &outBuf
|
||||||
|
cmd.Stderr = &errBuf
|
||||||
|
cmd.Dir = root
|
||||||
|
if err := cmd.Run(); err != nil {
|
||||||
|
fmt.Fprintf(os.Stderr, "chats facts: brain index: %v\n%s", err, errBuf.String())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
fmt.Printf("chats facts: written to brain (%s)\n", strings.TrimSpace(outBuf.String()))
|
||||||
}
|
}
|
||||||
@@ -1,20 +0,0 @@
|
|||||||
//usr/bin/env go run -tags=chats_import "$0" "$@"; exit
|
|
||||||
//go:build chats_import
|
|
||||||
//
|
|
||||||
// bin/chats/import.go - JSONL → markdown under var/chats/md/.
|
|
||||||
//
|
|
||||||
// ./bin/chats/import.go
|
|
||||||
//
|
|
||||||
// Conversion only. Brain ingest is bin/brain/index.go, not this command.
|
|
||||||
// NOTE: never run `gofmt -w` on this file — it breaks the shebang.
|
|
||||||
package main
|
|
||||||
|
|
||||||
import (
|
|
||||||
"os"
|
|
||||||
|
|
||||||
"github.com/eSlider/2dph/internal/chats"
|
|
||||||
)
|
|
||||||
|
|
||||||
func main() {
|
|
||||||
os.Exit(chats.RunImport(os.Args[1:]))
|
|
||||||
}
|
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
package chats
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"bufio"
|
"bufio"
|
||||||
@@ -13,7 +13,7 @@ import (
|
|||||||
"strings"
|
"strings"
|
||||||
)
|
)
|
||||||
|
|
||||||
func RunImport(args []string) int {
|
func runImport(args []string) int {
|
||||||
fs := flag.NewFlagSet("chats import", flag.ContinueOnError)
|
fs := flag.NewFlagSet("chats import", flag.ContinueOnError)
|
||||||
help := fs.Bool("help", false, "")
|
help := fs.Bool("help", false, "")
|
||||||
fs.SetOutput(os.Stderr)
|
fs.SetOutput(os.Stderr)
|
||||||
@@ -25,7 +25,7 @@ func RunImport(args []string) int {
|
|||||||
return 0
|
return 0
|
||||||
}
|
}
|
||||||
|
|
||||||
root := Dir()
|
root := chatsDir()
|
||||||
mdRoot := filepath.Join(root, "md")
|
mdRoot := filepath.Join(root, "md")
|
||||||
glob := filepath.Join(root, "telegram", "*", "messages.jsonl")
|
glob := filepath.Join(root, "telegram", "*", "messages.jsonl")
|
||||||
|
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"flag"
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"os/exec"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
func runIndex(args []string) int {
|
||||||
|
fs := flag.NewFlagSet("chats index", flag.ContinueOnError)
|
||||||
|
help := fs.Bool("help", false, "")
|
||||||
|
fs.SetOutput(os.Stderr)
|
||||||
|
if err := fs.Parse(args); err != nil {
|
||||||
|
return 2
|
||||||
|
}
|
||||||
|
if *help {
|
||||||
|
fmt.Fprintln(os.Stderr, "usage: chats index")
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
root := repoRoot()
|
||||||
|
mdDir := filepath.Join(chatsDir(), "md")
|
||||||
|
|
||||||
|
_, err := os.Stat(mdDir)
|
||||||
|
if os.IsNotExist(err) {
|
||||||
|
fmt.Fprintf(os.Stderr, "chats index: no chat markdown at %s; run 'chats import' first\n", mdDir)
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
|
||||||
|
indexScript := filepath.Join(root, "bin", "kb", "index")
|
||||||
|
if _, err := os.Stat(indexScript); os.IsNotExist(err) {
|
||||||
|
fmt.Fprintf(os.Stderr, "chats index: %s not found\n", indexScript)
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
|
||||||
|
cmd := exec.Command(indexScript, "--corpus", mdDir)
|
||||||
|
var outBuf, errBuf bytes.Buffer
|
||||||
|
cmd.Stdout = &outBuf
|
||||||
|
cmd.Stderr = &errBuf
|
||||||
|
cmd.Dir = root
|
||||||
|
|
||||||
|
if err := cmd.Run(); err != nil {
|
||||||
|
fmt.Fprintf(os.Stderr, "chats index: %v\n%s", err, errBuf.String())
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
result := strings.TrimSpace(outBuf.String())
|
||||||
|
if result == "" {
|
||||||
|
result = strings.TrimSpace(errBuf.String())
|
||||||
|
}
|
||||||
|
fmt.Printf("chats index: %s\n", result)
|
||||||
|
return 0
|
||||||
|
}
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
package chats
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"bufio"
|
"bufio"
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
package chats
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"errors"
|
"errors"
|
||||||
@@ -0,0 +1,115 @@
|
|||||||
|
// bin/chats - sync, import, index, extract facts, and apply chat data
|
||||||
|
// from Telegram, WhatsApp, LinkedIn into the brain and OnlyOffice CRM.
|
||||||
|
//
|
||||||
|
// Usage:
|
||||||
|
//
|
||||||
|
// chats sync telegram [--limit N] [--since DATE] [--phone PHONE]
|
||||||
|
// chats sync whatsapp [--qr] [--limit N]
|
||||||
|
// chats sync linkedin [--limit N]
|
||||||
|
// chats import # JSONL → MD (all sources)
|
||||||
|
// chats index # rebuild var/kb.lbug with chats
|
||||||
|
// chats facts # extract + cross-check
|
||||||
|
// chats apply [--dry-run] # push to OnlyOffice CRM
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
if len(os.Args) < 2 {
|
||||||
|
usage()
|
||||||
|
os.Exit(2)
|
||||||
|
}
|
||||||
|
cmd := os.Args[1]
|
||||||
|
args := os.Args[2:]
|
||||||
|
switch cmd {
|
||||||
|
case "sync":
|
||||||
|
if len(args) < 1 {
|
||||||
|
usage()
|
||||||
|
os.Exit(2)
|
||||||
|
}
|
||||||
|
platform := args[0]
|
||||||
|
platformArgs := args[1:]
|
||||||
|
switch platform {
|
||||||
|
case "telegram":
|
||||||
|
os.Exit(runSyncTelegram(platformArgs))
|
||||||
|
case "whatsapp":
|
||||||
|
fmt.Fprintf(os.Stderr, "chats: WhatsApp not implemented yet\n")
|
||||||
|
os.Exit(1)
|
||||||
|
case "linkedin":
|
||||||
|
os.Exit(runSyncLinkedIn(platformArgs))
|
||||||
|
default:
|
||||||
|
fmt.Fprintf(os.Stderr, "chats: unknown platform %q\n", platform)
|
||||||
|
os.Exit(2)
|
||||||
|
}
|
||||||
|
case "import":
|
||||||
|
os.Exit(runImport(args))
|
||||||
|
case "index":
|
||||||
|
os.Exit(runIndex(args))
|
||||||
|
case "facts":
|
||||||
|
os.Exit(runFacts(args))
|
||||||
|
case "apply":
|
||||||
|
os.Exit(runApply(args))
|
||||||
|
case "help", "-h", "--help":
|
||||||
|
usage()
|
||||||
|
return
|
||||||
|
default:
|
||||||
|
fmt.Fprintf(os.Stderr, "chats: unknown command %q\n", cmd)
|
||||||
|
usage()
|
||||||
|
os.Exit(2)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func usage() {
|
||||||
|
w := os.Stderr
|
||||||
|
fmt.Fprintln(w, `Usage: chats <command> [args]
|
||||||
|
|
||||||
|
Commands:
|
||||||
|
sync telegram [--limit N] [--since DATE] [--phone PHONE]
|
||||||
|
sync whatsapp [--qr] [--limit N]
|
||||||
|
sync linkedin [--limit N]
|
||||||
|
import JSONL → MD (all sources)
|
||||||
|
index rebuild var/kb.lbug with chats
|
||||||
|
facts extract + cross-check facts
|
||||||
|
apply [--dry-run] push to OnlyOffice CRM
|
||||||
|
|
||||||
|
Output layout:
|
||||||
|
var/chats/<platform>/<chat_id>/messages.jsonl
|
||||||
|
var/chats/md/<platform>/<chat_name>/messages.md`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// repoRoot locates the 2dph project root by walking up from the binary.
|
||||||
|
func repoRoot() string {
|
||||||
|
if v := os.Getenv("KB_ROOT"); v != "" {
|
||||||
|
return v
|
||||||
|
}
|
||||||
|
wd, err := os.Getwd()
|
||||||
|
if err != nil {
|
||||||
|
return "."
|
||||||
|
}
|
||||||
|
for i := 0; i < 10; i++ {
|
||||||
|
if _, err := os.Stat(wd + "/var"); err == nil {
|
||||||
|
return wd
|
||||||
|
}
|
||||||
|
if _, err := os.Stat(wd + "/.git"); err == nil {
|
||||||
|
return wd
|
||||||
|
}
|
||||||
|
parent := wd
|
||||||
|
if idx := strings.LastIndex(wd, "/"); idx >= 0 {
|
||||||
|
parent = wd[:idx]
|
||||||
|
}
|
||||||
|
if parent == wd {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
wd = parent
|
||||||
|
}
|
||||||
|
return "."
|
||||||
|
}
|
||||||
|
|
||||||
|
// chatsDir returns var/chats under the repo root.
|
||||||
|
func chatsDir() string {
|
||||||
|
return repoRoot() + "/var/chats"
|
||||||
|
}
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
package chats
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"bufio"
|
"bufio"
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
package chats
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
@@ -1,41 +0,0 @@
|
|||||||
//usr/bin/env go run -tags=chats_sync "$0" "$@"; exit
|
|
||||||
//go:build chats_sync
|
|
||||||
//
|
|
||||||
// bin/chats/sync.go - download chat messages to var/chats/<platform>/.
|
|
||||||
//
|
|
||||||
// ./bin/chats/sync.go telegram [--limit N] [--phone PHONE]
|
|
||||||
// ./bin/chats/sync.go linkedin [--limit N] [--refresh]
|
|
||||||
//
|
|
||||||
// NOTE: never run `gofmt -w` on this file — it breaks the shebang.
|
|
||||||
package main
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
"os"
|
|
||||||
|
|
||||||
"github.com/eSlider/2dph/internal/chats"
|
|
||||||
)
|
|
||||||
|
|
||||||
func main() {
|
|
||||||
if len(os.Args) < 2 {
|
|
||||||
fmt.Fprintln(os.Stderr, `usage: bin/chats/sync.go telegram|linkedin [flags]`)
|
|
||||||
os.Exit(2)
|
|
||||||
}
|
|
||||||
platform := os.Args[1]
|
|
||||||
args := os.Args[2:]
|
|
||||||
switch platform {
|
|
||||||
case "telegram":
|
|
||||||
os.Exit(chats.RunSyncTelegram(args))
|
|
||||||
case "linkedin":
|
|
||||||
os.Exit(chats.RunSyncLinkedIn(args))
|
|
||||||
case "whatsapp":
|
|
||||||
fmt.Fprintln(os.Stderr, "chats: WhatsApp not implemented yet")
|
|
||||||
os.Exit(1)
|
|
||||||
case "help", "-h", "--help":
|
|
||||||
fmt.Fprintln(os.Stderr, `usage: bin/chats/sync.go telegram|linkedin [flags]`)
|
|
||||||
return
|
|
||||||
default:
|
|
||||||
fmt.Fprintf(os.Stderr, "chats: unknown platform %q\n", platform)
|
|
||||||
os.Exit(2)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
package chats
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
@@ -11,7 +11,7 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
func RunSyncTelegram(args []string) int {
|
func runSyncTelegram(args []string) int {
|
||||||
fs := flag.NewFlagSet("chats sync telegram", flag.ContinueOnError)
|
fs := flag.NewFlagSet("chats sync telegram", flag.ContinueOnError)
|
||||||
limit := fs.Int("limit", 0, "max messages per chat (0 = all)")
|
limit := fs.Int("limit", 0, "max messages per chat (0 = all)")
|
||||||
phone := fs.String("phone", "", "phone number (default env TELEGRAM_PHONE)")
|
phone := fs.String("phone", "", "phone number (default env TELEGRAM_PHONE)")
|
||||||
@@ -78,7 +78,7 @@ func RunSyncTelegram(args []string) int {
|
|||||||
defer cancel()
|
defer cancel()
|
||||||
|
|
||||||
start := time.Now()
|
start := time.Now()
|
||||||
if err := src.Sync(ctx, Dir(), *limit); err != nil {
|
if err := src.Sync(ctx, chatsDir(), *limit); err != nil {
|
||||||
fmt.Fprintf(os.Stderr, "chats sync telegram: %v\n", err)
|
fmt.Fprintf(os.Stderr, "chats sync telegram: %v\n", err)
|
||||||
return 1
|
return 1
|
||||||
}
|
}
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
package chats
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
@@ -28,7 +28,7 @@ func checkLinkedInSession(userDataDir string) (bool, error) {
|
|||||||
return false, nil
|
return false, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func RunSyncLinkedIn(args []string) int {
|
func runSyncLinkedIn(args []string) int {
|
||||||
fs := flag.NewFlagSet("chats sync linkedin", flag.ContinueOnError)
|
fs := flag.NewFlagSet("chats sync linkedin", flag.ContinueOnError)
|
||||||
limit := fs.Int("limit", 0, "max messages per conversation (0 = all)")
|
limit := fs.Int("limit", 0, "max messages per conversation (0 = all)")
|
||||||
refresh := fs.Bool("refresh", false, "refresh session from live webtop browser before sync")
|
refresh := fs.Bool("refresh", false, "refresh session from live webtop browser before sync")
|
||||||
@@ -72,7 +72,7 @@ func RunSyncLinkedIn(args []string) int {
|
|||||||
defer cancel()
|
defer cancel()
|
||||||
|
|
||||||
start := time.Now()
|
start := time.Now()
|
||||||
if err := src.Sync(ctx, Dir(), *limit); err != nil {
|
if err := src.Sync(ctx, chatsDir(), *limit); err != nil {
|
||||||
fmt.Fprintf(os.Stderr, "chats sync linkedin: %v\n", err)
|
fmt.Fprintf(os.Stderr, "chats sync linkedin: %v\n", err)
|
||||||
return 1
|
return 1
|
||||||
}
|
}
|
||||||
Vendored
@@ -2,10 +2,10 @@
|
|||||||
# bin/docker-entrypoint - run 2dph tools inside the container.
|
# bin/docker-entrypoint - run 2dph tools inside the container.
|
||||||
#
|
#
|
||||||
# brain shell (default)
|
# brain shell (default)
|
||||||
# brain search <q> bin/brain/search.go
|
# brain search <q> bin/kb/search
|
||||||
# brain index bin/kb/index --with-mail
|
# brain index bin/kb/index
|
||||||
# brain watch <dir> compiled /app/bin/watch (bin/brain/watch.go)
|
# brain watch <dir> watchdog re-indexer (bin/kb/watch)
|
||||||
# brain serve compiled /app/bin/serve (bin/brain/serve.go)
|
# brain serve async Go HTTP server (bin/serve)
|
||||||
# brain extract bin/facts/extract (docker×compose pairing)
|
# brain extract bin/facts/extract (docker×compose pairing)
|
||||||
# brain audit bin/facts/audit
|
# brain audit bin/facts/audit
|
||||||
#
|
#
|
||||||
@@ -18,7 +18,7 @@ shift || true
|
|||||||
case "$CMD" in
|
case "$CMD" in
|
||||||
shell) exec bash ;;
|
shell) exec bash ;;
|
||||||
search) exec "$KB_PY" /app/bin/kb/search "$@" ;;
|
search) exec "$KB_PY" /app/bin/kb/search "$@" ;;
|
||||||
index) exec "$KB_PY" /app/bin/kb/index --with-mail "$@" ;;
|
index) exec "$KB_PY" /app/bin/kb/index "$@" ;;
|
||||||
watch) exec /app/bin/watch "$@" ;;
|
watch) exec /app/bin/watch "$@" ;;
|
||||||
serve) exec /app/bin/serve "$@" ;;
|
serve) exec /app/bin/serve "$@" ;;
|
||||||
extract) exec "$KB_PY" /app/bin/facts/extract "$@" ;;
|
extract) exec "$KB_PY" /app/bin/facts/extract "$@" ;;
|
||||||
|
|||||||
+3
-19
@@ -26,7 +26,6 @@ from kblib import ( # noqa: E402
|
|||||||
open_readonly, stats,
|
open_readonly, stats,
|
||||||
)
|
)
|
||||||
from mdleaves import read_markdown, to_all, walk_markdown # noqa: E402
|
from mdleaves import read_markdown, to_all, walk_markdown # noqa: E402
|
||||||
from mailleafs import from_mail_root # noqa: E402
|
|
||||||
|
|
||||||
CORPUS_DEFAULTS = ["README.md", "PLAN.md", "AGENTS.md", "docs", "skills"]
|
CORPUS_DEFAULTS = ["README.md", "PLAN.md", "AGENTS.md", "docs", "skills"]
|
||||||
|
|
||||||
@@ -100,9 +99,6 @@ def main(argv: list[str]) -> int:
|
|||||||
p = argparse.ArgumentParser(description="build the 2dph brain index")
|
p = argparse.ArgumentParser(description="build the 2dph brain index")
|
||||||
p.add_argument("--corpus", action="append", help="extra markdown dir/file to index (may repeat)")
|
p.add_argument("--corpus", action="append", help="extra markdown dir/file to index (may repeat)")
|
||||||
p.add_argument("--rebuild", action="store_true", help="fresh db + indexes")
|
p.add_argument("--rebuild", action="store_true", help="fresh db + indexes")
|
||||||
p.add_argument("--with-mail", action="store_true", help="include var/mail message.md leafs")
|
|
||||||
p.add_argument("--since", default="", help="with --with-mail, only messages dated >= YYYY-MM-DD")
|
|
||||||
p.add_argument("--dry-run", action="store_true", help="count leafs, write nothing")
|
|
||||||
p.add_argument(
|
p.add_argument(
|
||||||
"--skip-indexes",
|
"--skip-indexes",
|
||||||
action="store_true",
|
action="store_true",
|
||||||
@@ -113,26 +109,14 @@ def main(argv: list[str]) -> int:
|
|||||||
a = p.parse_args(argv)
|
a = p.parse_args(argv)
|
||||||
|
|
||||||
from kblib import DB_PATH, VAR
|
from kblib import DB_PATH, VAR
|
||||||
|
VAR.mkdir(exist_ok=True)
|
||||||
|
if a.rebuild and DB_PATH.exists():
|
||||||
|
DB_PATH.unlink()
|
||||||
|
|
||||||
leafs = load_corpus(ROOT)
|
leafs = load_corpus(ROOT)
|
||||||
if a.corpus:
|
if a.corpus:
|
||||||
for source in a.corpus:
|
for source in a.corpus:
|
||||||
leafs.extend(load_corpus_glob(source))
|
leafs.extend(load_corpus_glob(source))
|
||||||
mail_n = 0
|
|
||||||
if a.with_mail:
|
|
||||||
mail = from_mail_root(ROOT / "var" / "mail", since=a.since)
|
|
||||||
mail_n = len(mail)
|
|
||||||
leafs.extend(mail)
|
|
||||||
|
|
||||||
if a.dry_run:
|
|
||||||
msg = {"indexed": 0, "corpus_total": len(leafs), "mail_leafs": mail_n, "dry_run": True}
|
|
||||||
print(json.dumps(msg, indent=2) if a.json else
|
|
||||||
f"brain/index: {len(leafs)} leafs would be indexed (mail={mail_n})")
|
|
||||||
return 0
|
|
||||||
|
|
||||||
VAR.mkdir(exist_ok=True)
|
|
||||||
if a.rebuild and DB_PATH.exists():
|
|
||||||
DB_PATH.unlink()
|
|
||||||
|
|
||||||
db, conn = connect(DB_PATH, read_only=False)
|
db, conn = connect(DB_PATH, read_only=False)
|
||||||
init_schema(conn)
|
init_schema(conn)
|
||||||
|
|||||||
+1
-1
@@ -1,5 +1,5 @@
|
|||||||
//usr/bin/env go run "$0" "$@"; exit
|
//usr/bin/env go run "$0" "$@"; exit
|
||||||
// bin/kb/watch.go — deprecated. Use bin/brain/watch.go.
|
// bin/kb/watch.go - re-index the 2dph brain when corpus files change.
|
||||||
//
|
//
|
||||||
// Usage:
|
// Usage:
|
||||||
//
|
//
|
||||||
|
|||||||
+2
-2
@@ -15,8 +15,8 @@ Writes one directory per message: var/mail/{folder}/{message_id}/
|
|||||||
attachments/ raw attachment files (zips unpacked to _unpacked/)
|
attachments/ raw attachment files (zips unpacked to _unpacked/)
|
||||||
attachments/*.md converted attachment content
|
attachments/*.md converted attachment content
|
||||||
|
|
||||||
Indexing is a separate step (`bin/brain/index.go --rebuild`): conversion can
|
Indexing is a separate step (bin/mail/index_mail): conversion can crash in
|
||||||
crash in native docling and must not leave the brain DB mid-transaction.
|
native docling and must not leave the brain DB mid-transaction.
|
||||||
|
|
||||||
Requires ONLYOFFICE_URL/USER/PASS in .env (or env). Idempotent: a message
|
Requires ONLYOFFICE_URL/USER/PASS in .env (or env). Idempotent: a message
|
||||||
already present (message.md exists) is skipped unless --force.
|
already present (message.md exists) is skipped unless --force.
|
||||||
|
|||||||
@@ -1,20 +0,0 @@
|
|||||||
//usr/bin/env go run -tags=mail_import "$0" "$@"; exit
|
|
||||||
//go:build mail_import
|
|
||||||
//
|
|
||||||
// bin/mail/import.go - message.json → markdown (no brain write).
|
|
||||||
//
|
|
||||||
// ./bin/mail/import.go --from-raw var/mail
|
|
||||||
//
|
|
||||||
// Indexing is bin/brain/index.go --rebuild, not this command.
|
|
||||||
// NOTE: never run `gofmt -w` on this file — it breaks the shebang.
|
|
||||||
package main
|
|
||||||
|
|
||||||
import (
|
|
||||||
"os"
|
|
||||||
|
|
||||||
"github.com/eSlider/2dph/internal/cmdbin"
|
|
||||||
)
|
|
||||||
|
|
||||||
func main() {
|
|
||||||
os.Exit(cmdbin.ExecFile("bin/mail/import", os.Args[1:]))
|
|
||||||
}
|
|
||||||
+120
-11
@@ -1,26 +1,135 @@
|
|||||||
#!/usr/bin/env python3
|
#!/usr/bin/env python3
|
||||||
"""mail/index_mail — deprecated. Use bin/brain/index.go --rebuild --with-mail.
|
"""mail/index_mail - rebuild the brain with every markdown under var/mail.
|
||||||
|
|
||||||
Ladybug corrupts its WAL on bulk-insert into an already-indexed DB, so this
|
Ladybug corrupts its WAL when brand-new leafs are bulk-inserted while the
|
||||||
shim always rebuilds (repo corpus + var/mail). Conversion stays in mail/import.
|
FTS/VECTOR indexes already exist, so indexing ALWAYS runs as a fresh rebuild
|
||||||
|
(repo corpus + var/mail), matching the proven-safe `kb/index --rebuild` path.
|
||||||
|
Conversion and indexing stay separate: conversion can crash in native docling
|
||||||
|
and must not leave the brain DB mid-transaction.
|
||||||
|
|
||||||
|
bin/mail/index_mail rebuild the index incl. all mail
|
||||||
|
bin/mail/index_mail --dry-run count without writing
|
||||||
|
bin/mail/index_mail --limit N cap messages included
|
||||||
|
bin/mail/index_mail --since D only messages dated >= D (YYYY-MM-DD)
|
||||||
"""
|
"""
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import os
|
import argparse
|
||||||
|
import json
|
||||||
import sys
|
import sys
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
ROOT = Path(__file__).resolve().parents[2]
|
ROOT = Path(__file__).resolve().parents[2]
|
||||||
|
sys.path.insert(0, str(ROOT / "bin" / "tools"))
|
||||||
|
|
||||||
|
from kblib import DB_PATH, VAR, connect, ensure_indexes, init_schema, stats, upsert_leaf # noqa: E402
|
||||||
|
from mdleaves import read_markdown, to_all, walk_markdown # noqa: E402
|
||||||
|
|
||||||
|
|
||||||
|
def msg_date(md: Path) -> str:
|
||||||
|
j = md.parent / "message.json"
|
||||||
|
try:
|
||||||
|
d = json.loads(j.read_text(encoding="utf-8"))
|
||||||
|
return (d.get("receivedDate") or d.get("receivedAt") or "")[:10]
|
||||||
|
except Exception:
|
||||||
|
return ""
|
||||||
|
|
||||||
|
|
||||||
|
def mail_leafs(limit: int, since: str, repo: str = "ooMail") -> list[dict]:
|
||||||
|
root = ROOT / "var" / "mail"
|
||||||
|
mds = sorted(root.rglob("message.md"))
|
||||||
|
if since:
|
||||||
|
mds = [m for m in mds if msg_date(m) >= since]
|
||||||
|
if limit:
|
||||||
|
mds = mds[:limit]
|
||||||
|
leafs: list[dict] = []
|
||||||
|
for md in mds:
|
||||||
|
files = [md] + sorted((md.parent / "attachments").glob("*.md"))
|
||||||
|
for f in files:
|
||||||
|
if not f.exists():
|
||||||
|
continue
|
||||||
|
for lf in to_all(read_markdown(f), f, repo=repo):
|
||||||
|
lf["source"] = f"ooMail:{md.parent.name}:{f.name}"
|
||||||
|
lf["how"] = "mail/import"
|
||||||
|
leafs.append(lf)
|
||||||
|
return leafs
|
||||||
|
|
||||||
|
|
||||||
def main(argv: list[str]) -> int:
|
def main(argv: list[str]) -> int:
|
||||||
print(
|
p = argparse.ArgumentParser(description="rebuild the brain incl. all mail")
|
||||||
"bin/mail/index_mail is deprecated; use bin/brain/index.go --rebuild --with-mail",
|
p.add_argument("--dry-run", action="store_true", help="count only, write nothing")
|
||||||
file=sys.stderr,
|
p.add_argument("--limit", type=int, default=0, help="cap messages included")
|
||||||
)
|
p.add_argument("--since", default="", help="only messages dated >= YYYY-MM-DD")
|
||||||
index = ROOT / "bin" / "kb" / "index"
|
p.add_argument("--json", action="store_true")
|
||||||
os.execv(sys.executable, [sys.executable, str(index), "--rebuild", "--with-mail", *argv])
|
a = p.parse_args(argv)
|
||||||
return 1
|
|
||||||
|
mail = mail_leafs(a.limit, a.since)
|
||||||
|
if a.dry_run:
|
||||||
|
print(f"mail/index_mail: {len(mail)} mail leafs would be indexed")
|
||||||
|
return 0
|
||||||
|
|
||||||
|
# Fresh rebuild: delete DB, index repo corpus + mail, create indexes once
|
||||||
|
# at the end. Never insert into an already-indexed DB (WAL corruption).
|
||||||
|
VAR.mkdir(exist_ok=True)
|
||||||
|
if DB_PATH.exists():
|
||||||
|
DB_PATH.unlink()
|
||||||
|
|
||||||
|
corpus = _load_corpus()
|
||||||
|
leafs = corpus + mail
|
||||||
|
|
||||||
|
db, conn = connect(DB_PATH, read_only=False)
|
||||||
|
init_schema(conn)
|
||||||
|
embed = _embedder()
|
||||||
|
done, total = _index_leafs(conn, leafs, embed)
|
||||||
|
ensure_indexes(conn)
|
||||||
|
s = stats(conn)
|
||||||
|
conn.close()
|
||||||
|
db.close()
|
||||||
|
|
||||||
|
result = {"indexed": done, "corpus_total": total, "mail_leafs": len(mail),
|
||||||
|
**{k: v for k, v in s.items() if k in ("total", "by_root")}}
|
||||||
|
print(json.dumps(result, indent=2) if a.json else
|
||||||
|
f"mail/index_mail: indexed {done}/{total} leafs (mail={len(mail)}); db total {s['total']}")
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
CORPUS_DEFAULTS = ["README.md", "PLAN.md", "AGENTS.md", "docs", "skills"]
|
||||||
|
|
||||||
|
|
||||||
|
def _load_corpus() -> list[dict]:
|
||||||
|
files: list[Path] = []
|
||||||
|
for entry in CORPUS_DEFAULTS:
|
||||||
|
p = ROOT / entry
|
||||||
|
if p.is_file():
|
||||||
|
files.append(p)
|
||||||
|
elif p.is_dir():
|
||||||
|
files.extend(walk_markdown(p))
|
||||||
|
leafs: list[dict] = []
|
||||||
|
for path in files:
|
||||||
|
try:
|
||||||
|
leafs.extend(to_all(read_markdown(path), path, repo="eSlider/2dph"))
|
||||||
|
except OSError as e:
|
||||||
|
print(f"mail/index_mail: skip {path}: {e}", file=sys.stderr)
|
||||||
|
return leafs
|
||||||
|
|
||||||
|
|
||||||
|
def _index_leafs(conn, leafs: list[dict], embed_fn) -> tuple[int, int]:
|
||||||
|
count = 0
|
||||||
|
for lf in leafs:
|
||||||
|
query = f"{lf['heading']}\n\n{lf['text']}"
|
||||||
|
emb = embed_fn(lf["text"]) if lf["text"] else None
|
||||||
|
upsert_leaf(conn, text=query, root="info", confidence="confirmed",
|
||||||
|
source=lf["source"], source_rev="mail" if lf.get("how") == "mail/import" else "working-tree",
|
||||||
|
how=lf.get("how", "kb/index"), loc=lf["source"], type_=lf.get("type", "reference"),
|
||||||
|
embedding=emb)
|
||||||
|
count += 1
|
||||||
|
return count, len(leafs)
|
||||||
|
|
||||||
|
|
||||||
|
def _embedder():
|
||||||
|
from model2vec import StaticModel
|
||||||
|
model = StaticModel.from_pretrained("minishlab/potion-multilingual-128M")
|
||||||
|
return lambda text: model.encode([text])[0].astype(float).tolist()
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
|
|||||||
+1
-1
@@ -6,7 +6,7 @@
|
|||||||
// ./bin/mail/sync.go --dry-run
|
// ./bin/mail/sync.go --dry-run
|
||||||
//
|
//
|
||||||
// Writes raw message.json + attachments under var/mail/<folder>/<id>/; run
|
// Writes raw message.json + attachments under var/mail/<folder>/<id>/; run
|
||||||
// bin/mail/import.go --from-raw afterwards to convert everything to markdown.
|
// bin/mail/import --from-raw afterwards to convert everything to markdown.
|
||||||
//
|
//
|
||||||
// Shebang trick: first line is a Go `//` comment; the real code lives in the
|
// Shebang trick: first line is a Go `//` comment; the real code lives in the
|
||||||
// importable package (module path, never a relative import).
|
// importable package (module path, never a relative import).
|
||||||
|
|||||||
@@ -1,3 +0,0 @@
|
|||||||
// Commands in this directory are shebang mains (import.go), tagged so
|
|
||||||
// `go build ./bin/markdown` does not see two mains.
|
|
||||||
package main
|
|
||||||
@@ -1,20 +0,0 @@
|
|||||||
//usr/bin/env go run -tags=markdown_import "$0" "$@"; exit
|
|
||||||
//go:build markdown_import
|
|
||||||
//
|
|
||||||
// bin/markdown/import.go - split markdown into leafs (mistune).
|
|
||||||
//
|
|
||||||
// ./bin/markdown/import.go [dir]
|
|
||||||
// ./bin/markdown/import.go --files a.md,b.md --json
|
|
||||||
//
|
|
||||||
// NOTE: never run `gofmt -w` on this file — it breaks the shebang.
|
|
||||||
package main
|
|
||||||
|
|
||||||
import (
|
|
||||||
"os"
|
|
||||||
|
|
||||||
"github.com/eSlider/2dph/internal/cmdbin"
|
|
||||||
)
|
|
||||||
|
|
||||||
func main() {
|
|
||||||
os.Exit(cmdbin.ExecFile("bin/md/import", os.Args[1:]))
|
|
||||||
}
|
|
||||||
@@ -1,2 +0,0 @@
|
|||||||
// Commands in this directory are shebang mains (query.go).
|
|
||||||
package main
|
|
||||||
@@ -1,20 +0,0 @@
|
|||||||
//usr/bin/env go run -tags=postgres_query "$0" "$@"; exit
|
|
||||||
//go:build postgres_query
|
|
||||||
//
|
|
||||||
// bin/postgres/query.go - read-only Postgres as YAML.
|
|
||||||
//
|
|
||||||
// ./bin/postgres/query.go --profile onlyoffice -c 'SELECT 1'
|
|
||||||
//
|
|
||||||
// Profiles: $HOME/.config/brain/db-profiles.yml (credentials stay out of git).
|
|
||||||
// NOTE: never run `gofmt -w` on this file — it breaks the shebang.
|
|
||||||
package main
|
|
||||||
|
|
||||||
import (
|
|
||||||
"os"
|
|
||||||
|
|
||||||
"github.com/eSlider/2dph/internal/cmdbin"
|
|
||||||
)
|
|
||||||
|
|
||||||
func main() {
|
|
||||||
os.Exit(cmdbin.ExecFile("bin/db/psql-yq", os.Args[1:]))
|
|
||||||
}
|
|
||||||
+4
-4
@@ -135,7 +135,7 @@ def create_fts_and_vector(conn: ladybug.Connection, force: bool = False) -> None
|
|||||||
|
|
||||||
`force=True` is accepted for API compatibility but does **not** drop.
|
`force=True` is accepted for API compatibility but does **not** drop.
|
||||||
Fresh indexes require deleting `var/kb.lbug` and rebuilding
|
Fresh indexes require deleting `var/kb.lbug` and rebuilding
|
||||||
(`bin/brain/index.go --rebuild`).
|
(`bin/kb/index --rebuild`).
|
||||||
"""
|
"""
|
||||||
del force # API compat; DROP is unsafe — see docstring
|
del force # API compat; DROP is unsafe — see docstring
|
||||||
names = leaf_index_names(conn)
|
names = leaf_index_names(conn)
|
||||||
@@ -145,7 +145,7 @@ def create_fts_and_vector(conn: ladybug.Connection, force: bool = False) -> None
|
|||||||
except Exception as e:
|
except Exception as e:
|
||||||
raise RuntimeError(
|
raise RuntimeError(
|
||||||
"CREATE_FTS_INDEX failed (often ghost catalog after DROP INDEX). "
|
"CREATE_FTS_INDEX failed (often ghost catalog after DROP INDEX). "
|
||||||
"Delete var/kb.lbug and run bin/brain/index.go --rebuild. "
|
"Delete var/kb.lbug and run bin/kb/index --rebuild. "
|
||||||
f"Cause: {e}"
|
f"Cause: {e}"
|
||||||
) from e
|
) from e
|
||||||
if "Leaf_vec" not in names:
|
if "Leaf_vec" not in names:
|
||||||
@@ -158,7 +158,7 @@ def create_fts_and_vector(conn: ladybug.Connection, force: bool = False) -> None
|
|||||||
raise RuntimeError(
|
raise RuntimeError(
|
||||||
"CREATE_VECTOR_INDEX failed (often ghost catalog after DROP INDEX "
|
"CREATE_VECTOR_INDEX failed (often ghost catalog after DROP INDEX "
|
||||||
"Leaf.Leaf_vec → `_0_Leaf_vec_UPPER already exists in catalog`). "
|
"Leaf.Leaf_vec → `_0_Leaf_vec_UPPER already exists in catalog`). "
|
||||||
"Delete var/kb.lbug and run bin/brain/index.go --rebuild. "
|
"Delete var/kb.lbug and run bin/kb/index --rebuild. "
|
||||||
f"Cause: {e}"
|
f"Cause: {e}"
|
||||||
) from e
|
) from e
|
||||||
names = leaf_index_names(conn)
|
names = leaf_index_names(conn)
|
||||||
@@ -237,6 +237,6 @@ def stats(conn: ladybug.Connection) -> dict:
|
|||||||
|
|
||||||
def open_readonly() -> tuple[ladybug.Database, ladybug.Connection]:
|
def open_readonly() -> tuple[ladybug.Database, ladybug.Connection]:
|
||||||
if not DB_PATH.exists():
|
if not DB_PATH.exists():
|
||||||
raise FileNotFoundError(f"{DB_PATH} missing - run bin/brain/index.go --rebuild first")
|
raise FileNotFoundError(f"{DB_PATH} missing - run bin/kb/index first")
|
||||||
db, conn = connect(read_only=True)
|
db, conn = connect(read_only=True)
|
||||||
return db, conn
|
return db, conn
|
||||||
@@ -1,37 +0,0 @@
|
|||||||
"""Mail markdown under var/mail → info leafs. Conversion stays off the brain DB."""
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import json
|
|
||||||
from pathlib import Path
|
|
||||||
|
|
||||||
from mdleaves import read_markdown, to_all
|
|
||||||
|
|
||||||
|
|
||||||
def msg_date(md: Path) -> str:
|
|
||||||
j = md.parent / "message.json"
|
|
||||||
try:
|
|
||||||
d = json.loads(j.read_text(encoding="utf-8"))
|
|
||||||
return (d.get("receivedDate") or d.get("receivedAt") or "")[:10]
|
|
||||||
except (OSError, json.JSONDecodeError, TypeError):
|
|
||||||
return ""
|
|
||||||
|
|
||||||
|
|
||||||
def from_mail_root(root: Path, limit: int = 0, since: str = "", repo: str = "ooMail") -> list[dict]:
|
|
||||||
if not root.is_dir():
|
|
||||||
return []
|
|
||||||
mds = sorted(root.rglob("message.md"))
|
|
||||||
if since:
|
|
||||||
mds = [m for m in mds if msg_date(m) >= since]
|
|
||||||
if limit:
|
|
||||||
mds = mds[:limit]
|
|
||||||
leafs: list[dict] = []
|
|
||||||
for md in mds:
|
|
||||||
files = [md] + sorted((md.parent / "attachments").glob("*.md"))
|
|
||||||
for f in files:
|
|
||||||
if not f.exists():
|
|
||||||
continue
|
|
||||||
for lf in to_all(read_markdown(f), f, repo=repo):
|
|
||||||
lf["source"] = f"ooMail:{md.parent.name}:{f.name}"
|
|
||||||
lf["how"] = "mail/import"
|
|
||||||
leafs.append(lf)
|
|
||||||
return leafs
|
|
||||||
@@ -34,60 +34,3 @@ class BinLayoutTest(unittest.TestCase):
|
|||||||
def test_no_main_go_under_bin_brain(self) -> None:
|
def test_no_main_go_under_bin_brain(self) -> None:
|
||||||
main = ROOT / "bin" / "brain" / "main.go"
|
main = ROOT / "bin" / "brain" / "main.go"
|
||||||
self.assertFalse(main.exists(), "bin/brain/main.go is not a method")
|
self.assertFalse(main.exists(), "bin/brain/main.go is not a method")
|
||||||
|
|
||||||
def test_chats_methods_are_shebangs_not_main(self) -> None:
|
|
||||||
chats = ROOT / "bin" / "chats"
|
|
||||||
self.assertFalse(
|
|
||||||
(chats / "main.go").exists(),
|
|
||||||
"bin/chats/main.go is a dispatcher, not a method",
|
|
||||||
)
|
|
||||||
self.assertFalse(
|
|
||||||
(chats / "index_cmd.go").exists(),
|
|
||||||
"chats index is a brain write hiding under the wrong subject",
|
|
||||||
)
|
|
||||||
for method in ("sync.go", "import.go", "facts.go", "apply.go"):
|
|
||||||
p = chats / method
|
|
||||||
self.assertTrue(p.is_file(), f"missing bin/chats/{method}")
|
|
||||||
first = p.read_text().splitlines()[0]
|
|
||||||
self.assertTrue(
|
|
||||||
first.startswith("//usr/bin/env go run"),
|
|
||||||
f"{method} shebang, got {first!r}",
|
|
||||||
)
|
|
||||||
|
|
||||||
def test_chats_lib_lives_in_internal(self) -> None:
|
|
||||||
self.assertTrue(
|
|
||||||
(ROOT / "internal" / "chats" / "linkedin.go").is_file(),
|
|
||||||
"LinkedIn parser must live in internal/chats",
|
|
||||||
)
|
|
||||||
self.assertFalse(
|
|
||||||
(ROOT / "bin" / "chats" / "linkedin.go").exists(),
|
|
||||||
"parser must not stay under bin/chats as a second main",
|
|
||||||
)
|
|
||||||
|
|
||||||
def _assert_shebang(self, rel: str) -> None:
|
|
||||||
p = ROOT / rel
|
|
||||||
self.assertTrue(p.is_file(), f"missing {rel}")
|
|
||||||
first = p.read_text().splitlines()[0]
|
|
||||||
self.assertTrue(
|
|
||||||
first.startswith("//usr/bin/env go run"),
|
|
||||||
f"{rel} shebang, got {first!r}",
|
|
||||||
)
|
|
||||||
|
|
||||||
def test_brain_methods_are_shebangs(self) -> None:
|
|
||||||
for method in ("index.go", "get.go", "stats.go", "eval.go", "watch.go"):
|
|
||||||
self._assert_shebang(f"bin/brain/{method}")
|
|
||||||
|
|
||||||
def test_mail_import_is_shebang_not_brain_write(self) -> None:
|
|
||||||
self._assert_shebang("bin/mail/import.go")
|
|
||||||
index_mail = (ROOT / "bin" / "mail" / "index_mail").read_text()
|
|
||||||
self.assertIn(
|
|
||||||
"bin/brain/index.go",
|
|
||||||
index_mail,
|
|
||||||
"index_mail must point at bin/brain/index.go",
|
|
||||||
)
|
|
||||||
|
|
||||||
def test_markdown_import_is_shebang(self) -> None:
|
|
||||||
self._assert_shebang("bin/markdown/import.go")
|
|
||||||
|
|
||||||
def test_postgres_query_is_shebang(self) -> None:
|
|
||||||
self._assert_shebang("bin/postgres/query.go")
|
|
||||||
|
|||||||
@@ -1,46 +0,0 @@
|
|||||||
"""Mail markdown → leafs (no Ladybug). Brain index --with-mail uses this."""
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import json
|
|
||||||
import sys
|
|
||||||
import tempfile
|
|
||||||
import unittest
|
|
||||||
from pathlib import Path
|
|
||||||
|
|
||||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
|
||||||
|
|
||||||
import mailleafs # noqa: E402
|
|
||||||
|
|
||||||
|
|
||||||
class MailLeafsTest(unittest.TestCase):
|
|
||||||
def test_message_md_becomes_info_leaf(self) -> None:
|
|
||||||
root = Path(tempfile.mkdtemp())
|
|
||||||
msg = root / "inbox" / "alice-1"
|
|
||||||
msg.mkdir(parents=True)
|
|
||||||
(msg / "message.json").write_text(
|
|
||||||
json.dumps({"receivedDate": "2026-01-15T10:00:00Z", "subject": "Hello"}),
|
|
||||||
encoding="utf-8",
|
|
||||||
)
|
|
||||||
(msg / "message.md").write_text(
|
|
||||||
"---\nroot: info\n---\n\n# Hello\n\nFrom Alice to Bob.\n",
|
|
||||||
encoding="utf-8",
|
|
||||||
)
|
|
||||||
leafs = mailleafs.from_mail_root(root)
|
|
||||||
self.assertEqual(len(leafs), 1)
|
|
||||||
self.assertIn("Alice", leafs[0]["text"])
|
|
||||||
self.assertTrue(leafs[0]["source"].startswith("ooMail:"))
|
|
||||||
self.assertEqual(leafs[0]["how"], "mail/import")
|
|
||||||
|
|
||||||
def test_since_filters_by_message_json_date(self) -> None:
|
|
||||||
root = Path(tempfile.mkdtemp())
|
|
||||||
for name, day in (("old", "2025-01-01"), ("new", "2026-06-01")):
|
|
||||||
d = root / "inbox" / name
|
|
||||||
d.mkdir(parents=True)
|
|
||||||
(d / "message.json").write_text(
|
|
||||||
json.dumps({"receivedDate": f"{day}T00:00:00Z"}),
|
|
||||||
encoding="utf-8",
|
|
||||||
)
|
|
||||||
(d / "message.md").write_text(f"# {name}\n\nbody\n", encoding="utf-8")
|
|
||||||
leafs = mailleafs.from_mail_root(root, since="2026-01-01")
|
|
||||||
self.assertEqual(len(leafs), 1)
|
|
||||||
self.assertIn("new", leafs[0]["text"])
|
|
||||||
@@ -1,57 +0,0 @@
|
|||||||
"""Published docs must match live commands (Gitea SoT, brain/search, no fake --hop)."""
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import re
|
|
||||||
import unittest
|
|
||||||
from pathlib import Path
|
|
||||||
|
|
||||||
ROOT = Path(__file__).resolve().parents[2]
|
|
||||||
|
|
||||||
|
|
||||||
class PublishedDocsTest(unittest.TestCase):
|
|
||||||
def test_readme_points_issues_at_gitea(self) -> None:
|
|
||||||
text = (ROOT / "README.md").read_text()
|
|
||||||
self.assertIn(
|
|
||||||
"https://git.produktor.io/eSlider/2dph/issues",
|
|
||||||
text,
|
|
||||||
"README must point issues at Gitea",
|
|
||||||
)
|
|
||||||
|
|
||||||
def test_plan_d15_names_gitea_origin(self) -> None:
|
|
||||||
text = (ROOT / "PLAN.md").read_text()
|
|
||||||
self.assertIn("D15", text)
|
|
||||||
self.assertIn("git.produktor.io/eSlider/2dph", text)
|
|
||||||
|
|
||||||
def test_readme_primary_search_is_brain(self) -> None:
|
|
||||||
text = (ROOT / "README.md").read_text()
|
|
||||||
self.assertIn(
|
|
||||||
"bin/brain/search.go",
|
|
||||||
text,
|
|
||||||
"README deduction search must name bin/brain/search.go",
|
|
||||||
)
|
|
||||||
|
|
||||||
def test_readme_index_is_brain_not_index_mail(self) -> None:
|
|
||||||
text = (ROOT / "README.md").read_text()
|
|
||||||
self.assertIn("bin/brain/index.go", text)
|
|
||||||
self.assertNotIn(
|
|
||||||
"bin/mail/index_mail",
|
|
||||||
text,
|
|
||||||
"mail index is a brain write; README must name bin/brain/index.go",
|
|
||||||
)
|
|
||||||
|
|
||||||
def test_docs_do_not_claim_hop_walks(self) -> None:
|
|
||||||
paths = [
|
|
||||||
ROOT / "README.md",
|
|
||||||
ROOT / "docs" / "design.md",
|
|
||||||
ROOT / "skills" / "kb-search" / "SKILL.md",
|
|
||||||
ROOT / "skills" / "diataxis-docs" / "SKILL.md",
|
|
||||||
]
|
|
||||||
# Command-style `--hop 1` / `--hop N` plus follow/walk = the old lie.
|
|
||||||
# Honest "not implemented" notes must not match.
|
|
||||||
lie = re.compile(r"--hop (?:N|1).*(?:follow|walk)", re.I | re.S)
|
|
||||||
for path in paths:
|
|
||||||
text = path.read_text()
|
|
||||||
self.assertIsNone(
|
|
||||||
lie.search(text),
|
|
||||||
f"{path.relative_to(ROOT)} still claims --hop walks the graph",
|
|
||||||
)
|
|
||||||
+4
-4
@@ -1,4 +1,4 @@
|
|||||||
// Package watch polls corpus directories for changes and re-runs brain/index.
|
// Package watch polls corpus directories for changes and re-runs bin/kb/index.
|
||||||
//
|
//
|
||||||
// Port of the former bin/kb-watch bash script to an importable, testable Go
|
// Port of the former bin/kb-watch bash script to an importable, testable Go
|
||||||
// package. Polls file mtimes (no inotify deps); cheap and reliable.
|
// package. Polls file mtimes (no inotify deps); cheap and reliable.
|
||||||
@@ -18,8 +18,8 @@ import (
|
|||||||
type Options struct {
|
type Options struct {
|
||||||
Dirs []string
|
Dirs []string
|
||||||
Interval time.Duration
|
Interval time.Duration
|
||||||
// IndexCmd is the index command template. %s is replaced by the repo
|
// IndexCmd is the kb/index command template. %s is replaced by the repo
|
||||||
// root (from KB_ROOT). Defaults to `python3 <root>/bin/kb/index --with-mail`.
|
// root (from KB_ROOT). Defaults to `python3 <root>/bin/kb/index`.
|
||||||
IndexCmd string
|
IndexCmd string
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -67,7 +67,7 @@ func fromEnv(args []string) Options {
|
|||||||
if pys == "" {
|
if pys == "" {
|
||||||
pys = "python3"
|
pys = "python3"
|
||||||
}
|
}
|
||||||
opts.IndexCmd = pys + " <root>/bin/kb/index --with-mail"
|
opts.IndexCmd = pys + " <root>/bin/kb/index"
|
||||||
return opts
|
return opts
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -3,7 +3,6 @@ package watch
|
|||||||
import (
|
import (
|
||||||
"os"
|
"os"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"strings"
|
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
)
|
)
|
||||||
@@ -44,10 +43,7 @@ func TestFromEnvDefaults(t *testing.T) {
|
|||||||
if opts.Interval != 30*time.Second {
|
if opts.Interval != 30*time.Second {
|
||||||
t.Fatalf("default interval = %s, want 30s", opts.Interval)
|
t.Fatalf("default interval = %s, want 30s", opts.Interval)
|
||||||
}
|
}
|
||||||
if !strings.Contains(opts.IndexCmd, "kb/index") {
|
if opts.IndexCmd == "" {
|
||||||
t.Fatalf("default index cmd = %q, want kb/index", opts.IndexCmd)
|
t.Fatal("default index cmd is empty")
|
||||||
}
|
|
||||||
if !strings.Contains(opts.IndexCmd, "--with-mail") {
|
|
||||||
t.Fatalf("default index cmd must include --with-mail, got %q", opts.IndexCmd)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,7 +8,4 @@ Brain/ops/eSlider stack. Facts need proof or they are
|
|||||||
- [design](design.md) — schema, deduction model, sources
|
- [design](design.md) — schema, deduction model, sources
|
||||||
- [Gitea issues](https://git.produktor.io/eSlider/2dph/issues) — work board (origin)
|
- [Gitea issues](https://git.produktor.io/eSlider/2dph/issues) — work board (origin)
|
||||||
|
|
||||||
Search: `bin/brain/search.go "query"` (HTTP: `bin/brain/serve.go`). `--hop` is
|
|
||||||
not a walk; the flag errors until File/FROM_FILE edges exist.
|
|
||||||
|
|
||||||
Published docs live here and mirror the project state.
|
Published docs live here and mirror the project state.
|
||||||
|
|||||||
@@ -15,10 +15,9 @@ OO_CLI (default: $HOME/go/bin/oo)
|
|||||||
## Quick reference
|
## Quick reference
|
||||||
|
|
||||||
```
|
```
|
||||||
./bin/chats/sync.go telegram --limit 100
|
./bin/chat sync telegram --limit 100
|
||||||
./bin/chats/import.go
|
./bin/chat import
|
||||||
./bin/chats/facts.go
|
./bin/chat index
|
||||||
./bin/chats/apply.go --dry-run
|
./bin/chat facts
|
||||||
|
./bin/chat apply --dry-run
|
||||||
```
|
```
|
||||||
|
|
||||||
JSONL → markdown only. Brain ingest is `bin/brain/index.go` (not a `chats index`).
|
|
||||||
|
|||||||
@@ -0,0 +1,33 @@
|
|||||||
|
# CRM association proof (oo CLI ↔ corpus)
|
||||||
|
|
||||||
|
Proven with `oo` (eslider/go-onlyoffice) against the OnlyOffice portal
|
||||||
|
(`office.produktor.io`). Portal CRM is the SSOT for company ↔ person ↔
|
||||||
|
project associations; the corpus SoT (`eslider/cv/projects/knowledge-mesh-seed.yaml`)
|
||||||
|
is the second, independent source. Facts that can be backed by both are
|
||||||
|
written to the brain under `root=facts` by `bin/facts/crm`.
|
||||||
|
|
||||||
|
## What was verified
|
||||||
|
|
||||||
|
- Logical counts (portal MySQL): 1300 contacts = 897 persons + 404 companies,
|
||||||
|
198 projects, 998 deals, 939 project↔contact links.
|
||||||
|
- Every client company linked to a project has ≥1 person underneath.
|
||||||
|
- Every person `company_id` resolves to an existing company.
|
||||||
|
- Corpus org list (9) maps 1:1 onto CRM companies:
|
||||||
|
ProProdukt SL / produktor.io, Dyvenia, Immowelt AG, WhereGroup,
|
||||||
|
Keynote SIGOS, D2S/SYSTEMS, GRID, Pack und Cup, Markets Platform.
|
||||||
|
- 78 person↔company association facts written to the brain
|
||||||
|
(`how=crm-crosscheck`, `type=association`). Recall@5 in `bin/kb/eval` = 1.0.
|
||||||
|
|
||||||
|
## Mistakes found
|
||||||
|
|
||||||
|
| # | Mistake | Fix |
|
||||||
|
|---|---------|-----|
|
||||||
|
| 1 | Duplicate legal entity `GoldenRatio.Exchange` (contact 759) vs `Golden Ratio Exchange` (763); 3 deals (211, 287, 559) were linked to 759 | `oo contacts merge 759 763` — 763 kept, 759 removed, deal links re-pointed to 763 |
|
||||||
|
| 2 | `env/`-wide: OnlyOffice creds file used wrong UX (user `eslider`, password with `$2` suffix) making `oo` auth fail | `.env` fixed to `eslider@gmail.com` + clean password; `.env` stays gitignored |
|
||||||
|
|
||||||
|
## Gates after fix
|
||||||
|
|
||||||
|
- `uv run python -m unittest discover -s bin/tools -t .` → 26 tests OK
|
||||||
|
- `bin/facts/audit self` + `bin/facts/audit db` → ok
|
||||||
|
- `bin/kb/eval` → recall@5 = 1.0
|
||||||
|
- `go test ./...` (bin/server + bin/watch) → ok
|
||||||
+3
-3
@@ -17,14 +17,14 @@ as one consistent state.
|
|||||||
## Deduction search
|
## Deduction search
|
||||||
|
|
||||||
```
|
```
|
||||||
bin/brain/search.go "question"
|
bin/kb/search "question"
|
||||||
1. facts root — confirmed answers only → return with evidence links
|
1. facts root — confirmed answers only → return with evidence links
|
||||||
2. info root — supporting narrative → snippets, marked (not confirmed)
|
2. info root — supporting narrative → snippets, marked (not confirmed)
|
||||||
3. web-search — second independent source → upgrade hypothesis to confirmed
|
3. web-search — second independent source → upgrade hypothesis to confirmed
|
||||||
```
|
```
|
||||||
|
|
||||||
`--hop` is not implemented yet (needs File/FROM_FILE edges). The flag is an
|
`--hop N` follows graph edges (sibling leaves under a heading, owning file,
|
||||||
error; it is not a graph walk.
|
`related:` files, vector-neighbour leaves) — the deduction walk.
|
||||||
|
|
||||||
## Who / What / How / Where / When + evidence
|
## Who / What / How / Where / When + evidence
|
||||||
|
|
||||||
|
|||||||
@@ -1,39 +0,0 @@
|
|||||||
package chats
|
|
||||||
|
|
||||||
import (
|
|
||||||
"os"
|
|
||||||
"strings"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Root locates the 2dph project root (KB_ROOT, or walk up for var/ or .git).
|
|
||||||
func Root() string {
|
|
||||||
if v := os.Getenv("KB_ROOT"); v != "" {
|
|
||||||
return v
|
|
||||||
}
|
|
||||||
wd, err := os.Getwd()
|
|
||||||
if err != nil {
|
|
||||||
return "."
|
|
||||||
}
|
|
||||||
for i := 0; i < 10; i++ {
|
|
||||||
if _, err := os.Stat(wd + "/var"); err == nil {
|
|
||||||
return wd
|
|
||||||
}
|
|
||||||
if _, err := os.Stat(wd + "/.git"); err == nil {
|
|
||||||
return wd
|
|
||||||
}
|
|
||||||
parent := wd
|
|
||||||
if idx := strings.LastIndex(wd, "/"); idx >= 0 {
|
|
||||||
parent = wd[:idx]
|
|
||||||
}
|
|
||||||
if parent == wd {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
wd = parent
|
|
||||||
}
|
|
||||||
return "."
|
|
||||||
}
|
|
||||||
|
|
||||||
// Dir is var/chats under the project root.
|
|
||||||
func Dir() string {
|
|
||||||
return Root() + "/var/chats"
|
|
||||||
}
|
|
||||||
@@ -1,54 +0,0 @@
|
|||||||
package cmdbin
|
|
||||||
|
|
||||||
import (
|
|
||||||
"errors"
|
|
||||||
"os"
|
|
||||||
"os/exec"
|
|
||||||
"path/filepath"
|
|
||||||
"strings"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Root is the 2dph checkout (KB_ROOT, or walk up for .git / var).
|
|
||||||
func Root() string {
|
|
||||||
if v := os.Getenv("KB_ROOT"); v != "" {
|
|
||||||
return v
|
|
||||||
}
|
|
||||||
wd, err := os.Getwd()
|
|
||||||
if err != nil {
|
|
||||||
return "."
|
|
||||||
}
|
|
||||||
for i := 0; i < 10; i++ {
|
|
||||||
if _, err := os.Stat(filepath.Join(wd, ".git")); err == nil {
|
|
||||||
return wd
|
|
||||||
}
|
|
||||||
if _, err := os.Stat(filepath.Join(wd, "var")); err == nil {
|
|
||||||
return wd
|
|
||||||
}
|
|
||||||
parent := filepath.Dir(wd)
|
|
||||||
if parent == wd {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
wd = parent
|
|
||||||
}
|
|
||||||
return "."
|
|
||||||
}
|
|
||||||
|
|
||||||
// ExecFile runs repo-relative path (python/bash shebang scripts) with stdio.
|
|
||||||
func ExecFile(rel string, args []string) int {
|
|
||||||
path := filepath.Join(Root(), filepath.FromSlash(rel))
|
|
||||||
cmd := exec.Command(path, args...)
|
|
||||||
cmd.Stdin = os.Stdin
|
|
||||||
cmd.Stdout = os.Stdout
|
|
||||||
cmd.Stderr = os.Stderr
|
|
||||||
cmd.Dir = Root()
|
|
||||||
if err := cmd.Run(); err != nil {
|
|
||||||
if ee, ok := err.(*exec.ExitError); ok {
|
|
||||||
return ee.ExitCode()
|
|
||||||
}
|
|
||||||
if errors.Is(err, os.ErrNotExist) || strings.Contains(err.Error(), "no such file") {
|
|
||||||
return 127
|
|
||||||
}
|
|
||||||
return 1
|
|
||||||
}
|
|
||||||
return 0
|
|
||||||
}
|
|
||||||
@@ -1,34 +0,0 @@
|
|||||||
package cmdbin
|
|
||||||
|
|
||||||
import (
|
|
||||||
"os"
|
|
||||||
"path/filepath"
|
|
||||||
"testing"
|
|
||||||
)
|
|
||||||
|
|
||||||
func TestRootHonorsKBROOT(t *testing.T) {
|
|
||||||
dir := t.TempDir()
|
|
||||||
t.Setenv("KB_ROOT", dir)
|
|
||||||
if got := Root(); got != dir {
|
|
||||||
t.Fatalf("Root() = %q, want %q", got, dir)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestExecFileMissingIs127(t *testing.T) {
|
|
||||||
t.Setenv("KB_ROOT", t.TempDir())
|
|
||||||
if code := ExecFile("no/such-tool", nil); code != 127 {
|
|
||||||
t.Fatalf("exit = %d, want 127", code)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestExecFileRuns(t *testing.T) {
|
|
||||||
root := t.TempDir()
|
|
||||||
script := filepath.Join(root, "echo.sh")
|
|
||||||
if err := os.WriteFile(script, []byte("#!/bin/sh\nexit 3\n"), 0o755); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
t.Setenv("KB_ROOT", root)
|
|
||||||
if code := ExecFile("echo.sh", nil); code != 3 {
|
|
||||||
t.Fatalf("exit = %d, want 3", code)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -30,11 +30,12 @@ related:
|
|||||||
---
|
---
|
||||||
```
|
```
|
||||||
|
|
||||||
`bin/brain/index.go` reads this. `type` becomes a searchable column. `related:` is
|
`bin/kb/index` reads this. `type` becomes a searchable column and `related`
|
||||||
frontmatter for humans; graph hops from it are not implemented yet.
|
becomes a graph edge:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
bin/brain/search.go "deploy"
|
bin/kb/search "deploy" --type howto
|
||||||
|
bin/kb/search "Stecktafel" --hop 1 # follow links and related
|
||||||
```
|
```
|
||||||
|
|
||||||
## Audit checklist
|
## Audit checklist
|
||||||
@@ -45,7 +46,8 @@ bin/brain/search.go "deploy"
|
|||||||
The indexer chunks on H2, so split files also search better.
|
The indexer chunks on H2, so split files also search better.
|
||||||
3. Is `status: archive` set on anything superseded? Archived files stay indexed
|
3. Is `status: archive` set on anything superseded? Archived files stay indexed
|
||||||
but stop competing with current ones for a reader's attention.
|
but stop competing with current ones for a reader's attention.
|
||||||
4. Does every explanation link the reference it explains, and vice versa?
|
4. Does every explanation link the reference it explains, and vice versa? That
|
||||||
|
link is what `--hop 1` walks.
|
||||||
|
|
||||||
## Rule
|
## Rule
|
||||||
|
|
||||||
|
|||||||
+13
-14
@@ -2,10 +2,9 @@
|
|||||||
name: kb-search
|
name: kb-search
|
||||||
description: >-
|
description: >-
|
||||||
Deduction search over the 2dph brain (Ladybug graph: ops corpus, portfolio,
|
Deduction search over the 2dph brain (Ladybug graph: ops corpus, portfolio,
|
||||||
ssh hosts) with bin/brain/search.go instead of reading files or grepping
|
ssh hosts) with bin/kb/search instead of reading files or grepping repos.
|
||||||
repos. Use whenever a question starts with "where is", "what runs on",
|
Use whenever a question starts with "where is", "what runs on", "which file
|
||||||
"which file describes", "who is", "how is X done", before opening any
|
describes", "who is", "how is X done", before opening any documentation.
|
||||||
documentation.
|
|
||||||
---
|
---
|
||||||
|
|
||||||
# kb-search — deduction over facts and info
|
# kb-search — deduction over facts and info
|
||||||
@@ -23,24 +22,24 @@ second independent source when local roots cannot confirm. An answer is
|
|||||||
`(not confirmed)`.
|
`(not confirmed)`.
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
bin/brain/search.go "Matrix federation" # pointers + snippets, YAML
|
bin/kb/search "Matrix federation" # pointers + snippets, YAML
|
||||||
bin/brain/search.go "onlyoffice postgres" --root facts # restrict to confirmed
|
bin/kb/search "what runs on arc-2" --hop 1 # follow graph edges
|
||||||
bin/brain/search.go "where is cs-lexicon" --json | yq '.[].ref'
|
bin/kb/search "onlyoffice postgres" --root facts # restrict to confirmed
|
||||||
bin/brain/get.go <id> --body # full chunk only when needed
|
bin/kb/search "where is cs-lexicon" --json | yq '.[].ref'
|
||||||
bin/brain/stats.go # index health
|
bin/kb/get <id> --body # full chunk only when needed
|
||||||
bin/brain/eval.go # recall@5 >= 0.95 gate
|
bin/kb/stats # index health
|
||||||
|
bin/kb/eval # recall@5 >= 0.95 gate
|
||||||
```
|
```
|
||||||
|
|
||||||
`bin/kb/search` is a deprecated wrapper. `--hop` errors (File/FROM_FILE edges
|
|
||||||
are not wired yet); do not treat it as a graph walk.
|
|
||||||
|
|
||||||
## Rules
|
## Rules
|
||||||
|
|
||||||
- Search before you read. Never grep a repo for a concept the graph covers.
|
- Search before you read. Never grep a repo for a concept the graph covers.
|
||||||
- `--root facts` returns only confirmed evidence-linked answers. Default shows
|
- `--root facts` returns only confirmed evidence-linked answers. Default shows
|
||||||
facts first, then info leafs clearly marked `(not confirmed)`.
|
facts first, then info leafs clearly marked `(not confirmed)`.
|
||||||
- If recall looks wrong, run `bin/brain/eval.go`; it gates control questions and
|
- If recall looks wrong, run `bin/kb/eval`; it gates control questions and
|
||||||
should stay at or above 95% recall@5.
|
should stay at or above 95% recall@5.
|
||||||
|
- `--hop N` follows sibling leaves, owning files, `related:` links and
|
||||||
|
vector-neighbours — that is the deduction walk, not random expansion.
|
||||||
- Escalate to `web-search` (the `web-search` skill) as the independent second
|
- Escalate to `web-search` (the `web-search` skill) as the independent second
|
||||||
source when both local roots cannot confirm; never report an unconfirmed
|
source when both local roots cannot confirm; never report an unconfirmed
|
||||||
single-source local answer as fact.
|
single-source local answer as fact.
|
||||||
@@ -18,10 +18,9 @@ bin/web/search "postgres partial index" --lang en --fresh year
|
|||||||
|
|
||||||
## Web or knowledge base
|
## Web or knowledge base
|
||||||
|
|
||||||
`bin/brain/search.go` holds our own facts: the ops stack, portfolio, ssh hosts,
|
`bin/kb/search` holds our own facts: the ops stack, portfolio, ssh hosts, the
|
||||||
the lexicon. Go there first. Reach for `bin/web/search` when the answer is
|
lexicon. Go there first. Reach for `bin/web/search` when the answer is outside
|
||||||
outside our repos: upstream library behaviour, vendor documentation, public
|
our repos: upstream library behaviour, vendor documentation, public standards.
|
||||||
standards.
|
|
||||||
|
|
||||||
Keep the two apart. A finding is stronger when the reader can see that one
|
Keep the two apart. A finding is stronger when the reader can see that one
|
||||||
source was ours and one was not.
|
source was ours and one was not.
|
||||||
|
|||||||
Reference in New Issue
Block a user