conversations

package
v0.34.0 Latest Latest
Warning

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

Go to latest
Published: Oct 5, 2026 License: MIT Imports: 14 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 (
	MaxPendingChannelPosts      = 64
	MaxPendingChannelPostsBytes = 64 << 10
)

MaxPendingChannelPosts and MaxPendingChannelPostsBytes bound Conversation.PendingChannelPosts, both inclusive: a post landing exactly on either is admitted (#2499). Nothing else bounds the carry — a channel nobody answers would otherwise grow the registry file and the eventual stdin write without limit, reachable by any caller of the `channel.post` verb.

TWO CONSTANTS, BECAUSE ONE DOES NOT DO THE JOB. The byte cap alone admits 65536 one-byte posts, and every carried entry costs a separator in the rendered block the delivery seam composes, so the rendered size is not bounded by the byte cap on its own. The count cap alone would admit 64 posts of 64 KiB each.

MaxPendingChannelPostsBytes is the summed byte length of the stored texts, sized at ONE post's admitted size (control.MaxChannelPostBytes), so what accumulates can never make the eventual write to claude larger than a single post already can. The number is restated rather than imported for MaxSystemPromptBytes's reason: this package is a leaf and must not import internal/control. The two must move together.

MaxPendingChannelPosts is far above any plausible unanswered channel — a daily cron would need two months to reach it.

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

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

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 ContextUsageReading added in v0.19.0

type ContextUsageReading struct {
	// Model is the model claude reported the reading for.
	Model string `json:"model"`

	// TotalTokens is the context the conversation currently occupies.
	TotalTokens int `json:"total_tokens"`

	// MaxTokens is the window that context is measured against.
	MaxTokens int `json:"max_tokens"`

	// Percentage is claude's own rounded TotalTokens-of-MaxTokens figure, carried
	// rather than recomputed so a client sees the number claude reported.
	Percentage int `json:"percentage"`

	// AsOf is when the daemon recorded the reading, always UTC — normalised by
	// SetLastContextUsage, which is what makes the encoded form RFC 3339 with a Z
	// offset. time.Time marshals with whatever offset it carries, so the
	// normalisation lives at the one door rather than at each producer.
	AsOf time.Time `json:"as_of"`
}

ContextUsageReading is the SUMMARY of one context-window reading: the headline numbers a reconnecting client needs, and nothing else.

THE THREE INVENTORIES ARE DELIBERATELY ABSENT. The event this is projected from (turnevent.ContextUsage) also carries per-category, per-MCP-tool and per-memory-file breakdowns with their dropped counts. Those are not stored, for two independent reasons: they carry workspace memory-file paths and MCP server names that the frame's no-log rule keeps out of records, and a client coming back needs the headline numbers rather than a breakdown taken some turns ago. Do not "complete" this type by adding them.

All five keys always emit. A fresh session genuinely reads zero tokens at zero percent, so omitempty on the inner fields would encode a fact as an absence; the outer pointer on Conversation.LastContextUsage already carries the never-reported state.

The values are claude-authored and arrive bounded: streamsup's decodeContextUsage caps Model at its own string bound and is the single decoder BOTH lanes share, so nothing here re-bounds it.

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"`

	// ArchivedAt is when the conversation was archived (#2698), in UTC, so
	// every client can order its Archive screen newest-archived first. Set and
	// cleared together with IsArchived by Registry.SetArchived: stamped on the
	// active → archived transition, kept on a re-archive, nil once restored.
	// Nil on an archived row means it was archived before the stamp existed;
	// nothing invents a time for it.
	//
	// omitempty carries the same contract as IsArchived's: "an absent key
	// decodes as unstamped, with no migration step." A registry with no rows
	// archived since #2698 is byte-identical to its earlier form.
	ArchivedAt *time.Time `json:"archived_at,omitempty"`

	// IsMuted is the durable mute-notifications flag (#2571): true means the
	// operator silenced this conversation's alerts. It lives on the host so
	// every client reads one value; the clients raise their own alerts and
	// consult it. False by default.
	//
	// omitempty carries the same contract as IsArchived's: "an absent key
	// decodes as not muted, with no migration step." A registry with no muted
	// rows is byte-identical to its pre-#2571 form.
	IsMuted bool `json:"is_muted,omitempty"`

	// ReadUpTo is the host operator's durable history entry read mark.
	ReadUpTo uint64 `json:"read_up_to,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"`

	// LastContextUsage is the last context-window reading claude reported for
	// this conversation (#2460), so a client that reconnects, restarts, or opens
	// the conversation from a second device is shown the real numbers rather than
	// nothing or a transcript guess. nil means claude has never reported for this
	// conversation.
	//
	// A pointer for a reason adjacent to Name's and SystemPrompt's but not
	// identical: those need one to split "absent" from "explicitly empty", while
	// here a zero-valued reading is a FALSE reading — 0 tokens, 0%, the zero time
	// — that a client would render as fact. There is no explicitly-empty state
	// and nothing mints one: the only door, Registry.SetLastContextUsage, takes a
	// value rather than a pointer, so "clear it back to nil" is unreachable.
	//
	// omitempty carries the same contract as IsArchived's and SystemPrompt's: "an
	// absent key decodes as no reading, with no migration step." omitempty on a
	// pointer tests the pointer, so a registry whose rows all hold nil is
	// byte-identical to its pre-#2460 form.
	//
	// Written by both producers of a reading — the post-turn emitter arm (#2371)
	// and the on-demand request_context_usage flight (#2431) — through the one
	// setter. Last write wins; see SetLastContextUsage.
	LastContextUsage *ContextUsageReading `json:"last_context_usage,omitempty"`

	// PendingChannelPosts is the text posted into this channel that claude has not
	// been shown yet, oldest first (#2499). A `channel.post` records the content in
	// the durable log and pushes it to connected clients, but deliberately starts no
	// turn, so without this the operator's reply reaches claude with nothing before
	// it. The daemon's delivery seam carries these ahead of the next user turn it
	// writes and clears them once that write is confirmed.
	//
	// THIS IS THE ONE FIELD ON THIS RECORD THAT HOLDS CONVERSATION CONTENT, and it
	// is why the file's mode matters: Save already writes at 0600 through a temp +
	// rename, and SystemPrompt is already operator-authored content here, so the
	// row's sensitivity class is unchanged. Nothing in this package logs a record
	// field, so the text cannot leave the file by way of a log line.
	//
	// It is durable rather than in-memory because the whole point is a question
	// posted in the morning still being carried by a reply that evening, across a
	// daemon restart in between.
	//
	// omitempty carries the same contract as IsArchived's, SystemPrompt's and
	// LastContextUsage's: "an absent key decodes as nothing pending, with no
	// migration step." On a slice omitempty tests length, so a record whose last
	// entry was cleared omits the key exactly as one that never held a post does.
	//
	// Bounded by MaxPendingChannelPosts and MaxPendingChannelPostsBytes, enforced at
	// the one door — AppendPendingChannelPost. The bound refuses the NEWEST post
	// rather than evicting the oldest; that direction is load-bearing, and
	// ClearPendingChannelPosts records why.
	PendingChannelPosts []string `json:"pending_channel_posts,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

type ListFilter struct {
	IsPromoted *bool
	IsArchived *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. 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

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) AdvanceReadUpTo added in v0.33.0

func (r *Registry) AdvanceReadUpTo(id ConversationID, upTo, latest uint64, path string) (Conversation, bool, error)

AdvanceReadUpTo raises the host read mark of the conversation whose ID equals id (#2780) to max(held, min(upTo, latest)), where latest is the newest durable history entry id. A proposed mark past latest cannot mark future entries read, and a lower or equal one changes nothing. It returns the stored record and whether the mark advanced; a miss returns ErrConversationNotFound.

Unlike the other mutators it persists to path itself, and only on an actual advance. The compare, the write and a failed write's revert all run while saveMu and mu are held, as SwitchSession does: concurrent advances cannot regress the held or the saved mark, and no reader ever sees an advance that is not on disk. A retry after a failed save therefore advances afresh rather than reading as a no-op.

func (*Registry) AppendPendingChannelPost added in v0.20.0

func (r *Registry) AppendPendingChannelPost(id ConversationID, text string) bool

AppendPendingChannelPost appends text to the carry-forward record of the conversation whose ID equals id (#2499), so the daemon's next user turn for that conversation carries it to claude. Returns true when the text was recorded.

It sets exactly one field — PendingChannelPosts — so id, cwd, name, promoted/archived state, system prompt, last reading and session binding are structurally untouched, the same guarantee SetArchived and SetLastContextUsage give for theirs. The scan, the bound check and the append happen atomically under r.mu, so two concurrent posts into one channel are ordered rather than racing, and there is no find-then-mutate window a concurrent Create/Delete could redirect.

FALSE MEANS EITHER "no such row" OR "the bound is full", and the two are deliberately not distinguished. Every caller's response is the same — log and carry on, because a carry that could not be recorded must never turn a recorded post into a refusal — so a finer answer would be a distinction with no consumer.

THE BOUND REFUSES THE NEWEST POST RATHER THAN EVICTING THE OLDEST, and that direction is a correctness requirement rather than a preference. The consumer reads this record at composition time and clears the leading n entries once the write is confirmed, with a whole claude turn possible in between. Head eviction during that window would shift the entries the pending clear is counting, and the clear would then drop text that was never carried. Refusing at the tail leaves a clear as the ONLY thing that removes an entry from the head, which makes entries [0..n) provably stable across the window. See ClearPendingChannelPosts.

No UTF-8 validation, for SetWorkspaceLabel's stated reason: the text reached Go through encoding/json at the control-plane boundary, which has already substituted U+FFFD, so the round-trip-fidelity hazard SetSystemPrompt refuses cannot arrive at this door. The empty string is admitted — the verb's own handler refuses an empty message, and this layer stores what it is given.

AppendPendingChannelPost does NOT call Save — disk persistence is the caller's concern, matching the convention every other setter in this file states. It takes no logger, and nothing in this package logs a record field, so the posted text cannot leave the registry file by way of a log line.

func (*Registry) ClearPendingChannelPosts added in v0.20.0

func (r *Registry) ClearPendingChannelPosts(id ConversationID, n int) bool

ClearPendingChannelPosts drops the leading n entries from the carry-forward record of the conversation whose ID equals id (#2499). Returns true on hit, false on miss; on a miss no field of any record is modified.

N, NOT "ALL", is the whole point. The consumer reads the record at composition time and clears once the write to claude is confirmed, and a post can land in between — so clearing everything would discard text that was never carried, and the ticket's "carried exactly once" would hold in one direction only. n is the count the consumer actually composed; entries past it stay pending for the next turn. AppendPendingChannelPost's refuse-the-newest bound is what makes the leading n the same entries the consumer read.

n <= 0 mutates nothing and still reports the hit, which is the right answer for a confirmed delivery that carried nothing. n >= len clears the record; a reslice past the end is deliberately not a panic here, because the consumer's count and this record are read under two separate lock acquisitions and a shorter record is a legitimate outcome rather than a programming error.

The tail is kept by RESLICING rather than by copying down. The elements ahead of the new head are not written, which is what keeps a concurrently-held snapshot from PendingChannelPosts consistent, and the retained backing array is bounded by MaxPendingChannelPostsBytes.

ClearPendingChannelPosts does NOT call Save — disk persistence is the caller's concern, matching the convention every other setter in this file states.

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.

On a hit, the observer installed by SetOnDelete is called with id after r.mu is released; a miss never calls it.

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) MarkSeeded added in v0.27.0

func (r *Registry) MarkSeeded()

MarkSeeded sets the seed marker. There is no way to clear it. It does NOT call Save — persistence is the caller's concern, as for every other mutator here.

func (*Registry) PendingChannelPosts added in v0.20.0

func (r *Registry) PendingChannelPosts(id ConversationID) []string

PendingChannelPosts returns the carry-forward record of the conversation whose ID equals id, oldest first (#2499), or nil when the registry holds no row for id or the row has nothing pending. The two absent cases are one answer because the consumer composes the same identity prompt for both.

IT RETURNS A FRESH COPY, never the stored slice. WorkspaceLabel's argument transfers: handing back a collection that a mutator writes under r.mu is an escape the signature should make impossible rather than one a caller must remember not to take. The elements are strings, so the copy is as deep as it needs to be.

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

func (r *Registry) RebindSession(oldID, newID string) bool

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) RekeyCwds added in v0.23.0

func (r *Registry) RekeyCwds(rekey map[string]string) int

RekeyCwds rewrites a workspace's cwd across the whole registry in one step (#2568): every conversation whose Cwd is a key of rekey gets the mapped value, and the workspace label stored under that key moves with it, so a label key keeps byte-equalling a stored Cwd (the invariant rename_workspace's workspace.not_found refusal is built on). It returns the number of rows rewritten.

Where keys collapse, the label already stored under the new key wins and the old key's label is dropped. Between two old keys collapsing into one unlabelled new key, the old keys are visited in sorted order and the first label to land wins, so the outcome does not depend on map iteration order. Every old key is deleted either way. An entry mapping a key to itself is ignored.

Rows and labels change under one hold of mu, so no reader sees a row moved without its label. The caller resolves the new values before calling — no filesystem work happens under the lock. Like every mutator here it does NOT call Save and does not log.

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) Seeded added in v0.27.0

func (r *Registry) Seeded() bool

Seeded reports whether the host's one-time starting point has been settled (#2569): seeded, or skipped because conversations already existed.

func (*Registry) SetArchived added in v0.16.0

func (r *Registry) SetArchived(id ConversationID, archived bool, now time.Time) 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 the two archive fields — IsArchived and its ArchivedAt stamp (#2698) — so id, cwd, name, promoted state, LastUsedAt and session binding are structurally untouched. This is the deterministic enforcement of the "flips only the archive state" 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, and the flag and its stamp can never be observed disagreeing.

The single archived bool both sets and clears. Archiving an active row stamps ArchivedAt with now in UTC — the caller passes now, as the idle sweep's callers do. SetArchived(id, true) on an already-archived row returns true and changes nothing, so the original stamp is kept, and a row archived before the stamp existed stays unstamped rather than reading as the newest archive. Restoring clears both fields.

SetArchived does NOT call Save — disk persistence is the caller's concern, matching the Create / Update / Promote / Delete / RebindSession convention.

func (*Registry) SetLastContextUsage added in v0.19.0

func (r *Registry) SetLastContextUsage(id ConversationID, reading ContextUsageReading) bool

SetLastContextUsage records the last context-window reading claude reported for the conversation whose ID equals id (#2460). Returns true on hit, false on miss; on a miss no field of any record is modified.

It sets exactly one field — LastContextUsage — so id, cwd, name, promoted/archived state, system prompt and session binding are structurally untouched, the same guarantee SetArchived and SetSystemPrompt give for theirs. The scan and mutation happen atomically under r.mu, so there is no find-then-mutate window a concurrent Create/Delete could redirect.

IT TAKES A VALUE, NOT A POINTER, which is the one place it deliberately departs from SetSystemPrompt's tri-state door. No producer of a reading ever clears one: a conversation that has never been reported on carries nil from creation, and once claude has answered there is always a last reading. A value argument makes "set it back to nil" unreachable rather than merely unused.

LAST WRITE WINS, AND THAT IS THE INTENDED BEHAVIOUR. The two producers — the post-turn emitter arm and the on-demand request_context_usage flight — run on different goroutines and can settle seconds apart; both readings are valid "last reading" values and r.mu makes the write safe. Do not add AsOf comparison or any other ordering machinery here.

AsOf is normalised to UTC so the encoded form is RFC 3339 with a Z offset: time.Time marshals with whatever offset it carries, so a caller-side .UTC() would be one forgettable step per producer. The instant is preserved — this changes the location, not the time.

No value validation and no second byte bound. Model arrives from streamsup's decodeContextUsage, the single decoder both lanes share, which already caps it; the other three are decoded ints. No invalid-UTF-8 sentinel either, for SetWorkspaceLabel's stated reason: the string reached Go through encoding/json, which has already substituted U+FFFD, so the round-trip-fidelity hazard SetSystemPrompt refuses cannot arrive at this door.

The value is copied into a fresh local before its address is taken, so the stored pointer never aliases a caller-held variable — the idiom Promote uses for Name and SetSystemPrompt for its prompt.

SetLastContextUsage does NOT call Save — disk persistence is the caller's concern, matching the Create / Update / Promote / Delete / RebindSession / SetArchived / SetSystemPrompt / SetWorkspaceLabel convention. It takes no logger, and nothing in this package logs a record field, so a reading cannot leave the registry file by way of a log line.

func (*Registry) SetMuted added in v0.24.0

func (r *Registry) SetMuted(id ConversationID, muted bool) bool

SetMuted sets the durable mute-notifications flag of the conversation whose ID equals id (#2572): muted=true mutes it, muted=false unmutes it. Returns true on hit, false on miss; on miss no field of any record is modified.

It sets exactly one field — IsMuted — with the same guarantees SetArchived gives for its own: the scan and mutation happen atomically under r.mu, and setting the value the row already has is a hit that changes nothing.

SetMuted does NOT call Save — disk persistence is the caller's concern.

func (*Registry) SetOnDelete added in v0.22.0

func (r *Registry) SetOnDelete(fn func(id ConversationID))

SetOnDelete installs fn as the registry's removal observer, replacing any earlier one; nil clears it. Delete calls fn once per removed conversation, with that conversation's id, and never on a miss. Delete is the single path both removals take — the delete_conversation handler and the idle Sweep — so this one slot sees every removal (#1502). The daemon uses it to free the removed conversation's replay-ring entry.

fn runs on the deleting goroutine after r.mu is released, so it may call back into the registry and takes no lock-order position beneath r.mu. It must not block for long: the handler and the sweep both wait on it.

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

func (r *Registry) SetWorkspaceLabel(cwd string, label *string)

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) SwitchSession added in v0.29.0

func (r *Registry) SwitchSession(id ConversationID, oldID, newID, path string) (bool, error)

SwitchSession serializes the rebind and its Save with other registry saves and mutations. A failed Save restores the binding and appended history entry before any competing mutation can observe the transient new binding.

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

func (r *Registry) WorkspaceLabel(cwd string) (string, bool)

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.

Jump to

Keyboard shortcuts

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