conversations

package
v0.11.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 14, 2026 License: MIT Imports: 13 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

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

View Source
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

View Source
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")
)

Sentinel errors returned by Promote. Callers (CLI, wire-protocol layer) distinguish refusal cases via errors.Is and map to user-facing codes.

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 its LastUsedAt is at least archiveIdleThreshold in the past. The boundary is inclusive: exactly 30 days idle archives.

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

func Sweep(reg *Registry, now time.Time) int

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.

func ValidID

func ValidID(s string) bool

ValidID reports whether s is a canonical UUIDv4 string of the shape NewID produces: 36 chars, lowercase hex, dashes at positions 8/13/18/23, version-4 nibble (0x4_) at position 14, and RFC 4122 variant (0x8/0x9/0xa/0xb) at position 19. Empty input returns false.

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 captured at conversation
	// creation time. Always present; never updated after creation.
	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)
	//   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"`

	// 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

type ListFilter struct {
	IsPromoted *bool
}

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.

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

func Load(path string) (*Registry, error)

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) Save

func (r *Registry) Save(path string) error

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) 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).

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL