about summary refs log tree commit diff
path: root/git.odin
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 /git.odin
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.
Diffstat (limited to 'git.odin')
-rw-r--r--git.odin336
1 files changed, 336 insertions, 0 deletions
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
+}