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
package main

// Session storage.
//
// hans keeps every turn it has ever run, as a tree. This is not a feature that
// was designed and then built; it is the shape the Interactions API already
// has, written down instead of thrown away.
//
// Each call to that API names a `previous_interaction_id` and is answered with
// an id of its own. That is a parent pointer. The REPL used to keep only the
// newest id (`lastID`), overwriting it every turn, which walks one path through
// a structure that was always a tree and discards the rest. Storing the pointer
// instead of overwriting it costs one column and buys branching, resumption,
// and a second process reading the conversation while the first is having it.
//
// Two consequences are worth stating, because they are what make the HTTP
// server in serve.go simple:
//
//   - Two turns naming the same parent are siblings, not a conflict. The REPL
//     and an HTTP client can run against one session at the same time and
//     neither loses anything; they simply end up on different branches. This is
//     verified behaviour, not an assumption: the API accepts both children and
//     each inherits the parent's context.
//   - The store is append-only. Nothing is ever updated in place except a
//     session's name, so there is no lost update to protect against and no
//     lock to hold across a turn that takes a minute.
//
// The server's id encodes this too. Decoded, a v1_ id is a two-field protobuf
// whose first field is the root interaction's id and whose second is this
// one's — so the server is itself tracking the root of the tree we are storing.
// hans does not parse that; it is noted because it is the reason to trust that
// branching is intended rather than tolerated.

import (
	"bytes"
	"crypto/rand"
	"database/sql"
	"encoding/binary"
	"encoding/json"
	"fmt"
	"log"
	"os"
	"path/filepath"
	"reflect"
	"strconv"
	"strings"
	"time"

	_ "modernc.org/sqlite"
)

// ============================================================================
// Schema
// ============================================================================

// Each migration is applied exactly once, in order, tracked by schema_version.
// Never modify an existing migration — add a new one instead.

const storeMigration001 = `
CREATE TABLE schema_version (
  version     INTEGER PRIMARY KEY,
  applied_at  INTEGER NOT NULL
);

-- One conversation tree.
--
-- cwd is recorded because a session's turns ran tools against it: a transcript
-- of file reads means nothing without the directory the paths were relative
-- to. It is also what the server checks before running a turn, since it cannot
-- change directory per request.
CREATE TABLE sessions (
  id          INTEGER PRIMARY KEY AUTOINCREMENT,
  name        TEXT    NOT NULL,
  cwd         TEXT    NOT NULL,
  model       TEXT    NOT NULL,
  created_at  INTEGER NOT NULL
);
CREATE UNIQUE INDEX idx_sessions_name ON sessions(name);

-- One interaction: what we sent, what came back, and which node it followed.
--
-- parent_id is a local node id and is NULL at a root. interaction_id is the
-- server's id for the same turn, and is the pointer the next turn sends as
-- previous_interaction_id. Both are kept because they fail differently: the
-- server may evict an interaction, at which point interaction_id is worthless
-- and the conversation is reconstructed by walking parent_id to the root and
-- replaying. The local tree is the source of truth; the server's copy is a
-- bandwidth optimisation.
--
-- The step columns hold raw JSON exactly as it went over the wire, including
-- the opaque "signature" blobs on thought and function_call steps. Those are
-- backend-validated: a replayed history that has lost them is rejected, so
-- nothing here may normalise or prettify them.
--
--   input_json    steps we sent (user_input, or function_result on a tool turn)
--   output_json   steps the model returned (thought, model_output, function_call)
--   results_json  function_result steps produced by running this node's calls
--
-- error is set when a turn failed. Such a node is kept rather than rolled back:
-- an interrupted or failed turn is a thing that happened, and a client that
-- POSTed and lost its connection needs to find out which.
CREATE TABLE nodes (
  id              INTEGER PRIMARY KEY AUTOINCREMENT,
  session_id      INTEGER NOT NULL REFERENCES sessions(id),
  parent_id       INTEGER REFERENCES nodes(id),
  interaction_id  TEXT    NOT NULL DEFAULT '',
  input_json      TEXT    NOT NULL DEFAULT '[]',
  output_json     TEXT    NOT NULL DEFAULT '[]',
  results_json    TEXT    NOT NULL DEFAULT '[]',
  actor           TEXT    NOT NULL DEFAULT 'repl',
  usage_json      TEXT    NOT NULL DEFAULT '{}',
  error           TEXT    NOT NULL DEFAULT '',
  started_at      INTEGER NOT NULL,
  finished_at     INTEGER NOT NULL DEFAULT 0
);
CREATE INDEX idx_nodes_session ON nodes(session_id, id);
CREATE INDEX idx_nodes_parent ON nodes(parent_id);
`

