Documentation
¶
Overview ¶
Package conversations defines the Phase 3 Conversation entity: a long-lived thread that owns a sequence of underlying claude sessions and carries presentation metadata (name, promoted/unpromoted state).
This package is intentionally I/O-free. Persistence (sessions.json-style registry on disk) lands in #217.
Index ¶
- Constants
- Variables
- func RunSweepLoop(ctx context.Context, reg *Registry, path string, interval time.Duration, ...) error
- func ShouldArchive(c Conversation, now time.Time) bool
- func Sweep(reg *Registry, now time.Time) int
- func ValidID(s string) bool
- type Conversation
- type ConversationID
- type ListFilter
- type Registry
- func (r *Registry) Create(c Conversation)
- func (r *Registry) Delete(id ConversationID) bool
- func (r *Registry) Get(id ConversationID) (Conversation, bool)
- func (r *Registry) List(filter ...ListFilter) []Conversation
- func (r *Registry) Promote(id ConversationID, name string) error
- func (r *Registry) RebindSession(oldID, newID string) bool
- func (r *Registry) Save(path string) error
- func (r *Registry) SetArchived(id ConversationID, archived bool) bool
- func (r *Registry) SetSystemPrompt(id ConversationID, prompt *string) error
- func (r *Registry) SetWorkspaceLabel(cwd string, label *string)
- func (r *Registry) Update(id ConversationID, fn func(*Conversation)) bool
- func (r *Registry) WorkspaceLabel(cwd string) (string, bool)
Constants ¶
const MaxSystemPromptBytes = 8192
MaxSystemPromptBytes bounds Conversation.SystemPrompt, inclusive: a value of exactly this many bytes is accepted. Bytes rather than runes, because both the registry file and the wire frame that carries the value are byte-budgeted.
The value has to fit inside a v2 application envelope (capped at 65519 bytes, docs/protocol-mobile.md § Application-envelope size cap) with room to spare for the rest of a payload, and this is far above any hand-written channel instruction. It is deliberately not an argv constraint — the prompt reaches claude through a file, never as a command-line value.
const SweepInterval = time.Hour
SweepInterval is the production tick interval for RunSweepLoop. One hour is safe relative to archiveIdleThreshold (30 days): missing one tick delays an archive by one hour, which is harmless.
Variables ¶
var ( ErrConversationNotFound = errors.New("conversations: conversation not found") ErrConversationAlreadyPromoted = errors.New("conversations: conversation already promoted") ErrPromotionNameInUse = errors.New("conversations: promotion name already in use") ErrPromotionNameEmpty = errors.New("conversations: promotion name is empty") ErrSystemPromptTooLong = errors.New("conversations: system prompt exceeds the maximum byte length") ErrSystemPromptInvalidUTF8 = errors.New("conversations: system prompt is not valid UTF-8") )
Sentinel errors returned by Promote and SetSystemPrompt. Callers (CLI, wire-protocol layer) distinguish refusal cases via errors.Is and map to user-facing codes.
Every sentinel is static and returned naked: no refusal path interpolates the rejected value, its length, or the conversation id, so a caller's log or wire reply cannot pick up a fragment of an operator's prompt from an error.
Functions ¶
func RunSweepLoop ¶
func RunSweepLoop(ctx context.Context, reg *Registry, path string, interval time.Duration, log *slog.Logger) error
RunSweepLoop ticks every interval and applies Sweep + (conditional) Save to reg. On each tick it calls Sweep(reg, time.Now()). When the returned count is non-zero it calls reg.Save(path); a successful Save logs at INFO with the archived count, a failed Save logs at ERROR and the loop continues to the next tick. A zero-count tick does NOT call Save (avoids fsync churn on every hour with no changes).
Designed to be run as a goroutine inside an errgroup (or equivalent) supervising it via context cancellation. Returns nil on ctx cancellation. Does NOT perform a final on-shutdown sweep — by design; the next pyry start will run the next tick within SweepInterval.
Save errors are ALWAYS non-fatal: a transient failure (e.g. disk briefly unwritable) must not bring down the daemon's errgroup. Tick frequency is hourly, so a single missed Save loses at most one hour of archived-count persistence; the next successful tick archives the same set again.
Caller responsibilities:
- reg has been Loaded by the caller before this loop starts.
- path is the same path the caller will Load from on the next pyry start.
- log is non-nil (the pool's logger or slog.Default()).
- interval > 0 (callers in production pass SweepInterval; tests pass small deterministic values). interval <= 0 panics via time.NewTicker.
func ShouldArchive ¶
func ShouldArchive(c Conversation, now time.Time) bool
ShouldArchive reports whether c should be auto-archived as of now.
A conversation archives iff it is unpromoted (a discussion, not a channel) AND not manually archived AND its LastUsedAt is at least archiveIdleThreshold in the past. The boundary is inclusive: exactly 30 days idle archives. Auto-archive deletes the row, so it must not claim a conversation the user archived to keep — manual archive (#880/#881) is recoverable by design and stays durable until the user unarchives.
Pure function. No I/O, no clock — the caller passes now. The sweep loop (#220) is responsible for picking now (typically time.Now()) and for iterating the registry.
func Sweep ¶
Sweep removes every conversation in reg for which ShouldArchive(c, now) returns true. Returns the number of entries archived.
Sweep operates on a snapshot of reg.List(): the underlying slice may be modified (by Delete) during iteration without affecting the snapshot the loop is walking.
Sweep does NOT call reg.Save — disk persistence is the daemon-wiring ticket's concern. Callers responsible for durability must Save themselves after Sweep returns.
Types ¶
type Conversation ¶
type Conversation struct {
// ID is the conversation's stable identifier. Always present.
ID ConversationID `json:"id"`
// Name is the user-visible display name. A pointer so that "absent"
// (nil — the user has never named this conversation) is distinguishable
// from "explicitly empty" (non-nil pointer to ""). Unpromoted
// conversations typically leave this nil; promoted conversations
// (channels) usually carry a name.
Name *string `json:"name,omitempty"`
// Cwd is the absolute working directory recorded for the conversation,
// captured at creation time. Always present. Updated by the change_workspace
// verb (#823), which stores the $HOME-confined realpath of a client-chosen
// target; the new folder takes effect on the conversation's next fresh
// session spawn (conv.Cwd is deliberately decoupled from a running session's
// captured spawn WorkDir, #685/#686).
Cwd string `json:"cwd"`
// CurrentSessionID is the underlying claude session this conversation
// currently points at. Empty string when no session is bound (e.g., a
// freshly created conversation that has not yet been started, or one
// whose session has been archived). Empty values are omitted from the
// JSON output.
CurrentSessionID string `json:"current_session_id,omitempty"`
// SessionHistory is the ordered list of prior session IDs that this
// conversation has pointed at, in chronological (oldest-first) order.
// The most recently retired session sits at the tail
// (SessionHistory[len-1]); rotation appends in place
// (append(SessionHistory, prevID)). Chronological ordering is chosen
// because it matches the natural append pattern and avoids O(n) shifts
// on every rotation; presentation layers that want newest-first can
// reverse on read. An empty/nil slice is omitted from JSON output.
SessionHistory []string `json:"session_history,omitempty"`
// IsPromoted distinguishes the two conversation modes:
// false — discussion (ephemeral, eligible for auto-archive unless IsArchived)
// true — channel (long-lived, named, exempt from auto-archive)
// Always serialized; the field is meaningful in both states and the
// unpromoted default ("discussion") must be explicit on disk.
IsPromoted bool `json:"is_promoted"`
// IsArchived is the durable manual-archive flag: true means the user
// archived this conversation, false means it is active. Flipped by
// Registry.SetArchived and consumed by the archive/unarchive verbs (#881)
// and by ShouldArchive, which exempts archived rows from the idle sweep's
// hard delete (#1488).
//
// omitempty is deliberate and, unlike IsPromoted, correct here: the
// contract is "absent key decodes as active, with no migration step." A
// pre-#880 on-disk row (no is_archived key) decodes to false = active, and
// an active conversation re-serializes with the key omitted — so a registry
// of all-active rows is byte-identical to its pre-#880 form. Only genuinely
// archived rows gain "is_archived": true. Do not "fix" this to drop
// omitempty for consistency with IsPromoted: their contracts are opposite.
IsArchived bool `json:"is_archived,omitempty"`
// SystemPrompt is the operator-set system prompt this conversation carries,
// so two conversations on the same repository can be told to behave
// differently. A pointer for the same reason as Name: nil is "absent" (no
// prompt — the default), a non-nil pointer to "" is "explicitly empty". A
// plain string with omitempty cannot express that split; both states would
// serialize away and both would decode to "".
//
// omitempty carries the same contract as IsArchived's, for the same reason:
// "an absent key decodes as no prompt, with no migration step." omitempty on
// a pointer tests the pointer, not the pointee, so a nil prompt omits the key
// while a non-nil pointer to "" still emits "system_prompt": "" — which is
// what keeps the two states distinguishable on disk. A registry whose rows
// all hold nil is therefore byte-identical to its pre-#2149 form.
//
// Written only by Registry.SetSystemPrompt, which bounds the value at
// MaxSystemPromptBytes and refuses invalid UTF-8; nothing mints the
// explicitly-empty state today. Read by the spawn path and the read-back
// verb (#2150, #2152).
SystemPrompt *string `json:"system_prompt,omitempty"`
// LastUsedAt is bumped whenever the conversation has user activity.
// Used by "recently active" sorts and by the auto-archive predicate
// (#219). Always present.
LastUsedAt time.Time `json:"last_used_at"`
}
Conversation is the on-disk and in-memory shape of a Phase 3 conversation. Field tags are snake_case to match the existing sessions registry style (internal/sessions/registry.go).
Field ordering is preserved exactly as the AC requires; do not re-order to optimize struct padding — the JSON encoding is the source of truth and reviewer diff stability matters more than a few padding bytes per record.
type ConversationID ¶
type ConversationID string
ConversationID is a per-conversation identifier. Distinct from sessions.SessionID so that a value of one type cannot be silently passed where the other is expected — a Conversation carries both its own ID and a CurrentSessionID, and confusing them is the most plausible bug in the upcoming registry/API code.
The empty ConversationID ("") is the unset sentinel. Format conventions (UUIDv4 vs. other) are not fixed here; #217 owns the generator and the validity predicate.
func NewID ¶
func NewID() (ConversationID, error)
NewID returns a fresh UUIDv4-shaped ConversationID, drawn from crypto/rand. Returns an error only when the system rng fails.
type ListFilter ¶
ListFilter narrows the result of List. A nil pointer field means "no filter on this field"; a non-nil pointer matches entries whose corresponding field equals the pointed-to value. When more than one field is set, they AND: an entry is returned only if it matches every non-nil field.
type Registry ¶
type Registry struct {
// contains filtered or unexported fields
}
Registry is the in-memory conversation list, guarded by a mutex. Construct via Load (cold-start or warm-start from disk); persist via Save. All methods are safe for concurrent use.
func Load ¶
Load reads path. A missing file returns an empty *Registry with no error (cold start). A zero-byte file returns an empty *Registry with no error. Malformed JSON returns a wrapped error and a nil *Registry.
The returned *Registry is independent of the on-disk file: subsequent Save calls re-encode from the in-memory slice; the file may move or be deleted between Load and Save without affecting in-memory state.
func (*Registry) Create ¶
func (r *Registry) Create(c Conversation)
Create appends c to the in-memory list. Caller owns uniqueness — Create does not validate that c.ID is unique, well-formed, or non-empty.
func (*Registry) Delete ¶
func (r *Registry) Delete(id ConversationID) bool
Delete removes the conversation whose ID equals id. Returns true on hit, false on miss. Mutex-guarded; safe for concurrent use alongside the other Registry methods.
Delete does NOT call Save — disk persistence is the caller's concern, matching the Create / Update / Promote convention.
func (*Registry) Get ¶
func (r *Registry) Get(id ConversationID) (Conversation, bool)
Get returns the first conversation whose ID equals id, and true if one was found. Comparison is byte-exact.
func (*Registry) List ¶
func (r *Registry) List(filter ...ListFilter) []Conversation
List returns a copy of the in-memory conversation list, optionally narrowed by filter. Callers may mutate the returned slice and its elements without affecting registry state.
The variadic shape is for ergonomics, not for AND-composition: when more than one ListFilter is supplied, only filter[0] is consulted.
func (*Registry) Promote ¶
func (r *Registry) Promote(id ConversationID, name string) error
Promote flips the conversation with id to promoted state and sets its display name to a non-nil pointer to name. Returns one of the exported sentinels on refusal:
- ErrConversationNotFound — id is not present in the registry.
- ErrConversationAlreadyPromoted — target already has IsPromoted == true.
- ErrPromotionNameInUse — another *promoted* conversation already uses name (case-sensitive byte-exact comparison; unpromoted conversations do not participate in the uniqueness check).
- ErrPromotionNameEmpty — name is empty or contains only whitespace.
Validation, uniqueness scan, and mutation all happen under r.mu so a concurrent second Promote with the same name cannot slip through. On any refusal the registry is left untouched and no field of any record is modified. Persistence is the caller's responsibility — Promote does not call Save, matching the Create / Update convention.
func (*Registry) RebindSession ¶ added in v0.15.0
RebindSession re-points the conversation currently bound to oldID at newID, recording oldID in SessionHistory. Returns true iff a conversation was rebound. The scan and mutation happen atomically under r.mu, so there is no find-then-update window a concurrent Create/Delete could redirect.
- hit → CurrentSessionID = newID; SessionHistory = append(SessionHistory, oldID)
- miss → no mutation, false (the rotated session is owned by no conversation)
An empty oldID returns false immediately without scanning: an unbound conversation carries CurrentSessionID == "" (the unset sentinel) and must NEVER be swept into a rebind by a stray empty-id call. This is a data-integrity guard at the primitive boundary, not the primary eviction defense — that lives at the call site, which only rebinds on a /clear rotation (where NewID is non-empty). Precondition (caller-guaranteed on the rotation path): oldID and newID are non-empty and distinct.
First match wins, mirroring Get/Update: a session id binds exactly one conversation (set once at creation), so the first match is the only match; pathological duplicates rebind the first only — deterministic and documented.
RebindSession does NOT call Save — disk persistence is the caller's concern, matching the Create / Update / Promote / Delete convention.
func (*Registry) Save ¶
Save writes the registry atomically: temp file in filepath.Dir(path) at mode 0600, fsync, rename into place. Parent directory is created with mode 0700 if missing. Returns a wrapped error on any step failure; on failure the pre-existing target file (if any) is left untouched (rename is the commit point).
Entries are sorted by LastUsedAt then ID before serialization to guarantee byte-identical output for the same logical content.
func (*Registry) SetArchived ¶ added in v0.16.0
func (r *Registry) SetArchived(id ConversationID, archived bool) bool
SetArchived flips the durable archived flag of the conversation whose ID equals id: archived=true archives it, archived=false restores it to active. Returns true on hit, false on miss; on miss no field of any record is modified (AC: "miss for an unknown id, leaving the registry unmodified").
It sets exactly one field — IsArchived — so id, cwd, name, promoted state, and session binding are structurally untouched. This is the deterministic enforcement of the ticket's "flips exactly one field" constraint: the #881 verb handler that calls this cannot get it wrong, because the method has no way to touch another field. The scan and mutation happen atomically under r.mu, so there is no find-then-mutate window a concurrent Create/Delete could redirect.
The single archived bool both sets and clears — SetArchived(id, true) on an already-archived row returns true and leaves it archived (idempotent / symmetric toggle), so no separate Archive/Unarchive pair is needed.
SetArchived does NOT call Save — disk persistence is the caller's concern, matching the Create / Update / Promote / Delete / RebindSession convention.
func (*Registry) SetSystemPrompt ¶ added in v0.16.0
func (r *Registry) SetSystemPrompt(id ConversationID, prompt *string) error
SetSystemPrompt sets the operator-set system prompt of the conversation whose ID equals id. It sets exactly one field — SystemPrompt — so id, cwd, name, promoted/archived state, and session binding are structurally untouched, the same guarantee SetArchived gives for its own field.
The *string argument spans all three prompt states through one validated door, mirroring SetArchived's single argument that both sets and clears:
- nil → the conversation returns to "no prompt" (the default).
- non-nil "" → the explicitly-empty state.
- non-nil text → stored verbatim after validation.
Refusals, each a static exported sentinel:
- ErrSystemPromptTooLong — *prompt exceeds MaxSystemPromptBytes.
- ErrSystemPromptInvalidUTF8 — *prompt is not valid UTF-8.
- ErrConversationNotFound — id is not present in the registry.
On any refusal no field of any record is modified. Value validation runs before the lock (it reads only the caller's value), so the refusal ordering is value-first then identity — the same ordering Promote uses, where the empty-name check likewise precedes the not-found scan. Length is checked before UTF-8 validity so a hostile oversize value is rejected in O(1) rather than after a full validity scan; a value that is both over-length and invalid therefore returns ErrSystemPromptTooLong.
Invalid UTF-8 is refused rather than sanitized because encoding/json substitutes U+FFFD on marshal: such a value would not survive Save → Load unchanged, and the substitution can grow it past the bound after admission. Refusing at the door is what keeps "stored verbatim" and "round-trips unchanged" simultaneously true.
The pointee is copied into a fresh local before its address is taken, so the stored pointer never aliases a caller-held variable — the same defensive idiom Promote uses for Name. Get and List keep copying records shallowly and sharing the stored pointer, exactly as they already do for Name.
SetSystemPrompt does NOT call Save — disk persistence is the caller's concern, matching the Create / Update / Promote / Delete / RebindSession / SetArchived convention. It takes no logger, and nothing in this package logs a record field, so the value cannot leave the registry file by way of a log line.
func (*Registry) SetWorkspaceLabel ¶ added in v0.16.0
SetWorkspaceLabel stores the display name for the workspace at cwd, or clears it (#2206). The nullable argument spans both states through one door, mirroring SetSystemPrompt's *string and SetArchived's single bool that both sets and clears:
- nil → the key is deleted, so WorkspaceLabel reports absent rather than a present empty string.
- non-nil "" → the explicitly-empty label, stored and reported present.
- non-nil text → stored verbatim.
It has no failure mode and returns nothing. In particular it does NOT check cwd against the conversation list — #2207's handler owns the not-found refusal — and, unlike its neighbour SetSystemPrompt, it does NOT validate the value. Non-blank and length bounds belong to the wire handler; this layer stores what it is given, under the key it is given. Any future caller (a CLI binding, a second verb) inherits an unvalidated door and must bring its own bounds: the two setters sit adjacent in this file with deliberately opposite contracts.
Storing verbatim assumes a valid-UTF-8 label for round-trip fidelity, since encoding/json substitutes U+FFFD on marshal — the hazard SetSystemPrompt refuses with a sentinel. No sentinel here, because the wire path cannot produce the input: encoding/json performs the same substitution while decoding into a Go string, so whatever reaches a handler is already valid UTF-8.
The pointee is copied into a fresh local before it is stored, so the map never aliases a caller-held variable — the defensive idiom Promote uses for Name and SetSystemPrompt for its prompt. The map is allocated lazily on the first store, which is also the path a registry freshly loaded from a pre-#2206 file takes: its map is nil, and assignment to a nil map panics.
SetWorkspaceLabel does NOT call Save — disk persistence is the caller's concern, matching the Create / Update / Promote / Delete / RebindSession / SetArchived / SetSystemPrompt convention. It takes no logger, and nothing in this package logs a record field, so a label cannot leave the registry file by way of a log line.
func (*Registry) Update ¶
func (r *Registry) Update(id ConversationID, fn func(*Conversation)) bool
Update locates the conversation with matching id, invokes fn with a pointer to that entry under the registry lock, and returns true. On miss, returns false and does not invoke fn.
fn runs with r.mu held. fn MUST NOT call back into the registry — sync.Mutex is non-reentrant, and any Registry method would deadlock. fn MUST NOT retain the *Conversation pointer past return: the slice may be reallocated by a future Create. fn may read and mutate any field; the registry does not validate post-mutation state (e.g., does not reject a flip that duplicates another entry's ID).
func (*Registry) WorkspaceLabel ¶ added in v0.16.0
WorkspaceLabel returns the operator-set display name stored for the workspace at cwd, and true if one is set (#2206). Comparison is byte-exact, the same contract Get gives for a conversation id: two paths differing only in a trailing separator, a trailing space, or case are distinct workspaces, and nothing here normalizes, resolves, joins, stats, or opens the key — at this layer a cwd is a map key and nothing more.
It answers for one workspace at a time and deliberately does NOT hand back the map. A caller ranging over a shared map outside r.mu while another goroutine writes it is not a race the detector reports but a fatal "concurrent map iteration and map write" throw that kills the daemon, so the per-key signature makes the escape structurally impossible rather than forbidding it in prose. The consuming slices (#2208, #2210) call this once per conversation behind their own narrow interfaces, which *Registry satisfies structurally.
A cleared label reads as absent, never as a present empty string; an explicitly-empty label reads as ("", true). The two states stay distinct.