memorelay

package
v0.172.0 Latest Latest
Warning

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

Go to latest
Published: Nov 8, 2026 License: MIT Imports: 24 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 memorelay RELAYS cairn scope memos to dispatched agents: muster reads the live memos of the scopes its agents work on from a cairn memo listener, with ONE read-only credential, and hands each agent each memo once, as a turn through the agent's own gateway.

Why muster relays, instead of each agent asking

cairn's memos reach a host session through a hook that runs cairn's client with the host's own credential. An agent pod has neither: no client, no credential, and a network policy that keeps it off private addresses. Putting a credential in every pod would also multiply the one hazard the listener has — it locks a PEER out for 15 minutes after 5 refused credentials in a minute, and behind a node's masquerade every pod on that node is one peer, the node's own host sessions included. One process holding one credential is one backoff for the whole fleet (Listener).

How a memo reaches an agent

Through Gateway — agentgateway.Gateway's Resolve and Send, the path an operator's chat message and a dispatch's first turn already travel. There is no second channel: a memo arrives as a turn, lands in the agent's transcript beside every other message, and waits for an agent that is mid-turn (the runtime's typed `busy` pastes nothing, and the next tick offers it again).

⚠ THAT WAIT IS A PROPERTY OF ONE RUNTIME, SO ONLY ITS AGENTS ARE SERVED. The claude-code runtime (cmd/ccd) refuses a turn that arrives during another before it pastes anything. No other kind is known to, so an agent of any other kind is counted (ResultKindUnsupported) and sent nothing.

What is delivered is a fenced block (Render): cairn's own fence, standing line and field replacement, re-applied here because the relay cannot know it is talking to a real listener.

Which agents, and which scope

🔴 ONLY THE OPERATOR'S AGENTS, AND THE DATABASE ENFORCES IT. The credential is the operator's view of their own cairn; an agent owned by any other user of this deployment must never be shown it. Relay.Run acts as authz.Operator, so row-level security hands it the operator's agents and nobody else's, and Relay checks the owner again itself (a store without row-level security — every fake — still has to be refused).

An agent's scopes are derived, never configured per agent and never guessed: the repository the agent was dispatched for, else the repository its task names, through ScopeForRepo — and then through the deployment's ScopeMap, which may name a SET of scopes for one repository (cairn files memos under a clone's directory name, which need not be the repository's). An agent with no repository gets nothing, and is counted (ResultNoScope).

Once

"Already delivered" is a durable record per agent ROW (Ledger) — an agent's id is never reused, so a re-dispatch is a new agent and sees every live memo once. The record is written after the send, when it is true; PGLedger says what that order costs. A retracted or expired memo simply stops being listed by the listener, so it stops being delivered; one already delivered is not recalled (it is in the agent's context, as on a host).

A delivery runs under the agent's session claim (agents.Store.ClaimKickoff — the claim a first turn holds), and re-reads the agent and the record under it. So a memo never takes the session from a first turn that is still being handed over, and two processes cannot both send one agent the same memo — unless the first one's record could not be written (ResultRecordFailed), which is the same exposure as a process killed before its record.

