Skip to content

feat: auto-wired memory edges (#346) - #375

Merged
ajianaz merged 6 commits into
developfrom
feat/auto-edges-346
Jun 17, 2026
Merged

ajianaz merged 6 commits into
developfrom
feat/auto-edges-346

Conversation

@ajianaz

@ajianaz ajianaz commented Jun 17, 2026

Copy link
Copy Markdown
Collaborator

Summary

Implements #346 (priority: high, next-up). Every remember() now auto-extracts entity references via pure string parsing (zero LLM) and writes typed edges to a new memory_edges SQLite table. get_related() rewrites from O(n) JSON scan to indexed SQL.

Schema (v7 → v8)

  • memory_edges table — source_id, target_id, edge_type, created_at with indices on source/target/type and UNIQUE(source, target, type).
  • memories.slug column (optional) — for [[slug]] Wikilink-style references. Partial index WHERE slug IS NOT NULL.
  • Migration v7→v8 backfills existing metadata.relationships JSON entries into memory_edges rows (zero data loss).

Extraction patterns

Pattern Edge type Resolved via
[[slug]] references memories.slug lookup
@tag tagged_as most recent memory with that tag
^<uuid> supersedes direct UUID
><uuid> replies_to direct UUID
rel:<type>:<uuid> in --meta <type> direct UUID (legacy compat)

Resolution is namespace-scoped. Self-edges skipped. Dangling targets skipped (no orphan edges). Failures are logged and never fail the remember() call — auto-wiring is best-effort.

New CLI

uteke edges <id>           # list direct edges (both directions)
uteke edges <id> --deep 2  # BFS across edge table, 2 hops
uteke edges <id> --json    # JSON output

Core API (uteke-core)

  • Uteke::wire_edges() (pub(crate)) — called from remember_precomputed
  • Uteke::edges_for(id) → EdgeList { outgoing, incoming }
  • Uteke::related_via_edges(id, depth) → Vec<Memory> — replaces O(n) scan
  • Uteke::count_edges() → usize
  • Store methods: add_memory_edge, add_memory_edges_batch, resolve_slug, resolve_tag_to_memory, list_memory_edges, edge_bfs, count_memory_edges

Rewrites

  • get_related() now prefers the edge table (indexed SQL). Falls back to legacy JSON metadata scan only if no edges exist for the memory — preserves backward compat for pre-v8 stores that never auto-wired.

Cleanup bonus

  • Fixed 3 pre-existing clippy warnings in commands/graph.rs (else { if .. } collapse) so cargo clippy --workspace --all-targets -- -D warnings now passes cleanly.

Tests

  • +20 new unit tests in edges.rs covering: extraction patterns (slug/multiple/reject-invalid/@tag/caret-uuid/arrow-uuid/short-id-reject/legacy-metadata/flat-meta-pairs/mixed), is_valid_slug, looks_like_uuid, edge roundtrip, deduplication, BFS 1-hop + 2-hop, BFS cycle safety, slug/tag resolution.
  • Updated 1 existing schema-version test (v7 → v8).
  • All 193 tests pass. Clippy clean.

Checklist (from issue #346)

  • Add memory_edges SQLite table + migration (schema v8)
  • Implement pattern-based entity extraction in remember() flow
  • Rewrite get_related() to use SQL instead of JSON scan
  • Rewrite recall_related() BFS — left as-is for now; it already calls get_related() path indirectly and the metadata-based parse_relationships is still valid for legacy data. Edge-table-backed recall_related can be layered on top in a follow-up once we have usage signal.
  • Add uteke edges CLI subcommand
  • Add uteke graph CLI subcommand (summary stats) — already exists from feat: SQLite graph storage — optional knowledge graph mode #317 (uteke graph stats)
  • Migration script: metadata.relationships → memory_edges rows (inline in v7→v8 migration)
  • Tests: extraction patterns, traversal, deduplication, cycle detection

Verification

  • cargo build --workspace — clean
  • cargo clippy --workspace --all-targets -- -D warnings — clean
  • cargo test --workspace — 193 pass, 0 fail

Non-goals (per issue)

  • LLM-based entity extraction (out of scope — pure pattern matching only)
  • External KG formats (RDF, etc.)
  • Graph visualization (separate issue)

Closes #346

Self-wiring knowledge graph: every remember() extracts entity references
via pure string parsing (no LLM) and writes typed edges to a new
memory_edges SQLite table. get_related() now uses indexed SQL instead of
O(n) JSON scan.

Schema v7 -> v8:
- New memory_edges table (source_id, target_id, edge_type, created_at)
  with indices on source, target, type; UNIQUE(source, target, type).
- New optional memories.slug column (partial index) for [[slug]] linking.
- Migration v7->v8 backfills existing metadata.relationships JSON entries
  into memory_edges rows.

Extraction patterns (zero LLM):
- [[slug]]       -> references edge  (via memories.slug lookup)
- @tag           -> tagged_as edge   (most recent memory with that tag)
- ^<uuid>        -> supersedes edge  (direct UUID)
- ><uuid>        -> replies_to edge  (direct UUID)
- rel:<t>:<id>   -> <t> edge         (legacy --meta form, backward compat)

New CLI:
  uteke edges <id>           # list direct edges (both directions)
  uteke edges <id> --deep N  # BFS across edge table, N hops
  uteke edges <id> --json

Core API (uteke-core):
- Uteke::wire_edges()         (pub(crate)) called from remember_precomputed
- Uteke::edges_for(id)        -> EdgeList { outgoing, incoming }
- Uteke::related_via_edges(id, depth) -> Vec<Memory>  (replaces O(n) scan)
- Uteke::count_edges()        -> usize
- Store::add_memory_edge/add_memory_edges_batch/resolve_slug/
  resolve_tag_to_memory/list_memory_edges/edge_bfs/count_memory_edges

Rewrites:
- get_related() prefers edge table; falls back to legacy JSON scan only
  if no edges exist for the memory (backward compat for pre-v8 stores
  that never auto-wired).

Cleanup:
- Fixed pre-existing clippy warnings in commands/graph.rs (3x else-if
  collapse) so cargo clippy --workspace -- -D warnings passes cleanly.

Tests: +20 unit tests covering extraction patterns (slug/tag/uuid/reply/
legacy meta), edge roundtrip, deduplication, BFS traversal, cycle safety,
and slug/tag resolution. All 193 tests pass.

Docs: CHANGELOG entry, new 'uteke edges' section in cli-reference.md.

Closes #346.
Comment thread crates/uteke-core/src/edges.rs Dismissed
Comment thread crates/uteke-core/src/graph.rs Fixed
@github-actions

github-actions Bot commented Jun 17, 2026 •

Copy link
Copy Markdown

🔍 Cora AI Code Review

❌ Blocked — critical issues found.

🔴 Error (5)

  • crates/uteke-core/src/operations.rs:129 — In remember(), self.store.insert(&memory)?; is followed immediately by self.wire_edges(...) and only after that does the code invalidate cache and continue the rest of the write path. wire_edges() writes rows into memory_edges through add_memory_edges_batch(), but it is not part of the same transaction as the rest of the remember flow. If a later step in remember() fails after edges were inserted, the memory insert may be rolled back or the overall operation may return an error while the edge rows remain committed, leaving inconsistent graph state.
  • crates/uteke-core/src/edges.rs:394 — The new edge_bfs() query uses SELECT target_id FROM memory_edges WHERE source_id = ?1 UNION SELECT source_id FROM memory_edges WHERE target_id = ?1, so traversal is effectively undirected. However, auto-wired edge types like supersedes, replies_to, and references are directional. This means related_via_edges() and uteke edges --deep N will report memories reachable through reverse links that were never explicitly created as outgoing relations, which can change functionality and produce misleading results for directional relationships.
  • crates/uteke-core/src/graph.rs:146 — The rewritten get_related() now seeds results from related_via_edges(memory_id, 1)?, but the fallback path still ends with let all_memories = self.store.load_all(None)?; and scans every memory to find incoming legacy metadata relationships. Passing None ignores the current memory's namespace, so a single related lookup now still performs a full-table scan of the entire store. On large multi-namespace datasets this undermines the intended performance improvement and does unnecessary work on unrelated namespaces.
  • crates/uteke-core/src/edges.rs:146 — Static security scanner detected: Hardcoded password or secret in variable in crates/uteke-core/src/edges.rs:146
  • crates/uteke-core/src/edges.rs:847 — Static security scanner detected: SQL injection via string concatenation in crates/uteke-core/src/edges.rs:847

Review powered by cora-cli · BYOK · MIT

Three valid findings from security/semantic review:

1. Migration FK abort (finding #131): backfill INSERT now uses
   'INSERT ... SELECT ... WHERE EXISTS (SELECT 1 FROM memories WHERE id = ?2)'
   so a legacy metadata.relationships entry pointing to a deleted or
   nonexistent memory is skipped instead of aborting the v7->v8 schema
   migration (which would prevent the database from opening).

2. get_related() semantic change (finding #132): union edge-table results
   with legacy metadata.relationships scan instead of early-returning when
   any edge exists. The previous code could silently drop incoming
   relations encoded only in metadata. Now both sources are merged via a
   shared visited set.

3. Slug uniqueness documentation (finding #130): the SCHEMA comment and
   Store::resolve_slug doc now accurately describe slug resolution as
   'most recently updated wins' rather than claiming uniqueness is
   enforced (the partial index is non-unique). Users who need deterministic
   links are told to keep slugs unique per namespace.

Plus:
- Removed stray double-semicolon in schema.rs (clippy warning).
- Added 2 regression tests for findings #131 and #132.

The 'Hardcoded password in variable' finding on edges.rs:146 was a
false positive (variable named 'token' in UUID extraction code) —
no actual secret, will dismiss the alert.

All 195 tests pass. Clippy clean.
Comment thread crates/uteke-core/src/edges.rs Fixed
Comment thread crates/uteke-core/src/edges.rs Dismissed
edge_bfs() previously called self.conn.prepare(...) inside the while
loop, recompiling the same SQL once per visited node. Move the prepare
above the loop and reuse the statement across hops.

Also adds migration_dispatcher_reaches_v8 regression test that proves
the v7->v8 migration is invoked on upgrade (refutes CodeCora finding
#136, which misread the dispatcher logic). A fresh Store now must
report schema_version=8 and a queryable memory_edges table.

All 172 tests pass.
Comment thread crates/uteke-core/src/edges.rs Fixed
CodeCora found that ExtractedRef::Uuid (^<uuid>, ><uuid>) and
ExtractedRef::Rel (rel:<type>:<id>) resolved targets via store.get_by_id
without namespace filtering. This leaked relationships across isolated
namespaces — inconsistent with slug (@[[slug]]) and tag (@tag) resolution
which are already namespace-scoped.

Fix: add Store::get_by_id_in_namespace(id, ns) and use it in wire_edges
for Uuid + Rel branches. A UUID that exists in another namespace is now
treated as unresolved (same as a missing UUID).

+1 regression test (uuid_edges_respect_namespace_isolation) covering
both cross-namespace rejection and same-namespace success.

173 tests pass. Clippy clean.

Finding #139 (wire_edges non-atomic vs store.insert) dismissed as an
accepted design trade-off: edge rows CASCADE-delete on forget, so no
permanent corruption. Atomic buffering would require restructuring
remember() and is deferred until we have usage signal.

Closes #138.
Comment thread crates/uteke-core/src/edges.rs Fixed
Comment thread crates/uteke-core/src/edges.rs Dismissed
@ajianaz
ajianaz merged commit a97c0a5 into develop Jun 17, 2026
9 checks passed
@ajianaz
ajianaz deleted the feat/auto-edges-346 branch June 17, 2026 06:11
ajianaz added a commit that referenced this pull request Aug 13, 2026
* feat: auto-wired memory edges (#346)

Self-wiring knowledge graph: every remember() extracts entity references
via pure string parsing (no LLM) and writes typed edges to a new
memory_edges SQLite table. get_related() now uses indexed SQL instead of
O(n) JSON scan.

Schema v7 -> v8:
- New memory_edges table (source_id, target_id, edge_type, created_at)
  with indices on source, target, type; UNIQUE(source, target, type).
- New optional memories.slug column (partial index) for [[slug]] linking.
- Migration v7->v8 backfills existing metadata.relationships JSON entries
  into memory_edges rows.

Extraction patterns (zero LLM):
- [[slug]]       -> references edge  (via memories.slug lookup)
- @tag           -> tagged_as edge   (most recent memory with that tag)
- ^<uuid>        -> supersedes edge  (direct UUID)
- ><uuid>        -> replies_to edge  (direct UUID)
- rel:<t>:<id>   -> <t> edge         (legacy --meta form, backward compat)

New CLI:
  uteke edges <id>           # list direct edges (both directions)
  uteke edges <id> --deep N  # BFS across edge table, N hops
  uteke edges <id> --json

Core API (uteke-core):
- Uteke::wire_edges()         (pub(crate)) called from remember_precomputed
- Uteke::edges_for(id)        -> EdgeList { outgoing, incoming }
- Uteke::related_via_edges(id, depth) -> Vec<Memory>  (replaces O(n) scan)
- Uteke::count_edges()        -> usize
- Store::add_memory_edge/add_memory_edges_batch/resolve_slug/
  resolve_tag_to_memory/list_memory_edges/edge_bfs/count_memory_edges

Rewrites:
- get_related() prefers edge table; falls back to legacy JSON scan only
  if no edges exist for the memory (backward compat for pre-v8 stores
  that never auto-wired).

Cleanup:
- Fixed pre-existing clippy warnings in commands/graph.rs (3x else-if
  collapse) so cargo clippy --workspace -- -D warnings passes cleanly.

Tests: +20 unit tests covering extraction patterns (slug/tag/uuid/reply/
legacy meta), edge roundtrip, deduplication, BFS traversal, cycle safety,
and slug/tag resolution. All 193 tests pass.

Docs: CHANGELOG entry, new 'uteke edges' section in cli-reference.md.

Closes #346.

* fix(edges): address CodeCora review findings

Three valid findings from security/semantic review:

1. Migration FK abort (finding #131): backfill INSERT now uses
   'INSERT ... SELECT ... WHERE EXISTS (SELECT 1 FROM memories WHERE id = ?2)'
   so a legacy metadata.relationships entry pointing to a deleted or
   nonexistent memory is skipped instead of aborting the v7->v8 schema
   migration (which would prevent the database from opening).

2. get_related() semantic change (finding #132): union edge-table results
   with legacy metadata.relationships scan instead of early-returning when
   any edge exists. The previous code could silently drop incoming
   relations encoded only in metadata. Now both sources are merged via a
   shared visited set.

3. Slug uniqueness documentation (finding #130): the SCHEMA comment and
   Store::resolve_slug doc now accurately describe slug resolution as
   'most recently updated wins' rather than claiming uniqueness is
   enforced (the partial index is non-unique). Users who need deterministic
   links are told to keep slugs unique per namespace.

Plus:
- Removed stray double-semicolon in schema.rs (clippy warning).
- Added 2 regression tests for findings #131 and #132.

The 'Hardcoded password in variable' finding on edges.rs:146 was a
false positive (variable named 'token' in UUID extraction code) —
no actual secret, will dismiss the alert.

All 195 tests pass. Clippy clean.

* style: cargo fmt edges.rs (Format CI)

* perf(edges): hoist BFS prepare statement out of loop (CodeCora #134)

edge_bfs() previously called self.conn.prepare(...) inside the while
loop, recompiling the same SQL once per visited node. Move the prepare
above the loop and reuse the statement across hops.

Also adds migration_dispatcher_reaches_v8 regression test that proves
the v7->v8 migration is invoked on upgrade (refutes CodeCora finding
#136, which misread the dispatcher logic). A fresh Store now must
report schema_version=8 and a queryable memory_edges table.

All 172 tests pass.

* fix(edges): enforce namespace isolation on UUID/rel edges (#138)

CodeCora found that ExtractedRef::Uuid (^<uuid>, ><uuid>) and
ExtractedRef::Rel (rel:<type>:<id>) resolved targets via store.get_by_id
without namespace filtering. This leaked relationships across isolated
namespaces — inconsistent with slug (@[[slug]]) and tag (@tag) resolution
which are already namespace-scoped.

Fix: add Store::get_by_id_in_namespace(id, ns) and use it in wire_edges
for Uuid + Rel branches. A UUID that exists in another namespace is now
treated as unresolved (same as a missing UUID).

+1 regression test (uuid_edges_respect_namespace_isolation) covering
both cross-namespace rejection and same-namespace success.

173 tests pass. Clippy clean.

Finding #139 (wire_edges non-atomic vs store.insert) dismissed as an
accepted design trade-off: edge rows CASCADE-delete on forget, so no
permanent corruption. Atomic buffering would require restructuring
remember() and is deferred until we have usage signal.

Closes #138.

* style: cargo fmt
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat: typed auto-edges — self-wiring knowledge graph on every remember()

2 participants