// Which model answered a node.
//
// The JSON inside a node is one provider's wire format, and its signatures are
// one model's: a Gemini thought signature means nothing to Anthropic, and a
// Claude thinking signature is not accepted by a different Claude. A session
// records the model it was started with, but a branch may continue with
// another, so the session's model no longer says what wrote a given node. Each
// node records its own, and the backend replaying a path sends a node verbatim
// only when it is its own model's.
//
// Existing nodes are filled from their session, which is what answered them
// while a session could only have one model.
const storeMigration002 = `
ALTER TABLE nodes ADD COLUMN model TEXT NOT NULL DEFAULT '';
UPDATE nodes SET model = (SELECT s.model FROM sessions s WHERE s.id = nodes.session_id);
`

var storeMigrations = []string{storeMigration001, storeMigration002}

// ============================================================================
// Opening
// ============================================================================

// store is the pair of handles hans talks to SQLite through: one connection for
// writing, several for reading.
//
// The split is mailweb's, for mailweb's reason: SQLite admits one writer at a
// time, so writes are serialised to a single connection, while WAL exists
// precisely so readers never contend. Capping the whole pool at one would hand
// every page render the same queue as a running turn — and a turn holds its
// write for as long as the model takes to answer, which is up to a minute.
// Reads open the same file with mode=ro, so SQLite itself refuses a write
// issued through the wrong handle: the rule is enforced rather than merely
// stated.
type store struct {
	// Read serves every query that renders a page. Read-only at the SQLite
	// level, so it cannot be misused.
	Read *sql.DB
	// Write serves migrations and every mutation. One connection.
	Write *sql.DB
	// Path is the database file, kept for error messages.
	Path string
}

// readPoolSize is how many concurrent reads may be in flight. This is a
// single-user application behind a loopback address; the figure only has to
// cover a handful of agents reading while one turn writes.
const readPoolSize = 4

// DefaultDBPath is where sessions live unless -db says otherwise. It follows
// XDG_DATA_HOME so the database is not in the working directory: hans is run
// from whichever project is being worked on, and a per-directory database would
// scatter sessions across the filesystem and hide the tree from itself.
func DefaultDBPath() string {
	dir := os.Getenv("XDG_DATA_HOME")
	if dir == "" {
		home, err := os.UserHomeDir()
		if err != nil {
			// Nothing better is available, and returning an error here would
			// oblige every caller to handle a case that cannot happen on a
			// system with a home directory.
			return "hans.db"
		}
		dir = filepath.Join(home, ".local", "share")
	}
	return filepath.Join(dir, "hans", "hans.db")
}