The wire contract (`GET /client/v1/memos`, the memo's field names) and the block shape were read from cairn at revision f283823: internal/memowire, internal/memo/block.go, predicates.go.

Index

Constants

View Source
const (
	// OutcomeDelivered: the turn carrying the memos completed.
	OutcomeDelivered = "delivered"
	// OutcomeUnconfirmed: the turn was handed to the agent's runtime and then failed, timed out
	// or was cut off — the text may have been pasted, so it is never sent a second time.
	OutcomeUnconfirmed = "unconfirmed"
)

Outcome values a Ledger row records. Both mean "this agent is not sent these memos again".

View Source
const (

	// RefusedBackoff is how long the relay sends NOTHING after the listener refused its
	// credential (a 401).
	//
	// 🔴 IT IS THE LISTENER'S OWN LOCKOUT LENGTH, AND THE ARITHMETIC IS THE POINT. The listener
	// locks a peer out for 900 s after 5 refused credentials in 60 s, and behind a node's
	// masquerade every pod on that node — and the node's own host sessions — are ONE peer. With
	// this backoff the relay's refused requests are at least 900 s apart, so any 60 s window holds
	// at most one of them: it can never be what trips the lockout, and it probes a peer locked out
	// by something else at most once per lockout.
	RefusedBackoff = 15 * time.Minute

	// StartDelay is how long a new process sends nothing at all.
	//
	// 🔴 A NEWLY ISSUED CREDENTIAL IS REFUSED FOR UP TO 30 s, because the listener re-reads its
	// journal on a 30 s timer. A relay that asked the moment it started would be refused by a
	// correct credential and then sit out [RefusedBackoff]. It also bounds a crash loop: a process
	// that dies and restarts sends at most one request per StartDelay, however fast it restarts.
	StartDelay = time.Minute

	// UnreadableBackoff is how long a scope the listener answered its uniform miss for (404: no
	// such scope, or one this credential cannot read) is not asked for again. A 404 comes AFTER
	// authentication, so it counts toward no lockout; this only stops a request per tick for a
	// scope that will keep missing.
	UnreadableBackoff = 15 * time.Minute
)
View Source
const (
	ResultEligible    = "eligible"
	ResultForeign     = "foreign"      // a row this deployment's prefix did not produce
	ResultNotOperator = "not_operator" // owned by a user the credential does not belong to
	ResultNotRunning  = "not_running"  // any status but `running`
	// ResultKindUnsupported: a kind whose runtime is not KNOWN to refuse a turn while another
	// is running. Only the claude-code runtime answers a typed `busy` before pasting anything.
	ResultKindUnsupported   = "kind_unsupported"
	ResultKickoffOwed       = "kickoff_owed" // its first turn has not been handed over yet
	ResultNoToken           = "no_token"     // no gateway credential can be derived
	ResultNoScope           = "no_scope"     // neither the agent nor its task names a repository
	ResultScopeLookupFailed = "scope_lookup_failed"
)

The closed vocabulary of what one agent's check came to. Every listed agent is counted under exactly one, each tick.

View Source
const (
	ResultBusy           = agentgateway.UnsentBusy
	ResultNotReady       = agentgateway.UnsentNotReady
	ResultUnauthorized   = agentgateway.UnsentUnauthorized // the runtime refused muster's own bearer
	ResultRejected       = agentgateway.UnsentRejected     // the runtime refused the request's shape (a typed 400)
	ResultNeverConnected = agentgateway.UnsentNeverConnected
	ResultUnresolved     = "unresolved"
	ResultNoSession      = "no_session"
	// ResultSessionClaimed: another delivery holds the agent's session claim — its first turn
	// (internal/agentkickoff), another process's memo turn, or (the common case) THIS process's
	// own earlier memo turn, still running: once per tick for as long as it runs.
	ResultSessionClaimed = "session_claimed"
	// ResultClaimFailed: the claim could not be asked for at all (the database). Nothing is
	// sent on a claim that was not verified.
	ResultClaimFailed = "claim_failed"
	// ResultMoved: under the claim, the agent was no longer eligible for this scope, or had
	// already been sent everything in the batch.
	ResultMoved            = "moved"
	ResultLedgerUnreadable = "ledger_unreadable"
	ResultRecordFailed     = "record_failed"
)

What one delivery came to (beyond OutcomeDelivered and OutcomeUnconfirmed). Every one but the last sends nothing, and the memos are offered again next tick.

View Source
const AuditAction = "memo.delivered"

AuditAction is the audit_log action a delivery is recorded under, and auditObject the object: the agent ROW's id, which is an identity column and so is never reused — a re-dispatched task gets a new agent, a new id and therefore every live memo once.

View Source
const DefaultInterval = time.Minute

DefaultInterval is how often Relay.Run looks for memos to deliver. Each tick costs one listener request per distinct scope, one at a time.

View Source
const DefaultTurnTimeout = 15 * time.Minute

DefaultTurnTimeout bounds one delivered turn for a kind with no budget of its own.

View Source
const (

	// MaxPerDelivery is the most memos one delivered turn carries; the rest go in later turns,
	// oldest first. A scope may hold 200 live memos of 4 KiB each, and one turn is one paste.
	MaxPerDelivery = 5
)

The fenced block an agent is shown. Its shape is cairn's own (`internal/memo/block.go` at the revision named in the package doc): an opening marker at column 0 carrying a fresh nonce, the standing lines, one stanza per memo, a closing marker — and EVERY line between the markers behind [contentPrefix], which is what makes the fence structural: no memo text can reach column 0, where the markers live. The rendering itself is internal/fence's (extracted from here; a byte golden checked that the move changed no byte, and was deleted after it landed).

🔴 EVERY FIELD IS SANITISED HERE, AGAIN, ALTHOUGH THE LISTENER ALREADY RENDERED IT. The relay cannot know it is talking to a real listener, so what arrives is untrusted text and the same replacement runs on every output. Rendering already-rendered text is a no-op (U+FFFD is never fence.Unsafe), so a real listener's memos pass through unchanged.

Variables

View Source
var (
	// ErrNotYet: inside [StartDelay]. No request was sent.
	ErrNotYet = errors.New("memorelay: inside the start delay; nothing was sent")
	// ErrBackedOff: the listener refused the credential earlier and [RefusedBackoff] has not
	// passed. No request was sent.
	ErrBackedOff = errors.New("memorelay: backed off after a refused credential; nothing was sent")
	// ErrRefused: the listener answered 401 to THIS request. [RefusedBackoff] starts now.
	ErrRefused = errors.New("memorelay: the listener refused the relay's credential (401)")
	// ErrScopeUnreadable: the listener answered its uniform miss for the scope (404) to THIS
	// request. The scope's [UnreadableBackoff] starts now.
	ErrScopeUnreadable = errors.New("memorelay: the listener has no such scope for this credential (404)")
	// ErrScopeBackedOff: the scope missed earlier and its [UnreadableBackoff] has not passed. No
	// request was sent.
	ErrScopeBackedOff = errors.New("memorelay: the scope missed earlier; nothing was sent for it")
	// ErrUnreachable: no answer at all — the request could not be made, or its answer not read.
	ErrUnreachable = errors.New("memorelay: the listener could not be reached")
	// ErrUnexpectedStatus: an answer whose status is none of 200, 401, 404. The listener IS
	// there, so this says nothing about the next scope.
	ErrUnexpectedStatus = errors.New("memorelay: the listener answered an unexpected status")
	// ErrMalformed: a 200 whose body is not the wire contract.
	ErrMalformed = errors.New("memorelay: the listener's answer is not a memo list")
)

The closed set of ways asking the listener ends without memos. Each is counted under its own name ([Outcome]); none is retried inside a tick.

Functions

func Render

func Render(scope string, memos []Memo) string

Render is the whole turn delivered to an agent for memos on scope: [preface], a blank line, then the fenced block with every memo's FULL body (the pod has no cairn client to run a `memo-read` with, so a preview would point at a command that does not exist there). Zero memos render as zero bytes.

func ScopeForRepo

func ScopeForRepo(repo string) string

ScopeForRepo is the cairn scope a repository's memos are filed under, or "" when repo names none.

cairn derives a scope from the basename of a clone's directory, normalised (lower-cased, every run outside `[a-z0-9.-]` folded to one `-`, leading and trailing `-` trimmed). A dispatched agent has no clone to ask, only the `owner/name` it was dispatched for, so the NAME stands in for the directory: a clone made with the default `git clone` is named after the repository.

⚠ A CLONE KEPT UNDER ANOTHER DIRECTORY NAME FILES ITS MEMOS UNDER THAT NAME, and this function cannot know it. Such a repository's agents ask for a scope that either does not exist or holds nothing — the listener answers its uniform miss, which the relay counts and does not retry for UnreadableBackoff. Nothing is guessed.

Types

type Config

type Config struct {
	// Agents is the agents store. REQUIRED.
	Agents agents.Store
	// TaskRepo returns the `owner/name` a task names ("" when it names none or no longer
	// exists). REQUIRED: it is the second half of the scope derivation.
	TaskRepo func(ctx context.Context, taskID int64) (string, error)
	// Gateway runs the turn. REQUIRED.
	Gateway Gateway
	// Source lists a scope's live memos. REQUIRED.
	Source Source
	// Ledger records what each agent was sent. REQUIRED.
	Ledger Ledger
	// NamespacePrefix is the deployment's configured agent namespace prefix; a row is this
	// deployment's iff its namespace is agents.NamespaceFor(prefix, name).
	NamespacePrefix string
	// ScopeMap maps a repository's derived scope to the set of scopes its agents read. Optional:
	// nil reads each repository's derived scope alone. See [ScopeMap].
	ScopeMap ScopeMap
	// Logger is optional. No line it is given ever carries memo text.
	Logger *log.Logger
	// TurnHold, when set, is called with the agent as a memo turn is sent and
	// returns the function that ends it: cmd/muster-server passes
	// api.Server.OutcomeHold, so a dispatched agent reading a memo (a claude-code
	// turn streams nothing until it ends) is working to the outcome watchdog,
	// never "silent", and the memo turn's reply is judged as nothing. Optional.
	TurnHold func(a agents.Agent) (release func())
}

Config is everything the relay needs. Every field without a stated default is required.

type Gateway

type Gateway interface {
	Resolve(ctx context.Context, a agents.Agent) (agentgateway.Target, error)
	Send(ctx context.Context, t agentgateway.Target, sessionKey, message string, emit func(string)) (string, error)
}

Gateway is a delivered turn's two halves, exactly internal/agentkickoff's: Resolve contacts no runtime, Send runs the turn. agentgateway.Gateway satisfies it.

type Key

type Key struct {
	Scope string
	ID    int64
}

Key names one memo. An id alone would do against one listener; the scope is carried so two scopes can never suppress each other's memos whatever a listener numbers them.

type Ledger

type Ledger interface {
	// Delivered returns every memo agentID has a record for.
	Delivered(ctx context.Context, agentID int64) (map[Key]bool, error)
	// Record appends one row: these memos of scope were sent to a, with outcome.
	Record(ctx context.Context, a agents.Agent, scope string, ids []int64, outcome string) error
}

Ledger is the durable record of which memos each agent has been sent. It is what makes "once" survive a restart of this process.

type Listener

type Listener struct {
	// contains filtered or unexported fields
}

Listener is the relay's ONE way to the cairn memo listener, and the fleet's one lockout guard: every agent's memos are fetched through it, so there is one credential, one backoff and one request in flight for all of them.

func NewListener

func NewListener(baseURL, token string, now func() time.Time) (*Listener, error)

NewListener builds the guard for the listener at baseURL (`http://host:port`), authenticated by token. now is the clock (nil: time.Now); the start delay runs from this call.

func (*Listener) Live

func (l *Listener) Live(ctx context.Context, scope string) ([]Memo, error)

Live returns scope's live memos — unexpired, unretracted, oldest first — or one of the errors above. It sends at most one request, and none at all inside the start delay, a refused-credential backoff or the scope's own miss backoff.

type Memo

type Memo struct {
	ID        int64
	Scope     string
	Sender    string
	CreatedAt string
	ExpiresAt string
	Subject   string
	Body      string
	Tombstone string
	// contains filtered or unexported fields
}

Memo is one live memo as the listener sent it: cairn's `memo.Rendered`, whose JSON keys are its Go field names. Every string is UNTRUSTED TEXT (see block.go).

type PGLedger

type PGLedger struct {
	// contains filtered or unexported fields
}

PGLedger keeps the record in audit_log: one row per delivered turn, owned by the operator (whose agents these are — see the package doc), action AuditAction, object the agent, detail `{"scope":…,"memos":[…],"outcome":…}`.

🔴 IT IS AN APPEND-ONLY LOG ON PURPOSE, AND THAT FIXES THE ORDER OF A DELIVERY. A row is written AFTER the send, when it is true, and never deleted; there is no claim to take first and undo later. So a process KILLED between a send and its row sends those memos once more after it restarts. A graceful shutdown is not that case: a cut-off turn is recorded on a detached budget before the pool closes (Relay.Done).

⚠ TWO THINGS THIS SHAPE COSTS, STATED: the rows appear in the admin page's recent activity (one per delivered turn — an untrusted block injected into an agent is an event an admin may want to see), and pruning audit_log rows younger than the longest memo lifetime would deliver their memos again. Nothing prunes audit_log today.

func NewPGLedger

func NewPGLedger(pool *pgxpool.Pool) *PGLedger

NewPGLedger builds the audit_log-backed ledger.

func (*PGLedger) Delivered

func (l *PGLedger) Delivered(ctx context.Context, agentID int64) (map[Key]bool, error)

Delivered reads the agent's rows. A row whose detail does not parse is skipped, never an error: only this package writes the action, and one unreadable row must not stop every delivery to the agent.

func (*PGLedger) Record

func (l *PGLedger) Record(ctx context.Context, a agents.Agent, scope string, ids []int64, outcome string) error

Record appends the row as the acting principal's own entry (audit_log's self_append policy): the relay runs as the operator, and a.OwnerID is the operator's by Relay's own gate.

