about summary refs log tree commit diff
diff options
context:
space:
mode:
authorPjotr Prins <pjotr.public01@thebird.nl>2026-11-16 16:35:24 +0000
committerPjotr Prins <pjotr.public01@thebird.nl>2026-11-16 16:35:24 +0000
commitd5e90011f764ba27251936d4fa628e1100145773 (patch)
tree0f671a2b19bb24af91201776746b8e6d511eb95b
parentdc4c16203674191c4821b2f7b53e01febb7a11a6 (diff)
downloadai-memory-d5e90011f764ba27251936d4fa628e1100145773.tar.gz
symbols: C and C++ declarations from ctags, diffed between blobs
C and C++ were the one language family where the store could only say "a hunk
landed inside this function". A diff line cannot be read for declarations
there: inside a body `foo(bar);` calls something, inside a class body the same
bytes declare a constructor, and pangemma indents both the same way (of 248538
changed lines in its history, 14991 are indented `name(` lines, and the most
frequent are calls). So the file is handed to universal-ctags and the tags of a
commit's blob are diffed against its parent's: present only in the new blob is
an add, only in the old one is a remove, and a name whose tag survives both is
left to hunk context, which is the honest answer for "the change was inside
this".

The cost is bounded by a cache keyed by git object id (new table `blobs`): a
blob's tags can never change, so each file version is parsed once per store.
On the pangemma history (688 commits, 1163 distinct C/C++ blobs) the first full
pass takes 26 s and touches go from 1404 context-only rows to 6888 add, 5125
remove, 1505 context; the second pass takes 11 s and runs no ctags at all.

ctags is optional at run time. Without it the store behaves exactly as before
and `sync` says so once. The Guix package bakes its absolute path into
$AI_MEMORY_CTAGS through wrap-program, and the check phase now builds a
two-commit git repository with one C++ file to prove it end to end: the
function added in the second commit is `add`, the one whose body changed is
`context`.

Details found by running it on a real history, all in this commit:

- lambdas are tagged by default under names ctags derives from a hash of the
  file (`__anon426fc91f0102`), so every touched file reported seven functions
  added and seven removed per commit; `--extras=-{anonymous}` turns them off.
- `--kinds-C++=+p` is needed or prototypes are invisible and a declaration in a
  header would never be seen.
- include guards (`#define CALC_H`, `#define __CALC_H__`) are filtered: they are
  bookkeeping, while other macros are kept as `const`.
- merge_decl keyed a commit's declarations by bare identifier, so two files
  declaring the same name in one commit collided and one lost its attribution.
  It is keyed by (file, name) now -- a bug that applied to Odin and Rust too.
-rw-r--r--README.md11
-rw-r--r--db.odin8
-rw-r--r--doc/SKILL.md35
-rw-r--r--git.odin397
-rw-r--r--guix.scm62
-rw-r--r--lang.odin52
-rw-r--r--main.odin2
-rw-r--r--schema.sql14
8 files changed, 560 insertions, 21 deletions
diff --git a/README.md b/README.md
index 772c8df..01be428 100644
--- a/README.md
+++ b/README.md
@@ -22,7 +22,7 @@ ai-memory -C REPO log           # recent commits, and how much reasoning each ca
 | 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) |
+| `symbols` + `touches` | derived | every declaration a commit added, removed, or merely *enclosed* (hunk context) |
 | `reasoning` | **authored** | append-only thoughts, conclusions and questions, each with its basis and an optional `supersedes` link |
 
 `sync` owns the derived rows; only the `reasoning` table is written by hand
@@ -53,6 +53,15 @@ first build is not quick (Guix does not substitute Odin). For hacking on it,
 the header of `guix.scm` lists the `odin build` line the package uses, and
 `guix shell -D -f guix.scm -- odin version` gets you a compiler shell.
 
