perf(sf): index memory_relations.to_id for reverse-edge lookups

Audit of all FROM/INTO/UPDATE clauses in the codebase against
CREATE TABLE statements found one missing index. memory_relations
PK is (from_id, to_id, rel) — covers from_id as leading column. But
memory-relations.ts:233 queries `WHERE to_id = :id` which would
full-scan once the relation count grows.

Added idx_memory_relations_to. Cheap insertion cost; avoids the
worst-case query as soon as a ranker consumer starts traversing
edges (the natural next-step from 23c5de38b).

Schema-gap audit (option 3 in the redirect): no other ghost-table
references found. unit_claims has its own .sf/unit-claims.db and
self-contained schema in unit-ownership.ts. active_decisions /
active_requirements / active_memories are CREATE VIEW IF NOT EXISTS,
properly created. "INTO worktree" was a JSDoc false positive.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
Mikael Hugo 2026-05-03 00:05:05 +02:00
parent 72104aed1d
commit 1da4d5fdf6

View file

@ -313,6 +313,12 @@ function initSchema(db: DbAdapter, fileBacked: boolean): void {
FOREIGN KEY (to_id) REFERENCES memories(id) ON DELETE CASCADE
)
`);
// PK covers from_id as leading column already; reverse lookups
// (memory-relations.ts queries WHERE to_id = ?) need their own index
// to avoid a full table scan as the relation count grows.
db.exec(
"CREATE INDEX IF NOT EXISTS idx_memory_relations_to ON memory_relations(to_id)",
);
db.exec(`
CREATE TABLE IF NOT EXISTS memory_sources (