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
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
|
// inventory is a mobile-first voice+vision inventory capture app. You open a box
// on your phone, point the camera and talk; a Gemini Live agent records the
// contents into a flexible SQLite graph via tool calls. See DESIGN.md.
//
// This build (Phase 1 + 2) implements the foundation:
// - an open, LLM-friendly data model: entities + attributes + relations +
// photos (BLOBs), plus capture-session audit rows,
// - invite-token session auth (copied from weekplan),
// - a mobile-first browse/edit UI (no AI yet) to view and correct inventory.
//
// The Gemini Live proxy (live.go / session.go / tools.go) plugs into the same
// DB and auth in later phases.
//
// Auth is invite-token based (no stored passwords): mint a login link with
// `inventory gen-link`, open it once to obtain a long-lived session cookie.
//
// Usage:
//
// inventory serve [--addr host:port] [--base-url url] <db>
// inventory gen-link [--admin] [--username name] [--base-url url] <db>
package main
import (
"crypto/rand"
"database/sql"
"encoding/base64"
"encoding/json"
"flag"
"fmt"
"io"
"log"
"net/http"
"os"
"path/filepath"
"strconv"
"strings"
"time"
_ "modernc.org/sqlite"
)
// ============================================================================
// Schema + migrations
// ============================================================================
//
// Each migration is applied exactly once, in order, tracked by schema_version.
// Never modify an existing migration — add a new one instead.
const initSchema = `
CREATE TABLE IF NOT EXISTS schema_version (
version INTEGER PRIMARY KEY,
applied_at INTEGER NOT NULL
);
`
var dbMigrations = []struct {
version int
sql string
}{
{1, `
CREATE TABLE sessions (
session_id TEXT PRIMARY KEY,
username TEXT NOT NULL,
is_admin INTEGER NOT NULL DEFAULT 0,
created_at INTEGER NOT NULL
);
CREATE TABLE invite_tokens (
token TEXT PRIMARY KEY,
username TEXT NOT NULL,
is_admin INTEGER NOT NULL DEFAULT 0,
created_at INTEGER NOT NULL,
expires_at INTEGER NOT NULL,
used_at INTEGER
);
-- An entity is any recorded thing. "kind" is free text the model coins:
-- "box", "item", "location", "tote", ... The graph shape is intentionally open.
CREATE TABLE entities (
id INTEGER PRIMARY KEY AUTOINCREMENT,
kind TEXT NOT NULL DEFAULT 'item',
name TEXT NOT NULL,
notes TEXT NOT NULL DEFAULT '',
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL
);
CREATE INDEX idx_entities_kind ON entities(kind);
-- Arbitrary key/value attributes per entity (qty, colour, condition, brand...).
CREATE TABLE entity_attrs (
entity_id INTEGER NOT NULL REFERENCES entities(id) ON DELETE CASCADE,
key TEXT NOT NULL,
value TEXT NOT NULL DEFAULT '',
PRIMARY KEY (entity_id, key)
);
-- Free-text relation edges: "contained_in", "located_at", "part_of", ...
CREATE TABLE relations (
id INTEGER PRIMARY KEY AUTOINCREMENT,
from_id INTEGER NOT NULL REFERENCES entities(id) ON DELETE CASCADE,
to_id INTEGER NOT NULL REFERENCES entities(id) ON DELETE CASCADE,
rel TEXT NOT NULL
);
CREATE INDEX idx_relations_from ON relations(from_id);
CREATE INDEX idx_relations_to ON relations(to_id);
-- Multiple archival JPEG photos per entity, stored as BLOBs.
CREATE TABLE photos (
id INTEGER PRIMARY KEY AUTOINCREMENT,
entity_id INTEGER NOT NULL REFERENCES entities(id) ON DELETE CASCADE,
blob BLOB NOT NULL,
mime TEXT NOT NULL DEFAULT 'image/jpeg',
caption TEXT NOT NULL DEFAULT '',
created_at INTEGER NOT NULL
);
CREATE INDEX idx_photos_entity ON photos(entity_id);
-- Audit of what the model did in a capture session.
CREATE TABLE capture_sessions (
id INTEGER PRIMARY KEY AUTOINCREMENT,
started_at INTEGER NOT NULL,
ended_at INTEGER,
transcript TEXT NOT NULL DEFAULT '',
event_log TEXT NOT NULL DEFAULT ''
);
`},
// Per-session token usage + expected cost. Tokens are the authoritative
// counts Gemini reports; cost is derived from the model rates AT CAPTURE TIME
// and frozen in the row, so changing rates later never rewrites history. The
// raw token counts are also kept so cost can be recomputed if ever needed.
{2, `
ALTER TABLE capture_sessions ADD COLUMN model TEXT NOT NULL DEFAULT '';
ALTER TABLE capture_sessions ADD COLUMN tokens_audio_in INTEGER NOT NULL DEFAULT 0;
ALTER TABLE capture_sessions ADD COLUMN tokens_audio_out INTEGER NOT NULL DEFAULT 0;
ALTER TABLE capture_sessions ADD COLUMN tokens_image_in INTEGER NOT NULL DEFAULT 0;
ALTER TABLE capture_sessions ADD COLUMN tokens_text_in INTEGER NOT NULL DEFAULT 0;
ALTER TABLE capture_sessions ADD COLUMN tokens_text_out INTEGER NOT NULL DEFAULT 0;
ALTER TABLE capture_sessions ADD COLUMN tokens_thoughts INTEGER NOT NULL DEFAULT 0;
ALTER TABLE capture_sessions ADD COLUMN tokens_tool_use INTEGER NOT NULL DEFAULT 0;
ALTER TABLE capture_sessions ADD COLUMN tokens_cached INTEGER NOT NULL DEFAULT 0;
ALTER TABLE capture_sessions ADD COLUMN tokens_total INTEGER NOT NULL DEFAULT 0;
ALTER TABLE capture_sessions ADD COLUMN video_frames INTEGER NOT NULL DEFAULT 0;
ALTER TABLE capture_sessions ADD COLUMN cost_usd REAL NOT NULL DEFAULT 0;
`},
}
func openDB(path string) *sql.DB {
if dir := filepath.Dir(path); dir != "" {
if err := os.MkdirAll(dir, 0o755); err != nil {
log.Panicf("create db dir %q: %v", dir, err)
}
}
db, err := sql.Open("sqlite", path)
if err != nil {
log.Panicf("open db %q: %v", path, err)
}
if _, err := db.Exec("PRAGMA foreign_keys = ON"); err != nil {
log.Panicf("pragma foreign_keys: %v", err)
}
if _, err := db.Exec("PRAGMA journal_mode = WAL"); err != nil {
log.Panicf("pragma journal_mode: %v", err)
}
if _, err := db.Exec(initSchema); err != nil {
log.Panicf("initSchema: %v", err)
}
for _, m := range dbMigrations {
var count int
db.QueryRow(`SELECT COUNT(*) FROM schema_version WHERE version = ?`, m.version).Scan(&count)
if count > 0 {
continue
}
tx, err := db.Begin()
if err != nil {
log.Panicf("begin migration %d: %v", m.version, err)
}
if _, err := tx.Exec(m.sql); err != nil {
tx.Rollback()
log.Panicf("migration %d: %v", m.version, err)
}
if _, err := tx.Exec(`INSERT INTO schema_version (version, applied_at) VALUES (?, ?)`,
m.version, time.Now().Unix()); err != nil {
tx.Rollback()
log.Panicf("record migration %d: %v", m.version, err)
}
if err := tx.Commit(); err != nil {
log.Panicf("commit migration %d: %v", m.version, err)
}
log.Printf("applied migration %d", m.version)
}
return db
}
func mustExec(db *sql.DB, query string, args ...any) sql.Result {
res, err := db.Exec(query, args...)
if err != nil {
log.Panicf("exec %q: %v", query, err)
}
return res
}
// ============================================================================
// Auth (invite-token -> session cookie) — copied from weekplan
// ============================================================================
func randomBase64(n int) string {
b := make([]byte, n)
if _, err := rand.Read(b); err != nil {
log.Panicf("rand: %v", err)
}
return base64.URLEncoding.EncodeToString(b)
}
func makeInviteToken(db *sql.DB, baseURL, username string, isAdmin bool, ttl time.Duration) string {
token := randomBase64(24)
now := time.Now().Unix()
isAdminInt := 0
if isAdmin {
isAdminInt = 1
}
mustExec(db,
`INSERT INTO invite_tokens (token, username, is_admin, created_at, expires_at) VALUES (?,?,?,?,?)`,
token, username, isAdminInt, now, now+int64(ttl.Seconds()),
)
payload, _ := json.Marshal(map[string]string{"username": username, "token": token})
who := base64.URLEncoding.EncodeToString(payload)
return strings.TrimRight(baseURL, "/") + "/?who=" + who
}
func setSessionCookie(w http.ResponseWriter, sessionID string) {
http.SetCookie(w, &http.Cookie{
Name: "session", Value: sessionID, Path: "/",
HttpOnly: true, SameSite: http.SameSiteLaxMode, MaxAge: 365 * 24 * 60 * 60,
})
}
func currentSession(db *sql.DB, w http.ResponseWriter, r *http.Request) (string, bool, bool) {
cookie, err := r.Cookie("session")
if err != nil {
return "", false, false
}
var username string
var isAdmin int
err = db.QueryRow(`SELECT username, is_admin FROM sessions WHERE session_id = ?`, cookie.Value).
Scan(&username, &isAdmin)
if err != nil {
return "", false, false
}
setSessionCookie(w, cookie.Value)
return username, isAdmin == 1, true
}
func requireSessionJSON(db *sql.DB, w http.ResponseWriter, r *http.Request) (string, bool, bool) {
username, isAdmin, ok := currentSession(db, w, r)
if !ok {
http.Error(w, "unauthorized", http.StatusUnauthorized)
}
return username, isAdmin, ok
}
// ============================================================================
// Models
// ============================================================================
type entity struct {
ID int64
Kind string
Name string
Notes string
CreatedAt int64
UpdatedAt int64
Attrs []attr
}
type attr struct {
Key string
Value string
}
type relationView struct {
ID int64
Rel string
OtherID int64
OtherName string
OtherKind string
Outgoing bool // true: this entity is from_id; false: this entity is to_id
}
type photoMeta struct {
ID int64
Caption string
Mime string
}
// ============================================================================
// Data access — entities
// ============================================================================
func loadAttrs(db *sql.DB, entityID int64) ([]attr, error) {
rows, err := db.Query(`SELECT key, value FROM entity_attrs WHERE entity_id = ? ORDER BY key`, entityID)
if err != nil {
return nil, err
}
defer rows.Close()
var out []attr
for rows.Next() {
var a attr
if err := rows.Scan(&a.Key, &a.Value); err != nil {
return nil, err
}
out = append(out, a)
}
return out, rows.Err()
}
// loadEntities returns entities, optionally filtered by a search query matching
// name/notes/kind or an attribute value.
func loadEntities(db *sql.DB, query string) ([]entity, error) {
var rows *sql.Rows
var err error
if q := strings.TrimSpace(query); q != "" {
like := "%" + strings.ToLower(q) + "%"
rows, err = db.Query(`
SELECT DISTINCT e.id, e.kind, e.name, e.notes, e.created_at, e.updated_at
FROM entities e
LEFT JOIN entity_attrs a ON a.entity_id = e.id
WHERE lower(e.name) LIKE ? OR lower(e.notes) LIKE ? OR lower(e.kind) LIKE ?
OR lower(a.value) LIKE ? OR lower(a.key) LIKE ?
ORDER BY e.updated_at DESC`, like, like, like, like, like)
} else {
rows, err = db.Query(`
SELECT id, kind, name, notes, created_at, updated_at
FROM entities ORDER BY updated_at DESC`)
}
if err != nil {
return nil, err
}
defer rows.Close()
var out []entity
for rows.Next() {
var e entity
if err := rows.Scan(&e.ID, &e.Kind, &e.Name, &e.Notes, &e.CreatedAt, &e.UpdatedAt); err != nil {
return nil, err
}
out = append(out, e)
}
return out, rows.Err()
}
func loadEntity(db *sql.DB, id int64) (*entity, error) {
var e entity
err := db.QueryRow(`
SELECT id, kind, name, notes, created_at, updated_at FROM entities WHERE id = ?`, id).
Scan(&e.ID, &e.Kind, &e.Name, &e.Notes, &e.CreatedAt, &e.UpdatedAt)
if err != nil {
return nil, err
}
if e.Attrs, err = loadAttrs(db, id); err != nil {
return nil, err
}
return &e, nil
}
func loadRelations(db *sql.DB, id int64) ([]relationView, error) {
rows, err := db.Query(`
SELECT r.id, r.rel, e.id, e.name, e.kind, 1 AS outgoing
FROM relations r JOIN entities e ON e.id = r.to_id
WHERE r.from_id = ?
UNION ALL
SELECT r.id, r.rel, e.id, e.name, e.kind, 0 AS outgoing
FROM relations r JOIN entities e ON e.id = r.from_id
WHERE r.to_id = ?
ORDER BY 6 DESC, 2`, id, id)
if err != nil {
return nil, err
}
defer rows.Close()
var out []relationView
for rows.Next() {
var rv relationView
var outgoing int
if err := rows.Scan(&rv.ID, &rv.Rel, &rv.OtherID, &rv.OtherName, &rv.OtherKind, &outgoing); err != nil {
return nil, err
}
rv.Outgoing = outgoing == 1
out = append(out, rv)
}
return out, rows.Err()
}
func loadPhotoMetas(db *sql.DB, entityID int64) ([]photoMeta, error) {
rows, err := db.Query(`SELECT id, caption, mime FROM photos WHERE entity_id = ? ORDER BY id`, entityID)
if err != nil {
return nil, err
}
defer rows.Close()
var out []photoMeta
for rows.Next() {
var p photoMeta
if err := rows.Scan(&p.ID, &p.Caption, &p.Mime); err != nil {
return nil, err
}
out = append(out, p)
}
return out, rows.Err()
}
// searchCriteria is the structured, multi-field search request from the model's
// search tool. Each field is a list of substrings that are OR-combined within
// the field; the fields themselves are AND-combined. Empty fields add no
// constraint. Matching is case-insensitive substring (lower(col) LIKE %term%).
//
// kind:["room","box"], name:["cellar"] => (kind~room OR kind~box) AND (name~cellar)
type searchCriteria struct {
Kind []string
Name []string
Notes []string
AttrKey []string
AttrValue []string
}
// empty reports whether no field carries any (non-empty) term.
func (c searchCriteria) empty() bool {
return len(c.Kind) == 0 && len(c.Name) == 0 && len(c.Notes) == 0 &&
len(c.AttrKey) == 0 && len(c.AttrValue) == 0
}
// orLike builds an OR-group of case-insensitive substring matches for expr
// against terms, e.g. ("lower(e.name)", ["a","b"]) =>
// "(lower(e.name) LIKE ? OR lower(e.name) LIKE ?)" with args ["%a%","%b%"].
// Returns "" (and no args) when terms is empty.
func orLike(expr string, terms []string) (string, []any) {
var parts []string
var args []any
for _, t := range terms {
t = strings.TrimSpace(t)
if t == "" {
continue
}
parts = append(parts, expr+" LIKE ?")
args = append(args, "%"+strings.ToLower(t)+"%")
}
if len(parts) == 0 {
return "", nil
}
return "(" + strings.Join(parts, " OR ") + ")", args
}
// searchWindow bounds how many rows we step from the cursor to derive a count
// without materializing the whole result set. We step at most searchWindow+1
// rows: the count is exact up to searchWindow, or reported as capped ("N+")
// when a further row exists. Only the first searchDetail rows are kept in full.
const (
searchWindow = 50
searchDetail = 25
)
// nameRankExpr builds a SQL scalar that scores how well e.name matches the given
// name terms (mirrors the old Go nameMatchScore): exact 4 > prefix 3 >
// word-boundary 2 > substring 1, taking the best-scoring term via max(...).
// Returns ("0", nil) when there are no usable terms (no ranking). The returned
// args must be bound BEFORE the WHERE args (the expression sits in SELECT).
func nameRankExpr(terms []string) (string, []any) {
var cases []string
var args []any
for _, t := range terms {
t = strings.ToLower(strings.TrimSpace(t))
if t == "" {
continue
}
// exact, prefix (t%), word-boundary (' name' LIKE '% t%'), substring (%t%)
cases = append(cases, `(CASE
WHEN lower(e.name) = ? THEN 4
WHEN lower(e.name) LIKE ? THEN 3
WHEN (' ' || lower(e.name)) LIKE ? THEN 2
WHEN lower(e.name) LIKE ? THEN 1
ELSE 0 END)`)
args = append(args, t, t+"%", "% "+t+"%", "%"+t+"%")
}
if len(cases) == 0 {
return "0", nil
}
if len(cases) == 1 {
return cases[0], args
}
return "max(" + strings.Join(cases, ",") + ")", args
}
// searchEntitiesGraph returns entities enriched with their attributes and their
// neighbours in both directions, for the model's search tool. Each entity is a
// map ready to hand to the LLM:
//
// { id, kind, name, notes,
// attrs: [{key,value}...],
// relations_incoming: [{id,name,kind,rel}...], // things pointing at this entity
// relations_outgoing: [{id,name,kind,rel}...] } // things this entity points at
//
// rel is the relation verb (e.g. "located_at", "contained_in").
//
// If id > 0 it looks up that single entity; otherwise it filters by the
// structured criteria (see searchCriteria). Attribute matching uses an EXISTS
// subquery so attr_key / attr_value are independent OR-lists. Ranking is done in
// SQL (ORDER BY name-relevance, then recency) so the best reuse candidate comes
// first. To count without materializing everything we step at most
// searchWindow+1 rows from the cursor, keeping full detail only for the first
// searchDetail. Returns (results, total, capped, err): total is the exact match
// count when capped is false, or searchWindow when capped is true (more exist).
func searchEntitiesGraph(db *sql.DB, crit searchCriteria, id int64) ([]map[string]any, int, bool, error) {
const cols = `
e.id, e.kind, e.name, e.notes,
(SELECT json_group_array(json_object('key',a.key,'value',a.value))
FROM entity_attrs a WHERE a.entity_id = e.id) AS attrs,
(SELECT json_group_array(json_object('id',f.id,'name',f.name,'kind',f.kind,'rel',r.rel))
FROM relations r JOIN entities f ON f.id = r.from_id WHERE r.to_id = e.id) AS rel_in,
(SELECT json_group_array(json_object('id',t.id,'name',t.name,'kind',t.kind,'rel',r.rel))
FROM relations r JOIN entities t ON t.id = r.to_id WHERE r.from_id = e.id) AS rel_out`
var rows *sql.Rows
var err error
if id > 0 {
rows, err = db.Query(`SELECT `+cols+`, 0 AS rank FROM entities e WHERE e.id = ?`, id)
} else if !crit.empty() {
var groups []string
var whereArgs []any
add := func(clause string, cargs []any) {
if clause != "" {
groups = append(groups, clause)
whereArgs = append(whereArgs, cargs...)
}
}
if c, a := orLike("lower(e.kind)", crit.Kind); c != "" {
add(c, a)
}
if c, a := orLike("lower(e.name)", crit.Name); c != "" {
add(c, a)
}
if c, a := orLike("lower(e.notes)", crit.Notes); c != "" {
add(c, a)
}
// Attribute matching: independent OR-lists for key and value, wrapped in
// an EXISTS so a match on any attribute row qualifies the entity.
keyC, keyA := orLike("lower(a.key)", crit.AttrKey)
valC, valA := orLike("lower(a.value)", crit.AttrValue)
if keyC != "" || valC != "" {
conds := []string{"a.entity_id = e.id"}
var eargs []any
if keyC != "" {
conds = append(conds, keyC)
eargs = append(eargs, keyA...)
}
if valC != "" {
conds = append(conds, valC)
eargs = append(eargs, valA...)
}
add("EXISTS (SELECT 1 FROM entity_attrs a WHERE "+strings.Join(conds, " AND ")+")", eargs)
}
if len(groups) == 0 {
return nil, 0, false, nil
}
// rankExpr sits in SELECT, so its args bind before the WHERE args.
rankExpr, rankArgs := nameRankExpr(crit.Name)
args := append(append([]any{}, rankArgs...), whereArgs...)
q := `SELECT ` + cols + `, ` + rankExpr + ` AS rank FROM entities e WHERE ` +
strings.Join(groups, " AND ") +
fmt.Sprintf(` ORDER BY rank DESC, e.updated_at DESC LIMIT %d`, searchWindow+1)
rows, err = db.Query(q, args...)
} else {
return nil, 0, false, nil
}
if err != nil {
return nil, 0, false, err
}
defer rows.Close()
unmarshalArr := func(s string) []map[string]any {
if s == "" {
return []map[string]any{}
}
var out []map[string]any
if err := json.Unmarshal([]byte(s), &out); err != nil {
return []map[string]any{}
}
return out
}
var results []map[string]any
total := 0
capped := false
for rows.Next() {
// One row beyond the window means "there are more" — stop counting.
if total >= searchWindow {
capped = true
break
}
var eid, rank int64
var kind, name, notes string
var attrs, relIn, relOut string
if err := rows.Scan(&eid, &kind, &name, ¬es, &attrs, &relIn, &relOut, &rank); err != nil {
return nil, 0, false, err
}
total++
// Keep full detail only for the first searchDetail rows; rows beyond that
// (up to the window) are counted but not returned.
if len(results) < searchDetail {
results = append(results, map[string]any{
"id": eid,
"kind": kind,
"name": name,
"notes": notes,
"attrs": unmarshalArr(attrs),
"relations_incoming": unmarshalArr(relIn),
"relations_outgoing": unmarshalArr(relOut),
})
}
}
if err := rows.Err(); err != nil {
return nil, 0, false, err
}
return results, total, capped, nil
}
// distinctKinds returns the set of kinds currently in use, for the UI datalist.
func distinctKinds(db *sql.DB) []string {
rows, err := db.Query(`SELECT DISTINCT kind FROM entities ORDER BY kind`)
if err != nil {
return nil
}
defer rows.Close()
var out []string
for rows.Next() {
var k string
if err := rows.Scan(&k); err == nil {
out = append(out, k)
}
}
return out
}
// ============================================================================
// HTTP server
// ============================================================================
type server struct {
db *sql.DB
baseURL string
model string
statsReg *statsRegistry
}
func (s *server) render(w http.ResponseWriter, name string, data map[string]any) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
if err := tmpl.ExecuteTemplate(w, name, data); err != nil {
log.Printf("render %s: %v", name, err)
}
}
// isFragmentRequest reports whether the SPA router asked for a bare content
// fragment (via the X-Fragment header) rather than a full HTML page. Full pages
// are still served for first paint, direct deep-links and no-JS clients.
func isFragmentRequest(r *http.Request) bool {
return r.Header.Get("X-Fragment") == "1"
}
// renderFragment renders just a content block (e.g. "list_content",
// "entity_content") without the surrounding base shell, for SPA innerHTML swaps.
func (s *server) renderFragment(w http.ResponseWriter, name string, data map[string]any) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
if err := tmpl.ExecuteTemplate(w, name, data); err != nil {
log.Printf("render fragment %s: %v", name, err)
}
}
func (s *server) gate(w http.ResponseWriter, r *http.Request) (string, bool) {
username, _, ok := currentSession(s.db, w, r)
if !ok {
s.render(w, "login", map[string]any{})
return "", false
}
return username, true
}
func writeJSON(w http.ResponseWriter, v any) {
w.Header().Set("Content-Type", "application/json")
if err := json.NewEncoder(w).Encode(v); err != nil {
log.Printf("encode json: %v", err)
}
}
func atoi64(s string) int64 { n, _ := strconv.ParseInt(s, 10, 64); return n }
// ---- browse / list ----
func (s *server) handleIndex(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" {
http.NotFound(w, r)
return
}
if _, ok := s.gate(w, r); !ok {
return
}
query := r.URL.Query().Get("q")
entities, err := loadEntities(s.db, query)
if err != nil {
http.Error(w, "db error", 500)
log.Printf("loadEntities: %v", err)
return
}
data := map[string]any{
"Nav": "browse", "Page": "list", "Model": s.model,
"Query": query, "Entities": entities, "HasEntities": len(entities) > 0,
}
if isFragmentRequest(r) {
s.renderFragment(w, "list_content", data)
return
}
s.render(w, "list", data)
}
// ---- capture (voice+vision) ----
func (s *server) handleCapturePage(w http.ResponseWriter, r *http.Request) {
if _, ok := s.gate(w, r); !ok {
return
}
s.render(w, "capture", map[string]any{"Nav": "capture", "Page": "capture", "Model": s.model})
}
// ---- entity create ----
func (s *server) handleEntityCreate(w http.ResponseWriter, r *http.Request) {
if _, ok := s.gate(w, r); !ok {
return
}
name := strings.TrimSpace(r.FormValue("name"))
kind := strings.TrimSpace(r.FormValue("kind"))
if kind == "" {
kind = "item"
}
if name == "" {
http.Error(w, "name required", 400)
return
}
now := time.Now().Unix()
res := mustExec(s.db,
`INSERT INTO entities (kind, name, notes, created_at, updated_at) VALUES (?,?,?,?,?)`,
kind, name, "", now, now)
id, _ := res.LastInsertId()
http.Redirect(w, r, fmt.Sprintf("/e/%d", id), http.StatusSeeOther)
}
// ---- entity detail / edit ----
func (s *server) handleEntity(w http.ResponseWriter, r *http.Request) {
if _, ok := s.gate(w, r); !ok {
return
}
id := atoi64(r.PathValue("id"))
if r.Method == http.MethodPost {
s.saveEntity(w, r, id)
return
}
e, err := loadEntity(s.db, id)
if err != nil {
http.NotFound(w, r)
return
}
rels, err := loadRelations(s.db, id)
if err != nil {
http.Error(w, "db error", 500)
return
}
photos, err := loadPhotoMetas(s.db, id)
if err != nil {
http.Error(w, "db error", 500)
return
}
// candidate entities to relate to (all others)
all, _ := loadEntities(s.db, "")
others := make([]entity, 0, len(all))
for _, o := range all {
if o.ID != id {
others = append(others, o)
}
}
data := map[string]any{
"Nav": "browse", "Page": "entity", "Model": s.model,
"E": e, "Relations": rels, "Photos": photos,
"Kinds": distinctKinds(s.db), "Others": others,
"HasPhotos": len(photos) > 0,
}
if isFragmentRequest(r) {
s.renderFragment(w, "entity_content", data)
return
}
s.render(w, "entity", data)
}
func (s *server) saveEntity(w http.ResponseWriter, r *http.Request, id int64) {
r.ParseForm()
name := strings.TrimSpace(r.FormValue("name"))
if name == "" {
http.Error(w, "name required", 400)
return
}
kind := strings.TrimSpace(r.FormValue("kind"))
if kind == "" {
kind = "item"
}
notes := r.FormValue("notes")
// attributes come as parallel attr_key[] / attr_value[] arrays
keys := r.Form["attr_key"]
values := r.Form["attr_value"]
tx, err := s.db.Begin()
if err != nil {
http.Error(w, "db error", 500)
return
}
defer tx.Rollback()
if _, err := tx.Exec(`UPDATE entities SET name=?, kind=?, notes=?, updated_at=? WHERE id=?`,
name, kind, notes, time.Now().Unix(), id); err != nil {
http.Error(w, "db error", 500)
return
}
if _, err := tx.Exec(`DELETE FROM entity_attrs WHERE entity_id = ?`, id); err != nil {
http.Error(w, "db error", 500)
return
}
seen := map[string]bool{}
for i := range keys {
k := strings.TrimSpace(keys[i])
if k == "" || seen[k] {
continue
}
seen[k] = true
v := ""
if i < len(values) {
v = strings.TrimSpace(values[i])
}
if _, err := tx.Exec(
`INSERT INTO entity_attrs (entity_id, key, value) VALUES (?,?,?)`, id, k, v); err != nil {
http.Error(w, "db error", 500)
return
}
}
if err := tx.Commit(); err != nil {
http.Error(w, "db error", 500)
return
}
http.Redirect(w, r, fmt.Sprintf("/e/%d", id), http.StatusSeeOther)
}
func (s *server) handleEntityDelete(w http.ResponseWriter, r *http.Request) {
if _, ok := s.gate(w, r); !ok {
return
}
mustExec(s.db, `DELETE FROM entities WHERE id = ?`, atoi64(r.PathValue("id")))
http.Redirect(w, r, "/", http.StatusSeeOther)
}
// ---- relations ----
func (s *server) handleRelationAdd(w http.ResponseWriter, r *http.Request) {
if _, ok := s.gate(w, r); !ok {
return
}
fromID := atoi64(r.FormValue("from_id"))
toID := atoi64(r.FormValue("to_id"))
rel := strings.TrimSpace(r.FormValue("rel"))
if fromID == 0 || toID == 0 || rel == "" || fromID == toID {
http.Redirect(w, r, fmt.Sprintf("/e/%d", fromID), http.StatusSeeOther)
return
}
mustExec(s.db, `INSERT INTO relations (from_id, to_id, rel) VALUES (?,?,?)`, fromID, toID, rel)
http.Redirect(w, r, fmt.Sprintf("/e/%d", fromID), http.StatusSeeOther)
}
func (s *server) handleRelationRemove(w http.ResponseWriter, r *http.Request) {
if _, ok := s.gate(w, r); !ok {
return
}
relID := atoi64(r.FormValue("id"))
back := atoi64(r.FormValue("entity_id"))
mustExec(s.db, `DELETE FROM relations WHERE id = ?`, relID)
http.Redirect(w, r, fmt.Sprintf("/e/%d", back), http.StatusSeeOther)
}
// ---- photos ----
// handlePhotoUpload accepts a multipart file upload and stores it as a blob.
func (s *server) handlePhotoUpload(w http.ResponseWriter, r *http.Request) {
if _, ok := s.gate(w, r); !ok {
return
}
entityID := atoi64(r.FormValue("entity_id"))
if entityID == 0 {
http.Error(w, "entity_id required", 400)
return
}
if err := r.ParseMultipartForm(32 << 20); err != nil {
http.Error(w, "bad upload", 400)
return
}
file, hdr, err := r.FormFile("photo")
if err != nil {
http.Redirect(w, r, fmt.Sprintf("/e/%d", entityID), http.StatusSeeOther)
return
}
defer file.Close()
buf := make([]byte, 0, hdr.Size)
tmp := make([]byte, 64*1024)
for {
n, err := file.Read(tmp)
if n > 0 {
buf = append(buf, tmp[:n]...)
}
if err != nil {
break
}
}
mime := hdr.Header.Get("Content-Type")
if mime == "" {
mime = "image/jpeg"
}
mustExec(s.db,
`INSERT INTO photos (entity_id, blob, mime, caption, created_at) VALUES (?,?,?,?,?)`,
entityID, buf, mime, strings.TrimSpace(r.FormValue("caption")), time.Now().Unix())
http.Redirect(w, r, fmt.Sprintf("/e/%d", entityID), http.StatusSeeOther)
}
func (s *server) handlePhotoServe(w http.ResponseWriter, r *http.Request) {
if _, ok := s.gate(w, r); !ok {
return
}
id := atoi64(r.PathValue("id"))
var blob []byte
var mime string
err := s.db.QueryRow(`SELECT blob, mime FROM photos WHERE id = ?`, id).Scan(&blob, &mime)
if err != nil {
http.NotFound(w, r)
return
}
if mime == "" {
mime = "image/jpeg"
}
w.Header().Set("Content-Type", mime)
w.Header().Set("Cache-Control", "private, max-age=86400")
w.Write(blob)
}
func (s *server) handlePhotoDelete(w http.ResponseWriter, r *http.Request) {
if _, ok := s.gate(w, r); !ok {
return
}
id := atoi64(r.FormValue("id"))
back := atoi64(r.FormValue("entity_id"))
mustExec(s.db, `DELETE FROM photos WHERE id = ?`, id)
http.Redirect(w, r, fmt.Sprintf("/e/%d", back), http.StatusSeeOther)
}
// ---- auth endpoints ----
func (s *server) handleLogin(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "method not allowed", 405)
return
}
var req struct {
Username string `json:"username"`
Token string `json:"token"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, "bad request", 400)
return
}
var isAdminInt int
var expiresAt int64
var usedAt sql.NullInt64
err := s.db.QueryRow(
`SELECT is_admin, expires_at, used_at FROM invite_tokens WHERE token=? AND username=?`,
req.Token, req.Username).Scan(&isAdminInt, &expiresAt, &usedAt)
if err != nil {
http.Error(w, "Invalid login link.", 401)
return
}
if usedAt.Valid {
http.Error(w, "Login link already used.", 401)
return
}
if time.Now().Unix() > expiresAt {
http.Error(w, "Login link expired.", 401)
return
}
mustExec(s.db, `UPDATE invite_tokens SET used_at=? WHERE token=?`, time.Now().Unix(), req.Token)
if existing, err := r.Cookie("session"); err == nil {
mustExec(s.db, `DELETE FROM sessions WHERE session_id = ?`, existing.Value)
}
sessionID := randomBase64(32)
mustExec(s.db, `INSERT INTO sessions (session_id, username, is_admin, created_at) VALUES (?,?,?,?)`,
sessionID, req.Username, isAdminInt, time.Now().Unix())
setSessionCookie(w, sessionID)
writeJSON(w, map[string]any{"ok": true, "username": req.Username, "is_admin": isAdminInt == 1})
}
func (s *server) handleMe(w http.ResponseWriter, r *http.Request) {
username, isAdmin, ok := requireSessionJSON(s.db, w, r)
if !ok {
return
}
writeJSON(w, map[string]any{"ok": true, "username": username, "is_admin": isAdmin})
}
// handleClientError logs a JS error reported by the browser. The SPA shell
// installs global window.onerror / unhandledrejection handlers that POST here,
// so client-side failures (anywhere in the SPA, not just an active capture
// WebSocket) surface in the server journal. Always logged via log.Printf and
// mirrored to dbg. Auth via the session cookie; a failure here must never break
// the page, so we accept best-effort and always return 204.
func (s *server) handleClientError(w http.ResponseWriter, r *http.Request) {
if _, _, ok := currentSession(s.db, w, r); !ok {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
var req struct {
Context string `json:"context"`
Text string `json:"text"`
URL string `json:"url"`
}
if err := json.NewDecoder(io.LimitReader(r.Body, 16<<10)).Decode(&req); err != nil {
w.WriteHeader(http.StatusNoContent)
return
}
ctx := strings.TrimSpace(req.Context)
if ctx == "" {
ctx = "client"
}
log.Printf("client error [%s] at %s: %s", ctx, req.URL, req.Text)
dbg("client error [%s] at %s: %s", ctx, req.URL, req.Text)
w.WriteHeader(http.StatusNoContent)
}
// ============================================================================
// Commands
// ============================================================================
const defaultBaseURL = "http://localhost:8773"
// defaultModel is the model id used unless overridden by --model. Sourced from
// the single ModelConfig in model.go.
var defaultModel = activeModel.ID
func cmdServe(dbPath, baseURL, addr, model string) {
db := openDB(dbPath)
defer db.Close()
s := &server{db: db, baseURL: baseURL, model: model, statsReg: newStatsRegistry()}
exe, _ := os.Executable()
if exe == "" {
exe = "inventory"
}
absDB, _ := filepath.Abs(dbPath)
if absDB == "" {
absDB = dbPath
}
fmt.Printf("Create a login link with:\n %s gen-link --admin --base-url %s %s\n", exe, baseURL, absDB)
mux := http.NewServeMux()
mux.HandleFunc("GET /", s.handleIndex)
mux.HandleFunc("GET /capture", s.handleCapturePage)
mux.HandleFunc("GET /ws/capture", s.authedCaptureWS)
mux.HandleFunc("GET /capture/stats", s.handleCaptureStats)
mux.HandleFunc("POST /entities", s.handleEntityCreate)
mux.HandleFunc("GET /e/{id}", s.handleEntity)
mux.HandleFunc("POST /e/{id}", s.handleEntity)
mux.HandleFunc("POST /e/{id}/delete", s.handleEntityDelete)
mux.HandleFunc("POST /relations/add", s.handleRelationAdd)
mux.HandleFunc("POST /relations/remove", s.handleRelationRemove)
mux.HandleFunc("POST /photos/upload", s.handlePhotoUpload)
mux.HandleFunc("GET /photos/{id}", s.handlePhotoServe)
mux.HandleFunc("POST /photos/delete", s.handlePhotoDelete)
mux.HandleFunc("POST /api/login", s.handleLogin)
mux.HandleFunc("GET /api/me", s.handleMe)
mux.HandleFunc("POST /api/client-error", s.handleClientError)
fmt.Fprintf(os.Stderr, "inventory: listening on http://%s (db: %s, model: %s)\n", addr, dbPath, model)
if err := http.ListenAndServe(addr, mux); err != nil {
log.Panicf("listen: %v", err)
}
}
func cmdGenLink(args []string) {
fs := flag.NewFlagSet("gen-link", flag.ExitOnError)
isAdmin := fs.Bool("admin", false, "generate an admin link")
username := fs.String("username", "", "username for the invite (default 'admin' if --admin)")
baseURL := fs.String("base-url", defaultBaseURL, "base URL for the link")
fs.Parse(args)
if fs.NArg() != 1 {
log.Panicf("usage: inventory gen-link [--admin] [--username <name>] [--base-url <url>] <db>")
}
if *username == "" {
if *isAdmin {
*username = "admin"
} else {
log.Panicf("--username is required for non-admin links")
}
}
db := openDB(fs.Arg(0))
defer db.Close()
fmt.Println(makeInviteToken(db, *baseURL, *username, *isAdmin, 12*time.Hour))
}
func defaultDBPath() string {
home, _ := os.UserHomeDir()
return filepath.Join(home, ".local", "share", "inventory", "inventory.db")
}
func main() {
log.SetFlags(0)
if len(os.Args) < 2 {
fmt.Fprintf(os.Stderr, "usage: inventory <command> [args]\n")
fmt.Fprintf(os.Stderr, "commands:\n")
fmt.Fprintf(os.Stderr, " serve [--addr host:port] [--base-url url] [--model name] <db>\n")
fmt.Fprintf(os.Stderr, " gen-link [--admin] [--username name] [--base-url url] <db>\n")
os.Exit(1)
}
switch os.Args[1] {
case "serve":
fs := flag.NewFlagSet("serve", flag.ExitOnError)
addr := fs.String("addr", "127.0.0.1:8773", "listen address")
baseURL := fs.String("base-url", defaultBaseURL, "base URL for invite links")
model := fs.String("model", defaultModel, "Gemini Live model")
fs.Parse(os.Args[2:])
dbPath := defaultDBPath()
if fs.NArg() >= 1 {
dbPath = fs.Arg(0)
}
cmdServe(dbPath, *baseURL, *addr, *model)
case "gen-link":
cmdGenLink(os.Args[2:])
case "live-test":
cmdLiveTest(os.Args[2:])
default:
log.Panicf("unknown command %q", os.Args[1])
}
}
|