type Relay

type Relay struct {
	// contains filtered or unexported fields
}

Relay delivers memos. Build it with New.

func New

func New(cfg Config) (*Relay, error)

New validates the configuration and builds the relay.

func (*Relay) Counts

func (r *Relay) Counts() map[string]int

Counts is a snapshot of everything counted so far, keyed "<family>/<result>" with the families `agent`, `upstream` and `delivery`. The same increments feed internal/metrics.

func (*Relay) Done

func (r *Relay) Done() <-chan struct{}

Done is closed once Relay.Run has returned — after every delivery it started has recorded its outcome. The process's shutdown waits on it before closing the database pool, so a turn cut off by a redeploy is recorded rather than delivered again by the next process.

func (*Relay) Hold added in v0.165.0

func (r *Relay) Hold(a agents.Agent) (release func())

Hold holds a's turn the way every memo turn to it is held (Config.TurnHold) and returns the release; a no-op without a TurnHold.

func (*Relay) Run

func (r *Relay) Run(ctx context.Context, interval time.Duration)

Run ticks every interval until ctx is cancelled, then waits for in-flight deliveries to record their outcome and closes Relay.Done.

func (*Relay) ScopeMap

func (r *Relay) ScopeMap() ScopeMap

ScopeMap is the map this relay classifies with — what the wiring handed it, for the wiring's own test to read back.

