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 [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] [--gist ONE-LINE] attach [--session S] link unattached reasoning to a commit why [--all] [--full] commits and reasoning that touched a symbol list [--limit N] one line per reasoning entry, newest commit first [--session S] [--kind K] [--commit HASH] search [--all] [--full] full-text search over reasoning (--all also shows superseded entries) log [--limit N] recent commits and how much reasoning they carry status row counts topic index (derived from the store; see scripts/index.scm): update-index [--rebuild] bring the Xapian index up to date search [--limit N] QUERY... with --index: search it, with prefixes topic: repo: type: session: commit: date: (without --index, search stays SQLite FTS) 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 --index DIR the topic index directory (default: .d/index; $AI_MEMORY_INDEX) --index-script PATH the Guile indexer (default: installed share/ai-memory/index.scm, else scripts/index.scm; $AI_MEMORY_INDEX_SCRIPT) The store defaults to /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 a == "--index": name = "--index" case a == "--index-script": name = "--index-script" 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 case strings.has_prefix(a, "--index="): name = "--index" value = a[len("--index="):] has_value = true case strings.has_prefix(a, "--index-script="): name = "--index-script" value = a[len("--index-script="):] 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 } switch name { case "--db": DB_PATH = value case "--index": INDEX_PATH = value case "--index-script": INDEX_SCRIPT = value case: 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 "update-index": ok = cmd_update_index(flag_bool(args[1:], "--rebuild")) case "search": // The index answers concept queries; the store's own FTS answers // text. Asking for --index is how a caller chooses. if index_requested() { ok = cmd_search_index(args[1:], parse_int(flag_or(args[1:], "--limit", "0"), 0)) } else { ok = cmd_search(args[1:]) } case "log": ok = cmd_log(args[1:]) case "list": ok = cmd_list(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 } // Count rows, not insert attempts: `insert or ignore' reports success for a // touch that already existed, which made re-syncs look like they added work. touches_before := count_rows(&db, "touches") commits_before := count_rows(&db, "commits") n_commit: 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, &db) if !ok_decls { db_exec(&db, "rollback") return false } for d in decls { insert_touch(&db, c.hash, d) } } if !db_exec(&db, "commit") { return false } fmt.printfln("examined %d commits: %d new, %d symbol touches new", n_commit, count_rows(&db, "commits") - commits_before, count_rows(&db, "touches") - touches_before) 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) // The gist is what listings show. Given explicitly it is the claim itself; // otherwise fall back to the body's first sentence, which is a floor, not an // equivalent. gist := flag_or(args, "--gist", "") gist_given := len(gist) > 0 if !gist_given { gist = gist_of(body) } // Reasoning may predate the commit: --commit none leaves it unattached. // // Every form of --commit is resolved to the FULL forty-character hash here, // before anything touches SQL. A short hash used to be taken as written: // git accepted it, the commit row was imported under its full hash, and the // reasoning row then named the short one -- which failed deep inside SQLite // ("sql error (Error): SQL logic error") *after* the commit had been written. 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: if full, fok := resolve_commit_ref(c); fok { commit = full has_commit = true } else { fmt.eprintfln("ai-memory: --commit %s is not a commit in %s", c, repo_label()) fmt.eprintln("ai-memory: nothing was written. Give a hash git knows " + "(it may be shortened), or --commit none to record it " + "unattached and `attach` it later.") return false } } db, ok := open_db() if !ok { return false } defer db_close(&db) // One transaction around the import and the insert: if the insert fails, the // imported commit row goes with it, and a caller who saw an error has a store // that looks exactly as it did before. (Measured before this: a short // --commit left the commit row behind and recorded nothing.) if !db_exec(&db, "begin immediate") { return false } committed := false defer if !committed { db_exec(&db, "rollback") } // 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, gist, gist_source, body) values (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)`) 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, gist) // assessed when the caller said what the entry claims, derived when it is the // body's first sentence -- only the latter may ever be recomputed. gist_source := "derived" if gist_given { gist_source = "assessed" } stmt_bind_text(&s, 9, gist_source) stmt_bind_text(&s, 10, body) if stmt_step(&s) != .Done { return false } stmt_close(&s) if !db_exec(&db, "commit") { return false } committed = true if has_commit { fmt.printfln("recorded %s on %s: %s", kind, short_hash(commit), gist) } else { fmt.printfln("recorded %s (not attached to a commit yet): %s", kind, gist) } if !gist_given { // The first sentence is a floor: it usually says what the entry is about, // not what it claims. Written at record time, --gist can say both. fmt.eprintln("ai-memory: no --gist given, used the body's first sentence") } 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 } // Same rule as `record --commit`: whatever git answers with, the store keys // commits by the full hash, so a short ref must be resolved before SQL. if full, fok := resolve_commit_ref(hash); fok { hash = full } else { fmt.eprintfln("ai-memory: %s is not a commit in %s", hash, repo_label()) fmt.eprintln("ai-memory: nothing was attached.") 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") full := flag_bool(args, "--full") 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_date(row.author_ts), row.subject, row.kind, row.symbol, row.change) print_reasoning(reasoning_for(&db, row.commit_hash), show_all, full) } return true } cmd_search :: proc(args: []string) -> bool { query_text, found := first_positional(args) if !found { fmt.eprintln("ai-memory: search needs a query") return false } show_all := flag_bool(args, "--all") full := flag_bool(args, "--full") db, ok := open_db() if !ok { return false } defer db_close(&db) s, sok := stmt(&db, `select r.id, r.kind, r.basis, r.gist, r.body, r.created_at, c.subject, (select min(s.id) from reasoning s where s.supersedes = r.id), r.commit_hash 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, query_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), gist = stmt_col_text(&s, 3), body = stmt_col_text(&s, 4), superseded_by = stmt_col_i64(&s, 7), } if r.superseded_by != 0 && !show_all { hidden += 1 continue } hash := stmt_col_text(&s, 8) origin := "uncommitted" if len(hash) > 0 { origin = short_hash(hash) } label := fmt.tprintf("%s %s #%d %s", origin, fmt_date(stmt_col_i64(&s, 5)), 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) } text := r.gist if len(text) == 0 { text = gist_of(r.body) } fmt.printfln("%s: %s", label, text) if full { fmt.printfln(" %s", indent_rest(r.body)) } subject := stmt_col_text(&s, 6) if len(subject) > 0 { fmt.printfln(" on %s", subject) } } if n == 0 { fmt.printfln("nothing matches %q", query_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_date(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, gist: 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 } // Substring, not suffix: `why geno2mdb' should reach geno2mdb.main, and the // documented behaviour is a LIKE '%...%' scan. It was a suffix match // (LIKE '%name'), which could not find a file's own symbols at all. 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.gist, 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), gist = stmt_col_text(&s, 3), body = stmt_col_text(&s, 4), superseded_by = stmt_col_i64(&s, 5), }) } 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 renders entries gist-first: the claim on one line, and the // long form only when FULL is set. SHOW_ALL admits superseded entries. print_reasoning :: proc(rows: []Reasoning_Row, show_all: bool, full: 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) } text := r.gist if len(text) == 0 { text = gist_of(r.body) } fmt.printfln(" %s: %s", label, text) if full { fmt.printfln(" %s", 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 } // resolve_commit_ref turns whatever the caller wrote into the full hash git // reports for it -- a short hash, a tag, HEAD~2, a branch -- or fails, in which // case the caller must not touch the store. The store keys commits by the full // hash (that is what `sync` and `git_commit' write), so a short ref passed // through to SQL names a row that cannot exist. resolve_commit_ref :: proc(ref: string) -> (hash: string, ok: bool) { // No `^{commit}` suffix: it needs string formatting, and Odin's // process_exec passes argv straight to git, so the plain ref is both simpler // and enough -- rev-parse answers a short hash, a tag, a branch, HEAD~3 or a // full hash with the full object id. Whether that object is a commit is then // settled by `git show' in ensure_commit, which says so in words. out, good := git([]string{"rev-parse", "--verify", ref}, context.temp_allocator, false) if !good { return "", false } hash = strings.trim_space(out) return hash, len(hash) == 40 } short_hash :: proc(hash: string) -> string { if len(hash) <= 7 { return hash } return hash[:7] } // fmt_date renders a timestamp as dd/mm, in UTC. The year appears only when it // is not the current one: listings are read for order and recency, and a full // ISO stamp next to every hash drowns the hash. fmt_date :: proc(ts: i64) -> string { if ts == 0 { return "--/--" } t := time.unix(ts, 0) year, month, day := time.date(t) if year != time.year(time.now()) { return fmt.tprintf("%02d/%02d/%02d", day, int(month), year %% 100) } return fmt.tprintf("%02d/%02d", day, int(month)) } // indent_rest keeps multi-line reasoning readable under its commit line. // one_line flattens a body onto one line and truncates it, for listings. one_line :: proc(s: string, max: int) -> string { out := make([dynamic]u8, 0, len(s), context.temp_allocator) space := false for i in 0 ..< len(s) { c := s[i] if c == '\n' || c == '\r' || c == '\t' || c == ' ' { space = len(out) > 0 continue } if space { append(&out, ' ') space = false } append(&out, c) } if len(out) <= max { return string(out[:]) } return fmt.tprintf("%s...", string(out[:max - 3])) } 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 } // ---- list ----------------------------------------------------------------- // cmd_list prints one line per reasoning entry, newest commit first, so the // record can be skimmed without following symbol to commit to entry. cmd_list :: proc(args: []string) -> bool { limit := parse_int(flag_or(args, "--limit", "40"), 40) session := flag_or(args, "--session", "") kind := flag_or(args, "--kind", "") commit := flag_or(args, "--commit", "") db, ok := open_db() if !ok { return false } defer db_close(&db) // Anonymous placeholders, bound in the order they appear. query := `select r.id, r.kind, r.gist, r.body, r.commit_hash, coalesce(c.author_ts, 0), (select min(s.id) from reasoning s where s.supersedes = r.id), r.created_at from reasoning r left join commits c on c.hash = r.commit_hash` conds := make([dynamic]string, 0, 3, context.temp_allocator) if len(session) > 0 { append(&conds, "r.session_id = ?") } if len(kind) > 0 { append(&conds, "r.kind = ?") } if len(commit) > 0 { append(&conds, "r.commit_hash like ?") } if len(conds) > 0 { filter := "" for c, i in conds { if i > 0 { filter = fmt.tprintf("%s and", filter) } filter = fmt.tprintf("%s %s", filter, c) } query = fmt.tprintf("%s where%s", query, filter) } // Unattached entries first: they are the work that has no commit yet. query = fmt.tprintf("%s order by (r.commit_hash is null) desc, c.author_ts desc, r.id limit ?", query) s, sok := stmt(&db, query) if !sok { return false } defer stmt_close(&s) idx := 1 if len(session) > 0 { stmt_bind_text(&s, idx, session) idx += 1 } if len(kind) > 0 { stmt_bind_text(&s, idx, kind) idx += 1 } if len(commit) > 0 { stmt_bind_text(&s, idx, fmt.tprintf("%s%%", commit)) idx += 1 } stmt_bind_i64(&s, idx, i64(limit)) for { rc := stmt_step(&s) if rc == .Done { break } if rc != .Row { return false } hash := stmt_col_text(&s, 4) label := "uncommitted" if len(hash) > 0 { label = short_hash(hash) } kind_text := stmt_col_text(&s, 1) superseded := stmt_col_i64(&s, 6) if superseded != 0 { kind_text = fmt.tprintf("%s->#%d", kind_text, superseded) } // Gist first; the body only if no gist was ever written. text := stmt_col_text(&s, 2) if len(text) == 0 { text = one_line(stmt_col_text(&s, 3), 96) } // An unattached entry has no commit date; its own created_at is the date // that means something for it. ts := stmt_col_i64(&s, 5) if ts == 0 { ts = stmt_col_i64(&s, 7) } fmt.printfln("%s %s #%d %s %s", label, fmt_date(ts), stmt_col_i64(&s, 0), kind_text, text) } return true }