v0.3.1 5c1a9ec

session_portable.go RawHistoryFolder

1package core
2
3import (
4	"bufio"
5	"bytes"
6	"encoding/json"
7	"errors"
8	"fmt"
9	"io"
10	"os"
11	"path/filepath"
12	"sort"
13	"strings"
14	"time"
15
16	"github.com/bnema/zut/packages/provider"
17	"github.com/google/uuid"
18)
19
20// PortableExt is the filesystem extension used for exported sessions.
21// A ".zutsession" is just a zut JSONL session file with the meta
22// header rewritten so the importing user gets fresh ownership.
23const PortableExt = ".zutsession"
24
25// ExportSession writes the session at srcPath to dstPath as a
26// portable .zutsession file. If dstPath is an existing directory the
27// file is created inside it with a name derived from the session's
28// meta ("YYYYMMDD-HHMMSS-<first-prompt-excerpt>.zutsession"). The
29// destination's directory is created if needed. Returns the final
30// resolved path so the caller can tell the user where it landed.
31//
32// The on-disk format is unchanged from a live session; only the
33// meta.cwd is stripped of its per-machine prefix (the importing
34// user doesn't care what directory it came from). Everything else
35// round-trips byte-for-byte.
36func ExportSession(srcPath, dstPath string) (string, error) {
37	if srcPath == "" {
38		return "", errors.New("export: source path is empty")
39	}
40	if dstPath == "" {
41		return "", errors.New("export: destination path is empty")
42	}
43
44	// Read the effective snapshot so a later model/provider update is not
45	// replaced by the stale metadata in the first row.
46	snapshot, err := ReadSessionSnapshot(srcPath)
47	if err != nil {
48		return "", fmt.Errorf("export: read session snapshot: %w", err)
49	}
50
51	// Read the source meta up-front so we can name the output sensibly
52	// when dstPath is a directory, and so we can validate it's a real
53	// session before starting to write.
54	src, err := os.Open(srcPath)
55	if err != nil {
56		return "", fmt.Errorf("export: open source: %w", err)
57	}
58	defer src.Close()
59
60	sc := bufio.NewScanner(src)
61	sc.Buffer(make([]byte, 0, 64*1024), 20*1024*1024)
62	if !sc.Scan() {
63		return "", errors.New("export: session file is empty")
64	}
65	var head sessionLine
66	if err := json.Unmarshal(sc.Bytes(), &head); err != nil {
67		return "", fmt.Errorf("export: parse meta: %w", err)
68	}
69	if head.Type != "meta" || head.Meta == nil {
70		return "", errors.New("export: first line is not a meta row")
71	}
72
73	// Scan the rest of the file for the first user message so we can
74	// build a humane filename. Only reads if dstPath doesn't already
75	// end in .zutsession.
76	firstPrompt := ""
77	if !strings.HasSuffix(strings.ToLower(dstPath), PortableExt) {
78		if fi, _ := os.Stat(dstPath); fi == nil || fi.IsDir() {
79			p, err := firstUserPrompt(src)
80			if err != nil {
81				return "", fmt.Errorf("export: read first prompt: %w", err)
82			}
83			firstPrompt = p
84		}
85	}
86
87	// Resolve dstPath: if it's a directory, build a name inside it.
88	outPath := dstPath
89	if fi, err := os.Stat(dstPath); err == nil && fi.IsDir() {
90		name := filenameFor(head.Meta.Started, head.Meta.ID, firstPrompt)
91		outPath = filepath.Join(dstPath, name)
92	} else if !strings.HasSuffix(strings.ToLower(outPath), PortableExt) {
93		outPath += PortableExt
94	}
95
96	// Re-open the source from the top since we advanced the scanner.
97	if _, err := src.Seek(0, io.SeekStart); err != nil {
98		return "", fmt.Errorf("export: rewind: %w", err)
99	}
100
101	if err := os.MkdirAll(filepath.Dir(outPath), 0o755); err != nil {
102		return "", fmt.Errorf("export: mkdir dst: %w", err)
103	}
104	dst, err := os.OpenFile(outPath, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o644)
105	if err != nil {
106		return "", fmt.Errorf("export: create dst: %w", err)
107	}
108	defer dst.Close()
109	bw := bufio.NewWriter(dst)
110
111	// Rewrite the meta row: strip the cwd (the importing user has
112	// their own) and keep everything else identical. ID stays so the
113	// export is traceable; the importer will rotate to a fresh ID.
114	exportMeta := snapshot.Meta
115	exportMeta.CWD = ""
116	metaLine, err := json.Marshal(sessionLine{Type: "meta", Meta: &exportMeta})
117	if err != nil {
118		return "", fmt.Errorf("export: marshal meta: %w", err)
119	}
120	if _, err := bw.Write(metaLine); err != nil {
121		return "", err
122	}
123	if err := bw.WriteByte('\n'); err != nil {
124		return "", err
125	}
126
127	// Stream every non-meta row verbatim. Use ReadBytes instead of
128	// bufio.Scanner: large sessions can contain very long JSONL rows
129	// (image blocks, big tool outputs, compacted history) that exceed
130	// Scanner's token limit and fail with "token too long".
131	r := bufio.NewReader(src)
132	for {
133		line, err := r.ReadBytes('\n')
134		if len(line) > 0 {
135			line = bytes.TrimRight(line, "\r\n")
136			var h sessionLineHead
137			if err := json.Unmarshal(line, &h); err == nil && h.Type != "meta" {
138				if _, werr := bw.Write(line); werr != nil {
139					return "", werr
140				}
141				if werr := bw.WriteByte('\n'); werr != nil {
142					return "", werr
143				}
144			}
145		}
146		if err == io.EOF {
147			break
148		}
149		if err != nil {
150			return "", fmt.Errorf("export: read source: %w", err)
151		}
152	}
153	if err := bw.Flush(); err != nil {
154		return "", err
155	}
156	return outPath, nil
157}
158
159// ImportSession copies the .zutsession file at srcPath into the
160// running user's session store under the given root+cwd, rewriting
161// the meta's id / cwd / started fields so the imported session is
162// owned by the current user / directory / clock. Returns the path
163// of the created session file, ready to pass to OpenSession.
164//
165// The imported session is a first-class zut session: it'll show up
166// in /sessions, /jump, and on-disk summaries just like any other.
167// Messages and usage rows are preserved verbatim.
168func ImportSession(srcPath, root, cwd, version string) (string, error) {
169	if srcPath == "" {
170		return "", errors.New("import: source path is empty")
171	}
172	src, err := os.Open(srcPath)
173	if err != nil {
174		return "", fmt.Errorf("import: open source: %w", err)
175	}
176	defer src.Close()
177
178	// Read the effective metadata before committing to a destination. Meta
179	// rows are append-only, so the first row may describe an older provider or
180	// model after a runtime switch.
181	snapshot, err := ReadSessionSnapshot(srcPath)
182	if err != nil {
183		return "", fmt.Errorf("import: read session snapshot: %w", err)
184	}
185
186	// Validate the file header before committing to a destination.
187	sc := bufio.NewScanner(src)
188	sc.Buffer(make([]byte, 0, 64*1024), 20*1024*1024)
189	if !sc.Scan() {
190		return "", errors.New("import: session file is empty")
191	}
192	var head sessionLine
193	if err := json.Unmarshal(sc.Bytes(), &head); err != nil {
194		return "", fmt.Errorf("import: parse meta: %w", err)
195	}
196	if head.Type != "meta" || head.Meta == nil {
197		return "", errors.New("import: first line is not a meta row")
198	}
199
200	// Build the destination inside the current cwd's session dir
201	// with a fresh timestamped name.
202	dir := SessionsDir(root, cwd)
203	if err := os.MkdirAll(dir, 0o755); err != nil {
204		return "", err
205	}
206	newID := uuid.NewString()
207	name := fmt.Sprintf("%s-%s.jsonl", time.Now().UTC().Format("20060102-150405"), newID[:8])
208	outPath := filepath.Join(dir, name)
209	dst, err := os.OpenFile(outPath, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o644)
210	if err != nil {
211		return "", fmt.Errorf("import: create dst: %w", err)
212	}
213	defer dst.Close()
214	bw := bufio.NewWriter(dst)
215
216	// Write a fresh meta row claiming ownership.
217	importMeta := SessionMeta{
218		ID:       newID,
219		CWD:      cwd,
220		Model:    snapshot.Meta.Model,
221		Provider: snapshot.Meta.Provider,
222		Started:  time.Now().UTC(),
223		Version:  version,
224		Title:    snapshot.Title,
225	}
226	metaLine, err := json.Marshal(sessionLine{Type: "meta", Meta: &importMeta})
227	if err != nil {
228		return "", fmt.Errorf("import: marshal meta: %w", err)
229	}
230	if _, err := bw.Write(metaLine); err != nil {
231		return "", err
232	}
233	if err := bw.WriteByte('\n'); err != nil {
234		return "", err
235	}
236
237	// Rewind the source and stream every non-meta row. Avoid
238	// bufio.Scanner so exported sessions with huge JSONL rows import
239	// cleanly.
240	if _, err := src.Seek(0, io.SeekStart); err != nil {
241		return "", fmt.Errorf("import: rewind: %w", err)
242	}
243	if err := forEachJSONLLine(src, func(line []byte) error {
244		var h sessionLineHead
245		if err := json.Unmarshal(line, &h); err != nil || h.Type == "meta" {
246			return nil
247		}
248		if _, err := bw.Write(line); err != nil {
249			return err
250		}
251		return bw.WriteByte('\n')
252	}); err != nil {
253		return "", fmt.Errorf("import: read source: %w", err)
254	}
255	if err := bw.Flush(); err != nil {
256		return "", err
257	}
258	return outPath, nil
259}
260
261// BranchSession creates a new session in root/cwd that contains the
262// parent's messages 0..upToMessageIdx-1 (i.e. the first N user+
263// assistant+tool rows). The new meta records Parent=<parent id> and
264// ForkPoint=N so /session tree can rebuild the branch topology
265// later. The effective repaired prefix is materialized, and all eligible
266// usage checkpoints at or before the cut are preserved so the running cost
267// tracker can reconstruct the final-turn delta. A boundary that ends on a
268// tool call is extended through its paired tool result.
269//
270// upToMessageIdx is a count over the flat message stream as
271// returned by OpenSession. To "branch at user turn 3" the caller
272// passes the index of that user message in msgs + 1 (so the
273// message itself is included). The caller figures that out; this
274// helper rejects a count outside the current effective snapshot.
275//
276// Returns the path of the new session file, ready for OpenSession.
277func BranchSession(parentPath, root, cwd, version string, upToMessageIdx int) (string, error) {
278	return branchSession(parentPath, root, cwd, version, upToMessageIdx, false)
279}
280
281// BranchSessionHidden creates a branch that participates in /session tree but
282// is hidden from the flat /sessions picker. Used for in-place tree navigation.
283func BranchSessionHidden(parentPath, root, cwd, version string, upToMessageIdx int) (string, error) {
284	return branchSession(parentPath, root, cwd, version, upToMessageIdx, true)
285}
286
287func branchSession(parentPath, root, cwd, version string, upToMessageIdx int, hideFromSessions bool) (string, error) {
288	if parentPath == "" {
289		return "", errors.New("branch: parent path is empty")
290	}
291	if upToMessageIdx < 0 {
292		return "", errors.New("branch: upToMessageIdx must be >= 0")
293	}
294
295	snapshot, err := ReadSessionSnapshot(parentPath)
296	if err != nil {
297		return "", fmt.Errorf("branch: read parent snapshot: %w", err)
298	}
299	if upToMessageIdx > len(snapshot.Messages) {
300		return "", fmt.Errorf("branch: upToMessageIdx %d exceeds effective message count %d", upToMessageIdx, len(snapshot.Messages))
301	}
302
303	// A tool-call row is not a safe provider boundary by itself. Accept the
304	// convenient row index used by existing callers, but extend it through the
305	// immediately paired tool result when necessary. Orphan calls already have
306	// a synthetic result in the shared snapshot.
307	limit := upToMessageIdx
308	if limit > 0 && limit < len(snapshot.Messages) && messageHasToolCalls(snapshot.Messages[limit-1]) && snapshot.Messages[limit].Role == provider.RoleTool {
309		limit++
310	}
311
312	extensionState, err := readExtensionStateAtFork(parentPath, limit)
313	if err != nil {
314		return "", err
315	}
316	return writeBranchSession(root, cwd, version, snapshot.Meta, snapshot.Messages, snapshot.UsageCheckpoints, limit, hideFromSessions, extensionState)
317}
318
319// BranchSessionHiddenFromHistory creates a hidden tree branch from a
320// pre-compaction transcript segment. The segment is already repaired and is
321// kept separate from the effective snapshot so normal resume semantics remain
322// unchanged while older fork points stay usable.
323func BranchSessionHiddenFromHistory(parentPath, root, cwd, version string, segment SessionHistorySegment, upToMessageIdx int) (string, error) {
324	if parentPath == "" {
325		return "", errors.New("branch: parent path is empty")
326	}
327	if upToMessageIdx < 0 {
328		return "", errors.New("branch: upToMessageIdx must be >= 0")
329	}
330	if upToMessageIdx > len(segment.Messages) {
331		return "", fmt.Errorf("branch: upToMessageIdx %d exceeds historical message count %d", upToMessageIdx, len(segment.Messages))
332	}
333
334	snapshot, err := ReadSessionSnapshot(parentPath)
335	if err != nil {
336		return "", fmt.Errorf("branch: read parent snapshot: %w", err)
337	}
338	limit := upToMessageIdx
339	if limit > 0 && limit < len(segment.Messages) && messageHasToolCalls(segment.Messages[limit-1]) && segment.Messages[limit].Role == provider.RoleTool {
340		limit++
341	}
342	extensionState, err := readExtensionStateAtFork(parentPath, limit)
343	if err != nil {
344		return "", err
345	}
346	return writeBranchSession(root, cwd, version, snapshot.Meta, segment.Messages, segment.UsageCheckpoints, limit, true, extensionState)
347}
348
349// readExtensionStateAtFork reconstructs the latest extension snapshot that was
350// persisted at or before a branch boundary. Extension state is independent of
351// provider messages, but its timeline still follows the effective message
352// stream across compaction rows.
353func readExtensionStateAtFork(path string, limit int) (map[string]json.RawMessage, error) {
354	f, err := os.Open(path)
355	if err != nil {
356		return nil, fmt.Errorf("branch: open parent for extension state: %w", err)
357	}
358	defer f.Close()
359
360	state := make(map[string]json.RawMessage)
361	forkState := make(map[string]json.RawMessage)
362	cloneState := func(source map[string]json.RawMessage) map[string]json.RawMessage {
363		clone := make(map[string]json.RawMessage, len(source))
364		for name, raw := range source {
365			clone[name] = append(json.RawMessage(nil), raw...)
366		}
367		return clone
368	}
369	applyState := func(target map[string]json.RawMessage, row sessionLine) {
370		if len(row.State) == 0 || strings.TrimSpace(string(row.State)) == "null" {
371			delete(target, row.Extension)
372			return
373		}
374		if json.Valid(row.State) {
375			target[row.Extension] = append(json.RawMessage(nil), row.State...)
376		}
377	}
378	effectiveCount := 0
379	err = forEachStrictJSONLLine(f, func(line []byte, lineNo int) error {
380		var head sessionLineHead
381		if err := json.Unmarshal(line, &head); err != nil {
382			return fmt.Errorf("line %d: invalid JSON: %w", lineNo, err)
383		}
384		switch head.Type {
385		case "meta", "usage", "rename":
386			return nil
387		case "message":
388			if _, err := hydrateMessage(line); err != nil {
389				return fmt.Errorf("line %d: invalid message row: %w", lineNo, err)
390			}
391			effectiveCount++
392		case "compaction":
393			messages, err := hydrateCompaction(line)
394			if err != nil {
395				return fmt.Errorf("line %d: invalid compaction row: %w", lineNo, err)
396			}
397			effectiveCount = len(messages)
398			// A compaction replaces the effective transcript. State that was
399			// recorded anywhere before this boundary belongs to every fork
400			// inside the replacement transcript, even when its old message
401			// index was after the requested fork point.
402			forkState = cloneState(state)
403		case "extension_state":
404			var row sessionLine
405			if err := json.Unmarshal(line, &row); err != nil {
406				return fmt.Errorf("line %d: invalid extension state row: %w", lineNo, err)
407			}
408			if row.Extension == "" || len(row.State) > maxExtensionStateBytes {
409				return nil
410			}
411			applyState(state, row)
412			if effectiveCount <= limit {
413				applyState(forkState, row)
414			}
415		default:
416			return fmt.Errorf("line %d: unknown row type %q", lineNo, head.Type)
417		}
418		return nil
419	})
420	if err != nil {
421		return nil, fmt.Errorf("branch: read extension state: %w", err)
422	}
423	return forkState, nil
424}
425
426func writeBranchSession(root, cwd, version string, parent SessionMeta, messages []provider.Message, checkpoints []SessionUsageCheckpoint, limit int, hideFromSessions bool, extensionState map[string]json.RawMessage) (string, error) {
427	dir := SessionsDir(root, cwd)
428	if err := os.MkdirAll(dir, 0o755); err != nil {
429		return "", err
430	}
431	newID := uuid.NewString()
432	name := fmt.Sprintf("%s-%s.jsonl", time.Now().UTC().Format("20060102-150405"), newID[:8])
433	outPath := filepath.Join(dir, name)
434	// Build in a same-directory temporary file. Rename is atomic only when
435	// the temporary and final paths share a directory; closing the file first
436	// also ensures no buffered writer or descriptor can expose a partial branch.
437	dst, err := os.CreateTemp(dir, ".zut-branch-*.tmp")
438	if err != nil {
439		return "", fmt.Errorf("branch: create temp: %w", err)
440	}
441	tmpPath := dst.Name()
442	if err := dst.Chmod(0o644); err != nil {
443		_ = dst.Close()
444		_ = os.Remove(tmpPath)
445		return "", fmt.Errorf("branch: chmod temp: %w", err)
446	}
447	committed := false
448	defer func() {
449		_ = dst.Close()
450		if !committed {
451			_ = os.Remove(tmpPath)
452			_ = os.Remove(outPath)
453		}
454	}()
455	bw := bufio.NewWriter(dst)
456
457	branchMeta := SessionMeta{
458		ID:               newID,
459		CWD:              cwd,
460		Model:            parent.Model,
461		Provider:         parent.Provider,
462		Started:          time.Now().UTC(),
463		Version:          version,
464		Parent:           parent.ID,
465		ForkPoint:        limit,
466		HideFromSessions: hideFromSessions,
467	}
468	metaLine, err := json.Marshal(sessionLine{Type: "meta", Meta: &branchMeta})
469	if err != nil {
470		return "", fmt.Errorf("branch: marshal meta: %w", err)
471	}
472	if _, err := bw.Write(metaLine); err != nil {
473		return "", err
474	}
475	if err := bw.WriteByte('\n'); err != nil {
476		return "", err
477	}
478
479	for idx := 0; idx < limit; idx++ {
480		msg := messages[idx]
481		line, err := json.Marshal(sessionLine{Type: "message", Message: &msg})
482		if err != nil {
483			return "", fmt.Errorf("branch: marshal message %d: %w", idx, err)
484		}
485		if _, err := bw.Write(line); err != nil {
486			return "", err
487		}
488		if err := bw.WriteByte('\n'); err != nil {
489			return "", err
490		}
491	}
492
493	// Extension snapshots are branch state, not provider-visible transcript
494	// content. Write the latest snapshot that existed at the fork point so a
495	// child branch starts from the same extension state as its copied prefix.
496	extensionNames := make([]string, 0, len(extensionState))
497	for name := range extensionState {
498		extensionNames = append(extensionNames, name)
499	}
500	sort.Strings(extensionNames)
501	for _, name := range extensionNames {
502		line, err := json.Marshal(sessionLine{Type: "extension_state", Extension: name, State: extensionState[name]})
503		if err != nil {
504			return "", fmt.Errorf("branch: marshal extension state: %w", err)
505		}
506		if _, err := bw.Write(line); err != nil {
507			return "", fmt.Errorf("branch: write extension state: %w", err)
508		}
509		if err := bw.WriteByte('\n'); err != nil {
510			return "", fmt.Errorf("branch: terminate extension state row: %w", err)
511		}
512	}
513	// Preserve every cumulative checkpoint that belongs to this prefix. The
514	// final two rows are needed to reconstruct LastTurnUsage as a delta.
515	for _, checkpoint := range checkpoints {
516		if checkpoint.MessageCount > limit {
517			continue
518		}
519		usageLine, err := json.Marshal(sessionLine{
520			Type:       "usage",
521			Usage:      &checkpoint.Cumulative,
522			Cumulative: &checkpoint.Cumulative,
523		})
524		if err != nil {
525			return "", fmt.Errorf("branch: marshal usage: %w", err)
526		}
527		if _, err := bw.Write(usageLine); err != nil {
528			return "", err
529		}
530		if err := bw.WriteByte('\n'); err != nil {
531			return "", err
532		}
533	}
534
535	if err := bw.Flush(); err != nil {
536		return "", err
537	}
538	if err := dst.Sync(); err != nil {
539		return "", fmt.Errorf("branch: sync temp: %w", err)
540	}
541	if err := dst.Close(); err != nil {
542		return "", fmt.Errorf("branch: close temp: %w", err)
543	}
544	if err := os.Rename(tmpPath, outPath); err != nil {
545		return "", fmt.Errorf("branch: commit: %w", err)
546	}
547	committed = true
548	return outPath, nil
549}
550
551func lastUserText(msgs []provider.Message) string {
552	for i := len(msgs) - 1; i >= 0; i-- {
553		if msgs[i].Role != provider.RoleUser {
554			continue
555		}
556		if text := strings.TrimSpace(firstTextFromMessage(msgs[i])); text != "" {
557			return text
558		}
559	}
560	return ""
561}
562
563// TreeNode is one entry in the branch tree returned by
564// BuildSessionTree. Children are populated by linking on Parent ID.
565type TreeNode struct {
566	Summary  SessionSummary
567	Meta     SessionMeta
568	Children []*TreeNode
569}
570
571// BuildSessionTree loads every session in the cwd dir and returns
572// the forest rooted at parentless sessions, with each non-root
573// session placed under its parent. Used by /session tree to render
574// the branch hierarchy.
575func BuildSessionTree(root, cwd string) []*TreeNode {
576	dir := SessionsDir(root, cwd)
577	entries, err := os.ReadDir(dir)
578	if err != nil {
579		return nil
580	}
581	nodes := make(map[string]*TreeNode)
582	order := []string{}
583	for _, e := range entries {
584		if e.IsDir() || !strings.HasSuffix(e.Name(), ".jsonl") {
585			continue
586		}
587		path := filepath.Join(dir, e.Name())
588		summary := describeSession(path)
589		meta, _ := readSessionMeta(path)
590		if meta.ID == "" {
591			continue
592		}
593		nodes[meta.ID] = &TreeNode{Summary: summary, Meta: meta}
594		order = append(order, meta.ID)
595	}
596	return linkSessionTreeNodes(nodes, order)
597}
598
599// BuildSessionTreeStrict is the complete-read counterpart to the permissive
600// forest builder. It validates every session file before linking any node, so
601// callers that need a complete forest cannot silently omit malformed members.
602func BuildSessionTreeStrict(root, cwd string) ([]*TreeNode, error) {
603	dir := SessionsDir(root, cwd)
604	entries, err := os.ReadDir(dir)
605	if err != nil {
606		if errors.Is(err, os.ErrNotExist) {
607			return nil, nil
608		}
609		return nil, fmt.Errorf("build session tree: read directory: %w", err)
610	}
611	nodes := make(map[string]*TreeNode)
612	order := make([]string, 0, len(entries))
613	for _, e := range entries {
614		if e.IsDir() || !strings.HasSuffix(e.Name(), ".jsonl") {
615			continue
616		}
617		path := filepath.Join(dir, e.Name())
618		snapshot, err := ReadSessionSnapshot(path)
619		if err != nil {
620			return nil, fmt.Errorf("build session tree: read %q: %w", path, err)
621		}
622		if snapshot.Meta.ID == "" {
623			return nil, fmt.Errorf("build session tree: %q has no session id", path)
624		}
625		summary := SessionSummary{
626			Path:          path,
627			Started:       snapshot.Meta.Started,
628			Model:         snapshot.Meta.Model,
629			Provider:      snapshot.Meta.Provider,
630			MessageCount:  len(snapshot.Messages),
631			FirstUserText: firstUserTextFromMessages(snapshot.Messages),
632			Title:         snapshot.Meta.Title,
633		}
634		if len(snapshot.UsageCheckpoints) > 0 {
635			summary.TotalCost = snapshot.UsageCheckpoints[len(snapshot.UsageCheckpoints)-1].Cumulative.CostUSD
636		}
637		if _, exists := nodes[snapshot.Meta.ID]; exists {
638			return nil, fmt.Errorf("build session tree: duplicate session id %q", snapshot.Meta.ID)
639		}
640		nodes[snapshot.Meta.ID] = &TreeNode{Summary: summary, Meta: snapshot.Meta}
641		order = append(order, snapshot.Meta.ID)
642	}
643	return linkSessionTreeNodes(nodes, order), nil
644}
645
646// BuildSessionTreeFamilyStrict locates the current session using lightweight
647// metadata headers, then strictly validates only that root and its descendants.
648// A corrupt unrelated root in the same cwd bucket must not hide an otherwise
649// readable current family, while a corrupt member of the selected family still
650// fails the whole preflight.
651func BuildSessionTreeFamilyStrict(root, cwd, currentPath string) ([]*TreeNode, error) {
652	if currentPath == "" {
653		return nil, errors.New("build session family: current path is empty")
654	}
655	dir := SessionsDir(root, cwd)
656	entries, err := os.ReadDir(dir)
657	if err != nil {
658		if errors.Is(err, os.ErrNotExist) {
659			return nil, nil
660		}
661		return nil, fmt.Errorf("build session family: read directory: %w", err)
662	}
663	cleanCurrent := filepath.Clean(currentPath)
664	nodes := make(map[string]*TreeNode)
665	order := make([]string, 0, len(entries))
666	for _, entry := range entries {
667		if entry.IsDir() || !strings.HasSuffix(entry.Name(), ".jsonl") {
668			continue
669		}
670		path := filepath.Join(dir, entry.Name())
671		meta, err := readSessionMetaHeader(path)
672		if err != nil {
673			if filepath.Clean(path) == cleanCurrent {
674				return nil, fmt.Errorf("build session family: read current metadata %q: %w", path, err)
675			}
676			// A file whose header is unreadable cannot be associated with the
677			// selected family. Valid descendants are linked below and fully
678			// preflighted; unrelated corrupt roots stay out of this family.
679			continue
680		}
681		if _, exists := nodes[meta.ID]; exists {
682			return nil, fmt.Errorf("build session family: duplicate session id %q", meta.ID)
683		}
684		nodes[meta.ID] = &TreeNode{
685			Summary: SessionSummary{Path: path, Started: meta.Started, Model: meta.Model, Provider: meta.Provider},
686			Meta:    meta,
687		}
688		order = append(order, meta.ID)
689	}
690	roots := linkSessionTreeNodes(nodes, order)
691	var familyRoot *TreeNode
692	for _, candidate := range roots {
693		if treeNodeContainsPath(candidate, cleanCurrent) {
694			familyRoot = candidate
695			break
696		}
697	}
698	if familyRoot == nil {
699		return nil, fmt.Errorf("build session family: current path %q is not in the session forest", currentPath)
700	}
701	var validate func(*TreeNode) error
702	validate = func(node *TreeNode) error {
703		snapshot, err := ReadSessionSnapshot(node.Summary.Path)
704		if err != nil {
705			return fmt.Errorf("build session family: read %q: %w", node.Summary.Path, err)
706		}
707		if snapshot.Meta.ID != node.Meta.ID {
708			return fmt.Errorf("build session family: session id changed in %q", node.Summary.Path)
709		}
710		node.Meta = snapshot.Meta
711		node.Summary = SessionSummary{
712			Path:          node.Summary.Path,
713			Started:       snapshot.Meta.Started,
714			Model:         snapshot.Meta.Model,
715			Provider:      snapshot.Meta.Provider,
716			MessageCount:  len(snapshot.Messages),
717			FirstUserText: firstUserTextFromMessages(snapshot.Messages),
718			Title:         snapshot.Meta.Title,
719		}
720		if len(snapshot.UsageCheckpoints) > 0 {
721			node.Summary.TotalCost = snapshot.UsageCheckpoints[len(snapshot.UsageCheckpoints)-1].Cumulative.CostUSD
722		}
723		for _, child := range node.Children {
724			if err := validate(child); err != nil {
725				return err
726			}
727		}
728		return nil
729	}
730	if err := validate(familyRoot); err != nil {
731		return nil, err
732	}
733	return []*TreeNode{familyRoot}, nil
734}
735
736func readSessionMetaHeader(path string) (SessionMeta, error) {
737	f, err := os.Open(path)
738	if err != nil {
739		return SessionMeta{}, err
740	}
741	defer f.Close()
742	line, err := bufio.NewReader(f).ReadBytes('\n')
743	if err != nil && len(line) == 0 {
744		return SessionMeta{}, err
745	}
746	line = bytes.TrimSpace(line)
747	var row sessionLine
748	if err := json.Unmarshal(line, &row); err != nil {
749		return SessionMeta{}, err
750	}
751	if row.Type != "meta" || row.Meta == nil || row.Meta.ID == "" {
752		return SessionMeta{}, errors.New("first row is not a valid meta row")
753	}
754	return *row.Meta, nil
755}
756
757func treeNodeContainsPath(node *TreeNode, path string) bool {
758	if node == nil {
759		return false
760	}
761	if filepath.Clean(node.Summary.Path) == filepath.Clean(path) {
762		return true
763	}
764	for _, child := range node.Children {
765		if treeNodeContainsPath(child, path) {
766			return true
767		}
768	}
769	return false
770}
771
772func linkSessionTreeNodes(nodes map[string]*TreeNode, order []string) []*TreeNode {
773	var roots []*TreeNode
774	for _, id := range order {
775		n := nodes[id]
776		if n.Meta.Parent == "" {
777			roots = append(roots, n)
778			continue
779		}
780		if parent, ok := nodes[n.Meta.Parent]; ok {
781			parent.Children = append(parent.Children, n)
782		} else {
783			// Parent file missing (was manually deleted). Treat as a root so it
784			// still shows up in the tree.
785			roots = append(roots, n)
786		}
787	}
788	return roots
789}
790
791// scanSessionMeta reads JSONL rows without hydrating transcript content and
792// returns the latest valid metadata row. Listing and ID lookup only need this
793// small projection; full snapshot validation remains the responsibility of
794// resume, export, branching, and tree preflight callers.
795func scanSessionMeta(path string) (meta SessionMeta, err error) {
796	f, err := os.Open(path)
797	if err != nil {
798		return SessionMeta{}, err
799	}
800	defer f.Close()
801
802	var sawMeta bool
803	err = forEachStrictJSONLLine(f, func(line []byte, lineNo int) error {
804		var head sessionLineHead
805		if err := json.Unmarshal(line, &head); err != nil {
806			return fmt.Errorf("line %d: invalid JSON: %w", lineNo, err)
807		}
808		if head.Type == "" {
809			return fmt.Errorf("line %d: missing row type", lineNo)
810		}
811		if !sawMeta && head.Type != "meta" {
812			return fmt.Errorf("line %d: first row is not meta", lineNo)
813		}
814		switch head.Type {
815		case "meta":
816			var row struct {
817				Meta *SessionMeta `json:"meta"`
818			}
819			if err := json.Unmarshal(line, &row); err != nil {
820				return fmt.Errorf("line %d: invalid meta row: %w", lineNo, err)
821			}
822			if row.Meta == nil || row.Meta.ID == "" {
823				return fmt.Errorf("line %d: meta row has no session id", lineNo)
824			}
825			meta = *row.Meta
826			sawMeta = true
827		case "message", "compaction", "usage", "rename":
828			// These rows are intentionally not hydrated here.
829		default:
830			return fmt.Errorf("line %d: unknown row type %q", lineNo, head.Type)
831		}
832		return nil
833	})
834	if err != nil {
835		return SessionMeta{}, fmt.Errorf("session metadata %q: %w", path, err)
836	}
837	if !sawMeta {
838		return SessionMeta{}, fmt.Errorf("session metadata %q: file is empty", path)
839	}
840	return meta, nil
841}
842
843// readSessionMeta returns the latest validated metadata for path without
844// reconstructing its transcript. Full snapshot validation is performed by
845// callers that need messages rather than listing metadata.
846func readSessionMeta(path string) (SessionMeta, error) {
847	return scanSessionMeta(path)
848}
849
850// FindSessionByID looks up a session file in root/cwd whose meta id
851// matches. Used by /session tree when the user picks an entry. O(n)
852// over the files in the dir; the list is small in practice.
853func FindSessionByID(root, cwd, id string) string {
854	dir := SessionsDir(root, cwd)
855	entries, err := os.ReadDir(dir)
856	if err != nil {
857		return ""
858	}
859	for _, e := range entries {
860		if e.IsDir() || !strings.HasSuffix(e.Name(), ".jsonl") {
861			continue
862		}
863		path := filepath.Join(dir, e.Name())
864		meta, err := scanSessionMeta(path)
865		if err != nil {
866			continue
867		}
868		if meta.ID == id {
869			return path
870		}
871	}
872	return ""
873}
874
875// firstUserPrompt scans forward from the current source position
876// looking for the first user-role message and returns its text.
877// Used to build a humane export filename. Uses Reader instead of
878// Scanner so a very large JSONL row before the first user prompt
879// cannot trip Scanner's token limit.
880func firstUserPrompt(src io.Reader) (string, error) {
881	r := bufio.NewReader(src)
882	for {
883		lineBytes, err := r.ReadBytes('\n')
884		if len(lineBytes) > 0 {
885			lineBytes = bytes.TrimRight(lineBytes, "\r\n")
886			var line sessionLine
887			if err := json.Unmarshal(lineBytes, &line); err == nil {
888				if line.Type == "message" && line.Message != nil && line.Message.Role == "user" {
889					b, _ := json.Marshal(line.Message)
890					var m struct {
891						Content []struct {
892							Text string `json:"text"`
893						} `json:"content"`
894					}
895					_ = json.Unmarshal(b, &m)
896					for _, c := range m.Content {
897						if c.Text != "" {
898							return c.Text, nil
899						}
900					}
901				}
902			}
903		}
904		if err == io.EOF {
905			return "", nil
906		}
907		if err != nil {
908			return "", err
909		}
910	}
911}
912
913// filenameFor builds a descriptive .zutsession filename from the
914// session's start time and, when available, an excerpt of the
915// first user prompt.
916func filenameFor(started time.Time, id, firstPrompt string) string {
917	base := started.UTC().Format("20060102-150405")
918	if id != "" && len(id) >= 8 {
919		base += "-" + id[:8]
920	}
921	slug := slugify(firstPrompt, 40)
922	if slug != "" {
923		base += "-" + slug
924	}
925	return base + PortableExt
926}
927
928// slugify lowercases, strips punctuation, collapses whitespace to
929// hyphens, and truncates to max runes so it's safe as a filename.
930func slugify(s string, max int) string {
931	s = strings.TrimSpace(strings.ToLower(s))
932	if s == "" {
933		return ""
934	}
935	var out strings.Builder
936	prevDash := false
937	for _, r := range s {
938		switch {
939		case r >= 'a' && r <= 'z', r >= '0' && r <= '9':
940			out.WriteRune(r)
941			prevDash = false
942		default:
943			if !prevDash && out.Len() > 0 {
944				out.WriteByte('-')
945				prevDash = true
946			}
947		}
948		if out.Len() >= max {
949			break
950		}
951	}
952	return strings.TrimRight(out.String(), "-")
953}

Keyboard shortcuts

Single-key shortcuts are on. ctrl k and esc work whatever this says.

ctrl k :
go to a section, branch, tag, file or repository
?
this list
j k
move the row cursor down / up
enter
open the row under the cursor; on Files, a directory opens or closes in place
↑ ↓ ← → home end
in the file tree (focus on a row): previous / next row, close / open a directory or go to its parent / first entry, first / last row. They never open a file
l h
on Files: open a directory or a file / close a directory or go up to its parent, then to the parent page. Elsewhere: into the side panel (on a merge request, its files) / back to the content; there j k move between its controls
g g G
first / last row
/
filter the list; on Files, find a file anywhere in the repository (esc clears, enter opens the best match)
b
switch branch or tag
g s g f g c g b g m g i g r g a
tabs: summary, files, commits, branches & tags, merge requests, issues, releases, actions (when available)
g h
home
w
wide mode: use the whole width of the screen, or not (remembered)
y
copy a permalink pinned to the commit
d u x
diff: split / unified / collapse or expand all
e E
diff: the whole file in view / every file, with the lines the hunks hide
n
merge request: next note in the diff
esc
close a dialog, leave a field

Branches 1

Tags 476

↑↓ moveenter openesc close