func (*Relay) Tick

func (r *Relay) Tick(ctx context.Context) error

Tick makes one pass: classify every agent, ask the listener once per distinct scope, and start a delivery for each agent with memos it has not been sent.

🔴 A REFUSED CREDENTIAL ENDS THE TICK. The listener is asked for nothing more — not for the next scope, not on the next tick — until RefusedBackoff has passed; Listener holds that rule, and this loop simply stops asking when told. An unreachable listener ends the tick too (each further scope would only wait out another timeout).

func (*Relay) Wait

func (r *Relay) Wait()

Wait blocks until every delivery started by Relay.Tick has finished.

type ScopeMap

type ScopeMap map[string][]string

ScopeMap is the deployment's DETERMINISTIC mapping from a repository's derived scope (what ScopeForRepo answers) to the SET of cairn scopes an agent working on that repository reads. A repository absent from the map reads exactly its derived scope.

🔴 IT EXISTS BECAUSE cairn NAMES A SCOPE AFTER A CLONE'S DIRECTORY, NOT ITS REPOSITORY. A repository cloned under another directory name has its memos filed under that name by host sessions, while the relay derives the repository's own name — and when BOTH scopes exist the mismatch is silent (the listener answers 200 for the one nobody writes to). The map names, per repository, every scope its memos are filed under. It is configuration and not a rule, because which directory a clone lives in is a fact about a deployment's hosts, not about the repository.

⚠ AN ENTRY REPLACES THE DEFAULT, IT DOES NOT ADD TO IT: a repository mapped to {b} reads b and NOT its own name. Name the derived scope in the set to keep it.

func ParseScopeMap

func ParseScopeMap(spec string) (ScopeMap, error)

ParseScopeMap reads `repo=scope,scope;repo=scope`. Every name must already be in the normalised form ScopeForRepo produces (so a key can only ever match by equality), every entry needs at least one scope, and a repository may appear once. Whitespace around names is ignored; an empty spec is an empty map.

func (ScopeMap) String

func (m ScopeMap) String() string

String renders the map in the form ParseScopeMap reads, keys sorted — for the boot banner.

type Source

type Source interface {
	Live(ctx context.Context, scope string) ([]Memo, error)
}

Source is where live memos come from. Listener is the production one.

Jump to

Keyboard shortcuts

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