// openStore opens (creating if needed) the session database and applies
// migrations.
func openStore(path string) (*store, error) {
	if dir := filepath.Dir(path); dir != "" {
		if err := os.MkdirAll(dir, 0o700); err != nil {
			return nil, fmt.Errorf("create %s: %w", dir, err)
		}
	}

	// The pragmas travel in the DSN rather than a post-open PRAGMA because
	// busy_timeout is per-connection state: the modernc driver applies _pragma
	// parameters to every connection it opens, whereas db.Exec("PRAGMA …")
	// configures only whichever pooled connection happens to run it.
	write, err := sql.Open("sqlite",
		"file:"+path+"?_pragma=busy_timeout(30000)&_pragma=journal_mode(WAL)")
	if err != nil {
		return nil, fmt.Errorf("open db: %w", err)
	}
	write.SetMaxOpenConns(1)

	if err := migrateStore(write); err != nil {
		write.Close()
		return nil, err
	}

	// Opened after migrations rather than beside them: mode=ro cannot create a
	// file, so on a fresh install this must run once the writer has made one.
	//
	// No journal_mode pragma here. Setting it writes to the database header,
	// which a read-only connection may not do; the mode is a property of the
	// file the writer has already established.
	read, err := sql.Open("sqlite",
		"file:"+path+"?mode=ro&_pragma=busy_timeout(30000)")
	if err != nil {
		write.Close()
		return nil, fmt.Errorf("open read pool: %w", err)
	}
	read.SetMaxOpenConns(readPoolSize)
	// sql.Open is lazy, so a bad path would otherwise surface on the first
	// query rather than at startup.
	if err := read.Ping(); err != nil {
		read.Close()
		write.Close()
		return nil, fmt.Errorf("ping read pool: %w", err)
	}

	return &store{Read: read, Write: write, Path: path}, nil
}

func (s *store) Close() error {
	if s == nil {
		return nil
	}
	var firstErr error
	if s.Read != nil {
		if err := s.Read.Close(); err != nil {
			firstErr = err
		}
	}
	if s.Write != nil {
		if err := s.Write.Close(); err != nil && firstErr == nil {
			firstErr = err
		}
	}
	return firstErr
}

func migrateStore(db *sql.DB) error {
	var tableCount int
	err := db.QueryRow(
		`SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name='schema_version'`,
	).Scan(&tableCount)
	if err != nil {
		return fmt.Errorf("check schema_version: %w", err)
	}

	current := 0
	if tableCount > 0 {
		var v sql.NullInt64
		if err := db.QueryRow(`SELECT MAX(version) FROM schema_version`).Scan(&v); err != nil {
			return fmt.Errorf("read schema version: %w", err)
		}
		if v.Valid {
			current = int(v.Int64)
		}
	}

	for i, migration := range storeMigrations {
		version := i + 1
		if version <= current {
			continue
		}
		log.Printf("db: applying migration %d", version)
		tx, err := db.Begin()
		if err != nil {
			return fmt.Errorf("begin migration %d: %w", version, err)
		}
		if _, err := tx.Exec(migration); err != nil {
			tx.Rollback()
			return fmt.Errorf("migration %d: %w", version, err)
		}
		if _, err := tx.Exec(
			`INSERT INTO schema_version (version, applied_at) VALUES (?, ?)`,
			version, time.Now().Unix(),
		); err != nil {
			tx.Rollback()
			return fmt.Errorf("record migration %d: %w", version, err)
		}
		if err := tx.Commit(); err != nil {
			return fmt.Errorf("commit migration %d: %w", version, err)
		}
	}
	return nil
}

// ============================================================================
// Types
// ============================================================================

// session is one conversation tree.
type session struct {
	ID        int64
	Name      string
	Cwd       string
	Model     string
	CreatedAt time.Time

	// Nodes and LastAt are populated by listSessions for the index rendering,
	// and are zero elsewhere.
	Nodes  int
	LastAt time.Time
}

// node is one interaction.
type node struct {
	ID        int64
	SessionID int64
	ParentID  int64 // 0 at a root
	// Model is the model that answered this node, and therefore whose wire
	// format its steps are in. See storeMigration002.
	Model         string
	InteractionID string
	Input         []json.RawMessage
	Output        []json.RawMessage
	Results       []json.RawMessage
	Actor         string
	Usage         interactionUsage
	Error         string
	StartedAt     time.Time
	FinishedAt    time.Time

	// Children is the number of nodes naming this one as parent. It is what
	// makes a leaf visible as a leaf, and a branch point as a branch point.
	// Populated by the queries that render trees; zero elsewhere.
	Children int
}

