Documentation
¶
Overview ¶
Package registry owns the agent/version domain: agent creation, resolution, effective-permission computation, and the publication state machine.
Platform staff is membership of the staff organization.
A deployment names its staff organization and that organization's domain (config auth.staffOrg, auth.staffDomain). An account is platform staff exactly while three facts hold, none of which a person can set about themselves:
- the account is active;
- its address is verified and its domain is exactly the staff domain (plain ASCII, so an internationalised look-alike never matches); a stored address changes only at erasure, and signing in to it needs its mailbox or the directory, where nobody changes their own;
- it is an active member of the staff organization, which only that organization's admins grant.
Founding the staff organization is reserved to platform staff (the API's CreateOrg), so a deployment's first staff are seeded by its operator. The staff organization admits nobody whose address is outside its domain, at every door: the activation chokepoint (invitations, approvals), the pending doors (the fold-in, provisioning) and the invitation itself. The flag is recomputed by SyncStaffIn inside the transaction of every membership change, at sign-in, and over every candidate once when the server starts, and each change is audited as user.staff_sync naming the rule. Nothing else writes platform_staff: neither a directory group nor a domain alone makes anyone staff.
Index ¶
- Constants
- Variables
- func ArchiveKey(digest string) string
- func IPClusterHash(secret []byte, ip string, now time.Time) string
- type ActivateMemberRequest
- type Admission
- type Admitter
- type Agent
- type ArchiveHandOff
- type ArchiveInfo
- type BlobStore
- type CopyForkArgs
- type CreateAgentInput
- type ErrAdmissionRefused
- type ErrKnowledgeShipping
- type ErrValidation
- type EventSink
- type FoldInRequest
- type FoldInResult
- type ForkCommit
- type ForkHandOff
- type ForkInput
- type ForkRepos
- type GitArchiver
- type KnowledgeShipping
- type LocalFS
- type MembershipVia
- type OrgEventSink
- type OrgGateError
- type Pipeline
- type PolicyGate
- type PolicySubmission
- type Ref
- type Refusal
- type Resolved
- type S3API
- type S3Options
- type S3Store
- type Seats
- type Service
- func (s *Service) ActivateMember(ctx context.Context, req ActivateMemberRequest) (bool, error)
- func (s *Service) CheckPrivateAgentCap(ctx context.Context, a Agent) error
- func (s *Service) CheckPrivateAgentCapFor(ctx context.Context, orgID uuid.UUID, n int64) error
- func (s *Service) CheckPrivateAgentCapInTx(ctx context.Context, q *storegen.Queries, a Agent) error
- func (s *Service) CheckSeatAllowanceIn(ctx context.Context, q *storegen.Queries, orgID uuid.UUID) error
- func (s *Service) CheckStaffOrgAddress(ctx context.Context, q *storegen.Queries, orgID uuid.UUID, email string) error
- func (s *Service) CheckStaffOrgDoorIn(ctx context.Context, q *storegen.Queries, orgID, userID uuid.UUID) error
- func (s *Service) CopyFork(ctx context.Context, args CopyForkArgs, p *auth.Principal, pipeline Pipeline) error
- func (s *Service) CreateAgent(ctx context.Context, p *auth.Principal, in CreateAgentInput, ...) (Agent, error)
- func (s *Service) EffectiveRole(ctx context.Context, p *auth.Principal, a Agent) (auth.AgentRole, error)
- func (s *Service) EmitAgentEvent(ctx context.Context, agentID uuid.UUID, event string, payload map[string]any)
- func (s *Service) EmitTransition(ctx context.Context, res TransitionResult)
- func (s *Service) Entitlements() entitlements.Resolver
- func (s *Service) FoldIn(ctx context.Context, req FoldInRequest) (FoldInResult, error)
- func (s *Service) FoldInSweep(ctx context.Context, orgID uuid.UUID, domain string) (int, error)
- func (s *Service) Fork(ctx context.Context, p *auth.Principal, src Agent, in ForkInput, ...) (Agent, error)
- func (s *Service) HasAdmitter() bool
- func (s *Service) OrgGate(ctx context.Context, orgID uuid.UUID, act auth.Action) error
- func (s *Service) OrgGateFor(ctx context.Context, a Agent, act auth.Action) error
- func (s *Service) OrgGateIn(ctx context.Context, q *storegen.Queries, orgID uuid.UUID, act auth.Action) error
- func (s *Service) ReconcileStuckForks(ctx context.Context) (int, error)
- func (s *Service) ReconcileStuckSubmissions(ctx context.Context) (int, error)
- func (s *Service) Resolve(ctx context.Context, namespace, name string) (Agent, error)
- func (s *Service) ResolveIncludingDeleted(ctx context.Context, namespace, name string) (Agent, error)
- func (s *Service) ResolveVersion(ctx context.Context, a Agent, rangeStr, channel string) (Resolved, error)
- func (s *Service) Restore(ctx context.Context, a Agent, actorEvent audit.Event) error
- func (s *Service) ResyncStaff(ctx context.Context) (int, error)
- func (s *Service) ResyncStaffIn(ctx context.Context, q *storegen.Queries, reason string, actor audit.Event) (int, error)
- func (s *Service) Retire(ctx context.Context, a Agent, actorEvent audit.Event) error
- func (s *Service) Seats(ctx context.Context, orgID uuid.UUID) (Seats, error)
- func (s *Service) SetAdmitter(a Admitter)
- func (s *Service) SetArchiveHandOff(h ArchiveHandOff)
- func (s *Service) SetBlobStore(b BlobStore)
- func (s *Service) SetEntitlements(r entitlements.Resolver)
- func (s *Service) SetEventSink(sink EventSink)
- func (s *Service) SetForkHandOff(h ForkHandOff)
- func (s *Service) SetForkRepos(r ForkRepos)
- func (s *Service) SetGitArchiver(g GitArchiver)
- func (s *Service) SetIPClusterSecret(secret []byte)
- func (s *Service) SetLogger(l *slog.Logger)
- func (s *Service) SetOrgEventSink(sink OrgEventSink)
- func (s *Service) SetPipeline(p Pipeline)
- func (s *Service) SetPolicyGate(g PolicyGate)
- func (s *Service) SetPublicPublish2FA(on bool)
- func (s *Service) SetStaffChanged(fn func())
- func (s *Service) SetStaffOrg(handle, domain string)
- func (s *Service) StaffConfigured() bool
- func (s *Service) StaffOrgMembersNotStaff(ctx context.Context) ([]string, error)
- func (s *Service) StoreTagArchive(ctx context.Context, args StoreTagArchiveArgs, pipeline Pipeline) error
- func (s *Service) SubmitTag(ctx context.Context, p *auth.Principal, a Agent, tag string, ...) (Version, error)
- func (s *Service) SubmitVersion(ctx context.Context, p *auth.Principal, a Agent, in SubmitInput, ...) (Version, error)
- func (s *Service) SyncStaff(ctx context.Context, userID uuid.UUID, reason string, actor audit.Event) error
- func (s *Service) SyncStaffIn(ctx context.Context, q *storegen.Queries, userID uuid.UUID, reason string, ...) error
- func (s *Service) Tombstone(ctx context.Context, a Agent, actorEvent audit.Event) error
- func (s *Service) Transition(ctx context.Context, versionID uuid.UUID, to Status, reason string, ...) error
- func (s *Service) TransitionFrom(ctx context.Context, versionID uuid.UUID, from, to Status, reason string, ...) error
- func (s *Service) TransitionInTx(ctx context.Context, q *storegen.Queries, versionID uuid.UUID, to Status, ...) (TransitionResult, error)
- func (s *Service) TransitionWith(ctx context.Context, versionID uuid.UUID, to Status, reason string, ...) error
- type ShippedKnowledgeRecord
- type ShippedPack
- type ShippedPackOrigin
- type ShippingVersion
- type Status
- type StoreTagArchiveArgs
- type SubmitInput
- type Ticket
- type TransitionCause
- type TransitionResult
- type UnscannedStandingError
- type Version
Constants ¶
const ( ForkCopying = "copying" ForkReady = "ready" ForkFailed = "failed" )
ForkState is a fork's copy, as fork_state records it.
const ( // ShippedViaClient: the upload carried the publisher's confirmation. ShippedViaClient = "client" // ShippedViaTagPush: the release was built from a pushed or submitted // tag, which carries no confirmation. ShippedViaTagPush = "tag-push" // ShippedViaFork: the release is a fork's first version, copied from // the release it forks. ShippedViaFork = "fork" )
How a version's shipped packs came to be released.
const ( ShippedOriginOwn = "own" ShippedOriginOrg = "org" )
The kinds of store a shipped pack can be laid down from.
const ( SlugKnowledgeShippingUnacknowledged = "knowledge-shipping-unacknowledged" SlugKnowledgeShippingInvalid = "knowledge-shipping-invalid" )
Problem slugs of a refused shipping confirmation.
const ( StatePending = "pending" StateActive = "active" )
The membership states (memberships.state). A pending membership holds no seat and confers nothing; an active one is a member.
const ( OrgStateActive = "active" OrgStateSuspended = "suspended" OrgStateDecommissioning = "decommissioning" OrgStateDecommissioned = "decommissioned" )
The organization states (orgs.state, migration 00032).
const ( StaffSyncSignIn = "sign-in" StaffSyncMembership = "membership" StaffSyncErasure = "erasure" StaffSyncState = "account-state" StaffSyncStartup = "startup" )
The reasons a staff sync ran, for the audit row.
const ( ScanStatusPipeline = "pipeline" ScanStatusSkipped = "skipped" )
The scan statuses a version carries (agent_versions.scan_status): admitted through the pipeline, or skipped — no run, no findings, no attestation, the verdict "unscanned".
const AdmissionKindVersionSubmit = "version.submit"
AdmissionKindVersionSubmit is the one admission kind today.
const JobCopyFork = "registry.copy_fork"
JobCopyFork is the worker's job that copies a fork's repository and submits its first version.
const JobStoreTagArchive = "registry.store_tag_archive"
JobStoreTagArchive is the worker's job that stores a git-tag submission's archive and enters the version into the machine.
const SourceGitTag = "git-tag"
SourceGitTag is the version source of a tag submission (a push's auto-publish, or POST /versions {tag}).
const StaffRule = "staff-org"
StaffRule is the rule name the audit row records for the staff organization's grant or revocation.
const StuckForkCap = StuckSubmissionCap
StuckForkCap is how long a fork may stay `copying` before the watchdog marks it failed: the same allowance a handed-off tag archive gets, since the copy waits in the sandbox queue behind scans too.
const StuckSubmissionCap = 2 * time.Hour
StuckSubmissionCap is how long a handed-off submission may stay `submitted` before the watchdog rejects it. Longer than a scan's 30 minutes, because the store job waits in the sandbox queue behind scans and a rejection burns the version string, where a stuck scan only goes to review; the job's own retries are over well before it.
Variables ¶
var ( // ErrForkSourceNotForkable reports an origin that is not public, or // that the platform has quarantined or blocked. ErrForkSourceNotForkable = errors.New("registry: only a public QuickAgent in good standing can be forked") // ErrNothingToFork reports an origin with no published version. ErrNothingToFork = errors.New("registry: the QuickAgent has no published version to fork") // ErrNameTaken reports a fork whose name the target namespace already // has; the API answers 409 name-taken, and the person picks another. ErrNameTaken = errors.New("registry: the namespace already has a QuickAgent of that name") // ErrNameHeld reports a name a deleted agent holds for good. ErrNameHeld = errors.New("registry: the name is held by a deleted QuickAgent") // ErrForkTree reports a release whose files cannot be a fork's tree // (a .git path, a file that is not a regular one): ForkRepos wraps it, // and the fork fails rather than retrying. ErrForkTree = errors.New("registry: the release's files cannot be a fork's tree") )
var AgentNameRe = regexp.MustCompile(`^[a-z0-9](?:[a-z0-9-]{0,63}[a-z0-9])?$`)
AgentNameRe is the agent-name grammar.
var BuildArchive = archive.BuildArchive
BuildArchive writes the deterministic tar.zst (see archive.BuildArchive).
ErrAdmissionUnavailable reports that the Admitter could not answer. The submission is refused and nothing was stored.
var ErrAlreadyAMember = errors.New("registry: this person is already a member of another organization")
ErrAlreadyAMember reports that the person is an active member of another organization (one organization per person).
var ErrArchiveMismatch = errors.New("registry: rebuilt archive does not match the recorded digest")
ErrArchiveMismatch reports that the archive rebuilt from the recorded commit does not have the recorded digest. Retrying cannot fix it; the watchdog rejects the version.
var ErrBadTransition = errors.New("registry: illegal state transition")
ErrBadTransition reports a state-machine violation.
var ErrBlocked = errors.New("registry: agent blocked by trust & safety")
ErrBlocked reports that trust & safety has disabled the agent.
var ErrDenied = errors.New("registry: denied")
ErrDenied wraps authorization failures with domain context.
var ErrNoMatch = errors.New("registry: no version matches")
ErrNoMatch means no published version satisfies the request.
var ErrNotFound = errors.New("registry: not found")
ErrNotFound is returned when an agent or namespace does not exist.
var ErrNotRetired = errors.New("registry: this QuickAgent is not retired")
ErrNotRetired reports a Restore of an agent that is not retired.
var ErrPipelineSkipOnRestore = errors.New("registry: this QuickAgent is off the pipeline and cannot be made public")
ErrPipelineSkipOnRestore reports a Restore to public of an agent whose pipeline: skip was set while it was retired: a public agent is always scanned. The API answers it as PATCH answers the same state, 409 agent-unscanned.
var ErrPrivateAgentCap = errors.New("registry: this namespace holds as many private agents as its tier allows")
ErrPrivateAgentCap reports that a namespace holds as many private agents as its subscription tier allows. The API answers 422 private-agent-cap. A cap never deletes: over it, nothing can be added and nothing already private is touched.
var ErrRetired = errors.New("registry: this QuickAgent is retired")
ErrRetired reports a write a retired agent does not take: a submission, or making it public other than by Restore. The API answers 409 agent-retired.
var ErrScanNotScheduled = errors.New("registry: version recorded but its scan could not be scheduled")
ErrScanNotScheduled reports that a version was recorded but its scan could not be started. The version stays in `scanning`; the pipeline watchdog routes it to review once it passes the 30-minute cap.
var ErrSeatAllowance = errors.New("registry: this organization holds as many seats as its subscription allows")
ErrSeatAllowance reports that the organization holds as many seats as its subscription allows. Nothing is removed when it is returned: over the allowance nothing can be added and nothing is lost.
var ErrSeatsNotOffered = errors.New("registry: this organization's subscription does not include seats")
ErrSeatsNotOffered reports that the organization may hold no seats at all — a subscription that is not paying. Distinct from the allowance being reached, so the caller can say which it is.
var ErrStaffOrgDomain = errors.New("registry: the staff organization admits only addresses at its domain")
ErrStaffOrgDomain refuses an address outside the staff domain at one of the staff organization's doors.
var ErrTwoFactorRequired = errors.New("registry: two-factor authentication required")
ErrTwoFactorRequired reports the public-publish 2FA gate. It is distinct from ErrDenied so the API can answer 403 with an actionable message rather than folding it into a validation error.
var ErrUnscannedOnPublic = errors.New("registry: an unscanned version is published only on a private organization agent")
ErrUnscannedOnPublic reports a version admitted unscanned about to be published on an agent that is not a private one of an organization's — the state that is ruled out at every layer.
var ErrVersionMoved = errors.New("registry: version moved before the transition")
ErrVersionMoved reports that a transition's precondition failed: the version was no longer in the state the caller decided from (a decision reached late, after the watchdog routed the version to review). The caller's decision is stale, not wrong; it stops.
var ErrVersionsInFlight = errors.New("registry: a version of this QuickAgent is still in flight")
ErrVersionsInFlight reports a delete of an agent a version of which the pipeline or a reviewer has yet to decide: the verdict would otherwise land on a tombstone. The API answers 409.
var ParseRef = manifest.ParseRef
ParseRef parses "ns/name[@range]" (see manifest.ParseRef).
var WalkWorkspace = archive.WalkWorkspace
WalkWorkspace lists workspace files for validation and archiving.
Functions ¶
func ArchiveKey ¶
ArchiveKey computes the content-addressed storage key for a digest ("sha256:<hex>" → "releases/<hex[0:2]>/<hex>.tar.zst").
func IPClusterHash ¶
IPClusterHash is the value agent_versions.submitter_ip_hash carries (the S8 "IP cluster" signal). It is HMAC-SHA256 over the address with a key derived from the deployment secret and the calendar month, so the same address hashes alike within a month — which is the window the ClawHavoc pattern (1,184 skills from 12 accounts in days) needs — and differently across months and deployments. The address itself is never stored, and a leaked hash set cannot be reversed without the secret. The "YYYY-MM:" prefix makes the rotation visible and keeps comparisons within one key.
Loopback and unspecified addresses record nothing: a submission from the server's own host is the operator (or a test suite), and a "cluster" of everything published from localhost is noise, not a signal.
Types ¶
type ActivateMemberRequest ¶
type ActivateMemberRequest struct {
OrgID uuid.UUID
UserID uuid.UUID
// Role is what the person will hold.
Role auth.OrgRole
// Via names the door, for the audit row and the event.
Via MembershipVia
// Actor carries the acting principal (the invitee for an accept, the
// admin for an approval), filled in by the API layer the way every
// other audited act is.
Actor audit.Event
// Spend runs inside the same transaction, before the seat is counted:
// the invitation door spends its token here. Putting it inside means a
// token cannot be consumed by an activation that is then refused, and
// that the invitation has left the open count by the time the seat is
// counted — so the seat it reserved is the one being taken, not a
// second one. nil for a door that reserves nothing.
Spend func(ctx context.Context, q *storegen.Queries) error
}
ActivateMemberRequest is what one activation needs.
type Admission ¶
type Admission struct {
// Kind names the act; today only "version.submit".
Kind string
// Subject is the namespace the release is submitted under; Submitter
// the person submitting it, who is not always the namespace.
Subject entitlements.Subject
Submitter uuid.UUID
AgentID uuid.UUID
// Visibility is the agent's, Source the submission door's
// ("git-tag" | "cli-upload").
Visibility string
Source string
}
Admission describes the submission being admitted.
type Admitter ¶
type Admitter interface {
// Admit returns a ticket the core carries on the version.submitted
// event, or a Refusal the API turns into a problem response. An error
// is "unknown": the core fails closed with ErrAdmissionUnavailable and
// stores nothing.
Admit(ctx context.Context, req Admission) (Ticket, *Refusal, error)
// Void cancels a ticket the core could not honour — the version row was
// never created. It must be idempotent.
Void(ctx context.Context, t Ticket) error
}
Admitter is asked once per submission.
type Agent ¶
type Agent = storegen.GetAgentByPathRow
Agent is the resolved agent row with namespace context.
type ArchiveHandOff ¶
type ArchiveHandOff interface {
StoreTagArchive(ctx context.Context, args StoreTagArchiveArgs) error
}
ArchiveHandOff enqueues JobStoreTagArchive. The git role sets it (api.Server.DeferTagArchives); a role that holds the store writes the archive itself.
type BlobStore ¶
type BlobStore interface {
Put(ctx context.Context, key string, r io.Reader) error
Get(ctx context.Context, key string) (io.ReadCloser, error)
Exists(ctx context.Context, key string) (bool, error)
// Delete removes an object; a key that is not there is not an error,
// so a sweep that runs twice is a sweep that ran.
Delete(ctx context.Context, key string) error
}
BlobStore stores release archives content-addressed by digest. Keys look like "releases/ab/sha256:abcd....tar.zst"; the implementation maps them to its backend. Objects are write-once: Put to an existing key verifies nothing and returns nil (same content by construction).
type CopyForkArgs ¶
CopyForkArgs are the job's arguments: the fork, and the account that asked for it, whose standing the worker reloads before submitting.
type CreateAgentInput ¶
type CreateAgentInput struct {
Namespace string
Name string
Visibility string
Summary string
// Modes are the run modes the agent supports; empty means
// [autonomous], the mode every v1 package maps to.
Modes []string
}
CreateAgentInput is the validated input for CreateAgent.
type ErrAdmissionRefused ¶
type ErrAdmissionRefused struct {
Refusal Refusal
}
ErrAdmissionRefused wraps a Refusal as an error the API maps onto a problem of the refusal's own status.
func (*ErrAdmissionRefused) Error ¶
func (e *ErrAdmissionRefused) Error() string
type ErrKnowledgeShipping ¶
ErrKnowledgeShipping reports a release whose shipped packs are not confirmed, or whose confirmation is wrong. Slug is the problem the API answers; Packs names the packs it is about.
func (*ErrKnowledgeShipping) Error ¶
func (e *ErrKnowledgeShipping) Error() string
type ErrValidation ¶
type ErrValidation struct{ Issues []error }
ErrValidation carries manifest/validation failures to the API layer.
func (*ErrValidation) Error ¶
func (e *ErrValidation) Error() string
type EventSink ¶
EventSink receives a committed state transition so the caller can fan it out to webhooks. It runs after the transition transaction commits, so a webhook failure never affects the state change. agentID lets the sink resolve the owning org; payload carries version/from/to.
type FoldInRequest ¶
type FoldInRequest struct {
UserID uuid.UUID
// Email and EmailVerified are the identity token's fresh assertion,
// not the stored address: the step runs on what the directory
// said at this sign-in.
Email string
EmailVerified bool
// Actor is the audit event to fill in — the person themselves.
Actor audit.Event
}
FoldInRequest is one person's fold-in, at their sign-in.
type FoldInResult ¶
type FoldInResult struct {
// Fired is whether this call wrote a pending membership.
Fired bool
// OrgHandle is the organization at the domain, when it fired.
OrgHandle string
}
FoldInResult says what the fold-in did.
type ForkCommit ¶
type ForkCommit struct {
// BaseCommit is the commit whose tree the fork's starts from. Empty
// means Dir's files are the tree instead (an origin version with no
// commit behind it: one uploaded rather than tagged).
BaseCommit string
Dir string
// ManifestPath's content is replaced with Manifest.
ManifestPath string
Manifest []byte
// Parent is the commit the fork's continues; empty for a root commit.
Parent string
Message string
// Refs are moved to the commit, whatever they held (the fork's default
// branch, which the copy left at the origin's release, and its release
// tag).
Refs []string
// Author is the account that forked, as a commit's identity.
AuthorName string
AuthorEmail string
When time.Time
}
ForkCommit is the fork's one commit: a tree, the manifest replaced in it, the parent it continues from, and the refs moved to it.
type ForkHandOff ¶
type ForkHandOff interface {
CopyFork(ctx context.Context, args CopyForkArgs) error
}
ForkHandOff enqueues JobCopyFork (api.Server's queue).
type ForkRepos ¶
type ForkRepos interface {
// CopyHistory creates dst as a bare repository on defaultBranch and
// copies into it commit and its history from src, through a tag of
// src that points at it, with defaultBranch at commit; nothing else of
// src comes over (copied, never shared through alternates, so nothing
// done to src later reaches dst). An empty commit, a commit no tag of
// src points at, or a src that was never pushed to leaves dst empty.
CopyHistory(ctx context.Context, src, dst uuid.UUID, defaultBranch, commit string) error
// RemoveRepository deletes a repository a failed copy left behind.
RemoveRepository(repoID uuid.UUID) error
// HasCommit reports whether commit is a commit in repo.
HasCommit(ctx context.Context, repoID uuid.UUID, commit string) (bool, error)
// ReadFileAt reads path's blob at commit.
ReadFileAt(ctx context.Context, repoID uuid.UUID, commit, path string) ([]byte, error)
// CommitFork writes one commit and points its refs at it.
CommitFork(ctx context.Context, repoID uuid.UUID, c ForkCommit) (string, error)
}
ForkRepos is what CopyFork needs of the repositories: a role that can read and write them (the worker, `all`) wires it.
type GitArchiver ¶
type GitArchiver interface {
MaterializeTag(ctx context.Context, repoID uuid.UUID, tag, dst string) (commitSHA string, err error)
MaterializeCommit(ctx context.Context, repoID uuid.UUID, commit, dst string) error
}
GitArchiver materializes the tree of a tag into a workspace directory and returns the peeled commit id (git archive, never a working-tree checkout; export-ignore disabled — the manifest allowlist is the only filter). MaterializeCommit does the same for a commit already resolved: the worker rebuilds a git-tag submission's archive from the commit the git role recorded.
type KnowledgeShipping ¶
type KnowledgeShipping struct {
Packs []ShippedPack
}
KnowledgeShipping is a publisher's confirmation that the packs a release ships become readable with it: one entry per shipped pack.
type LocalFS ¶
type LocalFS struct {
Root string
}
LocalFS is the self-host/dev BlobStore (no hard cloud dependency); the S3 implementation is S3Store.
func NewLocalFS ¶
NewLocalFS creates the root directory if needed.
type MembershipVia ¶
type MembershipVia string
MembershipVia names the door a membership came through, for the audit row and the event payload.
const ( ViaInvitation MembershipVia = "invitation" // the invitee accepted ViaApproval MembershipVia = "approval" // an admin approved a pending member ViaRoleChange MembershipVia = "role" // an admin changed an existing member's role // The two provisioning doors, which write pending and nothing else: // the organization's IdP, and its domain. ViaSCIM MembershipVia = "scim" ViaDomain MembershipVia = "domain" )
The doors a membership comes through.
func DoorOf ¶
func DoorOf(viaSCIM, viaDomain bool) MembershipVia
DoorOf names the provisioning door a membership row records, from its two flags: the IdP's door first, since provisioning is the organization's own act and the domain is the registry's inference. An admin-granted membership has neither and is "".
type OrgEventSink ¶
OrgEventSink receives an organization-scoped event after it has committed (the API layer's webhook fan-out plus extension hooks). Set by the api layer; nil means no fan-out.
type OrgGateError ¶
OrgGateError is why the organization's state refused an act. State is what the organization is in; DecommissionAt is set during a hold, so a refusal can say when the erasure runs.
func (*OrgGateError) Absent ¶
func (e *OrgGateError) Absent() bool
Absent reports whether the organization should answer as if it did not exist: suspended by platform staff, or already erased. A decommissioning organization is not absent — its members still read it.
func (*OrgGateError) Error ¶
func (e *OrgGateError) Error() string
type Pipeline ¶
Pipeline is what happens after a version enters the machine: the scan orchestrator. Implementations run AFTER the submission transaction commits.
The error return is load-bearing: a hand-off that fails (queue down, scan crashed) leaves the version parked in `scanning`, and a seam that cannot report that made the failure invisible to the submitter and to the logs.
type PolicyGate ¶
type PolicyGate interface {
// CheckSubmission returns the blocking issues, or nil to allow.
CheckSubmission(ctx context.Context, in PolicySubmission) []error
}
PolicyGate evaluates the policy knobs that reject a submission before it ever enters the state machine: blockedCapabilities, allowedLicenses and requireEvals. It is a seam because resolving the effective policy needs the scan package, which already depends on this one.
type PolicySubmission ¶
type PolicySubmission struct {
// NamespaceKind / NamespaceID select the org overlay ("org" only).
NamespaceKind string
NamespaceID uuid.UUID
// Public marks a public agent (allowedLicenses applies to those).
Public bool
// License is the manifest's SPDX id.
License string
// ManifestJSON is the canonical manifest (capability tokens).
ManifestJSON []byte
// Files is the workspace inventory (requireEvals looks for evals/).
Files []manifest.FileInfo
}
PolicySubmission is what the policy gate judges.
type Ref ¶
Ref and ParseRef live in pkg/manifest so the CLI (a separate module) parses references identically; aliases keep internal call sites.
type Refusal ¶
Refusal is an admission the Admitter declined: the status and problem slug the API answers with, a title and a detail in the crisp register, and Fields the response carries at top level so a client can render its own sentence (a balance and a reset date, say).
type S3API ¶
type S3API interface {
PutObject(ctx context.Context, in *s3.PutObjectInput, opts ...func(*s3.Options)) (*s3.PutObjectOutput, error)
GetObject(ctx context.Context, in *s3.GetObjectInput, opts ...func(*s3.Options)) (*s3.GetObjectOutput, error)
HeadObject(ctx context.Context, in *s3.HeadObjectInput, opts ...func(*s3.Options)) (*s3.HeadObjectOutput, error)
DeleteObject(ctx context.Context, in *s3.DeleteObjectInput, opts ...func(*s3.Options)) (*s3.DeleteObjectOutput, error)
}
S3API is the slice of the S3 client S3Store uses. Narrowing it to three calls is what lets the tests run against an in-process fake instead of a network: see blobstore_s3_test.go.
type S3Options ¶
type S3Options struct {
Bucket string
Region string
// Prefix is prepended to every key, letting one bucket host several
// environments. A trailing slash is optional.
Prefix string
// Endpoint overrides the AWS endpoint (MinIO, or an S3-compatible store).
Endpoint string
// UsePathStyle addresses buckets as {endpoint}/{bucket}/{key}. MinIO
// needs it; AWS does not.
UsePathStyle bool
}
S3Options configures the S3-backed BlobStore.
type S3Store ¶
type S3Store struct {
// contains filtered or unexported fields
}
S3Store is the hosted BlobStore. Keys are content-addressed by the caller (ArchiveKey), so an object's name already commits to its bytes.
func NewS3 ¶
NewS3 builds an S3Store using the ambient AWS credential chain (task role on ECS, instance profile, environment, or shared config).
func NewS3WithAPI ¶
NewS3WithAPI builds an S3Store over an existing client (tests, and callers that already hold a configured s3.Client).
func (*S3Store) Delete ¶
Delete implements BlobStore. S3 answers a delete of a missing key with success, which is the contract.
func (*S3Store) Put ¶
Put implements BlobStore with write-once semantics.
If-None-Match: * makes S3 itself refuse to overwrite an existing object, so two workers racing on the same digest cannot interleave a partial rewrite of a blob a third reader is already streaming. The 412 that a loser gets back is success from this layer's point of view: the key is content-addressed, so whoever won stored the same bytes.
type Seats ¶
type Seats struct {
Used int64 `json:"used"`
Invited int64 `json:"invited"`
Pending int64 `json:"pending"`
Max int64 `json:"max"`
}
Seats is what an organization holds against its allowance: Used is its active memberships, Invited its open invitations — an invitation reserves a seat when it is sent, so the wall is met by the admin who invites, not by the person who accepts — and Pending the people waiting for an admin, who hold none. Max is the allowance; 0 means unbounded, which is what a registry with no extension answers.
type Service ¶
type Service struct {
// contains filtered or unexported fields
}
Service is the agent-domain service shared by the API and git layers. Bare repositories are NOT created here: the git layer initializes them lazily on first access (only the git role mounts repo storage).
func NewService ¶
NewService assembles the registry service. blobs may be nil for callers that never submit versions (the git role's read paths).
func (*Service) ActivateMember ¶
ActivateMember is the one operation that makes a membership active.
It reports whether this call was the activation: a membership that was already active is left alone and reports false, so a repeated accept or a double-clicked approval does not fire a second `member.added`.
func (*Service) CheckPrivateAgentCap ¶
CheckPrivateAgentCap is checkPrivateAgentCap for the handler that flips an existing agent to private.
func (*Service) CheckPrivateAgentCapFor ¶
CheckPrivateAgentCapFor refuses adding n more private agents to an organization's namespace at once — an erased account's catalogue moving in (the transfer door respects the cap). n of zero always passes.
func (*Service) CheckPrivateAgentCapInTx ¶
CheckPrivateAgentCapInTx is the private-agent cap for the handler that flips an agent's visibility, inside that handler's transaction: it takes the namespace's row lock first, so the count and the update commit together.
func (*Service) CheckSeatAllowanceIn ¶
func (s *Service) CheckSeatAllowanceIn(ctx context.Context, q *storegen.Queries, orgID uuid.UUID) error
CheckSeatAllowanceIn reports whether the organization may take one more seat, for a door that reserves one before any membership exists — an admin sending an invitation. It runs inside the caller's transaction, so the count and the insert that consumes it commit together; the caller holds the organization's row lock first, as ActivateMember does.
func (*Service) CheckStaffOrgAddress ¶
func (s *Service) CheckStaffOrgAddress(ctx context.Context, q *storegen.Queries, orgID uuid.UUID, email string) error
CheckStaffOrgAddress is the door check for an address that has no account behind it yet: an invitation to the staff organization is refused unless the address is at its domain. The address is checked as written; the accept checks the account's verified one.
func (*Service) CheckStaffOrgDoorIn ¶
func (s *Service) CheckStaffOrgDoorIn(ctx context.Context, q *storegen.Queries, orgID, userID uuid.UUID) error
CheckStaffOrgDoorIn refuses to admit userID to orgID when orgID is the staff organization and the account's verified address is not at its domain. Every door into an organization calls it inside its own transaction; for any other organization it answers nil.
func (*Service) CopyFork ¶
func (s *Service) CopyFork(ctx context.Context, args CopyForkArgs, p *auth.Principal, pipeline Pipeline) error
CopyFork is JobCopyFork's handler. p is the account that forked, as it stands now (nil when it no longer does), and pipeline the queue the first version goes to. It is idempotent: a fork that is no longer `copying` is done, and a copy a crash left half-made is started again from nothing. What the job cannot fix by trying again (the account gone, the forked version withdrawn, a submission the gates or admission refuse) marks the fork failed with the reason and returns nil; anything else is returned for the queue to retry, and the watchdog marks a fork that never finishes.
func (*Service) CreateAgent ¶
func (s *Service) CreateAgent(ctx context.Context, p *auth.Principal, in CreateAgentInput, actorEvent audit.Event) (Agent, error)
CreateAgent creates the agent row and its bare repository. The caller is authorized here: personal namespace = self; org namespace = any active member (a seat buys a share of the organization's namespace, and an admin is a member with more). A pending member is not one: their membership never reaches Principal.OrgRoles.
func (*Service) EffectiveRole ¶
func (s *Service) EffectiveRole(ctx context.Context, p *auth.Principal, a Agent) (auth.AgentRole, error)
EffectiveRole computes the caller's effective agent role: max(namespace-derived, explicit user grant, explicit team grants).
func (*Service) EmitAgentEvent ¶
func (s *Service) EmitAgentEvent(ctx context.Context, agentID uuid.UUID, event string, payload map[string]any)
EmitAgentEvent publishes a non-transition agent event — today the advisory the rescan path drafts.
func (*Service) EmitTransition ¶
func (s *Service) EmitTransition(ctx context.Context, res TransitionResult)
EmitTransition fans a committed transition out to the event sink. Best-effort: the sink logs its own errors and never affects the transition.
func (*Service) Entitlements ¶
func (s *Service) Entitlements() entitlements.Resolver
Entitlements returns the wired resolver, or the shipped defaults when none was set. Defaulting to the OSS resolver rather than to nil means a half-wired service still enforces quotas — an unwired seam must not read as "no limits".
func (*Service) FoldIn ¶
func (s *Service) FoldIn(ctx context.Context, req FoldInRequest) (FoldInResult, error)
FoldIn runs the sign-in step for one person. It is idempotent on (organization, person): a second sign-in finds the pending row and writes nothing. Every reason not to fire returns a zero result and no error; an error is a failure to look, which the caller logs — a sign-in never fails because the fold-in could not run.
func (*Service) FoldInSweep ¶
FoldInSweep folds in every account already known at a domain the organization has just gained — at its creation, or a DNS verification — so its admins see them at once rather than as each signs in. Reports how many it folded in. The listing applies the same rules as FoldIn; the write is the same write.
func (*Service) Fork ¶
func (s *Service) Fork(ctx context.Context, p *auth.Principal, src Agent, in ForkInput, actorEvent audit.Event) (Agent, error)
Fork records a fork of src for p in in.Namespace and hands its copy to a worker. src is resolved and readable by p (the handler's agentForAction). The fork is returned `copying`.
func (*Service) HasAdmitter ¶
HasAdmitter reports whether an admission seam is wired: whether this deployment runs the extension that sells things.
func (*Service) OrgGate ¶
OrgGate reports whether the organization's state permits act on it or on something under it. An active organization permits everything; a suspended or decommissioned one nothing; one in its decommission hold only the read-only actions (auth.ReadOnly). An organization that does not exist is ErrNotFound. An unreadable state is an error, never permission.
func (*Service) OrgGateFor ¶
OrgGateFor is OrgGate for an agent's namespace: a personal namespace has no state and always passes.
func (*Service) OrgGateIn ¶
func (s *Service) OrgGateIn(ctx context.Context, q *storegen.Queries, orgID uuid.UUID, act auth.Action) error
OrgGateIn is OrgGate inside a caller's transaction, so a state read under the organization's row lock is the one the change commits against.
func (*Service) ReconcileStuckForks ¶
ReconcileStuckForks is the watchdog for forks whose copy never finished: past StuckForkCap, each is marked failed so its readers are told rather than left waiting. Returns how many it marked.
func (*Service) ReconcileStuckSubmissions ¶
ReconcileStuckSubmissions is the watchdog for handed-off git-tag submissions whose archive was never stored (a store job out of retries, a digest mismatch, a worker without the git volume): past the cap, each is rejected through scanning with a pipeline-error cause, so it is never served and an extension that charged for it refunds. It is not routed to review, since a reviewer's approval would publish a version with no archive behind it. Returns how many it rejected.
func (*Service) Resolve ¶
Resolve loads an agent by namespace/name path.
A deleted agent's tombstone is not found: every route by name, the git transport, the extensions' read seam and the tag-push submission all resolve through here, so a tombstone answers the 404 a missing name gets on all of them at once.
func (*Service) ResolveIncludingDeleted ¶
func (s *Service) ResolveIncludingDeleted(ctx context.Context, namespace, name string) (Agent, error)
ResolveIncludingDeleted is Resolve with a deleted agent's tombstone found, not hidden: the trust & safety actions' door to an agent its publisher deleted, and the create's way to tell a held name from a taken one once the namespace has admitted the caller. No read a publisher or a consumer makes goes through it, save one: the advisories of an agent the caller holds a release of reach its owning organization's gate through it, after the holder is proved.
func (*Service) ResolveVersion ¶
func (s *Service) ResolveVersion(ctx context.Context, a Agent, rangeStr, channel string) (Resolved, error)
ResolveVersion picks the version for a ref within an agent.
func (*Service) Restore ¶
Restore returns a retired agent to the visibility it had. Back to public it meets the rules any agent becoming public meets: not off the pipeline, no unscanned version standing. Back to private it takes a place under the private-agent cap again, so the cap is checked under the namespace's lock.
func (*Service) ResyncStaff ¶
ResyncStaff is ResyncStaffIn in a transaction of its own, run once when the server starts, so a configuration change takes effect then rather than at each person's next sign-in.
func (*Service) ResyncStaffIn ¶
func (s *Service) ResyncStaffIn(ctx context.Context, q *storegen.Queries, reason string, actor audit.Event) (int, error)
ResyncStaffIn recomputes every account the rule could change — everyone flagged today and every active member of the staff organization — inside the caller's transaction, under an advisory lock so two replicas starting at once do not both audit the same change. It reports how many accounts it looked at.
func (*Service) Retire ¶
Retire makes the agent private and labels it retired, keeping the visibility it had for Restore. It takes no new submission until it is restored. A retired agent holds no place under the private-agent cap, so retiring is never refused by it. Retiring an agent that is already retired changes nothing and is not an error.
func (*Service) Seats ¶
Seats reports the organization's seat usage against its allowance, for the org resource and for a refusal's fields.
func (*Service) SetAdmitter ¶
SetAdmitter wires the admission seam; nil (the core build) admits all.
func (*Service) SetArchiveHandOff ¶
func (s *Service) SetArchiveHandOff(h ArchiveHandOff)
SetArchiveHandOff makes this process hand git-tag archive writes to a worker instead of writing them.
func (*Service) SetBlobStore ¶
SetBlobStore wires archive storage (required for submissions).
func (*Service) SetEntitlements ¶
func (s *Service) SetEntitlements(r entitlements.Resolver)
SetEntitlements wires the quota resolver.
func (*Service) SetEventSink ¶
SetEventSink wires the post-commit transition fan-out (webhooks).
func (*Service) SetForkHandOff ¶
func (s *Service) SetForkHandOff(h ForkHandOff)
SetForkHandOff wires the queue Fork hands the copy to.
func (*Service) SetForkRepos ¶
SetForkRepos wires the repositories CopyFork copies.
func (*Service) SetGitArchiver ¶
func (s *Service) SetGitArchiver(g GitArchiver)
SetGitArchiver wires tag-archive production for git-tag submissions.
func (*Service) SetIPClusterSecret ¶
SetIPClusterSecret installs the deployment secret the hash derives from. Empty disables the signal (no hash is recorded).
func (*Service) SetOrgEventSink ¶
func (s *Service) SetOrgEventSink(sink OrgEventSink)
SetOrgEventSink wires the post-commit organization fan-out.
func (*Service) SetPipeline ¶
SetPipeline wires the post-submission pipeline.
func (*Service) SetPolicyGate ¶
func (s *Service) SetPolicyGate(g PolicyGate)
SetPolicyGate wires submission-time policy enforcement.
func (*Service) SetPublicPublish2FA ¶
SetPublicPublish2FA enables the 2FA gate: publishing to a public namespace requires a second factor the sign-in provider asserted.
func (*Service) SetStaffChanged ¶
func (s *Service) SetStaffChanged(fn func())
SetStaffChanged names a function to call after a sync changed someone's platform_staff. It runs inside the sync's transaction, before it commits, so it must not read the change back: the directory mirror it serves queues a run for a few seconds later.
func (*Service) SetStaffOrg ¶
SetStaffOrg names the staff organization and its domain. Both empty (the default) leaves platform_staff alone: nothing syncs and no door checks.
func (*Service) StaffConfigured ¶
StaffConfigured reports whether a staff organization is named.
func (*Service) StaffOrgMembersNotStaff ¶
StaffOrgMembersNotStaff returns the handles of the staff organization's active members who are not platform staff: members from before the organization's door checked the domain, or whose account is no longer active. They are reported, never removed: removing a member is the organization's admins' act.
func (*Service) StoreTagArchive ¶
func (s *Service) StoreTagArchive(ctx context.Context, args StoreTagArchiveArgs, pipeline Pipeline) error
StoreTagArchive is JobStoreTagArchive's handler: it stores the archive of a handed-off git-tag submission and enters the version into the machine, handing it to pipeline (the worker's queue). It is idempotent: a version that is no longer `submitted` was already taken in, and an archive already in the store is not written again (write-once).
func (*Service) SubmitTag ¶
func (s *Service) SubmitTag(ctx context.Context, p *auth.Principal, a Agent, tag string, actorEvent audit.Event) (Version, error)
SubmitTag prepares a workspace from a repo tag and submits it (git-tag source; used by POST /versions {tag} and the post-receive auto-publish).
func (*Service) SubmitVersion ¶
func (s *Service) SubmitVersion(ctx context.Context, p *auth.Principal, a Agent, in SubmitInput, actorEvent audit.Event) (Version, error)
SubmitVersion validates, archives, records, and hands the version to the pipeline: submitted→scanning.
func (*Service) SyncStaff ¶
func (s *Service) SyncStaff(ctx context.Context, userID uuid.UUID, reason string, actor audit.Event) error
SyncStaff is SyncStaffIn in a transaction of its own, for a door that has no transaction open (the sign-in).
func (*Service) SyncStaffIn ¶
func (s *Service) SyncStaffIn(ctx context.Context, q *storegen.Queries, userID uuid.UUID, reason string, actor audit.Event) error
SyncStaffIn recomputes one account's platform_staff inside the caller's transaction and audits a change. actor is the act's principal (the admin who approved or removed, the person signing in); a zero actor is the system. With no staff organization configured it does nothing.
func (*Service) Tombstone ¶
Tombstone deletes an agent that has version history. Every published or quarantined version is yanked, the agent becomes private and deleted, and every read by name stops finding it. Nothing is removed: the version rows (which the 00004 trigger keeps), the archives, the receipts and the audit trail all stay, and the row holds the name in its namespace for good. The caller has already refused the cases the tombstone does not take: trust & safety records and versions still in flight. The audit event says how many were yanked.
func (*Service) Transition ¶
func (s *Service) Transition(ctx context.Context, versionID uuid.UUID, to Status, reason string, actorEvent audit.Event) error
Transition moves a version to a new status with full state-machine enforcement: row lock, edge validation, audit, and latest-published maintenance.
func (*Service) TransitionFrom ¶
func (s *Service) TransitionFrom(ctx context.Context, versionID uuid.UUID, from, to Status, reason string, actorEvent audit.Event, cause TransitionCause) error
TransitionFrom is TransitionWith with a precondition: the version must still be in `from` under the row lock, or nothing moves and ErrVersionMoved says so. A decision made about a version in one state must not be applied to it in another — a scan's verdict reaching a version the watchdog has since handed to a reviewer.
func (*Service) TransitionInTx ¶
func (s *Service) TransitionInTx(ctx context.Context, q *storegen.Queries, versionID uuid.UUID, to Status, reason string, actorEvent audit.Event) (TransitionResult, error)
TransitionInTx is Transition's body, executed inside a transaction the caller owns. It exists so a decision that must be atomic with its transition — a review verdict, say — commits as one unit instead of leaving the two halves able to disagree. Callers MUST pass the returned result to EmitTransition after their transaction commits.
type ShippedKnowledgeRecord ¶
type ShippedKnowledgeRecord struct {
By *uuid.UUID `json:"by,omitempty"`
At time.Time `json:"at"`
Via string `json:"via"`
Packs []ShippedPack `json:"packs"`
}
ShippedKnowledgeRecord is what a version keeps of that confirmation. By is the account that confirmed; a release with no request to carry a confirmation has none.
func ShippedKnowledgeOf ¶
func ShippedKnowledgeOf(v Version) *ShippedKnowledgeRecord
ShippedKnowledgeOf reads a version's record; nil when it has none.
type ShippedPack ¶
type ShippedPack struct {
Name string `json:"name"`
Origin *ShippedPackOrigin `json:"origin,omitempty"`
}
ShippedPack is one pack of a release's shipped knowledge, as confirmed and as recorded. A pack with no origin is the publisher's own files.
type ShippedPackOrigin ¶
type ShippedPackOrigin struct {
Kind string `json:"kind"`
Org string `json:"org,omitempty"`
PackID uuid.UUID `json:"packId"`
}
ShippedPackOrigin is the store pack a shipped pack was laid down from.
type ShippingVersion ¶
ShippingVersion is a version of an agent that ships packs and has not been yanked or rejected.
func VersionsShippingKnowledge ¶
func VersionsShippingKnowledge(ctx context.Context, q *storegen.Queries, agentID uuid.UUID) ([]ShippingVersion, error)
VersionsShippingKnowledge lists the versions of an agent, other than yanked or rejected ones, that ship knowledge packs.
type Status ¶
type Status string
Status is a publication state. The state machine lives on agent_versions.status; every transition is audited and executed under SELECT … FOR UPDATE (single writer).
const ( StatusSubmitted Status = "submitted" StatusScanning Status = "scanning" StatusNeedsReview Status = "needs_review" // StatusApproved is RESERVED and never written: review collapses // approval and publication into one needs_review → published // transition so the "no path to published skips the gate" property is // one edge, and no version can be stranded between the two. It stays in the enum because narrowing it is a // breaking API change; readers must tolerate it and will not see it. StatusApproved Status = "approved" StatusPublished Status = "published" StatusRejected Status = "rejected" StatusYanked Status = "yanked" StatusQuarantined Status = "quarantined" StatusBlocked Status = "blocked" )
Publication states.
type StoreTagArchiveArgs ¶
StoreTagArchiveArgs are the job's arguments.
type SubmitInput ¶
type SubmitInput struct {
Source string // git-tag | cli-upload
Tag string // git-tag source: the vX.Y.Z tag
CommitSHA string
Workspace string
ClaimedDigest string // cli-upload: client digest to cross-check (may be empty)
// DraftRun is the hosted draft a cli-upload says it was published
// from. A claim only: the scan asks the extension's DraftProvenance
// whether it holds, and the client is never believed.
DraftRun *uuid.UUID
// KnowledgeShipping is the publisher's confirmation of the packs an
// upload ships; a tag-built submission carries none.
KnowledgeShipping *KnowledgeShipping
// contains filtered or unexported fields
}
SubmitInput carries one publication submission. Workspace is a directory holding the exact tree to publish; the handler prepares it from `git archive` (git-tag source) or the uploaded archive (cli-upload).
type Ticket ¶
type Ticket struct {
ID string
}
Ticket is an Admitter's handle on one admission; empty means none.
type TransitionCause ¶
TransitionCause is the pipeline's account of a transition it made. A PipelineError is the platform's own fault — a stage error, a fatal report, a scan that never finished — routing the version to review with an S0/pipeline-error finding; an extension that charged for the submission refunds on it.
type TransitionResult ¶
type TransitionResult struct {
AgentID uuid.UUID
VersionID uuid.UUID
Version string
From Status
To Status
Reason string
Event string
// Cause is what the pipeline said about a transition it made (zero for
// every other actor), carried onto the event.
Cause TransitionCause
}
TransitionResult describes a committed transition. Event is the webhook name for the edge, or "" when the edge has no external event.
type UnscannedStandingError ¶
type UnscannedStandingError struct{ N int64 }
UnscannedStandingError reports a Restore to public refused because N versions admitted unscanned still stand.
func (*UnscannedStandingError) Error ¶
func (e *UnscannedStandingError) Error() string