about summary refs log tree commit diff
path: root/main.odin
blob: 44c2ff16f784a4144fe87490117976f59767c778 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
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] [--gist ONE-LINE]
  attach <HASH|HEAD> [--session S] link unattached reasoning to a commit
  why <symbol> [--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 <text> [--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: <store>.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 <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 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
}