// IsLeaf reports whether nothing follows this node, i.e. whether it is a head
// a turn can be appended to without branching.
func (n node) IsLeaf() bool { return n.Children == 0 }

// Duration is how long the turn took, or zero if it never finished.
func (n node) Duration() time.Duration {
	if n.FinishedAt.IsZero() || n.StartedAt.IsZero() {
		return 0
	}
	return n.FinishedAt.Sub(n.StartedAt)
}

// ============================================================================
// Writing
// ============================================================================

// errNameTaken is returned when a caller asked for a session name that already
// exists. It is a distinct error because it is the caller's mistake and not a
// fault: answering it with a 500 would report a database failure for what is a
// name collision, and send whoever hit it looking in the wrong place.
var errNameTaken = fmt.Errorf("session name already taken")

// createSession records a new conversation tree. A name is generated when none
// is given, because a session that is only ever an integer is unusable from the
// command line and unmemorable in a listing.
func (s *store) createSession(name, cwd, model string) (*session, error) {
	if name == "" {
		var err error
		name, err = s.uniqueName()
		if err != nil {
			return nil, err
		}
	}
	now := time.Now()
	res, err := s.Write.Exec(
		`INSERT INTO sessions (name, cwd, model, created_at) VALUES (?, ?, ?, ?)`,
		name, cwd, model, now.Unix())
	if err != nil {
		// The unique index on name is the only constraint that a caller can
		// trip, so this is matched on rather than inspected through the
		// driver's error type: modernc's is not part of database/sql, and
		// depending on it would tie this to that driver.
		if strings.Contains(err.Error(), "UNIQUE constraint failed: sessions.name") {
			return nil, fmt.Errorf("%w: %q", errNameTaken, name)
		}
		return nil, fmt.Errorf("create session: %w", err)
	}
	id, err := res.LastInsertId()
	if err != nil {
		return nil, fmt.Errorf("create session: %w", err)
	}
	return &session{ID: id, Name: name, Cwd: cwd, Model: model, CreatedAt: now}, nil
}

// beginNode records a turn that is about to run, before the model is called.
//
// The node exists in the database while the turn is in flight, so a client that
// disconnects from a blocking POST can still find out what happened, and a
// crash leaves evidence rather than silence. finishNode completes it.
func (s *store) beginNode(sessionID, parentID int64, model, actor string, input []json.RawMessage) (int64, error) {
	var parent any
	if parentID != 0 {
		parent = parentID
	}
	res, err := s.Write.Exec(
		`INSERT INTO nodes (session_id, parent_id, model, actor, input_json, started_at)
		 VALUES (?, ?, ?, ?, ?, ?)`,
		sessionID, parent, model, actor, marshalSteps(input), time.Now().Unix())
	if err != nil {
		return 0, fmt.Errorf("begin node: %w", err)
	}
	id, err := res.LastInsertId()
	if err != nil {
		return 0, fmt.Errorf("begin node: %w", err)
	}
	return id, nil
}

// finishNode completes a node begun by beginNode.
func (s *store) finishNode(id int64, interactionID string, output, results []json.RawMessage, usage interactionUsage, turnErr string) error {
	usageJSON, err := json.Marshal(usage)
	if err != nil {
		usageJSON = []byte("{}")
	}
	_, err = s.Write.Exec(
		`UPDATE nodes
		    SET interaction_id = ?, output_json = ?, results_json = ?,
		        usage_json = ?, error = ?, finished_at = ?
		  WHERE id = ?`,
		interactionID, marshalSteps(output), marshalSteps(results),
		string(usageJSON), turnErr, time.Now().Unix(), id)
	if err != nil {
		return fmt.Errorf("finish node: %w", err)
	}
	return nil
}

