package runs import "context" // Journal records a sequence of entries, such as an agent loop's model and // tool calls, as steps of the run. Entry n is the step at the journal's base // plus n, so a replay finds every entry where it was written and the workflow's // later steps follow the last one. type Journal[E any] struct { rc *Context name string base int } // Journal starts a journal at the run's next step. name must be unique within // the workflow. func (rc *Context) Journal[E any](name string) *Journal[E] { return &Journal[E]{rc: rc, name: "journal:" + name, base: rc.next} } // Lookup returns the entry recorded at pos, or nil when there is none. A // position with no entry is where live work starts, so a requested // cancellation stops the run there, as it does before a step. func (j *Journal[E]) Lookup(ctx context.Context, pos int64) (*E, error) { seq := j.base + int(pos) saved, ok := j.rc.saved[seq] if !ok { return nil, j.rc.checkCancel(ctx) } entry, err := replay[E](saved, j.name) if err != nil { return nil, err } j.rc.reach(seq) return &entry, nil } // Record saves entry at pos, fenced by the run's lease like any step. func (j *Journal[E]) Record(ctx context.Context, pos int64, entry E) error { seq := j.base + int(pos) if _, err := j.rc.record(ctx, seq, j.name, entry, nil); err != nil { return err } j.rc.reach(seq) return nil } // reach moves the run's next step past seq. func (rc *Context) reach(seq int) { rc.next = max(rc.next, seq+1) }