+A C or C++ declaration cannot be read off a diff line -- inside a body
+`foo(bar);` calls something, inside a class body the same bytes declare a
+constructor -- so those files are handed to `universal-ctags`, and the tags of a
+commit's blob are diffed against its parent's to say what was added or removed.
+That is an optional runtime dependency: without `ctags` on the box (or in
+`$AI_MEMORY_CTAGS`) the store still works, C and C++ files simply keep hunk
+context and get no add/remove.  Each blob version is parsed once and cached by
+its git object id, so re-syncing an imported history runs no ctags at all.
+
 The optional topic index shells out to a small Guile program
 (`scripts/index.scm`) because `libxapian` is C++-only and
 [guile-xapian](https://git.systemreboot.net/guile-xapian/) already ships the C++
diff --git a/db.odin b/db.odin
index dc10cab..9fd1a9c 100644
--- a/db.odin
+++ b/db.odin
@@ -274,6 +274,14 @@ db_migrate :: proc(db: ^Db) -> bool {
 		version = 5
 	}
 
+	// Version 6: the blobs table, the C/C++ declaration cache.  SCHEMA creates it
+	// with `create table if not exists', so this step only moves the stamp -- but
+	// it still has to exist, or an older binary would go on writing a store that
+	// a newer one had already added the table to, without ever saying so.
+	if version == 5 {
+		version = 6
+	}
+
 	// Only ever move the stamp forward.  Writing it unconditionally is how the
 	// downgrade happened: a binary that knows no steps past v3 still stamped 3.
 	if version > started_at {
diff --git a/doc/SKILL.md b/doc/SKILL.md
index 41b0af9..0450e08 100644
--- a/doc/SKILL.md
+++ b/doc/SKILL.md
@@ -11,7 +11,7 @@ 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) |
+| `symbols` + `touches` | derived | every declaration a commit added, 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.
@@ -42,8 +42,14 @@ guix shell -D -f guix.scm -- odin build . -out:bin/ai-memory -vet -strict-style
 ```
 
 `guix build -f guix.scm` also runs the package's check phase, which builds a
-throwaway store, records an entry, indexes it and queries it -- that is what
-proves the Guile side is wired up.
+throwaway store, records an entry, indexes it, queries it, and then makes a
+two-commit git repository holding one C++ file to prove the ctags half (an added
+function is `add`, a changed body is `context`).
+
+`universal-ctags` is what turns C and C++ files into symbols; the Guix package
+bakes its absolute path into `$AI_MEMORY_CTAGS`, so nothing depends on PATH.  If
+the binary is missing the store still works -- C and C++ simply keep hunk
+context and get no `add`/`remove` -- and `sync` says so once on stderr.
 
 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
@@ -248,9 +254,26 @@ nothing.  Amending *before* recording is cheaper than repairing afterwards.
 
 - `[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.
+- Declarations come from three places: a line scanner for `.odin` and `.rs`, and
+  for C and C++ (`.c .h .cc .cpp .cxx .hpp .hh .hxx .ipp .tpp .inl`)
+  `universal-ctags` over the file itself, diffed between the commit's blob and
+  its parent's -- which is why a C++ `add` means the declaration is new, not that
+  a line mentioning it moved.  Everything else still gets hunk-context symbols
+  (`[fn name, context]`) thanks to git's userdiff drivers, so "which function was
+  I in" works for Python, Go, … too.
+- The ctags pass is cached per git blob (table `blobs`), keyed by object id: a
+  file version is parsed once per store, and re-syncing an imported history runs
+  no ctags at all.  Dropping the table only costs time.
+- C and C++ keep their extension in the symbol name
+  (`lmm.cpp.mdb_analyze`), so a declaration in a header and the definition in the
+  source are two symbols that `why compute_maf` shows side by side.  Directories
+  are still stripped, so a file that moved between directories reads as the same
+  symbol (that collision predates ctags and applies to every language).
+- Kinds are the same five as everywhere else: `fn` for functions, prototypes and
+  methods; `type` for class, struct, union, enum, typedef; `const` for macros
+  except include guards; `var` for file-scope variables.  Class members,
+  enumerators, lambdas and namespaces are deliberately not tags here -- they churn
+  without changing what a hunk was about.
 - `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.
diff --git a/git.odin b/git.odin
index 27a64cb..f8e0c02 100644
--- a/git.odin
+++ b/git.odin
@@ -100,10 +100,12 @@ git_log :: proc(limit: int) -> ([]Git_Commit, bool) {
 	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) {
+// git_touched reports the symbols commit HASH touched, from three sources:
+// declarations that appear or disappear on +/- lines (Odin, Rust), declarations
+// diffed between file blobs by ctags (C, C++), and the enclosing item named in
+// each hunk header (git's userdiff patterns, so no parsing needed).  DB is the
+// store whose blob cache the ctags pass reads and fills; nil disables it.
+git_touched :: proc(hash: string, db: ^Db = nil) -> ([]Decl, bool) {
 	raw, ok := git([]string{"show", "--unified=0", "--no-color", "--no-renames",
 	                        "--format=", "--no-ext-diff", hash})
 	if !ok {
@@ -144,6 +146,18 @@ git_touched :: proc(hash: string) -> ([]Decl, bool) {
 		}
 	}
 
+	if db != nil {
+		// C-family declarations are not readable off a line, so they come from
+		// the file blobs -- see c_family_decls.
+		cdecls, cok := c_family_decls(db, hash)
+		if !cok {
+			return nil, false
+		}
+		for d in cdecls {
+			merge_decl(&found, d)
+		}
+	}
+
 	decls := make([dynamic]Decl, 0, len(found))
 	for _, d in found {
 		append(&decls, d)
@@ -151,6 +165,372 @@ git_touched :: proc(hash: string) -> ([]Decl, bool) {
 	return decls[:], true
 }
 
+// ---- C and C++ declarations, from universal-ctags ---------------------------
+//
+// A C-family declaration cannot be read off a diff line: inside a function body
+// `foo(bar);' calls something, inside a class body the same bytes declare a
+// constructor, and both are indented the same way.  So the file itself is handed
+// to ctags -- a real parser -- and the *sets* of declarations in the parent blob
+// and the new blob are compared; what is only in the new one was added, what is
+// only in the old one was removed.  A name whose tag survives both is left to
+// hunk context, which is the honest answer for "the change was inside this".
+//
+// The cost is bounded by caching: a blob's tags are stored under its git object
+// id, and a blob never changes, so each file version is parsed once per store
+// however many commits mention it.  Re-syncing an imported history runs no ctags
+// at all.
+
+// ctags_path returns the ctags to run: $AI_MEMORY_CTAGS (the Guix package bakes
+// in an absolute path, so this does not depend on PATH), else `ctags'.
+ctags_path :: proc() -> string {
+	if env := os.get_env("AI_MEMORY_CTAGS", context.temp_allocator); len(env) > 0 {
+		return env
+	}
+	return "ctags"
+}
+
+// CTAGS_MISSING keeps the warning to one line: ctags is optional, and a missing
+// binary must not turn every sync into a wall of text.
+CTAGS_MISSING: bool
+
+// Blob_Change is one file in `git show --raw': the path, and the object ids
+// before and after.  An all-zero id means the file did not exist on that side.
+Blob_Change :: struct {
+	path: string,
+	old:  string,
+	new:  string,
+}
+
+// raw_changes lists the file-level changes of HASH.
+raw_changes :: proc(hash: string) -> ([]Blob_Change, bool) {
+	raw, ok := git([]string{"show", "--raw", "--no-renames", "--no-abbrev",
+	                        "--no-color", "--format=", hash})
+	if !ok {
+		return nil, false
+	}
+	changes := make([dynamic]Blob_Change, 0, 8)
+	for line in split_byte(raw, '\n') {
+		// ":100644 100644 <old> <new> M\tpath"
+		if len(line) == 0 || line[0] != ':' {
+			continue
+		}
+		fields := split_byte(line, ' ')
+		if len(fields) < 5 {
+			continue
+		}
+		tab := strings.index_byte(fields[4], '\t')
+		if tab < 0 {
+			continue
+		}
+		append(&changes, Blob_Change{
+			path = fields[4][tab + 1:],
+			old  = fields[2],
+			new  = fields[3],
+		})
+	}
+	return changes[:], true
+}
+
+// sha_absent reports whether an object id names nothing, i.e. the file was added
+// (old side) or deleted (new side).
+sha_absent :: proc(sha: string) -> bool {
+	if len(sha) == 0 {
+		return true
+	}
+	for c in sha {
+		if c != '0' {
+			return false
+		}
+	}
+	return true
+}
+
+// Blob_Source is one blob to parse, with the suffix EXT so ctags can tell a C
+// file from a C++ one.
+Blob_Source :: struct {
+	blob: string,
+	ext:  string,
+}
+
+// c_family_decls reports the C-family declarations HASH added and removed.
+//
+// A commit that touches no C-family file costs one `git show --raw' and returns
+// nothing.  ctags itself is only run for blobs the cache does not have, and if
+// ctags cannot be run at all the store keeps working the way it did before this
+// pass existed: hunk context, no add/remove for C and C++.
+c_family_decls :: proc(db: ^Db, hash: string) -> (decls: []Decl, ok: bool) {
+	changes, ok_changes := raw_changes(hash)
+	if !ok_changes {
+		return nil, false
+	}
+
+	// Which blobs this commit needs, and the suffix to parse each under.  One
+	// blob can appear twice (a file changed in two commits); the map keeps one.
+	needed := make(map[string]string)
+	defer delete(needed)
+	n := 0
+	for change in changes {
+		if lang_of(change.path) != .C_Family {
+			continue
+		}
+		n += 1
+		ext := c_family_ext(change.path)
+		if !sha_absent(change.old) {
+			needed[change.old] = ext
+		}
+		if !sha_absent(change.new) {
+			needed[change.new] = ext
+		}
+	}
+	if n == 0 {
+		return nil, true
+	}
+	if len(needed) == 0 {
+		return nil, true
+	}
+
+	// The store's cache first; whatever is left is parsed in one ctags run.
+	tags := make(map[string]string)
+	defer delete(tags)
+	sources := make([dynamic]Blob_Source, 0, len(needed))
+	for blob, ext in needed {
+		if cached, has := cached_blob_tags(db, blob); has {
+			tags[blob] = cached
+		} else {
+			append(&sources, Blob_Source{blob = blob, ext = ext})
+		}
+	}
+	if len(sources) > 0 {
+		fresh, ok_parse := parse_blob_tags(sources[:])
+		if !ok_parse {
+			// Caches stay valid; the commit simply gets no declaration-level
+			// attribution for its C-family files.  Not an error: imports must
+			// not stop because a helper is missing.
+			return nil, true
+		}
+		for blob, t in fresh {
+			tags[blob] = t
+			store_blob_tags(db, blob, t)
+		}
+	}
+
+	out := make([dynamic]Decl, 0, 8)
+	for change in changes {
+		if lang_of(change.path) != .C_Family {
+			continue
+		}
+		old_tags := tags[change.old] or_else ""
+		new_tags := tags[change.new] or_else ""
+		old_set := make(map[string]bool)
+		defer delete(old_set)
+		for line in split_byte(old_tags, '\n') {
+			if len(line) > 0 {
+				old_set[line] = true
+			}
+		}
+		new_set := make(map[string]bool)
+		defer delete(new_set)
+		for line in split_byte(new_tags, '\n') {
+			if len(line) > 0 {
+				new_set[line] = true
+			}
+		}
+		for line in split_byte(new_tags, '\n') {
+			if len(line) == 0 || old_set[line] {
+				continue
+			}
+			if d, is_decl := decl_of_tag(line, change.path); is_decl {
+				d.added = true
+				append(&out, d)
+			}
+		}
+		for line in split_byte(old_tags, '\n') {
+			if len(line) == 0 || new_set[line] {
+				continue
+			}
+			if d, is_decl := decl_of_tag(line, change.path); is_decl {
+				d.removed = true
+				append(&out, d)
+			}
+		}
+	}
+	return out[:], true
+}
+
+// decl_of_tag turns a cached tag line, "<ctags kind><TAB><name>", into a Decl.
+decl_of_tag :: proc(tag, file: string) -> (d: Decl, ok: bool) {
+	tab := strings.index_byte(tag, '\t')
+	if tab < 0 {
+		return {}, false
+	}
+	tag_kind := tag[:tab]
+	kind, is_decl := c_family_kind(tag_kind)
+	if !is_decl {
+		return {}, false
+	}
+	name := tag[tab + 1:]
+	if len(name) == 0 {
+		return {}, false
+	}
+	// `#define CALC_H' and `#define __CALC_H__' guard a header; they are
+	// bookkeeping, not something a reader asks why about.
+	if tag_kind == "macro" && is_include_guard(name) {
+		return {}, false
+	}
+	return Decl{name = name, kind = kind, file = file}, true
+}
+
+// is_include_guard reports whether NAME looks like a header guard.
+is_include_guard :: proc(name: string) -> bool {
+	if strings.has_prefix(name, "__") {
+		return true
+	}
+	return strings.has_suffix(name, "_H") || strings.has_suffix(name, "_H__") ||
+	       strings.has_suffix(name, "_HPP") || strings.has_suffix(name, "_HH") ||
+	       strings.has_suffix(name, "_INCLUDED")
+}
+
+// c_family_ext returns the suffix of PATH, which is what ctags keys the language
+// on; the temporary file keeps it.
+c_family_ext :: proc(path: string) -> string {
+	for ext in C_EXTENSIONS {
+		if strings.has_suffix(path, ext) {
+			return ext
+		}
+	}
+	return ""
+}
+
+// cached_blob_tags reads the tags of BLOB from the store, if they were parsed
+// before.
+cached_blob_tags :: proc(db: ^Db, blob: string) -> (tags: string, ok: bool) {
+	s, sok := stmt(db, "select tags from blobs where blob = ?1")
+	if !sok {
+		return "", false
+	}
+	defer stmt_close(&s)
+	stmt_bind_text(&s, 1, blob)
+	if stmt_step(&s) != .Row {
+		return "", false
+	}
+	return stmt_col_text(&s, 0), true
+}
+
+// store_blob_tags adds a parsed blob to the cache.  `on conflict do nothing':
+// a blob's tags are a function of its content, so an existing row is already
+// right, and re-writing it would only churn the file.
+store_blob_tags :: proc(db: ^Db, blob, tags: string) -> bool {
+	s, ok := stmt(db, `insert into blobs (blob, tags) values (?1, ?2)
+	                   on conflict (blob) do nothing`)
+	if !ok {
+		return false
+	}
+	defer stmt_close(&s)
+	stmt_bind_text(&s, 1, blob)
+	stmt_bind_text(&s, 2, tags)
+	return stmt_step(&s) == .Done
+}
+
+// parse_blob_tags parses each source blob with one ctags run and returns, per
+// blob, its tags as "<ctags kind><TAB><name>" lines.  The raw ctags kind is kept
+// in the cache and mapped to the store's vocabulary when the tag is used, so a
+// changed mapping does not need the blobs re-parsed.
+//
+// The blobs have to be real files: ctags reads the language from the name.  They
+// are written into one temporary directory and removed again.
+parse_blob_tags :: proc(sources: []Blob_Source) -> (tags: map[string]string, ok: bool) {
+	tmp_root, tmp_err := os.temp_directory(context.temp_allocator)
+	if tmp_err != nil {
+		fmt.eprintfln("ai-memory: no temporary directory: %v", tmp_err)
+		return nil, false
+	}
+	dir := fmt.tprintf("%s/ai-memory-tags-%d", tmp_root, os.get_pid())
+	if err := os.make_directory_all(dir); err != nil {
+		fmt.eprintfln("ai-memory: cannot create %s: %v", dir, err)
+		return nil, false
+	}
+	defer os.remove_all(dir)
+
+	paths := make([dynamic]string, 0, len(sources))
+	by_path := make(map[string]string)
+	defer delete(by_path)
+	for src, i in sources {
+		content, cat_ok := git([]string{"cat-file", "blob", src.blob})
+		if !cat_ok {
+			continue
+		}
+		path := fmt.tprintf("%s/%d%s", dir, i, src.ext)
+		if err := os.write_entire_file_from_bytes(path, transmute([]u8)content); err != nil {
+			fmt.eprintfln("ai-memory: cannot write %s: %v", path, err)
+			continue
+		}
+		append(&paths, path)
+		by_path[path] = src.blob
+	}
+	if len(paths) == 0 {
+		return make(map[string]string), true
+	}
+
+	args := make([dynamic]string, 0, len(paths) + 8, context.temp_allocator)
+	append(&args, "--sort=no", "--fields=+K", "-o", "-")
+	// Lambdas are tagged by default, under names ctags derives from a hash of
+	// the file (`__anon426fc91f0102'): they change whenever the line moves, so
+	// every commit would report a handful of functions added and removed.  They
+	// are not declarations a reader asks about; the enclosing function is what
+	// hunk context already gives.
+	append(&args, "--extras=-{anonymous}")
+	// Prototypes are off by default, and without them a declaration in a header
+	// is invisible: only definitions in .cpp files would ever be `added'.
+	append(&args, "--kinds-C=+p", "--kinds-C++=+p")
+	append(&args, ..paths[:])
+
+	out, run_ok := run_capture(ctags_path(), args[:])
+	if !run_ok {
+		if !CTAGS_MISSING {
+			CTAGS_MISSING = true
+			fmt.eprintln("ai-memory: ctags is not runnable, so C and C++ declarations " +
+			             "keep hunk context only (set $AI_MEMORY_CTAGS)")
+		}
+		return nil, false
+	}
+
+	tags = make(map[string]string)
+	for line in split_byte(out, '\n') {
+		if len(line) == 0 || line[0] == '!' {
+			continue
+		}
+		// "name<TAB>path<TAB>/^pattern$/;"<TAB>kind[<TAB>extra fields]"
+		fields := split_byte(line, '\t')
+		if len(fields) < 4 {
+			continue
+		}
+		name := fields[0]
+		blob := by_path[fields[1]] or_else ""
+		if len(blob) == 0 || len(name) == 0 {
+			continue
+		}
+		tag := fmt.tprintf("%s\t%s", fields[3], name)
+		tags[blob] = strings.concatenate({tags[blob] or_else "", tag, "\n"}, context.temp_allocator)
+	}
+	return tags, true
+}
+
+// run_capture runs EXE with ARGS and returns its stdout.  Unlike `git', a failure
+// here is not fatal: ctags is an optional helper.
+run_capture :: proc(exe: string, args: []string) -> (out: string, ok: bool) {
+	cmd := make([dynamic]string, 0, len(args) + 1, context.temp_allocator)
+	append(&cmd, exe)
+	append(&cmd, ..args)
+	state, stdout, _, err := os.process_exec({command = cmd[:]}, context.temp_allocator)
+	if err != nil {
+		return "", false
+	}
+	if state.exit_code != 0 {
+		return "", false
+	}
+	return string(stdout), true
+}
+
 // is_change_line reports an added or removed line, excluding file headers.
 is_change_line :: proc(line: string) -> bool {
 	if len(line) < 2 {
@@ -165,12 +545,17 @@ is_change_line :: proc(line: string) -> bool {
 // 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 {
+	// Keyed by file *and* name, not by name: `main.open_store' and `db.open'
+	// in one commit are two symbols, and merging them threw one away and
+	// gave the survivor the other file's attribution.  The separator cannot
+	// occur in a path or an identifier.
+	key := fmt.tprintf("%s\x1f%s", d.file, d.name)
+	if old, exists := m[key]; 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
+	m[key] = d
 }
 
 // hunk_context returns the text after the closing "@@" of a hunk header.
diff --git a/guix.scm b/guix.scm
index 7733f83..04f4075 100644
--- a/guix.scm
+++ b/guix.scm
@@ -38,10 +38,12 @@
   #:use-module (guix packages)
   #:use-module (guix utils)
   #:use-module (gnu packages bash)
+  #:use-module (gnu packages code)
   #:use-module (gnu packages guile)
   #:use-module (gnu packages guile-xyz)
   #:use-module (gnu packages llvm)
-  #:use-module (gnu packages sqlite))
+  #:use-module (gnu packages sqlite)
+  #:use-module (gnu packages version-control))
 
 (define %source-dir (dirname (current-filename)))
 
@@ -219,9 +221,13 @@ to link the system SQLite3 instead of a bundled copy.")
     (build-system gnu-build-system)
     ;; libsqlite3.so is linked at run time; the topic index (scripts/index.scm)
     ;; is a Guile program, because libxapian is C++-only and guile-xapian
-    ;; already has the C++ shim that a foreign call would otherwise need.
-    (inputs (list sqlite guile-3.0 guile-xapian guile-sqlite3))
-    (native-inputs (list odin odin-sqlite3))
+    ;; already has the C++ shim that a foreign call would otherwise need;
+    ;; universal-ctags writes the C/C++ declarations that no diff line can.
+    (inputs (list sqlite guile-3.0 guile-xapian guile-sqlite3 universal-ctags))
+    ;; git drives the whole derived half of the store, so it is a runtime
+    ;; dependency too -- but it belongs to the user's environment, not to this
+    ;; profile, which is why it is only a native input for the check phase.
+    (native-inputs (list odin odin-sqlite3 git))
     (arguments
      (list
       #:phases
@@ -300,7 +306,50 @@ to link the system SQLite3 instead of a bundled copy.")
                           (string-append "./bin/ai-memory --index tmp/index"
                                          " search topic:index"
                                          " | grep -q"
-                                         " '\"title\":\"gisttext names the document\"'")))))
+                                         " '\"title\":\"gisttext names the document\"'"))
+                  ;; C and C++ declarations, end to end: they come from ctags
+                  ;; over the file blobs, diffed between a commit and its
+                  ;; parent, so only a real (throwaway) repository can prove
+                  ;; it.  The same file gains `dec' in the second commit:
+                  ;; `dec' must be an add, and `inc' -- whose body changed but
+                  ;; whose declaration did not -- must not be.
+                  (mkdir-p "tmp/cpp")
+                  ;; The binary under test is unwrapped here, so the path the
+                  ;; install phase bakes into the wrapper is set by hand.
+                  (setenv "AI_MEMORY_CTAGS"
+                          (string-append #$(this-package-input "universal-ctags")
+                                         "/bin/ctags"))
+                  (invoke "git" "init" "-q" "tmp/cpp")
+                  (call-with-output-file "tmp/cpp/kern.cpp"
+                    (lambda (out)
+                      (display "int inc(int a) {\n  return a + 1;\n}\n" out)))
+                  (invoke "git" "-C" "tmp/cpp" "add" "kern.cpp")
+                  (invoke "git" "-C" "tmp/cpp" "-c" "user.name=check"
+                          "-c" "user.email=check@example" "commit" "-qm" "add inc")
+                  (call-with-output-file "tmp/cpp/kern.cpp"
+                    (lambda (out)
+                      (display (string-append
+                                "int inc(int a) {\n  int one = 1;\n  return a + one;\n}\n"
+                                "\nint dec(int a) {\n  return a - 1;\n}\n")
+                               out)))
+                  (invoke "git" "-C" "tmp/cpp" "-c" "user.name=check"
+                          "-c" "user.email=check@example" "commit" "-qam" "add dec")
+                  (invoke "./bin/ai-memory" "-C" "tmp/cpp" "--db"
+                          "tmp/cpp/store.sqlite" "init")
+                  (invoke "./bin/ai-memory" "-C" "tmp/cpp" "--db"
+                          "tmp/cpp/store.sqlite" "import")
+                  (invoke "sh" "-c"
+                          (string-append "./bin/ai-memory -C tmp/cpp --db"
+                                         " tmp/cpp/store.sqlite why dec"
+                                         " | grep -q 'fn kern.cpp.dec, add'"))
+                  (invoke "sh" "-c"
+                          (string-append "./bin/ai-memory -C tmp/cpp --db"
+                                         " tmp/cpp/store.sqlite why inc"
+                                         " | grep -q 'fn kern.cpp.inc, add'"))
+                  (invoke "sh" "-c"
+                          (string-append "./bin/ai-memory -C tmp/cpp --db"
+                                         " tmp/cpp/store.sqlite why inc"
+                                         " | grep -q 'fn kern.cpp.inc, context'")))))
             (replace 'install
               (lambda _
                 (install-file "bin/ai-memory"
@@ -316,6 +365,9 @@ to link the system SQLite3 instead of a bundled copy.")
                 (install-file "doc/SKILL.md"
                               (string-append #$output "/share/doc/ai-memory"))
                 (wrap-program (string-append #$output "/bin/ai-memory")
+                  `("AI_MEMORY_CTAGS" =
+                    (,(string-append #$(this-package-input "universal-ctags")
+                                     "/bin/ctags")))
                   `("GUILE" = (,(string-append #$(this-package-input "guile") "/bin/guile")))
                   `("GUILE_LOAD_PATH" = (,(string-append #$(this-package-input "guile-xapian")
                                                          "/share/guile/site/3.0:"
diff --git a/lang.odin b/lang.odin
index b3a5ff8..58d2f34 100644
--- a/lang.odin
+++ b/lang.odin
@@ -7,9 +7,29 @@ import "core:strings"
 Lang :: enum {
 	Odin,
 	Rust,
+	C_Family, // .c .h .cc .cpp .cxx .hpp .hh .hxx .ipp .tpp .inl
 	Other,
 }
 
+// C_EXTENSIONS are the suffixes handed to ctags.  `.h' is shared by C and C++,
+// which is why the family is named C_Family and not Cpp: universal-ctags picks
+// the dialect from the extension, and for a header that could be either it reads
+// the syntax.  The list lives here so that `lang_of', the commit's file list and
+// symbol_name all agree on what a C-family file is.
+C_EXTENSIONS :: [?]string{
+	".c",
+	".h",
+	".cc",
+	".cpp",
+	".cxx",
+	".hpp",
+	".hh",
+	".hxx",
+	".ipp",
+	".tpp",
+	".inl",
+}
+
 lang_of :: proc(file: string) -> Lang {
 	switch {
 	case strings.has_suffix(file, ".odin"):
@@ -17,6 +37,11 @@ lang_of :: proc(file: string) -> Lang {
 	case strings.has_suffix(file, ".rs"):
 		return .Rust
 	}
+	for ext in C_EXTENSIONS {
+		if strings.has_suffix(file, ext) {
+			return .C_Family
+		}
+	}
 	return .Other
 }
 
@@ -28,11 +53,38 @@ parse_decl :: proc(file, line: string) -> (name: string, kind: string, ok: bool)
 		return parse_odin_decl(line)
 	case .Rust:
 		return parse_rust_decl(line)
+	case .C_Family:
+		// Deliberately no lexical scan.  In C and C++ a diff line cannot say
+		// whether it declares anything: inside a body `foo(bar);' is a call and
+		// inside a class body the same bytes declare a constructor, and both are
+		// indented the same way.  Declarations come from ctags over the whole
+		// file instead -- see blob_tags in git.odin -- and what a hunk line can
+		// still give us is the enclosing function, which is the hunk-header path.
 	case .Other:
 	}
 	return "", "", false
 }
 
+// c_family_kind maps a universal-ctags kind name to the store's vocabulary,
+// rather than inventing a second one.  The kinds left out are the ones that
+// churn without changing what a hunk was about: members and enumerators and
+// variables inside a body, namespaces (structure, not behaviour), and the
+// bookkeeping tags (header, parameter) that say nothing about a declaration.
+c_family_kind :: proc(tag_kind: string) -> (kind: string, ok: bool) {
+	switch tag_kind {
+	case "function", "prototype", "method":
+		return "fn", true
+	case "class", "struct", "union", "enum", "typedef":
+		return "type", true
+	case "macro":
+		// A macro is a named constant as far as a reader is concerned.
+		return "const", true
+	case "variable", "externvar":
+		return "var", true
+	}
+	return "", false
+}
+
 // -- Odin -------------------------------------------------------------------
 //
 //	NAME :: proc ...            -> proc
diff --git a/main.odin b/main.odin
index f9d1d20..0d4c58a 100644
--- a/main.odin
+++ b/main.odin
@@ -220,7 +220,7 @@ cmd_sync :: proc(args: []string, default_limit: int) -> bool {
 		}
 		n_commit += 1
 
-		decls, ok_decls := git_touched(c.hash)
+		decls, ok_decls := git_touched(c.hash, &db)
 		if !ok_decls {
 			db_exec(&db, "rollback")
 			return false
diff --git a/schema.sql b/schema.sql
index e624369..1d38f7a 100644
--- a/schema.sql
+++ b/schema.sql
@@ -1,4 +1,4 @@
--- ai-memory schema, version 3.
+-- ai-memory schema, version 6.
 --
 -- commits  : one row per git commit, derived from `git log' by `sync'.
 -- symbols  : one declared identifier per row (proc, fn, type, const, var).
@@ -63,6 +63,16 @@ 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);
 
+-- blobs: the C/C++ declaration cache.  One row per git blob that ctags has
+-- parsed, keyed by object id, holding that blob's tags as "<ctags kind>\t<name>"
+-- lines.  A blob's content cannot change, so a row can never go stale; this is
+-- purely a speed cache -- drop the table and the next `sync' re-derives it in a
+-- couple of ctags runs per new file version instead of one per commit per file.
+create table if not exists blobs (
+	blob text primary key,
+	tags text not null
+);
+
 create virtual table if not exists reasoning_fts using fts5 (
 	body, content = 'reasoning', content_rowid = 'id'
 );
@@ -80,4 +90,4 @@ create trigger if not exists reasoning_after_update after update on reasoning be
 	insert into reasoning_fts (rowid, body) values (new.id, new.body);
 end;
 
-pragma user_version = 5;
+pragma user_version = 6;