// marshalSteps renders a step list as JSON, never failing: the steps are raw
// JSON already, so the only way this can go wrong is a nil slice.
//
// The steps are joined, not re-encoded. json.Marshal would rewrite each one —
// escaping <, > and & among other things — and a stored step must be the
// bytes that went over the wire: a provider checks thinking signatures and
// caches prompts by prefix, and the replay recognises a tool round sent twice
// by comparing bytes (carriesResults).
func marshalSteps(steps []json.RawMessage) string {
	if len(steps) == 0 {
		return "[]"
	}
	return string(rawList(steps))
}

func unmarshalSteps(s string) []json.RawMessage {
	if s == "" || s == "[]" {
		return nil
	}
	var out []json.RawMessage
	if err := json.Unmarshal([]byte(s), &out); err != nil {
		return nil
	}
	return out
}

// ============================================================================
// Names
// ============================================================================
//
// A session needs a handle that survives being typed into a terminal and read
// out of a listing. The row id is neither: "run a turn on 47" says nothing
// about which conversation 47 is, and two ids differing in one digit are two
// different conversations.
//
// So each session gets a two-word name — `amber-heron`, `quiet-fig` — drawn at
// creation. The pairs are deliberately concrete and unrelated to each other, so
// that two names differ in more than one letter and a misremembered one fails
// to resolve rather than resolving to somebody else's session. Names are unique
// (there is a unique index) and both name and id address a session, so a client
// holding either can use it.

var nameAdjectives = []string{
	"amber", "brisk", "calm", "dusky", "eager", "faint", "glad", "hazy",
	"idle", "jolly", "keen", "lucid", "mellow", "noble", "opal", "plain",
	"quiet", "rapid", "sable", "tidy", "umber", "vivid", "warm", "young",
}

var nameNouns = []string{
	"alder", "brook", "cedar", "dune", "elm", "fig", "grove", "heron",
	"iris", "juniper", "kelp", "larch", "moss", "nettle", "oak", "pine",
	"quince", "reed", "sedge", "thorn", "umbel", "vine", "willow", "yarrow",
}

// uniqueName draws names until one is free.
//
// The retry is bounded rather than a bare loop: with 576 combinations a
// database holding most of them would otherwise spin, and the fallback appends
// the row-id-like suffix that guarantees termination. Running out of names is a
// sign of a database nobody has pruned, not an error worth refusing on.
func (s *store) uniqueName() (string, error) {
	for attempt := 0; attempt < 40; attempt++ {
		name := randomName()
		var exists int
		err := s.Read.QueryRow(`SELECT COUNT(*) FROM sessions WHERE name = ?`, name).Scan(&exists)
		if err != nil {
			return "", fmt.Errorf("check name: %w", err)
		}
		if exists == 0 {
			return name, nil
		}
	}
	return fmt.Sprintf("%s-%d", randomName(), time.Now().UnixNano()%100000), nil
}

func randomName() string {
	adj := nameAdjectives[randIndex(len(nameAdjectives))]
	noun := nameNouns[randIndex(len(nameNouns))]
	return adj + "-" + noun
}

// randIndex draws a uniform index using the system CSPRNG. These names are not
// secrets — they are handles in a listing — but crypto/rand is already imported
// for the delimiter tokens and needs no seeding, whereas math/rand would need
// to be seeded correctly to avoid every process picking the same first name.
func randIndex(n int) int {
	b := make([]byte, 2)
	if _, err := rand.Read(b); err != nil {
		return 0
	}
	return int(binary.BigEndian.Uint16(b)) % n
}

// ============================================================================
// Reading
// ============================================================================

