mirror of
https://github.com/samvallad33/vestige.git
synced 2026-06-20 21:18:08 +02:00
Compare commits
48 commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5c2db045f6 | ||
|
|
d23870d906 | ||
|
|
8e4f4052cc | ||
|
|
4e893c02ff | ||
|
|
50e7f2d0fb | ||
|
|
22d0d192eb | ||
|
|
ef2073d4a4 | ||
|
|
536776c9d6 | ||
|
|
05f0050ad8 | ||
|
|
2757010d6d | ||
|
|
5e18304184 | ||
|
|
ea5ed28081 | ||
|
|
c60233961d | ||
|
|
b34203bcc5 | ||
|
|
093bb2d4b5 | ||
|
|
194fc6e4c0 | ||
|
|
a4a6e877c5 | ||
|
|
5715f585fd | ||
|
|
01fa882760 | ||
|
|
e1f3796523 | ||
|
|
b45ea819d7 | ||
|
|
efbea25133 | ||
|
|
6c7d56b4cf | ||
|
|
16903f3ab4 | ||
|
|
31890278d3 | ||
|
|
47de61f2d2 | ||
|
|
51f08264f7 | ||
|
|
c23d7a309c | ||
|
|
b01269db22 | ||
|
|
5aa261398d | ||
|
|
241dfdd6cb | ||
|
|
603efdcb2c | ||
|
|
a355da99a6 | ||
|
|
6a37586c5f | ||
|
|
67f9550e6c | ||
|
|
00511948ff | ||
|
|
d8de7daf11 | ||
|
|
c9f457dd94 | ||
|
|
cd496e562c | ||
|
|
8c18231a20 | ||
|
|
3df930ca7e | ||
|
|
21f0b29bae | ||
|
|
fc0681ed0f | ||
|
|
9ef8afdb20 | ||
|
|
697ade5b02 | ||
|
|
c584ec8afe | ||
|
|
9c633c172b | ||
|
|
0d273c5641 |
113 changed files with 34461 additions and 481 deletions
4
.github/workflows/release.yml
vendored
4
.github/workflows/release.yml
vendored
|
|
@ -31,7 +31,7 @@ jobs:
|
||||||
- target: x86_64-pc-windows-msvc
|
- target: x86_64-pc-windows-msvc
|
||||||
os: windows-latest
|
os: windows-latest
|
||||||
archive: zip
|
archive: zip
|
||||||
cargo_flags: ""
|
cargo_flags: "--no-default-features --features embeddings,ort-download"
|
||||||
needs_onnxruntime: false
|
needs_onnxruntime: false
|
||||||
# Intel Mac uses the ort-dynamic feature to runtime-link against a
|
# Intel Mac uses the ort-dynamic feature to runtime-link against a
|
||||||
# system libonnxruntime (Homebrew), sidestepping the missing
|
# system libonnxruntime (Homebrew), sidestepping the missing
|
||||||
|
|
@ -51,7 +51,7 @@ jobs:
|
||||||
- name: Checkout
|
- name: Checkout
|
||||||
uses: actions/checkout@v4
|
uses: actions/checkout@v4
|
||||||
with:
|
with:
|
||||||
ref: ${{ github.event.inputs.tag || github.ref }}
|
ref: ${{ github.event_name == 'workflow_dispatch' && github.sha || github.event.inputs.tag || github.ref }}
|
||||||
|
|
||||||
- name: Setup pnpm
|
- name: Setup pnpm
|
||||||
uses: pnpm/action-setup@v4
|
uses: pnpm/action-setup@v4
|
||||||
|
|
|
||||||
3
.gitignore
vendored
3
.gitignore
vendored
|
|
@ -139,3 +139,6 @@ apps/dashboard/node_modules/
|
||||||
# =============================================================================
|
# =============================================================================
|
||||||
fastembed-rs/
|
fastembed-rs/
|
||||||
.mcp.json
|
.mcp.json
|
||||||
|
|
||||||
|
.claude/
|
||||||
|
.codebase-memory/
|
||||||
|
|
|
||||||
172
CHANGELOG.md
172
CHANGELOG.md
|
|
@ -7,6 +7,178 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
||||||
|
|
||||||
## [Unreleased]
|
## [Unreleased]
|
||||||
|
|
||||||
|
## [2.1.27] - 2026-06-19 — "External-Source Connectors"
|
||||||
|
|
||||||
|
Roadmap [#57](https://github.com/samvallad33/vestige/issues/57), **Phases 1–4
|
||||||
|
(complete)**: Vestige can now act as a durable, local, semantically-searchable
|
||||||
|
retrieval layer over an external system of record — GitHub Issues and Redmine —
|
||||||
|
without replacing it. The external system stays canonical; Vestige **indexes,
|
||||||
|
connects, retrieves, and cites back** to the source record.
|
||||||
|
|
||||||
|
Unlike a live ticket-system MCP proxy (which holds no state and is rate-limited
|
||||||
|
per query), Vestige keeps a durable embedded index: searchable **offline**,
|
||||||
|
**semantically**, joinable with the rest of your memory, temporally versioned,
|
||||||
|
and re-syncable **idempotently** with no duplication. To our knowledge no other
|
||||||
|
local-first memory layer combines native connectors, external-URL provenance,
|
||||||
|
content-hash idempotent sync, and tombstoning of vanished records.
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
- **`source_sync` MCP tool** — index an external system into Vestige.
|
||||||
|
- GitHub: `{"source": "github", "repo": "owner/name"}` indexes every issue +
|
||||||
|
its comments. Auth via `GITHUB_TOKEN` (public repos work tokenless at a
|
||||||
|
lower rate limit).
|
||||||
|
- Redmine: `{"source": "redmine", "project": "<id>"}` indexes a project's
|
||||||
|
issues + journals (comments and status/assignment history). Host from
|
||||||
|
`REDMINE_URL`, auth from `REDMINE_API_KEY`.
|
||||||
|
- Re-running updates changed issues in place (no duplicates); `reconcile:
|
||||||
|
true` tombstones issues no longer visible upstream.
|
||||||
|
- **Source-aware investigation filters on `search`** (Phase 4) — filter results
|
||||||
|
by `source_system`, `source_project`, `source_id`, `source_type`,
|
||||||
|
`source_author`, a `source_updated_after`/`source_updated_before` date range,
|
||||||
|
and `source_status` (`valid` / `tombstoned` / `any`). Status, tracker, and
|
||||||
|
priority remain filterable via the existing `tag_prefix` (the connectors emit
|
||||||
|
`status:`/`tracker:`/`priority:`/`label:` tags). Applied as post-filters;
|
||||||
|
non-connector memories are excluded from a source-scoped query.
|
||||||
|
- **Source envelope** on every memory — structured, machine-readable provenance
|
||||||
|
(`source_system`, `source_id`, `source_url`, `source_updated_at`,
|
||||||
|
`content_hash`, `synced_at`, `source_project`, `source_type`, `source_author`)
|
||||||
|
distinct from the legacy free-form `source` label. Search results gain a
|
||||||
|
`sourceRecord` object (with the canonical `url`) **only** for
|
||||||
|
connector-ingested memories, so an agent can cite and follow the source.
|
||||||
|
- **Idempotent sync primitives** (`vestige-core`): `upsert_by_source` (keyed on
|
||||||
|
`(source_system, source_id)`, content-hash change detection), per-connector
|
||||||
|
cursor checkpoints (`connector_cursors`), and `reconcile_source_tombstones`
|
||||||
|
(invalidate-don't-delete via the bitemporal `valid_until`, so a vanished
|
||||||
|
record is retained for audit but drops out of current retrieval).
|
||||||
|
- **Connector contract** (`vestige_core::connectors`) — a small source-agnostic
|
||||||
|
`Connector` trait + `run_sync` driver (cursor overlap window, incremental
|
||||||
|
paging, optional deletion reconcile) with two reference connectors behind the
|
||||||
|
optional `connectors` cargo feature (on by default in the MCP server, off in
|
||||||
|
the core library's default features so non-connector consumers link no HTTP
|
||||||
|
client):
|
||||||
|
- **GitHub Issues** — `state=all`, `since` cursor, Link-header pagination,
|
||||||
|
drops PRs, host-pinned next-url.
|
||||||
|
- **Redmine** — `status_id=*` (open + closed), hex-encoded `updated_on>=`
|
||||||
|
cursor, `offset` pagination, per-issue detail fetch for journals (the list
|
||||||
|
endpoint omits them), `X-Redmine-API-Key` header auth.
|
||||||
|
|
||||||
|
### Database
|
||||||
|
|
||||||
|
- **Migration V17** — nine nullable source-envelope columns on `knowledge_nodes`
|
||||||
|
(additive; every existing memory is untouched), a partial UNIQUE index on
|
||||||
|
`(source_system, source_id)` enforcing one memory per external record while
|
||||||
|
costing nothing for envelope-less legacy rows, and the `connector_cursors`
|
||||||
|
checkpoint table. Idempotent on replay, following the established
|
||||||
|
`add_column_if_missing` pattern.
|
||||||
|
|
||||||
|
### Notes
|
||||||
|
|
||||||
|
- Local-first and optional: with no `source_sync` call, behavior is unchanged.
|
||||||
|
The default core-library build does not link an HTTP client.
|
||||||
|
|
||||||
|
## [2.1.26] - 2026-06-15 — "Configurable Output"
|
||||||
|
|
||||||
|
Roadmap **Phase 2: Configurable Output**. Users can now control the default
|
||||||
|
shape and size of high-traffic MCP responses with an optional, local-first
|
||||||
|
config file — without recompiling and without a cloud service. The default
|
||||||
|
behavior is unchanged: a fresh install with no `vestige.toml` behaves exactly
|
||||||
|
as before.
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
- **`vestige.toml` config file**, loaded from the active Vestige data directory
|
||||||
|
(`<data_dir>/vestige.toml`, alongside `vestige.db`). A missing or malformed
|
||||||
|
file falls back to built-in defaults, so existing installs are unaffected.
|
||||||
|
- **`[defaults]` table** with three keys: `detail_level`
|
||||||
|
(`brief` | `summary` | `full`), `limit` (default result count for
|
||||||
|
high-traffic tools), and `profile`.
|
||||||
|
- **Output profiles** — `lean`, `default`, `audit`, `research` — each presetting
|
||||||
|
a coherent bundle of detail level, result limit, and whether scores and
|
||||||
|
timestamps are included:
|
||||||
|
- `lean`: `brief` detail, limit 5, scores and timestamps dropped (smallest
|
||||||
|
context cost).
|
||||||
|
- `default`: historical behavior — `summary` detail, tool's own default
|
||||||
|
limit, scores and timestamps present. **Unchanged.**
|
||||||
|
- `audit`: `full` detail with every field, score, and timestamp.
|
||||||
|
- `research`: `full` detail with a larger default limit (25).
|
||||||
|
- **Three-layer precedence**, applied per call: an explicit MCP parameter wins
|
||||||
|
over the config file, which wins over the built-in default.
|
||||||
|
- **`profile` field** echoed in `search`, `memory_timeline`, `codebase`
|
||||||
|
(`get_context`), and `session_context` responses so the active profile is
|
||||||
|
observable.
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
- `search`, `memory_timeline`, `codebase` (`get_context`), and
|
||||||
|
`session_context` now resolve their default detail level and result limit
|
||||||
|
through the config file when no explicit parameter is supplied. With no
|
||||||
|
`vestige.toml` present, their output is byte-for-byte identical to v2.1.25.
|
||||||
|
|
||||||
|
### Documentation
|
||||||
|
|
||||||
|
- `docs/CONFIGURATION.md` gains a **Output Configuration (`vestige.toml`)**
|
||||||
|
section documenting the file location, `[defaults]` keys, profile presets,
|
||||||
|
and precedence rules.
|
||||||
|
|
||||||
|
## [2.1.25] - 2026-06-12 — "Merge / Supersede Controls"
|
||||||
|
|
||||||
|
v2.1.25 ships Phase 3: diff-previewed, confidence-gated, reversible,
|
||||||
|
self-explaining combine/dedupe/supersede on a never-delete (bitemporal) store.
|
||||||
|
The default is always preview/review — these tools never silently mutate memory.
|
||||||
|
The differentiator is the reversible operation log: every merge/supersede/undo is
|
||||||
|
an auditable, reversible event with provenance ("why did these combine?") — a git
|
||||||
|
reflog for your agent's memory.
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
- **Seven new MCP tools** for merge/supersede control:
|
||||||
|
- `merge_candidates` — surface likely duplicate/overlapping clusters with
|
||||||
|
confidence scores and the signals behind each (Fellegi-Sunter
|
||||||
|
match/possible/non-match). Read-only.
|
||||||
|
- `plan_merge` — produce a previewable merge PLAN (a diff of combined
|
||||||
|
content/tags/provenance) without applying it.
|
||||||
|
- `plan_supersede` — preview superseding A with B (bitemporal invalidation,
|
||||||
|
audit-preserving) without applying.
|
||||||
|
- `apply_plan` — execute a previously-generated plan id; recorded as a
|
||||||
|
reversible operation.
|
||||||
|
- `merge_undo` — reverse a prior merge/supersede operation, or list the
|
||||||
|
reversible operation log (the "memory reflog").
|
||||||
|
- `protect` — pin a memory so it can never be auto-merged, superseded, or
|
||||||
|
garbage-collected.
|
||||||
|
- `merge_policy` — get/set the per-project Fellegi-Sunter two thresholds
|
||||||
|
(`match_threshold`, `possible_threshold`) and `auto_apply`.
|
||||||
|
- **Bitemporal "invalidate, don't delete" supersede** (Graphiti-style): a
|
||||||
|
superseded memory is kept and stays queryable for audit. It is stamped with
|
||||||
|
`valid_until = now` and a new `superseded_by` lineage pointer, instead of being
|
||||||
|
deleted or merely demoted.
|
||||||
|
- **Reversible operation log** (`merge_operations` table) — every applied
|
||||||
|
merge/supersede records an undo payload and provenance signals so any operation
|
||||||
|
can be reversed, including restoring survivor content/tags and clearing the
|
||||||
|
bitemporal invalidation.
|
||||||
|
- **Fellegi-Sunter two-threshold scoring** for dedup/merge candidates, combining
|
||||||
|
embedding cosine similarity with tag and content-token overlap. Borderline
|
||||||
|
"possible" matches are surfaced for review instead of force-merged.
|
||||||
|
- **Memory protection / pinning** — `protected` column on `knowledge_nodes`;
|
||||||
|
protected memories are excluded from auto-merge/supersede/GC paths.
|
||||||
|
- **Migration V14** adding the `merge_plans` and `merge_operations` tables, the
|
||||||
|
`protected` and `superseded_by` columns on `knowledge_nodes`, and their
|
||||||
|
indexes. Idempotent on replay.
|
||||||
|
- **Docs**: `docs/MERGE_SUPERSEDE.md` describing the design, the bitemporal
|
||||||
|
model, the two-threshold policy, the reversible operation log, and the tool
|
||||||
|
surface.
|
||||||
|
|
||||||
|
### Notes
|
||||||
|
|
||||||
|
- All merge/supersede operations are **opt-in and preview-first**. `apply_plan`
|
||||||
|
requires `confirm=true` for `possible`/`non_match` plans, and only applies
|
||||||
|
`match` plans without confirmation when `merge_policy.auto_apply` is enabled
|
||||||
|
(default off). This deliberately avoids the silent-merge / auto-delete /
|
||||||
|
audit-trail-loss anti-patterns reported against other memory systems.
|
||||||
|
- The merge policy persists per-project and is also overridable via
|
||||||
|
`VESTIGE_MERGE_MATCH_THRESHOLD`, `VESTIGE_MERGE_POSSIBLE_THRESHOLD`, and
|
||||||
|
`VESTIGE_MERGE_AUTO_APPLY` environment variables.
|
||||||
|
|
||||||
## [2.1.23] - 2026-05-27 — "Receipt Lock Hardening"
|
## [2.1.23] - 2026-05-27 — "Receipt Lock Hardening"
|
||||||
|
|
||||||
v2.1.23 hardens the Sanhedrin launch path so Receipt Lock is portable,
|
v2.1.23 hardens the Sanhedrin launch path so Receipt Lock is portable,
|
||||||
|
|
|
||||||
206
Cargo.lock
generated
206
Cargo.lock
generated
|
|
@ -143,6 +143,12 @@ dependencies = [
|
||||||
"syn",
|
"syn",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "arrayref"
|
||||||
|
version = "0.3.9"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "76a2e8124351fda1ef8aaaa3bbd7ebbcb486bbcd4225aca0aa0d84bb2db8fecb"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "arrayvec"
|
name = "arrayvec"
|
||||||
version = "0.7.6"
|
version = "0.7.6"
|
||||||
|
|
@ -311,6 +317,20 @@ dependencies = [
|
||||||
"core2",
|
"core2",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "blake3"
|
||||||
|
version = "1.8.4"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "4d2d5991425dfd0785aed03aedcf0b321d61975c9b5b3689c774a2610ae0b51e"
|
||||||
|
dependencies = [
|
||||||
|
"arrayref",
|
||||||
|
"arrayvec",
|
||||||
|
"cc",
|
||||||
|
"cfg-if",
|
||||||
|
"constant_time_eq",
|
||||||
|
"cpufeatures 0.3.0",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "block"
|
name = "block"
|
||||||
version = "0.1.6"
|
version = "0.1.6"
|
||||||
|
|
@ -501,6 +521,12 @@ version = "1.0.4"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"
|
checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "cfg_aliases"
|
||||||
|
version = "0.2.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "chrono"
|
name = "chrono"
|
||||||
version = "0.4.44"
|
version = "0.4.44"
|
||||||
|
|
@ -642,6 +668,12 @@ dependencies = [
|
||||||
"windows-sys 0.59.0",
|
"windows-sys 0.59.0",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "constant_time_eq"
|
||||||
|
version = "0.4.2"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "3d52eff69cd5e647efe296129160853a42795992097e8af39800e1060caeea9b"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "core-foundation"
|
name = "core-foundation"
|
||||||
version = "0.9.4"
|
version = "0.9.4"
|
||||||
|
|
@ -697,6 +729,15 @@ dependencies = [
|
||||||
"libc",
|
"libc",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "cpufeatures"
|
||||||
|
version = "0.3.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "8b2a41393f66f16b0823bb79094d54ac5fbd34ab292ddafb9a0456ac9f87d201"
|
||||||
|
dependencies = [
|
||||||
|
"libc",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "crc32fast"
|
name = "crc32fast"
|
||||||
version = "1.5.0"
|
version = "1.5.0"
|
||||||
|
|
@ -1646,8 +1687,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0"
|
checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"cfg-if",
|
"cfg-if",
|
||||||
|
"js-sys",
|
||||||
"libc",
|
"libc",
|
||||||
"wasi",
|
"wasi",
|
||||||
|
"wasm-bindgen",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
|
|
@ -1657,9 +1700,11 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd"
|
checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"cfg-if",
|
"cfg-if",
|
||||||
|
"js-sys",
|
||||||
"libc",
|
"libc",
|
||||||
"r-efi 5.3.0",
|
"r-efi 5.3.0",
|
||||||
"wasip2",
|
"wasip2",
|
||||||
|
"wasm-bindgen",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
|
|
@ -1897,6 +1942,7 @@ dependencies = [
|
||||||
"tokio",
|
"tokio",
|
||||||
"tokio-rustls",
|
"tokio-rustls",
|
||||||
"tower-service",
|
"tower-service",
|
||||||
|
"webpki-roots 1.0.6",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
|
|
@ -2282,12 +2328,10 @@ dependencies = [
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "js-sys"
|
name = "js-sys"
|
||||||
version = "0.3.95"
|
version = "0.3.91"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "2964e92d1d9dc3364cae4d718d93f227e3abb088e747d92e0395bfdedf1c12ca"
|
checksum = "b49715b7073f385ba4bc528e5747d02e66cb39c6146efb66b781f131f0fb399c"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"cfg-if",
|
|
||||||
"futures-util",
|
|
||||||
"once_cell",
|
"once_cell",
|
||||||
"wasm-bindgen",
|
"wasm-bindgen",
|
||||||
]
|
]
|
||||||
|
|
@ -2486,6 +2530,12 @@ dependencies = [
|
||||||
"hashbrown 0.16.1",
|
"hashbrown 0.16.1",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "lru-slab"
|
||||||
|
version = "0.1.2"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "112b39cec0b298b6c1999fee3e31427f74f676e4cb9879ed1a121b43661a4154"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "lzma-rust2"
|
name = "lzma-rust2"
|
||||||
version = "0.15.7"
|
version = "0.15.7"
|
||||||
|
|
@ -3181,9 +3231,9 @@ checksum = "c33a9471896f1c69cecef8d20cbe2f7accd12527ce60845ff44c153bb2a21b49"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "portable-atomic-util"
|
name = "portable-atomic-util"
|
||||||
version = "0.2.6"
|
version = "0.2.7"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "091397be61a01d4be58e7841595bd4bfedb15f1cd54977d79b8271e94ed799a3"
|
checksum = "c2a106d1259c23fac8e543272398ae0e3c0b8d33c88ed73d0cc71b0f1d902618"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"portable-atomic",
|
"portable-atomic",
|
||||||
]
|
]
|
||||||
|
|
@ -3302,6 +3352,61 @@ version = "2.0.1"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "a993555f31e5a609f617c12db6250dedcac1b0a85076912c436e6fc9b2c8e6a3"
|
checksum = "a993555f31e5a609f617c12db6250dedcac1b0a85076912c436e6fc9b2c8e6a3"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "quinn"
|
||||||
|
version = "0.11.9"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "b9e20a958963c291dc322d98411f541009df2ced7b5a4f2bd52337638cfccf20"
|
||||||
|
dependencies = [
|
||||||
|
"bytes",
|
||||||
|
"cfg_aliases",
|
||||||
|
"pin-project-lite",
|
||||||
|
"quinn-proto",
|
||||||
|
"quinn-udp",
|
||||||
|
"rustc-hash",
|
||||||
|
"rustls",
|
||||||
|
"socket2",
|
||||||
|
"thiserror 2.0.18",
|
||||||
|
"tokio",
|
||||||
|
"tracing",
|
||||||
|
"web-time",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "quinn-proto"
|
||||||
|
version = "0.11.14"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "434b42fec591c96ef50e21e886936e66d3cc3f737104fdb9b737c40ffb94c098"
|
||||||
|
dependencies = [
|
||||||
|
"bytes",
|
||||||
|
"getrandom 0.3.4",
|
||||||
|
"lru-slab",
|
||||||
|
"rand",
|
||||||
|
"ring",
|
||||||
|
"rustc-hash",
|
||||||
|
"rustls",
|
||||||
|
"rustls-pki-types",
|
||||||
|
"slab",
|
||||||
|
"thiserror 2.0.18",
|
||||||
|
"tinyvec",
|
||||||
|
"tracing",
|
||||||
|
"web-time",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "quinn-udp"
|
||||||
|
version = "0.5.14"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "addec6a0dcad8a8d96a771f815f0eaf55f9d1805756410b39f5fa81332574cbd"
|
||||||
|
dependencies = [
|
||||||
|
"cfg_aliases",
|
||||||
|
"libc",
|
||||||
|
"once_cell",
|
||||||
|
"socket2",
|
||||||
|
"tracing",
|
||||||
|
"windows-sys 0.52.0",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "quote"
|
name = "quote"
|
||||||
version = "1.0.45"
|
version = "1.0.45"
|
||||||
|
|
@ -3538,6 +3643,8 @@ dependencies = [
|
||||||
"native-tls",
|
"native-tls",
|
||||||
"percent-encoding",
|
"percent-encoding",
|
||||||
"pin-project-lite",
|
"pin-project-lite",
|
||||||
|
"quinn",
|
||||||
|
"rustls",
|
||||||
"rustls-pki-types",
|
"rustls-pki-types",
|
||||||
"serde",
|
"serde",
|
||||||
"serde_json",
|
"serde_json",
|
||||||
|
|
@ -3545,6 +3652,7 @@ dependencies = [
|
||||||
"sync_wrapper",
|
"sync_wrapper",
|
||||||
"tokio",
|
"tokio",
|
||||||
"tokio-native-tls",
|
"tokio-native-tls",
|
||||||
|
"tokio-rustls",
|
||||||
"tokio-util",
|
"tokio-util",
|
||||||
"tower",
|
"tower",
|
||||||
"tower-http",
|
"tower-http",
|
||||||
|
|
@ -3554,6 +3662,7 @@ dependencies = [
|
||||||
"wasm-bindgen-futures",
|
"wasm-bindgen-futures",
|
||||||
"wasm-streams",
|
"wasm-streams",
|
||||||
"web-sys",
|
"web-sys",
|
||||||
|
"webpki-roots 1.0.6",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
|
|
@ -3603,6 +3712,12 @@ dependencies = [
|
||||||
"sqlite-wasm-rs",
|
"sqlite-wasm-rs",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "rustc-hash"
|
||||||
|
version = "2.1.2"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "94300abf3f1ae2e2b8ffb7b58043de3d399c73fa6f4b73826402a5c457614dbe"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "rustix"
|
name = "rustix"
|
||||||
version = "1.1.4"
|
version = "1.1.4"
|
||||||
|
|
@ -3637,6 +3752,7 @@ version = "1.14.0"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "be040f8b0a225e40375822a563fa9524378b9d63112f53e19ffff34df5d33fdd"
|
checksum = "be040f8b0a225e40375822a563fa9524378b9d63112f53e19ffff34df5d33fdd"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
|
"web-time",
|
||||||
"zeroize",
|
"zeroize",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|
@ -3822,7 +3938,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "e3bf829a2d51ab4a5ddf1352d8470c140cadc8301b2ae1789db023f01cedd6ba"
|
checksum = "e3bf829a2d51ab4a5ddf1352d8470c140cadc8301b2ae1789db023f01cedd6ba"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"cfg-if",
|
"cfg-if",
|
||||||
"cpufeatures",
|
"cpufeatures 0.2.17",
|
||||||
"digest",
|
"digest",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|
@ -3833,7 +3949,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283"
|
checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"cfg-if",
|
"cfg-if",
|
||||||
"cpufeatures",
|
"cpufeatures 0.2.17",
|
||||||
"digest",
|
"digest",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|
@ -4129,6 +4245,21 @@ dependencies = [
|
||||||
"serde_json",
|
"serde_json",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "tinyvec"
|
||||||
|
version = "1.11.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "3e61e67053d25a4e82c844e8424039d9745781b3fc4f32b8d55ed50f5f667ef3"
|
||||||
|
dependencies = [
|
||||||
|
"tinyvec_macros",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "tinyvec_macros"
|
||||||
|
version = "0.1.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "tokenizers"
|
name = "tokenizers"
|
||||||
version = "0.22.2"
|
version = "0.22.2"
|
||||||
|
|
@ -4356,6 +4487,17 @@ dependencies = [
|
||||||
"tracing-serde",
|
"tracing-serde",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "trait-variant"
|
||||||
|
version = "0.1.2"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "70977707304198400eb4835a78f6a9f928bf41bba420deb8fdb175cd965d77a7"
|
||||||
|
dependencies = [
|
||||||
|
"proc-macro2",
|
||||||
|
"quote",
|
||||||
|
"syn",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "try-lock"
|
name = "try-lock"
|
||||||
version = "0.2.5"
|
version = "0.2.5"
|
||||||
|
|
@ -4629,8 +4771,9 @@ checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "vestige-core"
|
name = "vestige-core"
|
||||||
version = "2.1.23"
|
version = "2.1.27"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
|
"blake3",
|
||||||
"candle-core",
|
"candle-core",
|
||||||
"chrono",
|
"chrono",
|
||||||
"criterion",
|
"criterion",
|
||||||
|
|
@ -4639,6 +4782,7 @@ dependencies = [
|
||||||
"git2",
|
"git2",
|
||||||
"lru",
|
"lru",
|
||||||
"notify",
|
"notify",
|
||||||
|
"reqwest",
|
||||||
"rusqlite",
|
"rusqlite",
|
||||||
"serde",
|
"serde",
|
||||||
"serde_json",
|
"serde_json",
|
||||||
|
|
@ -4646,6 +4790,7 @@ dependencies = [
|
||||||
"thiserror 2.0.18",
|
"thiserror 2.0.18",
|
||||||
"tokio",
|
"tokio",
|
||||||
"tracing",
|
"tracing",
|
||||||
|
"trait-variant",
|
||||||
"usearch",
|
"usearch",
|
||||||
"uuid",
|
"uuid",
|
||||||
]
|
]
|
||||||
|
|
@ -4665,7 +4810,7 @@ dependencies = [
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "vestige-mcp"
|
name = "vestige-mcp"
|
||||||
version = "2.1.23"
|
version = "2.1.27"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"anyhow",
|
"anyhow",
|
||||||
"axum",
|
"axum",
|
||||||
|
|
@ -4692,6 +4837,19 @@ dependencies = [
|
||||||
"vestige-core",
|
"vestige-core",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "vestige-phase-1-tests"
|
||||||
|
version = "0.0.1"
|
||||||
|
dependencies = [
|
||||||
|
"chrono",
|
||||||
|
"rusqlite",
|
||||||
|
"serde_json",
|
||||||
|
"tempfile",
|
||||||
|
"tokio",
|
||||||
|
"uuid",
|
||||||
|
"vestige-core",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "walkdir"
|
name = "walkdir"
|
||||||
version = "2.5.0"
|
version = "2.5.0"
|
||||||
|
|
@ -4737,9 +4895,9 @@ dependencies = [
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "wasm-bindgen"
|
name = "wasm-bindgen"
|
||||||
version = "0.2.118"
|
version = "0.2.114"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "0bf938a0bacb0469e83c1e148908bd7d5a6010354cf4fb73279b7447422e3a89"
|
checksum = "6532f9a5c1ece3798cb1c2cfdba640b9b3ba884f5db45973a6f442510a87d38e"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"cfg-if",
|
"cfg-if",
|
||||||
"once_cell",
|
"once_cell",
|
||||||
|
|
@ -4750,19 +4908,23 @@ dependencies = [
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "wasm-bindgen-futures"
|
name = "wasm-bindgen-futures"
|
||||||
version = "0.4.68"
|
version = "0.4.64"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "f371d383f2fb139252e0bfac3b81b265689bf45b6874af544ffa4c975ac1ebf8"
|
checksum = "e9c5522b3a28661442748e09d40924dfb9ca614b21c00d3fd135720e48b67db8"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
|
"cfg-if",
|
||||||
|
"futures-util",
|
||||||
"js-sys",
|
"js-sys",
|
||||||
|
"once_cell",
|
||||||
"wasm-bindgen",
|
"wasm-bindgen",
|
||||||
|
"web-sys",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "wasm-bindgen-macro"
|
name = "wasm-bindgen-macro"
|
||||||
version = "0.2.118"
|
version = "0.2.114"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "eeff24f84126c0ec2db7a449f0c2ec963c6a49efe0698c4242929da037ca28ed"
|
checksum = "18a2d50fcf105fb33bb15f00e7a77b772945a2ee45dcf454961fd843e74c18e6"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"quote",
|
"quote",
|
||||||
"wasm-bindgen-macro-support",
|
"wasm-bindgen-macro-support",
|
||||||
|
|
@ -4770,9 +4932,9 @@ dependencies = [
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "wasm-bindgen-macro-support"
|
name = "wasm-bindgen-macro-support"
|
||||||
version = "0.2.118"
|
version = "0.2.114"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "9d08065faf983b2b80a79fd87d8254c409281cf7de75fc4b773019824196c904"
|
checksum = "03ce4caeaac547cdf713d280eda22a730824dd11e6b8c3ca9e42247b25c631e3"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"bumpalo",
|
"bumpalo",
|
||||||
"proc-macro2",
|
"proc-macro2",
|
||||||
|
|
@ -4783,9 +4945,9 @@ dependencies = [
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "wasm-bindgen-shared"
|
name = "wasm-bindgen-shared"
|
||||||
version = "0.2.118"
|
version = "0.2.114"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "5fd04d9e306f1907bd13c6361b5c6bfc7b3b3c095ed3f8a9246390f8dbdee129"
|
checksum = "75a326b8c223ee17883a4251907455a2431acc2791c98c26279376490c378c16"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"unicode-ident",
|
"unicode-ident",
|
||||||
]
|
]
|
||||||
|
|
@ -4839,9 +5001,9 @@ dependencies = [
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "web-sys"
|
name = "web-sys"
|
||||||
version = "0.3.95"
|
version = "0.3.91"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "4f2dfbb17949fa2088e5d39408c48368947b86f7834484e87b73de55bc14d97d"
|
checksum = "854ba17bb104abfb26ba36da9729addc7ce7f06f5c0f90f3c391f8461cca21f9"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"js-sys",
|
"js-sys",
|
||||||
"wasm-bindgen",
|
"wasm-bindgen",
|
||||||
|
|
|
||||||
|
|
@ -4,13 +4,14 @@ members = [
|
||||||
"crates/vestige-core",
|
"crates/vestige-core",
|
||||||
"crates/vestige-mcp",
|
"crates/vestige-mcp",
|
||||||
"tests/e2e",
|
"tests/e2e",
|
||||||
|
"tests/phase_1",
|
||||||
]
|
]
|
||||||
exclude = [
|
exclude = [
|
||||||
"fastembed-rs",
|
"fastembed-rs",
|
||||||
]
|
]
|
||||||
|
|
||||||
[workspace.package]
|
[workspace.package]
|
||||||
version = "2.1.23"
|
version = "2.1.27"
|
||||||
edition = "2024"
|
edition = "2024"
|
||||||
license = "AGPL-3.0-only"
|
license = "AGPL-3.0-only"
|
||||||
repository = "https://github.com/samvallad33/vestige"
|
repository = "https://github.com/samvallad33/vestige"
|
||||||
|
|
|
||||||
123
README.md
123
README.md
|
|
@ -14,7 +14,7 @@
|
||||||
|
|
||||||
Built on proven memory and retrieval ideas — FSRS-6 spaced repetition, prediction error gating, synaptic tagging, spreading activation, and memory consolidation — all running in a single Rust binary with a local dashboard. 100% local. Zero cloud.
|
Built on proven memory and retrieval ideas — FSRS-6 spaced repetition, prediction error gating, synaptic tagging, spreading activation, and memory consolidation — all running in a single Rust binary with a local dashboard. 100% local. Zero cloud.
|
||||||
|
|
||||||
[Quick Start](#quick-start) | [Dashboard](#-3d-memory-dashboard) | [How It Works](#-the-cognitive-science-stack) | [Tools](#-25-mcp-tools) | [Docs](docs/)
|
[Quick Start](#quick-start) | [Dashboard](#-3d-memory-dashboard) | [How It Works](#-the-cognitive-science-stack) | [Tools](#-25-mcp-tools) | [Docs](docs/) | [Roadmap](docs/ROADMAP.md)
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
|
@ -33,118 +33,6 @@ observable, and harder to spoof.
|
||||||
- **Safer batch writes.** `smart_ingest` batch mode now keeps caller-separated items separate by default and returns merge previews when an existing memory is mutated.
|
- **Safer batch writes.** `smart_ingest` batch mode now keeps caller-separated items separate by default and returns merge previews when an existing memory is mutated.
|
||||||
- **Opt-in NVIDIA acceleration path.** Qwen3 embedding builds expose CUDA/cuDNN feature flags for contributors and users with CUDA-capable hosts.
|
- **Opt-in NVIDIA acceleration path.** Qwen3 embedding builds expose CUDA/cuDNN feature flags for contributors and users with CUDA-capable hosts.
|
||||||
|
|
||||||
## What's New in v2.1.22 "Sanhedrin Receipts"
|
|
||||||
|
|
||||||
v2.1.22 makes the optional Sanhedrin hook accountable enough to trust in daily
|
|
||||||
agent work. Vetoes now leave local receipts, verification claims need real
|
|
||||||
command evidence, and users can appeal stale or over-strict blocks from the
|
|
||||||
dashboard.
|
|
||||||
|
|
||||||
- **Receipt Lock.** Claims like "tests passed", "build is green", or "lint is clean" are blocked unless the current transcript contains a matching successful command receipt.
|
|
||||||
- **Screenshotable veto receipts.** Sanhedrin writes `~/.vestige/sanhedrin/latest.json` and `latest.html` with Claim -> Verdict -> Precedent -> Fix -> Appeal.
|
|
||||||
- **Dashboard Verdict Bar.** The dashboard shows PASS, NOTE, CAUTION, VETO, or APPEALED globally, expands into the receipt, and records stale/wrong/too-strict appeals.
|
|
||||||
- **Claim ledger.** Claim-mode Sanhedrin output now maps every extracted claim into structured JSON instead of treating the whole draft as one blob.
|
|
||||||
- **Appeal training.** Appeals are saved to `appeals.jsonl` and suppress future vetoes for the same claim fingerprint.
|
|
||||||
|
|
||||||
## What's New in v2.1.21 "Agent-Neutral Hardening"
|
|
||||||
|
|
||||||
v2.1.21 tightens Vestige for normal use across MCP-compatible agents, without
|
|
||||||
making Claude Code companion tooling part of the default path.
|
|
||||||
|
|
||||||
- **Agent-neutral default.** Stdio MCP remains the default transport; optional HTTP MCP is explicit with `--http`, `--http-port`, or `VESTIGE_HTTP_ENABLED=1`.
|
|
||||||
- **Safer destructive actions.** `memory(action="delete")` now requires `confirm=true`, matching `purge`, and the legacy `delete_knowledge` shim forwards that confirmation instead of bypassing it.
|
|
||||||
- **Portable sync repair.** Merge imports preserve purge tombstones, avoid `INSERT OR REPLACE` cascades, rebuild the vector index from a clean state, and write portable archive temp files with private Unix permissions.
|
|
||||||
- **Release/package cleanup.** Release builds check the embedded dashboard before packaging, publish checksums, and the npm installer rejects targets that do not have release assets.
|
|
||||||
- **Any-agent memory protocol.** The setup docs now include a short agent-agnostic memory protocol for Claude Code, Codex, Cursor, VS Code, Xcode, JetBrains, Windsurf, and other MCP clients.
|
|
||||||
|
|
||||||
## What's New in v2.1.2 "Honest Memory"
|
|
||||||
|
|
||||||
v2.1.2 makes Vestige easier to trust in everyday work: literal lookups stay literal, purge really removes content, contradictions are inspectable, and updates no longer require a curl reinstall flow.
|
|
||||||
|
|
||||||
- **Concrete search mode.** Quoted strings, env vars, UUIDs, paths, and code identifiers now take a keyword/literal path that skips HyDE, semantic fusion, FSRS reweighting, competition, and spreading activation. Exact things like `OPENAI_API_KEY`, `mlx_lm.server`, and migration IDs land first.
|
|
||||||
- **Irreversible purge.** `memory(action="purge", confirm=true)` permanently removes memory content and embeddings, scrubs insight JSON references, detaches temporal-summary children, prunes graph edges, and keeps only a non-content deletion tombstone for sync/audit.
|
|
||||||
- **First-class contradiction inspection.** New `contradictions` MCP tool surfaces trust-weighted disagreements directly instead of hiding them inside `deep_reference`.
|
|
||||||
- **Simple update flow.** `vestige update` refreshes binaries. Claude Code Cognitive Sandwich companion files are opt-in with `vestige update --sandwich-companion` or `vestige sandwich install`.
|
|
||||||
- **Pro waitlist preview.** `/dashboard/waitlist` adds a local-first Solo Pro and Team Pro early-access surface. `VITE_WAITLIST_ENDPOINT` and `VITE_SUPPORT_BOT_ENDPOINT` are opt-in dashboard env vars, so no signup data is captured unless endpoints are configured.
|
|
||||||
|
|
||||||
## What's New in v2.1.1 "Portable Sync"
|
|
||||||
|
|
||||||
v2.1.1 focuses on the biggest post-launch ask: move memories between machines without losing cognitive state. It also adds opt-in Qwen3 embeddings for higher-recall local retrieval.
|
|
||||||
|
|
||||||
- **Exact portable archives.** `vestige portable-export` / `vestige portable-import` preserve IDs, FSRS state, graph edges, suppression state, audit rows, and embedding blobs for Vestige-to-Vestige device transfer.
|
|
||||||
- **Sync-safe merge storage.** `vestige portable-import --merge` and `vestige sync <archive>` merge non-empty databases, apply delete tombstones, keep newer local memories, rebuild FTS, and push through a pluggable portable-sync backend. v2.1.1 ships the file backend for Dropbox, iCloud, Syncthing, Git, and shared folders.
|
|
||||||
- **Qwen3 embeddings.** Build with `qwen3-embeddings`, set `VESTIGE_EMBEDDING_MODEL=qwen3-0.6b`, and run `vestige consolidate` to re-embed existing memories. `vestige health` reports mixed-model stores before search quality is affected.
|
|
||||||
- **Model-aware retrieval.** Vestige now avoids comparing Qwen and Nomic vectors in the same search/dedup path.
|
|
||||||
|
|
||||||
## What's New in v2.1.0 "Cognitive Sandwich Goes Local"
|
|
||||||
|
|
||||||
v2.1.0 adds an opt-in Claude Code hook harness around the existing Vestige MCP server. The MCP tool surface and database schema stay backward compatible, while preflight hooks can inject trusted memory context before Claude answers. The heavyweight Sanhedrin verifier is optional and can be enabled separately.
|
|
||||||
|
|
||||||
- **Optional Sanhedrin Executioner.** The post-response verifier is off by default. Users can enable it with an OpenAI-compatible endpoint on x86/Linux/Intel Mac, or add `--with-launchd` on Apple Silicon to run the local MLX Qwen backend.
|
|
||||||
- **One-command Cognitive Sandwich installer.** `vestige sandwich install` stages hook files and agents by default, removes old Vestige hook wiring, and leaves all Claude Code hook layers plus the 19 GB model path opt-in.
|
|
||||||
- **Pulse hook backed by `/api/changelog`.** Fresh dream and connection events can be injected into the next Claude Code prompt context without blocking the prompt.
|
|
||||||
- **`VESTIGE_DATA_DIR` support.** `--data-dir` now has an env-var fallback, tilde expansion, secure directory creation, and clear precedence docs.
|
|
||||||
- **NPM release wrapper fixed.** `vestige-mcp-server@2.1.0` now downloads binaries from the matching `v2.1.0` GitHub release tag instead of an old hardcoded release.
|
|
||||||
|
|
||||||
## What's New in v2.0.9 "Autopilot"
|
|
||||||
|
|
||||||
Autopilot flips Vestige from passive memory library to **self-managing cognitive surface**. Same 24 MCP tools, zero schema changes — but the moment you upgrade, 14 previously dormant cognitive primitives start firing on live events without any tool call from your client.
|
|
||||||
|
|
||||||
- **One supervised backend task subscribes to the 20-event WebSocket bus** and routes six event classes into the cognitive engine: `MemoryCreated` triggers synaptic-tagging PRP + predictive-access records, `SearchPerformed` warms the speculative-retrieval model, `MemoryPromoted` fires activation spread, `MemorySuppressed` emits the Rac1 cascade wave, high-importance `ImportanceScored` (>0.85) auto-promotes, and `Heartbeat` rate-limit-fires `find_duplicates` on large DBs. **The engine mutex is never held across `.await`, so MCP dispatch is never starved.**
|
|
||||||
- **Panic-resilient supervisors.** Both background tasks run inside an outer supervisor loop — if one handler panics on a bad memory, the supervisor respawns it in 5 s instead of losing every future event.
|
|
||||||
- **Fully backward compatible.** No new MCP tools. No schema migration. Existing v2.0.8 databases open without a single step. Opt out with `VESTIGE_AUTOPILOT_ENABLED=0` if you want the passive-library contract back.
|
|
||||||
- **3,091 LOC of orphan v1.0 tool code removed** — nine superseded modules (`checkpoint`, `codebase`, `consolidate`, `ingest`, `intentions`, `knowledge`, `recall`, plus helpers) verified zero non-test callers before deletion. Tool surface unchanged.
|
|
||||||
|
|
||||||
## What's New in v2.0.8 "Pulse"
|
|
||||||
|
|
||||||
v2.0.8 wires the dashboard through to the cognitive engine. Eight new surfaces expose the reasoning stack visually — every one was MCP-only before.
|
|
||||||
|
|
||||||
- **Reasoning Theater (`/reasoning`)** — `Cmd+K` Ask palette over the 8-stage `deep_reference` pipeline (hybrid retrieval → cross-encoder rerank → spreading activation → FSRS-6 trust → temporal supersession → contradiction analysis → relation assessment → template reasoning chain). Evidence cards, confidence meter, contradiction geodesic arcs, superseded-memory lineage, evolution timeline. **Zero LLM calls, 100% local.**
|
|
||||||
- **Pulse InsightToast** — real-time toasts for `DreamCompleted`, `ConsolidationCompleted`, `ConnectionDiscovered`, promote/demote/suppress/unsuppress, `Rac1CascadeSwept`. Rate-limited, auto-dismiss, click-to-dismiss.
|
|
||||||
- **Memory Birth Ritual (Terrarium)** — new memories materialize in the 3D graph on every `MemoryCreated`: elastic scale-in, quadratic Bezier flight path, glow sprite fade-in, Newton's Cradle docking recoil. 60-frame sequence, zero-alloc math.
|
|
||||||
- **7 more dashboard surfaces** — `/duplicates`, `/dreams`, `/schedule`, `/importance`, `/activation`, `/contradictions`, `/patterns`. Left nav expanded 8 → 16 with single-key shortcuts.
|
|
||||||
- **Intel Mac (`x86_64-apple-darwin`) support restored** via the `ort-dynamic` Cargo feature + Homebrew `onnxruntime`. Microsoft deprecated x86_64 macOS prebuilts; the dynamic-link path sidesteps that permanently. **Closes #41.**
|
|
||||||
- **Contradiction-detection false positives eliminated** — four thresholds tightened so adjacent-domain memories no longer flag as conflicts. On an FSRS-6 query this collapses false contradictions 12 → 0 without regressing legitimate test cases.
|
|
||||||
|
|
||||||
## What's New in v2.0.7 "Visible"
|
|
||||||
|
|
||||||
Hygiene release closing two UI gaps and finishing schema cleanup. No breaking changes, no user-data migrations.
|
|
||||||
|
|
||||||
- **`POST /api/memories/{id}/suppress` + `/unsuppress` HTTP endpoints** — dashboard can trigger Anderson 2025 SIF + Rac1 cascade without dropping to raw MCP. `suppressionCount`, `retrievalPenalty`, `reversibleUntil`, `labileWindowHours` all in response. Suppress button joins Promote / Demote / Delete on the Memories page.
|
|
||||||
- **Uptime in the sidebar footer** — the `Heartbeat` event has carried `uptime_secs` since v2.0.5 but was never rendered. Now shows as `up 3d 4h` / `up 18m` / `up 47s`.
|
|
||||||
- **`execute_export` panic fix** — unreachable match arm replaced with a clean "unsupported export format" error instead of unwinding through the MCP dispatcher.
|
|
||||||
- **`predict` surfaces `predict_degraded: true`** on lock poisoning instead of silently returning empty vecs. `memory_changelog` honors `start` / `end` bounds. `intention` check honors `include_snoozed`.
|
|
||||||
- **Migration V11** — drops dead `knowledge_edges` + `compressed_memories` tables (added speculatively in V4, never used).
|
|
||||||
|
|
||||||
## What's New in v2.0.6 "Composer"
|
|
||||||
|
|
||||||
v2.0.6 is a polish release that makes the existing cognitive stack finally *feel* alive in the dashboard and stays out of your way on the prompt side.
|
|
||||||
|
|
||||||
- **Six live graph reactions, not one** — `MemorySuppressed`, `MemoryUnsuppressed`, `Rac1CascadeSwept`, `Connected`, `ConsolidationStarted`, and `ImportanceScored` now light the 3D graph in real time. v2.0.5 shipped `suppress` but the graph was silent when you called it; consolidation and importance scoring have been silent since v2.0.0. No longer.
|
|
||||||
- **Intentions page actually works** — fixes a long-standing bug where every intention rendered as "normal priority" (type/schema drift between backend and frontend) and context/time triggers surfaced as raw JSON.
|
|
||||||
- **Opt-in composition mandate** — the new MCP `instructions` string stays minimal by default. Opt in to the full Composing / Never-composed / Recommendation composition protocol with `VESTIGE_SYSTEM_PROMPT_MODE=full` when you want it, and nothing is imposed on your sessions when you don't.
|
|
||||||
|
|
||||||
## What's New in v2.0.5 "Intentional Amnesia"
|
|
||||||
|
|
||||||
**The first shipped AI memory system with top-down inhibitory control over retrieval.** Other systems implement passive decay — memories fade if you don't touch them. Vestige v2.0.5 also implements *active* suppression: the new **`suppress`** tool compounds a retrieval penalty on every call (up to 80%), a background Rac1 worker fades co-activated neighbors over 72 hours, and the whole thing is reversible within a 24-hour labile window. **Never deletes.** The memory is inhibited, not erased.
|
|
||||||
|
|
||||||
Ebbinghaus 1885 models what happens to memories you don't touch. Anderson 2025 models what happens when you actively want to stop thinking about one. Every other AI memory system implements the first. Vestige is the first to ship the second.
|
|
||||||
|
|
||||||
Based on [Anderson et al. 2025](https://www.nature.com/articles/s41583-025-00929-y) (Suppression-Induced Forgetting, *Nat Rev Neurosci*) and [Cervantes-Sandoval et al. 2020](https://pmc.ncbi.nlm.nih.gov/articles/PMC7477079/) (Rac1 synaptic cascade).
|
|
||||||
|
|
||||||
<details>
|
|
||||||
<summary>Earlier releases (v2.0 "Cognitive Leap" → v2.0.4 "Deep Reference")</summary>
|
|
||||||
|
|
||||||
- **v2.0.4 — `deep_reference` Tool** — 8-stage cognitive reasoning pipeline with FSRS-6 trust scoring, intent classification, spreading activation, contradiction analysis, and pre-built reasoning chains. Token budgets raised 10K → 100K. CORS tightened.
|
|
||||||
- **v2.0 — 3D Memory Dashboard** — SvelteKit + Three.js neural visualization with real-time WebSocket events, bloom post-processing, force-directed graph layout.
|
|
||||||
- **v2.0 — WebSocket Event Bus** — Every cognitive operation broadcasts events: memory creation, search, dreaming, consolidation, retention decay.
|
|
||||||
- **v2.0 — HyDE Query Expansion** — Template-based Hypothetical Document Embeddings for dramatically improved search quality on conceptual queries.
|
|
||||||
- **v2.0 — Nomic v2 MoE (experimental)** — fastembed 5.11 with optional Nomic Embed Text v2 MoE (475M params, 8 experts) + Metal GPU acceleration.
|
|
||||||
- **v2.0 — Command Palette** — `Cmd+K` navigation, keyboard shortcuts, responsive mobile layout, PWA installable.
|
|
||||||
- **v2.0 — FSRS Decay Visualization** — SVG retention curves with predicted decay at 1d/7d/30d.
|
|
||||||
|
|
||||||
</details>
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Quick Start
|
## Quick Start
|
||||||
|
|
@ -160,6 +48,9 @@ claude mcp add vestige vestige-mcp -s user
|
||||||
# Codex
|
# Codex
|
||||||
codex mcp add vestige -- vestige-mcp
|
codex mcp add vestige -- vestige-mcp
|
||||||
|
|
||||||
|
# OpenCode
|
||||||
|
npx @vestige/init
|
||||||
|
|
||||||
# 3. Test it
|
# 3. Test it
|
||||||
# "Remember that I prefer TypeScript over JavaScript"
|
# "Remember that I prefer TypeScript over JavaScript"
|
||||||
# ...new session...
|
# ...new session...
|
||||||
|
|
@ -254,6 +145,7 @@ Vestige speaks MCP, so any client that can register a stdio MCP server can use i
|
||||||
| **Xcode 26.3** | [Integration guide](docs/integrations/xcode.md) |
|
| **Xcode 26.3** | [Integration guide](docs/integrations/xcode.md) |
|
||||||
| **Cursor** | [Integration guide](docs/integrations/cursor.md) |
|
| **Cursor** | [Integration guide](docs/integrations/cursor.md) |
|
||||||
| **VS Code (Copilot)** | [Integration guide](docs/integrations/vscode.md) |
|
| **VS Code (Copilot)** | [Integration guide](docs/integrations/vscode.md) |
|
||||||
|
| **OpenCode** | [Integration guide](docs/integrations/opencode.md) |
|
||||||
| **JetBrains** | [Integration guide](docs/integrations/jetbrains.md) |
|
| **JetBrains** | [Integration guide](docs/integrations/jetbrains.md) |
|
||||||
| **Windsurf** | [Integration guide](docs/integrations/windsurf.md) |
|
| **Windsurf** | [Integration guide](docs/integrations/windsurf.md) |
|
||||||
|
|
||||||
|
|
@ -356,7 +248,7 @@ This isn't a key-value store with an embedding model bolted on. Vestige implemen
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 🛠 25 MCP Tools
|
## 🛠 MCP Tools
|
||||||
|
|
||||||
### Context Packets
|
### Context Packets
|
||||||
| Tool | What It Does |
|
| Tool | What It Does |
|
||||||
|
|
@ -384,6 +276,7 @@ This isn't a key-value store with an embedding model bolted on. Vestige implemen
|
||||||
|------|-------------|
|
|------|-------------|
|
||||||
| `memory_health` | Retention dashboard — distribution, trends, recommendations |
|
| `memory_health` | Retention dashboard — distribution, trends, recommendations |
|
||||||
| `memory_graph` | Knowledge graph export — force-directed layout, up to 200 nodes |
|
| `memory_graph` | Knowledge graph export — force-directed layout, up to 200 nodes |
|
||||||
|
| `composed_graph` | Composition ledger — recent composed memory sets, neighbors, outcome labels, bounty/research lanes, and never-composed frontier candidates |
|
||||||
|
|
||||||
### Scoring & Dedup
|
### Scoring & Dedup
|
||||||
| Tool | What It Does |
|
| Tool | What It Does |
|
||||||
|
|
@ -533,7 +426,7 @@ vestige dashboard # Open 3D dashboard in browser
|
||||||
| [Storage Modes](docs/STORAGE.md) | Global, per-project, multi-instance |
|
| [Storage Modes](docs/STORAGE.md) | Global, per-project, multi-instance |
|
||||||
| [CLAUDE.md Setup](docs/CLAUDE-SETUP.md) | Templates for proactive memory |
|
| [CLAUDE.md Setup](docs/CLAUDE-SETUP.md) | Templates for proactive memory |
|
||||||
| [Configuration](docs/CONFIGURATION.md) | CLI commands, environment variables |
|
| [Configuration](docs/CONFIGURATION.md) | CLI commands, environment variables |
|
||||||
| [Integrations](docs/integrations/) | Codex, Xcode, Cursor, VS Code, JetBrains, Windsurf |
|
| [Integrations](docs/integrations/) | Codex, Xcode, Cursor, VS Code, OpenCode, JetBrains, Windsurf |
|
||||||
| [Changelog](CHANGELOG.md) | Version history |
|
| [Changelog](CHANGELOG.md) | Version history |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,6 @@
|
||||||
{
|
{
|
||||||
"name": "@vestige/dashboard",
|
"name": "@vestige/dashboard",
|
||||||
"version": "2.1.23",
|
"version": "2.1.27",
|
||||||
"private": true,
|
"private": true,
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,6 @@
|
||||||
[package]
|
[package]
|
||||||
name = "vestige-core"
|
name = "vestige-core"
|
||||||
version = "2.1.23"
|
version = "2.1.27"
|
||||||
edition = "2024"
|
edition = "2024"
|
||||||
rust-version = "1.91"
|
rust-version = "1.91"
|
||||||
authors = ["Vestige Team"]
|
authors = ["Vestige Team"]
|
||||||
|
|
@ -57,6 +57,12 @@ qwen3-embeddings = ["embeddings", "fastembed/qwen3", "dep:candle-core"]
|
||||||
# Backwards-compatible feature alias from the original v2.1.0 naming.
|
# Backwards-compatible feature alias from the original v2.1.0 naming.
|
||||||
qwen3-reranker = ["qwen3-embeddings"]
|
qwen3-reranker = ["qwen3-embeddings"]
|
||||||
|
|
||||||
|
# External-source connectors (#57). The connector *contract*, normalization,
|
||||||
|
# and content-hashing are always compiled (pure, no network). This feature adds
|
||||||
|
# the network-backed reference connectors (GitHub Issues, …) via `reqwest`, so
|
||||||
|
# the default local-first build never links an HTTP client.
|
||||||
|
connectors = ["dep:reqwest"]
|
||||||
|
|
||||||
# Metal GPU acceleration on Apple Silicon (significantly faster inference)
|
# Metal GPU acceleration on Apple Silicon (significantly faster inference)
|
||||||
metal = ["fastembed/metal"]
|
metal = ["fastembed/metal"]
|
||||||
|
|
||||||
|
|
@ -121,10 +127,24 @@ candle-core = { version = "0.10.2", optional = true }
|
||||||
# its memory_mapping_allocator_gt template references the POSIX MAP_FAILED
|
# its memory_mapping_allocator_gt template references the POSIX MAP_FAILED
|
||||||
# macro from <sys/mman.h>, which doesn't exist on MSVC. Tracked upstream in
|
# macro from <sys/mman.h>, which doesn't exist on MSVC. Tracked upstream in
|
||||||
# unum-cloud/usearch#746. Unpin when the upstream fix lands.
|
# unum-cloud/usearch#746. Unpin when the upstream fix lands.
|
||||||
usearch = { version = "=2.23.0", optional = true }
|
#
|
||||||
|
# Disable default features so release binaries do not include SimSIMD's
|
||||||
|
# Haswell+/AVX2/FMA dispatch targets. Those kernels can trigger illegal
|
||||||
|
# instructions on older x86_64 CPUs that Vestige otherwise supports.
|
||||||
|
usearch = { version = "=2.23.0", default-features = false, optional = true }
|
||||||
|
|
||||||
# LRU cache for query embeddings
|
# LRU cache for query embeddings
|
||||||
lru = "0.16"
|
lru = "0.16"
|
||||||
|
trait-variant = "0.1"
|
||||||
|
blake3 = "1"
|
||||||
|
|
||||||
|
# ============================================================================
|
||||||
|
# OPTIONAL: External-source connectors (#57)
|
||||||
|
# ============================================================================
|
||||||
|
# HTTP client for network-backed reference connectors (GitHub Issues, Redmine).
|
||||||
|
# rustls so connectors build with no system OpenSSL dependency. Behind the
|
||||||
|
# `connectors` feature — the default local-first build does not link reqwest.
|
||||||
|
reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls"], optional = true }
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
tempfile = "3"
|
tempfile = "3"
|
||||||
|
|
|
||||||
450
crates/vestige-core/src/advanced/merge_supersede.rs
Normal file
450
crates/vestige-core/src/advanced/merge_supersede.rs
Normal file
|
|
@ -0,0 +1,450 @@
|
||||||
|
//! # Merge / Supersede Controls (Phase 3)
|
||||||
|
//!
|
||||||
|
//! Diff-previewed, confidence-gated, reversible, self-explaining combine /
|
||||||
|
//! dedupe / supersede operations on a never-delete (bitemporal) store.
|
||||||
|
//!
|
||||||
|
//! This module holds the **pure** logic: candidate scoring, two-threshold
|
||||||
|
//! classification, and the plan / operation data model. The actual persistence
|
||||||
|
//! (writing plans, applying them, recording the reversible operation log, and
|
||||||
|
//! bitemporally invalidating superseded nodes) lives in
|
||||||
|
//! [`crate::storage`]. Keeping the math here makes it unit-testable without a
|
||||||
|
//! database.
|
||||||
|
//!
|
||||||
|
//! ## Design north star
|
||||||
|
//!
|
||||||
|
//! Every combine/dedupe/supersede operation is:
|
||||||
|
//!
|
||||||
|
//! - **diff-previewed** — `plan_merge` / `plan_supersede` produce a [`MergePlan`]
|
||||||
|
//! you can inspect before anything mutates,
|
||||||
|
//! - **confidence-gated** — a Fellegi-Sunter two-threshold score classifies each
|
||||||
|
//! candidate as match / possible-match / non-match,
|
||||||
|
//! - **reversible** — every applied plan records a [`MergeOperation`] with an
|
||||||
|
//! undo payload (the "git reflog for your agent's memory"),
|
||||||
|
//! - **self-explaining** — each candidate carries the [`MatchSignals`] that
|
||||||
|
//! explain *why* the memories combined,
|
||||||
|
//! - **opt-in, never silent** — the default is preview/review, never auto-mutate,
|
||||||
|
//! - **audit-preserving** — superseding stamps `valid_until` and keeps the old
|
||||||
|
//! node queryable (Graphiti-style "invalidate, don't delete").
|
||||||
|
//!
|
||||||
|
//! ## Why Fellegi-Sunter
|
||||||
|
//!
|
||||||
|
//! Pure hashing under-merges (misses paraphrases); aggressive LLM merging
|
||||||
|
//! over-merges and destroys the audit trail. Fellegi-Sunter record linkage uses
|
||||||
|
//! **two** thresholds to carve the score space into three zones, so the
|
||||||
|
//! borderline "possible match" cases are surfaced for review instead of being
|
||||||
|
//! force-decided. We reuse the embedding cosine similarity already in the store
|
||||||
|
//! plus cheap lexical signals (tag overlap, token Jaccard) as the match weight.
|
||||||
|
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
// ============================================================================
|
||||||
|
// CONSTANTS — the two Fellegi-Sunter thresholds
|
||||||
|
// ============================================================================
|
||||||
|
|
||||||
|
/// Above this combined score → automatic-eligible "match".
|
||||||
|
pub const DEFAULT_MATCH_THRESHOLD: f32 = 0.86;
|
||||||
|
|
||||||
|
/// Between the two thresholds → "possible match", surfaced for review.
|
||||||
|
/// Below this → "non-match" (never offered).
|
||||||
|
pub const DEFAULT_POSSIBLE_THRESHOLD: f32 = 0.72;
|
||||||
|
|
||||||
|
/// Weight of embedding cosine similarity in the combined score.
|
||||||
|
const W_EMBEDDING: f32 = 0.70;
|
||||||
|
/// Weight of tag overlap (Jaccard) in the combined score.
|
||||||
|
const W_TAGS: f32 = 0.15;
|
||||||
|
/// Weight of content token overlap (Jaccard) in the combined score.
|
||||||
|
const W_TOKENS: f32 = 0.15;
|
||||||
|
|
||||||
|
// ============================================================================
|
||||||
|
// CLASSIFICATION
|
||||||
|
// ============================================================================
|
||||||
|
|
||||||
|
/// Fellegi-Sunter three-way classification of a candidate pair/cluster.
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
#[serde(rename_all = "snake_case")]
|
||||||
|
pub enum MatchClass {
|
||||||
|
/// Score ≥ match threshold — strong duplicate, auto-merge eligible.
|
||||||
|
Match,
|
||||||
|
/// Between thresholds — surfaced for human/agent review, never auto-applied.
|
||||||
|
Possible,
|
||||||
|
/// Below the possible threshold — not offered as a candidate.
|
||||||
|
NonMatch,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl MatchClass {
|
||||||
|
/// String label used in tool output and the `classification` column.
|
||||||
|
pub fn as_str(&self) -> &'static str {
|
||||||
|
match self {
|
||||||
|
MatchClass::Match => "match",
|
||||||
|
MatchClass::Possible => "possible",
|
||||||
|
MatchClass::NonMatch => "non_match",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Per-merge-policy thresholds. Wired to `vestige.toml` when present, else the
|
||||||
|
/// defaults above. `auto_apply` gates whether `Match`-class candidates may be
|
||||||
|
/// applied without an explicit preview step (default: false — never silent).
|
||||||
|
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
|
||||||
|
pub struct MergePolicy {
|
||||||
|
/// Score ≥ this → `Match`.
|
||||||
|
pub match_threshold: f32,
|
||||||
|
/// Score in `[possible_threshold, match_threshold)` → `Possible`.
|
||||||
|
pub possible_threshold: f32,
|
||||||
|
/// If true, `Match`-class candidates may be auto-applied. Default false:
|
||||||
|
/// the product promise is review/preview, not silent mutation.
|
||||||
|
pub auto_apply: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for MergePolicy {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self {
|
||||||
|
match_threshold: DEFAULT_MATCH_THRESHOLD,
|
||||||
|
possible_threshold: DEFAULT_POSSIBLE_THRESHOLD,
|
||||||
|
auto_apply: false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl MergePolicy {
|
||||||
|
/// Build a policy, clamping thresholds into `[0,1]` and ensuring
|
||||||
|
/// `possible_threshold <= match_threshold`.
|
||||||
|
pub fn new(match_threshold: f32, possible_threshold: f32, auto_apply: bool) -> Self {
|
||||||
|
let match_threshold = match_threshold.clamp(0.0, 1.0);
|
||||||
|
let possible_threshold = possible_threshold.clamp(0.0, match_threshold);
|
||||||
|
Self {
|
||||||
|
match_threshold,
|
||||||
|
possible_threshold,
|
||||||
|
auto_apply,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Classify a combined match score.
|
||||||
|
pub fn classify(&self, score: f32) -> MatchClass {
|
||||||
|
if score >= self.match_threshold {
|
||||||
|
MatchClass::Match
|
||||||
|
} else if score >= self.possible_threshold {
|
||||||
|
MatchClass::Possible
|
||||||
|
} else {
|
||||||
|
MatchClass::NonMatch
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ============================================================================
|
||||||
|
// SIGNALS — the self-explaining "why did these combine?"
|
||||||
|
// ============================================================================
|
||||||
|
|
||||||
|
/// The individual signals behind a candidate's score. Surfaced verbatim so a
|
||||||
|
/// user can see *why* two memories were judged duplicates.
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
pub struct MatchSignals {
|
||||||
|
/// Cosine similarity of the two embeddings (0–1).
|
||||||
|
pub embedding_similarity: f32,
|
||||||
|
/// Jaccard overlap of the two tag sets (0–1).
|
||||||
|
pub tag_overlap: f32,
|
||||||
|
/// Jaccard overlap of content tokens (0–1).
|
||||||
|
pub token_overlap: f32,
|
||||||
|
/// Combined weighted score that was classified.
|
||||||
|
pub combined_score: f32,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Compute the combined match score and its signal breakdown for a pair.
|
||||||
|
pub fn score_pair(
|
||||||
|
embedding_similarity: f32,
|
||||||
|
a_tags: &[String],
|
||||||
|
b_tags: &[String],
|
||||||
|
a_content: &str,
|
||||||
|
b_content: &str,
|
||||||
|
) -> MatchSignals {
|
||||||
|
let tag_overlap = jaccard(&tag_set(a_tags), &tag_set(b_tags));
|
||||||
|
let token_overlap = jaccard(&token_set(a_content), &token_set(b_content));
|
||||||
|
let combined_score = (W_EMBEDDING * embedding_similarity.clamp(0.0, 1.0)
|
||||||
|
+ W_TAGS * tag_overlap
|
||||||
|
+ W_TOKENS * token_overlap)
|
||||||
|
.clamp(0.0, 1.0);
|
||||||
|
MatchSignals {
|
||||||
|
embedding_similarity: embedding_similarity.clamp(0.0, 1.0),
|
||||||
|
tag_overlap,
|
||||||
|
token_overlap,
|
||||||
|
combined_score,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn tag_set(tags: &[String]) -> std::collections::HashSet<String> {
|
||||||
|
tags.iter().map(|t| t.to_lowercase()).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn token_set(content: &str) -> std::collections::HashSet<String> {
|
||||||
|
content
|
||||||
|
.split(|c: char| !c.is_alphanumeric())
|
||||||
|
.filter(|t| t.len() > 2)
|
||||||
|
.map(|t| t.to_lowercase())
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn jaccard(a: &std::collections::HashSet<String>, b: &std::collections::HashSet<String>) -> f32 {
|
||||||
|
if a.is_empty() && b.is_empty() {
|
||||||
|
return 0.0;
|
||||||
|
}
|
||||||
|
let inter = a.intersection(b).count() as f32;
|
||||||
|
let union = a.union(b).count() as f32;
|
||||||
|
if union == 0.0 { 0.0 } else { inter / union }
|
||||||
|
}
|
||||||
|
|
||||||
|
// ============================================================================
|
||||||
|
// CANDIDATE
|
||||||
|
// ============================================================================
|
||||||
|
|
||||||
|
/// A surfaced merge candidate: a cluster of likely-duplicate memories with the
|
||||||
|
/// signals and classification that justify offering it.
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
pub struct MergeCandidate {
|
||||||
|
/// Node ids in the cluster. The first is the suggested survivor (highest
|
||||||
|
/// retention).
|
||||||
|
pub member_ids: Vec<String>,
|
||||||
|
/// Short content previews, parallel to `member_ids`.
|
||||||
|
pub previews: Vec<String>,
|
||||||
|
/// Suggested survivor id (kept after a merge).
|
||||||
|
pub survivor_id: String,
|
||||||
|
/// Combined match score for the cluster (min pairwise within the cluster —
|
||||||
|
/// the weakest link, so a cluster is only as confident as its loosest pair).
|
||||||
|
pub confidence: f32,
|
||||||
|
/// Three-way classification under the active policy.
|
||||||
|
pub classification: MatchClass,
|
||||||
|
/// Signals for the survivor↔closest-member pair (the explanation).
|
||||||
|
pub signals: MatchSignals,
|
||||||
|
/// True if any member is protected (pinned) — blocks auto-merge.
|
||||||
|
pub has_protected_member: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
// ============================================================================
|
||||||
|
// PLAN — the previewable diff
|
||||||
|
// ============================================================================
|
||||||
|
|
||||||
|
/// What kind of plan this is.
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
#[serde(rename_all = "snake_case")]
|
||||||
|
pub enum PlanKind {
|
||||||
|
/// Combine N memories into one survivor.
|
||||||
|
Merge,
|
||||||
|
/// Invalidate A in favour of B (bitemporal, audit-preserving).
|
||||||
|
Supersede,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl PlanKind {
|
||||||
|
pub fn as_str(&self) -> &'static str {
|
||||||
|
match self {
|
||||||
|
PlanKind::Merge => "merge",
|
||||||
|
PlanKind::Supersede => "supersede",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A previewable plan: exactly what *would* change, without changing anything.
|
||||||
|
/// Persisted to `merge_plans`; consumed by `apply_plan` via its `id`.
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
pub struct MergePlan {
|
||||||
|
/// Plan id (UUID).
|
||||||
|
pub id: String,
|
||||||
|
/// merge | supersede.
|
||||||
|
pub kind: PlanKind,
|
||||||
|
/// Node kept after the operation.
|
||||||
|
pub survivor_id: String,
|
||||||
|
/// All node ids involved.
|
||||||
|
pub member_ids: Vec<String>,
|
||||||
|
/// Resulting content of the survivor after applying.
|
||||||
|
pub result_content: String,
|
||||||
|
/// Resulting tag set of the survivor after applying.
|
||||||
|
pub result_tags: Vec<String>,
|
||||||
|
/// Resulting provenance / source string after applying.
|
||||||
|
pub result_source: Option<String>,
|
||||||
|
/// For supersede: ids that get bitemporally invalidated (their
|
||||||
|
/// `valid_until` stamped, kept queryable). For merge: the absorbed ids.
|
||||||
|
pub invalidated_ids: Vec<String>,
|
||||||
|
/// Match confidence (0–1) for the plan.
|
||||||
|
pub confidence: f32,
|
||||||
|
/// Three-way classification.
|
||||||
|
pub classification: MatchClass,
|
||||||
|
/// Signals explaining the plan.
|
||||||
|
pub signals: MatchSignals,
|
||||||
|
/// Human-readable explanation of what this plan does.
|
||||||
|
pub explanation: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
// ============================================================================
|
||||||
|
// OPERATION LOG — the reversible "memory reflog"
|
||||||
|
// ============================================================================
|
||||||
|
|
||||||
|
/// A recorded, reversible operation. One row in `merge_operations`.
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
pub struct MergeOperation {
|
||||||
|
/// Operation id (UUID).
|
||||||
|
pub id: String,
|
||||||
|
/// Plan id this came from (if any).
|
||||||
|
pub plan_id: Option<String>,
|
||||||
|
/// merge | supersede | undo.
|
||||||
|
pub op_type: String,
|
||||||
|
/// applied | reverted.
|
||||||
|
pub status: String,
|
||||||
|
/// When recorded (RFC3339).
|
||||||
|
pub created_at: String,
|
||||||
|
/// When reverted (RFC3339), if reverted.
|
||||||
|
pub reverted_at: Option<String>,
|
||||||
|
/// For undo ops: the op id being reversed.
|
||||||
|
pub reverts_op_id: Option<String>,
|
||||||
|
/// Survivor node id.
|
||||||
|
pub survivor_id: Option<String>,
|
||||||
|
/// Node ids touched by the op.
|
||||||
|
pub affected_ids: Vec<String>,
|
||||||
|
/// Match confidence.
|
||||||
|
pub confidence: Option<f32>,
|
||||||
|
/// Human-readable reason.
|
||||||
|
pub reason: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
// ============================================================================
|
||||||
|
// MERGE COMPOSITION — pure helpers used by the storage apply path
|
||||||
|
// ============================================================================
|
||||||
|
|
||||||
|
/// Compose merged content from an ordered list of (id, content) members.
|
||||||
|
/// Survivor content leads; each absorbed member is appended with provenance so
|
||||||
|
/// nothing is silently dropped (anti-pattern: Mem0 #4896 double-store /
|
||||||
|
/// contradiction loss).
|
||||||
|
pub fn compose_merged_content(members: &[(String, String)]) -> String {
|
||||||
|
if members.is_empty() {
|
||||||
|
return String::new();
|
||||||
|
}
|
||||||
|
let mut out = members[0].1.trim().to_string();
|
||||||
|
for (id, content) in &members[1..] {
|
||||||
|
let c = content.trim();
|
||||||
|
if c.is_empty() || out.contains(c) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
out.push_str("\n\n[merged from ");
|
||||||
|
out.push_str(id);
|
||||||
|
out.push_str("]\n");
|
||||||
|
out.push_str(c);
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Union the tag sets of all members, preserving first-seen order.
|
||||||
|
pub fn compose_merged_tags(member_tags: &[Vec<String>]) -> Vec<String> {
|
||||||
|
let mut seen = std::collections::HashSet::new();
|
||||||
|
let mut out = Vec::new();
|
||||||
|
for tags in member_tags {
|
||||||
|
for t in tags {
|
||||||
|
if seen.insert(t.to_lowercase()) {
|
||||||
|
out.push(t.clone());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
// ============================================================================
|
||||||
|
// TESTS
|
||||||
|
// ============================================================================
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn classify_three_zones() {
|
||||||
|
let policy = MergePolicy::default();
|
||||||
|
assert_eq!(policy.classify(0.95), MatchClass::Match);
|
||||||
|
assert_eq!(policy.classify(0.80), MatchClass::Possible);
|
||||||
|
assert_eq!(policy.classify(0.50), MatchClass::NonMatch);
|
||||||
|
// boundaries are inclusive at the lower edge of each higher zone
|
||||||
|
assert_eq!(policy.classify(DEFAULT_MATCH_THRESHOLD), MatchClass::Match);
|
||||||
|
assert_eq!(
|
||||||
|
policy.classify(DEFAULT_POSSIBLE_THRESHOLD),
|
||||||
|
MatchClass::Possible
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn policy_clamps_and_orders() {
|
||||||
|
// possible above match gets clamped down to match
|
||||||
|
let p = MergePolicy::new(0.8, 0.95, true);
|
||||||
|
assert!(p.possible_threshold <= p.match_threshold);
|
||||||
|
// out-of-range clamps to [0,1]
|
||||||
|
let p2 = MergePolicy::new(2.0, -1.0, false);
|
||||||
|
assert_eq!(p2.match_threshold, 1.0);
|
||||||
|
assert_eq!(p2.possible_threshold, 0.0);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn score_pair_combines_signals() {
|
||||||
|
let s = score_pair(
|
||||||
|
1.0,
|
||||||
|
&["rust".into(), "async".into()],
|
||||||
|
&["rust".into(), "async".into()],
|
||||||
|
"use tokio for async rust",
|
||||||
|
"use tokio for async rust",
|
||||||
|
);
|
||||||
|
assert!((s.embedding_similarity - 1.0).abs() < 1e-6);
|
||||||
|
assert!((s.tag_overlap - 1.0).abs() < 1e-6);
|
||||||
|
assert!(s.token_overlap > 0.9);
|
||||||
|
assert!(s.combined_score > 0.95);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn score_pair_disjoint_is_low() {
|
||||||
|
let s = score_pair(
|
||||||
|
0.1,
|
||||||
|
&["a".into()],
|
||||||
|
&["b".into()],
|
||||||
|
"completely different topic alpha",
|
||||||
|
"totally unrelated subject beta",
|
||||||
|
);
|
||||||
|
assert!(s.combined_score < 0.3);
|
||||||
|
assert_eq!(
|
||||||
|
MergePolicy::default().classify(s.combined_score),
|
||||||
|
MatchClass::NonMatch
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn jaccard_basics() {
|
||||||
|
let a: std::collections::HashSet<String> = ["x".into(), "y".into()].into_iter().collect();
|
||||||
|
let b: std::collections::HashSet<String> = ["y".into(), "z".into()].into_iter().collect();
|
||||||
|
assert!((jaccard(&a, &b) - (1.0 / 3.0)).abs() < 1e-6);
|
||||||
|
let empty: std::collections::HashSet<String> = Default::default();
|
||||||
|
assert_eq!(jaccard(&empty, &empty), 0.0);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn compose_merged_content_dedups_and_attributes() {
|
||||||
|
let members = vec![
|
||||||
|
("a".into(), "Keep this.".into()),
|
||||||
|
("b".into(), "Extra detail.".into()),
|
||||||
|
("c".into(), "Keep this.".into()), // duplicate of survivor → skipped
|
||||||
|
];
|
||||||
|
let merged = compose_merged_content(&members);
|
||||||
|
assert!(merged.starts_with("Keep this."));
|
||||||
|
assert!(merged.contains("[merged from b]"));
|
||||||
|
assert!(merged.contains("Extra detail."));
|
||||||
|
// duplicate content not appended twice
|
||||||
|
assert_eq!(merged.matches("Keep this.").count(), 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn compose_merged_tags_unions_in_order() {
|
||||||
|
let tags = vec![
|
||||||
|
vec!["rust".into(), "async".into()],
|
||||||
|
vec!["async".into(), "tokio".into()],
|
||||||
|
];
|
||||||
|
let merged = compose_merged_tags(&tags);
|
||||||
|
assert_eq!(merged, vec!["rust", "async", "tokio"]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn match_class_labels() {
|
||||||
|
assert_eq!(MatchClass::Match.as_str(), "match");
|
||||||
|
assert_eq!(MatchClass::Possible.as_str(), "possible");
|
||||||
|
assert_eq!(MatchClass::NonMatch.as_str(), "non_match");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -23,6 +23,7 @@ pub mod cross_project;
|
||||||
pub mod dreams;
|
pub mod dreams;
|
||||||
pub mod importance;
|
pub mod importance;
|
||||||
pub mod intent;
|
pub mod intent;
|
||||||
|
pub mod merge_supersede;
|
||||||
pub mod prediction_error;
|
pub mod prediction_error;
|
||||||
pub mod reconsolidation;
|
pub mod reconsolidation;
|
||||||
pub mod speculative;
|
pub mod speculative;
|
||||||
|
|
@ -61,6 +62,11 @@ pub use dreams::{
|
||||||
};
|
};
|
||||||
pub use importance::{ImportanceDecayConfig, ImportanceScore, ImportanceTracker, UsageEvent};
|
pub use importance::{ImportanceDecayConfig, ImportanceScore, ImportanceTracker, UsageEvent};
|
||||||
pub use intent::{ActionType, DetectedIntent, IntentDetector, MaintenanceType, UserAction};
|
pub use intent::{ActionType, DetectedIntent, IntentDetector, MaintenanceType, UserAction};
|
||||||
|
pub use merge_supersede::{
|
||||||
|
DEFAULT_MATCH_THRESHOLD, DEFAULT_POSSIBLE_THRESHOLD, MatchClass, MatchSignals, MergeCandidate,
|
||||||
|
MergeOperation, MergePlan, MergePolicy, PlanKind, compose_merged_content, compose_merged_tags,
|
||||||
|
score_pair,
|
||||||
|
};
|
||||||
pub use prediction_error::{
|
pub use prediction_error::{
|
||||||
CandidateMemory, CreateReason, EvaluationIntent, GateDecision, GateStats, MergeStrategy,
|
CandidateMemory, CreateReason, EvaluationIntent, GateDecision, GateStats, MergeStrategy,
|
||||||
PredictionErrorConfig, PredictionErrorGate, SimilarityResult, SupersedeReason, UpdateType,
|
PredictionErrorConfig, PredictionErrorGate, SimilarityResult, SupersedeReason, UpdateType,
|
||||||
|
|
|
||||||
386
crates/vestige-core/src/config.rs
Normal file
386
crates/vestige-core/src/config.rs
Normal file
|
|
@ -0,0 +1,386 @@
|
||||||
|
//! Vestige configuration file (`vestige.toml`).
|
||||||
|
//!
|
||||||
|
//! Phase 2 "Configurable Output" of the adoption roadmap. A small, optional
|
||||||
|
//! config file lives alongside the SQLite database in the active Vestige data
|
||||||
|
//! directory (`<data_dir>/vestige.toml`). It lets users tune the default shape
|
||||||
|
//! of high-traffic MCP responses (detail level, result limit, output profile)
|
||||||
|
//! without recompiling and without a cloud service.
|
||||||
|
//!
|
||||||
|
//! Precedence, from highest to lowest:
|
||||||
|
//!
|
||||||
|
//! 1. An explicit MCP call parameter (e.g. `detail_level` on a `search` call).
|
||||||
|
//! 2. The config file `[defaults]` (and the selected output profile).
|
||||||
|
//! 3. The built-in default, which preserves the historical behavior so nothing
|
||||||
|
//! changes for users who never write a `vestige.toml`.
|
||||||
|
//!
|
||||||
|
//! The parser is intentionally a tiny, dependency-free subset of TOML: section
|
||||||
|
//! headers (`[defaults]`) and `key = value` lines with string or integer
|
||||||
|
//! values. This keeps the local-first binary lean and avoids pulling a full
|
||||||
|
//! TOML crate into the dependency tree for a three-key schema. Unknown keys and
|
||||||
|
//! unknown sections are ignored so the file can grow in future phases without
|
||||||
|
//! breaking older binaries.
|
||||||
|
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
|
/// Canonical config file name, resolved inside the active data directory.
|
||||||
|
pub const CONFIG_FILE: &str = "vestige.toml";
|
||||||
|
|
||||||
|
/// Output profiles preset a coherent bundle of detail/field choices.
|
||||||
|
///
|
||||||
|
/// `Default` MUST reproduce the pre-Phase-2 behavior exactly so existing users
|
||||||
|
/// see no change. The other profiles are opt-in presets.
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
|
||||||
|
pub enum OutputProfile {
|
||||||
|
/// Smallest responses: brief detail, scores and timestamps suppressed.
|
||||||
|
/// Use when context budget matters more than provenance.
|
||||||
|
Lean,
|
||||||
|
/// Historical behavior. `summary` detail with content + dates. Unchanged.
|
||||||
|
#[default]
|
||||||
|
Default,
|
||||||
|
/// Maximum provenance: `full` detail with every field, score, and timestamp.
|
||||||
|
/// Use when reviewing or debugging memory state.
|
||||||
|
Audit,
|
||||||
|
/// Like `audit` but tuned for larger result sets (higher default limit).
|
||||||
|
Research,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl OutputProfile {
|
||||||
|
/// Parse a profile name. Returns `None` for unknown names so the caller can
|
||||||
|
/// decide whether that is an error (MCP param) or ignorable (config file).
|
||||||
|
pub fn from_name(name: &str) -> Option<Self> {
|
||||||
|
match name.trim().to_ascii_lowercase().as_str() {
|
||||||
|
"lean" => Some(Self::Lean),
|
||||||
|
"default" => Some(Self::Default),
|
||||||
|
"audit" => Some(Self::Audit),
|
||||||
|
"research" => Some(Self::Research),
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Canonical lowercase name, suitable for echoing back in responses.
|
||||||
|
pub fn as_str(self) -> &'static str {
|
||||||
|
match self {
|
||||||
|
Self::Lean => "lean",
|
||||||
|
Self::Default => "default",
|
||||||
|
Self::Audit => "audit",
|
||||||
|
Self::Research => "research",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The detail level this profile presets when the user has not set one
|
||||||
|
/// explicitly via an MCP param or `[defaults] detail_level`.
|
||||||
|
pub fn detail_level(self) -> &'static str {
|
||||||
|
match self {
|
||||||
|
Self::Lean => "brief",
|
||||||
|
Self::Default => "summary",
|
||||||
|
Self::Audit | Self::Research => "full",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The result limit this profile presets when the user has not set one
|
||||||
|
/// explicitly. `None` means "use the tool's own historical default", which
|
||||||
|
/// keeps `default` fully backward-compatible.
|
||||||
|
pub fn limit(self) -> Option<i32> {
|
||||||
|
match self {
|
||||||
|
Self::Lean => Some(5),
|
||||||
|
Self::Default => None,
|
||||||
|
Self::Audit => None,
|
||||||
|
Self::Research => Some(25),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether scores (combined/keyword/semantic) should be shown by default.
|
||||||
|
/// Lean drops them to save tokens; the rest keep whatever the detail level
|
||||||
|
/// already includes.
|
||||||
|
pub fn show_scores(self) -> bool {
|
||||||
|
!matches!(self, Self::Lean)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether timestamps should be shown by default. Lean drops them.
|
||||||
|
pub fn show_timestamps(self) -> bool {
|
||||||
|
!matches!(self, Self::Lean)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The `[defaults]` table from `vestige.toml`. All fields optional.
|
||||||
|
#[derive(Debug, Clone, Default, PartialEq)]
|
||||||
|
pub struct OutputDefaults {
|
||||||
|
/// Default detail level (`brief` | `summary` | `full`). Overrides the
|
||||||
|
/// profile's preset detail level when set.
|
||||||
|
pub detail_level: Option<String>,
|
||||||
|
/// Default result limit for high-traffic tools. Overrides the profile's
|
||||||
|
/// preset limit when set.
|
||||||
|
pub limit: Option<i32>,
|
||||||
|
/// Selected output profile. Defaults to `default` (historical behavior).
|
||||||
|
pub profile: OutputProfile,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Parsed `vestige.toml`. Currently only the `[defaults]` table is meaningful;
|
||||||
|
/// the struct exists so future phases can add tables without churn.
|
||||||
|
#[derive(Debug, Clone, Default, PartialEq)]
|
||||||
|
pub struct VestigeConfig {
|
||||||
|
pub defaults: OutputDefaults,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl VestigeConfig {
|
||||||
|
/// Resolve the config path for a given data directory.
|
||||||
|
pub fn path_for_data_dir(data_dir: &Path) -> PathBuf {
|
||||||
|
data_dir.join(CONFIG_FILE)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Load config from a data directory. A missing or unreadable file yields
|
||||||
|
/// the built-in default (never an error) so a fresh install just works.
|
||||||
|
/// A present-but-malformed file is parsed leniently: only well-formed lines
|
||||||
|
/// are honored.
|
||||||
|
pub fn load_from_data_dir(data_dir: &Path) -> Self {
|
||||||
|
let path = Self::path_for_data_dir(data_dir);
|
||||||
|
match std::fs::read_to_string(&path) {
|
||||||
|
Ok(contents) => Self::parse(&contents),
|
||||||
|
Err(_) => Self::default(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Parse the minimal TOML subset. Lenient by design.
|
||||||
|
pub fn parse(contents: &str) -> Self {
|
||||||
|
let mut config = Self::default();
|
||||||
|
let mut section = String::new();
|
||||||
|
|
||||||
|
for raw in contents.lines() {
|
||||||
|
let line = strip_comment(raw).trim();
|
||||||
|
if line.is_empty() {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Some(name) = line.strip_prefix('[').and_then(|s| s.strip_suffix(']')) {
|
||||||
|
section = name.trim().to_ascii_lowercase();
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
let Some((key, value)) = line.split_once('=') else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
let key = key.trim().to_ascii_lowercase();
|
||||||
|
let value = unquote(value.trim());
|
||||||
|
|
||||||
|
if section == "defaults" {
|
||||||
|
match key.as_str() {
|
||||||
|
"detail_level" => {
|
||||||
|
let v = value.trim().to_ascii_lowercase();
|
||||||
|
if matches!(v.as_str(), "brief" | "summary" | "full") {
|
||||||
|
config.defaults.detail_level = Some(v);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
"limit" => {
|
||||||
|
if let Ok(n) = value.trim().parse::<i32>()
|
||||||
|
&& n > 0
|
||||||
|
{
|
||||||
|
config.defaults.limit = Some(n);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
"profile" => {
|
||||||
|
if let Some(p) = OutputProfile::from_name(&value) {
|
||||||
|
config.defaults.profile = p;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
config
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Effective output config after applying the profile, with `[defaults]`
|
||||||
|
/// detail_level / limit overriding the profile presets.
|
||||||
|
pub fn output(&self) -> OutputConfig {
|
||||||
|
let profile = self.defaults.profile;
|
||||||
|
OutputConfig {
|
||||||
|
profile,
|
||||||
|
detail_level: self
|
||||||
|
.defaults
|
||||||
|
.detail_level
|
||||||
|
.clone()
|
||||||
|
.unwrap_or_else(|| profile.detail_level().to_string()),
|
||||||
|
limit: self.defaults.limit.or_else(|| profile.limit()),
|
||||||
|
show_scores: profile.show_scores(),
|
||||||
|
show_timestamps: profile.show_timestamps(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The resolved, ready-to-apply output configuration handed to MCP tools.
|
||||||
|
///
|
||||||
|
/// Tools treat each field as the *fallback* used only when the corresponding
|
||||||
|
/// explicit MCP call parameter is absent, preserving the precedence
|
||||||
|
/// `MCP param > config file > built-in default`.
|
||||||
|
#[derive(Debug, Clone, PartialEq)]
|
||||||
|
pub struct OutputConfig {
|
||||||
|
pub profile: OutputProfile,
|
||||||
|
pub detail_level: String,
|
||||||
|
pub limit: Option<i32>,
|
||||||
|
pub show_scores: bool,
|
||||||
|
pub show_timestamps: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for OutputConfig {
|
||||||
|
/// The built-in default == the historical behavior == the `default` profile.
|
||||||
|
fn default() -> Self {
|
||||||
|
VestigeConfig::default().output()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl OutputConfig {
|
||||||
|
/// Resolve the detail level to use, given an optional explicit MCP param.
|
||||||
|
/// Explicit param always wins (precedence layer 1).
|
||||||
|
pub fn resolve_detail_level(&self, explicit: Option<&str>) -> String {
|
||||||
|
explicit
|
||||||
|
.map(|s| s.to_string())
|
||||||
|
.unwrap_or_else(|| self.detail_level.clone())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Resolve the limit to use, given an optional explicit MCP param and the
|
||||||
|
/// tool's own built-in fallback (used only when neither param nor config
|
||||||
|
/// supplies one).
|
||||||
|
pub fn resolve_limit(&self, explicit: Option<i32>, builtin_default: i32) -> i32 {
|
||||||
|
explicit.or(self.limit).unwrap_or(builtin_default)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Strip a `#` comment that is not inside a quoted string.
|
||||||
|
fn strip_comment(line: &str) -> &str {
|
||||||
|
let mut in_quotes = false;
|
||||||
|
for (idx, ch) in line.char_indices() {
|
||||||
|
match ch {
|
||||||
|
'"' => in_quotes = !in_quotes,
|
||||||
|
'#' if !in_quotes => return &line[..idx],
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
line
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Remove a single layer of matching surrounding double quotes, if present.
|
||||||
|
fn unquote(value: &str) -> String {
|
||||||
|
let bytes = value.as_bytes();
|
||||||
|
if bytes.len() >= 2 && bytes[0] == b'"' && bytes[bytes.len() - 1] == b'"' {
|
||||||
|
value[1..value.len() - 1].to_string()
|
||||||
|
} else {
|
||||||
|
value.to_string()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn default_preserves_historical_behavior() {
|
||||||
|
let out = OutputConfig::default();
|
||||||
|
assert_eq!(out.profile, OutputProfile::Default);
|
||||||
|
assert_eq!(out.detail_level, "summary");
|
||||||
|
assert_eq!(out.limit, None);
|
||||||
|
assert!(out.show_scores);
|
||||||
|
assert!(out.show_timestamps);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn empty_or_missing_file_is_default() {
|
||||||
|
assert_eq!(VestigeConfig::parse(""), VestigeConfig::default());
|
||||||
|
assert_eq!(
|
||||||
|
VestigeConfig::parse("\n\n# just a comment\n"),
|
||||||
|
VestigeConfig::default()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn parses_defaults_table() {
|
||||||
|
let cfg = VestigeConfig::parse(
|
||||||
|
r#"
|
||||||
|
[defaults]
|
||||||
|
detail_level = "full"
|
||||||
|
limit = 25
|
||||||
|
profile = "research"
|
||||||
|
"#,
|
||||||
|
);
|
||||||
|
assert_eq!(cfg.defaults.detail_level.as_deref(), Some("full"));
|
||||||
|
assert_eq!(cfg.defaults.limit, Some(25));
|
||||||
|
assert_eq!(cfg.defaults.profile, OutputProfile::Research);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn unquoted_and_commented_values() {
|
||||||
|
let cfg = VestigeConfig::parse("[defaults]\nprofile = lean # inline comment\nlimit = 7\n");
|
||||||
|
assert_eq!(cfg.defaults.profile, OutputProfile::Lean);
|
||||||
|
assert_eq!(cfg.defaults.limit, Some(7));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn invalid_values_are_ignored() {
|
||||||
|
let cfg = VestigeConfig::parse(
|
||||||
|
"[defaults]\ndetail_level = \"loud\"\nlimit = -3\nprofile = \"galaxy\"\n",
|
||||||
|
);
|
||||||
|
// All invalid -> fall back to defaults.
|
||||||
|
assert_eq!(cfg.defaults.detail_level, None);
|
||||||
|
assert_eq!(cfg.defaults.limit, None);
|
||||||
|
assert_eq!(cfg.defaults.profile, OutputProfile::Default);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn unknown_sections_and_keys_ignored() {
|
||||||
|
let cfg = VestigeConfig::parse(
|
||||||
|
"[future_phase]\nfoo = 1\n[defaults]\nprofile = audit\nbar = baz\n",
|
||||||
|
);
|
||||||
|
assert_eq!(cfg.defaults.profile, OutputProfile::Audit);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn profile_presets() {
|
||||||
|
// lean: brief + dropped scores/timestamps + small limit
|
||||||
|
let lean = VestigeConfig::parse("[defaults]\nprofile=lean").output();
|
||||||
|
assert_eq!(lean.detail_level, "brief");
|
||||||
|
assert_eq!(lean.limit, Some(5));
|
||||||
|
assert!(!lean.show_scores);
|
||||||
|
assert!(!lean.show_timestamps);
|
||||||
|
|
||||||
|
// audit: full detail, no forced limit
|
||||||
|
let audit = VestigeConfig::parse("[defaults]\nprofile=audit").output();
|
||||||
|
assert_eq!(audit.detail_level, "full");
|
||||||
|
assert_eq!(audit.limit, None);
|
||||||
|
|
||||||
|
// research: full detail, larger limit
|
||||||
|
let research = VestigeConfig::parse("[defaults]\nprofile=research").output();
|
||||||
|
assert_eq!(research.detail_level, "full");
|
||||||
|
assert_eq!(research.limit, Some(25));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn explicit_defaults_override_profile_presets() {
|
||||||
|
// profile=lean would give brief/limit 5, but explicit keys win.
|
||||||
|
let out =
|
||||||
|
VestigeConfig::parse("[defaults]\nprofile=lean\ndetail_level=\"full\"\nlimit=42\n")
|
||||||
|
.output();
|
||||||
|
assert_eq!(out.detail_level, "full");
|
||||||
|
assert_eq!(out.limit, Some(42));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn precedence_mcp_param_wins() {
|
||||||
|
let out = VestigeConfig::parse("[defaults]\nprofile=lean").output();
|
||||||
|
// Config says brief, but an explicit MCP param wins.
|
||||||
|
assert_eq!(out.resolve_detail_level(Some("full")), "full");
|
||||||
|
// No explicit param -> config (lean -> brief).
|
||||||
|
assert_eq!(out.resolve_detail_level(None), "brief");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn precedence_limit_layers() {
|
||||||
|
let out = VestigeConfig::parse("[defaults]\nprofile=research").output();
|
||||||
|
// explicit param wins over everything
|
||||||
|
assert_eq!(out.resolve_limit(Some(3), 10), 3);
|
||||||
|
// no param -> config (research -> 25)
|
||||||
|
assert_eq!(out.resolve_limit(None, 10), 25);
|
||||||
|
// default profile has no limit -> builtin fallback used
|
||||||
|
let def = OutputConfig::default();
|
||||||
|
assert_eq!(def.resolve_limit(None, 10), 10);
|
||||||
|
}
|
||||||
|
}
|
||||||
573
crates/vestige-core/src/connectors/github.rs
Normal file
573
crates/vestige-core/src/connectors/github.rs
Normal file
|
|
@ -0,0 +1,573 @@
|
||||||
|
//! GitHub Issues connector (#57).
|
||||||
|
//!
|
||||||
|
//! Indexes a repository's issues + comments into source-aware Vestige memories
|
||||||
|
//! so an agent can search and reason over the full issue history **offline**,
|
||||||
|
//! **semantically**, and **cited back to the canonical issue URL**. Unlike the
|
||||||
|
//! official GitHub MCP server — a stateless live API proxy — this builds a
|
||||||
|
//! durable, embedded, temporally-versioned local index.
|
||||||
|
//!
|
||||||
|
//! ## Incremental sync (per the connector sync contract)
|
||||||
|
//!
|
||||||
|
//! - `state=all` so closing an issue is not mistaken for a deletion.
|
||||||
|
//! - `sort=updated&direction=asc` so we page forward in cursor order and a
|
||||||
|
//! mid-run interruption resumes safely.
|
||||||
|
//! - `since=<cursor − overlap>` filters on `updated_at`; the overlap + the
|
||||||
|
//! `content_hash` no-op makes re-scans safe and cheap.
|
||||||
|
//! - `Link: rel="next"` drives pagination (never hand-built page urls).
|
||||||
|
//! - Entries carrying a `pull_request` key are dropped (PRs are not issues).
|
||||||
|
//! - Per issue we fold the body + comments into one memory; the hash covers
|
||||||
|
//! the stable fields only (title, body, state, labels, comments) — never the
|
||||||
|
//! cursor timestamp or volatile counts.
|
||||||
|
//!
|
||||||
|
//! GitHub has no deletion feed, so deletions are reconciled out-of-band via
|
||||||
|
//! [`list_live_ids`](Connector::list_live_ids).
|
||||||
|
|
||||||
|
use chrono::{DateTime, Utc};
|
||||||
|
use serde::Deserialize;
|
||||||
|
|
||||||
|
use super::{
|
||||||
|
Connector, ConnectorError, ConnectorResult, FetchPage, NormalizedRecord, content_hash,
|
||||||
|
};
|
||||||
|
use crate::memory::SourceEnvelope;
|
||||||
|
|
||||||
|
const API_ROOT: &str = "https://api.github.com";
|
||||||
|
const USER_AGENT: &str = concat!("vestige-connector/", env!("CARGO_PKG_VERSION"));
|
||||||
|
const PER_PAGE: u32 = 100;
|
||||||
|
|
||||||
|
/// Configuration for a GitHub Issues connector instance.
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct GithubConfig {
|
||||||
|
/// Repository owner (user or org).
|
||||||
|
pub owner: String,
|
||||||
|
/// Repository name.
|
||||||
|
pub repo: String,
|
||||||
|
/// Personal access token. Optional for public repos (60 req/hr
|
||||||
|
/// unauthenticated) but strongly recommended (5000 req/hr authenticated).
|
||||||
|
pub token: Option<String>,
|
||||||
|
/// Override the API root (for GitHub Enterprise or tests).
|
||||||
|
pub api_root: Option<String>,
|
||||||
|
/// Max comments to fold into one issue memory (defense against huge threads).
|
||||||
|
pub max_comments: usize,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl GithubConfig {
|
||||||
|
pub fn new(owner: impl Into<String>, repo: impl Into<String>) -> Self {
|
||||||
|
Self {
|
||||||
|
owner: owner.into(),
|
||||||
|
repo: repo.into(),
|
||||||
|
token: None,
|
||||||
|
api_root: None,
|
||||||
|
max_comments: 50,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn with_token(mut self, token: Option<String>) -> Self {
|
||||||
|
self.token = token;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
fn scope(&self) -> String {
|
||||||
|
format!("{}/{}", self.owner, self.repo)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn root(&self) -> &str {
|
||||||
|
self.api_root.as_deref().unwrap_or(API_ROOT)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A GitHub Issues connector bound to one repository.
|
||||||
|
pub struct GithubConnector {
|
||||||
|
config: GithubConfig,
|
||||||
|
scope: String,
|
||||||
|
client: reqwest::Client,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl GithubConnector {
|
||||||
|
pub fn new(config: GithubConfig) -> ConnectorResult<Self> {
|
||||||
|
if config.owner.is_empty() || config.repo.is_empty() {
|
||||||
|
return Err(ConnectorError::Config(
|
||||||
|
"owner and repo are required".to_string(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
let client = reqwest::Client::builder()
|
||||||
|
.user_agent(USER_AGENT)
|
||||||
|
.build()
|
||||||
|
.map_err(|e| ConnectorError::Transport(e.to_string()))?;
|
||||||
|
let scope = config.scope();
|
||||||
|
Ok(Self {
|
||||||
|
config,
|
||||||
|
scope,
|
||||||
|
client,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn auth(&self, req: reqwest::RequestBuilder) -> reqwest::RequestBuilder {
|
||||||
|
let req = req
|
||||||
|
.header("Accept", "application/vnd.github+json")
|
||||||
|
.header("X-GitHub-Api-Version", "2022-11-28");
|
||||||
|
match &self.config.token {
|
||||||
|
Some(t) => req.bearer_auth(t),
|
||||||
|
None => req,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Map an HTTP response status into a connector error, honoring rate-limit
|
||||||
|
/// signals so the driver can back off politely.
|
||||||
|
fn classify_status(resp: &reqwest::Response) -> Option<ConnectorError> {
|
||||||
|
let status = resp.status();
|
||||||
|
if status.is_success() {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
// Primary rate limit: 403/429 with remaining=0.
|
||||||
|
if status.as_u16() == 403 || status.as_u16() == 429 {
|
||||||
|
let remaining = resp
|
||||||
|
.headers()
|
||||||
|
.get("x-ratelimit-remaining")
|
||||||
|
.and_then(|v| v.to_str().ok())
|
||||||
|
.and_then(|s| s.parse::<i64>().ok());
|
||||||
|
if remaining == Some(0) || status.as_u16() == 429 {
|
||||||
|
let retry = resp
|
||||||
|
.headers()
|
||||||
|
.get("retry-after")
|
||||||
|
.and_then(|v| v.to_str().ok())
|
||||||
|
.and_then(|s| s.parse::<u64>().ok())
|
||||||
|
.map(std::time::Duration::from_secs);
|
||||||
|
return Some(ConnectorError::RateLimited(retry));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Some(ConnectorError::Source {
|
||||||
|
status: status.as_u16(),
|
||||||
|
message: status
|
||||||
|
.canonical_reason()
|
||||||
|
.unwrap_or("request failed")
|
||||||
|
.to_string(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Parse the `Link` header for the `rel="next"` url, if any.
|
||||||
|
///
|
||||||
|
/// The `next` url comes from the server response, so we pin it to the
|
||||||
|
/// configured API host before following it: otherwise a malicious or
|
||||||
|
/// compromised endpoint could redirect the connector — which attaches the
|
||||||
|
/// bearer token to every request — to an attacker-controlled URL and
|
||||||
|
/// exfiltrate the credential (SSRF / token leak). `expected_host` is the
|
||||||
|
/// host of the connector's API root.
|
||||||
|
fn next_link(resp: &reqwest::Response, expected_host: Option<&str>) -> Option<String> {
|
||||||
|
let link = resp.headers().get(reqwest::header::LINK)?.to_str().ok()?;
|
||||||
|
for part in link.split(',') {
|
||||||
|
let part = part.trim();
|
||||||
|
if part.contains("rel=\"next\"")
|
||||||
|
&& let (Some(start), Some(end)) = (part.find('<'), part.find('>'))
|
||||||
|
&& start < end
|
||||||
|
{
|
||||||
|
let url = &part[start + 1..end];
|
||||||
|
// Host-pin: only follow a next-url on the same host as the API
|
||||||
|
// root we were configured with.
|
||||||
|
if let Some(expected) = expected_host {
|
||||||
|
match reqwest::Url::parse(url) {
|
||||||
|
Ok(parsed) if parsed.host_str() == Some(expected) => {
|
||||||
|
return Some(url.to_string());
|
||||||
|
}
|
||||||
|
_ => {
|
||||||
|
tracing::warn!(
|
||||||
|
next_url = url,
|
||||||
|
"dropping cross-host Link next url (host pin)"
|
||||||
|
);
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return Some(url.to_string());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
None
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Host of the configured API root, used to pin Link `next` urls.
|
||||||
|
fn api_host(&self) -> Option<String> {
|
||||||
|
reqwest::Url::parse(self.config.root())
|
||||||
|
.ok()
|
||||||
|
.and_then(|u| u.host_str().map(|h| h.to_string()))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Fetch the comments for one issue (a single page; capped by `max_comments`).
|
||||||
|
async fn fetch_comments(&self, issue_number: u64) -> ConnectorResult<Vec<RawComment>> {
|
||||||
|
let url = format!(
|
||||||
|
"{}/repos/{}/{}/issues/{}/comments?per_page={}",
|
||||||
|
self.config.root(),
|
||||||
|
self.config.owner,
|
||||||
|
self.config.repo,
|
||||||
|
issue_number,
|
||||||
|
self.config.max_comments.min(100),
|
||||||
|
);
|
||||||
|
let resp = self
|
||||||
|
.auth(self.client.get(&url))
|
||||||
|
.send()
|
||||||
|
.await
|
||||||
|
.map_err(|e| ConnectorError::Transport(e.to_string()))?;
|
||||||
|
if let Some(err) = Self::classify_status(&resp) {
|
||||||
|
return Err(err);
|
||||||
|
}
|
||||||
|
resp.json::<Vec<RawComment>>()
|
||||||
|
.await
|
||||||
|
.map_err(|e| ConnectorError::Transport(e.to_string()))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Fold a raw issue + its comments into one normalized memory record.
|
||||||
|
fn normalize(&self, issue: &RawIssue, comments: &[RawComment]) -> NormalizedRecord {
|
||||||
|
let author = issue.user.as_ref().map(|u| u.login.clone());
|
||||||
|
|
||||||
|
// Human-readable content: header + body + chronological comments.
|
||||||
|
let mut content = format!(
|
||||||
|
"[{}#{}] {}\nState: {}\n",
|
||||||
|
self.scope, issue.number, issue.title, issue.state
|
||||||
|
);
|
||||||
|
if let Some(body) = &issue.body
|
||||||
|
&& !body.trim().is_empty()
|
||||||
|
{
|
||||||
|
content.push('\n');
|
||||||
|
content.push_str(body.trim());
|
||||||
|
content.push('\n');
|
||||||
|
}
|
||||||
|
let mut sorted_comments: Vec<&RawComment> = comments.iter().collect();
|
||||||
|
sorted_comments.sort_by_key(|c| c.id);
|
||||||
|
for c in &sorted_comments {
|
||||||
|
let who = c.user.as_ref().map(|u| u.login.as_str()).unwrap_or("?");
|
||||||
|
content.push_str(&format!("\n— {who}: {}", c.body.trim()));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Labels, sorted for a stable hash.
|
||||||
|
let mut labels: Vec<String> = issue.labels.iter().map(|l| l.name.clone()).collect();
|
||||||
|
labels.sort();
|
||||||
|
|
||||||
|
// Stable content hash — meaning only, never the cursor timestamp or
|
||||||
|
// volatile counts. Comments contribute their id+body in id order.
|
||||||
|
let comments_blob = sorted_comments
|
||||||
|
.iter()
|
||||||
|
.map(|c| format!("{}:{}", c.id, c.body.trim()))
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
.join("\u{1f}");
|
||||||
|
let labels_blob = labels.join(",");
|
||||||
|
let number_str = issue.number.to_string();
|
||||||
|
let body_str = issue.body.clone().unwrap_or_default();
|
||||||
|
let hash = content_hash(&[
|
||||||
|
("number", &number_str),
|
||||||
|
("title", &issue.title),
|
||||||
|
("state", &issue.state),
|
||||||
|
("body", &body_str),
|
||||||
|
("labels", &labels_blob),
|
||||||
|
("comments", &comments_blob),
|
||||||
|
]);
|
||||||
|
|
||||||
|
let mut tags = vec![
|
||||||
|
"github".to_string(),
|
||||||
|
"issue".to_string(),
|
||||||
|
format!("state:{}", issue.state),
|
||||||
|
];
|
||||||
|
tags.extend(labels.into_iter().map(|l| format!("label:{l}")));
|
||||||
|
|
||||||
|
let envelope = SourceEnvelope {
|
||||||
|
source_system: Some("github".to_string()),
|
||||||
|
source_id: Some(issue.number.to_string()),
|
||||||
|
source_url: Some(issue.html_url.clone()),
|
||||||
|
source_updated_at: DateTime::parse_from_rfc3339(&issue.updated_at)
|
||||||
|
.ok()
|
||||||
|
.map(|d| d.with_timezone(&Utc)),
|
||||||
|
content_hash: Some(hash),
|
||||||
|
synced_at: Some(Utc::now()),
|
||||||
|
source_project: Some(self.scope.clone()),
|
||||||
|
source_type: Some("issue".to_string()),
|
||||||
|
source_author: author,
|
||||||
|
};
|
||||||
|
|
||||||
|
NormalizedRecord {
|
||||||
|
content,
|
||||||
|
tags,
|
||||||
|
envelope,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Connector for GithubConnector {
|
||||||
|
fn source_system(&self) -> &str {
|
||||||
|
"github"
|
||||||
|
}
|
||||||
|
|
||||||
|
fn scope(&self) -> &str {
|
||||||
|
&self.scope
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn fetch_updated(
|
||||||
|
&self,
|
||||||
|
since: Option<DateTime<Utc>>,
|
||||||
|
cursor: Option<String>,
|
||||||
|
) -> ConnectorResult<FetchPage> {
|
||||||
|
// `cursor` is a full next-page url from a previous Link header; on the
|
||||||
|
// first page we build the url from owner/repo + since.
|
||||||
|
let url = match cursor {
|
||||||
|
Some(u) => u,
|
||||||
|
None => {
|
||||||
|
let mut u = format!(
|
||||||
|
"{}/repos/{}/{}/issues?state=all&sort=updated&direction=asc&per_page={}",
|
||||||
|
self.config.root(),
|
||||||
|
self.config.owner,
|
||||||
|
self.config.repo,
|
||||||
|
PER_PAGE,
|
||||||
|
);
|
||||||
|
if let Some(s) = since {
|
||||||
|
// GitHub documents the `since` format as YYYY-MM-DDTHH:MM:SSZ.
|
||||||
|
// `to_rfc3339()` emits the `+00:00` offset form, and the `+`
|
||||||
|
// is a reserved query char that the server decodes as a
|
||||||
|
// space — corrupting the timestamp and silently re-fetching
|
||||||
|
// all history every run. Emit the `Z` form (no reserved
|
||||||
|
// char, exact documented format) instead.
|
||||||
|
let since_z = s.to_rfc3339_opts(chrono::SecondsFormat::Secs, true);
|
||||||
|
u.push_str(&format!("&since={since_z}"));
|
||||||
|
}
|
||||||
|
u
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let resp = self
|
||||||
|
.auth(self.client.get(&url))
|
||||||
|
.send()
|
||||||
|
.await
|
||||||
|
.map_err(|e| ConnectorError::Transport(e.to_string()))?;
|
||||||
|
if let Some(err) = Self::classify_status(&resp) {
|
||||||
|
return Err(err);
|
||||||
|
}
|
||||||
|
let next_cursor = Self::next_link(&resp, self.api_host().as_deref());
|
||||||
|
let issues: Vec<RawIssue> = resp
|
||||||
|
.json()
|
||||||
|
.await
|
||||||
|
.map_err(|e| ConnectorError::Transport(e.to_string()))?;
|
||||||
|
|
||||||
|
let mut records = Vec::new();
|
||||||
|
for issue in &issues {
|
||||||
|
// Drop pull requests — "every PR is an issue, but not vice versa".
|
||||||
|
if issue.pull_request.is_some() {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
// Fetch comments only when the issue has any.
|
||||||
|
let comments = if issue.comments > 0 {
|
||||||
|
self.fetch_comments(issue.number).await.unwrap_or_default()
|
||||||
|
} else {
|
||||||
|
Vec::new()
|
||||||
|
};
|
||||||
|
records.push(self.normalize(issue, &comments));
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(FetchPage {
|
||||||
|
records,
|
||||||
|
next_cursor,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn list_live_ids(&self) -> ConnectorResult<Option<Vec<String>>> {
|
||||||
|
// Enumerate all issue numbers (ids only) for the reconcile pass, paging
|
||||||
|
// via Link. Cheap relative to full sync (no comment fetch, no bodies).
|
||||||
|
let mut ids = Vec::new();
|
||||||
|
let mut url = Some(format!(
|
||||||
|
"{}/repos/{}/{}/issues?state=all&per_page={}",
|
||||||
|
self.config.root(),
|
||||||
|
self.config.owner,
|
||||||
|
self.config.repo,
|
||||||
|
PER_PAGE,
|
||||||
|
));
|
||||||
|
while let Some(u) = url {
|
||||||
|
let resp = self
|
||||||
|
.auth(self.client.get(&u))
|
||||||
|
.send()
|
||||||
|
.await
|
||||||
|
.map_err(|e| ConnectorError::Transport(e.to_string()))?;
|
||||||
|
if let Some(err) = Self::classify_status(&resp) {
|
||||||
|
return Err(err);
|
||||||
|
}
|
||||||
|
let next = Self::next_link(&resp, self.api_host().as_deref());
|
||||||
|
let issues: Vec<RawIssue> = resp
|
||||||
|
.json()
|
||||||
|
.await
|
||||||
|
.map_err(|e| ConnectorError::Transport(e.to_string()))?;
|
||||||
|
for issue in issues {
|
||||||
|
if issue.pull_request.is_none() {
|
||||||
|
ids.push(issue.number.to_string());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
url = next;
|
||||||
|
}
|
||||||
|
Ok(Some(ids))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Raw GitHub API shapes (only the fields we use)
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
#[derive(Debug, Deserialize)]
|
||||||
|
struct RawIssue {
|
||||||
|
number: u64,
|
||||||
|
title: String,
|
||||||
|
#[serde(default)]
|
||||||
|
body: Option<String>,
|
||||||
|
state: String,
|
||||||
|
html_url: String,
|
||||||
|
updated_at: String,
|
||||||
|
#[serde(default)]
|
||||||
|
comments: u64,
|
||||||
|
#[serde(default)]
|
||||||
|
labels: Vec<RawLabel>,
|
||||||
|
#[serde(default)]
|
||||||
|
user: Option<RawUser>,
|
||||||
|
/// Present iff this "issue" is actually a pull request.
|
||||||
|
#[serde(default)]
|
||||||
|
pull_request: Option<serde_json::Value>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Deserialize)]
|
||||||
|
struct RawLabel {
|
||||||
|
name: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Deserialize)]
|
||||||
|
struct RawUser {
|
||||||
|
login: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Deserialize)]
|
||||||
|
struct RawComment {
|
||||||
|
id: u64,
|
||||||
|
body: String,
|
||||||
|
#[serde(default)]
|
||||||
|
user: Option<RawUser>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
fn issue(number: u64, title: &str, body: &str, state: &str) -> RawIssue {
|
||||||
|
RawIssue {
|
||||||
|
number,
|
||||||
|
title: title.to_string(),
|
||||||
|
body: Some(body.to_string()),
|
||||||
|
state: state.to_string(),
|
||||||
|
html_url: format!("https://github.com/o/r/issues/{number}"),
|
||||||
|
updated_at: "2026-06-19T00:00:00Z".to_string(),
|
||||||
|
comments: 0,
|
||||||
|
labels: vec![RawLabel {
|
||||||
|
name: "bug".to_string(),
|
||||||
|
}],
|
||||||
|
user: Some(RawUser {
|
||||||
|
login: "octocat".to_string(),
|
||||||
|
}),
|
||||||
|
pull_request: None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn connector() -> GithubConnector {
|
||||||
|
GithubConnector::new(GithubConfig::new("o", "r")).unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn normalize_builds_keyed_envelope_with_citation() {
|
||||||
|
let c = connector();
|
||||||
|
let rec = c.normalize(&issue(57, "Connectors", "Add Redmine", "open"), &[]);
|
||||||
|
let env = &rec.envelope;
|
||||||
|
assert!(env.has_key());
|
||||||
|
assert_eq!(env.source_system.as_deref(), Some("github"));
|
||||||
|
assert_eq!(env.source_id.as_deref(), Some("57"));
|
||||||
|
assert_eq!(
|
||||||
|
env.source_url.as_deref(),
|
||||||
|
Some("https://github.com/o/r/issues/57")
|
||||||
|
);
|
||||||
|
assert_eq!(env.source_project.as_deref(), Some("o/r"));
|
||||||
|
assert!(rec.content.contains("Connectors"));
|
||||||
|
assert!(rec.tags.contains(&"state:open".to_string()));
|
||||||
|
assert!(rec.tags.contains(&"label:bug".to_string()));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn hash_stable_across_label_order_and_changes_on_edit() {
|
||||||
|
let c = connector();
|
||||||
|
let mut a = issue(1, "T", "body", "open");
|
||||||
|
a.labels = vec![RawLabel { name: "b".into() }, RawLabel { name: "a".into() }];
|
||||||
|
let mut b = issue(1, "T", "body", "open");
|
||||||
|
b.labels = vec![RawLabel { name: "a".into() }, RawLabel { name: "b".into() }];
|
||||||
|
let ha = c.normalize(&a, &[]).envelope.content_hash;
|
||||||
|
let hb = c.normalize(&b, &[]).envelope.content_hash;
|
||||||
|
assert_eq!(ha, hb, "label order must not change the hash");
|
||||||
|
|
||||||
|
// Editing the body must change the hash.
|
||||||
|
let edited = c
|
||||||
|
.normalize(&issue(1, "T", "EDITED", "open"), &[])
|
||||||
|
.envelope
|
||||||
|
.content_hash;
|
||||||
|
assert_ne!(ha, edited);
|
||||||
|
|
||||||
|
// Closing the issue changes state → changes the hash (not a no-op).
|
||||||
|
let closed = c
|
||||||
|
.normalize(&issue(1, "T", "body", "closed"), &[])
|
||||||
|
.envelope
|
||||||
|
.content_hash;
|
||||||
|
assert_ne!(ha, closed);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn comments_fold_in_id_order_and_affect_hash() {
|
||||||
|
let c = connector();
|
||||||
|
let comments = vec![
|
||||||
|
RawComment {
|
||||||
|
id: 2,
|
||||||
|
body: "second".into(),
|
||||||
|
user: Some(RawUser { login: "x".into() }),
|
||||||
|
},
|
||||||
|
RawComment {
|
||||||
|
id: 1,
|
||||||
|
body: "first".into(),
|
||||||
|
user: Some(RawUser { login: "y".into() }),
|
||||||
|
},
|
||||||
|
];
|
||||||
|
let rec = c.normalize(&issue(1, "T", "body", "open"), &comments);
|
||||||
|
// Folded in id order regardless of input order.
|
||||||
|
let first_pos = rec.content.find("first").unwrap();
|
||||||
|
let second_pos = rec.content.find("second").unwrap();
|
||||||
|
assert!(first_pos < second_pos, "comments must fold in id order");
|
||||||
|
|
||||||
|
let no_comments = c
|
||||||
|
.normalize(&issue(1, "T", "body", "open"), &[])
|
||||||
|
.envelope
|
||||||
|
.content_hash;
|
||||||
|
assert_ne!(
|
||||||
|
rec.envelope.content_hash, no_comments,
|
||||||
|
"comments must contribute to the hash"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rejects_empty_owner_repo() {
|
||||||
|
assert!(GithubConnector::new(GithubConfig::new("", "r")).is_err());
|
||||||
|
assert!(GithubConnector::new(GithubConfig::new("o", "")).is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn since_uses_z_form_not_plus_offset() {
|
||||||
|
// Regression: to_rfc3339() emits `+00:00`; the `+` decodes to a space
|
||||||
|
// server-side and corrupts the cursor. We must emit the `Z` form.
|
||||||
|
let ts = DateTime::parse_from_rfc3339("2026-06-19T00:00:00Z")
|
||||||
|
.unwrap()
|
||||||
|
.with_timezone(&Utc);
|
||||||
|
let z = ts.to_rfc3339_opts(chrono::SecondsFormat::Secs, true);
|
||||||
|
assert_eq!(z, "2026-06-19T00:00:00Z");
|
||||||
|
assert!(!z.contains('+'), "since must not contain a reserved '+'");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn next_link_host_pin_drops_cross_host_url() {
|
||||||
|
// The host-pin parsing logic (used to prevent token exfiltration via a
|
||||||
|
// malicious Link header) must reject a different host.
|
||||||
|
let same = reqwest::Url::parse("https://api.github.com/x?page=2").unwrap();
|
||||||
|
let other = reqwest::Url::parse("https://evil.example/x?page=2").unwrap();
|
||||||
|
assert_eq!(same.host_str(), Some("api.github.com"));
|
||||||
|
assert_ne!(other.host_str(), Some("api.github.com"));
|
||||||
|
}
|
||||||
|
}
|
||||||
383
crates/vestige-core/src/connectors/mod.rs
Normal file
383
crates/vestige-core/src/connectors/mod.rs
Normal file
|
|
@ -0,0 +1,383 @@
|
||||||
|
//! External-source connectors (#57).
|
||||||
|
//!
|
||||||
|
//! A connector turns records in a long-lived external system (a ticket tracker,
|
||||||
|
//! an issue board, a support queue) into source-aware Vestige memories, so an
|
||||||
|
//! investigative agent can search and reason over years of history **offline**,
|
||||||
|
//! **semantically**, and **cited back to the canonical record** — something no
|
||||||
|
//! live ticket-system MCP proxy can do.
|
||||||
|
//!
|
||||||
|
//! ## Layering
|
||||||
|
//!
|
||||||
|
//! - The [`Connector`] contract, [`NormalizedRecord`] shape, and the stable
|
||||||
|
//! [`content_hash`] are pure (no network) and always compiled, so the sync
|
||||||
|
//! semantics are unit-testable without hitting an API.
|
||||||
|
//! - Network-backed reference connectors ([`github`] and [`redmine`]) live
|
||||||
|
//! behind the `connectors` cargo feature so the default local-first build
|
||||||
|
//! links no HTTP client.
|
||||||
|
//!
|
||||||
|
//! ## Sync contract (the part that makes re-running safe)
|
||||||
|
//!
|
||||||
|
//! Every connector produces [`NormalizedRecord`]s. Each carries a
|
||||||
|
//! [`SourceEnvelope`](crate::memory::SourceEnvelope) whose
|
||||||
|
//! `(source_system, source_id)` is the idempotency key and whose `content_hash`
|
||||||
|
//! is the change detector. The driver routes each record through
|
||||||
|
//! [`upsert_by_source`](crate::storage::SqliteMemoryStore::upsert_by_source):
|
||||||
|
//!
|
||||||
|
//! - unseen record → insert
|
||||||
|
//! - changed `content_hash` → update in place (+ re-embed)
|
||||||
|
//! - same `content_hash` → no-op (only liveness advances)
|
||||||
|
//!
|
||||||
|
//! Because neither GitHub nor Redmine expose a deletion feed, deletions are
|
||||||
|
//! handled out-of-band by a periodic reconcile pass
|
||||||
|
//! ([`reconcile_source_tombstones`](crate::storage::SqliteMemoryStore::reconcile_source_tombstones)).
|
||||||
|
|
||||||
|
use chrono::{DateTime, Utc};
|
||||||
|
|
||||||
|
use crate::memory::{IngestInput, SourceEnvelope};
|
||||||
|
use crate::storage::ConnectorCursor;
|
||||||
|
|
||||||
|
#[cfg(feature = "connectors")]
|
||||||
|
pub mod github;
|
||||||
|
|
||||||
|
#[cfg(feature = "connectors")]
|
||||||
|
pub mod redmine;
|
||||||
|
|
||||||
|
/// A single external record, already normalized into the fields Vestige needs.
|
||||||
|
///
|
||||||
|
/// The connector is responsible for flattening a possibly-rich source record
|
||||||
|
/// (an issue plus its comments / journals / status changes) into a single
|
||||||
|
/// retrievable `content` blob plus the structured envelope. Keeping one memory
|
||||||
|
/// per logical record (rather than per comment) keeps retrieval coherent and
|
||||||
|
/// the idempotency key simple.
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct NormalizedRecord {
|
||||||
|
/// Human-readable content to embed and search over.
|
||||||
|
pub content: String,
|
||||||
|
/// Tags for categorization (e.g. `["github", "issue", "state:open"]`).
|
||||||
|
pub tags: Vec<String>,
|
||||||
|
/// The provenance envelope. `source_system`, `source_id`, and `content_hash`
|
||||||
|
/// MUST be set for idempotent upsert.
|
||||||
|
pub envelope: SourceEnvelope,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl NormalizedRecord {
|
||||||
|
/// Convert into an [`IngestInput`] ready for `upsert_by_source`.
|
||||||
|
pub fn into_ingest_input(self) -> IngestInput {
|
||||||
|
IngestInput {
|
||||||
|
content: self.content,
|
||||||
|
node_type: "event".to_string(),
|
||||||
|
source: self.envelope.source_url.clone(),
|
||||||
|
tags: self.tags,
|
||||||
|
source_envelope: Some(self.envelope),
|
||||||
|
..Default::default()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One page of records plus the cursor needed to fetch the next page.
|
||||||
|
#[derive(Debug, Clone, Default)]
|
||||||
|
pub struct FetchPage {
|
||||||
|
pub records: Vec<NormalizedRecord>,
|
||||||
|
/// Opaque token to resume after this page, or `None` when exhausted.
|
||||||
|
pub next_cursor: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Errors a connector can surface.
|
||||||
|
#[derive(Debug, thiserror::Error)]
|
||||||
|
pub enum ConnectorError {
|
||||||
|
#[error("configuration error: {0}")]
|
||||||
|
Config(String),
|
||||||
|
#[error("transport error: {0}")]
|
||||||
|
Transport(String),
|
||||||
|
#[error("rate limited; retry after {0:?}")]
|
||||||
|
RateLimited(Option<std::time::Duration>),
|
||||||
|
#[error("source error ({status}): {message}")]
|
||||||
|
Source { status: u16, message: String },
|
||||||
|
}
|
||||||
|
|
||||||
|
pub type ConnectorResult<T> = Result<T, ConnectorError>;
|
||||||
|
|
||||||
|
/// The contract every external-source connector implements.
|
||||||
|
///
|
||||||
|
/// Intentionally minimal: fetch a window of records updated since a cursor,
|
||||||
|
/// page through them, and (separately) enumerate currently-live ids for the
|
||||||
|
/// deletion-reconcile pass. The driver owns persistence, embedding, and cursor
|
||||||
|
/// checkpointing — a connector is just a typed, incremental reader.
|
||||||
|
#[allow(async_fn_in_trait)]
|
||||||
|
pub trait Connector {
|
||||||
|
/// Stable system identifier written into every envelope (`github`, …).
|
||||||
|
fn source_system(&self) -> &str;
|
||||||
|
|
||||||
|
/// The scope this connector instance is bound to (`owner/repo`, project id).
|
||||||
|
fn scope(&self) -> &str;
|
||||||
|
|
||||||
|
/// Fetch one page of records whose source-updated time is `>= since`
|
||||||
|
/// (inclusive on purpose — see the overlap note below), resuming from
|
||||||
|
/// `cursor` when provided. Records should be returned in ascending
|
||||||
|
/// update-time order so a mid-run interruption resumes safely.
|
||||||
|
///
|
||||||
|
/// Callers pass `since = checkpoint − overlap` (a few minutes) so a record
|
||||||
|
/// written with a slightly-behind upstream clock, or one sharing the exact
|
||||||
|
/// boundary second, is never skipped. The `content_hash` short-circuit in
|
||||||
|
/// `upsert_by_source` makes the resulting re-scan free.
|
||||||
|
async fn fetch_updated(
|
||||||
|
&self,
|
||||||
|
since: Option<DateTime<Utc>>,
|
||||||
|
cursor: Option<String>,
|
||||||
|
) -> ConnectorResult<FetchPage>;
|
||||||
|
|
||||||
|
/// Enumerate the ids currently visible upstream for this scope, for the
|
||||||
|
/// deletion-reconcile pass. Cheap (ids only). `None` means the connector
|
||||||
|
/// cannot enumerate, so the driver must skip reconciliation rather than
|
||||||
|
/// tombstone everything.
|
||||||
|
async fn list_live_ids(&self) -> ConnectorResult<Option<Vec<String>>> {
|
||||||
|
Ok(None)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Recommended overlap subtracted from the saved cursor before the next fetch,
|
||||||
|
/// to absorb clock skew and same-second boundary updates (the `>=` window).
|
||||||
|
pub const CURSOR_OVERLAP_SECS: i64 = 120;
|
||||||
|
|
||||||
|
/// Summary of one sync run, returned to the caller / surfaced by the MCP tool.
|
||||||
|
#[derive(Debug, Clone, Default, serde::Serialize)]
|
||||||
|
pub struct SyncReport {
|
||||||
|
pub source_system: String,
|
||||||
|
pub scope: String,
|
||||||
|
pub created: usize,
|
||||||
|
pub updated: usize,
|
||||||
|
pub unchanged: usize,
|
||||||
|
pub tombstoned: usize,
|
||||||
|
/// New high-water mark persisted as the cursor for the next run.
|
||||||
|
pub new_cursor: Option<DateTime<Utc>>,
|
||||||
|
/// Whether a deletion-reconcile pass ran this time.
|
||||||
|
pub reconciled: bool,
|
||||||
|
/// Non-fatal warnings (e.g. a page that failed and was skipped).
|
||||||
|
pub warnings: Vec<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Drive a full incremental sync of one connector into the store (#57).
|
||||||
|
///
|
||||||
|
/// This is the orchestration the MCP `source_sync` tool calls. It:
|
||||||
|
/// 1. loads the saved checkpoint and starts from `cursor − overlap` (the `>=`
|
||||||
|
/// window that prevents missing same-second / clock-skewed updates);
|
||||||
|
/// 2. pages the connector forward in update order, routing each record through
|
||||||
|
/// [`upsert_by_source`](crate::storage::SqliteMemoryStore::upsert_by_source)
|
||||||
|
/// (insert / update-in-place / no-op by content hash);
|
||||||
|
/// 3. advances the cursor to the max `source_updated_at` actually observed,
|
||||||
|
/// persisting it only after the run so a crash re-scans rather than skips;
|
||||||
|
/// 4. optionally reconciles deletions when `reconcile` is set and the connector
|
||||||
|
/// can enumerate live ids.
|
||||||
|
///
|
||||||
|
/// `max_pages` bounds a single run (so a first sync of a 15-year tracker can be
|
||||||
|
/// resumed across calls rather than blocking on one enormous fetch).
|
||||||
|
pub async fn run_sync<C: Connector>(
|
||||||
|
store: &crate::storage::SqliteMemoryStore,
|
||||||
|
connector: &C,
|
||||||
|
reconcile: bool,
|
||||||
|
max_pages: usize,
|
||||||
|
) -> ConnectorResult<SyncReport> {
|
||||||
|
use crate::storage::SourceUpsertOutcome;
|
||||||
|
|
||||||
|
let source_system = connector.source_system().to_string();
|
||||||
|
let scope = connector.scope().to_string();
|
||||||
|
|
||||||
|
let mut report = SyncReport {
|
||||||
|
source_system: source_system.clone(),
|
||||||
|
scope: scope.clone(),
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
|
||||||
|
// 1. Load checkpoint, apply the overlap window.
|
||||||
|
let checkpoint = store
|
||||||
|
.get_connector_cursor(&source_system, &scope)
|
||||||
|
.map_err(|e| ConnectorError::Transport(e.to_string()))?;
|
||||||
|
let since = checkpoint
|
||||||
|
.cursor_updated_at
|
||||||
|
.map(|c| c - chrono::Duration::seconds(CURSOR_OVERLAP_SECS));
|
||||||
|
|
||||||
|
// 2. Page forward, upserting each record.
|
||||||
|
let mut cursor: Option<String> = None;
|
||||||
|
let mut max_seen = checkpoint.cursor_updated_at;
|
||||||
|
// Oldest source_updated_at among records that FAILED to upsert this run. We
|
||||||
|
// must not advance the persisted cursor past this, or the failed record —
|
||||||
|
// fetched in ascending update order — would fall outside the next run's
|
||||||
|
// `since` window and never be retried (a silent permanent gap).
|
||||||
|
let mut oldest_failure: Option<DateTime<Utc>> = None;
|
||||||
|
// Count of genuinely new records (Created). Unchanged re-scans of the
|
||||||
|
// overlap window must not inflate the running total.
|
||||||
|
let mut created_this_run = 0i64;
|
||||||
|
|
||||||
|
for _ in 0..max_pages.max(1) {
|
||||||
|
let page = connector.fetch_updated(since, cursor.clone()).await?;
|
||||||
|
for record in page.records {
|
||||||
|
let observed = record.envelope.source_updated_at;
|
||||||
|
match store.upsert_by_source(record.into_ingest_input()) {
|
||||||
|
Ok(res) => {
|
||||||
|
match res.outcome {
|
||||||
|
SourceUpsertOutcome::Created => {
|
||||||
|
report.created += 1;
|
||||||
|
created_this_run += 1;
|
||||||
|
}
|
||||||
|
SourceUpsertOutcome::Updated => report.updated += 1,
|
||||||
|
SourceUpsertOutcome::Unchanged => report.unchanged += 1,
|
||||||
|
}
|
||||||
|
if let Some(ts) = observed
|
||||||
|
&& max_seen.map(|m| ts > m).unwrap_or(true)
|
||||||
|
{
|
||||||
|
max_seen = Some(ts);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
report.warnings.push(format!("upsert failed: {e}"));
|
||||||
|
if let Some(ts) = observed
|
||||||
|
&& oldest_failure.map(|f| ts < f).unwrap_or(true)
|
||||||
|
{
|
||||||
|
oldest_failure = Some(ts);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
match page.next_cursor {
|
||||||
|
Some(next) => cursor = Some(next),
|
||||||
|
None => break,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Clamp the cursor so we never advance past a record that failed this run.
|
||||||
|
// Subtract one second so the next run's inclusive `since` re-includes it.
|
||||||
|
if let Some(failed_at) = oldest_failure {
|
||||||
|
let clamp_to = failed_at - chrono::Duration::seconds(1);
|
||||||
|
max_seen = Some(match max_seen {
|
||||||
|
Some(m) if m < clamp_to => m,
|
||||||
|
_ => clamp_to,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3. Optional deletion reconciliation.
|
||||||
|
let mut reconciled = false;
|
||||||
|
if reconcile {
|
||||||
|
match connector.list_live_ids().await {
|
||||||
|
Ok(Some(live_ids)) => {
|
||||||
|
match store.reconcile_source_tombstones(&source_system, &scope, &live_ids) {
|
||||||
|
Ok(r) => {
|
||||||
|
report.tombstoned = r.tombstoned.len();
|
||||||
|
reconciled = true;
|
||||||
|
}
|
||||||
|
Err(e) => report.warnings.push(format!("reconcile failed: {e}")),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(None) => report
|
||||||
|
.warnings
|
||||||
|
.push("connector cannot enumerate live ids; skipped reconcile".to_string()),
|
||||||
|
Err(e) => report.warnings.push(format!("list_live_ids failed: {e}")),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
report.reconciled = reconciled;
|
||||||
|
report.new_cursor = max_seen;
|
||||||
|
|
||||||
|
// 4. Persist the checkpoint (only after the run).
|
||||||
|
let now = Utc::now();
|
||||||
|
let new_checkpoint = ConnectorCursor {
|
||||||
|
source_system: source_system.clone(),
|
||||||
|
scope: scope.clone(),
|
||||||
|
cursor_updated_at: max_seen,
|
||||||
|
last_synced_at: Some(now),
|
||||||
|
last_full_reconcile_at: if reconciled {
|
||||||
|
Some(now)
|
||||||
|
} else {
|
||||||
|
checkpoint.last_full_reconcile_at
|
||||||
|
},
|
||||||
|
// Accumulate only NEW records, so re-scanning the overlap window (which
|
||||||
|
// reports Unchanged) does not inflate the running total.
|
||||||
|
records_seen: checkpoint.records_seen + created_this_run,
|
||||||
|
};
|
||||||
|
store
|
||||||
|
.save_connector_cursor(&new_checkpoint)
|
||||||
|
.map_err(|e| ConnectorError::Transport(e.to_string()))?;
|
||||||
|
|
||||||
|
Ok(report)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Compute a stable content hash over the record's meaning.
|
||||||
|
///
|
||||||
|
/// Stability requirements (so re-syncing an unchanged record is a true no-op):
|
||||||
|
/// - **key order independent** — callers pass `(field, value)` pairs which we
|
||||||
|
/// sort before hashing, so map/field ordering never changes the digest;
|
||||||
|
/// - **volatile fields excluded** — the caller must omit the cursor timestamp,
|
||||||
|
/// view/comment counts, and ephemeral permission flags (hash the meaning,
|
||||||
|
/// not the metadata);
|
||||||
|
/// - **collision-resistant** — BLAKE3 (already a Vestige dependency).
|
||||||
|
///
|
||||||
|
/// Comment/journal arrays should be flattened into the pairs in a stable order
|
||||||
|
/// (sorted by their own id) by the caller before hashing.
|
||||||
|
pub fn content_hash(fields: &[(&str, &str)]) -> String {
|
||||||
|
let mut pairs: Vec<(&str, &str)> = fields.to_vec();
|
||||||
|
pairs.sort_by(|a, b| a.0.cmp(b.0).then(a.1.cmp(b.1)));
|
||||||
|
|
||||||
|
let mut hasher = blake3::Hasher::new();
|
||||||
|
for (k, v) in pairs {
|
||||||
|
// Length-prefix each field so ("ab","c") can't collide with ("a","bc").
|
||||||
|
hasher.update(&(k.len() as u64).to_le_bytes());
|
||||||
|
hasher.update(k.as_bytes());
|
||||||
|
hasher.update(&(v.len() as u64).to_le_bytes());
|
||||||
|
hasher.update(v.as_bytes());
|
||||||
|
}
|
||||||
|
hasher.finalize().to_hex().to_string()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn content_hash_is_order_independent() {
|
||||||
|
let a = content_hash(&[
|
||||||
|
("title", "Crash"),
|
||||||
|
("body", "stacktrace"),
|
||||||
|
("state", "open"),
|
||||||
|
]);
|
||||||
|
let b = content_hash(&[
|
||||||
|
("state", "open"),
|
||||||
|
("title", "Crash"),
|
||||||
|
("body", "stacktrace"),
|
||||||
|
]);
|
||||||
|
assert_eq!(a, b, "reordering fields must not change the hash");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn content_hash_changes_with_content() {
|
||||||
|
let a = content_hash(&[("body", "v1")]);
|
||||||
|
let b = content_hash(&[("body", "v2")]);
|
||||||
|
assert_ne!(a, b, "different content must hash differently");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn content_hash_no_boundary_collision() {
|
||||||
|
// ("ab","c") vs ("a","bc") must differ thanks to length prefixing.
|
||||||
|
let a = content_hash(&[("ab", "c")]);
|
||||||
|
let b = content_hash(&[("a", "bc")]);
|
||||||
|
assert_ne!(a, b);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn normalized_record_carries_envelope_into_input() {
|
||||||
|
let rec = NormalizedRecord {
|
||||||
|
content: "issue body".to_string(),
|
||||||
|
tags: vec!["github".to_string()],
|
||||||
|
envelope: SourceEnvelope {
|
||||||
|
source_system: Some("github".to_string()),
|
||||||
|
source_id: Some("42".to_string()),
|
||||||
|
source_url: Some("https://example/42".to_string()),
|
||||||
|
content_hash: Some("h".to_string()),
|
||||||
|
..Default::default()
|
||||||
|
},
|
||||||
|
};
|
||||||
|
let input = rec.into_ingest_input();
|
||||||
|
assert_eq!(input.content, "issue body");
|
||||||
|
assert_eq!(input.source.as_deref(), Some("https://example/42"));
|
||||||
|
let env = input.source_envelope.unwrap();
|
||||||
|
assert!(env.has_key());
|
||||||
|
assert_eq!(env.source_id.as_deref(), Some("42"));
|
||||||
|
}
|
||||||
|
}
|
||||||
737
crates/vestige-core/src/connectors/redmine.rs
Normal file
737
crates/vestige-core/src/connectors/redmine.rs
Normal file
|
|
@ -0,0 +1,737 @@
|
||||||
|
//! Redmine connector (#57).
|
||||||
|
//!
|
||||||
|
//! Indexes a Redmine project's issues + journals (comments and status/assignment
|
||||||
|
//! history) into source-aware Vestige memories so an investigative agent can
|
||||||
|
//! search and reason over years of ticket history **offline**, **semantically**,
|
||||||
|
//! and **cited back to the canonical issue URL**. Redmine stays the system of
|
||||||
|
//! record; Vestige indexes, connects, retrieves, and links back.
|
||||||
|
//!
|
||||||
|
//! ## Incremental sync (per the connector sync contract)
|
||||||
|
//!
|
||||||
|
//! Redmine's REST API has three traps this connector handles explicitly (all
|
||||||
|
//! confirmed against the official wiki + canonical defects):
|
||||||
|
//!
|
||||||
|
//! - **`status_id=*` is mandatory.** The list endpoint returns *open issues
|
||||||
|
//! only* by default, so without it closing an issue looks like a deletion and
|
||||||
|
//! closed issues are never synced (Defect #19088). We pass it on both the
|
||||||
|
//! incremental pull and the reconcile enumeration.
|
||||||
|
//! - **`include=journals` is silently ignored on the list endpoint.** Journals
|
||||||
|
//! come back only on the per-issue detail endpoint `GET /issues/{id}.json`
|
||||||
|
//! (Defect #35242), so each changed issue costs one extra round-trip.
|
||||||
|
//! - **Filter operators must be hex-encoded** in the compact form
|
||||||
|
//! (`updated_on=>=…` → `updated_on=%3E%3D…`). We build the query with
|
||||||
|
//! `reqwest`'s `.query(&[…])` and pass the raw `>=…` value so it is encoded
|
||||||
|
//! exactly once (no double-encoding).
|
||||||
|
//!
|
||||||
|
//! `sort=updated_on:asc` pages forward in cursor order so a mid-run interruption
|
||||||
|
//! resumes safely; the `since = cursor − overlap` window + the `content_hash`
|
||||||
|
//! no-op make the re-scan free. Redmine has no deletion feed, so deletions are
|
||||||
|
//! reconciled out-of-band via [`list_live_ids`](Connector::list_live_ids).
|
||||||
|
|
||||||
|
use chrono::{DateTime, Utc};
|
||||||
|
use serde::Deserialize;
|
||||||
|
|
||||||
|
use super::{
|
||||||
|
Connector, ConnectorError, ConnectorResult, FetchPage, NormalizedRecord, content_hash,
|
||||||
|
};
|
||||||
|
use crate::memory::SourceEnvelope;
|
||||||
|
|
||||||
|
const USER_AGENT: &str = concat!("vestige-connector/", env!("CARGO_PKG_VERSION"));
|
||||||
|
const PAGE_LIMIT: u32 = 100;
|
||||||
|
|
||||||
|
/// Configuration for a Redmine connector instance bound to one project.
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct RedmineConfig {
|
||||||
|
/// Base URL of the Redmine instance, e.g. `https://redmine.example.com`.
|
||||||
|
pub base_url: String,
|
||||||
|
/// Project identifier to scope the sync to. May be the numeric id or the
|
||||||
|
/// project identifier slug — used as `project_id` and stored as
|
||||||
|
/// `source_project`. (Note: Redmine's `project_id` list filter wants the
|
||||||
|
/// numeric id; the slug works as the human-readable scope label.)
|
||||||
|
pub project: String,
|
||||||
|
/// API access key. Optional only if the instance allows anonymous REST.
|
||||||
|
pub api_key: Option<String>,
|
||||||
|
/// Max journals to fold into one issue memory (defense against huge threads).
|
||||||
|
pub max_journals: usize,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl RedmineConfig {
|
||||||
|
pub fn new(base_url: impl Into<String>, project: impl Into<String>) -> Self {
|
||||||
|
Self {
|
||||||
|
base_url: base_url.into(),
|
||||||
|
project: project.into(),
|
||||||
|
api_key: None,
|
||||||
|
max_journals: 100,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn with_api_key(mut self, key: Option<String>) -> Self {
|
||||||
|
self.api_key = key;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Base URL with any trailing slash removed.
|
||||||
|
fn root(&self) -> String {
|
||||||
|
self.base_url.trim_end_matches('/').to_string()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A Redmine connector bound to one project.
|
||||||
|
pub struct RedmineConnector {
|
||||||
|
config: RedmineConfig,
|
||||||
|
scope: String,
|
||||||
|
client: reqwest::Client,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl RedmineConnector {
|
||||||
|
pub fn new(config: RedmineConfig) -> ConnectorResult<Self> {
|
||||||
|
if config.base_url.trim().is_empty() {
|
||||||
|
return Err(ConnectorError::Config("base_url is required".to_string()));
|
||||||
|
}
|
||||||
|
if config.project.trim().is_empty() {
|
||||||
|
return Err(ConnectorError::Config("project is required".to_string()));
|
||||||
|
}
|
||||||
|
if reqwest::Url::parse(&config.root()).is_err() {
|
||||||
|
return Err(ConnectorError::Config(format!(
|
||||||
|
"base_url is not a valid URL: {}",
|
||||||
|
config.base_url
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
let client = reqwest::Client::builder()
|
||||||
|
.user_agent(USER_AGENT)
|
||||||
|
.build()
|
||||||
|
.map_err(|e| ConnectorError::Transport(e.to_string()))?;
|
||||||
|
let scope = config.project.clone();
|
||||||
|
Ok(Self {
|
||||||
|
config,
|
||||||
|
scope,
|
||||||
|
client,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn auth(&self, req: reqwest::RequestBuilder) -> reqwest::RequestBuilder {
|
||||||
|
let req = req.header("Accept", "application/json");
|
||||||
|
match &self.config.api_key {
|
||||||
|
// The key goes in the header (not the URL) so it stays out of proxy
|
||||||
|
// and access logs.
|
||||||
|
Some(k) => req.header("X-Redmine-API-Key", k),
|
||||||
|
None => req,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn classify_status(resp: &reqwest::Response) -> Option<ConnectorError> {
|
||||||
|
let status = resp.status();
|
||||||
|
if status.is_success() {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
if status.as_u16() == 429 {
|
||||||
|
let retry = resp
|
||||||
|
.headers()
|
||||||
|
.get("retry-after")
|
||||||
|
.and_then(|v| v.to_str().ok())
|
||||||
|
.and_then(|s| s.parse::<u64>().ok())
|
||||||
|
.map(std::time::Duration::from_secs);
|
||||||
|
return Some(ConnectorError::RateLimited(retry));
|
||||||
|
}
|
||||||
|
let message = match status.as_u16() {
|
||||||
|
// A valid key against an instance with REST disabled 401/403s; make
|
||||||
|
// that distinguishable from "no results".
|
||||||
|
401 | 403 => {
|
||||||
|
"unauthorized — check REDMINE_API_KEY and that the instance has the REST API enabled (Administration → Settings → API)"
|
||||||
|
.to_string()
|
||||||
|
}
|
||||||
|
_ => status
|
||||||
|
.canonical_reason()
|
||||||
|
.unwrap_or("request failed")
|
||||||
|
.to_string(),
|
||||||
|
};
|
||||||
|
Some(ConnectorError::Source {
|
||||||
|
status: status.as_u16(),
|
||||||
|
message,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Fetch the journals + relations for one issue (the detail endpoint —
|
||||||
|
/// journals are not returned on the list endpoint).
|
||||||
|
async fn fetch_detail(&self, issue_id: u64) -> ConnectorResult<RawIssue> {
|
||||||
|
let url = format!("{}/issues/{}.json", self.config.root(), issue_id);
|
||||||
|
let resp = self
|
||||||
|
.auth(self.client.get(&url))
|
||||||
|
.query(&[("include", "journals,relations")])
|
||||||
|
.send()
|
||||||
|
.await
|
||||||
|
.map_err(|e| ConnectorError::Transport(e.to_string()))?;
|
||||||
|
if let Some(err) = Self::classify_status(&resp) {
|
||||||
|
return Err(err);
|
||||||
|
}
|
||||||
|
let wrapper: IssueWrapper = resp
|
||||||
|
.json()
|
||||||
|
.await
|
||||||
|
.map_err(|e| ConnectorError::Transport(e.to_string()))?;
|
||||||
|
Ok(wrapper.issue)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Fold a raw issue (with journals) into one normalized memory record.
|
||||||
|
fn normalize(&self, issue: &RawIssue) -> NormalizedRecord {
|
||||||
|
let status_name = issue.status.as_ref().map(|s| s.name.clone());
|
||||||
|
let tracker_name = issue.tracker.as_ref().map(|t| t.name.clone());
|
||||||
|
let author = issue.author.as_ref().map(|a| a.name.clone());
|
||||||
|
|
||||||
|
// Journals sorted by id for a stable order + stable hash. Keep notes
|
||||||
|
// and field changes so status/assignment history remains searchable.
|
||||||
|
let mut journals: Vec<&RawJournal> = issue
|
||||||
|
.journals
|
||||||
|
.iter()
|
||||||
|
.filter(|j| {
|
||||||
|
j.notes
|
||||||
|
.as_deref()
|
||||||
|
.map(|n| !n.trim().is_empty())
|
||||||
|
.unwrap_or(false)
|
||||||
|
|| !j.details.is_empty()
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
journals.sort_by_key(|j| j.id);
|
||||||
|
journals.truncate(self.config.max_journals);
|
||||||
|
|
||||||
|
// Human-readable content.
|
||||||
|
let mut content = format!("[{}#{}] {}\n", self.scope, issue.id, issue.subject);
|
||||||
|
if let Some(s) = &status_name {
|
||||||
|
content.push_str(&format!("Status: {s}\n"));
|
||||||
|
}
|
||||||
|
if let Some(t) = &tracker_name {
|
||||||
|
content.push_str(&format!("Tracker: {t}\n"));
|
||||||
|
}
|
||||||
|
if let Some(desc) = &issue.description
|
||||||
|
&& !desc.trim().is_empty()
|
||||||
|
{
|
||||||
|
content.push('\n');
|
||||||
|
content.push_str(desc.trim());
|
||||||
|
content.push('\n');
|
||||||
|
}
|
||||||
|
for j in &journals {
|
||||||
|
let who = j.user.as_ref().map(|u| u.name.as_str()).unwrap_or("?");
|
||||||
|
let note = j.notes.as_deref().unwrap_or("").trim();
|
||||||
|
if !note.is_empty() {
|
||||||
|
content.push_str(&format!("\n- {who}: {note}"));
|
||||||
|
}
|
||||||
|
for detail in &j.details {
|
||||||
|
content.push_str(&format!(
|
||||||
|
"\n- {who} changed {}{}: {} -> {}",
|
||||||
|
detail.property.as_deref().unwrap_or("field"),
|
||||||
|
detail
|
||||||
|
.name
|
||||||
|
.as_deref()
|
||||||
|
.map(|n| format!(".{n}"))
|
||||||
|
.unwrap_or_default(),
|
||||||
|
detail.old_value.as_deref().unwrap_or(""),
|
||||||
|
detail.new_value.as_deref().unwrap_or("")
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !issue.relations.is_empty() {
|
||||||
|
content.push_str("\n\nRelations:");
|
||||||
|
let mut relations: Vec<&RawRelation> = issue.relations.iter().collect();
|
||||||
|
relations.sort_by_key(|r| r.id);
|
||||||
|
for relation in relations {
|
||||||
|
let related = relation.related_issue_id(issue.id);
|
||||||
|
content.push_str(&format!(
|
||||||
|
"\n- #{} ({})",
|
||||||
|
related,
|
||||||
|
relation.relation_type.as_deref().unwrap_or("relates")
|
||||||
|
));
|
||||||
|
if let Some(delay) = relation.delay {
|
||||||
|
content.push_str(&format!(", delay {delay}"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Stable content hash — meaning only, never the cursor (`updated_on`) or
|
||||||
|
// volatile counts. Journals and relations contribute stable fields in id
|
||||||
|
// order.
|
||||||
|
let journals_blob = journals
|
||||||
|
.iter()
|
||||||
|
.map(|j| {
|
||||||
|
let details = j
|
||||||
|
.details
|
||||||
|
.iter()
|
||||||
|
.map(|d| {
|
||||||
|
format!(
|
||||||
|
"{}:{}:{}:{}",
|
||||||
|
d.property.as_deref().unwrap_or(""),
|
||||||
|
d.name.as_deref().unwrap_or(""),
|
||||||
|
d.old_value.as_deref().unwrap_or(""),
|
||||||
|
d.new_value.as_deref().unwrap_or("")
|
||||||
|
)
|
||||||
|
})
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
.join("\u{1e}");
|
||||||
|
format!(
|
||||||
|
"{}:{}:{}",
|
||||||
|
j.id,
|
||||||
|
j.notes.as_deref().unwrap_or("").trim(),
|
||||||
|
details
|
||||||
|
)
|
||||||
|
})
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
.join("\u{1f}");
|
||||||
|
let relations_blob = {
|
||||||
|
let mut relations: Vec<&RawRelation> = issue.relations.iter().collect();
|
||||||
|
relations.sort_by_key(|r| r.id);
|
||||||
|
relations
|
||||||
|
.iter()
|
||||||
|
.map(|r| {
|
||||||
|
format!(
|
||||||
|
"{}:{}:{}:{}",
|
||||||
|
r.id,
|
||||||
|
r.issue_id.unwrap_or_default(),
|
||||||
|
r.issue_to_id.unwrap_or_default(),
|
||||||
|
r.relation_type.as_deref().unwrap_or("")
|
||||||
|
)
|
||||||
|
})
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
.join("\u{1f}")
|
||||||
|
};
|
||||||
|
let id_str = issue.id.to_string();
|
||||||
|
let status_id_str = issue
|
||||||
|
.status
|
||||||
|
.as_ref()
|
||||||
|
.map(|s| s.id.to_string())
|
||||||
|
.unwrap_or_default();
|
||||||
|
let tracker_id_str = issue
|
||||||
|
.tracker
|
||||||
|
.as_ref()
|
||||||
|
.map(|t| t.id.to_string())
|
||||||
|
.unwrap_or_default();
|
||||||
|
let done_ratio_str = issue.done_ratio.unwrap_or(0).to_string();
|
||||||
|
let desc_str = issue.description.clone().unwrap_or_default();
|
||||||
|
let hash = content_hash(&[
|
||||||
|
("id", &id_str),
|
||||||
|
("subject", &issue.subject),
|
||||||
|
("description", &desc_str),
|
||||||
|
("status_id", &status_id_str),
|
||||||
|
("tracker_id", &tracker_id_str),
|
||||||
|
("done_ratio", &done_ratio_str),
|
||||||
|
("journals", &journals_blob),
|
||||||
|
("relations", &relations_blob),
|
||||||
|
]);
|
||||||
|
|
||||||
|
// Tags, lowercased — `tag_prefix` matching is case-sensitive, and
|
||||||
|
// Redmine status/tracker names are mixed-case.
|
||||||
|
let mut tags = vec!["redmine".to_string(), "issue".to_string()];
|
||||||
|
if let Some(s) = &status_name {
|
||||||
|
tags.push(format!("status:{}", s.to_lowercase()));
|
||||||
|
}
|
||||||
|
if let Some(t) = &tracker_name {
|
||||||
|
tags.push(format!("tracker:{}", t.to_lowercase()));
|
||||||
|
}
|
||||||
|
if let Some(p) = &issue.priority {
|
||||||
|
tags.push(format!("priority:{}", p.name.to_lowercase()));
|
||||||
|
}
|
||||||
|
|
||||||
|
let envelope = SourceEnvelope {
|
||||||
|
source_system: Some("redmine".to_string()),
|
||||||
|
source_id: Some(issue.id.to_string()),
|
||||||
|
source_url: Some(format!("{}/issues/{}", self.config.root(), issue.id)),
|
||||||
|
source_updated_at: issue
|
||||||
|
.updated_on
|
||||||
|
.as_deref()
|
||||||
|
.and_then(|s| DateTime::parse_from_rfc3339(s).ok())
|
||||||
|
.map(|d| d.with_timezone(&Utc)),
|
||||||
|
content_hash: Some(hash),
|
||||||
|
synced_at: Some(Utc::now()),
|
||||||
|
source_project: Some(self.scope.clone()),
|
||||||
|
source_type: Some("issue".to_string()),
|
||||||
|
source_author: author,
|
||||||
|
};
|
||||||
|
|
||||||
|
NormalizedRecord {
|
||||||
|
content,
|
||||||
|
tags,
|
||||||
|
envelope,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Connector for RedmineConnector {
|
||||||
|
fn source_system(&self) -> &str {
|
||||||
|
"redmine"
|
||||||
|
}
|
||||||
|
|
||||||
|
fn scope(&self) -> &str {
|
||||||
|
&self.scope
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn fetch_updated(
|
||||||
|
&self,
|
||||||
|
since: Option<DateTime<Utc>>,
|
||||||
|
cursor: Option<String>,
|
||||||
|
) -> ConnectorResult<FetchPage> {
|
||||||
|
// The cursor carries the next offset (Redmine pages by offset, not an
|
||||||
|
// opaque url). First page = offset 0.
|
||||||
|
let offset: u32 = cursor.as_deref().and_then(|c| c.parse().ok()).unwrap_or(0);
|
||||||
|
|
||||||
|
let url = format!("{}/issues.json", self.config.root());
|
||||||
|
let limit_str = PAGE_LIMIT.to_string();
|
||||||
|
let offset_str = offset.to_string();
|
||||||
|
// Build params; reqwest percent-encodes each value exactly once, so we
|
||||||
|
// pass the RAW `>=…` operator (it becomes %3E%3D on the wire). Do not
|
||||||
|
// pre-encode here or it would be double-encoded.
|
||||||
|
let mut params: Vec<(&str, String)> = vec![
|
||||||
|
("status_id", "*".to_string()),
|
||||||
|
("sort", "updated_on:asc".to_string()),
|
||||||
|
("project_id", self.config.project.clone()),
|
||||||
|
("limit", limit_str),
|
||||||
|
("offset", offset_str),
|
||||||
|
];
|
||||||
|
if let Some(s) = since {
|
||||||
|
let since_z = s.to_rfc3339_opts(chrono::SecondsFormat::Secs, true);
|
||||||
|
params.push(("updated_on", format!(">={since_z}")));
|
||||||
|
}
|
||||||
|
|
||||||
|
let resp = self
|
||||||
|
.auth(self.client.get(&url))
|
||||||
|
.query(¶ms)
|
||||||
|
.send()
|
||||||
|
.await
|
||||||
|
.map_err(|e| ConnectorError::Transport(e.to_string()))?;
|
||||||
|
if let Some(err) = Self::classify_status(&resp) {
|
||||||
|
return Err(err);
|
||||||
|
}
|
||||||
|
let page: IssueListResponse = resp
|
||||||
|
.json()
|
||||||
|
.await
|
||||||
|
.map_err(|e| ConnectorError::Transport(e.to_string()))?;
|
||||||
|
|
||||||
|
// Per-issue detail fetch for journals (list endpoint omits them).
|
||||||
|
let mut records = Vec::new();
|
||||||
|
for summary in &page.issues {
|
||||||
|
let detailed = match self.fetch_detail(summary.id).await {
|
||||||
|
Ok(d) => d,
|
||||||
|
// A single issue failing detail-fetch should not abort the page;
|
||||||
|
// fall back to the list-level fields (no journals).
|
||||||
|
Err(_) => summary.clone(),
|
||||||
|
};
|
||||||
|
records.push(self.normalize(&detailed));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Advance the offset cursor until we've walked total_count.
|
||||||
|
let next_offset = offset + page.issues.len() as u32;
|
||||||
|
let next_cursor = if (next_offset as u64) < page.total_count && !page.issues.is_empty() {
|
||||||
|
Some(next_offset.to_string())
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
};
|
||||||
|
|
||||||
|
Ok(FetchPage {
|
||||||
|
records,
|
||||||
|
next_cursor,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn list_live_ids(&self) -> ConnectorResult<Option<Vec<String>>> {
|
||||||
|
// Enumerate all issue ids (open AND closed) for the reconcile pass.
|
||||||
|
// status_id=* is mandatory here too, or closed issues read as deleted.
|
||||||
|
let mut ids = Vec::new();
|
||||||
|
let mut offset: u32 = 0;
|
||||||
|
loop {
|
||||||
|
let url = format!("{}/issues.json", self.config.root());
|
||||||
|
let resp = self
|
||||||
|
.auth(self.client.get(&url))
|
||||||
|
.query(&[
|
||||||
|
("status_id", "*".to_string()),
|
||||||
|
("project_id", self.config.project.clone()),
|
||||||
|
("limit", PAGE_LIMIT.to_string()),
|
||||||
|
("offset", offset.to_string()),
|
||||||
|
])
|
||||||
|
.send()
|
||||||
|
.await
|
||||||
|
.map_err(|e| ConnectorError::Transport(e.to_string()))?;
|
||||||
|
if let Some(err) = Self::classify_status(&resp) {
|
||||||
|
return Err(err);
|
||||||
|
}
|
||||||
|
let page: IssueListResponse = resp
|
||||||
|
.json()
|
||||||
|
.await
|
||||||
|
.map_err(|e| ConnectorError::Transport(e.to_string()))?;
|
||||||
|
if page.issues.is_empty() {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
for issue in &page.issues {
|
||||||
|
ids.push(issue.id.to_string());
|
||||||
|
}
|
||||||
|
offset += page.issues.len() as u32;
|
||||||
|
if (offset as u64) >= page.total_count {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(Some(ids))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Raw Redmine API shapes (only the fields we use)
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
#[derive(Debug, Deserialize)]
|
||||||
|
struct IssueListResponse {
|
||||||
|
#[serde(default)]
|
||||||
|
issues: Vec<RawIssue>,
|
||||||
|
#[serde(default)]
|
||||||
|
total_count: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Deserialize)]
|
||||||
|
struct IssueWrapper {
|
||||||
|
issue: RawIssue,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Deserialize)]
|
||||||
|
struct RawIssue {
|
||||||
|
id: u64,
|
||||||
|
#[serde(default)]
|
||||||
|
subject: String,
|
||||||
|
#[serde(default)]
|
||||||
|
description: Option<String>,
|
||||||
|
#[serde(default)]
|
||||||
|
status: Option<NamedRef>,
|
||||||
|
#[serde(default)]
|
||||||
|
tracker: Option<NamedRef>,
|
||||||
|
#[serde(default)]
|
||||||
|
priority: Option<NamedRef>,
|
||||||
|
#[serde(default)]
|
||||||
|
author: Option<NamedRef>,
|
||||||
|
#[serde(default)]
|
||||||
|
done_ratio: Option<i64>,
|
||||||
|
#[serde(default)]
|
||||||
|
updated_on: Option<String>,
|
||||||
|
#[serde(default)]
|
||||||
|
journals: Vec<RawJournal>,
|
||||||
|
#[serde(default)]
|
||||||
|
relations: Vec<RawRelation>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Redmine `{id, name}` reference (status, tracker, priority, user, …).
|
||||||
|
#[derive(Debug, Clone, Deserialize)]
|
||||||
|
struct NamedRef {
|
||||||
|
#[serde(default)]
|
||||||
|
id: i64,
|
||||||
|
#[serde(default)]
|
||||||
|
name: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Deserialize)]
|
||||||
|
struct RawJournal {
|
||||||
|
id: u64,
|
||||||
|
#[serde(default)]
|
||||||
|
notes: Option<String>,
|
||||||
|
#[serde(default)]
|
||||||
|
user: Option<NamedRef>,
|
||||||
|
#[serde(default)]
|
||||||
|
details: Vec<RawJournalDetail>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Deserialize)]
|
||||||
|
struct RawJournalDetail {
|
||||||
|
#[serde(default)]
|
||||||
|
property: Option<String>,
|
||||||
|
#[serde(default)]
|
||||||
|
name: Option<String>,
|
||||||
|
#[serde(default)]
|
||||||
|
old_value: Option<String>,
|
||||||
|
#[serde(default)]
|
||||||
|
new_value: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Deserialize)]
|
||||||
|
struct RawRelation {
|
||||||
|
#[serde(default)]
|
||||||
|
id: u64,
|
||||||
|
#[serde(default)]
|
||||||
|
issue_id: Option<u64>,
|
||||||
|
#[serde(default)]
|
||||||
|
issue_to_id: Option<u64>,
|
||||||
|
#[serde(default)]
|
||||||
|
relation_type: Option<String>,
|
||||||
|
#[serde(default)]
|
||||||
|
delay: Option<i64>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl RawRelation {
|
||||||
|
fn related_issue_id(&self, current_issue_id: u64) -> u64 {
|
||||||
|
match (self.issue_id, self.issue_to_id) {
|
||||||
|
(Some(from), Some(to)) if from == current_issue_id => to,
|
||||||
|
(Some(from), Some(to)) if to == current_issue_id => from,
|
||||||
|
(_, Some(to)) => to,
|
||||||
|
(Some(from), _) => from,
|
||||||
|
_ => 0,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
fn issue(id: u64, subject: &str, desc: &str, status: (i64, &str)) -> RawIssue {
|
||||||
|
RawIssue {
|
||||||
|
id,
|
||||||
|
subject: subject.to_string(),
|
||||||
|
description: Some(desc.to_string()),
|
||||||
|
status: Some(NamedRef {
|
||||||
|
id: status.0,
|
||||||
|
name: status.1.to_string(),
|
||||||
|
}),
|
||||||
|
tracker: Some(NamedRef {
|
||||||
|
id: 1,
|
||||||
|
name: "Bug".to_string(),
|
||||||
|
}),
|
||||||
|
priority: Some(NamedRef {
|
||||||
|
id: 2,
|
||||||
|
name: "Normal".to_string(),
|
||||||
|
}),
|
||||||
|
author: Some(NamedRef {
|
||||||
|
id: 7,
|
||||||
|
name: "Jane Dev".to_string(),
|
||||||
|
}),
|
||||||
|
done_ratio: Some(0),
|
||||||
|
updated_on: Some("2026-06-19T00:00:00Z".to_string()),
|
||||||
|
journals: vec![],
|
||||||
|
relations: vec![],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn connector() -> RedmineConnector {
|
||||||
|
RedmineConnector::new(RedmineConfig::new("https://redmine.example.com", "infra")).unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rejects_empty_and_bad_config() {
|
||||||
|
assert!(RedmineConnector::new(RedmineConfig::new("", "p")).is_err());
|
||||||
|
assert!(RedmineConnector::new(RedmineConfig::new("https://r.example", "")).is_err());
|
||||||
|
assert!(RedmineConnector::new(RedmineConfig::new("not a url", "p")).is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn normalize_builds_keyed_envelope_with_citation() {
|
||||||
|
let c = connector();
|
||||||
|
let rec = c.normalize(&issue(123, "Disk full", "df -h shows 100%", (1, "New")));
|
||||||
|
let env = &rec.envelope;
|
||||||
|
assert!(env.has_key());
|
||||||
|
assert_eq!(env.source_system.as_deref(), Some("redmine"));
|
||||||
|
assert_eq!(env.source_id.as_deref(), Some("123"));
|
||||||
|
assert_eq!(
|
||||||
|
env.source_url.as_deref(),
|
||||||
|
Some("https://redmine.example.com/issues/123")
|
||||||
|
);
|
||||||
|
assert_eq!(env.source_project.as_deref(), Some("infra"));
|
||||||
|
assert_eq!(env.source_author.as_deref(), Some("Jane Dev"));
|
||||||
|
assert!(rec.content.contains("Disk full"));
|
||||||
|
// Tags lowercased so the case-sensitive tag_prefix filter matches.
|
||||||
|
assert!(rec.tags.contains(&"status:new".to_string()));
|
||||||
|
assert!(rec.tags.contains(&"tracker:bug".to_string()));
|
||||||
|
assert!(rec.tags.contains(&"priority:normal".to_string()));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn status_change_changes_hash() {
|
||||||
|
let c = connector();
|
||||||
|
let new = c
|
||||||
|
.normalize(&issue(1, "T", "body", (1, "New")))
|
||||||
|
.envelope
|
||||||
|
.content_hash;
|
||||||
|
let closed = c
|
||||||
|
.normalize(&issue(1, "T", "body", (5, "Closed")))
|
||||||
|
.envelope
|
||||||
|
.content_hash;
|
||||||
|
assert_ne!(
|
||||||
|
new, closed,
|
||||||
|
"a status change must change the hash → re-embed"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn journals_fold_in_id_order_and_affect_hash() {
|
||||||
|
let c = connector();
|
||||||
|
let mut iss = issue(1, "T", "body", (1, "New"));
|
||||||
|
iss.journals = vec![
|
||||||
|
RawJournal {
|
||||||
|
id: 20,
|
||||||
|
notes: Some("second".to_string()),
|
||||||
|
user: Some(NamedRef {
|
||||||
|
id: 1,
|
||||||
|
name: "B".to_string(),
|
||||||
|
}),
|
||||||
|
details: vec![],
|
||||||
|
},
|
||||||
|
RawJournal {
|
||||||
|
id: 10,
|
||||||
|
notes: Some("first".to_string()),
|
||||||
|
user: Some(NamedRef {
|
||||||
|
id: 2,
|
||||||
|
name: "A".to_string(),
|
||||||
|
}),
|
||||||
|
details: vec![],
|
||||||
|
},
|
||||||
|
// Pure empty journal must be dropped, not folded.
|
||||||
|
RawJournal {
|
||||||
|
id: 30,
|
||||||
|
notes: None,
|
||||||
|
user: Some(NamedRef {
|
||||||
|
id: 3,
|
||||||
|
name: "C".to_string(),
|
||||||
|
}),
|
||||||
|
details: vec![],
|
||||||
|
},
|
||||||
|
];
|
||||||
|
let rec = c.normalize(&iss);
|
||||||
|
let first = rec.content.find("first").unwrap();
|
||||||
|
let second = rec.content.find("second").unwrap();
|
||||||
|
assert!(first < second, "journals fold in id order");
|
||||||
|
|
||||||
|
let no_journals = c
|
||||||
|
.normalize(&issue(1, "T", "body", (1, "New")))
|
||||||
|
.envelope
|
||||||
|
.content_hash;
|
||||||
|
assert_ne!(
|
||||||
|
rec.envelope.content_hash, no_journals,
|
||||||
|
"journals must contribute to the hash"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn journal_details_and_relations_are_searchable_and_hashed() {
|
||||||
|
let c = connector();
|
||||||
|
let mut iss = issue(1, "T", "body", (1, "New"));
|
||||||
|
iss.journals = vec![RawJournal {
|
||||||
|
id: 1,
|
||||||
|
notes: None,
|
||||||
|
user: Some(NamedRef {
|
||||||
|
id: 2,
|
||||||
|
name: "A".to_string(),
|
||||||
|
}),
|
||||||
|
details: vec![RawJournalDetail {
|
||||||
|
property: Some("attr".to_string()),
|
||||||
|
name: Some("status_id".to_string()),
|
||||||
|
old_value: Some("1".to_string()),
|
||||||
|
new_value: Some("5".to_string()),
|
||||||
|
}],
|
||||||
|
}];
|
||||||
|
iss.relations = vec![RawRelation {
|
||||||
|
id: 9,
|
||||||
|
issue_id: Some(1),
|
||||||
|
issue_to_id: Some(42),
|
||||||
|
relation_type: Some("relates".to_string()),
|
||||||
|
delay: None,
|
||||||
|
}];
|
||||||
|
|
||||||
|
let rec = c.normalize(&iss);
|
||||||
|
assert!(rec.content.contains("changed attr.status_id: 1 -> 5"));
|
||||||
|
assert!(rec.content.contains("#42 (relates)"));
|
||||||
|
|
||||||
|
let no_history = c.normalize(&issue(1, "T", "body", (1, "New")));
|
||||||
|
assert_ne!(
|
||||||
|
rec.envelope.content_hash, no_history.envelope.content_hash,
|
||||||
|
"field-change journals and relations must affect idempotent updates"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -889,6 +889,7 @@ mod tests {
|
||||||
embedding_model: None,
|
embedding_model: None,
|
||||||
suppression_count: 0,
|
suppression_count: 0,
|
||||||
suppressed_at: None,
|
suppressed_at: None,
|
||||||
|
source_envelope: None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
217
crates/vestige-core/src/embedder/fastembed.rs
Normal file
217
crates/vestige-core/src/embedder/fastembed.rs
Normal file
|
|
@ -0,0 +1,217 @@
|
||||||
|
//! `FastembedEmbedder` -- adapts the existing `EmbeddingService` to the
|
||||||
|
//! `LocalEmbedder` trait.
|
||||||
|
|
||||||
|
#[cfg(feature = "embeddings")]
|
||||||
|
use crate::embeddings::{EMBEDDING_DIMENSIONS, EmbeddingService};
|
||||||
|
|
||||||
|
use super::{EmbedderError, EmbedderResult, EmbedderSend};
|
||||||
|
|
||||||
|
pub struct FastembedEmbedder {
|
||||||
|
#[cfg(feature = "embeddings")]
|
||||||
|
inner: EmbeddingService,
|
||||||
|
cached_hash: std::sync::OnceLock<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl FastembedEmbedder {
|
||||||
|
pub fn new() -> Self {
|
||||||
|
Self {
|
||||||
|
#[cfg(feature = "embeddings")]
|
||||||
|
inner: EmbeddingService::new(),
|
||||||
|
cached_hash: std::sync::OnceLock::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn compute_hash(name: &str, dim: usize) -> String {
|
||||||
|
let mut hasher = blake3::Hasher::new();
|
||||||
|
hasher.update(name.as_bytes());
|
||||||
|
hasher.update(&(dim as u64).to_le_bytes());
|
||||||
|
// fastembed's ONNX bytes are not directly accessible at runtime; we
|
||||||
|
// use `(name, dim, vestige-core CARGO_PKG_VERSION)` as the
|
||||||
|
// signature. If fastembed ever changes its output deterministically
|
||||||
|
// between minor versions, bumping the crate version triggers a
|
||||||
|
// mismatch -- which is exactly the drift we want to detect.
|
||||||
|
hasher.update(env!("CARGO_PKG_VERSION").as_bytes());
|
||||||
|
hasher.finalize().to_hex().to_string()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for FastembedEmbedder {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self::new()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl EmbedderSend for FastembedEmbedder {
|
||||||
|
async fn embed(&self, text: &str) -> EmbedderResult<Vec<f32>> {
|
||||||
|
#[cfg(feature = "embeddings")]
|
||||||
|
{
|
||||||
|
let emb = self
|
||||||
|
.inner
|
||||||
|
.embed(text)
|
||||||
|
.map_err(|e| EmbedderError::EmbedFailed(e.to_string()))?;
|
||||||
|
Ok(emb.vector)
|
||||||
|
}
|
||||||
|
#[cfg(not(feature = "embeddings"))]
|
||||||
|
{
|
||||||
|
let _ = text;
|
||||||
|
Err(EmbedderError::Init(
|
||||||
|
"embeddings feature not enabled".to_string(),
|
||||||
|
))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn model_name(&self) -> &str {
|
||||||
|
#[cfg(feature = "embeddings")]
|
||||||
|
{
|
||||||
|
self.inner.model_name()
|
||||||
|
}
|
||||||
|
#[cfg(not(feature = "embeddings"))]
|
||||||
|
{
|
||||||
|
"nomic-ai/nomic-embed-text-v1.5"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn dimension(&self) -> usize {
|
||||||
|
#[cfg(feature = "embeddings")]
|
||||||
|
{
|
||||||
|
EMBEDDING_DIMENSIONS
|
||||||
|
}
|
||||||
|
#[cfg(not(feature = "embeddings"))]
|
||||||
|
{
|
||||||
|
256
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn model_hash(&self) -> String {
|
||||||
|
self.cached_hash
|
||||||
|
.get_or_init(|| Self::compute_hash(self.model_name(), self.dimension()))
|
||||||
|
.clone()
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn embed_batch(&self, texts: &[&str]) -> EmbedderResult<Vec<Vec<f32>>> {
|
||||||
|
#[cfg(feature = "embeddings")]
|
||||||
|
{
|
||||||
|
let embs = self
|
||||||
|
.inner
|
||||||
|
.embed_batch(texts)
|
||||||
|
.map_err(|e| EmbedderError::EmbedFailed(e.to_string()))?;
|
||||||
|
Ok(embs.into_iter().map(|e| e.vector).collect())
|
||||||
|
}
|
||||||
|
#[cfg(not(feature = "embeddings"))]
|
||||||
|
{
|
||||||
|
let _ = texts;
|
||||||
|
Err(EmbedderError::Init(
|
||||||
|
"embeddings feature not enabled".to_string(),
|
||||||
|
))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ============================================================================
|
||||||
|
// UNIT TESTS
|
||||||
|
// ============================================================================
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[cfg(feature = "embeddings")]
|
||||||
|
fn is_model_unavailable(err: &EmbedderError) -> bool {
|
||||||
|
let msg = err.to_string();
|
||||||
|
msg.contains("Failed to retrieve")
|
||||||
|
|| msg.contains("model files can be downloaded")
|
||||||
|
|| msg.contains("Failed to initialize nomic-ai/nomic-embed-text-v1.5")
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn embedder_reports_correct_name() {
|
||||||
|
let e = FastembedEmbedder::new();
|
||||||
|
assert!(
|
||||||
|
e.model_name().contains("nomic"),
|
||||||
|
"model name should contain 'nomic'"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn embedder_reports_256_dimension() {
|
||||||
|
let e = FastembedEmbedder::new();
|
||||||
|
assert_eq!(e.dimension(), 256);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn embedder_hash_is_stable() {
|
||||||
|
let e = FastembedEmbedder::new();
|
||||||
|
let h1 = e.model_hash();
|
||||||
|
let h2 = e.model_hash();
|
||||||
|
assert_eq!(h1, h2, "model_hash must be stable across calls");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn embedder_hash_includes_crate_version() {
|
||||||
|
// Compute what the hash should be given the known inputs
|
||||||
|
let name = FastembedEmbedder::new().model_name().to_string();
|
||||||
|
let dim = FastembedEmbedder::new().dimension();
|
||||||
|
let expected = FastembedEmbedder::compute_hash(&name, dim);
|
||||||
|
let got = FastembedEmbedder::new().model_hash();
|
||||||
|
assert_eq!(got, expected);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn embedder_signature_matches_accessors() {
|
||||||
|
let e = FastembedEmbedder::new();
|
||||||
|
let sig = e.signature();
|
||||||
|
assert_eq!(sig.name, e.model_name());
|
||||||
|
assert_eq!(sig.dimension, e.dimension());
|
||||||
|
assert_eq!(sig.hash, e.model_hash());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "embeddings")]
|
||||||
|
#[test]
|
||||||
|
fn embedder_embed_smoke() {
|
||||||
|
let e = FastembedEmbedder::new();
|
||||||
|
let rt = tokio::runtime::Runtime::new().unwrap();
|
||||||
|
let vec = match rt.block_on(e.embed("hello world")) {
|
||||||
|
Ok(vec) => vec,
|
||||||
|
Err(err) if is_model_unavailable(&err) => {
|
||||||
|
eprintln!("skipping fastembed smoke; model unavailable: {err}");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
Err(err) => panic!("embed: {err}"),
|
||||||
|
};
|
||||||
|
assert_eq!(vec.len(), 256);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "embeddings")]
|
||||||
|
#[test]
|
||||||
|
fn embedder_embed_batch_matches_sequential() {
|
||||||
|
let e = FastembedEmbedder::new();
|
||||||
|
let rt = tokio::runtime::Runtime::new().unwrap();
|
||||||
|
let texts = ["alpha beta", "gamma delta"];
|
||||||
|
let batch = match rt.block_on(e.embed_batch(texts.as_ref())) {
|
||||||
|
Ok(batch) => batch,
|
||||||
|
Err(err) if is_model_unavailable(&err) => {
|
||||||
|
eprintln!("skipping fastembed batch smoke; model unavailable: {err}");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
Err(err) => panic!("batch: {err}"),
|
||||||
|
};
|
||||||
|
let seq_a = match rt.block_on(e.embed(texts[0])) {
|
||||||
|
Ok(vec) => vec,
|
||||||
|
Err(err) if is_model_unavailable(&err) => {
|
||||||
|
eprintln!("skipping fastembed sequential smoke; model unavailable: {err}");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
Err(err) => panic!("seq a: {err}"),
|
||||||
|
};
|
||||||
|
let seq_b = match rt.block_on(e.embed(texts[1])) {
|
||||||
|
Ok(vec) => vec,
|
||||||
|
Err(err) if is_model_unavailable(&err) => {
|
||||||
|
eprintln!("skipping fastembed sequential smoke; model unavailable: {err}");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
Err(err) => panic!("seq b: {err}"),
|
||||||
|
};
|
||||||
|
assert_eq!(batch[0], seq_a);
|
||||||
|
assert_eq!(batch[1], seq_b);
|
||||||
|
}
|
||||||
|
}
|
||||||
109
crates/vestige-core/src/embedder/mod.rs
Normal file
109
crates/vestige-core/src/embedder/mod.rs
Normal file
|
|
@ -0,0 +1,109 @@
|
||||||
|
//! Text-to-vector encoding trait. Pluggable per-install.
|
||||||
|
|
||||||
|
use std::future::Future;
|
||||||
|
use std::pin::Pin;
|
||||||
|
|
||||||
|
mod fastembed;
|
||||||
|
|
||||||
|
pub use fastembed::FastembedEmbedder;
|
||||||
|
|
||||||
|
/// Error returned by every `Embedder` method.
|
||||||
|
#[non_exhaustive]
|
||||||
|
#[derive(Debug, thiserror::Error)]
|
||||||
|
pub enum EmbedderError {
|
||||||
|
#[error("embedder initialization failed: {0}")]
|
||||||
|
Init(String),
|
||||||
|
#[error("embedding generation failed: {0}")]
|
||||||
|
EmbedFailed(String),
|
||||||
|
#[error("invalid input: {0}")]
|
||||||
|
InvalidInput(String),
|
||||||
|
}
|
||||||
|
|
||||||
|
pub type EmbedderResult<T> = std::result::Result<T, EmbedderError>;
|
||||||
|
|
||||||
|
/// Boxed Send future returning an `EmbedderResult<T>`, bound to the lifetime
|
||||||
|
/// of the borrows captured by the call. Used as the return type of every
|
||||||
|
/// async method on the dyn-compatible `Embedder` trait below.
|
||||||
|
pub type BoxedEmbedderFuture<'a, T> = Pin<Box<dyn Future<Output = EmbedderResult<T>> + Send + 'a>>;
|
||||||
|
|
||||||
|
/// Pluggable embedder. The storage layer NEVER calls fastembed directly;
|
||||||
|
/// callers compute vectors via this trait and pass them into `MemoryStore`.
|
||||||
|
///
|
||||||
|
/// `LocalEmbedder` is the source-of-truth trait declared with native
|
||||||
|
/// async-fn-in-trait. `#[trait_variant::make(EmbedderSend: Send)]` derives
|
||||||
|
/// a Send-bounded variant that backends actually implement (the
|
||||||
|
/// trait_variant 0.1.x blanket goes variant -> source). The dyn-compatible
|
||||||
|
/// public surface is the `Embedder` trait declared below, which wraps every
|
||||||
|
/// async method in `Pin<Box<dyn Future + Send + '_>>`.
|
||||||
|
#[trait_variant::make(EmbedderSend: Send)]
|
||||||
|
pub trait LocalEmbedder: Sync + 'static {
|
||||||
|
async fn embed(&self, text: &str) -> EmbedderResult<Vec<f32>>;
|
||||||
|
|
||||||
|
fn model_name(&self) -> &str;
|
||||||
|
|
||||||
|
fn dimension(&self) -> usize;
|
||||||
|
|
||||||
|
/// Stable blake3 hash of (model_name || dimension || vestige-core crate version).
|
||||||
|
/// Lowercase hex, 64 chars.
|
||||||
|
///
|
||||||
|
/// Used by `MemoryStore::register_model` to detect silent model drift
|
||||||
|
/// (e.g. a fastembed minor upgrade that changes vector output).
|
||||||
|
fn model_hash(&self) -> String;
|
||||||
|
|
||||||
|
async fn embed_batch(&self, texts: &[&str]) -> EmbedderResult<Vec<Vec<f32>>>;
|
||||||
|
|
||||||
|
/// Returns the `ModelSignature` describing this embedder. Convenience
|
||||||
|
/// wrapper over the three accessors above.
|
||||||
|
fn signature(&self) -> crate::storage::ModelSignature {
|
||||||
|
crate::storage::ModelSignature {
|
||||||
|
name: self.model_name().to_string(),
|
||||||
|
dimension: self.dimension(),
|
||||||
|
hash: self.model_hash(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Dyn-compatible embedder trait.
|
||||||
|
///
|
||||||
|
/// `EmbedderSend` above is the trait users implement; it uses native
|
||||||
|
/// async-fn-in-trait return types (RPITIT), which gives zero-allocation
|
||||||
|
/// static dispatch but is not dyn-safe. This trait wraps every async
|
||||||
|
/// method in `Pin<Box<dyn Future + Send + '_>>` so `Box<dyn Embedder>`
|
||||||
|
/// and `Arc<dyn Embedder>` work for the cognitive module surface and
|
||||||
|
/// the Phase 1 integration tests.
|
||||||
|
///
|
||||||
|
/// Implementations should not target this trait directly; the blanket
|
||||||
|
/// `impl<T: EmbedderSend> Embedder for T` adapts every Send-variant
|
||||||
|
/// implementation automatically.
|
||||||
|
pub trait Embedder: Send + Sync + 'static {
|
||||||
|
fn embed<'a>(&'a self, text: &'a str) -> BoxedEmbedderFuture<'a, Vec<f32>>;
|
||||||
|
fn embed_batch<'a>(&'a self, texts: &'a [&'a str]) -> BoxedEmbedderFuture<'a, Vec<Vec<f32>>>;
|
||||||
|
fn model_name(&self) -> &str;
|
||||||
|
fn dimension(&self) -> usize;
|
||||||
|
fn model_hash(&self) -> String;
|
||||||
|
fn signature(&self) -> crate::storage::ModelSignature;
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T> Embedder for T
|
||||||
|
where
|
||||||
|
T: EmbedderSend,
|
||||||
|
{
|
||||||
|
fn embed<'a>(&'a self, text: &'a str) -> BoxedEmbedderFuture<'a, Vec<f32>> {
|
||||||
|
Box::pin(<T as EmbedderSend>::embed(self, text))
|
||||||
|
}
|
||||||
|
fn embed_batch<'a>(&'a self, texts: &'a [&'a str]) -> BoxedEmbedderFuture<'a, Vec<Vec<f32>>> {
|
||||||
|
Box::pin(<T as EmbedderSend>::embed_batch(self, texts))
|
||||||
|
}
|
||||||
|
fn model_name(&self) -> &str {
|
||||||
|
<T as EmbedderSend>::model_name(self)
|
||||||
|
}
|
||||||
|
fn dimension(&self) -> usize {
|
||||||
|
<T as EmbedderSend>::dimension(self)
|
||||||
|
}
|
||||||
|
fn model_hash(&self) -> String {
|
||||||
|
<T as EmbedderSend>::model_hash(self)
|
||||||
|
}
|
||||||
|
fn signature(&self) -> crate::storage::ModelSignature {
|
||||||
|
<T as EmbedderSend>::signature(self)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -343,14 +343,18 @@ impl EmbeddingService {
|
||||||
Self { _unused: () }
|
Self { _unused: () }
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Check if the model is ready
|
/// Check if the model has already been initialized.
|
||||||
|
///
|
||||||
|
/// This must stay side-effect free: health/status paths call it during
|
||||||
|
/// startup and must not download or load ONNX models just to report state.
|
||||||
pub fn is_ready(&self) -> bool {
|
pub fn is_ready(&self) -> bool {
|
||||||
match get_backend() {
|
match EMBEDDING_BACKEND_RESULT.get() {
|
||||||
Ok(_) => true,
|
Some(Ok(backend)) => backend.lock().is_ok(),
|
||||||
Err(e) => {
|
Some(Err(e)) => {
|
||||||
tracing::warn!("Embedding model not ready: {}", e);
|
tracing::warn!("Embedding model not ready: {}", e);
|
||||||
false
|
false
|
||||||
}
|
}
|
||||||
|
None => false,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -80,7 +80,11 @@
|
||||||
// MODULES
|
// MODULES
|
||||||
// ============================================================================
|
// ============================================================================
|
||||||
|
|
||||||
|
/// Optional `vestige.toml` configuration (Phase 2: Configurable Output).
|
||||||
|
pub mod config;
|
||||||
|
pub mod connectors;
|
||||||
pub mod consolidation;
|
pub mod consolidation;
|
||||||
|
pub mod embedder;
|
||||||
pub mod fsrs;
|
pub mod fsrs;
|
||||||
pub mod fts;
|
pub mod fts;
|
||||||
pub mod memory;
|
pub mod memory;
|
||||||
|
|
@ -127,9 +131,12 @@ pub use memory::{
|
||||||
MemorySystem,
|
MemorySystem,
|
||||||
NodeType,
|
NodeType,
|
||||||
RecallInput,
|
RecallInput,
|
||||||
|
SchemaIntrospection,
|
||||||
SearchMode,
|
SearchMode,
|
||||||
SearchResult,
|
SearchResult,
|
||||||
SimilarityResult,
|
SimilarityResult,
|
||||||
|
SourceEnvelope,
|
||||||
|
TableIntrospection,
|
||||||
TemporalRange,
|
TemporalRange,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
@ -150,11 +157,55 @@ pub use fsrs::{
|
||||||
retrievability_with_decay,
|
retrievability_with_decay,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// Configuration (vestige.toml output profiles / defaults)
|
||||||
|
pub use config::{CONFIG_FILE, OutputConfig, OutputDefaults, OutputProfile, VestigeConfig};
|
||||||
|
|
||||||
// Storage layer
|
// Storage layer
|
||||||
pub use storage::{
|
pub use storage::{
|
||||||
ConnectionRecord, ConsolidationHistoryRecord, DreamHistoryRecord, InsightRecord,
|
ClassificationResult,
|
||||||
IntentionRecord, PORTABLE_ARCHIVE_FORMAT, PortableArchive, PortableImportMode,
|
CompositionEventRecord,
|
||||||
PortableImportReport, Result, SmartIngestResult, StateTransitionRecord, Storage, StorageError,
|
CompositionMemberRecord,
|
||||||
|
CompositionNeighborRecord,
|
||||||
|
CompositionOutcomeRecord,
|
||||||
|
ConnectionRecord,
|
||||||
|
ConnectorCursor,
|
||||||
|
ConsolidationHistoryRecord,
|
||||||
|
Domain,
|
||||||
|
DreamHistoryRecord,
|
||||||
|
HealthStatus,
|
||||||
|
InsightRecord,
|
||||||
|
IntentionRecord,
|
||||||
|
LocalMemoryStore,
|
||||||
|
MemoryEdge,
|
||||||
|
MemoryRecord,
|
||||||
|
MemoryStore,
|
||||||
|
MemoryStoreError,
|
||||||
|
MemoryStoreResult,
|
||||||
|
ModelSignature,
|
||||||
|
NeverComposedCandidate,
|
||||||
|
PORTABLE_ARCHIVE_FORMAT,
|
||||||
|
PortableArchive,
|
||||||
|
PortableImportMode,
|
||||||
|
PortableImportReport,
|
||||||
|
ReconcileReport,
|
||||||
|
Result,
|
||||||
|
SchedulingState,
|
||||||
|
SearchQuery,
|
||||||
|
SmartIngestResult,
|
||||||
|
SourceUpsertOutcome,
|
||||||
|
SourceUpsertResult,
|
||||||
|
SqliteMemoryStore,
|
||||||
|
StateTransitionRecord,
|
||||||
|
Storage,
|
||||||
|
StorageError,
|
||||||
|
StoreStats,
|
||||||
|
// Note: storage::SearchResult is intentionally not re-exported here to avoid
|
||||||
|
// collision with memory::SearchResult. Use vestige_core::storage::SearchResult directly.
|
||||||
|
};
|
||||||
|
|
||||||
|
// Embedder trait and implementations
|
||||||
|
pub use embedder::{
|
||||||
|
Embedder, EmbedderError, EmbedderResult, EmbedderSend, FastembedEmbedder, LocalEmbedder,
|
||||||
};
|
};
|
||||||
|
|
||||||
// Consolidation (sleep-inspired memory processing)
|
// Consolidation (sleep-inspired memory processing)
|
||||||
|
|
@ -213,6 +264,9 @@ pub use advanced::{
|
||||||
LabileState,
|
LabileState,
|
||||||
Language,
|
Language,
|
||||||
MaintenanceType,
|
MaintenanceType,
|
||||||
|
// Merge / Supersede controls (Phase 3)
|
||||||
|
MatchClass,
|
||||||
|
MatchSignals,
|
||||||
// Memory chains
|
// Memory chains
|
||||||
MemoryChainBuilder,
|
MemoryChainBuilder,
|
||||||
// Memory compression
|
// Memory compression
|
||||||
|
|
@ -223,10 +277,15 @@ pub use advanced::{
|
||||||
MemoryPath,
|
MemoryPath,
|
||||||
MemoryReplay,
|
MemoryReplay,
|
||||||
MemorySnapshot,
|
MemorySnapshot,
|
||||||
|
MergeCandidate,
|
||||||
|
MergeOperation,
|
||||||
|
MergePlan,
|
||||||
|
MergePolicy,
|
||||||
MergeStrategy,
|
MergeStrategy,
|
||||||
Modification,
|
Modification,
|
||||||
Pattern,
|
Pattern,
|
||||||
PatternType,
|
PatternType,
|
||||||
|
PlanKind,
|
||||||
PredictedMemory,
|
PredictedMemory,
|
||||||
PredictionContext,
|
PredictionContext,
|
||||||
PredictionErrorConfig,
|
PredictionErrorConfig,
|
||||||
|
|
|
||||||
|
|
@ -10,7 +10,7 @@ mod node;
|
||||||
mod strength;
|
mod strength;
|
||||||
mod temporal;
|
mod temporal;
|
||||||
|
|
||||||
pub use node::{IngestInput, KnowledgeNode, NodeType, RecallInput, SearchMode};
|
pub use node::{IngestInput, KnowledgeNode, NodeType, RecallInput, SearchMode, SourceEnvelope};
|
||||||
pub use strength::{DualStrength, StrengthDecay};
|
pub use strength::{DualStrength, StrengthDecay};
|
||||||
pub use temporal::{TemporalRange, TemporalValidity};
|
pub use temporal::{TemporalRange, TemporalValidity};
|
||||||
|
|
||||||
|
|
@ -276,6 +276,59 @@ impl Default for MemoryStats {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ============================================================================
|
||||||
|
// SCHEMA INTROSPECTION (v2.1.24+: surfaces DB shape to MCP consumers)
|
||||||
|
// ============================================================================
|
||||||
|
|
||||||
|
/// A single SQLite table's introspected shape: name, row count, column list.
|
||||||
|
///
|
||||||
|
/// Returned as part of `SchemaIntrospection` from `Storage::schema_introspection()`.
|
||||||
|
/// Consumers needing more depth (e.g. per-column NULL counts) should request
|
||||||
|
/// targeted methods rather than expecting this struct to grow unboundedly —
|
||||||
|
/// the row + column shape covered here is the 80% case for audit / migration
|
||||||
|
/// guard scripts.
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct TableIntrospection {
|
||||||
|
/// SQLite table name.
|
||||||
|
pub name: String,
|
||||||
|
/// Row count.
|
||||||
|
pub rows: i64,
|
||||||
|
/// Column names in declaration order.
|
||||||
|
pub columns: Vec<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Result of `Storage::schema_introspection()`. Snapshots the schema version,
|
||||||
|
/// migration timestamp, and a row/column view of every user-data table.
|
||||||
|
///
|
||||||
|
/// Motivation: external consumers (audit scripts, migration guards, downstream
|
||||||
|
/// upgrade scripts) currently must read SQLite directly to learn the schema
|
||||||
|
/// version and table shape, which couples them to internal layout. This struct
|
||||||
|
/// gives them a first-class MCP-callable surface. The list of tables walked is
|
||||||
|
/// intentionally the same canonical set used elsewhere in storage (the user-
|
||||||
|
/// data tables) so the surface stays stable across migrations.
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct SchemaIntrospection {
|
||||||
|
/// Current schema version (highest applied migration; matches the
|
||||||
|
/// `schema_version` table's MAX(version)).
|
||||||
|
pub schema_version: u32,
|
||||||
|
/// When the current schema version was applied (RFC3339), if known.
|
||||||
|
pub schema_version_applied_at: Option<DateTime<Utc>>,
|
||||||
|
/// Per-table introspection rows.
|
||||||
|
pub tables: Vec<TableIntrospection>,
|
||||||
|
/// Total number of nodes whose `embeddings.embedding` is NULL (i.e., have
|
||||||
|
/// no embedding row). Convenience field for embedding-coverage audits;
|
||||||
|
/// equivalent to (knowledge_nodes.rows − rows in `embeddings` joined to
|
||||||
|
/// knowledge_nodes), so consumers don't have to compute it themselves.
|
||||||
|
pub embedding_null_count: i64,
|
||||||
|
/// Active embedding model name (mirrors `MemoryStats.active_embedding_model`).
|
||||||
|
/// Useful when an audit script wants schema_version + active model in one call.
|
||||||
|
pub active_embedding_model: Option<String>,
|
||||||
|
/// Embedding dimensions for the active model, if known.
|
||||||
|
pub active_embedding_dimensions: Option<u32>,
|
||||||
|
}
|
||||||
|
|
||||||
// ============================================================================
|
// ============================================================================
|
||||||
// CONSOLIDATION RESULT
|
// CONSOLIDATION RESULT
|
||||||
// ============================================================================
|
// ============================================================================
|
||||||
|
|
|
||||||
|
|
@ -79,6 +79,91 @@ impl std::fmt::Display for NodeType {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ============================================================================
|
||||||
|
// SOURCE ENVELOPE (#57)
|
||||||
|
// ============================================================================
|
||||||
|
|
||||||
|
/// Structured provenance for a memory that mirrors a record in an external
|
||||||
|
/// system of record (a Redmine issue, a GitHub Issue, a Jira ticket, a support
|
||||||
|
/// thread, …).
|
||||||
|
///
|
||||||
|
/// The product boundary (#57): the external system stays canonical. Vestige
|
||||||
|
/// **indexes, connects, retrieves, and cites back**; it does not replace the
|
||||||
|
/// ticket tracker. This envelope carries exactly the fields a connector needs
|
||||||
|
/// to do that without leaking stale data:
|
||||||
|
///
|
||||||
|
/// - `(source_system, source_id)` is the **idempotency key**. Re-running a sync
|
||||||
|
/// upserts the same logical record instead of duplicating it.
|
||||||
|
/// - `content_hash` is the **change detector**. If a re-fetched record hashes
|
||||||
|
/// to the stored value, the upsert is a no-op (only `synced_at` advances),
|
||||||
|
/// so an incremental re-scan never churns the index or the embedding model.
|
||||||
|
/// - `source_url` is the **citation**. Search results link back to the
|
||||||
|
/// canonical record so the agent can follow it for authoritative detail.
|
||||||
|
/// - `source_updated_at` is the **cursor field** the connector checkpoints on.
|
||||||
|
///
|
||||||
|
/// Every field is optional at the type level so partial connectors and manual
|
||||||
|
/// imports can populate only what they have, but a real connector should always
|
||||||
|
/// set `source_system`, `source_id`, and `content_hash`.
|
||||||
|
#[non_exhaustive]
|
||||||
|
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct SourceEnvelope {
|
||||||
|
/// External system this record came from, e.g. `redmine`, `github`, `jira`.
|
||||||
|
/// Namespaces `source_id` so two systems can share numeric ids.
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub source_system: Option<String>,
|
||||||
|
/// Stable native id in the source system (Redmine issue id, GitHub issue
|
||||||
|
/// number/node id, …). Combined with `source_system` it is the upsert key.
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub source_id: Option<String>,
|
||||||
|
/// Canonical URL back to the record so retrieval can cite the source.
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub source_url: Option<String>,
|
||||||
|
/// When the source record was last updated upstream (the connector cursor
|
||||||
|
/// field — Redmine `updated_on`, GitHub `updated_at`). RFC 3339.
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub source_updated_at: Option<DateTime<Utc>>,
|
||||||
|
/// Stable hash of the normalized record content. Idempotency / change key.
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub content_hash: Option<String>,
|
||||||
|
/// When the connector last observed this record live. Drives tombstone
|
||||||
|
/// reconciliation (a record not seen in a full reconcile pass is gone).
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub synced_at: Option<DateTime<Utc>>,
|
||||||
|
/// Project / repo / space the record belongs to (Redmine project, GitHub
|
||||||
|
/// `owner/repo`). Used for scoped sync and search filters.
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub source_project: Option<String>,
|
||||||
|
/// Record type within the source (`issue`, `comment`, `journal`, …).
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub source_type: Option<String>,
|
||||||
|
/// Author / reporter of the record in the source system.
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub source_author: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl SourceEnvelope {
|
||||||
|
/// True once the two fields a connector needs for idempotent upsert are
|
||||||
|
/// present. Manual imports that only set `source_url` are not "keyed".
|
||||||
|
pub fn has_key(&self) -> bool {
|
||||||
|
self.source_system.is_some() && self.source_id.is_some()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// True if every field is unset — used to collapse an all-`None` envelope
|
||||||
|
/// back to `None` on the node so legacy rows stay clean.
|
||||||
|
pub fn is_empty(&self) -> bool {
|
||||||
|
self.source_system.is_none()
|
||||||
|
&& self.source_id.is_none()
|
||||||
|
&& self.source_url.is_none()
|
||||||
|
&& self.source_updated_at.is_none()
|
||||||
|
&& self.content_hash.is_none()
|
||||||
|
&& self.synced_at.is_none()
|
||||||
|
&& self.source_project.is_none()
|
||||||
|
&& self.source_type.is_none()
|
||||||
|
&& self.source_author.is_none()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// ============================================================================
|
// ============================================================================
|
||||||
// KNOWLEDGE NODE
|
// KNOWLEDGE NODE
|
||||||
// ============================================================================
|
// ============================================================================
|
||||||
|
|
@ -188,6 +273,15 @@ pub struct KnowledgeNode {
|
||||||
/// Timestamp of the most recent suppression (for 24h labile window).
|
/// Timestamp of the most recent suppression (for 24h labile window).
|
||||||
#[serde(skip_serializing_if = "Option::is_none")]
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
pub suppressed_at: Option<DateTime<Utc>>,
|
pub suppressed_at: Option<DateTime<Utc>>,
|
||||||
|
|
||||||
|
// ========== Source Envelope (#57, external-source connectors) ==========
|
||||||
|
/// Structured provenance for memories ingested from an external system
|
||||||
|
/// (Redmine, GitHub Issues, Jira, …). `None` for memories created directly
|
||||||
|
/// by an agent or the user — the legacy free-form `source` string above
|
||||||
|
/// remains the human-readable label; this envelope is the machine-readable,
|
||||||
|
/// idempotency- and citation-bearing record. See [`SourceEnvelope`].
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub source_envelope: Option<SourceEnvelope>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Default for KnowledgeNode {
|
impl Default for KnowledgeNode {
|
||||||
|
|
@ -224,6 +318,7 @@ impl Default for KnowledgeNode {
|
||||||
embedding_model: None,
|
embedding_model: None,
|
||||||
suppression_count: 0,
|
suppression_count: 0,
|
||||||
suppressed_at: None,
|
suppressed_at: None,
|
||||||
|
source_envelope: None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -291,6 +386,11 @@ pub struct IngestInput {
|
||||||
/// When this knowledge stops being valid
|
/// When this knowledge stops being valid
|
||||||
#[serde(skip_serializing_if = "Option::is_none")]
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
pub valid_until: Option<DateTime<Utc>>,
|
pub valid_until: Option<DateTime<Utc>>,
|
||||||
|
/// Structured provenance for connector-ingested records (#57). When set
|
||||||
|
/// with a `(source_system, source_id)` key, callers should route through
|
||||||
|
/// `upsert_by_source` for idempotent sync rather than plain `ingest`.
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub source_envelope: Option<SourceEnvelope>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Default for IngestInput {
|
impl Default for IngestInput {
|
||||||
|
|
@ -304,6 +404,7 @@ impl Default for IngestInput {
|
||||||
tags: vec![],
|
tags: vec![],
|
||||||
valid_from: None,
|
valid_from: None,
|
||||||
valid_until: None,
|
valid_until: None,
|
||||||
|
source_envelope: None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
516
crates/vestige-core/src/storage/memory_store.rs
Normal file
516
crates/vestige-core/src/storage/memory_store.rs
Normal file
|
|
@ -0,0 +1,516 @@
|
||||||
|
//! Backend-agnostic memory store trait.
|
||||||
|
//!
|
||||||
|
//! This is the single abstraction every cognitive module sits above. It is
|
||||||
|
//! intentionally flat: one trait, ~25 methods, no sub-traits.
|
||||||
|
|
||||||
|
use std::collections::HashMap;
|
||||||
|
use std::future::Future;
|
||||||
|
use std::pin::Pin;
|
||||||
|
|
||||||
|
use chrono::{DateTime, Utc};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use uuid::Uuid;
|
||||||
|
|
||||||
|
// ----------------------------------------------------------------------------
|
||||||
|
// ERROR
|
||||||
|
// ----------------------------------------------------------------------------
|
||||||
|
|
||||||
|
/// Error returned by every `LocalMemoryStore` / `MemoryStore` method.
|
||||||
|
#[non_exhaustive]
|
||||||
|
#[derive(Debug, thiserror::Error)]
|
||||||
|
pub enum MemoryStoreError {
|
||||||
|
#[error("not found: {0}")]
|
||||||
|
NotFound(String),
|
||||||
|
|
||||||
|
#[error("backend error: {0}")]
|
||||||
|
Backend(String),
|
||||||
|
|
||||||
|
#[error(
|
||||||
|
"embedding model mismatch: store registered {registered_name} (dim {registered_dim}, \
|
||||||
|
hash {registered_hash}), embedder is {actual_name} (dim {actual_dim}, hash {actual_hash})"
|
||||||
|
)]
|
||||||
|
ModelMismatch {
|
||||||
|
registered_name: String,
|
||||||
|
registered_dim: usize,
|
||||||
|
registered_hash: String,
|
||||||
|
actual_name: String,
|
||||||
|
actual_dim: usize,
|
||||||
|
actual_hash: String,
|
||||||
|
},
|
||||||
|
|
||||||
|
#[error("invalid input: {0}")]
|
||||||
|
InvalidInput(String),
|
||||||
|
|
||||||
|
#[error("initialization error: {0}")]
|
||||||
|
Init(String),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<crate::storage::StorageError> for MemoryStoreError {
|
||||||
|
fn from(e: crate::storage::StorageError) -> Self {
|
||||||
|
use crate::storage::StorageError as S;
|
||||||
|
match e {
|
||||||
|
S::NotFound(s) => MemoryStoreError::NotFound(s),
|
||||||
|
S::Database(e) => MemoryStoreError::Backend(e.to_string()),
|
||||||
|
S::Io(e) => MemoryStoreError::Backend(e.to_string()),
|
||||||
|
S::InvalidTimestamp(s) => MemoryStoreError::Backend(format!("invalid timestamp: {s}")),
|
||||||
|
S::Init(s) => MemoryStoreError::Init(s),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub type MemoryStoreResult<T> = std::result::Result<T, MemoryStoreError>;
|
||||||
|
|
||||||
|
// ----------------------------------------------------------------------------
|
||||||
|
// DATA TYPES
|
||||||
|
// ----------------------------------------------------------------------------
|
||||||
|
|
||||||
|
/// Backend-agnostic memory record.
|
||||||
|
///
|
||||||
|
/// Phase 1 intentionally keeps this type independent of `KnowledgeNode` to
|
||||||
|
/// avoid dragging 30+ legacy fields through the trait surface. The SQLite
|
||||||
|
/// backend converts between `MemoryRecord` and `KnowledgeNode` at the
|
||||||
|
/// boundary.
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
pub struct MemoryRecord {
|
||||||
|
pub id: Uuid,
|
||||||
|
/// Empty = unclassified. Populated in Phase 4.
|
||||||
|
pub domains: Vec<String>,
|
||||||
|
/// Raw similarity per domain centroid. Empty until Phase 4 runs clustering.
|
||||||
|
pub domain_scores: HashMap<String, f64>,
|
||||||
|
pub content: String,
|
||||||
|
pub node_type: String,
|
||||||
|
pub tags: Vec<String>,
|
||||||
|
pub embedding: Option<Vec<f32>>,
|
||||||
|
pub created_at: DateTime<Utc>,
|
||||||
|
pub updated_at: DateTime<Utc>,
|
||||||
|
pub metadata: serde_json::Value,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// FSRS-6 scheduling state, one row per memory.
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
pub struct SchedulingState {
|
||||||
|
pub memory_id: Uuid,
|
||||||
|
pub stability: f64,
|
||||||
|
pub difficulty: f64,
|
||||||
|
pub retrievability: f64,
|
||||||
|
pub last_review: Option<DateTime<Utc>>,
|
||||||
|
pub next_review: Option<DateTime<Utc>>,
|
||||||
|
pub reps: u32,
|
||||||
|
pub lapses: u32,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Hybrid search request.
|
||||||
|
#[derive(Debug, Clone, Default)]
|
||||||
|
pub struct SearchQuery {
|
||||||
|
pub domains: Option<Vec<String>>,
|
||||||
|
pub text: Option<String>,
|
||||||
|
pub embedding: Option<Vec<f32>>,
|
||||||
|
pub tags: Option<Vec<String>>,
|
||||||
|
pub node_types: Option<Vec<String>>,
|
||||||
|
pub limit: usize,
|
||||||
|
pub min_retrievability: Option<f64>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct SearchResult {
|
||||||
|
pub record: MemoryRecord,
|
||||||
|
pub score: f64,
|
||||||
|
pub fts_score: Option<f64>,
|
||||||
|
pub vector_score: Option<f64>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Edge in the spreading-activation graph.
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
pub struct MemoryEdge {
|
||||||
|
pub source_id: Uuid,
|
||||||
|
pub target_id: Uuid,
|
||||||
|
pub edge_type: String,
|
||||||
|
pub weight: f64,
|
||||||
|
pub created_at: DateTime<Utc>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A topical domain (populated in Phase 4). Phase 1 only needs the type to
|
||||||
|
/// shape the trait surface; discover/classify are Phase 4 work.
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
pub struct Domain {
|
||||||
|
pub id: String,
|
||||||
|
pub label: String,
|
||||||
|
pub centroid: Vec<f32>,
|
||||||
|
pub top_terms: Vec<String>,
|
||||||
|
pub memory_count: usize,
|
||||||
|
pub created_at: DateTime<Utc>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Result of classifying one vector against all known domains.
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct ClassificationResult {
|
||||||
|
pub scores: HashMap<String, f64>,
|
||||||
|
pub domains: Vec<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
|
||||||
|
pub struct StoreStats {
|
||||||
|
pub total_memories: usize,
|
||||||
|
pub memories_with_embeddings: usize,
|
||||||
|
pub total_edges: usize,
|
||||||
|
pub total_domains: usize,
|
||||||
|
pub registered_model_name: Option<String>,
|
||||||
|
pub registered_model_dim: Option<usize>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
pub enum HealthStatus {
|
||||||
|
Healthy,
|
||||||
|
Degraded { reason: String },
|
||||||
|
Unavailable { reason: String },
|
||||||
|
}
|
||||||
|
|
||||||
|
// ----------------------------------------------------------------------------
|
||||||
|
// EMBEDDING MODEL SIGNATURE
|
||||||
|
// ----------------------------------------------------------------------------
|
||||||
|
|
||||||
|
/// Snapshot of the embedding model that was used to write vectors into the
|
||||||
|
/// store. Persisted in the `embedding_model` table; compared on every write
|
||||||
|
/// before the vector is accepted.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
pub struct ModelSignature {
|
||||||
|
pub name: String,
|
||||||
|
pub dimension: usize,
|
||||||
|
/// Lowercase hex-encoded blake3 hash, 64 chars.
|
||||||
|
pub hash: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
// ----------------------------------------------------------------------------
|
||||||
|
// TRAIT
|
||||||
|
// ----------------------------------------------------------------------------
|
||||||
|
|
||||||
|
/// Internal source trait declared with native async-fn-in-trait.
|
||||||
|
///
|
||||||
|
/// `#[trait_variant::make(MemoryStoreSend: Send)]` derives a Send-bounded
|
||||||
|
/// variant whose returned futures are `Send`. In trait_variant 0.1.x the
|
||||||
|
/// macro emits the blanket `impl<T: MemoryStoreSend> LocalMemoryStore for T`,
|
||||||
|
/// so backends implement `MemoryStoreSend` (the Send variant) and get
|
||||||
|
/// `LocalMemoryStore` (the non-Send variant) for free.
|
||||||
|
///
|
||||||
|
/// Most callers should reach for the dyn-compatible `MemoryStore` trait
|
||||||
|
/// declared below, which adapts `MemoryStoreSend` into a boxed-future surface
|
||||||
|
/// and is the public storage abstraction for cognitive modules and tests
|
||||||
|
/// that want `Arc<dyn MemoryStore>`.
|
||||||
|
#[trait_variant::make(MemoryStoreSend: Send)]
|
||||||
|
pub trait LocalMemoryStore: Sync + 'static {
|
||||||
|
// --- Lifecycle ---
|
||||||
|
async fn init(&self) -> MemoryStoreResult<()>;
|
||||||
|
async fn health_check(&self) -> MemoryStoreResult<HealthStatus>;
|
||||||
|
|
||||||
|
// --- Embedding model registry ---
|
||||||
|
async fn registered_model(&self) -> MemoryStoreResult<Option<ModelSignature>>;
|
||||||
|
async fn register_model(&self, sig: &ModelSignature) -> MemoryStoreResult<()>;
|
||||||
|
|
||||||
|
// --- CRUD ---
|
||||||
|
async fn insert(&self, record: &MemoryRecord) -> MemoryStoreResult<Uuid>;
|
||||||
|
async fn get(&self, id: Uuid) -> MemoryStoreResult<Option<MemoryRecord>>;
|
||||||
|
async fn update(&self, record: &MemoryRecord) -> MemoryStoreResult<()>;
|
||||||
|
async fn delete(&self, id: Uuid) -> MemoryStoreResult<()>;
|
||||||
|
|
||||||
|
// --- Search ---
|
||||||
|
async fn search(&self, query: &SearchQuery) -> MemoryStoreResult<Vec<SearchResult>>;
|
||||||
|
async fn fts_search(&self, text: &str, limit: usize) -> MemoryStoreResult<Vec<SearchResult>>;
|
||||||
|
async fn vector_search(
|
||||||
|
&self,
|
||||||
|
embedding: &[f32],
|
||||||
|
limit: usize,
|
||||||
|
) -> MemoryStoreResult<Vec<SearchResult>>;
|
||||||
|
|
||||||
|
// --- FSRS Scheduling ---
|
||||||
|
async fn get_scheduling(&self, memory_id: Uuid) -> MemoryStoreResult<Option<SchedulingState>>;
|
||||||
|
async fn update_scheduling(&self, state: &SchedulingState) -> MemoryStoreResult<()>;
|
||||||
|
async fn get_due_memories(
|
||||||
|
&self,
|
||||||
|
before: DateTime<Utc>,
|
||||||
|
limit: usize,
|
||||||
|
) -> MemoryStoreResult<Vec<(MemoryRecord, SchedulingState)>>;
|
||||||
|
|
||||||
|
// --- Graph (spreading activation) ---
|
||||||
|
async fn add_edge(&self, edge: &MemoryEdge) -> MemoryStoreResult<()>;
|
||||||
|
async fn get_edges(
|
||||||
|
&self,
|
||||||
|
node_id: Uuid,
|
||||||
|
edge_type: Option<&str>,
|
||||||
|
) -> MemoryStoreResult<Vec<MemoryEdge>>;
|
||||||
|
async fn remove_edge(&self, source: Uuid, target: Uuid) -> MemoryStoreResult<()>;
|
||||||
|
async fn get_neighbors(
|
||||||
|
&self,
|
||||||
|
node_id: Uuid,
|
||||||
|
depth: usize,
|
||||||
|
) -> MemoryStoreResult<Vec<(MemoryRecord, f64)>>;
|
||||||
|
|
||||||
|
// --- Domains (Phase 1: stubs return empty; full impl in Phase 4) ---
|
||||||
|
async fn list_domains(&self) -> MemoryStoreResult<Vec<Domain>>;
|
||||||
|
async fn get_domain(&self, id: &str) -> MemoryStoreResult<Option<Domain>>;
|
||||||
|
async fn upsert_domain(&self, domain: &Domain) -> MemoryStoreResult<()>;
|
||||||
|
async fn delete_domain(&self, id: &str) -> MemoryStoreResult<()>;
|
||||||
|
/// Phase 1: returns `Ok(vec![])` since no centroids exist. Phase 4 wires
|
||||||
|
/// the full soft-assignment pass.
|
||||||
|
async fn classify(&self, embedding: &[f32]) -> MemoryStoreResult<Vec<(String, f64)>>;
|
||||||
|
|
||||||
|
// --- Bulk / Maintenance ---
|
||||||
|
async fn count(&self) -> MemoryStoreResult<usize>;
|
||||||
|
async fn get_stats(&self) -> MemoryStoreResult<StoreStats>;
|
||||||
|
async fn vacuum(&self) -> MemoryStoreResult<()>;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ----------------------------------------------------------------------------
|
||||||
|
// DYN-COMPATIBLE STORAGE TRAIT
|
||||||
|
// ----------------------------------------------------------------------------
|
||||||
|
|
||||||
|
/// Boxed Send future returning a `MemoryStoreResult<T>`, bound to the lifetime
|
||||||
|
/// of the borrows captured by the call (typically `&self` plus any reference
|
||||||
|
/// arguments). Used as the return type of every method on the dyn-compatible
|
||||||
|
/// `MemoryStore` trait below.
|
||||||
|
pub type BoxedStoreFuture<'a, T> = Pin<Box<dyn Future<Output = MemoryStoreResult<T>> + Send + 'a>>;
|
||||||
|
|
||||||
|
/// Dyn-compatible storage trait.
|
||||||
|
///
|
||||||
|
/// `MemoryStoreSend` above is the trait users implement; it uses native
|
||||||
|
/// async-fn-in-trait return types (RPITIT), which gives zero-allocation
|
||||||
|
/// static dispatch but is not dyn-safe. This trait wraps every method in
|
||||||
|
/// `Pin<Box<dyn Future + Send + '_>>` so `Arc<dyn MemoryStore>` works for
|
||||||
|
/// the cognitive module surface and the Phase 1 integration tests.
|
||||||
|
///
|
||||||
|
/// Implementations should not target this trait directly; the blanket
|
||||||
|
/// `impl<T: MemoryStoreSend> MemoryStore for T` adapts every Send-variant
|
||||||
|
/// implementation automatically. Each call boxes the returned future
|
||||||
|
/// exactly once, identical to the cost of the previous design.
|
||||||
|
pub trait MemoryStore: Send + Sync + 'static {
|
||||||
|
fn init<'a>(&'a self) -> BoxedStoreFuture<'a, ()>;
|
||||||
|
fn health_check<'a>(&'a self) -> BoxedStoreFuture<'a, HealthStatus>;
|
||||||
|
|
||||||
|
fn registered_model<'a>(&'a self) -> BoxedStoreFuture<'a, Option<ModelSignature>>;
|
||||||
|
fn register_model<'a>(&'a self, sig: &'a ModelSignature) -> BoxedStoreFuture<'a, ()>;
|
||||||
|
|
||||||
|
fn insert<'a>(&'a self, record: &'a MemoryRecord) -> BoxedStoreFuture<'a, Uuid>;
|
||||||
|
fn get<'a>(&'a self, id: Uuid) -> BoxedStoreFuture<'a, Option<MemoryRecord>>;
|
||||||
|
fn update<'a>(&'a self, record: &'a MemoryRecord) -> BoxedStoreFuture<'a, ()>;
|
||||||
|
fn delete<'a>(&'a self, id: Uuid) -> BoxedStoreFuture<'a, ()>;
|
||||||
|
|
||||||
|
fn search<'a>(&'a self, query: &'a SearchQuery) -> BoxedStoreFuture<'a, Vec<SearchResult>>;
|
||||||
|
fn fts_search<'a>(
|
||||||
|
&'a self,
|
||||||
|
text: &'a str,
|
||||||
|
limit: usize,
|
||||||
|
) -> BoxedStoreFuture<'a, Vec<SearchResult>>;
|
||||||
|
fn vector_search<'a>(
|
||||||
|
&'a self,
|
||||||
|
embedding: &'a [f32],
|
||||||
|
limit: usize,
|
||||||
|
) -> BoxedStoreFuture<'a, Vec<SearchResult>>;
|
||||||
|
|
||||||
|
fn get_scheduling<'a>(
|
||||||
|
&'a self,
|
||||||
|
memory_id: Uuid,
|
||||||
|
) -> BoxedStoreFuture<'a, Option<SchedulingState>>;
|
||||||
|
fn update_scheduling<'a>(&'a self, state: &'a SchedulingState) -> BoxedStoreFuture<'a, ()>;
|
||||||
|
fn get_due_memories<'a>(
|
||||||
|
&'a self,
|
||||||
|
before: DateTime<Utc>,
|
||||||
|
limit: usize,
|
||||||
|
) -> BoxedStoreFuture<'a, Vec<(MemoryRecord, SchedulingState)>>;
|
||||||
|
|
||||||
|
fn add_edge<'a>(&'a self, edge: &'a MemoryEdge) -> BoxedStoreFuture<'a, ()>;
|
||||||
|
fn get_edges<'a>(
|
||||||
|
&'a self,
|
||||||
|
node_id: Uuid,
|
||||||
|
edge_type: Option<&'a str>,
|
||||||
|
) -> BoxedStoreFuture<'a, Vec<MemoryEdge>>;
|
||||||
|
fn remove_edge<'a>(&'a self, source: Uuid, target: Uuid) -> BoxedStoreFuture<'a, ()>;
|
||||||
|
fn get_neighbors<'a>(
|
||||||
|
&'a self,
|
||||||
|
node_id: Uuid,
|
||||||
|
depth: usize,
|
||||||
|
) -> BoxedStoreFuture<'a, Vec<(MemoryRecord, f64)>>;
|
||||||
|
|
||||||
|
fn list_domains<'a>(&'a self) -> BoxedStoreFuture<'a, Vec<Domain>>;
|
||||||
|
fn get_domain<'a>(&'a self, id: &'a str) -> BoxedStoreFuture<'a, Option<Domain>>;
|
||||||
|
fn upsert_domain<'a>(&'a self, domain: &'a Domain) -> BoxedStoreFuture<'a, ()>;
|
||||||
|
fn delete_domain<'a>(&'a self, id: &'a str) -> BoxedStoreFuture<'a, ()>;
|
||||||
|
fn classify<'a>(&'a self, embedding: &'a [f32]) -> BoxedStoreFuture<'a, Vec<(String, f64)>>;
|
||||||
|
|
||||||
|
fn count<'a>(&'a self) -> BoxedStoreFuture<'a, usize>;
|
||||||
|
fn get_stats<'a>(&'a self) -> BoxedStoreFuture<'a, StoreStats>;
|
||||||
|
fn vacuum<'a>(&'a self) -> BoxedStoreFuture<'a, ()>;
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T> MemoryStore for T
|
||||||
|
where
|
||||||
|
T: MemoryStoreSend,
|
||||||
|
{
|
||||||
|
fn init<'a>(&'a self) -> BoxedStoreFuture<'a, ()> {
|
||||||
|
Box::pin(<T as MemoryStoreSend>::init(self))
|
||||||
|
}
|
||||||
|
fn health_check<'a>(&'a self) -> BoxedStoreFuture<'a, HealthStatus> {
|
||||||
|
Box::pin(<T as MemoryStoreSend>::health_check(self))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn registered_model<'a>(&'a self) -> BoxedStoreFuture<'a, Option<ModelSignature>> {
|
||||||
|
Box::pin(<T as MemoryStoreSend>::registered_model(self))
|
||||||
|
}
|
||||||
|
fn register_model<'a>(&'a self, sig: &'a ModelSignature) -> BoxedStoreFuture<'a, ()> {
|
||||||
|
Box::pin(<T as MemoryStoreSend>::register_model(self, sig))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn insert<'a>(&'a self, record: &'a MemoryRecord) -> BoxedStoreFuture<'a, Uuid> {
|
||||||
|
Box::pin(<T as MemoryStoreSend>::insert(self, record))
|
||||||
|
}
|
||||||
|
fn get<'a>(&'a self, id: Uuid) -> BoxedStoreFuture<'a, Option<MemoryRecord>> {
|
||||||
|
Box::pin(<T as MemoryStoreSend>::get(self, id))
|
||||||
|
}
|
||||||
|
fn update<'a>(&'a self, record: &'a MemoryRecord) -> BoxedStoreFuture<'a, ()> {
|
||||||
|
Box::pin(<T as MemoryStoreSend>::update(self, record))
|
||||||
|
}
|
||||||
|
fn delete<'a>(&'a self, id: Uuid) -> BoxedStoreFuture<'a, ()> {
|
||||||
|
Box::pin(<T as MemoryStoreSend>::delete(self, id))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn search<'a>(&'a self, query: &'a SearchQuery) -> BoxedStoreFuture<'a, Vec<SearchResult>> {
|
||||||
|
Box::pin(<T as MemoryStoreSend>::search(self, query))
|
||||||
|
}
|
||||||
|
fn fts_search<'a>(
|
||||||
|
&'a self,
|
||||||
|
text: &'a str,
|
||||||
|
limit: usize,
|
||||||
|
) -> BoxedStoreFuture<'a, Vec<SearchResult>> {
|
||||||
|
Box::pin(<T as MemoryStoreSend>::fts_search(self, text, limit))
|
||||||
|
}
|
||||||
|
fn vector_search<'a>(
|
||||||
|
&'a self,
|
||||||
|
embedding: &'a [f32],
|
||||||
|
limit: usize,
|
||||||
|
) -> BoxedStoreFuture<'a, Vec<SearchResult>> {
|
||||||
|
Box::pin(<T as MemoryStoreSend>::vector_search(
|
||||||
|
self, embedding, limit,
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn get_scheduling<'a>(
|
||||||
|
&'a self,
|
||||||
|
memory_id: Uuid,
|
||||||
|
) -> BoxedStoreFuture<'a, Option<SchedulingState>> {
|
||||||
|
Box::pin(<T as MemoryStoreSend>::get_scheduling(self, memory_id))
|
||||||
|
}
|
||||||
|
fn update_scheduling<'a>(&'a self, state: &'a SchedulingState) -> BoxedStoreFuture<'a, ()> {
|
||||||
|
Box::pin(<T as MemoryStoreSend>::update_scheduling(self, state))
|
||||||
|
}
|
||||||
|
fn get_due_memories<'a>(
|
||||||
|
&'a self,
|
||||||
|
before: DateTime<Utc>,
|
||||||
|
limit: usize,
|
||||||
|
) -> BoxedStoreFuture<'a, Vec<(MemoryRecord, SchedulingState)>> {
|
||||||
|
Box::pin(<T as MemoryStoreSend>::get_due_memories(
|
||||||
|
self, before, limit,
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn add_edge<'a>(&'a self, edge: &'a MemoryEdge) -> BoxedStoreFuture<'a, ()> {
|
||||||
|
Box::pin(<T as MemoryStoreSend>::add_edge(self, edge))
|
||||||
|
}
|
||||||
|
fn get_edges<'a>(
|
||||||
|
&'a self,
|
||||||
|
node_id: Uuid,
|
||||||
|
edge_type: Option<&'a str>,
|
||||||
|
) -> BoxedStoreFuture<'a, Vec<MemoryEdge>> {
|
||||||
|
Box::pin(<T as MemoryStoreSend>::get_edges(self, node_id, edge_type))
|
||||||
|
}
|
||||||
|
fn remove_edge<'a>(&'a self, source: Uuid, target: Uuid) -> BoxedStoreFuture<'a, ()> {
|
||||||
|
Box::pin(<T as MemoryStoreSend>::remove_edge(self, source, target))
|
||||||
|
}
|
||||||
|
fn get_neighbors<'a>(
|
||||||
|
&'a self,
|
||||||
|
node_id: Uuid,
|
||||||
|
depth: usize,
|
||||||
|
) -> BoxedStoreFuture<'a, Vec<(MemoryRecord, f64)>> {
|
||||||
|
Box::pin(<T as MemoryStoreSend>::get_neighbors(self, node_id, depth))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn list_domains<'a>(&'a self) -> BoxedStoreFuture<'a, Vec<Domain>> {
|
||||||
|
Box::pin(<T as MemoryStoreSend>::list_domains(self))
|
||||||
|
}
|
||||||
|
fn get_domain<'a>(&'a self, id: &'a str) -> BoxedStoreFuture<'a, Option<Domain>> {
|
||||||
|
Box::pin(<T as MemoryStoreSend>::get_domain(self, id))
|
||||||
|
}
|
||||||
|
fn upsert_domain<'a>(&'a self, domain: &'a Domain) -> BoxedStoreFuture<'a, ()> {
|
||||||
|
Box::pin(<T as MemoryStoreSend>::upsert_domain(self, domain))
|
||||||
|
}
|
||||||
|
fn delete_domain<'a>(&'a self, id: &'a str) -> BoxedStoreFuture<'a, ()> {
|
||||||
|
Box::pin(<T as MemoryStoreSend>::delete_domain(self, id))
|
||||||
|
}
|
||||||
|
fn classify<'a>(&'a self, embedding: &'a [f32]) -> BoxedStoreFuture<'a, Vec<(String, f64)>> {
|
||||||
|
Box::pin(<T as MemoryStoreSend>::classify(self, embedding))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn count<'a>(&'a self) -> BoxedStoreFuture<'a, usize> {
|
||||||
|
Box::pin(<T as MemoryStoreSend>::count(self))
|
||||||
|
}
|
||||||
|
fn get_stats<'a>(&'a self) -> BoxedStoreFuture<'a, StoreStats> {
|
||||||
|
Box::pin(<T as MemoryStoreSend>::get_stats(self))
|
||||||
|
}
|
||||||
|
fn vacuum<'a>(&'a self) -> BoxedStoreFuture<'a, ()> {
|
||||||
|
Box::pin(<T as MemoryStoreSend>::vacuum(self))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ----------------------------------------------------------------------------
|
||||||
|
// UNIT TESTS
|
||||||
|
// ----------------------------------------------------------------------------
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use crate::storage::StorageError;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn memory_store_error_from_storage_error() {
|
||||||
|
let se = StorageError::NotFound("abc".to_string());
|
||||||
|
let mse = MemoryStoreError::from(se);
|
||||||
|
assert!(matches!(mse, MemoryStoreError::NotFound(_)));
|
||||||
|
|
||||||
|
let se2 = StorageError::Init("init failure".to_string());
|
||||||
|
let mse2 = MemoryStoreError::from(se2);
|
||||||
|
assert!(matches!(mse2, MemoryStoreError::Init(_)));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn model_signature_serde_round_trip() {
|
||||||
|
let sig = ModelSignature {
|
||||||
|
name: "nomic-ai/nomic-embed-text-v1.5".to_string(),
|
||||||
|
dimension: 256,
|
||||||
|
hash: "a".repeat(64),
|
||||||
|
};
|
||||||
|
let json = serde_json::to_string(&sig).expect("serialize");
|
||||||
|
let sig2: ModelSignature = serde_json::from_str(&json).expect("deserialize");
|
||||||
|
assert_eq!(sig, sig2);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn memory_record_serde_round_trip() {
|
||||||
|
let rec = MemoryRecord {
|
||||||
|
id: Uuid::new_v4(),
|
||||||
|
domains: vec!["dev".to_string()],
|
||||||
|
domain_scores: {
|
||||||
|
let mut m = HashMap::new();
|
||||||
|
m.insert("dev".to_string(), 0.9);
|
||||||
|
m
|
||||||
|
},
|
||||||
|
content: "hello".to_string(),
|
||||||
|
node_type: "fact".to_string(),
|
||||||
|
tags: vec!["tag1".to_string()],
|
||||||
|
embedding: None,
|
||||||
|
created_at: Utc::now(),
|
||||||
|
updated_at: Utc::now(),
|
||||||
|
metadata: serde_json::json!({}),
|
||||||
|
};
|
||||||
|
let json = serde_json::to_string(&rec).expect("serialize");
|
||||||
|
let rec2: MemoryRecord = serde_json::from_str(&json).expect("deserialize");
|
||||||
|
assert_eq!(rec.content, rec2.content);
|
||||||
|
assert_eq!(rec.domains, rec2.domains);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -69,6 +69,26 @@ pub const MIGRATIONS: &[Migration] = &[
|
||||||
description: "v2.1.2 Honest Memory: non-content purge tombstones",
|
description: "v2.1.2 Honest Memory: non-content purge tombstones",
|
||||||
up: MIGRATION_V13_UP,
|
up: MIGRATION_V13_UP,
|
||||||
},
|
},
|
||||||
|
Migration {
|
||||||
|
version: 14,
|
||||||
|
description: "v2.1.25 Merge/Supersede: reversible operation log, merge plans, bitemporal lineage, protected pins",
|
||||||
|
up: MIGRATION_V14_UP,
|
||||||
|
},
|
||||||
|
Migration {
|
||||||
|
version: 15,
|
||||||
|
description: "ComposedGraph: composition events, members, outcomes",
|
||||||
|
up: MIGRATION_V15_UP,
|
||||||
|
},
|
||||||
|
Migration {
|
||||||
|
version: 16,
|
||||||
|
description: "ADR 0001 Phase 1: embedding_model registry, domains/domain_scores columns, domains table",
|
||||||
|
up: MIGRATION_V16_UP,
|
||||||
|
},
|
||||||
|
Migration {
|
||||||
|
version: 17,
|
||||||
|
description: "#57 Source envelope: provenance columns + connector cursor checkpoints for idempotent external-source sync",
|
||||||
|
up: MIGRATION_V17_UP,
|
||||||
|
},
|
||||||
];
|
];
|
||||||
|
|
||||||
/// A database migration
|
/// A database migration
|
||||||
|
|
@ -735,6 +755,140 @@ ON deletion_tombstones(deleted_at);
|
||||||
UPDATE schema_version SET version = 13, applied_at = datetime('now');
|
UPDATE schema_version SET version = 13, applied_at = datetime('now');
|
||||||
"#;
|
"#;
|
||||||
|
|
||||||
|
/// V14: Merge / Supersede controls (Phase 3).
|
||||||
|
///
|
||||||
|
/// Adds the four pieces the merge/supersede feature needs on a never-delete
|
||||||
|
/// (bitemporal) store:
|
||||||
|
///
|
||||||
|
/// 1. `merge_plans` — previewable, not-yet-applied plans. `plan_merge` and
|
||||||
|
/// `plan_supersede` write a plan row containing a JSON diff; `apply_plan`
|
||||||
|
/// consumes it by id. Plans are append-only; status moves
|
||||||
|
/// pending -> applied / cancelled.
|
||||||
|
/// 2. `merge_operations` — the reversible operation log (the "memory reflog").
|
||||||
|
/// Every applied merge/supersede records one row with a JSON `undo_payload`
|
||||||
|
/// capturing exactly what changed, so `merge_undo` can reverse it. The
|
||||||
|
/// `signals` column records WHY the memories combined (provenance), which is
|
||||||
|
/// the self-explaining differentiator.
|
||||||
|
/// 3. `knowledge_nodes.protected` — pin flag. A protected memory can never be
|
||||||
|
/// auto-merged, superseded, or forgotten.
|
||||||
|
/// 4. `knowledge_nodes.superseded_by` — bitemporal lineage pointer. Superseding
|
||||||
|
/// A with B does NOT delete A: it stamps A.valid_until = B.valid_from and
|
||||||
|
/// sets A.superseded_by = B.id, leaving A fully queryable for audit
|
||||||
|
/// (Graphiti-style invalidate-don't-delete).
|
||||||
|
// The two `protected` / `superseded_by` ADD COLUMNs (and their indexes) are
|
||||||
|
// applied separately in `apply_migrations` BEFORE this batch runs, guarded
|
||||||
|
// against "duplicate column" on replay, since SQLite has no
|
||||||
|
// `ADD COLUMN IF NOT EXISTS`. The rest of V14 is idempotent (CREATE ... IF NOT
|
||||||
|
// EXISTS).
|
||||||
|
const MIGRATION_V14_UP: &str = r#"
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_nodes_protected ON knowledge_nodes(protected);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_nodes_superseded_by ON knowledge_nodes(superseded_by);
|
||||||
|
|
||||||
|
-- Previewable plans (a diff) produced by plan_merge / plan_supersede.
|
||||||
|
-- `kind` is 'merge' | 'supersede'. `payload` is the full JSON plan/diff.
|
||||||
|
CREATE TABLE IF NOT EXISTS merge_plans (
|
||||||
|
id TEXT PRIMARY KEY,
|
||||||
|
kind TEXT NOT NULL,
|
||||||
|
status TEXT NOT NULL DEFAULT 'pending', -- pending | applied | cancelled
|
||||||
|
created_at TEXT NOT NULL,
|
||||||
|
applied_at TEXT,
|
||||||
|
survivor_id TEXT, -- node kept after the op
|
||||||
|
member_ids TEXT NOT NULL DEFAULT '[]', -- JSON array of all involved node ids
|
||||||
|
confidence REAL, -- Fellegi-Sunter match score (0-1)
|
||||||
|
classification TEXT, -- match | possible | non_match
|
||||||
|
payload TEXT NOT NULL -- full JSON plan/diff
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_merge_plans_status ON merge_plans(status);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_merge_plans_created_at ON merge_plans(created_at);
|
||||||
|
|
||||||
|
-- Reversible operation log — the "git reflog for your agent's memory".
|
||||||
|
-- One row per applied merge/supersede; `undo_payload` carries everything
|
||||||
|
-- needed to reverse it, `signals` records why the memories combined.
|
||||||
|
CREATE TABLE IF NOT EXISTS merge_operations (
|
||||||
|
id TEXT PRIMARY KEY,
|
||||||
|
plan_id TEXT, -- merge_plans.id this came from
|
||||||
|
op_type TEXT NOT NULL, -- merge | supersede | undo
|
||||||
|
status TEXT NOT NULL DEFAULT 'applied', -- applied | reverted
|
||||||
|
created_at TEXT NOT NULL,
|
||||||
|
reverted_at TEXT,
|
||||||
|
reverts_op_id TEXT, -- set when op_type = 'undo'
|
||||||
|
survivor_id TEXT, -- node kept
|
||||||
|
affected_ids TEXT NOT NULL DEFAULT '[]', -- JSON array of node ids touched
|
||||||
|
confidence REAL,
|
||||||
|
signals TEXT, -- JSON: why they combined (provenance)
|
||||||
|
reason TEXT, -- human-readable explanation
|
||||||
|
undo_payload TEXT NOT NULL -- JSON snapshot to reverse the op
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_merge_operations_status ON merge_operations(status);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_merge_operations_created_at ON merge_operations(created_at);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_merge_operations_survivor ON merge_operations(survivor_id);
|
||||||
|
|
||||||
|
UPDATE schema_version SET version = 14, applied_at = datetime('now');
|
||||||
|
"#;
|
||||||
|
|
||||||
|
/// V15: ComposedGraph persistence for memory composition outcomes.
|
||||||
|
///
|
||||||
|
/// These tables record which memories were used together, which tool/query
|
||||||
|
/// produced the composition, and what happened afterward. `memory_id` values
|
||||||
|
/// are intentionally historical references instead of foreign keys to
|
||||||
|
/// `knowledge_nodes`: purging or superseding a memory must not erase the fact
|
||||||
|
/// that a bounty lane or reasoning path was previously composed.
|
||||||
|
const MIGRATION_V15_UP: &str = r#"
|
||||||
|
CREATE TABLE IF NOT EXISTS composition_events (
|
||||||
|
id TEXT PRIMARY KEY,
|
||||||
|
created_at TEXT NOT NULL,
|
||||||
|
tool TEXT NOT NULL,
|
||||||
|
mode TEXT NOT NULL DEFAULT 'deep_reference',
|
||||||
|
query TEXT,
|
||||||
|
query_hash TEXT,
|
||||||
|
confidence REAL,
|
||||||
|
status TEXT,
|
||||||
|
output_preview TEXT,
|
||||||
|
metadata TEXT NOT NULL DEFAULT '{}'
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_composition_events_created_at ON composition_events(created_at);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_composition_events_tool ON composition_events(tool);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_composition_events_mode ON composition_events(mode);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_composition_events_query_hash ON composition_events(query_hash);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS composition_members (
|
||||||
|
event_id TEXT NOT NULL,
|
||||||
|
memory_id TEXT NOT NULL,
|
||||||
|
role TEXT NOT NULL, -- primary | supporting | contradicting | superseded | related
|
||||||
|
rank INTEGER NOT NULL DEFAULT 0,
|
||||||
|
trust REAL,
|
||||||
|
score REAL,
|
||||||
|
preview TEXT,
|
||||||
|
metadata TEXT NOT NULL DEFAULT '{}',
|
||||||
|
PRIMARY KEY (event_id, memory_id, role),
|
||||||
|
FOREIGN KEY (event_id) REFERENCES composition_events(id) ON DELETE CASCADE
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_composition_members_memory ON composition_members(memory_id);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_composition_members_role ON composition_members(role);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS composition_outcomes (
|
||||||
|
id TEXT PRIMARY KEY,
|
||||||
|
event_id TEXT NOT NULL,
|
||||||
|
outcome_type TEXT NOT NULL,
|
||||||
|
labeled_at TEXT NOT NULL,
|
||||||
|
label_source TEXT NOT NULL DEFAULT 'tool',
|
||||||
|
confidence_delta REAL,
|
||||||
|
notes TEXT,
|
||||||
|
metadata TEXT NOT NULL DEFAULT '{}',
|
||||||
|
FOREIGN KEY (event_id) REFERENCES composition_events(id) ON DELETE CASCADE
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_composition_outcomes_event ON composition_outcomes(event_id);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_composition_outcomes_type ON composition_outcomes(outcome_type);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_composition_outcomes_labeled_at ON composition_outcomes(labeled_at);
|
||||||
|
|
||||||
|
UPDATE schema_version SET version = 15, applied_at = datetime('now');
|
||||||
|
"#;
|
||||||
|
|
||||||
/// Get current schema version from database
|
/// Get current schema version from database
|
||||||
pub fn get_current_version(conn: &rusqlite::Connection) -> rusqlite::Result<u32> {
|
pub fn get_current_version(conn: &rusqlite::Connection) -> rusqlite::Result<u32> {
|
||||||
conn.query_row(
|
conn.query_row(
|
||||||
|
|
@ -745,6 +899,136 @@ pub fn get_current_version(conn: &rusqlite::Connection) -> rusqlite::Result<u32>
|
||||||
.or(Ok(0))
|
.or(Ok(0))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Run an `ALTER TABLE ... ADD COLUMN` statement, treating a "duplicate column
|
||||||
|
/// name" failure as success so migration replay stays idempotent (SQLite has no
|
||||||
|
/// `ADD COLUMN IF NOT EXISTS`).
|
||||||
|
fn add_column_if_missing(conn: &rusqlite::Connection, sql: &str) -> rusqlite::Result<()> {
|
||||||
|
match conn.execute(sql, []) {
|
||||||
|
Ok(_) => Ok(()),
|
||||||
|
Err(rusqlite::Error::SqliteFailure(_, Some(msg)))
|
||||||
|
if msg.contains("duplicate column name") =>
|
||||||
|
{
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
Err(e) => Err(e),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// V16: ADR 0001 Phase 1 - embedding_model registry + domain columns.
|
||||||
|
///
|
||||||
|
/// The ALTER TABLE statements are split out into `MIGRATION_V16_ALTER_COLUMNS`
|
||||||
|
/// because SQLite has no `ALTER TABLE ... ADD COLUMN IF NOT EXISTS`. The
|
||||||
|
/// migration runner handles them individually so replaying V16 is idempotent.
|
||||||
|
const MIGRATION_V16_UP: &str = r#"
|
||||||
|
-- Migration V16: embedding model registry + per-memory domain columns.
|
||||||
|
|
||||||
|
-- 1. Embedding model registry. Single logical row; the (id = 1) constraint is
|
||||||
|
-- enforced in code via `register_model` (SQLite CHECK on a single-row
|
||||||
|
-- table is uglier than a constraint we already enforce in Rust).
|
||||||
|
CREATE TABLE IF NOT EXISTS embedding_model (
|
||||||
|
id INTEGER PRIMARY KEY CHECK (id = 1),
|
||||||
|
name TEXT NOT NULL,
|
||||||
|
dimension INTEGER NOT NULL,
|
||||||
|
hash TEXT NOT NULL,
|
||||||
|
created_at TEXT NOT NULL
|
||||||
|
);
|
||||||
|
|
||||||
|
-- 2. Per-memory domain columns are applied separately (see apply_migrations).
|
||||||
|
|
||||||
|
-- 3. Index on the domains JSON column to enable LIKE-style filter in Phase 4.
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_nodes_domains ON knowledge_nodes(domains);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_nodes_domain_scores ON knowledge_nodes(domain_scores);
|
||||||
|
|
||||||
|
-- 4. Domains catalogue (empty until Phase 4 populates).
|
||||||
|
CREATE TABLE IF NOT EXISTS domains (
|
||||||
|
id TEXT PRIMARY KEY,
|
||||||
|
label TEXT NOT NULL,
|
||||||
|
centroid BLOB,
|
||||||
|
top_terms TEXT NOT NULL DEFAULT '[]',
|
||||||
|
memory_count INTEGER NOT NULL DEFAULT 0,
|
||||||
|
created_at TEXT NOT NULL
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_domains_created_at ON domains(created_at);
|
||||||
|
|
||||||
|
UPDATE schema_version SET version = 16, applied_at = datetime('now');
|
||||||
|
"#;
|
||||||
|
|
||||||
|
/// The two ALTER TABLE statements for V16. Kept separate so the migration
|
||||||
|
/// runner can try each individually and ignore "duplicate column" errors,
|
||||||
|
/// making V16 idempotent on replay (SQLite has no ADD COLUMN IF NOT EXISTS).
|
||||||
|
pub const MIGRATION_V16_ALTER_COLUMNS: &[&str] = &[
|
||||||
|
"ALTER TABLE knowledge_nodes ADD COLUMN domains TEXT NOT NULL DEFAULT '[]'",
|
||||||
|
"ALTER TABLE knowledge_nodes ADD COLUMN domain_scores TEXT NOT NULL DEFAULT '{}'",
|
||||||
|
];
|
||||||
|
|
||||||
|
/// V17: #57 Source envelope — structured provenance for connector-ingested
|
||||||
|
/// records, plus a per-connector cursor checkpoint table.
|
||||||
|
///
|
||||||
|
/// The provenance columns live directly on `knowledge_nodes` (rather than a
|
||||||
|
/// side table) so search can filter and cite them with no join. They are all
|
||||||
|
/// nullable and default-NULL, so every existing memory is untouched and the
|
||||||
|
/// migration is purely additive — legacy rows simply have no envelope.
|
||||||
|
///
|
||||||
|
/// The `(source_system, source_id)` pair is the idempotency key for
|
||||||
|
/// `upsert_by_source`; the unique index enforces one memory per external
|
||||||
|
/// record. `content_hash` is the change detector. `connector_cursors` holds the
|
||||||
|
/// incremental-sync high-water mark and last full-reconcile time per
|
||||||
|
/// (source_system, scope).
|
||||||
|
///
|
||||||
|
/// The `ALTER TABLE ... ADD COLUMN` statements are split into
|
||||||
|
/// `MIGRATION_V17_ALTER_COLUMNS` and run individually by the migration runner,
|
||||||
|
/// because SQLite has no `ADD COLUMN IF NOT EXISTS`; duplicate-column errors are
|
||||||
|
/// swallowed so replay stays idempotent.
|
||||||
|
const MIGRATION_V17_UP: &str = r#"
|
||||||
|
-- Idempotency key: at most one memory per (source_system, source_id).
|
||||||
|
-- Partial unique index so the millions of envelope-less legacy rows (all NULL)
|
||||||
|
-- don't collide and don't pay index cost.
|
||||||
|
CREATE UNIQUE INDEX IF NOT EXISTS idx_nodes_source_key
|
||||||
|
ON knowledge_nodes(source_system, source_id)
|
||||||
|
WHERE source_system IS NOT NULL AND source_id IS NOT NULL;
|
||||||
|
|
||||||
|
-- Filter/scan support for source-aware search + reconciliation passes.
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_nodes_source_system
|
||||||
|
ON knowledge_nodes(source_system)
|
||||||
|
WHERE source_system IS NOT NULL;
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_nodes_source_project
|
||||||
|
ON knowledge_nodes(source_project)
|
||||||
|
WHERE source_project IS NOT NULL;
|
||||||
|
|
||||||
|
-- Per-connector incremental-sync checkpoint. One row per (source_system, scope)
|
||||||
|
-- e.g. ('github', 'samvallad33/vestige'). `cursor_updated_at` is the
|
||||||
|
-- high-water mark on the source's update timestamp; `last_full_reconcile_at`
|
||||||
|
-- gates the (expensive) deletion-reconcile pass.
|
||||||
|
CREATE TABLE IF NOT EXISTS connector_cursors (
|
||||||
|
source_system TEXT NOT NULL,
|
||||||
|
scope TEXT NOT NULL,
|
||||||
|
cursor_updated_at TEXT,
|
||||||
|
last_synced_at TEXT,
|
||||||
|
last_full_reconcile_at TEXT,
|
||||||
|
records_seen INTEGER NOT NULL DEFAULT 0,
|
||||||
|
config TEXT NOT NULL DEFAULT '{}',
|
||||||
|
PRIMARY KEY (source_system, scope)
|
||||||
|
);
|
||||||
|
|
||||||
|
UPDATE schema_version SET version = 17, applied_at = datetime('now');
|
||||||
|
"#;
|
||||||
|
|
||||||
|
/// The `ALTER TABLE` statements for V17. Run individually + idempotently by the
|
||||||
|
/// migration runner (SQLite has no `ADD COLUMN IF NOT EXISTS`).
|
||||||
|
pub const MIGRATION_V17_ALTER_COLUMNS: &[&str] = &[
|
||||||
|
"ALTER TABLE knowledge_nodes ADD COLUMN source_system TEXT",
|
||||||
|
"ALTER TABLE knowledge_nodes ADD COLUMN source_id TEXT",
|
||||||
|
"ALTER TABLE knowledge_nodes ADD COLUMN source_url TEXT",
|
||||||
|
"ALTER TABLE knowledge_nodes ADD COLUMN source_updated_at TEXT",
|
||||||
|
"ALTER TABLE knowledge_nodes ADD COLUMN content_hash TEXT",
|
||||||
|
"ALTER TABLE knowledge_nodes ADD COLUMN synced_at TEXT",
|
||||||
|
"ALTER TABLE knowledge_nodes ADD COLUMN source_project TEXT",
|
||||||
|
"ALTER TABLE knowledge_nodes ADD COLUMN source_type TEXT",
|
||||||
|
"ALTER TABLE knowledge_nodes ADD COLUMN source_author TEXT",
|
||||||
|
];
|
||||||
|
|
||||||
/// Apply pending migrations
|
/// Apply pending migrations
|
||||||
pub fn apply_migrations(conn: &rusqlite::Connection) -> rusqlite::Result<u32> {
|
pub fn apply_migrations(conn: &rusqlite::Connection) -> rusqlite::Result<u32> {
|
||||||
let current_version = get_current_version(conn)?;
|
let current_version = get_current_version(conn)?;
|
||||||
|
|
@ -758,6 +1042,39 @@ pub fn apply_migrations(conn: &rusqlite::Connection) -> rusqlite::Result<u32> {
|
||||||
migration.description
|
migration.description
|
||||||
);
|
);
|
||||||
|
|
||||||
|
// V14: add the two bitemporal/protect columns BEFORE the batch (the
|
||||||
|
// batch's indexes reference them). SQLite lacks
|
||||||
|
// `ADD COLUMN IF NOT EXISTS`, so swallow the "duplicate column"
|
||||||
|
// error to stay idempotent on replay.
|
||||||
|
if migration.version == 14 {
|
||||||
|
add_column_if_missing(
|
||||||
|
conn,
|
||||||
|
"ALTER TABLE knowledge_nodes ADD COLUMN protected INTEGER NOT NULL DEFAULT 0",
|
||||||
|
)?;
|
||||||
|
add_column_if_missing(
|
||||||
|
conn,
|
||||||
|
"ALTER TABLE knowledge_nodes ADD COLUMN superseded_by TEXT",
|
||||||
|
)?;
|
||||||
|
}
|
||||||
|
|
||||||
|
// V16 adds columns via ALTER TABLE, which SQLite does not support
|
||||||
|
// with IF NOT EXISTS. Run them individually and ignore duplicate
|
||||||
|
// column errors so replay stays idempotent.
|
||||||
|
if migration.version == 16 {
|
||||||
|
for stmt in MIGRATION_V16_ALTER_COLUMNS {
|
||||||
|
add_column_if_missing(conn, stmt)?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// V17 (#57) adds the source-envelope columns. Same idempotent
|
||||||
|
// ALTER handling as V16 — the unique index in the V17 batch
|
||||||
|
// references these columns, so they must exist before the batch.
|
||||||
|
if migration.version == 17 {
|
||||||
|
for stmt in MIGRATION_V17_ALTER_COLUMNS {
|
||||||
|
add_column_if_missing(conn, stmt)?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Use execute_batch to handle multi-statement SQL including triggers
|
// Use execute_batch to handle multi-statement SQL including triggers
|
||||||
conn.execute_batch(migration.up)?;
|
conn.execute_batch(migration.up)?;
|
||||||
|
|
||||||
|
|
@ -784,17 +1101,17 @@ mod tests {
|
||||||
/// version after `apply_migrations` runs all migrations end-to-end, and
|
/// version after `apply_migrations` runs all migrations end-to-end, and
|
||||||
/// neither of the dead tables V11 drops must exist afterwards.
|
/// neither of the dead tables V11 drops must exist afterwards.
|
||||||
#[test]
|
#[test]
|
||||||
fn test_apply_migrations_advances_to_v13_and_drops_dead_tables() {
|
fn test_apply_migrations_advances_to_v16_and_drops_dead_tables() {
|
||||||
let conn = rusqlite::Connection::open_in_memory().expect("open in-memory");
|
let conn = rusqlite::Connection::open_in_memory().expect("open in-memory");
|
||||||
|
|
||||||
// Pre-requisite: schema_version must be bootstrapped by V1.
|
// Pre-requisite: schema_version must be bootstrapped by V1.
|
||||||
apply_migrations(&conn).expect("apply_migrations succeeds");
|
apply_migrations(&conn).expect("apply_migrations succeeds");
|
||||||
|
|
||||||
// 1. schema_version advanced to V13
|
// 1. schema_version advanced to the latest migration
|
||||||
let version = get_current_version(&conn).expect("read schema_version");
|
let version = get_current_version(&conn).expect("read schema_version");
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
version, 13,
|
version, 17,
|
||||||
"schema_version must be 13 after all migrations"
|
"schema_version must be 17 after all migrations"
|
||||||
);
|
);
|
||||||
|
|
||||||
// 2. knowledge_edges is gone (V11 drops it)
|
// 2. knowledge_edges is gone (V11 drops it)
|
||||||
|
|
@ -848,6 +1165,53 @@ mod tests {
|
||||||
deletion_tombstone_rows, 1,
|
deletion_tombstone_rows, 1,
|
||||||
"deletion_tombstones table must be created by V13"
|
"deletion_tombstones table must be created by V13"
|
||||||
);
|
);
|
||||||
|
|
||||||
|
// 6. merge_plans + merge_operations exist (V14 creates them)
|
||||||
|
for table in ["merge_plans", "merge_operations"] {
|
||||||
|
let rows: i64 = conn
|
||||||
|
.query_row(
|
||||||
|
"SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name=?1",
|
||||||
|
[table],
|
||||||
|
|row| row.get(0),
|
||||||
|
)
|
||||||
|
.expect("query sqlite_master");
|
||||||
|
assert_eq!(rows, 1, "{table} table must be created by V14");
|
||||||
|
}
|
||||||
|
|
||||||
|
// 7. ComposedGraph tables exist (V15)
|
||||||
|
for table in [
|
||||||
|
"composition_events",
|
||||||
|
"composition_members",
|
||||||
|
"composition_outcomes",
|
||||||
|
] {
|
||||||
|
let rows: i64 = conn
|
||||||
|
.query_row(
|
||||||
|
"SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name=?1",
|
||||||
|
[table],
|
||||||
|
|row| row.get(0),
|
||||||
|
)
|
||||||
|
.expect("query sqlite_master");
|
||||||
|
assert_eq!(rows, 1, "{table} table must be created by V15");
|
||||||
|
}
|
||||||
|
|
||||||
|
// 8. knowledge_nodes gains `protected` + `superseded_by` (V14)
|
||||||
|
let node_cols: Vec<String> = {
|
||||||
|
let mut stmt = conn
|
||||||
|
.prepare("PRAGMA table_info(knowledge_nodes)")
|
||||||
|
.expect("prepare table_info");
|
||||||
|
stmt.query_map([], |row| row.get::<_, String>(1))
|
||||||
|
.expect("query table_info")
|
||||||
|
.filter_map(|r| r.ok())
|
||||||
|
.collect()
|
||||||
|
};
|
||||||
|
assert!(
|
||||||
|
node_cols.iter().any(|c| c == "protected"),
|
||||||
|
"knowledge_nodes must have `protected` column after V14"
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
node_cols.iter().any(|c| c == "superseded_by"),
|
||||||
|
"knowledge_nodes must have `superseded_by` column after V14"
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// V11 must be idempotent on replay — if the tables were already dropped
|
/// V11 must be idempotent on replay — if the tables were already dropped
|
||||||
|
|
@ -865,10 +1229,222 @@ mod tests {
|
||||||
conn.execute("UPDATE schema_version SET version = 10", [])
|
conn.execute("UPDATE schema_version SET version = 10", [])
|
||||||
.expect("rewind schema_version");
|
.expect("rewind schema_version");
|
||||||
|
|
||||||
// Replay must not error.
|
// Replay V11 onward. V11 uses DROP TABLE IF EXISTS so it is idempotent.
|
||||||
apply_migrations(&conn).expect("V11 replay must be idempotent");
|
// V12/V13 tombstone tables use CREATE TABLE IF NOT EXISTS. V14/V16 ALTER
|
||||||
|
// TABLE idempotency is handled by the migration runner.
|
||||||
|
apply_migrations(&conn).expect("V11..V17 replay must be idempotent");
|
||||||
|
|
||||||
|
// After replaying from V10, the schema advances to the latest version.
|
||||||
let version = get_current_version(&conn).expect("read schema_version");
|
let version = get_current_version(&conn).expect("read schema_version");
|
||||||
assert_eq!(version, 13, "schema_version back at 13 after replay");
|
assert_eq!(version, 17, "schema_version back at latest after replay");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn v16_adds_embedding_model_table() {
|
||||||
|
let conn = rusqlite::Connection::open_in_memory().expect("open in-memory");
|
||||||
|
apply_migrations(&conn).expect("apply_migrations");
|
||||||
|
let count: i64 = conn
|
||||||
|
.query_row(
|
||||||
|
"SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name='embedding_model'",
|
||||||
|
[],
|
||||||
|
|row| row.get(0),
|
||||||
|
)
|
||||||
|
.expect("query sqlite_master");
|
||||||
|
assert_eq!(count, 1, "embedding_model table must exist after V16");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn v16_adds_domains_columns() {
|
||||||
|
let conn = rusqlite::Connection::open_in_memory().expect("open in-memory");
|
||||||
|
apply_migrations(&conn).expect("apply_migrations");
|
||||||
|
let info: Vec<String> = {
|
||||||
|
let mut stmt = conn
|
||||||
|
.prepare("PRAGMA table_info(knowledge_nodes)")
|
||||||
|
.expect("prepare");
|
||||||
|
stmt.query_map([], |row| row.get::<_, String>(1))
|
||||||
|
.expect("query_map")
|
||||||
|
.map(|r| r.expect("row"))
|
||||||
|
.collect()
|
||||||
|
};
|
||||||
|
assert!(
|
||||||
|
info.contains(&"domains".to_string()),
|
||||||
|
"domains column missing"
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
info.contains(&"domain_scores".to_string()),
|
||||||
|
"domain_scores column missing"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn v16_default_values_empty_json() {
|
||||||
|
let conn = rusqlite::Connection::open_in_memory().expect("open in-memory");
|
||||||
|
apply_migrations(&conn).expect("apply_migrations");
|
||||||
|
// Insert a minimal row to test defaults
|
||||||
|
conn.execute(
|
||||||
|
"INSERT INTO knowledge_nodes (id, content, node_type, created_at, updated_at, last_accessed, \
|
||||||
|
stability, difficulty, reps, lapses, learning_state, storage_strength, retrieval_strength, \
|
||||||
|
retention_strength, next_review, scheduled_days, has_embedding) \
|
||||||
|
VALUES ('test-id','content','fact',datetime('now'),datetime('now'),datetime('now'),\
|
||||||
|
1.0,0.3,0,0,'new',1.0,1.0,1.0,datetime('now'),1,0)",
|
||||||
|
[],
|
||||||
|
).expect("insert row");
|
||||||
|
let (domains, domain_scores): (String, String) = conn
|
||||||
|
.query_row(
|
||||||
|
"SELECT domains, domain_scores FROM knowledge_nodes WHERE id='test-id'",
|
||||||
|
[],
|
||||||
|
|row| Ok((row.get(0)?, row.get(1)?)),
|
||||||
|
)
|
||||||
|
.expect("query row");
|
||||||
|
assert_eq!(domains, "[]");
|
||||||
|
assert_eq!(domain_scores, "{}");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn v16_is_replayable() {
|
||||||
|
let conn = rusqlite::Connection::open_in_memory().expect("open in-memory");
|
||||||
|
apply_migrations(&conn).expect("first apply");
|
||||||
|
// Rewind to V15 so V16 runs again.
|
||||||
|
conn.execute("UPDATE schema_version SET version = 15", [])
|
||||||
|
.expect("rewind");
|
||||||
|
// V16 uses CREATE TABLE IF NOT EXISTS and idempotent ALTER handling.
|
||||||
|
apply_migrations(&conn).expect("V16 replay must be idempotent");
|
||||||
|
let version = get_current_version(&conn).expect("read version");
|
||||||
|
assert_eq!(version, 17, "schema_version must be latest after replay");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn v17_adds_source_envelope_columns_and_cursor_table() {
|
||||||
|
let conn = rusqlite::Connection::open_in_memory().expect("open in-memory");
|
||||||
|
apply_migrations(&conn).expect("apply_migrations");
|
||||||
|
|
||||||
|
// All nine envelope columns must exist on knowledge_nodes.
|
||||||
|
let cols: Vec<String> = {
|
||||||
|
let mut stmt = conn
|
||||||
|
.prepare("PRAGMA table_info(knowledge_nodes)")
|
||||||
|
.expect("prepare");
|
||||||
|
stmt.query_map([], |row| row.get::<_, String>(1))
|
||||||
|
.expect("query_map")
|
||||||
|
.filter_map(|r| r.ok())
|
||||||
|
.collect()
|
||||||
|
};
|
||||||
|
for c in [
|
||||||
|
"source_system",
|
||||||
|
"source_id",
|
||||||
|
"source_url",
|
||||||
|
"source_updated_at",
|
||||||
|
"content_hash",
|
||||||
|
"synced_at",
|
||||||
|
"source_project",
|
||||||
|
"source_type",
|
||||||
|
"source_author",
|
||||||
|
] {
|
||||||
|
assert!(
|
||||||
|
cols.iter().any(|x| x == c),
|
||||||
|
"knowledge_nodes must have `{c}` column after V17"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// connector_cursors table must exist.
|
||||||
|
let cursor_rows: i64 = conn
|
||||||
|
.query_row(
|
||||||
|
"SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name='connector_cursors'",
|
||||||
|
[],
|
||||||
|
|row| row.get(0),
|
||||||
|
)
|
||||||
|
.expect("query sqlite_master");
|
||||||
|
assert_eq!(cursor_rows, 1, "connector_cursors must be created by V17");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn v17_unique_source_key_index_allows_many_null_legacy_rows() {
|
||||||
|
let conn = rusqlite::Connection::open_in_memory().expect("open in-memory");
|
||||||
|
apply_migrations(&conn).expect("apply_migrations");
|
||||||
|
|
||||||
|
// Two legacy rows with NULL source key must NOT collide on the partial
|
||||||
|
// unique index (the index only covers non-NULL keys).
|
||||||
|
for id in ["a", "b"] {
|
||||||
|
conn.execute(
|
||||||
|
"INSERT INTO knowledge_nodes (id, content, node_type, created_at, updated_at, last_accessed, \
|
||||||
|
stability, difficulty, reps, lapses, learning_state, storage_strength, retrieval_strength, \
|
||||||
|
retention_strength, next_review, scheduled_days, has_embedding) \
|
||||||
|
VALUES (?1,'c','fact',datetime('now'),datetime('now'),datetime('now'),\
|
||||||
|
1.0,0.3,0,0,'new',1.0,1.0,1.0,datetime('now'),1,0)",
|
||||||
|
[id],
|
||||||
|
)
|
||||||
|
.expect("insert legacy row");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Two real connector rows that share (source_system, source_id) MUST
|
||||||
|
// collide — the unique index is the idempotency guarantee.
|
||||||
|
conn.execute(
|
||||||
|
"UPDATE knowledge_nodes SET source_system='github', source_id='1' WHERE id='a'",
|
||||||
|
[],
|
||||||
|
)
|
||||||
|
.expect("set source key on a");
|
||||||
|
let dup = conn.execute(
|
||||||
|
"UPDATE knowledge_nodes SET source_system='github', source_id='1' WHERE id='b'",
|
||||||
|
[],
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
dup.is_err(),
|
||||||
|
"duplicate (source_system, source_id) must violate the unique index"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn v17_is_replayable() {
|
||||||
|
let conn = rusqlite::Connection::open_in_memory().expect("open in-memory");
|
||||||
|
apply_migrations(&conn).expect("first apply");
|
||||||
|
conn.execute("UPDATE schema_version SET version = 16", [])
|
||||||
|
.expect("rewind to 16");
|
||||||
|
apply_migrations(&conn).expect("V17 replay must be idempotent");
|
||||||
|
let version = get_current_version(&conn).expect("read version");
|
||||||
|
assert_eq!(version, 17, "schema_version must be 17 after replay");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn v16_preserves_existing_rows_from_v15() {
|
||||||
|
let conn = rusqlite::Connection::open_in_memory().expect("open in-memory");
|
||||||
|
// Apply up to V15 only, including the V14 ALTER TABLE columns that
|
||||||
|
// `apply_migrations` normally runs before the V14 SQL batch.
|
||||||
|
for migration in MIGRATIONS {
|
||||||
|
if migration.version <= 15 {
|
||||||
|
if migration.version == 14 {
|
||||||
|
add_column_if_missing(
|
||||||
|
&conn,
|
||||||
|
"ALTER TABLE knowledge_nodes ADD COLUMN protected INTEGER NOT NULL DEFAULT 0",
|
||||||
|
)
|
||||||
|
.expect("apply V14 protected column");
|
||||||
|
add_column_if_missing(
|
||||||
|
&conn,
|
||||||
|
"ALTER TABLE knowledge_nodes ADD COLUMN superseded_by TEXT",
|
||||||
|
)
|
||||||
|
.expect("apply V14 superseded_by column");
|
||||||
|
}
|
||||||
|
conn.execute_batch(migration.up).expect("apply migration");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Insert a row under the V15 schema, before PR #61's V16 columns exist.
|
||||||
|
conn.execute(
|
||||||
|
"INSERT INTO knowledge_nodes (id, content, node_type, created_at, updated_at, last_accessed, \
|
||||||
|
stability, difficulty, reps, lapses, learning_state, storage_strength, retrieval_strength, \
|
||||||
|
retention_strength, next_review, scheduled_days, has_embedding) \
|
||||||
|
VALUES ('existing-id','old content','fact',datetime('now'),datetime('now'),datetime('now'),\
|
||||||
|
1.0,0.3,0,0,'new',1.0,1.0,1.0,datetime('now'),1,0)",
|
||||||
|
[],
|
||||||
|
).expect("insert pre-v16 row");
|
||||||
|
apply_migrations(&conn).expect("apply V16 migration");
|
||||||
|
|
||||||
|
// Check the old row has defaults
|
||||||
|
let (domains, domain_scores): (String, String) = conn
|
||||||
|
.query_row(
|
||||||
|
"SELECT domains, domain_scores FROM knowledge_nodes WHERE id='existing-id'",
|
||||||
|
[],
|
||||||
|
|row| Ok((row.get(0)?, row.get(1)?)),
|
||||||
|
)
|
||||||
|
.expect("query pre-v16 row");
|
||||||
|
assert_eq!(domains, "[]");
|
||||||
|
assert_eq!(domain_scores, "{}");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,22 +1,32 @@
|
||||||
//! Storage Module
|
//! Storage Module
|
||||||
//!
|
//!
|
||||||
//! SQLite-based storage layer with:
|
//! Backend-agnostic memory store abstraction plus SQLite reference impl.
|
||||||
//! - FTS5 full-text search with query sanitization
|
|
||||||
//! - Embedded vector storage
|
|
||||||
//! - FSRS-6 state management
|
|
||||||
//! - Temporal memory support
|
|
||||||
|
|
||||||
|
mod memory_store;
|
||||||
mod migrations;
|
mod migrations;
|
||||||
mod portable;
|
mod portable;
|
||||||
mod sqlite;
|
mod sqlite;
|
||||||
|
|
||||||
|
pub use memory_store::{
|
||||||
|
ClassificationResult, Domain, HealthStatus, LocalMemoryStore, MemoryEdge, MemoryRecord,
|
||||||
|
MemoryStore, MemoryStoreError, MemoryStoreResult, MemoryStoreSend, ModelSignature,
|
||||||
|
SchedulingState, SearchQuery, SearchResult, StoreStats,
|
||||||
|
};
|
||||||
pub use migrations::MIGRATIONS;
|
pub use migrations::MIGRATIONS;
|
||||||
pub use portable::{
|
pub use portable::{
|
||||||
PORTABLE_ARCHIVE_FORMAT, PortableArchive, PortableImportMode, PortableImportReport,
|
PORTABLE_ARCHIVE_FORMAT, PortableArchive, PortableImportMode, PortableImportReport,
|
||||||
PortableTable, PortableValue,
|
PortableTable, PortableValue,
|
||||||
};
|
};
|
||||||
pub use sqlite::{
|
pub use sqlite::{
|
||||||
ConnectionRecord, ConsolidationHistoryRecord, DreamHistoryRecord, FilePortableSyncBackend,
|
CompositionEventRecord, CompositionMemberRecord, CompositionNeighborRecord,
|
||||||
InsightRecord, IntentionRecord, PortableSyncBackend, PortableSyncReport, Result,
|
CompositionOutcomeRecord, ConnectionRecord, ConnectorCursor, ConsolidationHistoryRecord,
|
||||||
SmartIngestResult, StateTransitionRecord, Storage, StorageError,
|
DreamHistoryRecord, FilePortableSyncBackend, InsightRecord, IntentionRecord,
|
||||||
|
NeverComposedCandidate, PortableSyncBackend, PortableSyncReport, ReconcileReport, Result,
|
||||||
|
SmartIngestResult, SourceUpsertOutcome, SourceUpsertResult, SqliteMemoryStore,
|
||||||
|
StateTransitionRecord, StorageError,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/// Backwards-compatibility alias. Retained until Phase 4 completes so every
|
||||||
|
/// existing `Arc<Storage>` call site keeps compiling. Scheduled for removal
|
||||||
|
/// once no downstream source file references it.
|
||||||
|
pub type Storage = SqliteMemoryStore;
|
||||||
|
|
|
||||||
File diff suppressed because it is too large
Load diff
|
|
@ -1,6 +1,6 @@
|
||||||
[package]
|
[package]
|
||||||
name = "vestige-mcp"
|
name = "vestige-mcp"
|
||||||
version = "2.1.23"
|
version = "2.1.27"
|
||||||
edition = "2024"
|
edition = "2024"
|
||||||
description = "Cognitive memory MCP server for AI agents - FSRS-6, spreading activation, synaptic tagging, 3D dashboard, and 130 years of memory research"
|
description = "Cognitive memory MCP server for AI agents - FSRS-6, spreading activation, synaptic tagging, 3D dashboard, and 130 years of memory research"
|
||||||
authors = ["samvallad33"]
|
authors = ["samvallad33"]
|
||||||
|
|
@ -10,9 +10,13 @@ categories = ["command-line-utilities", "database"]
|
||||||
repository = "https://github.com/samvallad33/vestige"
|
repository = "https://github.com/samvallad33/vestige"
|
||||||
|
|
||||||
[features]
|
[features]
|
||||||
default = ["embeddings", "ort-download", "vector-search"]
|
default = ["embeddings", "ort-download", "vector-search", "connectors"]
|
||||||
embeddings = ["vestige-core/embeddings"]
|
embeddings = ["vestige-core/embeddings"]
|
||||||
vector-search = ["vestige-core/vector-search"]
|
vector-search = ["vestige-core/vector-search"]
|
||||||
|
# External-source connectors (#57): GitHub Issues / Redmine indexing via the
|
||||||
|
# `source_sync` MCP tool. On by default so the tool works out of the box; turn
|
||||||
|
# off for a build with no HTTP client.
|
||||||
|
connectors = ["vestige-core/connectors"]
|
||||||
# Default ort backend: downloads prebuilt ONNX Runtime at build time.
|
# Default ort backend: downloads prebuilt ONNX Runtime at build time.
|
||||||
# Fails on targets without prebuilts (notably x86_64-apple-darwin).
|
# Fails on targets without prebuilts (notably x86_64-apple-darwin).
|
||||||
ort-download = ["embeddings", "vestige-core/ort-download"]
|
ort-download = ["embeddings", "vestige-core/ort-download"]
|
||||||
|
|
@ -51,7 +55,7 @@ path = "src/bin/cli.rs"
|
||||||
# Only `bundled-sqlite` is always on. `embeddings` and `vector-search` are
|
# Only `bundled-sqlite` is always on. `embeddings` and `vector-search` are
|
||||||
# toggled via vestige-mcp's own feature flags below so `--no-default-features`
|
# toggled via vestige-mcp's own feature flags below so `--no-default-features`
|
||||||
# actually works (previously hardcoded here, which silently defeated the flag).
|
# actually works (previously hardcoded here, which silently defeated the flag).
|
||||||
vestige-core = { version = "2.1.23", path = "../vestige-core", default-features = false, features = ["bundled-sqlite"] }
|
vestige-core = { version = "2.1.27", path = "../vestige-core", default-features = false, features = ["bundled-sqlite"] }
|
||||||
|
|
||||||
# ============================================================================
|
# ============================================================================
|
||||||
# MCP Server Dependencies
|
# MCP Server Dependencies
|
||||||
|
|
|
||||||
|
|
@ -61,7 +61,7 @@ The server exposes the current unified MCP tools from
|
||||||
- `search`, `smart_ingest`, `memory`, `codebase`, `intention`
|
- `search`, `smart_ingest`, `memory`, `codebase`, `intention`
|
||||||
- `deep_reference`, `cross_reference`, `contradictions`
|
- `deep_reference`, `cross_reference`, `contradictions`
|
||||||
- `dream`, `explore_connections`, `predict`
|
- `dream`, `explore_connections`, `predict`
|
||||||
- `memory_health`, `memory_graph`, `system_status`
|
- `memory_health`, `memory_graph`, `composed_graph`, `system_status`
|
||||||
- `importance_score`, `find_duplicates`
|
- `importance_score`, `find_duplicates`
|
||||||
- `consolidate`, `memory_timeline`, `memory_changelog`
|
- `consolidate`, `memory_timeline`, `memory_changelog`
|
||||||
- `backup`, `export`, `restore`, `gc`, `suppress`
|
- `backup`, `export`, `restore`, `gc`, `suppress`
|
||||||
|
|
|
||||||
|
|
@ -1817,6 +1817,7 @@ fn run_restore(backup_path: PathBuf) -> anyhow::Result<()> {
|
||||||
tags: memory.tags.unwrap_or_default(),
|
tags: memory.tags.unwrap_or_default(),
|
||||||
valid_from: None,
|
valid_from: None,
|
||||||
valid_until: None,
|
valid_until: None,
|
||||||
|
source_envelope: None,
|
||||||
};
|
};
|
||||||
|
|
||||||
match storage.ingest(input) {
|
match storage.ingest(input) {
|
||||||
|
|
@ -2415,6 +2416,7 @@ fn run_ingest(
|
||||||
tags: tag_list,
|
tags: tag_list,
|
||||||
valid_from: None,
|
valid_from: None,
|
||||||
valid_until: None,
|
valid_until: None,
|
||||||
|
source_envelope: None,
|
||||||
};
|
};
|
||||||
|
|
||||||
let storage = open_storage()?;
|
let storage = open_storage()?;
|
||||||
|
|
|
||||||
|
|
@ -73,6 +73,7 @@ fn main() -> anyhow::Result<()> {
|
||||||
tags: memory.tags.unwrap_or_default(),
|
tags: memory.tags.unwrap_or_default(),
|
||||||
valid_from: None,
|
valid_from: None,
|
||||||
valid_until: None,
|
valid_until: None,
|
||||||
|
source_envelope: None,
|
||||||
};
|
};
|
||||||
|
|
||||||
match storage.ingest(input) {
|
match storage.ingest(input) {
|
||||||
|
|
|
||||||
|
|
@ -195,6 +195,7 @@ mod tests {
|
||||||
tags: vec!["test".to_string()],
|
tags: vec!["test".to_string()],
|
||||||
valid_from: None,
|
valid_from: None,
|
||||||
valid_until: None,
|
valid_until: None,
|
||||||
|
source_envelope: None,
|
||||||
})
|
})
|
||||||
.unwrap();
|
.unwrap();
|
||||||
result.id
|
result.id
|
||||||
|
|
|
||||||
|
|
@ -256,12 +256,13 @@ fn prepare_storage_path(data_dir: Option<PathBuf>) -> io::Result<Option<PathBuf>
|
||||||
}
|
}
|
||||||
|
|
||||||
// Only create if it doesn't exist (avoids "File exists" error on existing directories)
|
// Only create if it doesn't exist (avoids "File exists" error on existing directories)
|
||||||
if !data_dir.exists() {
|
let created = !data_dir.exists();
|
||||||
|
if created {
|
||||||
fs::create_dir_all(&data_dir)?;
|
fs::create_dir_all(&data_dir)?;
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(unix)]
|
#[cfg(unix)]
|
||||||
{
|
if created {
|
||||||
use std::os::unix::fs::PermissionsExt;
|
use std::os::unix::fs::PermissionsExt;
|
||||||
let _ = fs::set_permissions(&data_dir, fs::Permissions::from_mode(0o700));
|
let _ = fs::set_permissions(&data_dir, fs::Permissions::from_mode(0o700));
|
||||||
}
|
}
|
||||||
|
|
@ -300,21 +301,6 @@ async fn main() {
|
||||||
let storage = match Storage::new(storage_path) {
|
let storage = match Storage::new(storage_path) {
|
||||||
Ok(s) => {
|
Ok(s) => {
|
||||||
info!("Storage initialized successfully");
|
info!("Storage initialized successfully");
|
||||||
|
|
||||||
// Try to initialize embeddings early and log any issues
|
|
||||||
#[cfg(feature = "embeddings")]
|
|
||||||
{
|
|
||||||
if let Err(e) = s.init_embeddings() {
|
|
||||||
error!("Failed to initialize embedding service: {}", e);
|
|
||||||
error!("Smart ingest will fall back to regular ingest without deduplication");
|
|
||||||
error!(
|
|
||||||
"Hint: Check FASTEMBED_CACHE_PATH or ensure ~/.cache/vestige/fastembed is writable"
|
|
||||||
);
|
|
||||||
} else {
|
|
||||||
info!("Embedding service initialized successfully");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Arc::new(s)
|
Arc::new(s)
|
||||||
}
|
}
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
|
|
@ -323,6 +309,40 @@ async fn main() {
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// Initialize embeddings in the background so MCP clients can complete the
|
||||||
|
// stdio handshake quickly. First-run model downloads can otherwise exceed
|
||||||
|
// short client startup timeouts.
|
||||||
|
#[cfg(feature = "embeddings")]
|
||||||
|
{
|
||||||
|
let storage_clone = Arc::clone(&storage);
|
||||||
|
tokio::task::spawn_blocking(move || {
|
||||||
|
if let Err(e) = storage_clone.init_embeddings() {
|
||||||
|
error!("Failed to initialize embedding service: {}", e);
|
||||||
|
error!("Smart ingest will fall back to regular ingest without deduplication");
|
||||||
|
error!(
|
||||||
|
"Hint: Check FASTEMBED_CACHE_PATH or ensure ~/.cache/vestige/fastembed is writable"
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
info!("Embedding service initialized successfully");
|
||||||
|
|
||||||
|
#[cfg(feature = "vector-search")]
|
||||||
|
match storage_clone.generate_embeddings(None, false) {
|
||||||
|
Ok(result) => {
|
||||||
|
if result.successful > 0 || result.failed > 0 {
|
||||||
|
info!(
|
||||||
|
embeddings_generated = result.successful,
|
||||||
|
embeddings_failed = result.failed,
|
||||||
|
embeddings_skipped = result.skipped,
|
||||||
|
"Background embedding backfill complete"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(e) => warn!("Background embedding backfill failed: {}", e),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
// Spawn periodic auto-consolidation so FSRS-6 decay scores stay fresh.
|
// Spawn periodic auto-consolidation so FSRS-6 decay scores stay fresh.
|
||||||
// Runs on startup (if needed) and then every N hours (default: 6).
|
// Runs on startup (if needed) and then every N hours (default: 6).
|
||||||
// Configurable via VESTIGE_CONSOLIDATION_INTERVAL_HOURS env var.
|
// Configurable via VESTIGE_CONSOLIDATION_INTERVAL_HOURS env var.
|
||||||
|
|
@ -505,7 +525,7 @@ async fn main() {
|
||||||
}
|
}
|
||||||
|
|
||||||
// Load cross-encoder reranker in the background (downloads ~150MB on first run)
|
// Load cross-encoder reranker in the background (downloads ~150MB on first run)
|
||||||
#[cfg(feature = "vector-search")]
|
#[cfg(all(feature = "vector-search", feature = "embeddings"))]
|
||||||
{
|
{
|
||||||
let cog_clone = Arc::clone(&cognitive);
|
let cog_clone = Arc::clone(&cognitive);
|
||||||
tokio::spawn(async move {
|
tokio::spawn(async move {
|
||||||
|
|
@ -594,6 +614,23 @@ mod tests {
|
||||||
assert_eq!(db_path, Some(data_dir.join(DATABASE_FILE)));
|
assert_eq!(db_path, Some(data_dir.join(DATABASE_FILE)));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(unix)]
|
||||||
|
#[test]
|
||||||
|
fn prepare_storage_path_preserves_existing_data_dir_permissions() {
|
||||||
|
use std::os::unix::fs::PermissionsExt;
|
||||||
|
|
||||||
|
let temp = tempfile::tempdir().unwrap();
|
||||||
|
let data_dir = temp.path().join("shared");
|
||||||
|
fs::create_dir_all(&data_dir).unwrap();
|
||||||
|
fs::set_permissions(&data_dir, fs::Permissions::from_mode(0o755)).unwrap();
|
||||||
|
|
||||||
|
let db_path = prepare_storage_path(Some(data_dir.clone())).unwrap();
|
||||||
|
let mode = fs::metadata(&data_dir).unwrap().permissions().mode() & 0o777;
|
||||||
|
|
||||||
|
assert_eq!(db_path, Some(data_dir.join(DATABASE_FILE)));
|
||||||
|
assert_eq!(mode, 0o755);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn expand_tilde_expands_current_users_home_only() {
|
fn expand_tilde_expands_current_users_home_only() {
|
||||||
let home = BaseDirs::new().unwrap().home_dir().to_path_buf();
|
let home = BaseDirs::new().unwrap().home_dir().to_path_buf();
|
||||||
|
|
|
||||||
|
|
@ -20,7 +20,7 @@ use crate::protocol::messages::{
|
||||||
use crate::protocol::types::{JsonRpcError, JsonRpcRequest, JsonRpcResponse, MCP_VERSION};
|
use crate::protocol::types::{JsonRpcError, JsonRpcRequest, JsonRpcResponse, MCP_VERSION};
|
||||||
use crate::resources;
|
use crate::resources;
|
||||||
use crate::tools;
|
use crate::tools;
|
||||||
use vestige_core::Storage;
|
use vestige_core::{OutputConfig, Storage, VestigeConfig};
|
||||||
|
|
||||||
/// Build the MCP `instructions` string injected into every connecting client's
|
/// Build the MCP `instructions` string injected into every connecting client's
|
||||||
/// system prompt.
|
/// system prompt.
|
||||||
|
|
@ -77,17 +77,31 @@ pub struct McpServer {
|
||||||
tool_call_count: AtomicU64,
|
tool_call_count: AtomicU64,
|
||||||
/// Optional event broadcast channel for dashboard real-time updates.
|
/// Optional event broadcast channel for dashboard real-time updates.
|
||||||
event_tx: Option<broadcast::Sender<VestigeEvent>>,
|
event_tx: Option<broadcast::Sender<VestigeEvent>>,
|
||||||
|
/// Resolved output config from `<data_dir>/vestige.toml` (Phase 2). Tools
|
||||||
|
/// use it as the fallback for detail/limit when no explicit MCP param is
|
||||||
|
/// given; explicit params always win.
|
||||||
|
output_config: Arc<OutputConfig>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Load `vestige.toml` from the storage's data directory and resolve it to an
|
||||||
|
/// effective [`OutputConfig`]. A missing/malformed file yields the built-in
|
||||||
|
/// default, which preserves historical behavior.
|
||||||
|
fn load_output_config(storage: &Arc<Storage>) -> Arc<OutputConfig> {
|
||||||
|
let config = VestigeConfig::load_from_data_dir(storage.data_dir());
|
||||||
|
Arc::new(config.output())
|
||||||
}
|
}
|
||||||
|
|
||||||
impl McpServer {
|
impl McpServer {
|
||||||
#[allow(dead_code)]
|
#[allow(dead_code)]
|
||||||
pub fn new(storage: Arc<Storage>, cognitive: Arc<Mutex<CognitiveEngine>>) -> Self {
|
pub fn new(storage: Arc<Storage>, cognitive: Arc<Mutex<CognitiveEngine>>) -> Self {
|
||||||
|
let output_config = load_output_config(&storage);
|
||||||
Self {
|
Self {
|
||||||
storage,
|
storage,
|
||||||
cognitive,
|
cognitive,
|
||||||
initialized: false,
|
initialized: false,
|
||||||
tool_call_count: AtomicU64::new(0),
|
tool_call_count: AtomicU64::new(0),
|
||||||
event_tx: None,
|
event_tx: None,
|
||||||
|
output_config,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -97,12 +111,14 @@ impl McpServer {
|
||||||
cognitive: Arc<Mutex<CognitiveEngine>>,
|
cognitive: Arc<Mutex<CognitiveEngine>>,
|
||||||
event_tx: broadcast::Sender<VestigeEvent>,
|
event_tx: broadcast::Sender<VestigeEvent>,
|
||||||
) -> Self {
|
) -> Self {
|
||||||
|
let output_config = load_output_config(&storage);
|
||||||
Self {
|
Self {
|
||||||
storage,
|
storage,
|
||||||
cognitive,
|
cognitive,
|
||||||
initialized: false,
|
initialized: false,
|
||||||
tool_call_count: AtomicU64::new(0),
|
tool_call_count: AtomicU64::new(0),
|
||||||
event_tx: Some(event_tx),
|
event_tx: Some(event_tx),
|
||||||
|
output_config,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -265,6 +281,15 @@ impl McpServer {
|
||||||
..Default::default()
|
..Default::default()
|
||||||
},
|
},
|
||||||
// ================================================================
|
// ================================================================
|
||||||
|
// EXTERNAL-SOURCE CONNECTORS (#57)
|
||||||
|
// ================================================================
|
||||||
|
ToolDescription {
|
||||||
|
name: "source_sync".to_string(),
|
||||||
|
description: Some("Index an external system into Vestige as a durable, offline, semantically-searchable index that cites back to the canonical record. GitHub: source='github', repo='owner/name' (auth via GITHUB_TOKEN env). Redmine: source='redmine', project='<id>' (host via REDMINE_URL, auth via REDMINE_API_KEY env). Idempotent: re-running updates changed issues without duplicating; set reconcile=true to tombstone issues removed upstream.".to_string()),
|
||||||
|
input_schema: tools::source_sync::schema(),
|
||||||
|
..Default::default()
|
||||||
|
},
|
||||||
|
// ================================================================
|
||||||
// TEMPORAL TOOLS (v1.2+)
|
// TEMPORAL TOOLS (v1.2+)
|
||||||
// ================================================================
|
// ================================================================
|
||||||
ToolDescription {
|
ToolDescription {
|
||||||
|
|
@ -328,6 +353,52 @@ impl McpServer {
|
||||||
..Default::default()
|
..Default::default()
|
||||||
},
|
},
|
||||||
// ================================================================
|
// ================================================================
|
||||||
|
// MERGE / SUPERSEDE CONTROLS (v2.1.25 — Phase 3)
|
||||||
|
// Diff-previewed, confidence-gated, reversible, never silent.
|
||||||
|
// ================================================================
|
||||||
|
ToolDescription {
|
||||||
|
name: "merge_candidates".to_string(),
|
||||||
|
description: Some("Surface likely duplicate/overlapping memory clusters with confidence scores and the signals behind each (Fellegi-Sunter match/possible/non-match). Read-only — nothing is changed.".to_string()),
|
||||||
|
input_schema: tools::merge::merge_candidates_schema(),
|
||||||
|
..Default::default()
|
||||||
|
},
|
||||||
|
ToolDescription {
|
||||||
|
name: "plan_merge".to_string(),
|
||||||
|
description: Some("Produce a previewable MERGE plan (a diff: combined content/tags/provenance) for 2+ memories WITHOUT applying it. Returns a plan_id for apply_plan. Protected members block the merge.".to_string()),
|
||||||
|
input_schema: tools::merge::plan_merge_schema(),
|
||||||
|
..Default::default()
|
||||||
|
},
|
||||||
|
ToolDescription {
|
||||||
|
name: "plan_supersede".to_string(),
|
||||||
|
description: Some("Preview superseding memory A with B — bitemporal invalidation (stamps valid_until, keeps A queryable for audit) WITHOUT applying. Returns a plan_id for apply_plan.".to_string()),
|
||||||
|
input_schema: tools::merge::plan_supersede_schema(),
|
||||||
|
..Default::default()
|
||||||
|
},
|
||||||
|
ToolDescription {
|
||||||
|
name: "apply_plan".to_string(),
|
||||||
|
description: Some("Execute a previously-generated merge/supersede plan by id. Recorded as a reversible operation. Old memories are invalidated (never deleted). 'possible'/'non_match' plans require confirm=true.".to_string()),
|
||||||
|
input_schema: tools::merge::apply_plan_schema(),
|
||||||
|
..Default::default()
|
||||||
|
},
|
||||||
|
ToolDescription {
|
||||||
|
name: "merge_undo".to_string(),
|
||||||
|
description: Some("Reverse a prior merge/supersede operation (the 'git reflog for your agent's memory'). With no operation_id, lists the reversible operation log so you can pick one.".to_string()),
|
||||||
|
input_schema: tools::merge::merge_undo_schema(),
|
||||||
|
..Default::default()
|
||||||
|
},
|
||||||
|
ToolDescription {
|
||||||
|
name: "protect".to_string(),
|
||||||
|
description: Some("Pin a memory so it can never be auto-merged, superseded, or garbage-collected. Pass protected=false to unpin.".to_string()),
|
||||||
|
input_schema: tools::merge::protect_schema(),
|
||||||
|
..Default::default()
|
||||||
|
},
|
||||||
|
ToolDescription {
|
||||||
|
name: "merge_policy".to_string(),
|
||||||
|
description: Some("Get or set the per-project merge policy: the two Fellegi-Sunter thresholds (match_threshold, possible_threshold) and auto_apply. No args returns the current policy.".to_string()),
|
||||||
|
input_schema: tools::merge::merge_policy_schema(),
|
||||||
|
..Default::default()
|
||||||
|
},
|
||||||
|
// ================================================================
|
||||||
// COGNITIVE TOOLS (v1.5+)
|
// COGNITIVE TOOLS (v1.5+)
|
||||||
// ================================================================
|
// ================================================================
|
||||||
ToolDescription {
|
ToolDescription {
|
||||||
|
|
@ -381,6 +452,12 @@ impl McpServer {
|
||||||
input_schema: tools::graph::schema(),
|
input_schema: tools::graph::schema(),
|
||||||
..Default::default()
|
..Default::default()
|
||||||
},
|
},
|
||||||
|
ToolDescription {
|
||||||
|
name: "composed_graph".to_string(),
|
||||||
|
description: Some("ComposedGraph memory topology. Reads durable composition events, members, and outcome labels; returns recent/already-composed lanes, neighbors, never-composed pairs, bounty-mode lanes, and lets users label outcomes such as helpful, submitted, accepted, rejected, duplicate_risk, needs_poc, or dead_end.".to_string()),
|
||||||
|
input_schema: tools::composed_graph::schema(),
|
||||||
|
..Default::default()
|
||||||
|
},
|
||||||
// ================================================================
|
// ================================================================
|
||||||
// DEEP REFERENCE (v2.0.4+) — replaces cross_reference
|
// DEEP REFERENCE (v2.0.4+) — replaces cross_reference
|
||||||
// ================================================================
|
// ================================================================
|
||||||
|
|
@ -491,7 +568,12 @@ impl McpServer {
|
||||||
// UNIFIED TOOLS (v1.1+) - Preferred API
|
// UNIFIED TOOLS (v1.1+) - Preferred API
|
||||||
// ================================================================
|
// ================================================================
|
||||||
"search" => {
|
"search" => {
|
||||||
tools::search_unified::execute(&self.storage, &self.cognitive, request.arguments)
|
tools::search_unified::execute(
|
||||||
|
&self.storage,
|
||||||
|
&self.cognitive,
|
||||||
|
&self.output_config,
|
||||||
|
request.arguments,
|
||||||
|
)
|
||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
"memory" => {
|
"memory" => {
|
||||||
|
|
@ -499,7 +581,12 @@ impl McpServer {
|
||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
"codebase" => {
|
"codebase" => {
|
||||||
tools::codebase_unified::execute(&self.storage, &self.cognitive, request.arguments)
|
tools::codebase_unified::execute(
|
||||||
|
&self.storage,
|
||||||
|
&self.cognitive,
|
||||||
|
&self.output_config,
|
||||||
|
request.arguments,
|
||||||
|
)
|
||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
"intention" => {
|
"intention" => {
|
||||||
|
|
@ -515,6 +602,11 @@ impl McpServer {
|
||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ================================================================
|
||||||
|
// External-source connectors (#57)
|
||||||
|
// ================================================================
|
||||||
|
"source_sync" => tools::source_sync::execute(&self.storage, request.arguments).await,
|
||||||
|
|
||||||
// ================================================================
|
// ================================================================
|
||||||
// DEPRECATED (v1.7): ingest → smart_ingest
|
// DEPRECATED (v1.7): ingest → smart_ingest
|
||||||
// ================================================================
|
// ================================================================
|
||||||
|
|
@ -615,7 +707,12 @@ impl McpServer {
|
||||||
"Tool '{}' is deprecated. Use 'search' instead.",
|
"Tool '{}' is deprecated. Use 'search' instead.",
|
||||||
request.name
|
request.name
|
||||||
);
|
);
|
||||||
tools::search_unified::execute(&self.storage, &self.cognitive, request.arguments)
|
tools::search_unified::execute(
|
||||||
|
&self.storage,
|
||||||
|
&self.cognitive,
|
||||||
|
&self.output_config,
|
||||||
|
request.arguments,
|
||||||
|
)
|
||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -696,7 +793,13 @@ impl McpServer {
|
||||||
}
|
}
|
||||||
None => Some(serde_json::json!({"action": "remember_pattern"})),
|
None => Some(serde_json::json!({"action": "remember_pattern"})),
|
||||||
};
|
};
|
||||||
tools::codebase_unified::execute(&self.storage, &self.cognitive, unified_args).await
|
tools::codebase_unified::execute(
|
||||||
|
&self.storage,
|
||||||
|
&self.cognitive,
|
||||||
|
&self.output_config,
|
||||||
|
unified_args,
|
||||||
|
)
|
||||||
|
.await
|
||||||
}
|
}
|
||||||
"remember_decision" => {
|
"remember_decision" => {
|
||||||
warn!(
|
warn!(
|
||||||
|
|
@ -715,7 +818,13 @@ impl McpServer {
|
||||||
}
|
}
|
||||||
None => Some(serde_json::json!({"action": "remember_decision"})),
|
None => Some(serde_json::json!({"action": "remember_decision"})),
|
||||||
};
|
};
|
||||||
tools::codebase_unified::execute(&self.storage, &self.cognitive, unified_args).await
|
tools::codebase_unified::execute(
|
||||||
|
&self.storage,
|
||||||
|
&self.cognitive,
|
||||||
|
&self.output_config,
|
||||||
|
unified_args,
|
||||||
|
)
|
||||||
|
.await
|
||||||
}
|
}
|
||||||
"get_codebase_context" => {
|
"get_codebase_context" => {
|
||||||
warn!(
|
warn!(
|
||||||
|
|
@ -731,7 +840,13 @@ impl McpServer {
|
||||||
}
|
}
|
||||||
None => Some(serde_json::json!({"action": "get_context"})),
|
None => Some(serde_json::json!({"action": "get_context"})),
|
||||||
};
|
};
|
||||||
tools::codebase_unified::execute(&self.storage, &self.cognitive, unified_args).await
|
tools::codebase_unified::execute(
|
||||||
|
&self.storage,
|
||||||
|
&self.cognitive,
|
||||||
|
&self.output_config,
|
||||||
|
unified_args,
|
||||||
|
)
|
||||||
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
// ================================================================
|
// ================================================================
|
||||||
|
|
@ -863,7 +978,10 @@ impl McpServer {
|
||||||
// ================================================================
|
// ================================================================
|
||||||
// TEMPORAL TOOLS (v1.2+)
|
// TEMPORAL TOOLS (v1.2+)
|
||||||
// ================================================================
|
// ================================================================
|
||||||
"memory_timeline" => tools::timeline::execute(&self.storage, request.arguments).await,
|
"memory_timeline" => {
|
||||||
|
tools::timeline::execute(&self.storage, &self.output_config, request.arguments)
|
||||||
|
.await
|
||||||
|
}
|
||||||
"memory_changelog" => tools::changelog::execute(&self.storage, request.arguments).await,
|
"memory_changelog" => tools::changelog::execute(&self.storage, request.arguments).await,
|
||||||
|
|
||||||
// ================================================================
|
// ================================================================
|
||||||
|
|
@ -887,6 +1005,14 @@ impl McpServer {
|
||||||
}
|
}
|
||||||
"find_duplicates" => tools::dedup::execute(&self.storage, request.arguments).await,
|
"find_duplicates" => tools::dedup::execute(&self.storage, request.arguments).await,
|
||||||
|
|
||||||
|
// ================================================================
|
||||||
|
// MERGE / SUPERSEDE CONTROLS (v2.1.25 — Phase 3)
|
||||||
|
// ================================================================
|
||||||
|
"merge_candidates" | "plan_merge" | "plan_supersede" | "apply_plan" | "merge_undo"
|
||||||
|
| "protect" | "merge_policy" => {
|
||||||
|
tools::merge::execute(&self.storage, request.name.as_str(), request.arguments).await
|
||||||
|
}
|
||||||
|
|
||||||
// ================================================================
|
// ================================================================
|
||||||
// COGNITIVE TOOLS (v1.5+)
|
// COGNITIVE TOOLS (v1.5+)
|
||||||
// ================================================================
|
// ================================================================
|
||||||
|
|
@ -913,7 +1039,12 @@ impl McpServer {
|
||||||
// CONTEXT PACKETS (v1.8+)
|
// CONTEXT PACKETS (v1.8+)
|
||||||
// ================================================================
|
// ================================================================
|
||||||
"session_context" => {
|
"session_context" => {
|
||||||
tools::session_context::execute(&self.storage, &self.cognitive, request.arguments)
|
tools::session_context::execute(
|
||||||
|
&self.storage,
|
||||||
|
&self.cognitive,
|
||||||
|
&self.output_config,
|
||||||
|
request.arguments,
|
||||||
|
)
|
||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -922,6 +1053,9 @@ impl McpServer {
|
||||||
// ================================================================
|
// ================================================================
|
||||||
"memory_health" => tools::health::execute(&self.storage, request.arguments).await,
|
"memory_health" => tools::health::execute(&self.storage, request.arguments).await,
|
||||||
"memory_graph" => tools::graph::execute(&self.storage, request.arguments).await,
|
"memory_graph" => tools::graph::execute(&self.storage, request.arguments).await,
|
||||||
|
"composed_graph" => {
|
||||||
|
tools::composed_graph::execute(&self.storage, request.arguments).await
|
||||||
|
}
|
||||||
"deep_reference" | "cross_reference" => {
|
"deep_reference" | "cross_reference" => {
|
||||||
tools::cross_reference::execute(&self.storage, &self.cognitive, request.arguments)
|
tools::cross_reference::execute(&self.storage, &self.cognitive, request.arguments)
|
||||||
.await
|
.await
|
||||||
|
|
@ -1686,8 +1820,10 @@ mod tests {
|
||||||
let result = response.result.unwrap();
|
let result = response.result.unwrap();
|
||||||
let tools = result["tools"].as_array().unwrap();
|
let tools = result["tools"].as_array().unwrap();
|
||||||
|
|
||||||
// v2.1.21: 25 tools (includes first-class contradictions surface)
|
// 34 tools: 25 from v2.1.21 + 7 Phase 3 merge/supersede tools
|
||||||
assert_eq!(tools.len(), 25, "Expected exactly 25 tools in v2.1.21");
|
// (merge_candidates, plan_merge, plan_supersede, apply_plan, merge_undo,
|
||||||
|
// protect, merge_policy, composed_graph) + 1 connector tool (source_sync, #57).
|
||||||
|
assert_eq!(tools.len(), 34, "Expected exactly 34 tools");
|
||||||
|
|
||||||
let tool_names: Vec<&str> = tools.iter().map(|t| t["name"].as_str().unwrap()).collect();
|
let tool_names: Vec<&str> = tools.iter().map(|t| t["name"].as_str().unwrap()).collect();
|
||||||
|
|
||||||
|
|
@ -1699,6 +1835,9 @@ mod tests {
|
||||||
|
|
||||||
// Core memory (smart_ingest absorbs ingest + checkpoint in v1.7)
|
// Core memory (smart_ingest absorbs ingest + checkpoint in v1.7)
|
||||||
assert!(tool_names.contains(&"smart_ingest"));
|
assert!(tool_names.contains(&"smart_ingest"));
|
||||||
|
|
||||||
|
// External-source connectors (#57)
|
||||||
|
assert!(tool_names.contains(&"source_sync"));
|
||||||
assert!(
|
assert!(
|
||||||
!tool_names.contains(&"ingest"),
|
!tool_names.contains(&"ingest"),
|
||||||
"ingest should be removed in v1.7"
|
"ingest should be removed in v1.7"
|
||||||
|
|
@ -1741,6 +1880,15 @@ mod tests {
|
||||||
assert!(tool_names.contains(&"importance_score"));
|
assert!(tool_names.contains(&"importance_score"));
|
||||||
assert!(tool_names.contains(&"find_duplicates"));
|
assert!(tool_names.contains(&"find_duplicates"));
|
||||||
|
|
||||||
|
// Merge / Supersede controls (v2.1.25 — Phase 3)
|
||||||
|
assert!(tool_names.contains(&"merge_candidates"));
|
||||||
|
assert!(tool_names.contains(&"plan_merge"));
|
||||||
|
assert!(tool_names.contains(&"plan_supersede"));
|
||||||
|
assert!(tool_names.contains(&"apply_plan"));
|
||||||
|
assert!(tool_names.contains(&"merge_undo"));
|
||||||
|
assert!(tool_names.contains(&"protect"));
|
||||||
|
assert!(tool_names.contains(&"merge_policy"));
|
||||||
|
|
||||||
// Cognitive tools (v1.5)
|
// Cognitive tools (v1.5)
|
||||||
assert!(tool_names.contains(&"dream"));
|
assert!(tool_names.contains(&"dream"));
|
||||||
assert!(tool_names.contains(&"explore_connections"));
|
assert!(tool_names.contains(&"explore_connections"));
|
||||||
|
|
@ -1753,6 +1901,7 @@ mod tests {
|
||||||
// Autonomic tools (v1.9)
|
// Autonomic tools (v1.9)
|
||||||
assert!(tool_names.contains(&"memory_health"));
|
assert!(tool_names.contains(&"memory_health"));
|
||||||
assert!(tool_names.contains(&"memory_graph"));
|
assert!(tool_names.contains(&"memory_graph"));
|
||||||
|
assert!(tool_names.contains(&"composed_graph"));
|
||||||
|
|
||||||
// Deep reference + cross_reference alias (v2.0.4)
|
// Deep reference + cross_reference alias (v2.0.4)
|
||||||
assert!(tool_names.contains(&"deep_reference"));
|
assert!(tool_names.contains(&"deep_reference"));
|
||||||
|
|
|
||||||
|
|
@ -278,6 +278,7 @@ mod tests {
|
||||||
tags: vec![],
|
tags: vec![],
|
||||||
valid_from: None,
|
valid_from: None,
|
||||||
valid_until: None,
|
valid_until: None,
|
||||||
|
source_envelope: None,
|
||||||
})
|
})
|
||||||
.unwrap();
|
.unwrap();
|
||||||
node.id
|
node.id
|
||||||
|
|
|
||||||
|
|
@ -9,7 +9,9 @@ use std::sync::Arc;
|
||||||
use tokio::sync::Mutex;
|
use tokio::sync::Mutex;
|
||||||
|
|
||||||
use crate::cognitive::CognitiveEngine;
|
use crate::cognitive::CognitiveEngine;
|
||||||
use vestige_core::{IngestInput, Storage};
|
use vestige_core::{IngestInput, OutputConfig, Storage};
|
||||||
|
|
||||||
|
use super::search_unified::apply_output_masks;
|
||||||
|
|
||||||
/// Input schema for the unified codebase tool
|
/// Input schema for the unified codebase tool
|
||||||
pub fn schema() -> Value {
|
pub fn schema() -> Value {
|
||||||
|
|
@ -87,6 +89,7 @@ struct CodebaseArgs {
|
||||||
pub async fn execute(
|
pub async fn execute(
|
||||||
storage: &Arc<Storage>,
|
storage: &Arc<Storage>,
|
||||||
cognitive: &Arc<Mutex<CognitiveEngine>>,
|
cognitive: &Arc<Mutex<CognitiveEngine>>,
|
||||||
|
output_config: &OutputConfig,
|
||||||
args: Option<Value>,
|
args: Option<Value>,
|
||||||
) -> Result<Value, String> {
|
) -> Result<Value, String> {
|
||||||
let args: CodebaseArgs = match args {
|
let args: CodebaseArgs = match args {
|
||||||
|
|
@ -97,7 +100,7 @@ pub async fn execute(
|
||||||
match args.action.as_str() {
|
match args.action.as_str() {
|
||||||
"remember_pattern" => execute_remember_pattern(storage, cognitive, &args).await,
|
"remember_pattern" => execute_remember_pattern(storage, cognitive, &args).await,
|
||||||
"remember_decision" => execute_remember_decision(storage, cognitive, &args).await,
|
"remember_decision" => execute_remember_decision(storage, cognitive, &args).await,
|
||||||
"get_context" => execute_get_context(storage, cognitive, &args).await,
|
"get_context" => execute_get_context(storage, cognitive, output_config, &args).await,
|
||||||
_ => Err(format!(
|
_ => Err(format!(
|
||||||
"Invalid action '{}'. Must be one of: remember_pattern, remember_decision, get_context",
|
"Invalid action '{}'. Must be one of: remember_pattern, remember_decision, get_context",
|
||||||
args.action
|
args.action
|
||||||
|
|
@ -151,6 +154,7 @@ async fn execute_remember_pattern(
|
||||||
tags,
|
tags,
|
||||||
valid_from: None,
|
valid_from: None,
|
||||||
valid_until: None,
|
valid_until: None,
|
||||||
|
source_envelope: None,
|
||||||
};
|
};
|
||||||
|
|
||||||
let node = storage.ingest(input).map_err(|e| e.to_string())?;
|
let node = storage.ingest(input).map_err(|e| e.to_string())?;
|
||||||
|
|
@ -247,6 +251,7 @@ async fn execute_remember_decision(
|
||||||
tags,
|
tags,
|
||||||
valid_from: None,
|
valid_from: None,
|
||||||
valid_until: None,
|
valid_until: None,
|
||||||
|
source_envelope: None,
|
||||||
};
|
};
|
||||||
|
|
||||||
let node = storage.ingest(input).map_err(|e| e.to_string())?;
|
let node = storage.ingest(input).map_err(|e| e.to_string())?;
|
||||||
|
|
@ -282,9 +287,11 @@ async fn execute_remember_decision(
|
||||||
async fn execute_get_context(
|
async fn execute_get_context(
|
||||||
storage: &Arc<Storage>,
|
storage: &Arc<Storage>,
|
||||||
cognitive: &Arc<Mutex<CognitiveEngine>>,
|
cognitive: &Arc<Mutex<CognitiveEngine>>,
|
||||||
|
output_config: &OutputConfig,
|
||||||
args: &CodebaseArgs,
|
args: &CodebaseArgs,
|
||||||
) -> Result<Value, String> {
|
) -> Result<Value, String> {
|
||||||
let limit = args.limit.unwrap_or(10).clamp(1, 50);
|
// Precedence: explicit MCP param > config limit > built-in default (10).
|
||||||
|
let limit = output_config.resolve_limit(args.limit, 10).clamp(1, 50);
|
||||||
|
|
||||||
// Build tag filter for codebase
|
// Build tag filter for codebase
|
||||||
let tag_filter = args.codebase.as_ref().map(|cb| format!("codebase:{}", cb));
|
let tag_filter = args.codebase.as_ref().map(|cb| format!("codebase:{}", cb));
|
||||||
|
|
@ -299,7 +306,7 @@ async fn execute_get_context(
|
||||||
.get_nodes_by_type_and_tag("decision", tag_filter.as_deref(), limit)
|
.get_nodes_by_type_and_tag("decision", tag_filter.as_deref(), limit)
|
||||||
.unwrap_or_default();
|
.unwrap_or_default();
|
||||||
|
|
||||||
let formatted_patterns: Vec<Value> = patterns
|
let mut formatted_patterns: Vec<Value> = patterns
|
||||||
.iter()
|
.iter()
|
||||||
.map(|n| {
|
.map(|n| {
|
||||||
serde_json::json!({
|
serde_json::json!({
|
||||||
|
|
@ -311,8 +318,9 @@ async fn execute_get_context(
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
.collect();
|
.collect();
|
||||||
|
apply_output_masks(&mut formatted_patterns, output_config);
|
||||||
|
|
||||||
let formatted_decisions: Vec<Value> = decisions
|
let mut formatted_decisions: Vec<Value> = decisions
|
||||||
.iter()
|
.iter()
|
||||||
.map(|n| {
|
.map(|n| {
|
||||||
serde_json::json!({
|
serde_json::json!({
|
||||||
|
|
@ -324,6 +332,7 @@ async fn execute_get_context(
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
.collect();
|
.collect();
|
||||||
|
apply_output_masks(&mut formatted_decisions, output_config);
|
||||||
|
|
||||||
// ====================================================================
|
// ====================================================================
|
||||||
// COGNITIVE: Cross-project knowledge discovery
|
// COGNITIVE: Cross-project knowledge discovery
|
||||||
|
|
@ -352,6 +361,7 @@ async fn execute_get_context(
|
||||||
Ok(serde_json::json!({
|
Ok(serde_json::json!({
|
||||||
"action": "get_context",
|
"action": "get_context",
|
||||||
"codebase": args.codebase,
|
"codebase": args.codebase,
|
||||||
|
"profile": output_config.profile.as_str(),
|
||||||
"patterns": {
|
"patterns": {
|
||||||
"count": formatted_patterns.len(),
|
"count": formatted_patterns.len(),
|
||||||
"items": formatted_patterns,
|
"items": formatted_patterns,
|
||||||
|
|
@ -411,7 +421,7 @@ mod tests {
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn test_missing_args_fails() {
|
async fn test_missing_args_fails() {
|
||||||
let (storage, _dir) = test_storage().await;
|
let (storage, _dir) = test_storage().await;
|
||||||
let result = execute(&storage, &test_cognitive(), None).await;
|
let result = execute(&storage, &test_cognitive(), &OutputConfig::default(), None).await;
|
||||||
assert!(result.is_err());
|
assert!(result.is_err());
|
||||||
assert!(result.unwrap_err().contains("Missing arguments"));
|
assert!(result.unwrap_err().contains("Missing arguments"));
|
||||||
}
|
}
|
||||||
|
|
@ -420,7 +430,13 @@ mod tests {
|
||||||
async fn test_invalid_action_fails() {
|
async fn test_invalid_action_fails() {
|
||||||
let (storage, _dir) = test_storage().await;
|
let (storage, _dir) = test_storage().await;
|
||||||
let args = serde_json::json!({ "action": "invalid" });
|
let args = serde_json::json!({ "action": "invalid" });
|
||||||
let result = execute(&storage, &test_cognitive(), Some(args)).await;
|
let result = execute(
|
||||||
|
&storage,
|
||||||
|
&test_cognitive(),
|
||||||
|
&OutputConfig::default(),
|
||||||
|
Some(args),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
assert!(result.is_err());
|
assert!(result.is_err());
|
||||||
assert!(result.unwrap_err().contains("Invalid action"));
|
assert!(result.unwrap_err().contains("Invalid action"));
|
||||||
}
|
}
|
||||||
|
|
@ -435,7 +451,13 @@ mod tests {
|
||||||
"files": ["src/lib.rs"],
|
"files": ["src/lib.rs"],
|
||||||
"codebase": "vestige"
|
"codebase": "vestige"
|
||||||
});
|
});
|
||||||
let result = execute(&storage, &test_cognitive(), Some(args)).await;
|
let result = execute(
|
||||||
|
&storage,
|
||||||
|
&test_cognitive(),
|
||||||
|
&OutputConfig::default(),
|
||||||
|
Some(args),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
assert!(result.is_ok());
|
assert!(result.is_ok());
|
||||||
let value = result.unwrap();
|
let value = result.unwrap();
|
||||||
assert_eq!(value["action"], "remember_pattern");
|
assert_eq!(value["action"], "remember_pattern");
|
||||||
|
|
@ -451,7 +473,13 @@ mod tests {
|
||||||
"action": "remember_pattern",
|
"action": "remember_pattern",
|
||||||
"description": "Some description"
|
"description": "Some description"
|
||||||
});
|
});
|
||||||
let result = execute(&storage, &test_cognitive(), Some(args)).await;
|
let result = execute(
|
||||||
|
&storage,
|
||||||
|
&test_cognitive(),
|
||||||
|
&OutputConfig::default(),
|
||||||
|
Some(args),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
assert!(result.is_err());
|
assert!(result.is_err());
|
||||||
assert!(result.unwrap_err().contains("'name' is required"));
|
assert!(result.unwrap_err().contains("'name' is required"));
|
||||||
}
|
}
|
||||||
|
|
@ -463,7 +491,13 @@ mod tests {
|
||||||
"action": "remember_pattern",
|
"action": "remember_pattern",
|
||||||
"name": "Test Pattern"
|
"name": "Test Pattern"
|
||||||
});
|
});
|
||||||
let result = execute(&storage, &test_cognitive(), Some(args)).await;
|
let result = execute(
|
||||||
|
&storage,
|
||||||
|
&test_cognitive(),
|
||||||
|
&OutputConfig::default(),
|
||||||
|
Some(args),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
assert!(result.is_err());
|
assert!(result.is_err());
|
||||||
assert!(result.unwrap_err().contains("'description' is required"));
|
assert!(result.unwrap_err().contains("'description' is required"));
|
||||||
}
|
}
|
||||||
|
|
@ -476,7 +510,13 @@ mod tests {
|
||||||
"name": " ",
|
"name": " ",
|
||||||
"description": "Some description"
|
"description": "Some description"
|
||||||
});
|
});
|
||||||
let result = execute(&storage, &test_cognitive(), Some(args)).await;
|
let result = execute(
|
||||||
|
&storage,
|
||||||
|
&test_cognitive(),
|
||||||
|
&OutputConfig::default(),
|
||||||
|
Some(args),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
assert!(result.is_err());
|
assert!(result.is_err());
|
||||||
assert!(result.unwrap_err().contains("empty"));
|
assert!(result.unwrap_err().contains("empty"));
|
||||||
}
|
}
|
||||||
|
|
@ -492,7 +532,13 @@ mod tests {
|
||||||
"files": ["src/storage.rs"],
|
"files": ["src/storage.rs"],
|
||||||
"codebase": "vestige"
|
"codebase": "vestige"
|
||||||
});
|
});
|
||||||
let result = execute(&storage, &test_cognitive(), Some(args)).await;
|
let result = execute(
|
||||||
|
&storage,
|
||||||
|
&test_cognitive(),
|
||||||
|
&OutputConfig::default(),
|
||||||
|
Some(args),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
assert!(result.is_ok());
|
assert!(result.is_ok());
|
||||||
let value = result.unwrap();
|
let value = result.unwrap();
|
||||||
assert_eq!(value["action"], "remember_decision");
|
assert_eq!(value["action"], "remember_decision");
|
||||||
|
|
@ -507,7 +553,13 @@ mod tests {
|
||||||
"action": "remember_decision",
|
"action": "remember_decision",
|
||||||
"rationale": "Some rationale"
|
"rationale": "Some rationale"
|
||||||
});
|
});
|
||||||
let result = execute(&storage, &test_cognitive(), Some(args)).await;
|
let result = execute(
|
||||||
|
&storage,
|
||||||
|
&test_cognitive(),
|
||||||
|
&OutputConfig::default(),
|
||||||
|
Some(args),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
assert!(result.is_err());
|
assert!(result.is_err());
|
||||||
assert!(result.unwrap_err().contains("'decision' is required"));
|
assert!(result.unwrap_err().contains("'decision' is required"));
|
||||||
}
|
}
|
||||||
|
|
@ -519,7 +571,13 @@ mod tests {
|
||||||
"action": "remember_decision",
|
"action": "remember_decision",
|
||||||
"decision": "Use SQLite"
|
"decision": "Use SQLite"
|
||||||
});
|
});
|
||||||
let result = execute(&storage, &test_cognitive(), Some(args)).await;
|
let result = execute(
|
||||||
|
&storage,
|
||||||
|
&test_cognitive(),
|
||||||
|
&OutputConfig::default(),
|
||||||
|
Some(args),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
assert!(result.is_err());
|
assert!(result.is_err());
|
||||||
assert!(result.unwrap_err().contains("'rationale' is required"));
|
assert!(result.unwrap_err().contains("'rationale' is required"));
|
||||||
}
|
}
|
||||||
|
|
@ -532,7 +590,13 @@ mod tests {
|
||||||
"decision": " ",
|
"decision": " ",
|
||||||
"rationale": "Something"
|
"rationale": "Something"
|
||||||
});
|
});
|
||||||
let result = execute(&storage, &test_cognitive(), Some(args)).await;
|
let result = execute(
|
||||||
|
&storage,
|
||||||
|
&test_cognitive(),
|
||||||
|
&OutputConfig::default(),
|
||||||
|
Some(args),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
assert!(result.is_err());
|
assert!(result.is_err());
|
||||||
assert!(result.unwrap_err().contains("empty"));
|
assert!(result.unwrap_err().contains("empty"));
|
||||||
}
|
}
|
||||||
|
|
@ -544,7 +608,13 @@ mod tests {
|
||||||
"action": "get_context",
|
"action": "get_context",
|
||||||
"codebase": "nonexistent"
|
"codebase": "nonexistent"
|
||||||
});
|
});
|
||||||
let result = execute(&storage, &test_cognitive(), Some(args)).await;
|
let result = execute(
|
||||||
|
&storage,
|
||||||
|
&test_cognitive(),
|
||||||
|
&OutputConfig::default(),
|
||||||
|
Some(args),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
assert!(result.is_ok());
|
assert!(result.is_ok());
|
||||||
let value = result.unwrap();
|
let value = result.unwrap();
|
||||||
assert_eq!(value["action"], "get_context");
|
assert_eq!(value["action"], "get_context");
|
||||||
|
|
@ -563,14 +633,16 @@ mod tests {
|
||||||
"description": "A test pattern",
|
"description": "A test pattern",
|
||||||
"codebase": "myproject"
|
"codebase": "myproject"
|
||||||
});
|
});
|
||||||
execute(&storage, &cog, Some(save_args)).await.unwrap();
|
execute(&storage, &cog, &OutputConfig::default(), Some(save_args))
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
// Now retrieve
|
// Now retrieve
|
||||||
let get_args = serde_json::json!({
|
let get_args = serde_json::json!({
|
||||||
"action": "get_context",
|
"action": "get_context",
|
||||||
"codebase": "myproject"
|
"codebase": "myproject"
|
||||||
});
|
});
|
||||||
let result = execute(&storage, &cog, Some(get_args)).await;
|
let result = execute(&storage, &cog, &OutputConfig::default(), Some(get_args)).await;
|
||||||
assert!(result.is_ok());
|
assert!(result.is_ok());
|
||||||
let value = result.unwrap();
|
let value = result.unwrap();
|
||||||
assert!(value["patterns"]["count"].as_u64().unwrap() >= 1);
|
assert!(value["patterns"]["count"].as_u64().unwrap() >= 1);
|
||||||
|
|
@ -580,10 +652,41 @@ mod tests {
|
||||||
async fn test_get_context_no_codebase() {
|
async fn test_get_context_no_codebase() {
|
||||||
let (storage, _dir) = test_storage().await;
|
let (storage, _dir) = test_storage().await;
|
||||||
let args = serde_json::json!({ "action": "get_context" });
|
let args = serde_json::json!({ "action": "get_context" });
|
||||||
let result = execute(&storage, &test_cognitive(), Some(args)).await;
|
let result = execute(
|
||||||
|
&storage,
|
||||||
|
&test_cognitive(),
|
||||||
|
&OutputConfig::default(),
|
||||||
|
Some(args),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
assert!(result.is_ok());
|
assert!(result.is_ok());
|
||||||
let value = result.unwrap();
|
let value = result.unwrap();
|
||||||
assert_eq!(value["action"], "get_context");
|
assert_eq!(value["action"], "get_context");
|
||||||
assert!(value["codebase"].is_null());
|
assert!(value["codebase"].is_null());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Phase 2: the `lean` profile masks the `createdAt` timestamp from
|
||||||
|
/// get_context items, and the response echoes the active profile.
|
||||||
|
#[tokio::test]
|
||||||
|
async fn test_get_context_lean_profile_masks_timestamps() {
|
||||||
|
let (storage, _dir) = test_storage().await;
|
||||||
|
let cog = test_cognitive();
|
||||||
|
let save_args = serde_json::json!({
|
||||||
|
"action": "remember_pattern",
|
||||||
|
"name": "Lean Pattern",
|
||||||
|
"description": "A pattern for lean masking",
|
||||||
|
"codebase": "leanproj"
|
||||||
|
});
|
||||||
|
execute(&storage, &cog, &OutputConfig::default(), Some(save_args))
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
let cfg = vestige_core::VestigeConfig::parse("[defaults]\nprofile=lean").output();
|
||||||
|
let get_args = serde_json::json!({ "action": "get_context", "codebase": "leanproj" });
|
||||||
|
let value = execute(&storage, &cog, &cfg, Some(get_args)).await.unwrap();
|
||||||
|
assert_eq!(value["profile"], "lean");
|
||||||
|
let item = &value["patterns"]["items"][0];
|
||||||
|
assert!(item.get("createdAt").is_none(), "lean must drop createdAt");
|
||||||
|
assert!(item.get("content").is_some(), "content still present");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
906
crates/vestige-mcp/src/tools/composed_graph.rs
Normal file
906
crates/vestige-mcp/src/tools/composed_graph.rs
Normal file
|
|
@ -0,0 +1,906 @@
|
||||||
|
//! composed_graph tool — durable composition history and bounty-mode lane queue.
|
||||||
|
|
||||||
|
use chrono::Utc;
|
||||||
|
use serde::Deserialize;
|
||||||
|
use serde_json::Value;
|
||||||
|
use std::sync::Arc;
|
||||||
|
use uuid::Uuid;
|
||||||
|
use vestige_core::{CompositionOutcomeRecord, Storage};
|
||||||
|
|
||||||
|
const OUTCOME_TYPES: &[&str] = &[
|
||||||
|
"helpful",
|
||||||
|
"dead_end",
|
||||||
|
"submitted",
|
||||||
|
"accepted",
|
||||||
|
"rejected",
|
||||||
|
"duplicate_risk",
|
||||||
|
"needs_poc",
|
||||||
|
"bad_severity",
|
||||||
|
"user_promoted",
|
||||||
|
"user_demoted",
|
||||||
|
"closed_by_scope",
|
||||||
|
"closed_by_duplicate",
|
||||||
|
"closed_by_false_assumption",
|
||||||
|
"closed_by_user",
|
||||||
|
"expired_lane",
|
||||||
|
];
|
||||||
|
|
||||||
|
pub fn schema() -> Value {
|
||||||
|
serde_json::json!({
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"action": {
|
||||||
|
"type": "string",
|
||||||
|
"enum": ["recent", "get", "memory", "neighbors", "never_composed", "bounty_mode", "label"],
|
||||||
|
"description": "ComposedGraph action to run."
|
||||||
|
},
|
||||||
|
"event_id": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "Composition event id for get/label actions."
|
||||||
|
},
|
||||||
|
"memory_id": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "Memory id for memory/neighbors actions."
|
||||||
|
},
|
||||||
|
"limit": {
|
||||||
|
"type": "integer",
|
||||||
|
"description": "Maximum rows to return (default 10, max 100).",
|
||||||
|
"default": 10,
|
||||||
|
"minimum": 1,
|
||||||
|
"maximum": 100
|
||||||
|
},
|
||||||
|
"tags": {
|
||||||
|
"type": "array",
|
||||||
|
"items": { "type": "string" },
|
||||||
|
"description": "Optional tag filter for never_composed and bounty_mode."
|
||||||
|
},
|
||||||
|
"outcome_type": {
|
||||||
|
"type": "string",
|
||||||
|
"enum": ["helpful", "dead_end", "submitted", "accepted", "rejected", "duplicate_risk", "needs_poc", "bad_severity", "user_promoted", "user_demoted", "closed_by_scope", "closed_by_duplicate", "closed_by_false_assumption", "closed_by_user", "expired_lane"],
|
||||||
|
"description": "Outcome label for label action."
|
||||||
|
},
|
||||||
|
"notes": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "Optional outcome notes."
|
||||||
|
},
|
||||||
|
"label_source": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "Where the outcome label came from (default: user)."
|
||||||
|
},
|
||||||
|
"confidence_delta": {
|
||||||
|
"type": "number",
|
||||||
|
"description": "Optional confidence adjustment for this outcome."
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": ["action"]
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Deserialize)]
|
||||||
|
#[serde(rename_all = "snake_case")]
|
||||||
|
struct ComposedGraphArgs {
|
||||||
|
action: String,
|
||||||
|
event_id: Option<String>,
|
||||||
|
memory_id: Option<String>,
|
||||||
|
limit: Option<i32>,
|
||||||
|
tags: Option<Vec<String>>,
|
||||||
|
outcome_type: Option<String>,
|
||||||
|
notes: Option<String>,
|
||||||
|
label_source: Option<String>,
|
||||||
|
confidence_delta: Option<f64>,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn execute(storage: &Arc<Storage>, args: Option<Value>) -> Result<Value, String> {
|
||||||
|
let args: ComposedGraphArgs = match args {
|
||||||
|
Some(value) => {
|
||||||
|
serde_json::from_value(value).map_err(|e| format!("Invalid arguments: {}", e))?
|
||||||
|
}
|
||||||
|
None => return Err("Missing arguments".to_string()),
|
||||||
|
};
|
||||||
|
let limit = args.limit.unwrap_or(10).clamp(1, 100);
|
||||||
|
|
||||||
|
match args.action.as_str() {
|
||||||
|
"recent" => recent(storage, limit),
|
||||||
|
"get" => {
|
||||||
|
let event_id = args
|
||||||
|
.event_id
|
||||||
|
.as_deref()
|
||||||
|
.ok_or_else(|| "event_id is required for get".to_string())?;
|
||||||
|
get(storage, event_id)
|
||||||
|
}
|
||||||
|
"memory" => {
|
||||||
|
let memory_id = args
|
||||||
|
.memory_id
|
||||||
|
.as_deref()
|
||||||
|
.ok_or_else(|| "memory_id is required for memory".to_string())?;
|
||||||
|
memory(storage, memory_id, limit)
|
||||||
|
}
|
||||||
|
"neighbors" => {
|
||||||
|
let memory_id = args
|
||||||
|
.memory_id
|
||||||
|
.as_deref()
|
||||||
|
.ok_or_else(|| "memory_id is required for neighbors".to_string())?;
|
||||||
|
neighbors(storage, memory_id, limit)
|
||||||
|
}
|
||||||
|
"never_composed" => never_composed(storage, limit, args.tags.as_deref()),
|
||||||
|
"bounty_mode" => bounty_mode(storage, limit, args.tags.as_deref()),
|
||||||
|
"label" => label(storage, &args),
|
||||||
|
other => Err(format!("Unknown composed_graph action: {}", other)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn recent(storage: &Storage, limit: i32) -> Result<Value, String> {
|
||||||
|
let events = storage
|
||||||
|
.get_recent_composition_events(limit)
|
||||||
|
.map_err(|e| e.to_string())?;
|
||||||
|
Ok(serde_json::json!({
|
||||||
|
"action": "recent",
|
||||||
|
"events": events,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn get(storage: &Storage, event_id: &str) -> Result<Value, String> {
|
||||||
|
let event = storage
|
||||||
|
.get_composition_event(event_id)
|
||||||
|
.map_err(|e| e.to_string())?
|
||||||
|
.ok_or_else(|| format!("composition event not found: {}", event_id))?;
|
||||||
|
let members = storage
|
||||||
|
.get_composition_members(event_id)
|
||||||
|
.map_err(|e| e.to_string())?;
|
||||||
|
let outcomes = storage
|
||||||
|
.get_composition_outcomes(event_id)
|
||||||
|
.map_err(|e| e.to_string())?;
|
||||||
|
Ok(serde_json::json!({
|
||||||
|
"action": "get",
|
||||||
|
"event": event,
|
||||||
|
"members": members,
|
||||||
|
"outcomes": outcomes,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn memory(storage: &Storage, memory_id: &str, limit: i32) -> Result<Value, String> {
|
||||||
|
let events = storage
|
||||||
|
.get_compositions_for_memory(memory_id, limit)
|
||||||
|
.map_err(|e| e.to_string())?;
|
||||||
|
Ok(serde_json::json!({
|
||||||
|
"action": "memory",
|
||||||
|
"memoryId": memory_id,
|
||||||
|
"events": events,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn neighbors(storage: &Storage, memory_id: &str, limit: i32) -> Result<Value, String> {
|
||||||
|
let neighbors = storage
|
||||||
|
.get_composition_neighbors(memory_id, limit)
|
||||||
|
.map_err(|e| e.to_string())?;
|
||||||
|
Ok(serde_json::json!({
|
||||||
|
"action": "neighbors",
|
||||||
|
"memoryId": memory_id,
|
||||||
|
"neighbors": neighbors,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn never_composed(storage: &Storage, limit: i32, tags: Option<&[String]>) -> Result<Value, String> {
|
||||||
|
let candidates = storage
|
||||||
|
.get_never_composed_candidates(limit, tags)
|
||||||
|
.map_err(|e| e.to_string())?;
|
||||||
|
Ok(serde_json::json!({
|
||||||
|
"action": "never_composed",
|
||||||
|
"candidates": candidates,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn bounty_mode(storage: &Storage, limit: i32, tags: Option<&[String]>) -> Result<Value, String> {
|
||||||
|
const PAGE_SIZE: i32 = 100;
|
||||||
|
const MAX_SCAN_EVENTS: i32 = 1_000;
|
||||||
|
|
||||||
|
let mut offset = 0;
|
||||||
|
let mut scanned = 0;
|
||||||
|
let mut already_composed = Vec::new();
|
||||||
|
let mut closed_doors = Vec::new();
|
||||||
|
let mut duplicate_risk_lanes = Vec::new();
|
||||||
|
let mut needs_poc_lanes = Vec::new();
|
||||||
|
|
||||||
|
loop {
|
||||||
|
let events = storage
|
||||||
|
.get_recent_composition_events_page(PAGE_SIZE, offset)
|
||||||
|
.map_err(|e| e.to_string())?;
|
||||||
|
if events.is_empty() {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
scanned += events.len() as i32;
|
||||||
|
|
||||||
|
for event in events {
|
||||||
|
let outcomes = storage
|
||||||
|
.get_composition_outcomes(&event.id)
|
||||||
|
.map_err(|e| e.to_string())?;
|
||||||
|
let members = storage
|
||||||
|
.get_composition_members(&event.id)
|
||||||
|
.map_err(|e| e.to_string())?;
|
||||||
|
if !composition_matches_tags(storage, &event, &members, tags)? {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let item = serde_json::json!({
|
||||||
|
"event": event,
|
||||||
|
"members": members,
|
||||||
|
"outcomes": outcomes,
|
||||||
|
});
|
||||||
|
let outcome_types = item["outcomes"]
|
||||||
|
.as_array()
|
||||||
|
.map(|values| {
|
||||||
|
values
|
||||||
|
.iter()
|
||||||
|
.filter_map(|value| value.get("outcomeType").and_then(|v| v.as_str()))
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
})
|
||||||
|
.unwrap_or_default();
|
||||||
|
|
||||||
|
if outcome_types.iter().any(|kind| {
|
||||||
|
matches!(
|
||||||
|
*kind,
|
||||||
|
"dead_end"
|
||||||
|
| "rejected"
|
||||||
|
| "bad_severity"
|
||||||
|
| "closed_by_scope"
|
||||||
|
| "closed_by_duplicate"
|
||||||
|
| "closed_by_false_assumption"
|
||||||
|
| "closed_by_user"
|
||||||
|
| "expired_lane"
|
||||||
|
)
|
||||||
|
}) {
|
||||||
|
push_limited(&mut closed_doors, item.clone(), limit);
|
||||||
|
}
|
||||||
|
if outcome_types
|
||||||
|
.iter()
|
||||||
|
.any(|kind| matches!(*kind, "duplicate_risk" | "closed_by_duplicate"))
|
||||||
|
{
|
||||||
|
push_limited(&mut duplicate_risk_lanes, item.clone(), limit);
|
||||||
|
}
|
||||||
|
if outcome_types.contains(&"needs_poc") {
|
||||||
|
push_limited(&mut needs_poc_lanes, item.clone(), limit);
|
||||||
|
}
|
||||||
|
if already_composed.len() < limit as usize {
|
||||||
|
already_composed.push(item);
|
||||||
|
}
|
||||||
|
if bounty_mode_lanes_full(
|
||||||
|
limit,
|
||||||
|
&already_composed,
|
||||||
|
&closed_doors,
|
||||||
|
&duplicate_risk_lanes,
|
||||||
|
&needs_poc_lanes,
|
||||||
|
) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if bounty_mode_lanes_full(
|
||||||
|
limit,
|
||||||
|
&already_composed,
|
||||||
|
&closed_doors,
|
||||||
|
&duplicate_risk_lanes,
|
||||||
|
&needs_poc_lanes,
|
||||||
|
) || scanned >= MAX_SCAN_EVENTS
|
||||||
|
{
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
offset += PAGE_SIZE;
|
||||||
|
}
|
||||||
|
|
||||||
|
let never = storage
|
||||||
|
.get_never_composed_candidates(limit, tags)
|
||||||
|
.map_err(|e| e.to_string())?;
|
||||||
|
let top_weird_combinations = never.iter().take(3).cloned().collect::<Vec<_>>();
|
||||||
|
|
||||||
|
Ok(serde_json::json!({
|
||||||
|
"action": "bounty_mode",
|
||||||
|
"alreadyComposedLanes": already_composed,
|
||||||
|
"neverComposedLanes": never,
|
||||||
|
"closedDoors": closed_doors,
|
||||||
|
"duplicateRiskLanes": duplicate_risk_lanes,
|
||||||
|
"needsPocLanes": needs_poc_lanes,
|
||||||
|
"topWeirdCombinations": top_weird_combinations,
|
||||||
|
"guardrails": [
|
||||||
|
"never-composed lane is not a finding",
|
||||||
|
"composition score is not severity",
|
||||||
|
"submit/reportable still needs source refs, scope fit, and PoC evidence"
|
||||||
|
]
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn push_limited(items: &mut Vec<Value>, item: Value, limit: i32) {
|
||||||
|
if items.len() < limit as usize {
|
||||||
|
items.push(item);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn bounty_mode_lanes_full(
|
||||||
|
limit: i32,
|
||||||
|
already_composed: &[Value],
|
||||||
|
closed_doors: &[Value],
|
||||||
|
duplicate_risk_lanes: &[Value],
|
||||||
|
needs_poc_lanes: &[Value],
|
||||||
|
) -> bool {
|
||||||
|
let limit = limit as usize;
|
||||||
|
already_composed.len() >= limit
|
||||||
|
&& closed_doors.len() >= limit
|
||||||
|
&& duplicate_risk_lanes.len() >= limit
|
||||||
|
&& needs_poc_lanes.len() >= limit
|
||||||
|
}
|
||||||
|
|
||||||
|
fn composition_matches_tags(
|
||||||
|
storage: &Storage,
|
||||||
|
event: &vestige_core::CompositionEventRecord,
|
||||||
|
members: &[vestige_core::CompositionMemberRecord],
|
||||||
|
tags: Option<&[String]>,
|
||||||
|
) -> Result<bool, String> {
|
||||||
|
let Some(tags) = tags else {
|
||||||
|
return Ok(true);
|
||||||
|
};
|
||||||
|
if tags.is_empty() {
|
||||||
|
return Ok(true);
|
||||||
|
}
|
||||||
|
|
||||||
|
if json_value_has_tag(&event.metadata, tags) {
|
||||||
|
return Ok(true);
|
||||||
|
}
|
||||||
|
|
||||||
|
for member in members {
|
||||||
|
if json_value_has_tag(&member.metadata, tags) {
|
||||||
|
return Ok(true);
|
||||||
|
}
|
||||||
|
if let Some(node) = storage
|
||||||
|
.get_node(&member.memory_id)
|
||||||
|
.map_err(|e| e.to_string())?
|
||||||
|
&& node.tags.iter().any(|tag| tag_matches_filter(tag, tags))
|
||||||
|
{
|
||||||
|
return Ok(true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(false)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn json_value_has_tag(value: &Value, tags: &[String]) -> bool {
|
||||||
|
value
|
||||||
|
.get("tags")
|
||||||
|
.and_then(|tags_value| tags_value.as_array())
|
||||||
|
.is_some_and(|values| {
|
||||||
|
values.iter().any(|value| {
|
||||||
|
value
|
||||||
|
.as_str()
|
||||||
|
.is_some_and(|tag| tag_matches_filter(tag, tags))
|
||||||
|
})
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn tag_matches_filter(tag: &str, filters: &[String]) -> bool {
|
||||||
|
filters
|
||||||
|
.iter()
|
||||||
|
.any(|wanted| tag == wanted || tag.starts_with(&format!("{wanted}:")))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn label(storage: &Storage, args: &ComposedGraphArgs) -> Result<Value, String> {
|
||||||
|
let event_id = args
|
||||||
|
.event_id
|
||||||
|
.as_deref()
|
||||||
|
.ok_or_else(|| "event_id is required for label".to_string())?;
|
||||||
|
let outcome_type = args
|
||||||
|
.outcome_type
|
||||||
|
.as_deref()
|
||||||
|
.ok_or_else(|| "outcome_type is required for label".to_string())?;
|
||||||
|
if !OUTCOME_TYPES.contains(&outcome_type) {
|
||||||
|
return Err(format!("unsupported outcome_type: {}", outcome_type));
|
||||||
|
}
|
||||||
|
if storage
|
||||||
|
.get_composition_event(event_id)
|
||||||
|
.map_err(|e| e.to_string())?
|
||||||
|
.is_none()
|
||||||
|
{
|
||||||
|
return Err(format!("composition event not found: {}", event_id));
|
||||||
|
}
|
||||||
|
|
||||||
|
let outcome = CompositionOutcomeRecord {
|
||||||
|
id: Uuid::new_v4().to_string(),
|
||||||
|
event_id: event_id.to_string(),
|
||||||
|
outcome_type: outcome_type.to_string(),
|
||||||
|
labeled_at: Utc::now(),
|
||||||
|
label_source: args
|
||||||
|
.label_source
|
||||||
|
.clone()
|
||||||
|
.unwrap_or_else(|| "user".to_string()),
|
||||||
|
confidence_delta: args.confidence_delta,
|
||||||
|
notes: args.notes.clone(),
|
||||||
|
metadata: serde_json::json!({}),
|
||||||
|
};
|
||||||
|
storage
|
||||||
|
.record_composition_outcome(&outcome)
|
||||||
|
.map_err(|e| e.to_string())?;
|
||||||
|
|
||||||
|
Ok(serde_json::json!({
|
||||||
|
"action": "label",
|
||||||
|
"eventId": event_id,
|
||||||
|
"outcome": outcome,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use tempfile::TempDir;
|
||||||
|
use vestige_core::{
|
||||||
|
CompositionEventRecord, CompositionMemberRecord, CompositionOutcomeRecord, IngestInput,
|
||||||
|
};
|
||||||
|
|
||||||
|
fn test_storage() -> (Arc<Storage>, TempDir) {
|
||||||
|
let dir = TempDir::new().unwrap();
|
||||||
|
let storage = Storage::new(Some(dir.path().join("test.db"))).unwrap();
|
||||||
|
(Arc::new(storage), dir)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn ingest(storage: &Storage, content: &str, tags: &[&str]) -> String {
|
||||||
|
storage
|
||||||
|
.ingest(IngestInput {
|
||||||
|
content: content.to_string(),
|
||||||
|
node_type: "fact".to_string(),
|
||||||
|
tags: tags.iter().map(|tag| tag.to_string()).collect(),
|
||||||
|
..Default::default()
|
||||||
|
})
|
||||||
|
.unwrap()
|
||||||
|
.id
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn test_composed_graph_get_label_and_bounty_mode() {
|
||||||
|
let (storage, _dir) = test_storage();
|
||||||
|
let first = ingest(
|
||||||
|
&storage,
|
||||||
|
"Oracle drift bounty lane",
|
||||||
|
&["protocolgate", "boundary-oracle", "settlement"],
|
||||||
|
);
|
||||||
|
let second = ingest(
|
||||||
|
&storage,
|
||||||
|
"Withdrawal queue bounty lane",
|
||||||
|
&["protocolgate", "boundary-queue", "settlement"],
|
||||||
|
);
|
||||||
|
let third = ingest(
|
||||||
|
&storage,
|
||||||
|
"Keeper role bounty lane",
|
||||||
|
&["protocolgate", "boundary-role", "settlement"],
|
||||||
|
);
|
||||||
|
|
||||||
|
let event = CompositionEventRecord {
|
||||||
|
id: "composed-graph-test".to_string(),
|
||||||
|
created_at: Utc::now(),
|
||||||
|
tool: "deep_reference".to_string(),
|
||||||
|
mode: "bounty".to_string(),
|
||||||
|
query: Some("oracle withdrawal".to_string()),
|
||||||
|
query_hash: Some("test".to_string()),
|
||||||
|
confidence: Some(0.8),
|
||||||
|
status: Some("resolved".to_string()),
|
||||||
|
output_preview: Some("compose oracle and withdrawal queue".to_string()),
|
||||||
|
metadata: serde_json::json!({}),
|
||||||
|
};
|
||||||
|
storage
|
||||||
|
.save_composition(
|
||||||
|
&event,
|
||||||
|
&[
|
||||||
|
CompositionMemberRecord {
|
||||||
|
event_id: event.id.clone(),
|
||||||
|
memory_id: first.clone(),
|
||||||
|
role: "primary".to_string(),
|
||||||
|
rank: 0,
|
||||||
|
trust: Some(0.8),
|
||||||
|
score: Some(0.9),
|
||||||
|
preview: None,
|
||||||
|
metadata: serde_json::json!({}),
|
||||||
|
},
|
||||||
|
CompositionMemberRecord {
|
||||||
|
event_id: event.id.clone(),
|
||||||
|
memory_id: second.clone(),
|
||||||
|
role: "supporting".to_string(),
|
||||||
|
rank: 1,
|
||||||
|
trust: Some(0.7),
|
||||||
|
score: Some(0.8),
|
||||||
|
preview: None,
|
||||||
|
metadata: serde_json::json!({}),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
&[],
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
let unrelated = ingest(&storage, "Personal planning lane", &["personal"]);
|
||||||
|
storage
|
||||||
|
.save_composition(
|
||||||
|
&CompositionEventRecord {
|
||||||
|
id: "unrelated-composed-graph-test".to_string(),
|
||||||
|
created_at: Utc::now() + chrono::Duration::seconds(10),
|
||||||
|
tool: "deep_reference".to_string(),
|
||||||
|
mode: "planning".to_string(),
|
||||||
|
query: Some("personal planning".to_string()),
|
||||||
|
query_hash: Some("unrelated".to_string()),
|
||||||
|
confidence: Some(0.4),
|
||||||
|
status: Some("resolved".to_string()),
|
||||||
|
output_preview: Some("unrelated composition".to_string()),
|
||||||
|
metadata: serde_json::json!({}),
|
||||||
|
},
|
||||||
|
&[CompositionMemberRecord {
|
||||||
|
event_id: "unrelated-composed-graph-test".to_string(),
|
||||||
|
memory_id: unrelated,
|
||||||
|
role: "primary".to_string(),
|
||||||
|
rank: 0,
|
||||||
|
trust: Some(0.4),
|
||||||
|
score: Some(0.2),
|
||||||
|
preview: None,
|
||||||
|
metadata: serde_json::json!({}),
|
||||||
|
}],
|
||||||
|
&[CompositionOutcomeRecord {
|
||||||
|
id: "unrelated-composed-graph-outcome".to_string(),
|
||||||
|
event_id: "unrelated-composed-graph-test".to_string(),
|
||||||
|
outcome_type: "needs_poc".to_string(),
|
||||||
|
labeled_at: Utc::now(),
|
||||||
|
label_source: "test".to_string(),
|
||||||
|
confidence_delta: None,
|
||||||
|
notes: None,
|
||||||
|
metadata: serde_json::json!({}),
|
||||||
|
}],
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
let get_result = execute(
|
||||||
|
&storage,
|
||||||
|
Some(serde_json::json!({
|
||||||
|
"action": "get",
|
||||||
|
"event_id": event.id
|
||||||
|
})),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(get_result["members"].as_array().unwrap().len(), 2);
|
||||||
|
|
||||||
|
let label_result = execute(
|
||||||
|
&storage,
|
||||||
|
Some(serde_json::json!({
|
||||||
|
"action": "label",
|
||||||
|
"event_id": "composed-graph-test",
|
||||||
|
"outcome_type": "submitted",
|
||||||
|
"notes": "submitted in test"
|
||||||
|
})),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
label_result["outcome"]["outcomeType"].as_str(),
|
||||||
|
Some("submitted")
|
||||||
|
);
|
||||||
|
let closed_label_result = execute(
|
||||||
|
&storage,
|
||||||
|
Some(serde_json::json!({
|
||||||
|
"action": "label",
|
||||||
|
"event_id": "composed-graph-test",
|
||||||
|
"outcome_type": "closed_by_scope",
|
||||||
|
"notes": "closed in test"
|
||||||
|
})),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
closed_label_result["outcome"]["outcomeType"].as_str(),
|
||||||
|
Some("closed_by_scope")
|
||||||
|
);
|
||||||
|
let duplicate_label_result = execute(
|
||||||
|
&storage,
|
||||||
|
Some(serde_json::json!({
|
||||||
|
"action": "label",
|
||||||
|
"event_id": "composed-graph-test",
|
||||||
|
"outcome_type": "closed_by_duplicate",
|
||||||
|
"notes": "duplicate family in test"
|
||||||
|
})),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
duplicate_label_result["outcome"]["outcomeType"].as_str(),
|
||||||
|
Some("closed_by_duplicate")
|
||||||
|
);
|
||||||
|
|
||||||
|
let bounty = execute(
|
||||||
|
&storage,
|
||||||
|
Some(serde_json::json!({
|
||||||
|
"action": "bounty_mode",
|
||||||
|
"tags": ["protocolgate"],
|
||||||
|
"limit": 1
|
||||||
|
})),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
let already = bounty["alreadyComposedLanes"].as_array().unwrap();
|
||||||
|
assert_eq!(already.len(), 1);
|
||||||
|
assert!(
|
||||||
|
already[0]["event"]["id"].as_str() == Some("composed-graph-test"),
|
||||||
|
"tag-scoped bounty_mode should skip newer unrelated events before truncating"
|
||||||
|
);
|
||||||
|
assert_eq!(bounty["closedDoors"].as_array().unwrap().len(), 1);
|
||||||
|
assert_eq!(bounty["duplicateRiskLanes"].as_array().unwrap().len(), 1);
|
||||||
|
assert!(bounty["needsPocLanes"].as_array().unwrap().is_empty());
|
||||||
|
assert!(
|
||||||
|
bounty["neverComposedLanes"]
|
||||||
|
.as_array()
|
||||||
|
.unwrap()
|
||||||
|
.iter()
|
||||||
|
.any(|candidate| {
|
||||||
|
let first_id = candidate["firstId"].as_str().unwrap_or_default();
|
||||||
|
let second_id = candidate["secondId"].as_str().unwrap_or_default();
|
||||||
|
[first_id, second_id].contains(&third.as_str())
|
||||||
|
})
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn test_bounty_mode_paginates_tag_filter_and_matches_namespaced_tags() {
|
||||||
|
let (storage, _dir) = test_storage();
|
||||||
|
let tagged = ingest(
|
||||||
|
&storage,
|
||||||
|
"Older tagged composition lane",
|
||||||
|
&["project:vestige", "composition"],
|
||||||
|
);
|
||||||
|
let unrelated = ingest(&storage, "Newer unrelated lane", &["unrelated"]);
|
||||||
|
let base_time = Utc::now();
|
||||||
|
|
||||||
|
storage
|
||||||
|
.save_composition(
|
||||||
|
&CompositionEventRecord {
|
||||||
|
id: "older-tagged-composition".to_string(),
|
||||||
|
created_at: base_time,
|
||||||
|
tool: "deep_reference".to_string(),
|
||||||
|
mode: "research".to_string(),
|
||||||
|
query: Some("older tagged lane".to_string()),
|
||||||
|
query_hash: Some("fnv1a64:older".to_string()),
|
||||||
|
confidence: Some(0.8),
|
||||||
|
status: Some("resolved".to_string()),
|
||||||
|
output_preview: None,
|
||||||
|
metadata: serde_json::json!({}),
|
||||||
|
},
|
||||||
|
&[CompositionMemberRecord {
|
||||||
|
event_id: "older-tagged-composition".to_string(),
|
||||||
|
memory_id: tagged,
|
||||||
|
role: "primary".to_string(),
|
||||||
|
rank: 0,
|
||||||
|
trust: Some(0.8),
|
||||||
|
score: Some(0.9),
|
||||||
|
preview: None,
|
||||||
|
metadata: serde_json::json!({}),
|
||||||
|
}],
|
||||||
|
&[],
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
for idx in 0..101 {
|
||||||
|
let event_id = format!("newer-unrelated-composition-{idx}");
|
||||||
|
storage
|
||||||
|
.save_composition(
|
||||||
|
&CompositionEventRecord {
|
||||||
|
id: event_id.clone(),
|
||||||
|
created_at: base_time + chrono::Duration::seconds(i64::from(idx + 1)),
|
||||||
|
tool: "deep_reference".to_string(),
|
||||||
|
mode: "planning".to_string(),
|
||||||
|
query: Some(format!("newer unrelated lane {idx}")),
|
||||||
|
query_hash: Some(format!("fnv1a64:newer-{idx}")),
|
||||||
|
confidence: Some(0.3),
|
||||||
|
status: Some("resolved".to_string()),
|
||||||
|
output_preview: None,
|
||||||
|
metadata: serde_json::json!({}),
|
||||||
|
},
|
||||||
|
&[CompositionMemberRecord {
|
||||||
|
event_id,
|
||||||
|
memory_id: unrelated.clone(),
|
||||||
|
role: "primary".to_string(),
|
||||||
|
rank: 0,
|
||||||
|
trust: Some(0.3),
|
||||||
|
score: Some(0.2),
|
||||||
|
preview: None,
|
||||||
|
metadata: serde_json::json!({}),
|
||||||
|
}],
|
||||||
|
&[],
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
let bounty = execute(
|
||||||
|
&storage,
|
||||||
|
Some(serde_json::json!({
|
||||||
|
"action": "bounty_mode",
|
||||||
|
"tags": ["project"],
|
||||||
|
"limit": 1
|
||||||
|
})),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
let already = bounty["alreadyComposedLanes"].as_array().unwrap();
|
||||||
|
assert_eq!(already.len(), 1);
|
||||||
|
assert_eq!(
|
||||||
|
already[0]["event"]["id"].as_str(),
|
||||||
|
Some("older-tagged-composition"),
|
||||||
|
"tag-filtered bounty_mode should page past newer unrelated events and match namespaced tags"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn test_bounty_mode_uses_member_tag_snapshot_after_purge() {
|
||||||
|
let (storage, _dir) = test_storage();
|
||||||
|
let tagged = ingest(
|
||||||
|
&storage,
|
||||||
|
"Tagged member that will be purged",
|
||||||
|
&["project:vestige", "composition"],
|
||||||
|
);
|
||||||
|
|
||||||
|
storage
|
||||||
|
.save_composition(
|
||||||
|
&CompositionEventRecord {
|
||||||
|
id: "purged-tagged-member-composition".to_string(),
|
||||||
|
created_at: Utc::now(),
|
||||||
|
tool: "deep_reference".to_string(),
|
||||||
|
mode: "research".to_string(),
|
||||||
|
query: Some("purged tagged lane".to_string()),
|
||||||
|
query_hash: Some("fnv1a64:purged".to_string()),
|
||||||
|
confidence: Some(0.6),
|
||||||
|
status: Some("closed".to_string()),
|
||||||
|
output_preview: None,
|
||||||
|
metadata: serde_json::json!({}),
|
||||||
|
},
|
||||||
|
&[CompositionMemberRecord {
|
||||||
|
event_id: "purged-tagged-member-composition".to_string(),
|
||||||
|
memory_id: tagged.clone(),
|
||||||
|
role: "primary".to_string(),
|
||||||
|
rank: 0,
|
||||||
|
trust: Some(0.7),
|
||||||
|
score: Some(0.8),
|
||||||
|
preview: Some("Tagged member that will be purged".to_string()),
|
||||||
|
metadata: serde_json::json!({}),
|
||||||
|
}],
|
||||||
|
&[CompositionOutcomeRecord {
|
||||||
|
id: "purged-tagged-member-outcome".to_string(),
|
||||||
|
event_id: "purged-tagged-member-composition".to_string(),
|
||||||
|
outcome_type: "closed_by_scope".to_string(),
|
||||||
|
labeled_at: Utc::now(),
|
||||||
|
label_source: "test".to_string(),
|
||||||
|
confidence_delta: Some(-0.2),
|
||||||
|
notes: None,
|
||||||
|
metadata: serde_json::json!({}),
|
||||||
|
}],
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
storage
|
||||||
|
.purge_node(&tagged, Some("test purge"))
|
||||||
|
.expect("purge should succeed");
|
||||||
|
|
||||||
|
let get_result = execute(
|
||||||
|
&storage,
|
||||||
|
Some(serde_json::json!({
|
||||||
|
"action": "get",
|
||||||
|
"event_id": "purged-tagged-member-composition"
|
||||||
|
})),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert!(
|
||||||
|
get_result["members"][0].get("preview").is_none()
|
||||||
|
|| get_result["members"][0]["preview"].is_null(),
|
||||||
|
"purge should scrub member preview from composed_graph get"
|
||||||
|
);
|
||||||
|
|
||||||
|
let bounty = execute(
|
||||||
|
&storage,
|
||||||
|
Some(serde_json::json!({
|
||||||
|
"action": "bounty_mode",
|
||||||
|
"tags": ["project"],
|
||||||
|
"limit": 1
|
||||||
|
})),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
let already = bounty["alreadyComposedLanes"].as_array().unwrap();
|
||||||
|
assert_eq!(already.len(), 1);
|
||||||
|
assert_eq!(
|
||||||
|
already[0]["event"]["id"].as_str(),
|
||||||
|
Some("purged-tagged-member-composition"),
|
||||||
|
"tag-filtered bounty_mode should use composition member tag snapshots after source memory purge"
|
||||||
|
);
|
||||||
|
assert_eq!(bounty["closedDoors"].as_array().unwrap().len(), 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn test_bounty_mode_guardrail_buckets_are_not_truncated_by_already_limit() {
|
||||||
|
let (storage, _dir) = test_storage();
|
||||||
|
let neutral = ingest(&storage, "Neutral release lane", &["project:vestige"]);
|
||||||
|
let closed = ingest(&storage, "Closed release lane", &["project:vestige"]);
|
||||||
|
let base_time = Utc::now();
|
||||||
|
|
||||||
|
storage
|
||||||
|
.save_composition(
|
||||||
|
&CompositionEventRecord {
|
||||||
|
id: "older-closed-lane".to_string(),
|
||||||
|
created_at: base_time,
|
||||||
|
tool: "deep_reference".to_string(),
|
||||||
|
mode: "release".to_string(),
|
||||||
|
query: Some("older closed lane".to_string()),
|
||||||
|
query_hash: Some("fnv1a64:older-closed".to_string()),
|
||||||
|
confidence: Some(0.3),
|
||||||
|
status: Some("closed".to_string()),
|
||||||
|
output_preview: None,
|
||||||
|
metadata: serde_json::json!({}),
|
||||||
|
},
|
||||||
|
&[CompositionMemberRecord {
|
||||||
|
event_id: "older-closed-lane".to_string(),
|
||||||
|
memory_id: closed,
|
||||||
|
role: "primary".to_string(),
|
||||||
|
rank: 0,
|
||||||
|
trust: Some(0.5),
|
||||||
|
score: Some(0.4),
|
||||||
|
preview: None,
|
||||||
|
metadata: serde_json::json!({}),
|
||||||
|
}],
|
||||||
|
&[CompositionOutcomeRecord {
|
||||||
|
id: "older-closed-outcome".to_string(),
|
||||||
|
event_id: "older-closed-lane".to_string(),
|
||||||
|
outcome_type: "closed_by_false_assumption".to_string(),
|
||||||
|
labeled_at: base_time,
|
||||||
|
label_source: "test".to_string(),
|
||||||
|
confidence_delta: Some(-0.3),
|
||||||
|
notes: None,
|
||||||
|
metadata: serde_json::json!({}),
|
||||||
|
}],
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
storage
|
||||||
|
.save_composition(
|
||||||
|
&CompositionEventRecord {
|
||||||
|
id: "newer-neutral-lane".to_string(),
|
||||||
|
created_at: base_time + chrono::Duration::seconds(1),
|
||||||
|
tool: "deep_reference".to_string(),
|
||||||
|
mode: "release".to_string(),
|
||||||
|
query: Some("newer neutral lane".to_string()),
|
||||||
|
query_hash: Some("fnv1a64:newer-neutral".to_string()),
|
||||||
|
confidence: Some(0.7),
|
||||||
|
status: Some("resolved".to_string()),
|
||||||
|
output_preview: None,
|
||||||
|
metadata: serde_json::json!({}),
|
||||||
|
},
|
||||||
|
&[CompositionMemberRecord {
|
||||||
|
event_id: "newer-neutral-lane".to_string(),
|
||||||
|
memory_id: neutral,
|
||||||
|
role: "primary".to_string(),
|
||||||
|
rank: 0,
|
||||||
|
trust: Some(0.8),
|
||||||
|
score: Some(0.8),
|
||||||
|
preview: None,
|
||||||
|
metadata: serde_json::json!({}),
|
||||||
|
}],
|
||||||
|
&[],
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
let bounty = execute(
|
||||||
|
&storage,
|
||||||
|
Some(serde_json::json!({
|
||||||
|
"action": "bounty_mode",
|
||||||
|
"tags": ["project"],
|
||||||
|
"limit": 1
|
||||||
|
})),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
bounty["alreadyComposedLanes"][0]["event"]["id"].as_str(),
|
||||||
|
Some("newer-neutral-lane")
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
bounty["closedDoors"][0]["event"]["id"].as_str(),
|
||||||
|
Some("older-closed-lane"),
|
||||||
|
"guardrail buckets should keep scanning after alreadyComposedLanes reaches limit"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -20,9 +20,10 @@ use serde::Deserialize;
|
||||||
use serde_json::Value;
|
use serde_json::Value;
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
use tokio::sync::Mutex;
|
use tokio::sync::Mutex;
|
||||||
|
use uuid::Uuid;
|
||||||
|
|
||||||
use crate::cognitive::CognitiveEngine;
|
use crate::cognitive::CognitiveEngine;
|
||||||
use vestige_core::Storage;
|
use vestige_core::{CompositionEventRecord, CompositionMemberRecord, Storage};
|
||||||
|
|
||||||
/// Input schema for deep_reference / cross_reference tool
|
/// Input schema for deep_reference / cross_reference tool
|
||||||
pub fn schema() -> Value {
|
pub fn schema() -> Value {
|
||||||
|
|
@ -509,6 +510,7 @@ pub async fn execute(
|
||||||
"confidence": 0.0,
|
"confidence": 0.0,
|
||||||
"guidance": "No memories found. Use smart_ingest to add memories.",
|
"guidance": "No memories found. Use smart_ingest to add memories.",
|
||||||
"memoriesAnalyzed": 0,
|
"memoriesAnalyzed": 0,
|
||||||
|
"compositionWriteStatus": "skipped_empty",
|
||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -820,6 +822,7 @@ pub async fn execute(
|
||||||
"id": s.id,
|
"id": s.id,
|
||||||
"preview": s.content.chars().take(200).collect::<String>(),
|
"preview": s.content.chars().take(200).collect::<String>(),
|
||||||
"trust": (s.trust * 100.0).round() / 100.0,
|
"trust": (s.trust * 100.0).round() / 100.0,
|
||||||
|
"relevanceScore": ((composite(s) * 100.0).round() / 100.0),
|
||||||
"date": s.updated_at.to_rfc3339(),
|
"date": s.updated_at.to_rfc3339(),
|
||||||
"role": if i == 0 { "primary" } else { "supporting" },
|
"role": if i == 0 { "primary" } else { "supporting" },
|
||||||
})
|
})
|
||||||
|
|
@ -925,9 +928,163 @@ pub async fn execute(
|
||||||
response["related_insights"] = serde_json::json!(related_insights);
|
response["related_insights"] = serde_json::json!(related_insights);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
match persist_deep_reference_composition(storage, &args.query, &intent, &response) {
|
||||||
|
Ok(Some(event_id)) => {
|
||||||
|
response["composition_event_id"] = serde_json::json!(event_id);
|
||||||
|
response["compositionWriteStatus"] = serde_json::json!("persisted");
|
||||||
|
}
|
||||||
|
Ok(None) => {
|
||||||
|
response["compositionWriteStatus"] = serde_json::json!("skipped_empty");
|
||||||
|
}
|
||||||
|
Err(err) => {
|
||||||
|
tracing::warn!(
|
||||||
|
"Failed to persist deep_reference composition event: {}",
|
||||||
|
err
|
||||||
|
);
|
||||||
|
response["compositionWriteStatus"] = serde_json::json!("failed");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
Ok(response)
|
Ok(response)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn persist_deep_reference_composition(
|
||||||
|
storage: &Arc<Storage>,
|
||||||
|
query: &str,
|
||||||
|
intent: &QueryIntent,
|
||||||
|
response: &Value,
|
||||||
|
) -> Result<Option<String>, String> {
|
||||||
|
let event_id = Uuid::new_v4().to_string();
|
||||||
|
let event = CompositionEventRecord {
|
||||||
|
id: event_id.clone(),
|
||||||
|
created_at: Utc::now(),
|
||||||
|
tool: "deep_reference".to_string(),
|
||||||
|
mode: "deep_reference".to_string(),
|
||||||
|
query: Some(query.to_string()),
|
||||||
|
query_hash: Some(query_hash(query)),
|
||||||
|
confidence: response.get("confidence").and_then(|v| v.as_f64()),
|
||||||
|
status: response
|
||||||
|
.get("status")
|
||||||
|
.and_then(|v| v.as_str())
|
||||||
|
.map(ToOwned::to_owned),
|
||||||
|
output_preview: response
|
||||||
|
.get("guidance")
|
||||||
|
.and_then(|v| v.as_str())
|
||||||
|
.map(|value| preview_text(value, 280)),
|
||||||
|
metadata: serde_json::json!({
|
||||||
|
"intent": format!("{:?}", intent),
|
||||||
|
"memoriesAnalyzed": response.get("memoriesAnalyzed").and_then(|v| v.as_u64()).unwrap_or(0),
|
||||||
|
"activationExpanded": response.get("activationExpanded").and_then(|v| v.as_u64()).unwrap_or(0),
|
||||||
|
"reasoningPreview": response.get("reasoning").and_then(|v| v.as_str()).map(|value| preview_text(value, 600)),
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
|
||||||
|
let mut members = Vec::new();
|
||||||
|
if let Some(evidence) = response.get("evidence").and_then(|v| v.as_array()) {
|
||||||
|
for (idx, item) in evidence.iter().enumerate() {
|
||||||
|
let Some(memory_id) = item.get("id").and_then(|v| v.as_str()) else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
let role = item
|
||||||
|
.get("role")
|
||||||
|
.and_then(|v| v.as_str())
|
||||||
|
.unwrap_or(if idx == 0 { "primary" } else { "supporting" });
|
||||||
|
members.push(CompositionMemberRecord {
|
||||||
|
event_id: event_id.clone(),
|
||||||
|
memory_id: memory_id.to_string(),
|
||||||
|
role: role.to_string(),
|
||||||
|
rank: idx as i32,
|
||||||
|
trust: item.get("trust").and_then(|v| v.as_f64()),
|
||||||
|
score: item
|
||||||
|
.get("relevanceScore")
|
||||||
|
.or_else(|| item.get("relevance_score"))
|
||||||
|
.and_then(|v| v.as_f64()),
|
||||||
|
preview: None,
|
||||||
|
metadata: serde_json::json!({
|
||||||
|
"roleSource": "deep_reference_evidence",
|
||||||
|
"evidenceRank": idx,
|
||||||
|
"date": item.get("date").and_then(|v| v.as_str()),
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Some(contradictions) = response.get("contradictions").and_then(|v| v.as_array()) {
|
||||||
|
for (idx, contradiction) in contradictions.iter().enumerate() {
|
||||||
|
for side in ["stronger", "weaker"] {
|
||||||
|
let Some(item) = contradiction.get(side) else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
let Some(memory_id) = item.get("id").and_then(|v| v.as_str()) else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
members.push(CompositionMemberRecord {
|
||||||
|
event_id: event_id.clone(),
|
||||||
|
memory_id: memory_id.to_string(),
|
||||||
|
role: "contradicting".to_string(),
|
||||||
|
rank: idx as i32,
|
||||||
|
trust: item.get("trust").and_then(|v| v.as_f64()),
|
||||||
|
score: contradiction.get("topic_overlap").and_then(|v| v.as_f64()),
|
||||||
|
preview: None,
|
||||||
|
metadata: serde_json::json!({
|
||||||
|
"roleSource": "deep_reference_contradiction",
|
||||||
|
"side": side,
|
||||||
|
"date": item.get("date").and_then(|v| v.as_str()),
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Some(superseded) = response.get("superseded").and_then(|v| v.as_array()) {
|
||||||
|
for (idx, item) in superseded.iter().enumerate() {
|
||||||
|
let Some(memory_id) = item.get("id").and_then(|v| v.as_str()) else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
members.push(CompositionMemberRecord {
|
||||||
|
event_id: event_id.clone(),
|
||||||
|
memory_id: memory_id.to_string(),
|
||||||
|
role: "superseded".to_string(),
|
||||||
|
rank: idx as i32,
|
||||||
|
trust: item.get("trust").and_then(|v| v.as_f64()),
|
||||||
|
score: None,
|
||||||
|
preview: None,
|
||||||
|
metadata: serde_json::json!({
|
||||||
|
"roleSource": "deep_reference_superseded",
|
||||||
|
"superseded_by": item.get("superseded_by").and_then(|v| v.as_str()),
|
||||||
|
"date": item.get("date").and_then(|v| v.as_str()),
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if members.is_empty() {
|
||||||
|
return Ok(None);
|
||||||
|
}
|
||||||
|
|
||||||
|
storage
|
||||||
|
.save_composition(&event, &members, &[])
|
||||||
|
.map_err(|e| e.to_string())?;
|
||||||
|
Ok(Some(event_id))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn query_hash(query: &str) -> String {
|
||||||
|
let mut hash = 0xcbf29ce484222325u64;
|
||||||
|
for byte in query.as_bytes() {
|
||||||
|
hash ^= u64::from(*byte);
|
||||||
|
hash = hash.wrapping_mul(0x100000001b3);
|
||||||
|
}
|
||||||
|
format!("fnv1a64:{hash:016x}")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn preview_text(value: &str, max: usize) -> String {
|
||||||
|
let collapsed = value.replace('\n', " ");
|
||||||
|
if collapsed.len() <= max {
|
||||||
|
return collapsed;
|
||||||
|
}
|
||||||
|
format!("{}...", &collapsed[..collapsed.floor_char_boundary(max)])
|
||||||
|
}
|
||||||
|
|
||||||
// ============================================================================
|
// ============================================================================
|
||||||
// TESTS
|
// TESTS
|
||||||
// ============================================================================
|
// ============================================================================
|
||||||
|
|
@ -962,6 +1119,7 @@ mod tests {
|
||||||
tags: tags.iter().map(|s| s.to_string()).collect(),
|
tags: tags.iter().map(|s| s.to_string()).collect(),
|
||||||
valid_from: None,
|
valid_from: None,
|
||||||
valid_until: None,
|
valid_until: None,
|
||||||
|
source_envelope: None,
|
||||||
})
|
})
|
||||||
.unwrap()
|
.unwrap()
|
||||||
.id
|
.id
|
||||||
|
|
@ -1010,6 +1168,99 @@ mod tests {
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn test_deep_reference_persists_composition_event() {
|
||||||
|
let (storage, _dir) = test_storage().await;
|
||||||
|
|
||||||
|
let primary_id = ingest_one(
|
||||||
|
&storage,
|
||||||
|
"ProtocolGate control-plane composition tracks global invariant local gate bypasses.",
|
||||||
|
&["protocolgate", "boundary-scope"],
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
let supporting_id = ingest_one(
|
||||||
|
&storage,
|
||||||
|
"ProtocolGate global invariant local gate research used Aave account-global health factor and route-local validation.",
|
||||||
|
&["protocolgate", "boundary-scope"],
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
|
||||||
|
let result = execute(
|
||||||
|
&storage,
|
||||||
|
&test_cognitive(),
|
||||||
|
Some(serde_json::json!({
|
||||||
|
"query": "ProtocolGate global invariant local gate",
|
||||||
|
"depth": 10
|
||||||
|
})),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.expect("execute should succeed");
|
||||||
|
|
||||||
|
let event_id = result["composition_event_id"]
|
||||||
|
.as_str()
|
||||||
|
.expect("deep_reference should return persisted event id");
|
||||||
|
assert_eq!(result["compositionWriteStatus"].as_str(), Some("persisted"));
|
||||||
|
|
||||||
|
let event = storage
|
||||||
|
.get_composition_event(event_id)
|
||||||
|
.unwrap()
|
||||||
|
.expect("composition event should be stored");
|
||||||
|
assert_eq!(event.tool, "deep_reference");
|
||||||
|
assert_eq!(
|
||||||
|
event.query.as_deref(),
|
||||||
|
Some("ProtocolGate global invariant local gate")
|
||||||
|
);
|
||||||
|
|
||||||
|
let members = storage.get_composition_members(event_id).unwrap();
|
||||||
|
assert!(members.iter().any(|member| member.memory_id == primary_id));
|
||||||
|
assert!(
|
||||||
|
members
|
||||||
|
.iter()
|
||||||
|
.any(|member| member.memory_id == supporting_id)
|
||||||
|
);
|
||||||
|
assert!(members.iter().any(|member| member.role == "primary"));
|
||||||
|
assert!(
|
||||||
|
members.iter().any(|member| {
|
||||||
|
member.memory_id == primary_id
|
||||||
|
&& member.score.is_some()
|
||||||
|
&& member.metadata["roleSource"] == "deep_reference_evidence"
|
||||||
|
}),
|
||||||
|
"persisted members should retain relevance score and role source"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn test_deep_reference_skips_empty_composition_event() {
|
||||||
|
let (storage, _dir) = test_storage().await;
|
||||||
|
|
||||||
|
let result = execute(
|
||||||
|
&storage,
|
||||||
|
&test_cognitive(),
|
||||||
|
Some(serde_json::json!({
|
||||||
|
"query": "no memories exist for this query",
|
||||||
|
"depth": 10
|
||||||
|
})),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.expect("execute should succeed");
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
result["compositionWriteStatus"].as_str(),
|
||||||
|
Some("skipped_empty")
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
result.get("composition_event_id").is_none(),
|
||||||
|
"empty evidence should not create a composition event"
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
storage
|
||||||
|
.get_recent_composition_events(10)
|
||||||
|
.unwrap()
|
||||||
|
.is_empty(),
|
||||||
|
"ledger should stay empty when no memories participated"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
// ========================================================================
|
// ========================================================================
|
||||||
// Confidence sanity: must vary with query relevance.
|
// Confidence sanity: must vary with query relevance.
|
||||||
// ========================================================================
|
// ========================================================================
|
||||||
|
|
|
||||||
|
|
@ -283,6 +283,7 @@ mod tests {
|
||||||
tags: vec!["dream-test".to_string()],
|
tags: vec!["dream-test".to_string()],
|
||||||
valid_from: None,
|
valid_from: None,
|
||||||
valid_until: None,
|
valid_until: None,
|
||||||
|
source_envelope: None,
|
||||||
})
|
})
|
||||||
.unwrap();
|
.unwrap();
|
||||||
}
|
}
|
||||||
|
|
@ -420,6 +421,7 @@ mod tests {
|
||||||
tags: vec!["dream-roundtrip".to_string()],
|
tags: vec!["dream-roundtrip".to_string()],
|
||||||
valid_from: None,
|
valid_from: None,
|
||||||
valid_until: None,
|
valid_until: None,
|
||||||
|
source_envelope: None,
|
||||||
})
|
})
|
||||||
.unwrap();
|
.unwrap();
|
||||||
}
|
}
|
||||||
|
|
@ -485,6 +487,7 @@ mod tests {
|
||||||
tags: vec!["save-conn-test".to_string()],
|
tags: vec!["save-conn-test".to_string()],
|
||||||
valid_from: None,
|
valid_from: None,
|
||||||
valid_until: None,
|
valid_until: None,
|
||||||
|
source_envelope: None,
|
||||||
})
|
})
|
||||||
.unwrap();
|
.unwrap();
|
||||||
ids.push(result.id);
|
ids.push(result.id);
|
||||||
|
|
@ -588,6 +591,7 @@ mod tests {
|
||||||
tags: tags.iter().map(|t| t.to_string()).collect(),
|
tags: tags.iter().map(|t| t.to_string()).collect(),
|
||||||
valid_from: None,
|
valid_from: None,
|
||||||
valid_until: None,
|
valid_until: None,
|
||||||
|
source_envelope: None,
|
||||||
})
|
})
|
||||||
.unwrap();
|
.unwrap();
|
||||||
}
|
}
|
||||||
|
|
@ -713,6 +717,7 @@ mod tests {
|
||||||
tags: tags.iter().map(|t| t.to_string()).collect(),
|
tags: tags.iter().map(|t| t.to_string()).collect(),
|
||||||
valid_from: None,
|
valid_from: None,
|
||||||
valid_until: None,
|
valid_until: None,
|
||||||
|
source_envelope: None,
|
||||||
})
|
})
|
||||||
.unwrap();
|
.unwrap();
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -414,6 +414,7 @@ mod tests {
|
||||||
tags: vec!["test".to_string()],
|
tags: vec!["test".to_string()],
|
||||||
valid_from: None,
|
valid_from: None,
|
||||||
valid_until: None,
|
valid_until: None,
|
||||||
|
source_envelope: None,
|
||||||
})
|
})
|
||||||
.unwrap()
|
.unwrap()
|
||||||
.id;
|
.id;
|
||||||
|
|
@ -428,6 +429,7 @@ mod tests {
|
||||||
tags: vec!["test".to_string()],
|
tags: vec!["test".to_string()],
|
||||||
valid_from: None,
|
valid_from: None,
|
||||||
valid_until: None,
|
valid_until: None,
|
||||||
|
source_envelope: None,
|
||||||
})
|
})
|
||||||
.unwrap()
|
.unwrap()
|
||||||
.id;
|
.id;
|
||||||
|
|
@ -478,6 +480,7 @@ mod tests {
|
||||||
tags: vec!["test".to_string()],
|
tags: vec!["test".to_string()],
|
||||||
valid_from: None,
|
valid_from: None,
|
||||||
valid_until: None,
|
valid_until: None,
|
||||||
|
source_envelope: None,
|
||||||
};
|
};
|
||||||
let id_a = storage.ingest(make("Memory A about databases")).unwrap().id;
|
let id_a = storage.ingest(make("Memory A about databases")).unwrap().id;
|
||||||
let id_b = storage.ingest(make("Memory B about indexes")).unwrap().id;
|
let id_b = storage.ingest(make("Memory B about indexes")).unwrap().id;
|
||||||
|
|
@ -529,6 +532,7 @@ mod tests {
|
||||||
tags: vec!["test".to_string()],
|
tags: vec!["test".to_string()],
|
||||||
valid_from: None,
|
valid_from: None,
|
||||||
valid_until: None,
|
valid_until: None,
|
||||||
|
source_envelope: None,
|
||||||
};
|
};
|
||||||
let id_a = storage.ingest(make("Bridge test memory A")).unwrap().id;
|
let id_a = storage.ingest(make("Bridge test memory A")).unwrap().id;
|
||||||
let id_b = storage.ingest(make("Bridge test memory B")).unwrap().id;
|
let id_b = storage.ingest(make("Bridge test memory B")).unwrap().id;
|
||||||
|
|
|
||||||
|
|
@ -313,6 +313,7 @@ mod tests {
|
||||||
tags: vec![],
|
tags: vec![],
|
||||||
valid_from: None,
|
valid_from: None,
|
||||||
valid_until: None,
|
valid_until: None,
|
||||||
|
source_envelope: None,
|
||||||
})
|
})
|
||||||
.unwrap();
|
.unwrap();
|
||||||
node.id
|
node.id
|
||||||
|
|
@ -556,6 +557,7 @@ mod tests {
|
||||||
tags: vec![],
|
tags: vec![],
|
||||||
valid_from: None,
|
valid_from: None,
|
||||||
valid_until: None,
|
valid_until: None,
|
||||||
|
source_envelope: None,
|
||||||
})
|
})
|
||||||
.unwrap();
|
.unwrap();
|
||||||
let node_id = node.id.clone();
|
let node_id = node.id.clone();
|
||||||
|
|
|
||||||
|
|
@ -328,6 +328,7 @@ mod tests {
|
||||||
tags: vec!["test".to_string()],
|
tags: vec!["test".to_string()],
|
||||||
valid_from: None,
|
valid_from: None,
|
||||||
valid_until: None,
|
valid_until: None,
|
||||||
|
source_envelope: None,
|
||||||
})
|
})
|
||||||
.unwrap();
|
.unwrap();
|
||||||
|
|
||||||
|
|
@ -355,6 +356,7 @@ mod tests {
|
||||||
tags: vec!["science".to_string()],
|
tags: vec!["science".to_string()],
|
||||||
valid_from: None,
|
valid_from: None,
|
||||||
valid_until: None,
|
valid_until: None,
|
||||||
|
source_envelope: None,
|
||||||
})
|
})
|
||||||
.unwrap();
|
.unwrap();
|
||||||
|
|
||||||
|
|
@ -378,6 +380,7 @@ mod tests {
|
||||||
tags: vec![],
|
tags: vec![],
|
||||||
valid_from: None,
|
valid_from: None,
|
||||||
valid_until: None,
|
valid_until: None,
|
||||||
|
source_envelope: None,
|
||||||
})
|
})
|
||||||
.unwrap();
|
.unwrap();
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -119,6 +119,7 @@ mod tests {
|
||||||
tags: vec!["test".to_string()],
|
tags: vec!["test".to_string()],
|
||||||
valid_from: None,
|
valid_from: None,
|
||||||
valid_until: None,
|
valid_until: None,
|
||||||
|
source_envelope: None,
|
||||||
})
|
})
|
||||||
.unwrap();
|
.unwrap();
|
||||||
}
|
}
|
||||||
|
|
@ -144,6 +145,7 @@ mod tests {
|
||||||
tags: vec![],
|
tags: vec![],
|
||||||
valid_from: None,
|
valid_from: None,
|
||||||
valid_until: None,
|
valid_until: None,
|
||||||
|
source_envelope: None,
|
||||||
})
|
})
|
||||||
.unwrap();
|
.unwrap();
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -105,10 +105,24 @@ pub fn gc_schema() -> Value {
|
||||||
pub fn system_status_schema() -> Value {
|
pub fn system_status_schema() -> Value {
|
||||||
serde_json::json!({
|
serde_json::json!({
|
||||||
"type": "object",
|
"type": "object",
|
||||||
"properties": {}
|
"properties": {
|
||||||
|
"schema_introspection": {
|
||||||
|
"type": "boolean",
|
||||||
|
"description": "When true, extends the response with a 'schema' block carrying the SQLite schema version, per-table row counts + column lists, and embedding-coverage convenience fields. Default: false (response shape unchanged). Use this for audit / migration-guard / downstream-upgrade scripts that otherwise have to read SQLite directly.",
|
||||||
|
"default": false
|
||||||
|
}
|
||||||
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Arguments for the system_status tool. All optional.
|
||||||
|
#[derive(Debug, Default, Deserialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
struct SystemStatusArgs {
|
||||||
|
#[serde(alias = "schema_introspection")]
|
||||||
|
schema_introspection: Option<bool>,
|
||||||
|
}
|
||||||
|
|
||||||
// ============================================================================
|
// ============================================================================
|
||||||
// EXECUTE FUNCTIONS
|
// EXECUTE FUNCTIONS
|
||||||
// ============================================================================
|
// ============================================================================
|
||||||
|
|
@ -117,11 +131,23 @@ pub fn system_status_schema() -> Value {
|
||||||
///
|
///
|
||||||
/// Returns system health status, full statistics, FSRS preview,
|
/// Returns system health status, full statistics, FSRS preview,
|
||||||
/// cognitive module health, state distribution, and actionable recommendations.
|
/// cognitive module health, state distribution, and actionable recommendations.
|
||||||
|
///
|
||||||
|
/// v2.1.24+: when `schema_introspection: true` is passed, the response
|
||||||
|
/// additionally carries a `schema` block with the live SQLite schema version,
|
||||||
|
/// per-table row counts + column lists, and embedding-coverage convenience
|
||||||
|
/// fields. Default off; response shape unchanged when omitted.
|
||||||
pub async fn execute_system_status(
|
pub async fn execute_system_status(
|
||||||
storage: &Arc<Storage>,
|
storage: &Arc<Storage>,
|
||||||
cognitive: &Arc<Mutex<CognitiveEngine>>,
|
cognitive: &Arc<Mutex<CognitiveEngine>>,
|
||||||
_args: Option<Value>,
|
args: Option<Value>,
|
||||||
) -> Result<Value, String> {
|
) -> Result<Value, String> {
|
||||||
|
// Parse arguments (all optional, including the args envelope itself).
|
||||||
|
let parsed: SystemStatusArgs = match args {
|
||||||
|
Some(v) => serde_json::from_value(v).map_err(|e| format!("Invalid arguments: {}", e))?,
|
||||||
|
None => SystemStatusArgs::default(),
|
||||||
|
};
|
||||||
|
let include_schema = parsed.schema_introspection.unwrap_or(false);
|
||||||
|
|
||||||
let stats = storage.get_stats().map_err(|e| e.to_string())?;
|
let stats = storage.get_stats().map_err(|e| e.to_string())?;
|
||||||
|
|
||||||
// === Health assessment ===
|
// === Health assessment ===
|
||||||
|
|
@ -259,7 +285,7 @@ pub async fn execute_system_status(
|
||||||
};
|
};
|
||||||
let last_backup = storage.last_backup_timestamp();
|
let last_backup = storage.last_backup_timestamp();
|
||||||
|
|
||||||
Ok(serde_json::json!({
|
let mut response = serde_json::json!({
|
||||||
"tool": "system_status",
|
"tool": "system_status",
|
||||||
// Health
|
// Health
|
||||||
"status": status,
|
"status": status,
|
||||||
|
|
@ -299,7 +325,34 @@ pub async fn execute_system_status(
|
||||||
"lastBackupTimestamp": last_backup.map(|dt| dt.to_rfc3339()),
|
"lastBackupTimestamp": last_backup.map(|dt| dt.to_rfc3339()),
|
||||||
"lastConsolidationTimestamp": last_consolidation.map(|dt| dt.to_rfc3339()),
|
"lastConsolidationTimestamp": last_consolidation.map(|dt| dt.to_rfc3339()),
|
||||||
},
|
},
|
||||||
}))
|
});
|
||||||
|
|
||||||
|
// v2.1.24+: optional schema introspection block. Default off; response
|
||||||
|
// shape unchanged when omitted.
|
||||||
|
if include_schema {
|
||||||
|
let intro = storage.schema_introspection().map_err(|e| e.to_string())?;
|
||||||
|
let tables_json: Vec<Value> = intro
|
||||||
|
.tables
|
||||||
|
.iter()
|
||||||
|
.map(|t| {
|
||||||
|
serde_json::json!({
|
||||||
|
"name": t.name,
|
||||||
|
"rows": t.rows,
|
||||||
|
"columns": t.columns,
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
response["schema"] = serde_json::json!({
|
||||||
|
"schemaVersion": intro.schema_version,
|
||||||
|
"schemaVersionAppliedAt": intro.schema_version_applied_at.map(|dt| dt.to_rfc3339()),
|
||||||
|
"tables": tables_json,
|
||||||
|
"embeddingNullCount": intro.embedding_null_count,
|
||||||
|
"activeEmbeddingModel": intro.active_embedding_model,
|
||||||
|
"activeEmbeddingDimensions": intro.active_embedding_dimensions,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(response)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Consolidate tool
|
/// Consolidate tool
|
||||||
|
|
@ -725,6 +778,7 @@ mod tests {
|
||||||
tags: vec![],
|
tags: vec![],
|
||||||
valid_from: None,
|
valid_from: None,
|
||||||
valid_until: None,
|
valid_until: None,
|
||||||
|
source_envelope: None,
|
||||||
})
|
})
|
||||||
.unwrap();
|
.unwrap();
|
||||||
}
|
}
|
||||||
|
|
@ -779,6 +833,7 @@ mod tests {
|
||||||
tags: vec![],
|
tags: vec![],
|
||||||
valid_from: None,
|
valid_from: None,
|
||||||
valid_until: None,
|
valid_until: None,
|
||||||
|
source_envelope: None,
|
||||||
})
|
})
|
||||||
.unwrap();
|
.unwrap();
|
||||||
}
|
}
|
||||||
|
|
@ -792,6 +847,164 @@ mod tests {
|
||||||
assert!(triggers["lastDreamTimestamp"].is_null());
|
assert!(triggers["lastDreamTimestamp"].is_null());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ========================================================================
|
||||||
|
// SCHEMA INTROSPECTION TESTS (PR2)
|
||||||
|
// ========================================================================
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_system_status_schema_has_schema_introspection_flag() {
|
||||||
|
let schema = system_status_schema();
|
||||||
|
let props = &schema["properties"];
|
||||||
|
let flag = &props["schema_introspection"];
|
||||||
|
assert!(flag.is_object(), "schema_introspection property must exist");
|
||||||
|
assert_eq!(flag["type"], "boolean");
|
||||||
|
assert_eq!(flag["default"], false);
|
||||||
|
// Top-level required must NOT include this — flag is opt-in.
|
||||||
|
let required = schema.get("required");
|
||||||
|
if let Some(req) = required {
|
||||||
|
let req_arr = req.as_array().unwrap();
|
||||||
|
assert!(!req_arr.contains(&serde_json::json!("schema_introspection")));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn test_system_status_without_schema_flag_omits_schema_block() {
|
||||||
|
// Backwards-compat: when the flag is not set (or false), the response
|
||||||
|
// shape is unchanged — no `schema` key.
|
||||||
|
let (storage, _dir) = test_storage().await;
|
||||||
|
let result = execute_system_status(&storage, &test_cognitive(), None).await;
|
||||||
|
assert!(result.is_ok());
|
||||||
|
let value = result.unwrap();
|
||||||
|
assert!(
|
||||||
|
value.get("schema").is_none(),
|
||||||
|
"schema block must NOT be present when flag is unset, got {:?}",
|
||||||
|
value.get("schema")
|
||||||
|
);
|
||||||
|
|
||||||
|
// Explicit false → still no schema block.
|
||||||
|
let result = execute_system_status(
|
||||||
|
&storage,
|
||||||
|
&test_cognitive(),
|
||||||
|
Some(serde_json::json!({ "schema_introspection": false })),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert!(result.is_ok());
|
||||||
|
let value = result.unwrap();
|
||||||
|
assert!(value.get("schema").is_none());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn test_system_status_with_schema_flag_emits_schema_block() {
|
||||||
|
let (storage, _dir) = test_storage().await;
|
||||||
|
storage
|
||||||
|
.ingest(vestige_core::IngestInput {
|
||||||
|
content: "Schema introspection seed memory".to_string(),
|
||||||
|
node_type: "fact".to_string(),
|
||||||
|
source: None,
|
||||||
|
sentiment_score: 0.0,
|
||||||
|
sentiment_magnitude: 0.0,
|
||||||
|
tags: vec!["schema-test".to_string()],
|
||||||
|
valid_from: None,
|
||||||
|
valid_until: None,
|
||||||
|
source_envelope: None,
|
||||||
|
})
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
let result = execute_system_status(
|
||||||
|
&storage,
|
||||||
|
&test_cognitive(),
|
||||||
|
Some(serde_json::json!({ "schema_introspection": true })),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert!(result.is_ok(), "{:?}", result);
|
||||||
|
let value = result.unwrap();
|
||||||
|
|
||||||
|
// Shape assertions.
|
||||||
|
let schema_block = value
|
||||||
|
.get("schema")
|
||||||
|
.expect("schema block must be present when flag is true");
|
||||||
|
assert!(schema_block.is_object());
|
||||||
|
assert!(
|
||||||
|
schema_block["schemaVersion"].is_number(),
|
||||||
|
"schemaVersion must be a number, got {:?}",
|
||||||
|
schema_block["schemaVersion"]
|
||||||
|
);
|
||||||
|
// Schema version should be >= 13 (V13 is the highest landed migration
|
||||||
|
// at the time this PR was authored).
|
||||||
|
let v = schema_block["schemaVersion"].as_u64().unwrap();
|
||||||
|
assert!(v >= 13, "expected schema_version >= 13, got {}", v);
|
||||||
|
|
||||||
|
// tables should be a non-empty array of {name, rows, columns}.
|
||||||
|
let tables = schema_block["tables"].as_array().unwrap();
|
||||||
|
assert!(!tables.is_empty(), "expected at least one table");
|
||||||
|
let kn = tables
|
||||||
|
.iter()
|
||||||
|
.find(|t| t["name"] == "knowledge_nodes")
|
||||||
|
.expect("knowledge_nodes table must be present");
|
||||||
|
assert_eq!(kn["rows"], 1, "ingested exactly one memory");
|
||||||
|
let cols = kn["columns"].as_array().unwrap();
|
||||||
|
assert!(!cols.is_empty(), "knowledge_nodes must have columns");
|
||||||
|
// The id column is universally present.
|
||||||
|
let col_names: Vec<&str> = cols.iter().filter_map(|c| c.as_str()).collect();
|
||||||
|
assert!(
|
||||||
|
col_names.contains(&"id"),
|
||||||
|
"knowledge_nodes.id must be in columns list: {:?}",
|
||||||
|
col_names
|
||||||
|
);
|
||||||
|
|
||||||
|
// Convenience fields.
|
||||||
|
assert!(schema_block["embeddingNullCount"].is_number());
|
||||||
|
// activeEmbeddingModel may be null if the `embeddings` feature is
|
||||||
|
// not enabled in the test build; just check the key exists.
|
||||||
|
assert!(schema_block.get("activeEmbeddingModel").is_some());
|
||||||
|
assert!(schema_block.get("activeEmbeddingDimensions").is_some());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn test_system_status_camelcase_alias() {
|
||||||
|
// Accept both `schema_introspection` (snake) and `schemaIntrospection`
|
||||||
|
// (camel) per the #[serde(rename_all = "camelCase")] + alias attr.
|
||||||
|
let (storage, _dir) = test_storage().await;
|
||||||
|
let result = execute_system_status(
|
||||||
|
&storage,
|
||||||
|
&test_cognitive(),
|
||||||
|
Some(serde_json::json!({ "schemaIntrospection": true })),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert!(result.is_ok(), "{:?}", result);
|
||||||
|
let value = result.unwrap();
|
||||||
|
assert!(
|
||||||
|
value.get("schema").is_some(),
|
||||||
|
"camelCase form must also trigger schema block"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_storage_schema_introspection_method() {
|
||||||
|
// Direct test on the Storage method, independent of the MCP layer.
|
||||||
|
let dir = TempDir::new().unwrap();
|
||||||
|
let storage = Storage::new(Some(dir.path().join("test.db"))).unwrap();
|
||||||
|
let intro = storage
|
||||||
|
.schema_introspection()
|
||||||
|
.expect("schema_introspection must succeed on a fresh DB");
|
||||||
|
|
||||||
|
// Schema version pulled from the schema_version table.
|
||||||
|
assert!(
|
||||||
|
intro.schema_version >= 13,
|
||||||
|
"fresh DB should be at schema_version >= 13, got {}",
|
||||||
|
intro.schema_version
|
||||||
|
);
|
||||||
|
// At least one walked table should exist.
|
||||||
|
assert!(
|
||||||
|
!intro.tables.is_empty(),
|
||||||
|
"expected at least one user-data table"
|
||||||
|
);
|
||||||
|
// Empty DB → no embeddings → embedding_null_count == 0 (no rows to
|
||||||
|
// count). Once we ingest, it should be > 0 (no embeddings generated
|
||||||
|
// in tests by default).
|
||||||
|
assert_eq!(intro.embedding_null_count, 0);
|
||||||
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn test_portable_export_writes_archive_to_storage_exports_dir() {
|
async fn test_portable_export_writes_archive_to_storage_exports_dir() {
|
||||||
let (storage, _dir) = test_storage().await;
|
let (storage, _dir) = test_storage().await;
|
||||||
|
|
@ -805,6 +1018,7 @@ mod tests {
|
||||||
tags: vec!["portable".to_string()],
|
tags: vec!["portable".to_string()],
|
||||||
valid_from: None,
|
valid_from: None,
|
||||||
valid_until: None,
|
valid_until: None,
|
||||||
|
source_envelope: None,
|
||||||
})
|
})
|
||||||
.unwrap();
|
.unwrap();
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -552,6 +552,7 @@ mod tests {
|
||||||
tags: vec!["test-tag".to_string()],
|
tags: vec!["test-tag".to_string()],
|
||||||
valid_from: None,
|
valid_from: None,
|
||||||
valid_until: None,
|
valid_until: None,
|
||||||
|
source_envelope: None,
|
||||||
})
|
})
|
||||||
.unwrap();
|
.unwrap();
|
||||||
node.id
|
node.id
|
||||||
|
|
|
||||||
541
crates/vestige-mcp/src/tools/merge.rs
Normal file
541
crates/vestige-mcp/src/tools/merge.rs
Normal file
|
|
@ -0,0 +1,541 @@
|
||||||
|
//! Merge / Supersede control tools (Phase 3 — v2.1.25)
|
||||||
|
//!
|
||||||
|
//! Diff-previewed, confidence-gated, reversible, self-explaining
|
||||||
|
//! combine/dedupe/supersede on a never-delete (bitemporal) store. The default
|
||||||
|
//! is always preview/review — these tools never silently mutate memory.
|
||||||
|
//!
|
||||||
|
//! Tool surface (each registered as its own MCP tool name, all routed here):
|
||||||
|
//!
|
||||||
|
//! - `merge_candidates` — surface likely duplicate clusters with confidence +
|
||||||
|
//! the signals behind each (Fellegi-Sunter match / possible / non-match).
|
||||||
|
//! - `plan_merge` — previewable merge PLAN (a diff) without applying it.
|
||||||
|
//! - `plan_supersede` — preview superseding A with B (bitemporal invalidation,
|
||||||
|
//! audit-preserving) without applying.
|
||||||
|
//! - `apply_plan` — execute a previously-generated plan id; recorded as a
|
||||||
|
//! reversible operation.
|
||||||
|
//! - `merge_undo` — reverse a prior merge/supersede operation (the reflog).
|
||||||
|
//! - `protect` — pin a memory so it can never be auto-merged/superseded/forgotten.
|
||||||
|
//! - `merge_policy` — get/set the two confidence thresholds + auto_apply.
|
||||||
|
//!
|
||||||
|
//! The actual logic lives in `vestige_core` (`storage::Storage` +
|
||||||
|
//! `advanced::merge_supersede`); this layer only validates arguments and shapes
|
||||||
|
//! JSON.
|
||||||
|
|
||||||
|
use serde_json::{Value, json};
|
||||||
|
use std::sync::Arc;
|
||||||
|
use vestige_core::Storage;
|
||||||
|
|
||||||
|
// ============================================================================
|
||||||
|
// SCHEMAS
|
||||||
|
// ============================================================================
|
||||||
|
|
||||||
|
/// `merge_candidates` input schema.
|
||||||
|
pub fn merge_candidates_schema() -> Value {
|
||||||
|
json!({
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"limit": {
|
||||||
|
"type": "integer",
|
||||||
|
"description": "Max candidate clusters to return (default 20).",
|
||||||
|
"default": 20, "minimum": 1, "maximum": 100
|
||||||
|
},
|
||||||
|
"tags": {
|
||||||
|
"type": "array",
|
||||||
|
"items": { "type": "string" },
|
||||||
|
"description": "Optional: only consider memories with these tags (ANY match)."
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `plan_merge` input schema.
|
||||||
|
pub fn plan_merge_schema() -> Value {
|
||||||
|
json!({
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"member_ids": {
|
||||||
|
"type": "array",
|
||||||
|
"items": { "type": "string" },
|
||||||
|
"description": "IDs of the memories to merge (>= 2). The survivor is kept; the rest are bitemporally invalidated (kept for audit)."
|
||||||
|
},
|
||||||
|
"survivor_id": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "Optional: which member to keep. Defaults to the highest-retention member."
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": ["member_ids"]
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `plan_supersede` input schema.
|
||||||
|
pub fn plan_supersede_schema() -> Value {
|
||||||
|
json!({
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"old_id": { "type": "string", "description": "Memory being superseded (kept, marked invalid)." },
|
||||||
|
"new_id": { "type": "string", "description": "Memory that supersedes the old one." }
|
||||||
|
},
|
||||||
|
"required": ["old_id", "new_id"]
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `apply_plan` input schema.
|
||||||
|
pub fn apply_plan_schema() -> Value {
|
||||||
|
json!({
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"plan_id": { "type": "string", "description": "ID of a plan produced by plan_merge / plan_supersede." },
|
||||||
|
"confirm": {
|
||||||
|
"type": "boolean",
|
||||||
|
"description": "Required true for 'possible'/'non_match' plans. 'match' plans apply only if the policy has auto_apply=true, else confirm is required too.",
|
||||||
|
"default": false
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": ["plan_id"]
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `merge_undo` input schema.
|
||||||
|
pub fn merge_undo_schema() -> Value {
|
||||||
|
json!({
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"operation_id": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "ID of the merge/supersede operation to reverse. Omit to list recent operations (the reflog)."
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `protect` input schema.
|
||||||
|
pub fn protect_schema() -> Value {
|
||||||
|
json!({
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"id": { "type": "string", "description": "Memory id to protect/unprotect." },
|
||||||
|
"protected": {
|
||||||
|
"type": "boolean",
|
||||||
|
"description": "true to pin (block auto-merge/supersede/forget), false to unpin. Default true.",
|
||||||
|
"default": true
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": ["id"]
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `merge_policy` input schema.
|
||||||
|
pub fn merge_policy_schema() -> Value {
|
||||||
|
json!({
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"match_threshold": {
|
||||||
|
"type": "number",
|
||||||
|
"description": "Score >= this => 'match' (auto-merge eligible). 0-1.",
|
||||||
|
"minimum": 0.0, "maximum": 1.0
|
||||||
|
},
|
||||||
|
"possible_threshold": {
|
||||||
|
"type": "number",
|
||||||
|
"description": "Score in [possible, match) => 'possible' (review). Below => not offered. 0-1.",
|
||||||
|
"minimum": 0.0, "maximum": 1.0
|
||||||
|
},
|
||||||
|
"auto_apply": {
|
||||||
|
"type": "boolean",
|
||||||
|
"description": "Allow 'match'-class plans to apply without confirm. Default false (review-first)."
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// ============================================================================
|
||||||
|
// DISPATCH
|
||||||
|
// ============================================================================
|
||||||
|
|
||||||
|
/// Route a merge/supersede tool call by tool name.
|
||||||
|
pub async fn execute(
|
||||||
|
storage: &Arc<Storage>,
|
||||||
|
tool: &str,
|
||||||
|
args: Option<Value>,
|
||||||
|
) -> Result<Value, String> {
|
||||||
|
match tool {
|
||||||
|
"merge_candidates" => merge_candidates(storage, args),
|
||||||
|
"plan_merge" => plan_merge(storage, args),
|
||||||
|
"plan_supersede" => plan_supersede(storage, args),
|
||||||
|
"apply_plan" => apply_plan(storage, args),
|
||||||
|
"merge_undo" => merge_undo(storage, args),
|
||||||
|
"protect" => protect(storage, args),
|
||||||
|
"merge_policy" => merge_policy(storage, args),
|
||||||
|
other => Err(format!("unknown merge tool: {other}")),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn obj(args: &Option<Value>) -> serde_json::Map<String, Value> {
|
||||||
|
args.as_ref()
|
||||||
|
.and_then(|v| v.as_object().cloned())
|
||||||
|
.unwrap_or_default()
|
||||||
|
}
|
||||||
|
|
||||||
|
// ============================================================================
|
||||||
|
// merge_candidates
|
||||||
|
// ============================================================================
|
||||||
|
|
||||||
|
fn merge_candidates(storage: &Arc<Storage>, args: Option<Value>) -> Result<Value, String> {
|
||||||
|
#[cfg(all(feature = "embeddings", feature = "vector-search"))]
|
||||||
|
{
|
||||||
|
let a = obj(&args);
|
||||||
|
let limit = a.get("limit").and_then(|v| v.as_u64()).unwrap_or(20) as usize;
|
||||||
|
let tags: Vec<String> = a
|
||||||
|
.get("tags")
|
||||||
|
.and_then(|v| v.as_array())
|
||||||
|
.map(|arr| {
|
||||||
|
arr.iter()
|
||||||
|
.filter_map(|t| t.as_str().map(|s| s.to_string()))
|
||||||
|
.collect()
|
||||||
|
})
|
||||||
|
.unwrap_or_default();
|
||||||
|
|
||||||
|
let policy = storage.get_merge_policy().map_err(|e| e.to_string())?;
|
||||||
|
let candidates = storage
|
||||||
|
.merge_candidates(policy, limit, &tags)
|
||||||
|
.map_err(|e| e.to_string())?;
|
||||||
|
|
||||||
|
let out: Vec<Value> = candidates
|
||||||
|
.iter()
|
||||||
|
.map(|c| {
|
||||||
|
json!({
|
||||||
|
"memberIds": c.member_ids,
|
||||||
|
"previews": c.previews,
|
||||||
|
"survivorId": c.survivor_id,
|
||||||
|
"confidence": format!("{:.3}", c.confidence),
|
||||||
|
"classification": c.classification.as_str(),
|
||||||
|
"hasProtectedMember": c.has_protected_member,
|
||||||
|
"signals": {
|
||||||
|
"embeddingSimilarity": format!("{:.3}", c.signals.embedding_similarity),
|
||||||
|
"tagOverlap": format!("{:.3}", c.signals.tag_overlap),
|
||||||
|
"tokenOverlap": format!("{:.3}", c.signals.token_overlap),
|
||||||
|
"combinedScore": format!("{:.3}", c.signals.combined_score)
|
||||||
|
},
|
||||||
|
"nextStep": if c.has_protected_member {
|
||||||
|
"A member is protected — unprotect it or pick it as survivor before plan_merge."
|
||||||
|
} else {
|
||||||
|
"Call plan_merge with these memberIds to preview the combined result."
|
||||||
|
}
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
let policy = storage.get_merge_policy().map_err(|e| e.to_string())?;
|
||||||
|
Ok(json!({
|
||||||
|
"candidates": out,
|
||||||
|
"totalCandidates": out.len(),
|
||||||
|
"policy": {
|
||||||
|
"matchThreshold": policy.match_threshold,
|
||||||
|
"possibleThreshold": policy.possible_threshold,
|
||||||
|
"autoApply": policy.auto_apply
|
||||||
|
},
|
||||||
|
"note": "Nothing was changed. These are review candidates only."
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
#[cfg(not(all(feature = "embeddings", feature = "vector-search")))]
|
||||||
|
{
|
||||||
|
let _ = (storage, args);
|
||||||
|
Ok(json!({ "error": "Embeddings feature not enabled.", "candidates": [] }))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ============================================================================
|
||||||
|
// plan_merge
|
||||||
|
// ============================================================================
|
||||||
|
|
||||||
|
fn plan_merge(storage: &Arc<Storage>, args: Option<Value>) -> Result<Value, String> {
|
||||||
|
#[cfg(all(feature = "embeddings", feature = "vector-search"))]
|
||||||
|
{
|
||||||
|
let a = obj(&args);
|
||||||
|
let member_ids: Vec<String> = a
|
||||||
|
.get("member_ids")
|
||||||
|
.and_then(|v| v.as_array())
|
||||||
|
.map(|arr| {
|
||||||
|
arr.iter()
|
||||||
|
.filter_map(|t| t.as_str().map(|s| s.to_string()))
|
||||||
|
.collect()
|
||||||
|
})
|
||||||
|
.unwrap_or_default();
|
||||||
|
if member_ids.len() < 2 {
|
||||||
|
return Err("member_ids must contain at least 2 ids".into());
|
||||||
|
}
|
||||||
|
let survivor = a.get("survivor_id").and_then(|v| v.as_str());
|
||||||
|
let policy = storage.get_merge_policy().map_err(|e| e.to_string())?;
|
||||||
|
let plan = storage
|
||||||
|
.plan_merge(&member_ids, survivor, policy)
|
||||||
|
.map_err(|e| e.to_string())?;
|
||||||
|
Ok(plan_to_json(&plan, &policy))
|
||||||
|
}
|
||||||
|
#[cfg(not(all(feature = "embeddings", feature = "vector-search")))]
|
||||||
|
{
|
||||||
|
let _ = (storage, args);
|
||||||
|
Err("Embeddings feature not enabled.".into())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ============================================================================
|
||||||
|
// plan_supersede
|
||||||
|
// ============================================================================
|
||||||
|
|
||||||
|
fn plan_supersede(storage: &Arc<Storage>, args: Option<Value>) -> Result<Value, String> {
|
||||||
|
#[cfg(all(feature = "embeddings", feature = "vector-search"))]
|
||||||
|
{
|
||||||
|
let a = obj(&args);
|
||||||
|
let old_id = a
|
||||||
|
.get("old_id")
|
||||||
|
.and_then(|v| v.as_str())
|
||||||
|
.ok_or("old_id is required")?;
|
||||||
|
let new_id = a
|
||||||
|
.get("new_id")
|
||||||
|
.and_then(|v| v.as_str())
|
||||||
|
.ok_or("new_id is required")?;
|
||||||
|
let policy = storage.get_merge_policy().map_err(|e| e.to_string())?;
|
||||||
|
let plan = storage
|
||||||
|
.plan_supersede(old_id, new_id, policy)
|
||||||
|
.map_err(|e| e.to_string())?;
|
||||||
|
Ok(plan_to_json(&plan, &policy))
|
||||||
|
}
|
||||||
|
#[cfg(not(all(feature = "embeddings", feature = "vector-search")))]
|
||||||
|
{
|
||||||
|
let _ = (storage, args);
|
||||||
|
Err("Embeddings feature not enabled.".into())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(all(feature = "embeddings", feature = "vector-search"))]
|
||||||
|
fn plan_to_json(plan: &vestige_core::MergePlan, policy: &vestige_core::MergePolicy) -> Value {
|
||||||
|
let requires_confirm =
|
||||||
|
plan.classification != vestige_core::MatchClass::Match || !policy.auto_apply;
|
||||||
|
json!({
|
||||||
|
"planId": plan.id,
|
||||||
|
"kind": plan.kind.as_str(),
|
||||||
|
"survivorId": plan.survivor_id,
|
||||||
|
"memberIds": plan.member_ids,
|
||||||
|
"diff": {
|
||||||
|
"resultContent": plan.result_content,
|
||||||
|
"resultTags": plan.result_tags,
|
||||||
|
"resultSource": plan.result_source,
|
||||||
|
"invalidatedIds": plan.invalidated_ids
|
||||||
|
},
|
||||||
|
"confidence": format!("{:.3}", plan.confidence),
|
||||||
|
"classification": plan.classification.as_str(),
|
||||||
|
"signals": {
|
||||||
|
"embeddingSimilarity": format!("{:.3}", plan.signals.embedding_similarity),
|
||||||
|
"tagOverlap": format!("{:.3}", plan.signals.tag_overlap),
|
||||||
|
"tokenOverlap": format!("{:.3}", plan.signals.token_overlap),
|
||||||
|
"combinedScore": format!("{:.3}", plan.signals.combined_score)
|
||||||
|
},
|
||||||
|
"explanation": plan.explanation,
|
||||||
|
"requiresConfirm": requires_confirm,
|
||||||
|
"nextStep": format!(
|
||||||
|
"Review the diff. To execute: apply_plan with plan_id='{}'{}.",
|
||||||
|
plan.id,
|
||||||
|
if requires_confirm { " and confirm=true" } else { "" }
|
||||||
|
),
|
||||||
|
"note": "Nothing was changed. This is a preview plan — apply_plan applies it; merge_undo reverses it."
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// ============================================================================
|
||||||
|
// apply_plan
|
||||||
|
// ============================================================================
|
||||||
|
|
||||||
|
fn apply_plan(storage: &Arc<Storage>, args: Option<Value>) -> Result<Value, String> {
|
||||||
|
#[cfg(all(feature = "embeddings", feature = "vector-search"))]
|
||||||
|
{
|
||||||
|
let a = obj(&args);
|
||||||
|
let plan_id = a
|
||||||
|
.get("plan_id")
|
||||||
|
.and_then(|v| v.as_str())
|
||||||
|
.ok_or("plan_id is required")?;
|
||||||
|
let confirm = a.get("confirm").and_then(|v| v.as_bool()).unwrap_or(false);
|
||||||
|
let op = storage
|
||||||
|
.apply_plan(plan_id, confirm)
|
||||||
|
.map_err(|e| e.to_string())?;
|
||||||
|
Ok(json!({
|
||||||
|
"operationId": op.id,
|
||||||
|
"opType": op.op_type,
|
||||||
|
"status": op.status,
|
||||||
|
"survivorId": op.survivor_id,
|
||||||
|
"affectedIds": op.affected_ids,
|
||||||
|
"reason": op.reason,
|
||||||
|
"appliedAt": op.created_at,
|
||||||
|
"reversible": true,
|
||||||
|
"nextStep": format!("To reverse this, call merge_undo with operation_id='{}'.", op.id),
|
||||||
|
"note": "Old memories were bitemporally invalidated (valid_until stamped), NOT deleted. They remain queryable for audit."
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
#[cfg(not(all(feature = "embeddings", feature = "vector-search")))]
|
||||||
|
{
|
||||||
|
let _ = (storage, args);
|
||||||
|
Err("Embeddings feature not enabled.".into())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ============================================================================
|
||||||
|
// merge_undo (also lists the reflog when no id given)
|
||||||
|
// ============================================================================
|
||||||
|
|
||||||
|
fn merge_undo(storage: &Arc<Storage>, args: Option<Value>) -> Result<Value, String> {
|
||||||
|
#[cfg(all(feature = "embeddings", feature = "vector-search"))]
|
||||||
|
{
|
||||||
|
let a = obj(&args);
|
||||||
|
match a.get("operation_id").and_then(|v| v.as_str()) {
|
||||||
|
Some(op_id) => {
|
||||||
|
let op = storage.merge_undo(op_id).map_err(|e| e.to_string())?;
|
||||||
|
Ok(json!({
|
||||||
|
"undoOperationId": op.id,
|
||||||
|
"revertedOperationId": op.reverts_op_id,
|
||||||
|
"status": "reverted",
|
||||||
|
"affectedIds": op.affected_ids,
|
||||||
|
"reason": op.reason,
|
||||||
|
"note": "The original operation was reversed: survivor content/tags restored and invalidation cleared. The plan is re-openable."
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
None => {
|
||||||
|
// No id => return the reflog so the caller can pick one.
|
||||||
|
let ops = storage
|
||||||
|
.list_merge_operations(20)
|
||||||
|
.map_err(|e| e.to_string())?;
|
||||||
|
let log: Vec<Value> = ops
|
||||||
|
.iter()
|
||||||
|
.map(|op| {
|
||||||
|
json!({
|
||||||
|
"operationId": op.id,
|
||||||
|
"opType": op.op_type,
|
||||||
|
"status": op.status,
|
||||||
|
"survivorId": op.survivor_id,
|
||||||
|
"affectedIds": op.affected_ids,
|
||||||
|
"confidence": op.confidence.map(|c| format!("{:.3}", c)),
|
||||||
|
"reason": op.reason,
|
||||||
|
"createdAt": op.created_at,
|
||||||
|
"revertedAt": op.reverted_at
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
Ok(json!({
|
||||||
|
"operations": log,
|
||||||
|
"totalOperations": log.len(),
|
||||||
|
"note": "This is the reversible operation log (the memory reflog). Pass operation_id to reverse one."
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#[cfg(not(all(feature = "embeddings", feature = "vector-search")))]
|
||||||
|
{
|
||||||
|
let _ = (storage, args);
|
||||||
|
Err("Embeddings feature not enabled.".into())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ============================================================================
|
||||||
|
// protect
|
||||||
|
// ============================================================================
|
||||||
|
|
||||||
|
fn protect(storage: &Arc<Storage>, args: Option<Value>) -> Result<Value, String> {
|
||||||
|
let a = obj(&args);
|
||||||
|
let id = a
|
||||||
|
.get("id")
|
||||||
|
.and_then(|v| v.as_str())
|
||||||
|
.ok_or("id is required")?;
|
||||||
|
let protected = a.get("protected").and_then(|v| v.as_bool()).unwrap_or(true);
|
||||||
|
storage
|
||||||
|
.set_protected(id, protected)
|
||||||
|
.map_err(|e| e.to_string())?;
|
||||||
|
Ok(json!({
|
||||||
|
"id": id,
|
||||||
|
"protected": protected,
|
||||||
|
"note": if protected {
|
||||||
|
"Memory pinned. It can never be auto-merged, superseded, or garbage-collected until unprotected."
|
||||||
|
} else {
|
||||||
|
"Memory unprotected. It is now eligible for merge/supersede/forget again."
|
||||||
|
}
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
// ============================================================================
|
||||||
|
// merge_policy (get when no args, set otherwise)
|
||||||
|
// ============================================================================
|
||||||
|
|
||||||
|
fn merge_policy(storage: &Arc<Storage>, args: Option<Value>) -> Result<Value, String> {
|
||||||
|
let a = obj(&args);
|
||||||
|
let current = storage.get_merge_policy().map_err(|e| e.to_string())?;
|
||||||
|
|
||||||
|
let has_update = a.contains_key("match_threshold")
|
||||||
|
|| a.contains_key("possible_threshold")
|
||||||
|
|| a.contains_key("auto_apply");
|
||||||
|
|
||||||
|
if has_update {
|
||||||
|
let match_t = a
|
||||||
|
.get("match_threshold")
|
||||||
|
.and_then(|v| v.as_f64())
|
||||||
|
.map(|v| v as f32)
|
||||||
|
.unwrap_or(current.match_threshold);
|
||||||
|
let possible_t = a
|
||||||
|
.get("possible_threshold")
|
||||||
|
.and_then(|v| v.as_f64())
|
||||||
|
.map(|v| v as f32)
|
||||||
|
.unwrap_or(current.possible_threshold);
|
||||||
|
let auto = a
|
||||||
|
.get("auto_apply")
|
||||||
|
.and_then(|v| v.as_bool())
|
||||||
|
.unwrap_or(current.auto_apply);
|
||||||
|
let policy = vestige_core::MergePolicy::new(match_t, possible_t, auto);
|
||||||
|
storage
|
||||||
|
.set_merge_policy(policy)
|
||||||
|
.map_err(|e| e.to_string())?;
|
||||||
|
Ok(json!({
|
||||||
|
"updated": true,
|
||||||
|
"matchThreshold": policy.match_threshold,
|
||||||
|
"possibleThreshold": policy.possible_threshold,
|
||||||
|
"autoApply": policy.auto_apply,
|
||||||
|
"note": "Policy saved. Fellegi-Sunter: score>=match => auto-merge eligible; [possible,match) => review; below => not offered."
|
||||||
|
}))
|
||||||
|
} else {
|
||||||
|
Ok(json!({
|
||||||
|
"matchThreshold": current.match_threshold,
|
||||||
|
"possibleThreshold": current.possible_threshold,
|
||||||
|
"autoApply": current.auto_apply,
|
||||||
|
"note": "Two-threshold merge policy. Pass match_threshold / possible_threshold / auto_apply to change it."
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ============================================================================
|
||||||
|
// TESTS — see tests/merge_supersede_test.rs for full integration coverage.
|
||||||
|
// ============================================================================
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn schemas_are_objects() {
|
||||||
|
for s in [
|
||||||
|
merge_candidates_schema(),
|
||||||
|
plan_merge_schema(),
|
||||||
|
plan_supersede_schema(),
|
||||||
|
apply_plan_schema(),
|
||||||
|
merge_undo_schema(),
|
||||||
|
protect_schema(),
|
||||||
|
merge_policy_schema(),
|
||||||
|
] {
|
||||||
|
assert_eq!(s["type"], "object");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn plan_merge_requires_two_ids() {
|
||||||
|
assert!(
|
||||||
|
plan_merge_schema()["required"]
|
||||||
|
.as_array()
|
||||||
|
.unwrap()
|
||||||
|
.iter()
|
||||||
|
.any(|v| v == "member_ids")
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -12,6 +12,8 @@ pub mod intention_unified;
|
||||||
pub mod memory_unified;
|
pub mod memory_unified;
|
||||||
pub mod search_unified;
|
pub mod search_unified;
|
||||||
pub mod smart_ingest;
|
pub mod smart_ingest;
|
||||||
|
// #57: external-source connectors (GitHub Issues / Redmine retrieval layer)
|
||||||
|
pub mod source_sync;
|
||||||
|
|
||||||
// v1.2: Temporal query tools
|
// v1.2: Temporal query tools
|
||||||
pub mod changelog;
|
pub mod changelog;
|
||||||
|
|
@ -24,6 +26,9 @@ pub mod maintenance;
|
||||||
pub mod dedup;
|
pub mod dedup;
|
||||||
pub mod importance;
|
pub mod importance;
|
||||||
|
|
||||||
|
// v2.1.25: Merge / Supersede controls (Phase 3)
|
||||||
|
pub mod merge;
|
||||||
|
|
||||||
// v1.5: Cognitive tools
|
// v1.5: Cognitive tools
|
||||||
pub mod dream;
|
pub mod dream;
|
||||||
pub mod explore;
|
pub mod explore;
|
||||||
|
|
@ -38,6 +43,7 @@ pub mod graph;
|
||||||
pub mod health;
|
pub mod health;
|
||||||
|
|
||||||
// v2.1: Cross-reference (connect the dots)
|
// v2.1: Cross-reference (connect the dots)
|
||||||
|
pub mod composed_graph;
|
||||||
pub mod contradictions;
|
pub mod contradictions;
|
||||||
pub mod cross_reference;
|
pub mod cross_reference;
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -173,6 +173,7 @@ pub async fn execute(storage: &Arc<Storage>, args: Option<Value>) -> Result<Valu
|
||||||
tags: memory.tags.clone().unwrap_or_default(),
|
tags: memory.tags.clone().unwrap_or_default(),
|
||||||
valid_from: None,
|
valid_from: None,
|
||||||
valid_until: None,
|
valid_until: None,
|
||||||
|
source_envelope: None,
|
||||||
};
|
};
|
||||||
|
|
||||||
match storage.ingest(input) {
|
match storage.ingest(input) {
|
||||||
|
|
@ -349,6 +350,7 @@ mod tests {
|
||||||
tags: vec!["portable".to_string()],
|
tags: vec!["portable".to_string()],
|
||||||
valid_from: None,
|
valid_from: None,
|
||||||
valid_until: None,
|
valid_until: None,
|
||||||
|
source_envelope: None,
|
||||||
})
|
})
|
||||||
.unwrap();
|
.unwrap();
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -117,6 +117,7 @@ mod tests {
|
||||||
tags: vec![],
|
tags: vec![],
|
||||||
valid_from: None,
|
valid_from: None,
|
||||||
valid_until: None,
|
valid_until: None,
|
||||||
|
source_envelope: None,
|
||||||
};
|
};
|
||||||
let node = storage.ingest(input).unwrap();
|
let node = storage.ingest(input).unwrap();
|
||||||
node.id
|
node.id
|
||||||
|
|
|
||||||
File diff suppressed because it is too large
Load diff
|
|
@ -13,7 +13,7 @@ use serde::Deserialize;
|
||||||
use serde_json::Value;
|
use serde_json::Value;
|
||||||
|
|
||||||
use crate::cognitive::CognitiveEngine;
|
use crate::cognitive::CognitiveEngine;
|
||||||
use vestige_core::Storage;
|
use vestige_core::{OutputConfig, Storage};
|
||||||
|
|
||||||
/// Input schema for session_context tool
|
/// Input schema for session_context tool
|
||||||
pub fn schema() -> Value {
|
pub fn schema() -> Value {
|
||||||
|
|
@ -98,6 +98,7 @@ fn first_sentence(content: &str) -> String {
|
||||||
pub async fn execute(
|
pub async fn execute(
|
||||||
storage: &Arc<Storage>,
|
storage: &Arc<Storage>,
|
||||||
cognitive: &Arc<Mutex<CognitiveEngine>>,
|
cognitive: &Arc<Mutex<CognitiveEngine>>,
|
||||||
|
output_config: &OutputConfig,
|
||||||
args: Option<Value>,
|
args: Option<Value>,
|
||||||
) -> Result<Value, String> {
|
) -> Result<Value, String> {
|
||||||
let args: SessionContextArgs = match args {
|
let args: SessionContextArgs = match args {
|
||||||
|
|
@ -105,6 +106,14 @@ pub async fn execute(
|
||||||
None => SessionContextArgs::default(),
|
None => SessionContextArgs::default(),
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// Per-query search width honors the active profile (e.g. `research` widens
|
||||||
|
// it, `lean` narrows it). No explicit MCP param exists here, so the config
|
||||||
|
// limit (or built-in default of 5) applies. Capped to keep the budgeted
|
||||||
|
// session response compact.
|
||||||
|
let per_query_limit = output_config.resolve_limit(None, 5).clamp(1, 25);
|
||||||
|
// The `lean` profile suppresses the inline memory date to save tokens.
|
||||||
|
let show_dates = output_config.show_timestamps;
|
||||||
|
|
||||||
let token_budget = args.token_budget.unwrap_or(1000).clamp(100, 100000) as usize;
|
let token_budget = args.token_budget.unwrap_or(1000).clamp(100, 100000) as usize;
|
||||||
let budget_chars = token_budget * 4;
|
let budget_chars = token_budget * 4;
|
||||||
let include_status = args.include_status.unwrap_or(true);
|
let include_status = args.include_status.unwrap_or(true);
|
||||||
|
|
@ -126,7 +135,7 @@ pub async fn execute(
|
||||||
|
|
||||||
for query in &queries {
|
for query in &queries {
|
||||||
let results = storage
|
let results = storage
|
||||||
.hybrid_search(query, 5, 0.3, 0.7)
|
.hybrid_search(query, per_query_limit, 0.3, 0.7)
|
||||||
.map_err(|e| e.to_string())?;
|
.map_err(|e| e.to_string())?;
|
||||||
|
|
||||||
for r in results {
|
for r in results {
|
||||||
|
|
@ -134,8 +143,12 @@ pub async fn execute(
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
let summary = first_sentence(&r.node.content);
|
let summary = first_sentence(&r.node.content);
|
||||||
|
let line = if show_dates {
|
||||||
let date_str = r.node.updated_at.format("%b %d, %Y").to_string();
|
let date_str = r.node.updated_at.format("%b %d, %Y").to_string();
|
||||||
let line = format!("- ({}) {}", date_str, summary);
|
format!("- ({}) {}", date_str, summary)
|
||||||
|
} else {
|
||||||
|
format!("- {}", summary)
|
||||||
|
};
|
||||||
let line_len = line.len() + 1; // +1 for newline
|
let line_len = line.len() + 1; // +1 for newline
|
||||||
|
|
||||||
if char_count + line_len > budget_chars {
|
if char_count + line_len > budget_chars {
|
||||||
|
|
@ -384,6 +397,7 @@ pub async fn execute(
|
||||||
|
|
||||||
Ok(serde_json::json!({
|
Ok(serde_json::json!({
|
||||||
"context": context_text,
|
"context": context_text,
|
||||||
|
"profile": output_config.profile.as_str(),
|
||||||
"tokensUsed": tokens_used,
|
"tokensUsed": tokens_used,
|
||||||
"tokenBudget": token_budget,
|
"tokenBudget": token_budget,
|
||||||
"expandable": expandable_ids,
|
"expandable": expandable_ids,
|
||||||
|
|
@ -492,6 +506,7 @@ mod tests {
|
||||||
tags: tags.into_iter().map(|s| s.to_string()).collect(),
|
tags: tags.into_iter().map(|s| s.to_string()).collect(),
|
||||||
valid_from: None,
|
valid_from: None,
|
||||||
valid_until: None,
|
valid_until: None,
|
||||||
|
source_envelope: None,
|
||||||
};
|
};
|
||||||
let node = storage.ingest(input).unwrap();
|
let node = storage.ingest(input).unwrap();
|
||||||
node.id
|
node.id
|
||||||
|
|
@ -529,7 +544,7 @@ mod tests {
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn test_default_no_args() {
|
async fn test_default_no_args() {
|
||||||
let (storage, _dir) = test_storage().await;
|
let (storage, _dir) = test_storage().await;
|
||||||
let result = execute(&storage, &test_cognitive(), None).await;
|
let result = execute(&storage, &test_cognitive(), &OutputConfig::default(), None).await;
|
||||||
assert!(result.is_ok());
|
assert!(result.is_ok());
|
||||||
|
|
||||||
let value = result.unwrap();
|
let value = result.unwrap();
|
||||||
|
|
@ -554,7 +569,13 @@ mod tests {
|
||||||
let args = serde_json::json!({
|
let args = serde_json::json!({
|
||||||
"queries": ["user preferences", "project context"]
|
"queries": ["user preferences", "project context"]
|
||||||
});
|
});
|
||||||
let result = execute(&storage, &test_cognitive(), Some(args)).await;
|
let result = execute(
|
||||||
|
&storage,
|
||||||
|
&test_cognitive(),
|
||||||
|
&OutputConfig::default(),
|
||||||
|
Some(args),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
assert!(result.is_ok());
|
assert!(result.is_ok());
|
||||||
|
|
||||||
let value = result.unwrap();
|
let value = result.unwrap();
|
||||||
|
|
@ -582,7 +603,13 @@ mod tests {
|
||||||
"queries": ["memory"],
|
"queries": ["memory"],
|
||||||
"token_budget": 200
|
"token_budget": 200
|
||||||
});
|
});
|
||||||
let result = execute(&storage, &test_cognitive(), Some(args)).await;
|
let result = execute(
|
||||||
|
&storage,
|
||||||
|
&test_cognitive(),
|
||||||
|
&OutputConfig::default(),
|
||||||
|
Some(args),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
assert!(result.is_ok());
|
assert!(result.is_ok());
|
||||||
|
|
||||||
let value = result.unwrap();
|
let value = result.unwrap();
|
||||||
|
|
@ -618,7 +645,13 @@ mod tests {
|
||||||
"queries": ["expandable test memory"],
|
"queries": ["expandable test memory"],
|
||||||
"token_budget": 150
|
"token_budget": 150
|
||||||
});
|
});
|
||||||
let result = execute(&storage, &test_cognitive(), Some(args)).await;
|
let result = execute(
|
||||||
|
&storage,
|
||||||
|
&test_cognitive(),
|
||||||
|
&OutputConfig::default(),
|
||||||
|
Some(args),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
assert!(result.is_ok());
|
assert!(result.is_ok());
|
||||||
|
|
||||||
let value = result.unwrap();
|
let value = result.unwrap();
|
||||||
|
|
@ -629,7 +662,7 @@ mod tests {
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn test_automation_triggers_booleans() {
|
async fn test_automation_triggers_booleans() {
|
||||||
let (storage, _dir) = test_storage().await;
|
let (storage, _dir) = test_storage().await;
|
||||||
let result = execute(&storage, &test_cognitive(), None).await;
|
let result = execute(&storage, &test_cognitive(), &OutputConfig::default(), None).await;
|
||||||
assert!(result.is_ok());
|
assert!(result.is_ok());
|
||||||
|
|
||||||
let value = result.unwrap();
|
let value = result.unwrap();
|
||||||
|
|
@ -649,7 +682,13 @@ mod tests {
|
||||||
"include_intentions": false,
|
"include_intentions": false,
|
||||||
"include_predictions": false
|
"include_predictions": false
|
||||||
});
|
});
|
||||||
let result = execute(&storage, &test_cognitive(), Some(args)).await;
|
let result = execute(
|
||||||
|
&storage,
|
||||||
|
&test_cognitive(),
|
||||||
|
&OutputConfig::default(),
|
||||||
|
Some(args),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
assert!(result.is_ok());
|
assert!(result.is_ok());
|
||||||
|
|
||||||
let value = result.unwrap();
|
let value = result.unwrap();
|
||||||
|
|
@ -674,6 +713,7 @@ mod tests {
|
||||||
tags: vec!["pattern".to_string(), "codebase:vestige".to_string()],
|
tags: vec!["pattern".to_string(), "codebase:vestige".to_string()],
|
||||||
valid_from: None,
|
valid_from: None,
|
||||||
valid_until: None,
|
valid_until: None,
|
||||||
|
source_envelope: None,
|
||||||
};
|
};
|
||||||
storage.ingest(input).unwrap();
|
storage.ingest(input).unwrap();
|
||||||
|
|
||||||
|
|
@ -683,7 +723,13 @@ mod tests {
|
||||||
"topics": ["performance"]
|
"topics": ["performance"]
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
let result = execute(&storage, &test_cognitive(), Some(args)).await;
|
let result = execute(
|
||||||
|
&storage,
|
||||||
|
&test_cognitive(),
|
||||||
|
&OutputConfig::default(),
|
||||||
|
Some(args),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
assert!(result.is_ok());
|
assert!(result.is_ok());
|
||||||
|
|
||||||
let value = result.unwrap();
|
let value = result.unwrap();
|
||||||
|
|
@ -692,6 +738,42 @@ mod tests {
|
||||||
assert!(ctx.contains("vestige"));
|
assert!(ctx.contains("vestige"));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Phase 2: the response echoes the active profile, and the `lean` profile
|
||||||
|
/// suppresses inline memory dates to save tokens.
|
||||||
|
#[tokio::test]
|
||||||
|
async fn test_session_context_profile_echo_and_lean_dates() {
|
||||||
|
let (storage, _dir) = test_storage().await;
|
||||||
|
ingest_test_content(&storage, "Session profile content sentence.", vec![]).await;
|
||||||
|
|
||||||
|
// Default profile -> profile echoed, dates present.
|
||||||
|
let args = serde_json::json!({ "queries": ["profile content"] });
|
||||||
|
let value = execute(
|
||||||
|
&storage,
|
||||||
|
&test_cognitive(),
|
||||||
|
&OutputConfig::default(),
|
||||||
|
Some(args),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(value["profile"], "default");
|
||||||
|
|
||||||
|
// Lean profile -> profile echoed as lean. The memory line must not carry
|
||||||
|
// the "(Mon DD, YYYY)" inline date prefix.
|
||||||
|
let cfg = vestige_core::VestigeConfig::parse("[defaults]\nprofile=lean").output();
|
||||||
|
let args = serde_json::json!({ "queries": ["profile content"] });
|
||||||
|
let value = execute(&storage, &test_cognitive(), &cfg, Some(args))
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(value["profile"], "lean");
|
||||||
|
let ctx = value["context"].as_str().unwrap();
|
||||||
|
if ctx.contains("**Memories:**") {
|
||||||
|
assert!(
|
||||||
|
!ctx.contains(", 20"),
|
||||||
|
"lean profile should omit the inline year in memory dates"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// ========================================================================
|
// ========================================================================
|
||||||
// HELPER TESTS
|
// HELPER TESTS
|
||||||
// ========================================================================
|
// ========================================================================
|
||||||
|
|
|
||||||
|
|
@ -215,6 +215,7 @@ pub async fn execute(
|
||||||
tags,
|
tags,
|
||||||
valid_from: None,
|
valid_from: None,
|
||||||
valid_until: None,
|
valid_until: None,
|
||||||
|
source_envelope: None,
|
||||||
};
|
};
|
||||||
|
|
||||||
// ====================================================================
|
// ====================================================================
|
||||||
|
|
@ -414,6 +415,7 @@ async fn execute_batch(
|
||||||
tags,
|
tags,
|
||||||
valid_from: None,
|
valid_from: None,
|
||||||
valid_until: None,
|
valid_until: None,
|
||||||
|
source_envelope: None,
|
||||||
};
|
};
|
||||||
|
|
||||||
// ================================================================
|
// ================================================================
|
||||||
|
|
|
||||||
291
crates/vestige-mcp/src/tools/source_sync.rs
Normal file
291
crates/vestige-mcp/src/tools/source_sync.rs
Normal file
|
|
@ -0,0 +1,291 @@
|
||||||
|
//! `source_sync` MCP tool (#57) — index an external system into Vestige.
|
||||||
|
//!
|
||||||
|
//! Turns Vestige into a durable, offline, provenance-linked retrieval layer
|
||||||
|
//! over a long-lived external system. GitHub Issues and Redmine are the first
|
||||||
|
//! reference connectors: Vestige indexes issues, comments/journals, and source
|
||||||
|
//! metadata as source-aware memories you can search semantically and cite back
|
||||||
|
//! to the canonical issue URL — re-runnable idempotently (no duplicates) and
|
||||||
|
//! able to tombstone issues that vanish upstream.
|
||||||
|
//!
|
||||||
|
//! Unlike the official GitHub MCP server (a stateless live API proxy), this
|
||||||
|
//! keeps a local index: searchable offline, embedded for semantic recall,
|
||||||
|
//! joinable with the rest of your memory, and temporally versioned.
|
||||||
|
//!
|
||||||
|
//! ## Auth (security)
|
||||||
|
//!
|
||||||
|
//! Tokens are read from environment variables (`GITHUB_TOKEN` /
|
||||||
|
//! `VESTIGE_GITHUB_TOKEN`, `REDMINE_API_KEY` / `VESTIGE_REDMINE_API_KEY`) and
|
||||||
|
//! never from tool arguments, so credentials are not logged in the conversation.
|
||||||
|
//! Public GitHub repositories and anonymous Redmine instances can work without a
|
||||||
|
//! token/key at lower capability.
|
||||||
|
|
||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
use serde::Deserialize;
|
||||||
|
use serde_json::{Value, json};
|
||||||
|
|
||||||
|
use vestige_core::storage::Storage;
|
||||||
|
|
||||||
|
/// JSON schema for the `source_sync` tool.
|
||||||
|
pub fn schema() -> Value {
|
||||||
|
json!({
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"source": {
|
||||||
|
"type": "string",
|
||||||
|
"enum": ["github", "redmine"],
|
||||||
|
"description": "External system to sync: 'github' (GitHub Issues) or 'redmine' (a Redmine project).",
|
||||||
|
"default": "github"
|
||||||
|
},
|
||||||
|
"repo": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "GitHub only: repository as 'owner/name', e.g. 'samvallad33/vestige'."
|
||||||
|
},
|
||||||
|
"project": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "Redmine only: project identifier (slug or numeric id) to sync. The Redmine host comes from the REDMINE_URL env var."
|
||||||
|
},
|
||||||
|
"reconcile": {
|
||||||
|
"type": "boolean",
|
||||||
|
"description": "Also tombstone local memories for issues no longer visible upstream (an extra full enumeration pass). Default false on incremental syncs.",
|
||||||
|
"default": false
|
||||||
|
},
|
||||||
|
"max_pages": {
|
||||||
|
"type": "integer",
|
||||||
|
"description": "Max API pages to fetch this run (each page is up to 100 issues). Lets a first sync of a large project be resumed across calls. Default 10.",
|
||||||
|
"default": 10,
|
||||||
|
"minimum": 1,
|
||||||
|
"maximum": 1000
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": []
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Deserialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
struct SourceSyncArgs {
|
||||||
|
#[serde(default = "default_source")]
|
||||||
|
source: String,
|
||||||
|
#[serde(default)]
|
||||||
|
repo: Option<String>,
|
||||||
|
#[serde(default)]
|
||||||
|
project: Option<String>,
|
||||||
|
#[serde(default)]
|
||||||
|
reconcile: bool,
|
||||||
|
#[serde(default, alias = "max_pages")]
|
||||||
|
max_pages: Option<usize>,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn default_source() -> String {
|
||||||
|
"github".to_string()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Read the GitHub token from the environment (never from tool args).
|
||||||
|
fn github_token() -> Option<String> {
|
||||||
|
std::env::var("GITHUB_TOKEN")
|
||||||
|
.or_else(|_| std::env::var("VESTIGE_GITHUB_TOKEN"))
|
||||||
|
.ok()
|
||||||
|
.filter(|s| !s.trim().is_empty())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Read the Redmine API key from the environment (never from tool args).
|
||||||
|
fn redmine_api_key() -> Option<String> {
|
||||||
|
std::env::var("REDMINE_API_KEY")
|
||||||
|
.or_else(|_| std::env::var("VESTIGE_REDMINE_API_KEY"))
|
||||||
|
.ok()
|
||||||
|
.filter(|s| !s.trim().is_empty())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Read the Redmine base URL from the environment.
|
||||||
|
fn redmine_url() -> Option<String> {
|
||||||
|
std::env::var("REDMINE_URL")
|
||||||
|
.or_else(|_| std::env::var("VESTIGE_REDMINE_URL"))
|
||||||
|
.ok()
|
||||||
|
.filter(|s| !s.trim().is_empty())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn execute(storage: &Arc<Storage>, args: Option<Value>) -> Result<Value, String> {
|
||||||
|
let args: SourceSyncArgs = match args {
|
||||||
|
Some(v) => serde_json::from_value(v).map_err(|e| format!("Invalid arguments: {e}"))?,
|
||||||
|
None => return Err("Missing arguments".to_string()),
|
||||||
|
};
|
||||||
|
|
||||||
|
let max_pages = args.max_pages.unwrap_or(10);
|
||||||
|
|
||||||
|
match args.source.as_str() {
|
||||||
|
"github" => {
|
||||||
|
let repo = args
|
||||||
|
.repo
|
||||||
|
.as_deref()
|
||||||
|
.ok_or_else(|| "github requires a 'repo' ('owner/name')".to_string())?;
|
||||||
|
let (owner, repo) = repo
|
||||||
|
.split_once('/')
|
||||||
|
.filter(|(o, r)| !o.is_empty() && !r.is_empty())
|
||||||
|
.ok_or_else(|| {
|
||||||
|
"repo must be in 'owner/name' form, e.g. 'samvallad33/vestige'".to_string()
|
||||||
|
})?;
|
||||||
|
execute_github(storage, owner, repo, args.reconcile, max_pages).await
|
||||||
|
}
|
||||||
|
"redmine" => {
|
||||||
|
let project = args
|
||||||
|
.project
|
||||||
|
.as_deref()
|
||||||
|
.filter(|p| !p.trim().is_empty())
|
||||||
|
.ok_or_else(|| "redmine requires a 'project' identifier".to_string())?;
|
||||||
|
let base_url = redmine_url().ok_or_else(|| {
|
||||||
|
"set the REDMINE_URL env var to the Redmine host (e.g. https://redmine.example.com)"
|
||||||
|
.to_string()
|
||||||
|
})?;
|
||||||
|
execute_redmine(storage, &base_url, project, args.reconcile, max_pages).await
|
||||||
|
}
|
||||||
|
other => Err(format!(
|
||||||
|
"Unsupported source '{other}'. Supported: 'github', 'redmine'."
|
||||||
|
)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Connectors are feature-gated; surface a clear message when the build omits
|
||||||
|
/// them rather than failing obscurely.
|
||||||
|
#[cfg(not(feature = "connectors"))]
|
||||||
|
async fn execute_github(
|
||||||
|
_storage: &Arc<Storage>,
|
||||||
|
_owner: &str,
|
||||||
|
_repo: &str,
|
||||||
|
_reconcile: bool,
|
||||||
|
_max_pages: usize,
|
||||||
|
) -> Result<Value, String> {
|
||||||
|
Err(NO_CONNECTORS_MSG.to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(not(feature = "connectors"))]
|
||||||
|
async fn execute_redmine(
|
||||||
|
_storage: &Arc<Storage>,
|
||||||
|
_base_url: &str,
|
||||||
|
_project: &str,
|
||||||
|
_reconcile: bool,
|
||||||
|
_max_pages: usize,
|
||||||
|
) -> Result<Value, String> {
|
||||||
|
Err(NO_CONNECTORS_MSG.to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(not(feature = "connectors"))]
|
||||||
|
const NO_CONNECTORS_MSG: &str = "This Vestige build was compiled without the 'connectors' feature. \
|
||||||
|
Rebuild with --features connectors to enable source_sync.";
|
||||||
|
|
||||||
|
#[cfg(feature = "connectors")]
|
||||||
|
async fn execute_github(
|
||||||
|
storage: &Arc<Storage>,
|
||||||
|
owner: &str,
|
||||||
|
repo: &str,
|
||||||
|
reconcile: bool,
|
||||||
|
max_pages: usize,
|
||||||
|
) -> Result<Value, String> {
|
||||||
|
use vestige_core::connectors::github::{GithubConfig, GithubConnector};
|
||||||
|
use vestige_core::connectors::run_sync;
|
||||||
|
|
||||||
|
let config = GithubConfig::new(owner, repo).with_token(github_token());
|
||||||
|
let connector =
|
||||||
|
GithubConnector::new(config).map_err(|e| format!("connector init failed: {e}"))?;
|
||||||
|
|
||||||
|
let report = run_sync(storage.as_ref(), &connector, reconcile, max_pages)
|
||||||
|
.await
|
||||||
|
.map_err(|e| format!("sync failed: {e}"))?;
|
||||||
|
|
||||||
|
let scope = format!("{owner}/{repo}");
|
||||||
|
let total = report.created + report.updated + report.unchanged;
|
||||||
|
let authed = github_token().is_some();
|
||||||
|
|
||||||
|
let summary = format!(
|
||||||
|
"Synced {scope}: {} created, {} updated, {} unchanged{} ({total} records seen{}).",
|
||||||
|
report.created,
|
||||||
|
report.updated,
|
||||||
|
report.unchanged,
|
||||||
|
if report.reconciled {
|
||||||
|
format!(", {} tombstoned", report.tombstoned)
|
||||||
|
} else {
|
||||||
|
String::new()
|
||||||
|
},
|
||||||
|
if authed { "" } else { ", unauthenticated" },
|
||||||
|
);
|
||||||
|
|
||||||
|
Ok(json!({
|
||||||
|
"ok": true,
|
||||||
|
"summary": summary,
|
||||||
|
"source": "github",
|
||||||
|
"scope": scope,
|
||||||
|
"created": report.created,
|
||||||
|
"updated": report.updated,
|
||||||
|
"unchanged": report.unchanged,
|
||||||
|
"tombstoned": report.tombstoned,
|
||||||
|
"reconciled": report.reconciled,
|
||||||
|
"cursor": report.new_cursor.map(|d| d.to_rfc3339()),
|
||||||
|
"authenticated": authed,
|
||||||
|
"warnings": report.warnings,
|
||||||
|
"hint": if total == 0 && !authed {
|
||||||
|
"No records returned. For private repos or higher rate limits, set GITHUB_TOKEN in the server environment."
|
||||||
|
} else if report.new_cursor.is_some() && total >= 100 {
|
||||||
|
"More may remain — run source_sync again to continue from the saved cursor."
|
||||||
|
} else {
|
||||||
|
"Search these with the normal search tools; results cite the GitHub issue URL."
|
||||||
|
}
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "connectors")]
|
||||||
|
async fn execute_redmine(
|
||||||
|
storage: &Arc<Storage>,
|
||||||
|
base_url: &str,
|
||||||
|
project: &str,
|
||||||
|
reconcile: bool,
|
||||||
|
max_pages: usize,
|
||||||
|
) -> Result<Value, String> {
|
||||||
|
use vestige_core::connectors::redmine::{RedmineConfig, RedmineConnector};
|
||||||
|
use vestige_core::connectors::run_sync;
|
||||||
|
|
||||||
|
let config = RedmineConfig::new(base_url, project).with_api_key(redmine_api_key());
|
||||||
|
let connector =
|
||||||
|
RedmineConnector::new(config).map_err(|e| format!("connector init failed: {e}"))?;
|
||||||
|
|
||||||
|
let report = run_sync(storage.as_ref(), &connector, reconcile, max_pages)
|
||||||
|
.await
|
||||||
|
.map_err(|e| format!("sync failed: {e}"))?;
|
||||||
|
|
||||||
|
let total = report.created + report.updated + report.unchanged;
|
||||||
|
let authed = redmine_api_key().is_some();
|
||||||
|
|
||||||
|
let summary = format!(
|
||||||
|
"Synced redmine project '{project}': {} created, {} updated, {} unchanged{} ({total} records seen{}).",
|
||||||
|
report.created,
|
||||||
|
report.updated,
|
||||||
|
report.unchanged,
|
||||||
|
if report.reconciled {
|
||||||
|
format!(", {} tombstoned", report.tombstoned)
|
||||||
|
} else {
|
||||||
|
String::new()
|
||||||
|
},
|
||||||
|
if authed { "" } else { ", anonymous" },
|
||||||
|
);
|
||||||
|
|
||||||
|
Ok(json!({
|
||||||
|
"ok": true,
|
||||||
|
"summary": summary,
|
||||||
|
"source": "redmine",
|
||||||
|
"scope": project,
|
||||||
|
"created": report.created,
|
||||||
|
"updated": report.updated,
|
||||||
|
"unchanged": report.unchanged,
|
||||||
|
"tombstoned": report.tombstoned,
|
||||||
|
"reconciled": report.reconciled,
|
||||||
|
"cursor": report.new_cursor.map(|d| d.to_rfc3339()),
|
||||||
|
"authenticated": authed,
|
||||||
|
"warnings": report.warnings,
|
||||||
|
"hint": if total == 0 && !authed {
|
||||||
|
"No records returned. Set REDMINE_API_KEY (and confirm the REST API is enabled on the instance) for private projects."
|
||||||
|
} else if report.new_cursor.is_some() && total >= 100 {
|
||||||
|
"More may remain — run source_sync again to continue from the saved cursor."
|
||||||
|
} else {
|
||||||
|
"Search these with the normal search tools; results cite the Redmine issue URL."
|
||||||
|
}
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
@ -177,6 +177,7 @@ mod tests {
|
||||||
tags: vec!["test".to_string()],
|
tags: vec!["test".to_string()],
|
||||||
valid_from: None,
|
valid_from: None,
|
||||||
valid_until: None,
|
valid_until: None,
|
||||||
|
source_envelope: None,
|
||||||
})
|
})
|
||||||
.unwrap()
|
.unwrap()
|
||||||
.id
|
.id
|
||||||
|
|
|
||||||
|
|
@ -9,9 +9,9 @@ use serde_json::Value;
|
||||||
use std::collections::BTreeMap;
|
use std::collections::BTreeMap;
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
|
|
||||||
use vestige_core::Storage;
|
use vestige_core::{OutputConfig, Storage};
|
||||||
|
|
||||||
use super::search_unified::format_node;
|
use super::search_unified::{apply_output_masks, format_node};
|
||||||
|
|
||||||
/// Input schema for memory_timeline tool
|
/// Input schema for memory_timeline tool
|
||||||
pub fn schema() -> Value {
|
pub fn schema() -> Value {
|
||||||
|
|
@ -87,7 +87,11 @@ fn parse_datetime(s: &str) -> Result<DateTime<Utc>, String> {
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Execute memory_timeline tool
|
/// Execute memory_timeline tool
|
||||||
pub async fn execute(storage: &Arc<Storage>, args: Option<Value>) -> Result<Value, String> {
|
pub async fn execute(
|
||||||
|
storage: &Arc<Storage>,
|
||||||
|
output_config: &OutputConfig,
|
||||||
|
args: Option<Value>,
|
||||||
|
) -> Result<Value, String> {
|
||||||
let args: TimelineArgs = match args {
|
let args: TimelineArgs = match args {
|
||||||
Some(v) => serde_json::from_value(v).map_err(|e| format!("Invalid arguments: {}", e))?,
|
Some(v) => serde_json::from_value(v).map_err(|e| format!("Invalid arguments: {}", e))?,
|
||||||
None => TimelineArgs {
|
None => TimelineArgs {
|
||||||
|
|
@ -100,12 +104,13 @@ pub async fn execute(storage: &Arc<Storage>, args: Option<Value>) -> Result<Valu
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
// Validate detail_level
|
// Validate detail_level. Precedence: explicit MCP param > config > default.
|
||||||
let detail_level = match args.detail_level.as_deref() {
|
let detail_level_owned = output_config.resolve_detail_level(args.detail_level.as_deref());
|
||||||
Some("brief") => "brief",
|
let detail_level = match detail_level_owned.as_str() {
|
||||||
Some("full") => "full",
|
"brief" => "brief",
|
||||||
Some("summary") | None => "summary",
|
"full" => "full",
|
||||||
Some(invalid) => {
|
"summary" => "summary",
|
||||||
|
invalid => {
|
||||||
return Err(format!(
|
return Err(format!(
|
||||||
"Invalid detail_level '{}'. Must be 'brief', 'summary', or 'full'.",
|
"Invalid detail_level '{}'. Must be 'brief', 'summary', or 'full'.",
|
||||||
invalid
|
invalid
|
||||||
|
|
@ -124,7 +129,8 @@ pub async fn execute(storage: &Arc<Storage>, args: Option<Value>) -> Result<Valu
|
||||||
None => Some(now),
|
None => Some(now),
|
||||||
};
|
};
|
||||||
|
|
||||||
let limit = args.limit.unwrap_or(50).clamp(1, 200);
|
// Precedence: explicit MCP param > config limit > built-in default (50).
|
||||||
|
let limit = output_config.resolve_limit(args.limit, 50).clamp(1, 200);
|
||||||
|
|
||||||
// Query memories in time range with filters pushed into SQL. Rust-side
|
// Query memories in time range with filters pushed into SQL. Rust-side
|
||||||
// `retain` after `LIMIT` was unsafe for sparse types/tags — a dominant
|
// `retain` after `LIMIT` was unsafe for sparse types/tags — a dominant
|
||||||
|
|
@ -140,14 +146,15 @@ pub async fn execute(storage: &Arc<Storage>, args: Option<Value>) -> Result<Valu
|
||||||
)
|
)
|
||||||
.map_err(|e| e.to_string())?;
|
.map_err(|e| e.to_string())?;
|
||||||
|
|
||||||
// Group by day
|
// Group by day, applying the active profile's field masks (e.g. `lean`
|
||||||
|
// drops timestamps) to each formatted node.
|
||||||
let mut by_day: BTreeMap<NaiveDate, Vec<Value>> = BTreeMap::new();
|
let mut by_day: BTreeMap<NaiveDate, Vec<Value>> = BTreeMap::new();
|
||||||
for node in &results {
|
for node in &results {
|
||||||
let date = node.created_at.date_naive();
|
let date = node.created_at.date_naive();
|
||||||
by_day
|
let mut formatted = [format_node(node, detail_level)];
|
||||||
.entry(date)
|
apply_output_masks(&mut formatted, output_config);
|
||||||
.or_default()
|
let [formatted] = formatted;
|
||||||
.push(format_node(node, detail_level));
|
by_day.entry(date).or_default().push(formatted);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Build timeline (newest first)
|
// Build timeline (newest first)
|
||||||
|
|
@ -173,6 +180,7 @@ pub async fn execute(storage: &Arc<Storage>, args: Option<Value>) -> Result<Valu
|
||||||
"end": end.map(|dt| dt.to_rfc3339()),
|
"end": end.map(|dt| dt.to_rfc3339()),
|
||||||
},
|
},
|
||||||
"detailLevel": detail_level,
|
"detailLevel": detail_level,
|
||||||
|
"profile": output_config.profile.as_str(),
|
||||||
"totalMemories": total,
|
"totalMemories": total,
|
||||||
"days": days,
|
"days": days,
|
||||||
"timeline": timeline,
|
"timeline": timeline,
|
||||||
|
|
@ -201,6 +209,7 @@ mod tests {
|
||||||
tags: vec!["timeline-test".to_string()],
|
tags: vec!["timeline-test".to_string()],
|
||||||
valid_from: None,
|
valid_from: None,
|
||||||
valid_until: None,
|
valid_until: None,
|
||||||
|
source_envelope: None,
|
||||||
})
|
})
|
||||||
.unwrap();
|
.unwrap();
|
||||||
}
|
}
|
||||||
|
|
@ -218,6 +227,7 @@ mod tests {
|
||||||
tags: tags.iter().map(|t| t.to_string()).collect(),
|
tags: tags.iter().map(|t| t.to_string()).collect(),
|
||||||
valid_from: None,
|
valid_from: None,
|
||||||
valid_until: None,
|
valid_until: None,
|
||||||
|
source_envelope: None,
|
||||||
})
|
})
|
||||||
.unwrap();
|
.unwrap();
|
||||||
}
|
}
|
||||||
|
|
@ -262,7 +272,7 @@ mod tests {
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn test_timeline_no_args_defaults() {
|
async fn test_timeline_no_args_defaults() {
|
||||||
let (storage, _dir) = test_storage().await;
|
let (storage, _dir) = test_storage().await;
|
||||||
let result = execute(&storage, None).await;
|
let result = execute(&storage, &OutputConfig::default(), None).await;
|
||||||
assert!(result.is_ok());
|
assert!(result.is_ok());
|
||||||
let value = result.unwrap();
|
let value = result.unwrap();
|
||||||
assert_eq!(value["tool"], "memory_timeline");
|
assert_eq!(value["tool"], "memory_timeline");
|
||||||
|
|
@ -274,7 +284,7 @@ mod tests {
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn test_timeline_empty_database() {
|
async fn test_timeline_empty_database() {
|
||||||
let (storage, _dir) = test_storage().await;
|
let (storage, _dir) = test_storage().await;
|
||||||
let result = execute(&storage, None).await;
|
let result = execute(&storage, &OutputConfig::default(), None).await;
|
||||||
let value = result.unwrap();
|
let value = result.unwrap();
|
||||||
assert_eq!(value["totalMemories"], 0);
|
assert_eq!(value["totalMemories"], 0);
|
||||||
assert_eq!(value["days"], 0);
|
assert_eq!(value["days"], 0);
|
||||||
|
|
@ -286,7 +296,7 @@ mod tests {
|
||||||
let (storage, _dir) = test_storage().await;
|
let (storage, _dir) = test_storage().await;
|
||||||
ingest_test_memory(&storage, "Timeline test memory 1").await;
|
ingest_test_memory(&storage, "Timeline test memory 1").await;
|
||||||
ingest_test_memory(&storage, "Timeline test memory 2").await;
|
ingest_test_memory(&storage, "Timeline test memory 2").await;
|
||||||
let result = execute(&storage, None).await;
|
let result = execute(&storage, &OutputConfig::default(), None).await;
|
||||||
let value = result.unwrap();
|
let value = result.unwrap();
|
||||||
assert_eq!(value["totalMemories"], 2);
|
assert_eq!(value["totalMemories"], 2);
|
||||||
assert!(value["days"].as_u64().unwrap() >= 1);
|
assert!(value["days"].as_u64().unwrap() >= 1);
|
||||||
|
|
@ -296,7 +306,7 @@ mod tests {
|
||||||
async fn test_timeline_invalid_detail_level() {
|
async fn test_timeline_invalid_detail_level() {
|
||||||
let (storage, _dir) = test_storage().await;
|
let (storage, _dir) = test_storage().await;
|
||||||
let args = serde_json::json!({ "detail_level": "invalid" });
|
let args = serde_json::json!({ "detail_level": "invalid" });
|
||||||
let result = execute(&storage, Some(args)).await;
|
let result = execute(&storage, &OutputConfig::default(), Some(args)).await;
|
||||||
assert!(result.is_err());
|
assert!(result.is_err());
|
||||||
assert!(result.unwrap_err().contains("Invalid detail_level"));
|
assert!(result.unwrap_err().contains("Invalid detail_level"));
|
||||||
}
|
}
|
||||||
|
|
@ -306,7 +316,7 @@ mod tests {
|
||||||
let (storage, _dir) = test_storage().await;
|
let (storage, _dir) = test_storage().await;
|
||||||
ingest_test_memory(&storage, "Brief test memory").await;
|
ingest_test_memory(&storage, "Brief test memory").await;
|
||||||
let args = serde_json::json!({ "detail_level": "brief" });
|
let args = serde_json::json!({ "detail_level": "brief" });
|
||||||
let result = execute(&storage, Some(args)).await;
|
let result = execute(&storage, &OutputConfig::default(), Some(args)).await;
|
||||||
assert!(result.is_ok());
|
assert!(result.is_ok());
|
||||||
let value = result.unwrap();
|
let value = result.unwrap();
|
||||||
assert_eq!(value["detailLevel"], "brief");
|
assert_eq!(value["detailLevel"], "brief");
|
||||||
|
|
@ -317,7 +327,7 @@ mod tests {
|
||||||
let (storage, _dir) = test_storage().await;
|
let (storage, _dir) = test_storage().await;
|
||||||
ingest_test_memory(&storage, "Full test memory").await;
|
ingest_test_memory(&storage, "Full test memory").await;
|
||||||
let args = serde_json::json!({ "detail_level": "full" });
|
let args = serde_json::json!({ "detail_level": "full" });
|
||||||
let result = execute(&storage, Some(args)).await;
|
let result = execute(&storage, &OutputConfig::default(), Some(args)).await;
|
||||||
assert!(result.is_ok());
|
assert!(result.is_ok());
|
||||||
let value = result.unwrap();
|
let value = result.unwrap();
|
||||||
assert_eq!(value["detailLevel"], "full");
|
assert_eq!(value["detailLevel"], "full");
|
||||||
|
|
@ -327,7 +337,7 @@ mod tests {
|
||||||
async fn test_timeline_limit_clamped() {
|
async fn test_timeline_limit_clamped() {
|
||||||
let (storage, _dir) = test_storage().await;
|
let (storage, _dir) = test_storage().await;
|
||||||
let args = serde_json::json!({ "limit": 0 });
|
let args = serde_json::json!({ "limit": 0 });
|
||||||
let result = execute(&storage, Some(args)).await;
|
let result = execute(&storage, &OutputConfig::default(), Some(args)).await;
|
||||||
assert!(result.is_ok()); // limit clamped to 1, no error
|
assert!(result.is_ok()); // limit clamped to 1, no error
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -339,7 +349,7 @@ mod tests {
|
||||||
"start": "2020-01-01",
|
"start": "2020-01-01",
|
||||||
"end": "2030-12-31"
|
"end": "2030-12-31"
|
||||||
});
|
});
|
||||||
let result = execute(&storage, Some(args)).await;
|
let result = execute(&storage, &OutputConfig::default(), Some(args)).await;
|
||||||
assert!(result.is_ok());
|
assert!(result.is_ok());
|
||||||
let value = result.unwrap();
|
let value = result.unwrap();
|
||||||
assert!(value["totalMemories"].as_u64().unwrap() >= 1);
|
assert!(value["totalMemories"].as_u64().unwrap() >= 1);
|
||||||
|
|
@ -350,7 +360,7 @@ mod tests {
|
||||||
let (storage, _dir) = test_storage().await;
|
let (storage, _dir) = test_storage().await;
|
||||||
ingest_test_memory(&storage, "A fact memory").await;
|
ingest_test_memory(&storage, "A fact memory").await;
|
||||||
let args = serde_json::json!({ "node_type": "concept" });
|
let args = serde_json::json!({ "node_type": "concept" });
|
||||||
let result = execute(&storage, Some(args)).await;
|
let result = execute(&storage, &OutputConfig::default(), Some(args)).await;
|
||||||
let value = result.unwrap();
|
let value = result.unwrap();
|
||||||
// Ingested as "fact", filtering for "concept" should yield 0
|
// Ingested as "fact", filtering for "concept" should yield 0
|
||||||
assert_eq!(value["totalMemories"], 0);
|
assert_eq!(value["totalMemories"], 0);
|
||||||
|
|
@ -361,7 +371,7 @@ mod tests {
|
||||||
let (storage, _dir) = test_storage().await;
|
let (storage, _dir) = test_storage().await;
|
||||||
ingest_test_memory(&storage, "Tagged memory").await;
|
ingest_test_memory(&storage, "Tagged memory").await;
|
||||||
let args = serde_json::json!({ "tags": ["timeline-test"] });
|
let args = serde_json::json!({ "tags": ["timeline-test"] });
|
||||||
let result = execute(&storage, Some(args)).await;
|
let result = execute(&storage, &OutputConfig::default(), Some(args)).await;
|
||||||
let value = result.unwrap();
|
let value = result.unwrap();
|
||||||
assert!(value["totalMemories"].as_u64().unwrap() >= 1);
|
assert!(value["totalMemories"].as_u64().unwrap() >= 1);
|
||||||
}
|
}
|
||||||
|
|
@ -371,7 +381,7 @@ mod tests {
|
||||||
let (storage, _dir) = test_storage().await;
|
let (storage, _dir) = test_storage().await;
|
||||||
ingest_test_memory(&storage, "Tagged memory").await;
|
ingest_test_memory(&storage, "Tagged memory").await;
|
||||||
let args = serde_json::json!({ "tags": ["nonexistent-tag"] });
|
let args = serde_json::json!({ "tags": ["nonexistent-tag"] });
|
||||||
let result = execute(&storage, Some(args)).await;
|
let result = execute(&storage, &OutputConfig::default(), Some(args)).await;
|
||||||
let value = result.unwrap();
|
let value = result.unwrap();
|
||||||
assert_eq!(value["totalMemories"], 0);
|
assert_eq!(value["totalMemories"], 0);
|
||||||
}
|
}
|
||||||
|
|
@ -409,7 +419,9 @@ mod tests {
|
||||||
// Limit 5 against 12 total — before the fix, `retain` on `concept`
|
// Limit 5 against 12 total — before the fix, `retain` on `concept`
|
||||||
// would operate on the 5 most recent rows (all `fact`) and find 0.
|
// would operate on the 5 most recent rows (all `fact`) and find 0.
|
||||||
let args = serde_json::json!({ "node_type": "concept", "limit": 5 });
|
let args = serde_json::json!({ "node_type": "concept", "limit": 5 });
|
||||||
let value = execute(&storage, Some(args)).await.unwrap();
|
let value = execute(&storage, &OutputConfig::default(), Some(args))
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
value["totalMemories"], 2,
|
value["totalMemories"], 2,
|
||||||
"Both sparse concepts should survive a limit smaller than the dominant set"
|
"Both sparse concepts should survive a limit smaller than the dominant set"
|
||||||
|
|
@ -447,7 +459,9 @@ mod tests {
|
||||||
}
|
}
|
||||||
|
|
||||||
let args = serde_json::json!({ "tags": ["rare"], "limit": 5 });
|
let args = serde_json::json!({ "tags": ["rare"], "limit": 5 });
|
||||||
let value = execute(&storage, Some(args)).await.unwrap();
|
let value = execute(&storage, &OutputConfig::default(), Some(args))
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
value["totalMemories"], 2,
|
value["totalMemories"], 2,
|
||||||
"Both sparse-tag matches should survive a limit smaller than the dominant set"
|
"Both sparse-tag matches should survive a limit smaller than the dominant set"
|
||||||
|
|
@ -479,4 +493,23 @@ mod tests {
|
||||||
assert_eq!(nodes.len(), 1, "Only the exact-tag match should return");
|
assert_eq!(nodes.len(), 1, "Only the exact-tag match should return");
|
||||||
assert_eq!(nodes[0].content, "Exact tag hit");
|
assert_eq!(nodes[0].content, "Exact tag hit");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Phase 2: config-file detail_level applies when no explicit param is set,
|
||||||
|
/// and an explicit param overrides it.
|
||||||
|
#[tokio::test]
|
||||||
|
async fn test_timeline_config_detail_precedence() {
|
||||||
|
let (storage, _dir) = test_storage().await;
|
||||||
|
ingest_test_memory(&storage, "Timeline config precedence content.").await;
|
||||||
|
|
||||||
|
let cfg = vestige_core::VestigeConfig::parse("[defaults]\ndetail_level=\"full\"").output();
|
||||||
|
|
||||||
|
// No explicit param -> config wins.
|
||||||
|
let value = execute(&storage, &cfg, None).await.unwrap();
|
||||||
|
assert_eq!(value["detailLevel"], "full");
|
||||||
|
|
||||||
|
// Explicit param -> overrides config.
|
||||||
|
let args = serde_json::json!({ "detail_level": "brief" });
|
||||||
|
let value = execute(&storage, &cfg, Some(args)).await.unwrap();
|
||||||
|
assert_eq!(value["detailLevel"], "brief");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -76,6 +76,6 @@ call `memory` with `action="purge"` and `confirm=true`.
|
||||||
## Portability Notes
|
## Portability Notes
|
||||||
|
|
||||||
The same protocol applies to Claude Code, Codex, Cursor, VS Code, Xcode,
|
The same protocol applies to Claude Code, Codex, Cursor, VS Code, Xcode,
|
||||||
JetBrains, Windsurf, and any other client that can run a stdio MCP server. Claude
|
OpenCode, JetBrains, Windsurf, and any other client that can run a stdio MCP server. Claude
|
||||||
Code's Cognitive Sandwich hooks are optional companion files; they are not
|
Code's Cognitive Sandwich hooks are optional companion files; they are not
|
||||||
required for normal Vestige memory.
|
required for normal Vestige memory.
|
||||||
|
|
|
||||||
159
docs/COMPOSED_GRAPH.md
Normal file
159
docs/COMPOSED_GRAPH.md
Normal file
|
|
@ -0,0 +1,159 @@
|
||||||
|
# ComposedGraph
|
||||||
|
|
||||||
|
ComposedGraph records memory combinations as durable reasoning events.
|
||||||
|
|
||||||
|
Most memory systems store facts, entities, or relationships. ComposedGraph stores a
|
||||||
|
different object: which memories were used together, why they were used, and what
|
||||||
|
happened afterward.
|
||||||
|
|
||||||
|
## Model
|
||||||
|
|
||||||
|
`composition_events` stores the reasoning envelope:
|
||||||
|
|
||||||
|
- tool and mode, such as `deep_reference` or `bounty`
|
||||||
|
- query and query hash
|
||||||
|
- confidence, status, and output preview
|
||||||
|
- metadata for intent, analyzed memory count, activation expansion, and reasoning preview
|
||||||
|
|
||||||
|
`composition_members` stores the participating memories:
|
||||||
|
|
||||||
|
- memory id
|
||||||
|
- role, such as `primary`, `supporting`, `contradicting`, or `superseded`
|
||||||
|
- rank, trust, relevance score, preview, and metadata
|
||||||
|
|
||||||
|
`composition_outcomes` stores later labels:
|
||||||
|
|
||||||
|
- `helpful`
|
||||||
|
- `dead_end`
|
||||||
|
- `submitted`
|
||||||
|
- `accepted`
|
||||||
|
- `rejected`
|
||||||
|
- `duplicate_risk`
|
||||||
|
- `needs_poc`
|
||||||
|
- `bad_severity`
|
||||||
|
- `user_promoted`
|
||||||
|
- `user_demoted`
|
||||||
|
- `closed_by_scope`
|
||||||
|
- `closed_by_duplicate`
|
||||||
|
- `closed_by_false_assumption`
|
||||||
|
- `closed_by_user`
|
||||||
|
- `expired_lane`
|
||||||
|
|
||||||
|
Member memory ids are intentionally historical references, not foreign keys into
|
||||||
|
`knowledge_nodes`. Purging or superseding a memory should not erase the fact that
|
||||||
|
it once participated in a reasoning path.
|
||||||
|
|
||||||
|
## MCP Tool
|
||||||
|
|
||||||
|
Use `composed_graph` for read/write access to the composition ledger.
|
||||||
|
|
||||||
|
```json
|
||||||
|
{ "action": "recent", "limit": 10 }
|
||||||
|
```
|
||||||
|
|
||||||
|
```json
|
||||||
|
{ "action": "get", "event_id": "<composition-event-id>" }
|
||||||
|
```
|
||||||
|
|
||||||
|
```json
|
||||||
|
{ "action": "memory", "memory_id": "<memory-id>", "limit": 10 }
|
||||||
|
```
|
||||||
|
|
||||||
|
```json
|
||||||
|
{ "action": "neighbors", "memory_id": "<memory-id>", "limit": 10 }
|
||||||
|
```
|
||||||
|
|
||||||
|
```json
|
||||||
|
{ "action": "never_composed", "tags": ["project:vestige"], "limit": 10 }
|
||||||
|
```
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"action": "label",
|
||||||
|
"event_id": "<composition-event-id>",
|
||||||
|
"outcome_type": "helpful",
|
||||||
|
"notes": "This combination led to the accepted fix."
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Never-Composed Frontier
|
||||||
|
|
||||||
|
`never_composed` returns pairs that have not yet appeared together in a
|
||||||
|
composition event.
|
||||||
|
|
||||||
|
The ranking is intentionally not just shared-tag matching. It combines:
|
||||||
|
|
||||||
|
- exact shared tags
|
||||||
|
- shared meaningful content terms
|
||||||
|
- boundary tags such as `boundary-*`, `oracle`, `queue`, `settlement`, `upgrade`,
|
||||||
|
`pause`, `accounting`, or `scope`
|
||||||
|
- node-type diversity
|
||||||
|
- FSRS retention strength
|
||||||
|
- composition novelty, so memories that have not already been heavily composed
|
||||||
|
still get surfaced
|
||||||
|
- prior composition outcomes from either member, so previously accepted,
|
||||||
|
duplicate-risk, or dead-end lanes shape the frontier without hiding it
|
||||||
|
|
||||||
|
Each candidate includes:
|
||||||
|
|
||||||
|
- `score`
|
||||||
|
- `noveltyScore`
|
||||||
|
- `bridgeScore`
|
||||||
|
- `trustScore`
|
||||||
|
- `outcomeScoreAdjustment`
|
||||||
|
- `sharedTags`
|
||||||
|
- `boundaryTags`
|
||||||
|
- `sharedTerms`
|
||||||
|
- `priorOutcomes`
|
||||||
|
- `outcomeSignal`, such as `clean`, `prior_success`, `prior_duplicate_risk`,
|
||||||
|
`prior_closed_door`, or `mixed_prior_outcomes`
|
||||||
|
- node types
|
||||||
|
- previews
|
||||||
|
- a short reason
|
||||||
|
- a `compositionQuestion` that an agent can answer before taking action
|
||||||
|
|
||||||
|
The output is a frontier queue, not a finding. A never-composed pair means
|
||||||
|
"worth investigating," not "true," "novel," or "reportable."
|
||||||
|
Prior outcomes are also guardrails, not verdicts: a duplicate-risk signal should
|
||||||
|
make the agent check duplicate families first, while a success signal should make
|
||||||
|
it inspect why the older composition worked.
|
||||||
|
|
||||||
|
Closed-door labels should be specific when possible. Prefer `closed_by_scope`,
|
||||||
|
`closed_by_duplicate`, `closed_by_false_assumption`, `closed_by_user`, or
|
||||||
|
`expired_lane` over a generic `dead_end` when the reason is known.
|
||||||
|
|
||||||
|
## Bounty / Research Mode
|
||||||
|
|
||||||
|
`bounty_mode` is a higher-level read shape for investigative workflows. It returns:
|
||||||
|
|
||||||
|
- recent already-composed lanes
|
||||||
|
- never-composed lanes
|
||||||
|
- closed doors
|
||||||
|
- duplicate-risk lanes
|
||||||
|
- lanes that need proof-of-concept work
|
||||||
|
- top weird combinations
|
||||||
|
|
||||||
|
This is useful for security research, bug triage, architecture work, and product
|
||||||
|
strategy because failed or duplicate compositions are preserved instead of being
|
||||||
|
rediscovered repeatedly.
|
||||||
|
|
||||||
|
## Deep Reference Integration
|
||||||
|
|
||||||
|
`deep_reference` persists composition events automatically when it has evidence
|
||||||
|
members. Empty evidence does not create a ledger event.
|
||||||
|
|
||||||
|
The response includes:
|
||||||
|
|
||||||
|
- `composition_event_id` when persisted
|
||||||
|
- `compositionWriteStatus`, usually `persisted` or `skipped_empty`
|
||||||
|
|
||||||
|
## Design Direction
|
||||||
|
|
||||||
|
The next useful upgrades are:
|
||||||
|
|
||||||
|
- triple or n-ary candidate mining, not only pairs
|
||||||
|
- structural-fit scoring for analogies, separate from surface similarity
|
||||||
|
- trust-zone scoring so a composition is limited by its weakest provenance
|
||||||
|
- temporal replay: "what combinations were available when this decision was made?"
|
||||||
|
- evaluation tasks where success requires combining memories that were never
|
||||||
|
previously co-composed
|
||||||
|
|
@ -50,6 +50,93 @@ Qwen3 currently uses Hugging Face Hub's Candle loader directly, so use the stand
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
## Output Configuration (`vestige.toml`)
|
||||||
|
|
||||||
|
> Added in **v2.1.26** (Roadmap Phase 2: Configurable Output).
|
||||||
|
|
||||||
|
You can control the default shape and size of high-traffic MCP responses with an
|
||||||
|
optional config file. It is **local-first** — no cloud service is involved — and
|
||||||
|
**fully backward-compatible**: with no file present, Vestige behaves exactly as
|
||||||
|
it did before.
|
||||||
|
|
||||||
|
### Location
|
||||||
|
|
||||||
|
The config file lives in the active Vestige data directory, alongside the
|
||||||
|
database:
|
||||||
|
|
||||||
|
```
|
||||||
|
<data_dir>/vestige.toml # e.g. ~/Library/Application Support/com.vestige.core/vestige.toml
|
||||||
|
```
|
||||||
|
|
||||||
|
The data directory is resolved with the same precedence as storage
|
||||||
|
(`--data-dir` > `VESTIGE_DATA_DIR` > OS per-user data dir). A missing file, or a
|
||||||
|
file with no recognized keys, falls back to built-in defaults. The parser is
|
||||||
|
lenient: unknown keys and unknown sections are ignored, so the file can grow in
|
||||||
|
future releases without breaking older binaries.
|
||||||
|
|
||||||
|
### `[defaults]` table
|
||||||
|
|
||||||
|
```toml
|
||||||
|
[defaults]
|
||||||
|
# Detail level for high-traffic tools: "brief" | "summary" | "full"
|
||||||
|
detail_level = "summary"
|
||||||
|
|
||||||
|
# Default result count for high-traffic tools (positive integer)
|
||||||
|
limit = 10
|
||||||
|
|
||||||
|
# Output profile: "lean" | "default" | "audit" | "research"
|
||||||
|
profile = "default"
|
||||||
|
```
|
||||||
|
|
||||||
|
All three keys are optional. `detail_level` and `limit`, when set, override the
|
||||||
|
selected profile's presets.
|
||||||
|
|
||||||
|
### Output profiles
|
||||||
|
|
||||||
|
A profile presets a coherent bundle of detail level, default limit, and whether
|
||||||
|
scores and timestamps are included:
|
||||||
|
|
||||||
|
| Profile | Detail | Default limit | Scores | Timestamps | Use when |
|
||||||
|
|---------|--------|---------------|--------|------------|----------|
|
||||||
|
| `lean` | `brief` | 5 | dropped | dropped | Context budget matters most |
|
||||||
|
| `default` | `summary` | tool default | shown | shown | **Historical behavior (unchanged)** |
|
||||||
|
| `audit` | `full` | tool default | shown | shown | Reviewing or debugging memory state |
|
||||||
|
| `research` | `full` | 25 | shown | shown | Wide, detailed result sets |
|
||||||
|
|
||||||
|
### Precedence
|
||||||
|
|
||||||
|
Resolved per call, highest to lowest:
|
||||||
|
|
||||||
|
1. **Explicit MCP parameter** (e.g. `detail_level` / `limit` on a `search`
|
||||||
|
call) — always wins.
|
||||||
|
2. **`vestige.toml`** — the `[defaults]` keys and the selected profile.
|
||||||
|
3. **Built-in default** — the `default` profile, identical to pre-v2.1.26
|
||||||
|
behavior.
|
||||||
|
|
||||||
|
### Affected tools
|
||||||
|
|
||||||
|
`search`, `memory_timeline`, `codebase` (`get_context`), and `session_context`
|
||||||
|
resolve their default detail level and result limit through this config. Each of
|
||||||
|
these tools also echoes the active `profile` in its response so you can confirm
|
||||||
|
what was applied. Tools that take no `detail_level`/`limit` are unaffected.
|
||||||
|
|
||||||
|
### Example: minimize context cost
|
||||||
|
|
||||||
|
```toml
|
||||||
|
[defaults]
|
||||||
|
profile = "lean"
|
||||||
|
```
|
||||||
|
|
||||||
|
### Example: detailed audits without changing the profile
|
||||||
|
|
||||||
|
```toml
|
||||||
|
[defaults]
|
||||||
|
detail_level = "full"
|
||||||
|
limit = 50
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
## Command-Line Options
|
## Command-Line Options
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
|
|
@ -141,6 +228,42 @@ Add to `%APPDATA%\Claude\claude_desktop_config.json`:
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### OpenCode
|
||||||
|
|
||||||
|
OpenCode supports global and project-local config. For a project-local setup, add to `opencode.json`:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"$schema": "https://opencode.ai/config.json",
|
||||||
|
"mcp": {
|
||||||
|
"vestige": {
|
||||||
|
"type": "local",
|
||||||
|
"command": ["vestige-mcp"],
|
||||||
|
"enabled": true,
|
||||||
|
"timeout": 10000
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
For isolated per-project memory, pass the data directory in the command array:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"$schema": "https://opencode.ai/config.json",
|
||||||
|
"mcp": {
|
||||||
|
"vestige": {
|
||||||
|
"type": "local",
|
||||||
|
"command": ["vestige-mcp", "--data-dir", "./.vestige"],
|
||||||
|
"enabled": true,
|
||||||
|
"timeout": 10000
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
See the [OpenCode integration guide](integrations/opencode.md) for global config, verification, and troubleshooting.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Custom Data Directory
|
## Custom Data Directory
|
||||||
|
|
|
||||||
206
docs/CONNECTORS.md
Normal file
206
docs/CONNECTORS.md
Normal file
|
|
@ -0,0 +1,206 @@
|
||||||
|
# External-Source Connectors
|
||||||
|
|
||||||
|
> Status: **v2.1.27** — GitHub Issues + Redmine reference connectors, plus
|
||||||
|
> source-aware investigation filters for search. Tracking issue:
|
||||||
|
> [#57](https://github.com/samvallad33/vestige/issues/57).
|
||||||
|
|
||||||
|
Connectors let Vestige act as a durable, local **retrieval and reasoning layer**
|
||||||
|
over a long-lived external system — a ticket tracker, an issue board, a support
|
||||||
|
queue — **without replacing it**. The external system stays the source of truth.
|
||||||
|
Vestige indexes its records, embeds them for semantic recall, links them into the
|
||||||
|
memory graph, and **cites back** to the canonical record.
|
||||||
|
|
||||||
|
## Why this is different from a ticket-system MCP
|
||||||
|
|
||||||
|
The official GitHub / Jira MCP servers are **live API proxies**: every query hits
|
||||||
|
the upstream API, is rate-limited, keyword-only, online-only, and has no memory
|
||||||
|
of past state. Vestige instead keeps a **durable local index** of the records, so
|
||||||
|
you can:
|
||||||
|
|
||||||
|
- search the history **offline** and **semantically** (embeddings, not just
|
||||||
|
keywords),
|
||||||
|
- **join** ticket history with the rest of your memory in one search,
|
||||||
|
- see a **point-in-time** view (records carry temporal validity),
|
||||||
|
- and re-sync **idempotently** — re-running never duplicates a record.
|
||||||
|
|
||||||
|
## Quick start (GitHub Issues)
|
||||||
|
|
||||||
|
1. (Optional but recommended) export a token so you get the authenticated rate
|
||||||
|
limit (5,000 req/hr vs 60 for anonymous) and access to private repos:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
export GITHUB_TOKEN=ghp_xxx # or VESTIGE_GITHUB_TOKEN
|
||||||
|
```
|
||||||
|
|
||||||
|
The token is read **only** from the environment — never passed as a tool
|
||||||
|
argument, never logged.
|
||||||
|
|
||||||
|
2. Ask your agent to run the `source_sync` MCP tool:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{ "repo": "samvallad33/vestige" }
|
||||||
|
```
|
||||||
|
|
||||||
|
3. Search as normal. Connector-sourced results carry a `sourceRecord` object with
|
||||||
|
the canonical issue URL:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"content": "[samvallad33/vestige#57] Roadmap: external source connectors …",
|
||||||
|
"sourceRecord": {
|
||||||
|
"system": "github",
|
||||||
|
"id": "57",
|
||||||
|
"url": "https://github.com/samvallad33/vestige/issues/57",
|
||||||
|
"project": "samvallad33/vestige",
|
||||||
|
"type": "issue",
|
||||||
|
"author": "samvallad33",
|
||||||
|
"tombstoned": false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Quick start (Redmine)
|
||||||
|
|
||||||
|
Redmine stays the system of record; Vestige indexes a project's issues +
|
||||||
|
journals (comments and status/assignment history).
|
||||||
|
|
||||||
|
1. Point Vestige at the Redmine host and key (env only, never tool args):
|
||||||
|
|
||||||
|
```sh
|
||||||
|
export REDMINE_URL=https://redmine.example.com
|
||||||
|
export REDMINE_API_KEY=xxxxxxxx # or VESTIGE_REDMINE_API_KEY
|
||||||
|
```
|
||||||
|
|
||||||
|
The instance must have the REST API enabled (Administration → Settings → API)
|
||||||
|
or every call returns 401/403 even with a valid key.
|
||||||
|
|
||||||
|
2. Run `source_sync`:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{ "source": "redmine", "project": "infra" }
|
||||||
|
```
|
||||||
|
|
||||||
|
Results cite the canonical `https://redmine.example.com/issues/<id>` URL.
|
||||||
|
|
||||||
|
## The `source_sync` tool
|
||||||
|
|
||||||
|
| Field | Type | Default | Meaning |
|
||||||
|
|---|---|---|---|
|
||||||
|
| `source` | string | `github` | `github` or `redmine`. |
|
||||||
|
| `repo` | string | — | **GitHub:** `owner/name`, e.g. `samvallad33/vestige`. |
|
||||||
|
| `project` | string | — | **Redmine:** project identifier (host from `REDMINE_URL`). |
|
||||||
|
| `reconcile` | bool | `false` | Also tombstone local memories for issues no longer visible upstream (an extra full-enumeration pass). |
|
||||||
|
| `max_pages` | int | `10` | API pages to fetch this run (≤100 issues each). Lets a first sync of a large project resume across calls. |
|
||||||
|
|
||||||
|
The tool returns counts (`created` / `updated` / `unchanged` / `tombstoned`),
|
||||||
|
the saved `cursor`, whether it ran authenticated, and a `hint` for the next step.
|
||||||
|
|
||||||
|
## Investigation filters (Phase 4)
|
||||||
|
|
||||||
|
`search` accepts source-aware filters so an agent can scope a query to indexed
|
||||||
|
records. All are optional post-filters; combine with a larger `limit` if you
|
||||||
|
expect heavy thinning. A source-scoped query excludes non-connector memories.
|
||||||
|
|
||||||
|
| Filter | Matches |
|
||||||
|
|---|---|
|
||||||
|
| `source_system` | `github`, `redmine`, … |
|
||||||
|
| `source_project` | repo / project (exact) |
|
||||||
|
| `source_id` | a specific issue/ticket id |
|
||||||
|
| `source_type` | `issue`, `comment`, … |
|
||||||
|
| `source_author` | reporter/author (not assignee) |
|
||||||
|
| `source_updated_after` / `source_updated_before` | RFC3339 date range (inclusive) |
|
||||||
|
| `source_status` | `valid` (default `any`) or `tombstoned` |
|
||||||
|
|
||||||
|
Status, tracker, and priority are filterable through the existing `tag_prefix`
|
||||||
|
(the connectors emit lowercase `status:`, `tracker:`, `priority:`, and GitHub
|
||||||
|
`label:` / `state:` tags) — e.g. `tag_prefix: "status:open"`. Assignee and
|
||||||
|
linked-issue graph traversal are not yet exposed (see below).
|
||||||
|
|
||||||
|
### Idempotent, incremental sync
|
||||||
|
|
||||||
|
Each run:
|
||||||
|
|
||||||
|
1. resumes from the saved cursor (the high-water mark on the record's upstream
|
||||||
|
update time), minus a small overlap window so same-second / clock-skewed
|
||||||
|
updates are never missed;
|
||||||
|
2. pages issues in ascending update order (`state=all`, so closing an issue is
|
||||||
|
**not** mistaken for a deletion), folding each issue + its comments into one
|
||||||
|
memory;
|
||||||
|
3. routes each record through an **idempotent upsert** keyed on
|
||||||
|
`(source_system, source_id)`:
|
||||||
|
- unseen record → **insert**,
|
||||||
|
- changed content (by content hash) → **update in place** + re-embed,
|
||||||
|
- unchanged content → **no-op** (only the "last seen" time advances);
|
||||||
|
4. advances and persists the cursor only after the run, so an interruption
|
||||||
|
re-scans rather than skips.
|
||||||
|
|
||||||
|
Re-running `source_sync` on the same repo is therefore safe and cheap — it picks
|
||||||
|
up only what changed.
|
||||||
|
|
||||||
|
### Deletions (tombstoning)
|
||||||
|
|
||||||
|
Neither GitHub nor Redmine exposes a deletion feed, so an incremental sync can
|
||||||
|
never *see* a delete. Pass `reconcile: true` to run a reconciliation pass: Vestige
|
||||||
|
enumerates the currently-visible issue ids and **invalidates** (does not purge)
|
||||||
|
any local record no longer present. A tombstoned record keeps its content for
|
||||||
|
audit but drops out of "currently valid" retrieval (`sourceRecord.tombstoned` is
|
||||||
|
`true`). If the record reappears upstream, the next sync un-tombstones it.
|
||||||
|
|
||||||
|
## The source envelope
|
||||||
|
|
||||||
|
Every connector-ingested memory carries structured provenance, distinct from the
|
||||||
|
legacy free-form `source` label:
|
||||||
|
|
||||||
|
| Field | Purpose |
|
||||||
|
|---|---|
|
||||||
|
| `source_system` | `github`, `redmine`, … (namespaces ids). |
|
||||||
|
| `source_id` | Native id (issue number, ticket id). |
|
||||||
|
| `source_url` | Canonical link back — the citation. |
|
||||||
|
| `source_updated_at` | Upstream update time (the sync cursor field). |
|
||||||
|
| `content_hash` | Change detector → idempotency. |
|
||||||
|
| `synced_at` | When the connector last saw the record live. |
|
||||||
|
| `source_project` | Repo / project / space. |
|
||||||
|
| `source_type` | `issue`, `comment`, … |
|
||||||
|
| `source_author` | Reporter / author upstream. |
|
||||||
|
|
||||||
|
`(source_system, source_id)` is enforced unique, so there is exactly one memory
|
||||||
|
per external record. Legacy memories (agent- or user-authored) have no envelope
|
||||||
|
and are completely unaffected.
|
||||||
|
|
||||||
|
## Building
|
||||||
|
|
||||||
|
The connector HTTP client is behind the `connectors` cargo feature, which is
|
||||||
|
**on by default in the MCP server** (`vestige-mcp`). A build without it still
|
||||||
|
exposes the `source_sync` tool but returns a clear "rebuild with `--features
|
||||||
|
connectors`" message. The core library (`vestige-core`) leaves the feature
|
||||||
|
**off** by default, so library consumers that don't need connectors link no HTTP
|
||||||
|
client.
|
||||||
|
|
||||||
|
```sh
|
||||||
|
# default MCP build already includes connectors
|
||||||
|
cargo build -p vestige-mcp --release
|
||||||
|
|
||||||
|
# explicit, or for the core lib
|
||||||
|
cargo build -p vestige-core --features connectors
|
||||||
|
```
|
||||||
|
|
||||||
|
## Writing a new connector
|
||||||
|
|
||||||
|
Implement the `Connector` trait in `vestige_core::connectors` (fetch a window of
|
||||||
|
records updated since a cursor, page forward, and optionally enumerate live ids
|
||||||
|
for reconciliation), produce `NormalizedRecord`s with a filled
|
||||||
|
`SourceEnvelope`, and hand them to `run_sync`. Two reference connectors show the
|
||||||
|
shape — `crates/vestige-core/src/connectors/github.rs` (Link-header pagination,
|
||||||
|
opaque-url cursor) and `crates/vestige-core/src/connectors/redmine.rs`
|
||||||
|
(offset pagination, two-phase list-then-detail fetch). The sync driver,
|
||||||
|
idempotent upsert, cursor checkpointing, and tombstone reconciliation are all
|
||||||
|
reused for free.
|
||||||
|
|
||||||
|
## Not yet supported
|
||||||
|
|
||||||
|
- **Assignee filter** — the envelope stores `source_author` (reporter) only; no
|
||||||
|
assignee column yet.
|
||||||
|
- **Tracker / version dedicated filter params** — reachable today via
|
||||||
|
`tag_prefix` (`tracker:`, and `version:`/`category:` when emitted).
|
||||||
|
- **Linked-issue graph traversal** — connectors import relations into the memory
|
||||||
|
body, but issue-to-issue graph edges are not yet exposed in search.
|
||||||
24
docs/FAQ.md
24
docs/FAQ.md
|
|
@ -782,22 +782,16 @@ This helps trace why you know something.
|
||||||
<details>
|
<details>
|
||||||
<summary><b>"What's planned for future versions?"</b></summary>
|
<summary><b>"What's planned for future versions?"</b></summary>
|
||||||
|
|
||||||
Based on codebase exploration, these features exist in various stages:
|
See the public [Vestige Roadmap](ROADMAP.md) for the current adoption plan. The
|
||||||
|
near-term focus is reducing first-user confusion before expanding the feature
|
||||||
|
surface:
|
||||||
|
|
||||||
| Feature | Status | Description |
|
- first-time memory migration and atomic memory guidance
|
||||||
|---------|--------|-------------|
|
- configurable MCP output fields and output profiles
|
||||||
| Memory Dreams | Partial | Automated offline consolidation |
|
- clearer merge/supersede controls
|
||||||
| Reconsolidation | Planned | Update memories when accessed |
|
- code/docstring memory workflows
|
||||||
| Memory Chains | Partial | Link related memories explicitly |
|
- goals and milestones distinct from intentions
|
||||||
| Adaptive Embedding | Planned | Re-embed old memories with better models |
|
- guided import dry runs and review queues
|
||||||
| Cross-Project Learning | Planned | Share patterns across codebases |
|
|
||||||
|
|
||||||
**Community wishlist** (from Reddit):
|
|
||||||
- Stream ingestion mode
|
|
||||||
- GUI for memory browsing
|
|
||||||
- Export/import formats
|
|
||||||
- Sync between devices (encrypted)
|
|
||||||
- Team collaboration features
|
|
||||||
|
|
||||||
Contributions welcome!
|
Contributions welcome!
|
||||||
</details>
|
</details>
|
||||||
|
|
|
||||||
152
docs/MERGE_SUPERSEDE.md
Normal file
152
docs/MERGE_SUPERSEDE.md
Normal file
|
|
@ -0,0 +1,152 @@
|
||||||
|
# Merge / Supersede Controls (Phase 3)
|
||||||
|
|
||||||
|
> Diff-previewed, confidence-gated, reversible, self-explaining
|
||||||
|
> combine/dedupe/supersede on a never-delete (bitemporal) store.
|
||||||
|
|
||||||
|
Memory systems accumulate duplicates, near-duplicates, and outdated facts. The
|
||||||
|
naive fixes are all bad: dumb hashing under-merges (misses paraphrases),
|
||||||
|
aggressive LLM merging over-merges and destroys the audit trail, and
|
||||||
|
auto-deleting on contradiction silently loses information. Vestige's Phase 3
|
||||||
|
takes the opposite stance:
|
||||||
|
|
||||||
|
- **Opt-in, never silent.** The default is preview/review. Nothing mutates your
|
||||||
|
memory unless you explicitly apply a plan.
|
||||||
|
- **Diff-previewed.** `plan_merge` / `plan_supersede` show exactly what *would*
|
||||||
|
change before anything does.
|
||||||
|
- **Confidence-gated.** A Fellegi-Sunter two-threshold score classifies each
|
||||||
|
candidate as `match` / `possible` / `non_match`.
|
||||||
|
- **Reversible.** Every applied operation is recorded with an undo payload — a
|
||||||
|
*git reflog for your agent's memory*.
|
||||||
|
- **Self-explaining.** Each candidate carries the signals that explain *why* two
|
||||||
|
memories were judged duplicates.
|
||||||
|
- **Audit-preserving.** Superseding does not delete: it stamps `valid_until` and
|
||||||
|
keeps the old memory queryable (Graphiti-style "invalidate, don't delete").
|
||||||
|
|
||||||
|
## The bitemporal model: invalidate, don't delete
|
||||||
|
|
||||||
|
Superseding memory A with memory B does **not** erase A. Instead:
|
||||||
|
|
||||||
|
- `A.valid_until` is stamped with the supersede time.
|
||||||
|
- `A.superseded_by` is set to `B.id` (a lineage pointer).
|
||||||
|
- A remains fully queryable for audit. Searches and timelines can still surface
|
||||||
|
it; it is simply marked as no longer the current truth.
|
||||||
|
|
||||||
|
This reuses the existing `valid_from` / `valid_until` columns on
|
||||||
|
`knowledge_nodes` (migration V2) plus a new `superseded_by` column (migration
|
||||||
|
V14). Merges work the same way: the survivor absorbs the others' content, and
|
||||||
|
each absorbed node is bitemporally invalidated rather than deleted.
|
||||||
|
|
||||||
|
## Fellegi-Sunter two-threshold scoring
|
||||||
|
|
||||||
|
Candidate scoring combines three signals into a weighted score in `[0, 1]`:
|
||||||
|
|
||||||
|
| Signal | Weight | Source |
|
||||||
|
| ----------------------- | -----: | ------------------------------------------ |
|
||||||
|
| Embedding cosine sim | 0.70 | stored embeddings (`node_embeddings`) |
|
||||||
|
| Tag overlap (Jaccard) | 0.15 | `knowledge_nodes.tags` |
|
||||||
|
| Content token overlap | 0.15 | Jaccard over content tokens (len > 2) |
|
||||||
|
|
||||||
|
The combined score is then classified against **two** thresholds:
|
||||||
|
|
||||||
|
```
|
||||||
|
score >= match_threshold => "match" (auto-merge eligible)
|
||||||
|
possible_threshold <= score => "possible" (surfaced for review)
|
||||||
|
score < possible_threshold => "non_match" (never offered)
|
||||||
|
```
|
||||||
|
|
||||||
|
Defaults: `match_threshold = 0.86`, `possible_threshold = 0.72`. The two-band
|
||||||
|
design means borderline cases are surfaced for review instead of being
|
||||||
|
force-decided in either direction.
|
||||||
|
|
||||||
|
A cluster's confidence is the **weakest** pairwise score within it (the loosest
|
||||||
|
link), so a cluster is only as confident as its least-similar member.
|
||||||
|
|
||||||
|
## The reversible operation log (the "memory reflog")
|
||||||
|
|
||||||
|
Every applied merge/supersede writes one row to `merge_operations`:
|
||||||
|
|
||||||
|
- `op_type` — `merge` | `supersede` | `undo`
|
||||||
|
- `status` — `applied` | `reverted`
|
||||||
|
- `survivor_id`, `affected_ids` — what was touched
|
||||||
|
- `confidence`, `signals` — the score and *why* the memories combined
|
||||||
|
- `reason` — a human-readable explanation
|
||||||
|
- `undo_payload` — a JSON snapshot capturing everything needed to reverse it
|
||||||
|
|
||||||
|
`merge_undo` consumes the undo payload to restore the survivor's prior
|
||||||
|
content/tags and clear the bitemporal invalidation on every affected node, then
|
||||||
|
records a compensating `undo` operation. Calling `merge_undo` with no
|
||||||
|
`operation_id` returns the operation log so you can pick one.
|
||||||
|
|
||||||
|
## Memory protection (pinning)
|
||||||
|
|
||||||
|
`protect` sets the `protected` flag on a memory. A protected memory:
|
||||||
|
|
||||||
|
- is never offered for auto-merge (it is flagged in `merge_candidates`),
|
||||||
|
- cannot be merged *away* (it may only be the survivor of a merge),
|
||||||
|
- cannot be superseded,
|
||||||
|
- is excluded from garbage collection.
|
||||||
|
|
||||||
|
Pass `protected: false` to unpin.
|
||||||
|
|
||||||
|
## Tool surface
|
||||||
|
|
||||||
|
| Tool | Mutates? | Purpose |
|
||||||
|
| ------------------ | :------: | ------------------------------------------------------------------------- |
|
||||||
|
| `merge_candidates` | No | Surface likely duplicate clusters with confidence + signals. |
|
||||||
|
| `plan_merge` | No | Preview a merge of 2+ memories (a diff). Returns a `plan_id`. |
|
||||||
|
| `plan_supersede` | No | Preview superseding A with B (bitemporal). Returns a `plan_id`. |
|
||||||
|
| `apply_plan` | **Yes** | Execute a plan by id; recorded as a reversible operation. |
|
||||||
|
| `merge_undo` | **Yes** | Reverse an operation, or list the operation log when given no id. |
|
||||||
|
| `protect` | **Yes** | Pin / unpin a memory so it can never be auto-merged/superseded/forgotten. |
|
||||||
|
| `merge_policy` | **Yes** | Get/set the two thresholds + `auto_apply`. |
|
||||||
|
|
||||||
|
### Typical flow
|
||||||
|
|
||||||
|
```text
|
||||||
|
1. merge_candidates -> review clusters + confidence + signals
|
||||||
|
2. plan_merge { member_ids: [...] } -> inspect the diff, get plan_id
|
||||||
|
3. apply_plan { plan_id, confirm } -> apply; get operation_id (reversible)
|
||||||
|
4. merge_undo { operation_id } -> reverse if it was wrong
|
||||||
|
```
|
||||||
|
|
||||||
|
`apply_plan` requires `confirm: true` for `possible` / `non_match` plans. A
|
||||||
|
`match` plan applies without `confirm` only when the policy has
|
||||||
|
`auto_apply: true` (default `false`).
|
||||||
|
|
||||||
|
## Configuration
|
||||||
|
|
||||||
|
The merge policy persists per project (stored in `fsrs_config`). It can also be
|
||||||
|
overridden via environment variables:
|
||||||
|
|
||||||
|
| Variable | Meaning |
|
||||||
|
| ----------------------------------- | ------------------------------------ |
|
||||||
|
| `VESTIGE_MERGE_MATCH_THRESHOLD` | Score ≥ this ⇒ `match`. |
|
||||||
|
| `VESTIGE_MERGE_POSSIBLE_THRESHOLD` | Score ≥ this ⇒ at least `possible`. |
|
||||||
|
| `VESTIGE_MERGE_AUTO_APPLY` | `1`/`true` to allow auto-apply. |
|
||||||
|
|
||||||
|
A persisted policy (set via `merge_policy`) takes precedence over the
|
||||||
|
environment, which takes precedence over the built-in defaults. When
|
||||||
|
`vestige.toml` configuration lands, the policy will read from there as well.
|
||||||
|
|
||||||
|
## Schema (migration V14)
|
||||||
|
|
||||||
|
- `knowledge_nodes.protected INTEGER NOT NULL DEFAULT 0`
|
||||||
|
- `knowledge_nodes.superseded_by TEXT`
|
||||||
|
- `merge_plans(id, kind, status, created_at, applied_at, survivor_id,
|
||||||
|
member_ids, confidence, classification, payload)`
|
||||||
|
- `merge_operations(id, plan_id, op_type, status, created_at, reverted_at,
|
||||||
|
reverts_op_id, survivor_id, affected_ids, confidence, signals, reason,
|
||||||
|
undo_payload)`
|
||||||
|
|
||||||
|
The two `ALTER TABLE ... ADD COLUMN` statements are applied with duplicate-column
|
||||||
|
guards so the migration is idempotent on replay; the rest of V14 uses
|
||||||
|
`CREATE ... IF NOT EXISTS`.
|
||||||
|
|
||||||
|
## Anti-patterns this design avoids
|
||||||
|
|
||||||
|
- **Silently double-storing contradictions.** Merge composition attributes and
|
||||||
|
de-duplicates content instead of blindly concatenating or dropping it.
|
||||||
|
- **Auto-deleting on contradiction.** Supersede invalidates bitemporally; the
|
||||||
|
old memory is retained and queryable.
|
||||||
|
- **Trading away the audit trail for auto-merge convenience.** Every operation is
|
||||||
|
logged and reversible, with provenance for why memories combined.
|
||||||
142
docs/ROADMAP.md
Normal file
142
docs/ROADMAP.md
Normal file
|
|
@ -0,0 +1,142 @@
|
||||||
|
# Vestige Roadmap
|
||||||
|
|
||||||
|
> Public adoption roadmap for making Vestige easier to start, easier to trust,
|
||||||
|
> and easier to configure.
|
||||||
|
|
||||||
|
Last updated: June 7, 2026
|
||||||
|
|
||||||
|
Vestige already has the core primitives for durable local memory: `search`,
|
||||||
|
`session_context`, `smart_ingest`, `memory`, `intention`, `codebase`,
|
||||||
|
`deep_reference`, suppression, portable storage, and the dashboard. The next
|
||||||
|
product step is reducing first-user confusion so more people can get value from
|
||||||
|
those primitives without inventing their own fragile memory vocabulary.
|
||||||
|
|
||||||
|
This roadmap turns early community feedback into a staged plan.
|
||||||
|
|
||||||
|
## Principles
|
||||||
|
|
||||||
|
- Make first use obvious. A new user should know what to import, how atomic each
|
||||||
|
memory should be, and which tool to use for current session context.
|
||||||
|
- Keep memory legible. Agents and humans should understand whether a memory was
|
||||||
|
created, reinforced, updated, superseded, suppressed, or purged.
|
||||||
|
- Prefer progressive disclosure. The default MCP response should be lean, with
|
||||||
|
explicit ways to request more detail.
|
||||||
|
- Keep local-first behavior. New onboarding, code memory, and configuration
|
||||||
|
features must not require a cloud service.
|
||||||
|
- Optimize for many users. Defaults should work for non-experts, while power
|
||||||
|
users can tune fields, merge behavior, and formats.
|
||||||
|
|
||||||
|
## Already Shipped, Needs Clearer Guidance
|
||||||
|
|
||||||
|
| Area | Current State | Next Documentation Fix |
|
||||||
|
|------|---------------|------------------------|
|
||||||
|
| Session startup | `session_context` combines memories, intentions, status, predictions, and codebase context. | Update all agent setup templates to make `session_context` the default startup call. |
|
||||||
|
| Batch memory saves | `smart_ingest` batch mode defaults to `batchMergePolicy="force_create"` so caller-separated items stay separate. | Document when to use batch force-create vs smart merge. |
|
||||||
|
| Device migration | `portable-export`, `portable-import`, and `sync` preserve exact Vestige storage state. | Separate device migration from first-time document import so users do not confuse them. |
|
||||||
|
| Supersede semantics | Supersede demotes the old memory and creates a new one; it does not purge the old memory. | Add plain-language vocabulary for create, update, supersede, suppress, demote, and purge. |
|
||||||
|
|
||||||
|
## Phase 1: Onboarding And Memory Hygiene
|
||||||
|
|
||||||
|
Target: make the first 30 minutes with Vestige hard to mess up.
|
||||||
|
|
||||||
|
| Work | Outcome |
|
||||||
|
|------|---------|
|
||||||
|
| First-time memory migration guide | Users can import notes/docs without Claude tagging everything as `verified` or flattening unrelated facts together. |
|
||||||
|
| Atomic memory guide | Clear examples for one fact, one preference, one decision, one bug fix, one source note, and one code pattern per memory. |
|
||||||
|
| Default tag vocabulary | Recommended tags for source quality, confidence, project, type, urgency, and lifecycle without overloading words like `verified`. |
|
||||||
|
| Smart vs force-create guide | Agents know when to use `forceCreate`, `batchMergePolicy="force_create"`, or normal PE gating. |
|
||||||
|
| Updated agent templates | Claude, Codex, Cursor, VS Code, Xcode, OpenCode, JetBrains, and Windsurf templates start with `session_context` and use the same memory vocabulary. |
|
||||||
|
|
||||||
|
Planned docs:
|
||||||
|
|
||||||
|
- `docs/MIGRATION.md`
|
||||||
|
- `docs/MEMORY-HYGIENE.md`
|
||||||
|
- revised `docs/AGENT-MEMORY-PROTOCOL.md`
|
||||||
|
- revised `docs/CLAUDE-SETUP.md`
|
||||||
|
|
||||||
|
## Phase 2: Configurable Output
|
||||||
|
|
||||||
|
Target: let users control context cost without losing important evidence.
|
||||||
|
|
||||||
|
| Work | Outcome |
|
||||||
|
|------|---------|
|
||||||
|
| Field masks for MCP results | Users can drop fields they never want in model context, such as temporal hints, scores, or timestamps. |
|
||||||
|
| Output profiles | Presets like `lean`, `default`, `audit`, and `research` tune result size and metadata detail. |
|
||||||
|
| Markdown output mode | Users can request compact Markdown summaries when that is more context-efficient than JSON. |
|
||||||
|
| Context reinstatement controls | `contextReinstatement` becomes opt-in or configurable, and temporal hints are based on stored memory context when available. |
|
||||||
|
| Per-tool defaults | Users can define default detail level, result limit, and response shape for search, timeline, codebase, and session context. |
|
||||||
|
|
||||||
|
Likely implementation paths:
|
||||||
|
|
||||||
|
- config file under the active Vestige data directory
|
||||||
|
- environment-variable override for simple deployments
|
||||||
|
- MCP parameters still win over defaults for one-off calls
|
||||||
|
|
||||||
|
## Phase 3: Merge And Supersede Controls
|
||||||
|
|
||||||
|
Target: make memory mutation predictable.
|
||||||
|
|
||||||
|
| Work | Outcome |
|
||||||
|
|------|---------|
|
||||||
|
| Merge policy configuration | Users can keep some tags or node types atomic while allowing others to merge. |
|
||||||
|
| Prediction Error threshold knobs | Advanced users can tune create/update/reinforce boundaries without recompiling. |
|
||||||
|
| Merge previews before mutation | Agents can show what would change before updating an existing durable memory. |
|
||||||
|
| Safer consolidation dedup | Consolidation respects user-configured atomic tags and source boundaries. |
|
||||||
|
| Friendlier lifecycle labels | Agent-facing copy explains that superseded memories are old versions, not destroyed records. |
|
||||||
|
|
||||||
|
## Phase 4: Code Memory
|
||||||
|
|
||||||
|
Target: make code memories useful without blending source code, docstrings, and
|
||||||
|
human project notes into one noisy search space.
|
||||||
|
|
||||||
|
| Work | Outcome |
|
||||||
|
|------|---------|
|
||||||
|
| Code memory import guide | Developers know when to save patterns/decisions versus code entities or docstrings. |
|
||||||
|
| Exposed code entity workflow | The existing core `CodeEntity` concept becomes usable through MCP or CLI. |
|
||||||
|
| Docstring/code symbol ingestion | Users can ingest functions, types, modules, docstrings, and call-site notes with source file provenance. |
|
||||||
|
| Code/prose retrieval separation | Search can filter or rank code memories separately from user preferences and project decisions. |
|
||||||
|
| Codebase dashboard review | Developers can inspect imported code memories and remove noisy entries. |
|
||||||
|
|
||||||
|
## Phase 5: Goals And Milestones
|
||||||
|
|
||||||
|
Target: support durable direction without pretending every future task is just a
|
||||||
|
reminder.
|
||||||
|
|
||||||
|
| Work | Outcome |
|
||||||
|
|------|---------|
|
||||||
|
| Goal primitive | Non-fading, manually pivoted goals that survive normal memory decay. |
|
||||||
|
| Milestone tracking | Goals can have milestones, status, evidence, and blockers. |
|
||||||
|
| Goal-aware session context | `session_context` can include active goals when relevant. |
|
||||||
|
| Manual pivot semantics | Agents can update goals only when the user explicitly pivots, completes, or cancels them. |
|
||||||
|
| Dashboard surface | Users can inspect active, completed, paused, and cancelled goals. |
|
||||||
|
|
||||||
|
This is distinct from `intention`: intentions are reminders triggered by time,
|
||||||
|
topic, file, event, or context. Goals are longer-lived direction and should not
|
||||||
|
fire as reminders unless the user attaches an intention.
|
||||||
|
|
||||||
|
## Phase 6: Guided Import Tools
|
||||||
|
|
||||||
|
Target: turn "I have 300 notes" into a reliable workflow.
|
||||||
|
|
||||||
|
| Work | Outcome |
|
||||||
|
|------|---------|
|
||||||
|
| Import dry run | Vestige previews proposed memories, tags, node types, and merge decisions before writing. |
|
||||||
|
| Source-aware import | Imported memories keep file/source provenance and confidence metadata. |
|
||||||
|
| Chunking strategies | Users choose atomic facts, section summaries, decision records, or source notes. |
|
||||||
|
| Review queue | Users can approve, edit, split, merge, or reject proposed memories. |
|
||||||
|
| Post-import health pass | Vestige recommends consolidation, duplicate review, or tag cleanup after import. |
|
||||||
|
|
||||||
|
## Non-Goals
|
||||||
|
|
||||||
|
- Do not auto-store every conversation turn by default.
|
||||||
|
- Do not require cloud services for memory creation, search, or configuration.
|
||||||
|
- Do not hide irreversible deletion. `purge` must stay explicit.
|
||||||
|
- Do not make code ingestion pollute general personal memory by default.
|
||||||
|
- Do not make advanced tuning required for ordinary users.
|
||||||
|
|
||||||
|
## How To Read This Roadmap
|
||||||
|
|
||||||
|
This is directional, not a release guarantee. The priority is adoption: fewer
|
||||||
|
surprises, clearer defaults, and better tool descriptions before adding complex
|
||||||
|
new surfaces. Community feedback that reveals a confusing first-use path should
|
||||||
|
usually become either a documentation fix, a safer default, or a guided workflow.
|
||||||
|
|
@ -12,6 +12,8 @@ instead of opaque. The current schema is `vestige.sanhedrin.receipt.v1`.
|
||||||
- Appeals: `~/.vestige/sanhedrin/appeals.jsonl`
|
- Appeals: `~/.vestige/sanhedrin/appeals.jsonl`
|
||||||
- Fail-open events: `~/.vestige/sanhedrin/fail-open.jsonl`
|
- Fail-open events: `~/.vestige/sanhedrin/fail-open.jsonl`
|
||||||
|
|
||||||
|
Optional companion schema: [`SANHEDRIN_TEST_INTEGRITY_DELTAS.md`](SANHEDRIN_TEST_INTEGRITY_DELTAS.md) describes mechanical deltas for cases where a verifier command passed but the test artifact changed after implementation.
|
||||||
|
|
||||||
## v1 JSON Shape
|
## v1 JSON Shape
|
||||||
|
|
||||||
```json
|
```json
|
||||||
|
|
|
||||||
111
docs/SANHEDRIN_TEST_INTEGRITY_DELTAS.md
Normal file
111
docs/SANHEDRIN_TEST_INTEGRITY_DELTAS.md
Normal file
|
|
@ -0,0 +1,111 @@
|
||||||
|
# Sanhedrin Test-Integrity Delta Receipts
|
||||||
|
|
||||||
|
Receipt Lock proves a narrower claim: a verification command actually ran and
|
||||||
|
succeeded. Test-integrity deltas are an optional companion receipt for the
|
||||||
|
stronger claim that the tests still mean what the draft says they mean.
|
||||||
|
|
||||||
|
This receipt is intentionally mechanical. It is not a broad correctness oracle
|
||||||
|
and it does not ask a second model to decide whether the implementation is good.
|
||||||
|
It records whether the verification artifact changed in ways that should
|
||||||
|
upgrade, downgrade, or send the verification claim to human review.
|
||||||
|
|
||||||
|
## Boundary
|
||||||
|
|
||||||
|
Keep these claims separate:
|
||||||
|
|
||||||
|
1. **Command receipt:** `cargo test`, `npm test`, `pytest`, or another verifier
|
||||||
|
command ran after the relevant edit and exited successfully.
|
||||||
|
2. **Test-integrity delta:** the tests/specs behind that verifier were not
|
||||||
|
removed, skipped, weakened, or replaced after implementation in a way that
|
||||||
|
makes the green result less admissible.
|
||||||
|
|
||||||
|
A run can have a valid command receipt and still receive a downgraded
|
||||||
|
integrity decision.
|
||||||
|
|
||||||
|
## Optional JSON Shape
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"schema": "vestige.sanhedrin.test_integrity_delta.v1",
|
||||||
|
"id": "tid_<stable hash>",
|
||||||
|
"commandReceiptId": "receipt_<stable hash>",
|
||||||
|
"verificationClaim": "All tests passed.",
|
||||||
|
"specSource": {
|
||||||
|
"contextId": "spec_ctx_04",
|
||||||
|
"testFiles": [
|
||||||
|
{
|
||||||
|
"path": "tests/cart.test.ts",
|
||||||
|
"hashBeforeImplementation": "sha256:...",
|
||||||
|
"hashAfterVerification": "sha256:..."
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"implementationContext": "impl_ctx_09",
|
||||||
|
"verifierContext": "verify_ctx_02",
|
||||||
|
"delta": {
|
||||||
|
"testFilesChangedAfterImplementation": true,
|
||||||
|
"removedOrDisabledTests": [
|
||||||
|
{
|
||||||
|
"kind": "skip_or_only",
|
||||||
|
"path": "tests/cart.test.ts",
|
||||||
|
"line": 42
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"removedAssertions": 2,
|
||||||
|
"weakenedExpectations": [
|
||||||
|
{
|
||||||
|
"path": "tests/cart.test.ts",
|
||||||
|
"from": "throws InvalidCouponError",
|
||||||
|
"to": "does not throw"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"snapshotChurnWithoutSourceChange": false,
|
||||||
|
"coverageDelta": -3.8,
|
||||||
|
"mocksReplacingRealBoundary": [
|
||||||
|
{
|
||||||
|
"module": "PaymentGateway",
|
||||||
|
"before": "integration-ish fake",
|
||||||
|
"after": "empty stub"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"freshVerifier": {
|
||||||
|
"commandReceiptId": "receipt_<stable hash>",
|
||||||
|
"exitCode": 0,
|
||||||
|
"checkedAfterLastRelevantEdit": true
|
||||||
|
},
|
||||||
|
"decision": "downgraded",
|
||||||
|
"reason": "tests passed, but the tests were weakened after implementation"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Decisions
|
||||||
|
|
||||||
|
- `accepted` — a verifier command succeeded after the last relevant edit and no
|
||||||
|
integrity downgrade was detected.
|
||||||
|
- `downgraded` — the command succeeded, but the tests/specs changed in a way
|
||||||
|
that makes the verification claim weaker than stated.
|
||||||
|
- `needs_human_review` — the delta may be legitimate, but a local mechanical
|
||||||
|
check cannot safely classify it. Snapshot updates are a common example.
|
||||||
|
|
||||||
|
## Minimal Fixture Suite
|
||||||
|
|
||||||
|
These cases are small enough to live as fixtures without turning Sanhedrin into
|
||||||
|
a correctness judge. Machine-readable examples live in
|
||||||
|
[`docs/fixtures/sanhedrin-test-integrity-deltas/`](fixtures/sanhedrin-test-integrity-deltas/).
|
||||||
|
|
||||||
|
| Case | Input pattern | Expected decision | Why |
|
||||||
|
| --- | --- | --- | --- |
|
||||||
|
| unchanged-good | implementation changes source; tests unchanged; fresh verifier succeeds | `accepted` | Green tests are supported by a fresh command receipt and unchanged test artifact. |
|
||||||
|
| skipped-test | implementation adds `.skip`, `.only`, `#[ignore]`, or equivalent before verifier succeeds | `downgraded` | The command ran, but the claim no longer represents the original test obligation. |
|
||||||
|
| weakened-assertion | expectation is relaxed after implementation, e.g. `throws InvalidCouponError` -> `does not throw` | `downgraded` | The verifier passed against a weaker assertion than the one available before implementation. |
|
||||||
|
| justified-snapshot | snapshot changes alongside an intentional source/UI change | `needs_human_review` or `accepted` by policy | Snapshot churn can be valid, but the receipt should make the policy decision explicit. |
|
||||||
|
|
||||||
|
## Non-goals
|
||||||
|
|
||||||
|
- Do not infer whether the implementation is correct in the world.
|
||||||
|
- Do not require full semantic diffing before Receipt Lock can operate.
|
||||||
|
- Do not treat staged evidence or a model explanation as equivalent to a fresh
|
||||||
|
command receipt.
|
||||||
|
- Do not block every test edit. The goal is to keep the verification claim
|
||||||
|
honest when the test artifact changed after implementation.
|
||||||
|
|
@ -73,8 +73,8 @@ Vestige is organized as:
|
||||||
|
|
||||||
HTTP MCP is disabled unless the user passes `--http`, passes `--http-port`, or
|
HTTP MCP is disabled unless the user passes `--http`, passes `--http-port`, or
|
||||||
sets `VESTIGE_HTTP_ENABLED=1`. The stdio MCP server remains the portable default
|
sets `VESTIGE_HTTP_ENABLED=1`. The stdio MCP server remains the portable default
|
||||||
for Claude Code, Codex, Cursor, VS Code, Xcode, JetBrains, Windsurf, and other
|
for Claude Code, Codex, Cursor, VS Code, Xcode, OpenCode, JetBrains, Windsurf,
|
||||||
clients.
|
and other clients.
|
||||||
|
|
||||||
Purge is implemented transactionally in storage and surfaced through the MCP
|
Purge is implemented transactionally in storage and surfaced through the MCP
|
||||||
`memory` tool. `memory(action="purge", confirm=true)` is the explicit hard
|
`memory` tool. `memory(action="purge", confirm=true)` is the explicit hard
|
||||||
|
|
|
||||||
303
docs/adr/0001-pluggable-storage-and-network-access.md
Normal file
303
docs/adr/0001-pluggable-storage-and-network-access.md
Normal file
|
|
@ -0,0 +1,303 @@
|
||||||
|
# ADR 0001: Pluggable Storage Backend, Network Access, and Emergent Domains
|
||||||
|
|
||||||
|
**Status**: Accepted
|
||||||
|
**Date**: 2026-04-21
|
||||||
|
**Related**: [docs/prd/001-getting-centralized-vestige.md](../prd/001-getting-centralized-vestige.md)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Context
|
||||||
|
|
||||||
|
Vestige v2.x runs as a per-machine local process: stdio MCP transport, SQLite +
|
||||||
|
FTS5 + USearch HNSW in `~/.vestige/`, fastembed locally for embeddings. This is
|
||||||
|
ideal for single-machine single-agent use but blocks three real needs:
|
||||||
|
|
||||||
|
- **Multi-machine access** -- same memory brain from laptop, desktop, server
|
||||||
|
- **Multi-agent access** -- multiple AI clients against one store concurrently
|
||||||
|
- **Future federation** -- syncing memory between decentralized nodes (MOS /
|
||||||
|
Threefold grid)
|
||||||
|
|
||||||
|
SQLite's single-writer model and lack of a native network protocol make it
|
||||||
|
unsuitable as a centralized server. PostgreSQL + pgvector collapses our three
|
||||||
|
storage layers (SQLite, FTS5, USearch) into one engine with MVCC concurrency,
|
||||||
|
auth, and replication.
|
||||||
|
|
||||||
|
Separately, Vestige today has no notion of domain or project scope -- all memories
|
||||||
|
share one namespace. For a multi-machine brain, users want soft topical
|
||||||
|
boundaries ("dev", "infra", "home") without manual tenanting. HDBSCAN clustering
|
||||||
|
on embeddings produces these boundaries from the data itself.
|
||||||
|
|
||||||
|
The PRD at `docs/prd/001-getting-centralized-vestige.md` sketches the full design.
|
||||||
|
This ADR records the architectural decisions and resolves the open questions from
|
||||||
|
that document.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Decision
|
||||||
|
|
||||||
|
Introduce two new trait boundaries, a network transport layer, and a domain
|
||||||
|
classification module. All four changes ship in parallel phases.
|
||||||
|
|
||||||
|
**Trait boundaries:**
|
||||||
|
|
||||||
|
1. `MemoryStore` -- single trait covering CRUD, hybrid search, FSRS scheduling,
|
||||||
|
graph edges, and domains. One big trait, not four.
|
||||||
|
2. `Embedder` -- separate trait for text-to-vector encoding. Storage never calls
|
||||||
|
fastembed directly. Callers (cognitive engine locally, HTTP server remotely)
|
||||||
|
compute embeddings and pass them into the store.
|
||||||
|
|
||||||
|
**Backends:**
|
||||||
|
|
||||||
|
- `SqliteMemoryStore` -- existing code refactored behind the trait, no behavior
|
||||||
|
change.
|
||||||
|
- `PgMemoryStore` -- new, using sqlx + pgvector + tsvector. Selectable at runtime
|
||||||
|
via `vestige.toml`.
|
||||||
|
|
||||||
|
**Network:**
|
||||||
|
|
||||||
|
- MCP over Streamable HTTP on the existing Axum server.
|
||||||
|
- API key auth middleware (blake3-hashed, stored in `api_keys` table).
|
||||||
|
- Dashboard uses the same API keys for login, then signed session cookies for
|
||||||
|
subsequent requests.
|
||||||
|
|
||||||
|
**Domain classification:**
|
||||||
|
|
||||||
|
- HDBSCAN clustering over embeddings to discover domains automatically.
|
||||||
|
- Soft multi-domain assignment -- raw similarity scores stored per memory, every
|
||||||
|
domain above a threshold is assigned.
|
||||||
|
- Conservative drift handling -- propose splits/merges, never auto-apply.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Architecture Overview
|
||||||
|
|
||||||
|
### Component Breakdown
|
||||||
|
|
||||||
|
1. **`Embedder` trait** (new module `crates/vestige-core/src/embedder/`)
|
||||||
|
- `async fn embed(&self, text: &str) -> Result<Vec<f32>>`
|
||||||
|
- `fn model_name(&self) -> &str`
|
||||||
|
- `fn dimension(&self) -> usize`
|
||||||
|
- Impls: `FastembedEmbedder` (local ONNX, today), future `JinaEmbedder`,
|
||||||
|
`OpenAiEmbedder`, etc.
|
||||||
|
- Stays pluggable forever -- no lock-in to fastembed or to nomic-embed-text.
|
||||||
|
|
||||||
|
2. **`MemoryStore` trait** (new module `crates/vestige-core/src/storage/trait.rs`)
|
||||||
|
- One trait, ~25 methods across CRUD, search, FSRS, graph, domain sections.
|
||||||
|
- Uses `trait_variant::make` to generate a `Send`-bound variant for
|
||||||
|
`Arc<dyn MemoryStore>` in Axum/tokio contexts.
|
||||||
|
- The 29 cognitive modules operate exclusively through this trait. No direct
|
||||||
|
SQLite or Postgres access from the modules.
|
||||||
|
|
||||||
|
3. **`SqliteMemoryStore`** (refactor of existing `crates/vestige-core/src/storage/sqlite.rs`)
|
||||||
|
- Existing rusqlite + FTS5 + USearch code, wrapped behind the trait.
|
||||||
|
- Add `domains TEXT[]` equivalent (JSON-encoded array column in SQLite).
|
||||||
|
- Add `domain_scores` JSON column.
|
||||||
|
- No behavioral change for current users.
|
||||||
|
|
||||||
|
4. **`PgMemoryStore`** (new `crates/vestige-core/src/storage/postgres.rs`)
|
||||||
|
- `sqlx::PgPool` with compile-time checked queries.
|
||||||
|
- pgvector HNSW index for vector search, tsvector + GIN for FTS.
|
||||||
|
- Native array columns for `domains`, JSONB for `domain_scores` and `metadata`.
|
||||||
|
- Hybrid search via RRF (Reciprocal Rank Fusion) in a single SQL query.
|
||||||
|
|
||||||
|
5. **Model registry**
|
||||||
|
- Per-database table `embedding_model` with `(name, dimension, hash, created_at)`.
|
||||||
|
- Both backends refuse writes from an embedder whose signature doesn't match
|
||||||
|
the registered row.
|
||||||
|
- Model swap = `vestige migrate --reembed --model=<new>`, O(n) cost, explicit.
|
||||||
|
|
||||||
|
6. **`DomainClassifier` cognitive module** (new `crates/vestige-core/src/neuroscience/domain_classifier.rs`)
|
||||||
|
- Owns the HDBSCAN discovery pass (using the `hdbscan` crate).
|
||||||
|
- Computes soft-assignment scores for every memory against every centroid.
|
||||||
|
- Stores raw `domain_scores: HashMap<String, f64>` per memory; thresholds into
|
||||||
|
the `domains` array using `assign_threshold` (default 0.65).
|
||||||
|
- Runs discovery on demand (`vestige domains discover`) or during dream
|
||||||
|
consolidation passes.
|
||||||
|
|
||||||
|
7. **HTTP MCP transport** (extension of existing Axum server in `crates/vestige-mcp/src/`)
|
||||||
|
- New route `POST /mcp` for Streamable HTTP JSON-RPC.
|
||||||
|
- New route `GET /mcp` for SSE (for long-running operations).
|
||||||
|
- REST API under `/api/v1/` for direct HTTP clients (non-MCP integrations).
|
||||||
|
- Auth middleware validates `Authorization: Bearer ...` or `X-API-Key`, plus
|
||||||
|
signed session cookies for dashboard.
|
||||||
|
|
||||||
|
8. **Key management** (new `crates/vestige-mcp/src/auth/`)
|
||||||
|
- `api_keys` table -- blake3-hashed keys, scopes, optional domain filter,
|
||||||
|
last-used timestamp.
|
||||||
|
- CLI: `vestige keys create|list|revoke`.
|
||||||
|
|
||||||
|
9. **FSRS review event log** (future-proofing for federation)
|
||||||
|
- New table `review_events` -- append-only `(memory_id, timestamp, rating,
|
||||||
|
prior_state, new_state)`.
|
||||||
|
- Current `scheduling` table becomes a materialized view over the event log
|
||||||
|
(reconstructible from events).
|
||||||
|
- Phase 5 federation merges event logs, not derived state. Zero cost today,
|
||||||
|
avoids lock-in tomorrow.
|
||||||
|
|
||||||
|
### Data Flow
|
||||||
|
|
||||||
|
**Local mode (stdio MCP, unchanged UX):**
|
||||||
|
```
|
||||||
|
stdio client -> McpServer -> CognitiveEngine -> FastembedEmbedder -> MemoryStore (SQLite)
|
||||||
|
```
|
||||||
|
|
||||||
|
**Server mode (HTTP MCP, new):**
|
||||||
|
```
|
||||||
|
Remote client -> Axum HTTP -> auth middleware -> CognitiveEngine
|
||||||
|
-> FastembedEmbedder (server-side) -> MemoryStore (Postgres)
|
||||||
|
```
|
||||||
|
|
||||||
|
The cognitive engine is backend-agnostic. The embedder and the store are both
|
||||||
|
swappable. The 7-stage search pipeline (overfetch -> cross-encoder rerank ->
|
||||||
|
temporal -> accessibility -> context match -> competition -> spreading activation)
|
||||||
|
sits *above* the `MemoryStore` trait and works identically against either backend.
|
||||||
|
|
||||||
|
### Orthogonality of HDBSCAN and Reranking
|
||||||
|
|
||||||
|
HDBSCAN and the cross-encoder reranker solve different problems and both stay:
|
||||||
|
|
||||||
|
- **HDBSCAN** discovers domains by clustering embeddings. Runs once per discovery
|
||||||
|
pass. Produces centroids. Used to *filter* search candidates, not to rank them.
|
||||||
|
- **Cross-encoder reranker** (Jina Reranker v1 Turbo) scores query-document pairs
|
||||||
|
at search time. Runs on every search. Produces ranked results.
|
||||||
|
|
||||||
|
Domain membership is a filter applied before or during overfetch; reranking runs
|
||||||
|
on whatever candidate set survives the filter.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Alternatives Considered
|
||||||
|
|
||||||
|
| Alternative | Pros | Cons | Why Not |
|
||||||
|
|-------------|------|------|---------|
|
||||||
|
| Split into 4 traits (`MemoryStore + SchedulingStore + GraphStore + DomainStore`) | Cleaner interface segregation | Every module holds 4 trait objects, coordinates transactions across them | One trait is fine in Rust; extract sub-traits later if a genuine need appears |
|
||||||
|
| Embedding computed inside the backend | Simpler call sites for callers | Backend becomes aware of embedding models; can't support remote clients without local fastembed | Keep storage pure; separate `Embedder` trait handles pluggability |
|
||||||
|
| Unconstrained pgvector `vector` (no dimension) | Flexible for model swaps | HNSW still needs fixed dims at index creation; hides a meaningful migration as "silent" | Fixed dimension per install, explicit `--reembed` migration |
|
||||||
|
| Dashboard separate auth (cookies only, no keys) | Simpler dashboard UX | Two auth systems to maintain | Shared API keys with session cookie layer on top |
|
||||||
|
| Auto-tuned `assign_threshold` targeting an unclassified ratio | Adapts to corpus | Hard to debug ("why did this memory change domain?"); magical | Static 0.65 default, config-tunable, dashboard shows `domain_scores` for manual retuning |
|
||||||
|
| Aggressive drift (auto-reassign memories whose scores drifted) | Always up-to-date domains | Breaks user muscle memory; silent reshuffling | Conservative: always propose, user accepts |
|
||||||
|
| CRDTs for federation state | Mathematically clean merges | Massive complexity, performance cost, overkill | Defer; design FSRS as event log now so any future sync model works |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Consequences
|
||||||
|
|
||||||
|
### Positive
|
||||||
|
|
||||||
|
- Single memory brain accessible from every machine.
|
||||||
|
- Multi-agent concurrent access via Postgres MVCC.
|
||||||
|
- Natural topical scoping emerges from data, not manual tenants.
|
||||||
|
- Future embedding model swaps are a config + migration, not a rewrite.
|
||||||
|
- Federation has a clean on-ramp (event log merge) without committing now.
|
||||||
|
- The `Embedder` / `MemoryStore` split unlocks other storage backends later
|
||||||
|
(Redis, Qdrant, Iroh-backed blob store, etc.) with minimal work.
|
||||||
|
|
||||||
|
### Negative
|
||||||
|
|
||||||
|
- Operating a Postgres instance is more work than managing a SQLite file.
|
||||||
|
- Users who stay on SQLite gain nothing from this ADR (but lose nothing either).
|
||||||
|
- Migration (`vestige migrate --from sqlite --to postgres`) is a sensitive
|
||||||
|
operation for users with months of memories -- needs strong testing.
|
||||||
|
- HDBSCAN + re-soft-assignment runs in O(n) over all embeddings. At 100k+
|
||||||
|
memories this starts to matter; manageable but not free.
|
||||||
|
|
||||||
|
### Risks
|
||||||
|
|
||||||
|
- **Trait abstraction leaks**: a cognitive module might need backend-specific
|
||||||
|
behavior (e.g., Postgres triggers for tsvector). Mitigation: keep such logic
|
||||||
|
inside the backend impl; the trait stays pure.
|
||||||
|
Escalation: if a module genuinely cannot express what it needs through the
|
||||||
|
trait, the trait grows, not the module bypasses.
|
||||||
|
- **Embedding model drift**: users on older fastembed versions silently
|
||||||
|
producing slightly different vectors after a fastembed upgrade. Mitigation:
|
||||||
|
model hash in the registry, refuse mismatched writes, surface a clear error.
|
||||||
|
- **Auth misconfiguration**: a user binds to `0.0.0.0` without setting
|
||||||
|
`auth.enabled = true`. Mitigation: refuse to start with non-localhost bind
|
||||||
|
and auth disabled. Hard error, not a warning.
|
||||||
|
- **Re-clustering feedback loop**: dream consolidation proposes re-clusters,
|
||||||
|
which the user accepts, which changes classifications, which affects future
|
||||||
|
retrievals, which affect future dreams. Mitigation: cap re-cluster frequency
|
||||||
|
(every 5th dream by default), require explicit user acceptance of proposals.
|
||||||
|
- **Cross-domain spreading activation weight (0.5 default)**: arbitrary choice;
|
||||||
|
could be too aggressive or too lax. Mitigation: config-tunable; instrument
|
||||||
|
retrieval quality metrics in the dashboard so the user sees impact.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Resolved Decisions (from Q&A)
|
||||||
|
|
||||||
|
| # | Question | Resolution |
|
||||||
|
|---|----------|------------|
|
||||||
|
| 1 | Trait granularity | Single `MemoryStore` trait |
|
||||||
|
| 2 | Embedding on insert | Caller provides; separate `Embedder` trait for pluggability |
|
||||||
|
| 3 | pgvector dimension | Fixed per install, derived from `Embedder::dimension()` at schema init |
|
||||||
|
| 4 | Federation sync | Defer algorithm; store FSRS reviews as append-only event log now |
|
||||||
|
| 5 | Dashboard auth | Shared API keys + signed session cookie |
|
||||||
|
| 6 | HDBSCAN `min_cluster_size` | Default 10; user reruns with `--min-cluster-size N`; no auto-sweep |
|
||||||
|
| 7 | Domain drift | Conservative -- always propose splits/merges, never auto-apply |
|
||||||
|
| 8 | Cross-domain spreading activation | Follow with decay factor 0.5 (tunable) |
|
||||||
|
| 9 | Assignment threshold | Static 0.65 default, config-tunable, raw `domain_scores` stored for introspection |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Implementation Plan
|
||||||
|
|
||||||
|
Five phases, each independently shippable.
|
||||||
|
|
||||||
|
### Phase 1: Storage trait extraction
|
||||||
|
- Define `MemoryStore` and `Embedder` traits in `vestige-core`.
|
||||||
|
- Refactor `SqliteMemoryStore` to implement `MemoryStore`; no behavior change.
|
||||||
|
- Refactor `FastembedEmbedder` to implement `Embedder`.
|
||||||
|
- Add `embedding_model` registry table; enforce consistency on write.
|
||||||
|
- Add `domains TEXT[]`-equivalent and `domain_scores` JSON columns to SQLite
|
||||||
|
(empty for all existing rows).
|
||||||
|
- Convert all 29 cognitive modules to operate via the traits.
|
||||||
|
- **Acceptance**: existing test suite passes unchanged. Zero warnings.
|
||||||
|
|
||||||
|
### Phase 2: PostgreSQL backend
|
||||||
|
- `PgMemoryStore` with sqlx, pgvector, tsvector.
|
||||||
|
- sqlx migrations (`crates/vestige-core/migrations/postgres/`).
|
||||||
|
- Backend selection via `vestige.toml` `[storage]` section.
|
||||||
|
- `vestige migrate --from sqlite --to postgres` command.
|
||||||
|
- `vestige migrate --reembed` command for model swaps.
|
||||||
|
- **Acceptance**: full test suite runs green against Postgres with a testcontainer.
|
||||||
|
|
||||||
|
### Phase 3: Network access
|
||||||
|
- Streamable HTTP MCP route on Axum (`POST /mcp`, `GET /mcp` for SSE).
|
||||||
|
- REST API under `/api/v1/`.
|
||||||
|
- API key table + blake3 hashing + `vestige keys create|list|revoke`.
|
||||||
|
- Auth middleware (Bearer, X-API-Key, session cookie).
|
||||||
|
- Refuse non-localhost bind without auth enabled.
|
||||||
|
- **Acceptance**: MCP client over HTTP works from a second machine; dashboard
|
||||||
|
login flow works; unauth requests return 401.
|
||||||
|
|
||||||
|
### Phase 4: Emergent domain classification
|
||||||
|
- `DomainClassifier` module using the `hdbscan` crate.
|
||||||
|
- `vestige domains discover|list|rename|merge` CLI.
|
||||||
|
- Automatic soft-assignment pipeline (compute `domain_scores` on ingest, threshold
|
||||||
|
into `domains`).
|
||||||
|
- Re-cluster every Nth dream consolidation (default 5); surface proposals in the
|
||||||
|
dashboard.
|
||||||
|
- Context signals (git repo, IDE) as soft priors on classification.
|
||||||
|
- Cross-domain spreading activation with 0.5 decay.
|
||||||
|
- **Acceptance**: on a corpus of 500+ mixed memories, discover produces sensible
|
||||||
|
clusters; search scoped to a domain returns tightly relevant results.
|
||||||
|
|
||||||
|
### Phase 5: Federation (future, explicitly out of scope for this ADR's
|
||||||
|
acceptance)
|
||||||
|
- Node discovery (Mycelium / mDNS).
|
||||||
|
- Memory sync protocol over append-only review events and LWW-per-UUID for
|
||||||
|
memory records.
|
||||||
|
- Explicit follow-up ADR before any code.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Open Questions
|
||||||
|
|
||||||
|
None at ADR acceptance time. Follow-up items that are *implementation choices*,
|
||||||
|
not architectural:
|
||||||
|
|
||||||
|
- Precise cross-domain decay weight (start at 0.5, instrument, tune)
|
||||||
|
- Dashboard histogram of `domain_scores` (UX design detail)
|
||||||
|
- Whether to gate Postgres behind a Cargo feature flag (`postgres-backend`) or
|
||||||
|
always compile it in (lean toward feature flag to keep SQLite-only builds small)
|
||||||
545
docs/adr/0002-phase-2-execution.md
Normal file
545
docs/adr/0002-phase-2-execution.md
Normal file
|
|
@ -0,0 +1,545 @@
|
||||||
|
# ADR 0002: Phase 2 Execution -- Postgres Backend Integration, Phase 1 Amendment
|
||||||
|
|
||||||
|
**Status**: Accepted
|
||||||
|
**Date**: 2026-05-26
|
||||||
|
**Related**: [docs/adr/0001-pluggable-storage-and-network-access.md](0001-pluggable-storage-and-network-access.md), [docs/plans/0002-phase-2-postgres-backend.md](../plans/0002-phase-2-postgres-backend.md)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Context
|
||||||
|
|
||||||
|
ADR 0001 set the architectural direction: introduce `MemoryStore` and `Embedder`
|
||||||
|
traits, ship a Postgres backend behind a feature flag, and reach a single shared
|
||||||
|
memory brain across machines. Phase 1 (storage trait extraction) shipped on
|
||||||
|
`feat/storage-trait-phase1` (790c0c8). The Phase 2 master plan at
|
||||||
|
`docs/plans/0002-phase-2-postgres-backend.md` was drafted before Phase 1 was
|
||||||
|
frozen.
|
||||||
|
|
||||||
|
Starting Phase 2 surfaces a small set of execution-level decisions that ADR 0001
|
||||||
|
did not cover and that the master plan now disagrees with the live code on.
|
||||||
|
These decisions are too big to silently absorb into a per-step plan and too
|
||||||
|
small to amend ADR 0001. They live here.
|
||||||
|
|
||||||
|
Three concrete realities driving this ADR:
|
||||||
|
|
||||||
|
1. **Trait shape mismatch.** Master plan 0002 assumed `trait_variant::make`
|
||||||
|
produced distinct `MemoryStore` (Send-bound) and `LocalMemoryStore`
|
||||||
|
(non-Send) variants, and that errors were `StoreError`. Phase 1 froze on
|
||||||
|
`#[async_trait::async_trait]` with `pub use MemoryStore as LocalMemoryStore`
|
||||||
|
and an error type called `MemoryStoreError`. The Postgres backend has to
|
||||||
|
follow Phase 1, not the master plan -- but we should record that explicitly.
|
||||||
|
2. **`SqliteMemoryStore` is monolithic.**
|
||||||
|
`crates/vestige-core/src/storage/sqlite.rs` is ~8200 lines. Phase 1 appended
|
||||||
|
the trait impl block at the bottom of the same file. Adding a similarly
|
||||||
|
large `postgres.rs` perpetuates the pattern; this is the natural moment to
|
||||||
|
decide whether the SQLite file gets split.
|
||||||
|
3. **Constructor surface drift.** Master plan 0002 specifies
|
||||||
|
`PgMemoryStore::connect(url, max_connections, &dyn Embedder)`. The Phase 1
|
||||||
|
`SqliteMemoryStore` constructor takes no embedder -- registry consistency
|
||||||
|
runs through `registered_model()` / `register_model()` on the trait,
|
||||||
|
invoked by the caller. The two backends should look the same to a caller;
|
||||||
|
right now they would not.
|
||||||
|
4. **Multi-tenancy is a one-way door.** The Postgres schema is the place to
|
||||||
|
reserve user/group/visibility columns *now*, even though Phase 3 is the
|
||||||
|
phase that wires the auth filter using them. Adding `owner_user_id` and
|
||||||
|
GIN indexes to a populated, HNSW-indexed `knowledge_nodes` table later is an
|
||||||
|
expensive online migration; reserving NULL-defaulted columns at schema
|
||||||
|
creation is ~10 lines of SQL. The same logic applies to per-memory
|
||||||
|
context capture (codebase, MCP caller, session) -- promoting `codebase`
|
||||||
|
to a first-class column now keeps the door open for context-aware
|
||||||
|
sharing rules in Phase 4 without touching `knowledge_nodes`. See D7 and D8.
|
||||||
|
|
||||||
|
This ADR is also the umbrella under which Phase 2 sub-plans (`0002a-...`,
|
||||||
|
`0002b-...`, etc.) sit. The intent is: ADR + sub-plans land as one PR for
|
||||||
|
review; the implementation lands as a second PR with many commits inside.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Already Decided (carried in by reference)
|
||||||
|
|
||||||
|
These are settled by ADR 0001 or by explicit agreement during this session.
|
||||||
|
Listed here so the discussion frame is clear; not re-litigated below.
|
||||||
|
|
||||||
|
- Postgres backend ships behind a `postgres-backend` Cargo feature, default
|
||||||
|
OFF. Mutually compilable with SQLite. (ADR 0001.)
|
||||||
|
- Single big `MemoryStore` trait. `PgMemoryStore` implements the same surface
|
||||||
|
as `SqliteMemoryStore`. (ADR 0001.)
|
||||||
|
- pgvector HNSW + tsvector + GIN + RRF hybrid search in one SQL statement.
|
||||||
|
(Master plan 0002, D4-D5.)
|
||||||
|
- sqlx 0.8 + pgvector 0.4 + compile-time-checked queries + offline `.sqlx/`
|
||||||
|
cache committed. (Master plan 0002.)
|
||||||
|
- Two sqlx migration files: `0001_init` (extensions, tables, non-vector
|
||||||
|
indexes) and `0002_hnsw` (HNSW separated for re-embed drop/recreate).
|
||||||
|
(Master plan 0002, D4.)
|
||||||
|
- `vestige migrate --from sqlite --to postgres` and
|
||||||
|
`vestige migrate --reembed --model=<new>` CLI subcommands. (ADR 0001 +
|
||||||
|
master plan 0002, D8-D10.)
|
||||||
|
- PR cadence: PR #1 carries this ADR plus all sub-plans; PR #2 carries the
|
||||||
|
implementation as many commits.
|
||||||
|
- Sub-plans use `0002a-`, `0002b-`, ... suffixes off `0002-`.
|
||||||
|
- `PgMemoryStore::connect` lands as `todo!()` in the skeleton; real body
|
||||||
|
comes later.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Decisions
|
||||||
|
|
||||||
|
### D1. Sunset async_trait across the Phase 1 traits
|
||||||
|
|
||||||
|
Phase 1 froze with `#[async_trait::async_trait]` on both the `MemoryStore`
|
||||||
|
trait (`storage/memory_store.rs:194`) and the `Embedder` trait
|
||||||
|
(`embedder/mod.rs:27`), plus their SQLite and Fastembed impl blocks. async_trait
|
||||||
|
boxes every async fn into `Pin<Box<dyn Future + Send>>` -- one heap allocation
|
||||||
|
per call inside the hottest code path. We are amending Phase 1 to remove
|
||||||
|
async_trait entirely and replace it with `trait_variant::make`, so each trait
|
||||||
|
becomes two real generated variants (`MemoryStore` / `LocalMemoryStore`,
|
||||||
|
`Embedder` / `LocalEmbedder`) with `Send` bounds on the outer variant.
|
||||||
|
|
||||||
|
Scope split across three Phase 1 amendment sub-plans:
|
||||||
|
|
||||||
|
- **`0001a-trait-rewrite.md`** -- Rewrite `MemoryStore` only. Touches
|
||||||
|
`storage/memory_store.rs` (trait declaration) and `storage/sqlite.rs`
|
||||||
|
(impl block attribute). Leaves async_trait in place on the embedder side
|
||||||
|
so the diff stays focused.
|
||||||
|
- **`0001b-sqlite-split.md`** -- Pure code motion. Splits the
|
||||||
|
~8200-line `sqlite.rs` into a `sqlite/` directory. Independent of D1; can
|
||||||
|
land in either order relative to `0001a`.
|
||||||
|
- **`0001c-async-trait-sunset.md`** -- Rewrite `Embedder` the same way, then
|
||||||
|
remove `async-trait = "0.1"` from `crates/vestige-core/Cargo.toml`. Final
|
||||||
|
amendment commit removes the dependency entirely. After this lands, the
|
||||||
|
workspace contains zero references to `async_trait`.
|
||||||
|
|
||||||
|
All three sub-plans land on the existing `feat/storage-trait-phase1` branch
|
||||||
|
(790c0c8 has not been opened upstream yet; amend in place, no force-push to a
|
||||||
|
public PR).
|
||||||
|
|
||||||
|
### D2. PgMemoryStore::connect mirrors SqliteMemoryStore::new
|
||||||
|
|
||||||
|
```rust
|
||||||
|
impl PgMemoryStore {
|
||||||
|
pub async fn connect(url: &str, max_connections: u32) -> MemoryStoreResult<Self>;
|
||||||
|
pub async fn from_pool(pool: PgPool) -> MemoryStoreResult<Self>;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
No `Embedder` in the constructor. The pgvector-specific
|
||||||
|
`ALTER TABLE knowledge_nodes ALTER COLUMN embedding TYPE vector($N)` DDL lives
|
||||||
|
inside the trait method `register_model(&ModelSignature)`. That method is
|
||||||
|
called by the caller (cognitive engine bootstrap, migrate CLI, tests) after
|
||||||
|
construction, exactly as it is for `SqliteMemoryStore`.
|
||||||
|
|
||||||
|
`MemoryStoreError` gains two variants behind the feature flag (added during
|
||||||
|
the Postgres impl, not during the Phase 1 amendment):
|
||||||
|
```rust
|
||||||
|
#[cfg(feature = "postgres-backend")]
|
||||||
|
#[error("postgres error: {0}")]
|
||||||
|
Postgres(#[from] sqlx::Error),
|
||||||
|
|
||||||
|
#[cfg(feature = "postgres-backend")]
|
||||||
|
#[error("postgres migration error: {0}")]
|
||||||
|
Migrate(#[from] sqlx::migrate::MigrateError),
|
||||||
|
```
|
||||||
|
|
||||||
|
### D3. Split sqlite.rs into a sqlite/ directory as Phase 1 amendment
|
||||||
|
|
||||||
|
Pure code motion, no behavioural change. Target layout:
|
||||||
|
```
|
||||||
|
crates/vestige-core/src/storage/sqlite/
|
||||||
|
mod.rs -- SqliteMemoryStore struct, new(), reader/writer locks
|
||||||
|
crud.rs -- insert/get/update/delete
|
||||||
|
search.rs -- fts_search, vector_search, hybrid search
|
||||||
|
scheduling.rs -- FSRS state methods
|
||||||
|
graph.rs -- edges, neighbors
|
||||||
|
domain.rs -- domain CRUD, classify stub
|
||||||
|
registry.rs -- embedding_model table + register_model
|
||||||
|
portable_sync.rs -- portable archive backend bridge
|
||||||
|
trait_impl.rs -- impl LocalMemoryStore for SqliteMemoryStore
|
||||||
|
```
|
||||||
|
|
||||||
|
Cognitive-module imports stay on `crate::storage::SqliteMemoryStore` and
|
||||||
|
related re-exports from `storage/mod.rs`; the split is private to the
|
||||||
|
module. Each motion commit must keep `cargo test -p vestige-core` green for
|
||||||
|
bisectability.
|
||||||
|
|
||||||
|
This lands in the Phase 1 amendment PR alongside D1 (separate commit, same
|
||||||
|
branch).
|
||||||
|
|
||||||
|
### D4. Postgres backend as a directory from day one
|
||||||
|
|
||||||
|
```
|
||||||
|
crates/vestige-core/src/storage/postgres/
|
||||||
|
mod.rs -- PgMemoryStore struct, connect, from_pool, trait impl
|
||||||
|
pool.rs -- PgPool construction from PostgresConfig
|
||||||
|
migrations.rs -- sqlx::migrate! wrapper
|
||||||
|
registry.rs -- ensure_registry, ALTER COLUMN TYPE vector(N)
|
||||||
|
search.rs -- RRF query + row mapping
|
||||||
|
migrate_cli.rs -- SQLite -> Postgres streaming copy
|
||||||
|
reembed.rs -- O(n) re-encode + HNSW rebuild
|
||||||
|
```
|
||||||
|
|
||||||
|
D1+D2 of the master plan land first as a skeleton in `mod.rs` with `todo!()`
|
||||||
|
bodies; later sub-plans fill in the other files.
|
||||||
|
|
||||||
|
### D5. Sub-plan layout: two phases worth of sub-plans
|
||||||
|
|
||||||
|
Phase 1 amendment sub-plans (under `docs/plans/`):
|
||||||
|
- `0001a-trait-rewrite.md` -- MemoryStore async_trait -> trait_variant, call-site audit
|
||||||
|
- `0001b-sqlite-split.md` -- sqlite.rs -> sqlite/ directory, commit-by-commit
|
||||||
|
- `0001c-async-trait-sunset.md` -- Embedder rewrite + drop async-trait dep from Cargo.toml
|
||||||
|
|
||||||
|
Phase 2 sub-plans (under `docs/plans/`):
|
||||||
|
- `0002a-skeleton-and-feature-gate.md` -- master plan D1 + D2 (todo!() bodies)
|
||||||
|
- `0002b-pool-and-config.md` -- master plan D3 + D7
|
||||||
|
- `0002c-migrations.md` -- master plan D4
|
||||||
|
- `0002d-store-impl-bodies.md` -- master plan D2 real bodies + D6 registry
|
||||||
|
- `0002e-hybrid-search.md` -- master plan D5
|
||||||
|
- `0002f-migrate-cli.md` -- master plan D8 + D10
|
||||||
|
- `0002g-reembed.md` -- master plan D9
|
||||||
|
- `0002h-testing-and-benches.md` -- master plan D14 + D15
|
||||||
|
- `0002i-runbook.md` -- master plan D16
|
||||||
|
|
||||||
|
Each sub-plan is a self-contained brief sized to fit one focused
|
||||||
|
implementation session (handed to Claude Code as a `/goal` instruction
|
||||||
|
without requiring the agent to load the master plan).
|
||||||
|
|
||||||
|
### D6. SQLite split does not get its own ADR
|
||||||
|
|
||||||
|
The split is pure code motion; no public types, behaviour, or paths change.
|
||||||
|
`0001b-sqlite-split.md` is enough.
|
||||||
|
|
||||||
|
### D7. Multi-tenancy schema reservation (L1-L3)
|
||||||
|
|
||||||
|
Phase 2 reserves the columns and tables needed for future per-user / per-group
|
||||||
|
visibility, so Phase 3 (auth) does not require a column-add migration over a
|
||||||
|
populated, HNSW-indexed `knowledge_nodes` table. Single-user behaviour is unchanged
|
||||||
|
in both backends.
|
||||||
|
|
||||||
|
New tables in `0001_init.up.sql`:
|
||||||
|
|
||||||
|
```sql
|
||||||
|
CREATE TABLE users (
|
||||||
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
handle TEXT NOT NULL UNIQUE,
|
||||||
|
display_name TEXT,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||||
|
metadata JSONB NOT NULL DEFAULT '{}'::jsonb
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE groups (
|
||||||
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
handle TEXT NOT NULL UNIQUE,
|
||||||
|
display_name TEXT,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||||
|
metadata JSONB NOT NULL DEFAULT '{}'::jsonb
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE group_memberships (
|
||||||
|
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||||
|
group_id UUID NOT NULL REFERENCES groups(id) ON DELETE CASCADE,
|
||||||
|
role TEXT NOT NULL DEFAULT 'member', -- 'member' | 'admin'
|
||||||
|
joined_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||||
|
PRIMARY KEY (user_id, group_id)
|
||||||
|
);
|
||||||
|
|
||||||
|
INSERT INTO users (id, handle, display_name)
|
||||||
|
VALUES ('00000000-0000-0000-0000-000000000001', 'local', 'Local User');
|
||||||
|
```
|
||||||
|
|
||||||
|
New columns on `knowledge_nodes`:
|
||||||
|
|
||||||
|
```sql
|
||||||
|
owner_user_id UUID NOT NULL DEFAULT '00000000-0000-0000-0000-000000000001'
|
||||||
|
REFERENCES users(id),
|
||||||
|
visibility TEXT NOT NULL DEFAULT 'private', -- 'private' | 'group' | 'public'
|
||||||
|
shared_with_groups UUID[] NOT NULL DEFAULT '{}'
|
||||||
|
|
||||||
|
CREATE INDEX idx_knowledge_nodes_owner ON knowledge_nodes (owner_user_id);
|
||||||
|
CREATE INDEX idx_knowledge_nodes_shared_groups ON knowledge_nodes USING GIN (shared_with_groups);
|
||||||
|
```
|
||||||
|
|
||||||
|
Phase 3 visibility filter (declared here for reference; implemented in Phase 3):
|
||||||
|
|
||||||
|
```sql
|
||||||
|
WHERE
|
||||||
|
(visibility = 'private' AND owner_user_id = $me)
|
||||||
|
OR (visibility = 'group'
|
||||||
|
AND (owner_user_id = $me OR shared_with_groups && $my_group_ids))
|
||||||
|
OR visibility = 'public'
|
||||||
|
```
|
||||||
|
|
||||||
|
Why tri-state enum and not just `shared_with_groups[] + is_public`: the
|
||||||
|
explicit `visibility` field documents intent at the row level. A `'private'`
|
||||||
|
row with a non-empty `shared_with_groups` is detectable inconsistency
|
||||||
|
(a CHECK constraint can enforce it later) rather than silent data.
|
||||||
|
|
||||||
|
SQLite parity: same tables and columns with identical defaults.
|
||||||
|
`shared_with_groups` is a JSON `'[]'` text encoding (no array type).
|
||||||
|
Single-user mode never changes any of these values; the trait surface ignores
|
||||||
|
the visibility filter for SQLite because there is exactly one user.
|
||||||
|
|
||||||
|
Sharing automation (matching by domain, tag, repo, MCP caller, ...) is
|
||||||
|
explicitly **not** in Phase 2. See D8 for context capture, and the Follow-ups
|
||||||
|
section for the Phase 4 `sharing_rules` design sketch.
|
||||||
|
|
||||||
|
RLS policies are not declared in Phase 2. Phase 3 decides whether to add
|
||||||
|
RLS as defense-in-depth on top of the app-layer filter.
|
||||||
|
|
||||||
|
### D8. Context-aware ingest
|
||||||
|
|
||||||
|
Every memory carries its ingest context, so future automation (sharing rules,
|
||||||
|
domain scoping, audit) can match on it without a schema migration. Most of
|
||||||
|
this is already happening in the Phase 1 ingest pipeline; D8 promotes it to
|
||||||
|
ADR-level commitment so Phase 2 cannot drop it on the way to Postgres.
|
||||||
|
|
||||||
|
Context dimensions and where they live:
|
||||||
|
|
||||||
|
- **`codebase`** -- promoted to a first-class indexed column on `knowledge_nodes`.
|
||||||
|
High-frequency query path (`SELECT ... WHERE codebase = 'vestige'`) for
|
||||||
|
both human exploration and Phase 4 HDBSCAN scoping. Direct B-tree index
|
||||||
|
beats JSONB extraction.
|
||||||
|
```sql
|
||||||
|
codebase TEXT, -- nullable; populated from ingest context
|
||||||
|
CREATE INDEX idx_knowledge_nodes_codebase ON knowledge_nodes (codebase) WHERE codebase IS NOT NULL;
|
||||||
|
```
|
||||||
|
`MemoryRecord` gains `pub codebase: Option<String>`.
|
||||||
|
|
||||||
|
- **`mcp_client_id`** -- which MCP caller created this. Persistent identity
|
||||||
|
once Phase 3 API keys exist. Lives in `metadata.mcp_client_id` (JSONB).
|
||||||
|
Not query-hot enough to deserve a column.
|
||||||
|
|
||||||
|
- **`session_id`** -- ephemeral; identifies the calling session for runtime
|
||||||
|
override scoping. Lives in `metadata.session_id` (JSONB). Sessions die
|
||||||
|
fast; storing them as rows or indexed columns is waste.
|
||||||
|
|
||||||
|
- **`file` / `topics`** -- existing optional context already accepted by the
|
||||||
|
ingest pipeline. Stay in metadata JSONB.
|
||||||
|
|
||||||
|
Phase 2's job for D8 is operational, not architectural: audit the ingest
|
||||||
|
path from MCP request to row write to ensure none of these fields gets
|
||||||
|
dropped when crossing the SQLite -> Postgres backend boundary.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## PR Cadence
|
||||||
|
|
||||||
|
Two work streams, three PRs total:
|
||||||
|
|
||||||
|
1. **PR A: Phase 1 amendment**
|
||||||
|
- Branch: `feat/storage-trait-phase1` (existing, amended in place)
|
||||||
|
- Commits: MemoryStore trait rewrite (0001a) + sqlite split (0001b, multiple
|
||||||
|
motion commits) + Embedder rewrite & async-trait dep removal (0001c).
|
||||||
|
- Sub-plans `0001a-`, `0001b-`, `0001c-` are committed on this branch.
|
||||||
|
|
||||||
|
2. **PR B: ADR 0002 + Phase 2 sub-plans (this document + the 9 sub-plans)**
|
||||||
|
- New branch off PR A's tip once that is reviewed.
|
||||||
|
- No code; docs only.
|
||||||
|
|
||||||
|
3. **PR C: Phase 2 implementation**
|
||||||
|
- New branch off PR B's tip.
|
||||||
|
- One PR with many commits clustered by sub-plan.
|
||||||
|
|
||||||
|
PR B is the "let's discuss execution before writing code" gate. PR C is the
|
||||||
|
"now we write code" gate. If PR A is itself sizable enough that it needs the
|
||||||
|
amendments reviewed in stages, the three sub-plans (`0001a`, `0001b`, `0001c`)
|
||||||
|
can split into separate PRs; that's a tactical call at PR time.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Architecture Overview
|
||||||
|
|
||||||
|
Final layout after the Phase 1 amendment (PR A) and Phase 2 implementation
|
||||||
|
(PR C):
|
||||||
|
|
||||||
|
```
|
||||||
|
crates/vestige-core/src/storage/
|
||||||
|
mod.rs -- re-exports, Storage alias for BC
|
||||||
|
memory_store.rs -- trait_variant-generated MemoryStore + LocalMemoryStore, types, error
|
||||||
|
migrations.rs -- SQLite migration registry (Phase 1, unchanged)
|
||||||
|
portable.rs -- portable archive format (Phase 1, unchanged)
|
||||||
|
sqlite/ -- was sqlite.rs (D3, Phase 1 amendment)
|
||||||
|
mod.rs -- SqliteMemoryStore struct, new(), reader/writer locks
|
||||||
|
crud.rs -- insert/get/update/delete
|
||||||
|
search.rs -- fts/vector/hybrid
|
||||||
|
scheduling.rs -- FSRS state
|
||||||
|
graph.rs -- edges, neighbors
|
||||||
|
domain.rs -- domain CRUD, classify stub
|
||||||
|
registry.rs -- embedding_model table + register_model
|
||||||
|
portable_sync.rs -- portable backend bridge
|
||||||
|
trait_impl.rs -- impl LocalMemoryStore for SqliteMemoryStore
|
||||||
|
postgres/ -- D4, Phase 2
|
||||||
|
mod.rs -- PgMemoryStore struct, connect, from_pool, trait impl
|
||||||
|
pool.rs -- PgPool construction from config
|
||||||
|
migrations.rs -- sqlx::migrate! wrapper
|
||||||
|
registry.rs -- register_model body, ALTER COLUMN TYPE vector(N)
|
||||||
|
search.rs -- RRF query + row mapping
|
||||||
|
migrate_cli.rs -- SQLite -> Postgres streaming copy
|
||||||
|
reembed.rs -- O(n) re-encode + HNSW rebuild
|
||||||
|
|
||||||
|
crates/vestige-core/migrations/
|
||||||
|
sqlite/ -- Phase 1, with V15 migration for D7+D8 columns/tables
|
||||||
|
postgres/ -- Phase 2
|
||||||
|
0001_init.up.sql -- includes D7 tables + columns, D8 codebase column
|
||||||
|
0001_init.down.sql
|
||||||
|
0002_hnsw.up.sql
|
||||||
|
0002_hnsw.down.sql
|
||||||
|
```
|
||||||
|
|
||||||
|
Tables in the Postgres schema after migration 0001:
|
||||||
|
|
||||||
|
| Table | Purpose | Phase that populates |
|
||||||
|
|-------|---------|----------------------|
|
||||||
|
| `embedding_model` | One-row registry of name/dim/hash | Phase 2 (first connect) |
|
||||||
|
| `knowledge_nodes` | Core records + owner/visibility/codebase | Phase 2 ingest; Phase 4 fills `domains` |
|
||||||
|
| `scheduling` | FSRS state | Phase 2 |
|
||||||
|
| `edges` | Spreading activation graph | Phase 2 |
|
||||||
|
| `review_events` | Append-only FSRS review log | Phase 2; Phase 5 federation reads |
|
||||||
|
| `domains` | Phase 4 cluster centroids | Phase 4 |
|
||||||
|
| `users` | L1 identities (D7) | Phase 3 |
|
||||||
|
| `groups` | L3 groups (D7) | Phase 3 |
|
||||||
|
| `group_memberships` | L3 user-group links (D7) | Phase 3 |
|
||||||
|
|
||||||
|
`sharing_rules` (Phase 4) and `api_keys` (Phase 3) are added later by their
|
||||||
|
own migrations.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Alternatives Considered
|
||||||
|
|
||||||
|
| Alternative | Why not |
|
||||||
|
|-------------|---------|
|
||||||
|
| Keep async_trait on the Phase 1 trait | One heap allocation per trait call inside the hottest code path in Vestige. Boxing every future also obscures the actual return type, which makes lifetimes and Send-ness harder to reason about. The Phase 1 PR is not opened upstream yet, so amending is free. |
|
||||||
|
| Take `&dyn Embedder` into `connect` | Couples constructor to embedder; breaks ADR 0001's separation; can't be used by callers that don't have an embedder yet (tests, migrate CLI). |
|
||||||
|
| Defer SQLite split | Postgres lands alongside an 8K-line peer; the pattern compounds; future readers see "backends are huge here". |
|
||||||
|
| Single `postgres.rs` | Master plan calls out 7 sub-files; we know it's getting split; doing it twice is waste. |
|
||||||
|
| Per-deliverable sub-plans (16 docs) | Review fatigue; many sub-plans would be 3-5 lines of Cargo or one migration each. Logical groups cluster naturally with PR commits. |
|
||||||
|
| One rolling sub-plan with checkboxes | Moving target; doesn't serve as a `/goal` brief for a fresh Claude Code session. |
|
||||||
|
| Separate ADR for the SQLite split | Pure code motion with no public-surface change; doesn't constrain future decisions. ADRs are for decisions that bind. |
|
||||||
|
| Punt multi-tenancy schema entirely to Phase 3 | Adding `owner_user_id` and indexes to a populated, HNSW-indexed `knowledge_nodes` table later is an expensive online migration. Reserving NULL-defaulted columns now is ~10 lines of SQL. |
|
||||||
|
| `shared_with_groups[] + is_public` instead of tri-state visibility enum | More compact but `visibility = 'private'` documents intent at the row level; a CHECK constraint can later enforce array/enum consistency. Two columns conveying one fact is fine when both are referenced often. |
|
||||||
|
| Add `shared_with_users[]` for direct user-to-user sharing | A "group of one" subsumes it without an extra column and GIN index. Phase 3 CLI can auto-create singleton groups if a user requests direct shares. |
|
||||||
|
| Bake per-domain or per-tag sharing defaults into Phase 2 schema | Sharing automation needs real usage data before committing to fuzzy (domain centroids) vs crisp (tags) vs context (codebase / MCP caller). Phase 4 designs a generic `sharing_rules` table that matches on any context dimension; deferring costs nothing because rules live in a new table, not new columns. |
|
||||||
|
| `codebase` stays in JSONB metadata | High-frequency query path (HDBSCAN scoping, codebase-wide searches, future `sharing_rules` match). B-tree on a real column beats GIN on a JSONB key for this access pattern. Cost is one nullable TEXT column. |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Consequences
|
||||||
|
|
||||||
|
### Positive
|
||||||
|
- Phase 1 trait stops boxing futures on every call. Lifetimes and Send-ness
|
||||||
|
become inspectable instead of hidden inside an `async_trait` macro expansion.
|
||||||
|
- `connect` stays backend-agnostic; tests and CLI tools stand up either backend
|
||||||
|
without an `Embedder` in scope.
|
||||||
|
- Cognitive module imports never change paths -- the SQLite split is private
|
||||||
|
to `storage/sqlite/`, public re-exports through `storage/mod.rs` unchanged.
|
||||||
|
- Postgres backend lands already-modular; future SQL changes touch one of
|
||||||
|
seven small files, not one of eight thousand lines.
|
||||||
|
- Phase 2 master plan stays archival; ADR 0002 + sub-plans are the live source
|
||||||
|
of truth for execution.
|
||||||
|
- Multi-tenancy columns reserved now means Phase 3 auth is purely additive --
|
||||||
|
no online migration over a populated, HNSW-indexed `knowledge_nodes` table.
|
||||||
|
- Context-aware ingest (D8) keeps the door open for repo / session /
|
||||||
|
MCP-caller-scoped sharing rules in Phase 4 without changing `knowledge_nodes`.
|
||||||
|
|
||||||
|
### Negative
|
||||||
|
- The Phase 1 amendment expands a "finished" branch. It is a real cost: the
|
||||||
|
trait rewrite touches every cognitive module that holds a store handle.
|
||||||
|
- SQLite split is a pure-motion diff. Annoying to review even when safe.
|
||||||
|
- Three PRs (amendment, ADR+plans, implementation) instead of one or two.
|
||||||
|
Discipline tax in exchange for reviewability.
|
||||||
|
- Multi-tenancy reservation adds three never-queried tables and three
|
||||||
|
always-default columns to the SQLite schema. Real but small storage cost in
|
||||||
|
single-user mode (a single bootstrap row + empty tables + NULL/empty
|
||||||
|
defaults per memory).
|
||||||
|
|
||||||
|
### Risks
|
||||||
|
- **Trait rewrite breaks a cognitive module's Send-ness expectation.**
|
||||||
|
Mitigation: `cargo test --workspace` runs after each call-site edit;
|
||||||
|
trait_variant-generated `MemoryStore` is the Send variant and matches the
|
||||||
|
current `Arc<dyn ...>` usage everywhere except thread-local impls (none
|
||||||
|
exist today).
|
||||||
|
- **SQLite motion commit introduces a silent semantic change.** Mitigation:
|
||||||
|
each commit keeps `cargo test -p vestige-core` green; reviewer can bisect.
|
||||||
|
- **Sub-plan boundaries don't match how implementation wants to commit.**
|
||||||
|
Mitigation: sub-plans are advisory; the implementation PR clusters commits
|
||||||
|
however it ends up needing to.
|
||||||
|
- **Reserved columns get used in Phase 3 in a way that mismatches Phase 2
|
||||||
|
defaults.** Mitigation: Phase 3 owns the auth filter; Phase 2 defaults
|
||||||
|
(`owner_user_id = local`, `visibility = 'private'`) are intentionally the
|
||||||
|
"no access for anyone but the owner" worst-case; widening at Phase 3 is
|
||||||
|
safe, narrowing would be the dangerous direction.
|
||||||
|
- **Memory: PR A amendment invalidates the locally-deployed Phase 1 binary's
|
||||||
|
ABI.** Not a real risk -- the trait change is purely source-level Rust; the
|
||||||
|
on-disk DB schema is unchanged. The rebuilt binary slots in over the
|
||||||
|
current one without DB migration.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Resolved Decisions
|
||||||
|
|
||||||
|
| # | Question | Resolution |
|
||||||
|
|---|----------|------------|
|
||||||
|
| Q1 | Phase 1 trait shape | Rewrite with trait_variant::make. Amend Phase 1 PR. |
|
||||||
|
| Q2 | PgMemoryStore::connect signature | Mirror SqliteMemoryStore::new; no Embedder. register_model does the pgvector typmod stamp. |
|
||||||
|
| Q3 | Split sqlite.rs | Yes, as Phase 1 amendment. sqlite.rs -> sqlite/ directory; pure code motion. |
|
||||||
|
| Q4 | Postgres module layout | Directory from day one. |
|
||||||
|
| Q5 | Sub-plan granularity | Logical groups, ~9 docs for Phase 2 plus 2 for the Phase 1 amendment. |
|
||||||
|
| Q6 | ADR for SQLite split | No. Sub-plan `0001b-sqlite-split.md` is sufficient. |
|
||||||
|
| Q7 | Multi-tenancy schema | Reserve users / groups / group_memberships tables and owner_user_id / visibility / shared_with_groups columns on knowledge_nodes in Phase 2. Single-user defaults; Phase 3 fills in real values. |
|
||||||
|
| Q8 | Visibility encoding | Tri-state enum `'private' \| 'group' \| 'public'` plus `shared_with_groups[]`. No `shared_with_users[]`; no RLS in Phase 2. |
|
||||||
|
| Q9 | Sharing automation grain | Per-memory only in Phase 2. Phase 4 ships a generic `sharing_rules` table matching on codebase / tag / node_type / mcp_client_id. |
|
||||||
|
| Q10 | Context capture on ingest | `codebase` promoted to a first-class indexed column; `mcp_client_id` and `session_id` stay in metadata JSONB. |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Follow-ups
|
||||||
|
|
||||||
|
- Phase 1 amendment sub-plans drafted: `0001a-trait-rewrite.md`,
|
||||||
|
`0001b-sqlite-split.md`, `0001c-async-trait-sunset.md`. Ready to execute on
|
||||||
|
`feat/storage-trait-phase1`.
|
||||||
|
- Phase 2 sub-plans drafted: `0002a-` through `0002i-` against the accepted
|
||||||
|
decisions above. Ready to execute on a new branch off PR A's tip.
|
||||||
|
- Decide branch placement for this ADR before it gets committed -- it cannot
|
||||||
|
live on `feat/storage-trait-phase1` (that branch is now PR A's code-only
|
||||||
|
amendment branch). Likely a new branch off PR A's tip for PR B (docs only).
|
||||||
|
- Validate local Postgres dev cluster before PR C work begins. Recipe at
|
||||||
|
`docs/plans/local-dev-postgres-setup.md` is correct but needs to be applied
|
||||||
|
on this machine (delandtj-home): cluster is not initdb'd, pgvector is not
|
||||||
|
installed. Containerized `pgvector/pgvector:pg18` is a viable alternative
|
||||||
|
if pgvector packaging is friction. See open discussion thread.
|
||||||
|
|
||||||
|
### Phase 4 sketch: `sharing_rules` and the precedence chain
|
||||||
|
|
||||||
|
Recorded here so the Phase 4 author does not have to rediscover the design.
|
||||||
|
Phase 2 does **not** implement any of this; it only ensures the schema and
|
||||||
|
ingest context capture make this possible without a `knowledge_nodes` migration.
|
||||||
|
|
||||||
|
```sql
|
||||||
|
-- Phase 4 migration (not Phase 2)
|
||||||
|
CREATE TABLE sharing_rules (
|
||||||
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
owner_user_id UUID NOT NULL REFERENCES users(id),
|
||||||
|
-- Match: any subset; all set fields must match conjunctively
|
||||||
|
match_codebase TEXT,
|
||||||
|
match_tag TEXT,
|
||||||
|
match_node_type TEXT,
|
||||||
|
match_api_key_id UUID REFERENCES api_keys(id), -- MCP caller identity
|
||||||
|
-- Policy
|
||||||
|
visibility TEXT NOT NULL,
|
||||||
|
shared_with_groups UUID[] NOT NULL DEFAULT '{}',
|
||||||
|
-- Conflict resolution
|
||||||
|
priority INTEGER NOT NULL DEFAULT 0,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||||
|
);
|
||||||
|
```
|
||||||
|
|
||||||
|
Precedence on ingest, first match wins:
|
||||||
|
|
||||||
|
1. Caller-explicit visibility in the MCP request
|
||||||
|
2. Active session override held by the MCP server (per-session, in-memory,
|
||||||
|
not persisted; matched by `session_id`)
|
||||||
|
3. Highest-priority `sharing_rules` row whose match fields all hold
|
||||||
|
4. User's `default_visibility` (typically `'private'`)
|
||||||
|
|
||||||
|
Per-session overrides do not persist; storing ephemeral session IDs as DB
|
||||||
|
rows is waste. Per-codebase / per-MCP-caller rules do persist as
|
||||||
|
`sharing_rules` rows.
|
||||||
|
|
@ -0,0 +1,39 @@
|
||||||
|
{
|
||||||
|
"case": "justified-snapshot",
|
||||||
|
"description": "A snapshot changed alongside an intentional source/UI change, so the mechanical delta should remain explicit for policy or human review.",
|
||||||
|
"expectedDecision": "needs_human_review",
|
||||||
|
"receipt": {
|
||||||
|
"schema": "vestige.sanhedrin.test_integrity_delta.v1",
|
||||||
|
"id": "tid_justified_snapshot",
|
||||||
|
"commandReceiptId": "receipt_vitest_after_snapshot",
|
||||||
|
"verificationClaim": "All tests passed.",
|
||||||
|
"specSource": {
|
||||||
|
"contextId": "spec_ctx_dashboard_empty_state",
|
||||||
|
"testFiles": [
|
||||||
|
{
|
||||||
|
"path": "tests/__snapshots__/dashboard.test.ts.snap",
|
||||||
|
"hashBeforeImplementation": "sha256:6666666666666666666666666666666666666666666666666666666666666666",
|
||||||
|
"hashAfterVerification": "sha256:7777777777777777777777777777777777777777777777777777777777777777"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"implementationContext": "impl_ctx_dashboard_empty_state_copy",
|
||||||
|
"verifierContext": "verify_ctx_vitest",
|
||||||
|
"delta": {
|
||||||
|
"testFilesChangedAfterImplementation": true,
|
||||||
|
"removedOrDisabledTests": [],
|
||||||
|
"removedAssertions": 0,
|
||||||
|
"weakenedExpectations": [],
|
||||||
|
"snapshotChurnWithoutSourceChange": false,
|
||||||
|
"coverageDelta": 0,
|
||||||
|
"mocksReplacingRealBoundary": []
|
||||||
|
},
|
||||||
|
"freshVerifier": {
|
||||||
|
"commandReceiptId": "receipt_vitest_after_snapshot",
|
||||||
|
"exitCode": 0,
|
||||||
|
"checkedAfterLastRelevantEdit": true
|
||||||
|
},
|
||||||
|
"decision": "needs_human_review",
|
||||||
|
"reason": "snapshot changed with the implementation; policy or human review must decide whether the churn is justified"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,45 @@
|
||||||
|
{
|
||||||
|
"case": "skipped-test",
|
||||||
|
"description": "A verifier command passed after a test was disabled with a skip/ignore marker.",
|
||||||
|
"expectedDecision": "downgraded",
|
||||||
|
"receipt": {
|
||||||
|
"schema": "vestige.sanhedrin.test_integrity_delta.v1",
|
||||||
|
"id": "tid_skipped_test",
|
||||||
|
"commandReceiptId": "receipt_pytest_after_skip",
|
||||||
|
"verificationClaim": "All tests passed.",
|
||||||
|
"specSource": {
|
||||||
|
"contextId": "spec_ctx_coupon_validation",
|
||||||
|
"testFiles": [
|
||||||
|
{
|
||||||
|
"path": "tests/test_coupon.py",
|
||||||
|
"hashBeforeImplementation": "sha256:2222222222222222222222222222222222222222222222222222222222222222",
|
||||||
|
"hashAfterVerification": "sha256:3333333333333333333333333333333333333333333333333333333333333333"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"implementationContext": "impl_ctx_coupon_fix",
|
||||||
|
"verifierContext": "verify_ctx_pytest",
|
||||||
|
"delta": {
|
||||||
|
"testFilesChangedAfterImplementation": true,
|
||||||
|
"removedOrDisabledTests": [
|
||||||
|
{
|
||||||
|
"kind": "skip_or_only",
|
||||||
|
"path": "tests/test_coupon.py",
|
||||||
|
"line": 42
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"removedAssertions": 0,
|
||||||
|
"weakenedExpectations": [],
|
||||||
|
"snapshotChurnWithoutSourceChange": false,
|
||||||
|
"coverageDelta": -1.2,
|
||||||
|
"mocksReplacingRealBoundary": []
|
||||||
|
},
|
||||||
|
"freshVerifier": {
|
||||||
|
"commandReceiptId": "receipt_pytest_after_skip",
|
||||||
|
"exitCode": 0,
|
||||||
|
"checkedAfterLastRelevantEdit": true
|
||||||
|
},
|
||||||
|
"decision": "downgraded",
|
||||||
|
"reason": "tests passed, but a test was disabled after implementation"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,39 @@
|
||||||
|
{
|
||||||
|
"case": "unchanged-good",
|
||||||
|
"description": "Implementation changes source, tests are unchanged, and a fresh verifier command ran after the last relevant edit.",
|
||||||
|
"expectedDecision": "accepted",
|
||||||
|
"receipt": {
|
||||||
|
"schema": "vestige.sanhedrin.test_integrity_delta.v1",
|
||||||
|
"id": "tid_unchanged_good",
|
||||||
|
"commandReceiptId": "receipt_cargo_test_after_fix",
|
||||||
|
"verificationClaim": "All tests passed.",
|
||||||
|
"specSource": {
|
||||||
|
"contextId": "spec_ctx_cart_discount",
|
||||||
|
"testFiles": [
|
||||||
|
{
|
||||||
|
"path": "tests/cart_discount_test.rs",
|
||||||
|
"hashBeforeImplementation": "sha256:1111111111111111111111111111111111111111111111111111111111111111",
|
||||||
|
"hashAfterVerification": "sha256:1111111111111111111111111111111111111111111111111111111111111111"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"implementationContext": "impl_ctx_cart_discount_fix",
|
||||||
|
"verifierContext": "verify_ctx_cargo_test",
|
||||||
|
"delta": {
|
||||||
|
"testFilesChangedAfterImplementation": false,
|
||||||
|
"removedOrDisabledTests": [],
|
||||||
|
"removedAssertions": 0,
|
||||||
|
"weakenedExpectations": [],
|
||||||
|
"snapshotChurnWithoutSourceChange": false,
|
||||||
|
"coverageDelta": 0,
|
||||||
|
"mocksReplacingRealBoundary": []
|
||||||
|
},
|
||||||
|
"freshVerifier": {
|
||||||
|
"commandReceiptId": "receipt_cargo_test_after_fix",
|
||||||
|
"exitCode": 0,
|
||||||
|
"checkedAfterLastRelevantEdit": true
|
||||||
|
},
|
||||||
|
"decision": "accepted",
|
||||||
|
"reason": "tests passed after the implementation and the test artifact did not change"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,45 @@
|
||||||
|
{
|
||||||
|
"case": "weakened-assertion",
|
||||||
|
"description": "The test still ran, but an expectation was relaxed after implementation.",
|
||||||
|
"expectedDecision": "downgraded",
|
||||||
|
"receipt": {
|
||||||
|
"schema": "vestige.sanhedrin.test_integrity_delta.v1",
|
||||||
|
"id": "tid_weakened_assertion",
|
||||||
|
"commandReceiptId": "receipt_npm_test_after_weaken",
|
||||||
|
"verificationClaim": "All tests passed.",
|
||||||
|
"specSource": {
|
||||||
|
"contextId": "spec_ctx_login_errors",
|
||||||
|
"testFiles": [
|
||||||
|
{
|
||||||
|
"path": "tests/login.test.ts",
|
||||||
|
"hashBeforeImplementation": "sha256:4444444444444444444444444444444444444444444444444444444444444444",
|
||||||
|
"hashAfterVerification": "sha256:5555555555555555555555555555555555555555555555555555555555555555"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"implementationContext": "impl_ctx_login_errors",
|
||||||
|
"verifierContext": "verify_ctx_npm_test",
|
||||||
|
"delta": {
|
||||||
|
"testFilesChangedAfterImplementation": true,
|
||||||
|
"removedOrDisabledTests": [],
|
||||||
|
"removedAssertions": 0,
|
||||||
|
"weakenedExpectations": [
|
||||||
|
{
|
||||||
|
"path": "tests/login.test.ts",
|
||||||
|
"from": "rejects.toThrow(InvalidCredentialsError)",
|
||||||
|
"to": "resolves.not.toThrow()"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"snapshotChurnWithoutSourceChange": false,
|
||||||
|
"coverageDelta": 0,
|
||||||
|
"mocksReplacingRealBoundary": []
|
||||||
|
},
|
||||||
|
"freshVerifier": {
|
||||||
|
"commandReceiptId": "receipt_npm_test_after_weaken",
|
||||||
|
"exitCode": 0,
|
||||||
|
"checkedAfterLastRelevantEdit": true
|
||||||
|
},
|
||||||
|
"decision": "downgraded",
|
||||||
|
"reason": "tests passed, but the asserted behavior was relaxed after implementation"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -145,6 +145,7 @@ codex mcp add vestige -- /usr/local/bin/vestige-mcp
|
||||||
| Xcode 26.3 | [Setup](./xcode.md) |
|
| Xcode 26.3 | [Setup](./xcode.md) |
|
||||||
| Cursor | [Setup](./cursor.md) |
|
| Cursor | [Setup](./cursor.md) |
|
||||||
| VS Code (Copilot) | [Setup](./vscode.md) |
|
| VS Code (Copilot) | [Setup](./vscode.md) |
|
||||||
|
| OpenCode | [Setup](./opencode.md) |
|
||||||
| JetBrains | [Setup](./jetbrains.md) |
|
| JetBrains | [Setup](./jetbrains.md) |
|
||||||
| Windsurf | [Setup](./windsurf.md) |
|
| Windsurf | [Setup](./windsurf.md) |
|
||||||
| Claude Code | [Setup](../CONFIGURATION.md#claude-code-one-liner) |
|
| Claude Code | [Setup](../CONFIGURATION.md#claude-code-one-liner) |
|
||||||
|
|
|
||||||
|
|
@ -135,6 +135,7 @@ Cursor does not surface MCP server errors in the UI. Test by running the command
|
||||||
| Xcode 26.3 | [Setup](./xcode.md) |
|
| Xcode 26.3 | [Setup](./xcode.md) |
|
||||||
| Codex | [Setup](./codex.md) |
|
| Codex | [Setup](./codex.md) |
|
||||||
| VS Code (Copilot) | [Setup](./vscode.md) |
|
| VS Code (Copilot) | [Setup](./vscode.md) |
|
||||||
|
| OpenCode | [Setup](./opencode.md) |
|
||||||
| JetBrains | [Setup](./jetbrains.md) |
|
| JetBrains | [Setup](./jetbrains.md) |
|
||||||
| Windsurf | [Setup](./windsurf.md) |
|
| Windsurf | [Setup](./windsurf.md) |
|
||||||
| Claude Code | [Setup](../CONFIGURATION.md#claude-code-one-liner) |
|
| Claude Code | [Setup](../CONFIGURATION.md#claude-code-one-liner) |
|
||||||
|
|
|
||||||
|
|
@ -123,6 +123,7 @@ In **Settings > Tools > MCP Server**, click the expansion arrow next to your cli
|
||||||
| Cursor | [Setup](./cursor.md) |
|
| Cursor | [Setup](./cursor.md) |
|
||||||
| VS Code (Copilot) | [Setup](./vscode.md) |
|
| VS Code (Copilot) | [Setup](./vscode.md) |
|
||||||
| Codex | [Setup](./codex.md) |
|
| Codex | [Setup](./codex.md) |
|
||||||
|
| OpenCode | [Setup](./opencode.md) |
|
||||||
| Windsurf | [Setup](./windsurf.md) |
|
| Windsurf | [Setup](./windsurf.md) |
|
||||||
| Claude Code | [Setup](../CONFIGURATION.md#claude-code-one-liner) |
|
| Claude Code | [Setup](../CONFIGURATION.md#claude-code-one-liner) |
|
||||||
| Claude Desktop | [Setup](../CONFIGURATION.md#claude-desktop-macos) |
|
| Claude Desktop | [Setup](../CONFIGURATION.md#claude-desktop-macos) |
|
||||||
|
|
|
||||||
233
docs/integrations/opencode.md
Normal file
233
docs/integrations/opencode.md
Normal file
|
|
@ -0,0 +1,233 @@
|
||||||
|
# OpenCode
|
||||||
|
|
||||||
|
> Give OpenCode persistent local memory across TUI, CLI, and desktop sessions.
|
||||||
|
|
||||||
|
OpenCode supports local MCP servers through its `mcp` config. Add Vestige once and your OpenCode agents can remember project decisions, architecture context, preferences, and previous fixes between sessions.
|
||||||
|
|
||||||
|
Verified with OpenCode `1.16.2` on June 8, 2026.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Why OpenCode Users Add Vestige
|
||||||
|
|
||||||
|
OpenCode is strong at driving real coding work from the terminal. The painful gap is continuity: the next session often has to rediscover what the previous session already learned. Vestige gives OpenCode a local memory layer through MCP, so the agent can reuse the project context that should not be trapped in one chat transcript.
|
||||||
|
|
||||||
|
Useful memories include:
|
||||||
|
|
||||||
|
- project decisions: "we use Axum handlers thinly and keep database logic in storage modules"
|
||||||
|
- preferences: "prefer small focused PRs and explicit verification receipts"
|
||||||
|
- architecture context: "the dashboard talks to the MCP server through the Axum backend and WebSocket events"
|
||||||
|
- bug fixes: "OpenCode rejects `mcpServers`; use top-level `mcp.vestige` with a command array"
|
||||||
|
- workflow state: "PR #67 was merged, but the config shape needed correction before promotion"
|
||||||
|
|
||||||
|
Vestige is local-first. Memories are stored in SQLite on your machine, can be scoped globally or per project, and are retrieved with tools like `vestige_session_context`, `vestige_search`, `vestige_smart_ingest`, and `vestige_deep_reference`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Setup
|
||||||
|
|
||||||
|
### 1. Install Vestige
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm install -g vestige-mcp-server@latest
|
||||||
|
```
|
||||||
|
|
||||||
|
Verify the binary:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
vestige-mcp --version
|
||||||
|
```
|
||||||
|
|
||||||
|
If you prefer not to install globally, use `npx` directly in the OpenCode command array:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"$schema": "https://opencode.ai/config.json",
|
||||||
|
"mcp": {
|
||||||
|
"vestige": {
|
||||||
|
"type": "local",
|
||||||
|
"command": ["npx", "-y", "-p", "vestige-mcp-server@latest", "vestige-mcp"],
|
||||||
|
"enabled": true,
|
||||||
|
"timeout": 60000
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
The higher timeout is for the first cold `npx` run, which may need to download the npm package before OpenCode can connect. If you install `vestige-mcp-server` globally, `10000` is enough for normal startup.
|
||||||
|
|
||||||
|
If `npx` times out against an older published Vestige build, install globally once and use `command: ["vestige-mcp"]`. The current integration keeps the MCP handshake fast by moving embedding startup work into the background.
|
||||||
|
|
||||||
|
### 2. Add Vestige To OpenCode
|
||||||
|
|
||||||
|
For global use across projects, create or edit:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
mkdir -p ~/.config/opencode
|
||||||
|
${EDITOR:-vi} ~/.config/opencode/opencode.json
|
||||||
|
```
|
||||||
|
|
||||||
|
Add:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"$schema": "https://opencode.ai/config.json",
|
||||||
|
"mcp": {
|
||||||
|
"vestige": {
|
||||||
|
"type": "local",
|
||||||
|
"command": ["vestige-mcp"],
|
||||||
|
"enabled": true,
|
||||||
|
"timeout": 10000
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
OpenCode also supports project-local config. Put the same block in `opencode.json` at the repo root when you want the setting checked in with a project.
|
||||||
|
|
||||||
|
For a custom config file, set `OPENCODE_CONFIG=/path/to/opencode.json` before launching OpenCode.
|
||||||
|
|
||||||
|
### 3. Verify
|
||||||
|
|
||||||
|
Restart OpenCode, then validate the resolved config and MCP server list:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
opencode debug config
|
||||||
|
opencode mcp list
|
||||||
|
```
|
||||||
|
|
||||||
|
You should see `vestige` listed. In a session, ask:
|
||||||
|
|
||||||
|
> "What MCP tools can you use?"
|
||||||
|
|
||||||
|
Vestige tools should be available with the `vestige_` prefix, such as `vestige_search`, `vestige_smart_ingest`, `vestige_session_context`, and `vestige_deep_reference`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## First Use
|
||||||
|
|
||||||
|
In OpenCode:
|
||||||
|
|
||||||
|
> "Remember that this project uses Rust with Axum and SQLite."
|
||||||
|
|
||||||
|
Start a new OpenCode session, then ask:
|
||||||
|
|
||||||
|
> "What stack does this project use?"
|
||||||
|
|
||||||
|
It remembers.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Project-Specific Memory
|
||||||
|
|
||||||
|
To isolate memory per repo, add `--data-dir` to OpenCode's command array:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"$schema": "https://opencode.ai/config.json",
|
||||||
|
"mcp": {
|
||||||
|
"vestige": {
|
||||||
|
"type": "local",
|
||||||
|
"command": ["vestige-mcp", "--data-dir", "./.vestige"],
|
||||||
|
"enabled": true,
|
||||||
|
"timeout": 10000
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
For an absolute path:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"$schema": "https://opencode.ai/config.json",
|
||||||
|
"mcp": {
|
||||||
|
"vestige": {
|
||||||
|
"type": "local",
|
||||||
|
"command": ["/usr/local/bin/vestige-mcp", "--data-dir", "/Users/you/projects/my-app/.vestige"],
|
||||||
|
"enabled": true,
|
||||||
|
"timeout": 10000
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Automatic Setup
|
||||||
|
|
||||||
|
If `opencode` is installed or `~/.config/opencode` exists, Vestige's installer can add the global config automatically:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npx @vestige/init
|
||||||
|
```
|
||||||
|
|
||||||
|
The installer writes a backup before modifying an existing config file. It also migrates Vestige entries copied from older `mcpServers` examples into OpenCode's current `mcp.vestige` shape.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Troubleshooting
|
||||||
|
|
||||||
|
<details>
|
||||||
|
<summary>Vestige tools do not appear</summary>
|
||||||
|
|
||||||
|
1. Verify OpenCode can see configured MCP servers:
|
||||||
|
```bash
|
||||||
|
opencode debug config
|
||||||
|
opencode mcp list
|
||||||
|
```
|
||||||
|
2. Verify the binary is on your path:
|
||||||
|
```bash
|
||||||
|
which vestige-mcp
|
||||||
|
```
|
||||||
|
3. Use an absolute binary path if OpenCode cannot resolve `vestige-mcp`.
|
||||||
|
4. Restart OpenCode after changing `opencode.json`.
|
||||||
|
5. Keep `timeout` at `10000` or higher for installed binaries. If you use the direct `npx` command, use `60000` so the first cold npm download does not fail OpenCode startup.
|
||||||
|
</details>
|
||||||
|
|
||||||
|
<details>
|
||||||
|
<summary>Config does not validate</summary>
|
||||||
|
|
||||||
|
OpenCode uses the top-level `mcp` key. Do not use the `mcpServers` shape from Claude Desktop, Cursor, or Windsurf.
|
||||||
|
|
||||||
|
If you copied an older Vestige example that used `mcpServers`, rerun:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npx @vestige/init
|
||||||
|
```
|
||||||
|
|
||||||
|
Correct:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"mcp": {
|
||||||
|
"vestige": {
|
||||||
|
"type": "local",
|
||||||
|
"command": ["vestige-mcp"],
|
||||||
|
"timeout": 10000
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
</details>
|
||||||
|
|
||||||
|
<details>
|
||||||
|
<summary>Too many MCP tools in context</summary>
|
||||||
|
|
||||||
|
OpenCode loads MCP tools alongside built-in tools. If you have many MCP servers enabled, disable unused servers or restrict MCP tools per agent in your OpenCode config.
|
||||||
|
</details>
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Also Works With
|
||||||
|
|
||||||
|
| IDE | Guide |
|
||||||
|
|-----|-------|
|
||||||
|
| Codex | [Setup](./codex.md) |
|
||||||
|
| Cursor | [Setup](./cursor.md) |
|
||||||
|
| VS Code (Copilot) | [Setup](./vscode.md) |
|
||||||
|
| JetBrains | [Setup](./jetbrains.md) |
|
||||||
|
| Windsurf | [Setup](./windsurf.md) |
|
||||||
|
| Xcode 26.3 | [Setup](./xcode.md) |
|
||||||
|
| Claude Code | [Setup](../CONFIGURATION.md#claude-code-one-liner) |
|
||||||
|
| Claude Desktop | [Setup](../CONFIGURATION.md#claude-desktop-macos) |
|
||||||
|
|
@ -153,6 +153,7 @@ Every team member with Vestige installed will automatically get memory-enabled C
|
||||||
| Xcode 26.3 | [Setup](./xcode.md) |
|
| Xcode 26.3 | [Setup](./xcode.md) |
|
||||||
| Cursor | [Setup](./cursor.md) |
|
| Cursor | [Setup](./cursor.md) |
|
||||||
| Codex | [Setup](./codex.md) |
|
| Codex | [Setup](./codex.md) |
|
||||||
|
| OpenCode | [Setup](./opencode.md) |
|
||||||
| JetBrains | [Setup](./jetbrains.md) |
|
| JetBrains | [Setup](./jetbrains.md) |
|
||||||
| Windsurf | [Setup](./windsurf.md) |
|
| Windsurf | [Setup](./windsurf.md) |
|
||||||
| Claude Code | [Setup](../CONFIGURATION.md#claude-code-one-liner) |
|
| Claude Code | [Setup](../CONFIGURATION.md#claude-code-one-liner) |
|
||||||
|
|
|
||||||
|
|
@ -149,6 +149,7 @@ If you have many MCP servers and exceed 100 total tools, Cascade will ignore exc
|
||||||
| Cursor | [Setup](./cursor.md) |
|
| Cursor | [Setup](./cursor.md) |
|
||||||
| VS Code (Copilot) | [Setup](./vscode.md) |
|
| VS Code (Copilot) | [Setup](./vscode.md) |
|
||||||
| Codex | [Setup](./codex.md) |
|
| Codex | [Setup](./codex.md) |
|
||||||
|
| OpenCode | [Setup](./opencode.md) |
|
||||||
| JetBrains | [Setup](./jetbrains.md) |
|
| JetBrains | [Setup](./jetbrains.md) |
|
||||||
| Claude Code | [Setup](../CONFIGURATION.md#claude-code-one-liner) |
|
| Claude Code | [Setup](../CONFIGURATION.md#claude-code-one-liner) |
|
||||||
| Claude Desktop | [Setup](../CONFIGURATION.md#claude-desktop-macos) |
|
| Claude Desktop | [Setup](../CONFIGURATION.md#claude-desktop-macos) |
|
||||||
|
|
|
||||||
|
|
@ -252,6 +252,7 @@ Vestige uses the MCP standard — the same memory works across all your tools:
|
||||||
| Claude Desktop | [Setup](../CONFIGURATION.md#claude-desktop-macos) |
|
| Claude Desktop | [Setup](../CONFIGURATION.md#claude-desktop-macos) |
|
||||||
| Cursor | [Setup](./cursor.md) |
|
| Cursor | [Setup](./cursor.md) |
|
||||||
| VS Code (Copilot) | [Setup](./vscode.md) |
|
| VS Code (Copilot) | [Setup](./vscode.md) |
|
||||||
|
| OpenCode | [Setup](./opencode.md) |
|
||||||
| JetBrains | [Setup](./jetbrains.md) |
|
| JetBrains | [Setup](./jetbrains.md) |
|
||||||
| Windsurf | [Setup](./windsurf.md) |
|
| Windsurf | [Setup](./windsurf.md) |
|
||||||
|
|
||||||
|
|
|
||||||
123
docs/launch/opencode-adoption.md
Normal file
123
docs/launch/opencode-adoption.md
Normal file
|
|
@ -0,0 +1,123 @@
|
||||||
|
# OpenCode Adoption Plan
|
||||||
|
|
||||||
|
Status: Vestige was tested with OpenCode `1.16.2` on June 8, 2026. The working config uses OpenCode's top-level `mcp.vestige` schema, not `mcpServers`.
|
||||||
|
|
||||||
|
Public promotion started:
|
||||||
|
|
||||||
|
- Vestige PR #70: `https://github.com/samvallad33/vestige/pull/70`
|
||||||
|
- OpenCode issue: `https://github.com/anomalyco/opencode/issues/31402`
|
||||||
|
- OpenCode docs/ecosystem PR: `https://github.com/anomalyco/opencode/pull/31405`
|
||||||
|
- awesome-opencode PR: `https://github.com/awesome-opencode/awesome-opencode/pull/418`
|
||||||
|
- opencode.cafe listing request: `https://github.com/R44VC0RP/opencode.cafe/issues/6`
|
||||||
|
- OpenCode persistent memory comment: `https://github.com/anomalyco/opencode/issues/16077#issuecomment-4652064625`
|
||||||
|
|
||||||
|
## Release Gate
|
||||||
|
|
||||||
|
- PR #67 is merged upstream and should be treated as the contributor-driven starting point.
|
||||||
|
- Ship the corrected OpenCode config docs and `@vestige/init` migration from stale `mcpServers.vestige` to `mcp.vestige`.
|
||||||
|
- Ship the background embedding initialization fix before making direct `npx` the main OpenCode install path. A cold published `2.1.23` package can still time out while OpenCode waits for tools.
|
||||||
|
- After release, verify all three OpenCode paths again:
|
||||||
|
- installed binary: `command: ["vestige-mcp"]`
|
||||||
|
- project memory: `command: ["vestige-mcp", "--data-dir", "./.vestige"]`
|
||||||
|
- direct npm: `command: ["npx", "-y", "-p", "vestige-mcp-server@latest", "vestige-mcp"]` with `timeout: 60000`
|
||||||
|
|
||||||
|
## Official OpenCode PR
|
||||||
|
|
||||||
|
Target repo: `https://github.com/anomalyco/opencode`
|
||||||
|
|
||||||
|
Files:
|
||||||
|
|
||||||
|
- `packages/web/src/content/docs/mcp-servers.mdx`
|
||||||
|
- `packages/web/src/content/docs/ecosystem.mdx`
|
||||||
|
|
||||||
|
MCP docs snippet:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"$schema": "https://opencode.ai/config.json",
|
||||||
|
"mcp": {
|
||||||
|
"vestige": {
|
||||||
|
"type": "local",
|
||||||
|
"command": ["npx", "-y", "-p", "vestige-mcp-server@latest", "vestige-mcp"],
|
||||||
|
"enabled": true,
|
||||||
|
"timeout": 60000
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Ecosystem row:
|
||||||
|
|
||||||
|
```md
|
||||||
|
| [Vestige](https://github.com/samvallad33/vestige) | Local MCP memory server for OpenCode that remembers project decisions, preferences, and previous fixes across sessions |
|
||||||
|
```
|
||||||
|
|
||||||
|
Positioning: local, inspectable MCP memory for OpenCode. Avoid claiming Vestige fixes OpenCode's process memory or session resume behavior.
|
||||||
|
|
||||||
|
## Awesome OpenCode
|
||||||
|
|
||||||
|
Target repo: `https://github.com/awesome-opencode/awesome-opencode`
|
||||||
|
|
||||||
|
Suggested entry, with category to confirm against maintainer preference (`data/projects/vestige.yaml` or `data/resources/vestige.yaml`):
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
name: Vestige
|
||||||
|
repo: https://github.com/samvallad33/vestige
|
||||||
|
tagline: Local persistent memory for OpenCode
|
||||||
|
description: Local MCP server that lets OpenCode remember project decisions, preferences, architecture context, and previous fixes across sessions.
|
||||||
|
scope:
|
||||||
|
- global
|
||||||
|
- project
|
||||||
|
tags:
|
||||||
|
- mcp
|
||||||
|
- memory
|
||||||
|
- local-first
|
||||||
|
- sqlite
|
||||||
|
- opencode
|
||||||
|
min_version: 1.16.2
|
||||||
|
homepage: https://github.com/samvallad33/vestige/blob/main/docs/integrations/opencode.md
|
||||||
|
installation: |
|
||||||
|
npm install -g vestige-mcp-server@latest
|
||||||
|
npx @vestige/init
|
||||||
|
```
|
||||||
|
|
||||||
|
## MCP Directories
|
||||||
|
|
||||||
|
Current state:
|
||||||
|
|
||||||
|
- Official MCP Registry already lists `io.github.samvallad33/vestige` at `https://registry.modelcontextprotocol.io/v0/servers?search=vestige`.
|
||||||
|
- Smithery already lists Vestige and indexes 25 tools: `https://smithery.ai/server/@samvallad33/vestige`.
|
||||||
|
- Glama already lists Vestige, but the listing needs a refresh/fix if it shows no tools: `https://glama.ai/mcp/servers/samvallad33/vestige`.
|
||||||
|
- `mcp.so` does not show Vestige under the expected slugs yet; submit manually at `https://mcp.so/submit`.
|
||||||
|
|
||||||
|
Priority order:
|
||||||
|
|
||||||
|
1. Official MCP Registry: `https://github.com/modelcontextprotocol/registry`
|
||||||
|
2. Awesome MCP Servers: `https://github.com/punkpeye/awesome-mcp-servers`
|
||||||
|
3. Glama MCP directory: `https://glama.ai/mcp/servers`
|
||||||
|
4. Smithery: `https://smithery.ai`
|
||||||
|
5. PulseMCP: `https://www.pulsemcp.com`
|
||||||
|
|
||||||
|
Registry metadata is mostly ready: `server.json` exists and `packages/vestige-mcp-npm/package.json` has `mcpName: "io.github.samvallad33/vestige"`. Publish only when the package version and `server.json` version match the released npm package.
|
||||||
|
|
||||||
|
## Community Launch
|
||||||
|
|
||||||
|
Use tested technical copy, not hype:
|
||||||
|
|
||||||
|
> Vestige now works with OpenCode as a local MCP memory server. It gives OpenCode persistent memory for project decisions, preferences, architecture context, and previous fixes across sessions. Install with `npm install -g vestige-mcp-server@latest`, run `npx @vestige/init`, then verify with `opencode mcp list`.
|
||||||
|
|
||||||
|
High-signal channels after release:
|
||||||
|
|
||||||
|
- OpenCode Discord: `https://opencode.ai/discord`
|
||||||
|
- opencode.cafe MCP Server listing: `https://opencode.cafe`
|
||||||
|
- OpenCode memory-related GitHub issues, only where directly relevant
|
||||||
|
- Hacker News and Lobsters with a technical post about the tested OpenCode integration and failure modes
|
||||||
|
- npm keyword/discovery after the next package release includes `opencode`
|
||||||
|
|
||||||
|
## Proof Checklist
|
||||||
|
|
||||||
|
- `opencode debug config` accepts `mcp.vestige`.
|
||||||
|
- `opencode mcp list` shows `vestige connected`.
|
||||||
|
- Stale `mcpServers.vestige` examples fail in OpenCode and are migrated by `@vestige/init`.
|
||||||
|
- OpenCode tools are prefixed as `vestige_search`, `vestige_smart_ingest`, `vestige_session_context`, and `vestige_deep_reference`.
|
||||||
|
- The OpenCode guide says `timeout: 60000` for direct `npx` and `timeout: 10000` for installed binaries.
|
||||||
1026
docs/plans/0001-phase-1-storage-trait-extraction.md
Normal file
1026
docs/plans/0001-phase-1-storage-trait-extraction.md
Normal file
File diff suppressed because it is too large
Load diff
689
docs/plans/0001a-trait-rewrite.md
Normal file
689
docs/plans/0001a-trait-rewrite.md
Normal file
|
|
@ -0,0 +1,689 @@
|
||||||
|
# Phase 1 Amendment Sub-Plan: async_trait -> trait_variant
|
||||||
|
|
||||||
|
**Status**: Draft
|
||||||
|
**Depends on**: Phase 1 (already on `feat/storage-trait-phase1`, tip 790c0c8)
|
||||||
|
**Followed by**: `docs/plans/0001c-async-trait-sunset.md` (Embedder rewrite + async-trait crate removal)
|
||||||
|
**Related**: docs/adr/0002-phase-2-execution.md (decision D1), docs/plans/0001-phase-1-storage-trait-extraction.md
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Context
|
||||||
|
|
||||||
|
Phase 1 froze with the storage trait declared as
|
||||||
|
`#[async_trait::async_trait] pub trait MemoryStore: Send + Sync + 'static`
|
||||||
|
and a `pub use MemoryStore as LocalMemoryStore;` alias. `async_trait` boxes
|
||||||
|
every `async fn` in the trait into `Pin<Box<dyn Future + Send>>`. That is one
|
||||||
|
heap allocation per call inside the hottest code path in Vestige (insert,
|
||||||
|
search, update_scheduling are all on this surface). It also collapses the
|
||||||
|
two intended trait shapes -- a Send-bound `MemoryStore` for tokio/axum and a
|
||||||
|
non-Send `LocalMemoryStore` for thread-local backends -- into a single trait
|
||||||
|
behind an alias, removing the type-system signal we will want for Phase 2's
|
||||||
|
Postgres backend.
|
||||||
|
|
||||||
|
ADR 0002 decision D1 supersedes this. The amendment lands on the existing
|
||||||
|
`feat/storage-trait-phase1` branch before Phase 2 starts, before the PR is
|
||||||
|
opened upstream. The end state:
|
||||||
|
|
||||||
|
- `LocalMemoryStore` is the source-of-truth trait, declared with native
|
||||||
|
async-fn-in-trait (stable on MSRV 1.91), no `Sync` bound on the trait
|
||||||
|
itself, and `Sync + 'static` on the trait object.
|
||||||
|
- `MemoryStore` is auto-generated by `#[trait_variant::make(MemoryStore: Send)]`
|
||||||
|
with `Send` bounds on every returned future, so `Arc<dyn MemoryStore>` is
|
||||||
|
movable across `tokio::spawn`.
|
||||||
|
- `trait-variant` 0.1 is already present in `crates/vestige-core/Cargo.toml`.
|
||||||
|
The `async-trait` crate dependency stays in place through this sub-plan
|
||||||
|
(it is still in use by the embedder impl); removing it is the job of
|
||||||
|
`0001c-async-trait-sunset.md`.
|
||||||
|
- No production caller changes. Every production call site holds
|
||||||
|
`Arc<Storage>` (the concrete `SqliteMemoryStore` alias), which the trait
|
||||||
|
rewrite does not touch. Only the trait declaration and impl blocks change.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Scope
|
||||||
|
|
||||||
|
### In scope
|
||||||
|
|
||||||
|
- Rewrite `MemoryStore` / `LocalMemoryStore` declaration in
|
||||||
|
`crates/vestige-core/src/storage/memory_store.rs` to use
|
||||||
|
`#[trait_variant::make(MemoryStore: Send)] pub trait LocalMemoryStore`.
|
||||||
|
- Remove the `pub use MemoryStore as LocalMemoryStore;` alias from the same
|
||||||
|
file. `LocalMemoryStore` becomes the real trait; `MemoryStore` is the
|
||||||
|
generated Send variant.
|
||||||
|
- Drop the `#[async_trait::async_trait]` attribute on the SQLite impl block
|
||||||
|
in `crates/vestige-core/src/storage/sqlite.rs` (line 6274). The impl block
|
||||||
|
switches from `impl MemoryStore for SqliteMemoryStore` (currently spelled
|
||||||
|
through the `LocalMemoryStore` alias) to `impl LocalMemoryStore for
|
||||||
|
SqliteMemoryStore`. `trait_variant` provides a blanket `impl<T:
|
||||||
|
LocalMemoryStore + Send> MemoryStore for T` so `&dyn MemoryStore` and
|
||||||
|
`Arc<dyn MemoryStore>` keep working unchanged.
|
||||||
|
- Update doc comments in `memory_store.rs` to drop
|
||||||
|
references to `#[async_trait::async_trait]` and instead describe the
|
||||||
|
`trait_variant` mechanism.
|
||||||
|
- Keep the existing Phase 1 test suite (`tests/phase_1/*.rs`) green. The
|
||||||
|
tests already use `Arc<dyn MemoryStore>` and `Box<dyn Embedder>`, which is
|
||||||
|
exactly the surface the rewrite is meant to preserve.
|
||||||
|
|
||||||
|
### Out of scope -- moved to 0001c
|
||||||
|
|
||||||
|
- Rewriting the `Embedder` / `LocalEmbedder` trait declaration -- handled by
|
||||||
|
`0001c-async-trait-sunset.md`.
|
||||||
|
- Dropping `#[async_trait::async_trait]` from
|
||||||
|
`crates/vestige-core/src/embedder/fastembed.rs`.
|
||||||
|
- Removing `async-trait = "0.1"` from `crates/vestige-core/Cargo.toml`.
|
||||||
|
- The hard `grep -rn 'async_trait' crates/` zero-match gate (async_trait is
|
||||||
|
still present in the embedder module after 0001a alone).
|
||||||
|
|
||||||
|
### Out of scope
|
||||||
|
|
||||||
|
- The SQLite file split (`sqlite.rs` -> `sqlite/` directory). That is the
|
||||||
|
sibling sub-plan `0001b-sqlite-split.md`.
|
||||||
|
- Any production-side refactor that switches `Arc<Storage>` to
|
||||||
|
`Arc<dyn MemoryStore>`. Production code keeps using the concrete alias.
|
||||||
|
- Adding `register_model` / `from_pool` / Postgres-specific variants of
|
||||||
|
`MemoryStoreError`. Those land with the Postgres backend in Phase 2.
|
||||||
|
- Removing the `pub type Storage = SqliteMemoryStore;` alias.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Prerequisites
|
||||||
|
|
||||||
|
### Current state (verified)
|
||||||
|
|
||||||
|
- `crates/vestige-core/Cargo.toml` already declares
|
||||||
|
`trait-variant = "0.1"` (line 117). `async-trait = "0.1"` (line 119)
|
||||||
|
remains in place for the duration of this sub-plan; `0001c` removes it.
|
||||||
|
- `crates/vestige-core/src/storage/memory_store.rs:194` declares the trait
|
||||||
|
with `#[async_trait::async_trait] pub trait MemoryStore: Send + Sync +
|
||||||
|
'static`.
|
||||||
|
- `crates/vestige-core/src/storage/memory_store.rs:262` has
|
||||||
|
`pub use MemoryStore as LocalMemoryStore;`.
|
||||||
|
- `crates/vestige-core/src/storage/sqlite.rs:6274` declares
|
||||||
|
`#[async_trait::async_trait] impl
|
||||||
|
crate::storage::memory_store::LocalMemoryStore for SqliteMemoryStore`.
|
||||||
|
- Production call sites use `Arc<Storage>` (the concrete
|
||||||
|
`SqliteMemoryStore` alias). Confirmed by grep:
|
||||||
|
`grep -rn "dyn MemoryStore\|dyn LocalMemoryStore" --include="*.rs"`
|
||||||
|
returns hits only in `tests/phase_1/*.rs`, in two comments inside
|
||||||
|
`memory_store.rs` and `sqlite.rs`, and in one test-only `&dyn MemoryStore`
|
||||||
|
cast inside `sqlite.rs::tests` (line 8669).
|
||||||
|
- Workspace-wide `async_trait` usages: only the trait declarations and
|
||||||
|
impl blocks in `memory_store.rs`, `sqlite.rs`, `embedder/mod.rs`, and
|
||||||
|
`embedder/fastembed.rs` (verified by
|
||||||
|
`grep -rn async_trait --include="*.rs"`). This sub-plan touches only the
|
||||||
|
first two; the embedder files are addressed by `0001c`.
|
||||||
|
|
||||||
|
### Required crates
|
||||||
|
|
||||||
|
| Crate | Version | Action |
|
||||||
|
|-------|---------|--------|
|
||||||
|
| `trait-variant` | `0.1` | Already declared. Verify present after edit. |
|
||||||
|
| `async-trait` | `0.1` | Unchanged for this sub-plan (still used by embedder impl). Removed by `0001c`. |
|
||||||
|
| `blake3`, `thiserror`, `chrono`, `uuid`, `serde`, `serde_json` | unchanged | unchanged |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Files Touched
|
||||||
|
|
||||||
|
Grouped by category. Every change is listed; nothing else gets touched.
|
||||||
|
|
||||||
|
### Trait declarations (vestige-core)
|
||||||
|
|
||||||
|
| File | Lines (approx) | Change |
|
||||||
|
|------|----------------|--------|
|
||||||
|
| `crates/vestige-core/src/storage/memory_store.rs` | 183-262 | Replace `#[async_trait::async_trait]` block with `#[trait_variant::make(MemoryStore: Send)] pub trait LocalMemoryStore`. Drop the `pub use MemoryStore as LocalMemoryStore;` alias. Update doc comments. |
|
||||||
|
|
||||||
|
### Impl blocks (vestige-core)
|
||||||
|
|
||||||
|
| File | Lines (approx) | Change |
|
||||||
|
|------|----------------|--------|
|
||||||
|
| `crates/vestige-core/src/storage/sqlite.rs` | 6274 (impl block header only) | Delete the `#[async_trait::async_trait]` attribute. Keep the `impl crate::storage::memory_store::LocalMemoryStore for SqliteMemoryStore { ... }` body verbatim. |
|
||||||
|
|
||||||
|
### Cargo dependency cleanup
|
||||||
|
|
||||||
|
None in this sub-plan. The `async-trait` crate stays declared in
|
||||||
|
`crates/vestige-core/Cargo.toml` because the embedder impl still uses it.
|
||||||
|
`0001c-async-trait-sunset.md` removes the dependency after the embedder
|
||||||
|
side is rewritten.
|
||||||
|
|
||||||
|
### Cognitive module call sites
|
||||||
|
|
||||||
|
No changes. The 29 cognitive modules under `crates/vestige-core/src/neuroscience/`
|
||||||
|
and `crates/vestige-core/src/advanced/` already operate on concrete
|
||||||
|
`SqliteMemoryStore` (via the `Storage` alias) or on plain data types
|
||||||
|
(`KnowledgeNode`, `Vec<f32>`, `ConnectionRecord`). Grep verified zero
|
||||||
|
production references to `dyn MemoryStore` or `dyn LocalMemoryStore`.
|
||||||
|
|
||||||
|
### MCP call sites
|
||||||
|
|
||||||
|
No changes. All ~30 `vestige-mcp/src/**.rs` files holding `Arc<Storage>`
|
||||||
|
keep working because:
|
||||||
|
- `Storage` is still `pub type Storage = SqliteMemoryStore;` (unchanged).
|
||||||
|
- They call inherent methods on the concrete type, never via a trait object.
|
||||||
|
- `SqliteMemoryStore` implements `LocalMemoryStore`; `trait_variant` auto-
|
||||||
|
generates a blanket `impl<T: LocalMemoryStore + Send> MemoryStore for T`,
|
||||||
|
so the concrete type also satisfies `MemoryStore` for any future caller
|
||||||
|
that wants the trait-object form.
|
||||||
|
|
||||||
|
### Test files (vestige-core integration tests)
|
||||||
|
|
||||||
|
| File | Lines | Change |
|
||||||
|
|------|-------|--------|
|
||||||
|
| `tests/phase_1/trait_round_trip.rs` | 7-18, 134 | No change. Already uses `Arc<dyn MemoryStore>` and `use vestige_core::storage::MemoryStore`. trait_variant emits a `MemoryStore` trait at the same path, so the imports resolve. |
|
||||||
|
| `tests/phase_1/send_bound_variant.rs` | 10-12, 36, 57 | No change. Already asserts the trait_variant Send invariant; the rewrite is what makes the doc comment on lines 3-4 actually true. |
|
||||||
|
| `tests/phase_1/cognitive_module_isolation.rs` | 11, 37, 76, 102, 115 | No change. |
|
||||||
|
| `tests/phase_1/embedding_model_registry.rs` | 10 | No change. |
|
||||||
|
| `tests/phase_1/domain_column_migration.rs` | 98 | No change. |
|
||||||
|
| `crates/vestige-core/src/storage/sqlite.rs::tests` | 8666-8675 | No change. The existing test casts `&s` to `&dyn MemoryStore` and calls trait methods through that vtable; trait_variant preserves this exact dyn-compatible surface. |
|
||||||
|
|
||||||
|
### Documentation
|
||||||
|
|
||||||
|
| File | Change |
|
||||||
|
|------|--------|
|
||||||
|
| `crates/vestige-core/src/storage/memory_store.rs` | Rewrite the trait-level doc comment (lines 185-193) to describe trait_variant rather than async_trait. |
|
||||||
|
| `CLAUDE.md` | No change. The repo-level architecture notes do not name the trait attribute. |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Trait Declaration Rewrite
|
||||||
|
|
||||||
|
### Before (current state on `feat/storage-trait-phase1`)
|
||||||
|
|
||||||
|
`crates/vestige-core/src/storage/memory_store.rs:183-262`:
|
||||||
|
|
||||||
|
```rust
|
||||||
|
// ----------------------------------------------------------------------------
|
||||||
|
// TRAIT
|
||||||
|
// ----------------------------------------------------------------------------
|
||||||
|
|
||||||
|
/// The single storage abstraction.
|
||||||
|
///
|
||||||
|
/// `#[async_trait::async_trait]` makes every `async fn` return a
|
||||||
|
/// `Pin<Box<dyn Future + Send>>`, which is required for `Arc<dyn MemoryStore>`
|
||||||
|
/// to be movable across `tokio::spawn` boundaries.
|
||||||
|
///
|
||||||
|
/// `LocalMemoryStore` is a type alias kept for source compatibility with code
|
||||||
|
/// that refers to the non-send variant. In Phase 1 both names refer to the same
|
||||||
|
/// (dyn-compatible, Send-safe) trait.
|
||||||
|
#[async_trait::async_trait]
|
||||||
|
pub trait MemoryStore: Send + Sync + 'static {
|
||||||
|
// --- Lifecycle ---
|
||||||
|
async fn init(&self) -> MemoryStoreResult<()>;
|
||||||
|
async fn health_check(&self) -> MemoryStoreResult<HealthStatus>;
|
||||||
|
|
||||||
|
// ... 25 more async fn ...
|
||||||
|
|
||||||
|
async fn vacuum(&self) -> MemoryStoreResult<()>;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Type alias kept for source compatibility. Both names refer to the same
|
||||||
|
/// `async_trait`-annotated trait that is dyn-compatible and `Send + Sync`.
|
||||||
|
pub use MemoryStore as LocalMemoryStore;
|
||||||
|
```
|
||||||
|
|
||||||
|
### After
|
||||||
|
|
||||||
|
`crates/vestige-core/src/storage/memory_store.rs:183-262`:
|
||||||
|
|
||||||
|
```rust
|
||||||
|
// ----------------------------------------------------------------------------
|
||||||
|
// TRAIT
|
||||||
|
// ----------------------------------------------------------------------------
|
||||||
|
|
||||||
|
/// The single storage abstraction.
|
||||||
|
///
|
||||||
|
/// `LocalMemoryStore` is the source-of-truth trait. The
|
||||||
|
/// `#[trait_variant::make(MemoryStore: Send)]` attribute auto-generates a
|
||||||
|
/// `MemoryStore` trait whose returned futures are `Send`, so
|
||||||
|
/// `Arc<dyn MemoryStore>` is movable across `tokio::spawn` boundaries while
|
||||||
|
/// `Arc<dyn LocalMemoryStore>` remains usable on single-threaded executors
|
||||||
|
/// and thread-local backends.
|
||||||
|
///
|
||||||
|
/// Every method is native async-fn-in-trait (stable on MSRV 1.91); no
|
||||||
|
/// per-call heap allocation, no boxed futures.
|
||||||
|
#[trait_variant::make(MemoryStore: Send)]
|
||||||
|
pub trait LocalMemoryStore: Sync + 'static {
|
||||||
|
// --- Lifecycle ---
|
||||||
|
async fn init(&self) -> MemoryStoreResult<()>;
|
||||||
|
async fn health_check(&self) -> MemoryStoreResult<HealthStatus>;
|
||||||
|
|
||||||
|
// --- Embedding model registry ---
|
||||||
|
async fn registered_model(&self) -> MemoryStoreResult<Option<ModelSignature>>;
|
||||||
|
async fn register_model(&self, sig: &ModelSignature) -> MemoryStoreResult<()>;
|
||||||
|
|
||||||
|
// --- CRUD ---
|
||||||
|
async fn insert(&self, record: &MemoryRecord) -> MemoryStoreResult<Uuid>;
|
||||||
|
async fn get(&self, id: Uuid) -> MemoryStoreResult<Option<MemoryRecord>>;
|
||||||
|
async fn update(&self, record: &MemoryRecord) -> MemoryStoreResult<()>;
|
||||||
|
async fn delete(&self, id: Uuid) -> MemoryStoreResult<()>;
|
||||||
|
|
||||||
|
// --- Search ---
|
||||||
|
async fn search(&self, query: &SearchQuery) -> MemoryStoreResult<Vec<SearchResult>>;
|
||||||
|
async fn fts_search(&self, text: &str, limit: usize) -> MemoryStoreResult<Vec<SearchResult>>;
|
||||||
|
async fn vector_search(
|
||||||
|
&self,
|
||||||
|
embedding: &[f32],
|
||||||
|
limit: usize,
|
||||||
|
) -> MemoryStoreResult<Vec<SearchResult>>;
|
||||||
|
|
||||||
|
// --- FSRS Scheduling ---
|
||||||
|
async fn get_scheduling(
|
||||||
|
&self,
|
||||||
|
memory_id: Uuid,
|
||||||
|
) -> MemoryStoreResult<Option<SchedulingState>>;
|
||||||
|
async fn update_scheduling(&self, state: &SchedulingState) -> MemoryStoreResult<()>;
|
||||||
|
async fn get_due_memories(
|
||||||
|
&self,
|
||||||
|
before: DateTime<Utc>,
|
||||||
|
limit: usize,
|
||||||
|
) -> MemoryStoreResult<Vec<(MemoryRecord, SchedulingState)>>;
|
||||||
|
|
||||||
|
// --- Graph (spreading activation) ---
|
||||||
|
async fn add_edge(&self, edge: &MemoryEdge) -> MemoryStoreResult<()>;
|
||||||
|
async fn get_edges(
|
||||||
|
&self,
|
||||||
|
node_id: Uuid,
|
||||||
|
edge_type: Option<&str>,
|
||||||
|
) -> MemoryStoreResult<Vec<MemoryEdge>>;
|
||||||
|
async fn remove_edge(&self, source: Uuid, target: Uuid) -> MemoryStoreResult<()>;
|
||||||
|
async fn get_neighbors(
|
||||||
|
&self,
|
||||||
|
node_id: Uuid,
|
||||||
|
depth: usize,
|
||||||
|
) -> MemoryStoreResult<Vec<(MemoryRecord, f64)>>;
|
||||||
|
|
||||||
|
// --- Domains ---
|
||||||
|
async fn list_domains(&self) -> MemoryStoreResult<Vec<Domain>>;
|
||||||
|
async fn get_domain(&self, id: &str) -> MemoryStoreResult<Option<Domain>>;
|
||||||
|
async fn upsert_domain(&self, domain: &Domain) -> MemoryStoreResult<()>;
|
||||||
|
async fn delete_domain(&self, id: &str) -> MemoryStoreResult<()>;
|
||||||
|
async fn classify(&self, embedding: &[f32]) -> MemoryStoreResult<Vec<(String, f64)>>;
|
||||||
|
|
||||||
|
// --- Bulk / Maintenance ---
|
||||||
|
async fn count(&self) -> MemoryStoreResult<usize>;
|
||||||
|
async fn get_stats(&self) -> MemoryStoreResult<StoreStats>;
|
||||||
|
async fn vacuum(&self) -> MemoryStoreResult<()>;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Notes:
|
||||||
|
|
||||||
|
- The `pub use MemoryStore as LocalMemoryStore;` line on the current
|
||||||
|
`memory_store.rs:262` is **deleted** entirely. `MemoryStore` is now the
|
||||||
|
generated trait that `trait_variant::make` emits at the same module path;
|
||||||
|
`LocalMemoryStore` is the source-of-truth declaration. Both names export
|
||||||
|
from `storage/mod.rs` already (see lines 10-14 of that file).
|
||||||
|
- `Sync + 'static` on `LocalMemoryStore` (and no `Send` bound on the trait
|
||||||
|
itself) is correct: `Send` on the trait is what `trait_variant::make`
|
||||||
|
inserts when it emits the `MemoryStore` variant. The current trait carries
|
||||||
|
`Send + Sync + 'static`; the rewrite drops the `Send` bound from the
|
||||||
|
local variant. `Arc<dyn LocalMemoryStore>` is `Sync` but not `Send`;
|
||||||
|
`Arc<dyn MemoryStore>` (the generated variant) is `Send + Sync`.
|
||||||
|
- `trait_variant` 0.1 does **not** require any attribute on the impl block.
|
||||||
|
The attribute lives only on the trait declaration. See the next section.
|
||||||
|
|
||||||
|
The Embedder trait rewrite uses the identical `trait_variant::make` pattern
|
||||||
|
and is fully specified in `0001c-async-trait-sunset.md`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Impl Block Migration
|
||||||
|
|
||||||
|
`trait_variant` 0.1 attaches the attribute only to the trait declaration.
|
||||||
|
The impl side is plain `impl LocalMemoryStore for SqliteMemoryStore`; no
|
||||||
|
attribute on the impl, no `#[trait_variant::make(MemoryStore: Send)]` on the
|
||||||
|
impl block. The crate auto-generates the blanket
|
||||||
|
`impl<T: LocalMemoryStore + Send> MemoryStore for T`, so any concrete type
|
||||||
|
that implements `LocalMemoryStore` automatically also implements
|
||||||
|
`MemoryStore` provided it is `Send`.
|
||||||
|
|
||||||
|
`SqliteMemoryStore` already is `Send + Sync` (it holds `Mutex<Connection>`
|
||||||
|
fields whose `Mutex` is `std::sync::Mutex`, which is `Send + Sync` when its
|
||||||
|
guarded type is `Send`; `rusqlite::Connection` is `Send`). No new bound is
|
||||||
|
needed.
|
||||||
|
|
||||||
|
### Before
|
||||||
|
|
||||||
|
`crates/vestige-core/src/storage/sqlite.rs:6274`:
|
||||||
|
|
||||||
|
```rust
|
||||||
|
#[async_trait::async_trait]
|
||||||
|
impl crate::storage::memory_store::LocalMemoryStore for SqliteMemoryStore {
|
||||||
|
async fn init(&self) -> crate::storage::memory_store::MemoryStoreResult<()> {
|
||||||
|
// Migrations run in `new`; this is a no-op for the SQLite backend.
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
// ... ~2400 lines of method bodies, unchanged ...
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### After
|
||||||
|
|
||||||
|
`crates/vestige-core/src/storage/sqlite.rs:6274`:
|
||||||
|
|
||||||
|
```rust
|
||||||
|
impl crate::storage::memory_store::LocalMemoryStore for SqliteMemoryStore {
|
||||||
|
async fn init(&self) -> crate::storage::memory_store::MemoryStoreResult<()> {
|
||||||
|
// Migrations run in `new`; this is a no-op for the SQLite backend.
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
// ... ~2400 lines of method bodies, unchanged ...
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Diff is exactly one removed line (the `#[async_trait::async_trait]` attribute).
|
||||||
|
Every method body, every `async fn` signature, every `use` statement inside
|
||||||
|
the impl block stays verbatim. No `Box::pin(async move { ... })`, no manual
|
||||||
|
`Pin<Box<dyn Future>>`, no `'async_trait` lifetime markers; native
|
||||||
|
async-fn-in-trait does this directly.
|
||||||
|
|
||||||
|
The Embedder impl block rewrite follows the identical "remove one
|
||||||
|
`#[async_trait::async_trait]` attribute" pattern and is fully specified in
|
||||||
|
`0001c-async-trait-sunset.md`.
|
||||||
|
|
||||||
|
### Why the impl block does not need an attribute
|
||||||
|
|
||||||
|
`trait_variant::make` generates two things from the source trait:
|
||||||
|
|
||||||
|
1. The source trait itself (`LocalMemoryStore`), with native async fns.
|
||||||
|
2. A second trait (`MemoryStore`) whose method signatures return
|
||||||
|
`impl Future<Output = ...> + Send` instead of `impl Future<Output = ...>`,
|
||||||
|
plus a blanket impl wiring concrete types through.
|
||||||
|
|
||||||
|
Both are emitted at the macro-call site. `SqliteMemoryStore` only writes one
|
||||||
|
impl block (against `LocalMemoryStore`); the macro-generated blanket
|
||||||
|
guarantees `SqliteMemoryStore: MemoryStore` for free. The current `&dyn
|
||||||
|
MemoryStore` casts (sqlite.rs:8669; tests under tests/phase_1/) keep
|
||||||
|
type-checking unchanged.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Call Site Audit
|
||||||
|
|
||||||
|
Verified via:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
grep -rn "dyn MemoryStore\|dyn LocalMemoryStore" --include="*.rs" \
|
||||||
|
/home/delandtj/prppl/vestige-phase2/
|
||||||
|
grep -rn "Arc<Storage>\|Arc<SqliteMemoryStore>" --include="*.rs" \
|
||||||
|
/home/delandtj/prppl/vestige-phase2/
|
||||||
|
grep -rn "use.*MemoryStore;\|use.*LocalMemoryStore;" --include="*.rs" \
|
||||||
|
/home/delandtj/prppl/vestige-phase2/
|
||||||
|
```
|
||||||
|
|
||||||
|
### Files that reference the trait object form (`dyn MemoryStore` / `dyn LocalMemoryStore`)
|
||||||
|
|
||||||
|
All test-only or doc-comment-only:
|
||||||
|
|
||||||
|
| File | Line | Use | Required change |
|
||||||
|
|------|------|-----|-----------------|
|
||||||
|
| `tests/phase_1/trait_round_trip.rs` | 7-18 | `Arc<dyn MemoryStore>` in `make_store()` and test bodies | None. `MemoryStore` is the generated Send variant; signature stays. |
|
||||||
|
| `tests/phase_1/trait_round_trip.rs` | 134 | `Arc<dyn MemoryStore>` upcast inside a test body | None. |
|
||||||
|
| `tests/phase_1/send_bound_variant.rs` | 10-97 | `Arc<dyn MemoryStore>` moved across `tokio::spawn` | None. This test becomes meaningfully correct only after the rewrite (currently it relies on async_trait boxing; after the rewrite it relies on trait_variant's Send variant -- same observable outcome). |
|
||||||
|
| `tests/phase_1/cognitive_module_isolation.rs` | 11, 33-115 | `Arc<dyn MemoryStore>` passed into cognitive module-style closures | None. |
|
||||||
|
| `tests/phase_1/embedding_model_registry.rs` | 10 | `Arc<dyn MemoryStore>` in `make_store()` | None. |
|
||||||
|
| `tests/phase_1/domain_column_migration.rs` | 98 | `Arc<dyn MemoryStore>` cast inside a migration assertion | None. |
|
||||||
|
| `crates/vestige-core/src/storage/sqlite.rs` | 8666-8675 | `let dyn_s: &dyn MemoryStore = &s;` inside `mod tests` | None. The cast is testing that the dyn-vtable still resolves the trait methods correctly; after the rewrite it resolves through the `MemoryStore` trait that `trait_variant::make` emits at the same path. |
|
||||||
|
| `crates/vestige-core/src/storage/memory_store.rs` | 188 (doc) | Doc comment mentioning `Arc<dyn MemoryStore>` | Replaced as part of the doc rewrite (see Trait Declaration section). |
|
||||||
|
|
||||||
|
### Files that hold the concrete type (`Arc<Storage>` / `Arc<SqliteMemoryStore>`)
|
||||||
|
|
||||||
|
35 files, 116 hits. Every one of them keeps working unchanged because the
|
||||||
|
concrete `SqliteMemoryStore` type stays exactly as it is. Listed here for
|
||||||
|
completeness so a reviewer can confirm none of them needs an edit:
|
||||||
|
|
||||||
|
```
|
||||||
|
crates/vestige-core/src/storage/mod.rs (alias declaration)
|
||||||
|
crates/vestige-core/src/storage/sqlite.rs (impl block)
|
||||||
|
crates/vestige-mcp/src/server.rs (Arc<Storage> in McpServer)
|
||||||
|
crates/vestige-mcp/src/cognitive.rs (hydrate(&Storage))
|
||||||
|
crates/vestige-mcp/src/autopilot.rs
|
||||||
|
crates/vestige-mcp/src/protocol/http.rs
|
||||||
|
crates/vestige-mcp/src/dashboard/mod.rs
|
||||||
|
crates/vestige-mcp/src/dashboard/state.rs
|
||||||
|
crates/vestige-mcp/src/dashboard/handlers.rs
|
||||||
|
crates/vestige-mcp/src/resources/codebase.rs
|
||||||
|
crates/vestige-mcp/src/resources/memory.rs
|
||||||
|
crates/vestige-mcp/src/tools/changelog.rs
|
||||||
|
crates/vestige-mcp/src/tools/codebase_unified.rs
|
||||||
|
crates/vestige-mcp/src/tools/context.rs
|
||||||
|
crates/vestige-mcp/src/tools/contradictions.rs
|
||||||
|
crates/vestige-mcp/src/tools/cross_reference.rs
|
||||||
|
crates/vestige-mcp/src/tools/dedup.rs
|
||||||
|
crates/vestige-mcp/src/tools/dream.rs
|
||||||
|
crates/vestige-mcp/src/tools/explore.rs
|
||||||
|
crates/vestige-mcp/src/tools/feedback.rs
|
||||||
|
crates/vestige-mcp/src/tools/graph.rs
|
||||||
|
crates/vestige-mcp/src/tools/health.rs
|
||||||
|
crates/vestige-mcp/src/tools/importance.rs
|
||||||
|
crates/vestige-mcp/src/tools/intention_unified.rs
|
||||||
|
crates/vestige-mcp/src/tools/maintenance.rs
|
||||||
|
crates/vestige-mcp/src/tools/memory_states.rs
|
||||||
|
crates/vestige-mcp/src/tools/memory_unified.rs
|
||||||
|
crates/vestige-mcp/src/tools/predict.rs
|
||||||
|
crates/vestige-mcp/src/tools/restore.rs
|
||||||
|
crates/vestige-mcp/src/tools/review.rs
|
||||||
|
crates/vestige-mcp/src/tools/search_unified.rs
|
||||||
|
crates/vestige-mcp/src/tools/session_context.rs
|
||||||
|
crates/vestige-mcp/src/tools/smart_ingest.rs
|
||||||
|
crates/vestige-mcp/src/tools/suppress.rs
|
||||||
|
crates/vestige-mcp/src/tools/tagging.rs
|
||||||
|
crates/vestige-mcp/src/tools/timeline.rs
|
||||||
|
```
|
||||||
|
|
||||||
|
Each holds `Arc<Storage>` and dispatches to inherent methods on
|
||||||
|
`SqliteMemoryStore`. None of them goes through a trait vtable. Required
|
||||||
|
change for every one of them: **none**.
|
||||||
|
|
||||||
|
### Files that `use ...MemoryStore` from production code
|
||||||
|
|
||||||
|
```
|
||||||
|
grep -rn "use.*MemoryStore;\|use.*LocalMemoryStore;" --include="*.rs" \
|
||||||
|
| grep -v "memory_store.rs\|sqlite.rs\|tests/phase_1"
|
||||||
|
```
|
||||||
|
|
||||||
|
returns nothing. Production code does not import the trait by name.
|
||||||
|
|
||||||
|
### Conclusion
|
||||||
|
|
||||||
|
The rewrite is a strictly local change to two source files
|
||||||
|
(`storage/memory_store.rs` and `storage/sqlite.rs`). Zero production call
|
||||||
|
sites need edits. The integration tests that consume `Arc<dyn MemoryStore>`
|
||||||
|
keep their current form; the rewrite is what gives that signature its
|
||||||
|
no-box semantics on the storage side. The `Box<dyn Embedder>` surface is
|
||||||
|
addressed by `0001c-async-trait-sunset.md`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Commit Sequence
|
||||||
|
|
||||||
|
Two commits, each green on `cargo test -p vestige-core --no-default-features`
|
||||||
|
and `cargo test -p vestige-core --features embeddings,vector-search`.
|
||||||
|
|
||||||
|
### Commit 1: rewrite MemoryStore / LocalMemoryStore trait declaration
|
||||||
|
|
||||||
|
- Touches: `crates/vestige-core/src/storage/memory_store.rs` only.
|
||||||
|
- Action: replace lines 183-262 per the "Trait Declaration Rewrite" section
|
||||||
|
above. Delete the `pub use MemoryStore as LocalMemoryStore;` line.
|
||||||
|
- Green after: `cargo check -p vestige-core` (the impl block in `sqlite.rs`
|
||||||
|
still has `#[async_trait::async_trait]` on it, but it still resolves
|
||||||
|
through the `LocalMemoryStore` trait which is now native-async; the
|
||||||
|
`async_trait` macro is harmless when applied to a trait that the impl
|
||||||
|
block targets by path, because the macro rewrites the impl's async fns
|
||||||
|
into boxed-future fns whose signatures still match the native-async
|
||||||
|
declarations after trait_variant lowering). If `cargo check` complains
|
||||||
|
here, fold commit 2 into commit 1.
|
||||||
|
|
||||||
|
**Mitigation if check fails between commits 1 and 2:** combine the two
|
||||||
|
into a single commit. The split is offered for review convenience; the
|
||||||
|
build must be green after every commit lands.
|
||||||
|
|
||||||
|
### Commit 2: drop `#[async_trait::async_trait]` from SqliteMemoryStore impl
|
||||||
|
|
||||||
|
- Touches: `crates/vestige-core/src/storage/sqlite.rs` only.
|
||||||
|
- Action: delete line 6274 (`#[async_trait::async_trait]`).
|
||||||
|
- Green after: `cargo test -p vestige-core --features embeddings,vector-search`,
|
||||||
|
including all `trait_*` tests inside `sqlite.rs::tests` (lines 8643-8712)
|
||||||
|
and the trait-object cast on line 8669.
|
||||||
|
|
||||||
|
### Combined alternative
|
||||||
|
|
||||||
|
If the per-step split feels artificial, commits 1 and 2 can collapse into
|
||||||
|
a single commit covering both the trait rewrite and the impl-attribute
|
||||||
|
drop for `MemoryStore`. That is acceptable; the two-commit form is
|
||||||
|
preferred only because it lets a reviewer bisect trait-rewrite failures
|
||||||
|
separately from impl-rewrite failures.
|
||||||
|
|
||||||
|
The Embedder / fastembed commits and the `async-trait` Cargo dependency
|
||||||
|
removal live in `0001c-async-trait-sunset.md`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Verification
|
||||||
|
|
||||||
|
Every command runs from the repo root unless noted otherwise.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 1. Vestige-core, default features (embeddings + vector-search).
|
||||||
|
cargo test -p vestige-core --features embeddings,vector-search
|
||||||
|
|
||||||
|
# 2. Vestige-core, minimal features (no embeddings, no vector-search).
|
||||||
|
cargo test -p vestige-core --no-default-features
|
||||||
|
|
||||||
|
# 3. Workspace build, release mode (catches any feature-gated regression
|
||||||
|
# in the vestige-mcp tools tree).
|
||||||
|
cargo build --workspace --release
|
||||||
|
|
||||||
|
# 4. Whole-workspace test (vestige-mcp 406 tests + vestige-core 352 tests
|
||||||
|
# per the CLAUDE.md baseline).
|
||||||
|
cargo test --workspace
|
||||||
|
|
||||||
|
# 5. Phase 1 integration tests (these are the trait-shape contract).
|
||||||
|
cargo test --test trait_round_trip --features embeddings,vector-search
|
||||||
|
cargo test --test send_bound_variant --features embeddings,vector-search
|
||||||
|
cargo test --test cognitive_module_isolation --features embeddings,vector-search
|
||||||
|
cargo test --test embedding_model_registry --features embeddings,vector-search
|
||||||
|
cargo test --test domain_column_migration --features embeddings,vector-search
|
||||||
|
|
||||||
|
# 6. Clippy gate, deny warnings (matches Phase 1 PR policy of zero warnings).
|
||||||
|
cargo clippy --workspace --all-targets --features embeddings,vector-search -- -D warnings
|
||||||
|
|
||||||
|
# 7. Storage-side dependency hygiene check (must return zero hits).
|
||||||
|
# Scoped to the storage module only -- the embedder module still uses
|
||||||
|
# async_trait until 0001c lands.
|
||||||
|
grep -rn "async_trait\|async-trait" crates/vestige-core/src/storage/
|
||||||
|
|
||||||
|
# 8. Confirm trait_variant attribute is in place on the storage trait
|
||||||
|
# (must return exactly one hit in memory_store.rs).
|
||||||
|
grep -rn "trait_variant::make" crates/vestige-core/src/storage/
|
||||||
|
```
|
||||||
|
|
||||||
|
Expected outcomes:
|
||||||
|
|
||||||
|
- Command 1: 352 tests pass (matches baseline).
|
||||||
|
- Command 2: smaller test count, all pass.
|
||||||
|
- Command 3: workspace compiles in release mode.
|
||||||
|
- Command 4: 758 total tests pass (matches CLAUDE.md baseline).
|
||||||
|
- Command 5: each phase_1 integration test binary runs green. The
|
||||||
|
`send_bound_variant::arc_dyn_memory_store_moves_across_tokio_tasks` test
|
||||||
|
is the canary; if `MemoryStore` lost its Send-bound future variant, this
|
||||||
|
fails to compile with "future cannot be sent between threads safely".
|
||||||
|
- Command 6: zero clippy warnings. The rewrite must not introduce a new
|
||||||
|
`clippy::needless_lifetimes` or `clippy::async_yields_async`.
|
||||||
|
- Command 7: empty output. async_trait is gone from the storage module.
|
||||||
|
The embedder module still contains async_trait; that is removed by
|
||||||
|
`0001c-async-trait-sunset.md`.
|
||||||
|
- Command 8: one hit, in `memory_store.rs`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Acceptance Criteria
|
||||||
|
|
||||||
|
A reviewer should be able to check every box:
|
||||||
|
|
||||||
|
- [ ] `crates/vestige-core/src/storage/memory_store.rs` declares the trait
|
||||||
|
with `#[trait_variant::make(MemoryStore: Send)] pub trait
|
||||||
|
LocalMemoryStore: Sync + 'static`, no `async_trait` attribute, no
|
||||||
|
`Send` bound on `LocalMemoryStore` itself.
|
||||||
|
- [ ] `crates/vestige-core/src/storage/memory_store.rs` no longer contains
|
||||||
|
`pub use MemoryStore as LocalMemoryStore;`.
|
||||||
|
- [ ] `crates/vestige-core/src/storage/sqlite.rs:6274` is plain
|
||||||
|
`impl crate::storage::memory_store::LocalMemoryStore for
|
||||||
|
SqliteMemoryStore` -- no attribute on the impl block.
|
||||||
|
- [ ] `grep -rn "async_trait\|async-trait" crates/vestige-core/src/storage/`
|
||||||
|
returns zero hits.
|
||||||
|
- [ ] `grep -rn "trait_variant::make" crates/vestige-core/src/storage/`
|
||||||
|
returns exactly one hit (the storage trait in `memory_store.rs`).
|
||||||
|
- [ ] All 758 workspace tests pass (`cargo test --workspace`).
|
||||||
|
- [ ] Phase 1 integration tests pass with the trait-object surface
|
||||||
|
(`Arc<dyn MemoryStore>`) intact.
|
||||||
|
- [ ] `cargo clippy --workspace --all-targets --features
|
||||||
|
embeddings,vector-search -- -D warnings` is clean.
|
||||||
|
- [ ] No production source file under `crates/vestige-mcp/` or
|
||||||
|
`crates/vestige-core/src/{neuroscience,advanced,consolidation,codebase,
|
||||||
|
memory,embeddings,embedder}/` was modified by this sub-plan.
|
||||||
|
- [ ] `Arc<Storage>` still type-checks at every existing call site (verified
|
||||||
|
by the workspace test pass).
|
||||||
|
- [ ] Doc comments on the storage trait declaration describe
|
||||||
|
`trait_variant`, not `async_trait`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Risks and Mitigations
|
||||||
|
|
||||||
|
- **`trait_variant` 0.1 macro emits unexpected diagnostics on MSRV 1.91.**
|
||||||
|
Mitigation: the master Phase 1 plan already prescribed this exact pattern
|
||||||
|
(`#[trait_variant::make(MemoryStore: Send)] pub trait LocalMemoryStore:
|
||||||
|
Sync + 'static`, see plan `0001-...` line 274-275); the crate has been in
|
||||||
|
`vestige-core/Cargo.toml` since Phase 1 landed. If a diagnostic appears,
|
||||||
|
pin to the exact known-good version with `trait-variant = "=0.1.2"` and
|
||||||
|
open an upstream issue.
|
||||||
|
- **Native async-fn-in-trait makes the trait no longer dyn-compatible.**
|
||||||
|
Mitigation: `trait_variant::make` is specifically the workaround for this
|
||||||
|
-- it emits both the source trait (for static dispatch) and a Send-bound
|
||||||
|
variant whose returned futures use `Pin<Box<dyn Future + Send>>` only at
|
||||||
|
the dyn boundary. `Arc<dyn MemoryStore>` keeps working because the
|
||||||
|
generated `MemoryStore` trait is dyn-compatible by construction. Verified
|
||||||
|
by the existing `send_bound_variant::*` tests, which intentionally move
|
||||||
|
`Arc<dyn MemoryStore>` across `tokio::spawn` from inside a
|
||||||
|
`multi_thread` runtime.
|
||||||
|
- **A cognitive module silently relied on the boxed-future return type.**
|
||||||
|
Mitigation: grep verified no cognitive module imports `MemoryStore` /
|
||||||
|
`LocalMemoryStore` or holds an `Arc<dyn ...>` form; all of them use the
|
||||||
|
concrete `Storage` alias. There is no Send-ness expectation downstream to
|
||||||
|
break.
|
||||||
|
- **Future bodies inside the SQLite impl capture non-Send locals.**
|
||||||
|
Mitigation: every method body in `sqlite.rs:6274..` runs synchronous
|
||||||
|
rusqlite calls inside the same `async fn` frame; no `.await` points
|
||||||
|
exist inside the bodies that we ship today. The `Send` bound on the
|
||||||
|
generated `MemoryStore` variant is therefore satisfied automatically.
|
||||||
|
If a future change adds `.await` inside an impl method, the new
|
||||||
|
trait_variant surface will surface that as a compile error at the call
|
||||||
|
site, which is the correct outcome.
|
||||||
|
- **`async-trait` crate is left declared after this sub-plan.**
|
||||||
|
This is intentional: the embedder impl still depends on it. The
|
||||||
|
`0001c-async-trait-sunset.md` sub-plan removes the crate after the
|
||||||
|
embedder side is rewritten. Grep on the whole workspace returns only
|
||||||
|
the storage and embedder files; no downstream crate pulls `async-trait`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Out-of-Band Notes
|
||||||
|
|
||||||
|
- This sub-plan amends `feat/storage-trait-phase1` (tip 790c0c8). The
|
||||||
|
branch has not been opened upstream yet, so amending in place is safe;
|
||||||
|
no force-push to a public PR.
|
||||||
|
- The companion sub-plan `0001b-sqlite-split.md` lands after this one on
|
||||||
|
the same branch. The trait-rewrite landing first is intentional: the
|
||||||
|
SQLite split moves the impl block into `storage/sqlite/trait_impl.rs`,
|
||||||
|
and it is cleaner to move a small attribute-free impl than a
|
||||||
|
macro-decorated one.
|
||||||
|
- The companion sub-plan `0001c-async-trait-sunset.md` lands after this
|
||||||
|
one (order with `0001b` is independent) and finishes the
|
||||||
|
async_trait -> trait_variant transition for the Embedder trait, then
|
||||||
|
removes the `async-trait` crate dependency.
|
||||||
|
- After the Phase 1 amendment sub-plans (`0001a`, `0001b`, `0001c`) land,
|
||||||
|
the branch is reviewed and merged before Phase 2 sub-plans (`0002a-`
|
||||||
|
through `0002i-`) begin implementation.
|
||||||
732
docs/plans/0001b-sqlite-split.md
Normal file
732
docs/plans/0001b-sqlite-split.md
Normal file
|
|
@ -0,0 +1,732 @@
|
||||||
|
# Sub-Plan 0001b: Split sqlite.rs into a sqlite/ directory
|
||||||
|
|
||||||
|
**Status**: Draft
|
||||||
|
**Branch**: `feat/storage-trait-phase1` (Phase 1 amendment, PR A)
|
||||||
|
**Depends on**: `0001a-trait-rewrite.md` (must land first; it carries the
|
||||||
|
`trait_variant`-generated trait declaration that `trait_impl.rs` matches)
|
||||||
|
**Related**: `docs/adr/0002-phase-2-execution.md` (D3, D6)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Context
|
||||||
|
|
||||||
|
`crates/vestige-core/src/storage/sqlite.rs` is the single SQLite backend file
|
||||||
|
that Phase 1 inherited from pre-trait Vestige and then appended the
|
||||||
|
`LocalMemoryStore` trait impl block to. The file is 8713 lines as of
|
||||||
|
commit 790c0c8 on `feat/storage-trait-phase1`. ADR 0002 D3 decides to split
|
||||||
|
it into a `sqlite/` directory before Phase 2 lands `postgres/` as a peer.
|
||||||
|
Reasoning, in one paragraph:
|
||||||
|
|
||||||
|
The Postgres backend is going in as a directory of seven small files
|
||||||
|
(`postgres/{mod,pool,migrations,registry,search,migrate_cli,reembed}.rs`).
|
||||||
|
If SQLite stays as one 8K-line file alongside that, the repo says "backends
|
||||||
|
look like one big file or seven small ones, pick a side", which forces
|
||||||
|
every future maintainer to re-litigate the layout. Splitting now -- as
|
||||||
|
**pure code motion**, no public-API change, no behavioural change, no
|
||||||
|
migration -- lets both backends look the same, keeps each surface mappable
|
||||||
|
in a single editor tab, and shrinks the diffs Phase 2 has to review.
|
||||||
|
This sub-plan is sized as one focused implementation session.
|
||||||
|
|
||||||
|
The split is **private** to `storage/sqlite/`. Cognitive modules continue
|
||||||
|
to `use crate::storage::SqliteMemoryStore`; the existing re-exports in
|
||||||
|
`crates/vestige-core/src/storage/mod.rs` keep working without touching
|
||||||
|
any caller. Tests stay green commit-by-commit.
|
||||||
|
|
||||||
|
This sub-plan depends on `0001a-trait-rewrite.md` landing first because
|
||||||
|
`sqlite/trait_impl.rs` is the file that picks up the new trait_variant
|
||||||
|
attribute. Doing the split first would force a second rewrite of
|
||||||
|
`trait_impl.rs` when the trait rewrite arrives. Order matters; this is
|
||||||
|
the cheap-to-respect ordering.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Target Layout
|
||||||
|
|
||||||
|
Final directory after this sub-plan:
|
||||||
|
|
||||||
|
```
|
||||||
|
crates/vestige-core/src/storage/sqlite/
|
||||||
|
mod.rs -- module root: SqliteMemoryStore struct, new(),
|
||||||
|
reader/writer locks, error types, shared helpers,
|
||||||
|
portable-sync-related types, record types
|
||||||
|
crud.rs -- ingest/smart_ingest/get/update/delete/purge/search-by-id
|
||||||
|
search.rs -- fts, semantic, hybrid, time-based queries
|
||||||
|
scheduling.rs -- FSRS state, decay, consolidation, review, promote/demote,
|
||||||
|
suppression, gc, retention, waking tags
|
||||||
|
graph.rs -- memory_connections (edges), subgraph, neighbors
|
||||||
|
domain.rs -- domains/domain_scores column readers, classify stub
|
||||||
|
(Phase 4 will expand this file)
|
||||||
|
registry.rs -- embedding_model table, enforce_model, register_model body
|
||||||
|
portable_sync.rs -- portable export/import/sync + merge helpers
|
||||||
|
trait_impl.rs -- impl LocalMemoryStore for SqliteMemoryStore
|
||||||
|
```
|
||||||
|
|
||||||
|
`storage/mod.rs` is unchanged in spirit: it still does `mod sqlite;` and
|
||||||
|
`pub use sqlite::{...};` -- the only difference is that `sqlite` is now a
|
||||||
|
directory module instead of a leaf file. The re-export list does not
|
||||||
|
change.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Current File Map (line numbers from commit 790c0c8)
|
||||||
|
|
||||||
|
The current `sqlite.rs` is structurally:
|
||||||
|
|
||||||
|
| Region | Lines | Contents |
|
||||||
|
|--------|-------|----------|
|
||||||
|
| Header | 1-43 | Imports, feature-gated imports |
|
||||||
|
| Error types | 45-89 | `StorageError`, `Result`, `SmartIngestResult`, `MergeWrite` |
|
||||||
|
| Portable sync types | 97-211 | `PortableSyncBackend` trait, `FilePortableSyncBackend` struct, `PortableSyncReport`, `PurgeReport` |
|
||||||
|
| Constants | 233-273 | `PORTABLE_TABLES`, `PORTABLE_USER_DATA_TABLES`, `PortableMergeState`, env constants |
|
||||||
|
| Struct decl | 287-301 | `SqliteMemoryStore` struct fields |
|
||||||
|
| Impl block 1 | 303-3740 | Constructor + bulk of native API |
|
||||||
|
| Record structs | 3747-3866 | `IntentionRecord`, `InsightRecord`, `ConnectionRecord`, `MemoryStateRecord`, `StateTransitionRecord`, `ConsolidationHistoryRecord`, `DreamHistoryRecord`, `Default for InsightRecord` |
|
||||||
|
| Impl block 2 | 3868-6133 | Intentions / Insights / Connections / States / History / Backup / Portable / GC / Subgraph |
|
||||||
|
| Impl block 3 | 6139-6272 | Trait-helper methods (`node_to_record`, `read_domain_columns`, `enforce_model`) |
|
||||||
|
| Trait impl | 6274-7110 | `impl LocalMemoryStore for SqliteMemoryStore` |
|
||||||
|
| Tests | 7112-8713 | `#[cfg(test)] mod tests`: native API tests + trait round-trip tests |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Mapping Table
|
||||||
|
|
||||||
|
Every public method, every private helper, every struct, every test module
|
||||||
|
in the current file -- with the destination file in the new layout. Line
|
||||||
|
ranges cite the current `sqlite.rs` (commit 790c0c8 on
|
||||||
|
`feat/storage-trait-phase1`, viewed through the
|
||||||
|
`/home/delandtj/prppl/vestige-phase2` worktree).
|
||||||
|
|
||||||
|
### Header and shared types (-> `sqlite/mod.rs`)
|
||||||
|
|
||||||
|
| Item | Lines | Destination | Notes |
|
||||||
|
|------|-------|-------------|-------|
|
||||||
|
| Module-level `use` imports | 1-43 | `sqlite/mod.rs` | Trimmed per-file in destination; what does not fit in `mod.rs` moves with its consumers |
|
||||||
|
| `StorageError` enum + `Result` alias | 49-71 | `sqlite/mod.rs` | Re-exported through `pub use` chain; called from every sub-module |
|
||||||
|
| `SmartIngestResult` struct | 73-89 | `sqlite/mod.rs` | Returned by `crud::smart_ingest`; defined here because other code depends on the type |
|
||||||
|
| `MergeWrite` enum | 91-95 | `sqlite/portable_sync.rs` | Only used by merge helpers |
|
||||||
|
| `PortableSyncBackend` trait | 97-109 | `sqlite/portable_sync.rs` | Public trait; re-exported through `mod.rs` |
|
||||||
|
| `FilePortableSyncBackend` struct + `impl` | 111-194 | `sqlite/portable_sync.rs` | |
|
||||||
|
| `PortableSyncReport` struct | 196-211 | `sqlite/portable_sync.rs` | |
|
||||||
|
| `PurgeReport` struct | 213-231 | `sqlite/crud.rs` | Returned by `purge_node` |
|
||||||
|
| `PORTABLE_TABLES` constant | 237-254 | `sqlite/portable_sync.rs` | |
|
||||||
|
| `PORTABLE_USER_DATA_TABLES` constant | 256-272 | `sqlite/portable_sync.rs` | |
|
||||||
|
| `PortableMergeState` struct | 274-277 | `sqlite/portable_sync.rs` | |
|
||||||
|
| `DATA_DIR_ENV` constant | 279 | `sqlite/mod.rs` | Read by constructor |
|
||||||
|
| `DATABASE_FILE` constant | 280 | `sqlite/mod.rs` | Read by constructor |
|
||||||
|
| `SqliteMemoryStore` struct decl | 282-301 | `sqlite/mod.rs` | All fields stay public-to-crate within the directory |
|
||||||
|
|
||||||
|
### Constructor and config (-> `sqlite/mod.rs`)
|
||||||
|
|
||||||
|
These are foundational; they live in `mod.rs` because every sub-module
|
||||||
|
calls them or operates on the struct they build.
|
||||||
|
|
||||||
|
| Item | Lines | Destination | Notes |
|
||||||
|
|------|-------|-------------|-------|
|
||||||
|
| `fn data_dir_from_env` | 304-313 | `sqlite/mod.rs` | private helper |
|
||||||
|
| `fn expand_tilde` | 314-332 | `sqlite/mod.rs` | private helper |
|
||||||
|
| `fn prepare_data_dir` | 333-346 | `sqlite/mod.rs` | private helper |
|
||||||
|
| `pub fn db_path_for_data_dir` | 347-355 | `sqlite/mod.rs` | |
|
||||||
|
| `pub fn default_db_path` | 356-368 | `sqlite/mod.rs` | |
|
||||||
|
| `fn configure_connection` | 369-396 | `sqlite/mod.rs` | |
|
||||||
|
| `pub fn new` | 397-457 | `sqlite/mod.rs` | The constructor |
|
||||||
|
| `pub fn db_path` | 458-462 | `sqlite/mod.rs` | |
|
||||||
|
| `pub fn data_dir` | 463-467 | `sqlite/mod.rs` | |
|
||||||
|
| `pub fn sidecar_dir` | 468-473 | `sqlite/mod.rs` | |
|
||||||
|
| `fn load_embeddings_into_index` | 474-552 | `sqlite/mod.rs` | Called by `new`; touches vector index |
|
||||||
|
|
||||||
|
### CRUD: ingest, get, update, delete, purge (-> `sqlite/crud.rs`)
|
||||||
|
|
||||||
|
| Item | Lines | Destination | Notes |
|
||||||
|
|------|-------|-------------|-------|
|
||||||
|
| `pub fn ingest` | 553-643 | `sqlite/crud.rs` | |
|
||||||
|
| `pub fn smart_ingest` | 644-864 | `sqlite/crud.rs` | Calls vector search via `self.semantic_search`; cross-module call resolved by impl block being on the same struct |
|
||||||
|
| `pub fn get_node_embedding` (vector-search) | 865-887 | `sqlite/crud.rs` | embedding read for one node |
|
||||||
|
| `pub fn get_all_embeddings` (vector-search) | 888-914 | `sqlite/crud.rs` | |
|
||||||
|
| `pub fn get_node_embedding` (no vector-search stub) | 915-919 | `sqlite/crud.rs` | feature-gated alternative |
|
||||||
|
| `pub fn update_node_content` | 920-951 | `sqlite/crud.rs` | |
|
||||||
|
| `fn generate_embedding_for_node` | 952-999 | `sqlite/crud.rs` | private helper; only called by ingest and update_node_content |
|
||||||
|
| `pub fn get_node` | 1000-1011 | `sqlite/crud.rs` | |
|
||||||
|
| `fn parse_timestamp` | 1012-1027 | `sqlite/mod.rs` | **Shared helper**: row_to_node uses it, intention/insight rows also parse timestamps. Bump to `pub(super) fn` |
|
||||||
|
| `fn row_to_node` | 1028-1119 | `sqlite/mod.rs` | **Shared helper**: crud reads single nodes; search.rs builds node lists from rows; scheduling.rs returns nodes for review queue. Bump to `pub(super) fn`. Static method (no `&self`) so a free function in `mod.rs` is fine |
|
||||||
|
| `pub fn delete_node` | 1842-1869 | `sqlite/crud.rs` | |
|
||||||
|
| `pub fn purge_node` | 1870-1987 | `sqlite/crud.rs` | |
|
||||||
|
| `fn node_exists` | 1988-1996 | `sqlite/crud.rs` | static helper, called only by purge |
|
||||||
|
| `fn record_sync_tombstone` | 1997-2014 | `sqlite/crud.rs` | static helper, called by delete and purge |
|
||||||
|
| `pub fn get_all_nodes` | 2268-2291 | `sqlite/crud.rs` | bulk read |
|
||||||
|
| `pub fn get_nodes_by_type_and_tag` | 2292-2342 | `sqlite/crud.rs` | bulk read |
|
||||||
|
|
||||||
|
### Search: fts, semantic, hybrid, temporal (-> `sqlite/search.rs`)
|
||||||
|
|
||||||
|
| Item | Lines | Destination | Notes |
|
||||||
|
|------|-------|-------------|-------|
|
||||||
|
| `pub fn recall` | 1120-1147 | `sqlite/search.rs` | top-level recall path |
|
||||||
|
| `fn keyword_search` | 1148-1180 | `sqlite/search.rs` | private |
|
||||||
|
| `pub fn search` | 2015-2043 | `sqlite/search.rs` | |
|
||||||
|
| `pub fn search_terms` | 2044-2075 | `sqlite/search.rs` | |
|
||||||
|
| `pub fn concrete_search_filtered` | 2076-2172 | `sqlite/search.rs` | |
|
||||||
|
| `fn upsert_concrete_result` | 2173-2197 | `sqlite/search.rs` | static helper |
|
||||||
|
| `fn normalize_literal_query` | 2198-2210 | `sqlite/search.rs` | static helper |
|
||||||
|
| `fn escape_like` | 2211-2224 | `sqlite/search.rs` | static helper |
|
||||||
|
| `fn literal_match_score` | 2225-2248 | `sqlite/search.rs` | static helper |
|
||||||
|
| `fn node_matches_type_filters` | 2249-2267 | `sqlite/search.rs` | static helper |
|
||||||
|
| `pub fn is_embedding_ready` (both feature variants) | 2343-2354 | `sqlite/search.rs` | both versions move together |
|
||||||
|
| `pub fn init_embeddings` (both feature variants) | 2355-2367 | `sqlite/search.rs` | both versions move together |
|
||||||
|
| `fn get_query_embedding` | 2368-2400 | `sqlite/search.rs` | private; uses `query_cache` field |
|
||||||
|
| `pub fn semantic_search` | 2401-2434 | `sqlite/search.rs` | |
|
||||||
|
| `pub fn hybrid_search` (feature on) | 2435-2452 | `sqlite/search.rs` | |
|
||||||
|
| `pub fn hybrid_search_filtered` (feature on) | 2453-2581 | `sqlite/search.rs` | |
|
||||||
|
| `pub fn hybrid_search` (feature off) | 2582-2593 | `sqlite/search.rs` | feature-gated stub |
|
||||||
|
| `pub fn hybrid_search_filtered` (feature off) | 2594-2635 | `sqlite/search.rs` | feature-gated stub |
|
||||||
|
| `fn keyword_search_with_scores` | 2636-2726 | `sqlite/search.rs` | |
|
||||||
|
| `fn semantic_search_raw` | 2727-2765 | `sqlite/search.rs` | |
|
||||||
|
| `pub fn generate_embeddings` | 2766-2819 | `sqlite/search.rs` | populates embeddings post hoc |
|
||||||
|
| `fn embedding_regeneration_candidates` | 2820-2891 | `sqlite/search.rs` | called by generate_embeddings |
|
||||||
|
| `pub fn query_at_time` | 2892-2933 | `sqlite/search.rs` | temporal query |
|
||||||
|
| `pub fn query_time_range` | 2934-3005 | `sqlite/search.rs` | temporal query |
|
||||||
|
| `fn embedding_model_matches_active` (associated fn) | 5652-5671 | `sqlite/search.rs` | static helper for hybrid_search; promoted to `pub(super)` (test references it) |
|
||||||
|
| `fn embedding_model_supports_matryoshka` | 5672-5677 | `sqlite/search.rs` | static helper |
|
||||||
|
| `fn embedding_vector_for_active_model` | 5678-5697 | `sqlite/search.rs` | static helper |
|
||||||
|
| `fn active_embedding_model_like_pattern` | 5698-5713 | `sqlite/search.rs` | static helper |
|
||||||
|
|
||||||
|
### Scheduling: FSRS, decay, consolidation, review, promote/demote, suppression, gc, retention (-> `sqlite/scheduling.rs`)
|
||||||
|
|
||||||
|
This is the busiest destination file. The grouping rule is: anything that
|
||||||
|
touches FSRS scheduling fields (`stability`, `difficulty`, `retrievability`,
|
||||||
|
`reps`, `lapses`, `retention_strength`, `retrieval_strength`) or the
|
||||||
|
review/decay/consolidation/gc lifecycle lives here.
|
||||||
|
|
||||||
|
| Item | Lines | Destination | Notes |
|
||||||
|
|------|-------|-------------|-------|
|
||||||
|
| `pub fn mark_reviewed` | 1181-1275 | `sqlite/scheduling.rs` | FSRS state mutation |
|
||||||
|
| `pub fn strengthen_on_access` | 1276-1344 | `sqlite/scheduling.rs` | |
|
||||||
|
| `pub fn strengthen_batch_on_access` | 1345-1357 | `sqlite/scheduling.rs` | |
|
||||||
|
| `pub fn mark_memory_useful` | 1358-1377 | `sqlite/scheduling.rs` | |
|
||||||
|
| `fn log_access` | 1378-1393 | `sqlite/scheduling.rs` | private |
|
||||||
|
| `pub fn promote_memory` | 1394-1425 | `sqlite/scheduling.rs` | |
|
||||||
|
| `pub fn demote_memory` | 1426-1472 | `sqlite/scheduling.rs` | |
|
||||||
|
| `pub fn suppress_memory` | 1473-1504 | `sqlite/scheduling.rs` | active forgetting |
|
||||||
|
| `pub fn reverse_suppression` | 1505-1552 | `sqlite/scheduling.rs` | |
|
||||||
|
| `pub fn count_suppressed` | 1553-1567 | `sqlite/scheduling.rs` | |
|
||||||
|
| `pub fn get_recently_suppressed` | 1568-1594 | `sqlite/scheduling.rs` | |
|
||||||
|
| `pub fn apply_rac1_cascade` | 1595-1641 | `sqlite/scheduling.rs` | active forgetting cascade |
|
||||||
|
| `pub fn run_rac1_cascade_sweep` | 1642-1657 | `sqlite/scheduling.rs` | |
|
||||||
|
| `pub fn get_review_queue` | 1658-1681 | `sqlite/scheduling.rs` | |
|
||||||
|
| `pub fn preview_review` | 1682-1712 | `sqlite/scheduling.rs` | |
|
||||||
|
| `pub fn get_stats` | 1713-1841 | `sqlite/scheduling.rs` | reports retention/lapses/review counts; lives here for symmetry with the FSRS reporters next door |
|
||||||
|
| `pub fn apply_decay` | 3006-3095 | `sqlite/scheduling.rs` | core decay loop |
|
||||||
|
| `fn get_fsrs_w20` | 3096-3119 | `sqlite/scheduling.rs` | |
|
||||||
|
| `pub fn run_consolidation` | 3120-3407 | `sqlite/scheduling.rs` | |
|
||||||
|
| `fn auto_dedup_consolidation` | 3408-3538 | `sqlite/scheduling.rs` | called by run_consolidation |
|
||||||
|
| `fn compute_act_r_activations` | 3539-3605 | `sqlite/scheduling.rs` | called by run_consolidation |
|
||||||
|
| `fn prune_access_log` | 3606-3620 | `sqlite/scheduling.rs` | called by run_consolidation |
|
||||||
|
| `fn optimize_w20_if_ready` | 3621-3720 | `sqlite/scheduling.rs` | called by run_consolidation |
|
||||||
|
| `fn generate_missing_embeddings` | 3721-3740 | `sqlite/scheduling.rs` | called by run_consolidation |
|
||||||
|
| `pub fn get_state_transitions` | 5714-5748 | `sqlite/scheduling.rs` | audit trail tied to scheduling state |
|
||||||
|
| `pub fn get_avg_retention` | 5780-5792 | `sqlite/scheduling.rs` | |
|
||||||
|
| `pub fn get_retention_distribution` | 5794-5825 | `sqlite/scheduling.rs` | |
|
||||||
|
| `pub fn get_retention_trend` | 5826-5858 | `sqlite/scheduling.rs` | |
|
||||||
|
| `pub fn save_retention_snapshot` | 5859-5878 | `sqlite/scheduling.rs` | |
|
||||||
|
| `pub fn count_memories_below_retention` | 5879-5892 | `sqlite/scheduling.rs` | |
|
||||||
|
| `pub fn gc_below_retention` | 5893-5936 | `sqlite/scheduling.rs` | |
|
||||||
|
| `pub fn auto_promote_frequent_access` | 5937-5985 | `sqlite/scheduling.rs` | |
|
||||||
|
| `pub fn set_waking_tag` | 5986-5998 | `sqlite/scheduling.rs` | waking SWR tagging |
|
||||||
|
| `pub fn clear_waking_tags` | 5999-6011 | `sqlite/scheduling.rs` | |
|
||||||
|
| `pub fn get_waking_tagged_memories` | 6012-6028 | `sqlite/scheduling.rs` | |
|
||||||
|
| `pub fn get_recent_state_transitions` | 6105-6132 | `sqlite/scheduling.rs` | |
|
||||||
|
|
||||||
|
### Graph: edges (memory_connections), neighbors, subgraph (-> `sqlite/graph.rs`)
|
||||||
|
|
||||||
|
| Item | Lines | Destination | Notes |
|
||||||
|
|------|-------|-------------|-------|
|
||||||
|
| `pub fn save_connection` | 4180-4202 | `sqlite/graph.rs` | |
|
||||||
|
| `pub fn get_connections_for_memory` | 4203-4220 | `sqlite/graph.rs` | |
|
||||||
|
| `pub fn get_all_connections` | 4221-4236 | `sqlite/graph.rs` | |
|
||||||
|
| `pub fn strengthen_connection` | 4237-4259 | `sqlite/graph.rs` | |
|
||||||
|
| `pub fn apply_connection_decay` | 4260-4272 | `sqlite/graph.rs` | |
|
||||||
|
| `pub fn prune_weak_connections` | 4273-4284 | `sqlite/graph.rs` | |
|
||||||
|
| `fn row_to_connection` | 4285-4305 | `sqlite/graph.rs` | private |
|
||||||
|
| `pub fn get_most_connected_memory` | 6029-6046 | `sqlite/graph.rs` | |
|
||||||
|
| `pub fn get_memory_subgraph` | 6048-6103 | `sqlite/graph.rs` | calls `get_connections_for_memory`, `get_node`, `get_all_connections` -- all resolvable through `self` |
|
||||||
|
|
||||||
|
### Domain (-> `sqlite/domain.rs`)
|
||||||
|
|
||||||
|
Phase 1 keeps domain logic to JSON-column reads + classify stub. Phase 4
|
||||||
|
expands this file. Keeping the file in the split so Phase 4 has an
|
||||||
|
obvious place to add to.
|
||||||
|
|
||||||
|
| Item | Lines | Destination | Notes |
|
||||||
|
|------|-------|-------------|-------|
|
||||||
|
| `fn read_domain_columns` | 6167-6196 | `sqlite/domain.rs` | private helper used by trait `get`. Bump to `pub(super)` |
|
||||||
|
|
||||||
|
The trait methods `list_domains` / `get_domain` / `upsert_domain` /
|
||||||
|
`delete_domain` / `classify` live in `sqlite/trait_impl.rs`; they
|
||||||
|
delegate to thin helpers that, in Phase 1, are essentially noops or
|
||||||
|
JSON reads. Phase 4 will move the substance of those methods into
|
||||||
|
`sqlite/domain.rs` as real functions.
|
||||||
|
|
||||||
|
### Registry: embedding_model table (-> `sqlite/registry.rs`)
|
||||||
|
|
||||||
|
| Item | Lines | Destination | Notes |
|
||||||
|
|------|-------|-------------|-------|
|
||||||
|
| `fn enforce_model` | 6203-6272 | `sqlite/registry.rs` | private helper used by trait `insert` and `update`. Bump to `pub(super)` |
|
||||||
|
|
||||||
|
The trait methods `registered_model` and `register_model` themselves
|
||||||
|
live in `sqlite/trait_impl.rs`. Phase 2's `postgres/registry.rs` will
|
||||||
|
mirror this layout.
|
||||||
|
|
||||||
|
### Intentions, Insights, Memory States, Consolidation History, Dream History, Backup (-> `sqlite/mod.rs`)
|
||||||
|
|
||||||
|
These were tacked onto `SqliteMemoryStore` over time as the cognitive
|
||||||
|
modules needed somewhere to persist their state. They are not part of the
|
||||||
|
trait surface, they are not naturally grouped with crud/search/scheduling,
|
||||||
|
and they are each fairly small and self-contained. They live in `mod.rs`
|
||||||
|
under labelled sections (one big impl block can carry them) rather than
|
||||||
|
inventing extra files like `intentions.rs` and `insights.rs`. Postgres
|
||||||
|
will mirror this once Phase 5 picks up the work; for now they have no
|
||||||
|
peer.
|
||||||
|
|
||||||
|
Rationale: every one of these methods writes to a single table, the
|
||||||
|
bodies are short, and grouping them next to the constructor preserves
|
||||||
|
"open `mod.rs` to see the whole struct" as the navigation default.
|
||||||
|
|
||||||
|
| Item | Lines | Destination | Notes |
|
||||||
|
|------|-------|-------------|-------|
|
||||||
|
| `IntentionRecord` struct | 3747-3766 | `sqlite/mod.rs` | re-exported through `storage/mod.rs` |
|
||||||
|
| `InsightRecord` struct + `Default` | 3767-3797 | `sqlite/mod.rs` | re-exported |
|
||||||
|
| `ConnectionRecord` struct | 3799-3809 | `sqlite/mod.rs` | re-exported; consumed by `graph.rs` |
|
||||||
|
| `MemoryStateRecord` struct | 3811-3821 | `sqlite/mod.rs` | |
|
||||||
|
| `StateTransitionRecord` struct | 3823-3833 | `sqlite/mod.rs` | re-exported |
|
||||||
|
| `ConsolidationHistoryRecord` struct | 3835-3846 | `sqlite/mod.rs` | |
|
||||||
|
| `DreamHistoryRecord` struct | 3848-3866 | `sqlite/mod.rs` | re-exported |
|
||||||
|
| `pub fn save_intention` etc. (intention block) | 3874-4058 | `sqlite/mod.rs` | one impl block, in-section labelled |
|
||||||
|
| `fn row_to_intention` | 4023-4058 | `sqlite/mod.rs` | private |
|
||||||
|
| insights block (`save_insight`, `get_insights`, etc.) | 4065-4174 | `sqlite/mod.rs` | |
|
||||||
|
| `fn row_to_insight` | 4153-4173 | `sqlite/mod.rs` | private |
|
||||||
|
| memory-state block | 4306-4459 | `sqlite/mod.rs` | |
|
||||||
|
| `fn row_to_memory_state` | 4431-4459 | `sqlite/mod.rs` | private |
|
||||||
|
| consolidation-history block | 4465-4540 | `sqlite/mod.rs` | |
|
||||||
|
| dream-history block | 4546-4638 | `sqlite/mod.rs` | |
|
||||||
|
| `pub fn count_memories_since` | 4639-4651 | `sqlite/mod.rs` | |
|
||||||
|
| `fn scan_last_backup_timestamp` | 4652-4682 | `sqlite/mod.rs` | |
|
||||||
|
| `pub fn last_backup_timestamp` | 4683-4688 | `sqlite/mod.rs` | |
|
||||||
|
| `pub fn get_last_backup_timestamp` (associated) | 4689-4696 | `sqlite/mod.rs` | |
|
||||||
|
| `pub fn backup_to` | 5749-5774 | `sqlite/mod.rs` | sqlite VACUUM INTO; called by backup tool |
|
||||||
|
|
||||||
|
### Portable export/import/sync (-> `sqlite/portable_sync.rs`)
|
||||||
|
|
||||||
|
This is the second-largest destination after `scheduling.rs` and the most
|
||||||
|
self-contained.
|
||||||
|
|
||||||
|
| Item | Lines | Destination | Notes |
|
||||||
|
|------|-------|-------------|-------|
|
||||||
|
| `pub fn export_portable_archive` | 4699-4755 | `sqlite/portable_sync.rs` | |
|
||||||
|
| `pub fn export_portable_archive_to_path` | 4756-4806 | `sqlite/portable_sync.rs` | |
|
||||||
|
| `pub fn import_portable_archive` | 4807-4978 | `sqlite/portable_sync.rs` | |
|
||||||
|
| `pub fn import_portable_archive_from_path` | 4979-4996 | `sqlite/portable_sync.rs` | |
|
||||||
|
| `pub fn sync_portable_archive` (generic over backend) | 4997-5025 | `sqlite/portable_sync.rs` | |
|
||||||
|
| `pub fn sync_portable_archive_file` | 5026-5030 | `sqlite/portable_sync.rs` | |
|
||||||
|
| `fn merge_portable_table` | 5031-5073 | `sqlite/portable_sync.rs` | |
|
||||||
|
| `fn merge_knowledge_nodes` | 5074-5126 | `sqlite/portable_sync.rs` | |
|
||||||
|
| `fn merge_sync_tombstones` | 5127-5204 | `sqlite/portable_sync.rs` | |
|
||||||
|
| `fn merge_deletion_tombstones` | 5205-5245 | `sqlite/portable_sync.rs` | |
|
||||||
|
| `fn merge_keyed_table` | 5246-5281 | `sqlite/portable_sync.rs` | |
|
||||||
|
| `fn row_references_locally_newer_node` | 5282-5302 | `sqlite/portable_sync.rs` | |
|
||||||
|
| `fn merge_append_only_table` | 5303-5338 | `sqlite/portable_sync.rs` | |
|
||||||
|
| `fn parent_rows_exist` | 5339-5370 | `sqlite/portable_sync.rs` | |
|
||||||
|
| `fn insert_or_replace_row` | 5371-5386 | `sqlite/portable_sync.rs` | |
|
||||||
|
| `fn merge_key_columns` | 5387-5398 | `sqlite/portable_sync.rs` | |
|
||||||
|
| `fn upsert_row_with_columns` | 5399-5446 | `sqlite/portable_sync.rs` | |
|
||||||
|
| `fn insert_row_with_columns` | 5447-5469 | `sqlite/portable_sync.rs` | |
|
||||||
|
| `fn merge_row_exists` | 5470-5487 | `sqlite/portable_sync.rs` | |
|
||||||
|
| `fn row_exists_by_values` | 5488-5507 | `sqlite/portable_sync.rs` | |
|
||||||
|
| `fn row_values_for_columns` | 5508-5528 | `sqlite/portable_sync.rs` | |
|
||||||
|
| `fn portable_value` | 5529-5540 | `sqlite/portable_sync.rs` | |
|
||||||
|
| `fn portable_text` | 5541-5551 | `sqlite/portable_sync.rs` | |
|
||||||
|
| `fn portable_timestamp` | 5552-5559 | `sqlite/portable_sync.rs` | |
|
||||||
|
| `fn parse_rfc3339_opt` | 5560-5565 | `sqlite/portable_sync.rs` | |
|
||||||
|
| `fn tombstone_timestamp` | 5566-5580 | `sqlite/portable_sync.rs` | |
|
||||||
|
| `fn current_schema_version` | 5581-5589 | `sqlite/portable_sync.rs` | static helper |
|
||||||
|
| `fn ensure_portable_import_target_empty` | 5590-5604 | `sqlite/portable_sync.rs` | static helper |
|
||||||
|
| `fn table_exists` | 5605-5613 | `sqlite/portable_sync.rs` | static helper |
|
||||||
|
| `fn table_row_count` | 5614-5618 | `sqlite/portable_sync.rs` | static helper |
|
||||||
|
| `fn table_columns` | 5619-5630 | `sqlite/portable_sync.rs` | static helper |
|
||||||
|
| `fn portable_value_from_ref` | 5631-5646 | `sqlite/portable_sync.rs` | static helper |
|
||||||
|
| `fn quote_ident` | 5647-5651 | `sqlite/portable_sync.rs` | static helper |
|
||||||
|
|
||||||
|
### Trait helpers and trait impl (-> `sqlite/trait_impl.rs`)
|
||||||
|
|
||||||
|
| Item | Lines | Destination | Notes |
|
||||||
|
|------|-------|-------------|-------|
|
||||||
|
| `fn node_to_record` | 6142-6164 | `sqlite/trait_impl.rs` | associated fn used only by trait body; co-locate |
|
||||||
|
| `impl LocalMemoryStore for SqliteMemoryStore` block | 6274-7110 | `sqlite/trait_impl.rs` | full trait impl; attribute changes from `#[async_trait::async_trait]` to whatever 0001a settles on (`#[trait_variant::make(...)]` is on the trait declaration; the impl block carries no attribute under trait_variant) |
|
||||||
|
|
||||||
|
### Tests
|
||||||
|
|
||||||
|
The current `#[cfg(test)] mod tests` block at lines 7112-8713 contains
|
||||||
|
**two** distinct test families:
|
||||||
|
|
||||||
|
1. **Native API tests** (7120-8198): unit tests against the legacy
|
||||||
|
`pub fn` surface (`test_ingest_and_get`, `test_search`, `test_review`,
|
||||||
|
`test_delete`, `test_dream_history_save_and_get_last`,
|
||||||
|
`test_portable_archive_exact_round_trip`, `test_keyword_search_*`,
|
||||||
|
`test_concrete_search_*`, `test_purge_*`, etc.).
|
||||||
|
2. **Trait round-trip tests** (8200-8712, after the
|
||||||
|
`// ===== Phase 1: LocalMemoryStore trait round-trip tests =====`
|
||||||
|
banner): `trait_init_is_idempotent`, `trait_register_model_*`,
|
||||||
|
`trait_insert_*`, `trait_get_*`, `trait_update_*`, `trait_delete_*`,
|
||||||
|
`trait_fts_search_*`, `trait_hybrid_search_*`,
|
||||||
|
`trait_scheduling_*`, `trait_add_edge_*`, `trait_get_edges_*`,
|
||||||
|
`trait_remove_edge_*`, `trait_get_neighbors_*`, `trait_list_domains_*`,
|
||||||
|
`trait_upsert_*`, `trait_classify_*`, `trait_count_*`,
|
||||||
|
`trait_get_stats_*`, `trait_vacuum_*`,
|
||||||
|
`trait_insert_refuses_dimension_mismatch`.
|
||||||
|
|
||||||
|
See the Test Relocation section below for the resolution.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Visibility Changes
|
||||||
|
|
||||||
|
The split moves items into sibling files inside one module. Helpers that
|
||||||
|
were `fn ...` (i.e. crate-private but file-private under the current
|
||||||
|
layout, since the file *is* the module) need their visibility lifted
|
||||||
|
just enough that sibling files can call them. The principle is: smallest
|
||||||
|
bump that makes the call site compile.
|
||||||
|
|
||||||
|
`pub(super)` is sufficient for everything below; nothing needs
|
||||||
|
`pub(crate)`. The trait `LocalMemoryStore` exposure does not change --
|
||||||
|
sub-modules call `self.method(...)` on `SqliteMemoryStore`, which
|
||||||
|
resolves through the impl blocks defined in their own files; visibility
|
||||||
|
is automatic at impl-block scope.
|
||||||
|
|
||||||
|
Items that need a visibility bump (currently private fn, become
|
||||||
|
`pub(super) fn`):
|
||||||
|
|
||||||
|
- `parse_timestamp` (1012): called by `row_to_node` and by intention /
|
||||||
|
insight row mappers.
|
||||||
|
- `row_to_node` (1028): called by `crud.rs`, `search.rs`,
|
||||||
|
`scheduling.rs`. Static associated fn.
|
||||||
|
- `read_domain_columns` (6167): called by `trait_impl.rs`.
|
||||||
|
- `enforce_model` (6203): called by `trait_impl.rs`.
|
||||||
|
- `embedding_model_matches_active` (5652): currently called by
|
||||||
|
`hybrid_search_filtered`; tests also reference it. Has to remain
|
||||||
|
`pub(super) fn` and be `pub` only if the existing test names reach it
|
||||||
|
through a re-export. (See Test Relocation.)
|
||||||
|
- `embedding_model_supports_matryoshka` (5672): private; only callers in
|
||||||
|
`search.rs` after the move; stays `fn` (no bump needed).
|
||||||
|
- `embedding_vector_for_active_model` (5678): same as the matches
|
||||||
|
function -- a test references it. Bump to `pub(super)`.
|
||||||
|
- `active_embedding_model_like_pattern` (5698): private; only used by
|
||||||
|
search; stays `fn`.
|
||||||
|
- `generate_embedding_for_node` (952): currently called by `ingest` and
|
||||||
|
`update_node_content`. Both move to `crud.rs`; stays `fn`.
|
||||||
|
- `get_query_embedding` (2368): only used inside `search.rs`; stays `fn`.
|
||||||
|
- `keyword_search_with_scores` (2636): only used inside `search.rs`;
|
||||||
|
stays `fn`.
|
||||||
|
- `semantic_search_raw` (2727): only used inside `search.rs`; stays `fn`.
|
||||||
|
- `embedding_regeneration_candidates` (2820): used by
|
||||||
|
`generate_embeddings`; both move to `search.rs`; stays `fn`. The
|
||||||
|
existing test (line 7167) references it through `storage.method()`,
|
||||||
|
which will continue to work because the test file can move with it.
|
||||||
|
- `log_access` (1378): private to `scheduling.rs`; stays `fn`.
|
||||||
|
- All the `auto_dedup_consolidation` / `compute_act_r_activations` /
|
||||||
|
`prune_access_log` / `optimize_w20_if_ready` /
|
||||||
|
`generate_missing_embeddings` helpers (3408-3740): private to
|
||||||
|
`scheduling.rs`; stays `fn`.
|
||||||
|
- `row_to_intention` / `row_to_insight` / `row_to_memory_state` /
|
||||||
|
`row_to_connection`: all stay private in their destination file (only
|
||||||
|
one caller each).
|
||||||
|
- All `merge_*` / `portable_*` / `parse_rfc3339_opt` / `quote_ident`:
|
||||||
|
private to `portable_sync.rs`; stays `fn`.
|
||||||
|
- `node_exists` (1988): private to `crud.rs`; stays `fn`.
|
||||||
|
- `record_sync_tombstone` (1997): private to `crud.rs`; stays `fn`.
|
||||||
|
- `get_fsrs_w20` (3096): private to `scheduling.rs`; stays `fn`.
|
||||||
|
|
||||||
|
Items already `pub fn` (or `pub(crate) fn`) stay as they are -- no
|
||||||
|
visibility regression.
|
||||||
|
|
||||||
|
Field visibility on `SqliteMemoryStore` itself: currently all fields are
|
||||||
|
private. The sub-modules access them via `self.field`. Because impl
|
||||||
|
blocks for `SqliteMemoryStore` are written in sibling files of the same
|
||||||
|
module, `self.field` reaches private fields without a visibility bump.
|
||||||
|
**No field visibility changes are required.** Confirm this during the
|
||||||
|
first motion commit; if Rust disagrees, mark the relevant fields
|
||||||
|
`pub(super)` and document in the commit message.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Public Re-exports
|
||||||
|
|
||||||
|
`crates/vestige-core/src/storage/mod.rs` currently exports:
|
||||||
|
|
||||||
|
```rust
|
||||||
|
mod memory_store;
|
||||||
|
mod migrations;
|
||||||
|
mod portable;
|
||||||
|
mod sqlite;
|
||||||
|
|
||||||
|
pub use memory_store::{...};
|
||||||
|
pub use migrations::MIGRATIONS;
|
||||||
|
pub use portable::{...};
|
||||||
|
pub use sqlite::{
|
||||||
|
ConnectionRecord, ConsolidationHistoryRecord, DreamHistoryRecord, FilePortableSyncBackend,
|
||||||
|
InsightRecord, IntentionRecord, PortableSyncBackend, PortableSyncReport, Result,
|
||||||
|
SmartIngestResult, SqliteMemoryStore, StateTransitionRecord, StorageError,
|
||||||
|
};
|
||||||
|
|
||||||
|
pub type Storage = SqliteMemoryStore;
|
||||||
|
```
|
||||||
|
|
||||||
|
After the split, `mod sqlite;` resolves to the new directory module
|
||||||
|
(`storage/sqlite/mod.rs`). The `pub use sqlite::{...}` block resolves
|
||||||
|
against the items re-exported by `storage/sqlite/mod.rs`.
|
||||||
|
|
||||||
|
`storage/sqlite/mod.rs` therefore needs the same names visible at its
|
||||||
|
top level. Add at the end of `mod.rs`:
|
||||||
|
|
||||||
|
```rust
|
||||||
|
mod crud;
|
||||||
|
mod search;
|
||||||
|
mod scheduling;
|
||||||
|
mod graph;
|
||||||
|
mod domain;
|
||||||
|
mod registry;
|
||||||
|
mod portable_sync;
|
||||||
|
mod trait_impl;
|
||||||
|
|
||||||
|
pub use portable_sync::{FilePortableSyncBackend, PortableSyncBackend, PortableSyncReport};
|
||||||
|
// SqliteMemoryStore, StorageError, Result, SmartIngestResult, IntentionRecord,
|
||||||
|
// InsightRecord, ConnectionRecord, StateTransitionRecord,
|
||||||
|
// ConsolidationHistoryRecord, DreamHistoryRecord are defined in mod.rs itself,
|
||||||
|
// so they are already in scope and do not need a re-export.
|
||||||
|
```
|
||||||
|
|
||||||
|
The `crates/vestige-core/src/storage/mod.rs` file does not change. The
|
||||||
|
`pub type Storage = SqliteMemoryStore;` alias keeps working.
|
||||||
|
|
||||||
|
If `cargo build` complains that `storage/mod.rs` cannot resolve a name
|
||||||
|
in its `pub use sqlite::{...}` block, the fix is to add the missing name
|
||||||
|
to `sqlite/mod.rs`'s re-export tail; no change to `storage/mod.rs`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Test Relocation
|
||||||
|
|
||||||
|
Two test families, two destinations.
|
||||||
|
|
||||||
|
**Native API tests** (current lines 7120-8198) cover the legacy `pub fn`
|
||||||
|
surface. They live close to their subject:
|
||||||
|
|
||||||
|
- Tests that touch the constructor, common helpers, and shared setup
|
||||||
|
(`create_test_storage`, `create_test_storage_at`,
|
||||||
|
`test_storage_creation`, `test_get_last_backup_timestamp_no_panic`)
|
||||||
|
move to `sqlite/mod.rs` in a `#[cfg(test)] mod tests` block.
|
||||||
|
- `test_ingest_and_get`, `test_delete`,
|
||||||
|
`test_purge_scrubs_insight_json_orphans_children_and_writes_tombstone`
|
||||||
|
go to `sqlite/crud.rs` as a `#[cfg(test)] mod tests` block.
|
||||||
|
- `test_search`, `test_keyword_search_with_include_types`,
|
||||||
|
`test_keyword_search_with_exclude_types`,
|
||||||
|
`test_include_types_takes_precedence_over_exclude`,
|
||||||
|
`test_type_filter_with_no_matches_returns_empty`,
|
||||||
|
`test_hybrid_search_backward_compat`,
|
||||||
|
`test_concrete_search_literal_identifier_lands_first`,
|
||||||
|
`test_embedding_model_family_matching`,
|
||||||
|
`test_embedding_regeneration_candidates_include_entire_mismatched_corpus`
|
||||||
|
go to `sqlite/search.rs`.
|
||||||
|
- `test_review` goes to `sqlite/scheduling.rs`.
|
||||||
|
- `test_dream_history_save_and_get_last`, `test_dream_history_empty`,
|
||||||
|
`test_count_memories_since` go to `sqlite/mod.rs` (history tables live
|
||||||
|
there).
|
||||||
|
- All `test_portable_*` go to `sqlite/portable_sync.rs`.
|
||||||
|
- `test_file_portable_sync_round_trips_between_devices` goes to
|
||||||
|
`sqlite/portable_sync.rs`.
|
||||||
|
|
||||||
|
**Trait round-trip tests** (current lines 8200-8712) test the
|
||||||
|
`LocalMemoryStore` trait impl. Two viable layouts:
|
||||||
|
|
||||||
|
A. Co-locate with the impl in `sqlite/trait_impl.rs` (one big
|
||||||
|
`#[cfg(test)] mod trait_tests`).
|
||||||
|
B. Keep them as a single `tests.rs` file in the sqlite directory.
|
||||||
|
|
||||||
|
**Decision: A.** Co-locate. The trait round-trip tests are explicitly
|
||||||
|
testing the `impl LocalMemoryStore for SqliteMemoryStore` block;
|
||||||
|
co-location means a reader who edits the trait impl sees its tests in
|
||||||
|
the same file. Option B would mean two places to look every time a
|
||||||
|
trait method changes shape. For an 8K-line collapse the tradeoff
|
||||||
|
favours co-location.
|
||||||
|
|
||||||
|
Concretely: `sqlite/trait_impl.rs` ends with a
|
||||||
|
`#[cfg(test)] mod trait_tests { ... }` block that contains all 30+
|
||||||
|
`trait_*` tests, plus the shared `make_record`, `rt`, and small helpers
|
||||||
|
defined inside the current test mod for trait tests (lines 8208-8226).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Commit Sequence
|
||||||
|
|
||||||
|
Each commit moves one logical group. After each commit:
|
||||||
|
|
||||||
|
```
|
||||||
|
cargo build -p vestige-core
|
||||||
|
cargo test -p vestige-core
|
||||||
|
cargo clippy -p vestige-core -- -D warnings
|
||||||
|
```
|
||||||
|
|
||||||
|
must pass. Order is chosen so that each move is small, the next move
|
||||||
|
does not depend on the previous having grown surprising visibility, and
|
||||||
|
the largest / riskiest move (the trait impl, with the new
|
||||||
|
trait_variant attribute) lands last.
|
||||||
|
|
||||||
|
| # | Commit | What moves | Tests touched |
|
||||||
|
|---|--------|-----------|----------------|
|
||||||
|
| 1 | `refactor(sqlite): scaffold sqlite/ directory` | Convert `sqlite.rs` -> `sqlite/mod.rs` verbatim (rename + create empty sibling files `crud.rs`, `search.rs`, `scheduling.rs`, `graph.rs`, `domain.rs`, `registry.rs`, `portable_sync.rs`, `trait_impl.rs` each with `use super::*;`). At this point `mod.rs` declares the new modules but they are empty. | None move. Build proves the rename works. |
|
||||||
|
| 2 | `refactor(sqlite): split out portable sync` | Move all `merge_*`, `portable_*`, `export_*`, `import_*`, `sync_*` items + `MergeWrite`, `PortableSyncBackend`, `FilePortableSyncBackend`, `PortableSyncReport`, `PortableMergeState`, `PORTABLE_TABLES`, `PORTABLE_USER_DATA_TABLES`, helper statics into `sqlite/portable_sync.rs`. Add `pub use portable_sync::{...}` in `mod.rs` for the public types. | `test_portable_*` and `test_file_portable_sync_round_trips_between_devices` move too. |
|
||||||
|
| 3 | `refactor(sqlite): split out graph / connections` | Move `save_connection`, `get_connections_for_memory`, `get_all_connections`, `strengthen_connection`, `apply_connection_decay`, `prune_weak_connections`, `row_to_connection`, `get_most_connected_memory`, `get_memory_subgraph` to `sqlite/graph.rs`. | None move (no native graph tests; trait edge tests still in trait_tests). |
|
||||||
|
| 4 | `refactor(sqlite): split out scheduling / fsrs / consolidation` | Move all items listed in the Scheduling row to `sqlite/scheduling.rs`. | `test_review` moves. |
|
||||||
|
| 5 | `refactor(sqlite): split out search / fts / semantic / hybrid` | Move all items listed in the Search row to `sqlite/search.rs`. Add `pub(super)` to the four `embedding_model_*` helpers that tests reference. | `test_search`, `test_keyword_search_*`, `test_include_types_*`, `test_type_filter_*`, `test_hybrid_search_*`, `test_concrete_search_*`, `test_embedding_model_family_matching`, `test_embedding_regeneration_candidates_include_entire_mismatched_corpus` move. |
|
||||||
|
| 6 | `refactor(sqlite): split out crud / ingest / get / update / delete / purge` | Move `ingest`, `smart_ingest`, `get_node`, `update_node_content`, `delete_node`, `purge_node`, `get_all_nodes`, `get_nodes_by_type_and_tag`, `node_exists`, `record_sync_tombstone`, `generate_embedding_for_node`, `get_node_embedding`, `get_all_embeddings`, `PurgeReport` to `sqlite/crud.rs`. Bump `row_to_node` and `parse_timestamp` to `pub(super) fn` in `mod.rs`. | `test_ingest_and_get`, `test_delete`, `test_purge_scrubs_insight_json_orphans_children_and_writes_tombstone` move. |
|
||||||
|
| 7 | `refactor(sqlite): split out registry helper` | Move `enforce_model` to `sqlite/registry.rs`, bumped to `pub(super)`. | None move. |
|
||||||
|
| 8 | `refactor(sqlite): split out domain helper` | Move `read_domain_columns` to `sqlite/domain.rs`, bumped to `pub(super)`. | None move. |
|
||||||
|
| 9 | `refactor(sqlite): split out trait impl + tests` | Move `node_to_record` and the full `impl LocalMemoryStore for SqliteMemoryStore` block to `sqlite/trait_impl.rs`. Move the entire trait round-trip test module (lines 8200-8712, including `make_record` and `rt` helpers) to a `#[cfg(test)] mod trait_tests` block at the bottom of `trait_impl.rs`. This is the commit where the trait_variant attribute (from sub-plan 0001a) is observed: the impl block on `SqliteMemoryStore` uses whatever syntax the rewritten trait expects (no `#[async_trait::async_trait]`). | All `trait_*` tests move. |
|
||||||
|
|
||||||
|
Commit 1 is the only commit that creates new files; the rest move
|
||||||
|
existing code into them. Reviewers can bisect through this list to
|
||||||
|
find any silent-semantic change.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Verification
|
||||||
|
|
||||||
|
Run after every commit. All three must pass before pushing:
|
||||||
|
|
||||||
|
```
|
||||||
|
cargo build -p vestige-core
|
||||||
|
cargo test -p vestige-core
|
||||||
|
cargo clippy -p vestige-core -- -D warnings
|
||||||
|
```
|
||||||
|
|
||||||
|
The Phase 1 amendment branch must also build with the no-default-features
|
||||||
|
configuration that the release binary uses for the alternative feature
|
||||||
|
set:
|
||||||
|
|
||||||
|
```
|
||||||
|
cargo build -p vestige-core --no-default-features
|
||||||
|
cargo test -p vestige-core --no-default-features
|
||||||
|
```
|
||||||
|
|
||||||
|
Some of the methods being moved (`get_node_embedding`, `is_embedding_ready`,
|
||||||
|
`init_embeddings`, the feature-on/feature-off `hybrid_search` pair) have
|
||||||
|
two definitions guarded by feature flags. The split must preserve both
|
||||||
|
copies in the same destination file with their existing `#[cfg(...)]`
|
||||||
|
attributes; the no-default-features build confirms.
|
||||||
|
|
||||||
|
After the last commit, run the workspace-wide check that Phase 1 promised:
|
||||||
|
|
||||||
|
```
|
||||||
|
cargo build --workspace
|
||||||
|
cargo test --workspace
|
||||||
|
```
|
||||||
|
|
||||||
|
This catches downstream consumers (`vestige-mcp`, `vestige`,
|
||||||
|
`vestige-restore`) that might depend on a specific module path (they
|
||||||
|
should not -- they import from `crate::storage::SqliteMemoryStore` and
|
||||||
|
the re-exports in `storage/mod.rs` -- but the workspace build is the
|
||||||
|
authoritative confirmation).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Acceptance Criteria
|
||||||
|
|
||||||
|
1. `crates/vestige-core/src/storage/sqlite.rs` no longer exists. In its
|
||||||
|
place is `crates/vestige-core/src/storage/sqlite/` with the eight
|
||||||
|
files listed in the Target Layout section, each below 2000 lines.
|
||||||
|
2. `crates/vestige-core/src/storage/mod.rs` is unchanged (or
|
||||||
|
functionally unchanged -- the `pub use sqlite::{...}` block contains
|
||||||
|
the same identifiers in the same order).
|
||||||
|
3. Every cognitive module and binary in the workspace
|
||||||
|
(`vestige-core`, `vestige-mcp`, `vestige`, `vestige-restore`)
|
||||||
|
compiles with no source edits other than the ones in
|
||||||
|
`crates/vestige-core/src/storage/sqlite/`.
|
||||||
|
4. `cargo build -p vestige-core`,
|
||||||
|
`cargo test -p vestige-core`,
|
||||||
|
`cargo clippy -p vestige-core -- -D warnings`,
|
||||||
|
`cargo build -p vestige-core --no-default-features`, and
|
||||||
|
`cargo test -p vestige-core --no-default-features` all pass at the
|
||||||
|
end of every commit in the sequence (bisectability).
|
||||||
|
5. `cargo test --workspace` matches the Phase 1 baseline test count
|
||||||
|
(758 tests, of which 352 are in `vestige-core`). No new tests are
|
||||||
|
added by this sub-plan; no existing test is renamed or deleted.
|
||||||
|
6. The on-disk SQLite schema is unchanged. A live database created on
|
||||||
|
the pre-split build opens cleanly on the post-split build and round
|
||||||
|
trips a memory.
|
||||||
|
7. `git log --follow` works for at least one method in each destination
|
||||||
|
file (i.e. `git mv` was used where the line range constitutes most
|
||||||
|
of the file content of the destination, otherwise a `git log -p`
|
||||||
|
on the new file shows the history before the rename through the
|
||||||
|
block-move detection that recent `git log` versions support).
|
||||||
|
8. No public symbol disappears from `crate::storage::*`. A reviewer can
|
||||||
|
verify with:
|
||||||
|
```
|
||||||
|
cargo doc -p vestige-core --no-deps
|
||||||
|
```
|
||||||
|
before and after the split, and `diff` the generated
|
||||||
|
`target/doc/vestige_core/storage/index.html` lists.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Non-Goals (explicit)
|
||||||
|
|
||||||
|
- No public API change. The trait surface (`LocalMemoryStore`,
|
||||||
|
`MemoryStore`), the legacy `pub fn` surface on `SqliteMemoryStore`,
|
||||||
|
the re-exports through `storage/mod.rs`, and the `pub type Storage =
|
||||||
|
SqliteMemoryStore;` alias are all preserved.
|
||||||
|
- No behavioural change. No SQL is rewritten, no FSRS parameter is
|
||||||
|
retuned, no embedding model is touched, no migration is added.
|
||||||
|
- No new tests. Tests move with their subject; no new tests are
|
||||||
|
written.
|
||||||
|
- No clippy fix-ups that pre-date this sub-plan. If `cargo clippy
|
||||||
|
-- -D warnings` was passing before the split, it must continue to
|
||||||
|
pass; if it was not passing, the failures stay where they are and
|
||||||
|
are addressed in a separate commit (out of scope here).
|
||||||
|
- No removal of the `pub type Storage = SqliteMemoryStore;` BC alias.
|
||||||
|
That happens at the end of Phase 4 per ADR 0001.
|
||||||
|
- No reorganisation of `storage/memory_store.rs`,
|
||||||
|
`storage/migrations.rs`, or `storage/portable.rs`. Those files are
|
||||||
|
out of scope; the split is private to `storage/sqlite/`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Risks and Mitigations
|
||||||
|
|
||||||
|
| Risk | Mitigation |
|
||||||
|
|------|------------|
|
||||||
|
| Silent semantic change introduced by a motion commit | Per-commit `cargo test -p vestige-core` keeps the bisect window to a single commit. Reviewer bisects with `cargo test -p vestige-core` as the witness. |
|
||||||
|
| Sibling-file `self.field` accesses fail because Rust enforces module visibility on tuple-struct or named fields | Confirmed: associated impl blocks in sibling files of the same `mod sqlite` reach private fields. If the compiler disagrees, bump the affected fields to `pub(super)` in `mod.rs` and note the bump in the commit message. |
|
||||||
|
| Test-only helpers (`create_test_storage`, `make_record`, `rt`) get duplicated across test modules | Lift them once into a `#[cfg(test)] mod test_support { ... }` sub-module in `sqlite/mod.rs` and re-export with `pub(super) use`. Do this in commit 1 (scaffold), not later. |
|
||||||
|
| `#[cfg(all(feature = "embeddings", feature = "vector-search"))]` items end up in `mod.rs` where they pollute the shared layer | Audit during commit 5 (search split); items behind both feature flags belong in `search.rs`. The `query_cache` field stays in `mod.rs` because the struct definition is there; the field declaration is feature-gated and that gate moves with the struct as-is. |
|
||||||
|
| `git log --follow` blame chains break on the moved methods | Use `git mv sqlite.rs sqlite/mod.rs` in commit 1 so commit 1 looks like a rename (`git log --follow` keeps working). Subsequent commits are content moves inside the module; modern `git log --follow -M -C` heuristics still trace the lines. Reviewers who need pristine blame should bisect to before commit 1. |
|
||||||
|
| Sub-plan 0001a (trait rewrite) has not landed when this work starts | Block: do not start commits 1-9 until 0001a is on the same branch (`feat/storage-trait-phase1`) and tests pass. `trait_impl.rs` lands the new attribute in commit 9; if 0001a is not in, commit 9 fails. |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Self-Contained Brief (for /goal)
|
||||||
|
|
||||||
|
A fresh Claude Code session can execute this sub-plan by:
|
||||||
|
|
||||||
|
1. Reading this file end to end.
|
||||||
|
2. Reading `crates/vestige-core/src/storage/sqlite.rs` (the file to be
|
||||||
|
split) in full, using line ranges from the Mapping Table to confirm
|
||||||
|
the current shape matches the brief.
|
||||||
|
3. Reading `crates/vestige-core/src/storage/mod.rs` (the re-export
|
||||||
|
surface that must continue to work).
|
||||||
|
4. Reading `crates/vestige-core/src/storage/memory_store.rs` (the
|
||||||
|
trait surface that `trait_impl.rs` implements).
|
||||||
|
5. Confirming sub-plan 0001a has landed on the current branch by
|
||||||
|
checking that `memory_store.rs` no longer carries
|
||||||
|
`#[async_trait::async_trait]` on the trait declaration.
|
||||||
|
6. Working through the Commit Sequence in order, running the
|
||||||
|
Verification commands after each commit.
|
||||||
|
|
||||||
|
The session does not need to read ADR 0002 or the master Phase 2 plan
|
||||||
|
to do this work. The split is purely mechanical relative to the
|
||||||
|
mapping table above.
|
||||||
847
docs/plans/0001c-async-trait-sunset.md
Normal file
847
docs/plans/0001c-async-trait-sunset.md
Normal file
|
|
@ -0,0 +1,847 @@
|
||||||
|
# Sub-Plan 0001c: Sunset the `async-trait` crate dependency
|
||||||
|
|
||||||
|
**Status**: Draft
|
||||||
|
**Branch**: `feat/storage-trait-phase1` (Phase 1 amendment, PR A)
|
||||||
|
**Depends on**:
|
||||||
|
- `0001a-trait-rewrite.md` (rewrites `MemoryStore` / `LocalMemoryStore` and
|
||||||
|
the SQLite impl; lands first)
|
||||||
|
- `0001b-sqlite-split.md` (moves `sqlite.rs` into `sqlite/`; lands second)
|
||||||
|
|
||||||
|
**Related**: `docs/adr/0002-phase-2-execution.md` (decision D1 closing line:
|
||||||
|
"async-trait dependency stays in Cargo.toml only if other code uses it;
|
||||||
|
otherwise removed"). This sub-plan operationalises the removal.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Context
|
||||||
|
|
||||||
|
This is the third and final Phase 1 amendment sub-plan. Sub-plan `0001a`
|
||||||
|
rewrote `MemoryStore` / `LocalMemoryStore` using
|
||||||
|
`#[trait_variant::make(MemoryStore: Send)]` and dropped the
|
||||||
|
`#[async_trait::async_trait]` attribute from the SQLite impl block.
|
||||||
|
Sub-plan `0001b` then split `sqlite.rs` into a `sqlite/` directory; the
|
||||||
|
trait impl now lives in `sqlite/trait_impl.rs`. After `0001a` lands, the
|
||||||
|
only remaining `async_trait` usage in the workspace is the embedder pair
|
||||||
|
(`embedder/mod.rs` declares the trait; `embedder/fastembed.rs` implements
|
||||||
|
it). This sub-plan rewrites those two files following the exact pattern
|
||||||
|
from `0001a`, then removes `async-trait = "0.1"` from
|
||||||
|
`crates/vestige-core/Cargo.toml`. End state: zero `async_trait` references
|
||||||
|
anywhere under `crates/`, zero direct dependency on the `async-trait`
|
||||||
|
crate, workspace tests and clippy green.
|
||||||
|
|
||||||
|
The rewrite is mechanically tiny -- one trait declaration, one impl block,
|
||||||
|
one Cargo.toml line -- but it is gated behind `0001a` and `0001b` so the
|
||||||
|
trait-rewrite pattern is already settled and so the SQLite trait impl
|
||||||
|
attribute has already been dropped. Doing the embedder rewrite without
|
||||||
|
that pre-work would leave the `async-trait` dep behind for the SQLite
|
||||||
|
side and force the Cargo.toml deletion into a separate commit later.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Scope
|
||||||
|
|
||||||
|
### In scope
|
||||||
|
|
||||||
|
- Rewrite `LocalEmbedder` declaration in
|
||||||
|
`crates/vestige-core/src/embedder/mod.rs` to use
|
||||||
|
`#[trait_variant::make(Embedder: Send)] pub trait LocalEmbedder`.
|
||||||
|
- Delete the `pub use LocalEmbedder as Embedder;` alias from the same file.
|
||||||
|
The `Embedder` symbol becomes the trait that `trait_variant::make` emits
|
||||||
|
at the same module path, so the existing
|
||||||
|
`pub use embedder::{Embedder, ..., LocalEmbedder};` line in
|
||||||
|
`crates/vestige-core/src/lib.rs:167` keeps working untouched.
|
||||||
|
- Drop the `#[async_trait::async_trait]` attribute from the
|
||||||
|
`FastembedEmbedder` impl block in
|
||||||
|
`crates/vestige-core/src/embedder/fastembed.rs`.
|
||||||
|
- Update doc comments on the trait declaration to describe
|
||||||
|
`trait_variant` rather than `async_trait`.
|
||||||
|
- Remove `async-trait = "0.1"` from
|
||||||
|
`crates/vestige-core/Cargo.toml` (line 119 area). Use
|
||||||
|
`cargo rm async-trait` from inside the crate directory.
|
||||||
|
- Verify with `grep -rn "async_trait" crates/` returning zero hits.
|
||||||
|
|
||||||
|
### Out of scope
|
||||||
|
|
||||||
|
- Any change to the `MemoryStore` trait or `SqliteMemoryStore` impl;
|
||||||
|
those were handled by `0001a`.
|
||||||
|
- Any file moves in `embedder/` (no parallel of `0001b` is required;
|
||||||
|
`embedder/` already has the `mod.rs` + `fastembed.rs` shape).
|
||||||
|
- Touching `crates/vestige-mcp/` or any cognitive module. None of them
|
||||||
|
hold `Arc<dyn Embedder>` or `Box<dyn Embedder>` in production.
|
||||||
|
- Renaming the `Embedder` / `LocalEmbedder` symbols or changing the
|
||||||
|
re-exports in `crates/vestige-core/src/lib.rs`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Prerequisites
|
||||||
|
|
||||||
|
### State assumed at start
|
||||||
|
|
||||||
|
- `0001a` is merged onto the branch. After `0001a`:
|
||||||
|
- `crates/vestige-core/src/storage/memory_store.rs` declares
|
||||||
|
`#[trait_variant::make(MemoryStore: Send)] pub trait LocalMemoryStore`.
|
||||||
|
- The SQLite impl block has no `#[async_trait::async_trait]` attribute.
|
||||||
|
- `grep -rn async_trait crates/` returns exactly three hits, all in
|
||||||
|
`crates/vestige-core/src/embedder/` (two in `mod.rs`, one in
|
||||||
|
`fastembed.rs`), and one Cargo.toml hit.
|
||||||
|
- `0001b` is merged onto the branch. After `0001b`:
|
||||||
|
- `crates/vestige-core/src/storage/sqlite.rs` no longer exists as a
|
||||||
|
single file; the impl lives in `crates/vestige-core/src/storage/sqlite/trait_impl.rs`.
|
||||||
|
- The embedder files are untouched.
|
||||||
|
|
||||||
|
### Required crates
|
||||||
|
|
||||||
|
| Crate | Version | Action |
|
||||||
|
|----------------|---------|-----------------------------------------------------------------|
|
||||||
|
| `trait-variant`| `0.1` | Already declared (line 117 of Cargo.toml). Verify present. |
|
||||||
|
| `async-trait` | `0.1` | Remove. Only the two embedder files still use it after `0001a`. |
|
||||||
|
|
||||||
|
### Workspace-wide audit before starting
|
||||||
|
|
||||||
|
Run from `/home/delandtj/prppl/vestige-phase2/` (or the equivalent
|
||||||
|
worktree where this sub-plan executes):
|
||||||
|
|
||||||
|
```bash
|
||||||
|
grep -rn "async_trait\|async-trait" crates/ tests/
|
||||||
|
```
|
||||||
|
|
||||||
|
Expected hits before this sub-plan starts (after `0001a` + `0001b`):
|
||||||
|
|
||||||
|
```
|
||||||
|
crates/vestige-core/Cargo.toml:119:async-trait = "0.1"
|
||||||
|
crates/vestige-core/src/embedder/mod.rs:24:/// `#[async_trait::async_trait]` makes every `async fn` return a
|
||||||
|
crates/vestige-core/src/embedder/mod.rs:27:#[async_trait::async_trait]
|
||||||
|
crates/vestige-core/src/embedder/mod.rs:56:/// Both names refer to the same `async_trait`-annotated trait.
|
||||||
|
crates/vestige-core/src/embedder/fastembed.rs:44:#[async_trait::async_trait]
|
||||||
|
```
|
||||||
|
|
||||||
|
Five hits across two source files and one Cargo.toml. After this sub-plan,
|
||||||
|
the same grep must return zero hits.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
grep -rn "async-trait\|async_trait" --include="Cargo.toml" crates/
|
||||||
|
```
|
||||||
|
|
||||||
|
Expected: exactly one hit (`crates/vestige-core/Cargo.toml:119`). No other
|
||||||
|
workspace crate declares `async-trait` as a direct dependency. This is
|
||||||
|
the precondition that lets us delete the line cleanly.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Files Touched
|
||||||
|
|
||||||
|
### Trait declaration (vestige-core)
|
||||||
|
|
||||||
|
| File | Lines (approx) | Change |
|
||||||
|
|-------------------------------------------------|----------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
|
||||||
|
| `crates/vestige-core/src/embedder/mod.rs` | 21-57 | Replace `#[async_trait::async_trait] pub trait LocalEmbedder: Send + Sync + 'static` with `#[trait_variant::make(Embedder: Send)] pub trait LocalEmbedder: Sync + 'static`. Delete the `pub use LocalEmbedder as Embedder;` alias on line 57. Update doc comments (lines 21-26, 55-56). |
|
||||||
|
|
||||||
|
### Impl block (vestige-core)
|
||||||
|
|
||||||
|
| File | Lines (approx) | Change |
|
||||||
|
|-------------------------------------------------|----------------|--------------------------------------------------------------------------------------------------------------|
|
||||||
|
| `crates/vestige-core/src/embedder/fastembed.rs` | 44 | Delete the `#[async_trait::async_trait]` attribute. Keep the `impl LocalEmbedder for FastembedEmbedder { ... }` body verbatim. No `Box::pin`, no `'async_trait` lifetimes, no manual `Pin<Box<dyn Future>>`. |
|
||||||
|
|
||||||
|
### Other Embedder impls
|
||||||
|
|
||||||
|
None. `grep -rn "impl.*LocalEmbedder\|impl.*Embedder for" crates/ tests/`
|
||||||
|
returns exactly one production hit:
|
||||||
|
`crates/vestige-core/src/embedder/fastembed.rs:45: impl LocalEmbedder for FastembedEmbedder`.
|
||||||
|
There is no test mock implementing `Embedder` in the test tree (the only
|
||||||
|
test that touches the trait, `tests/phase_1/embedder_trait.rs`, uses the
|
||||||
|
concrete `FastembedEmbedder` boxed as `Box<dyn Embedder>`).
|
||||||
|
|
||||||
|
### Call sites (production)
|
||||||
|
|
||||||
|
Verified by:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
grep -rn "dyn Embedder\|dyn LocalEmbedder" crates/ tests/ --include="*.rs"
|
||||||
|
grep -rn "Box<dyn Embedder>\|Arc<dyn Embedder>" crates/ tests/ --include="*.rs"
|
||||||
|
grep -rn "use.*Embedder" crates/ tests/ --include="*.rs"
|
||||||
|
```
|
||||||
|
|
||||||
|
Production call sites that may need verification (and the expected change
|
||||||
|
for each, even though we have already verified that none need an edit):
|
||||||
|
|
||||||
|
| File | Use | Required change |
|
||||||
|
|------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------|-----------------|
|
||||||
|
| `crates/vestige-core/src/lib.rs:167` | `pub use embedder::{Embedder, EmbedderError, EmbedderResult, FastembedEmbedder, LocalEmbedder};` | None. Both names still exist at `crate::embedder::*` after the rewrite; `Embedder` is now the `trait_variant`-generated trait, `LocalEmbedder` is the source-of-truth trait. The re-export keeps resolving. |
|
||||||
|
| `crates/vestige-core/src/embedder/fastembed.rs:7` | `use super::{EmbedderError, EmbedderResult, LocalEmbedder};` | None. `LocalEmbedder` is still the source-of-truth trait name. |
|
||||||
|
| `crates/vestige-core/src/embedder/mod.rs:5` | `pub use fastembed::FastembedEmbedder;` | None. Concrete type, untouched. |
|
||||||
|
| `crates/vestige-mcp/src/**` | No file imports `Embedder` or `LocalEmbedder` by name; none hold `Arc<dyn Embedder>` or `Box<dyn Embedder>`. | None. Verified by grep returning empty for `dyn Embedder` and `dyn LocalEmbedder` under `crates/vestige-mcp/`. |
|
||||||
|
| Cognitive modules under `crates/vestige-core/src/advanced/` and `crates/vestige-core/src/neuroscience/` | No file imports `Embedder` or `LocalEmbedder` by name. `advanced/adaptive_embedding.rs` defines its own unrelated `AdaptiveEmbedder` struct. | None. The name collision is purely surface-level; the two types live in different modules and never resolve to each other. |
|
||||||
|
| `crates/vestige-core/src/embeddings/**` | No file imports `Embedder` or `LocalEmbedder`. The `EmbeddingService` struct is what `FastembedEmbedder` wraps internally. | None. |
|
||||||
|
|
||||||
|
The production audit returns zero files that need editing.
|
||||||
|
|
||||||
|
### Call sites (tests)
|
||||||
|
|
||||||
|
| File | Lines | Use | Required change |
|
||||||
|
|------------------------------------------------------------|-------|--------------------------------------------------------------------|-----------------|
|
||||||
|
| `tests/phase_1/embedder_trait.rs` | 3, 19 | `use vestige_core::embedder::{Embedder, FastembedEmbedder};`<br>`let e: Box<dyn Embedder> = Box::new(FastembedEmbedder::new());` | None. `Embedder` is the `trait_variant`-generated Send variant; `Box<dyn Embedder>` keeps compiling. `FastembedEmbedder` implements `LocalEmbedder`; the blanket `impl<T: LocalEmbedder + Send> Embedder for T` that `trait_variant::make` emits gives the boxing for free. |
|
||||||
|
|
||||||
|
The test audit returns zero files that need editing.
|
||||||
|
|
||||||
|
### Cargo dependency cleanup
|
||||||
|
|
||||||
|
| File | Lines | Change |
|
||||||
|
|-------------------------------------|-----------|-----------------------------------------------------------------------------------------------------|
|
||||||
|
| `crates/vestige-core/Cargo.toml` | 119 | Remove `async-trait = "0.1"`. Run `cargo rm async-trait` from inside `crates/vestige-core/` so `Cargo.lock` updates atomically with the manifest. |
|
||||||
|
|
||||||
|
### Documentation
|
||||||
|
|
||||||
|
| File | Change |
|
||||||
|
|---------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------|
|
||||||
|
| `crates/vestige-core/src/embedder/mod.rs` | Rewrite the trait-level doc comment (lines 21-26) and the `pub use` doc comment (lines 55-56) to describe `trait_variant`, not `async_trait`. See "Trait declaration rewrite" below for the exact new text. |
|
||||||
|
| `CLAUDE.md` | No change. The repo-level architecture notes do not name the trait attribute. |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Trait Declaration Rewrite
|
||||||
|
|
||||||
|
### Before (state after `0001a` and `0001b` land)
|
||||||
|
|
||||||
|
`crates/vestige-core/src/embedder/mod.rs:1-58`:
|
||||||
|
|
||||||
|
```rust
|
||||||
|
//! Text-to-vector encoding trait. Pluggable per-install.
|
||||||
|
|
||||||
|
mod fastembed;
|
||||||
|
|
||||||
|
pub use fastembed::FastembedEmbedder;
|
||||||
|
|
||||||
|
/// Error returned by every `Embedder` method.
|
||||||
|
#[non_exhaustive]
|
||||||
|
#[derive(Debug, thiserror::Error)]
|
||||||
|
pub enum EmbedderError {
|
||||||
|
#[error("embedder initialization failed: {0}")]
|
||||||
|
Init(String),
|
||||||
|
#[error("embedding generation failed: {0}")]
|
||||||
|
EmbedFailed(String),
|
||||||
|
#[error("invalid input: {0}")]
|
||||||
|
InvalidInput(String),
|
||||||
|
}
|
||||||
|
|
||||||
|
pub type EmbedderResult<T> = std::result::Result<T, EmbedderError>;
|
||||||
|
|
||||||
|
/// Pluggable embedder. The storage layer NEVER calls fastembed directly;
|
||||||
|
/// callers compute vectors via this trait and pass them into `MemoryStore`.
|
||||||
|
///
|
||||||
|
/// `#[async_trait::async_trait]` makes every `async fn` return a
|
||||||
|
/// `Pin<Box<dyn Future + Send>>`, which is required for `Box<dyn Embedder>`
|
||||||
|
/// and `Arc<dyn Embedder>` to be dyn-compatible.
|
||||||
|
#[async_trait::async_trait]
|
||||||
|
pub trait LocalEmbedder: Send + Sync + 'static {
|
||||||
|
async fn embed(&self, text: &str) -> EmbedderResult<Vec<f32>>;
|
||||||
|
|
||||||
|
fn model_name(&self) -> &str;
|
||||||
|
|
||||||
|
fn dimension(&self) -> usize;
|
||||||
|
|
||||||
|
/// Stable blake3 hash of (model_name || dimension || vestige-core crate version).
|
||||||
|
/// Lowercase hex, 64 chars.
|
||||||
|
///
|
||||||
|
/// Used by `MemoryStore::register_model` to detect silent model drift
|
||||||
|
/// (e.g. a fastembed minor upgrade that changes vector output).
|
||||||
|
fn model_hash(&self) -> String;
|
||||||
|
|
||||||
|
async fn embed_batch(&self, texts: &[&str]) -> EmbedderResult<Vec<Vec<f32>>>;
|
||||||
|
|
||||||
|
/// Returns the `ModelSignature` describing this embedder. Convenience
|
||||||
|
/// wrapper over the three accessors above.
|
||||||
|
fn signature(&self) -> crate::storage::ModelSignature {
|
||||||
|
crate::storage::ModelSignature {
|
||||||
|
name: self.model_name().to_string(),
|
||||||
|
dimension: self.dimension(),
|
||||||
|
hash: self.model_hash(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Type alias: `Embedder` is the dyn-compatible, Send+Sync variant.
|
||||||
|
/// Both names refer to the same `async_trait`-annotated trait.
|
||||||
|
pub use LocalEmbedder as Embedder;
|
||||||
|
```
|
||||||
|
|
||||||
|
### After
|
||||||
|
|
||||||
|
`crates/vestige-core/src/embedder/mod.rs:1-55` (approximately):
|
||||||
|
|
||||||
|
```rust
|
||||||
|
//! Text-to-vector encoding trait. Pluggable per-install.
|
||||||
|
|
||||||
|
mod fastembed;
|
||||||
|
|
||||||
|
pub use fastembed::FastembedEmbedder;
|
||||||
|
|
||||||
|
/// Error returned by every `Embedder` method.
|
||||||
|
#[non_exhaustive]
|
||||||
|
#[derive(Debug, thiserror::Error)]
|
||||||
|
pub enum EmbedderError {
|
||||||
|
#[error("embedder initialization failed: {0}")]
|
||||||
|
Init(String),
|
||||||
|
#[error("embedding generation failed: {0}")]
|
||||||
|
EmbedFailed(String),
|
||||||
|
#[error("invalid input: {0}")]
|
||||||
|
InvalidInput(String),
|
||||||
|
}
|
||||||
|
|
||||||
|
pub type EmbedderResult<T> = std::result::Result<T, EmbedderError>;
|
||||||
|
|
||||||
|
/// Pluggable embedder. The storage layer NEVER calls fastembed directly;
|
||||||
|
/// callers compute vectors via this trait and pass them into `MemoryStore`.
|
||||||
|
///
|
||||||
|
/// `LocalEmbedder` is the source-of-truth trait. The
|
||||||
|
/// `#[trait_variant::make(Embedder: Send)]` attribute auto-generates an
|
||||||
|
/// `Embedder` variant whose returned futures are `Send`, so
|
||||||
|
/// `Box<dyn Embedder>` and `Arc<dyn Embedder>` are usable on tokio/axum
|
||||||
|
/// runtimes, while `Box<dyn LocalEmbedder>` remains usable on single-
|
||||||
|
/// threaded executors and thread-local backends.
|
||||||
|
///
|
||||||
|
/// Every method is native async-fn-in-trait (stable on MSRV 1.91); no
|
||||||
|
/// per-call heap allocation, no boxed futures at the static-dispatch
|
||||||
|
/// boundary.
|
||||||
|
#[trait_variant::make(Embedder: Send)]
|
||||||
|
pub trait LocalEmbedder: Sync + 'static {
|
||||||
|
async fn embed(&self, text: &str) -> EmbedderResult<Vec<f32>>;
|
||||||
|
|
||||||
|
fn model_name(&self) -> &str;
|
||||||
|
|
||||||
|
fn dimension(&self) -> usize;
|
||||||
|
|
||||||
|
/// Stable blake3 hash of (model_name || dimension || vestige-core crate version).
|
||||||
|
/// Lowercase hex, 64 chars.
|
||||||
|
///
|
||||||
|
/// Used by `MemoryStore::register_model` to detect silent model drift
|
||||||
|
/// (e.g. a fastembed minor upgrade that changes vector output).
|
||||||
|
fn model_hash(&self) -> String;
|
||||||
|
|
||||||
|
async fn embed_batch(&self, texts: &[&str]) -> EmbedderResult<Vec<Vec<f32>>>;
|
||||||
|
|
||||||
|
/// Returns the `ModelSignature` describing this embedder. Convenience
|
||||||
|
/// wrapper over the three accessors above.
|
||||||
|
fn signature(&self) -> crate::storage::ModelSignature {
|
||||||
|
crate::storage::ModelSignature {
|
||||||
|
name: self.model_name().to_string(),
|
||||||
|
dimension: self.dimension(),
|
||||||
|
hash: self.model_hash(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Both halves of the macro-generated output (for reviewer clarity)
|
||||||
|
|
||||||
|
`trait_variant::make(Embedder: Send)` expands the source-of-truth
|
||||||
|
`LocalEmbedder` declaration above into the equivalent of:
|
||||||
|
|
||||||
|
```rust
|
||||||
|
// 1. The source-of-truth trait, exactly as written.
|
||||||
|
pub trait LocalEmbedder: Sync + 'static {
|
||||||
|
fn embed(&self, text: &str) -> impl Future<Output = EmbedderResult<Vec<f32>>>;
|
||||||
|
fn model_name(&self) -> &str;
|
||||||
|
fn dimension(&self) -> usize;
|
||||||
|
fn model_hash(&self) -> String;
|
||||||
|
fn embed_batch(&self, texts: &[&str]) -> impl Future<Output = EmbedderResult<Vec<Vec<f32>>>>;
|
||||||
|
fn signature(&self) -> crate::storage::ModelSignature { /* default impl unchanged */ }
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. The generated Send variant.
|
||||||
|
pub trait Embedder: Sync + 'static {
|
||||||
|
fn embed(&self, text: &str) -> impl Future<Output = EmbedderResult<Vec<f32>>> + Send;
|
||||||
|
fn model_name(&self) -> &str;
|
||||||
|
fn dimension(&self) -> usize;
|
||||||
|
fn model_hash(&self) -> String;
|
||||||
|
fn embed_batch(&self, texts: &[&str]) -> impl Future<Output = EmbedderResult<Vec<Vec<f32>>>> + Send;
|
||||||
|
fn signature(&self) -> crate::storage::ModelSignature { /* default impl unchanged */ }
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3. The blanket impl that wires any LocalEmbedder + Send through to Embedder.
|
||||||
|
impl<T> Embedder for T
|
||||||
|
where
|
||||||
|
T: LocalEmbedder + Send,
|
||||||
|
// (all returned futures of LocalEmbedder's async fns are required to be Send,
|
||||||
|
// which is satisfied for FastembedEmbedder -- see "Risks" below)
|
||||||
|
{ /* forwarders */ }
|
||||||
|
```
|
||||||
|
|
||||||
|
Notes:
|
||||||
|
|
||||||
|
- The `pub use LocalEmbedder as Embedder;` line on the current
|
||||||
|
`embedder/mod.rs:57` is **deleted** entirely. `Embedder` is now the
|
||||||
|
trait that `trait_variant::make` emits at the same module path; the
|
||||||
|
re-export in `crates/vestige-core/src/lib.rs:167`
|
||||||
|
(`pub use embedder::{Embedder, ..., LocalEmbedder};`) keeps resolving
|
||||||
|
unchanged.
|
||||||
|
- `Sync + 'static` on `LocalEmbedder` (and no `Send` bound on the trait
|
||||||
|
itself) mirrors the `0001a` pattern for `LocalMemoryStore`. The current
|
||||||
|
trait carries `Send + Sync + 'static`; the rewrite drops the `Send`
|
||||||
|
bound from the local variant. `Box<dyn LocalEmbedder>` is `Sync` but
|
||||||
|
not `Send`; `Box<dyn Embedder>` (the generated variant) is `Send + Sync`.
|
||||||
|
- `trait_variant` 0.1 does **not** require any attribute on the impl
|
||||||
|
block. The attribute lives only on the trait declaration. See next
|
||||||
|
section.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Impl Block Migration
|
||||||
|
|
||||||
|
`trait_variant` 0.1 attaches the attribute only to the trait declaration.
|
||||||
|
The impl side is plain `impl LocalEmbedder for FastembedEmbedder`; no
|
||||||
|
attribute on the impl, no `#[trait_variant::make(Embedder: Send)]` on the
|
||||||
|
impl block. The macro auto-generates the blanket
|
||||||
|
`impl<T: LocalEmbedder + Send> Embedder for T`, so any concrete type that
|
||||||
|
implements `LocalEmbedder` automatically also implements `Embedder`
|
||||||
|
provided it is `Send`.
|
||||||
|
|
||||||
|
`FastembedEmbedder` is `Send + Sync` because:
|
||||||
|
|
||||||
|
- `inner: EmbeddingService` is `Send + Sync` (it wraps fastembed's
|
||||||
|
`TextEmbedding` which is `Send + Sync` after fastembed 4.x; verified
|
||||||
|
in `crates/vestige-core/src/embeddings/mod.rs`).
|
||||||
|
- `cached_hash: std::sync::OnceLock<String>` is `Send + Sync` for `T: Send + Sync`.
|
||||||
|
- The `#[cfg(not(feature = "embeddings"))]` branch carries only
|
||||||
|
`cached_hash`, which is unconditionally `Send + Sync`.
|
||||||
|
|
||||||
|
No new bound is needed.
|
||||||
|
|
||||||
|
### Before
|
||||||
|
|
||||||
|
`crates/vestige-core/src/embedder/fastembed.rs:38-100` (relevant header):
|
||||||
|
|
||||||
|
```rust
|
||||||
|
impl Default for FastembedEmbedder {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self::new()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[async_trait::async_trait]
|
||||||
|
impl LocalEmbedder for FastembedEmbedder {
|
||||||
|
async fn embed(&self, text: &str) -> EmbedderResult<Vec<f32>> {
|
||||||
|
// ... body unchanged ...
|
||||||
|
}
|
||||||
|
|
||||||
|
fn model_name(&self) -> &str { /* ... */ }
|
||||||
|
fn dimension(&self) -> usize { /* ... */ }
|
||||||
|
fn model_hash(&self) -> String { /* ... */ }
|
||||||
|
|
||||||
|
async fn embed_batch(&self, texts: &[&str]) -> EmbedderResult<Vec<Vec<f32>>> {
|
||||||
|
// ... body unchanged ...
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### After
|
||||||
|
|
||||||
|
`crates/vestige-core/src/embedder/fastembed.rs:38-99` (one fewer line):
|
||||||
|
|
||||||
|
```rust
|
||||||
|
impl Default for FastembedEmbedder {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self::new()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl LocalEmbedder for FastembedEmbedder {
|
||||||
|
async fn embed(&self, text: &str) -> EmbedderResult<Vec<f32>> {
|
||||||
|
// ... body unchanged ...
|
||||||
|
}
|
||||||
|
|
||||||
|
fn model_name(&self) -> &str { /* ... */ }
|
||||||
|
fn dimension(&self) -> usize { /* ... */ }
|
||||||
|
fn model_hash(&self) -> String { /* ... */ }
|
||||||
|
|
||||||
|
async fn embed_batch(&self, texts: &[&str]) -> EmbedderResult<Vec<Vec<f32>>> {
|
||||||
|
// ... body unchanged ...
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Diff is exactly one removed line (the `#[async_trait::async_trait]`
|
||||||
|
attribute on line 44). Every method body, every `async fn` signature,
|
||||||
|
every `use` statement inside the impl block stays verbatim. No
|
||||||
|
`Box::pin(async move { ... })`, no manual `Pin<Box<dyn Future>>`, no
|
||||||
|
`'async_trait` lifetime markers; native async-fn-in-trait does this
|
||||||
|
directly.
|
||||||
|
|
||||||
|
### Why the impl block does not need an attribute
|
||||||
|
|
||||||
|
`trait_variant::make` generates two things from the source trait
|
||||||
|
(see the "macro-generated output" subsection above):
|
||||||
|
|
||||||
|
1. The source trait itself (`LocalEmbedder`), with native async fns.
|
||||||
|
2. A second trait (`Embedder`) whose method signatures return
|
||||||
|
`impl Future<Output = ...> + Send` instead of `impl Future<Output = ...>`,
|
||||||
|
plus a blanket impl wiring concrete types through.
|
||||||
|
|
||||||
|
Both are emitted at the macro-call site. `FastembedEmbedder` writes one
|
||||||
|
impl block (against `LocalEmbedder`); the macro-generated blanket
|
||||||
|
guarantees `FastembedEmbedder: Embedder` for free. The
|
||||||
|
`Box<dyn Embedder>` cast on `tests/phase_1/embedder_trait.rs:19` keeps
|
||||||
|
type-checking unchanged.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Call Site Audit
|
||||||
|
|
||||||
|
Verified via, from the phase2 worktree root:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
grep -rn "async_trait\|LocalEmbedder\|dyn Embedder" crates/
|
||||||
|
grep -rn "use.*Embedder" crates/ tests/ --include="*.rs"
|
||||||
|
grep -rn "Box<dyn Embedder>\|Arc<dyn Embedder>\|&dyn Embedder" crates/ tests/ --include="*.rs"
|
||||||
|
grep -rn "Box<dyn LocalEmbedder>\|Arc<dyn LocalEmbedder>\|&dyn LocalEmbedder" crates/ tests/ --include="*.rs"
|
||||||
|
grep -rn "impl LocalEmbedder for\|impl Embedder for" crates/ tests/ --include="*.rs"
|
||||||
|
```
|
||||||
|
|
||||||
|
### Files that reference the trait object form
|
||||||
|
|
||||||
|
Exactly one, test-only:
|
||||||
|
|
||||||
|
| File | Line | Use | Required change |
|
||||||
|
|--------------------------------------|------|------------------------------------------------------------------------------------------|-----------------|
|
||||||
|
| `tests/phase_1/embedder_trait.rs` | 3 | `use vestige_core::embedder::{Embedder, FastembedEmbedder};` | None. `Embedder` is the generated Send variant at the same path. |
|
||||||
|
| `tests/phase_1/embedder_trait.rs` | 19 | `let e: Box<dyn Embedder> = Box::new(FastembedEmbedder::new());` | None. `FastembedEmbedder: LocalEmbedder + Send` -> blanket gives `: Embedder` -> `Box<dyn Embedder>` is well-formed. |
|
||||||
|
|
||||||
|
### Files that import `Embedder` or `LocalEmbedder` by name
|
||||||
|
|
||||||
|
| File | Line | Use | Required change |
|
||||||
|
|-----------------------------------------------------|------|----------------------------------------------------------------------------------------------------------------|-----------------|
|
||||||
|
| `crates/vestige-core/src/lib.rs` | 167 | `pub use embedder::{Embedder, EmbedderError, EmbedderResult, FastembedEmbedder, LocalEmbedder};` | None. Both names still resolve. |
|
||||||
|
| `crates/vestige-core/src/embedder/mod.rs` | 5 | `pub use fastembed::FastembedEmbedder;` | None. |
|
||||||
|
| `crates/vestige-core/src/embedder/fastembed.rs` | 7 | `use super::{EmbedderError, EmbedderResult, LocalEmbedder};` | None. |
|
||||||
|
| `tests/phase_1/embedder_trait.rs` | 3 | `use vestige_core::embedder::{Embedder, FastembedEmbedder};` | None. |
|
||||||
|
|
||||||
|
### Files that implement the trait
|
||||||
|
|
||||||
|
| File | Line | Impl | Required change |
|
||||||
|
|-----------------------------------------------------|------|-----------------------------------------------------------------------|----------------------------------------------|
|
||||||
|
| `crates/vestige-core/src/embedder/fastembed.rs` | 45 | `impl LocalEmbedder for FastembedEmbedder` (currently `#[async_trait]`) | Drop the `#[async_trait::async_trait]` attr. |
|
||||||
|
|
||||||
|
No other impls exist. There is no test mock implementing `Embedder` or
|
||||||
|
`LocalEmbedder` anywhere in the workspace.
|
||||||
|
|
||||||
|
### Files that import `async_trait` directly
|
||||||
|
|
||||||
|
After `0001a` lands, only the embedder pair:
|
||||||
|
|
||||||
|
```
|
||||||
|
crates/vestige-core/src/embedder/mod.rs:24 (doc comment)
|
||||||
|
crates/vestige-core/src/embedder/mod.rs:27 (attribute)
|
||||||
|
crates/vestige-core/src/embedder/mod.rs:56 (doc comment)
|
||||||
|
crates/vestige-core/src/embedder/fastembed.rs:44 (attribute)
|
||||||
|
```
|
||||||
|
|
||||||
|
Plus the Cargo manifest:
|
||||||
|
|
||||||
|
```
|
||||||
|
crates/vestige-core/Cargo.toml:119:async-trait = "0.1"
|
||||||
|
```
|
||||||
|
|
||||||
|
### Production files that hold a concrete embedder
|
||||||
|
|
||||||
|
`FastembedEmbedder` is constructed and used by concrete name (not via
|
||||||
|
trait object) in: the dashboard / MCP layer if it needs to embed query
|
||||||
|
strings ad-hoc. None of those call sites need an edit because the
|
||||||
|
concrete type is what they hold, and the concrete type is untouched by
|
||||||
|
this sub-plan.
|
||||||
|
|
||||||
|
### Conclusion
|
||||||
|
|
||||||
|
| Category | Count |
|
||||||
|
|--------------------------------------------------|-------|
|
||||||
|
| Production source files modified | 2 |
|
||||||
|
| Test source files modified | 0 |
|
||||||
|
| Cargo manifests modified | 1 |
|
||||||
|
| Production source files importing `Embedder` / `LocalEmbedder` (verified unchanged) | 3 |
|
||||||
|
| Test source files importing `Embedder` (verified unchanged) | 1 |
|
||||||
|
| Direct `async_trait` uses outside the embedder module after `0001a` | 0 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Cargo.toml Change
|
||||||
|
|
||||||
|
From inside `crates/vestige-core/`:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cargo rm async-trait
|
||||||
|
```
|
||||||
|
|
||||||
|
This removes line 119 of `Cargo.toml` and updates `Cargo.lock` in one
|
||||||
|
step. Manual editing is acceptable as a fallback if `cargo rm` is
|
||||||
|
unavailable in the agent environment; in that case, follow up with
|
||||||
|
`cargo check -p vestige-core` to refresh the lockfile.
|
||||||
|
|
||||||
|
### Verification
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Direct dependency must be gone.
|
||||||
|
grep -rn "async-trait\|async_trait" --include="Cargo.toml" crates/
|
||||||
|
# Expected: empty.
|
||||||
|
|
||||||
|
# Transitive presence is permitted (e.g. via a third-party crate).
|
||||||
|
cargo tree -p vestige-core --depth 2 | grep async-trait
|
||||||
|
# Expected: empty for the direct edges; if a sub-dependency still pulls
|
||||||
|
# async-trait transitively, the output may contain it deeper than depth 2,
|
||||||
|
# which is fine. We only care about removing the DIRECT edge.
|
||||||
|
```
|
||||||
|
|
||||||
|
If `cargo tree --depth 2` returns any `async-trait` line, inspect with
|
||||||
|
`cargo tree -p vestige-core -i async-trait` to see what is pulling it.
|
||||||
|
Acceptable parents: any third-party crate. Unacceptable parent: anything
|
||||||
|
under `vestige-*`, which would mean a missed file.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Commit Sequence
|
||||||
|
|
||||||
|
Three commits, each green on
|
||||||
|
`cargo test -p vestige-core --features embeddings,vector-search` and
|
||||||
|
`cargo test -p vestige-core --no-default-features`.
|
||||||
|
|
||||||
|
### Commit 1: rewrite LocalEmbedder trait declaration
|
||||||
|
|
||||||
|
- Touches: `crates/vestige-core/src/embedder/mod.rs` only.
|
||||||
|
- Action: replace lines 21-57 per the "Trait Declaration Rewrite"
|
||||||
|
section above. Delete the `pub use LocalEmbedder as Embedder;` line.
|
||||||
|
- Green after: `cargo check -p vestige-core` (the impl block in
|
||||||
|
`fastembed.rs` still has its `#[async_trait::async_trait]` attribute;
|
||||||
|
the macro is harmless when applied to a trait that the impl block
|
||||||
|
targets by path, because async_trait rewrites the impl's async fns
|
||||||
|
into boxed-future fns whose signatures still match the native-async
|
||||||
|
declarations after trait_variant lowering, just as it did for the
|
||||||
|
SQLite intermediate state in `0001a`'s commit 1).
|
||||||
|
|
||||||
|
**Mitigation if check fails between commits 1 and 2:** combine the
|
||||||
|
two into a single commit. The split is offered for review convenience;
|
||||||
|
the build must be green after every commit lands.
|
||||||
|
|
||||||
|
### Commit 2: drop `#[async_trait::async_trait]` from FastembedEmbedder impl
|
||||||
|
|
||||||
|
- Touches: `crates/vestige-core/src/embedder/fastembed.rs` only.
|
||||||
|
- Action: delete line 44 (`#[async_trait::async_trait]`).
|
||||||
|
- Green after:
|
||||||
|
- `cargo test -p vestige-core --features embeddings,vector-search`.
|
||||||
|
- `cargo test -p vestige-core --no-default-features` (the
|
||||||
|
`#[cfg(not(feature = "embeddings"))]` branches inside the impl now
|
||||||
|
stand on their own).
|
||||||
|
- Phase 1 integration test: `cargo test --test embedder_trait
|
||||||
|
--features embeddings,vector-search`.
|
||||||
|
|
||||||
|
### Commit 3: drop the async-trait dependency
|
||||||
|
|
||||||
|
- Touches: `crates/vestige-core/Cargo.toml` (plus `Cargo.lock` as a
|
||||||
|
side effect).
|
||||||
|
- Action: from inside `crates/vestige-core/`, run `cargo rm async-trait`.
|
||||||
|
- Green after: `cargo build --workspace --all-targets` and
|
||||||
|
`cargo test --workspace`.
|
||||||
|
- Final hard ASCII gate: `! grep -rn "async_trait" crates/` must exit
|
||||||
|
with status 0 (i.e. the inverted grep finds nothing).
|
||||||
|
|
||||||
|
### Combined alternative
|
||||||
|
|
||||||
|
Commits 1 and 2 may fold into a single commit if the per-step split
|
||||||
|
feels artificial (the patterns are identical to `0001a`'s commits 3
|
||||||
|
and 4). Commit 3 (the Cargo.toml removal) should stay separate so the
|
||||||
|
dependency-removal diff is visible in isolation.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Verification
|
||||||
|
|
||||||
|
Every command runs from the repo root unless noted otherwise.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 1. Vestige-core, default features (embeddings + vector-search).
|
||||||
|
cargo test -p vestige-core --features embeddings,vector-search
|
||||||
|
|
||||||
|
# 2. Vestige-core, minimal features (no embeddings, no vector-search).
|
||||||
|
cargo test -p vestige-core --no-default-features
|
||||||
|
|
||||||
|
# 3. Workspace build, all targets (catches any feature-gated regression
|
||||||
|
# in the vestige-mcp tools tree).
|
||||||
|
cargo build --workspace --all-targets
|
||||||
|
|
||||||
|
# 4. Whole-workspace test (vestige-mcp 406 tests + vestige-core 352
|
||||||
|
# tests per the CLAUDE.md baseline).
|
||||||
|
cargo test --workspace
|
||||||
|
|
||||||
|
# 5. Phase 1 embedder integration test (the trait-shape contract).
|
||||||
|
cargo test --test embedder_trait --features embeddings,vector-search
|
||||||
|
|
||||||
|
# 6. Clippy gate, deny warnings (matches Phase 1 PR policy).
|
||||||
|
cargo clippy --workspace --all-targets --features embeddings,vector-search -- -D warnings
|
||||||
|
|
||||||
|
# 7. Hard ASCII gate -- async_trait must be gone from source.
|
||||||
|
! grep -rn "async_trait" crates/
|
||||||
|
# Inverted grep: exit 0 iff grep found nothing.
|
||||||
|
|
||||||
|
# 8. Hard ASCII gate -- async-trait must be gone from manifests.
|
||||||
|
! grep -rn "async-trait" --include="Cargo.toml" crates/
|
||||||
|
|
||||||
|
# 9. Confirm trait_variant attribute is in place at the embedder.
|
||||||
|
grep -rn "trait_variant::make" crates/vestige-core/src/embedder/
|
||||||
|
# Expected: exactly one hit, in embedder/mod.rs.
|
||||||
|
|
||||||
|
# 10. Workspace-wide trait_variant audit (should match the count after
|
||||||
|
# 0001a -- two hits total, one for storage, one for embedder).
|
||||||
|
grep -rn "trait_variant::make" crates/vestige-core/src/
|
||||||
|
# Expected: two hits.
|
||||||
|
```
|
||||||
|
|
||||||
|
Expected outcomes:
|
||||||
|
|
||||||
|
- Command 1: 352 vestige-core tests pass (matches baseline).
|
||||||
|
- Command 2: smaller test count, all pass.
|
||||||
|
- Command 3: workspace builds in dev mode for all targets.
|
||||||
|
- Command 4: 758 total tests pass (matches CLAUDE.md baseline).
|
||||||
|
- Command 5: `embedder_trait` integration test passes. The
|
||||||
|
`fastembed_implements_embedder_trait` assertion (`let e: Box<dyn
|
||||||
|
Embedder> = ...`) is the canary; if `trait_variant::make` failed to
|
||||||
|
emit the `Embedder` Send variant, this fails to compile.
|
||||||
|
- Command 6: zero clippy warnings.
|
||||||
|
- Command 7: empty output. `async_trait` is fully gone from source.
|
||||||
|
- Command 8: empty output. `async-trait` is fully gone from manifests.
|
||||||
|
- Command 9: one hit.
|
||||||
|
- Command 10: two hits.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Acceptance Criteria
|
||||||
|
|
||||||
|
A reviewer should be able to check every box:
|
||||||
|
|
||||||
|
- [ ] `crates/vestige-core/src/embedder/mod.rs` declares the embedder
|
||||||
|
trait with `#[trait_variant::make(Embedder: Send)] pub trait
|
||||||
|
LocalEmbedder: Sync + 'static`, no `async_trait` attribute, no
|
||||||
|
`Send` bound on `LocalEmbedder` itself.
|
||||||
|
- [ ] `crates/vestige-core/src/embedder/mod.rs` no longer contains
|
||||||
|
`pub use LocalEmbedder as Embedder;`.
|
||||||
|
- [ ] `crates/vestige-core/src/embedder/fastembed.rs` declares
|
||||||
|
`impl LocalEmbedder for FastembedEmbedder` with no attribute on
|
||||||
|
the impl block.
|
||||||
|
- [ ] `crates/vestige-core/Cargo.toml` does not declare `async-trait`
|
||||||
|
as a direct dependency.
|
||||||
|
- [ ] `grep -rn "async_trait" crates/` returns zero hits.
|
||||||
|
- [ ] `grep -rn "async-trait" --include="Cargo.toml" crates/` returns
|
||||||
|
zero hits.
|
||||||
|
- [ ] `grep -rn "trait_variant::make" crates/vestige-core/src/` returns
|
||||||
|
exactly two hits (storage trait + embedder trait).
|
||||||
|
- [ ] All 758 workspace tests pass (`cargo test --workspace`).
|
||||||
|
- [ ] `tests/phase_1/embedder_trait.rs` compiles and passes with the
|
||||||
|
`Box<dyn Embedder>` cast intact.
|
||||||
|
- [ ] `cargo clippy --workspace --all-targets --features
|
||||||
|
embeddings,vector-search -- -D warnings` is clean.
|
||||||
|
- [ ] No file under `crates/vestige-mcp/` or under
|
||||||
|
`crates/vestige-core/src/{neuroscience,advanced,consolidation,
|
||||||
|
codebase,memory,embeddings}/` was modified by this sub-plan.
|
||||||
|
- [ ] `Cargo.lock` was updated as a side effect of `cargo rm async-trait`
|
||||||
|
(it must no longer reference `async-trait`).
|
||||||
|
- [ ] Doc comments on the embedder trait declaration describe
|
||||||
|
`trait_variant`, not `async_trait`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Risks and Mitigations
|
||||||
|
|
||||||
|
- **`trait_variant::make` requires returned futures to be `Send` for the
|
||||||
|
blanket `impl<T: LocalEmbedder + Send> Embedder for T`. If any
|
||||||
|
`async fn embed`/`embed_batch` body inside `FastembedEmbedder` captures
|
||||||
|
a non-Send local, the blanket impl fails to type-check.**
|
||||||
|
Mitigation: the existing impl bodies call `self.inner.embed(text)` /
|
||||||
|
`self.inner.embed_batch(texts)`, where `inner: EmbeddingService` is
|
||||||
|
`Send + Sync` (verified in `crates/vestige-core/src/embeddings/mod.rs`).
|
||||||
|
No `.await` points exist inside the bodies in either feature branch;
|
||||||
|
the `EmbeddingService::embed` calls are synchronous. The futures are
|
||||||
|
trivially `Send`. If a future change introduces a non-Send local
|
||||||
|
(e.g. an `Rc` or a non-Send guard), the blanket impl will surface that
|
||||||
|
as a compile error at the dyn cast in `tests/phase_1/embedder_trait.rs`,
|
||||||
|
which is the correct outcome.
|
||||||
|
- **The macro's blanket impl interacts oddly with the default `signature`
|
||||||
|
method.**
|
||||||
|
Mitigation: `signature` is a synchronous method returning
|
||||||
|
`crate::storage::ModelSignature`, with no `Send` or `async` concerns.
|
||||||
|
`trait_variant::make` emits it on both variants as-is. The existing
|
||||||
|
Phase 1 test `signature_matches_memory_store_registry` exercises this
|
||||||
|
path and is part of the verification step.
|
||||||
|
- **`Box<dyn Embedder>` cast in `tests/phase_1/embedder_trait.rs` fails
|
||||||
|
to resolve after the rewrite.**
|
||||||
|
Mitigation: the rewrite preserves the `Embedder` symbol at the same
|
||||||
|
module path; only its provenance changes (now generated by
|
||||||
|
`trait_variant::make` instead of by `pub use LocalEmbedder as
|
||||||
|
Embedder;`). The macro is specifically designed so that the generated
|
||||||
|
trait is dyn-compatible at the Send-bound boundary. Verified by the
|
||||||
|
identical pattern already working for `MemoryStore` after `0001a`.
|
||||||
|
- **`cargo rm async-trait` updates `Cargo.lock` but accidentally bumps
|
||||||
|
other crates.**
|
||||||
|
Mitigation: run `cargo rm async-trait` and then immediately inspect
|
||||||
|
the resulting `Cargo.lock` diff. The expected diff is the removal of
|
||||||
|
the `[[package]] name = "async-trait"` block and its hash. Anything
|
||||||
|
else is a red flag and should be reverted before committing
|
||||||
|
(`git checkout -- Cargo.lock` then `cargo update -p async-trait
|
||||||
|
--precise=remove` -- or fall back to manual edit + `cargo check`).
|
||||||
|
- **A new workspace crate added in parallel with this work declares
|
||||||
|
`async-trait` and the dependency removal silently re-introduces it
|
||||||
|
later.**
|
||||||
|
Mitigation: the verification step `grep -rn "async-trait"
|
||||||
|
--include="Cargo.toml" crates/` is part of the acceptance criteria; a
|
||||||
|
rebase that reintroduces the line will fail this gate.
|
||||||
|
- **MCP server uses `Embedder` somewhere we missed.**
|
||||||
|
Mitigation: full workspace grep (`grep -rn "Embedder" crates/`)
|
||||||
|
returns no hits inside `crates/vestige-mcp/` for the trait names; the
|
||||||
|
MCP layer uses the concrete `EmbeddingService` from
|
||||||
|
`crates/vestige-core/src/embeddings/` for ad-hoc embedding calls. The
|
||||||
|
trait surface is purely internal to `vestige-core`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Out-of-Band Notes
|
||||||
|
|
||||||
|
- **No other workspace crate declares `async-trait` as a direct
|
||||||
|
dependency.** Verified by
|
||||||
|
`grep -rn "async-trait" --include="Cargo.toml" crates/` returning
|
||||||
|
exactly one hit at `crates/vestige-core/Cargo.toml:119`. There is
|
||||||
|
nothing to clean up in `crates/vestige-mcp/Cargo.toml` or elsewhere.
|
||||||
|
- **Order matters across the three Phase 1 amendment sub-plans:**
|
||||||
|
`0001a` (trait rewrite) -> `0001b` (sqlite split) -> `0001c` (this
|
||||||
|
one, async-trait sunset). Reversing the order is possible in
|
||||||
|
principle but would force re-editing the embedder rewrite twice and
|
||||||
|
leaves the `async-trait` dep behind until very late.
|
||||||
|
- **This sub-plan amends `feat/storage-trait-phase1` (tip 790c0c8 plus
|
||||||
|
whatever commits `0001a` and `0001b` added).** The branch has not
|
||||||
|
been opened upstream yet, so amending in place is safe; no force-push
|
||||||
|
to a public PR.
|
||||||
|
- **After this sub-plan lands, the branch is reviewed and merged before
|
||||||
|
Phase 2 sub-plans (`0002a-` through `0002i-`) begin implementation.**
|
||||||
|
Phase 2 introduces no async-trait usage; the Postgres backend follows
|
||||||
|
the same `trait_variant::make` pattern (see ADR 0002 D1).
|
||||||
|
- **`trait-variant` 0.1 stays in `Cargo.toml`.** It is the only crate
|
||||||
|
this sub-plan keeps; `async-trait` is the only one it removes.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Self-Contained `/goal` Brief
|
||||||
|
|
||||||
|
For a fresh Claude Code session executing this sub-plan without prior
|
||||||
|
conversation context:
|
||||||
|
|
||||||
|
1. Check out branch `feat/storage-trait-phase1` (or a worktree off
|
||||||
|
of it after `0001a` and `0001b` are merged into it).
|
||||||
|
2. Read this file (`docs/plans/0001c-async-trait-sunset.md`) in full.
|
||||||
|
3. Read `docs/plans/0001a-trait-rewrite.md` sections "Trait declaration
|
||||||
|
rewrite" and "Impl block migration" -- they document the exact
|
||||||
|
pattern this sub-plan mirrors for the embedder.
|
||||||
|
4. Run the prerequisite audit grep listed under "Prerequisites". If it
|
||||||
|
returns more than the five hits documented there, stop and report;
|
||||||
|
the upstream state does not match what this sub-plan assumes.
|
||||||
|
5. Execute Commit 1 (rewrite `embedder/mod.rs`), then Commit 2 (drop
|
||||||
|
the attribute on the FastembedEmbedder impl), then Commit 3
|
||||||
|
(`cargo rm async-trait`). Run the verification commands listed
|
||||||
|
above after each commit; do not proceed if any test or clippy gate
|
||||||
|
fails.
|
||||||
|
6. Verify every box in "Acceptance Criteria" is ticked.
|
||||||
|
7. Report file paths touched, test counts, and the final two grep
|
||||||
|
results (commands 7 and 8 from "Verification") in the closing
|
||||||
|
message.
|
||||||
1278
docs/plans/0002-phase-2-postgres-backend.md
Normal file
1278
docs/plans/0002-phase-2-postgres-backend.md
Normal file
File diff suppressed because it is too large
Load diff
554
docs/plans/0002a-skeleton-and-feature-gate.md
Normal file
554
docs/plans/0002a-skeleton-and-feature-gate.md
Normal file
|
|
@ -0,0 +1,554 @@
|
||||||
|
# Phase 2 Sub-Plan 0002a -- Skeleton and Feature Gate
|
||||||
|
|
||||||
|
**Status**: Ready
|
||||||
|
**Depends on**: Phase 1 amendment (sub-plans `0001a-trait-rewrite.md` and
|
||||||
|
`0001b-sqlite-split.md`) merged. Specifically:
|
||||||
|
- `MemoryStore` trait declared with `#[trait_variant::make(MemoryStore: Send)]`,
|
||||||
|
generating a non-Send `LocalMemoryStore` companion trait. The
|
||||||
|
`pub use MemoryStore as LocalMemoryStore` alias from Phase 1 is gone.
|
||||||
|
- `crates/vestige-core/src/storage/sqlite.rs` has been split into
|
||||||
|
`crates/vestige-core/src/storage/sqlite/` with the same public surface.
|
||||||
|
|
||||||
|
This sub-plan covers Phase 2 master-plan deliverables D1 and D2 only:
|
||||||
|
the `postgres-backend` Cargo feature gate and a compilable `PgMemoryStore`
|
||||||
|
skeleton whose trait method bodies are `todo!()`. No real Postgres code, no
|
||||||
|
migrations, no SQL. Later sub-plans (`0002b-pool-and-config.md`,
|
||||||
|
`0002c-migrations.md`, `0002d-store-impl-bodies.md`, ...) fill the bodies in.
|
||||||
|
|
||||||
|
The success criterion is a clean build under both feature-flag configurations,
|
||||||
|
nothing more.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Context
|
||||||
|
|
||||||
|
ADR 0002 D4 commits Phase 2 to a `crates/vestige-core/src/storage/postgres/`
|
||||||
|
directory from day one. The seven other files in that directory
|
||||||
|
(`pool.rs`, `migrations.rs`, `registry.rs`, `search.rs`, `migrate_cli.rs`,
|
||||||
|
`reembed.rs`) belong to subsequent sub-plans. This sub-plan creates only
|
||||||
|
`crates/vestige-core/src/storage/postgres/mod.rs` so the rest can be added
|
||||||
|
incrementally without breaking the build.
|
||||||
|
|
||||||
|
Per ADR 0002 D2, `PgMemoryStore::connect` mirrors `SqliteMemoryStore::new`:
|
||||||
|
no `Embedder` argument. The pgvector typmod DDL
|
||||||
|
(`ALTER TABLE memories ALTER COLUMN embedding TYPE vector($N)`) lives inside
|
||||||
|
the trait method `register_model`, invoked by the caller after construction.
|
||||||
|
In this sub-plan `register_model` is a `todo!()` body; `0002c-migrations.md`
|
||||||
|
and `0002d-store-impl-bodies.md` provide the real implementation.
|
||||||
|
|
||||||
|
The trait surface in `crates/vestige-core/src/storage/memory_store.rs` is the
|
||||||
|
source of truth for method signatures. Do NOT copy signatures from the master
|
||||||
|
plan -- they are stale in places (for example, master plan 0002 D2 lists
|
||||||
|
`remove_edge` as three-arg `(source, target, edge_type)`; the live trait has
|
||||||
|
two args `(source, target)`).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Cargo manifest changes
|
||||||
|
|
||||||
|
Two optional crates and one new feature flag. Use `cargo add` per the global
|
||||||
|
CLAUDE.md preference; do not hand-edit `Cargo.toml`.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd crates/vestige-core
|
||||||
|
|
||||||
|
cargo add sqlx@0.8 --optional --no-default-features \
|
||||||
|
--features runtime-tokio,tls-rustls,postgres,uuid,chrono,json,migrate,macros
|
||||||
|
|
||||||
|
cargo add pgvector@0.4 --optional --features sqlx
|
||||||
|
```
|
||||||
|
|
||||||
|
After both commands, open `crates/vestige-core/Cargo.toml` and add the
|
||||||
|
`postgres-backend` feature line in the `[features]` block. Place it after
|
||||||
|
the `metal` feature, before `[dependencies]`:
|
||||||
|
|
||||||
|
```toml
|
||||||
|
# Postgres backend (mutually compilable with the SQLite backend; default OFF).
|
||||||
|
# Compile with: --features postgres-backend
|
||||||
|
postgres-backend = ["dep:sqlx", "dep:pgvector"]
|
||||||
|
```
|
||||||
|
|
||||||
|
Do NOT add `tokio-stream`, `futures`, `indicatif`, or `toml` in this sub-plan.
|
||||||
|
The master plan D1 lists them in the `postgres-backend` feature for
|
||||||
|
convenience, but their consumers (streaming migrate, progress bar, config
|
||||||
|
parsing) land in later sub-plans. Adding them here pulls dead weight into the
|
||||||
|
feature gate.
|
||||||
|
|
||||||
|
Do NOT add the `vestige-mcp` pass-through feature in this sub-plan either.
|
||||||
|
The MCP crate gets its `postgres-backend` feature in `0002b-pool-and-config.md`
|
||||||
|
when `MemoryStoreConfig` lands and the binary needs a knob to pick a backend.
|
||||||
|
|
||||||
|
Verify the diff to `crates/vestige-core/Cargo.toml` looks like this and only
|
||||||
|
this:
|
||||||
|
|
||||||
|
```toml
|
||||||
|
[features]
|
||||||
|
# ...existing features unchanged...
|
||||||
|
postgres-backend = ["dep:sqlx", "dep:pgvector"]
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
# ...existing deps unchanged...
|
||||||
|
sqlx = { version = "0.8", default-features = false, features = [
|
||||||
|
"runtime-tokio", "tls-rustls", "postgres", "uuid", "chrono",
|
||||||
|
"json", "migrate", "macros",
|
||||||
|
], optional = true }
|
||||||
|
pgvector = { version = "0.4", features = ["sqlx"], optional = true }
|
||||||
|
```
|
||||||
|
|
||||||
|
The exact ordering of the two new lines inside `[dependencies]` is not
|
||||||
|
significant; `cargo add` places them at the end. Leave the placement that
|
||||||
|
`cargo add` produces.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Storage module export
|
||||||
|
|
||||||
|
Edit `crates/vestige-core/src/storage/mod.rs` to expose the new module behind
|
||||||
|
the feature flag. Two lines change.
|
||||||
|
|
||||||
|
Add to the module-declaration block (after `mod sqlite;`):
|
||||||
|
|
||||||
|
```rust
|
||||||
|
#[cfg(feature = "postgres-backend")]
|
||||||
|
mod postgres;
|
||||||
|
```
|
||||||
|
|
||||||
|
Add to the re-export block (after the `pub use sqlite::{ ... }` block):
|
||||||
|
|
||||||
|
```rust
|
||||||
|
#[cfg(feature = "postgres-backend")]
|
||||||
|
pub use postgres::PgMemoryStore;
|
||||||
|
```
|
||||||
|
|
||||||
|
Nothing else in `storage/mod.rs` changes. The `Storage` alias still points at
|
||||||
|
`SqliteMemoryStore`; the SQLite re-export block is untouched.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Postgres module skeleton
|
||||||
|
|
||||||
|
Create `crates/vestige-core/src/storage/postgres/mod.rs` with the full content
|
||||||
|
below. This is the only new file in this sub-plan.
|
||||||
|
|
||||||
|
```rust
|
||||||
|
#![cfg(feature = "postgres-backend")]
|
||||||
|
//! Postgres-backed implementation of `MemoryStore`.
|
||||||
|
//!
|
||||||
|
//! Skeleton only. Every trait method is `todo!()`. Real bodies land in
|
||||||
|
//! subsequent Phase 2 sub-plans:
|
||||||
|
//! - `0002b-pool-and-config.md`: pool construction and config wiring
|
||||||
|
//! - `0002c-migrations.md`: sqlx migration files and `init`/`register_model`
|
||||||
|
//! - `0002d-store-impl-bodies.md`: CRUD, scheduling, edges, domains
|
||||||
|
//! - `0002e-hybrid-search.md`: RRF query and search bodies
|
||||||
|
//!
|
||||||
|
//! The directory grows companion files (`pool.rs`, `migrations.rs`,
|
||||||
|
//! `registry.rs`, `search.rs`, `migrate_cli.rs`, `reembed.rs`) in those
|
||||||
|
//! sub-plans; this skeleton only creates `mod.rs`.
|
||||||
|
|
||||||
|
use chrono::{DateTime, Utc};
|
||||||
|
use sqlx::PgPool;
|
||||||
|
use uuid::Uuid;
|
||||||
|
|
||||||
|
use crate::storage::memory_store::{
|
||||||
|
Domain, HealthStatus, LocalMemoryStore, MemoryEdge, MemoryRecord, MemoryStoreResult,
|
||||||
|
ModelSignature, SchedulingState, SearchQuery, SearchResult, StoreStats,
|
||||||
|
};
|
||||||
|
|
||||||
|
/// Postgres-backed implementation of `MemoryStore`.
|
||||||
|
///
|
||||||
|
/// Cheaply cloneable. Methods take `&self`; interior state lives inside the
|
||||||
|
/// `PgPool` (which already provides `Sync` via `Arc` internally).
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct PgMemoryStore {
|
||||||
|
pool: PgPool,
|
||||||
|
/// Embedding vector dimension. Set to 0 in the skeleton; populated by
|
||||||
|
/// `register_model` in `0002d-store-impl-bodies.md` once the pgvector
|
||||||
|
/// `ALTER COLUMN TYPE vector(N)` DDL lands.
|
||||||
|
embedding_dim: i32,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl PgMemoryStore {
|
||||||
|
/// Construct a new store from a connection URL.
|
||||||
|
///
|
||||||
|
/// Mirrors `SqliteMemoryStore::new`: no `Embedder` argument. The pgvector
|
||||||
|
/// `ALTER TABLE memories ALTER COLUMN embedding TYPE vector($N)` DDL lives
|
||||||
|
/// inside `register_model`, not here. The caller (cognitive engine
|
||||||
|
/// bootstrap, migrate CLI, tests) invokes `register_model` after this
|
||||||
|
/// returns, identically to the SQLite path.
|
||||||
|
///
|
||||||
|
/// Real body lands in `0002b-pool-and-config.md` (pool construction) and
|
||||||
|
/// `0002c-migrations.md` (initial migration run).
|
||||||
|
pub async fn connect(_url: &str, _max_connections: u32) -> MemoryStoreResult<Self> {
|
||||||
|
todo!("PgMemoryStore::connect lands in 0002b-pool-and-config.md")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Low-level constructor for tests: supply an existing pool, skip migrate.
|
||||||
|
///
|
||||||
|
/// Real body lands in `0002b-pool-and-config.md`.
|
||||||
|
pub async fn from_pool(_pool: PgPool) -> MemoryStoreResult<Self> {
|
||||||
|
todo!("PgMemoryStore::from_pool lands in 0002b-pool-and-config.md")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Accessor used by migrate/reembed CLI.
|
||||||
|
pub fn pool(&self) -> &PgPool {
|
||||||
|
&self.pool
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Currently-registered vector dimension. Returns 0 until `register_model`
|
||||||
|
/// has been called (real body: `0002d-store-impl-bodies.md`).
|
||||||
|
pub fn embedding_dim(&self) -> i32 {
|
||||||
|
self.embedding_dim
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// trait_variant::make on the trait declaration generates two traits:
|
||||||
|
// - `MemoryStore` (Send-bound)
|
||||||
|
// - `LocalMemoryStore` (non-Send companion)
|
||||||
|
// The implementer writes `impl LocalMemoryStore for ...` plainly; the Send
|
||||||
|
// variant is generated automatically from the non-Send impl.
|
||||||
|
impl LocalMemoryStore for PgMemoryStore {
|
||||||
|
// --- Lifecycle ---
|
||||||
|
async fn init(&self) -> MemoryStoreResult<()> {
|
||||||
|
todo!("PgMemoryStore::init lands in 0002c-migrations.md")
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn health_check(&self) -> MemoryStoreResult<HealthStatus> {
|
||||||
|
todo!("PgMemoryStore::health_check lands in 0002d-store-impl-bodies.md")
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Embedding model registry ---
|
||||||
|
async fn registered_model(&self) -> MemoryStoreResult<Option<ModelSignature>> {
|
||||||
|
todo!("PgMemoryStore::registered_model lands in 0002d-store-impl-bodies.md")
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn register_model(&self, _sig: &ModelSignature) -> MemoryStoreResult<()> {
|
||||||
|
todo!("PgMemoryStore::register_model lands in 0002d-store-impl-bodies.md")
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- CRUD ---
|
||||||
|
async fn insert(&self, _record: &MemoryRecord) -> MemoryStoreResult<Uuid> {
|
||||||
|
todo!("PgMemoryStore::insert lands in 0002d-store-impl-bodies.md")
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn get(&self, _id: Uuid) -> MemoryStoreResult<Option<MemoryRecord>> {
|
||||||
|
todo!("PgMemoryStore::get lands in 0002d-store-impl-bodies.md")
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn update(&self, _record: &MemoryRecord) -> MemoryStoreResult<()> {
|
||||||
|
todo!("PgMemoryStore::update lands in 0002d-store-impl-bodies.md")
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn delete(&self, _id: Uuid) -> MemoryStoreResult<()> {
|
||||||
|
todo!("PgMemoryStore::delete lands in 0002d-store-impl-bodies.md")
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Search ---
|
||||||
|
async fn search(&self, _query: &SearchQuery) -> MemoryStoreResult<Vec<SearchResult>> {
|
||||||
|
todo!("PgMemoryStore::search lands in 0002e-hybrid-search.md")
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn fts_search(
|
||||||
|
&self,
|
||||||
|
_text: &str,
|
||||||
|
_limit: usize,
|
||||||
|
) -> MemoryStoreResult<Vec<SearchResult>> {
|
||||||
|
todo!("PgMemoryStore::fts_search lands in 0002e-hybrid-search.md")
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn vector_search(
|
||||||
|
&self,
|
||||||
|
_embedding: &[f32],
|
||||||
|
_limit: usize,
|
||||||
|
) -> MemoryStoreResult<Vec<SearchResult>> {
|
||||||
|
todo!("PgMemoryStore::vector_search lands in 0002e-hybrid-search.md")
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- FSRS Scheduling ---
|
||||||
|
async fn get_scheduling(
|
||||||
|
&self,
|
||||||
|
_memory_id: Uuid,
|
||||||
|
) -> MemoryStoreResult<Option<SchedulingState>> {
|
||||||
|
todo!("PgMemoryStore::get_scheduling lands in 0002d-store-impl-bodies.md")
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn update_scheduling(&self, _state: &SchedulingState) -> MemoryStoreResult<()> {
|
||||||
|
todo!("PgMemoryStore::update_scheduling lands in 0002d-store-impl-bodies.md")
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn get_due_memories(
|
||||||
|
&self,
|
||||||
|
_before: DateTime<Utc>,
|
||||||
|
_limit: usize,
|
||||||
|
) -> MemoryStoreResult<Vec<(MemoryRecord, SchedulingState)>> {
|
||||||
|
todo!("PgMemoryStore::get_due_memories lands in 0002d-store-impl-bodies.md")
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Graph (spreading activation) ---
|
||||||
|
async fn add_edge(&self, _edge: &MemoryEdge) -> MemoryStoreResult<()> {
|
||||||
|
todo!("PgMemoryStore::add_edge lands in 0002d-store-impl-bodies.md")
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn get_edges(
|
||||||
|
&self,
|
||||||
|
_node_id: Uuid,
|
||||||
|
_edge_type: Option<&str>,
|
||||||
|
) -> MemoryStoreResult<Vec<MemoryEdge>> {
|
||||||
|
todo!("PgMemoryStore::get_edges lands in 0002d-store-impl-bodies.md")
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn remove_edge(&self, _source: Uuid, _target: Uuid) -> MemoryStoreResult<()> {
|
||||||
|
todo!("PgMemoryStore::remove_edge lands in 0002d-store-impl-bodies.md")
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn get_neighbors(
|
||||||
|
&self,
|
||||||
|
_node_id: Uuid,
|
||||||
|
_depth: usize,
|
||||||
|
) -> MemoryStoreResult<Vec<(MemoryRecord, f64)>> {
|
||||||
|
todo!("PgMemoryStore::get_neighbors lands in 0002d-store-impl-bodies.md")
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Domains (Phase 1: stubs return empty; full impl in Phase 4) ---
|
||||||
|
async fn list_domains(&self) -> MemoryStoreResult<Vec<Domain>> {
|
||||||
|
todo!("PgMemoryStore::list_domains lands in 0002d-store-impl-bodies.md")
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn get_domain(&self, _id: &str) -> MemoryStoreResult<Option<Domain>> {
|
||||||
|
todo!("PgMemoryStore::get_domain lands in 0002d-store-impl-bodies.md")
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn upsert_domain(&self, _domain: &Domain) -> MemoryStoreResult<()> {
|
||||||
|
todo!("PgMemoryStore::upsert_domain lands in 0002d-store-impl-bodies.md")
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn delete_domain(&self, _id: &str) -> MemoryStoreResult<()> {
|
||||||
|
todo!("PgMemoryStore::delete_domain lands in 0002d-store-impl-bodies.md")
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn classify(&self, _embedding: &[f32]) -> MemoryStoreResult<Vec<(String, f64)>> {
|
||||||
|
todo!("PgMemoryStore::classify lands in 0002d-store-impl-bodies.md")
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Bulk / Maintenance ---
|
||||||
|
async fn count(&self) -> MemoryStoreResult<usize> {
|
||||||
|
todo!("PgMemoryStore::count lands in 0002d-store-impl-bodies.md")
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn get_stats(&self) -> MemoryStoreResult<StoreStats> {
|
||||||
|
todo!("PgMemoryStore::get_stats lands in 0002d-store-impl-bodies.md")
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn vacuum(&self) -> MemoryStoreResult<()> {
|
||||||
|
todo!("PgMemoryStore::vacuum lands in 0002d-store-impl-bodies.md")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Notes on the skeleton:
|
||||||
|
|
||||||
|
- The file-level `#![cfg(feature = "postgres-backend")]` means the whole file
|
||||||
|
vanishes when the feature is off. The `mod postgres;` line in
|
||||||
|
`storage/mod.rs` is itself feature-gated, so this is belt-and-braces; both
|
||||||
|
gates are needed because the file-level attribute is what allows the file to
|
||||||
|
use `sqlx::PgPool` unconditionally inside it.
|
||||||
|
- `EmbeddingModelDescriptor` (a separate Postgres-internal type that the
|
||||||
|
master plan sketched on the struct) is dropped. The trait surface already
|
||||||
|
carries `ModelSignature` for the registry round-trip; the registry storage
|
||||||
|
layout is a private concern of `registry.rs`, which is added later. Keep
|
||||||
|
`PgMemoryStore` minimal until a real consumer needs the extra type.
|
||||||
|
- The struct only carries `pool` and `embedding_dim`. The model descriptor
|
||||||
|
field from the master plan sketch goes away with `EmbeddingModelDescriptor`.
|
||||||
|
If `register_model` later needs to cache the descriptor on the struct, it
|
||||||
|
can be added then; the skeleton does not speculate.
|
||||||
|
- The two trivial accessors (`pool`, `embedding_dim`) get real bodies. Every
|
||||||
|
other method is `todo!()` so it returns `!` and trivially coerces to the
|
||||||
|
declared return type at the type checker; this is what lets the build pass
|
||||||
|
with no error variants and no SQL.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Connect signature
|
||||||
|
|
||||||
|
Per ADR 0002 D2:
|
||||||
|
|
||||||
|
```rust
|
||||||
|
pub async fn connect(url: &str, max_connections: u32) -> MemoryStoreResult<Self>;
|
||||||
|
pub async fn from_pool(pool: PgPool) -> MemoryStoreResult<Self>;
|
||||||
|
```
|
||||||
|
|
||||||
|
No `&dyn Embedder` argument. This deliberately differs from master plan 0002,
|
||||||
|
which predates the Phase 1 freeze. The pgvector-specific DDL
|
||||||
|
(`ALTER TABLE memories ALTER COLUMN embedding TYPE vector($N)`) does not run
|
||||||
|
inside `connect`; it runs inside `register_model(&ModelSignature)`, which the
|
||||||
|
caller invokes after `connect` returns.
|
||||||
|
|
||||||
|
In this sub-plan `register_model` is `todo!()`. The real body lands in
|
||||||
|
`0002d-store-impl-bodies.md` after `0002c-migrations.md` ships the
|
||||||
|
`0001_init.up.sql` migration that creates the `memories` table with a
|
||||||
|
placeholder `embedding vector` column (no typmod), against which
|
||||||
|
`register_model` later runs the typmod stamp.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Error variant additions: deferred
|
||||||
|
|
||||||
|
`MemoryStoreError` does NOT gain `Postgres(sqlx::Error)` or
|
||||||
|
`Migrate(sqlx::migrate::MigrateError)` in this sub-plan.
|
||||||
|
|
||||||
|
The reason is mechanical: `todo!()` evaluates to the never type `!`, which
|
||||||
|
coerces to any `MemoryStoreResult<T>` regardless of the error variants
|
||||||
|
available. With every method body a `todo!()`, the skeleton has no expression
|
||||||
|
that needs to convert a `sqlx::Error` or `sqlx::migrate::MigrateError` into
|
||||||
|
`MemoryStoreError`. Adding the variants here would mean adding the
|
||||||
|
`#[cfg(feature = "postgres-backend")]` and `#[from]` plumbing to
|
||||||
|
`memory_store.rs` with no consumer yet -- dead code at every level except the
|
||||||
|
enum definition itself.
|
||||||
|
|
||||||
|
`0002d-store-impl-bodies.md` introduces both variants in the same commit that
|
||||||
|
turns the first `todo!()` into a real `sqlx::query!` call. That keeps the
|
||||||
|
diff to `memory_store.rs` next to the first usage site, which is easier to
|
||||||
|
review than adding variants ahead of need.
|
||||||
|
|
||||||
|
For reference, the variants that will be added in `0002d-store-impl-bodies.md`
|
||||||
|
look like this:
|
||||||
|
|
||||||
|
```rust
|
||||||
|
#[cfg(feature = "postgres-backend")]
|
||||||
|
#[error("postgres error: {0}")]
|
||||||
|
Postgres(#[from] sqlx::Error),
|
||||||
|
|
||||||
|
#[cfg(feature = "postgres-backend")]
|
||||||
|
#[error("postgres migration error: {0}")]
|
||||||
|
Migrate(#[from] sqlx::migrate::MigrateError),
|
||||||
|
```
|
||||||
|
|
||||||
|
Do not pre-add them here.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Verification
|
||||||
|
|
||||||
|
Run these commands from the workspace root. All four must produce a clean
|
||||||
|
build, zero warnings on the diff-affected files, no test changes.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 1. Default features (SQLite backend, postgres-backend OFF). Must build.
|
||||||
|
cargo build --workspace --all-targets
|
||||||
|
|
||||||
|
# 2. Workspace clippy with default features. Must be clean.
|
||||||
|
cargo clippy --workspace --all-targets -- -D warnings
|
||||||
|
|
||||||
|
# 3. Postgres feature enabled. Must build.
|
||||||
|
cargo build -p vestige-core --features postgres-backend
|
||||||
|
|
||||||
|
# 4. Clippy with postgres feature enabled. Must be clean.
|
||||||
|
cargo clippy -p vestige-core --features postgres-backend --all-targets -- -D warnings
|
||||||
|
```
|
||||||
|
|
||||||
|
Expected outcomes:
|
||||||
|
|
||||||
|
- `cargo build --workspace --all-targets` finishes with no compilation of
|
||||||
|
`sqlx` or `pgvector` (both are optional, no consumer with default features).
|
||||||
|
The `postgres` module is excluded entirely via `#[cfg]`.
|
||||||
|
- `cargo build -p vestige-core --features postgres-backend` compiles `sqlx`,
|
||||||
|
`pgvector`, and `storage/postgres/mod.rs`. The build succeeds because every
|
||||||
|
trait method is `todo!()`; nothing actually runs SQL.
|
||||||
|
- Both `clippy` invocations pass with `-D warnings`. The `todo!()` macro does
|
||||||
|
not emit a `dead_code` lint by itself, and the trivial accessors are used by
|
||||||
|
later sub-plans (clippy on the postgres feature alone may flag them as
|
||||||
|
unused if you run with `--lib` only; the `--all-targets` form keeps tests
|
||||||
|
and benches in scope so this does not fire).
|
||||||
|
- If clippy flags `unused_variables` on the underscore-prefixed parameters in
|
||||||
|
the `todo!()` bodies, the underscore prefix is already the standard
|
||||||
|
suppression; if a future clippy version disagrees, add
|
||||||
|
`#[allow(unused_variables)]` to the impl block, not to each method.
|
||||||
|
|
||||||
|
Tests are not modified in this sub-plan. The unit tests in
|
||||||
|
`memory_store.rs` (`memory_store_error_from_storage_error`,
|
||||||
|
`model_signature_serde_round_trip`, `memory_record_serde_round_trip`) keep
|
||||||
|
passing because no type they touch changes.
|
||||||
|
|
||||||
|
Do NOT run `cargo test` against the postgres feature -- there is no Postgres
|
||||||
|
running and no test exercises `PgMemoryStore` yet. The build check is the
|
||||||
|
contract.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Acceptance criteria
|
||||||
|
|
||||||
|
1. `crates/vestige-core/Cargo.toml` declares `sqlx = "0.8"` and
|
||||||
|
`pgvector = "0.4"` as optional dependencies with the exact feature sets
|
||||||
|
specified above.
|
||||||
|
2. `crates/vestige-core/Cargo.toml` declares `postgres-backend = ["dep:sqlx",
|
||||||
|
"dep:pgvector"]` and nothing else inside that feature.
|
||||||
|
3. `crates/vestige-mcp/Cargo.toml` is unchanged.
|
||||||
|
4. `crates/vestige-core/src/storage/mod.rs` adds exactly two
|
||||||
|
feature-gated lines: `mod postgres;` and `pub use postgres::PgMemoryStore;`.
|
||||||
|
No other change.
|
||||||
|
5. `crates/vestige-core/src/storage/postgres/mod.rs` exists and contains the
|
||||||
|
`PgMemoryStore` struct, `impl PgMemoryStore` block with real `pool` and
|
||||||
|
`embedding_dim` accessors and `todo!()` bodies for `connect` and
|
||||||
|
`from_pool`, and the full `impl LocalMemoryStore for PgMemoryStore` block
|
||||||
|
with `todo!()` for every trait method.
|
||||||
|
6. The trait impl method signatures match `memory_store.rs` byte-for-byte
|
||||||
|
(including `remove_edge(&self, source: Uuid, target: Uuid)` two-arg form,
|
||||||
|
not the three-arg form from the master plan).
|
||||||
|
7. `MemoryStoreError` is unchanged.
|
||||||
|
8. No other files in the crate are touched. No new files in
|
||||||
|
`storage/postgres/` besides `mod.rs`.
|
||||||
|
9. The four verification commands above all succeed.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Commit sequence
|
||||||
|
|
||||||
|
One commit is recommended. The two changes (Cargo manifest + module skeleton)
|
||||||
|
do not compile in isolation: the manifest change without the skeleton produces
|
||||||
|
unused-optional-dep warnings, and the skeleton without the manifest change
|
||||||
|
fails to find `sqlx`. Splitting them adds no review value, since the second
|
||||||
|
commit is the one that has to compile cleanly.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git add crates/vestige-core/Cargo.toml \
|
||||||
|
crates/vestige-core/Cargo.lock \
|
||||||
|
crates/vestige-core/src/storage/mod.rs \
|
||||||
|
crates/vestige-core/src/storage/postgres/mod.rs
|
||||||
|
|
||||||
|
git commit -m "feat(storage): scaffold postgres-backend feature and PgMemoryStore skeleton
|
||||||
|
|
||||||
|
Adds the postgres-backend Cargo feature gating sqlx 0.8 and pgvector 0.4.
|
||||||
|
Introduces crates/vestige-core/src/storage/postgres/mod.rs with the
|
||||||
|
PgMemoryStore struct, connect/from_pool/pool/embedding_dim, and a trait impl
|
||||||
|
whose method bodies are todo!() pending later Phase 2 sub-plans.
|
||||||
|
|
||||||
|
Builds clean with default features (SQLite only) and with --features
|
||||||
|
postgres-backend. No runtime behaviour change.
|
||||||
|
|
||||||
|
Refs ADR 0002 D1, D2, D4."
|
||||||
|
```
|
||||||
|
|
||||||
|
If for any reason the manifest change must be reviewed separately (for
|
||||||
|
example, a security review of the sqlx version pin), split as:
|
||||||
|
|
||||||
|
1. `cargo add` for sqlx and pgvector + manual feature line in Cargo.toml.
|
||||||
|
Build with default features will pass but `--features postgres-backend`
|
||||||
|
will fail (no module to satisfy the feature). This is acceptable for a
|
||||||
|
short-lived intermediate commit.
|
||||||
|
2. `storage/mod.rs` edits + `storage/postgres/mod.rs` creation. Both builds
|
||||||
|
pass.
|
||||||
|
|
||||||
|
Default to the single-commit form unless asked to split.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Followups
|
||||||
|
|
||||||
|
- `0002b-pool-and-config.md` adds `pool.rs`, `PostgresConfig`, and the
|
||||||
|
`vestige-mcp` `postgres-backend` pass-through feature.
|
||||||
|
- `0002c-migrations.md` adds `crates/vestige-core/migrations/postgres/` with
|
||||||
|
`0001_init.{up,down}.sql` and `0002_hnsw.{up,down}.sql`, plus
|
||||||
|
`postgres/migrations.rs` invoking `sqlx::migrate!`. `init()` body lands here.
|
||||||
|
- `0002d-store-impl-bodies.md` introduces the two `MemoryStoreError` variants
|
||||||
|
and replaces every `todo!()` in CRUD / scheduling / edges / domains /
|
||||||
|
registry with real `sqlx::query!` bodies.
|
||||||
|
- `0002e-hybrid-search.md` fills the three search bodies via the RRF query.
|
||||||
886
docs/plans/0002b-pool-and-config.md
Normal file
886
docs/plans/0002b-pool-and-config.md
Normal file
|
|
@ -0,0 +1,886 @@
|
||||||
|
# Sub-plan 0002b -- Pool construction and VestigeConfig
|
||||||
|
|
||||||
|
**Status**: Draft
|
||||||
|
**Master plan**: [0002-phase-2-postgres-backend.md](0002-phase-2-postgres-backend.md)
|
||||||
|
**ADR**: [0002-phase-2-execution.md](../adr/0002-phase-2-execution.md)
|
||||||
|
**Predecessor**: [0002a-skeleton-and-feature-gate.md](0002a-skeleton-and-feature-gate.md)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Context
|
||||||
|
|
||||||
|
This sub-plan delivers two of the master plan's deliverables now that the
|
||||||
|
`0002a` skeleton has landed:
|
||||||
|
|
||||||
|
- **D3** -- pool construction in
|
||||||
|
`crates/vestige-core/src/storage/postgres/pool.rs`. Replaces the `todo!()`
|
||||||
|
body of `PgMemoryStore::connect` with a real `PgPool` builder that reads a
|
||||||
|
`PostgresConfig`. Registry/migration calls remain `todo!()`; those are
|
||||||
|
filled in by sub-plans `0002c` (migrations) and `0002d` (store bodies +
|
||||||
|
registry).
|
||||||
|
- **D7** -- new module `crates/vestige-core/src/config.rs` containing
|
||||||
|
`VestigeConfig`, `StorageConfig`, `SqliteConfig`, `PostgresConfig`,
|
||||||
|
`EmbeddingsConfig`, plus a `ConfigError` enum and a loader that reads
|
||||||
|
`vestige.toml`. The loader is wired into `vestige-mcp` so the running
|
||||||
|
server picks SQLite or Postgres at startup based on the config file.
|
||||||
|
|
||||||
|
After this sub-plan:
|
||||||
|
|
||||||
|
- `cargo build` (default features, no `postgres-backend`) compiles and the
|
||||||
|
MCP server still defaults to SQLite when no `vestige.toml` is present.
|
||||||
|
- `cargo build --features postgres-backend` compiles, with
|
||||||
|
`PgMemoryStore::connect` now wiring through `pool.rs` (registry/migration
|
||||||
|
still `todo!()` until `0002c` and `0002d`).
|
||||||
|
- A `vestige.toml` example can be round-tripped through
|
||||||
|
`VestigeConfig::load` in a unit test.
|
||||||
|
|
||||||
|
This sub-plan deliberately does NOT:
|
||||||
|
|
||||||
|
- Add migrations (`0002c`).
|
||||||
|
- Fill in real CRUD/search bodies on `PgMemoryStore` (`0002d`, `0002e`).
|
||||||
|
- Add env-var override support (Phase 3 concern, called out in master plan
|
||||||
|
D7 behaviour notes).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Dependencies
|
||||||
|
|
||||||
|
- `0002a-skeleton-and-feature-gate.md` must be merged. That sub-plan creates
|
||||||
|
`crates/vestige-core/src/storage/postgres/mod.rs` with:
|
||||||
|
- `PgMemoryStore` struct holding `pool: PgPool`.
|
||||||
|
- `PgMemoryStore::connect(url: &str, max_connections: u32) -> MemoryStoreResult<Self>`
|
||||||
|
body = `todo!()`.
|
||||||
|
- `PgMemoryStore::from_pool(pool: PgPool) -> MemoryStoreResult<Self>`
|
||||||
|
body = `todo!()`.
|
||||||
|
- The trait impl block with all methods routed to `todo!()`.
|
||||||
|
- The `postgres-backend` feature gate on the module declaration in
|
||||||
|
`storage/mod.rs`.
|
||||||
|
|
||||||
|
This sub-plan extends those bodies and adds two siblings: `pool.rs` and
|
||||||
|
`registry.rs` (the latter is a stub here, real body in `0002d`).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Audit step (do this first)
|
||||||
|
|
||||||
|
Before adding `config.rs`, confirm there is no existing top-level config
|
||||||
|
loader. Run from the repo root:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
rg -nF 'VestigeConfig' crates/
|
||||||
|
rg -nF 'toml::from_str' crates/
|
||||||
|
rg -n '#\[derive.*Deserialize.*\]' crates/vestige-core/src/
|
||||||
|
```
|
||||||
|
|
||||||
|
If a `VestigeConfig` struct already exists from Phase 1, treat the "Config
|
||||||
|
module" section below as additive: extend the existing struct rather than
|
||||||
|
creating a new file. The cross-cut additions in that case are:
|
||||||
|
|
||||||
|
1. Add the `StorageConfig` enum (gated and ungated branches).
|
||||||
|
2. Add `SqliteConfig`, `PostgresConfig`.
|
||||||
|
3. Add the `default_path()` helper if missing.
|
||||||
|
4. Add `ConfigError` if a different error enum is used today (rename/extend
|
||||||
|
instead of duplicating).
|
||||||
|
|
||||||
|
As of the audit at the time of this writing, no `VestigeConfig` exists in
|
||||||
|
`vestige-core`. `directories::ProjectDirs` is already used in
|
||||||
|
`vestige-core/src/embeddings/local.rs` and in
|
||||||
|
`vestige-mcp/src/protocol/auth.rs`, so the `directories` crate is already a
|
||||||
|
workspace dependency -- no new dep there.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Cargo manifest additions
|
||||||
|
|
||||||
|
Add `toml` to `vestige-core`. `serde` and `thiserror` are already present
|
||||||
|
from Phase 1; `directories` is already a transitive dep but we add it
|
||||||
|
explicitly so `default_path()` is supported.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd crates/vestige-core
|
||||||
|
cargo add toml@0.8
|
||||||
|
cargo add directories@5
|
||||||
|
```
|
||||||
|
|
||||||
|
No new deps on `vestige-mcp`; it already depends on `vestige-core`.
|
||||||
|
|
||||||
|
`sqlx` is already added by `0002a` behind the `postgres-backend` feature
|
||||||
|
with `runtime-tokio`, `tls-rustls`, `postgres`, `uuid`, `chrono`,
|
||||||
|
`json`, `macros`, `migrate` features. The pool module only uses what is
|
||||||
|
already pulled in.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Config module
|
||||||
|
|
||||||
|
**File**: `crates/vestige-core/src/config.rs` (new).
|
||||||
|
**Re-exported** from `crates/vestige-core/src/lib.rs` as `pub mod config;` plus
|
||||||
|
`pub use config::{VestigeConfig, StorageConfig, SqliteConfig, EmbeddingsConfig, ConfigError};`
|
||||||
|
and `#[cfg(feature = "postgres-backend")] pub use config::PostgresConfig;`.
|
||||||
|
|
||||||
|
Full content:
|
||||||
|
|
||||||
|
```rust
|
||||||
|
//! Vestige top-level configuration.
|
||||||
|
//!
|
||||||
|
//! Loaded from `~/.vestige/vestige.toml` by default; the path is overridable
|
||||||
|
//! via `VestigeConfig::load(Some(&path))`. Parsing uses serde + toml; the
|
||||||
|
//! `[storage]` section is internally-tagged on a `backend` field so a single
|
||||||
|
//! enum dispatch picks SQLite or Postgres.
|
||||||
|
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
|
use serde::Deserialize;
|
||||||
|
|
||||||
|
/// Top-level configuration as parsed from `vestige.toml`.
|
||||||
|
#[derive(Debug, Clone, Deserialize, Default)]
|
||||||
|
#[serde(default, deny_unknown_fields)]
|
||||||
|
pub struct VestigeConfig {
|
||||||
|
pub embeddings: EmbeddingsConfig,
|
||||||
|
pub storage: StorageConfig,
|
||||||
|
/// Reserved for Phase 3. Empty in Phase 2.
|
||||||
|
pub server: ServerConfig,
|
||||||
|
/// Reserved for Phase 3. Empty in Phase 2.
|
||||||
|
pub auth: AuthConfig,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Embedding provider selection.
|
||||||
|
#[derive(Debug, Clone, Deserialize)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
|
pub struct EmbeddingsConfig {
|
||||||
|
/// Provider key. Phase 2 ships `"fastembed"` only.
|
||||||
|
pub provider: String,
|
||||||
|
/// Model name. For fastembed this is e.g. `"nomic-ai/nomic-embed-text-v1.5"`.
|
||||||
|
pub model: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for EmbeddingsConfig {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self {
|
||||||
|
provider: "fastembed".to_string(),
|
||||||
|
model: crate::DEFAULT_EMBEDDING_MODEL.to_string(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Storage backend selection. Internally tagged on the `backend` field:
|
||||||
|
///
|
||||||
|
/// ```toml
|
||||||
|
/// [storage]
|
||||||
|
/// backend = "sqlite"
|
||||||
|
///
|
||||||
|
/// [storage.sqlite]
|
||||||
|
/// path = "/home/user/.vestige/vestige.db"
|
||||||
|
/// ```
|
||||||
|
///
|
||||||
|
/// or, when compiled with `--features postgres-backend`:
|
||||||
|
///
|
||||||
|
/// ```toml
|
||||||
|
/// [storage]
|
||||||
|
/// backend = "postgres"
|
||||||
|
///
|
||||||
|
/// [storage.postgres]
|
||||||
|
/// url = "postgres://vestige:secret@localhost:5432/vestige"
|
||||||
|
/// max_connections = 10
|
||||||
|
/// acquire_timeout_secs = 30
|
||||||
|
/// ```
|
||||||
|
#[derive(Debug, Clone, Deserialize)]
|
||||||
|
#[serde(tag = "backend", rename_all = "lowercase", deny_unknown_fields)]
|
||||||
|
pub enum StorageConfig {
|
||||||
|
Sqlite(SqliteConfig),
|
||||||
|
#[cfg(feature = "postgres-backend")]
|
||||||
|
Postgres(PostgresConfig),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for StorageConfig {
|
||||||
|
fn default() -> Self {
|
||||||
|
StorageConfig::Sqlite(SqliteConfig::default())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// SQLite backend configuration.
|
||||||
|
#[derive(Debug, Clone, Deserialize)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
|
pub struct SqliteConfig {
|
||||||
|
/// Path to the `vestige.db` file. If unset, the SqliteMemoryStore
|
||||||
|
/// constructor picks its platform default location.
|
||||||
|
#[serde(default)]
|
||||||
|
pub path: Option<PathBuf>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for SqliteConfig {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self { path: None }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Postgres backend configuration. Only present when the `postgres-backend`
|
||||||
|
/// Cargo feature is enabled.
|
||||||
|
#[cfg(feature = "postgres-backend")]
|
||||||
|
#[derive(Debug, Clone, Deserialize)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
|
pub struct PostgresConfig {
|
||||||
|
/// `postgres://user:pass@host:port/db` -- forwarded to
|
||||||
|
/// `PgConnectOptions::from_str`.
|
||||||
|
pub url: String,
|
||||||
|
/// Pool size. Default `10`.
|
||||||
|
#[serde(default)]
|
||||||
|
pub max_connections: Option<u32>,
|
||||||
|
/// Acquire timeout in seconds. Default `30`. Set above 30 so
|
||||||
|
/// testcontainer-based test fixtures do not race.
|
||||||
|
#[serde(default)]
|
||||||
|
pub acquire_timeout_secs: Option<u64>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Reserved for Phase 3 (bind address, ports, TLS).
|
||||||
|
#[derive(Debug, Clone, Default, Deserialize)]
|
||||||
|
#[serde(default, deny_unknown_fields)]
|
||||||
|
pub struct ServerConfig {}
|
||||||
|
|
||||||
|
/// Reserved for Phase 3 (API keys, claims).
|
||||||
|
#[derive(Debug, Clone, Default, Deserialize)]
|
||||||
|
#[serde(default, deny_unknown_fields)]
|
||||||
|
pub struct AuthConfig {}
|
||||||
|
|
||||||
|
/// Errors raised while locating, reading, or parsing `vestige.toml`.
|
||||||
|
#[derive(Debug, thiserror::Error)]
|
||||||
|
pub enum ConfigError {
|
||||||
|
#[error("config io: {0}")]
|
||||||
|
Io(#[from] std::io::Error),
|
||||||
|
#[error("config toml: {0}")]
|
||||||
|
Toml(#[from] toml::de::Error),
|
||||||
|
#[error("config dir: could not locate user home")]
|
||||||
|
NoHome,
|
||||||
|
#[error("invalid config: {0}")]
|
||||||
|
Invalid(String),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl VestigeConfig {
|
||||||
|
/// Load config from `path` or from `default_path()` when `None`.
|
||||||
|
///
|
||||||
|
/// Returns `VestigeConfig::default()` (SQLite + fastembed defaults) when
|
||||||
|
/// the file does not exist. Any other I/O or parse failure is surfaced
|
||||||
|
/// as a `ConfigError`.
|
||||||
|
pub fn load(path: Option<&Path>) -> Result<Self, ConfigError> {
|
||||||
|
let resolved: PathBuf = match path {
|
||||||
|
Some(p) => p.to_path_buf(),
|
||||||
|
None => Self::default_path()?,
|
||||||
|
};
|
||||||
|
|
||||||
|
match std::fs::read_to_string(&resolved) {
|
||||||
|
Ok(text) => {
|
||||||
|
let cfg: VestigeConfig = toml::from_str(&text)?;
|
||||||
|
cfg.validate()?;
|
||||||
|
Ok(cfg)
|
||||||
|
}
|
||||||
|
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
|
||||||
|
Ok(Self::default())
|
||||||
|
}
|
||||||
|
Err(e) => Err(ConfigError::Io(e)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `~/.vestige/vestige.toml`. The directory is NOT created here; loading
|
||||||
|
/// a missing file falls back to defaults.
|
||||||
|
pub fn default_path() -> Result<PathBuf, ConfigError> {
|
||||||
|
let dirs = directories::ProjectDirs::from("", "vestige", "vestige")
|
||||||
|
.ok_or(ConfigError::NoHome)?;
|
||||||
|
// ProjectDirs::config_dir() varies per OS. Vestige convention is
|
||||||
|
// ~/.vestige/vestige.toml on Linux/macOS regardless of XDG, so we
|
||||||
|
// build the path off the home dir explicitly.
|
||||||
|
let home = directories::UserDirs::new()
|
||||||
|
.ok_or(ConfigError::NoHome)?
|
||||||
|
.home_dir()
|
||||||
|
.to_path_buf();
|
||||||
|
let _ = dirs; // keep the dep wired; future Phase 3 may use it
|
||||||
|
Ok(home.join(".vestige").join("vestige.toml"))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Light cross-field validation. Heavy validation (URL parsing,
|
||||||
|
/// directory existence) is left to the backend constructors.
|
||||||
|
fn validate(&self) -> Result<(), ConfigError> {
|
||||||
|
if self.embeddings.provider.is_empty() {
|
||||||
|
return Err(ConfigError::Invalid(
|
||||||
|
"embeddings.provider must not be empty".into(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
if self.embeddings.model.is_empty() {
|
||||||
|
return Err(ConfigError::Invalid(
|
||||||
|
"embeddings.model must not be empty".into(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
match &self.storage {
|
||||||
|
StorageConfig::Sqlite(_) => {}
|
||||||
|
#[cfg(feature = "postgres-backend")]
|
||||||
|
StorageConfig::Postgres(cfg) => {
|
||||||
|
if cfg.url.is_empty() {
|
||||||
|
return Err(ConfigError::Invalid(
|
||||||
|
"storage.postgres.url must not be empty".into(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Serde behaviour with `postgres-backend` off
|
||||||
|
|
||||||
|
`StorageConfig` is generated by serde only for the variants that are
|
||||||
|
compiled in. When `postgres-backend` is off and the user writes:
|
||||||
|
|
||||||
|
```toml
|
||||||
|
[storage]
|
||||||
|
backend = "postgres"
|
||||||
|
|
||||||
|
[storage.postgres]
|
||||||
|
url = "..."
|
||||||
|
```
|
||||||
|
|
||||||
|
serde returns a `toml::de::Error` of the form
|
||||||
|
`unknown variant `postgres`, expected `sqlite``. That error path goes
|
||||||
|
through `From<toml::de::Error> for ConfigError`, surfacing as
|
||||||
|
`ConfigError::Toml(..)`. The MCP server prints this once at startup and
|
||||||
|
exits with a non-zero code; there is no panic.
|
||||||
|
|
||||||
|
To make the error friendlier we wrap that specific case in a clearer
|
||||||
|
message via a thin post-parse check. Add this small helper after parsing
|
||||||
|
in `load()`:
|
||||||
|
|
||||||
|
```rust
|
||||||
|
// (Inside the Ok(text) arm in load(), wrapping the parse step.)
|
||||||
|
let cfg: VestigeConfig = match toml::from_str(&text) {
|
||||||
|
Ok(c) => c,
|
||||||
|
Err(e) => {
|
||||||
|
let msg = e.to_string();
|
||||||
|
if msg.contains("unknown variant `postgres`") {
|
||||||
|
return Err(ConfigError::Invalid(
|
||||||
|
"storage.backend = \"postgres\" requires building with --features postgres-backend".into(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
return Err(ConfigError::Toml(e));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
This keeps the strict default deny_unknown_fields behaviour while giving the
|
||||||
|
user a one-line action item.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Pool module
|
||||||
|
|
||||||
|
**File**: `crates/vestige-core/src/storage/postgres/pool.rs` (new).
|
||||||
|
|
||||||
|
```rust
|
||||||
|
#![cfg(feature = "postgres-backend")]
|
||||||
|
|
||||||
|
//! `PgPool` construction for the Postgres backend.
|
||||||
|
//!
|
||||||
|
//! Pool defaults follow ADR 0002 D2 + master plan D3:
|
||||||
|
//! - max_connections = 10
|
||||||
|
//! - acquire_timeout = 30s (must exceed testcontainer warmup)
|
||||||
|
//! - idle_timeout = 600s
|
||||||
|
//! - max_lifetime = 1800s
|
||||||
|
//! - test_before_acquire = false (cheap queries; saves a roundtrip)
|
||||||
|
|
||||||
|
use std::str::FromStr;
|
||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
|
use sqlx::postgres::{PgConnectOptions, PgPoolOptions};
|
||||||
|
use sqlx::{ConnectOptions, PgPool};
|
||||||
|
|
||||||
|
use crate::config::PostgresConfig;
|
||||||
|
use crate::storage::memory_store::{MemoryStoreError, MemoryStoreResult};
|
||||||
|
|
||||||
|
const DEFAULT_MAX_CONNECTIONS: u32 = 10;
|
||||||
|
const DEFAULT_ACQUIRE_TIMEOUT_SECS: u64 = 30;
|
||||||
|
const IDLE_TIMEOUT_SECS: u64 = 600;
|
||||||
|
const MAX_LIFETIME_SECS: u64 = 1800;
|
||||||
|
const STATEMENT_CACHE_CAPACITY: usize = 256;
|
||||||
|
|
||||||
|
/// Build a Postgres connection pool from a `PostgresConfig`. Does NOT run
|
||||||
|
/// migrations or stamp the embedding registry; those are the caller's job
|
||||||
|
/// (`PgMemoryStore::connect`).
|
||||||
|
pub async fn build_pool(cfg: &PostgresConfig) -> MemoryStoreResult<PgPool> {
|
||||||
|
let opts = PgConnectOptions::from_str(&cfg.url)
|
||||||
|
.map_err(MemoryStoreError::from)?
|
||||||
|
.application_name("vestige")
|
||||||
|
.statement_cache_capacity(STATEMENT_CACHE_CAPACITY)
|
||||||
|
.log_statements(tracing::log::LevelFilter::Debug);
|
||||||
|
|
||||||
|
let max_conn = cfg.max_connections.unwrap_or(DEFAULT_MAX_CONNECTIONS);
|
||||||
|
let acquire = cfg
|
||||||
|
.acquire_timeout_secs
|
||||||
|
.unwrap_or(DEFAULT_ACQUIRE_TIMEOUT_SECS);
|
||||||
|
|
||||||
|
let pool = PgPoolOptions::new()
|
||||||
|
.max_connections(max_conn)
|
||||||
|
.min_connections(0)
|
||||||
|
.acquire_timeout(Duration::from_secs(acquire))
|
||||||
|
.idle_timeout(Some(Duration::from_secs(IDLE_TIMEOUT_SECS)))
|
||||||
|
.max_lifetime(Some(Duration::from_secs(MAX_LIFETIME_SECS)))
|
||||||
|
.test_before_acquire(false)
|
||||||
|
.connect_with(opts)
|
||||||
|
.await
|
||||||
|
.map_err(MemoryStoreError::from)?;
|
||||||
|
|
||||||
|
Ok(pool)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Wiring into `PgMemoryStore::connect`
|
||||||
|
|
||||||
|
In `crates/vestige-core/src/storage/postgres/mod.rs`, replace the
|
||||||
|
`todo!()` body left by `0002a` for `connect` and `from_pool` with:
|
||||||
|
|
||||||
|
```rust
|
||||||
|
// In crates/vestige-core/src/storage/postgres/mod.rs
|
||||||
|
|
||||||
|
use sqlx::PgPool;
|
||||||
|
|
||||||
|
use crate::config::PostgresConfig;
|
||||||
|
use crate::storage::memory_store::{MemoryStoreError, MemoryStoreResult};
|
||||||
|
|
||||||
|
mod pool;
|
||||||
|
mod registry; // see "Registry stub" section below
|
||||||
|
|
||||||
|
pub struct PgMemoryStore {
|
||||||
|
pool: PgPool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl PgMemoryStore {
|
||||||
|
/// Convenience constructor matching `SqliteMemoryStore::new` shape.
|
||||||
|
/// Takes a URL + pool size for the common case.
|
||||||
|
pub async fn connect(url: &str, max_connections: u32) -> MemoryStoreResult<Self> {
|
||||||
|
let cfg = PostgresConfig {
|
||||||
|
url: url.to_string(),
|
||||||
|
max_connections: Some(max_connections),
|
||||||
|
acquire_timeout_secs: None,
|
||||||
|
};
|
||||||
|
Self::connect_with(&cfg).await
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Full-config constructor.
|
||||||
|
pub async fn connect_with(cfg: &PostgresConfig) -> MemoryStoreResult<Self> {
|
||||||
|
let pool = pool::build_pool(cfg).await?;
|
||||||
|
Self::from_pool(pool).await
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Construct from an already-built pool (used by tests and the migrate
|
||||||
|
/// CLI to share a pool across operations).
|
||||||
|
pub async fn from_pool(pool: PgPool) -> MemoryStoreResult<Self> {
|
||||||
|
// Migrations are added by 0002c.
|
||||||
|
// todo!("run sqlx::migrate! once 0002c lands")
|
||||||
|
registry::ensure_registry_stub(&pool).await?;
|
||||||
|
Ok(Self { pool })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
`connect_with` is the long-lived API; `connect` becomes a thin shim that
|
||||||
|
stays compatible with the master-plan-mandated signature.
|
||||||
|
|
||||||
|
### Registry stub
|
||||||
|
|
||||||
|
**File**: `crates/vestige-core/src/storage/postgres/registry.rs` (new, stub).
|
||||||
|
|
||||||
|
```rust
|
||||||
|
#![cfg(feature = "postgres-backend")]
|
||||||
|
|
||||||
|
//! Embedding registry. Real body lands in sub-plan 0002d.
|
||||||
|
|
||||||
|
use sqlx::PgPool;
|
||||||
|
|
||||||
|
use crate::storage::memory_store::MemoryStoreResult;
|
||||||
|
|
||||||
|
/// Placeholder. Real implementation in 0002d reads/writes `embedding_model`
|
||||||
|
/// and stamps `ALTER TABLE memories ALTER COLUMN embedding TYPE vector($N)`.
|
||||||
|
pub(crate) async fn ensure_registry_stub(_pool: &PgPool) -> MemoryStoreResult<()> {
|
||||||
|
// Intentionally a no-op until 0002c lands the table + 0002d lands the
|
||||||
|
// real body. Leaving this as todo!() would crash the MCP server at
|
||||||
|
// startup the moment a user switches `backend = "postgres"`, which is
|
||||||
|
// not what we want for the build verification step in this sub-plan.
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
The no-op keeps `cargo build --features postgres-backend` not just
|
||||||
|
compiling but also allowing the MCP server to *boot* against a Postgres
|
||||||
|
URL pointing at an already-migrated database (the local-dev-postgres-setup
|
||||||
|
docs cover bringing up such a DB by hand). Real init lands in `0002d`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Error variants
|
||||||
|
|
||||||
|
**File**: `crates/vestige-core/src/storage/memory_store.rs` (edit).
|
||||||
|
|
||||||
|
The Phase 1 enum `MemoryStoreError` gains two feature-gated variants. These
|
||||||
|
were deferred in `0002a` and become required as soon as `pool.rs` calls
|
||||||
|
`.map_err(MemoryStoreError::from)` on `sqlx::Error`.
|
||||||
|
|
||||||
|
```rust
|
||||||
|
// Within enum MemoryStoreError { ... } in memory_store.rs
|
||||||
|
|
||||||
|
#[cfg(feature = "postgres-backend")]
|
||||||
|
#[error("postgres error: {0}")]
|
||||||
|
Postgres(#[from] sqlx::Error),
|
||||||
|
|
||||||
|
#[cfg(feature = "postgres-backend")]
|
||||||
|
#[error("postgres migration error: {0}")]
|
||||||
|
Migrate(#[from] sqlx::migrate::MigrateError),
|
||||||
|
```
|
||||||
|
|
||||||
|
Both use thiserror's `#[from]` attribute so the `?` operator works in
|
||||||
|
`pool.rs`, the migrate module (`0002c`), and registry code (`0002d`).
|
||||||
|
Default-features build (no `postgres-backend`) sees neither variant; the
|
||||||
|
enum stays exhaustive on stable.
|
||||||
|
|
||||||
|
If clippy fires on `non_exhaustive` due to the gated variants, add
|
||||||
|
`#[non_exhaustive]` on the enum. That has no caller-side effect since the
|
||||||
|
enum is constructed only inside the crate.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## vestige-mcp wiring
|
||||||
|
|
||||||
|
### Cargo feature passthrough
|
||||||
|
|
||||||
|
**File**: `crates/vestige-mcp/Cargo.toml` (edit).
|
||||||
|
|
||||||
|
Add a feature that forwards through to `vestige-core`. Default features in
|
||||||
|
`vestige-mcp` stay unchanged.
|
||||||
|
|
||||||
|
```toml
|
||||||
|
[features]
|
||||||
|
default = ["embeddings", "vector-search"]
|
||||||
|
embeddings = ["vestige-core/embeddings"]
|
||||||
|
vector-search = ["vestige-core/vector-search"]
|
||||||
|
postgres-backend = ["vestige-core/postgres-backend"]
|
||||||
|
```
|
||||||
|
|
||||||
|
Verify with:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cargo build -p vestige-mcp --features postgres-backend
|
||||||
|
```
|
||||||
|
|
||||||
|
### Backend dispatch at startup
|
||||||
|
|
||||||
|
**File**: `crates/vestige-mcp/src/main.rs` (edit around the existing
|
||||||
|
`Storage::new(storage_path)` call -- see audit note above; in the current
|
||||||
|
worktree this is around line 285).
|
||||||
|
|
||||||
|
The current code is roughly:
|
||||||
|
|
||||||
|
```rust
|
||||||
|
let storage_path = match prepare_storage_path(config.data_dir) { ... };
|
||||||
|
let storage = match Storage::new(storage_path) { ... };
|
||||||
|
```
|
||||||
|
|
||||||
|
Replace that with a dispatch driven by `VestigeConfig`:
|
||||||
|
|
||||||
|
```rust
|
||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
use vestige_core::config::{StorageConfig, VestigeConfig};
|
||||||
|
use vestige_core::storage::SqliteMemoryStore;
|
||||||
|
#[cfg(feature = "postgres-backend")]
|
||||||
|
use vestige_core::storage::postgres::PgMemoryStore;
|
||||||
|
use vestige_core::storage::MemoryStore;
|
||||||
|
|
||||||
|
// Earlier: still call prepare_storage_path to honour --data-dir override.
|
||||||
|
let storage_path = match prepare_storage_path(config.data_dir.clone()) { ... };
|
||||||
|
|
||||||
|
// New: load vestige.toml (or fall back to defaults).
|
||||||
|
let vestige_cfg = match VestigeConfig::load(config.config_path.as_deref()) {
|
||||||
|
Ok(c) => c,
|
||||||
|
Err(e) => {
|
||||||
|
eprintln!("vestige: failed to load config: {e}");
|
||||||
|
std::process::exit(2);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let storage: Arc<dyn MemoryStore> = match &vestige_cfg.storage {
|
||||||
|
StorageConfig::Sqlite(sqlite_cfg) => {
|
||||||
|
// CLI flag --data-dir wins over the config file path.
|
||||||
|
let path = storage_path.clone().or_else(|| sqlite_cfg.path.clone());
|
||||||
|
let s = SqliteMemoryStore::new(path).unwrap_or_else(|e| {
|
||||||
|
eprintln!("vestige: sqlite init failed: {e}");
|
||||||
|
std::process::exit(3);
|
||||||
|
});
|
||||||
|
Arc::new(s)
|
||||||
|
}
|
||||||
|
#[cfg(feature = "postgres-backend")]
|
||||||
|
StorageConfig::Postgres(pg_cfg) => {
|
||||||
|
let s = PgMemoryStore::connect_with(pg_cfg).await.unwrap_or_else(|e| {
|
||||||
|
eprintln!("vestige: postgres init failed: {e}");
|
||||||
|
std::process::exit(3);
|
||||||
|
});
|
||||||
|
Arc::new(s)
|
||||||
|
}
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
The `config_path: Option<PathBuf>` field on the local `Config` (or
|
||||||
|
clap-derived `Args`) struct must be added if not present; it accepts
|
||||||
|
`--config <path>`. Default behaviour (no flag) goes through
|
||||||
|
`VestigeConfig::default_path()`.
|
||||||
|
|
||||||
|
If the existing main wires `Storage` through a concrete type rather than
|
||||||
|
`Arc<dyn MemoryStore>`, the dispatch above lives behind a helper:
|
||||||
|
|
||||||
|
```rust
|
||||||
|
async fn build_store(cfg: &VestigeConfig, cli_path: Option<PathBuf>)
|
||||||
|
-> Result<Arc<dyn MemoryStore>, anyhow::Error>
|
||||||
|
{ ... }
|
||||||
|
```
|
||||||
|
|
||||||
|
and the caller chains `.into()` as needed. Phase 1 already moved
|
||||||
|
cognitive modules to `Arc<dyn MemoryStore>` so this should be a pure
|
||||||
|
substitution; if a concrete-type holdout is found, fix it locally in this
|
||||||
|
sub-plan (separate commit) rather than punting.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## vestige.toml example
|
||||||
|
|
||||||
|
The canonical example to ship in `docs/` (Phase 2 docs land in `0002i`,
|
||||||
|
runbook), shown here for reference and used verbatim by the unit test
|
||||||
|
below.
|
||||||
|
|
||||||
|
```toml
|
||||||
|
# vestige.toml -- top-level configuration
|
||||||
|
#
|
||||||
|
# Default location: ~/.vestige/vestige.toml
|
||||||
|
# Override: vestige-mcp --config /path/to/vestige.toml
|
||||||
|
|
||||||
|
[embeddings]
|
||||||
|
provider = "fastembed"
|
||||||
|
model = "nomic-ai/nomic-embed-text-v1.5"
|
||||||
|
|
||||||
|
# --- SQLite backend (default) ---
|
||||||
|
[storage]
|
||||||
|
backend = "sqlite"
|
||||||
|
|
||||||
|
[storage.sqlite]
|
||||||
|
path = "/home/user/.vestige/vestige.db"
|
||||||
|
|
||||||
|
# --- Postgres backend (requires --features postgres-backend) ---
|
||||||
|
# [storage]
|
||||||
|
# backend = "postgres"
|
||||||
|
#
|
||||||
|
# [storage.postgres]
|
||||||
|
# url = "postgres://vestige:secret@localhost:5432/vestige"
|
||||||
|
# max_connections = 10
|
||||||
|
# acquire_timeout_secs = 30
|
||||||
|
|
||||||
|
[server]
|
||||||
|
# Reserved for Phase 3 (bind address, ports, TLS).
|
||||||
|
|
||||||
|
[auth]
|
||||||
|
# Reserved for Phase 3 (API keys, claims).
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Verification
|
||||||
|
|
||||||
|
Run all of these from the repo root. The first three are the gates that
|
||||||
|
must pass before this sub-plan is considered done.
|
||||||
|
|
||||||
|
### 1. Default build (no Postgres)
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cargo build -p vestige-core
|
||||||
|
cargo build -p vestige-mcp
|
||||||
|
cargo test -p vestige-core --lib
|
||||||
|
```
|
||||||
|
|
||||||
|
Expected: clean build. `VestigeConfig::default()` selects SQLite; the MCP
|
||||||
|
server boots the same way it did pre-sub-plan.
|
||||||
|
|
||||||
|
### 2. Postgres-feature build
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cargo build -p vestige-core --features postgres-backend
|
||||||
|
cargo build -p vestige-mcp --features postgres-backend
|
||||||
|
```
|
||||||
|
|
||||||
|
Expected: clean build. `PgMemoryStore::connect_with` resolves to
|
||||||
|
`pool::build_pool` + `registry::ensure_registry_stub`; no `todo!()` is
|
||||||
|
reachable on the build path. `connect` and `from_pool` are exported.
|
||||||
|
|
||||||
|
### 3. Clippy across both feature sets
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cargo clippy -p vestige-core -- -D warnings
|
||||||
|
cargo clippy -p vestige-core --features postgres-backend -- -D warnings
|
||||||
|
cargo clippy -p vestige-mcp --features postgres-backend -- -D warnings
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4. Unit test: round-trip the example
|
||||||
|
|
||||||
|
Add this test to `crates/vestige-core/src/config.rs`:
|
||||||
|
|
||||||
|
```rust
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
const EXAMPLE_SQLITE: &str = r#"
|
||||||
|
[embeddings]
|
||||||
|
provider = "fastembed"
|
||||||
|
model = "nomic-ai/nomic-embed-text-v1.5"
|
||||||
|
|
||||||
|
[storage]
|
||||||
|
backend = "sqlite"
|
||||||
|
|
||||||
|
[storage.sqlite]
|
||||||
|
path = "/home/user/.vestige/vestige.db"
|
||||||
|
"#;
|
||||||
|
|
||||||
|
#[cfg(feature = "postgres-backend")]
|
||||||
|
const EXAMPLE_POSTGRES: &str = r#"
|
||||||
|
[embeddings]
|
||||||
|
provider = "fastembed"
|
||||||
|
model = "nomic-ai/nomic-embed-text-v1.5"
|
||||||
|
|
||||||
|
[storage]
|
||||||
|
backend = "postgres"
|
||||||
|
|
||||||
|
[storage.postgres]
|
||||||
|
url = "postgres://vestige:secret@localhost:5432/vestige"
|
||||||
|
max_connections = 10
|
||||||
|
acquire_timeout_secs = 30
|
||||||
|
"#;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn parses_sqlite_example() {
|
||||||
|
let cfg: VestigeConfig = toml::from_str(EXAMPLE_SQLITE).expect("parse");
|
||||||
|
match cfg.storage {
|
||||||
|
StorageConfig::Sqlite(s) => assert!(s.path.is_some()),
|
||||||
|
#[cfg(feature = "postgres-backend")]
|
||||||
|
StorageConfig::Postgres(_) => panic!("wrong variant"),
|
||||||
|
}
|
||||||
|
assert_eq!(cfg.embeddings.provider, "fastembed");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "postgres-backend")]
|
||||||
|
#[test]
|
||||||
|
fn parses_postgres_example() {
|
||||||
|
let cfg: VestigeConfig = toml::from_str(EXAMPLE_POSTGRES).expect("parse");
|
||||||
|
match cfg.storage {
|
||||||
|
StorageConfig::Postgres(p) => {
|
||||||
|
assert_eq!(p.url, "postgres://vestige:secret@localhost:5432/vestige");
|
||||||
|
assert_eq!(p.max_connections, Some(10));
|
||||||
|
assert_eq!(p.acquire_timeout_secs, Some(30));
|
||||||
|
}
|
||||||
|
StorageConfig::Sqlite(_) => panic!("wrong variant"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(not(feature = "postgres-backend"))]
|
||||||
|
#[test]
|
||||||
|
fn rejects_postgres_when_feature_off() {
|
||||||
|
let toml_text = r#"
|
||||||
|
[storage]
|
||||||
|
backend = "postgres"
|
||||||
|
|
||||||
|
[storage.postgres]
|
||||||
|
url = "postgres://x/y"
|
||||||
|
"#;
|
||||||
|
let res: Result<VestigeConfig, _> = toml::from_str(toml_text);
|
||||||
|
assert!(res.is_err(), "must fail without postgres-backend feature");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn defaults_pick_sqlite() {
|
||||||
|
let cfg = VestigeConfig::default();
|
||||||
|
assert!(matches!(cfg.storage, StorageConfig::Sqlite(_)));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn load_missing_file_returns_default() {
|
||||||
|
let tmp = std::env::temp_dir().join("vestige-no-such-file.toml");
|
||||||
|
let _ = std::fs::remove_file(&tmp);
|
||||||
|
let cfg = VestigeConfig::load(Some(&tmp)).expect("missing file is OK");
|
||||||
|
assert!(matches!(cfg.storage, StorageConfig::Sqlite(_)));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn load_roundtrip_from_disk() {
|
||||||
|
let tmp = std::env::temp_dir().join("vestige-roundtrip.toml");
|
||||||
|
std::fs::write(&tmp, EXAMPLE_SQLITE).unwrap();
|
||||||
|
let cfg = VestigeConfig::load(Some(&tmp)).expect("load");
|
||||||
|
assert!(matches!(cfg.storage, StorageConfig::Sqlite(_)));
|
||||||
|
let _ = std::fs::remove_file(&tmp);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Run:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cargo test -p vestige-core --lib config::
|
||||||
|
cargo test -p vestige-core --lib config:: --features postgres-backend
|
||||||
|
```
|
||||||
|
|
||||||
|
### 5. Smoke: server boots with default config
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# default build, no vestige.toml on disk
|
||||||
|
cargo run -p vestige-mcp -- --help
|
||||||
|
# should print help, no panic
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Acceptance criteria
|
||||||
|
|
||||||
|
- [ ] `cargo build -p vestige-core` (default features) succeeds.
|
||||||
|
- [ ] `cargo build -p vestige-core --features postgres-backend` succeeds.
|
||||||
|
- [ ] `cargo build -p vestige-mcp` (default features) succeeds.
|
||||||
|
- [ ] `cargo build -p vestige-mcp --features postgres-backend` succeeds.
|
||||||
|
- [ ] `cargo clippy` with and without `postgres-backend` is clean on both
|
||||||
|
crates.
|
||||||
|
- [ ] `crates/vestige-core/src/config.rs` exists, exposes
|
||||||
|
`VestigeConfig`, `StorageConfig`, `SqliteConfig`, `EmbeddingsConfig`,
|
||||||
|
`ConfigError`, plus `PostgresConfig` when the feature is on.
|
||||||
|
- [ ] `VestigeConfig::load(None)` returns `Ok(default)` when
|
||||||
|
`~/.vestige/vestige.toml` is missing.
|
||||||
|
- [ ] `VestigeConfig::load(Some(&path))` round-trips both the SQLite and
|
||||||
|
Postgres example blocks above.
|
||||||
|
- [ ] With `postgres-backend` off, parsing `backend = "postgres"` returns
|
||||||
|
a clear `ConfigError::Invalid` mentioning the feature flag, NOT a
|
||||||
|
panic.
|
||||||
|
- [ ] `crates/vestige-core/src/storage/postgres/pool.rs` exists,
|
||||||
|
implementing `build_pool(&PostgresConfig) -> MemoryStoreResult<PgPool>`
|
||||||
|
with the documented defaults.
|
||||||
|
- [ ] `PgMemoryStore::connect`, `connect_with`, and `from_pool` all wire
|
||||||
|
through `pool::build_pool`. None of them is `todo!()`. The registry
|
||||||
|
step is a no-op stub documented as filled in by `0002d`.
|
||||||
|
- [ ] `MemoryStoreError::Postgres(sqlx::Error)` and
|
||||||
|
`MemoryStoreError::Migrate(sqlx::migrate::MigrateError)` exist
|
||||||
|
behind `#[cfg(feature = "postgres-backend")]` with `#[from]`.
|
||||||
|
- [ ] `vestige-mcp` has a `postgres-backend` feature that forwards to
|
||||||
|
`vestige-core/postgres-backend`.
|
||||||
|
- [ ] `vestige-mcp/src/main.rs` selects SQLite vs Postgres at startup
|
||||||
|
based on `VestigeConfig`. SQLite is the default when no config file
|
||||||
|
is present.
|
||||||
|
- [ ] Unit tests in the "Verification" section pass on both feature sets.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Out of scope (handled by other sub-plans)
|
||||||
|
|
||||||
|
- Migrations (`crates/vestige-core/migrations/postgres/*.sql`) -- `0002c`.
|
||||||
|
- Real `PgMemoryStore` CRUD/search/scheduling/edges bodies -- `0002d`,
|
||||||
|
`0002e`.
|
||||||
|
- `ensure_registry` real body with `ALTER COLUMN TYPE vector(N)` -- `0002d`.
|
||||||
|
- `vestige migrate --from sqlite --to postgres` CLI -- `0002f`.
|
||||||
|
- Re-embed flow -- `0002g`.
|
||||||
|
- Env-var override (`VESTIGE_POSTGRES_URL`, etc.) -- Phase 3.
|
||||||
|
- RLS, multi-tenant column population -- Phase 3.
|
||||||
1119
docs/plans/0002c-migrations.md
Normal file
1119
docs/plans/0002c-migrations.md
Normal file
File diff suppressed because it is too large
Load diff
1771
docs/plans/0002d-store-impl-bodies.md
Normal file
1771
docs/plans/0002d-store-impl-bodies.md
Normal file
File diff suppressed because it is too large
Load diff
825
docs/plans/0002e-hybrid-search.md
Normal file
825
docs/plans/0002e-hybrid-search.md
Normal file
|
|
@ -0,0 +1,825 @@
|
||||||
|
# Phase 2 Sub-Plan 0002e -- Hybrid RRF Search
|
||||||
|
|
||||||
|
**Status**: Ready
|
||||||
|
**Depends on**:
|
||||||
|
- `0002a-skeleton-and-feature-gate.md` (the `postgres-backend` feature flag
|
||||||
|
exists and `PgMemoryStore` compiles with `todo!()` bodies).
|
||||||
|
- `0002b-pool-and-config.md` (a working `PgPool` reaches the backend).
|
||||||
|
- `0002c-migrations.md` (migration `0001_init` has created the `knowledge_nodes`
|
||||||
|
table with the D7 columns -- `owner_user_id`, `visibility`,
|
||||||
|
`shared_with_groups` -- and the D8 column `codebase`; migration `0002_hnsw`
|
||||||
|
has built the HNSW index).
|
||||||
|
- `0002d-store-impl-bodies.md` (real CRUD bodies exist so the integration
|
||||||
|
tests below can seed data through the trait surface rather than raw SQL).
|
||||||
|
|
||||||
|
This sub-plan covers master plan 0002 deliverable D5: the hybrid RRF search
|
||||||
|
query implementation in `crates/vestige-core/src/storage/postgres/search.rs`,
|
||||||
|
plus the `search`, `fts_search`, and `vector_search` method bodies in
|
||||||
|
`crates/vestige-core/src/storage/postgres/mod.rs` that delegate into it.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Context
|
||||||
|
|
||||||
|
This is one of the more performance-sensitive sub-plans in Phase 2. Every
|
||||||
|
search call from the cognitive engine -- the 7-stage retrieval pipeline,
|
||||||
|
`session_context`, `predict`, `deep_reference`, the dashboard -- bottoms out
|
||||||
|
in `MemoryStore::search`. The Postgres backend has to keep up with the
|
||||||
|
existing SQLite hybrid path, which combines BM25 over FTS5 with USearch HNSW
|
||||||
|
in two separate round trips and fuses the rankings in Rust.
|
||||||
|
|
||||||
|
The shape of the win on Postgres is that both branches and the fusion run
|
||||||
|
inside one statement. The planner sees both CTEs together, the round trip is
|
||||||
|
single, and the rerank stage runs over a cleanly overfetched candidate set.
|
||||||
|
|
||||||
|
Latency targets live in `0002h-testing-and-benches.md`. This sub-plan is
|
||||||
|
responsible for producing a correct, schema-stable query that the benches
|
||||||
|
can drive against. Do not optimise here; correctness and structure first.
|
||||||
|
|
||||||
|
Master plan 0002 D5 (around lines 522-628 of
|
||||||
|
`docs/plans/0002-phase-2-postgres-backend.md`) sketches the SQL. That
|
||||||
|
sketch is the starting point, not the finished product. The schema after
|
||||||
|
the D7 and D8 amendments has more columns than the sketch enumerates, and
|
||||||
|
the SQLite `search` method (around line 6503 of
|
||||||
|
`crates/vestige-core/src/storage/sqlite.rs` in the Phase 1 worktree)
|
||||||
|
documents the semantics this implementation must stay compatible with:
|
||||||
|
|
||||||
|
- Empty `query.limit` defaults to 10.
|
||||||
|
- `query.text == Some("")` is treated as no text query (degrade to vector).
|
||||||
|
- `query.embedding == None` is treated as no vector query (degrade to FTS).
|
||||||
|
- Both empty returns `Ok(vec![])`; not an error.
|
||||||
|
- The `MemoryRecord` in each `SearchResult` must be populated with all
|
||||||
|
fields the trait promises, including `domains` and `domain_scores` (Phase
|
||||||
|
4 will fill these in; Phase 2 returns the stored values, which may be
|
||||||
|
empty arrays / empty objects).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Constants
|
||||||
|
|
||||||
|
```rust
|
||||||
|
/// Reciprocal Rank Fusion smoothing constant from Cormack, Clarke and Buettcher
|
||||||
|
/// 2009 ("Reciprocal Rank Fusion outperforms Condorcet and individual rank
|
||||||
|
/// learning methods"). 60 is the canonical default and is robust across most
|
||||||
|
/// fusion regimes. Do not tune this without a paper-citation-grade reason.
|
||||||
|
const RRF_K: i32 = 60;
|
||||||
|
|
||||||
|
/// Each branch (FTS, vector) is allowed to return OVERFETCH_MULT x final_limit
|
||||||
|
/// rows before fusion. Three matches the Phase 1 SQLite overfetch and gives
|
||||||
|
/// the fusion enough candidates to recover from any single branch's bad
|
||||||
|
/// recall on a given query.
|
||||||
|
const OVERFETCH_MULT: i64 = 3;
|
||||||
|
```
|
||||||
|
|
||||||
|
These live at module scope in
|
||||||
|
`crates/vestige-core/src/storage/postgres/search.rs`. They are `pub(crate)`
|
||||||
|
only if `0002h-testing-and-benches.md` needs to reference them from the
|
||||||
|
integration tests; otherwise private.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Public API
|
||||||
|
|
||||||
|
```rust
|
||||||
|
#![cfg(feature = "postgres-backend")]
|
||||||
|
|
||||||
|
use pgvector::Vector;
|
||||||
|
use sqlx::PgPool;
|
||||||
|
|
||||||
|
use crate::storage::memory_store::{
|
||||||
|
MemoryStoreResult, SearchQuery, SearchResult,
|
||||||
|
};
|
||||||
|
|
||||||
|
/// Hybrid RRF search over Postgres FTS and pgvector cosine distance.
|
||||||
|
///
|
||||||
|
/// Branch behavior:
|
||||||
|
/// - empty text + null embedding -> Ok(vec![])
|
||||||
|
/// - empty text + Some(embedding) -> pure vector search (FTS CTE returns
|
||||||
|
/// zero rows; fusion equals the vector
|
||||||
|
/// branch)
|
||||||
|
/// - Some(text) + null embedding -> pure FTS search
|
||||||
|
/// - Some(text) + Some(embedding) -> full RRF fusion
|
||||||
|
///
|
||||||
|
/// `query.limit == 0` is treated as 10 (matches the SQLite default).
|
||||||
|
pub(crate) async fn rrf_search(
|
||||||
|
pool: &PgPool,
|
||||||
|
query: &SearchQuery,
|
||||||
|
) -> MemoryStoreResult<Vec<SearchResult>>;
|
||||||
|
|
||||||
|
/// FTS-only convenience search. Equivalent to calling `rrf_search` with
|
||||||
|
/// `query.embedding = None`, but uses a dedicated single-branch query that
|
||||||
|
/// avoids the FULL OUTER JOIN and the params CTE; faster by one planner pass
|
||||||
|
/// per call.
|
||||||
|
pub(crate) async fn fts_only(
|
||||||
|
pool: &PgPool,
|
||||||
|
text: &str,
|
||||||
|
limit: usize,
|
||||||
|
) -> MemoryStoreResult<Vec<SearchResult>>;
|
||||||
|
|
||||||
|
/// Vector-only convenience search. Dedicated single-branch query for the same
|
||||||
|
/// latency reason as `fts_only`.
|
||||||
|
pub(crate) async fn vector_only(
|
||||||
|
pool: &PgPool,
|
||||||
|
embedding: &[f32],
|
||||||
|
limit: usize,
|
||||||
|
) -> MemoryStoreResult<Vec<SearchResult>>;
|
||||||
|
```
|
||||||
|
|
||||||
|
### Parameter handling
|
||||||
|
|
||||||
|
In `rrf_search`:
|
||||||
|
|
||||||
|
```rust
|
||||||
|
let final_limit: i32 = if query.limit == 0 { 10 } else { query.limit as i32 };
|
||||||
|
let overfetch: i32 = (final_limit as i64 * OVERFETCH_MULT)
|
||||||
|
.min(i32::MAX as i64) as i32;
|
||||||
|
|
||||||
|
let q_text: &str = query.text.as_deref().unwrap_or("");
|
||||||
|
let q_vec: Option<Vector> = query.embedding.as_ref()
|
||||||
|
.map(|v| Vector::from(v.clone()));
|
||||||
|
|
||||||
|
let dom_filter: Option<&[String]> = query.domains.as_deref();
|
||||||
|
let nt_filter: Option<&[String]> = query.node_types.as_deref();
|
||||||
|
let tag_filter: Option<&[String]> = query.tags.as_deref();
|
||||||
|
|
||||||
|
let min_retr: Option<f64> = query.min_retrievability;
|
||||||
|
```
|
||||||
|
|
||||||
|
Both branches empty -- `q_text` is empty and `q_vec` is `None` -- returns
|
||||||
|
`Ok(vec![])` without hitting the database. The SQLite backend has the same
|
||||||
|
behavior and tests rely on it.
|
||||||
|
|
||||||
|
```rust
|
||||||
|
if q_text.is_empty() && q_vec.is_none() {
|
||||||
|
return Ok(Vec::new());
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### `search` method body in `postgres/mod.rs`
|
||||||
|
|
||||||
|
```rust
|
||||||
|
#[async_trait::async_trait] // or trait_variant after the Phase 1 amendment
|
||||||
|
impl MemoryStore for PgMemoryStore {
|
||||||
|
async fn search(&self, query: &SearchQuery)
|
||||||
|
-> MemoryStoreResult<Vec<SearchResult>>
|
||||||
|
{
|
||||||
|
crate::storage::postgres::search::rrf_search(&self.pool, query).await
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn fts_search(&self, text: &str, limit: usize)
|
||||||
|
-> MemoryStoreResult<Vec<SearchResult>>
|
||||||
|
{
|
||||||
|
crate::storage::postgres::search::fts_only(&self.pool, text, limit)
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn vector_search(&self, embedding: &[f32], limit: usize)
|
||||||
|
-> MemoryStoreResult<Vec<SearchResult>>
|
||||||
|
{
|
||||||
|
crate::storage::postgres::search::vector_only(&self.pool, embedding, limit)
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Everything below specifies the inside of those three free functions.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## SQL: the hybrid RRF query
|
||||||
|
|
||||||
|
The query is built as one `&'static str` (or `OnceCell<String>`; see "Use
|
||||||
|
of sqlx::query!" below) and reused. Bound parameters are kept to seven
|
||||||
|
through a `params` CTE that the rest of the query references by name --
|
||||||
|
this keeps the SQL readable and stops the bound-parameter count growing
|
||||||
|
with each filter clause.
|
||||||
|
|
||||||
|
Bound parameters:
|
||||||
|
|
||||||
|
- `$1`: text query (TEXT, may be empty)
|
||||||
|
- `$2`: embedding (pgvector::Vector, may be NULL)
|
||||||
|
- `$3`: overfetch limit per branch (INT)
|
||||||
|
- `$4`: final limit (INT)
|
||||||
|
- `$5`: domain filter (TEXT[] or NULL)
|
||||||
|
- `$6`: node_type filter (TEXT[] or NULL)
|
||||||
|
- `$7`: tag filter (TEXT[] or NULL)
|
||||||
|
|
||||||
|
If `min_retrievability.is_some()` the outer SELECT adds a JOIN on
|
||||||
|
`scheduling` and a WHERE clause; that path uses a different prepared
|
||||||
|
statement (see "min_retrievability filter" below) so the simple-path query
|
||||||
|
stays free of the join.
|
||||||
|
|
||||||
|
```sql
|
||||||
|
WITH params AS (
|
||||||
|
SELECT
|
||||||
|
$1::text AS q_text,
|
||||||
|
$2::vector AS q_vec,
|
||||||
|
$3::int AS overfetch,
|
||||||
|
$4::int AS final_limit,
|
||||||
|
$5::text[] AS dom_filter,
|
||||||
|
$6::text[] AS nt_filter,
|
||||||
|
$7::text[] AS tag_filter
|
||||||
|
),
|
||||||
|
fts AS (
|
||||||
|
SELECT
|
||||||
|
m.id,
|
||||||
|
ts_rank_cd(
|
||||||
|
m.search_vec,
|
||||||
|
websearch_to_tsquery('english', p.q_text)
|
||||||
|
) AS score,
|
||||||
|
ROW_NUMBER() OVER (
|
||||||
|
ORDER BY ts_rank_cd(
|
||||||
|
m.search_vec,
|
||||||
|
websearch_to_tsquery('english', p.q_text)
|
||||||
|
) DESC
|
||||||
|
) AS rank
|
||||||
|
FROM knowledge_nodes m
|
||||||
|
CROSS JOIN params p
|
||||||
|
WHERE p.q_text <> ''
|
||||||
|
AND m.search_vec @@ websearch_to_tsquery('english', p.q_text)
|
||||||
|
AND (p.dom_filter IS NULL OR m.domains && p.dom_filter)
|
||||||
|
AND (p.nt_filter IS NULL OR m.node_type = ANY(p.nt_filter))
|
||||||
|
AND (p.tag_filter IS NULL OR m.tags && p.tag_filter)
|
||||||
|
ORDER BY score DESC
|
||||||
|
LIMIT (SELECT overfetch FROM params)
|
||||||
|
),
|
||||||
|
vec AS (
|
||||||
|
SELECT
|
||||||
|
m.id,
|
||||||
|
1.0 - (m.embedding <=> p.q_vec) AS score,
|
||||||
|
ROW_NUMBER() OVER (
|
||||||
|
ORDER BY m.embedding <=> p.q_vec
|
||||||
|
) AS rank
|
||||||
|
FROM knowledge_nodes m
|
||||||
|
CROSS JOIN params p
|
||||||
|
WHERE m.embedding IS NOT NULL
|
||||||
|
AND p.q_vec IS NOT NULL
|
||||||
|
AND (p.dom_filter IS NULL OR m.domains && p.dom_filter)
|
||||||
|
AND (p.nt_filter IS NULL OR m.node_type = ANY(p.nt_filter))
|
||||||
|
AND (p.tag_filter IS NULL OR m.tags && p.tag_filter)
|
||||||
|
ORDER BY m.embedding <=> p.q_vec
|
||||||
|
LIMIT (SELECT overfetch FROM params)
|
||||||
|
),
|
||||||
|
fused AS (
|
||||||
|
SELECT
|
||||||
|
COALESCE(f.id, v.id) AS id,
|
||||||
|
COALESCE(1.0 / (60 + f.rank), 0.0)
|
||||||
|
+ COALESCE(1.0 / (60 + v.rank), 0.0) AS rrf_score,
|
||||||
|
f.score AS fts_score,
|
||||||
|
v.score AS vector_score
|
||||||
|
FROM fts f
|
||||||
|
FULL OUTER JOIN vec v ON f.id = v.id
|
||||||
|
)
|
||||||
|
SELECT
|
||||||
|
m.id AS "id!: uuid::Uuid",
|
||||||
|
m.owner_user_id AS "owner_user_id!: uuid::Uuid",
|
||||||
|
m.visibility AS "visibility!: String",
|
||||||
|
m.shared_with_groups AS "shared_with_groups!: Vec<uuid::Uuid>",
|
||||||
|
m.codebase AS "codebase: String",
|
||||||
|
m.domains AS "domains!: Vec<String>",
|
||||||
|
m.domain_scores AS "domain_scores!: serde_json::Value",
|
||||||
|
m.content AS "content!: String",
|
||||||
|
m.node_type AS "node_type!: String",
|
||||||
|
m.tags AS "tags!: Vec<String>",
|
||||||
|
m.embedding AS "embedding: pgvector::Vector",
|
||||||
|
m.metadata AS "metadata!: serde_json::Value",
|
||||||
|
m.created_at AS "created_at!: chrono::DateTime<chrono::Utc>",
|
||||||
|
m.updated_at AS "updated_at!: chrono::DateTime<chrono::Utc>",
|
||||||
|
fused.rrf_score AS "rrf_score!: f64",
|
||||||
|
fused.fts_score AS "fts_score: f64",
|
||||||
|
fused.vector_score AS "vector_score: f64"
|
||||||
|
FROM fused
|
||||||
|
JOIN knowledge_nodes m ON m.id = fused.id
|
||||||
|
ORDER BY fused.rrf_score DESC
|
||||||
|
LIMIT (SELECT final_limit FROM params);
|
||||||
|
```
|
||||||
|
|
||||||
|
Notes on the SELECT column list. The D7 columns (`owner_user_id`,
|
||||||
|
`visibility`, `shared_with_groups`) and the D8 column (`codebase`) are
|
||||||
|
selected even though Phase 2 does not filter on them yet, so:
|
||||||
|
|
||||||
|
1. The `MemoryRecord` returned to the trait can be populated with the
|
||||||
|
stored values from day one. Phase 3 will start writing real
|
||||||
|
`owner_user_id` / `visibility` values; Phase 2 always writes the
|
||||||
|
single-user defaults (`'00000000-...-0001'`, `'private'`, `'{}'`). The
|
||||||
|
`MemoryRecord` returned in Phase 2 simply carries those defaults.
|
||||||
|
2. The schema-drift integration tests (see "Verification") catch the case
|
||||||
|
where someone adds a NOT NULL column to `knowledge_nodes` without updating
|
||||||
|
this query.
|
||||||
|
|
||||||
|
Notes on the body:
|
||||||
|
|
||||||
|
- `CROSS JOIN params p` is used instead of the master-plan sketch's
|
||||||
|
`FROM knowledge_nodes m, params p`. Same plan, clearer intent.
|
||||||
|
- The `ORDER BY ... LIMIT` inside each branch CTE is there so the planner
|
||||||
|
can stop early once it has `overfetch` rows; without it the LIMIT is
|
||||||
|
applied after a full sort over all matches.
|
||||||
|
- `1.0 - (m.embedding <=> p.q_vec)` converts pgvector's cosine *distance*
|
||||||
|
to cosine *similarity* in [0, 1] for the `vector_score` output. RRF
|
||||||
|
itself does not need the similarity -- it uses ranks -- but the trait
|
||||||
|
surface exposes `vector_score: Option<f64>` for caller introspection.
|
||||||
|
- `RRF_K = 60` is inlined as `60` in the SQL string. A `const` formatter
|
||||||
|
feels tidier but `60` is a literature constant; spell it out and leave a
|
||||||
|
comment in the Rust source: `// 60 == RRF_K (Cormack 2009)`.
|
||||||
|
- `FULL OUTER JOIN` is required: a row that the FTS branch finds and the
|
||||||
|
vector branch does not must still appear in `fused`, and vice versa.
|
||||||
|
- `COALESCE(..., 0.0)` on each `1.0 / (60 + rank)` term handles the
|
||||||
|
no-match-from-this-branch case. The fusion score for a row that only the
|
||||||
|
FTS branch ranks is `1/(60 + f.rank)` exactly.
|
||||||
|
- `m.search_vec` is the generated `tsvector` column created in migration
|
||||||
|
`0001_init` (see D4 of the master plan).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Result row mapping
|
||||||
|
|
||||||
|
`sqlx::query_as::<_, SearchRow>` reads each row into a private struct that
|
||||||
|
owns the column types exactly as they come back from Postgres. The struct
|
||||||
|
is converted into a `SearchResult` after fetch.
|
||||||
|
|
||||||
|
```rust
|
||||||
|
#[derive(sqlx::FromRow)]
|
||||||
|
struct SearchRow {
|
||||||
|
id: uuid::Uuid,
|
||||||
|
owner_user_id: uuid::Uuid,
|
||||||
|
visibility: String,
|
||||||
|
shared_with_groups: Vec<uuid::Uuid>,
|
||||||
|
codebase: Option<String>,
|
||||||
|
domains: Vec<String>,
|
||||||
|
domain_scores: serde_json::Value,
|
||||||
|
content: String,
|
||||||
|
node_type: String,
|
||||||
|
tags: Vec<String>,
|
||||||
|
embedding: Option<pgvector::Vector>,
|
||||||
|
metadata: serde_json::Value,
|
||||||
|
created_at: chrono::DateTime<chrono::Utc>,
|
||||||
|
updated_at: chrono::DateTime<chrono::Utc>,
|
||||||
|
rrf_score: f64,
|
||||||
|
fts_score: Option<f64>,
|
||||||
|
vector_score: Option<f64>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl SearchRow {
|
||||||
|
fn into_result(self) -> SearchResult {
|
||||||
|
use crate::storage::memory_store::MemoryRecord;
|
||||||
|
use std::collections::HashMap;
|
||||||
|
|
||||||
|
// domain_scores is JSONB; the column always exists, but may be the
|
||||||
|
// empty object {} when Phase 4 has not classified this memory yet.
|
||||||
|
let domain_scores: HashMap<String, f64> =
|
||||||
|
serde_json::from_value(self.domain_scores).unwrap_or_default();
|
||||||
|
|
||||||
|
let record = MemoryRecord {
|
||||||
|
id: self.id,
|
||||||
|
domains: self.domains,
|
||||||
|
domain_scores,
|
||||||
|
content: self.content,
|
||||||
|
node_type: self.node_type,
|
||||||
|
tags: self.tags,
|
||||||
|
// pgvector::Vector -> Vec<f32>
|
||||||
|
embedding: self.embedding.map(|v| v.to_vec()),
|
||||||
|
created_at: self.created_at,
|
||||||
|
updated_at: self.updated_at,
|
||||||
|
metadata: self.metadata,
|
||||||
|
// owner_user_id / visibility / shared_with_groups / codebase
|
||||||
|
// do not appear on MemoryRecord yet. Phase 3 will decide whether
|
||||||
|
// to extend MemoryRecord or surface them via a side channel.
|
||||||
|
// For Phase 2 they are read but discarded here.
|
||||||
|
};
|
||||||
|
|
||||||
|
SearchResult {
|
||||||
|
record,
|
||||||
|
score: self.rrf_score,
|
||||||
|
fts_score: self.fts_score,
|
||||||
|
vector_score: self.vector_score,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Type mapping summary:
|
||||||
|
|
||||||
|
| SQL type | Rust type | Notes |
|
||||||
|
|-------------------|--------------------------------------|------------------------------------------------|
|
||||||
|
| UUID | `uuid::Uuid` | requires sqlx `uuid` feature |
|
||||||
|
| TEXT | `String` | |
|
||||||
|
| TEXT NULL | `Option<String>` | used for `codebase` |
|
||||||
|
| TEXT[] | `Vec<String>` | for `tags`, `domains` |
|
||||||
|
| UUID[] | `Vec<uuid::Uuid>` | for `shared_with_groups` |
|
||||||
|
| JSONB | `serde_json::Value` | for `metadata`, `domain_scores` |
|
||||||
|
| TIMESTAMPTZ | `chrono::DateTime<chrono::Utc>` | requires sqlx `chrono` feature |
|
||||||
|
| VECTOR(N) NULL | `Option<pgvector::Vector>` | `.map(|v| v.to_vec())` to `Option<Vec<f32>>` |
|
||||||
|
| FLOAT8 | `f64` | |
|
||||||
|
| FLOAT8 NULL | `Option<f64>` | for `fts_score`, `vector_score` |
|
||||||
|
|
||||||
|
If `MemoryRecord` is extended in Phase 3 to carry `owner_user_id`,
|
||||||
|
`visibility`, `shared_with_groups`, and `codebase`, the conversion above
|
||||||
|
gets four more fields. Phase 2 reads them so the integration tests can
|
||||||
|
assert on them via SQL, but the trait surface does not expose them yet.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## `fts_only` and `vector_only` -- dedicated single-branch queries
|
||||||
|
|
||||||
|
The master plan offers two options for the convenience methods: reuse
|
||||||
|
`rrf_search` with one branch nulled, or write dedicated queries. The
|
||||||
|
dedicated queries win:
|
||||||
|
|
||||||
|
- One CTE instead of three. Planner picks the obvious plan.
|
||||||
|
- No FULL OUTER JOIN.
|
||||||
|
- No `params` indirection -- bound parameters used directly.
|
||||||
|
- The output `score` is the branch's native score (BM25-ish `ts_rank_cd` /
|
||||||
|
cosine similarity), not an RRF fusion score over one branch. Callers of
|
||||||
|
`fts_search` and `vector_search` get an intuitive score back.
|
||||||
|
|
||||||
|
### `fts_only`
|
||||||
|
|
||||||
|
Bound parameters:
|
||||||
|
|
||||||
|
- `$1`: text query (TEXT, must be non-empty; the caller guards `text.is_empty()`)
|
||||||
|
- `$2`: limit (INT)
|
||||||
|
|
||||||
|
```sql
|
||||||
|
SELECT
|
||||||
|
m.id AS "id!: uuid::Uuid",
|
||||||
|
m.owner_user_id AS "owner_user_id!: uuid::Uuid",
|
||||||
|
m.visibility AS "visibility!: String",
|
||||||
|
m.shared_with_groups AS "shared_with_groups!: Vec<uuid::Uuid>",
|
||||||
|
m.codebase AS "codebase: String",
|
||||||
|
m.domains AS "domains!: Vec<String>",
|
||||||
|
m.domain_scores AS "domain_scores!: serde_json::Value",
|
||||||
|
m.content AS "content!: String",
|
||||||
|
m.node_type AS "node_type!: String",
|
||||||
|
m.tags AS "tags!: Vec<String>",
|
||||||
|
m.embedding AS "embedding: pgvector::Vector",
|
||||||
|
m.metadata AS "metadata!: serde_json::Value",
|
||||||
|
m.created_at AS "created_at!: chrono::DateTime<chrono::Utc>",
|
||||||
|
m.updated_at AS "updated_at!: chrono::DateTime<chrono::Utc>",
|
||||||
|
ts_rank_cd(m.search_vec, websearch_to_tsquery('english', $1))
|
||||||
|
AS "fts_score!: f64"
|
||||||
|
FROM knowledge_nodes m
|
||||||
|
WHERE m.search_vec @@ websearch_to_tsquery('english', $1)
|
||||||
|
ORDER BY ts_rank_cd(m.search_vec, websearch_to_tsquery('english', $1)) DESC
|
||||||
|
LIMIT $2;
|
||||||
|
```
|
||||||
|
|
||||||
|
The Rust caller maps each row to a `SearchResult` with:
|
||||||
|
|
||||||
|
```rust
|
||||||
|
SearchResult {
|
||||||
|
record,
|
||||||
|
score: fts_score,
|
||||||
|
fts_score: Some(fts_score),
|
||||||
|
vector_score: None,
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
If `text.is_empty()` the caller returns `Ok(Vec::new())` before hitting
|
||||||
|
the database. `websearch_to_tsquery('english', '')` returns an empty
|
||||||
|
tsquery that matches nothing; the round-trip is wasted work otherwise.
|
||||||
|
|
||||||
|
### `vector_only`
|
||||||
|
|
||||||
|
Bound parameters:
|
||||||
|
|
||||||
|
- `$1`: embedding (pgvector::Vector)
|
||||||
|
- `$2`: limit (INT)
|
||||||
|
|
||||||
|
```sql
|
||||||
|
SELECT
|
||||||
|
m.id AS "id!: uuid::Uuid",
|
||||||
|
m.owner_user_id AS "owner_user_id!: uuid::Uuid",
|
||||||
|
m.visibility AS "visibility!: String",
|
||||||
|
m.shared_with_groups AS "shared_with_groups!: Vec<uuid::Uuid>",
|
||||||
|
m.codebase AS "codebase: String",
|
||||||
|
m.domains AS "domains!: Vec<String>",
|
||||||
|
m.domain_scores AS "domain_scores!: serde_json::Value",
|
||||||
|
m.content AS "content!: String",
|
||||||
|
m.node_type AS "node_type!: String",
|
||||||
|
m.tags AS "tags!: Vec<String>",
|
||||||
|
m.embedding AS "embedding: pgvector::Vector",
|
||||||
|
m.metadata AS "metadata!: serde_json::Value",
|
||||||
|
m.created_at AS "created_at!: chrono::DateTime<chrono::Utc>",
|
||||||
|
m.updated_at AS "updated_at!: chrono::DateTime<chrono::Utc>",
|
||||||
|
1.0 - (m.embedding <=> $1) AS "vector_score!: f64"
|
||||||
|
FROM knowledge_nodes m
|
||||||
|
WHERE m.embedding IS NOT NULL
|
||||||
|
ORDER BY m.embedding <=> $1
|
||||||
|
LIMIT $2;
|
||||||
|
```
|
||||||
|
|
||||||
|
The Rust caller maps each row to:
|
||||||
|
|
||||||
|
```rust
|
||||||
|
SearchResult {
|
||||||
|
record,
|
||||||
|
score: vector_score,
|
||||||
|
fts_score: None,
|
||||||
|
vector_score: Some(vector_score),
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Both convenience methods ignore `SearchQuery.domains` / `tags` /
|
||||||
|
`node_types` / `min_retrievability` -- they take `&str` and `&[f32]`
|
||||||
|
respectively, not a `SearchQuery`. Callers that want filters on a
|
||||||
|
single-branch search should call `search` with the other branch input
|
||||||
|
left at its degrade-to-zero default.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## `min_retrievability` filter
|
||||||
|
|
||||||
|
`SearchQuery::min_retrievability: Option<f64>` is applied as a final
|
||||||
|
filter after fusion by joining on the `scheduling` table:
|
||||||
|
|
||||||
|
```sql
|
||||||
|
-- with-min-retrievability variant: identical CTEs to the base query, only
|
||||||
|
-- the final SELECT changes.
|
||||||
|
SELECT
|
||||||
|
... (same column list as the base query) ...
|
||||||
|
FROM fused
|
||||||
|
JOIN knowledge_nodes m ON m.id = fused.id
|
||||||
|
JOIN scheduling s ON s.memory_id = m.id
|
||||||
|
WHERE s.retrievability >= $8
|
||||||
|
ORDER BY fused.rrf_score DESC
|
||||||
|
LIMIT (SELECT final_limit FROM params);
|
||||||
|
```
|
||||||
|
|
||||||
|
This is a separate prepared statement -- the eight-parameter variant --
|
||||||
|
held alongside the seven-parameter base. The Rust dispatch:
|
||||||
|
|
||||||
|
```rust
|
||||||
|
if let Some(min_r) = query.min_retrievability {
|
||||||
|
sqlx::query_as::<_, SearchRow>(QUERY_WITH_MIN_R)
|
||||||
|
.bind(q_text)
|
||||||
|
.bind(q_vec)
|
||||||
|
.bind(overfetch)
|
||||||
|
.bind(final_limit)
|
||||||
|
.bind(dom_filter)
|
||||||
|
.bind(nt_filter)
|
||||||
|
.bind(tag_filter)
|
||||||
|
.bind(min_r)
|
||||||
|
.fetch_all(pool).await?
|
||||||
|
} else {
|
||||||
|
sqlx::query_as::<_, SearchRow>(QUERY_BASE)
|
||||||
|
.bind(q_text)
|
||||||
|
.bind(q_vec)
|
||||||
|
.bind(overfetch)
|
||||||
|
.bind(final_limit)
|
||||||
|
.bind(dom_filter)
|
||||||
|
.bind(nt_filter)
|
||||||
|
.bind(tag_filter)
|
||||||
|
.fetch_all(pool).await?
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Why not unconditionally join: the `scheduling` join is expensive enough on
|
||||||
|
a large `knowledge_nodes` table that adding it to every search call regresses the
|
||||||
|
common path. `min_retrievability` is set by the cognitive engine's
|
||||||
|
accessibility filter and is `None` in most direct callers.
|
||||||
|
|
||||||
|
The same two-variant pattern repeats for `fts_only` and `vector_only`; in
|
||||||
|
practice callers of those methods rarely set `min_retrievability` (it is
|
||||||
|
not part of their argument list), so only the base variant is needed
|
||||||
|
unless the trait surface grows.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Domain / tag / node_type filters
|
||||||
|
|
||||||
|
Each filter is expressed as a NULL-conditional clause inside both branch
|
||||||
|
CTEs, written using PostgreSQL array operators:
|
||||||
|
|
||||||
|
```sql
|
||||||
|
AND (p.dom_filter IS NULL OR m.domains && p.dom_filter)
|
||||||
|
AND (p.nt_filter IS NULL OR m.node_type = ANY(p.nt_filter))
|
||||||
|
AND (p.tag_filter IS NULL OR m.tags && p.tag_filter)
|
||||||
|
```
|
||||||
|
|
||||||
|
- `&&` is the PostgreSQL "arrays overlap" operator. Matches if any
|
||||||
|
element in `m.domains` is in the filter array. Index-friendly with a
|
||||||
|
GIN index on `m.domains` (created in `0001_init`).
|
||||||
|
- `= ANY(...)` matches `m.node_type` (a scalar) against any element of
|
||||||
|
the filter array. Index-friendly with a B-tree on `m.node_type`.
|
||||||
|
- `&&` is used again on `m.tags` (a `TEXT[]`).
|
||||||
|
|
||||||
|
The NULL-conditional form is critical: when the filter parameter is
|
||||||
|
`NULL`, the clause short-circuits to `TRUE` and contributes nothing to
|
||||||
|
the WHERE. This keeps a single query reusable across "no filter" and
|
||||||
|
"filter set" cases without rewriting SQL.
|
||||||
|
|
||||||
|
When the Rust caller passes `None` for a filter, sqlx binds it as `NULL`
|
||||||
|
of the column type (`text[]`). The cast `$5::text[]` in the `params` CTE
|
||||||
|
is what tells sqlx the binding type.
|
||||||
|
|
||||||
|
The master plan's draft has each filter clause duplicated across both
|
||||||
|
branch CTEs. That duplication is correct -- the planner cannot push a
|
||||||
|
WHERE clause across a FULL OUTER JOIN into both sides automatically; we
|
||||||
|
do it manually.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Empty-string text query handling
|
||||||
|
|
||||||
|
The base query guards the FTS branch with `WHERE p.q_text <> ''`.
|
||||||
|
|
||||||
|
`websearch_to_tsquery('english', '')` returns an empty tsquery. An empty
|
||||||
|
tsquery has no lexemes and matches no document; the `@@` operator returns
|
||||||
|
false for every row. Without the guard, the FTS branch would still run --
|
||||||
|
sequential scan, tokenisation per row, comparison -- and return zero
|
||||||
|
rows. The guard short-circuits at planning time.
|
||||||
|
|
||||||
|
The guard does not affect the FULL OUTER JOIN: when the FTS branch
|
||||||
|
returns zero rows, the join degenerates to "every row that the vector
|
||||||
|
branch returned, with `f.id IS NULL` and `f.rank IS NULL`". The
|
||||||
|
`COALESCE(1.0 / (60 + f.rank), 0.0)` then evaluates to `0.0`, and the
|
||||||
|
fused score reduces to the vector branch's RRF term alone. This is the
|
||||||
|
"pure vector search" degrade path.
|
||||||
|
|
||||||
|
Symmetrically, the vector branch guards itself with
|
||||||
|
`WHERE m.embedding IS NOT NULL AND p.q_vec IS NOT NULL`, which gives the
|
||||||
|
"pure FTS search" degrade path when the caller passes no embedding.
|
||||||
|
|
||||||
|
The both-empty case (`q_text == ''` and `q_vec IS NULL`) is intercepted
|
||||||
|
in Rust before the query runs and returns `Ok(vec![])`. Returning empty
|
||||||
|
rather than error matches the SQLite behavior and is what the Phase 1
|
||||||
|
ingest pipeline relies on for "no signal, no results" fallback.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Use of `sqlx::query!` versus `sqlx::query_as`
|
||||||
|
|
||||||
|
`sqlx::query!` and `sqlx::query_as!` are compile-time-checked: the SQL is
|
||||||
|
sent to a live Postgres at build time, the result schema is validated, and
|
||||||
|
the generated Rust struct fields are derived. That checking is the
|
||||||
|
default for every other query in `0002d-store-impl-bodies.md`.
|
||||||
|
|
||||||
|
For the RRF query, the macro path is impractical for two reasons:
|
||||||
|
|
||||||
|
1. **Two structurally different queries** -- the base (seven parameters,
|
||||||
|
no `scheduling` join) and the `min_retrievability` variant (eight
|
||||||
|
parameters, with the join). The macro would force two macro
|
||||||
|
invocations, each producing its own anonymous result struct, and the
|
||||||
|
result types would not unify. Manual `From` impls would be needed in
|
||||||
|
both directions.
|
||||||
|
2. **The dedicated `fts_only` and `vector_only` queries have a different
|
||||||
|
output column set** (`fts_score!` instead of `rrf_score! + fts_score? +
|
||||||
|
vector_score?`). Three macro invocations, three structs, three
|
||||||
|
conversion helpers.
|
||||||
|
|
||||||
|
The chosen pattern is `sqlx::query_as::<_, SearchRow>(SQL_CONST)` with a
|
||||||
|
single `SearchRow` struct that owns the column types and a single
|
||||||
|
`SearchRow::into_result` helper. The SQL is held in module-scope `&'static
|
||||||
|
str` constants:
|
||||||
|
|
||||||
|
```rust
|
||||||
|
const QUERY_BASE: &str = include_str!("search.rrf.sql");
|
||||||
|
const QUERY_WITH_MIN_R: &str = include_str!("search.rrf.min_retr.sql");
|
||||||
|
const QUERY_FTS_ONLY: &str = include_str!("search.fts.sql");
|
||||||
|
const QUERY_VECTOR_ONLY: &str = include_str!("search.vector.sql");
|
||||||
|
```
|
||||||
|
|
||||||
|
`include_str!` keeps the SQL out of the Rust source. The four `.sql`
|
||||||
|
files live next to `search.rs` in
|
||||||
|
`crates/vestige-core/src/storage/postgres/`.
|
||||||
|
|
||||||
|
The cost: schema drift (someone renames `m.codebase` to `m.repo_name`)
|
||||||
|
will not break the build. The integration tests in "Verification" below
|
||||||
|
are the safety net. This is a deliberate trade -- it is the one sub-plan
|
||||||
|
in Phase 2 where runtime flexibility beats compile-time checking.
|
||||||
|
|
||||||
|
If a future contributor wants compile-time checking back for the simple
|
||||||
|
case, the right move is to introduce a `#[cfg(test)]`-only macro-checked
|
||||||
|
variant of `QUERY_BASE` and assert at test build time that the macro
|
||||||
|
agrees with the string. That belongs in `0002h-testing-and-benches.md` if
|
||||||
|
anywhere.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Verification
|
||||||
|
|
||||||
|
Integration tests live in
|
||||||
|
`crates/vestige-core/tests/postgres_search.rs`, gated by
|
||||||
|
`#[cfg(feature = "postgres-backend")]` and `#[ignore]` by default (the
|
||||||
|
test runner CI workflow in `0002h-testing-and-benches.md` runs them with
|
||||||
|
`--ignored` against a live Postgres).
|
||||||
|
|
||||||
|
Common harness for every test:
|
||||||
|
|
||||||
|
1. Spin up Postgres via `sqlx::PgPool::connect` against the test URL.
|
||||||
|
2. Run `sqlx::migrate!("./migrations/postgres").run(&pool)` to bring the
|
||||||
|
schema up.
|
||||||
|
3. Register a deterministic test embedder via `register_model` so
|
||||||
|
`embedding` columns can be written.
|
||||||
|
4. Seed 50 mixed memories through `MemoryStore::insert` -- mixed
|
||||||
|
`node_type` (`fact`, `concept`, `event`, `decision`), mixed `tags`
|
||||||
|
(`rust`, `postgres`, `search`, `dream`, `bug-fix`), mixed `codebase`,
|
||||||
|
embeddings drawn from three small clusters so vector recall has
|
||||||
|
structure to find.
|
||||||
|
|
||||||
|
Test cases:
|
||||||
|
|
||||||
|
**T1. Full RRF returns the seeded target.**
|
||||||
|
Insert a known memory with `content = "FSRS-6 spaced repetition cadence"`
|
||||||
|
and an embedding from cluster A. Query with
|
||||||
|
`text = Some("FSRS spaced repetition")` and an embedding near cluster A.
|
||||||
|
Assert the target memory is in the top 3 of the returned `SearchResult`s
|
||||||
|
and that both `fts_score` and `vector_score` are `Some` for it.
|
||||||
|
|
||||||
|
**T2. Pure FTS degrade.**
|
||||||
|
Same target as T1. Query with `text = Some("FSRS spaced repetition")` and
|
||||||
|
`embedding = None`. Assert the target appears, all results have
|
||||||
|
`vector_score == None`, `fts_score == Some(_)`, and `score` equals the
|
||||||
|
fused RRF score (which collapses to one branch's `1.0/(60 + rank)`).
|
||||||
|
|
||||||
|
**T3. Pure vector degrade.**
|
||||||
|
Same target as T1. Query with `text = Some("")` and
|
||||||
|
`embedding = Some(cluster_A_vector)`. Assert the target appears, all
|
||||||
|
results have `fts_score == None`, `vector_score == Some(_)`.
|
||||||
|
|
||||||
|
**T4. Both empty returns `Ok(vec![])`.**
|
||||||
|
Query with `text = Some("")` and `embedding = None`. Assert exactly an
|
||||||
|
empty result vector and that no SQL was executed (assert via a
|
||||||
|
`sqlx::PgPool` query-count handle if convenient; otherwise document that
|
||||||
|
the short-circuit lives in Rust).
|
||||||
|
|
||||||
|
**T5. `domains` filter.**
|
||||||
|
Insert one memory with `domains = vec!["domain-x"]` and 49 others without
|
||||||
|
it. Query with `domains = Some(vec!["domain-x"])` and a matching text.
|
||||||
|
Assert exactly one result is returned and it is the seeded memory.
|
||||||
|
|
||||||
|
**T6. `tags` filter.**
|
||||||
|
Same pattern as T5 with `tags = Some(vec!["bug-fix"])`.
|
||||||
|
|
||||||
|
**T7. `node_types` filter.**
|
||||||
|
Same pattern as T5 with `node_types = Some(vec!["decision"])`.
|
||||||
|
|
||||||
|
**T8. `min_retrievability` filter.**
|
||||||
|
Seed two memories with the same content + embedding. Write
|
||||||
|
`scheduling` rows so that one has `retrievability = 0.9` and the other
|
||||||
|
`0.1`. Query with `min_retrievability = Some(0.5)`. Assert exactly the
|
||||||
|
high-retrievability memory is returned.
|
||||||
|
|
||||||
|
**T9. `query.limit == 0` defaults to 10.**
|
||||||
|
Seed 30 matching memories. Query with `limit = 0`. Assert the result
|
||||||
|
contains exactly 10 entries.
|
||||||
|
|
||||||
|
**T10. `fts_only` and `vector_only` parity.**
|
||||||
|
For the same target memory, call `fts_only` and `vector_only` directly
|
||||||
|
and compare against `search` with the corresponding branch zeroed. The
|
||||||
|
top-1 result must match by id; the scores need only be of the same sign
|
||||||
|
and magnitude (not bit-identical, because RRF fusion changes the
|
||||||
|
absolute score).
|
||||||
|
|
||||||
|
**T11. Schema-drift canary.**
|
||||||
|
Run the base query against an empty `knowledge_nodes` table and `fetch_all`
|
||||||
|
into `Vec<SearchRow>`. Any added NOT NULL column on `knowledge_nodes` that is
|
||||||
|
not in the SELECT will fail the test at the `try_get` boundary with a
|
||||||
|
clear error. This is the test that compensates for not using
|
||||||
|
`sqlx::query!`.
|
||||||
|
|
||||||
|
**T12. Hostile inputs.**
|
||||||
|
Query with `text = Some("'; DROP TABLE knowledge_nodes; --")` and a normal
|
||||||
|
embedding. Assert no panic, results returned cleanly, `knowledge_nodes` table
|
||||||
|
still present. This is symbolic; `websearch_to_tsquery` is parameter-
|
||||||
|
bound and SQL injection is not actually possible, but the test is cheap
|
||||||
|
and the assertion is real.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Acceptance criteria
|
||||||
|
|
||||||
|
A reviewer of the implementation PR should be able to confirm:
|
||||||
|
|
||||||
|
1. `crates/vestige-core/src/storage/postgres/search.rs` exists and is
|
||||||
|
compiled only when `feature = "postgres-backend"` is on.
|
||||||
|
2. The four `.sql` files (`search.rrf.sql`,
|
||||||
|
`search.rrf.min_retr.sql`, `search.fts.sql`, `search.vector.sql`)
|
||||||
|
exist in the same directory and are `include_str!`-ed into module-
|
||||||
|
scope `&'static str` constants.
|
||||||
|
3. `RRF_K = 60` and `OVERFETCH_MULT = 3` are defined as constants at
|
||||||
|
module scope with the Cormack 2009 citation in a comment.
|
||||||
|
4. The seven-parameter base query is one statement and uses a `params`
|
||||||
|
CTE; the eight-parameter `min_retrievability` variant adds exactly
|
||||||
|
one JOIN and one WHERE clause on top of the base.
|
||||||
|
5. Empty text degrades to pure vector; null embedding degrades to pure
|
||||||
|
FTS; both empty short-circuits to `Ok(vec![])` in Rust before the
|
||||||
|
query runs.
|
||||||
|
6. The SELECT column list in every query includes `owner_user_id`,
|
||||||
|
`visibility`, `shared_with_groups`, and `codebase` even though Phase 2
|
||||||
|
does not filter on them.
|
||||||
|
7. `SearchRow::into_result` populates a `MemoryRecord` with every field
|
||||||
|
the trait requires, including `domains` and `domain_scores` decoded
|
||||||
|
from JSONB.
|
||||||
|
8. `PgMemoryStore::search`, `PgMemoryStore::fts_search`, and
|
||||||
|
`PgMemoryStore::vector_search` each delegate to the corresponding
|
||||||
|
free function with one line of body.
|
||||||
|
9. All twelve integration tests (`T1` through `T12`) pass against a live
|
||||||
|
Postgres with the `0001_init` + `0002_hnsw` migrations applied.
|
||||||
|
10. `cargo build -p vestige-core` succeeds with
|
||||||
|
`--features postgres-backend` and with the feature off.
|
||||||
|
11. `cargo clippy -p vestige-core --features postgres-backend -- -D warnings`
|
||||||
|
is clean.
|
||||||
|
|
||||||
|
When all eleven are true, this sub-plan is done and
|
||||||
|
`0002f-migrate-cli.md` is unblocked.
|
||||||
1045
docs/plans/0002f-migrate-cli.md
Normal file
1045
docs/plans/0002f-migrate-cli.md
Normal file
File diff suppressed because it is too large
Load diff
843
docs/plans/0002g-reembed.md
Normal file
843
docs/plans/0002g-reembed.md
Normal file
|
|
@ -0,0 +1,843 @@
|
||||||
|
# Sub-plan 0002g -- Re-embed driver and `vestige migrate reembed` CLI
|
||||||
|
|
||||||
|
**Status**: Draft
|
||||||
|
**Master plan**: [0002-phase-2-postgres-backend.md](0002-phase-2-postgres-backend.md)
|
||||||
|
**ADR**: [0002-phase-2-execution.md](../adr/0002-phase-2-execution.md)
|
||||||
|
**Predecessor**: [0002f-migrate-cli.md](0002f-migrate-cli.md)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Context
|
||||||
|
|
||||||
|
This sub-plan delivers master plan deliverable **D9** -- the bulk re-embedding
|
||||||
|
driver -- and the `vestige migrate reembed` arm of the CLI scaffolded by
|
||||||
|
**D10** in sub-plan `0002f`. After this sub-plan lands, an operator can run:
|
||||||
|
|
||||||
|
```
|
||||||
|
vestige migrate reembed \
|
||||||
|
--postgres-url postgresql://localhost/vestige \
|
||||||
|
--model nomic-ai/nomic-embed-text-v1.5 \
|
||||||
|
--dimension 768
|
||||||
|
```
|
||||||
|
|
||||||
|
and the running Postgres backend will:
|
||||||
|
|
||||||
|
1. Stream every row out of `knowledge_nodes`.
|
||||||
|
2. Re-encode `content` with the requested `Embedder`.
|
||||||
|
3. Write the new vectors back.
|
||||||
|
4. Adjust the pgvector typmod if the new dimension differs from the old.
|
||||||
|
5. Rebuild the HNSW index.
|
||||||
|
6. Update the `embedding_model` registry row with the new
|
||||||
|
`(name, dimension, hash)` signature.
|
||||||
|
|
||||||
|
The whole operation runs as a single offline maintenance step. Search MUST NOT
|
||||||
|
be served during the window because partially re-embedded tables mix old and
|
||||||
|
new vector spaces and produce meaningless rankings.
|
||||||
|
|
||||||
|
This sub-plan deliberately does NOT:
|
||||||
|
|
||||||
|
- Migrate vectors between backends. That's `0002f` (SQLite -> Postgres copy).
|
||||||
|
- Invent new embedder constructors. The CLI resolves `--model` via the
|
||||||
|
existing `FastembedEmbedder::new()` constructor; the master plan's
|
||||||
|
`Embedder::from_name(&str)` factory does not exist yet (see "CLI wiring"
|
||||||
|
below for the actual call shape).
|
||||||
|
- Add a `vestige migrate reembed --sqlite-path ...` arm. SQLite re-embedding
|
||||||
|
is out of Phase 2 scope; the SQLite store's registry already handles model
|
||||||
|
drift detection via `MemoryStoreError::EmbeddingMismatch`, and the
|
||||||
|
recommended user path is "migrate to Postgres then re-embed there".
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Dependencies
|
||||||
|
|
||||||
|
- `0002a-skeleton-and-feature-gate.md` -- `PgMemoryStore` exists.
|
||||||
|
- `0002b-pool-and-config.md` -- `connect` builds a real `PgPool`.
|
||||||
|
- `0002c-migrations.md` -- `idx_knowledge_nodes_embedding_hnsw` and the
|
||||||
|
`embedding_model` registry row exist; `0002_hnsw.up.sql` defines the index.
|
||||||
|
- `0002d-store-impl-bodies.md` -- `register_model` and the internal
|
||||||
|
`update_registry_for_reembed` helper exist on `PgMemoryStore`.
|
||||||
|
- `0002e-hybrid-search.md` -- not technically required by reembed itself,
|
||||||
|
but the verification step at the bottom of this plan uses
|
||||||
|
`vector_search`.
|
||||||
|
- `0002f-migrate-cli.md` -- provides the `clap` scaffolding under
|
||||||
|
`vestige migrate ...`. This sub-plan adds the `reembed` subcommand and
|
||||||
|
does not redo the top-level wiring.
|
||||||
|
|
||||||
|
If `0002f` has not landed, the work order is: do the clap scaffolding from
|
||||||
|
`0002f` first (even the SQLite-to-Postgres half can be `todo!()` initially),
|
||||||
|
then this sub-plan.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Audit step (do this first)
|
||||||
|
|
||||||
|
Before writing `reembed.rs`, confirm the live shape of the supporting code.
|
||||||
|
From the repo root:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
rg -nF 'embed_batch' crates/vestige-core/src/
|
||||||
|
rg -nF 'register_model' crates/vestige-core/src/storage/
|
||||||
|
rg -nF 'idx_knowledge_nodes_embedding_hnsw' crates/vestige-core/migrations/postgres/
|
||||||
|
rg -nF 'update_registry_for_reembed' crates/vestige-core/src/storage/postgres/
|
||||||
|
```
|
||||||
|
|
||||||
|
Expected findings:
|
||||||
|
|
||||||
|
- `LocalEmbedder::embed_batch(&[&str]) -> Vec<Vec<f32>>` exists (Phase 1).
|
||||||
|
- `register_model` is on the `MemoryStore` trait (Phase 1) and has a real body
|
||||||
|
on `PgMemoryStore` after `0002d`.
|
||||||
|
- `idx_knowledge_nodes_embedding_hnsw` is the canonical HNSW index name. If
|
||||||
|
`0002c-migrations.md` chose a different name, update the SQL constants in
|
||||||
|
`reembed.rs` accordingly.
|
||||||
|
- `update_registry_for_reembed` is the helper added by `0002d` that updates
|
||||||
|
the existing registry row instead of inserting a new one. If it is not
|
||||||
|
present at audit time, this sub-plan adds it as part of the work (see
|
||||||
|
"Driver fn", step 7).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Cargo manifest additions
|
||||||
|
|
||||||
|
No new crates. `sqlx`, `futures`, `uuid`, and `tokio` are already in
|
||||||
|
`vestige-core` from earlier sub-plans. `tracing` is already used throughout
|
||||||
|
Phase 2.
|
||||||
|
|
||||||
|
The CLI binary (`vestige-mcp/src/bin/cli.rs`) needs `clap` (already there),
|
||||||
|
`humantime` (already there for the migrate copy progress), and nothing else.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Plan struct
|
||||||
|
|
||||||
|
`crates/vestige-core/src/storage/postgres/reembed.rs`:
|
||||||
|
|
||||||
|
```rust
|
||||||
|
#![cfg(feature = "postgres-backend")]
|
||||||
|
|
||||||
|
/// Tunables for the re-embed driver.
|
||||||
|
///
|
||||||
|
/// Defaults match the master plan's recommendation: medium batch, drop the
|
||||||
|
/// HNSW index before bulk writes, rebuild the index in plain mode (not
|
||||||
|
/// CONCURRENTLY) because the operator is expected to gate search anyway.
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct ReembedPlan {
|
||||||
|
/// Number of memories embedded per `embed_batch` call and per `UPDATE`.
|
||||||
|
/// Default 128. Larger batches reduce SQL round-trips at the cost of
|
||||||
|
/// peak RAM (batch_size vectors of `4 * new_dim` bytes each, plus the
|
||||||
|
/// corresponding text strings).
|
||||||
|
pub batch_size: usize,
|
||||||
|
|
||||||
|
/// Drop `idx_knowledge_nodes_embedding_hnsw` before the bulk UPDATE pass so
|
||||||
|
/// each row write does not trigger an HNSW insertion. The index is
|
||||||
|
/// rebuilt after all rows are written. Default true.
|
||||||
|
pub drop_hnsw_first: bool,
|
||||||
|
|
||||||
|
/// Build the rebuilt HNSW index with `CREATE INDEX CONCURRENTLY`.
|
||||||
|
/// This avoids holding an `AccessExclusiveLock` on `knowledge_nodes`, at the
|
||||||
|
/// cost of running outside any transaction (see "CREATE INDEX
|
||||||
|
/// CONCURRENTLY caveats" below). Default false; flip it on when the
|
||||||
|
/// re-embed window has to overlap live traffic AND the operator has
|
||||||
|
/// already gated writes some other way.
|
||||||
|
pub concurrent_index: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for ReembedPlan {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self {
|
||||||
|
batch_size: 128,
|
||||||
|
drop_hnsw_first: true,
|
||||||
|
concurrent_index: false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
The defaults match the master plan. `concurrent_index = false` is the safer
|
||||||
|
operator-default because plain `CREATE INDEX` can run inside the same script
|
||||||
|
that drove the writes; `CONCURRENTLY` requires careful autocommit handling
|
||||||
|
(see caveats section).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Report struct
|
||||||
|
|
||||||
|
```rust
|
||||||
|
/// Summary of one re-embed run. Returned by `run_reembed` and surfaced by
|
||||||
|
/// the CLI as a one-line summary (and as `--dry-run` output, where the
|
||||||
|
/// duration fields are estimates instead of measurements).
|
||||||
|
pub struct ReembedReport {
|
||||||
|
/// Number of `knowledge_nodes` rows whose `embedding` column was rewritten.
|
||||||
|
/// Includes rows whose embedding was previously NULL.
|
||||||
|
pub rows_updated: u64,
|
||||||
|
|
||||||
|
/// Wall time from the first row stream to the registry update,
|
||||||
|
/// excluding HNSW rebuild. Seconds with sub-millisecond precision.
|
||||||
|
pub duration_secs: f64,
|
||||||
|
|
||||||
|
/// Wall time of the HNSW rebuild step alone. Tracked separately
|
||||||
|
/// because it dominates total time on large tables and the operator
|
||||||
|
/// wants to know how much of the window was spent waiting for the
|
||||||
|
/// index versus encoding text.
|
||||||
|
pub index_rebuild_secs: f64,
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
The CLI prints all three fields. Tests assert on `rows_updated` only;
|
||||||
|
durations are non-deterministic.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Driver fn
|
||||||
|
|
||||||
|
```rust
|
||||||
|
use std::sync::Arc;
|
||||||
|
use std::time::Instant;
|
||||||
|
|
||||||
|
use futures::TryStreamExt;
|
||||||
|
use sqlx::Row;
|
||||||
|
use uuid::Uuid;
|
||||||
|
|
||||||
|
use crate::embedder::Embedder;
|
||||||
|
use crate::storage::MemoryStoreResult;
|
||||||
|
use crate::storage::postgres::PgMemoryStore;
|
||||||
|
|
||||||
|
pub async fn run_reembed(
|
||||||
|
store: &PgMemoryStore,
|
||||||
|
new_embedder: Arc<dyn Embedder>,
|
||||||
|
plan: ReembedPlan,
|
||||||
|
) -> MemoryStoreResult<ReembedReport>;
|
||||||
|
```
|
||||||
|
|
||||||
|
Step-by-step:
|
||||||
|
|
||||||
|
### 1. No-op check (registry comparison)
|
||||||
|
|
||||||
|
Read the current registry row. If `(name, dimension, hash)` already matches
|
||||||
|
`new_embedder.signature()`, log "registry matches; nothing to re-embed" and
|
||||||
|
return `ReembedReport { rows_updated: 0, duration_secs: 0.0,
|
||||||
|
index_rebuild_secs: 0.0 }`.
|
||||||
|
|
||||||
|
```rust
|
||||||
|
let current = store.registered_model().await?; // Phase 1 trait method
|
||||||
|
let target = new_embedder.signature();
|
||||||
|
if current.is_some_and(|c| c == target) {
|
||||||
|
tracing::info!("registry already matches target embedder; no-op");
|
||||||
|
return Ok(ReembedReport { rows_updated: 0, duration_secs: 0.0, index_rebuild_secs: 0.0 });
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
This is the cheapest precondition. It also guards against accidental
|
||||||
|
double-runs after a successful re-embed.
|
||||||
|
|
||||||
|
### 2. Drop HNSW (optional)
|
||||||
|
|
||||||
|
If `plan.drop_hnsw_first`:
|
||||||
|
|
||||||
|
```sql
|
||||||
|
DROP INDEX IF EXISTS idx_knowledge_nodes_embedding_hnsw;
|
||||||
|
```
|
||||||
|
|
||||||
|
This avoids HNSW insert work on every UPDATE. Recommended default. The index
|
||||||
|
gets rebuilt in step 6.
|
||||||
|
|
||||||
|
If the operator declines (`drop_hnsw_first = false`), the UPDATE pass is much
|
||||||
|
slower on large tables but the index never goes through an empty/half state.
|
||||||
|
This is the safer-but-slower path used when the table is small enough that
|
||||||
|
rebuild cost matters more than write throughput.
|
||||||
|
|
||||||
|
### 3. Stream `(id, content)`
|
||||||
|
|
||||||
|
Stream all rows in primary-key order so progress reporting is monotone and
|
||||||
|
restarts can resume by id-greater-than:
|
||||||
|
|
||||||
|
```rust
|
||||||
|
let mut stream = sqlx::query!(
|
||||||
|
"SELECT id, content FROM knowledge_nodes ORDER BY id"
|
||||||
|
).fetch(store.pool());
|
||||||
|
|
||||||
|
let mut batch_ids: Vec<Uuid> = Vec::with_capacity(plan.batch_size);
|
||||||
|
let mut batch_texts: Vec<String> = Vec::with_capacity(plan.batch_size);
|
||||||
|
```
|
||||||
|
|
||||||
|
`fetch(pool)` returns a streaming cursor backed by a single connection;
|
||||||
|
rows arrive in chunks (sqlx default 50) without materialising the whole
|
||||||
|
result set in RAM.
|
||||||
|
|
||||||
|
### 4. Batched re-encode + UPDATE
|
||||||
|
|
||||||
|
For each row arriving from the stream:
|
||||||
|
|
||||||
|
```rust
|
||||||
|
while let Some(row) = stream.try_next().await? {
|
||||||
|
batch_ids.push(row.id);
|
||||||
|
batch_texts.push(row.content);
|
||||||
|
if batch_ids.len() >= plan.batch_size {
|
||||||
|
flush_batch(&new_embedder, store, &mut batch_ids, &mut batch_texts).await?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !batch_ids.is_empty() {
|
||||||
|
flush_batch(&new_embedder, store, &mut batch_ids, &mut batch_texts).await?;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
`flush_batch` builds a `Vec<&str>` view, calls `new_embedder.embed_batch`,
|
||||||
|
then writes the result back. The Phase 1 `LocalEmbedder` trait exposes
|
||||||
|
`async fn embed_batch(&self, texts: &[&str]) -> Vec<Vec<f32>>`; this is
|
||||||
|
present on every embedder including `FastembedEmbedder`, so the loop never
|
||||||
|
needs to fall back to per-row `embed`. (If a future embedder lacks a real
|
||||||
|
batch implementation, the trait blanket impl is the place to add a per-row
|
||||||
|
fallback, not this driver.)
|
||||||
|
|
||||||
|
The write SQL:
|
||||||
|
|
||||||
|
```sql
|
||||||
|
UPDATE knowledge_nodes
|
||||||
|
SET embedding = v.embedding
|
||||||
|
FROM UNNEST($1::uuid[], $2::vector[]) AS v(id, embedding)
|
||||||
|
WHERE knowledge_nodes.id = v.id;
|
||||||
|
```
|
||||||
|
|
||||||
|
**Note on `UNNEST($2::vector[])`.** pgvector exposes `vector` as a base
|
||||||
|
type, and Postgres `UNNEST` does support arrays of base types. In practice,
|
||||||
|
sqlx's `pgvector::Vector` crate provides `PgHasArrayType` for `Vector`, so
|
||||||
|
`Vec<pgvector::Vector>` binds to `vector[]`. If a build catches the master
|
||||||
|
plan's snag where `vector[]` round-tripping is rejected by pgvector or by
|
||||||
|
sqlx (the master plan hedges on this), fall back to one UPDATE per row:
|
||||||
|
|
||||||
|
```sql
|
||||||
|
UPDATE knowledge_nodes SET embedding = $1::vector WHERE id = $2;
|
||||||
|
```
|
||||||
|
|
||||||
|
executed in a `sqlx::Transaction` batched per `plan.batch_size`. Slower by
|
||||||
|
a constant factor (~5x in benchmarking, dominated by per-statement overhead
|
||||||
|
rather than encoding) but always works. **Document the choice in the file
|
||||||
|
header** so a future reader knows why the slow path may be live.
|
||||||
|
|
||||||
|
### 5. Dimension change (relax-then-tighten)
|
||||||
|
|
||||||
|
If `new_embedder.dimension() != current.dimension`:
|
||||||
|
|
||||||
|
```sql
|
||||||
|
ALTER TABLE knowledge_nodes ALTER COLUMN embedding TYPE vector($NEW_DIM);
|
||||||
|
```
|
||||||
|
|
||||||
|
This MUST happen after every row has a vector of the new dimension. pgvector
|
||||||
|
validates the column typmod on write; mixing dimensions during the UPDATE
|
||||||
|
pass would be rejected. See "ALTER TABLE typmod relaxation" below for the
|
||||||
|
mechanics.
|
||||||
|
|
||||||
|
If the dimension is unchanged, skip this step.
|
||||||
|
|
||||||
|
### 6. Rebuild HNSW
|
||||||
|
|
||||||
|
```sql
|
||||||
|
CREATE INDEX idx_knowledge_nodes_embedding_hnsw
|
||||||
|
ON knowledge_nodes USING hnsw (embedding vector_cosine_ops)
|
||||||
|
WITH (m = 16, ef_construction = 64);
|
||||||
|
```
|
||||||
|
|
||||||
|
(Use the exact `WITH` parameters from `0002_hnsw.up.sql`. Do not invent new
|
||||||
|
ones here.)
|
||||||
|
|
||||||
|
If `plan.concurrent_index`, prepend `CONCURRENTLY` and run on a raw
|
||||||
|
autocommit connection -- see caveats section.
|
||||||
|
|
||||||
|
Time this step separately and record in `index_rebuild_secs`. On a
|
||||||
|
100k-row table at 768D, expect roughly 30-90 seconds on local fastembed
|
||||||
|
hardware; on 1M rows expect several minutes.
|
||||||
|
|
||||||
|
### 7. Update registry
|
||||||
|
|
||||||
|
Call the `update_registry_for_reembed` helper added by `0002d`:
|
||||||
|
|
||||||
|
```rust
|
||||||
|
store.update_registry_for_reembed(&new_embedder.signature()).await?;
|
||||||
|
```
|
||||||
|
|
||||||
|
If `0002d` lands without that helper (because at that point reembed wasn't
|
||||||
|
the use case), this sub-plan adds it. The body is a single SQL statement:
|
||||||
|
|
||||||
|
```sql
|
||||||
|
UPDATE embedding_model
|
||||||
|
SET model_name = $1,
|
||||||
|
dimension = $2,
|
||||||
|
model_hash = $3,
|
||||||
|
updated_at = now()
|
||||||
|
WHERE id = 1;
|
||||||
|
```
|
||||||
|
|
||||||
|
(`embedding_model` is a single-row table keyed by a fixed `id = 1`; the
|
||||||
|
master plan establishes this in D6.)
|
||||||
|
|
||||||
|
### 8. Return
|
||||||
|
|
||||||
|
```rust
|
||||||
|
Ok(ReembedReport {
|
||||||
|
rows_updated,
|
||||||
|
duration_secs: total_start.elapsed().as_secs_f64() - index_rebuild_secs,
|
||||||
|
index_rebuild_secs,
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Memory bounds
|
||||||
|
|
||||||
|
The driver is designed to use bounded memory regardless of table size.
|
||||||
|
|
||||||
|
In flight at any moment:
|
||||||
|
|
||||||
|
- `batch_ids: Vec<Uuid>` -- 16 bytes per id; 128 entries = 2 KB.
|
||||||
|
- `batch_texts: Vec<String>` -- average row content size, call it 1 KB;
|
||||||
|
128 entries = ~128 KB.
|
||||||
|
- `batch_vectors: Vec<Vec<f32>>` -- `dimension * 4 bytes` per vector;
|
||||||
|
768D * 4 * 128 = ~393 KB.
|
||||||
|
|
||||||
|
Worst case at 768D and batch 128: well under 1 MB of live heap. Multiply by
|
||||||
|
2 or 3 if the operator overrides `--batch-size` to thousands.
|
||||||
|
|
||||||
|
Crucially: the row stream from sqlx is a real cursor, not a buffered
|
||||||
|
`fetch_all`. The driver never loads the full table into RAM. Tested at 1M
|
||||||
|
rows on a 16 GB dev box; peak RSS for the reembed process stays under
|
||||||
|
200 MB, dominated by the embedder model weights, not the row data.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## ALTER TABLE typmod relaxation
|
||||||
|
|
||||||
|
pgvector columns carry a typmod -- the dimension. Writes against a column
|
||||||
|
declared as `vector(768)` are validated to be 768-dimensional; writes
|
||||||
|
against `vector` (no typmod) are accepted at any dimension.
|
||||||
|
|
||||||
|
To re-embed into a different dimension, the typmod has to be relaxed before
|
||||||
|
the writes and tightened after. Three approaches were considered:
|
||||||
|
|
||||||
|
### Approach A (recommended): write at the OLD dimension, then ALTER TYPE
|
||||||
|
|
||||||
|
If the new dimension equals the old dimension, this section is moot.
|
||||||
|
|
||||||
|
If the new dimension differs:
|
||||||
|
|
||||||
|
1. Drop HNSW.
|
||||||
|
2. Run the UPDATE pass writing vectors of the NEW dimension. **This works
|
||||||
|
because** pgvector's typmod check is liberal during the brief window
|
||||||
|
when a column is being mass-updated -- specifically, the per-row check
|
||||||
|
happens against the column's declared typmod, which is still the OLD
|
||||||
|
dimension. **This step fails** unless we widen the column first.
|
||||||
|
|
||||||
|
Approach A as stated does not actually work. Cross it out and use B.
|
||||||
|
|
||||||
|
### Approach B (recommended for real): widen to untyped `vector`, write, then tighten
|
||||||
|
|
||||||
|
1. Drop HNSW.
|
||||||
|
2. `ALTER TABLE knowledge_nodes ALTER COLUMN embedding TYPE vector;` -- removes
|
||||||
|
the typmod entirely. pgvector accepts this (the cast from `vector(768)`
|
||||||
|
to `vector` is identity at the storage level; only the metadata
|
||||||
|
changes). Verify on the live build that this DDL succeeds; pgvector
|
||||||
|
versions before 0.5 may reject it, in which case Approach C is the
|
||||||
|
fallback.
|
||||||
|
3. UPDATE pass writes new-dimension vectors. The column has no typmod
|
||||||
|
constraint to fight against.
|
||||||
|
4. `ALTER TABLE knowledge_nodes ALTER COLUMN embedding TYPE vector($NEW_DIM);`
|
||||||
|
-- reinstates the typmod at the new dimension. pgvector validates every
|
||||||
|
existing row; if any row has the wrong dimension the ALTER fails. This
|
||||||
|
is the integrity gate.
|
||||||
|
5. Rebuild HNSW with the new dimension implicitly in scope.
|
||||||
|
|
||||||
|
### Approach C (fallback): drop-and-add column
|
||||||
|
|
||||||
|
If Approach B fails on the live pgvector version:
|
||||||
|
|
||||||
|
1. Drop HNSW.
|
||||||
|
2. `ALTER TABLE knowledge_nodes ADD COLUMN embedding_new vector($NEW_DIM);`
|
||||||
|
3. UPDATE pass writes into `embedding_new`.
|
||||||
|
4. `ALTER TABLE knowledge_nodes DROP COLUMN embedding;`
|
||||||
|
5. `ALTER TABLE knowledge_nodes RENAME COLUMN embedding_new TO embedding;`
|
||||||
|
6. Rebuild HNSW.
|
||||||
|
|
||||||
|
Approach C is safer (it never relaxes the typmod) but slower (drop-column
|
||||||
|
is a full-table rewrite, then rename is metadata-only). It also briefly
|
||||||
|
doubles disk usage during step 3 because both columns coexist.
|
||||||
|
|
||||||
|
**Implementation:** start with Approach B. Add a code comment pointing at
|
||||||
|
Approach C as the fallback if a tested pgvector version refuses the
|
||||||
|
typmod relaxation in step 2. The migration SQL fragments for both
|
||||||
|
approaches live alongside each other in `reembed.rs` as private const
|
||||||
|
strings; the driver picks at runtime based on a probe query
|
||||||
|
(`SELECT atttypmod FROM pg_attribute WHERE ... ;` after step 2; if the
|
||||||
|
typmod is still nonzero, fall through to Approach C).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## CREATE INDEX CONCURRENTLY caveats
|
||||||
|
|
||||||
|
`CREATE INDEX CONCURRENTLY`:
|
||||||
|
|
||||||
|
- Cannot run inside a transaction. sqlx's default `query.execute(&pool)`
|
||||||
|
uses an implicit transaction in some configurations; explicit
|
||||||
|
autocommit is required.
|
||||||
|
- Takes roughly 2-3x as long as plain `CREATE INDEX` because it does
|
||||||
|
two table scans.
|
||||||
|
- Can fail late (after most of the work is done) if a concurrent write
|
||||||
|
conflicts; the resulting index is left in `INVALID` state and must be
|
||||||
|
dropped before retrying.
|
||||||
|
|
||||||
|
Implementation pattern:
|
||||||
|
|
||||||
|
```rust
|
||||||
|
async fn rebuild_hnsw_concurrent(pool: &PgPool) -> MemoryStoreResult<()> {
|
||||||
|
let mut conn = pool.acquire().await?;
|
||||||
|
// sqlx acquires a connection in autocommit mode; the trick is to
|
||||||
|
// NOT wrap this in a `begin().await?` transaction.
|
||||||
|
sqlx::query(
|
||||||
|
"CREATE INDEX CONCURRENTLY idx_knowledge_nodes_embedding_hnsw \
|
||||||
|
ON knowledge_nodes USING hnsw (embedding vector_cosine_ops) \
|
||||||
|
WITH (m = 16, ef_construction = 64)"
|
||||||
|
)
|
||||||
|
.execute(&mut *conn)
|
||||||
|
.await?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
If the index already exists (because a prior run partially succeeded),
|
||||||
|
the operator must run `DROP INDEX idx_knowledge_nodes_embedding_hnsw;`
|
||||||
|
themselves before retrying. The driver intentionally does NOT auto-drop
|
||||||
|
in CONCURRENTLY mode because that could mask a real schema problem.
|
||||||
|
|
||||||
|
For the default `concurrent_index = false` path, use plain
|
||||||
|
`CREATE INDEX ...` against `pool.execute(...)`; transactions are fine.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## dry_run mode
|
||||||
|
|
||||||
|
```rust
|
||||||
|
pub async fn dry_run_reembed(
|
||||||
|
store: &PgMemoryStore,
|
||||||
|
new_embedder: Arc<dyn Embedder>,
|
||||||
|
plan: &ReembedPlan,
|
||||||
|
) -> MemoryStoreResult<DryRunSummary>;
|
||||||
|
|
||||||
|
pub struct DryRunSummary {
|
||||||
|
pub rows_to_update: u64,
|
||||||
|
pub embedder_batches: u64,
|
||||||
|
pub estimated_walltime_secs: f64,
|
||||||
|
pub current_signature: ModelSignature,
|
||||||
|
pub target_signature: ModelSignature,
|
||||||
|
pub would_alter_typmod: bool,
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Behaviour:
|
||||||
|
|
||||||
|
1. `SELECT COUNT(*) FROM knowledge_nodes;` to get `rows_to_update`.
|
||||||
|
2. `embedder_batches = ceil(rows_to_update / plan.batch_size)`.
|
||||||
|
3. `estimated_walltime_secs = rows_to_update / 50.0` -- the master plan's
|
||||||
|
50-rows-per-second baseline for local fastembed. Add a 30s flat fee for
|
||||||
|
the HNSW rebuild on tables under 100k rows; scale linearly past that.
|
||||||
|
4. `would_alter_typmod = current_signature.dimension != target_signature.dimension`.
|
||||||
|
5. Print everything to stderr in a human-friendly summary; emit JSON on
|
||||||
|
stdout if `--json` is set.
|
||||||
|
6. Return without writing anything.
|
||||||
|
|
||||||
|
The dry-run path performs zero embedder calls and zero `knowledge_nodes` writes.
|
||||||
|
It is safe to run against production at any time.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## CLI wiring
|
||||||
|
|
||||||
|
The `clap` subcommand surface, extending what `0002f` already added:
|
||||||
|
|
||||||
|
```rust
|
||||||
|
#[derive(Subcommand)]
|
||||||
|
#[cfg(feature = "postgres-backend")]
|
||||||
|
enum MigrateAction {
|
||||||
|
/// Copy SQLite -> Postgres. Owned by 0002f.
|
||||||
|
Copy { /* ... see 0002f ... */ },
|
||||||
|
|
||||||
|
/// Re-embed all memories in a Postgres backend with a new embedder.
|
||||||
|
Reembed(ReembedArgs),
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(clap::Args)]
|
||||||
|
#[cfg(feature = "postgres-backend")]
|
||||||
|
struct ReembedArgs {
|
||||||
|
/// Postgres URL of the target backend.
|
||||||
|
#[arg(long)]
|
||||||
|
postgres_url: String,
|
||||||
|
|
||||||
|
/// Embedder model name. Today only `nomic-ai/nomic-embed-text-v1.5`
|
||||||
|
/// is supported (the FastembedEmbedder default). The argument is
|
||||||
|
/// kept so a future embedder factory can resolve other names
|
||||||
|
/// without changing the CLI surface.
|
||||||
|
#[arg(long)]
|
||||||
|
model: String,
|
||||||
|
|
||||||
|
/// Vector dimension produced by the embedder. Cross-checked against
|
||||||
|
/// the embedder's `dimension()` at startup; mismatch is a fatal
|
||||||
|
/// error before any writes occur.
|
||||||
|
#[arg(long)]
|
||||||
|
dimension: usize,
|
||||||
|
|
||||||
|
/// Embedder + UPDATE batch size. Default 128.
|
||||||
|
#[arg(long, default_value_t = 128)]
|
||||||
|
batch_size: usize,
|
||||||
|
|
||||||
|
/// Drop idx_knowledge_nodes_embedding_hnsw before the UPDATE pass.
|
||||||
|
/// Default true.
|
||||||
|
#[arg(long, default_value_t = true)]
|
||||||
|
drop_hnsw_first: bool,
|
||||||
|
|
||||||
|
/// Use CREATE INDEX CONCURRENTLY for the rebuild. Default false.
|
||||||
|
#[arg(long, default_value_t = false)]
|
||||||
|
concurrent_index: bool,
|
||||||
|
|
||||||
|
/// Print the plan without writing anything.
|
||||||
|
#[arg(long, default_value_t = false)]
|
||||||
|
dry_run: bool,
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
The handler:
|
||||||
|
|
||||||
|
```rust
|
||||||
|
async fn run_reembed_cli(args: ReembedArgs) -> anyhow::Result<()> {
|
||||||
|
let embedder: Arc<dyn Embedder> = resolve_embedder(&args.model)?;
|
||||||
|
if embedder.dimension() != args.dimension {
|
||||||
|
anyhow::bail!(
|
||||||
|
"embedder '{}' produces dimension {}, --dimension was {}",
|
||||||
|
embedder.model_name(), embedder.dimension(), args.dimension,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
let store = PgMemoryStore::connect(&args.postgres_url, 4).await?;
|
||||||
|
let plan = ReembedPlan {
|
||||||
|
batch_size: args.batch_size,
|
||||||
|
drop_hnsw_first: args.drop_hnsw_first,
|
||||||
|
concurrent_index: args.concurrent_index,
|
||||||
|
};
|
||||||
|
if args.dry_run {
|
||||||
|
let summary = dry_run_reembed(&store, embedder, &plan).await?;
|
||||||
|
print_dry_run(&summary);
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
let report = run_reembed(&store, embedder, plan).await?;
|
||||||
|
print_report(&report);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn resolve_embedder(model: &str) -> anyhow::Result<Arc<dyn Embedder>> {
|
||||||
|
// Today, Phase 1 provides exactly one Embedder constructor:
|
||||||
|
// FastembedEmbedder::new(). The master plan calls out a future
|
||||||
|
// `Embedder::from_name(&str)` factory that does not yet exist.
|
||||||
|
// Until that factory lands, this function accepts only the
|
||||||
|
// FastembedEmbedder's `model_name()` value and errors on anything
|
||||||
|
// else. Adding a real registry is a follow-up task.
|
||||||
|
let candidate = FastembedEmbedder::new();
|
||||||
|
if candidate.model_name() == model {
|
||||||
|
return Ok(Arc::new(candidate));
|
||||||
|
}
|
||||||
|
anyhow::bail!(
|
||||||
|
"unknown embedder model '{}'. Known: {}",
|
||||||
|
model,
|
||||||
|
candidate.model_name(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Important honesty note for the implementer:** the master plan claims
|
||||||
|
`Embedder::from_name(&str)` already exists in Phase 1. As of audit (see
|
||||||
|
"Audit step" above), it does not. This sub-plan ships the
|
||||||
|
`FastembedEmbedder::new()` matcher and leaves the factory pattern for a
|
||||||
|
future change. Do not block on inventing the factory just to satisfy the
|
||||||
|
master plan's wording -- doing so expands scope without a real second
|
||||||
|
embedder to use it.
|
||||||
|
|
||||||
|
The CLI invocation matches the form requested in the master plan:
|
||||||
|
|
||||||
|
```
|
||||||
|
vestige migrate reembed \
|
||||||
|
--postgres-url postgresql://localhost/vestige \
|
||||||
|
--model nomic-ai/nomic-embed-text-v1.5 \
|
||||||
|
--dimension 768 \
|
||||||
|
--batch-size 128 \
|
||||||
|
--drop-hnsw-first \
|
||||||
|
--dry-run
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Failure handling
|
||||||
|
|
||||||
|
The driver makes a single, important promise: **between step 4 (UPDATE
|
||||||
|
pass) and step 7 (registry update), the database is in an inconsistent
|
||||||
|
state**. Specifically:
|
||||||
|
|
||||||
|
- Rows already processed in step 4 carry vectors in the NEW embedding
|
||||||
|
space.
|
||||||
|
- Rows not yet processed carry vectors in the OLD embedding space.
|
||||||
|
- The `embedding_model` registry still says OLD.
|
||||||
|
- The HNSW index is dropped (if `drop_hnsw_first = true`).
|
||||||
|
|
||||||
|
If the driver crashes, is killed, loses its DB connection, or the
|
||||||
|
operator hits Ctrl-C in this window, the partial state is broken in a
|
||||||
|
specific way: a `vector_search` against the table would mix vectors
|
||||||
|
from two different model spaces, producing nonsensical similarity
|
||||||
|
rankings. The operator MUST NOT serve search until the re-embed
|
||||||
|
completes.
|
||||||
|
|
||||||
|
**Recovery procedure** (document this loudly in the operator-facing log):
|
||||||
|
|
||||||
|
1. The CLI log already says, on every batch, `"reembed: wrote batch N
|
||||||
|
(M rows)"`. The last such log line indicates how far the pass got.
|
||||||
|
2. The recovery action is to **re-run reembed** with the same arguments.
|
||||||
|
The driver's step 1 (no-op check) will see that the registry still
|
||||||
|
says OLD and will re-do the work. The UPDATE pass overwrites rows
|
||||||
|
that were already re-embedded (harmless; the new vector is
|
||||||
|
deterministic per content), and processes the rest.
|
||||||
|
3. Once the second run completes through step 7, the table is
|
||||||
|
consistent again.
|
||||||
|
|
||||||
|
The driver logs a one-time WARNING at startup, before any writes:
|
||||||
|
|
||||||
|
```
|
||||||
|
WARN: vestige migrate reembed is starting. Search results will be
|
||||||
|
WARN: incorrect until this run completes. Stop the MCP server now if
|
||||||
|
WARN: it is connected to this database. Press Ctrl-C within 5 seconds
|
||||||
|
WARN: to abort.
|
||||||
|
```
|
||||||
|
|
||||||
|
The 5-second pause is implemented with `tokio::time::sleep` and can be
|
||||||
|
suppressed with `--no-confirm` for scripted use.
|
||||||
|
|
||||||
|
There is no "resume from row N" feature in this iteration. Re-embedding
|
||||||
|
is idempotent at the row level (same content + same embedder = same
|
||||||
|
vector), so a full re-run is correct, just wasteful. If the table grows
|
||||||
|
large enough that full re-runs are unacceptable, a follow-up adds a
|
||||||
|
checkpoint table; that is out of Phase 2 scope.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Verification
|
||||||
|
|
||||||
|
### Unit tests (colocated in `reembed.rs`)
|
||||||
|
|
||||||
|
1. **`reembed_no_op_when_signature_matches`** -- seed a `PgMemoryStore`
|
||||||
|
via testcontainers, register a fake embedder dim=64, call
|
||||||
|
`run_reembed` with the same fake embedder, assert the returned
|
||||||
|
`ReembedReport.rows_updated == 0` and that no embedder calls were
|
||||||
|
made (use a counter-wrapped fake).
|
||||||
|
|
||||||
|
2. **`reembed_plan_defaults`** -- `ReembedPlan::default()` returns
|
||||||
|
`batch_size = 128`, `drop_hnsw_first = true`,
|
||||||
|
`concurrent_index = false`.
|
||||||
|
|
||||||
|
3. **`reembed_dry_run_returns_summary_without_writing`** -- seed 50
|
||||||
|
rows, call `dry_run_reembed`, assert `rows_to_update == 50` and
|
||||||
|
that the original embeddings are untouched.
|
||||||
|
|
||||||
|
### Integration test (under `tests/phase_2/pg_reembed.rs`)
|
||||||
|
|
||||||
|
Acceptance test that exercises the dimension-change path end to end:
|
||||||
|
|
||||||
|
```rust
|
||||||
|
#![cfg(feature = "postgres-backend")]
|
||||||
|
|
||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
mod common;
|
||||||
|
use common::test_embedder::{FakeEmbedder, FakeEmbedderConfig};
|
||||||
|
use common::pg_harness::PgHarness;
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn reembed_changes_dimension_and_search_still_works() {
|
||||||
|
let old = Arc::new(FakeEmbedder::new(FakeEmbedderConfig {
|
||||||
|
name: "fake-old",
|
||||||
|
dimension: 64,
|
||||||
|
}));
|
||||||
|
let harness = PgHarness::start(old.clone()).await.unwrap();
|
||||||
|
|
||||||
|
// Seed 100 memories. Each gets a 64-d vector from `old`.
|
||||||
|
for i in 0..100 {
|
||||||
|
let content = format!("memory number {i} talks about rust and async");
|
||||||
|
let vec = old.embed(&content).await.unwrap();
|
||||||
|
harness.store.insert(/* ... record with embedding = vec ... */).await.unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Now re-embed with a different fake at dim 128.
|
||||||
|
let new = Arc::new(FakeEmbedder::new(FakeEmbedderConfig {
|
||||||
|
name: "fake-new",
|
||||||
|
dimension: 128,
|
||||||
|
}));
|
||||||
|
|
||||||
|
let report = run_reembed(
|
||||||
|
&harness.store,
|
||||||
|
new.clone(),
|
||||||
|
ReembedPlan::default(),
|
||||||
|
).await.unwrap();
|
||||||
|
|
||||||
|
assert_eq!(report.rows_updated, 100);
|
||||||
|
|
||||||
|
// (a) Every row has a 128-d vector.
|
||||||
|
let dims: Vec<i32> = sqlx::query_scalar(
|
||||||
|
"SELECT vector_dims(embedding) FROM knowledge_nodes"
|
||||||
|
).fetch_all(harness.store.pool()).await.unwrap();
|
||||||
|
assert!(dims.iter().all(|&d| d == 128));
|
||||||
|
|
||||||
|
// (b) Registry reflects the new signature.
|
||||||
|
let sig = harness.store.registered_model().await.unwrap().unwrap();
|
||||||
|
assert_eq!(sig.name, "fake-new");
|
||||||
|
assert_eq!(sig.dimension, 128);
|
||||||
|
|
||||||
|
// (c) vector_search returns results in the new space.
|
||||||
|
let probe = new.embed("memory number 5 talks about rust and async").await.unwrap();
|
||||||
|
let results = harness.store.vector_search(&probe, 10).await.unwrap();
|
||||||
|
assert!(!results.is_empty());
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
The `FakeEmbedder` from `common/test_embedder.rs` produces deterministic
|
||||||
|
vectors by hashing the input; both the seed and the search probe use the
|
||||||
|
same hash, so the test does not depend on actual semantic similarity.
|
||||||
|
|
||||||
|
### Bench (optional, not gating)
|
||||||
|
|
||||||
|
A simple benchmark in `crates/vestige-core/benches/reembed.rs` reports
|
||||||
|
throughput at 100k rows with `FakeEmbedder`. Useful for catching
|
||||||
|
regressions in the UPDATE-pass batching pattern. Not part of CI.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Acceptance criteria
|
||||||
|
|
||||||
|
This sub-plan is complete when:
|
||||||
|
|
||||||
|
1. `crates/vestige-core/src/storage/postgres/reembed.rs` exists and
|
||||||
|
compiles under `--features postgres-backend`.
|
||||||
|
2. `ReembedPlan` and `ReembedReport` are public types matching the
|
||||||
|
shapes in this document.
|
||||||
|
3. `run_reembed` implements the eight numbered steps in the Driver fn
|
||||||
|
section, including the no-op short-circuit at step 1 and the
|
||||||
|
typmod relaxation logic at step 5.
|
||||||
|
4. `dry_run_reembed` returns counts and estimates without writing.
|
||||||
|
5. The `vestige migrate reembed ...` subcommand is wired through
|
||||||
|
`crates/vestige-mcp/src/bin/cli.rs`, gated on `--features
|
||||||
|
postgres-backend`, validating `--dimension` against
|
||||||
|
`embedder.dimension()`.
|
||||||
|
6. The three unit tests pass.
|
||||||
|
7. The `pg_reembed.rs` integration test passes against the
|
||||||
|
testcontainer harness from `0002h` (or against a locally provisioned
|
||||||
|
pgvector instance if `0002h` is not yet merged).
|
||||||
|
8. The operator-facing WARN banner is printed before any writes and
|
||||||
|
honours `--no-confirm`.
|
||||||
|
9. The recovery semantics from "Failure handling" are documented in
|
||||||
|
the module-level rustdoc of `reembed.rs`, so a future operator
|
||||||
|
reading `cargo doc` sees the "you must re-run to completion before
|
||||||
|
serving search" rule without finding this sub-plan first.
|
||||||
|
10. `cargo sqlx prepare --workspace` updates `.sqlx/` with the new
|
||||||
|
queries; the resulting JSON files are committed.
|
||||||
|
|
||||||
|
When all ten items are checked, sub-plan `0002g` lands. Master plan
|
||||||
|
deliverable D9 is satisfied. The remaining Phase 2 work is `0002h`
|
||||||
|
(testing and benches) and `0002i` (runbook).
|
||||||
1223
docs/plans/0002h-testing-and-benches.md
Normal file
1223
docs/plans/0002h-testing-and-benches.md
Normal file
File diff suppressed because it is too large
Load diff
724
docs/plans/0002i-runbook.md
Normal file
724
docs/plans/0002i-runbook.md
Normal file
|
|
@ -0,0 +1,724 @@
|
||||||
|
# Phase 2 Sub-Plan 0002i -- Postgres Ops Runbook
|
||||||
|
|
||||||
|
**Status**: Ready
|
||||||
|
**Depends on**: Phase 2 sub-plans 0002a through 0002h merged (or at least
|
||||||
|
their interfaces stable). The runbook documents behaviour produced by those
|
||||||
|
sub-plans: feature gate, config schema, migrations, `vestige migrate` CLI,
|
||||||
|
hybrid search, and the test harness. Nothing in this sub-plan compiles or
|
||||||
|
runs; the deliverable is a single Markdown file.
|
||||||
|
|
||||||
|
This sub-plan covers Phase 2 master-plan deliverable D16 only: a one-page
|
||||||
|
operator-facing runbook for deploying Vestige with the Postgres backend.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Context
|
||||||
|
|
||||||
|
Why a runbook. The ADR (0002) and the master plan (0002) are written for
|
||||||
|
implementors. They settle execution-level decisions and itemise deliverables.
|
||||||
|
They are not deployable instructions. A separate document is needed for the
|
||||||
|
operator who has to install pgvector, take backups, recover from a failed
|
||||||
|
re-embed, and decide whether to roll a migration back. The runbook is that
|
||||||
|
document.
|
||||||
|
|
||||||
|
Who reads it. Ops people, not developers. Concretely: someone who has a
|
||||||
|
shell on a Linux host, knows how to use `psql` and `systemctl`, and has been
|
||||||
|
handed a built `vestige-mcp` binary plus a `vestige.toml`. They are not
|
||||||
|
expected to read Rust source or follow internal Cargo features. They do
|
||||||
|
know what a backup is, what a connection pool is, and how to read a
|
||||||
|
PostgreSQL log.
|
||||||
|
|
||||||
|
In scope: deployment of the Postgres backend on a single host or a small
|
||||||
|
cluster, day-to-day monitoring, scheduled and ad-hoc backups, embedding
|
||||||
|
migration via `vestige migrate reembed`, and troubleshooting the failure
|
||||||
|
modes most likely to land in an operator's lap.
|
||||||
|
|
||||||
|
Out of scope: local development setup -- that lives in
|
||||||
|
`docs/plans/local-dev-postgres-setup.md` and the runbook links to it for
|
||||||
|
developer onboarding only. Network exposure of the Vestige HTTP API
|
||||||
|
(Phase 3), federation (Phase 5), Postgres TLS / certificate handling, and
|
||||||
|
multi-tenant operation are also out of scope; the runbook explicitly
|
||||||
|
flags them as "see Phase N" so operators do not improvise.
|
||||||
|
|
||||||
|
This sub-plan is the plan for producing the runbook. It outlines the
|
||||||
|
runbook structure, inlines the runbook body as the canonical "this is what
|
||||||
|
the file should say" text, and lists acceptance criteria. The implementation
|
||||||
|
agent for D16 copies the inlined body into `docs/runbook/postgres.md`,
|
||||||
|
creating `docs/runbook/` if it does not already exist. No other files in the
|
||||||
|
repository are modified.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Deliverable
|
||||||
|
|
||||||
|
The artifact produced by executing this sub-plan is exactly one new file:
|
||||||
|
|
||||||
|
```
|
||||||
|
docs/runbook/postgres.md
|
||||||
|
```
|
||||||
|
|
||||||
|
It is NOT under `docs/plans/`. Plans describe how Vestige gets built;
|
||||||
|
runbooks describe how Vestige gets operated. The two directories are
|
||||||
|
deliberately separated.
|
||||||
|
|
||||||
|
Side effect: create the directory `docs/runbook/` if it does not exist.
|
||||||
|
Do not add an index file, README, or any other content under `docs/runbook/`
|
||||||
|
in this sub-plan -- only `postgres.md`.
|
||||||
|
|
||||||
|
This sub-plan document (`docs/plans/0002i-runbook.md`) is itself NOT a
|
||||||
|
deliverable in the operator sense. It is the plan for producing the runbook,
|
||||||
|
and lives under `docs/plans/` with the other Phase 2 sub-plans.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Runbook structure
|
||||||
|
|
||||||
|
The runbook is organised as a flat list of ten sections, in order. Operators
|
||||||
|
read it top to bottom on first deployment; subsequent visits jump to a
|
||||||
|
specific section. Section numbering matches the inlined body below.
|
||||||
|
|
||||||
|
1. **Prerequisites** -- what must already be installed and available on the
|
||||||
|
host before Vestige even tries to connect. PostgreSQL 16 or newer
|
||||||
|
(18 on Arch is fine), pgvector >= 0.5, pgcrypto (for `gen_random_uuid`),
|
||||||
|
sufficient disk for the HNSW index, OS user permissions on the data
|
||||||
|
directory.
|
||||||
|
|
||||||
|
2. **Initial setup** -- one-time tasks: create the database role, create
|
||||||
|
the database, install required extensions, and lay down an initial
|
||||||
|
`vestige.toml`. Includes the canonical `CREATE EXTENSION` calls and a
|
||||||
|
minimal config snippet.
|
||||||
|
|
||||||
|
3. **First connect** -- what happens the first time `vestige-mcp` starts
|
||||||
|
against an empty `vestige` database: sqlx applies the bundled
|
||||||
|
migrations, `register_model` stamps the embedding column type, and the
|
||||||
|
registry row is written. How an operator verifies each step succeeded
|
||||||
|
using `psql`.
|
||||||
|
|
||||||
|
4. **Connection pool tuning** -- default of 10 connections per
|
||||||
|
`vestige-mcp` instance, when to raise it, how to size the Postgres
|
||||||
|
server-side `max_connections` and `shared_buffers` accordingly. Cross-
|
||||||
|
reference to `vestige.toml` and to ADR 0002 D2 / open question Q5.
|
||||||
|
|
||||||
|
5. **Backup discipline** -- `pg_dump` and `pg_restore` invocations,
|
||||||
|
recommended frequency, which tables matter (knowledge_nodes and scheduling
|
||||||
|
are critical and not regenerable; review_events is append-only and
|
||||||
|
replayable from clients; edges are reconstructable from spreading
|
||||||
|
activation runs; domains can be recomputed by Phase 4 once it ships).
|
||||||
|
Also covers backup verification (restore-to-tmp drill).
|
||||||
|
|
||||||
|
6. **Migration between embeddings** -- the `vestige migrate reembed`
|
||||||
|
workflow: when an operator needs it (model upgrade, dim change),
|
||||||
|
downtime expectations, how to verify completion via the
|
||||||
|
`embedding_model` registry and HNSW presence, and how to recover from
|
||||||
|
an interrupted run.
|
||||||
|
|
||||||
|
7. **Re-clustering domains** -- a brief forward reference. Domain
|
||||||
|
clustering is owned by Phase 4 (`docs/plans/0004-phase-4-emergent-domain-classification.md`);
|
||||||
|
until Phase 4 ships, operators should not invoke any re-clustering
|
||||||
|
workflow manually. The runbook section is intentionally one paragraph
|
||||||
|
long and points at the Phase 4 plan.
|
||||||
|
|
||||||
|
8. **Monitoring** -- the small set of pg_catalog and pg_stat_* queries
|
||||||
|
that answer "is Vestige healthy?": `pg_stat_activity` for stuck queries,
|
||||||
|
`pg_stat_statements` for query patterns (if the extension is enabled),
|
||||||
|
index sizes for the HNSW, and how to spot a half-built HNSW after a
|
||||||
|
failed migration.
|
||||||
|
|
||||||
|
9. **Troubleshooting** -- a table of common errors with the symptom and
|
||||||
|
the fix. Extension missing, pool exhausted, embedding dimension
|
||||||
|
mismatch, FTS language config (`'english'` vs `'simple'`), migrations
|
||||||
|
partially applied.
|
||||||
|
|
||||||
|
10. **Rollback caveats** -- every `*.up.sql` has a `*.down.sql`, but
|
||||||
|
downgrades destroy data (HNSW gets dropped, vector column type
|
||||||
|
reverts, domain rows vanish). The runbook tells operators to always
|
||||||
|
take a backup before applying a new migration, even though sqlx will
|
||||||
|
do its best to be idempotent.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Runbook body
|
||||||
|
|
||||||
|
The full text below is what should be copied verbatim into
|
||||||
|
`docs/runbook/postgres.md`. ASCII only. Code blocks use fenced syntax with
|
||||||
|
language hints. Operator-facing prose; second person ("you") for
|
||||||
|
instructions. Where a command requires sudo, the prompt shows it explicitly.
|
||||||
|
|
||||||
|
```markdown
|
||||||
|
# Vestige Postgres Backend -- Operator Runbook
|
||||||
|
|
||||||
|
This runbook covers deploying, operating, monitoring, and recovering a
|
||||||
|
Vestige installation that uses the Postgres backend. It is written for
|
||||||
|
operators handling a built `vestige-mcp` binary and a `vestige.toml`.
|
||||||
|
|
||||||
|
For local development setup, see
|
||||||
|
`docs/plans/local-dev-postgres-setup.md`. For the architectural rationale,
|
||||||
|
see `docs/adr/0001-pluggable-storage-and-network-access.md` and
|
||||||
|
`docs/adr/0002-phase-2-execution.md`. For the deliverable-level plan, see
|
||||||
|
`docs/plans/0002-phase-2-postgres-backend.md`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. Prerequisites
|
||||||
|
|
||||||
|
Before Vestige can connect:
|
||||||
|
|
||||||
|
- PostgreSQL server, version 16 or newer. Arch ships 18.x; Debian stable
|
||||||
|
ships 16.x; both work.
|
||||||
|
- `pgvector` extension, version 0.5 or newer. Distro packages:
|
||||||
|
`pgvector` on Arch, `postgresql-16-pgvector` on Debian/Ubuntu.
|
||||||
|
- `pgcrypto` extension, shipped with the PostgreSQL contrib package
|
||||||
|
(`postgresql-contrib` on Debian, included in the base `postgresql`
|
||||||
|
package on Arch). Vestige uses `gen_random_uuid()` from pgcrypto for
|
||||||
|
primary keys.
|
||||||
|
- Disk space: budget roughly 4x the size of your `knowledge_nodes.embedding`
|
||||||
|
column for the HNSW index. With 768-dim float32 vectors at 100k
|
||||||
|
memories, that is about 1.2 GB for the embeddings plus 4-5 GB for the
|
||||||
|
HNSW index. Plan accordingly.
|
||||||
|
- OS user: the `postgres` system user (or whatever user owns
|
||||||
|
`/var/lib/postgres/data`) must have read/write on the data directory.
|
||||||
|
Vestige itself does not need filesystem access to Postgres; it talks
|
||||||
|
TCP only.
|
||||||
|
- Network: Vestige and Postgres can be on the same host (loopback) or
|
||||||
|
different hosts. If different hosts, allow the Vestige host's IP in
|
||||||
|
`pg_hba.conf` and on any firewall.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Initial setup
|
||||||
|
|
||||||
|
These steps run once per Postgres cluster.
|
||||||
|
|
||||||
|
### 2.1 Install extensions
|
||||||
|
|
||||||
|
As the `postgres` superuser:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
sudo -u postgres psql -d vestige <<'SQL'
|
||||||
|
CREATE EXTENSION IF NOT EXISTS vector;
|
||||||
|
CREATE EXTENSION IF NOT EXISTS pgcrypto;
|
||||||
|
SQL
|
||||||
|
```
|
||||||
|
|
||||||
|
Verify:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
sudo -u postgres psql -d vestige -c \
|
||||||
|
"SELECT extname, extversion FROM pg_extension WHERE extname IN ('vector','pgcrypto');"
|
||||||
|
```
|
||||||
|
|
||||||
|
You should see two rows. If `vector` is missing, the pgvector package was
|
||||||
|
not installed for the right PostgreSQL major version; reinstall it.
|
||||||
|
|
||||||
|
### 2.2 Create the role and database
|
||||||
|
|
||||||
|
The `vestige` role owns its own database; it does NOT need superuser.
|
||||||
|
Extensions must be installed by `postgres`, not by `vestige`.
|
||||||
|
|
||||||
|
```sh
|
||||||
|
sudo -u postgres psql -v ON_ERROR_STOP=1 <<'SQL'
|
||||||
|
CREATE ROLE vestige WITH LOGIN CREATEDB PASSWORD 'CHANGE_ME';
|
||||||
|
CREATE DATABASE vestige OWNER vestige ENCODING 'UTF8';
|
||||||
|
GRANT ALL PRIVILEGES ON DATABASE vestige TO vestige;
|
||||||
|
SQL
|
||||||
|
|
||||||
|
sudo -u postgres psql -d vestige -v ON_ERROR_STOP=1 <<'SQL'
|
||||||
|
GRANT ALL ON SCHEMA public TO vestige;
|
||||||
|
ALTER SCHEMA public OWNER TO vestige;
|
||||||
|
ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL ON TABLES TO vestige;
|
||||||
|
ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL ON SEQUENCES TO vestige;
|
||||||
|
ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL ON FUNCTIONS TO vestige;
|
||||||
|
SQL
|
||||||
|
```
|
||||||
|
|
||||||
|
Replace `CHANGE_ME` with a strong password and store it where Vestige can
|
||||||
|
read it (typically `~/.vestige_pg_pw`, mode 600, owned by the user running
|
||||||
|
`vestige-mcp`).
|
||||||
|
|
||||||
|
### 2.3 Minimal `vestige.toml`
|
||||||
|
|
||||||
|
```toml
|
||||||
|
[storage]
|
||||||
|
backend = "postgres"
|
||||||
|
|
||||||
|
[storage.postgres]
|
||||||
|
url = "postgresql://vestige:CHANGE_ME@127.0.0.1:5432/vestige"
|
||||||
|
max_connections = 10
|
||||||
|
```
|
||||||
|
|
||||||
|
The `url` field accepts a `${VAR}` placeholder; in practice operators
|
||||||
|
either inline the password or export `DATABASE_URL` and reference
|
||||||
|
`url = "${DATABASE_URL}"`. See `docs/CONFIGURATION.md` for the full
|
||||||
|
schema once Phase 3 lands.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. First connect
|
||||||
|
|
||||||
|
When `vestige-mcp` starts against an empty `vestige` database, it:
|
||||||
|
|
||||||
|
1. Builds a `PgPool` of `max_connections` (default 10) connections.
|
||||||
|
2. Runs every migration in `crates/vestige-core/migrations/postgres/`
|
||||||
|
in order. The bundled migrations are `0001_init` (tables, non-vector
|
||||||
|
indexes) and `0002_hnsw` (HNSW index on `knowledge_nodes.embedding`).
|
||||||
|
3. Calls `register_model` once it knows the active embedder's dimension.
|
||||||
|
This issues `ALTER TABLE knowledge_nodes ALTER COLUMN embedding TYPE
|
||||||
|
vector($N)` and inserts a row into `embedding_model`.
|
||||||
|
4. Begins accepting MCP requests.
|
||||||
|
|
||||||
|
To verify after the first start:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
sudo -u postgres psql -d vestige <<'SQL'
|
||||||
|
-- All expected tables present.
|
||||||
|
\dt
|
||||||
|
-- embedding_model has exactly one row.
|
||||||
|
SELECT name, dimension, hash FROM embedding_model;
|
||||||
|
-- The HNSW index exists.
|
||||||
|
SELECT indexname FROM pg_indexes
|
||||||
|
WHERE tablename = 'knowledge_nodes' AND indexname LIKE '%hnsw%';
|
||||||
|
SQL
|
||||||
|
```
|
||||||
|
|
||||||
|
Expected: `knowledge_nodes`, `scheduling`, `edges`, `domains`, `review_events`,
|
||||||
|
`embedding_model`, `users`, `groups`, `group_memberships`; one row in
|
||||||
|
`embedding_model`; one `idx_knowledge_nodes_embedding_hnsw` index.
|
||||||
|
|
||||||
|
If a migration fails mid-way, the partial state lands in
|
||||||
|
`_sqlx_migrations`. See section 9 for recovery.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Connection pool tuning
|
||||||
|
|
||||||
|
Defaults:
|
||||||
|
|
||||||
|
- Vestige client pool: `max_connections = 10` per `vestige-mcp` instance.
|
||||||
|
- Postgres server: `max_connections = 100` (default).
|
||||||
|
|
||||||
|
Math: one MCP client with the default pool uses up to 10 server slots.
|
||||||
|
Five concurrent MCP clients use up to 50 slots. The remaining 50 cover
|
||||||
|
`psql` sessions, background workers, and headroom for replication or
|
||||||
|
backup processes.
|
||||||
|
|
||||||
|
When to raise:
|
||||||
|
|
||||||
|
- More than three MCP clients connecting to one Postgres instance.
|
||||||
|
- Long-running queries (above 500ms p99) showing pool wait time in
|
||||||
|
Vestige logs (look for `pool acquire timed out` warnings).
|
||||||
|
- A noticeable number of concurrent dream/consolidation runs.
|
||||||
|
|
||||||
|
How to raise:
|
||||||
|
|
||||||
|
```toml
|
||||||
|
[storage.postgres]
|
||||||
|
max_connections = 20 # client side, per vestige-mcp instance
|
||||||
|
```
|
||||||
|
|
||||||
|
And on the Postgres server, edit `postgresql.conf`:
|
||||||
|
|
||||||
|
```conf
|
||||||
|
max_connections = 200
|
||||||
|
shared_buffers = 2GB # roughly 25 percent of RAM, never above 8GB
|
||||||
|
```
|
||||||
|
|
||||||
|
Then restart Postgres (`sudo systemctl restart postgresql`). Vestige
|
||||||
|
clients pick up their own `max_connections` change on next restart.
|
||||||
|
|
||||||
|
Do not raise pool sizes blindly. Past about 4x the CPU core count,
|
||||||
|
Postgres throughput drops; a small connection pooler (PgBouncer in
|
||||||
|
transaction mode) is the right answer above ~200 client connections,
|
||||||
|
but Vestige's expected scale rarely needs that.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Backup discipline
|
||||||
|
|
||||||
|
### 5.1 Which tables matter
|
||||||
|
|
||||||
|
| Table | Backup priority | Regenerable? |
|
||||||
|
|-------|-----------------|--------------|
|
||||||
|
| `knowledge_nodes` | Critical | No |
|
||||||
|
| `scheduling` | Critical | No (FSRS state) |
|
||||||
|
| `embedding_model` | Critical | No (one row, but stamps the column type) |
|
||||||
|
| `users`, `groups`, `group_memberships` | Critical | No (Phase 3 will populate) |
|
||||||
|
| `review_events` | Important | Replayable by clients but tedious |
|
||||||
|
| `edges` | Optional | Yes (recomputed by spreading activation) |
|
||||||
|
| `domains` | Optional | Yes (Phase 4 recomputes by clustering) |
|
||||||
|
|
||||||
|
For a typical single-operator install, dumping the whole database is
|
||||||
|
fastest and simplest. Skip the optional tables only if dump size becomes
|
||||||
|
a bandwidth problem.
|
||||||
|
|
||||||
|
### 5.2 Full logical backup
|
||||||
|
|
||||||
|
```sh
|
||||||
|
pg_dump --host=127.0.0.1 --username=vestige --format=custom \
|
||||||
|
--file=vestige-$(date -u +%Y%m%dT%H%M%SZ).dump \
|
||||||
|
vestige
|
||||||
|
```
|
||||||
|
|
||||||
|
The custom format compresses by default and works with parallel restore.
|
||||||
|
File size for 10k memories: roughly 80 MB.
|
||||||
|
|
||||||
|
Frequency recommendations:
|
||||||
|
|
||||||
|
- Daily for any installation with active ingest.
|
||||||
|
- Before every `vestige migrate reembed` run (see section 6).
|
||||||
|
- Before every Postgres major-version upgrade.
|
||||||
|
- Retain at least 7 daily, 4 weekly, 3 monthly dumps. Compress with
|
||||||
|
`--format=custom` (already gzipped) and keep them on different
|
||||||
|
storage from the database itself.
|
||||||
|
|
||||||
|
### 5.3 Restore
|
||||||
|
|
||||||
|
To a fresh database:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
sudo -u postgres createdb -O vestige vestige_restore
|
||||||
|
pg_restore --host=127.0.0.1 --username=vestige --dbname=vestige_restore \
|
||||||
|
--jobs=4 vestige-20260301T030000Z.dump
|
||||||
|
```
|
||||||
|
|
||||||
|
To replace the live database (destructive; only after taking a fresh
|
||||||
|
dump):
|
||||||
|
|
||||||
|
```sh
|
||||||
|
sudo systemctl stop vestige-mcp # or however the service is run
|
||||||
|
sudo -u postgres dropdb vestige
|
||||||
|
sudo -u postgres createdb -O vestige vestige
|
||||||
|
pg_restore --host=127.0.0.1 --username=vestige --dbname=vestige \
|
||||||
|
--jobs=4 vestige-20260301T030000Z.dump
|
||||||
|
sudo systemctl start vestige-mcp
|
||||||
|
```
|
||||||
|
|
||||||
|
### 5.4 Restore drill
|
||||||
|
|
||||||
|
Run a restore-to-throwaway-database every month and run `vestige search`
|
||||||
|
or a manual `psql` count against it. A backup you have not restored is a
|
||||||
|
backup you do not have.
|
||||||
|
|
||||||
|
```sh
|
||||||
|
sudo -u postgres createdb -O vestige vestige_restore_drill
|
||||||
|
pg_restore --host=127.0.0.1 --username=vestige --dbname=vestige_restore_drill \
|
||||||
|
--jobs=4 vestige-latest.dump
|
||||||
|
PGPASSWORD="$(cat ~/.vestige_pg_pw)" psql -h 127.0.0.1 -U vestige \
|
||||||
|
-d vestige_restore_drill \
|
||||||
|
-c 'SELECT count(*) FROM knowledge_nodes;'
|
||||||
|
sudo -u postgres dropdb vestige_restore_drill
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. Migration between embeddings
|
||||||
|
|
||||||
|
Use `vestige migrate reembed` when:
|
||||||
|
|
||||||
|
- Upgrading to a new embedding model that produces a different dimension
|
||||||
|
(for example, swapping from `nomic-embed-text-v1.5` 768D to a 1024D
|
||||||
|
model).
|
||||||
|
- Switching providers and the model hash differs even at the same
|
||||||
|
dimension.
|
||||||
|
|
||||||
|
What it does:
|
||||||
|
|
||||||
|
1. Reads every row from `knowledge_nodes`, re-encodes the `content` column
|
||||||
|
through the new embedder, and writes the new vector back.
|
||||||
|
2. Drops the HNSW index before the re-encode loop (this is the default;
|
||||||
|
`--concurrent-index` keeps it during the run at the cost of speed).
|
||||||
|
3. Updates the `embedding_model` row with the new name, dimension, and
|
||||||
|
hash.
|
||||||
|
4. Rebuilds the HNSW index with the new vectors.
|
||||||
|
|
||||||
|
### 6.1 Before starting
|
||||||
|
|
||||||
|
- Take a fresh backup (section 5.2). The tool refuses to start without a
|
||||||
|
`--yes` flag if it detects no recent backup; ignore at your peril.
|
||||||
|
- Stop ingest. Vestige's MCP server can stay running for read-only
|
||||||
|
access, but pause any client that calls `smart_ingest` or
|
||||||
|
`update_scheduling`.
|
||||||
|
- Have the new embedder model available locally. The CLI loads it
|
||||||
|
before the first row is touched; if loading fails, no data is changed.
|
||||||
|
|
||||||
|
### 6.2 Running
|
||||||
|
|
||||||
|
```sh
|
||||||
|
vestige migrate reembed --model=<new-model-name> --yes
|
||||||
|
```
|
||||||
|
|
||||||
|
Add `--concurrent-index` if you cannot accept the brief window during
|
||||||
|
HNSW rebuild where queries do not use the index (sequential scan
|
||||||
|
fallback works but is slow).
|
||||||
|
|
||||||
|
The tool prints a progress bar via `indicatif`. Expected throughput:
|
||||||
|
roughly 200 memories per second per CPU core for a 768D ONNX model.
|
||||||
|
10,000 memories on an 8-core box: about 6 seconds, plus HNSW rebuild
|
||||||
|
(another 30-90 seconds at that scale).
|
||||||
|
|
||||||
|
### 6.3 Verifying completion
|
||||||
|
|
||||||
|
```sh
|
||||||
|
sudo -u postgres psql -d vestige <<'SQL'
|
||||||
|
-- Registry reflects the new model.
|
||||||
|
SELECT name, dimension, hash FROM embedding_model;
|
||||||
|
-- HNSW index is present and not partial.
|
||||||
|
SELECT indexname, indexdef
|
||||||
|
FROM pg_indexes
|
||||||
|
WHERE tablename = 'knowledge_nodes' AND indexname LIKE '%hnsw%';
|
||||||
|
-- All rows have a non-null embedding of the new dimension.
|
||||||
|
SELECT count(*) FILTER (WHERE embedding IS NULL) AS missing,
|
||||||
|
count(*) AS total
|
||||||
|
FROM knowledge_nodes;
|
||||||
|
SQL
|
||||||
|
```
|
||||||
|
|
||||||
|
Expected: registry shows the new model name and dimension, one HNSW
|
||||||
|
index, zero missing embeddings.
|
||||||
|
|
||||||
|
### 6.4 Recovering from an interrupted run
|
||||||
|
|
||||||
|
`vestige migrate reembed` is restartable. On interruption:
|
||||||
|
|
||||||
|
- The `embedding_model` row may or may not have been updated. Check it
|
||||||
|
manually and roll forward by re-running with `--yes --resume` (the
|
||||||
|
tool detects the inconsistency and finishes the rows that still hold
|
||||||
|
old embeddings).
|
||||||
|
- The HNSW index may be missing. Re-running the command rebuilds it as
|
||||||
|
its last step.
|
||||||
|
- If the system is in a state the tool refuses to reason about, restore
|
||||||
|
from the backup taken in 6.1.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 7. Re-clustering domains
|
||||||
|
|
||||||
|
Domain clustering is owned by Phase 4
|
||||||
|
(`docs/plans/0004-phase-4-emergent-domain-classification.md`). Until
|
||||||
|
Phase 4 ships, the `domains` table is reserved schema and is populated
|
||||||
|
only by tests. Operators must not invoke any domain re-clustering
|
||||||
|
workflow manually; there is no supported one in Phase 2.
|
||||||
|
|
||||||
|
When Phase 4 lands, this section is replaced with the real procedure.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 8. Monitoring
|
||||||
|
|
||||||
|
### 8.1 Quick health check
|
||||||
|
|
||||||
|
```sh
|
||||||
|
PGPASSWORD="$(cat ~/.vestige_pg_pw)" psql -h 127.0.0.1 -U vestige -d vestige <<'SQL'
|
||||||
|
SELECT count(*) AS memory_count FROM knowledge_nodes;
|
||||||
|
SELECT name, dimension FROM embedding_model;
|
||||||
|
SELECT pg_size_pretty(pg_database_size('vestige')) AS db_size;
|
||||||
|
SQL
|
||||||
|
```
|
||||||
|
|
||||||
|
### 8.2 In-flight queries
|
||||||
|
|
||||||
|
```sql
|
||||||
|
SELECT pid, now() - query_start AS runtime, state, query
|
||||||
|
FROM pg_stat_activity
|
||||||
|
WHERE datname = 'vestige' AND state <> 'idle'
|
||||||
|
ORDER BY runtime DESC NULLS LAST;
|
||||||
|
```
|
||||||
|
|
||||||
|
Anything over 5 seconds with `state = 'active'` deserves a look. HNSW
|
||||||
|
search queries should land well under 100ms on properly-sized hardware.
|
||||||
|
|
||||||
|
### 8.3 Query pattern analysis
|
||||||
|
|
||||||
|
If `pg_stat_statements` is loaded (`shared_preload_libraries =
|
||||||
|
'pg_stat_statements'` in `postgresql.conf`):
|
||||||
|
|
||||||
|
```sql
|
||||||
|
SELECT calls, mean_exec_time, query
|
||||||
|
FROM pg_stat_statements
|
||||||
|
WHERE query ILIKE '%knowledge_nodes%'
|
||||||
|
ORDER BY mean_exec_time DESC
|
||||||
|
LIMIT 20;
|
||||||
|
```
|
||||||
|
|
||||||
|
Look for hybrid-search queries that have drifted above 100ms p50. The
|
||||||
|
usual culprit is a missing or half-built HNSW index.
|
||||||
|
|
||||||
|
### 8.4 Index health
|
||||||
|
|
||||||
|
```sql
|
||||||
|
SELECT indexname, pg_size_pretty(pg_relation_size(indexrelid)) AS size,
|
||||||
|
idx_scan, idx_tup_read
|
||||||
|
FROM pg_indexes
|
||||||
|
JOIN pg_stat_user_indexes USING (indexrelid)
|
||||||
|
WHERE schemaname = 'public' AND relname = 'knowledge_nodes';
|
||||||
|
```
|
||||||
|
|
||||||
|
A HNSW index with `idx_scan = 0` after several hours of traffic usually
|
||||||
|
means the planner is preferring sequential scan -- either the table is
|
||||||
|
too small to bother with the index (fine) or the index is corrupt and
|
||||||
|
needs rebuilding (`REINDEX INDEX idx_knowledge_nodes_embedding_hnsw;`).
|
||||||
|
|
||||||
|
### 8.5 Spotting half-built HNSW
|
||||||
|
|
||||||
|
After a failed migration or a crashed `reembed`:
|
||||||
|
|
||||||
|
```sql
|
||||||
|
SELECT indexname, indisvalid, indisready
|
||||||
|
FROM pg_indexes
|
||||||
|
JOIN pg_index ON indexrelid = (schemaname || '.' || indexname)::regclass
|
||||||
|
WHERE tablename = 'knowledge_nodes';
|
||||||
|
```
|
||||||
|
|
||||||
|
Any row with `indisvalid = false` is broken. Drop and recreate:
|
||||||
|
|
||||||
|
```sql
|
||||||
|
DROP INDEX IF EXISTS idx_knowledge_nodes_embedding_hnsw;
|
||||||
|
CREATE INDEX idx_knowledge_nodes_embedding_hnsw
|
||||||
|
ON knowledge_nodes USING hnsw (embedding vector_cosine_ops);
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 9. Troubleshooting
|
||||||
|
|
||||||
|
| Symptom | Likely cause | Fix |
|
||||||
|
|---------|--------------|-----|
|
||||||
|
| `ERROR: extension "vector" is not available` on start | pgvector not installed for this Postgres major version | Install the distro package matching `pg_config --version`, then `CREATE EXTENSION vector;` as superuser |
|
||||||
|
| `pool timed out while waiting for an open connection` in Vestige logs | Pool too small or stuck queries holding connections | Raise `max_connections` in `vestige.toml`; investigate `pg_stat_activity` for queries above 5s |
|
||||||
|
| `vector dimensions do not match` on insert | `embedding_model` was stamped at one dimension and a different embedder is now running | Re-run `vestige migrate reembed --model=<correct>` or fix the embedder configuration |
|
||||||
|
| Hybrid search returns the same row twice | Stale `.sqlx/` query cache from before D5 landed | Run `cargo sqlx prepare` in `crates/vestige-core/`, rebuild the binary |
|
||||||
|
| `text search configuration "english" does not exist` | Postgres locale build does not include the english dictionary (rare on Alpine) | Install the language-pack or override the FTS language in `vestige.toml` (see `[storage.postgres.fts]` once Phase 2 D5 lands) |
|
||||||
|
| `relation "_sqlx_migrations" exists, but migration X is in "applied" with no checksum` | Previous run died between `BEGIN` and `COMMIT` | Stop Vestige, restore from backup, restart |
|
||||||
|
| HNSW index very large compared to data | `m` and `ef_construction` defaults too high for the corpus | Acceptable for now; tuning lands as part of Phase 4 |
|
||||||
|
| `permission denied for schema public` on a new install | `vestige` role does not own `public` | Re-run the grants block in section 2.2 as `postgres` |
|
||||||
|
|
||||||
|
If a problem is not in this table, capture: PostgreSQL log
|
||||||
|
(`/var/log/postgres/`, journalctl `-u postgresql`), Vestige log
|
||||||
|
(`RUST_LOG=debug,sqlx=info` for a fresh run), the migration state
|
||||||
|
(`SELECT * FROM _sqlx_migrations ORDER BY version;`), and file a bug.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 10. Rollback caveats
|
||||||
|
|
||||||
|
Every migration in `crates/vestige-core/migrations/postgres/` has a
|
||||||
|
matching `*.down.sql`. `sqlx migrate revert` walks them in reverse order.
|
||||||
|
|
||||||
|
This is not the same as risk-free. The `0002_hnsw.down.sql` drops the
|
||||||
|
HNSW index (rebuildable, expensive). The `0001_init.down.sql` drops
|
||||||
|
every table -- including `knowledge_nodes`, including data. Down migrations
|
||||||
|
exist for development, not for casual production use.
|
||||||
|
|
||||||
|
Before applying any new migration:
|
||||||
|
|
||||||
|
1. Take a backup (section 5.2).
|
||||||
|
2. Run the migration on a restored copy first if you can afford the time.
|
||||||
|
3. Read the new migration's `*.up.sql` and `*.down.sql` to understand
|
||||||
|
what changes.
|
||||||
|
|
||||||
|
To revert one migration manually:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
sqlx migrate revert \
|
||||||
|
--database-url "postgresql://vestige:...@127.0.0.1:5432/vestige" \
|
||||||
|
--source crates/vestige-core/migrations/postgres
|
||||||
|
```
|
||||||
|
|
||||||
|
Note that Vestige's binary does not run `sqlx migrate revert`
|
||||||
|
automatically. Reverts are always an explicit operator decision.
|
||||||
|
|
||||||
|
If a revert fails partway through, treat the database as inconsistent:
|
||||||
|
restore from the backup taken in step 1.
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Cross-references
|
||||||
|
|
||||||
|
- `docs/adr/0001-pluggable-storage-and-network-access.md` -- ADR that
|
||||||
|
established the pluggable backend.
|
||||||
|
- `docs/adr/0002-phase-2-execution.md` -- ADR settling Phase 2 execution
|
||||||
|
decisions; section "Architecture Overview" lists every table the
|
||||||
|
runbook references.
|
||||||
|
- `docs/plans/0002-phase-2-postgres-backend.md` -- master plan; D16
|
||||||
|
(deliverables list) and the Open Implementation Questions section
|
||||||
|
(especially Q4 HNSW rebuild and Q5 pool sizing) inform the runbook's
|
||||||
|
recommendations.
|
||||||
|
- `docs/plans/local-dev-postgres-setup.md` -- developer-facing recipe
|
||||||
|
for a one-machine Arch / CachyOS dev cluster. The runbook links to it
|
||||||
|
as the "for development, see" pointer.
|
||||||
|
- `docs/CONFIGURATION.md` -- existing config doc; section 4 of the
|
||||||
|
runbook ("Connection pool tuning") cross-references it for the
|
||||||
|
authoritative `vestige.toml` schema.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Verification
|
||||||
|
|
||||||
|
A reviewer is given:
|
||||||
|
|
||||||
|
- A fresh Linux VM (Debian 12 or Arch current; both must work) with
|
||||||
|
network access and no Postgres installed.
|
||||||
|
- A built `vestige-mcp` binary for that platform.
|
||||||
|
- The runbook (`docs/runbook/postgres.md`).
|
||||||
|
|
||||||
|
The reviewer follows the runbook top to bottom and reaches a state in
|
||||||
|
which Vestige answers MCP requests against the Postgres backend.
|
||||||
|
Checkpoints, in order:
|
||||||
|
|
||||||
|
1. After section 1 (Prerequisites): `pg_config --version` returns 16 or
|
||||||
|
newer; `pkg-config --modversion libpq` resolves; the `pgvector`
|
||||||
|
distro package is installed.
|
||||||
|
2. After section 2.1 (Extensions): two rows in
|
||||||
|
`SELECT extname FROM pg_extension WHERE extname IN ('vector', 'pgcrypto');`.
|
||||||
|
3. After section 2.2 (Role + DB): `psql -U vestige -h 127.0.0.1 -d vestige -c '\conninfo'`
|
||||||
|
succeeds.
|
||||||
|
4. After section 2.3 (Config): `vestige.toml` parses (test by
|
||||||
|
`vestige config print` once that subcommand lands, otherwise
|
||||||
|
`vestige-mcp --check-config`).
|
||||||
|
5. After section 3 (First connect): the eight expected tables are
|
||||||
|
present; `embedding_model` has exactly one row; the HNSW index
|
||||||
|
exists; `vestige-mcp` log shows "Postgres backend ready".
|
||||||
|
6. After section 5.2 (Backup): the dump file exists and `pg_restore -l`
|
||||||
|
on it lists the expected tables.
|
||||||
|
7. After section 5.4 (Restore drill): the drill database holds the same
|
||||||
|
row count as the source.
|
||||||
|
|
||||||
|
If any checkpoint fails, the runbook section that produced the failure
|
||||||
|
is the one that needs revision. Capture the exact command, exit code,
|
||||||
|
and log line; revise the runbook in a follow-up PR.
|
||||||
|
|
||||||
|
A second reviewer reads the runbook without executing it and checks for:
|
||||||
|
|
||||||
|
- ASCII only; no em dashes, no curly quotes, no Unicode arrows, no
|
||||||
|
ellipses, no bullets (`*`/`-` ASCII only).
|
||||||
|
- Every section number from 1 to 10 present and in order.
|
||||||
|
- Every cross-reference resolves to an existing file or to a Phase
|
||||||
|
number explicitly marked as "future".
|
||||||
|
- No code block longer than 30 lines; if longer, it should be split or
|
||||||
|
referenced from another file.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Acceptance criteria
|
||||||
|
|
||||||
|
- [ ] `docs/runbook/` directory exists.
|
||||||
|
- [ ] `docs/runbook/postgres.md` exists and matches the inlined body
|
||||||
|
above byte-for-byte after stripping the outer code fence used in
|
||||||
|
this sub-plan to embed it.
|
||||||
|
- [ ] All ten sections from the "Runbook structure" outline are present
|
||||||
|
under their stated headings.
|
||||||
|
- [ ] No file other than `docs/runbook/postgres.md` is created or
|
||||||
|
modified by executing this sub-plan.
|
||||||
|
- [ ] ASCII only: no em dashes, no curly quotes, no Unicode arrows,
|
||||||
|
no ellipses, no Unicode bullets (`grep -P '[^\x00-\x7F]'
|
||||||
|
docs/runbook/postgres.md` returns no matches).
|
||||||
|
- [ ] Every cross-reference in the runbook points at a file that exists
|
||||||
|
in the repository at the time of merge, OR is explicitly framed
|
||||||
|
as "future Phase N" with a pointer to the relevant plan document.
|
||||||
|
- [ ] Every command block is copy-pastable: no `<placeholder>` syntax
|
||||||
|
that does not also have an inline note describing what to
|
||||||
|
substitute.
|
||||||
|
- [ ] A second pair of eyes confirms the verification checkpoints in the
|
||||||
|
preceding section are reproducible.
|
||||||
|
- [ ] The runbook is no longer than the inlined body in this sub-plan;
|
||||||
|
operators reach the end without losing patience.
|
||||||
1435
docs/plans/0003-phase-3-network-access.md
Normal file
1435
docs/plans/0003-phase-3-network-access.md
Normal file
File diff suppressed because it is too large
Load diff
883
docs/plans/0004-phase-4-emergent-domain-classification.md
Normal file
883
docs/plans/0004-phase-4-emergent-domain-classification.md
Normal file
|
|
@ -0,0 +1,883 @@
|
||||||
|
# Phase 4 Plan: Emergent Domain Classification
|
||||||
|
|
||||||
|
**Status**: Draft
|
||||||
|
**Depends on**: Phase 1 (domain columns on memories, `Domain` struct + `DomainStore` methods on `MemoryStore`, `Embedder` trait), Phase 2 (Postgres JSONB + TEXT[] support for domain fields, `embedding_model` registry parity), Phase 3 (Axum HTTP server, REST `/api/v1/` scaffolding, API key auth middleware, signed dashboard session cookies)
|
||||||
|
**Related**: docs/adr/0001-pluggable-storage-and-network-access.md (Phase 4), docs/prd/001-getting-centralized-vestige.md (Emergent Domain Model)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Scope
|
||||||
|
|
||||||
|
### In scope
|
||||||
|
|
||||||
|
- `DomainClassifier` cognitive module under `crates/vestige-core/src/neuroscience/domain_classifier.rs`, alongside existing neuroscience modules (spreading_activation, synaptic_tagging, ...).
|
||||||
|
- HDBSCAN discovery pipeline using the `hdbscan` crate (v0.10): load all embeddings, cluster, extract centroids, extract top-terms via TF-IDF over cluster members, persist via the trait's `DomainStore` methods.
|
||||||
|
- Soft-assignment pipeline: for each memory, compute `cosine_similarity(memory.embedding, domain.centroid)` for every domain, store raw scores in `domain_scores` JSONB, threshold into `domains[]` using `assign_threshold` (default 0.65).
|
||||||
|
- Automatic classification on ingest: run through `CognitiveEngine` / `smart_ingest` so new memories get classified against existing centroids immediately; skip when `domain_count == 0` (Phase 0 accumulation).
|
||||||
|
- Re-cluster hook in dream consolidation: every Nth four-phase dream cycle (N=5 default) triggers a discovery pass and generates proposals (split / merge / none). Proposals land in a new `domain_proposals` table, surface in the dashboard, and are never auto-applied (conservative drift, ADR Q7).
|
||||||
|
- Context signals: `SignalSource` trait with `GitRepoSignal` (detects `.git` in CWD or `metadata.cwd`) and `IdeHintSignal` (reads `metadata.editor` / `metadata.ide`). Each returns a `boost_map` of `domain_id -> additive delta` (typical +0.05). Injected as a `signal_boost: Option<HashMap<String, f64>>` parameter into `DomainClassifier::classify`.
|
||||||
|
- Cross-domain spreading activation decay: `ActivationNetwork` traversal multiplies the edge's effective weight by `cross_domain_decay` (default 0.5) when `target.domains` and `source.domains` are disjoint. Strict "no overlap" policy, not graded.
|
||||||
|
- CLI subcommands (in `crates/vestige-mcp/src/bin/cli.rs`, under a new `Domains` command group): `list`, `discover [--min-cluster-size N] [--force]`, `rename <id> <new_label>`, `merge <a> <b> [--into <id>]`. Human-readable tables on stdout; JSON via `--json`.
|
||||||
|
- Dashboard UI additions (`apps/dashboard/src/routes/(app)/domains/`): list page, per-domain detail (memories, centroid top_terms, score histogram, proposal review controls).
|
||||||
|
- REST endpoints under `/api/v1/domains` (introduced by Phase 3 skeleton, implemented in Phase 4): list, discover, rename, merge, proposal list / accept / reject.
|
||||||
|
- Config additions: `[domains]` section in `vestige.toml` covering `assign_threshold`, `recluster_interval`, `min_cluster_size`, `cross_domain_decay`, `discovery_threshold`, `merge_threshold`, `signal_boost` (per-signal toggle).
|
||||||
|
|
||||||
|
### Out of scope
|
||||||
|
|
||||||
|
- Phase 5 federation (explicit separate ADR). Domain centroids are installation-local; no sync.
|
||||||
|
- Learned re-weighting of domain scores (future, only if retrieval-quality metrics show a need).
|
||||||
|
- Interactive cluster-membership editing in the UI (drag-and-drop reassign) -- future enhancement.
|
||||||
|
- Multi-user domain namespaces. One domain set per installation; API keys that carry `domain_filter` just restrict access, they do not create namespaces.
|
||||||
|
- Auto-sweep of `min_cluster_size` / auto-tuned `assign_threshold` (ADR resolution Q6 + Q9: static defaults, user tunes).
|
||||||
|
- Graded cross-domain decay (`|A intersect B| / max(|A|,|B|)`) -- strict "no overlap" is the Phase 4 rule.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Prerequisites
|
||||||
|
|
||||||
|
Artifacts that Phases 1-3 are expected to have landed:
|
||||||
|
|
||||||
|
- In `vestige-core`:
|
||||||
|
- `Embedder` trait (`crates/vestige-core/src/embedder/`).
|
||||||
|
- `MemoryStore` trait (`crates/vestige-core/src/storage/trait.rs` or similar) including `DomainStore` methods: `list_domains`, `get_domain`, `upsert_domain`, `delete_domain`, `classify(&[f32]) -> Vec<(String, f64)>`, plus a bulk accessor such as `all_embeddings()` (already present in sqlite.rs as `get_all_embeddings`) and a `get_all_memories_with_embeddings()` iterator for discovery. The trait must expose a method to batch-update `(domains, domain_scores)` for a memory id.
|
||||||
|
- `Domain` struct: `{ id: String, label: String, centroid: Vec<f32>, top_terms: Vec<String>, memory_count: usize, created_at: DateTime<Utc> }`.
|
||||||
|
- Columns on memories in both SQLite and Postgres: `domains TEXT[]` (or JSON array on SQLite) and `domain_scores JSONB` (or TEXT JSON on SQLite).
|
||||||
|
- The `domains` table in both backends (see PRD schema sketch).
|
||||||
|
- In `vestige-mcp`:
|
||||||
|
- Axum `/api/v1/` router prefix with auth middleware.
|
||||||
|
- CLI skeleton (`bin/cli.rs`) using `clap`; Phase 4 adds a `Domains` subcommand tree.
|
||||||
|
- REST handlers file structure ready under `crates/vestige-mcp/src/dashboard/handlers.rs` (legacy) and a dedicated REST handler under `/api/v1/`; Phase 4 adds `domains.rs` handler module.
|
||||||
|
- SvelteKit dashboard (`apps/dashboard/`) with existing `(app)/memories`, `(app)/timeline`, `(app)/stats`, etc. Phase 4 adds `(app)/domains/`.
|
||||||
|
|
||||||
|
New workspace crate additions required (added manually to `Cargo.toml`, since `cargo add` is not run from the plan):
|
||||||
|
|
||||||
|
- `hdbscan = "0.10"` in `crates/vestige-core/Cargo.toml` (feature-gated behind `domain-classification`).
|
||||||
|
- Optional: a lightweight stop-word constant inline; no external stop-word crate -- the neuroscience modules already do tokenization on whitespace + length>3 (see `dreams.rs::content_similarity`). Reuse that style; no `ndarray` needed because `hdbscan` v0.10 accepts `&[Vec<f32>]` directly (verified from PRD snippet).
|
||||||
|
- No new deps in `vestige-mcp` for Phase 4 -- CLI reuses `clap` / `colored` / `comfy-table` if already present, otherwise a hand-rolled padded print. We pick hand-rolled to avoid adding a table crate; this matches the existing style of `run_stats` in `cli.rs`.
|
||||||
|
|
||||||
|
Test fixtures:
|
||||||
|
|
||||||
|
- A JSON seed corpus checked into `tests/phase_4/fixtures/seed_500.json` containing >= 500 memories drawn from three plausible clusters. A builder function `tests/phase_4/support/fixtures.rs::build_seed_corpus()` deterministically generates or loads this corpus. Each record has `content`, `tags`, `embedding` (768D bge-base-en-v1.5; use a committed vector or a deterministic mock embedder in tests). For deterministic tests we fake embeddings by hashing content -- acceptable as long as the fake preserves cluster separability (prefix-based: "DEV-...", "INFRA-...", "HOME-..." seeds three Gaussian blobs).
|
||||||
|
- Reuse `Embedder` mock from Phase 1 tests (`MockEmbedder`) for discovery tests that need real cosine similarity.
|
||||||
|
- A minimal git-repo fixture created in a tempdir (`tempfile::tempdir` + `std::process::Command::new("git").arg("init")`) for context-signal tests.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Deliverables
|
||||||
|
|
||||||
|
1. `DomainClassifier` cognitive module: struct, defaults, `classify`, `classify_with_boost`, `reassign_all`, `discover`.
|
||||||
|
2. `domain_terms` helper (TF-IDF over cluster members, returning `top_k` terms).
|
||||||
|
3. `cli domains discover` subcommand.
|
||||||
|
4. `cli domains list` / `rename` / `merge` subcommands.
|
||||||
|
5. Auto-classify hook on ingest (wired into the cognitive engine's ingest pipeline before persistence).
|
||||||
|
6. Re-cluster hook in dream consolidation (`DreamEngine::run` orchestrator gets an optional `DomainReClusterHook`; triggers every Nth dream).
|
||||||
|
7. Context signal extractor module (`crates/vestige-core/src/neuroscience/context_signals.rs`) with `SignalSource` trait + `GitRepoSignal` + `IdeHintSignal`.
|
||||||
|
8. Cross-domain spreading activation decay in `ActivationNetwork::activate` (config-driven).
|
||||||
|
9. `vestige.toml` `[domains]` section + defaults loader.
|
||||||
|
10. Dashboard UI: SvelteKit routes `(app)/domains/+page.svelte` (list), `(app)/domains/[id]/+page.svelte` (detail), `(app)/domains/proposals/+page.svelte` (review).
|
||||||
|
11. REST endpoints under `/api/v1/domains` + `/api/v1/domains/proposals`.
|
||||||
|
12. `domain_proposals` table + migration + `DomainProposal` trait methods on `MemoryStore`.
|
||||||
|
13. WebSocket event `VestigeEvent::DomainProposalCreated` so the dashboard gets a live notification after a re-cluster fires.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Detailed Task Breakdown
|
||||||
|
|
||||||
|
### 1. `DomainClassifier` cognitive module
|
||||||
|
|
||||||
|
**File**: `crates/vestige-core/src/neuroscience/domain_classifier.rs`
|
||||||
|
**Export**: in `crates/vestige-core/src/neuroscience/mod.rs`, add `pub mod domain_classifier;` and re-export `pub use domain_classifier::{DomainClassifier, ClassificationResult, DomainProposal, ProposalKind};`
|
||||||
|
**Deps**: `hdbscan = "0.10"`, `serde`, `serde_json`, `chrono`, `tracing`, existing `crate::storage::Domain`, `crate::storage::MemoryStore` trait.
|
||||||
|
|
||||||
|
Struct and defaults (match PRD exactly):
|
||||||
|
|
||||||
|
```rust
|
||||||
|
pub struct DomainClassifier {
|
||||||
|
pub assign_threshold: f64, // default 0.65
|
||||||
|
pub discovery_threshold: usize, // default 150
|
||||||
|
pub recluster_interval: usize, // default 5 (every 5th dream)
|
||||||
|
pub min_cluster_size: usize, // default 10
|
||||||
|
pub min_samples: usize, // default 5 (HDBSCAN)
|
||||||
|
pub cross_domain_decay: f64, // default 0.5
|
||||||
|
pub merge_threshold: f64, // default 0.90 (centroid cosine)
|
||||||
|
pub top_terms_k: usize, // default 10
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for DomainClassifier { ... }
|
||||||
|
```
|
||||||
|
|
||||||
|
Result types:
|
||||||
|
|
||||||
|
```rust
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct ClassificationResult {
|
||||||
|
pub scores: HashMap<String, f64>, // raw per-domain similarities
|
||||||
|
pub domains: Vec<String>, // above assign_threshold
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub enum ProposalKind {
|
||||||
|
Split { parent: String, children: Vec<String> },
|
||||||
|
Merge { targets: Vec<String>, suggested_label: String },
|
||||||
|
NewCluster { top_terms: Vec<String> },
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct DomainProposal {
|
||||||
|
pub id: String, // uuid v4
|
||||||
|
pub kind: ProposalKind,
|
||||||
|
pub rationale: String,
|
||||||
|
pub confidence: f64,
|
||||||
|
pub created_at: DateTime<Utc>,
|
||||||
|
pub status: ProposalStatus, // Pending | Accepted | Rejected
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Key methods (all pure where possible; all pub):
|
||||||
|
|
||||||
|
```rust
|
||||||
|
impl DomainClassifier {
|
||||||
|
pub fn classify(&self, embedding: &[f32], domains: &[Domain]) -> ClassificationResult;
|
||||||
|
|
||||||
|
pub fn classify_with_boost(
|
||||||
|
&self,
|
||||||
|
embedding: &[f32],
|
||||||
|
domains: &[Domain],
|
||||||
|
boost: Option<&HashMap<String, f64>>,
|
||||||
|
) -> ClassificationResult;
|
||||||
|
|
||||||
|
pub async fn reassign_all(
|
||||||
|
&self,
|
||||||
|
store: &dyn MemoryStore,
|
||||||
|
domains: &[Domain],
|
||||||
|
) -> Result<usize, StorageError>;
|
||||||
|
|
||||||
|
pub async fn discover(
|
||||||
|
&self,
|
||||||
|
store: &dyn MemoryStore,
|
||||||
|
) -> Result<Vec<Domain>, StorageError>;
|
||||||
|
|
||||||
|
pub async fn propose_changes(
|
||||||
|
&self,
|
||||||
|
store: &dyn MemoryStore,
|
||||||
|
existing: &[Domain],
|
||||||
|
newly_discovered: &[Domain],
|
||||||
|
) -> Result<Vec<DomainProposal>, StorageError>;
|
||||||
|
|
||||||
|
pub async fn apply_proposal(
|
||||||
|
&self,
|
||||||
|
store: &dyn MemoryStore,
|
||||||
|
proposal: &DomainProposal,
|
||||||
|
) -> Result<(), StorageError>;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Behavior notes:
|
||||||
|
|
||||||
|
- `classify` returns empty `{ scores: {}, domains: [] }` iff `domains.is_empty()` (accumulation phase). This matches the PRD snippet verbatim.
|
||||||
|
- `classify_with_boost` adds the boost delta to each score AFTER cosine, before thresholding. It clamps to `[0.0, 1.0]`. Boost keys not present in `domains` are ignored.
|
||||||
|
- `reassign_all` streams memories in batches of 500 (iterator on the store) to keep memory bounded; for each memory issues a single `UPDATE memories SET domains = ?, domain_scores = ? WHERE id = ?` call. Returns count of memories whose `domains` vector actually changed.
|
||||||
|
- `discover` loads all `(id, embedding)` pairs via an `all_embeddings()` method on the store (exists under `#[cfg(all(feature = "embeddings", feature = "vector-search"))]` in `sqlite.rs::get_all_embeddings`; Phase 1 should promote this onto the trait -- if not yet promoted, add the method). Then:
|
||||||
|
1. Build `Vec<Vec<f32>>` and index -> id map.
|
||||||
|
2. `Hdbscan::default_hyper_params(&embeddings).min_cluster_size(self.min_cluster_size).min_samples(self.min_samples).build()` (exact builder depends on hdbscan 0.10 surface; see Open Question).
|
||||||
|
3. `let labels = clusterer.cluster()?;`
|
||||||
|
4. `let centers = clusterer.calc_centers(Center::Centroid, &labels)?;`
|
||||||
|
5. Group indices by label ignoring -1 (noise). For each cluster compute `top_terms` via `compute_top_terms`.
|
||||||
|
6. Preserve stable IDs where possible: match each new cluster centroid to the closest existing domain by cosine; if similarity > 0.85, reuse the existing domain id + label. Otherwise generate a fresh id `cluster_{n}` with a label derived from the first 2 terms.
|
||||||
|
7. Upsert all resulting `Domain`s via the store.
|
||||||
|
- `propose_changes` compares old vs new clusters:
|
||||||
|
- **Split**: an old domain that best-matches two or more new domains each with >= `min_cluster_size` members. Rationale: "domain `dev` is now 2 clusters of >=10 memories: `systems` and `networking`".
|
||||||
|
- **Merge**: two old domains whose centroids now satisfy `cosine > merge_threshold` get a merge proposal.
|
||||||
|
- **NewCluster**: a new cluster that doesn't match any old domain above 0.85 similarity.
|
||||||
|
- `apply_proposal` runs the split or merge against the store (reassign memberships via `reassign_all`), then marks the proposal `Accepted`. It never runs automatically -- only via the CLI or dashboard.
|
||||||
|
|
||||||
|
Helper:
|
||||||
|
|
||||||
|
```rust
|
||||||
|
fn compute_top_terms(documents: &[&str], k: usize) -> Vec<String>;
|
||||||
|
```
|
||||||
|
|
||||||
|
Uses TF-IDF with IDF computed over the entire passed-in corpus (the `documents` slice), tokenization = whitespace split, lowercase, strip non-alphanumeric, drop tokens shorter than 4 chars and a small built-in stop-word list (`the`, `and`, `for`, `that`, `with`, ...). Matches the tokenizer used in `dreams.rs::content_similarity` and `dreams.rs::extract_patterns` so behavior is predictable.
|
||||||
|
|
||||||
|
Cosine similarity helper:
|
||||||
|
|
||||||
|
```rust
|
||||||
|
fn cosine_similarity(a: &[f32], b: &[f32]) -> f64;
|
||||||
|
```
|
||||||
|
|
||||||
|
Keep the existing crate-level `cosine_similarity` if already present (check `embeddings::` or `search::`); otherwise add a private one. Returns 0.0 on dimension mismatch, panics would be a bug.
|
||||||
|
|
||||||
|
### 2. Top-terms computation helper
|
||||||
|
|
||||||
|
**File**: same module, private section.
|
||||||
|
|
||||||
|
- `fn tokenize(text: &str) -> Vec<String>`: lowercase, split on non-alphanumeric, filter len >= 4, drop stop-words.
|
||||||
|
- `fn tfidf_top_k(docs: &[&str], k: usize) -> Vec<String>`:
|
||||||
|
1. `tf[doc_idx][term] = count / total_terms`.
|
||||||
|
2. `df[term] = docs containing term`.
|
||||||
|
3. `idf[term] = log((N + 1) / (df[term] + 1)) + 1` (smoothed).
|
||||||
|
4. For each term, average `tf` across docs in the cluster; multiply by `idf`; sort desc; return top `k`.
|
||||||
|
|
||||||
|
Cluster top-terms are computed over cluster members only, with IDF over the **whole corpus** (all memory contents), not the cluster, so common words get penalized globally. Recompute global IDF once per `discover` call.
|
||||||
|
|
||||||
|
### 3. CLI subcommand: `vestige domains discover`
|
||||||
|
|
||||||
|
**File**: `crates/vestige-mcp/src/bin/cli.rs`
|
||||||
|
|
||||||
|
Add to `enum Commands`:
|
||||||
|
|
||||||
|
```rust
|
||||||
|
/// Emergent domain management
|
||||||
|
Domains {
|
||||||
|
#[command(subcommand)]
|
||||||
|
action: DomainAction,
|
||||||
|
},
|
||||||
|
```
|
||||||
|
|
||||||
|
```rust
|
||||||
|
#[derive(clap::Subcommand)]
|
||||||
|
enum DomainAction {
|
||||||
|
/// List all discovered domains
|
||||||
|
List {
|
||||||
|
#[arg(long)] json: bool,
|
||||||
|
},
|
||||||
|
/// Run HDBSCAN discovery on all embeddings and propose domains
|
||||||
|
Discover {
|
||||||
|
#[arg(long, default_value_t = 10)] min_cluster_size: usize,
|
||||||
|
/// Skip the proposal flow and write new domains directly (first-time use)
|
||||||
|
#[arg(long)] force: bool,
|
||||||
|
#[arg(long)] json: bool,
|
||||||
|
},
|
||||||
|
/// Rename a domain (by id)
|
||||||
|
Rename {
|
||||||
|
id: String,
|
||||||
|
new_label: String,
|
||||||
|
},
|
||||||
|
/// Merge two domains
|
||||||
|
Merge {
|
||||||
|
a: String,
|
||||||
|
b: String,
|
||||||
|
#[arg(long)] into: Option<String>, // default: `a`
|
||||||
|
},
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Handler plumbing lives in `run_domains(action)` dispatching to `run_domains_list`, `run_domains_discover`, `run_domains_rename`, `run_domains_merge`. Each opens the default `Storage`, constructs a `DomainClassifier::default()`, and invokes the appropriate method.
|
||||||
|
|
||||||
|
Output format for `list`:
|
||||||
|
|
||||||
|
```
|
||||||
|
ID LABEL MEMORIES TOP TERMS
|
||||||
|
dev Development 87 rust, trait, async, tokio, zinit
|
||||||
|
infra Infrastructure 47 bgp, sonic, vlan, frr, peering
|
||||||
|
home Home 31 solar, kwh, battery, pool, esphome
|
||||||
|
(unclassified) 12
|
||||||
|
```
|
||||||
|
|
||||||
|
Produced via plain `print!` with `%-15s %-18s %-10d %s` style padding. `--json` emits `serde_json::to_string_pretty(&domains)`.
|
||||||
|
|
||||||
|
Output format for `discover` with `--force`:
|
||||||
|
|
||||||
|
```
|
||||||
|
HDBSCAN: 500 embeddings, min_cluster_size=10, min_samples=5
|
||||||
|
Found 3 clusters (ignoring 14 noise points)
|
||||||
|
cluster_0 (N=47) top: bgp, sonic, vlan, frr, peering
|
||||||
|
cluster_1 (N=31) top: solar, kwh, battery, pool, esphome
|
||||||
|
cluster_2 (N=22) top: rust, trait, async, tokio, zinit
|
||||||
|
|
||||||
|
Writing 3 domains to the store...
|
||||||
|
Soft-assigning 500 memories against centroids...
|
||||||
|
multi-domain: 43
|
||||||
|
single-domain: 412
|
||||||
|
unclassified (below threshold 0.65): 45
|
||||||
|
Done in 7.4s.
|
||||||
|
```
|
||||||
|
|
||||||
|
Output format for `discover` without `--force` (post-Phase-0):
|
||||||
|
|
||||||
|
```
|
||||||
|
HDBSCAN: 623 embeddings, min_cluster_size=10
|
||||||
|
Comparing to existing 3 domains...
|
||||||
|
|
||||||
|
Proposals (pending, accept via dashboard or `vestige domains proposals`):
|
||||||
|
[split] dev -> (systems:34, networking:28) confidence 0.82
|
||||||
|
[new] cluster_5 (books, novels, reading) confidence 0.71
|
||||||
|
|
||||||
|
Run `vestige domains proposals` to review, or open the dashboard.
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4. CLI: `list`, `rename`, `merge`
|
||||||
|
|
||||||
|
- `list`: calls `store.list_domains()`, fetches unclassified count via `store.count_memories_without_domains()` (Phase 1 should have provided this; if not, Phase 4 adds it to the trait and both backends).
|
||||||
|
- `rename`: `store.get_domain(id)` -> mutate `label` -> `store.upsert_domain`. No memory touch.
|
||||||
|
- `merge`: load both, compute blended centroid (weighted by `memory_count`), merge `top_terms` (union, recompute TF-IDF rank if both sides share the corpus), delete the non-`into` domain, call `reassign_all`. Wrapped in a transaction on Postgres; on SQLite rely on the existing writer-lock pattern.
|
||||||
|
|
||||||
|
### 5. Auto-classify on ingest
|
||||||
|
|
||||||
|
**File**: `crates/vestige-core/src/cognitive.rs` (or equivalent ingest entry in `vestige-mcp/src/tools/smart_ingest.rs`).
|
||||||
|
|
||||||
|
Integration point: just before the record is persisted in the smart-ingest path, after the embedder has produced `embedding` and before `storage.insert(...)`. Trace the current call site -- today `Storage::ingest(IngestInput)` computes embedding inside storage; in Phase 1 the embedder becomes external (ADR decision Q2), so classification can hook right there in the cognitive engine.
|
||||||
|
|
||||||
|
Pseudocode:
|
||||||
|
|
||||||
|
```rust
|
||||||
|
let embedding = embedder.embed(&input.content).await?;
|
||||||
|
let domains = store.list_domains().await?;
|
||||||
|
|
||||||
|
let (domains_assigned, domain_scores) = if domains.is_empty() {
|
||||||
|
(Vec::new(), HashMap::new())
|
||||||
|
} else {
|
||||||
|
let boost = context_signals.gather_boost(&input.metadata, &domains);
|
||||||
|
let result = classifier.classify_with_boost(&embedding, &domains, boost.as_ref());
|
||||||
|
(result.domains, result.scores)
|
||||||
|
};
|
||||||
|
|
||||||
|
record.embedding = Some(embedding);
|
||||||
|
record.domains = domains_assigned;
|
||||||
|
record.domain_scores = domain_scores;
|
||||||
|
store.insert(&record).await?;
|
||||||
|
```
|
||||||
|
|
||||||
|
Edge cases:
|
||||||
|
|
||||||
|
- Accumulation phase (`domains.is_empty()`): skip classification entirely. Zero overhead.
|
||||||
|
- Embedding failed / skipped: leave `domains = []`, `domain_scores = {}`. Never fail ingest because of classification.
|
||||||
|
- Metric: emit `VestigeEvent::MemoryClassified { id, domains, top_score }` on the WebSocket bus so the dashboard sees it live.
|
||||||
|
|
||||||
|
### 6. Re-cluster hook in dream consolidation
|
||||||
|
|
||||||
|
**File**: `crates/vestige-core/src/advanced/dreams.rs` (long file, 1131-line `dream()` entry on the `MemoryDreamer` impl) plus `crates/vestige-core/src/consolidation/phases.rs` (the `DreamEngine::run` orchestrator).
|
||||||
|
|
||||||
|
Design: the `DreamEngine::run(...)` returns `FourPhaseDreamResult`. It does not currently know how many times it has run. Phase 4 introduces a persistent counter on disk (column `dream_cycle_count` on a new singleton `system_state` table, or a simple row in the existing `metadata` / `embedding_model` registry). After the Integration phase finishes, the cognitive engine increments the counter and, if `counter % recluster_interval == 0`, launches discovery asynchronously:
|
||||||
|
|
||||||
|
Extension struct in `phases.rs`:
|
||||||
|
|
||||||
|
```rust
|
||||||
|
pub struct DreamReClusterHook<'a> {
|
||||||
|
pub classifier: &'a DomainClassifier,
|
||||||
|
pub store: &'a dyn MemoryStore,
|
||||||
|
pub event_tx: Option<&'a tokio::sync::mpsc::UnboundedSender<VestigeEvent>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a> DreamReClusterHook<'a> {
|
||||||
|
pub async fn tick(&self, cycle_count: usize) -> Result<Vec<DomainProposal>, StorageError> {
|
||||||
|
if cycle_count == 0 || cycle_count % self.classifier.recluster_interval != 0 {
|
||||||
|
return Ok(vec![]);
|
||||||
|
}
|
||||||
|
let existing = self.store.list_domains().await?;
|
||||||
|
let rediscovered = self.classifier.discover(self.store).await?;
|
||||||
|
let proposals = self
|
||||||
|
.classifier
|
||||||
|
.propose_changes(self.store, &existing, &rediscovered)
|
||||||
|
.await?;
|
||||||
|
for p in &proposals {
|
||||||
|
self.store.insert_domain_proposal(p).await?;
|
||||||
|
if let Some(tx) = self.event_tx {
|
||||||
|
let _ = tx.send(VestigeEvent::DomainProposalCreated {
|
||||||
|
id: p.id.clone(),
|
||||||
|
kind: format!("{:?}", p.kind),
|
||||||
|
confidence: p.confidence,
|
||||||
|
timestamp: Utc::now(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(proposals)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Caller wires `tick()` after `DreamEngine::run()` returns, at the ingest/consolidation orchestrator level. The hook never mutates existing domains -- it only writes proposals. The acceptance path is manual (CLI or dashboard).
|
||||||
|
|
||||||
|
Counter storage: add method `store.bump_dream_cycle_count() -> Result<usize>` returning the new count. Single-row table:
|
||||||
|
|
||||||
|
```sql
|
||||||
|
CREATE TABLE IF NOT EXISTS system_state (
|
||||||
|
key TEXT PRIMARY KEY,
|
||||||
|
value TEXT NOT NULL
|
||||||
|
);
|
||||||
|
-- seed: ('dream_cycle_count', '0')
|
||||||
|
```
|
||||||
|
|
||||||
|
### 7. Context signal extractor
|
||||||
|
|
||||||
|
**File**: `crates/vestige-core/src/neuroscience/context_signals.rs`
|
||||||
|
|
||||||
|
```rust
|
||||||
|
pub trait SignalSource: Send + Sync {
|
||||||
|
/// Returns domain_id -> additive boost (positive or negative, typically in [-0.1, +0.1]).
|
||||||
|
fn boost_map(
|
||||||
|
&self,
|
||||||
|
input_metadata: &serde_json::Value,
|
||||||
|
domains: &[Domain],
|
||||||
|
) -> HashMap<String, f64>;
|
||||||
|
|
||||||
|
fn name(&self) -> &'static str;
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct GitRepoSignal {
|
||||||
|
pub boost: f64, // default +0.05
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct IdeHintSignal {
|
||||||
|
pub boost: f64,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct ContextSignals {
|
||||||
|
sources: Vec<Box<dyn SignalSource>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ContextSignals {
|
||||||
|
pub fn gather_boost(
|
||||||
|
&self,
|
||||||
|
input_metadata: &serde_json::Value,
|
||||||
|
domains: &[Domain],
|
||||||
|
) -> Option<HashMap<String, f64>>;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Signal encoding convention (document in the module header):
|
||||||
|
|
||||||
|
- A signal is a **soft prior**. It nudges the post-cosine score by a small additive delta, clamped to `[-0.10, +0.10]` per signal.
|
||||||
|
- Multiple signals sum, then the final boost per domain is clamped to `[-0.15, +0.15]` so signals cannot by themselves push a memory into or out of a domain; the embedding similarity dominates.
|
||||||
|
- Signals target domains by heuristic: `GitRepoSignal` boosts any domain whose `top_terms` overlaps `{"rust","async","trait","function","class","def","git","commit","fn","code"}`. `IdeHintSignal` does the same for `{"file","line","editor","vscode","neovim","rust-analyzer","lsp"}`.
|
||||||
|
- All signal boosts are logged via `tracing::debug!` so users can audit why a memory picked up a domain.
|
||||||
|
|
||||||
|
`GitRepoSignal::boost_map` implementation:
|
||||||
|
|
||||||
|
```rust
|
||||||
|
fn boost_map(&self, meta: &Value, domains: &[Domain]) -> HashMap<String, f64> {
|
||||||
|
let is_git = meta.get("cwd")
|
||||||
|
.and_then(|v| v.as_str())
|
||||||
|
.map(|cwd| std::path::Path::new(cwd).join(".git").exists())
|
||||||
|
.unwrap_or(false)
|
||||||
|
|| meta.get("git_repo").is_some();
|
||||||
|
if !is_git { return HashMap::new(); }
|
||||||
|
let mut out = HashMap::new();
|
||||||
|
for d in domains {
|
||||||
|
let code_hits = d.top_terms.iter()
|
||||||
|
.filter(|t| CODE_TERMS.contains(t.as_str()))
|
||||||
|
.count();
|
||||||
|
if code_hits > 0 { out.insert(d.id.clone(), self.boost); }
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Config knob in `[domains.signals]`: `git = true`, `ide = true`, `git_boost = 0.05`, `ide_boost = 0.05`.
|
||||||
|
|
||||||
|
### 8. Cross-domain spreading activation decay
|
||||||
|
|
||||||
|
**File**: `crates/vestige-core/src/neuroscience/spreading_activation.rs`
|
||||||
|
|
||||||
|
Modify `ActivationConfig`:
|
||||||
|
|
||||||
|
```rust
|
||||||
|
pub struct ActivationConfig {
|
||||||
|
pub decay_factor: f64,
|
||||||
|
pub max_hops: u32,
|
||||||
|
pub min_threshold: f64,
|
||||||
|
pub allow_cycles: bool,
|
||||||
|
pub cross_domain_decay: f64, // NEW, default 0.5
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Domain metadata on nodes: the current `ActivationNode` has `id`, `activation`, `last_activated`, `edges: Vec<String>`. Phase 4 adds `pub domains: Vec<String>`. Populated when nodes get added (propagated from the memory's `domains` field). The network is rebuilt on each search from the store; if the in-memory network is persisted (check `ActivationNetwork` lifetime in `CognitiveEngine`), the population happens in the engine at boot and on insert.
|
||||||
|
|
||||||
|
Traversal change, in `ActivationNetwork::activate` loop, replacing the single line `let propagated = current_activation * edge.strength * self.config.decay_factor;`:
|
||||||
|
|
||||||
|
```rust
|
||||||
|
let cross_penalty = {
|
||||||
|
let src_doms = self.nodes.get(¤t_id).map(|n| &n.domains);
|
||||||
|
let tgt_doms = self.nodes.get(&target_id).map(|n| &n.domains);
|
||||||
|
match (src_doms, tgt_doms) {
|
||||||
|
(Some(s), Some(t)) if !s.is_empty() && !t.is_empty() => {
|
||||||
|
let overlap = s.iter().any(|d| t.contains(d));
|
||||||
|
if overlap { 1.0 } else { self.config.cross_domain_decay }
|
||||||
|
}
|
||||||
|
_ => 1.0, // unclassified on either side: no penalty
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let propagated = current_activation * edge.strength * self.config.decay_factor * cross_penalty;
|
||||||
|
```
|
||||||
|
|
||||||
|
Rationale for "unclassified -> no penalty": unclassified memories are Phase-0 or low-confidence corpus members; penalizing them would block useful cross-pollination during the accumulation ramp.
|
||||||
|
|
||||||
|
API to update a node's domains after reclassification:
|
||||||
|
|
||||||
|
```rust
|
||||||
|
pub fn set_node_domains(&mut self, id: &str, domains: Vec<String>);
|
||||||
|
```
|
||||||
|
|
||||||
|
Called by the reassignment pipeline after `reassign_all`.
|
||||||
|
|
||||||
|
### 9. `vestige.toml` `[domains]` section
|
||||||
|
|
||||||
|
**File**: wherever `vestige.toml` is loaded (search for `[storage]` / `[server]` loaders). Add:
|
||||||
|
|
||||||
|
```toml
|
||||||
|
[domains]
|
||||||
|
assign_threshold = 0.65
|
||||||
|
discovery_threshold = 150
|
||||||
|
recluster_interval = 5
|
||||||
|
min_cluster_size = 10
|
||||||
|
min_samples = 5
|
||||||
|
cross_domain_decay = 0.5
|
||||||
|
merge_threshold = 0.90
|
||||||
|
top_terms_k = 10
|
||||||
|
|
||||||
|
[domains.signals]
|
||||||
|
git = true
|
||||||
|
ide = true
|
||||||
|
git_boost = 0.05
|
||||||
|
ide_boost = 0.05
|
||||||
|
```
|
||||||
|
|
||||||
|
Rust-side: `DomainsConfig { ... }` struct with `serde(default)` so `vestige.toml` without a `[domains]` section falls back to hard-coded defaults. `DomainClassifier::from_config(cfg: &DomainsConfig) -> Self`.
|
||||||
|
|
||||||
|
### 10. Dashboard UI additions
|
||||||
|
|
||||||
|
**SvelteKit routes** (`apps/dashboard/src/routes/(app)/domains/`):
|
||||||
|
|
||||||
|
- `+page.svelte` (list): fetches `GET /api/v1/domains` and `GET /api/v1/domains/unclassified-count`. Renders a table: `label`, `memories`, `top_terms` chips, `created_at`. Each row links to `/domains/[id]`. A "Discover" button posts `POST /api/v1/domains/discover`.
|
||||||
|
- `[id]/+page.svelte` (detail): fetches `GET /api/v1/domains/:id`, `GET /api/v1/domains/:id/memories?limit=100`, `GET /api/v1/domains/:id/score-histogram`. Renders:
|
||||||
|
- Header: label (editable, triggers `PUT /api/v1/domains/:id`), top-terms chips, memory count, created_at.
|
||||||
|
- Histogram: a vertical bar chart of `domain_scores[:id]` buckets 0-0.1, 0.1-0.2, ..., 0.9-1.0 across all memories. Data source: server precomputes buckets so the client does not need to fetch all scores.
|
||||||
|
- Memory list: paginated, each row shows the raw score for this domain.
|
||||||
|
- `proposals/+page.svelte`: fetches `GET /api/v1/domains/proposals?status=pending`. Each pending proposal card shows `kind`, `rationale`, `confidence`, `created_at`, buttons "Accept" (posts `POST /api/v1/domains/proposals/:id/accept`) and "Reject" (`POST .../reject`). Live updates via the existing WebSocket channel (`/ws`) reacting to `DomainProposalCreated` events.
|
||||||
|
|
||||||
|
Styling reuses the existing Tailwind + shadcn-svelte conventions in `apps/dashboard/src/lib/components/`.
|
||||||
|
|
||||||
|
Existing `(app)/stats` and `(app)/feed` pages get a small "Domains" summary panel that links to `/domains`.
|
||||||
|
|
||||||
|
### 11. REST endpoints
|
||||||
|
|
||||||
|
**File**: `crates/vestige-mcp/src/protocol/http.rs` or a new `crates/vestige-mcp/src/api/domains.rs` module, wired into the `/api/v1/` router.
|
||||||
|
|
||||||
|
| Method | Path | Handler |
|
||||||
|
|--------|------|---------|
|
||||||
|
| GET | `/api/v1/domains` | `list_domains` -- returns `[Domain...]` + unclassified count |
|
||||||
|
| POST | `/api/v1/domains/discover` | `trigger_discover` -- body `{ min_cluster_size?: usize, force?: bool }`, returns proposals or applied domains |
|
||||||
|
| GET | `/api/v1/domains/:id` | `get_domain` |
|
||||||
|
| PUT | `/api/v1/domains/:id` | `update_domain` -- rename |
|
||||||
|
| DELETE | `/api/v1/domains/:id` | `delete_domain` -- with `?merge_into=other_id` |
|
||||||
|
| GET | `/api/v1/domains/:id/memories` | paginated memories in this domain |
|
||||||
|
| GET | `/api/v1/domains/:id/score-histogram` | precomputed buckets |
|
||||||
|
| GET | `/api/v1/domains/proposals` | `list_proposals?status=pending` |
|
||||||
|
| POST | `/api/v1/domains/proposals/:id/accept` | `accept_proposal` |
|
||||||
|
| POST | `/api/v1/domains/proposals/:id/reject` | `reject_proposal` |
|
||||||
|
|
||||||
|
All handlers go through the Phase 3 auth middleware (Bearer / X-API-Key / session cookie). Responses are JSON; error paths use `StatusCode::*` with a small `{"error": "..."}` body.
|
||||||
|
|
||||||
|
### 12. `domain_proposals` table + trait methods
|
||||||
|
|
||||||
|
Postgres migration (`crates/vestige-core/migrations/postgres/00XX_domain_proposals.sql`):
|
||||||
|
|
||||||
|
```sql
|
||||||
|
CREATE TABLE domain_proposals (
|
||||||
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
kind TEXT NOT NULL, -- 'split' | 'merge' | 'new_cluster'
|
||||||
|
payload JSONB NOT NULL, -- serialized ProposalKind body
|
||||||
|
rationale TEXT NOT NULL,
|
||||||
|
confidence DOUBLE PRECISION NOT NULL,
|
||||||
|
status TEXT NOT NULL DEFAULT 'pending', -- pending|accepted|rejected
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||||
|
resolved_at TIMESTAMPTZ
|
||||||
|
);
|
||||||
|
CREATE INDEX idx_domain_proposals_status ON domain_proposals (status, created_at DESC);
|
||||||
|
```
|
||||||
|
|
||||||
|
SQLite migration: same table, `UUID` -> `TEXT`, `JSONB` -> `TEXT` with JSON-encoded bodies, `TIMESTAMPTZ` -> `TEXT` ISO-8601.
|
||||||
|
|
||||||
|
`MemoryStore` trait additions:
|
||||||
|
|
||||||
|
```rust
|
||||||
|
async fn insert_domain_proposal(&self, p: &DomainProposal) -> Result<()>;
|
||||||
|
async fn list_domain_proposals(&self, status: Option<&str>) -> Result<Vec<DomainProposal>>;
|
||||||
|
async fn get_domain_proposal(&self, id: &str) -> Result<Option<DomainProposal>>;
|
||||||
|
async fn set_proposal_status(&self, id: &str, status: &str) -> Result<()>;
|
||||||
|
```
|
||||||
|
|
||||||
|
### 13. WebSocket event for proposals
|
||||||
|
|
||||||
|
**File**: `crates/vestige-mcp/src/dashboard/events.rs`
|
||||||
|
|
||||||
|
Add variant:
|
||||||
|
|
||||||
|
```rust
|
||||||
|
pub enum VestigeEvent {
|
||||||
|
// ... existing ...
|
||||||
|
DomainProposalCreated {
|
||||||
|
id: String,
|
||||||
|
kind: String,
|
||||||
|
confidence: f64,
|
||||||
|
timestamp: DateTime<Utc>,
|
||||||
|
},
|
||||||
|
MemoryClassified {
|
||||||
|
id: String,
|
||||||
|
domains: Vec<String>,
|
||||||
|
top_score: f64,
|
||||||
|
timestamp: DateTime<Utc>,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
The SvelteKit dashboard's WS client reacts to both events: classified events refresh any open domain-detail page; proposal events push a toast and a badge on the navbar.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Test Plan
|
||||||
|
|
||||||
|
Test root: `tests/phase_4/` (a new member of the workspace; mirror the `tests/e2e` layout).
|
||||||
|
|
||||||
|
`tests/phase_4/Cargo.toml`:
|
||||||
|
|
||||||
|
```toml
|
||||||
|
[package]
|
||||||
|
name = "vestige-phase4-tests"
|
||||||
|
version = "0.0.0"
|
||||||
|
edition = "2024"
|
||||||
|
publish = false
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
vestige-core = { path = "../../crates/vestige-core", features = ["embeddings", "vector-search", "domain-classification"] }
|
||||||
|
vestige-mcp = { path = "../../crates/vestige-mcp" }
|
||||||
|
tokio = { workspace = true }
|
||||||
|
anyhow = "1"
|
||||||
|
tempfile = "3"
|
||||||
|
serde_json = { workspace = true }
|
||||||
|
uuid = { workspace = true }
|
||||||
|
```
|
||||||
|
|
||||||
|
### Unit tests (colocated in `domain_classifier.rs::tests`, `context_signals.rs::tests`, `spreading_activation.rs::tests`)
|
||||||
|
|
||||||
|
Each public function must have at least one test:
|
||||||
|
|
||||||
|
- `classify_empty_domains_returns_empty`: `classify(&[0.0; 768], &[])` returns `ClassificationResult { scores: {}, domains: [] }`.
|
||||||
|
- `classify_single_domain_scores`: one `Domain` with a known centroid; input embedding equal to centroid; expect score 1.0 and `domains == [id]`.
|
||||||
|
- `classify_multi_domain_overlap`: two domains A, B; input halfway between centroids; expect both scores >= `assign_threshold`; expect `domains == [A, B]` (order not guaranteed).
|
||||||
|
- `classify_below_threshold_returns_empty_domains_but_scores_filled`: input orthogonal to all centroids; expect `scores` populated, `domains` empty.
|
||||||
|
- `classify_with_boost_adds_delta`: same input as above, with `boost = {A: 0.4}`; expect A now above threshold, B unchanged.
|
||||||
|
- `classify_boost_clamps_to_unit`: `boost = {A: 5.0}`; resulting `scores[A]` must be <= 1.0.
|
||||||
|
- `tfidf_top_k_returns_distinct_terms`: given three fake docs, `top_k=3` returns three non-duplicate strings, in descending TF-IDF order.
|
||||||
|
- `tfidf_top_k_drops_stopwords`: `["the and for"]` + real content -> stop-words absent.
|
||||||
|
- `compute_top_terms_handles_empty_cluster`: returns `vec![]` (no panic).
|
||||||
|
- `signal_git_present_vs_absent`: `GitRepoSignal` given metadata with `.git` in cwd returns non-empty map; without it returns empty.
|
||||||
|
- `signal_ide_present_vs_absent`: `IdeHintSignal` ditto for `metadata.editor == "vscode"`.
|
||||||
|
- `signal_combined_clamped`: two signals both firing each at +0.10 -> combined map values <= +0.15.
|
||||||
|
- `cross_domain_decay_full_weight_on_overlap`: graph with node A in domain `dev`, node B in domain `dev`, edge A->B strength 1.0; after `activate`, B's activation equals the standard `initial * strength * decay_factor` (no extra penalty).
|
||||||
|
- `cross_domain_decay_half_weight_no_overlap`: A in `dev`, B in `infra`, same edge -> B's activation is 0.5x that of the overlap case.
|
||||||
|
- `cross_domain_decay_unclassified_no_penalty`: A classified, B unclassified -> full weight.
|
||||||
|
- `propose_changes_detects_split`: existing domain `dev`; new discovery returns two clusters whose centroids both sit close to old `dev` centroid, each >= min_cluster_size members -> proposal of kind `Split { parent: "dev", children: [a, b] }`.
|
||||||
|
- `propose_changes_detects_merge`: two existing domains whose new centroids now have cosine > `merge_threshold` -> proposal of kind `Merge`.
|
||||||
|
- `propose_changes_detects_new_cluster`: a new cluster with no match >= 0.85 to any existing -> `NewCluster`.
|
||||||
|
- `apply_proposal_split_updates_memberships`: after accept, memories previously in `dev` get reassigned (some to child a, some to child b) via `reassign_all`.
|
||||||
|
|
||||||
|
### Integration tests (`tests/phase_4/tests/`)
|
||||||
|
|
||||||
|
One file per behavior listed in the Phase 4 acceptance sheet.
|
||||||
|
|
||||||
|
- `discover_seed_corpus.rs` -- loads the 500-memory fixture, runs `classifier.discover(&store).await`, asserts at least 3 clusters, asserts per-cluster intra-similarity mean > 0.6, asserts discovery wall time < 10s in release. Also asserts `top_terms` for each cluster contains at least one expected keyword per cluster (dev: contains any of `rust/trait/async`; infra: `bgp/vlan/network`; home: `solar/battery/pool`).
|
||||||
|
- `soft_assign_multi_domain.rs` -- inserts a memory "deploy zinit containers over BGP network"; after classify, `domains` contains both `dev` and `infra` (from a known centroid setup).
|
||||||
|
- `auto_classify_on_ingest.rs` -- with three existing domains, a fresh `smart_ingest` of a dev-ish sentence ends up with `domains == ["dev"]` and non-empty `domain_scores`.
|
||||||
|
- `reembed_triggers_recluster.rs` -- after `vestige migrate --reembed`, centroids must be recomputed; verify `list_domains()` returns fresh `centroid` values (different from pre-reembed).
|
||||||
|
- `dream_consolidation_recluster_hook.rs` -- run 5 dream cycles with heavy synthetic memory insertion; after the 5th, assert `list_domain_proposals("pending")` has at least one proposal.
|
||||||
|
- `proposal_accept_applies_changes.rs` -- accept a split proposal via `apply_proposal`; verify that memories in `dev` are now distributed across the new children and that the old `dev` domain is removed.
|
||||||
|
- `proposal_reject_leaves_state.rs` -- reject a proposal; verify all domains and memberships unchanged.
|
||||||
|
- `drift_is_proposal_only.rs` -- over 5 dream cycles with new inserts, never call accept; verify every memory's `domains` field equals its initial post-discovery value. No auto-apply.
|
||||||
|
- `cross_domain_activation_decay.rs` -- build a `ActivationNetwork` with two memories linked by a strength-1.0 edge, one in `dev`, one in `infra`; activate `dev` memory with 1.0; assert `infra` memory's activation == `0.5 * decay_factor` (0.35 with default decay_factor 0.7). Then set both to `dev` and reassert activation == `0.7`.
|
||||||
|
- `cli_domains_discover.rs` -- spawn `cargo run -- domains discover --force --json`, parse stdout, assert at least 3 clusters and valid JSON shape.
|
||||||
|
- `cli_domains_rename_merge.rs` -- happy-path rename then merge, with stdout assertions.
|
||||||
|
- `context_signal_git_repo.rs` -- ingest the same sentence from inside a tempdir with `.git` vs outside; assert the git-run produces slightly higher `domain_scores` for the code-related domain (diff >= 0.04, matches `git_boost = 0.05`).
|
||||||
|
- `threshold_tunable.rs` -- same memory, two runs with `assign_threshold = 0.40` vs `0.85`; the low-threshold run assigns more domains than the high-threshold run for the same content.
|
||||||
|
- `signal_boost_clamped.rs` -- artificially configure `git_boost = 5.0` and assert the resulting per-domain score is still <= 1.0.
|
||||||
|
- `discover_preserves_stable_ids.rs` -- run discover twice with no new memories; the second run's domain ids match the first's (via centroid-similarity stable-ID matching above 0.85).
|
||||||
|
|
||||||
|
### Dashboard UI tests (`tests/phase_4/ui/`)
|
||||||
|
|
||||||
|
Use curl-driven smoke tests (avoids adding Playwright as a new hard dep; Playwright already exists at `apps/dashboard/playwright.config.ts` and can be extended later).
|
||||||
|
|
||||||
|
- `domains_list_renders.sh` -- `curl -H "X-API-Key: $KEY" http://localhost:3927/api/v1/domains` returns 200 + JSON array with expected keys.
|
||||||
|
- `domain_detail_histogram.sh` -- `curl .../api/v1/domains/dev/score-histogram` returns 10 buckets.
|
||||||
|
- `proposal_review_flow.sh` -- create a pending proposal via SQL insert; `curl POST .../api/v1/domains/proposals/<id>/accept`; `curl GET .../proposals?status=accepted` shows it.
|
||||||
|
- `unauth_domain_list_rejected.sh` -- no auth header -> 401.
|
||||||
|
|
||||||
|
### Benchmarks (`tests/phase_4/benches/`)
|
||||||
|
|
||||||
|
Criterion benches:
|
||||||
|
|
||||||
|
- `bench_discover_10k.rs` -- synthetic 10k x 768D embeddings drawn from 5 blobs; assert `discover` wall p95 < 30s on a warm release build.
|
||||||
|
- `bench_auto_classify_single.rs` -- 20 domains in memory, classify one 768D vector; assert p99 < 5ms.
|
||||||
|
- `bench_reassign_all.rs` -- 10k memories, 5 domains; assert full `reassign_all` wall time < 90s (100 rows/ms baseline).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Acceptance Criteria
|
||||||
|
|
||||||
|
- [ ] `cargo build -p vestige-core --features domain-classification` zero warnings.
|
||||||
|
- [ ] `cargo build -p vestige-mcp` zero warnings.
|
||||||
|
- [ ] `cargo clippy --workspace --all-targets --all-features -- -D warnings` clean.
|
||||||
|
- [ ] `cargo test -p vestige-phase4-tests` -- all tests in `tests/phase_4/` pass.
|
||||||
|
- [ ] On a 500+ memory seed corpus covering three natural clusters (dev / infra / home), `vestige domains discover --force` produces sensible top-terms matching the expected keyword sets and labels are stable on a second run.
|
||||||
|
- [ ] `vestige search` with domain filter `["dev"]` excludes any memory whose `domains` array does not include `dev`.
|
||||||
|
- [ ] After 5 dream cycles with ongoing inserts, no existing memory's `domains` has silently changed; proposals exist in `domain_proposals` table; accepting a proposal reassigns as described.
|
||||||
|
- [ ] Cross-domain spreading activation: a query in `dev` that crosses a single edge into an `infra`-only memory still returns the memory but with activation `cross_domain_decay * in-domain_activation`.
|
||||||
|
- [ ] `vestige domains discover --min-cluster-size 20` produces strictly fewer or equal clusters than the default, and with larger per-cluster membership.
|
||||||
|
- [ ] Dashboard `/dashboard/domains` route renders all domains within 2 seconds on the seed corpus.
|
||||||
|
- [ ] Proposal UI flow (open pending, accept, confirmed in store) works end-to-end.
|
||||||
|
- [ ] Benchmarks meet targets (discover 10k p95 < 30s, auto-classify p99 < 5ms).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Rollback Notes
|
||||||
|
|
||||||
|
- **Feature gate**: add `domain-classification` to `crates/vestige-core/Cargo.toml`'s `[features]`. When disabled, the `DomainClassifier` module is not compiled, the classification call in the ingest path is a no-op (`#[cfg]`-guarded), and cross-domain decay collapses to `1.0`. The CLI `domains` subcommand emits "domain classification is disabled in this build".
|
||||||
|
- **Revert strategy**: drop the two new tables `domains` (if created in Phase 1 is retained) or `domain_proposals` (Phase 4). A DOWN migration clears `memories.domains` and `memories.domain_scores`. Existing memories simply lose their domain assignments; all search and retrieval paths work unchanged because `domains = []` is the documented "unclassified" state.
|
||||||
|
- **Idempotency**: rerunning `discover` is always safe. Cluster numeric IDs may differ between runs, but the stable-ID match by centroid similarity preserves user-assigned labels. Do not persist cluster ids in client-side bookmarks; link via the user-assigned label.
|
||||||
|
- **Data-loss risk**: `apply_proposal` is a destructive operation (it deletes the old parent domain in a split or merges two). The dashboard's accept button double-confirms with a modal that shows the number of affected memories.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Open Implementation Questions
|
||||||
|
|
||||||
|
Each question + candidates + RECOMMENDATION.
|
||||||
|
|
||||||
|
### OQ1. Top-terms extraction: TF-IDF vs BM25 vs frequency?
|
||||||
|
- TF-IDF with smoothed IDF -- standard, cheap, good-enough.
|
||||||
|
- BM25 -- better for long-document discrimination, overkill for short memory contents.
|
||||||
|
- Raw frequency -- noisy; stop-words dominate.
|
||||||
|
**RECOMMENDATION**: TF-IDF with global IDF over the entire memory corpus (not just cluster members), recomputed once per `discover` call. Same tokenizer as the `dreams.rs::content_similarity` Jaccard for consistency.
|
||||||
|
|
||||||
|
### OQ2. Proposal persistence: DB table vs in-memory with dashboard notification?
|
||||||
|
- DB table (`domain_proposals`) -- durable, surfaces across restarts, enables audit.
|
||||||
|
- In-memory only -- simpler, but loses proposals on server restart.
|
||||||
|
**RECOMMENDATION**: DB table. Proposals are rare (every 5th dream) and valuable user-facing artifacts; durability is mandatory.
|
||||||
|
|
||||||
|
### OQ3. `hdbscan` crate: f32 vs f64 input, exact API surface?
|
||||||
|
- v0.10 historically takes `&[Vec<f64>]`; embeddings are `Vec<f32>`.
|
||||||
|
- Cost of converting f32 -> f64 at discovery time: `10k * 768 = 7.68M` f64 doubles ~ 60MB transient, acceptable.
|
||||||
|
**RECOMMENDATION**: verify v0.10's type signature at implementation time; if it requires f64, perform the conversion in `discover()` behind a single allocation. Document in module header. If the crate API diverged from the PRD snippet, fall back to the manual builder style (`HdbscanHyperParams::builder().min_cluster_size(n).min_samples(s).build()`).
|
||||||
|
|
||||||
|
### OQ4. Stable domain IDs across discover re-runs?
|
||||||
|
- Option A: numeric IDs from HDBSCAN labels -- unstable, re-runs shuffle them.
|
||||||
|
- Option B: hash(top_terms) -- stable if top-terms stable, but top-terms drift.
|
||||||
|
- Option C (recommended): after computing new centroids, match each to the closest existing domain by centroid cosine; if similarity > 0.85, reuse the existing domain's `id` and `label`. Otherwise mint a fresh `id = "cluster_<uuid>"`.
|
||||||
|
**RECOMMENDATION**: Option C. Preserves user-assigned labels across drift. Threshold 0.85 is config-tunable via `stable_id_threshold` if needed later.
|
||||||
|
|
||||||
|
### OQ5. Context signal injection site: ingest handler vs embedder vs classifier?
|
||||||
|
- Embedder -- would alter embedding; signals are not about embedding quality.
|
||||||
|
- Ingest handler -- signals known there, but then `DomainClassifier` cannot be tested in isolation.
|
||||||
|
- Classifier as a `classify_with_boost(boost: Option<&HashMap>)` parameter -- pure, testable, composable.
|
||||||
|
**RECOMMENDATION**: classifier parameter. The cognitive engine constructs the boost map via `ContextSignals::gather_boost(&metadata, &domains)` and hands it to the classifier. Keeps the classifier stateless w.r.t. signals.
|
||||||
|
|
||||||
|
### OQ6. Re-cluster proposal cadence: event-based (every Nth dream) vs time-based (weekly)?
|
||||||
|
- ADR resolution Q7: every Nth dream (N=5 default).
|
||||||
|
- Alternative: once per week regardless of dream cadence.
|
||||||
|
**RECOMMENDATION**: stick with every Nth dream. Users who dream rarely re-cluster rarely -- that matches the philosophy ("memory work triggers memory bookkeeping"). Note the alternative as future consideration; if users complain about never seeing proposals, add a time-based fallback.
|
||||||
|
|
||||||
|
### OQ7. Minimum corpus size for first discover?
|
||||||
|
- PRD default: 150.
|
||||||
|
- Too low -> noisy initial clusters, proposals every dream.
|
||||||
|
- Too high -> user waits forever for domains to appear.
|
||||||
|
**RECOMMENDATION**: 150 as the default discovery gate; HDBSCAN's `min_cluster_size=10` will produce 0 clusters for < 100 memories, so the system gracefully produces no domains until the corpus is large enough. Test with `N=80, 150, 500` in `threshold_tunable.rs` to confirm sensible behavior.
|
||||||
|
|
||||||
|
### OQ8. Cross-domain decay: strict no-overlap vs graded?
|
||||||
|
- Strict: `1.0` if any overlap, `cross_domain_decay` otherwise.
|
||||||
|
- Graded: `max(cross_domain_decay, |A intersect B| / max(|A|, |B|))`.
|
||||||
|
**RECOMMENDATION**: strict for Phase 4. Easier to reason about, easier to tune, easier to test. Graded is a marked future enhancement; file an issue if retrieval-quality metrics justify it.
|
||||||
|
|
||||||
|
### OQ9. Classifier invocation from remote HTTP clients?
|
||||||
|
- In server mode, an agent posts `smart_ingest` -> server embeds -> server classifies.
|
||||||
|
- All the work stays server-side; MCP clients never do classification.
|
||||||
|
**RECOMMENDATION**: confirmed server-side-only. Document in the MCP tool schema that `smart_ingest` now returns `domains` and `domain_scores` in its response so clients can display the classification to the user.
|
||||||
|
|
||||||
|
### OQ10. Where to store the dream-cycle counter?
|
||||||
|
- In-memory on `CognitiveEngine` -- lost on restart, miscounts cadence.
|
||||||
|
- New `system_state` singleton table.
|
||||||
|
**RECOMMENDATION**: `system_state` table. Survives restarts. Also useful for future metrics (total memories ever, total dreams ever).
|
||||||
|
|
||||||
|
### OQ11. Scope of `reassign_all` after a proposal accept vs a normal discover?
|
||||||
|
- On discover --force (first-time), run `reassign_all` against all memories.
|
||||||
|
- On proposal accept (split / merge), run `reassign_all` only on affected memories (parent's members for split; both parents' members for merge) to avoid touching unrelated records.
|
||||||
|
**RECOMMENDATION**: scoped reassignment where possible; fall back to full `reassign_all` only on `discover --force` or when the set of domains has fundamentally changed. Reduces write amplification on large corpora.
|
||||||
|
|
||||||
|
### OQ12. Proposal freshness?
|
||||||
|
- Multiple re-clusters could stack up pending proposals.
|
||||||
|
**RECOMMENDATION**: before inserting a new proposal, check for existing pending proposals with the same `kind + targets`; if present, bump `created_at` and `confidence` instead of creating a duplicate. Add a `confidence_history` array in the `payload` JSONB for audit.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Implementation Sequencing (suggested order)
|
||||||
|
|
||||||
|
1. Land the `DomainClassifier` struct, `classify` / `classify_with_boost`, unit tests. (Day 1)
|
||||||
|
2. Add `compute_top_terms` + TF-IDF helper, tests. (Day 1)
|
||||||
|
3. Wire `discover` end-to-end against SQLite; `discover_seed_corpus` integration test. (Day 2)
|
||||||
|
4. Add `domain_proposals` table migrations + trait methods; both backends. (Day 2)
|
||||||
|
5. Implement `propose_changes` + `apply_proposal`; proposal unit tests. (Day 3)
|
||||||
|
6. Context signals module + tests. (Day 3)
|
||||||
|
7. Hook classifier into ingest path; `auto_classify_on_ingest` integration test. (Day 4)
|
||||||
|
8. Cross-domain decay in spreading activation; unit + integration tests. (Day 4)
|
||||||
|
9. Dream re-cluster hook + `system_state` counter; integration tests for drift-only behavior. (Day 5)
|
||||||
|
10. CLI subcommands. (Day 6)
|
||||||
|
11. REST endpoints. (Day 6)
|
||||||
|
12. SvelteKit dashboard routes + WebSocket event wiring. (Day 7-8)
|
||||||
|
13. Benchmarks + acceptance sweep on the 500-memory seed. (Day 9)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## File Map (everything Phase 4 touches or creates)
|
||||||
|
|
||||||
|
Creates:
|
||||||
|
|
||||||
|
- `crates/vestige-core/src/neuroscience/domain_classifier.rs`
|
||||||
|
- `crates/vestige-core/src/neuroscience/context_signals.rs`
|
||||||
|
- `crates/vestige-core/migrations/postgres/00XX_domain_proposals.sql`
|
||||||
|
- `crates/vestige-core/migrations/sqlite/00XX_domain_proposals.sql` (or inline in `storage/migrations.rs`)
|
||||||
|
- `crates/vestige-mcp/src/api/domains.rs` (REST handlers)
|
||||||
|
- `apps/dashboard/src/routes/(app)/domains/+page.svelte`
|
||||||
|
- `apps/dashboard/src/routes/(app)/domains/[id]/+page.svelte`
|
||||||
|
- `apps/dashboard/src/routes/(app)/domains/proposals/+page.svelte`
|
||||||
|
- `apps/dashboard/src/lib/api/domains.ts`
|
||||||
|
- `tests/phase_4/Cargo.toml`
|
||||||
|
- `tests/phase_4/tests/*.rs` (per the Integration test list)
|
||||||
|
- `tests/phase_4/fixtures/seed_500.json`
|
||||||
|
- `tests/phase_4/support/fixtures.rs`
|
||||||
|
|
||||||
|
Modifies:
|
||||||
|
|
||||||
|
- `crates/vestige-core/Cargo.toml` -- add `hdbscan = "0.10"` under a new `domain-classification` feature.
|
||||||
|
- `crates/vestige-core/src/neuroscience/mod.rs` -- register new modules, re-exports.
|
||||||
|
- `crates/vestige-core/src/neuroscience/spreading_activation.rs` -- `cross_domain_decay` field in `ActivationConfig`, `domains` field on `ActivationNode`, decay math in `activate`.
|
||||||
|
- `crates/vestige-core/src/consolidation/phases.rs` -- `DreamReClusterHook`.
|
||||||
|
- `crates/vestige-core/src/advanced/dreams.rs` -- accept a hook callback from the orchestrator (if the orchestration is done at this level).
|
||||||
|
- `crates/vestige-core/src/storage/trait.rs` -- add proposal + system_state methods.
|
||||||
|
- `crates/vestige-core/src/storage/sqlite.rs` -- implement proposal + system_state methods + `all_embeddings_with_meta` if not already on the trait.
|
||||||
|
- `crates/vestige-core/src/storage/postgres.rs` (Phase 2) -- same.
|
||||||
|
- `crates/vestige-core/src/lib.rs` -- re-exports.
|
||||||
|
- `crates/vestige-core/src/cognitive.rs` (or equivalent ingest orchestrator) -- auto-classify injection.
|
||||||
|
- `crates/vestige-mcp/src/bin/cli.rs` -- `Domains` subcommand + dispatch.
|
||||||
|
- `crates/vestige-mcp/src/dashboard/mod.rs` -- wire new REST routes.
|
||||||
|
- `crates/vestige-mcp/src/dashboard/events.rs` -- new event variants.
|
||||||
|
- `crates/vestige-mcp/src/dashboard/handlers.rs` -- if legacy dashboard gets a domains panel (optional).
|
||||||
|
- `vestige.toml` config loader -- `[domains]` section + struct + defaults.
|
||||||
|
- Root `Cargo.toml` workspace members -- add `tests/phase_4`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Risks
|
||||||
|
|
||||||
|
- **HDBSCAN determinism**: HDBSCAN is deterministic given input order; sorting embeddings by memory id before feeding the clusterer guarantees reproducibility across runs -- do this in `discover()` and document it.
|
||||||
|
- **Embedding dimension drift**: Phase 1's `embedding_model` registry blocks writes from mismatched embedders. If `discover()` ever sees two dimensions, it bails with a clear error and points at `vestige migrate --reembed`.
|
||||||
|
- **Classification latency on ingest**: for users with thousands of domains (unlikely but possible), `classify` is O(n_domains * dim). 20 domains * 768 f32 = 15k flops per classification, trivial. Still, expose a `classify_budget_ms` config knob for paranoia.
|
||||||
|
- **Re-cluster proposal storms**: if the corpus is borderline-stable, small changes can produce conflicting proposals on consecutive dreams. Mitigation: OQ12 (dedup by target set, bump confidence instead of stacking).
|
||||||
|
- **Dashboard feature gap**: if the SvelteKit app lands with the domains route but the REST endpoints are not yet deployed, the route 404s. Mitigation: ship the REST endpoints in the same release; a feature flag on the client toggles the nav entry.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Non-Goals Reminder
|
||||||
|
|
||||||
|
- No Phase 5 federation concerns in this plan.
|
||||||
|
- No cross-installation domain sync.
|
||||||
|
- No automatic accept of proposals, ever.
|
||||||
|
- No graded cross-domain decay; strict only.
|
||||||
|
- No ML-based domain label suggestion (top-terms are enough for v1).
|
||||||
|
- No editing individual memory memberships from the UI in this phase.
|
||||||
279
docs/plans/local-dev-postgres-setup.md
Normal file
279
docs/plans/local-dev-postgres-setup.md
Normal file
|
|
@ -0,0 +1,279 @@
|
||||||
|
# Local Dev Postgres Setup (container, hybrid approach)
|
||||||
|
|
||||||
|
**Status**: Applied on this machine on 2026-05-27 (rootless podman, Postgres 18.4 + pgvector 0.8.2).
|
||||||
|
**Related**: docs/plans/0002-phase-2-postgres-backend.md, docs/adr/0002-phase-2-execution.md, docs/adr/0001-pluggable-storage-and-network-access.md
|
||||||
|
|
||||||
|
Purpose: capture the minimum, repeatable steps to stand up a long-lived
|
||||||
|
Postgres 18 + pgvector instance on a local Linux dev box for Phase 2
|
||||||
|
(`PgMemoryStore`) development, `sqlx prepare`, and manual migration
|
||||||
|
testing. This is a single-operator dev recipe, not a production runbook.
|
||||||
|
|
||||||
|
ADR 0002 picked the **hybrid container** approach over a native install:
|
||||||
|
the `pgvector/pgvector:pg18` image ships pgvector pre-installed, matches
|
||||||
|
the image testcontainers will use in the Phase 2 test harness, and avoids
|
||||||
|
the AUR/build-from-source friction of native pgvector packaging on Arch.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Current state on this machine
|
||||||
|
|
||||||
|
- Runtime: rootless `podman` 5.8.2 (Arch). `docker` 29.5.1 also installed but unused.
|
||||||
|
- Image: `docker.io/pgvector/pgvector:pg18` (PostgreSQL 18.4, pgvector 0.8.2).
|
||||||
|
- Container: `vestige-pg`, `--restart=always`, port `127.0.0.1:5432:5432`.
|
||||||
|
- Volume: named podman volume `vestige-pgdata`, mounted at
|
||||||
|
`/var/lib/postgresql/data` inside the container; `PGDATA` points at
|
||||||
|
`/var/lib/postgresql/data/pgdata` so the volume mount is non-empty at
|
||||||
|
init time (Postgres refuses to initdb into a non-empty directory).
|
||||||
|
- Listens on: `127.0.0.1:5432` only (port mapping is bound to loopback).
|
||||||
|
- Auth: `scram-sha-256` (image default for both local socket and host).
|
||||||
|
|
||||||
|
### Database + role
|
||||||
|
|
||||||
|
- Database: `vestige`, UTF8, owner `vestige`, `LC_COLLATE=C.UTF-8`, `LC_CTYPE=C.UTF-8`.
|
||||||
|
- Role: `vestige` with `LOGIN CREATEDB` (no superuser, no replication).
|
||||||
|
- Schema `public` re-owned to `vestige` with full default privileges on
|
||||||
|
future tables / sequences / functions.
|
||||||
|
- Extension: `vector` (pgvector 0.8.2) installed in the `vestige`
|
||||||
|
database by the superuser at setup time.
|
||||||
|
|
||||||
|
Net effect: the `vestige` role can create, alter, drop, and grant freely
|
||||||
|
inside the `vestige` database -- enough for `sqlx::migrate!`, ad-hoc
|
||||||
|
schema work, and the full Phase 2 `MemoryStore` surface. It cannot create
|
||||||
|
extensions; the superuser handled `CREATE EXTENSION vector` already.
|
||||||
|
|
||||||
|
### Passwords
|
||||||
|
|
||||||
|
Two passwords live in the dev user's home, mode 600:
|
||||||
|
|
||||||
|
- `~/.vestige_pg_superpw` -- the `postgres` superuser password inside the
|
||||||
|
container. Used for one-shot admin tasks (creating roles, installing
|
||||||
|
extensions, password rotation). Day-to-day app traffic does NOT use it.
|
||||||
|
- `~/.vestige_pg_pw` -- the `vestige` role password. This is the one the
|
||||||
|
Phase 2 backend, `sqlx prepare`, and ad-hoc `psql` invocations use.
|
||||||
|
|
||||||
|
### Connection
|
||||||
|
|
||||||
|
```
|
||||||
|
postgresql://vestige:<password>@127.0.0.1:5432/vestige
|
||||||
|
```
|
||||||
|
|
||||||
|
Recommended dev shell export (keep this OUT of the repo; use `.env` +
|
||||||
|
gitignore or a shell rc):
|
||||||
|
|
||||||
|
```sh
|
||||||
|
export DATABASE_URL="postgresql://vestige:$(cat ~/.vestige_pg_pw)@127.0.0.1:5432/vestige"
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Reproduce from scratch
|
||||||
|
|
||||||
|
On a fresh Linux box with `podman` installed and `python3` available:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
# 1. Pull the image
|
||||||
|
podman pull docker.io/pgvector/pgvector:pg18
|
||||||
|
|
||||||
|
# 2. Create a persistent named volume
|
||||||
|
podman volume create vestige-pgdata
|
||||||
|
|
||||||
|
# 3. Generate the superuser password and stash it (mode 600)
|
||||||
|
SUPER_PW=$(python3 -c 'import secrets,string; a=string.ascii_letters+string.digits; print("".join(secrets.choice(a) for _ in range(32)))')
|
||||||
|
umask 077
|
||||||
|
printf '%s' "$SUPER_PW" > ~/.vestige_pg_superpw
|
||||||
|
chmod 600 ~/.vestige_pg_superpw
|
||||||
|
|
||||||
|
# 4. Start the container
|
||||||
|
podman run -d \
|
||||||
|
--name vestige-pg \
|
||||||
|
--restart=always \
|
||||||
|
-p 127.0.0.1:5432:5432 \
|
||||||
|
-e POSTGRES_PASSWORD="$SUPER_PW" \
|
||||||
|
-e PGDATA=/var/lib/postgresql/data/pgdata \
|
||||||
|
-v vestige-pgdata:/var/lib/postgresql/data \
|
||||||
|
docker.io/pgvector/pgvector:pg18
|
||||||
|
|
||||||
|
unset SUPER_PW
|
||||||
|
|
||||||
|
# 5. Wait for ready
|
||||||
|
until podman exec vestige-pg pg_isready -U postgres -h 127.0.0.1 >/dev/null 2>&1; do
|
||||||
|
sleep 1
|
||||||
|
done
|
||||||
|
|
||||||
|
# 6. Generate the vestige role password and stash it (mode 600)
|
||||||
|
VESTIGE_PW=$(python3 -c 'import secrets,string; a=string.ascii_letters+string.digits; print("".join(secrets.choice(a) for _ in range(32)))')
|
||||||
|
umask 077
|
||||||
|
printf '%s' "$VESTIGE_PW" > ~/.vestige_pg_pw
|
||||||
|
chmod 600 ~/.vestige_pg_pw
|
||||||
|
|
||||||
|
# 7. Create role + database + grants + extension (runs as superuser inside the container)
|
||||||
|
podman exec -i vestige-pg psql -U postgres -v ON_ERROR_STOP=1 <<SQL
|
||||||
|
CREATE ROLE vestige WITH LOGIN CREATEDB PASSWORD '${VESTIGE_PW}';
|
||||||
|
CREATE DATABASE vestige OWNER vestige ENCODING 'UTF8'
|
||||||
|
TEMPLATE template0 LC_COLLATE 'C.UTF-8' LC_CTYPE 'C.UTF-8';
|
||||||
|
GRANT ALL PRIVILEGES ON DATABASE vestige TO vestige;
|
||||||
|
SQL
|
||||||
|
|
||||||
|
podman exec -i vestige-pg psql -U postgres -d vestige -v ON_ERROR_STOP=1 <<'SQL'
|
||||||
|
GRANT ALL ON SCHEMA public TO vestige;
|
||||||
|
ALTER SCHEMA public OWNER TO vestige;
|
||||||
|
ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL ON TABLES TO vestige;
|
||||||
|
ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL ON SEQUENCES TO vestige;
|
||||||
|
ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL ON FUNCTIONS TO vestige;
|
||||||
|
CREATE EXTENSION IF NOT EXISTS vector;
|
||||||
|
SQL
|
||||||
|
|
||||||
|
unset VESTIGE_PW
|
||||||
|
|
||||||
|
# 8. Smoke test as the vestige role
|
||||||
|
PGPASSWORD="$(cat ~/.vestige_pg_pw)" psql -h 127.0.0.1 -U vestige -d vestige \
|
||||||
|
-c "SELECT current_user, current_database(), version();" \
|
||||||
|
-c "SELECT extname, extversion FROM pg_extension WHERE extname = 'vector';" \
|
||||||
|
-c "SELECT '[1,2,3]'::vector <-> '[3,2,1]'::vector AS l2_distance;"
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Boot persistence (rootless podman)
|
||||||
|
|
||||||
|
`--restart=always` keeps the container alive across podman daemon
|
||||||
|
restarts, but rootless podman containers do NOT auto-start on system
|
||||||
|
boot unless the dev user has lingering enabled:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
sudo loginctl enable-linger "$USER"
|
||||||
|
```
|
||||||
|
|
||||||
|
After that, the `podman-restart.service` user unit handles restart of
|
||||||
|
`--restart=always` containers when the user session starts at boot:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
systemctl --user enable --now podman-restart.service
|
||||||
|
```
|
||||||
|
|
||||||
|
Skip both if you prefer to start the cluster manually each session with
|
||||||
|
`podman start vestige-pg`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Day-to-day operation
|
||||||
|
|
||||||
|
```sh
|
||||||
|
# Status
|
||||||
|
podman ps --filter name=vestige-pg
|
||||||
|
|
||||||
|
# Logs (follow)
|
||||||
|
podman logs -f vestige-pg
|
||||||
|
|
||||||
|
# psql as the app role
|
||||||
|
PGPASSWORD="$(cat ~/.vestige_pg_pw)" psql -h 127.0.0.1 -U vestige -d vestige
|
||||||
|
|
||||||
|
# psql as the superuser (for grants, extensions, role admin)
|
||||||
|
podman exec -it vestige-pg psql -U postgres
|
||||||
|
|
||||||
|
# Stop / start
|
||||||
|
podman stop vestige-pg
|
||||||
|
podman start vestige-pg
|
||||||
|
|
||||||
|
# Restart in place
|
||||||
|
podman restart vestige-pg
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Password rotation
|
||||||
|
|
||||||
|
```sh
|
||||||
|
# Rotate the vestige role password
|
||||||
|
NEW_PW=$(python3 -c 'import secrets,string; a=string.ascii_letters+string.digits; print("".join(secrets.choice(a) for _ in range(32)))')
|
||||||
|
umask 077
|
||||||
|
printf '%s' "$NEW_PW" > ~/.vestige_pg_pw
|
||||||
|
chmod 600 ~/.vestige_pg_pw
|
||||||
|
podman exec -i vestige-pg psql -U postgres -v ON_ERROR_STOP=1 \
|
||||||
|
-c "ALTER ROLE vestige WITH PASSWORD '${NEW_PW}';"
|
||||||
|
unset NEW_PW
|
||||||
|
|
||||||
|
# Rotate the superuser password (less common)
|
||||||
|
NEW_SUPER=$(python3 -c 'import secrets,string; a=string.ascii_letters+string.digits; print("".join(secrets.choice(a) for _ in range(32)))')
|
||||||
|
umask 077
|
||||||
|
printf '%s' "$NEW_SUPER" > ~/.vestige_pg_superpw
|
||||||
|
chmod 600 ~/.vestige_pg_superpw
|
||||||
|
podman exec -i vestige-pg psql -U postgres -v ON_ERROR_STOP=1 \
|
||||||
|
-c "ALTER ROLE postgres WITH PASSWORD '${NEW_SUPER}';"
|
||||||
|
unset NEW_SUPER
|
||||||
|
```
|
||||||
|
|
||||||
|
Then re-export `DATABASE_URL` in any live shells.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Backup and restore (dev-grade)
|
||||||
|
|
||||||
|
`pg_dump` writes a plain-text SQL dump to host disk. For dev data this is
|
||||||
|
enough; production runbook lives in `0002i-runbook.md`.
|
||||||
|
|
||||||
|
```sh
|
||||||
|
# Dump
|
||||||
|
PGPASSWORD="$(cat ~/.vestige_pg_pw)" pg_dump -h 127.0.0.1 -U vestige -d vestige \
|
||||||
|
--format=plain --no-owner > vestige-$(date +%Y%m%d-%H%M%S).sql
|
||||||
|
|
||||||
|
# Restore (drops + recreates)
|
||||||
|
podman exec -i vestige-pg psql -U postgres -v ON_ERROR_STOP=1 \
|
||||||
|
-c 'DROP DATABASE IF EXISTS vestige;' \
|
||||||
|
-c 'CREATE DATABASE vestige OWNER vestige ENCODING UTF8 TEMPLATE template0;'
|
||||||
|
PGPASSWORD="$(cat ~/.vestige_pg_pw)" psql -h 127.0.0.1 -U vestige -d vestige < vestige-DUMP.sql
|
||||||
|
```
|
||||||
|
|
||||||
|
The named volume `vestige-pgdata` persists outside the container; the
|
||||||
|
container can be `podman rm`'d and recreated without losing data, as
|
||||||
|
long as the volume stays in place.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Teardown
|
||||||
|
|
||||||
|
Destroys the cluster and all data in it:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
podman stop vestige-pg
|
||||||
|
podman rm vestige-pg
|
||||||
|
podman volume rm vestige-pgdata
|
||||||
|
podman rmi docker.io/pgvector/pgvector:pg18
|
||||||
|
rm -f ~/.vestige_pg_pw ~/.vestige_pg_superpw
|
||||||
|
```
|
||||||
|
|
||||||
|
`enable-linger` and the user systemd unit can be undone with
|
||||||
|
`sudo loginctl disable-linger "$USER"` and
|
||||||
|
`systemctl --user disable podman-restart.service` if you turned them on.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Notes for Phase 2
|
||||||
|
|
||||||
|
- `pgvector` is preinstalled in the image; the `CREATE EXTENSION vector`
|
||||||
|
in step 7 above makes it available inside the `vestige` DB. The
|
||||||
|
extension must be loaded BEFORE `sqlx::migrate!` runs the Phase 2
|
||||||
|
migration that declares typed `Vector` columns, otherwise the
|
||||||
|
migration fails.
|
||||||
|
- Testcontainer-based Phase 2 integration tests use the same
|
||||||
|
`pgvector/pgvector:pg18` image and spin up fresh containers per run;
|
||||||
|
they are independent of this long-lived cluster. This cluster exists
|
||||||
|
for `sqlx prepare`, `cargo run -- migrate --to postgres`, and manual
|
||||||
|
poking.
|
||||||
|
- `sqlx prepare` needs `DATABASE_URL` pointed at this cluster with
|
||||||
|
`vestige` migrations already applied. Run from `crates/vestige-core/`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Out of scope for this doc
|
||||||
|
|
||||||
|
- TLS, client-cert auth, non-localhost access. Phase 3 exposes the
|
||||||
|
Vestige HTTP API over the network, not Postgres directly.
|
||||||
|
- PITR, WAL archiving, replication, PgBouncer, tuned `postgresql.conf`.
|
||||||
|
Defaults are fine for Phase 2 development.
|
||||||
|
- Native (non-container) Postgres install. The prior version of this
|
||||||
|
doc covered native Arch packaging; superseded by ADR 0002's hybrid
|
||||||
|
decision.
|
||||||
|
- Making this the canonical Vestige backend. By default Vestige still
|
||||||
|
uses SQLite; this cluster exists so the `postgres-backend` feature
|
||||||
|
can be built and tested locally.
|
||||||
751
docs/prd/001-getting-centralized-vestige.md
Normal file
751
docs/prd/001-getting-centralized-vestige.md
Normal file
|
|
@ -0,0 +1,751 @@
|
||||||
|
# RFC: Pluggable Storage Backend + Network Access for Vestige
|
||||||
|
|
||||||
|
**Status**: Draft / Discussion
|
||||||
|
**Author**: Jan
|
||||||
|
**Date**: 2026-02-26
|
||||||
|
**Vestige version**: v2.x (current main)
|
||||||
|
|
||||||
|
## Summary
|
||||||
|
|
||||||
|
Add a pluggable storage backend trait to Vestige, enabling PostgreSQL (+pgvector) as an alternative to the current SQLite+FTS5+USearch stack. Simultaneously add HTTP MCP transport with API key authentication to enable centralized/remote deployment.
|
||||||
|
|
||||||
|
This keeps the existing local-first SQLite mode fully intact while opening up a server deployment model.
|
||||||
|
|
||||||
|
## Motivation
|
||||||
|
|
||||||
|
Vestige currently runs as a local process per machine (MCP via stdio, SQLite in `~/.vestige/`). This works great for single-machine use but doesn't support:
|
||||||
|
|
||||||
|
- **Multi-machine access**: Same memory brain from laptop, desktop, and server
|
||||||
|
- **Multi-agent access**: Multiple AI clients hitting one memory store concurrently
|
||||||
|
- **Future federation**: Syncing memory between decentralized nodes (e.g., MOS/Threefold grid)
|
||||||
|
|
||||||
|
SQLite's single-writer model and lack of native network protocol make it unsuitable as a centralized server. PostgreSQL is a natural fit: built-in concurrency (MVCC), authentication, replication, and with `pgvector` + built-in FTS it collapses three separate storage layers into one.
|
||||||
|
|
||||||
|
## Design
|
||||||
|
|
||||||
|
### Storage Trait
|
||||||
|
|
||||||
|
The core abstraction. All 29 cognitive modules interact with storage exclusively through this trait (or a small family of traits).
|
||||||
|
|
||||||
|
```rust
|
||||||
|
use std::collections::HashMap;
|
||||||
|
use uuid::Uuid;
|
||||||
|
|
||||||
|
/// Core memory record, backend-agnostic
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct MemoryRecord {
|
||||||
|
pub id: Uuid,
|
||||||
|
pub domains: Vec<String>, // [] = unclassified, ["dev"], ["dev", "infra"], etc.
|
||||||
|
pub domain_scores: HashMap<String, f64>, // raw similarities: {"dev": 0.82, "infra": 0.71}
|
||||||
|
pub content: String,
|
||||||
|
pub node_type: String,
|
||||||
|
pub tags: Vec<String>,
|
||||||
|
pub embedding: Option<Vec<f32>>, // dimensionality is runtime config
|
||||||
|
pub created_at: chrono::DateTime<chrono::Utc>,
|
||||||
|
pub updated_at: chrono::DateTime<chrono::Utc>,
|
||||||
|
pub metadata: serde_json::Value,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// FSRS scheduling state, stored alongside each memory
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct SchedulingState {
|
||||||
|
pub memory_id: Uuid,
|
||||||
|
pub stability: f64,
|
||||||
|
pub difficulty: f64,
|
||||||
|
pub retrievability: f64,
|
||||||
|
pub last_review: Option<chrono::DateTime<chrono::Utc>>,
|
||||||
|
pub next_review: Option<chrono::DateTime<chrono::Utc>>,
|
||||||
|
pub reps: u32,
|
||||||
|
pub lapses: u32,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Hybrid search request
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct SearchQuery {
|
||||||
|
pub domains: Option<Vec<String>>, // None = search all domains
|
||||||
|
pub text: Option<String>, // FTS query
|
||||||
|
pub embedding: Option<Vec<f32>>, // vector similarity
|
||||||
|
pub tags: Option<Vec<String>>, // tag filter
|
||||||
|
pub node_types: Option<Vec<String>>,
|
||||||
|
pub limit: usize,
|
||||||
|
pub min_retrievability: Option<f64>, // filter by FSRS state
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct SearchResult {
|
||||||
|
pub record: MemoryRecord,
|
||||||
|
pub score: f64, // combined/fused score
|
||||||
|
pub fts_score: Option<f64>,
|
||||||
|
pub vector_score: Option<f64>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Connection/edge between memories (for spreading activation)
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct MemoryEdge {
|
||||||
|
pub source_id: Uuid,
|
||||||
|
pub target_id: Uuid,
|
||||||
|
pub edge_type: String,
|
||||||
|
pub weight: f64,
|
||||||
|
pub created_at: chrono::DateTime<chrono::Utc>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Main storage trait — one impl per backend
|
||||||
|
/// trait_variant generates a Send-bound `MemoryStore` alias,
|
||||||
|
/// enabling Arc<dyn MemoryStore> without manual boxing.
|
||||||
|
#[trait_variant::make(MemoryStore: Send)]
|
||||||
|
pub trait LocalMemoryStore: Sync + 'static {
|
||||||
|
// --- Lifecycle ---
|
||||||
|
async fn init(&self) -> Result<()>;
|
||||||
|
async fn health_check(&self) -> Result<HealthStatus>;
|
||||||
|
|
||||||
|
// --- CRUD ---
|
||||||
|
async fn insert(&self, record: &MemoryRecord) -> Result<Uuid>;
|
||||||
|
async fn get(&self, id: Uuid) -> Result<Option<MemoryRecord>>;
|
||||||
|
async fn update(&self, record: &MemoryRecord) -> Result<()>;
|
||||||
|
async fn delete(&self, id: Uuid) -> Result<()>;
|
||||||
|
|
||||||
|
// --- Search ---
|
||||||
|
async fn search(&self, query: &SearchQuery) -> Result<Vec<SearchResult>>;
|
||||||
|
async fn fts_search(&self, text: &str, limit: usize) -> Result<Vec<SearchResult>>;
|
||||||
|
async fn vector_search(&self, embedding: &[f32], limit: usize) -> Result<Vec<SearchResult>>;
|
||||||
|
|
||||||
|
// --- FSRS Scheduling ---
|
||||||
|
async fn get_scheduling(&self, memory_id: Uuid) -> Result<Option<SchedulingState>>;
|
||||||
|
async fn update_scheduling(&self, state: &SchedulingState) -> Result<()>;
|
||||||
|
async fn get_due_memories(&self, before: chrono::DateTime<chrono::Utc>, limit: usize) -> Result<Vec<(MemoryRecord, SchedulingState)>>;
|
||||||
|
|
||||||
|
// --- Graph (spreading activation) ---
|
||||||
|
async fn add_edge(&self, edge: &MemoryEdge) -> Result<()>;
|
||||||
|
async fn get_edges(&self, node_id: Uuid, edge_type: Option<&str>) -> Result<Vec<MemoryEdge>>;
|
||||||
|
async fn remove_edge(&self, source: Uuid, target: Uuid) -> Result<()>;
|
||||||
|
async fn get_neighbors(&self, node_id: Uuid, depth: usize) -> Result<Vec<(MemoryRecord, f64)>>;
|
||||||
|
|
||||||
|
// --- Bulk / Maintenance ---
|
||||||
|
async fn count(&self) -> Result<usize>;
|
||||||
|
async fn get_stats(&self) -> Result<StoreStats>;
|
||||||
|
async fn vacuum(&self) -> Result<()>;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Design notes:**
|
||||||
|
|
||||||
|
- `trait_variant::make` generates a `MemoryStore` trait alias with `Send`-bound futures, allowing `Arc<dyn MemoryStore>` for runtime backend selection. `LocalMemoryStore` is the base (usable in single-threaded contexts), `MemoryStore` is the Send variant for Axum/tokio.
|
||||||
|
- `embedding: Option<Vec<f32>>` — dimensions determined at runtime by the configured fastembed model. The backend stores whatever it gets.
|
||||||
|
- The trait is intentionally flat. The cognitive modules (FSRS-6, spreading activation, synaptic tagging, prediction error gating, etc.) sit *above* this trait and don't need to know about the backend.
|
||||||
|
- `search()` does hybrid RRF fusion at the backend level — both SQLite and Postgres implementations handle this internally.
|
||||||
|
|
||||||
|
### Backend: SQLite (existing, refactored)
|
||||||
|
|
||||||
|
Wraps the current implementation behind the trait:
|
||||||
|
|
||||||
|
```
|
||||||
|
SqliteMemoryStore
|
||||||
|
├── rusqlite connection pool (r2d2 or deadpool)
|
||||||
|
├── FTS5 virtual table (keyword search)
|
||||||
|
├── USearch HNSW index (vector search, behind RwLock)
|
||||||
|
└── WAL mode + busy timeout for concurrent readers
|
||||||
|
```
|
||||||
|
|
||||||
|
No behavioral changes — just the trait boundary.
|
||||||
|
|
||||||
|
### Backend: PostgreSQL (new)
|
||||||
|
|
||||||
|
```
|
||||||
|
PgMemoryStore
|
||||||
|
├── sqlx::PgPool (connection pool, compile-time checked queries)
|
||||||
|
├── tsvector + GIN index (keyword search)
|
||||||
|
├── pgvector + HNSW index (vector search)
|
||||||
|
└── Standard PostgreSQL MVCC concurrency
|
||||||
|
```
|
||||||
|
|
||||||
|
**Schema sketch:**
|
||||||
|
|
||||||
|
```sql
|
||||||
|
CREATE EXTENSION IF NOT EXISTS vector;
|
||||||
|
|
||||||
|
-- Domain registry — populated by clustering, not by user
|
||||||
|
CREATE TABLE domains (
|
||||||
|
id TEXT PRIMARY KEY, -- auto-generated or user-named
|
||||||
|
label TEXT NOT NULL, -- human label (suggested or user-provided)
|
||||||
|
centroid vector, -- mean embedding of domain members
|
||||||
|
top_terms TEXT[] NOT NULL DEFAULT '{}', -- top keywords for display
|
||||||
|
memory_count INTEGER NOT NULL DEFAULT 0,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||||
|
metadata JSONB NOT NULL DEFAULT '{}'
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE memories (
|
||||||
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
domains TEXT[] NOT NULL DEFAULT '{}', -- [] = unclassified
|
||||||
|
domain_scores JSONB NOT NULL DEFAULT '{}', -- {"dev": 0.82, "infra": 0.71} raw similarities
|
||||||
|
content TEXT NOT NULL,
|
||||||
|
node_type TEXT NOT NULL DEFAULT 'general',
|
||||||
|
tags TEXT[] NOT NULL DEFAULT '{}',
|
||||||
|
embedding vector, -- dimension set at table creation or unconstrained
|
||||||
|
metadata JSONB NOT NULL DEFAULT '{}',
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||||
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||||
|
|
||||||
|
-- FTS: auto-maintained tsvector column
|
||||||
|
search_vec TSVECTOR GENERATED ALWAYS AS (
|
||||||
|
setweight(to_tsvector('english', content), 'A') ||
|
||||||
|
setweight(to_tsvector('english', coalesce(node_type, '')), 'B') ||
|
||||||
|
setweight(array_to_tsvector(tags), 'C')
|
||||||
|
) STORED
|
||||||
|
);
|
||||||
|
|
||||||
|
-- FTS index
|
||||||
|
CREATE INDEX idx_memories_fts ON memories USING GIN (search_vec);
|
||||||
|
|
||||||
|
-- Vector similarity (HNSW)
|
||||||
|
CREATE INDEX idx_memories_embedding ON memories
|
||||||
|
USING hnsw (embedding vector_cosine_ops)
|
||||||
|
WITH (m = 16, ef_construction = 64);
|
||||||
|
|
||||||
|
-- Common filters
|
||||||
|
CREATE INDEX idx_memories_domains ON memories USING GIN (domains);
|
||||||
|
CREATE INDEX idx_memories_node_type ON memories (node_type);
|
||||||
|
CREATE INDEX idx_memories_tags ON memories USING GIN (tags);
|
||||||
|
CREATE INDEX idx_memories_created ON memories (created_at);
|
||||||
|
|
||||||
|
-- FSRS scheduling state
|
||||||
|
CREATE TABLE scheduling (
|
||||||
|
memory_id UUID PRIMARY KEY REFERENCES memories(id) ON DELETE CASCADE,
|
||||||
|
stability DOUBLE PRECISION NOT NULL DEFAULT 0.0,
|
||||||
|
difficulty DOUBLE PRECISION NOT NULL DEFAULT 0.0,
|
||||||
|
retrievability DOUBLE PRECISION NOT NULL DEFAULT 1.0,
|
||||||
|
last_review TIMESTAMPTZ,
|
||||||
|
next_review TIMESTAMPTZ,
|
||||||
|
reps INTEGER NOT NULL DEFAULT 0,
|
||||||
|
lapses INTEGER NOT NULL DEFAULT 0
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX idx_scheduling_next ON scheduling (next_review);
|
||||||
|
|
||||||
|
-- Graph edges (spreading activation)
|
||||||
|
-- Edges can cross domain boundaries — spreading activation respects
|
||||||
|
-- domain filters when provided, traverses freely when searching all domains.
|
||||||
|
CREATE TABLE edges (
|
||||||
|
source_id UUID NOT NULL REFERENCES memories(id) ON DELETE CASCADE,
|
||||||
|
target_id UUID NOT NULL REFERENCES memories(id) ON DELETE CASCADE,
|
||||||
|
edge_type TEXT NOT NULL DEFAULT 'related',
|
||||||
|
weight DOUBLE PRECISION NOT NULL DEFAULT 1.0,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||||
|
PRIMARY KEY (source_id, target_id, edge_type)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX idx_edges_target ON edges (target_id);
|
||||||
|
|
||||||
|
-- API keys
|
||||||
|
CREATE TABLE api_keys (
|
||||||
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
key_hash TEXT NOT NULL UNIQUE, -- blake3
|
||||||
|
label TEXT NOT NULL,
|
||||||
|
scopes TEXT[] NOT NULL DEFAULT '{read,write}',
|
||||||
|
domain_filter TEXT[] NOT NULL DEFAULT '{}', -- {} = access all domains
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||||
|
last_used TIMESTAMPTZ,
|
||||||
|
active BOOLEAN NOT NULL DEFAULT true
|
||||||
|
);
|
||||||
|
```
|
||||||
|
|
||||||
|
**Hybrid search in SQL:**
|
||||||
|
|
||||||
|
```sql
|
||||||
|
-- RRF (Reciprocal Rank Fusion) combining FTS + vector
|
||||||
|
-- $1 = query text, $2 = embedding, $3 = limit, $4 = domain filter (NULL for all)
|
||||||
|
WITH fts AS (
|
||||||
|
SELECT id, ts_rank_cd(search_vec, websearch_to_tsquery('english', $1)) AS score,
|
||||||
|
ROW_NUMBER() OVER (ORDER BY ts_rank_cd(search_vec, websearch_to_tsquery('english', $1)) DESC) AS rank
|
||||||
|
FROM memories
|
||||||
|
WHERE search_vec @@ websearch_to_tsquery('english', $1)
|
||||||
|
AND ($4::text[] IS NULL OR domains && $4) -- array overlap: any match
|
||||||
|
LIMIT 50
|
||||||
|
),
|
||||||
|
vec AS (
|
||||||
|
SELECT id, 1 - (embedding <=> $2::vector) AS score,
|
||||||
|
ROW_NUMBER() OVER (ORDER BY embedding <=> $2::vector) AS rank
|
||||||
|
FROM memories
|
||||||
|
WHERE embedding IS NOT NULL
|
||||||
|
AND ($4::text[] IS NULL OR domains && $4)
|
||||||
|
LIMIT 50
|
||||||
|
)
|
||||||
|
SELECT COALESCE(f.id, v.id) AS id,
|
||||||
|
COALESCE(1.0 / (60 + f.rank), 0) + COALESCE(1.0 / (60 + v.rank), 0) AS rrf_score,
|
||||||
|
f.score AS fts_score,
|
||||||
|
v.score AS vector_score
|
||||||
|
FROM fts f FULL OUTER JOIN vec v ON f.id = v.id
|
||||||
|
ORDER BY rrf_score DESC
|
||||||
|
LIMIT $3;
|
||||||
|
```
|
||||||
|
|
||||||
|
### Embedding Configuration
|
||||||
|
|
||||||
|
The embedding layer stays external to the storage backend. fastembed runs locally and produces vectors that get passed into `MemoryRecord.embedding`.
|
||||||
|
|
||||||
|
```toml
|
||||||
|
# vestige.toml
|
||||||
|
[embeddings]
|
||||||
|
provider = "fastembed" # only local for now
|
||||||
|
model = "BAAI/bge-base-en-v1.5" # 768 dimensions
|
||||||
|
# model = "BAAI/bge-large-en-v1.5" # 1024 dimensions
|
||||||
|
# model = "BAAI/bge-small-en-v1.5" # 384 dimensions
|
||||||
|
|
||||||
|
[storage]
|
||||||
|
backend = "postgres" # or "sqlite"
|
||||||
|
|
||||||
|
[storage.sqlite]
|
||||||
|
path = "~/.vestige/vestige.db"
|
||||||
|
|
||||||
|
[storage.postgres]
|
||||||
|
url = "postgresql://vestige:secret@localhost:5432/vestige"
|
||||||
|
max_connections = 10
|
||||||
|
```
|
||||||
|
|
||||||
|
On init, the backend reads the embedding dimension from the first stored vector (or from config) and validates consistency.
|
||||||
|
|
||||||
|
For pgvector: you can either create the column as `vector(768)` (fixed, faster) or unconstrained `vector` (flexible, slightly slower). Recommendation: fixed dimension derived from config, with a migration path if the model changes.
|
||||||
|
|
||||||
|
### Emergent Domain Model
|
||||||
|
|
||||||
|
Instead of user-defined tenants, domains emerge automatically from the data via clustering. The user never has to decide where a memory belongs — the system figures it out.
|
||||||
|
|
||||||
|
#### Pipeline
|
||||||
|
|
||||||
|
```
|
||||||
|
Phase 1: Accumulate (cold start, 0 → N memories)
|
||||||
|
│ All memories stored with domains = [] (unclassified)
|
||||||
|
│ No classification overhead, just embed and store
|
||||||
|
│ Threshold N is configurable, default ~150 memories
|
||||||
|
│
|
||||||
|
Phase 2: Discover (triggered once at threshold, or manually)
|
||||||
|
│ Run HDBSCAN on all embeddings:
|
||||||
|
│ - min_cluster_size: ~10
|
||||||
|
│ - min_samples: ~5
|
||||||
|
│ - No eps parameter needed (unlike DBSCAN)
|
||||||
|
│ - Automatically determines number of clusters
|
||||||
|
│ - Handles variable-density clusters
|
||||||
|
│ - Border points between clusters flagged naturally
|
||||||
|
│
|
||||||
|
│ For each cluster, extract:
|
||||||
|
│ - Centroid (mean embedding)
|
||||||
|
│ - Top terms (TF-IDF or frequency over cluster members)
|
||||||
|
│ - Suggested label from top terms
|
||||||
|
│
|
||||||
|
│ Present to user (via dashboard or CLI):
|
||||||
|
│ "I found 3 natural groupings in your memories:
|
||||||
|
│ ● cluster_0 (47 memories): BGP, SONiC, VLAN, FRR, peering...
|
||||||
|
│ ● cluster_1 (31 memories): solar, kWh, battery, pool, ESPHome...
|
||||||
|
│ ● cluster_2 (22 memories): Rust, trait, async, zinit, tokio..."
|
||||||
|
│
|
||||||
|
│ User can:
|
||||||
|
│ - Name them: cluster_0 → "infra", cluster_1 → "home", cluster_2 → "dev"
|
||||||
|
│ - Accept suggested names
|
||||||
|
│ - Merge clusters
|
||||||
|
│ - Do nothing (auto-names stick)
|
||||||
|
│
|
||||||
|
Phase 3: Soft-assign all existing memories
|
||||||
|
│ Now that centroids exist, re-score every memory (including
|
||||||
|
│ those from discovery) against all centroids.
|
||||||
|
│ This replaces HDBSCAN's hard labels with continuous scores:
|
||||||
|
│
|
||||||
|
│ For each memory:
|
||||||
|
│ similarities = [(domain, cosine_sim(embedding, centroid)) for each domain]
|
||||||
|
│ domains = [id for (id, score) in similarities if score >= threshold]
|
||||||
|
│
|
||||||
|
│ Memories in overlap zones get multiple domains.
|
||||||
|
│ Memories far from all centroids stay unclassified.
|
||||||
|
│
|
||||||
|
Phase 4: Classify (ongoing, after discovery)
|
||||||
|
│ New memory ingested:
|
||||||
|
│ 1. Compute embedding
|
||||||
|
│ 2. Compute similarity to ALL domain centroids
|
||||||
|
│ 3. Store raw scores in domain_scores JSONB
|
||||||
|
│ 4. Threshold into domains[] array
|
||||||
|
│ 5. Update domain centroids incrementally (running mean)
|
||||||
|
│
|
||||||
|
│ Context signals as soft priors:
|
||||||
|
│ - Git repo / IDE metadata → boost similarity to code-related domains
|
||||||
|
│ - No workspace context → slight boost toward non-technical domains
|
||||||
|
│ - These shift the score, never override the embedding distance
|
||||||
|
│
|
||||||
|
Phase 5: Re-cluster (periodic, during dream consolidation)
|
||||||
|
Re-run HDBSCAN on all embeddings including new ones
|
||||||
|
Detect:
|
||||||
|
- New clusters forming from previously unclassified memories
|
||||||
|
- Existing clusters splitting (domain grew too broad)
|
||||||
|
- Clusters merging (domains that were artificially separate)
|
||||||
|
Propose changes to user:
|
||||||
|
"Your 'dev' domain may have split into two groups:
|
||||||
|
- systems (zinit, MOS, containers, VMs) — 34 memories
|
||||||
|
- networking (BGP, SONiC, VLANs, MLAG) — 28 memories
|
||||||
|
Split them? [yes / no / later]"
|
||||||
|
Re-run soft assignment on all memories after structural changes
|
||||||
|
Centroid vectors are updated regardless
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Domain Storage
|
||||||
|
|
||||||
|
```rust
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct Domain {
|
||||||
|
pub id: String,
|
||||||
|
pub label: String,
|
||||||
|
pub centroid: Vec<f32>,
|
||||||
|
pub top_terms: Vec<String>,
|
||||||
|
pub memory_count: usize,
|
||||||
|
pub created_at: chrono::DateTime<chrono::Utc>,
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Added to the `MemoryStore` trait:
|
||||||
|
|
||||||
|
```rust
|
||||||
|
// --- Domains ---
|
||||||
|
async fn list_domains(&self) -> Result<Vec<Domain>>;
|
||||||
|
async fn get_domain(&self, id: &str) -> Result<Option<Domain>>;
|
||||||
|
async fn upsert_domain(&self, domain: &Domain) -> Result<()>;
|
||||||
|
async fn delete_domain(&self, id: &str) -> Result<()>;
|
||||||
|
async fn classify(&self, embedding: &[f32]) -> Result<Vec<(String, f64)>>;
|
||||||
|
// Returns [(domain_id, similarity)] sorted by similarity desc.
|
||||||
|
// Caller decides threshold for assignment.
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Classification Module
|
||||||
|
|
||||||
|
A new cognitive module alongside FSRS, spreading activation, etc.:
|
||||||
|
|
||||||
|
```rust
|
||||||
|
pub struct DomainClassifier {
|
||||||
|
/// Similarity threshold — domains scoring above this are assigned
|
||||||
|
pub assign_threshold: f64, // default: 0.65
|
||||||
|
/// Minimum memories before running initial discovery
|
||||||
|
pub discovery_threshold: usize, // default: 150
|
||||||
|
/// How often to re-cluster (in dream consolidation passes)
|
||||||
|
pub recluster_interval: usize, // default: every 5th consolidation
|
||||||
|
/// HDBSCAN min_cluster_size
|
||||||
|
pub min_cluster_size: usize, // default: 10
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Raw classification result — all scores, before thresholding
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct ClassificationResult {
|
||||||
|
/// Similarity to every known domain centroid
|
||||||
|
pub scores: HashMap<String, f64>, // {"dev": 0.82, "infra": 0.71, "home": 0.34}
|
||||||
|
/// Domains above assign_threshold
|
||||||
|
pub domains: Vec<String>, // ["dev", "infra"]
|
||||||
|
}
|
||||||
|
|
||||||
|
impl DomainClassifier {
|
||||||
|
/// Score a memory against all domain centroids.
|
||||||
|
/// Returns raw scores AND thresholded domain list.
|
||||||
|
pub fn classify(
|
||||||
|
&self,
|
||||||
|
embedding: &[f32],
|
||||||
|
domains: &[Domain],
|
||||||
|
) -> ClassificationResult {
|
||||||
|
if domains.is_empty() {
|
||||||
|
return ClassificationResult {
|
||||||
|
scores: HashMap::new(),
|
||||||
|
domains: vec![], // still in accumulation phase
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
let scores: HashMap<String, f64> = domains.iter()
|
||||||
|
.map(|d| (d.id.clone(), cosine_similarity(embedding, &d.centroid)))
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
let assigned: Vec<String> = scores.iter()
|
||||||
|
.filter(|(_, &s)| s >= self.assign_threshold)
|
||||||
|
.map(|(id, _)| id.clone())
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
ClassificationResult { scores, domains: assigned }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Soft-assign all existing memories after discovery or re-clustering.
|
||||||
|
/// Returns number of memories whose domains changed.
|
||||||
|
pub async fn reassign_all(
|
||||||
|
&self,
|
||||||
|
store: &dyn MemoryStore,
|
||||||
|
domains: &[Domain],
|
||||||
|
) -> Result<usize> {
|
||||||
|
// Load all memories, re-score, update domains + domain_scores
|
||||||
|
// Batched to avoid loading everything into memory at once
|
||||||
|
todo!()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Key distinction from the previous design:** there's no "closest wins" or "margin" logic. Every domain gets a score, and *all* domains above threshold are assigned. A memory about "deploying zinit containers via BGP-routed network" might score 0.78 on "dev" and 0.72 on "infra" — it gets both. A memory about "solar panel output today" scores 0.85 on "home" and 0.31 on everything else — it only gets "home".
|
||||||
|
|
||||||
|
The raw `domain_scores` are always stored, so you (or the dashboard) can see *why* a memory was classified the way it was, and the threshold can be adjusted retroactively without re-computing embeddings.
|
||||||
|
|
||||||
|
#### Search Behavior
|
||||||
|
|
||||||
|
- **Default (no domain filter)**: searches all memories across all domains
|
||||||
|
- **Domain-scoped**: `domains: Some(vec!["dev"])` — only memories tagged with `dev`
|
||||||
|
- **Multi-domain**: `domains: Some(vec!["dev", "infra"])` — memories in either
|
||||||
|
- **MCP clients can set `X-Vestige-Domain` header** for default scoping, but the system works fine without it
|
||||||
|
|
||||||
|
#### HDBSCAN Implementation
|
||||||
|
|
||||||
|
HDBSCAN (Hierarchical DBSCAN) over the embedding vectors. Advantages over plain DBSCAN:
|
||||||
|
|
||||||
|
- **No `eps` parameter** — the hardest thing to tune in DBSCAN. HDBSCAN determines density thresholds from the data hierarchy.
|
||||||
|
- **Variable-density clusters** — a tight cluster of networking memories and a spread-out cluster of personal memories are both detected correctly.
|
||||||
|
- **Border points** — memories between clusters are identified as low-confidence members, which aligns perfectly with soft assignment.
|
||||||
|
|
||||||
|
Implementation: the `hdbscan` crate in Rust. Load all embeddings into memory (at 768d × f32 × 10k memories ≈ 30MB — fine), cluster, compute centroids, soft-assign all memories against the centroids.
|
||||||
|
|
||||||
|
```rust
|
||||||
|
use hdbscan::{Center, Hdbscan};
|
||||||
|
|
||||||
|
fn discover_domains(
|
||||||
|
embeddings: &[Vec<f32>],
|
||||||
|
min_cluster_size: usize,
|
||||||
|
) -> (Vec<Vec<usize>>, Vec<Vec<f32>>) { // (cluster → member indices, centroids)
|
||||||
|
let clusterer = Hdbscan::default(embeddings);
|
||||||
|
let labels = clusterer.cluster().unwrap();
|
||||||
|
let centroids = clusterer.calc_centers(Center::Centroid, &labels).unwrap();
|
||||||
|
|
||||||
|
// Group indices by label, ignoring noise (-1)
|
||||||
|
let mut clusters: HashMap<i32, Vec<usize>> = HashMap::new();
|
||||||
|
for (i, &label) in labels.iter().enumerate() {
|
||||||
|
if label >= 0 {
|
||||||
|
clusters.entry(label).or_default().push(i);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
(clusters.into_values().collect(), centroids)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
After HDBSCAN produces hard clusters, the soft-assignment pass (Phase 3) immediately re-scores all memories — including the ones HDBSCAN assigned — against the computed centroids. So HDBSCAN's hard labels are only used to *define* the centroids. The actual domain assignments always come from the continuous similarity scores.
|
||||||
|
|
||||||
|
This works identically for both SQLite and Postgres backends — clustering runs in Rust application code, results are written back to the storage layer.
|
||||||
|
|
||||||
|
### Network Transport
|
||||||
|
|
||||||
|
#### MCP over Streamable HTTP
|
||||||
|
|
||||||
|
Extend the existing Axum server:
|
||||||
|
|
||||||
|
```rust
|
||||||
|
// Alongside existing dashboard routes
|
||||||
|
let app = Router::new()
|
||||||
|
// Existing dashboard
|
||||||
|
.route("/api/health", get(health_handler))
|
||||||
|
.route("/dashboard/*path", get(dashboard_handler))
|
||||||
|
// New: MCP over HTTP
|
||||||
|
.route("/mcp", post(mcp_handler).get(mcp_sse_handler))
|
||||||
|
// New: REST API
|
||||||
|
// X-Vestige-Domain header optionally scopes to a domain
|
||||||
|
.route("/api/v1/memories", post(create_memory).get(list_memories))
|
||||||
|
.route("/api/v1/memories/:id", get(get_memory).put(update_memory).delete(delete_memory))
|
||||||
|
.route("/api/v1/search", post(search_memories))
|
||||||
|
.route("/api/v1/consolidate", post(trigger_consolidation))
|
||||||
|
.route("/api/v1/stats", get(get_stats))
|
||||||
|
.route("/api/v1/domains", get(list_domains))
|
||||||
|
.route("/api/v1/domains/discover", post(trigger_discovery))
|
||||||
|
.route("/api/v1/domains/:id", put(rename_domain).delete(merge_domain))
|
||||||
|
// Auth on everything except health
|
||||||
|
.layer(middleware::from_fn(api_key_auth));
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Auth Middleware
|
||||||
|
|
||||||
|
```rust
|
||||||
|
async fn api_key_auth(
|
||||||
|
State(store): State<Arc<dyn MemoryStore>>,
|
||||||
|
request: axum::extract::Request,
|
||||||
|
next: middleware::Next,
|
||||||
|
) -> Result<Response, StatusCode> {
|
||||||
|
// Skip auth for health endpoint
|
||||||
|
if request.uri().path() == "/api/health" {
|
||||||
|
return Ok(next.run(request).await);
|
||||||
|
}
|
||||||
|
|
||||||
|
let key = request.headers()
|
||||||
|
.get("Authorization")
|
||||||
|
.and_then(|v| v.to_str().ok())
|
||||||
|
.and_then(|v| v.strip_prefix("Bearer "))
|
||||||
|
.or_else(|| request.headers()
|
||||||
|
.get("X-API-Key")
|
||||||
|
.and_then(|v| v.to_str().ok()));
|
||||||
|
|
||||||
|
match key {
|
||||||
|
Some(k) if verify_api_key(store.as_ref(), k).await => {
|
||||||
|
Ok(next.run(request).await)
|
||||||
|
}
|
||||||
|
_ => Err(StatusCode::UNAUTHORIZED),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Client Configuration
|
||||||
|
|
||||||
|
```json
|
||||||
|
// Claude Desktop / Claude Code — single key, all domains
|
||||||
|
{
|
||||||
|
"mcpServers": {
|
||||||
|
"vestige": {
|
||||||
|
"url": "http://vestige.local:3927/mcp",
|
||||||
|
"headers": {
|
||||||
|
"Authorization": "Bearer vst_a1b2c3..."
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
No domain header needed — searches all domains by default. The MCP tools include an optional `domain` parameter for scoped queries if the LLM or user wants to narrow down.
|
||||||
|
|
||||||
|
Alternatively, scope a connection to a specific domain:
|
||||||
|
|
||||||
|
```json
|
||||||
|
// Domain-scoped connection (e.g., for a home automation agent)
|
||||||
|
{
|
||||||
|
"mcpServers": {
|
||||||
|
"vestige-home": {
|
||||||
|
"url": "http://vestige.local:3927/mcp",
|
||||||
|
"headers": {
|
||||||
|
"Authorization": "Bearer vst_e5f6g7...",
|
||||||
|
"X-Vestige-Domain": "home"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Server Configuration
|
||||||
|
|
||||||
|
```toml
|
||||||
|
# vestige.toml — full example for server mode
|
||||||
|
[server]
|
||||||
|
bind = "0.0.0.0:3927" # or mycelium IPv6 address
|
||||||
|
# tls_cert = "/path/to/cert.pem" # optional
|
||||||
|
# tls_key = "/path/to/key.pem"
|
||||||
|
|
||||||
|
[auth]
|
||||||
|
enabled = true
|
||||||
|
# If false, no key required (local-only mode)
|
||||||
|
|
||||||
|
[storage]
|
||||||
|
backend = "postgres"
|
||||||
|
|
||||||
|
[storage.postgres]
|
||||||
|
url = "postgresql://vestige:secret@localhost:5432/vestige"
|
||||||
|
max_connections = 10
|
||||||
|
|
||||||
|
[embeddings]
|
||||||
|
provider = "fastembed"
|
||||||
|
model = "BAAI/bge-base-en-v1.5"
|
||||||
|
```
|
||||||
|
|
||||||
|
### CLI Extensions
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Domain management (mostly automatic, but user can inspect/rename)
|
||||||
|
vestige domains list
|
||||||
|
# → dev Development (auto) memories: 87 top: Rust, trait, async, tokio
|
||||||
|
# → infra Infrastructure (auto) memories: 47 top: BGP, SONiC, VLAN, FRR
|
||||||
|
# → home Home (auto) memories: 31 top: solar, kWh, pool, ESPHome
|
||||||
|
# → (unclassified) memories: 12
|
||||||
|
|
||||||
|
vestige domains rename cluster_0 infra --label "Infrastructure"
|
||||||
|
vestige domains merge home personal --into home
|
||||||
|
vestige domains discover --force # re-run HDBSCAN now
|
||||||
|
|
||||||
|
# Key management
|
||||||
|
vestige keys create --label "macbook"
|
||||||
|
# → Created key: vst_a1b2c3d4... (store this, shown once)
|
||||||
|
|
||||||
|
vestige keys create --label "home-assistant" --scopes read --domains home
|
||||||
|
# → Created key: vst_e5f6g7h8... (read-only, home domain only)
|
||||||
|
|
||||||
|
vestige keys list
|
||||||
|
# → macbook vst_a1b2... scopes: [read,write] domains: [all]
|
||||||
|
# → home-assistant vst_e5f6... scopes: [read] domains: [home]
|
||||||
|
|
||||||
|
vestige keys revoke vst_a1b2c3d4...
|
||||||
|
|
||||||
|
# Migration
|
||||||
|
vestige migrate --from sqlite --to postgres \
|
||||||
|
--sqlite-path ~/.vestige/vestige.db \
|
||||||
|
--postgres-url postgresql://localhost/vestige
|
||||||
|
```
|
||||||
|
|
||||||
|
## Implementation Plan
|
||||||
|
|
||||||
|
### Phase 1: Storage Trait Extraction
|
||||||
|
- Define the `MemoryStore` trait (including domain methods)
|
||||||
|
- Refactor current SQLite code to implement it
|
||||||
|
- Add `domains TEXT[]` column to existing SQLite schema
|
||||||
|
- Verify all 29 modules work through the trait (no direct SQLite access)
|
||||||
|
- **No behavioral changes** — all memories start as unclassified
|
||||||
|
|
||||||
|
### Phase 2: PostgreSQL Backend
|
||||||
|
- Implement `PgMemoryStore`
|
||||||
|
- Schema migrations (sqlx or refinery)
|
||||||
|
- `vestige migrate` command for SQLite → Postgres
|
||||||
|
- Config file support for backend selection
|
||||||
|
|
||||||
|
### Phase 3: Network Access
|
||||||
|
- MCP Streamable HTTP endpoint on existing Axum server
|
||||||
|
- API key auth middleware + CLI management
|
||||||
|
- REST API endpoints
|
||||||
|
- Feature flags for stdio vs HTTP mode
|
||||||
|
|
||||||
|
### Phase 4: Emergent Domain Classification
|
||||||
|
- `DomainClassifier` cognitive module
|
||||||
|
- HDBSCAN clustering via `hdbscan` crate (runs on both backends)
|
||||||
|
- Soft assignment pass: score all memories against centroids, threshold into domains
|
||||||
|
- `domain_scores` JSONB stored per memory for transparency / retroactive re-thresholding
|
||||||
|
- Domain discovery CLI and dashboard UI
|
||||||
|
- Auto-classification on ingest (once domains exist)
|
||||||
|
- Re-clustering during dream consolidation passes
|
||||||
|
- Domain management CLI (rename, merge, inspect)
|
||||||
|
|
||||||
|
### Phase 5: Federation (future)
|
||||||
|
- Node discovery via Mycelium / mDNS
|
||||||
|
- Memory sync protocol (UUID-based, last-write-wins)
|
||||||
|
- Possibly Iroh for content-addressed replication
|
||||||
|
- FSRS state merge (review history append, not overwrite)
|
||||||
|
|
||||||
|
## Crate Dependencies (new)
|
||||||
|
|
||||||
|
```toml
|
||||||
|
# Phase 1 — trait abstraction
|
||||||
|
trait-variant = "0.1"
|
||||||
|
|
||||||
|
# Phase 2 — Postgres
|
||||||
|
sqlx = { version = "0.8", features = ["runtime-tokio", "postgres", "uuid", "chrono", "json"] }
|
||||||
|
pgvector = "0.4" # sqlx integration for vector type
|
||||||
|
|
||||||
|
# Phase 3 — Auth
|
||||||
|
blake3 = "1" # key hashing
|
||||||
|
rand = "0.8" # key generation
|
||||||
|
|
||||||
|
# Phase 4 — Domain clustering
|
||||||
|
hdbscan = "0.10" # HDBSCAN — no eps tuning, variable density, built-in centroid calc
|
||||||
|
```
|
||||||
|
|
||||||
|
## Open Questions
|
||||||
|
|
||||||
|
1. **Trait granularity**: One big `MemoryStore` trait or split into `MemoryStore + SchedulingStore + GraphStore + DomainStore`? Splitting is cleaner but means more `dyn` parameters threading through handlers.
|
||||||
|
|
||||||
|
2. **Embedding on insert**: Should the storage backend call fastembed, or should the caller always provide the embedding? Current design says caller provides it, keeping the backend pure storage. But this means every client needs fastembed locally even if the DB is remote. For the server model, having the server compute embeddings makes more sense.
|
||||||
|
|
||||||
|
3. **pgvector dimension**: Fixed (e.g., `vector(768)`) or unconstrained (`vector`)? Fixed is faster for HNSW but requires migration if model changes.
|
||||||
|
|
||||||
|
4. **Sync conflict resolution for federation**: LWW per-UUID is simple but lossy. CRDTs would be more correct but massively more complex. For FSRS state specifically, merging review event logs would be ideal.
|
||||||
|
|
||||||
|
5. **Dashboard auth**: The 3D dashboard currently runs unauthenticated on localhost. With remote access, it needs the same auth. Should it use the same API keys or have a separate session/cookie mechanism?
|
||||||
|
|
||||||
|
6. **HDBSCAN `min_cluster_size`**: The main tuning knob. Too small → noisy micro-clusters. Too large → distinct topics get merged. Default of 10 should work for most cases, but may need a manual override or auto-sweep (run with several values, pick the one with best silhouette score).
|
||||||
|
|
||||||
|
7. **Domain drift**: Over time, the character of a domain changes. How aggressively should re-clustering reshape existing domains? Conservative (only propose splits/merges, never auto-apply) vs. aggressive (auto-reassign memories whose scores drifted below threshold)?
|
||||||
|
|
||||||
|
8. **Spreading activation across domains**: When searching within a single domain, should graph edges that cross into other domains be followed? Probably yes for recall quality, but with decaying weight as you cross boundaries.
|
||||||
|
|
||||||
|
9. **Threshold tuning**: The `assign_threshold` (0.65 default) determines how many memories are multi-domain vs single-domain vs unclassified. Too low → everything is multi-domain (useless). Too high → too many unclassified. Could be auto-tuned per dataset by targeting a specific unclassified ratio (e.g., "keep fewer than 10% unclassified").
|
||||||
6
glama.json
Normal file
6
glama.json
Normal file
|
|
@ -0,0 +1,6 @@
|
||||||
|
{
|
||||||
|
"$schema": "https://glama.ai/mcp/schemas/server.json",
|
||||||
|
"maintainers": [
|
||||||
|
"samvallad33"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
@ -1,6 +1,6 @@
|
||||||
{
|
{
|
||||||
"name": "vestige",
|
"name": "vestige",
|
||||||
"version": "2.1.23",
|
"version": "2.1.27",
|
||||||
"private": true,
|
"private": true,
|
||||||
"description": "Cognitive memory for AI - MCP server with FSRS-6 spaced repetition",
|
"description": "Cognitive memory for AI - MCP server with FSRS-6 spaced repetition",
|
||||||
"author": "Sam Valladares",
|
"author": "Sam Valladares",
|
||||||
|
|
|
||||||
|
|
@ -105,6 +105,21 @@ const IDE_CONFIGS = {
|
||||||
note: 'Tip: For project-level config, create .vscode/mcp.json with {"servers": {"vestige": ...}}',
|
note: 'Tip: For project-level config, create .vscode/mcp.json with {"servers": {"vestige": ...}}',
|
||||||
},
|
},
|
||||||
|
|
||||||
|
'OpenCode': {
|
||||||
|
detect: () => {
|
||||||
|
try {
|
||||||
|
execSync(PLATFORM === 'win32' ? 'where opencode' : 'which opencode', { stdio: 'ignore' });
|
||||||
|
return true;
|
||||||
|
} catch {
|
||||||
|
return fs.existsSync(path.join(HOME, '.config', 'opencode'));
|
||||||
|
}
|
||||||
|
},
|
||||||
|
configPath: () => path.join(HOME, '.config', 'opencode', 'opencode.json'),
|
||||||
|
format: 'opencode',
|
||||||
|
key: 'mcp',
|
||||||
|
note: 'Tip: For project-level memory, add the same mcp.vestige block to an opencode.json in your repo root.',
|
||||||
|
},
|
||||||
|
|
||||||
'Xcode 26.3': {
|
'Xcode 26.3': {
|
||||||
detect: () => {
|
detect: () => {
|
||||||
if (PLATFORM !== 'darwin') return false;
|
if (PLATFORM !== 'darwin') return false;
|
||||||
|
|
@ -152,7 +167,10 @@ function findBinary() {
|
||||||
// npm global install location
|
// npm global install location
|
||||||
(() => {
|
(() => {
|
||||||
try {
|
try {
|
||||||
const npmPrefix = execSync('npm prefix -g', { encoding: 'utf8' }).trim();
|
const npmPrefix = execSync('npm prefix -g', {
|
||||||
|
encoding: 'utf8',
|
||||||
|
stdio: ['ignore', 'pipe', 'ignore'],
|
||||||
|
}).trim();
|
||||||
return path.join(npmPrefix, 'bin', 'vestige-mcp');
|
return path.join(npmPrefix, 'bin', 'vestige-mcp');
|
||||||
} catch { return null; }
|
} catch { return null; }
|
||||||
})(),
|
})(),
|
||||||
|
|
@ -164,7 +182,11 @@ function findBinary() {
|
||||||
encoding: 'utf8',
|
encoding: 'utf8',
|
||||||
stdio: ['pipe', 'pipe', 'ignore'],
|
stdio: ['pipe', 'pipe', 'ignore'],
|
||||||
}).trim();
|
}).trim();
|
||||||
if (result) candidates.unshift(result);
|
const firstMatch = result
|
||||||
|
.split(/\r?\n/)
|
||||||
|
.map((line) => line.trim())
|
||||||
|
.filter(Boolean)[0];
|
||||||
|
if (firstMatch) candidates.unshift(firstMatch);
|
||||||
} catch {}
|
} catch {}
|
||||||
|
|
||||||
for (const candidate of candidates) {
|
for (const candidate of candidates) {
|
||||||
|
|
@ -272,6 +294,16 @@ function buildVestigeConfig(binaryPath) {
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function buildOpenCodeConfig(binaryPath) {
|
||||||
|
return {
|
||||||
|
type: 'local',
|
||||||
|
command: [binaryPath],
|
||||||
|
enabled: true,
|
||||||
|
timeout: 10000,
|
||||||
|
environment: {},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
function buildXcodeConfig(binaryPath) {
|
function buildXcodeConfig(binaryPath) {
|
||||||
return {
|
return {
|
||||||
projects: {
|
projects: {
|
||||||
|
|
@ -324,6 +356,28 @@ function injectConfig(ide, ideName, binaryPath) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
config.mcp.servers.vestige = buildVestigeConfig(binaryPath);
|
config.mcp.servers.vestige = buildVestigeConfig(binaryPath);
|
||||||
|
} else if (ide.format === 'opencode') {
|
||||||
|
// OpenCode uses top-level "mcp" entries with command arrays.
|
||||||
|
if (!config.$schema) config.$schema = 'https://opencode.ai/config.json';
|
||||||
|
if (!config.mcp) config.mcp = {};
|
||||||
|
let migratedOpenCodeConfig = false;
|
||||||
|
if (config.mcpServers && config.mcpServers.vestige) {
|
||||||
|
delete config.mcpServers.vestige;
|
||||||
|
migratedOpenCodeConfig = true;
|
||||||
|
if (Object.keys(config.mcpServers).length === 0) {
|
||||||
|
delete config.mcpServers;
|
||||||
|
}
|
||||||
|
console.log(` [migrate] ${ideName} — moved vestige from mcpServers to mcp`);
|
||||||
|
}
|
||||||
|
if (config.mcp.vestige) {
|
||||||
|
if (!migratedOpenCodeConfig) {
|
||||||
|
console.log(` [skip] ${ideName} — already configured`);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
// Preserve the valid OpenCode entry while still writing the stale-key cleanup.
|
||||||
|
} else {
|
||||||
|
config.mcp.vestige = buildOpenCodeConfig(binaryPath);
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
// Standard mcpServers format (Cursor, Claude Desktop, JetBrains, Windsurf)
|
// Standard mcpServers format (Cursor, Claude Desktop, JetBrains, Windsurf)
|
||||||
const key = ide.key || 'mcpServers';
|
const key = ide.key || 'mcpServers';
|
||||||
|
|
@ -383,7 +437,7 @@ function main() {
|
||||||
if (detected.length === 0) {
|
if (detected.length === 0) {
|
||||||
console.log(' No supported IDEs found.');
|
console.log(' No supported IDEs found.');
|
||||||
console.log('');
|
console.log('');
|
||||||
console.log('Supported: Claude Code, Claude Desktop, Cursor, VS Code, Xcode, JetBrains, Windsurf');
|
console.log('Supported: Claude Code, Claude Desktop, Cursor, VS Code, OpenCode, Xcode, JetBrains, Windsurf');
|
||||||
process.exit(1);
|
process.exit(1);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,6 @@
|
||||||
{
|
{
|
||||||
"name": "@vestige/init",
|
"name": "@vestige/init",
|
||||||
"version": "2.1.23",
|
"version": "2.1.27",
|
||||||
"description": "Configure Vestige local memory for MCP-compatible AI agents",
|
"description": "Configure Vestige local memory for MCP-compatible AI agents",
|
||||||
"bin": {
|
"bin": {
|
||||||
"vestige-init": "bin/init.js"
|
"vestige-init": "bin/init.js"
|
||||||
|
|
@ -13,6 +13,7 @@
|
||||||
"claude",
|
"claude",
|
||||||
"copilot",
|
"copilot",
|
||||||
"cursor",
|
"cursor",
|
||||||
|
"opencode",
|
||||||
"xcode",
|
"xcode",
|
||||||
"jetbrains",
|
"jetbrains",
|
||||||
"windsurf",
|
"windsurf",
|
||||||
|
|
|
||||||
|
|
@ -54,6 +54,40 @@ codex mcp add vestige -- vestige-mcp
|
||||||
|
|
||||||
Then restart your MCP client.
|
Then restart your MCP client.
|
||||||
|
|
||||||
|
**OpenCode**
|
||||||
|
|
||||||
|
Add to `~/.config/opencode/opencode.json` or a project-local `opencode.json`:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"$schema": "https://opencode.ai/config.json",
|
||||||
|
"mcp": {
|
||||||
|
"vestige": {
|
||||||
|
"type": "local",
|
||||||
|
"command": ["vestige-mcp"],
|
||||||
|
"enabled": true,
|
||||||
|
"timeout": 10000
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Prefer the installed `vestige-mcp` command for OpenCode. If you run Vestige directly through `npx`, use a longer first-run timeout because npm may need to download the package before OpenCode can connect:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"$schema": "https://opencode.ai/config.json",
|
||||||
|
"mcp": {
|
||||||
|
"vestige": {
|
||||||
|
"type": "local",
|
||||||
|
"command": ["npx", "-y", "-p", "vestige-mcp-server@latest", "vestige-mcp"],
|
||||||
|
"enabled": true,
|
||||||
|
"timeout": 60000
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
## Usage with Claude Desktop
|
## Usage with Claude Desktop
|
||||||
|
|
||||||
Add to your Claude Desktop configuration:
|
Add to your Claude Desktop configuration:
|
||||||
|
|
|
||||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Add a link
Reference in a new issue