abilityrequest

package
v0.0.0-...-4c3468c Latest Latest
Warning

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

Go to latest
Published: Nov 2, 2026 License: AGPL-3.0 Imports: 29 Imported by: 0

Documentation

Overview

Package abilityrequest is the person's side of the ability engine's write rail (engine v4 §1.4, §4; amendments W1, W3): the queue, approve and decline of assistant_ability_requests rows created by site_ability_run.

Shape follows internal/assistantrequest: session principal only, the approval is digest-bound and happens once, and every decision commits with its audit row. W1: the approver's hold on the row's operator_permission is re-checked HERE, in the service, not only by route middleware.

Index

Constants

View Source
const (
	// DetailChangedSinceRead: the page changed after the AI read it.
	DetailChangedSinceRead = mcp.PageEditConflictChangedSinceRead
	// DetailEditorOpen: someone has the page open in an editor (Elementor or
	// the WordPress editor).
	DetailEditorOpen = mcp.PageEditConflictEditorOpen
	// DetailAutosavePending: someone has unsaved Elementor changes on it.
	DetailAutosavePending = mcp.PageEditConflictAutosavePending
)

Outcome details of a wpmgr/page-edit refused as a conflict: the closed set the site answers with (mcp's page-edit conflict reasons, the one set the AI and this outcome both use), and the only values outcome_detail carries.

View Source
const (
	// OutsideChangeActiveKit: the site's active Elementor kit.
	OutsideChangeActiveKit = "active_kit"
	// OutsideChangeOtherPosts: another post or page, or its data, written,
	// trashed or deleted.
	OutsideChangeOtherPosts = "other_posts"
	// OutsideChangeTerms: categories or tags.
	OutsideChangeTerms = "terms"
	// OutsideChangeSiteSettings: a site setting.
	OutsideChangeSiteSettings = "site_settings"
	// OutsideChangeUsers: a user account, a role, or the site's
	// administrators.
	OutsideChangeUsers = "users"
)

Outside changes of a wpmgr/page-edit refused with side_effect_detected: the kind of thing Elementor's save changed outside the page, and the only values outside_change carries.

View Source
const (
	CodeRequestChanged     = "ability_request_changed"
	CodeSessionRequired    = "ability_request_session_required"
	CodePermissionRequired = "ability_request_permission_required"
	CodeWriteToolsDisabled = "ability_request_write_tools_disabled"
	CodeConnectionInactive = "ability_request_connection_inactive"
	CodeAssistantPaused    = "ability_request_assistant_paused"
	CodeCapabilityNotHeld  = "ability_request_capability_not_held"
	CodeSiteLeftScope      = "ability_request_site_left_scope"
	CodeLedgerFailed       = "ability_request_ledger_failed"
)

Refusal codes a person sees.

View Source
const (
	UndoDone             = "undone"
	UndoRefusedConflict  = "refused_conflict"
	UndoRefusedPublished = "refused_published"
	UndoFailed           = "failed"
)

Undo results (m156 undo_state).

View Source
const (
	// UndoCodeSnapshotTampered: the copy the site kept for the change, its
	// record and the hash the undo sent are not one; nothing was changed.
	UndoCodeSnapshotTampered = "snapshot_tampered"
	// UndoCodeRestoreMismatch: the site's put-back did not read back as the
	// copy.
	UndoCodeRestoreMismatch = "restore_mismatch"
)

Undo codes (m169 undo_code): why a failed undo failed, for the two answers the person is told about in their own words. The table admits only these, and only on a failed undo.

View Source
const (
	// UndoReconcileInterval is how often stuck undos are looked for.
	UndoReconcileInterval = time.Minute
	// StuckUndoAfter is how long an undo may stay in_progress before the
	// reconciler asks the site. It is past the revert's send budget, the
	// finish budget and the command token's settle time, so no revert sent
	// by the request that started the undo can still arrive.
	StuckUndoAfter = undoSendBudget + undoFinishBudget + tokenSettled + 30*time.Second
)
View Source
const (
	ScanInterval  = 15 * time.Second
	SweepInterval = time.Minute
	// BackoffBase and BackoffCap bound how soon a request that could not
	// start is tried again.
	BackoffBase = 30 * time.Second
	BackoffCap  = 5 * time.Minute

	// StaleDispatchAfter: a dispatched row with no reply recorded after this
	// is moved to outcome_unknown (the worker died between send and record).
	StaleDispatchAfter = 3 * time.Minute
)

Timing and limits.

View Source
const (
	OutcomeCreated        = "created"
	OutcomeApplied        = "applied"
	OutcomeRefused        = "refused"
	OutcomeVerifyMismatch = "verify_mismatch"
	OutcomeFailed         = "failed"
	OutcomeUnknown        = "outcome_unknown"
	OutcomeNotSent        = "not_sent"
)

Outcomes (m156's closed set).

View Source
const (
	ReasonGrantInactive          = "grant_inactive"
	ReasonAssistantPaused        = "assistant_paused"
	ReasonOrganisationDeleted    = "organisation_deleted"
	ReasonCapabilityNotHeld      = "capability_not_held"
	ReasonSiteAbsent             = "site_absent"
	ReasonForbiddenByContext     = "forbidden_by_context"
	ReasonAgentOutdated          = "agent_outdated"
	ReasonDispatchDeadlinePassed = "dispatch_deadline_passed"
	ReasonTransportPreSend       = "transport_pre_send"
	ReasonEntryChanged           = "entry_changed"
	ReasonEntryDisabled          = "entry_disabled"
	// m161: the REST route a rest-write request was approved against.
	ReasonRouteChanged  = "route_changed"
	ReasonRouteDisabled = "route_disabled"
	// m174: a request the site's setting approved, whose setting, or whose
	// connection's switch, no longer allows it when it is sent; or whose
	// catalogue entry or route was re-classed since.
	ReasonSettingChanged = "setting_changed"
	ReasonClassChanged   = "class_changed"
)

Reasons an approved request closed without being sent.

View Source
const (
	AttemptSiteUnreachable    = "site_unreachable"
	AttemptSiteBusy           = "site_busy"
	AttemptOrgBusy            = "org_busy"
	AttemptContextUnavailable = "context_unavailable"
	AttemptWriteToolsDisabled = "write_tools_disabled"
)

Transient reasons; the row stays approved.

View Source
const CodeUndoBusy = "ability_request_undo_busy"

CodeUndoBusy refuses, before anything is sent, the undo of a page-builder draft while a page edit of that draft is still being made or undone. The undo stays available.

View Source
const CodeUndoEditorOpen = "ability_request_undo_editor_open"

CodeUndoEditorOpen: the site refused the undo because the page is open in an editor there. Nothing was changed and the undo is available again; it can run once the editor is closed and WordPress frees the page.

View Source
const CodeUndoRetry = "ability_request_undo_retry"

CodeUndoRetry: the site did not settle the undo; it is open again.

View Source
const CodeUndoUnavailable = "ability_request_undo_unavailable"

CodeUndoUnavailable refuses an undo that is not open: not done, already undone or started, past its window, or a page edit with a later edit of the same page still in effect.

Variables

This section is empty.

Functions

func NewContentRetentionPeriodicJob

func NewContentRetentionPeriodicJob() *river.PeriodicJob

func QueueForTenant

func QueueForTenant(tenantID uuid.UUID) string

QueueForTenant is the dispatch queue a tenant's jobs run on.

func Queues

func Queues() map[string]river.QueueConfig

Queues is the River queue configuration the dispatch jobs need.

func UndoOffered

func UndoOffered(r sqlc.AssistantAbilityRequest, agentVersion string, newestEdit bool, now time.Time) bool

UndoOffered is the card's "Undo" button, computed server-side. newestEdit says whether a wpmgr/page-edit row is the newest applied edit of its post that has not been undone (Service.NewestEdits); an older edit offers no undo, since undo goes newest first. It is ignored for every other ability.

Types

type AbilityAgent

type AbilityAgent interface {
	AbilityRun(ctx context.Context, siteID uuid.UUID, siteURL string, call agentcmd.AbilityRunCall) (agentcmd.AbilityRunResponse, error)
}

AbilityAgent is the one agent call the worker and undo make.

type ApprovalDTO

type ApprovalDTO struct {
	Source string `json:"source"`
	// Setting is the setting an approval by a setting relied on. Null for a
	// person's approval.
	Setting *ApprovalSettingDTO `json:"setting"`
}

ApprovalDTO is how an approved request was approved: by a person from the dashboard, or by the site's setting with no person deciding it.

type ApprovalSettingDTO

type ApprovalSettingDTO struct {
	Mode                string     `json:"mode"`
	Source              string     `json:"source"`
	SetByUserID         *uuid.UUID `json:"set_by_user_id"`
	SetByName           *string    `json:"set_by_name"`
	SetByAccountDeleted bool       `json:"set_by_account_deleted"`
	SetAt               *time.Time `json:"set_at"`
}

ApprovalSettingDTO is the site setting an approval by a setting relied on, copied onto the request when it was approved. SetByName is a person's name: render it as text.

type ApproveBody

type ApproveBody struct {
	PresentedDigest string `json:"presented_digest"`
}

ApproveBody is the approve request body.

type ContentEditingEnabler

type ContentEditingEnabler interface {
	ContentEditingEnable(ctx context.Context, siteID uuid.UUID, siteURL string) (agentcmd.ContentEditingEnableResponse, error)
}

ContentEditingEnabler sends content_editing_enable. *agentcmd.Client satisfies it.

type ContentEditingState

type ContentEditingState struct {
	SiteID          uuid.UUID  `json:"site_id"`
	Enabled         bool       `json:"enabled"`
	EnabledAt       *time.Time `json:"enabled_at"`
	PrincipalUserID *int64     `json:"principal_user_id"`
	EnabledBy       *uuid.UUID `json:"enabled_by"`
}

ContentEditingState is a site's content-editing state on the wire.

type ContentRetentionArgs

type ContentRetentionArgs struct{}

func (ContentRetentionArgs) InsertOpts

func (ContentRetentionArgs) InsertOpts() river.InsertOpts

func (ContentRetentionArgs) Kind

type ContentRetentionWorker

type ContentRetentionWorker struct {
	river.WorkerDefaults[ContentRetentionArgs]
	// BatchSize defaults to contentRetentionBatchSize when zero.
	BatchSize int32
	// contains filtered or unexported fields
}

ContentRetentionWorker visits the backlog in bounded batches within its timeout. Each call commits independently; every run starts at the beginning.

func NewContentRetentionWorker

func NewContentRetentionWorker(pool *db.Pool, logger *slog.Logger) *ContentRetentionWorker

func (*ContentRetentionWorker) Timeout

func (*ContentRetentionWorker) Work

type ContextRules

type ContextRules interface {
	ForbiddenByContext(ctx context.Context, tenantID, siteID uuid.UUID, tool string) (matchedEntry string, forbidden bool, err error)
}

ContextRules reads the operator's AI rules. *mcp.Service satisfies it.

type DecideResult

type DecideResult struct {
	// Decided is false when the engine is not wired, or the request had
	// already been decided; the request then waits as it is.
	Decided   bool
	Outcome   aipolicy.Outcome
	Ask       aipolicy.AskReason
	Class     aipolicy.Class
	ResumesAt time.Time
	// Approved is the approved row, set with OutcomeAutoBySetting.
	Approved sqlc.AssistantAbilityRequest
}

DecideResult is the outcome of Decide.

type DispatchArgs

type DispatchArgs struct {
	TenantID  uuid.UUID `json:"tenant_id"`
	RequestID uuid.UUID `json:"request_id"`
	SiteID    uuid.UUID `json:"site_id"`
	GrantID   uuid.UUID `json:"grant_id"`
}

DispatchArgs is one approved request to try. Ids only.

func (DispatchArgs) InsertOpts

func (a DispatchArgs) InsertOpts() river.InsertOpts

InsertOpts pins the job to its tenant's shard, at most one live job per request. MaxAttempts 1: a job that errors after the send must not run the send again; the next scan decides afresh from the row.

func (DispatchArgs) Kind

func (DispatchArgs) Kind() string

Kind implements river.JobArgs.

type DispatchWorker

type DispatchWorker struct {
	river.WorkerDefaults[DispatchArgs]
	// contains filtered or unexported fields
}

DispatchWorker tries one approved request.

func NewDispatchWorker

func NewDispatchWorker(svc *Service) *DispatchWorker

NewDispatchWorker builds the dispatch worker.

func (*DispatchWorker) Timeout

Timeout bounds one dispatch; the send is bounded well below it.

func (*DispatchWorker) Work

Work tries one approved request.

type Enqueuer

type Enqueuer interface {
	EnqueueDispatch(ctx context.Context, args DispatchArgs) error
}

Enqueuer inserts dispatch jobs.

type EntryEncoder

type EntryEncoder func(sqlc.AbilityCatalogue) ([]byte, string, error)

EntryEncoder is abilities.SendableEntry, handed in by main.go.

type GrantAuthorizer

type GrantAuthorizer interface {
	AuthorizeGrant(ctx context.Context, tenantID uuid.UUID, v mcp.GrantVerdict) (mcp.AuthorizedRequest, error)
}

GrantAuthorizer derives what a verdict confers.

type GrantVerdicts

type GrantVerdicts interface {
	ReCheckGrantAuthorization(ctx context.Context, tenantID, grantID uuid.UUID) (mcp.GrantVerdict, error)
}

GrantVerdicts and GrantAuthorizer are internal/assistantrequest's.

type Handler

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

Handler serves the ability request queue and its decisions.

func NewHandler

func NewHandler(svc *Service) *Handler

NewHandler builds the handler.

func (*Handler) Register

func (h *Handler) Register(r *gin.RouterGroup)

Register mounts, on the authenticated /api/v1 group:

GET  /sites/:siteId/ai/ability-requests
POST /sites/:siteId/ai/ability-requests/:requestId/approve
POST /sites/:siteId/ai/ability-requests/:requestId/decline

Route middleware requires site.content.edit and site access; the service re-checks the row's own operator_permission (W1). Decisions take JSON only (the CSRF guard for a cookie-authenticated change).

func (*Handler) RenderAbilityRequests

func (h *Handler) RenderAbilityRequests(ctx context.Context, p domain.Principal, rows []sqlc.AssistantAbilityRequest) ([]any, error)

RenderAbilityRequests renders rows exactly as the request queues return them, for the AI activity feed: the same object, the same digest rule, the same agent versions for the recovery undo, the same newest-edit rule for a page edit's undo and the same setter names.

type ListResponse

type ListResponse struct {
	Requests []RequestDTO `json:"requests"`
	Limit    int32        `json:"limit"`
	Offset   int32        `json:"offset"`
}

ListResponse is a page of the queue.

type OrgListResponse

type OrgListResponse struct {
	Requests     []RequestDTO `json:"requests"`
	PendingCount int64        `json:"pending_count"`
	Limit        int32        `json:"limit"`
	Offset       int32        `json:"offset"`
}

OrgListResponse is a page of the organisation-wide queue with the badge.

type OrgQueue

type OrgQueue struct {
	Requests     []sqlc.AssistantAbilityRequest
	PendingCount int64
}

OrgQueue is a page of the organisation-wide queue and the badge count.

type PageBuilderDTO

type PageBuilderDTO struct {
	Builder string `json:"builder"`
	Format  string `json:"format"`
	Version string `json:"version"`
	Layout  string `json:"layout"`
}

PageBuilderDTO is the page builder of a page-create request.

type PageMediaDTO

type PageMediaDTO struct {
	ID       int64  `json:"id"`
	Filename string `json:"filename"`
	Mime     string `json:"mime"`
	Width    int64  `json:"width"`
	Height   int64  `json:"height"`
}

PageMediaDTO is one image a page-create request places.

type PolicyApproval

type PolicyApproval struct {
	TenantID, RequestID, SiteID uuid.UUID
	SiteMode                    aipolicy.Mode
	ModeSource                  string
	ModeVersion                 int64
	SetterUserID                uuid.UUID
	SetterSetAt                 time.Time
	BaseClass, Class            aipolicy.Class
	DispatchWindowSeconds       int32
}

PolicyApproval is the compare-and-set that approves a request under the site's setting. The statement must also require the request to be pending, unchecked and unexpired, the site's mode, its source, version, setter and set time to be these, the mode to allow the class, and the connection to run by the site's setting. The approval records each of them, as the request's backstop requires.

type PolicyAsk

type PolicyAsk struct {
	TenantID, RequestID uuid.UUID
	BaseClass, Class    aipolicy.Class
	Reason              aipolicy.AskReason
}

PolicyAsk records why a request waits. The statement must require the request to be pending and unchecked.

type PolicyRepo

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

PolicyRepo is the production PolicyStore. Every read and write runs in an organisation-wide tenant transaction that carries no user and no site allowlist (db.InTenantTx): the counts must see every site of the connection, and the request's backstop refuses an approval by a setting while a user id is in the transaction.

func NewPolicyRepo

func NewPolicyRepo(pool *db.Pool, rec *audit.Recorder) *PolicyRepo

NewPolicyRepo builds the store.

func (*PolicyRepo) Approving

func (r *PolicyRepo) Approving(ctx context.Context, tenantID uuid.UUID, fn func(tx PolicyTx) error) error

func (*PolicyRepo) Snapshot

func (r *PolicyRepo) Snapshot(ctx context.Context, tenantID, requestID uuid.UUID) (PolicySnapshot, error)

type PolicySnapshot

type PolicySnapshot struct {
	// Request is the request row as stored.
	Request sqlc.AssistantAbilityRequest
	// StoredClass is the catalogue entry's change_class, or for a REST
	// write the route row's.
	StoredClass aipolicy.Class
	// AIDraft is true when the site holds a done, not-undone page creation
	// whose created post is the request's target.
	AIDraft bool
	// SiteMode, SiteModeSource, SiteModeVersion, SiteSetter and SiteSetAt
	// are sites.ai_mode*.
	SiteMode        aipolicy.Mode
	SiteModeSource  string
	SiteModeVersion int64
	SiteSetter      uuid.UUID
	SiteSetAt       time.Time
	// ConnectionAuto and ConnectionSetter are mcp_grants.ai_auto*.
	ConnectionAuto   aipolicy.ConnectionAuto
	ConnectionSetter uuid.UUID
	// TooOld is true when the request was created longer ago than a
	// decision by setting may follow it (unsettledAge), by the database's
	// clock. Such a request waits for a person with not_checked.
	TooOld bool
}

PolicySnapshot is what one decision reads about one request.

type PolicyStore

type PolicyStore interface {
	// Snapshot reads the request and its stored inputs, read-only, in a
	// tenant transaction with no user.
	Snapshot(ctx context.Context, tenantID, requestID uuid.UUID) (PolicySnapshot, error)
	// Approving runs fn in the approving transaction: a tenant transaction
	// with no user and no site allowlist, holding the tenant's policy lock.
	Approving(ctx context.Context, tenantID uuid.UUID, fn func(tx PolicyTx) error) error
}

PolicyStore is the database side of Decide.

type PolicyTx

type PolicyTx interface {
	Snapshot(ctx context.Context, tenantID, requestID uuid.UUID) (PolicySnapshot, error)
	// DraftUsage counts the connection's approvals by setting in the draft
	// classes over the window, and whether siteID is among their sites.
	DraftUsage(ctx context.Context, tenantID, grantID, siteID uuid.UUID) (aipolicy.Usage, error)
	// ApproveByPolicy is the compare-and-set; pgx.ErrNoRows when it
	// touched no row.
	ApproveByPolicy(ctx context.Context, a PolicyApproval) (sqlc.AssistantAbilityRequest, error)
	// RecordAsk writes the reason; pgx.ErrNoRows when it touched no row.
	RecordAsk(ctx context.Context, a PolicyAsk) error
	// Audit writes one audit row in this transaction.
	Audit(ctx context.Context, e audit.Event) error
}

PolicyTx is what Decide does inside the approving transaction.

type ReconcileArgs

type ReconcileArgs struct{}

ReconcileArgs: stale dispatched rows to outcome_unknown, and the ledger resolution of outcome_unknown rows.

func (ReconcileArgs) Kind

func (ReconcileArgs) Kind() string

Kind implements river.JobArgs.

type ReconcileWorker

type ReconcileWorker struct {
	river.WorkerDefaults[ReconcileArgs]
	// contains filtered or unexported fields
}

ReconcileWorker runs the reconciler.

func NewReconcileWorker

func NewReconcileWorker(svc *Service) *ReconcileWorker

NewReconcileWorker builds the reconciler.

func (*ReconcileWorker) Work

Work runs one reconcile pass: stale sends first, then the ledger.

type RequestDTO

type RequestDTO struct {
	ContentClearedAt *time.Time `json:"content_cleared_at"`
	ID               uuid.UUID  `json:"id"`
	SiteID           uuid.UUID  `json:"site_id"`
	AbilityName      string     `json:"ability_name"`
	InputJSON        string     `json:"input_json"`
	TitleExcerpt     *string    `json:"title_excerpt"`
	Editor           *string    `json:"editor"`
	PostType         *string    `json:"post_type"`
	EffectCopy       string     `json:"effect_copy"`
	Snapshot         string     `json:"snapshot"`
	SiteLabel        string     `json:"site_label"`
	SiteHost         string     `json:"site_host"`
	GrantLabel       string     `json:"grant_label"`
	GrantVia         string     `json:"grant_via"`
	SetupClient      *string    `json:"setup_client"`
	CardCopyVersion  int32      `json:"card_copy_version"`
	PresentedDigest  *string    `json:"presented_digest,omitempty"`
	State            string     `json:"state"`
	CreatedAt        time.Time  `json:"created_at"`
	ExpiresAt        time.Time  `json:"expires_at"`
	DecidedAt        *time.Time `json:"decided_at"`
	Outcome          *string    `json:"outcome"`
	OutcomeCode      *string    `json:"outcome_code"`
	// OutcomeDetail says which conflict refused a wpmgr/page-edit:
	// changed_since_read, editor_open or autosave_pending (outcomeDetailFor).
	// Null for every other row. Never the site's own words.
	OutcomeDetail *string `json:"outcome_detail"`
	// OutsideChange says what a wpmgr/page-edit refused with
	// side_effect_detected changed outside the page: active_kit,
	// other_posts, terms, site_settings or users (outsideChangeFor). Null
	// for every other row. Never the site's own words.
	OutsideChange *string `json:"outside_change"`
	NotSentReason *string `json:"not_sent_reason"`
	CreatedPostID *int64  `json:"created_post_id"`
	Trashed       *bool   `json:"trashed"`
	// Restored is a failed wpmgr/rest-write's own-undo report: true when the
	// whole post is back as it was, false when the title and excerpt were
	// put back but other changes the site made remain (or the put-back
	// itself failed), null when nothing needed restoring or for any other
	// ability.
	Restored  *bool   `json:"restored"`
	UndoState *string `json:"undo_state"`
	// UndoCode says why a failed undo failed: snapshot_tampered (the copy
	// the site kept for the change was changed on the site, so it was not
	// used and nothing changed) or restore_mismatch (the site's put-back did
	// not read back as the copy). Null for every other row (undoCodeOf).
	UndoCode           *string    `json:"undo_code"`
	UndoAvailableUntil *time.Time `json:"undo_available_until"`
	// UndoOffered is whether POST .../undo would start an undo now: a done
	// row's undo inside its window (for a page edit, only the newest applied
	// edit of its page not yet undone), or the recovery undo of a draft a
	// failed or given-up write left on the site (GH #826).
	UndoOffered bool `json:"undo_offered"`
	// ResolveGaveUp is true once WPMgr stopped checking the site for the
	// outcome of a write whose reply was lost (GH #825): the result is final
	// and the person should look at the site's drafts.
	ResolveGaveUp bool `json:"resolve_gave_up"`
	// RouteID, RouteSHA256 and CardFacts are a wpmgr/rest-write request's
	// reviewed route, its approved hash and its structured card (null for
	// every other ability). CardFacts is the object the MCP layer built at
	// creation: every site string in it is under a from_the_site member,
	// cleaned and capped. It is passed through as stored, never added to.
	RouteID     *string         `json:"route_id"`
	RouteSHA256 *string         `json:"route_sha256"`
	CardFacts   json.RawMessage `json:"card_facts"`
	// PageMedia is a wpmgr/page-create request's images, in outline order,
	// as the site described them at precheck (null when the outline has no
	// image, and for every other ability). Each filename came from the site.
	PageMedia []PageMediaDTO `json:"page_media"`
	// Approval is how the request was approved: by a person, or by the
	// site's setting with no person deciding (ADR-065). Null until it is
	// approved, and for a request that never will be.
	Approval *ApprovalDTO `json:"approval"`
	// ChangeClass is the kind of change WPMgr decided the request is, from
	// its own records; ChangeKindName is that kind's name as copy uses it.
	// Both null before WPMgr decided, and the name null for always_ask.
	ChangeClass    *string `json:"change_class"`
	ChangeKindName *string `json:"change_kind_name"`
	// AskReason is why the request was left for a person instead of being
	// approved by a setting. It stays set after a person approves it.
	AskReason *string `json:"ask_reason"`
	// PageBuilder is the page builder that builds a wpmgr/page-create
	// request's page, as the site's precheck named it (null for a page in a
	// WordPress editor, and for every other ability). Version came from the
	// site.
	PageBuilder *PageBuilderDTO `json:"page_builder"`
	// PageEdit is a wpmgr/page-edit request's card (null for every other
	// ability): the post, the page builder, each change, and the page's
	// outline after the edit, as the control plane checked them against
	// the site's precheck. Every value under a from_the_site member came
	// from the site. It is passed through as stored, never added to.
	PageEdit json.RawMessage `json:"page_edit"`
}

RequestDTO is one ability request on the wire. site_label, site_host, grant_label and title_excerpt are text to render as text nodes. input_json is the exact input until ContentClearedAt is set, then it is {}.

type RiverEnqueuer

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

RiverEnqueuer inserts dispatch jobs on a started River client.

func NewRiverEnqueuer

func NewRiverEnqueuer(client *river.Client[pgx.Tx]) *RiverEnqueuer

NewRiverEnqueuer wraps a started River client.

func (*RiverEnqueuer) EnqueueDispatch

func (e *RiverEnqueuer) EnqueueDispatch(ctx context.Context, args DispatchArgs) error

EnqueueDispatch inserts one dispatch job.

type RouteEncoder

type RouteEncoder func(sqlc.RestRouteCatalogue) ([]byte, string, error)

RouteEncoder is abilities.SendableRoute, handed in by main.go.

type ScanArgs

type ScanArgs struct{}

ScanArgs is the periodic scan for approved requests that are due.

func (ScanArgs) Kind

func (ScanArgs) Kind() string

Kind implements river.JobArgs.

type ScanWorker

type ScanWorker struct {
	river.WorkerDefaults[ScanArgs]
	// contains filtered or unexported fields
}

ScanWorker runs the scan.

func NewScanWorker

func NewScanWorker(svc *Service) *ScanWorker

NewScanWorker builds the scan worker; wire the enqueuer after River starts.

func (*ScanWorker) SetEnqueuer

func (w *ScanWorker) SetEnqueuer(e Enqueuer)

SetEnqueuer wires the River enqueuer.

func (*ScanWorker) Work

func (w *ScanWorker) Work(ctx context.Context, _ *river.Job[ScanArgs]) error

Work runs one scan.

type Service

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

Service is the queue, approve and decline.

func NewService

func NewService(pool *db.Pool, grants GrantVerdicts, az GrantAuthorizer, rec *audit.Recorder, logger *slog.Logger) *Service

NewService builds the service; the write switch starts off.

func (*Service) AgentVersions

func (s *Service) AgentVersions(ctx context.Context, p domain.Principal, rows []sqlc.AssistantAbilityRequest) map[uuid.UUID]string

AgentVersions returns the recorded agent version of each site whose rows could offer a recovery undo (a failed or outcome_unknown row), for the card's undo_offered. Done rows need no version. It reads under the caller's principal. On a read error it logs and returns what it has: a missing version offers no recovery undo, which is the safe answer.

func (*Service) Approve

func (s *Service) Approve(ctx context.Context, approver domain.Principal, siteID, requestID uuid.UUID, presentedDigest string) (sqlc.AssistantAbilityRequest, error)

Approve records one person's digest-bound approval.

func (*Service) ContentEditing

func (s *Service) ContentEditing(ctx context.Context, p domain.Principal, siteID uuid.UUID) (ContentEditingState, error)

ContentEditing reads one site's state.

func (*Service) Decide

func (s *Service) Decide(ctx context.Context, tenantID, requestID uuid.UUID) (DecideResult, error)

Decide decides one request that was just created pending. It never returns an approval it did not commit. A decision that errors records nothing: the request stays pending and waits for a person, and nothing approves it automatically later.

func (*Service) DecideAbilityRequest

func (s *Service) DecideAbilityRequest(ctx context.Context, tenantID, requestID uuid.UUID) (mcp.AbilityDecision, error)

DecideAbilityRequest is mcp.AbilityDecider: Decide, answered in the MCP package's terms. It takes ids only.

func (*Service) Decline

func (s *Service) Decline(ctx context.Context, decider domain.Principal, siteID, requestID uuid.UUID) (sqlc.AssistantAbilityRequest, error)

Decline records one person's refusal. W1 applies to decline too: only a person who could approve may decide.

func (*Service) EnableContentEditing

func (s *Service) EnableContentEditing(ctx context.Context, p domain.Principal, siteID uuid.UUID) (ContentEditingState, error)

EnableContentEditing asks the site's agent to create (or confirm) its content service user, then records it with the acting person.

func (*Service) List

func (s *Service) List(ctx context.Context, p domain.Principal, siteID *uuid.UUID, limit, offset int32) ([]sqlc.AssistantAbilityRequest, error)

List is the queue for one site (or the organisation), newest first.

func (*Service) ListOrg

func (s *Service) ListOrg(ctx context.Context, p domain.Principal, state *string, limit, offset int32) (OrgQueue, error)

ListOrg is the organisation-wide queue (GH #828), optionally narrowed to one state, with the number still waiting for a decision. Both reads run under the caller's own principal, so a site collaborator sees and counts only their own sites.

func (*Service) NewestEdits

func (s *Service) NewestEdits(ctx context.Context, p domain.Principal, rows []sqlc.AssistantAbilityRequest) map[uuid.UUID]bool

NewestEdits returns which of rows' wpmgr/page-edit requests are the newest applied edit of their post that has not been undone, for the card's undo_offered: undo goes newest first, so an older edit offers none. Only a row whose own undo is open is looked up, with one read per post. It reads under the caller's principal. On a read error it logs and returns what it has: a page edit missing from the answer offers no undo, which is the safe answer.

func (*Service) SetDispatchEnqueuer

func (s *Service) SetDispatchEnqueuer(e Enqueuer)

SetDispatchEnqueuer wires the enqueuer an approval by setting uses to send the change at once. Without it the periodic scan sends it.

func (*Service) SetEnabler

func (s *Service) SetEnabler(e ContentEditingEnabler)

SetEnabler wires the enable command.

func (*Service) SetPolicy

func (s *Service) SetPolicy(store PolicyStore, setters SetterResolver)

SetPolicy wires the engine. Until both are set, Decide decides nothing and every request waits for a person, as before.

func (*Service) SetRouteEncoder

func (s *Service) SetRouteEncoder(route RouteEncoder)

SetRouteEncoder wires the route bytes for wpmgr/rest-write. Without it a request naming a route waits with write_tools_disabled and the sweeper closes it at its deadline.

func (*Service) SetSender

func (s *Service) SetSender(agent AbilityAgent, entry EntryEncoder, rules ContextRules)

SetSender wires the send path. Without it every approved row waits with write_tools_disabled and the sweeper closes it at its deadline.

func (*Service) SetWriteToolsEnabled

func (s *Service) SetWriteToolsEnabled(on bool)

SetWriteToolsEnabled is WPMGR_MCP_WRITE_TOOLS.

func (*Service) Undo

func (s *Service) Undo(ctx context.Context, p domain.Principal, siteID, requestID uuid.UUID) (sqlc.AssistantAbilityRequest, error)

Undo starts and finishes a person's undo of a done request. The agent takes the object from its own ledger row for this request id (W3): the revert carries no input and never a post id. Its only parameters are p.revert (undoRevertFor): the snapshot hash a page edit's outcome recorded, or the page edits of a draft WPMgr created, which name ledger rows on the site and nothing the agent acts on directly.

type SetterResolver

type SetterResolver interface {
	ResolveSetter(ctx context.Context, tenantID, userID uuid.UUID) aipolicy.Setter
}

SetterResolver builds the person's current principal in the tenant and their account's status. Production is middleware.Authenticator's ResolveSetter, the session authenticator's own code path.

type SweepArgs

type SweepArgs struct{}

SweepArgs: lapsed waiting rows expire; approved rows past deadline close.

func (SweepArgs) Kind

func (SweepArgs) Kind() string

Kind implements river.JobArgs.

type SweepWorker

type SweepWorker struct {
	river.WorkerDefaults[SweepArgs]
	// contains filtered or unexported fields
}

SweepWorker runs the sweeper.

func NewSweepWorker

func NewSweepWorker(svc *Service) *SweepWorker

NewSweepWorker builds the sweeper.

func (*SweepWorker) Work

func (w *SweepWorker) Work(ctx context.Context, _ *river.Job[SweepArgs]) error

Work runs one sweep; both passes run even if the first fails.

type UndoReconcileArgs

type UndoReconcileArgs struct{}

UndoReconcileArgs is the periodic stuck-undo pass.

func (UndoReconcileArgs) Kind

func (UndoReconcileArgs) Kind() string

Kind implements river.JobArgs.

type UndoReconcileWorker

type UndoReconcileWorker struct {
	river.WorkerDefaults[UndoReconcileArgs]
	// contains filtered or unexported fields
}

UndoReconcileWorker runs the stuck-undo pass.

func NewUndoReconcileWorker

func NewUndoReconcileWorker(svc *Service) *UndoReconcileWorker

NewUndoReconcileWorker builds the stuck-undo reconciler.

func (*UndoReconcileWorker) Timeout

Timeout bounds one pass: every row's ledger call is bounded.

func (*UndoReconcileWorker) Work

Work runs one pass.

Jump to

Keyboard shortcuts

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