// listSessions returns every session, most recently active first.
//
// "Active" is the newest node, not the creation time: a session returned to
// after a week belongs at the top, and one created and abandoned does not.
func (s *store) listSessions() ([]session, error) {
	rows, err := s.Read.Query(`
		SELECT se.id, se.name, se.cwd, se.model, se.created_at,
		       COUNT(n.id),
		       COALESCE(MAX(n.started_at), se.created_at)
		  FROM sessions se
		  LEFT JOIN nodes n ON n.session_id = se.id
		 GROUP BY se.id
		 ORDER BY COALESCE(MAX(n.started_at), se.created_at) DESC`)
	if err != nil {
		return nil, fmt.Errorf("list sessions: %w", err)
	}
	defer rows.Close()

	var out []session
	for rows.Next() {
		var se session
		var created, last int64
		if err := rows.Scan(&se.ID, &se.Name, &se.Cwd, &se.Model, &created, &se.Nodes, &last); err != nil {
			return nil, fmt.Errorf("scan session: %w", err)
		}
		se.CreatedAt = time.Unix(created, 0)
		se.LastAt = time.Unix(last, 0)
		out = append(out, se)
	}
	return out, rows.Err()
}

// findSession looks a session up by name or by id, so that a URL and a command
// line can use whichever the reader has.
//
// Name is tried first and separately, rather than in one `name = ? OR id = ?`
// query. Names are generated but may also be given, and nothing stops a session
// being called "5"; in a single query that session and the session with id 5
// both match and SQLite picks one. Whichever it picked would be right half the
// time, which is the worst available behaviour. Trying the name first makes the
// rule statable: an explicit name wins, and an id resolves only when no session
// answers to it as a name.
func (s *store) findSession(ref string) (*session, error) {
	sess, err := s.sessionWhere(`name = ?`, ref)
	if err != nil || sess != nil {
		return sess, err
	}
	id, err := strconv.ParseInt(ref, 10, 64)
	if err != nil {
		return nil, nil
	}
	return s.sessionWhere(`id = ?`, id)
}

// sessionByID looks a session up by row id alone. It exists so that internal
// callers, which hold an id and not a name, cannot be misdirected by a session
// named after a number.
func (s *store) sessionByID(id int64) (*session, error) {
	return s.sessionWhere(`id = ?`, id)
}

func (s *store) sessionWhere(cond string, arg any) (*session, error) {
	var se session
	var created int64
	err := s.Read.QueryRow(
		`SELECT id, name, cwd, model, created_at FROM sessions WHERE `+cond, arg).
		Scan(&se.ID, &se.Name, &se.Cwd, &se.Model, &created)
	if err == sql.ErrNoRows {
		return nil, nil
	}
	if err != nil {
		return nil, fmt.Errorf("find session (%s): %w", cond, err)
	}
	se.CreatedAt = time.Unix(created, 0)
	return &se, nil
}

// nodeColumns is the select list every node query shares, including the child
// count that distinguishes a leaf from a branch point.
const nodeColumns = `
	n.id, n.session_id, COALESCE(n.parent_id, 0), n.model, n.interaction_id,
	n.input_json, n.output_json, n.results_json, n.actor, n.usage_json,
	n.error, n.started_at, n.finished_at,
	(SELECT COUNT(*) FROM nodes c WHERE c.parent_id = n.id)`

func scanNode(sc interface{ Scan(...any) error }) (node, error) {
	var n node
	var input, output, results, usage string
	var started, finished int64
	err := sc.Scan(&n.ID, &n.SessionID, &n.ParentID, &n.Model, &n.InteractionID,
		&input, &output, &results, &n.Actor, &usage,
		&n.Error, &started, &finished, &n.Children)
	if err != nil {
		return node{}, err
	}
	n.Input = unmarshalSteps(input)
	n.Output = unmarshalSteps(output)
	n.Results = unmarshalSteps(results)
	json.Unmarshal([]byte(usage), &n.Usage)
	n.StartedAt = time.Unix(started, 0)
	if finished > 0 {
		n.FinishedAt = time.Unix(finished, 0)
	}
	return n, nil
}

// getNode returns one node by id, or nil when there is none.
func (s *store) getNode(id int64) (*node, error) {
	row := s.Read.QueryRow(`SELECT `+nodeColumns+` FROM nodes n WHERE n.id = ?`, id)
	n, err := scanNode(row)
	if err == sql.ErrNoRows {
		return nil, nil
	}
	if err != nil {
		return nil, fmt.Errorf("get node %d: %w", id, err)
	}
	return &n, nil
}

