v0.21.0 cd9706d

session_portable.go RawHistoryFolder

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

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