about summary refs log tree commit diff
diff options
context:
space:
mode:
authorPjotr Prins <pjotr.public01@thebird.nl>2026-11-11 22:05:35 +0000
committerPjotr Prins <pjotr.public01@thebird.nl>2026-11-11 22:05:35 +0000
commitaa6fe5369c7733e8bc881623ab6734cfef9cb66c (patch)
tree8d6d929282388b5b003f7f932765089e370de78a
downloadai-memory-aa6fe5369c7733e8bc881623ab6734cfef9cb66c.tar.gz
initial ai-memory: derive commits and symbols from git, author the why
commits, symbols and touches are derived from `git log`/`git show` by
`sync`; only reasoning is authored, and it is append-only.  Each entry
records a basis (how it was established) and may supersede an earlier
entry instead of rewriting it.

Symbols come from two signals: declarations added or removed on diff
lines (Odin and Rust), and the enclosing item named in git's own hunk
headers, which needs no parser and works for any language with a
userdiff driver.

Links SQLite through the odin-sqlite3 bindings; guix.scm builds both the
compiler and the tool.  doc/SKILL.md is the operating guide.
-rw-r--r--.gitignore5
-rw-r--r--db.odin259
-rw-r--r--doc/SKILL.md136
-rw-r--r--git.odin336
-rw-r--r--guix.scm262
-rw-r--r--lang.odin196
-rw-r--r--main.odin843
-rw-r--r--schema.sql75
8 files changed, 2112 insertions, 0 deletions
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..0364839
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,5 @@
+# the store is local working memory, not source
+/ai-memory.sqlite
+/ai-memory.sqlite-*
+# local build output of `odin build . -out:bin/ai-memory'
+/bin/
diff --git a/db.odin b/db.odin
new file mode 100644
index 0000000..a15ea36
--- /dev/null
+++ b/db.odin
@@ -0,0 +1,259 @@
+package main
+
+import "core:c"
+import "core:fmt"
+import "core:strings"
+import sqlite3 "sqlite3:sqlite3"
+
+// The database is a file next to the sources.  It must not be called
+// `ai-memory': that is the name of the binary `odin build -out:ai-memory'
+// produces.
+DEFAULT_DB_PATH :: "ai-memory.sqlite"
+
+SCHEMA :: #load("schema.sql", string)
+
+Db :: struct {
+	handle: ^sqlite3.Connection,
+}
+
+Stmt :: struct {
+	db:     ^Db,
+	handle: ^sqlite3.Statement,
+}
+
+db_open :: proc(path: string) -> (db: Db, ok: bool) {
+	cpath := strings.clone_to_cstring(path, context.temp_allocator)
+	if rc := sqlite3.open(cpath, &db.handle); rc != .Ok {
+		fmt.eprintfln("ai-memory: cannot open %q: %v", path, rc)
+		return {}, false
+	}
+	// Foreign keys are off by default in SQLite; WAL keeps readers (the
+	// assistant) out of the writer's way.
+	if !db_exec(&db, "pragma journal_mode = wal") ||
+	   !db_exec(&db, "pragma foreign_keys = on") ||
+	   !db_exec(&db, "pragma busy_timeout = 5000") {
+		db_close(&db)
+		return {}, false
+	}
+	return db, true
+}
+
+db_close :: proc(db: ^Db) {
+	if db.handle != nil {
+		sqlite3.close(db.handle)
+		db.handle = nil
+	}
+}
+
+db_exec :: proc(db: ^Db, sql: string) -> bool {
+	csql := strings.clone_to_cstring(sql, context.temp_allocator)
+	err: cstring
+	if rc := sqlite3.exec(db.handle, csql, nil, nil, &err); rc != .Ok {
+		db_report(db, rc, err)
+		return false
+	}
+	return true
+}
+
+// db_report prints a SQLite failure.  The extended code says *which* constraint
+// failed, which the primary code hides.
+db_report :: proc(db: ^Db, rc: sqlite3.Result_Code, err: cstring) {
+	msg := ""
+	if err != nil {
+		msg = strings.clone(string(err), context.temp_allocator)
+		sqlite3.free(cast(rawptr)err)
+	} else if db.handle != nil {
+		msg = string(sqlite3.errmsg(db.handle))
+	}
+	extended := rc
+	if db.handle != nil {
+		extended = sqlite3.extended_errcode(db.handle)
+	}
+	if extended != rc {
+		fmt.eprintfln("ai-memory: sql error (%v/%v): %s", rc, extended, msg)
+	} else {
+		fmt.eprintfln("ai-memory: sql error (%v): %s", rc, msg)
+	}
+	#partial switch extended {
+	case .Constraint_ForeignKey:
+		fmt.eprintln("ai-memory: the row this refers to does not exist yet " +
+		             "(for commits: run `sync')")
+	case .Constraint_Unique:
+		fmt.eprintln("ai-memory: that entry already exists")
+	case:
+	}
+}
+
+stmt :: proc(db: ^Db, sql: string) -> (s: Stmt, ok: bool) {
+	s.db = db
+	csql := strings.clone_to_cstring(sql, context.temp_allocator)
+	if rc := sqlite3.prepare(db.handle, csql, c.int(len(sql)), &s.handle, nil); rc != .Ok {
+		db_report(db, rc, nil)
+		return {}, false
+	}
+	return s, true
+}
+
+stmt_close :: proc(s: ^Stmt) {
+	if s.handle != nil {
+		sqlite3.finalize(s.handle)
+		s.handle = nil
+	}
+}
+
+// bind_text copies VALUE into SQLite's own buffer, so the caller's string may
+// be temporary.
+stmt_bind_text :: proc(s: ^Stmt, idx: int, value: string) -> bool {
+	cvalue := strings.clone_to_cstring(value, context.temp_allocator)
+	rc := sqlite3.bind_text(s.handle, c.int(idx), cvalue, c.int(len(value)),
+	                        sqlite3.Destructor{behaviour = .Transient})
+	if rc != .Ok {
+		db_report(s.db, rc, nil)
+		return false
+	}
+	return true
+}
+
+stmt_bind_i64 :: proc(s: ^Stmt, idx: int, value: i64) -> bool {
+	rc := sqlite3.bind_int64(s.handle, c.int(idx), c.int64_t(value))
+	if rc != .Ok {
+		db_report(s.db, rc, nil)
+		return false
+	}
+	return true
+}
+
+stmt_bind_null :: proc(s: ^Stmt, idx: int) -> bool {
+	rc := sqlite3.bind_null(s.handle, c.int(idx))
+	if rc != .Ok {
+		db_report(s.db, rc, nil)
+		return false
+	}
+	return true
+}
+
+// stmt_step returns the raw result code: .Row, .Done or an error.
+stmt_step :: proc(s: ^Stmt) -> sqlite3.Result_Code {
+	rc := sqlite3.step(s.handle)
+	if rc != .Row && rc != .Done {
+		db_report(s.db, rc, nil)
+	}
+	return rc
+}
+
+stmt_col_text :: proc(s: ^Stmt, idx: int, allocator := context.temp_allocator) -> string {
+	c := sqlite3.column_text(s.handle, c.int(idx))
+	if c == nil {
+		return ""
+	}
+	return strings.clone(string(c), allocator)
+}
+
+stmt_col_i64 :: proc(s: ^Stmt, idx: int) -> i64 {
+	return i64(sqlite3.column_int64(s.handle, c.int(idx)))
+}
+
+// db_migrate creates the schema and upgrades older stores in place.
+db_migrate :: proc(db: ^Db) -> bool {
+	// SCHEMA's `create table if not exists' never alters an existing table, and
+	// it creates indexes over the columns added since version 1.  So the column
+	// additions have to happen before SCHEMA runs.  A fresh store is version 0
+	// and simply gets everything from SCHEMA.
+	// Version 2 added the basis and supersedes columns to reasoning.
+	if db_user_version(db) == 1 {
+		if !db_exec(db, "alter table reasoning add column basis text") {
+			return false
+		}
+		if !db_exec(db, "alter table reasoning add column supersedes integer references reasoning(id)") {
+			return false
+		}
+		if !db_exec(db, "pragma user_version = 2") {
+			return false
+		}
+	}
+
+	// Version 3 added symbols.basename so that an unqualified identifier is an
+	// index seek rather than a LIKE scan.
+	if db_user_version(db) == 2 {
+		if !db_exec(db, "alter table symbols add column basename text") {
+			return false
+		}
+		if !db_backfill_basename(db) {
+			return false
+		}
+		if !db_exec(db, "pragma user_version = 3") {
+			return false
+		}
+	}
+
+	return db_exec(db, SCHEMA)
+}
+
+// db_backfill_basename fills symbols.basename for stores created before
+// version 3.  The value is the identifier after the last dot of the qualified
+// name; SQLite has no right-to-left string functions, so this walks the rows.
+db_backfill_basename :: proc(db: ^Db) -> bool {
+	Rows :: struct {
+		id:   i64,
+		name: string,
+	}
+	rows := make([dynamic]Rows, 0, 1024)
+	defer delete(rows)
+
+	s, ok := stmt(db, "select id, name from symbols")
+	if !ok {
+		return false
+	}
+	for stmt_step(&s) == .Row {
+		append(&rows, Rows{
+			id = stmt_col_i64(&s, 0),
+			name = strings.clone(stmt_col_text(&s, 1), context.temp_allocator),
+		})
+	}
+	stmt_close(&s)
+
+	if !db_exec(db, "begin") {
+		return false
+	}
+	// One statement per row: after SQLITE_DONE a statement must be reset before
+	// it can be re-bound, and this binding set does not expose sqlite3_reset.
+	// Preparing again is cheap enough for a one-off migration.
+	for row in rows {
+		base := row.name
+		if dot := strings.last_index_byte(base, '.'); dot >= 0 {
+			base = base[dot + 1:]
+		}
+		u, uok := stmt(db, "update symbols set basename = ?1 where id = ?2")
+		if !uok {
+			db_exec(db, "rollback")
+			return false
+		}
+		stmt_bind_text(&u, 1, base)
+		stmt_bind_i64(&u, 2, row.id)
+		done := stmt_step(&u) == .Done
+		stmt_close(&u)
+		if !done {
+			db_exec(db, "rollback")
+			return false
+		}
+	}
+	return db_exec(db, "commit")
+}
+
+// db_user_version reads the store's schema version (0 for an empty database).
+db_user_version :: proc(db: ^Db) -> int {
+	s, ok := stmt(db, "pragma user_version")
+	if !ok {
+		return 0
+	}
+	defer stmt_close(&s)
+	if stmt_step(&s) != .Row {
+		return 0
+	}
+	return int(stmt_col_i64(&s, 0))
+}
+
+// sqlite_changes reports rows modified by the most recent statement.
+sqlite_changes :: proc(db: ^Db) -> i64 {
+	return i64(sqlite3.changes(db.handle))
+}
diff --git a/doc/SKILL.md b/doc/SKILL.md
new file mode 100644
index 0000000..717b84b
--- /dev/null
+++ b/doc/SKILL.md
@@ -0,0 +1,136 @@
+---
+name: gn-memory
+description: Keep a repository's ai-memory SQLite store current — import git history, record reasoning while working, and answer "why does this code look like this?" before changing it.
+---
+
+# gn-memory
+
+`ai-memory` is a per-repository store that links **what changed** (derived from
+git) to **why it changed** (written by you).  Three tables:
+
+| table | source | contents |
+|---|---|---|
+| `commits` | derived | hash, author timestamp, subject, body |
+| `symbols` + `touches` | derived | every declaration a commit added, modified, removed, or merely *enclosed* (hunk context) |
+| `reasoning` | **authored** | append-only thoughts, conclusions and questions; each records its `basis` and may `supersede` an earlier entry |
+
+Query flow: symbol → commits that touched it → reasoning behind those commits.
+
+## Getting the binary
+
+```sh
+guix build -f guix.scm          # build (odin + sqlite are in guix.scm)
+$(guix build -f guix.scm)/bin/ai-memory --help
+```
+
+Or build locally into `bin/` (gitignored) with the flags listed at the top of
+`guix.scm`:
+
+```sh
+guix shell -D -f guix.scm -- odin build . -out:bin/ai-memory -vet -strict-style \
+  -collection:sqlite3=$GUIX_ENVIRONMENT/share/odin-sqlite3 \
+  -define:SQLITE3_SYSTEM_LIB=true -define:SQLITE3_DYNAMIC_LIB=true \
+  "-extra-linker-flags:-L$GUIX_ENVIRONMENT/lib -Wl,-rpath,$GUIX_ENVIRONMENT/lib"
+```
+
+The store defaults to `<repo>/ai-memory.sqlite`; override with `--db PATH` or
+`$AI_MEMORY_DB`.  `--repo PATH` / `-C PATH` selects the repository, and may be
+given before or after the command.
+
+## Session protocol
+
+1. **Once per repo**: `ai-memory -C REPO init` (idempotent, creates/upgrades the schema).
+2. **After every commit**: `ai-memory -C REPO sync`.  It is cheap and idempotent —
+   re-running it only refreshes derived rows.  Use `import` instead of `sync`
+   only to pull in a *whole* history the first time (`import` has no limit).
+3. **Before changing code**: ask the store, do not guess.
+   `ai-memory -C REPO why SYMBOL` and `ai-memory -C REPO search TEXT`.
+4. **While working**: record as you go, not at the end.  `--kind thought` for
+   what you are weighing, `--kind conclusion` for what you settled on, and
+   `--kind question` when you need an answer from the user.
+5. **Before the commit exists** there is nothing to attach to: use
+   `--commit none`, then after committing run
+   `ai-memory -C REPO attach HEAD --session S`.
+6. **Correcting yourself is not a normal record.**  `--supersedes ID` changes what
+   `why` and `search` answer from then on, so it needs the user's consent first —
+   see the Rules below.
+
+```sh
+ai-memory -C REPO record --session fix-parser --step 1 \
+  --kind thought --basis "read at git.odin:120-141" \
+  --body "Hunk headers name the enclosing fn; a new fn needs the declarative scan." --commit none
+ai-memory -C REPO record --session fix-parser --step 2 \
+  --kind conclusion --basis "measured on genenetwork4, 281 commits in 2.5 s" \
+  --body "Keep both signals; add ctags only if add/remove proves noisy."
+ai-memory -C REPO attach HEAD --session fix-parser
+```
+
+`record` and `attach` import the commit on demand, so they work immediately after
+committing even if `sync` has not run yet.
+
+## Rules
+
+- **Never write to `commits`, `symbols` or `touches` by hand.**  They are derived;
+  `sync` owns them and hand edits will be silently overwritten or duplicated.
+- **`reasoning` is append-only.**  Do not edit or delete an entry to change your
+  mind: record a correction with `--supersedes ID`.  The old entry stays visible as
+  `#12 [superseded by #15]`, `why` and `search` answer with the correction, and
+  `--all` shows the whole chain.  `attach` is the only other update the tool makes
+  (setting a NULL `commit_hash`).
+- **Ask the user before superseding.**  `--supersedes` rewrites history as far as
+  every later reader is concerned: `why` and `search` stop answering with the old
+  entry, and that entry collapses to a one-line stub.  The row survives, but the
+  record's answer does not.  So: say which entry id you propose to replace, what
+  it claimed, what the replacement says, and on what basis — then wait for a yes.
+  Do not bundle it into a batch of records, and never supersede an entry written by
+  someone else without their consent.  If the user declines, either record the
+  correction as a new standing entry without `--supersedes` (both claims stay
+  visible and the contradiction is on the record) or do not record it at all.
+- **Every entry says how it was established** (`--basis`): `read at src/lib.rs:412-470`,
+  `from commit message`, `measured on the gn4 instance`, or plainly `inferred`.
+  Inference and observation look identical in prose, and that is exactly what makes
+  a wrong entry unrecognisable later.
+- **One session per task**, monotonically increasing `--step`.  `(session_id, step, kind)`
+  is unique, so re-running a step is a no-op rather than a duplicate.
+- **Make bodies self-contained.**  Say what you considered, what you chose, what
+  you rejected and why.  A future reader has the diff but not the conversation.
+- **Name what you renamed.**  Symbols are `<file-base>.<identifier>` (e.g.
+  `gemma.compute_gemma`); an old name keeps its history, so mention the new name
+  in the body to keep `search` useful.
+- **Never commit the store or the build output.**  `/bin/` and `ai-memory.sqlite*` are
+  in `.gitignore`; commit only source.  Importing history is read-only — `-C`
+  never touches the working tree.
+
+## Interpretation
+
+- `[fn gemma.compute_gemma, context]` means a hunk landed *inside* that function,
+  not that the function was declared.  `add`/`remove`/`mod` are declaration changes.
+- Only `.odin` and `.rs` are parsed for declarations.  Everything else still gets
+  hunk-context symbols (`[fn name, context]`) thanks to git's userdiff drivers, so
+  "which function was I in" works for C, Python, Go, … too.
+- `why SYMBOL` tries three things in order, all but the last indexed: the
+  qualified name (`gemma.compute_gemma`), then the bare identifier via
+  `symbols.basename` (`compute_gemma`), then a `LIKE '%…%'` scan for partial names.
+- `log` prints how many reasoning entries each commit carries — commits with `(0)`
+  are the ones worth annotating later.
+
+## Troubleshooting
+
+- `no commits to import` — the repo has no history yet, or `--repo` points elsewhere.
+- `why` finds nothing — run `sync` first; or the symbol lives in a file type we do
+  not parse for declarations.
+- `search` finds nothing after manual DB edits — FTS is trigger-maintained; rebuild
+  with `insert into reasoning_fts(reasoning_fts) values('rebuild')`.
+- Direct inspection is fine (read-only):
+
+```sh
+sqlite3 ai-memory.sqlite \
+  "select c.hash, c.subject, r.kind, r.body
+     from symbols s join touches t on t.symbol_id = s.id
+       join commits c on c.hash = t.commit_hash
+       left join reasoning r on r.commit_hash = c.hash
+    where s.name like '%compute_gemma'
+    order by c.author_ts desc;"
+```
+
+- `commit`, `symbol` and `touch` are SQL keywords; the tables are plural.
diff --git a/git.odin b/git.odin
new file mode 100644
index 0000000..27a64cb
--- /dev/null
+++ b/git.odin
@@ -0,0 +1,336 @@
+package main
+
+import "core:fmt"
+import "core:os"
+import "core:strconv"
+import "core:strings"
+
+// Field/record separators for git log parsing; these control characters do not
+// occur in commit messages.
+REC_SEP :: 0x1e
+FLD_SEP :: 0x1f
+
+// REPO_DIR is the repository git commands run in; empty means the current
+// directory.  Set from --repo PATH.
+REPO_DIR: string
+
+Git_Commit :: struct {
+	hash:      string,
+	author_ts: i64,
+	subject:   string,
+	body:      string,
+}
+
+// A symbol a commit touched.  `added'/`removed' come from declarations that
+// appear or disappear in the diff; `in_context' marks the enclosing item named in
+// a hunk header, i.e. "the change happened inside this function".
+Decl :: struct {
+	name:    string, // unqualified identifier
+	kind:    string, // proc | fn | type | const | var
+	file:    string,
+	added:   bool,
+	removed: bool,
+	in_context: bool,
+}
+
+// git runs `git ARGS' in REPO_DIR and captures its stdout.
+git :: proc(args: []string, allocator := context.temp_allocator, report := true) -> (out: string, ok: bool) {
+	cmd := make([dynamic]string, 0, len(args) + 1, context.temp_allocator)
+	append(&cmd, "git")
+	append(&cmd, ..args)
+
+	desc := os.Process_Desc{command = cmd[:]}
+	if len(REPO_DIR) > 0 {
+		desc.working_dir = REPO_DIR
+	}
+
+	state, stdout, stderr, err := os.process_exec(desc, context.temp_allocator)
+	if err != nil {
+		fmt.eprintfln("ai-memory: cannot run git: %v", err)
+		return "", false
+	}
+	if state.exit_code != 0 {
+		if report {
+			msg := strings.trim_space(string(stderr))
+			fmt.eprintfln("ai-memory: git %s failed: %s", args[0], msg)
+		}
+		return "", false
+	}
+	return strings.clone(string(stdout), allocator), true
+}
+
+// git_log reads the history, newest first.  LIMIT of 0 means everything.
+git_log :: proc(limit: int) -> ([]Git_Commit, bool) {
+	// A fresh repository has no commits yet; that is not an error here, so the
+	// probe stays quiet.
+	if _, has_head := git([]string{"rev-parse", "--verify", "--quiet", "HEAD"},
+	                     context.temp_allocator, false); !has_head {
+		return nil, true
+	}
+
+	args := make([dynamic]string, 0, 8, context.temp_allocator)
+	append(&args, "log", "--format=%H%x1f%at%x1f%s%x1f%b%x1e")
+	if limit > 0 {
+		append(&args, fmt.tprintf("-n%d", limit))
+	}
+	raw, ok := git(args[:])
+	if !ok {
+		return nil, false
+	}
+
+	commits := make([dynamic]Git_Commit, 0, 256)
+	for raw_part in split_byte(raw, REC_SEP) {
+		part := strings.trim_space(raw_part)
+		if len(part) == 0 {
+			continue
+		}
+		fields := split_byte(part, FLD_SEP)
+		if len(fields) < 3 {
+			continue
+		}
+		c: Git_Commit
+		c.hash = fields[0]
+		c.author_ts = parse_i64(fields[1])
+		c.subject = fields[2]
+		if len(fields) > 3 {
+			c.body = join_fields(fields[3:])
+		}
+		append(&commits, c)
+	}
+	return commits[:], true
+}
+
+// git_touched reports the symbols commit HASH touched, from two sources:
+// declarations that appear or disappear on +/- lines, and the enclosing item
+// named in each hunk header (git's userdiff patterns, so no parsing needed).
+git_touched :: proc(hash: string) -> ([]Decl, bool) {
+	raw, ok := git([]string{"show", "--unified=0", "--no-color", "--no-renames",
+	                        "--format=", "--no-ext-diff", hash})
+	if !ok {
+		return nil, false
+	}
+
+	found := make(map[string]Decl)
+	defer delete(found)
+
+	file := ""
+	for line in split_byte(raw, '\n') {
+		switch {
+		case strings.has_prefix(line, "+++ b/"):
+			file = line[len("+++ b/"):]
+			if i := strings.index_byte(file, '\t'); i >= 0 {
+				file = file[:i]
+			}
+
+		case strings.has_prefix(line, "@@ "):
+			// "@@ -412,6 +412,7 @@ fn hash_pve(state: &PveState) -> Result<()>"
+			if ctx, has_ctx := hunk_context(line); has_ctx {
+				if name, kind, is_decl := symbol_in_context(file, ctx); is_decl {
+					merge_decl(&found, Decl{name = name, kind = kind, file = file, in_context = true})
+				}
+			}
+
+		case is_change_line(line):
+			name, kind, is_decl := parse_decl(file, line[1:])
+			if is_decl {
+				merge_decl(&found, Decl{
+					name    = name,
+					kind    = kind,
+					file    = file,
+					added   = line[0] == '+',
+					removed = line[0] == '-',
+				})
+			}
+		}
+	}
+
+	decls := make([dynamic]Decl, 0, len(found))
+	for _, d in found {
+		append(&decls, d)
+	}
+	return decls[:], true
+}
+
+// is_change_line reports an added or removed line, excluding file headers.
+is_change_line :: proc(line: string) -> bool {
+	if len(line) < 2 {
+		return false
+	}
+	if line[0] != '+' && line[0] != '-' {
+		return false
+	}
+	return !strings.has_prefix(line, "+++") && !strings.has_prefix(line, "---")
+}
+
+// merge_decl adds D to M, keeping the strongest evidence seen for the symbol.
+merge_decl :: proc(m: ^map[string]Decl, decl: Decl) {
+	d := decl
+	if old, exists := m[d.name]; exists {
+		d.added = d.added || old.added
+		d.removed = d.removed || old.removed
+		d.in_context = d.in_context || old.in_context
+	}
+	m[d.name] = d
+}
+
+// hunk_context returns the text after the closing "@@" of a hunk header.
+hunk_context :: proc(line: string) -> (ctx: string, ok: bool) {
+	rest := line[len("@@ "):]
+	i := strings.index(rest, " @@")
+	if i < 0 {
+		return "", false
+	}
+	ctx = strings.trim_space(rest[i + len(" @@"):])
+	return ctx, len(ctx) > 0
+}
+
+// symbol_in_context names the enclosing item from a hunk header.  Our language
+// parsers handle Odin and Rust signatures; everything else falls back to "the
+// identifier in front of the parameter list".
+symbol_in_context :: proc(file, ctx: string) -> (name: string, kind: string, ok: bool) {
+	if name, kind, ok = parse_decl(file, ctx); ok {
+		return name, kind, true
+	}
+	if name, ok = signature_name(ctx); ok {
+		return name, "fn", true
+	}
+	return "", "", false
+}
+
+// signature_name picks the identifier in front of the first parameter list that
+// is not a keyword, e.g. "static void hash_pve(int a)" -> "hash_pve".
+signature_name :: proc(ctx: string) -> (name: string, ok: bool) {
+	for i in 0 ..< len(ctx) {
+		if ctx[i] != '(' {
+			continue
+		}
+		start := i
+		for start > 0 && is_ident_byte(ctx[start - 1]) {
+			start -= 1
+		}
+		if start == i {
+			continue
+		}
+		candidate := ctx[start:i]
+		if !is_keyword(candidate) {
+			return candidate, true
+		}
+	}
+	return "", false
+}
+
+is_ident_byte :: proc(c: u8) -> bool {
+	return c == '_' || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
+	       (c >= '0' && c <= '9')
+}
+
+is_keyword :: proc(s: string) -> bool {
+	keywords := [?]string{
+		"if", "for", "while", "switch", "match", "return", "when", "else",
+		"sizeof", "alignof", "offsetof", "typeof", "catch", "assert", "cast",
+		"transmute", "in", "do", "and", "or", "not", "unsafe", "async",
+	}
+	for k in keywords {
+		if s == k {
+			return true
+		}
+	}
+	return false
+}
+
+// symbol_name qualifies a declaration with the file it lives in, so that
+// `main.open_store' and `db.open' do not collide.
+symbol_name :: proc(file, name: string) -> string {
+	base := file
+	if i := strings.last_index_byte(base, '/'); i >= 0 {
+		base = base[i + 1:]
+	}
+	extensions := [?]string{".odin", ".rs"}
+	for ext in extensions {
+		if strings.has_suffix(base, ext) {
+			base = base[:len(base) - len(ext)]
+			break
+		}
+	}
+	if len(base) == 0 {
+		return name
+	}
+	return fmt.tprintf("%s.%s", base, name)
+}
+
+// change_of collapses "saw it added and removed" into a single "mod", and
+// anything only seen in hunk headers into "context".
+change_of :: proc(d: Decl) -> string {
+	switch {
+	case d.added && d.removed:
+		return "mod"
+	case d.removed:
+		return "remove"
+	case d.added:
+		return "add"
+	}
+	return "context"
+}
+
+// split_byte splits s on a single-byte separator, borrowing from s.
+split_byte :: proc(s: string, sep: u8) -> []string {
+	parts := make([dynamic]string, 0, 16, context.temp_allocator)
+	start := 0
+	for i in 0 ..< len(s) {
+		if s[i] == sep {
+			append(&parts, s[start:i])
+			start = i + 1
+		}
+	}
+	append(&parts, s[start:])
+	return parts[:]
+}
+
+// parse_i64 parses an i64, defaulting to 0 (timestamps only).
+parse_i64 :: proc(s: string) -> i64 {
+	if v, ok := strconv.parse_i64(s, 10); ok {
+		return v
+	}
+	return 0
+}
+
+// join_fields re-assembles a commit body that happened to contain the field
+// separator.
+join_fields :: proc(fields: []string) -> string {
+	if len(fields) == 0 {
+		return ""
+	}
+	out := fields[0]
+	for f in fields[1:] {
+		out = fmt.tprintf("%s\x1f%s", out, f)
+	}
+	return out
+}
+
+// git_commit reads a single commit's metadata, for commits that `record' or
+// `attach' refer to before the next `sync'.
+git_commit :: proc(hash: string) -> (c: Git_Commit, ok: bool) {
+	raw, good := git([]string{"show", "--no-patch", "--no-color",
+	                        "--format=%H%x1f%at%x1f%s%x1f%b%x1e", hash})
+	if !good {
+		return {}, false
+	}
+	for raw_part in split_byte(raw, REC_SEP) {
+		part := strings.trim_space(raw_part)
+		if len(part) == 0 {
+			continue
+		}
+		fields := split_byte(part, FLD_SEP)
+		if len(fields) < 3 {
+			continue
+		}
+		c.hash = fields[0]
+		c.author_ts = parse_i64(fields[1])
+		c.subject = fields[2]
+		if len(fields) > 3 {
+			c.body = join_fields(fields[3:])
+		}
+		return c, true
+	}
+	return {}, false
+}
diff --git a/guix.scm b/guix.scm
new file mode 100644
index 0000000..62fcf75
--- /dev/null
+++ b/guix.scm
@@ -0,0 +1,262 @@
+;;; ai-memory -- guix.scm
+;;;
+;;; Development environment and package definitions for ai-memory, plus its
+;;; dependencies that are not in Guix: the Odin compiler and the odin-sqlite3
+;;; bindings.
+;;;
+;;; Development shell with `odin', `clang' and the SQLite bindings on PATH:
+;;;
+;;;   guix shell -D -f guix.scm -- odin version
+;;;
+;;; ai-memory links against SQLite, so building it needs a library collection
+;;; (for "sqlite3:sqlite3"), two #config defines and a search path for
+;;; libsqlite3.  Inside the shell, use the flags the package build uses:
+;;;
+;;;   odin build . -out:bin/ai-memory -vet -strict-style \
+;;;     -collection:sqlite3=$GUIX_ENVIRONMENT/share/odin-sqlite3 \
+;;;     -define:SQLITE3_SYSTEM_LIB=true -define:SQLITE3_DYNAMIC_LIB=true \
+;;;     "-extra-linker-flags:-L$GUIX_ENVIRONMENT/lib -Wl,-rpath,$GUIX_ENVIRONMENT/lib"
+;;;
+;;; Build and install the project:
+;;;
+;;;   guix build -f guix.scm
+;;;
+;;; Build only a dependency (useful while hacking on a package):
+;;;
+;;;   guix build -f guix.scm -e '(@ (guix) odin)'
+;;;   guix build -f guix.scm -e '(@ (guix) odin-sqlite3)'
+;;;
+;;; Note: guix does not substitute Odin, so the first build compiles clang and
+;;; LLVM if no substitutes are available for them.
+
+(define-module (guix)
+  #:use-module ((guix licenses) #:prefix license:)
+  #:use-module (guix build-system copy)
+  #:use-module (guix build-system gnu)
+  #:use-module (guix gexp)
+  #:use-module (guix git-download)
+  #:use-module (guix packages)
+  #:use-module (guix utils)
+  #:use-module (gnu packages bash)
+  #:use-module (gnu packages llvm)
+  #:use-module (gnu packages sqlite))
+
+(define %source-dir (dirname (current-filename)))
+
+;; Machine state in the working tree that must not leak into the build.
+(define (source-file? file stat)
+  (not (member file
+               (list (string-append %source-dir "/.git")
+                     (string-append %source-dir "/bin")
+                     (string-append %source-dir "/ai-memory.sqlite")
+                     (string-append %source-dir "/ai-memory.sqlite-wal")
+                     (string-append %source-dir "/ai-memory.sqlite-shm")))))
+
+;; Odin is not packaged in Guix, so build the compiler here.  Upstream's
+;; build_odin.sh supports LLVM 17 through 22 and uses clang as both the
+;; bootstrap C++ compiler and (at run time) the linker driver; keep these
+;; inputs in sync with what src/build_odin.sh accepts.
+(define-public odin
+  (let ((commit "9a6991685ddf663956d9836602eb421e141fc443")
+        (revision "0"))
+    (package
+      (name "odin")
+      (version (git-version "dev-2026-11a" revision commit))
+      (source
+       (origin
+         (method git-fetch)
+         (uri (git-reference
+               (url "https://github.com/odin-lang/Odin")
+               (commit commit)))
+         (file-name (git-file-name name version))
+         (sha256
+          (base32 "0qd1mbad3j4409ylhhrndr5i5nc6im3s3q4dvqqlwnv68qg66wq4"))))
+      (build-system gnu-build-system)
+      (inputs
+       (list bash-minimal                 ;for the wrappers
+             clang-toolchain-22           ;C++ bootstrap compiler and linker driver
+             llvm-22))                    ;code generation
+      (arguments
+       (list
+        #:modules `((guix build gnu-build-system)
+                    (guix build utils)
+                    (ice-9 popen)
+                    (ice-9 rdelim)
+                    (srfi srfi-13))
+        #:phases
+        #~(modify-phases %standard-phases
+            (delete 'configure)
+            (replace 'build
+              ;; This reproduces the "release" branch of upstream's
+              ;; build_odin.sh for Linux.  The script itself is not used
+              ;; because it derives the version string from the build date,
+              ;; which is not reproducible, and because it probes for brew,
+              ;; llvm-config-$version and the like.
+              (lambda* (#:key inputs #:allow-other-keys)
+                (define llvm-config
+                  (search-input-file inputs "/bin/llvm-config"))
+                (define (llvm-flags . args)
+                  ;; --libfiles prints one file per line, the rest is on a
+                  ;; single line; flatten it all into a list of arguments.
+                  (let* ((port (apply open-pipe* OPEN_READ llvm-config args))
+                         (lines (let loop ((line (read-line port))
+                                           (acc '()))
+                                  (if (eof-object? line)
+                                      (reverse acc)
+                                      (loop (read-line port)
+                                            (cons line acc)))))
+                         (status (close-pipe port)))
+                    (unless (zero? status)
+                      (error "llvm-config failed" args status))
+                    (string-tokenize (string-join lines " "))))
+                (apply invoke "clang++"
+                       (append
+                        (list "src/main.cpp" "src/libtommath.cpp"
+                              "-o" "odin"
+                              "-std=c++14" "-O3" "-pthread"
+                              "-Wno-switch" "-Wno-macro-redefined"
+                              "-Wno-unused-value"
+                              (string-append "-DODIN_VERSION_RAW=\""
+                                             #$version "\""))
+                        (llvm-flags "--cxxflags" "--ldflags")
+                        (list "-lstdc++" "-ldl" "-lm")
+                        (llvm-flags "--libs" "core" "native" "passes"
+                                    "arm" "aarch64" "x86" "webassembly"
+                                    "riscv"
+                                    "--system-libs" "--libfiles")))))
+            (replace 'check
+              ;; There is no make-based test suite; use upstream's own smoke
+              ;; test: compile and run examples/demo.
+              (lambda* (#:key tests? #:allow-other-keys)
+                (when tests?
+                  (invoke "./odin" "version")
+                  (invoke "./odin" "run" "examples/demo"
+                          "-vet" "-strict-style" "--" "Hellope" "World"))))
+            (replace 'install
+              (lambda* (#:key inputs outputs #:allow-other-keys)
+                (define llvm-config
+                  (search-input-file inputs "/bin/llvm-config"))
+                (define libdir
+                  (string-trim-both
+                   (let* ((port (open-pipe* OPEN_READ llvm-config "--libdir"))
+                          (line (read-line port))
+                          (status (close-pipe port)))
+                     (unless (zero? status)
+                       (error "llvm-config failed" "--libdir" status))
+                     line)))
+                (define root (string-append #$output "/lib/odin"))
+                (install-file "odin" (string-append #$output "/bin"))
+                ;; The compiler looks up `base' and `core' through ODIN_ROOT
+                ;; and finds `vendor' below it.
+                (for-each (lambda (dir)
+                            (copy-recursively dir
+                                              (string-append root "/" dir)))
+                          '("base" "core" "vendor"))
+                (wrap-program (string-append #$output "/bin/odin")
+                  `("ODIN_ROOT" ":" prefix (,root))
+                  ;; odin(1) shells out to clang to link programs.
+                  `("PATH" ":" prefix
+                    (,#$(file-append (this-package-input "clang-toolchain")
+                                     "/bin")))
+                  ;; libLLVM is linked dynamically.
+                  `("LD_LIBRARY_PATH" ":" prefix (,libdir))))))))
+      (home-page "https://odin-lang.org")
+      (synopsis "Compiler for the Odin programming language")
+      (description
+       "Odin is a general-purpose programming language with distinct typing,
+built for high performance, modern systems, and data-oriented
+programming.  This package provides @command{odin}, the compiler and its
+standard library collections (@code{core} and @code{vendor}).")
+      (license license:zlib))))
+
+;; Odin bindings for SQLite3.  Upstream also vendors a prebuilt libsqlite3.a;
+;; it is deliberately not installed.  The bindings are instead used with
+;; SQLITE3_SYSTEM_LIB, so programs link the packaged SQLite3 below.
+(define-public odin-sqlite3
+  (let ((commit "0666d2d4af9efe32a7a7c26184536e8c3be79b3b")
+        (revision "0"))
+    (package
+      (name "odin-sqlite3")
+      (version (git-version "0" revision commit))
+      (source
+       (origin
+         (method git-fetch)
+         (uri (git-reference
+               (url "https://github.com/saenai255/odin-sqlite3")
+               (commit commit)))
+         (file-name (git-file-name name version))
+         (sha256
+          (base32 "0nnyppg08x28p097lb1xlkxwl2w0m3b9amv142jxpr8mg22wz636"))))
+      (build-system copy-build-system)
+      (arguments
+       (list
+        ;; Consumed as `-collection:sqlite3=<prefix>', so the package keeps its
+        ;; own directory: Odin sources import "sqlite3:sqlite3" and
+        ;; "sqlite3:addons".
+        #:install-plan
+        #~'(("sqlite.odin" "share/odin-sqlite3/sqlite3/")
+          ("addons" "share/odin-sqlite3/sqlite3/addons"))))
+      (home-page "https://github.com/saenai255/odin-sqlite3")
+      (synopsis "Odin bindings to the SQLite3 C API")
+      (description
+       "Odin bindings for the SQLite3 C API, covering most of the C interface,
+plus an addon package with higher-level query, execute and prepare helpers
+built on Odin reflection.  Build with @code{-define:SQLITE3_SYSTEM_LIB=true}
+to link the system SQLite3 instead of a bundled copy.")
+      (license license:expat))))
+
+(define-public ai-memory
+  (package
+    (name "ai-memory")
+    (version "0.1.0")
+    ;; While developing, build the working tree.  Once this package is
+    ;; released, switch to a git-fetch or url-fetch origin.
+    ;; The working tree, minus the local build output (bin/) and the local
+    ;; store, which are machine state rather than source.
+    (source (local-file %source-dir #:recursive? #t #:select? source-file?))
+    (build-system gnu-build-system)
+    (inputs (list sqlite))                  ;libsqlite3.so, linked at run time
+    (native-inputs (list odin odin-sqlite3))
+    (arguments
+     (list
+      #:phases
+      #~(let* ((sqlite #$(this-package-input "sqlite"))
+               (bindings #$(file-append (this-package-native-input
+                                         "odin-sqlite3")
+                                        "/share/odin-sqlite3"))
+               ;; odin-sqlite3 asks for "system:libsqlite3.so"; odin links that
+               ;; as -l:libsqlite3.so, so it needs both a search path at link
+               ;; time and an rpath at run time.
+               (flags (list "-vet" "-strict-style"
+                            (string-append "-collection:sqlite3=" bindings)
+                            "-define:SQLITE3_SYSTEM_LIB=true"
+                            "-define:SQLITE3_DYNAMIC_LIB=true"
+                            (string-append "-extra-linker-flags:-L" sqlite
+                                           "/lib -Wl,-rpath," sqlite "/lib"))))
+          (modify-phases %standard-phases
+            (delete 'configure)
+            (replace 'build
+              (lambda _
+                (mkdir-p "bin")
+                (apply invoke "odin" "build" "." "-out:bin/ai-memory" flags)))
+            (replace 'check
+              (lambda* (#:key tests? #:allow-other-keys)
+                (when tests?
+                  (mkdir-p "bin")
+                  (apply invoke "odin" "build" "."
+                         "-out:bin/ai-memory-check" flags)
+                  ;; Links and runs; fail loudly if libsqlite3 is missing.
+                  (invoke "./bin/ai-memory-check"))))
+            (replace 'install
+              (lambda _
+                (install-file "bin/ai-memory"
+                              (string-append #$output "/bin"))))))))
+    (home-page "https://github.com/ai-memory/ai-memory")
+    (synopsis "Memory for AI assistants")
+    (description
+     "ai-memory is a store for facts that an AI assistant should remember
+across sessions.  It keeps them in a SQLite database.")
+    ;; TODO: pick the license once the project settles on one.
+    (license license:expat)))
+
+ai-memory
diff --git a/lang.odin b/lang.odin
new file mode 100644
index 0000000..b3a5ff8
--- /dev/null
+++ b/lang.odin
@@ -0,0 +1,196 @@
+package main
+
+import "core:strings"
+
+// Symbol extraction is per-language: the diff only shows text, so each
+// language needs its own idea of what a declaration looks like.
+Lang :: enum {
+	Odin,
+	Rust,
+	Other,
+}
+
+lang_of :: proc(file: string) -> Lang {
+	switch {
+	case strings.has_suffix(file, ".odin"):
+		return .Odin
+	case strings.has_suffix(file, ".rs"):
+		return .Rust
+	}
+	return .Other
+}
+
+// parse_decl reports the declaration NAME and KIND introduced or removed by a
+// single line of a diff, if that line declares something.
+parse_decl :: proc(file, line: string) -> (name: string, kind: string, ok: bool) {
+	switch lang_of(file) {
+	case .Odin:
+		return parse_odin_decl(line)
+	case .Rust:
+		return parse_rust_decl(line)
+	case .Other:
+	}
+	return "", "", false
+}
+
+// -- Odin -------------------------------------------------------------------
+//
+//	NAME :: proc ...            -> proc
+//	NAME :: struct/enum/...     -> type
+//	NAME :: value               -> const
+//	NAME: Type                  -> var (top level only: struct fields are indented)
+//	NAME := value               -> var (top level only)
+parse_odin_decl :: proc(line: string) -> (name: string, kind: string, ok: bool) {
+	indented := len(line) > 0 && (line[0] == ' ' || line[0] == '\t')
+	s := strings.trim_left_space(line)
+	if len(s) == 0 || s[0] == '@' || s[0] == '/' || s[0] == '}' || s[0] == '#' {
+		return "", "", false
+	}
+
+	if sep := strings.index(s, "::"); sep >= 0 {
+		lhs := strings.trim_space(s[:sep])
+		if !is_ident(lhs) {
+			return "", "", false
+		}
+		rhs := strings.trim_space(s[sep + 2:])
+		switch {
+		case strings.has_prefix(rhs, "proc"):
+			return lhs, "proc", true
+		case strings.has_prefix(rhs, "struct"),
+		     strings.has_prefix(rhs, "enum"),
+		     strings.has_prefix(rhs, "union"),
+		     strings.has_prefix(rhs, "bit_set"),
+		     strings.has_prefix(rhs, "distinct"),
+		     strings.has_prefix(rhs, "#type"),
+		     strings.has_prefix(rhs, "map["),
+		     strings.has_prefix(rhs, "matrix["),
+		     strings.has_prefix(rhs, "proc{"):
+			return lhs, "type", true
+		case:
+			return lhs, "const", true
+		}
+	}
+
+	// Globals: only when not indented, otherwise this is a struct field.
+	if indented {
+		return "", "", false
+	}
+	if sep := strings.index(s, ":="); sep > 0 {
+		lhs := strings.trim_space(s[:sep])
+		if is_ident(lhs) {
+			return lhs, "var", true
+		}
+	}
+	if sep := strings.index_byte(s, ':'); sep > 0 {
+		lhs := strings.trim_space(s[:sep])
+		if is_ident(lhs) {
+			return lhs, "var", true
+		}
+	}
+	return "", "", false
+}
+
+// -- Rust -------------------------------------------------------------------
+//
+//	fn NAME / pub fn NAME       -> fn   (methods included; they are indented)
+//	struct/enum/trait/type/mod  -> type
+//	const NAME: / static NAME:  -> const
+parse_rust_decl :: proc(line: string) -> (name: string, kind: string, ok: bool) {
+	s := strings.trim_left_space(line)
+	if len(s) == 0 || s[0] == '/' || s[0] == '#' || s[0] == '}' {
+		return "", "", false
+	}
+
+	// Drop modifiers so that `pub(crate) async unsafe fn` still matches.
+	for {
+		switch {
+		case strings.has_prefix(s, "pub(crate) "):
+			s = strings.trim_left_space(s[len("pub(crate) "):])
+		case strings.has_prefix(s, "pub(super) "):
+			s = strings.trim_left_space(s[len("pub(super) "):])
+		case strings.has_prefix(s, "pub "):
+			s = strings.trim_left_space(s[len("pub "):])
+		case strings.has_prefix(s, "async "):
+			s = strings.trim_left_space(s[len("async "):])
+		case strings.has_prefix(s, "unsafe "):
+			s = strings.trim_left_space(s[len("unsafe "):])
+		case strings.has_prefix(s, "extern "):
+			// `extern "C" fn foo'
+			s = strings.trim_left_space(s[len("extern "):])
+			if len(s) > 0 && s[0] == '"' {
+				if end := strings.index_byte(s[1:], '"'); end >= 0 {
+					s = strings.trim_left_space(s[end + 2:])
+				}
+			}
+		case strings.has_prefix(s, "const fn "):
+			// const fn is a function, not a constant
+			if n, nok := ident_after(s, "const fn "); nok {
+				return n, "fn", true
+			}
+			return "", "", false
+		case strings.has_prefix(s, "default "), strings.has_prefix(s, "unsafe impl "):
+			s = strings.trim_left_space(s[strings.index_byte(s, ' ') + 1:])
+		case:
+		}
+		break
+	}
+
+	entries := [?]struct {
+		prefix: string,
+		kind:   string,
+	}{
+		{"fn ", "fn"},
+		{"struct ", "type"},
+		{"enum ", "type"},
+		{"trait ", "type"},
+		{"type ", "type"},
+		{"mod ", "type"},
+		{"union ", "type"},
+		{"const ", "const"},
+		{"static ", "const"},
+	}
+	for e in entries {
+		if strings.has_prefix(s, e.prefix) {
+			if n, nok := ident_after(s, e.prefix); nok {
+				return n, e.kind, true
+			}
+			return "", "", false
+		}
+	}
+	return "", "", false
+}
+
+// ident_after reads the identifier that follows PREFIX in S.
+ident_after :: proc(s, prefix: string) -> (name: string, ok: bool) {
+	rest := strings.trim_left_space(s[len(prefix):])
+	end := 0
+	for end < len(rest) {
+		c := rest[end]
+		if (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_' {
+			end += 1
+		} else {
+			break
+		}
+	}
+	if end == 0 {
+		return "", false
+	}
+	return rest[:end], true
+}
+
+is_ident :: proc(s: string) -> bool {
+	if len(s) == 0 {
+		return false
+	}
+	for c, i in s {
+		switch {
+		case c == '_':
+		case c >= 'a' && c <= 'z':
+		case c >= 'A' && c <= 'Z':
+		case c >= '0' && c <= '9' && i > 0:
+		case:
+			return false
+		}
+	}
+	return true
+}
diff --git a/main.odin b/main.odin
new file mode 100644
index 0000000..ee0da51
--- /dev/null
+++ b/main.odin
@@ -0,0 +1,843 @@
+package main
+
+import "core:fmt"
+import "core:os"
+import "core:strconv"
+import "core:strings"
+import "core:time"
+
+USAGE :: `ai-memory - project memory for an AI assistant
+
+usage: ai-memory <command> [options]
+
+  init                             create or upgrade the database
+  import [--limit N]               import a whole git history (default: all commits)
+  sync [--limit N]                 import recent commits (default: 200)
+  record --kind K --body TEXT      append a reasoning entry
+         [--session S] [--step N] [--commit HASH|HEAD|none]
+         [--basis HOW] [--supersedes ID]
+  attach <HASH|HEAD> [--session S] link unattached reasoning to a commit
+  why <symbol> [--all]             commits and reasoning that touched a symbol
+  search <text> [--all]            full-text search over reasoning
+                                   (--all also shows superseded entries)
+  log [--limit N]                  recent commits and how much reasoning they carry
+  status                           row counts
+
+global options (before or after the command):
+
+  --repo PATH, -C PATH             work on the git repository at PATH
+  --db PATH                        use PATH for the store instead of the default
+
+The store defaults to <repo>/ai-memory.sqlite; set $AI_MEMORY_DB to override.`
+
+// Set by the global options, before any command runs.
+DB_PATH: string
+
+main :: proc() {
+	args := os.args[1:]
+	if len(args) == 0 {
+		fmt.print(USAGE)
+		return
+	}
+
+	// Peel the global options out, wherever they appear.
+	rest := make([dynamic]string, 0, len(args), context.temp_allocator)
+	i := 0
+	for i < len(args) {
+		a := args[i]
+		name := ""
+		value := ""
+		has_value := false
+
+		switch {
+		case a == "--repo", a == "-C":
+			name = "--repo"
+		case a == "--db":
+			name = "--db"
+		case strings.has_prefix(a, "--repo="):
+			name = "--repo"
+			value = a[len("--repo="):]
+			has_value = true
+		case strings.has_prefix(a, "--db="):
+			name = "--db"
+			value = a[len("--db="):]
+			has_value = true
+		}
+
+		if len(name) == 0 {
+			append(&rest, a)
+			i += 1
+			continue
+		}
+		if !has_value {
+			if i + 1 >= len(args) {
+				fmt.eprintfln("ai-memory: %s needs a value", name)
+				os.exit(1)
+			}
+			value = args[i + 1]
+			i += 2
+		} else {
+			i += 1
+		}
+
+		if name == "--db" {
+			DB_PATH = value
+		} else {
+			REPO_DIR = value
+		}
+	}
+
+	args = rest[:]
+
+	if len(REPO_DIR) > 0 {
+		if _, err := os.stat(REPO_DIR, context.temp_allocator); err != nil {
+			fmt.eprintfln("ai-memory: no such repository directory: %s", REPO_DIR)
+			os.exit(1)
+		}
+	}
+
+	if len(args) == 0 {
+		fmt.print(USAGE)
+		return
+	}
+
+	ok: bool
+	switch args[0] {
+	case "init":
+		ok = cmd_init()
+	case "import":
+		ok = cmd_sync(args[1:], 0)
+	case "sync":
+		ok = cmd_sync(args[1:], 200)
+	case "record":
+		ok = cmd_record(args[1:])
+	case "attach":
+		ok = cmd_attach(args[1:])
+	case "why":
+		ok = cmd_why(args[1:])
+	case "search":
+		ok = cmd_search(args[1:])
+	case "log":
+		ok = cmd_log(args[1:])
+	case "status":
+		ok = cmd_status()
+	case "help", "--help", "-h":
+		fmt.print(USAGE)
+		ok = true
+	case:
+		fmt.eprintfln("ai-memory: unknown command %q", args[0])
+		fmt.print(USAGE)
+		ok = false
+	}
+	if !ok {
+		os.exit(1)
+	}
+}
+
+// ---- commands -------------------------------------------------------------
+
+cmd_init :: proc() -> bool {
+	db, ok := open_db()
+	if !ok {
+		return false
+	}
+	defer db_close(&db)
+	fmt.printfln("store ready at %s", db_path())
+	return true
+}
+
+cmd_sync :: proc(args: []string, default_limit: int) -> bool {
+	limit := parse_int(flag_or(args, "--limit", fmt.tprintf("%d", default_limit)), default_limit)
+
+	db, ok := open_db()
+	if !ok {
+		return false
+	}
+	defer db_close(&db)
+
+	commits, ok_log := git_log(limit)
+	if !ok_log {
+		return false
+	}
+	if len(commits) == 0 {
+		fmt.println("no commits to import")
+		return true
+	}
+
+	n_commit, n_touch: int
+	db_exec(&db, "begin")
+	for c in commits {
+		if !insert_commit(&db, c) {
+			db_exec(&db, "rollback")
+			return false
+		}
+		n_commit += 1
+
+		decls, ok_decls := git_touched(c.hash)
+		if !ok_decls {
+			db_exec(&db, "rollback")
+			return false
+		}
+		for d in decls {
+			if insert_touch(&db, c.hash, d) {
+				n_touch += 1
+			}
+		}
+	}
+	if !db_exec(&db, "commit") {
+		return false
+	}
+
+	fmt.printfln("synced %d commits, %d symbol touches", n_commit, n_touch)
+	return true
+}
+
+cmd_record :: proc(args: []string) -> bool {
+	kind := flag_or(args, "--kind", "thought")
+
+	body, has_body := flag(args, "--body")
+	if !has_body {
+		data, err := os.read_entire_file_from_file(os.stdin, context.temp_allocator)
+		if err != nil || len(data) == 0 {
+			fmt.eprintln("ai-memory: record needs --body TEXT (or text on stdin)")
+			return false
+		}
+		body = strings.trim_space(string(data))
+	}
+	if len(body) == 0 {
+		fmt.eprintln("ai-memory: refusing to record an empty body")
+		return false
+	}
+
+	session := flag_or(args, "--session", "")
+	step := parse_int(flag_or(args, "--step", "-1"), -1)
+
+	// How the claim was established, e.g. "read at src/lib.rs:120-140".
+	// Facts and inferences look the same in prose; this keeps them apart.
+	basis := flag_or(args, "--basis", "")
+
+	// Corrections point at the entry they replace rather than rewriting it.
+	supersedes := parse_int(flag_or(args, "--supersedes", "-1"), -1)
+
+	// Reasoning may predate the commit: --commit none leaves it unattached.
+	commit := ""
+	has_commit := false
+	switch c := flag_or(args, "--commit", "HEAD"); c {
+	case "none", "":
+		has_commit = false
+	case "HEAD":
+		if h, hok := head_commit(); hok {
+			commit = h
+			has_commit = true
+		}
+	case:
+		commit = c
+		has_commit = true
+	}
+
+	db, ok := open_db()
+	if !ok {
+		return false
+	}
+	defer db_close(&db)
+
+	// The commit may be newer than the last sync; the FK on reasoning.commit_hash
+	// requires the row to exist, so import it on demand.
+	if has_commit && !ensure_commit(&db, commit) {
+		return false
+	}
+
+	s, sok := stmt(&db, `insert or ignore into reasoning
+	                       (commit_hash, session_id, step, created_at, kind,
+	                        basis, supersedes, body)
+	                     values (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)`)
+	if !sok {
+		return false
+	}
+	defer stmt_close(&s)
+
+	if has_commit {
+		stmt_bind_text(&s, 1, commit)
+	} else {
+		stmt_bind_null(&s, 1)
+	}
+	if len(session) > 0 {
+		stmt_bind_text(&s, 2, session)
+	} else {
+		stmt_bind_null(&s, 2)
+	}
+	if step >= 0 {
+		stmt_bind_i64(&s, 3, i64(step))
+	} else {
+		stmt_bind_null(&s, 3)
+	}
+	stmt_bind_i64(&s, 4, time.time_to_unix(time.now()))
+	stmt_bind_text(&s, 5, kind)
+	if len(basis) > 0 {
+		stmt_bind_text(&s, 6, basis)
+	} else {
+		stmt_bind_null(&s, 6)
+	}
+	if supersedes >= 0 {
+		stmt_bind_i64(&s, 7, i64(supersedes))
+	} else {
+		stmt_bind_null(&s, 7)
+	}
+	stmt_bind_text(&s, 8, body)
+
+	if stmt_step(&s) != .Done {
+		return false
+	}
+	if has_commit {
+		fmt.printfln("recorded %s on %s", kind, short_hash(commit))
+	} else {
+		fmt.printfln("recorded %s (not attached to a commit yet)", kind)
+	}
+	return true
+}
+
+// cmd_attach links reasoning that was written before its commit existed.
+cmd_attach :: proc(args: []string) -> bool {
+	hash, found := first_positional(args)
+	if !found {
+		fmt.eprintln("ai-memory: attach needs a commit hash (or HEAD)")
+		return false
+	}
+	if hash == "HEAD" {
+		if h, hok := head_commit(); hok {
+			hash = h
+		} else {
+			fmt.eprintln("ai-memory: no HEAD to attach to")
+			return false
+		}
+	}
+	session := flag_or(args, "--session", "")
+
+	db, ok := open_db()
+	if !ok {
+		return false
+	}
+	defer db_close(&db)
+
+	query := "update reasoning set commit_hash = ?1 where commit_hash is null"
+	if len(session) > 0 {
+		query = "update reasoning set commit_hash = ?1 where commit_hash is null and session_id = ?2"
+	}
+	if !ensure_commit(&db, hash) {
+		return false
+	}
+	s, sok := stmt(&db, query)
+	if !sok {
+		return false
+	}
+	defer stmt_close(&s)
+	stmt_bind_text(&s, 1, hash)
+	if len(session) > 0 {
+		stmt_bind_text(&s, 2, session)
+	}
+	if stmt_step(&s) != .Done {
+		return false
+	}
+	fmt.printfln("attached %d reasoning entries to %s",
+	             int(sqlite_changes(&db)), short_hash(hash))
+	return true
+}
+
+cmd_why :: proc(args: []string) -> bool {
+	show_all := flag_bool(args, "--all")
+	name, found := first_positional(args)
+	if !found {
+		fmt.eprintln("ai-memory: why needs a symbol, e.g. `ai-memory why main.open_store'")
+		return false
+	}
+
+	db, ok := open_db()
+	if !ok {
+		return false
+	}
+	defer db_close(&db)
+
+	rows := lookup_touches(&db, name)
+	if len(rows) == 0 {
+		fmt.printfln("no commits touch %q", name)
+		return true
+	}
+	for row in rows {
+		fmt.printfln("%s  %s  %s  [%s %s, %s]",
+		             short_hash(row.commit_hash), fmt_ts(row.author_ts),
+		             row.subject, row.kind, row.symbol, row.change)
+		print_reasoning(reasoning_for(&db, row.commit_hash), show_all)
+	}
+	return true
+}
+
+cmd_search :: proc(args: []string) -> bool {
+	text, found := first_positional(args)
+	if !found {
+		fmt.eprintln("ai-memory: search needs a query")
+		return false
+	}
+	show_all := flag_bool(args, "--all")
+
+	db, ok := open_db()
+	if !ok {
+		return false
+	}
+	defer db_close(&db)
+
+	s, sok := stmt(&db, `select r.id, r.kind, r.basis, r.body, r.created_at, c.subject,
+	                         (select min(s.id) from reasoning s where s.supersedes = r.id)
+	                     from reasoning_fts f
+	                       join reasoning r on r.id = f.rowid
+	                       left join commits c on c.hash = r.commit_hash
+	                     where reasoning_fts match ?1
+	                     order by r.created_at desc
+	                     limit 20`)
+	if !sok {
+		return false
+	}
+	defer stmt_close(&s)
+	stmt_bind_text(&s, 1, text)
+
+	n := 0
+	hidden := 0
+	for {
+		rc := stmt_step(&s)
+		if rc == .Done {
+			break
+		}
+		if rc != .Row {
+			return false
+		}
+		n += 1
+		r := Reasoning_Row{
+			id = stmt_col_i64(&s, 0),
+			kind = stmt_col_text(&s, 1),
+			basis = stmt_col_text(&s, 2),
+			body = stmt_col_text(&s, 3),
+			superseded_by = stmt_col_i64(&s, 6),
+		}
+		if r.superseded_by != 0 && !show_all {
+			hidden += 1
+			continue
+		}
+		label := fmt.tprintf("%s  #%d %s", fmt_ts(stmt_col_i64(&s, 4)), r.id, r.kind)
+		if len(r.basis) > 0 {
+			label = fmt.tprintf("%s (%s)", label, r.basis)
+		}
+		if r.superseded_by != 0 {
+			label = fmt.tprintf("%s [superseded by #%d]", label, r.superseded_by)
+		}
+		fmt.printfln("%s: %s", label, indent_rest(r.body))
+		subject := stmt_col_text(&s, 5)
+		if len(subject) > 0 {
+			fmt.printfln("    on %s", subject)
+		}
+	}
+	if n == 0 {
+		fmt.printfln("nothing matches %q", text)
+	} else if hidden > 0 && !show_all {
+		fmt.printfln("(%d superseded match(es) hidden; --all shows them)", hidden)
+	}
+	return true
+}
+
+cmd_log :: proc(args: []string) -> bool {
+	limit := parse_int(flag_or(args, "--limit", "20"), 20)
+
+	db, ok := open_db()
+	if !ok {
+		return false
+	}
+	defer db_close(&db)
+
+	// A correlated count rather than a GROUP BY, so SQLite can walk
+	// commit_ts_idx backwards and stop after LIMIT rows instead of sorting the
+	// whole history.
+	s, sok := stmt(&db, `select c.hash, c.author_ts, c.subject,
+	                          (select count(*) from reasoning r
+	                           where r.commit_hash = c.hash)
+	                   from commits c
+	                   order by c.author_ts desc
+	                   limit ?1`)
+	if !sok {
+		return false
+	}
+	defer stmt_close(&s)
+	stmt_bind_i64(&s, 1, i64(limit))
+
+	for {
+		rc := stmt_step(&s)
+		if rc == .Done {
+			break
+		}
+		if rc != .Row {
+			return false
+		}
+		fmt.printfln("%s  %s  %s  (%d)",
+		             short_hash(stmt_col_text(&s, 0)), fmt_ts(stmt_col_i64(&s, 1)),
+		             stmt_col_text(&s, 2), stmt_col_i64(&s, 3))
+	}
+	return true
+}
+
+cmd_status :: proc() -> bool {
+	db, ok := open_db()
+	if !ok {
+		return false
+	}
+	defer db_close(&db)
+
+	tables := [?]string{"commits", "symbols", "touches", "reasoning"}
+	for table in tables {
+		fmt.printfln("%s: %d", table, count_rows(&db, table))
+	}
+	return true
+}
+
+// ---- queries --------------------------------------------------------------
+
+Touch_Row :: struct {
+	commit_hash: string,
+	author_ts:   i64,
+	subject:     string,
+	symbol:      string,
+	kind:        string,
+	file:        string,
+	change:      string,
+}
+
+Reasoning_Row :: struct {
+	id:            i64,
+	kind:          string,
+	basis:         string,
+	body:          string,
+	superseded_by: i64, // 0 when the entry still stands
+}
+
+TOUCH_QUERY :: `select c.hash, c.author_ts, c.subject, s.name, s.kind, s.file, t.change
+                from touches t
+                  join symbols s on s.id = t.symbol_id
+                  join commits c on c.hash = t.commit_hash
+                where %s
+                order by c.author_ts desc`
+
+// lookup_touches tries an exact symbol name first, then a suffix match so that
+// `why open_store' works without the file qualifier.
+// lookup_touches tries the qualified name, then the bare identifier (an index
+// seek on symbols.basename), and only then a substring scan.
+lookup_touches :: proc(db: ^Db, name: string) -> []Touch_Row {
+	exact := run_touches(db, fmt.tprintf(TOUCH_QUERY, "s.name = ?1"), name)
+	if len(exact) > 0 {
+		return exact
+	}
+	by_basename := run_touches(db, fmt.tprintf(TOUCH_QUERY, "s.basename = ?1"), name)
+	if len(by_basename) > 0 {
+		return by_basename
+	}
+	return run_touches(db, fmt.tprintf(TOUCH_QUERY, "s.name like ?1"),
+	                   fmt.tprintf("%%%s", name))
+}
+
+run_touches :: proc(db: ^Db, query, name: string) -> []Touch_Row {
+	s, ok := stmt(db, query)
+	if !ok {
+		return nil
+	}
+	defer stmt_close(&s)
+	stmt_bind_text(&s, 1, name)
+
+	rows := make([dynamic]Touch_Row, 0, 16)
+	for {
+		rc := stmt_step(&s)
+		if rc == .Done {
+			break
+		}
+		if rc != .Row {
+			return rows[:]
+		}
+		append(&rows, Touch_Row{
+			commit_hash = stmt_col_text(&s, 0),
+			author_ts   = stmt_col_i64(&s, 1),
+			subject     = stmt_col_text(&s, 2),
+			symbol      = stmt_col_text(&s, 3),
+			kind        = stmt_col_text(&s, 4),
+			file        = stmt_col_text(&s, 5),
+			change      = stmt_col_text(&s, 6),
+		})
+	}
+	return rows[:]
+}
+
+// reasoning_for returns the reasoning attached to a commit.  SUPERSEDED_BY is
+// the id of the entry that replaced this one, or 0.
+reasoning_for :: proc(db: ^Db, commit_hash: string) -> []Reasoning_Row {
+	s, ok := stmt(db, `select r.id, r.kind, r.basis, r.body,
+	                         (select min(s.id) from reasoning s
+	                          where s.supersedes = r.id)
+	                  from reasoning r
+	                  where r.commit_hash = ?1
+	                  order by r.created_at, r.id`)
+	if !ok {
+		return nil
+	}
+	defer stmt_close(&s)
+	stmt_bind_text(&s, 1, commit_hash)
+
+	rows := make([dynamic]Reasoning_Row, 0, 4)
+	for {
+		rc := stmt_step(&s)
+		if rc == .Done {
+			break
+		}
+		if rc != .Row {
+			return rows[:]
+		}
+		append(&rows, Reasoning_Row{
+			id = stmt_col_i64(&s, 0),
+			kind = stmt_col_text(&s, 1),
+			basis = stmt_col_text(&s, 2),
+			body = stmt_col_text(&s, 3),
+			superseded_by = stmt_col_i64(&s, 4),
+		})
+	}
+	return rows[:]
+}
+
+// print_reasoning renders entries.  A superseded entry is reduced to its id and
+// its replacement unless SHOW_ALL is set: the correction is what stands, but the
+// fact that a claim was made and replaced stays visible.
+print_reasoning :: proc(rows: []Reasoning_Row, show_all: bool) {
+	for r in rows {
+		if r.superseded_by != 0 && !show_all {
+			fmt.printfln("    #%d %s [superseded by #%d]", r.id, r.kind, r.superseded_by)
+			continue
+		}
+		label := fmt.tprintf("#%d %s", r.id, r.kind)
+		if len(r.basis) > 0 {
+			label = fmt.tprintf("%s (%s)", label, r.basis)
+		}
+		if r.superseded_by != 0 {
+			label = fmt.tprintf("%s [superseded by #%d]", label, r.superseded_by)
+		}
+		fmt.printfln("    %s: %s", label, indent_rest(r.body))
+	}
+}
+
+// TABLE always comes from cmd_status, never from user input.
+count_rows :: proc(db: ^Db, table: string) -> i64 {
+	s, ok := stmt(db, fmt.tprintf("select count(*) from %s", table))
+	if !ok {
+		return 0
+	}
+	defer stmt_close(&s)
+	if stmt_step(&s) != .Row {
+		return 0
+	}
+	return stmt_col_i64(&s, 0)
+}
+
+// ---- writes ---------------------------------------------------------------
+
+insert_commit :: proc(db: ^Db, c: Git_Commit) -> bool {
+	s, ok := stmt(db, `insert into commits (hash, author_ts, subject, body)
+	                   values (?1, ?2, ?3, ?4)
+	                   on conflict (hash) do update set
+	                     author_ts = excluded.author_ts,
+	                     subject   = excluded.subject,
+	                     body      = excluded.body`)
+	if !ok {
+		return false
+	}
+	defer stmt_close(&s)
+	stmt_bind_text(&s, 1, c.hash)
+	stmt_bind_i64(&s, 2, c.author_ts)
+	stmt_bind_text(&s, 3, c.subject)
+	if len(c.body) > 0 {
+		stmt_bind_text(&s, 4, c.body)
+	} else {
+		stmt_bind_null(&s, 4)
+	}
+	return stmt_step(&s) == .Done
+}
+
+// ensure_commit makes sure a commit row exists, importing it from git when
+// reasoning or an attachment refers to a commit that `sync' has not seen yet.
+ensure_commit :: proc(db: ^Db, hash: string) -> bool {
+	s, ok := stmt(db, "select 1 from commits where hash = ?1")
+	if !ok {
+		return false
+	}
+	stmt_bind_text(&s, 1, hash)
+	exists := stmt_step(&s) == .Row
+	stmt_close(&s)
+	if exists {
+		return true
+	}
+
+	c, found := git_commit(hash)
+	if !found {
+		fmt.eprintfln("ai-memory: %s is not a commit in %s", short_hash(hash),
+		              repo_label())
+		return false
+	}
+	if !insert_commit(db, c) {
+		return false
+	}
+	fmt.printfln("imported %s (%s)", short_hash(c.hash), c.subject)
+	return true
+}
+
+
+// repo_label names the repository for messages.
+repo_label :: proc() -> string {
+	if len(REPO_DIR) > 0 {
+		return REPO_DIR
+	}
+	return "the current directory"
+}
+
+insert_touch :: proc(db: ^Db, commit_hash: string, d: Decl) -> bool {
+	name := symbol_name(d.file, d.name)
+
+	s, ok := stmt(db, `insert into symbols (name, basename, file, kind)
+	                   values (?1, ?2, ?3, ?4)
+	                   on conflict (name) do update set
+	                     basename = excluded.basename,
+	                     file     = excluded.file,
+	                     kind     = excluded.kind
+	                   returning id`)
+	if !ok {
+		return false
+	}
+	defer stmt_close(&s)
+	stmt_bind_text(&s, 1, name)
+	// d.name is the bare identifier, i.e. the part after the qualifier.
+	stmt_bind_text(&s, 2, d.name)
+	if len(d.file) > 0 {
+		stmt_bind_text(&s, 3, d.file)
+	} else {
+		stmt_bind_null(&s, 3)
+	}
+	stmt_bind_text(&s, 4, d.kind)
+	if stmt_step(&s) != .Row {
+		return false
+	}
+	symbol_id := stmt_col_i64(&s, 0)
+
+	t, tok := stmt(db, `insert or ignore into touches (commit_hash, symbol_id, change)
+	                    values (?1, ?2, ?3)`)
+	if !tok {
+		return false
+	}
+	defer stmt_close(&t)
+	stmt_bind_text(&t, 1, commit_hash)
+	stmt_bind_i64(&t, 2, symbol_id)
+	stmt_bind_text(&t, 3, change_of(d))
+	return stmt_step(&t) == .Done
+}
+
+// ---- helpers --------------------------------------------------------------
+
+open_db :: proc() -> (db: Db, ok: bool) {
+	path := db_path()
+	db, ok = db_open(path)
+	if !ok {
+		return {}, false
+	}
+	if !db_migrate(&db) {
+		db_close(&db)
+		return {}, false
+	}
+	return db, true
+}
+
+db_path :: proc() -> string {
+	if len(DB_PATH) > 0 {
+		return DB_PATH
+	}
+	if p := os.get_env("AI_MEMORY_DB", context.temp_allocator); len(p) > 0 {
+		return p
+	}
+	if len(REPO_DIR) > 0 {
+		return fmt.tprintf("%s/ai-memory.sqlite", REPO_DIR)
+	}
+	return DEFAULT_DB_PATH
+}
+
+head_commit :: proc() -> (hash: string, ok: bool) {
+	out, good := git([]string{"rev-parse", "--verify", "HEAD"}, context.temp_allocator, false)
+	if !good {
+		return "", false
+	}
+	hash = strings.trim_space(out)
+	return hash, len(hash) > 0
+}
+
+short_hash :: proc(hash: string) -> string {
+	if len(hash) <= 7 {
+		return hash
+	}
+	return hash[:7]
+}
+
+fmt_ts :: proc(ts: i64) -> string {
+	t := time.unix(ts, 0)
+	s, ok := time.time_to_rfc3339(t, 0, false, context.temp_allocator)
+	if !ok {
+		return fmt.tprintf("%d", ts)
+	}
+	return s
+}
+
+// indent_rest keeps multi-line reasoning readable under its commit line.
+indent_rest :: proc(s: string) -> string {
+	out, _ := strings.replace_all(s, "\n", "\n        ", context.temp_allocator)
+	return out
+}
+
+flag :: proc(args: []string, name: string) -> (value: string, found: bool) {
+	for a, i in args {
+		if a == name && i + 1 < len(args) {
+			return args[i + 1], true
+		}
+		if strings.has_prefix(a, name) && len(a) > len(name) && a[len(name)] == '=' {
+			return a[len(name) + 1:], true
+		}
+	}
+	return "", false
+}
+
+flag_or :: proc(args: []string, name, default_value: string) -> string {
+	if v, found := flag(args, name); found {
+		return v
+	}
+	return default_value
+}
+
+first_positional :: proc(args: []string) -> (value: string, found: bool) {
+	for a in args {
+		if !strings.has_prefix(a, "-") {
+			return a, true
+		}
+	}
+	return "", false
+}
+
+parse_int :: proc(s: string, default_value: int) -> int {
+	if v, ok := strconv.parse_int(s, 10); ok {
+		return v
+	}
+	return default_value
+}
+
+// flag_bool reports whether a valueless flag was given.
+flag_bool :: proc(args: []string, name: string) -> bool {
+	for a in args {
+		if a == name {
+			return true
+		}
+	}
+	return false
+}
+
diff --git a/schema.sql b/schema.sql
new file mode 100644
index 0000000..ecdbe1d
--- /dev/null
+++ b/schema.sql
@@ -0,0 +1,75 @@
+-- ai-memory schema, version 3.
+--
+-- commits  : one row per git commit, derived from `git log' by `sync'.
+-- symbols  : one declared identifier per row (proc, fn, type, const, var).
+-- touches  : which symbols a commit added, modified, removed or enclosed.
+-- reasoning: appends the *why*; may exist before the commit does, in which
+--            case commit_hash is NULL until `attach' sets it.  `basis' records
+--            how the entry was established; `supersedes' points at the entry a
+--            correction replaces, so nothing is ever overwritten.
+
+create table if not exists commits (
+	hash      text primary key,
+	author_ts integer not null,
+	subject   text not null,
+	body      text
+);
+
+create table if not exists symbols (
+	id       integer primary key,
+	name     text not null unique,   -- qualified: <file base>.<identifier>
+	basename text,                   -- the bare identifier, indexed for lookups
+	file     text,
+	kind     text not null           -- proc | fn | type | const | var
+);
+
+create table if not exists touches (
+	commit_hash text not null references commits(hash) on delete cascade,
+	symbol_id   integer not null references symbols(id),
+	change      text not null,   -- add | mod | remove
+	primary key (commit_hash, symbol_id, change)
+);
+
+create table if not exists reasoning (
+	id          integer primary key,
+	commit_hash text references commits(hash) on delete cascade,
+	session_id  text,
+	step        integer,
+	created_at  integer not null,
+	kind        text not null,   -- thought | conclusion | question
+	-- How the entry was established: "read at src/lib.rs:120-140",
+	-- "from commit message", "measured on the bulklmm instance", ...
+	basis       text,
+	-- A correction points at the entry it replaces instead of editing it.
+	supersedes  integer references reasoning(id),
+	body        text not null,
+	unique (session_id, step, kind)
+);
+
+create index if not exists reasoning_superseded_idx on reasoning (supersedes);
+
+create index if not exists touch_symbol_idx on touches (symbol_id);
+create index if not exists reasoning_commit_idx on reasoning (commit_hash);
+-- Unqualified lookups (`why open_store') are an index seek, not a LIKE scan.
+create index if not exists symbol_basename_idx on symbols (basename);
+-- `log' walks commits newest-first; the index lets it stop after LIMIT rows.
+create index if not exists commit_ts_idx on commits (author_ts);
+
+create virtual table if not exists reasoning_fts using fts5 (
+	body, content = 'reasoning', content_rowid = 'id'
+);
+
+create trigger if not exists reasoning_after_insert after insert on reasoning begin
+	insert into reasoning_fts (rowid, body) values (new.id, new.body);
+end;
+
+create trigger if not exists reasoning_after_delete after delete on reasoning begin
+	insert into reasoning_fts (reasoning_fts, rowid, body) values ('delete', old.id, old.body);
+end;
+
+create trigger if not exists reasoning_after_update after update on reasoning begin
+	insert into reasoning_fts (reasoning_fts, rowid, body) values ('delete', old.id, old.body);
+	insert into reasoning_fts (rowid, body) values (new.id, new.body);
+end;
+
+pragma user_version = 3;