// sessionNodes returns every node of a session in creation order.
func (s *store) sessionNodes(sessionID int64) ([]node, error) {
	rows, err := s.Read.Query(
		`SELECT `+nodeColumns+` FROM nodes n WHERE n.session_id = ? ORDER BY n.id`,
		sessionID)
	if err != nil {
		return nil, fmt.Errorf("session nodes: %w", err)
	}
	defer rows.Close()

	var out []node
	for rows.Next() {
		n, err := scanNode(rows)
		if err != nil {
			return nil, fmt.Errorf("scan node: %w", err)
		}
		out = append(out, n)
	}
	return out, rows.Err()
}

// head returns the node a turn should follow by default: the newest leaf of the
// session.
//
// Newest rather than "the only one" because a branched session has several
// leaves and something has to be chosen; newest is the one a reader most likely
// just made. A client that wants a different branch names its node explicitly,
// which is the whole point of addressing nodes.
//
// Returns nil for a session with no nodes yet, whose next turn is its root.
func (s *store) head(sessionID int64) (*node, error) {
	row := s.Read.QueryRow(`
		SELECT `+nodeColumns+`
		  FROM nodes n
		 WHERE n.session_id = ?
		   AND NOT EXISTS (SELECT 1 FROM nodes c WHERE c.parent_id = n.id)
		 ORDER BY n.id DESC
		 LIMIT 1`, sessionID)
	n, err := scanNode(row)
	if err == sql.ErrNoRows {
		return nil, nil
	}
	if err != nil {
		return nil, fmt.Errorf("head of session %d: %w", sessionID, err)
	}
	return &n, nil
}

// pathTo returns the nodes from the root of the tree down to id, inclusive.
//
// This is the conversation as the model saw it at that point, and it is what
// gets replayed when the server has forgotten an interaction. It is also the
// reason branching costs nothing to read: two branches share this prefix and
// diverge only at the node where they were taken.
//
// The walk is a recursive CTE rather than a loop of queries because the depth
// is unbounded and a query per turn would make reading a long session O(n)
// round trips.
func (s *store) pathTo(id int64) ([]node, error) {
	rows, err := s.Read.Query(`
		WITH RECURSIVE ancestry(id) AS (
		    SELECT ?
		    UNION ALL
		    SELECT n.parent_id FROM nodes n JOIN ancestry a ON n.id = a.id
		     WHERE n.parent_id IS NOT NULL
		)
		SELECT `+nodeColumns+`
		  FROM nodes n JOIN ancestry a ON n.id = a.id
		 ORDER BY n.id`, id)
	if err != nil {
		return nil, fmt.Errorf("path to %d: %w", id, err)
	}
	defer rows.Close()

	var out []node
	for rows.Next() {
		n, err := scanNode(rows)
		if err != nil {
			return nil, fmt.Errorf("scan node: %w", err)
		}
		out = append(out, n)
	}
	return out, rows.Err()
}

// carriesResults reports whether next is the continuation that sent results
// back to the model, i.e. whether it will replay them as its own input.
func carriesResults(next node, results []json.RawMessage) bool {
	if next.Error != "" || len(results) == 0 || len(next.Input) != len(results) {
		return false
	}
	for i := range results {
		if !sameJSON(next.Input[i], results[i]) {
			return false
		}
	}
	return true
}

// sameJSON compares two encodings of a step. Equal bytes are the common
// case; otherwise they are compared as values, since nodes written before
// steps were stored verbatim hold re-encoded copies (with <, > and &
// escaped) of what the next node holds raw.
func sameJSON(a, b json.RawMessage) bool {
	if bytes.Equal(a, b) {
		return true
	}
	var va, vb any
	if json.Unmarshal(a, &va) != nil || json.Unmarshal(b, &vb) != nil {
		return false
	}
	return reflect.DeepEqual(va, vb)
}