Documentation
¶
Overview ¶
Package store is the log of record (SP2 §4): one gapless, append-only sequence per room, in PostgreSQL. The database enforces the invariants too (migrations/20260927120000_rooms.sql), so a bug or a stolen broker credential cannot rewrite history.
Index ¶
- Constants
- Variables
- func IsDataError(err error) bool
- func Migrate(ctx context.Context, dsn string, log *slog.Logger) (int, error)
- func ValidDrillID(id string) bool
- type Approval
- type DrillReport
- type Exception
- type GitHubLink
- type GitHubState
- type Grant
- type GrantEvent
- type GrantFilter
- type GrantMove
- type Handoff
- type IntentSample
- type NewGrant
- type NewRoom
- type Promotion
- type Queued
- type Role
- type RoomState
- type Server
- type SlackCode
- type SlackLink
- type Store
- func (s *Store) Append(ctx context.Context, d envelope.Draft) (envelope.Event, bool, error)
- func (s *Store) AppendAsBridge(ctx context.Context, bridgeRun string, d envelope.Draft) (envelope.Event, bool, error)
- func (s *Store) AppendAsDriver(ctx context.Context, driver string, epoch int64, d envelope.Draft) (envelope.Event, bool, error)
- func (s *Store) Approval(ctx context.Context, id string) (Approval, error)
- func (s *Store) BriefSources(ctx context.Context, roomID string) ([]envelope.Event, error)
- func (s *Store) BriefSourcesThrough(ctx context.Context, roomID string, seq int64) ([]envelope.Event, error)
- func (s *Store) Bundle(ctx context.Context, room, run, digest string) ([]byte, error)
- func (s *Store) ChangeDriver(ctx context.Context, roomID string, expect int64, to, reason string, ...) (envelope.Event, bool, error)
- func (s *Store) ClaimBridge(ctx context.Context, roomID, runID string, ...) (string, bool, error)
- func (s *Store) Close()
- func (s *Store) CloseOutputApproval(ctx context.Context, id, state string) (Approval, error)
- func (s *Store) CloseRoom(ctx context.Context, roomID, reason string) error
- func (s *Store) ConfirmGitHubLink(ctx context.Context, stateSHA256 []byte, sub string, now time.Time) (string, error)
- func (s *Store) CreateGrant(ctx context.Context, n NewGrant) (Grant, error)
- func (s *Store) Cursor(ctx context.Context, roomID, originClient string) (int64, error)
- func (s *Store) Decide(ctx context.Context, approvalID, decision, by, reason string, d envelope.Draft) (envelope.Event, Approval, error)
- func (s *Store) DecideException(ctx context.Context, id, state, by, note string, expires time.Time) (Exception, error)
- func (s *Store) Deliveries(ctx context.Context, roomID, runID string, after, through int64, limit int) ([]envelope.Event, error)
- func (s *Store) Disable(ctx context.Context, sub string) error
- func (s *Store) DrillPassed(ctx context.Context, id string) (pass, found bool, err error)
- func (s *Store) DriverSeen(ctx context.Context, roomID, principal string, acted bool) error
- func (s *Store) Enqueue(ctx context.Context, d envelope.Draft, author, text string) (envelope.Event, error)
- func (s *Store) EnsureRoom(ctx context.Context, r NewRoom) (bool, error)
- func (s *Store) Exception(ctx context.Context, id string) (Exception, error)
- func (s *Store) ExpireDriver(ctx context.Context, roomID string, expect int64, to string, d envelope.Draft) (envelope.Event, bool, error)
- func (s *Store) ExpireDue(ctx context.Context) ([]envelope.Event, error)
- func (s *Store) ExpiredVerdicts(ctx context.Context, before time.Time, limit int) ([]envelope.Event, error)
- func (s *Store) Failed(ctx context.Context, sub string) (failures int, err error)
- func (s *Store) Fork(ctx context.Context, src string, upTo int64, r NewRoom, d envelope.Draft, ...) (envelope.Event, error)
- func (s *Store) GetHandoff(ctx context.Context, id string, now time.Time) (Handoff, error)
- func (s *Store) GitHubLinkHolder(ctx context.Context, githubID int64) (string, bool, error)
- func (s *Store) GitHubLinkOf(ctx context.Context, sub string) (GitHubLink, bool, error)
- func (s *Store) GitHubState(ctx context.Context, stateSHA256 []byte, now time.Time) (GitHubState, error)
- func (s *Store) Grant(ctx context.Context, id string) (Grant, error)
- func (s *Store) GrantEvents(ctx context.Context, id string) ([]GrantEvent, error)
- func (s *Store) Grants(ctx context.Context, f GrantFilter) ([]Grant, error)
- func (s *Store) InsertIntentSample(ctx context.Context, in IntentSample, retentionDays int) (int64, error)
- func (s *Store) IntentSamplesSince(ctx context.Context, days int) ([]IntentSample, error)
- func (s *Store) Lagging(ctx context.Context, sub string, limit int) ([]string, error)
- func (s *Store) LapsedDrivers(ctx context.Context) ([]RoomState, error)
- func (s *Store) LastAck(ctx context.Context, roomID, runID string) (int64, error)
- func (s *Store) LastEventAt(ctx context.Context, ids []string) (map[string]time.Time, error)
- func (s *Store) LastHarnessEnd(ctx context.Context, roomID, runID string) (string, error)
- func (s *Store) LastHarnessError(ctx context.Context, roomID, runID string) (code, detail string, err error)
- func (s *Store) LastHarnessStatus(ctx context.Context, roomID, runID string) (string, error)
- func (s *Store) LastTaskState(ctx context.Context, roomID string, after int64) (json.RawMessage, error)
- func (s *Store) LatestDrill(ctx context.Context, version, configHash string) (id string, at time.Time, pass, found bool, err error)
- func (s *Store) LinkSlack(ctx context.Context, codeSHA256 []byte, team, sub string, now time.Time) (SlackCode, error)
- func (s *Store) Listen(ctx context.Context, ready func(), fn func(roomID string, seq int64)) error
- func (s *Store) LookupGrants(ctx context.Context, repository, class, policyHash string, ...) ([]Grant, []string, error)
- func (s *Store) MintSlackCode(ctx context.Context, codeSHA256 []byte, c SlackCode, now time.Time) error
- func (s *Store) MoveGrant(ctx context.Context, id string, m GrantMove) (Grant, error)
- func (s *Store) MovePromotion(ctx context.Context, id, state string, pullRequest int, by string) (Promotion, error)
- func (s *Store) OldestPending(ctx context.Context) (time.Duration, int, error)
- func (s *Store) OpenApprovals(ctx context.Context, roomID string) ([]Approval, error)
- func (s *Store) OutputEvents(ctx context.Context, room, run, outputID string) ([]envelope.Event, error)
- func (s *Store) PendingApprovals(ctx context.Context, roomID string) (int, error)
- func (s *Store) PendingRuns(ctx context.Context, roomID string, within time.Duration) ([]string, error)
- func (s *Store) Ping(ctx context.Context) error
- func (s *Store) PolicyAudit(ctx context.Context, repository string) ([]Promotion, []Exception, error)
- func (s *Store) PromoteQueued(ctx context.Context, roomID string, ref int64, driver string, epoch int64, ...) (envelope.Event, error)
- func (s *Store) Promotion(ctx context.Context, id string) (Promotion, error)
- func (s *Store) Prompters(ctx context.Context, roomID, runID string) ([]string, error)
- func (s *Store) PruneHandoffs(ctx context.Context, before time.Time) (int64, error)
- func (s *Store) PurgeExpired(ctx context.Context) (rooms, events int64, err error)
- func (s *Store) PurgeIntentSamples(ctx context.Context) (int64, error)
- func (s *Store) PutBundle(ctx context.Context, room, run, digest string, b []byte) error
- func (s *Store) PutDrillReport(ctx context.Context, r DrillReport) error
- func (s *Store) PutHandoff(ctx context.Context, h Handoff) error
- func (s *Store) Queue(ctx context.Context, roomID string) ([]Queued, error)
- func (s *Store) Range(ctx context.Context, roomID string, afterSeq int64, limit int) ([]envelope.Event, error)
- func (s *Store) Recheck(ctx context.Context) error
- func (s *Store) RecordPromotion(ctx context.Context, p Promotion) (Promotion, error)
- func (s *Store) RecordRunRequest(ctx context.Context, d envelope.Draft, runID string, refs []int64, ...) (envelope.Event, error)
- func (s *Store) RemoveQueued(ctx context.Context, roomID string, ref int64, d envelope.Draft) (envelope.Event, error)
- func (s *Store) RequestApproval(ctx context.Context, a Approval, d envelope.Draft) (Approval, envelope.Event, error)
- func (s *Store) RequestException(ctx context.Context, e Exception) (Exception, error)
- func (s *Store) RequestOutputApproval(ctx context.Context, a Approval, d envelope.Draft) (Approval, envelope.Event, error)
- func (s *Store) Room(ctx context.Context, id string) (RoomState, error)
- func (s *Store) SchemaCurrent(ctx context.Context) error
- func (s *Store) SchemaReady(ctx context.Context) (bool, error)
- func (s *Store) SealedSince(ctx context.Context, since time.Time, limit int) ([]RoomState, error)
- func (s *Store) SetGitHubStateUser(ctx context.Context, stateSHA256 []byte, githubID int64, login string, ...) error
- func (s *Store) SetIntentSampleOutcome(ctx context.Context, id int64, outcome string) (bool, error)
- func (s *Store) SetQueued(ctx context.Context, roomID string, ref int64, to, runID string) error
- func (s *Store) SetWebhookCursor(ctx context.Context, sub, room string, seq int64) error
- func (s *Store) SlackCode(ctx context.Context, codeSHA256 []byte, now time.Time) (SlackCode, error)
- func (s *Store) SlackLink(ctx context.Context, team, user string) (sub string, found bool, err error)
- func (s *Store) SlackLinksOf(ctx context.Context, sub string) ([]SlackLink, error)
- func (s *Store) StartGitHubLink(ctx context.Context, stateSHA256 []byte, sub string, nonceSHA256 []byte, ...) error
- func (s *Store) Stored(ctx context.Context, d envelope.Draft) (envelope.Event, bool, error)
- func (s *Store) Subscriber(ctx context.Context, sub string, generation int) (failures int, disabled bool, err error)
- func (s *Store) Succeeded(ctx context.Context, sub string) error
- func (s *Store) SupersedeAnswered(ctx context.Context) ([]envelope.Event, error)
- func (s *Store) SweepBundles(ctx context.Context, now time.Time) (int64, error)
- func (s *Store) TaskReasons(ctx context.Context, after map[string]int64) (map[string]string, error)
- func (s *Store) TaskStateAt(ctx context.Context, roomID string, after, upTo int64) (json.RawMessage, error)
- func (s *Store) TouchBridge(ctx context.Context, roomID, runID string) (bool, error)
- func (s *Store) TouchGitHubLink(ctx context.Context, sub string, now time.Time) (bool, error)
- func (s *Store) Unfinished(ctx context.Context, clientPrefix string, first, last int64) ([]envelope.Event, error)
- func (s *Store) UnlinkGitHub(ctx context.Context, sub, actor string, admin bool, now time.Time) (bool, error)
- func (s *Store) UnlinkSlack(ctx context.Context, team, user, sub string) (gone bool, err error)
- func (s *Store) UnpostedVerdicts(ctx context.Context, since time.Time, limit int, exclude []string) ([]envelope.Event, error)
- func (s *Store) WebhookCursor(ctx context.Context, sub, room string) (int64, error)
Constants ¶
const ( ApprovalPending = "pending" ApprovalApproved = "approved" ApprovalDenied = "denied" ApprovalExpired = "expired" ApprovalSuperseded = "superseded" )
An approval's states: pending, then closed once (SP2 §6).
const ( GitHubLinked = "linked" GitHubRelinked = "relinked" GitHubUnlinked = "unlinked" GitHubAdminUnlinked = "admin_unlinked" )
The link acts, github_link_events.act: a closed list.
const ( MaxGrantList = 500 MaxGrantEvents = 200 )
MaxGrantList bounds one listing of grants, and MaxGrantEvents one grant's history.
const ( SampleShadowed = "shadowed" SampleConfirmed = "confirmed" SampleCancelled = "cancelled" SampleExpired = "expired" )
The outcomes of an intent sample (SI19): shadowed when stage 1 classified and answered as ever, then, from stage 3, what became of the confirm.
const ( PromotionRequested = "requested" PromotionPROpened = "pr_opened" PromotionMerged = "merged" PromotionAbandoned = "abandoned" ExceptionRequested = "requested" ExceptionApproved = "approved" ExceptionRefused = "refused" )
The promotion workflow's states (merge policy stage 6).
const ( // MaxSlackCodes bounds the live codes in all: each Slack user holds one at most. MaxSlackCodes = 1000 // MaxSlackLinks bounds the Slack users one ZITADEL account holds. MaxSlackLinks = 5 )
The Slack self-serve link's bounds (docs/superpowers/specs/2026-10-28-slack-self-serve-link-design.md).
const BundleRetention = 14 * 24 * time.Hour
BundleRetention is how long a bundle is kept once stored, unless a pending approval binds it.
const ListenApplication = "room-broker-listen"
ListenApplication is the listener connection's application_name, so an operator can find it in pg_stat_activity.
const MaxBundle = 8 << 20
MaxBundle is a push bundle's cap, the design's 8 MiB (hardening.MaxBundle).
const MaxDrillReport = 256 << 10
MaxDrillReport bounds one stored drill report's JSON (HR38).
const MaxGitHubPending = 3
MaxGitHubPending bounds one sub's live flows.
const MinRetention = 24 * time.Hour
MinRetention is the schema's floor on a room's retention (rooms.retention >= 1 day), like the Room CRD's <n>d.
const VerdictsClient = "broker:verdicts"
VerdictsClient is the origin of the leader's verdict_posted and verdict_not_posted records. Their origin_seq is the verdict's seq, so the idempotency key is the record, and a new leader writes nothing twice.
Variables ¶
var ( // ErrAlreadyDecided is a decision on an approval that is no longer pending: // the first valid decision won, or its call already has a result, or its run ended. ErrAlreadyDecided = errors.New("already_decided") // ErrApprovalExpired is a human decision on an approval past its deadline: // the deadline decides, so a late decision never wins over the expiry sweep. ErrApprovalExpired = errors.New("approval_expired") // ErrNoApproval is an approval id the room log does not hold. ErrNoApproval = errors.New("no such approval") // ErrBadDecision is a human decision other than approved or denied. ErrBadDecision = errors.New("a decision is approved or denied") // ErrTooLarge is an approval whose request event would exceed the payload cap: // stored as an oversize stub, it would not be the request the row records. ErrTooLarge = errors.New("the approval request exceeds the payload cap") // ErrBindingConflict is a retried output approval naming another digest or branch than the one // its output's approval already binds. ErrBindingConflict = errors.New("the output's approval binds another digest or branch") )
var ( // ErrDigestMismatch is a bundle whose bytes do not hash to the digest it was stored under. ErrDigestMismatch = errors.New("the bundle's sha256 is not its digest") // ErrBundleTooLarge is an empty bundle or one over MaxBundle. ErrBundleTooLarge = errors.New("a bundle is 1 byte to 8 MiB") // ErrNoBundle is a bundle the store does not hold for that room, run and digest. ErrNoBundle = errors.New("no such bundle") )
var ( ErrServerTooOld = errors.New("the server is below Postgres 16") ErrWrongRole = errors.New("connected as another role") ErrBypassesRLS = errors.New("the role bypasses row-level security") ErrMissingRoles = errors.New("the login roles are missing") ErrSchemaBehind = errors.New("the schema is behind the binary") ErrSchemaAhead = errors.New("the schema is ahead of the binary") )
What a Check or a schema check refused, for a caller that maps it to a code (the preflight's database check): each is matched with errors.Is, and leaves the message as it was.
var ( // ErrDrillExists is a second report under a drill id: each drill is scored once. ErrDrillExists = errors.New("a report for this drill is already stored") // ErrBadDrillReport is a report the table would refuse: a bad id, version, hash or time, or a // report that is not one JSON value of at most MaxDrillReport bytes. ErrBadDrillReport = errors.New("a drill report has an id, a version, a 64-hex hash, a time and a JSON report of at most 256 KiB") )
var ( // ErrStaleEpoch is a driver change whose expected epoch the room has moved past. ErrStaleEpoch = errors.New("stale_epoch") // ErrInvalidDriver is a change to no principal, or to the current holder. ErrInvalidDriver = errors.New("the next driver is a principal other than the holder") // ErrNotLapsed is a lease expiry of a holder who is not a lapsed human, or to // another principal than the room's fallback. ErrNotLapsed = errors.New("the holder is no lapsed human") )
var ( ErrTooManyPending = errors.New("too many GitHub links are in progress for the account") // ErrStateInvalid is a state that is unknown, expired, already used or, at the confirm, not yet // through the callback. ErrStateInvalid = errors.New("the GitHub link state is unknown, expired or used") // ErrSubMismatch is a confirm under another sub than the one that started the flow. ErrSubMismatch = errors.New("the GitHub link was started by another account") // ErrGitHubTaken is a GitHub id linked to another sub: an admin unlinks it first. ErrGitHubTaken = errors.New("the GitHub account is linked to another account") )
The link's refusals, each a reason the page names.
var ( ErrNoGrant = errors.New("no such approval grant") // ErrGrantState is a move the grant's status does not allow: revoking a revoked grant, // reconfirming an active one, using a suspended one. ErrGrantState = errors.New("the approval grant does not move that way from its status") // ErrGrantVersion is a move bound to a version the grant has since left (MP12). ErrGrantVersion = errors.New("the approval grant moved on since that version was read") )
The grant refusals callers branch on.
var ( ErrNoPolicyRecord = errors.New("store: no such promotion or exception") // ErrPolicyMoved is a move the record's state does not allow: it was decided or closed already, // or the move skips what it needs (a pull request number). ErrPolicyMoved = errors.New("store: the record cannot move so") // ErrPromotionOpen is a second open promotion of one class. ErrPromotionOpen = errors.New("store: the class has an open promotion") // ErrExceptionUnusable is a promotion naming an exception that is not approved, has expired, or // is another class's or minimum's. ErrExceptionUnusable = errors.New("store: the exception is not an approved one of this class") )
The workflow's refusals, each one a reason the API names.
var ( // ErrNotQueued is a state move from a state the queued message is no longer in. ErrNotQueued = errors.New("not_queued") // ErrNotAQueuedMessage is an Enqueue whose draft is not the queued message it // records: not a message, not delivery queued, another text or another author. ErrNotAQueuedMessage = errors.New("the draft is not this queued message by its actor") // ErrBadMove is a queue move the state machine has no edge for. ErrBadMove = errors.New("a queued message moves once, out of queued; promoted and consumed name their run") // ErrNotAuthor is a removal by neither the message's author nor the driver (§2). ErrNotAuthor = errors.New("only the author or the driver removes a queued message") )
var ( ErrCodeInvalid = errors.New("the link code is unknown, expired or used") ErrTooManyCodes = errors.New("too many link codes are waiting") ErrTooManyLinks = errors.New("the account holds the most Slack users it may") // ErrAlreadyLinked is a Slack user linked to another account: a link is never moved silently, // it is unlinked first. ErrAlreadyLinked = errors.New("the Slack user is linked to another account") )
The link's refusals, each a reason the page names.
var ( ErrNoRoom = errors.New("no such room") ErrSealed = errors.New("room is sealed") ErrLeaseLost = errors.New("the bridge lease is held by another run") ErrInvalidRetention = errors.New("retention must be at least a day") // ErrNoBridgeRun is AppendAsBridge without a run: it would append unfenced. ErrNoBridgeRun = errors.New("a bridge append names its run") // ErrKeyConflict is an idempotency key already stored for another kind of event: // a replay of it would report a change that never happened. ErrKeyConflict = errors.New("idempotency key already used by another event type") )
The store's sentinel errors; callers compare with errors.Is.
var ErrBadIntentSample = errors.New("store: not a valid intent sample")
ErrBadIntentSample is a sample the table's checks refuse: a malformed channel, an empty or oversized reply, a label outside the nine, a retention under a day.
var ErrBadSeq = errors.New("bad_seq")
ErrBadSeq is a fork point outside the source room's log.
var ErrForkTooLarge = errors.New("fork prefix over the caps")
ErrForkTooLarge is a prefix over MaxForkEvents or MaxForkBytes.
var ErrLedgerUnreadable = errors.New("rooms_broker cannot read the migration ledger: set broker.database.ownerSecret, " +
"whose migrate grants SELECT (version) ON public.room_broker_revisions TO rooms_broker (docs/database.md)")
ErrLedgerUnreadable is a schema version serve could not read: its ledger exists but this role cannot read it. The broker refuses to serve it, as it refuses a schema behind or ahead (v4 D9): migrate, with broker.database.ownerSecret, adopts an Atlas operator's ledger and grants the read.
var ErrNoHandoff = errors.New("no such handoff")
ErrNoHandoff is an unknown or expired handoff id.
ErrUnavailable is a database Check could not ask: unreachable, not answering, starting up or out of connections. Unlike a refusal (a wrong password, a missing database, a certificate the client cannot verify), it may pass on a retry.
Functions ¶
func IsDataError ¶
IsDataError reports a value PostgreSQL refuses outright (SQLSTATE class 22, such as 22P05 for a NUL in jsonb). Retrying cannot help, so the caller stores a stub instead.
func Migrate ¶
Migrate applies the embedded migrations in order, recording each file's SHA-256. A file whose checksum changed after it was applied, or a recorded version this binary does not ship, is refused: the database is ahead of or different from the code. It returns how many it applied.
func ValidDrillID ¶ added in v0.47.0
ValidDrillID reports whether id is a drill id the table takes.
Types ¶
type Approval ¶
type Approval struct {
ID, RoomID, RunID, EventID, CallID, Class, State string
// BindingBranch is the branch a forge.push approval binds, from the run's AgentRun (D5): the
// boundary the repository ruleset already enforces on that run's token. Empty otherwise.
BindingBranch string
// BindingDigest and BindingOutput bind a factory-requested forge.push approval to one push
// bundle's digest and the output id that carries it (hardening HR28). Empty on every other row.
BindingDigest, BindingOutput string
Action json.RawMessage
Prompters []string
RequestedSeq int64
RequestedAt, ExpiresAt time.Time
// DecidedBy is who closed the row, a human or the broker; empty while pending.
DecidedBy string
}
Approval is one row of the approvals projection.
func (Approval) DigestBound ¶ added in v0.46.0
DigestBound reports whether a is a factory-requested approval of one push bundle (HR28).
type DrillReport ¶ added in v0.47.0
type DrillReport struct {
ID string
Version string
ConfigHash string
At time.Time
Pass bool
Report json.RawMessage
}
DrillReport is one scored drill as the store keeps it (HR38): what it proved (a Maku version under one hardening configuration hash), when, whether it passed, and the scorer's report.
func (DrillReport) Validate ¶ added in v0.47.0
func (r DrillReport) Validate() error
Validate holds r to what the table takes.
type Exception ¶ added in v0.40.0
type Exception struct {
ID string `json:"id"`
Repository string `json:"repository"`
Class string `json:"class"`
Minimum int `json:"minimum"`
Justification string `json:"justification"`
RequestedBy string `json:"requestedBy"`
RequestedAt time.Time `json:"requestedAt"`
State string `json:"state"`
DecidedBy string `json:"decidedBy,omitempty"`
DecidedAt *time.Time `json:"decidedAt,omitempty"`
Note string `json:"note,omitempty"`
ExpiresAt *time.Time `json:"expiresAt,omitempty"`
}
Exception is one operator exception below the evidence minimum (MP7).
type GitHubLink ¶ added in v0.47.0
type GitHubLink struct {
Sub string
GitHubID int64
Login string
LinkedAt time.Time
LastSeenAt time.Time
}
GitHubLink is a sub's link: the numeric GitHub id, the login at link time (display only), and when the human last authenticated.
type GitHubState ¶ added in v0.47.0
type GitHubState struct {
Sub string
NonceSHA256 []byte
Expires time.Time
GitHubID int64
Login string
}
GitHubState is a flow in progress: who started it, the SHA-256 of the cookie nonce that must come back with it, and, once the callback ran, the GitHub user it proved.
type Grant ¶ added in v0.40.0
type Grant struct {
ID, Repository, Class string
Version int
Files []string
DiffShape, PolicyHash string
OriginPR int
CreatedBy string
CreatedAt, RenewedAt time.Time
ExpiresAt time.Time
Status string
StatusAt, LastUsedAt time.Time
LastUsedPR int
}
Grant is one saved approval grant as stored. LastUsedAt is zero and LastUsedPR 0 until it is used. PolicyHash (column policy_hash, wire key policyHash) carries the resolved class's hash since B13: the class definition, the policy and the repository's binding together, not the file's hash.
type GrantEvent ¶ added in v0.40.0
type GrantEvent struct {
ID int64
GrantID string
Version int
Event, Actor, Reason string
PolicyHash, Head string
PR int
At time.Time
}
GrantEvent is one entry of a grant's audit.
type GrantFilter ¶ added in v0.40.0
GrantFilter narrows a listing: by repository (lowercase owner/name), class and status; "" is any.
type GrantMove ¶ added in v0.40.0
type GrantMove struct {
Event, Actor, Reason string
Version int
PolicyHash string
Lifetime time.Duration
PR int
Head string
}
GrantMove is one move of a grant: its event, the version it was read at (0 for whichever is current), who made it and why. PolicyHash is the class definition a reconfirmation binds to, or the one a suspension was found under (the resolved class's hash, B13); Lifetime is a renewal's, from now; PR and Head are a use's.
type Handoff ¶ added in v0.53.0
type Handoff struct {
ID, Principal string
Args, Plan json.RawMessage
Hash string
CreatedAt time.Time
ExpiresAt time.Time
}
Handoff is one stored plan held on the broker (UX2), bound to the principal that asked for it until ExpiresAt.
type IntentSample ¶ added in v0.45.0
type IntentSample struct {
ID int64 `json:"id"`
Channel string `json:"channel"`
Reply string `json:"reply"`
Intent string `json:"intent"`
Confidence float64 `json:"confidence"`
Outcome string `json:"outcome"`
CreatedAt time.Time `json:"createdAt"`
}
IntentSample is one reply of an opted-in channel with its label. Reply must already be redacted.
type NewGrant ¶ added in v0.40.0
type NewGrant struct {
ID, Repository, Class string
Files []string
DiffShape, PolicyHash string
OriginPR int
CreatedBy string
Lifetime time.Duration
}
NewGrant is a grant to create: its predicate (validated by the caller, checked again by the table), its origin, its creator and its lifetime from now.
type NewRoom ¶
type NewRoom struct {
ID string
Driver string // spec.driver: the initial holder, and the system fallback
Retention time.Duration
}
NewRoom is what EnsureRoom needs from a Room CR.
type Promotion ¶ added in v0.40.0
type Promotion struct {
ID string `json:"id"`
Repository string `json:"repository"`
Class string `json:"class"`
Threshold int `json:"threshold"`
Evidence json.RawMessage `json:"evidence"`
ExceptionID string `json:"exceptionId,omitempty"`
RequestedBy string `json:"requestedBy"`
RequestedAt time.Time `json:"requestedAt"`
State string `json:"state"`
PullRequest int `json:"pullRequest,omitempty"`
ClosedBy string `json:"closedBy,omitempty"`
ClosedAt *time.Time `json:"closedAt,omitempty"`
}
Promotion is one request to promote a class to live, on the evidence it was granted on.
type Role ¶ added in v0.47.0
type Role string
Role is one of the three fixed database roles. The migrations GRANT to them by name, so an install cannot rename them (v4 D9).
type RoomState ¶
type RoomState struct {
ID string
LastSeq int64
Driver string
DriverEpoch int64
// FallbackDriver is the system holder a lapsed human driver falls back to, or "".
FallbackDriver string
Sealed bool
ClosedAt *time.Time
LastEventAt time.Time
}
RoomState is a room's row as the broker reads it.
type Server ¶ added in v0.47.0
Server is what Check read about the connection: the server's version, the role connected and whether the connection is encrypted. TLS is reported, never required: the demo's hop is plain.
func Check ¶ added in v0.47.0
Check refuses a connection the room log must not run on, with one message per failure: a server below Postgres 16, a role other than the one expected, a role that bypasses row-level security (superuser, BYPASSRLS, membership in a role that is either, and, for the broker and the retention job, membership in the owner role or owning a table without FORCE ROW LEVEL SECURITY), and, for the owner, a missing login role the migrations GRANT to. The owner owns every table the files create, so owning one is its job, not a bypass. The room log's immutability rests on the grants and the policies (T12, SC-10), so none of these is a warning.
type SlackCode ¶
SlackCode is what a code binds: the Slack user it was minted for, as the App saw them (their handle and display name, display only), and when it expires.
type Store ¶
type Store struct {
// Server is what Open's Check read: the server's version, the role and whether the
// connection is encrypted.
Server Server
MaxEvents int64
MaxBytes int64
// MaxForkEvents and MaxForkBytes cap a fork's prefix. The copy is one
// transaction inside an act's 15 s, and its time grows faster than its
// length: 5,000 events took 2.5 s on a local Postgres, 20,000 took 28.6 s.
MaxForkEvents int64
MaxForkBytes int64
// Now stamps event timestamps. Lease freshness and close dates use the
// database's now() instead: one clock for every broker replica.
Now func() time.Time
// ListenPing is how long Listen waits for a notification before it pings,
// so a half-open connection after a failover is noticed (default 30 s).
ListenPing time.Duration
// contains filtered or unexported fields
}
Store is the room log over a PostgreSQL pool, connected as rooms_broker.
func Open ¶
Open connects as role with every session bounded, so no statement, lock queue or abandoned transaction holds a room's row lock for long, and the pool capped at 8 connections. A value set in the URL wins. It refuses what Check refuses: a server below 16, another role, or a role that bypasses row-level security.
func (*Store) Append ¶
Append adds d to its room's log, for writers that hold no bridge lease (humans, the broker, system callers). dup is true for a replayed idempotency key; a key stored for another event type is ErrKeyConflict.
func (*Store) AppendAsBridge ¶
func (s *Store) AppendAsBridge(ctx context.Context, bridgeRun string, d envelope.Draft) (envelope.Event, bool, error)
AppendAsBridge appends for the bridge of bridgeRun, and refuses with ErrLeaseLost once another run holds the room's bridge lease (ruling P17, review I7).
func (*Store) AppendAsDriver ¶
func (s *Store) AppendAsDriver(ctx context.Context, driver string, epoch int64, d envelope.Draft) (envelope.Event, bool, error)
AppendAsDriver appends a driver-only action for driver, and refuses with ErrStaleEpoch unless driver still holds the token at epoch (§2): the check runs under the room's row lock, so it holds across broker replicas.
func (*Store) BriefSources ¶
BriefSources returns what the next run's brief may quote from the log: the room's latest agent handoff and latest agent review_verdict, in seq order (review 4.4 M3 and I3). Only agents wrote them; no window of the log is read.
func (*Store) BriefSourcesThrough ¶
func (s *Store) BriefSourcesThrough(ctx context.Context, roomID string, seq int64) ([]envelope.Event, error)
BriefSourcesThrough is BriefSources as the log stood at seq: what a fork at seq bases its run on (§5).
func (*Store) Bundle ¶ added in v0.46.0
Bundle returns the bundle run stored in room under digest, or ErrNoBundle.
func (*Store) ChangeDriver ¶
func (s *Store) ChangeDriver(ctx context.Context, roomID string, expect int64, to, reason string, d envelope.Draft) (envelope.Event, bool, error)
ChangeDriver moves the token only if the room's epoch is still expect, the fence that makes a give, a take and a lease expiry safe across replicas (§2). d carries the actor, origin and idempotency key; the store fills the type and the DriverPayload. A replayed key returns the stored event, dup true, and moves nothing.
func (*Store) ClaimBridge ¶
func (s *Store) ClaimBridge(ctx context.Context, roomID, runID string, live func(ctx context.Context, runID string) bool) (string, bool, error)
ClaimBridge takes the room's bridge lease for runID (ruling P17). It lives in the room's row, so every broker replica agrees (review I7). Another run keeps it for as long as live(holder) is true, however long since its bridge was seen: a quiet or cut-off bridge may still have a harness at work, and two runs must never execute in one room (ruling SBB, F15). A run that ended frees it at once. live may call the Kubernetes API, so it runs outside any transaction, and the takeover that follows is a compare-and-swap on the holder it asked about. A sealed room refuses every claim with ErrSealed, also one sealed while live runs: the swap requires the room unsealed, and the retry that follows reads the seal.
func (*Store) CloseOutputApproval ¶ added in v0.46.0
CloseOutputApproval closes a pending digest-bound approval as state, which is superseded only: the factory's close when a later push of the run replaces the one it held (HR27). A row already closed is returned as it is, with no event. A row that is not digest-bound is ErrNoApproval: the bridge's approvals are not the factory's to close.
func (*Store) CloseRoom ¶
CloseRoom seals the log with a final state_changed{room_phase: Closed}. Its retention clock starts now (OD-17). Closing twice is a no-op.
func (*Store) ConfirmGitHubLink ¶ added in v0.47.0
func (s *Store) ConfirmGitHubLink(ctx context.Context, stateSHA256 []byte, sub string, now time.Time) (string, error)
ConfirmGitHubLink links sub to the GitHub user its flow proved, consuming the flow, and appends the act, in one transaction. A flow that is unknown, expired or not through the callback is ErrStateInvalid; another sub's is ErrSubMismatch; an id linked to another sub ErrGitHubTaken. The refusals write nothing. It answers GitHubLinked, or GitHubRelinked when sub had a link.
func (*Store) CreateGrant ¶ added in v0.40.0
CreateGrant stores a grant, active at version 1 until now plus its lifetime, with its created event.
func (*Store) Cursor ¶
Cursor is the highest origin_seq stored for originClient in the room, 0 if none: where a reconnecting writer resumes.
func (*Store) Decide ¶
func (s *Store) Decide(ctx context.Context, approvalID, decision, by, reason string, d envelope.Draft) (envelope.Event, Approval, error)
Decide records a human's decision, approved or denied, and appends approval_decided in one transaction. UPDATE … WHERE state = 'pending' under the room's row lock is the whole race (§2): the first valid decision wins, and every later one, a supersede included, is ErrAlreadyDecided. A decision on a call that already has a result closes the approval as superseded and is ErrAlreadyDecided too. One past the deadline, read in the same transaction, closes it as expired and is ErrApprovalExpired, as is any decision on an expired approval. Like the driver's acts, d's key is checked first: a replayed decision returns its stored event, and a key stored for anything else is ErrKeyConflict.
func (*Store) DecideException ¶ added in v0.40.0
func (s *Store) DecideException(ctx context.Context, id, state, by, note string, expires time.Time) (Exception, error)
DecideException approves (until expires) or refuses a requested exception, once.
func (*Store) Deliveries ¶
func (s *Store) Deliveries(ctx context.Context, roomID, runID string, after, through int64, limit int) ([]envelope.Event, error)
Deliveries returns up to limit of the run's deliveries in (after, through], in seq order, through events_deliveries: a stream's replay reads only what it may send, never the room's whole log (review I3).
func (*Store) DrillPassed ¶ added in v0.47.0
DrillPassed is whether the stored report of drill id passed, and whether one is stored: what the factory marks a manifest with when its report was stored by an earlier pass (#520's review).
func (*Store) DriverSeen ¶
DriverSeen is the holder's heartbeat (every ping) and, with acted, its last action. Anyone but the holder is a no-op.
func (*Store) Enqueue ¶
func (s *Store) Enqueue(ctx context.Context, d envelope.Draft, author, text string) (envelope.Event, error)
Enqueue appends a queued message and its FIFO row in one transaction (§2). author is always d's actor, and text its payload's: anything else is ErrNotAQueuedMessage. A replayed key returns the stored event and adds no row; a key stored for anything but a queued message is ErrKeyConflict.
func (*Store) EnsureRoom ¶
EnsureRoom inserts the room's row once. created is false when it already existed. fallback_driver is the system holder a lapsed human driver falls back to (§2); a room that starts with a human driver has none until a system principal holds it. A retention under MinRetention is refused with ErrInvalidRetention before the database, whose check (Ruling AE) would refuse it as a bare 23514.
func (*Store) ExpireDriver ¶
func (s *Store) ExpireDriver(ctx context.Context, roomID string, expect int64, to string, d envelope.Draft) (envelope.Event, bool, error)
ExpireDriver is the lease sweeper's ChangeDriver to the room's fallback, with the reason lease_expired. It moves the token only if a human still holds it at expect and is still lapsed under the row lock (ErrNotLapsed otherwise): one who came back between the sweep's read and this write keeps it.
func (*Store) ExpireDue ¶
ExpireDue closes every pending approval past its deadline as expired (§6 Timeouts), in open rooms: a sealed room takes no event. It returns the events it appended; one a human decided meanwhile is skipped.
func (*Store) ExpiredVerdicts ¶
func (s *Store) ExpiredVerdicts(ctx context.Context, before time.Time, limit int) ([]envelope.Event, error)
ExpiredVerdicts are the verdicts UnpostedVerdicts no longer returns: stamped at or before before, oldest first, with no outcome yet (review 3.5 m2b).
func (*Store) Fork ¶
func (s *Store) Fork(ctx context.Context, src string, upTo int64, r NewRoom, d envelope.Draft, fields map[string]any) (envelope.Event, error)
Fork creates room r from events 1..upTo of src, copied with their seq, id and idempotency key (§5), then appends d as state_changed{forked_from}: fields, plus the source room and seq. The copy is the fork's own, so it outlives src's purge, and a copied key deduplicates the Room controller's seq-1 Open. It runs as the broker's role, under the grants and triggers every append meets: the row starts empty, and nothing in src changes, a sealed src included. A prefix over MaxForkEvents or MaxForkBytes is refused with ErrForkTooLarge.
The fork also carries the source's queue as it stood at upTo: the messages queued by then and not yet taken out of the queue, each queued again in the fork. One gap: a row consumed through POST /v1/rooms/{id}/queue/consume (Store.SetQueued) leaves no event to date it, so it is carried only while it is still queued; consumed that way after upTo and before the fork, it is not.
func (*Store) GetHandoff ¶ added in v0.53.0
GetHandoff returns the stored handoff for id when its expiry is after now, or ErrNoHandoff when unknown or expired.
func (*Store) GitHubLinkHolder ¶ added in v0.47.0
GitHubLinkHolder is the sub whose link holds githubID; found is false when none does.
func (*Store) GitHubLinkOf ¶ added in v0.47.0
GitHubLinkOf is sub's link; found is false when it has none.
func (*Store) GitHubState ¶ added in v0.47.0
func (s *Store) GitHubState(ctx context.Context, stateSHA256 []byte, now time.Time) (GitHubState, error)
GitHubState reads a live flow: ErrStateInvalid when it is unknown or expired.
func (*Store) GrantEvents ¶ added in v0.40.0
GrantEvents is a grant's audit, oldest first, at most MaxGrantEvents.
func (*Store) Grants ¶ added in v0.40.0
Grants lists grants, newest first, at most f.Limit (MaxGrantList when 0 or more).
func (*Store) InsertIntentSample ¶ added in v0.45.0
func (s *Store) InsertIntentSample(ctx context.Context, in IntentSample, retentionDays int) (int64, error)
InsertIntentSample stores a shadowed sample that expires retentionDays from now, and returns its id. The expiry is stamped here so the retention job needs no configuration.
func (*Store) IntentSamplesSince ¶ added in v0.45.0
IntentSamplesSince lists the samples of the last days days, oldest first: what `maku-broker intent-samples` exports for labelling.
func (*Store) Lagging ¶
Lagging lists up to limit rooms whose last_seq is past the subscriber's cursor, newest activity first. The emitter asks on each reconnect of Listen, since notifications sent while the listener was down are gone.
func (*Store) LapsedDrivers ¶
LapsedDrivers lists human holders disconnected over 2 min or idle over 15 min, in open rooms that have a system holder to fall back to.
func (*Store) LastAck ¶
LastAck is where a bridge's deliveries resume: the highest ref the run's bridge acknowledged as delivered, interrupted, undeliverable or decision_applied, 0 if none. A ref that is not a seq, or not a delivery of this run, is skipped.
func (*Store) LastEventAt ¶
LastEventAt is when each room's log last moved, for the rooms in ids that exist. One query: the room list reads it for every row it shows.
func (*Store) LastHarnessEnd ¶
LastHarnessEnd is the run's last loop end reason the bridge recorded (harness_end), "" for none.
func (*Store) LastHarnessError ¶ added in v0.43.0
func (s *Store) LastHarnessError(ctx context.Context, roomID, runID string) (code, detail string, err error)
LastHarnessError is the code and detail of the run's last harness_error (a conversation error the harness reported), "" for either when absent.
func (*Store) LastHarnessStatus ¶
LastHarnessStatus is the run's last execution_status the bridge mirrored (ruling P15).
func (*Store) LastTaskState ¶
func (s *Store) LastTaskState(ctx context.Context, roomID string, after int64) (json.RawMessage, error)
LastTaskState is the payload of the room's highest-seq state_changed{kind:task} above seq after, or nil when the factory wrote none there. The seq decides, so a late or replayed write cannot win. A fork passes its fork point: the facts at or below it are its source's.
func (*Store) LatestDrill ¶ added in v0.47.0
func (s *Store) LatestDrill(ctx context.Context, version, configHash string) (id string, at time.Time, pass, found bool, err error)
LatestDrill returns the newest report for version and configHash, passing or not, and whether there is one (R6, #531's review): a fail newer than a pass makes R6 false until a newer pass.
func (*Store) LinkSlack ¶
func (s *Store) LinkSlack(ctx context.Context, codeSHA256 []byte, team, sub string, now time.Time) (SlackCode, error)
LinkSlack uses a live code of team once and links its Slack user to sub. A Slack user linked to another account is ErrAlreadyLinked, and an account past MaxSlackLinks ErrTooManyLinks; either leaves the code unused. A link to the same account is refreshed.
func (*Store) Listen ¶
Listen holds one LISTEN session on a dedicated connection, outside the pool, so neither starves the other. It calls ready once LISTEN is in place, then fn for every notification, from its own goroutine: fn must not block, or PostgreSQL's notification queue backs up and every append fails. It returns nil when ctx ends and an error when the connection is lost; the caller reconnects and catches up, since notifications sent meanwhile are gone.
func (*Store) LookupGrants ¶ added in v0.40.0
func (s *Store) LookupGrants(ctx context.Context, repository, class, policyHash string, maxLifetime time.Duration, actor string) ([]Grant, []string, error)
LookupGrants is the factory's read of a repository class's grants, immediately before a decision (merge policy stage 5): under their row locks, an active or suspended grant past its expiry or past maxLifetime since its last renewal is expired, an active one made under another policy than policyHash is suspended until reconfirmed, and the grants still active are returned with the events the lookup recorded.
func (*Store) MintSlackCode ¶
func (s *Store) MintSlackCode(ctx context.Context, codeSHA256 []byte, c SlackCode, now time.Time) error
MintSlackCode stores a code by its hash for c's Slack user, replacing that user's earlier code, after purging every expired or used one. It refuses once MaxSlackCodes are live.
func (*Store) MoveGrant ¶ added in v0.40.0
MoveGrant makes one move of grant id, under the grant's row lock: revoked, disabled, suspended, expired, reconfirmed, renewed or used. A move its status does not allow is ErrGrantState, one bound to a version since left ErrGrantVersion, an unknown grant ErrNoGrant.
func (*Store) MovePromotion ¶ added in v0.40.0
func (s *Store) MovePromotion(ctx context.Context, id, state string, pullRequest int, by string) (Promotion, error)
MovePromotion moves a promotion to state, naming its pull request (0 keeps the one it names).
func (*Store) OldestPending ¶
OldestPending is the age of the oldest pending approval in an open room, and how many there are, on the database's clock.
func (*Store) OpenApprovals ¶
OpenApprovals lists the room's pending approvals, oldest first, for the state frame: a page's tail of 500 events may not reach back to a request.
func (*Store) OutputEvents ¶ added in v0.46.0
func (s *Store) OutputEvents(ctx context.Context, room, run, outputID string) ([]envelope.Event, error)
OutputEvents returns run's message events in room whose output record names outputID, oldest first, at most maxOutputEvents: what output_status reads. The caller still reads each through envelope.ReadOutput, which trusts the stamp, never the payload.
func (*Store) PendingApprovals ¶
PendingApprovals counts the room's undecided approvals; a sealed room has none anyone can decide.
func (*Store) PendingRuns ¶
func (s *Store) PendingRuns(ctx context.Context, roomID string, within time.Duration) ([]string, error)
PendingRuns lists the runs requested in the room within the last within whose run has not joined yet (review 4.4 I2): a rendered claim not applied, or a factory run the watch has not seen.
func (*Store) PolicyAudit ¶ added in v0.40.0
func (s *Store) PolicyAudit(ctx context.Context, repository string) ([]Promotion, []Exception, error)
PolicyAudit is repository's newest promotions and exceptions, newest first.
func (*Store) PromoteQueued ¶
func (s *Store) PromoteQueued(ctx context.Context, roomID string, ref int64, driver string, epoch int64, runID string, d envelope.Draft) (envelope.Event, error)
PromoteQueued turns a queued message into steering for runID, in one transaction fenced on the driver token (§2): the row moves to promoted and the steering message, caused by it, is appended together, or neither is. d carries the actor, origin and key; the store fills the type, the cause and the payload.
func (*Store) Prompters ¶
Prompters are the humans who prompted a run, whom OD-16's four-eyes rule keeps from deciding its approvals: whoever requested it, steered it, or wrote a queued message its brief consumed or that was promoted to it.
func (*Store) PruneHandoffs ¶ added in v0.53.0
PruneHandoffs deletes every stored handoff whose expiry is at or before before, and returns how many were deleted.
func (*Store) PurgeExpired ¶
PurgeExpired deletes every expired room's log, then its row, one room per transaction, so each stays bounded by the room limits (100 000 events). Each transaction runs under its own purgeStatementTimeout (SET LOCAL), not the session's statement_timeout. It runs as rooms_retention; the broker's role holds no DELETE and fails. Every table referencing rooms (queue, approvals, and webhook_cursors and output_bundles when their migrations ran) is deleted before the room's row.
func (*Store) PurgeIntentSamples ¶ added in v0.45.0
PurgeIntentSamples deletes every sample past its expiry and returns how many. It runs as rooms_retention; the broker's role holds no DELETE.
func (*Store) PutBundle ¶ added in v0.46.0
PutBundle stores b, a run's push bundle, under (run, digest) in room (HR22). digest must be b's hex sha256. A second put of the same run and digest is a no-op. A sealed room takes none.
func (*Store) PutDrillReport ¶ added in v0.47.0
func (s *Store) PutDrillReport(ctx context.Context, r DrillReport) error
PutDrillReport stores r once: a second report under its id is ErrDrillExists, whatever it holds.
func (*Store) PutHandoff ¶ added in v0.53.0
PutHandoff inserts or replaces h by its ID.
func (*Store) Range ¶
func (s *Store) Range(ctx context.Context, roomID string, afterSeq int64, limit int) ([]envelope.Event, error)
Range returns up to limit events of the room after afterSeq, in seq order.
func (*Store) Recheck ¶ added in v0.48.0
Recheck runs Open's Check again on the pool, for the preflight's database check: the server may have been downgraded or the role altered since the broker started.
func (*Store) RecordPromotion ¶ added in v0.40.0
RecordPromotion records p as requested, now: ErrPromotionOpen beside an open one of its class, ErrExceptionUnusable when its exception cannot carry it.
func (*Store) RecordRunRequest ¶
func (s *Store) RecordRunRequest(ctx context.Context, d envelope.Draft, runID string, refs []int64, fields map[string]any) (envelope.Event, error)
RecordRunRequest records the request of runID in d's room as state_changed{run_requested}, and moves the queued messages its brief quoted (refs) to consumed by runID, in one transaction: a brief's messages are consumed exactly when its run is on the record. The store fills d's type and payload: fields, plus runId and consumed, the refs it moved (one removed meanwhile stays removed). A replayed key returns the stored record and moves nothing; a key stored for anything else is ErrKeyConflict.
func (*Store) RemoveQueued ¶
func (s *Store) RemoveQueued(ctx context.Context, roomID string, ref int64, d envelope.Draft) (envelope.Event, error)
RemoveQueued withdraws a queued message for d's actor, its author or the driver (ErrNotAuthor otherwise), and records state_changed{queued_removed} in the same transaction. The store fills d's type and payload.
func (*Store) RequestApproval ¶
func (s *Store) RequestApproval(ctx context.Context, a Approval, d envelope.Draft) (Approval, envelope.Event, error)
RequestApproval records a pending approval and appends approval_requested in one transaction, fenced on the run's bridge lease like its other appends (Ruling Y). It is idempotent per (room, run, eventId): a bridge that re-sends the request, after a restart too, gets the stored approval back and no event.
func (*Store) RequestException ¶ added in v0.40.0
RequestException records e as requested, now.
func (*Store) RequestOutputApproval ¶ added in v0.46.0
func (s *Store) RequestOutputApproval(ctx context.Context, a Approval, d envelope.Draft) (Approval, envelope.Event, error)
RequestOutputApproval records a pending forge.push approval bound to one push bundle (hardening HR27, HR28) and appends its approval_requested, in one transaction. The factory asks for it, so no bridge lease fences it: a's run may have ended. a names its id, room, run, branch, digest, output, action, prompters and deadline; its event and call ids are "output:<output>". It is idempotent per (run, output): a retried request gets the stored approval back and no event.
func (*Store) SchemaCurrent ¶ added in v0.47.0
SchemaCurrent is serve's check that the schema is the one this binary was built for: the newest recorded revision must be the newest embedded file. A ledger behind names migrate; a ledger ahead is migrate's own refusal. A ledger the role cannot read is ErrLedgerUnreadable.
func (*Store) SchemaReady ¶
SchemaReady backs /startupz: the Atlas migration has run.
func (*Store) SealedSince ¶ added in v0.40.1
SealedSince is the rooms sealed at or after since, the last closed first, at most limit: the rooms list's closed view. The factory deletes a task's Room object once it ends; its sealed row stays until retention purges it.
func (*Store) SetGitHubStateUser ¶ added in v0.47.0
func (s *Store) SetGitHubStateUser(ctx context.Context, stateSHA256 []byte, githubID int64, login string, now time.Time) error
SetGitHubStateUser records the GitHub user the callback proved on a live flow, once: a flow that already holds one is ErrStateInvalid, so a replayed callback cannot swap the account.
func (*Store) SetIntentSampleOutcome ¶ added in v0.45.0
SetIntentSampleOutcome moves a shadowed sample to confirmed, cancelled or expired, once, through the table's one function: the broker holds no UPDATE. It reports whether this call moved it.
func (*Store) SetQueued ¶
SetQueued moves a queued message out of queued: ErrNotQueued when it is no longer queued, ErrSealed once its room is sealed. A row moves once; promoted and consumed name the run (the steered one, or the one whose brief took it), removed names none: any other move is ErrBadMove.
func (*Store) SetWebhookCursor ¶
SetWebhookCursor moves the subscriber's cursor in room to seq; it never moves back.
func (*Store) SlackCode ¶
SlackCode reads a live code without using it: ErrCodeInvalid when it is unknown, expired or used.
func (*Store) SlackLink ¶
func (s *Store) SlackLink(ctx context.Context, team, user string) (sub string, found bool, err error)
SlackLink is the ZITADEL sub a Slack user is linked to; found is false when none is.
func (*Store) SlackLinksOf ¶
SlackLinksOf lists the account's Slack users, oldest link first.
func (*Store) StartGitHubLink ¶ added in v0.47.0
func (s *Store) StartGitHubLink(ctx context.Context, stateSHA256 []byte, sub string, nonceSHA256 []byte, expires, now time.Time) error
StartGitHubLink stores a new flow for sub, after purging every expired one. It refuses once sub holds MaxGitHubPending live flows.
func (*Store) Stored ¶
Stored returns the event already stored under d's idempotency key, if any. An act whose side effect lies outside the log, such as a run request, checks it first, so a replayed key never repeats that effect.
func (*Store) Subscriber ¶
func (s *Store) Subscriber(ctx context.Context, sub string, generation int) (failures int, disabled bool, err error)
Subscriber registers a webhook subscriber and returns where it stands (R17, R18), in one transaction. On the name's first insert only, every existing room gets a cursor at its last_seq, so no history is replayed; a re-added name keeps its row and its cursors. A new generation re-enables the subscriber.
func (*Store) SupersedeAnswered ¶
SupersedeAnswered closes as superseded every pending approval whose call has a tool_result (5.2 contract 5: the harness ran or rejected it), then every one whose run has ended: neither is left for approvers, nor counted as pending, nor holds its room AwaitingHuman.
func (*Store) SweepBundles ¶ added in v0.46.0
SweepBundles deletes the bundles stored more than BundleRetention before now, unless a pending approval binds one, and returns how many. It runs as rooms_retention, through the table's one function; the broker's role holds no DELETE.
func (*Store) TaskReasons ¶ added in v0.30.1
TaskReasons is the reason code of each room's last task facts above its bound in after (a fork's fork point, as in LastTaskState), for the rooms that have facts there. One query: the room list reads it for every failed row it shows.
func (*Store) TaskStateAt ¶
func (s *Store) TaskStateAt(ctx context.Context, roomID string, after, upTo int64) (json.RawMessage, error)
TaskStateAt is the payload of the room's highest-seq state_changed{kind:task} with after < seq <= upTo, or nil when there is none: the task facts as they stood at upTo. after is a fork's fork point, as in LastTaskState.
func (*Store) TouchBridge ¶
TouchBridge reports whether runID still holds the room's lease. held is false when another run took it: that bridge is displaced, and its appends fail with ErrLeaseLost.
func (*Store) TouchGitHubLink ¶ added in v0.47.0
TouchGitHubLink refreshes sub's last_seen_at when it is over an hour old, so each human writes at most once an hour. moved is whether it did; an unlinked sub moves nothing.
func (*Store) Unfinished ¶
func (s *Store) Unfinished(ctx context.Context, clientPrefix string, first, last int64) ([]envelope.Event, error)
Unfinished returns the opening event of every idempotency scope the broker writes, named clientPrefix+<anything>, that stored its seq first but not its seq last, in the rooms still open. The prefix is literal. The caller owns what the scope and its seqs mean (runwatch: a run that joined and never left).
func (*Store) UnlinkGitHub ¶ added in v0.47.0
func (s *Store) UnlinkGitHub(ctx context.Context, sub, actor string, admin bool, now time.Time) (bool, error)
UnlinkGitHub removes sub's link and appends the act: unlinked by the human, admin_unlinked when admin (an admin's page, or the break-glass command), with actor naming who. gone is false when there was nothing to remove, and then nothing is written.
func (*Store) UnlinkSlack ¶
UnlinkSlack removes a Slack user's link: only when it is sub's, or whoever's it is when sub is "" (the Slack user's own request, through the App). gone is false when there was nothing to remove.
func (*Store) UnpostedVerdicts ¶
func (s *Store) UnpostedVerdicts(ctx context.Context, since time.Time, limit int, exclude []string) ([]envelope.Event, error)
UnpostedVerdicts are agents' review verdicts after since, oldest first, with no outcome yet (SP2 design §3), leaving out the event ids in exclude: the verdicts the poster holds in backoff, so they never starve the next ones.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package migrations is the schema, embedded for room-broker migrate (adoption 3b).
|
Package migrations is the schema, embedded for room-broker migrate (adoption 3b). |