Documentation
¶
Overview ¶
Package coordination provides durable, project-scoped correspondence between agents. Credentials identify senders; message payloads never choose identity.
Index ¶
- Constants
- Variables
- func CallbackSignature(secret []byte, id string, sequence int64, timestamp string, body []byte) string
- func LocalProjectID(workspace string) string
- func NewPeerHTTPClient(endpoint string) (*http.Client, error)
- func NormalizeOwnedPath(p string) (string, error)
- func ValidateCallbackDestinations(destinations map[string]string) error
- func ValidatePeerEndpoint(endpoint string) error
- func WithTransportExecution(ctx context.Context, peerID string, proof TransportExecution) (context.Context, error)
- type Binding
- type CallbackDelivery
- type CallbackSubscription
- type CallbackWorker
- type CompatibilityChange
- type Contract
- type ContractAcknowledgement
- type ContractArtifact
- type ContractBlocker
- type ContractDependency
- type ContractReadiness
- type ContractSpec
- type CorrespondencePage
- type CredentialMetadata
- type DependencyBlocker
- type DependencyGraph
- type DependencyNode
- type DispatchOptions
- type Dispatcher
- type Escalation
- type Event
- type Execution
- type Executor
- type Lease
- type Message
- type Peer
- type ReconcileTaskUsageInput
- type ReconcileTaskUsageResult
- type RepositoryInfo
- type ReviewRequestInput
- type ReviewRequestResult
- type RuntimeObservation
- type RuntimePresence
- type SendInput
- type SessionPeer
- type SessionTransport
- type State
- type Store
- func (s *Store) AcknowledgeContract(ctx context.Context, peerID, id string, expectedRevision int64) (ContractAcknowledgement, error)
- func (s *Store) AcquireLease(ctx context.Context, peerID, ownerID string, ttl time.Duration) (Lease, error)
- func (s *Store) Authenticate(ctx context.Context, token string) (Peer, error)
- func (s *Store) AuthenticateScoped(ctx context.Context, token string) (Peer, context.Context, error)
- func (s *Store) Await(ctx context.Context, peerID, messageID string, afterRevision int64) (Message, error)
- func (s *Store) BeginTaskUsage(ctx context.Context, messageID string) error
- func (s *Store) BindSession(ctx context.Context, peerID, sessionID string) error
- func (s *Store) BindSessionTransport(ctx context.Context, sessionID string, remote Peer, ...) (SessionTransport, error)
- func (s *Store) CallbackDeliveries(ctx context.Context, peerID, id string) ([]CallbackDelivery, error)
- func (s *Store) CallbackSubscriptions(ctx context.Context, peerID string) ([]CallbackSubscription, error)
- func (s *Store) CancelCallback(ctx context.Context, peerID, id string) error
- func (s *Store) CheckOwnedPaths(ctx context.Context, peerID string, paths []string) error
- func (s *Store) CheckTaskUsage(ctx context.Context, messageID string) error
- func (s *Store) Claim(ctx context.Context, peerID string) (Message, error)
- func (s *Store) ClaimLease(ctx context.Context, lease Lease) (Message, error)
- func (s *Store) ClearSessionTransport(ctx context.Context, sessionID string) error
- func (s *Store) CompleteLease(ctx context.Context, lease Lease, messageID string, payload json.RawMessage) (Message, error)
- func (s *Store) ConfigureSessionPeer(ctx context.Context, anchorSession, targetSession, endpoint string, ...) (Peer, error)
- func (s *Store) ConfigureSessionPeerWithTTL(ctx context.Context, anchorSession, targetSession, endpoint string, ...) (Peer, CredentialMetadata, error)
- func (s *Store) ContractReadiness(ctx context.Context, peerID, id string) (ContractReadiness, error)
- func (s *Store) ContractRevision(ctx context.Context, peerID, id string, revision int64) (ContractSpec, error)
- func (s *Store) Correspondence(ctx context.Context, peerID, beforeID string, limit int) (CorrespondencePage, error)
- func (s *Store) CreateContract(ctx context.Context, peerID string, spec ContractSpec) (Contract, error)
- func (s *Store) DeleteContract(ctx context.Context, peerID, id string, expectedRevision int64) error
- func (s *Store) DisablePeer(ctx context.Context, peerID string) error
- func (s *Store) DispatchBindings(ctx context.Context, afterID string, limit int) ([]Binding, error)
- func (s *Store) Events(ctx context.Context, peerID string, after int64, limit int) ([]Event, error)
- func (s *Store) ExternalClaim(ctx context.Context, peerID string) (Message, error)
- func (s *Store) ExternalReply(ctx context.Context, peerID, messageID string, payload json.RawMessage, ...) (Message, error)
- func (s *Store) ExternalSend(ctx context.Context, peerID string, in SendInput) (Message, error)
- func (s *Store) ExternalTransition(ctx context.Context, peerID, messageID string, revision int64, event string, ...) (Message, error)
- func (s *Store) FinishTaskUsage(ctx context.Context, messageID string) error
- func (s *Store) Graph(ctx context.Context, viewerPeerID, messageID string, limit int) (DependencyGraph, error)
- func (s *Store) Inbox(ctx context.Context, peerID string, limit int) ([]Message, error)
- func (s *Store) ListContracts(ctx context.Context, peerID string) ([]Contract, error)
- func (s *Store) LocalPeersForSession(ctx context.Context, sessionID string) ([]SessionPeer, error)
- func (s *Store) MessageEvents(ctx context.Context, peerID, messageID string, afterRevision int64, limit int) ([]Event, error)
- func (s *Store) PeerForSession(ctx context.Context, sessionID string) (Peer, error)
- func (s *Store) Peers(ctx context.Context, peerID string) ([]Peer, error)
- func (s *Store) PendingCount(ctx context.Context, peerID string) (int, error)
- func (s *Store) PublishRuntimePresence(ctx context.Context, observer string, observations []RuntimeObservation) error
- func (s *Store) Read(ctx context.Context, peerID, messageID string) (Message, error)
- func (s *Store) ReadContract(ctx context.Context, peerID, id string) (Contract, error)
- func (s *Store) ReadEscalations(ctx context.Context, peerID string, after int64, limit int) ([]Escalation, error)
- func (s *Store) ReconcileExecutionContracts(ctx context.Context, lease Lease, messageID string) error
- func (s *Store) ReconcileTaskUsage(ctx context.Context, peerID string, in ReconcileTaskUsageInput) (ReconcileTaskUsageResult, error)
- func (s *Store) RecordTaskUsage(ctx context.Context, messageID, key string, sample UsageSample) error
- func (s *Store) RecoverExternal(ctx context.Context, peerID string) error
- func (s *Store) RegisterPeer(ctx context.Context, peer Peer) (Peer, string, error)
- func (s *Store) RegisterRepositorySessionPeer(ctx context.Context, sessionID, name, role string) (Peer, error)
- func (s *Store) RegisterSessionPeer(ctx context.Context, sessionID, name, role string) (Peer, error)
- func (s *Store) ReleaseLease(ctx context.Context, lease Lease) error
- func (s *Store) RemoveRuntimeObserver(ctx context.Context, observer string) error
- func (s *Store) RenewLease(ctx context.Context, lease Lease, ttl time.Duration) (Lease, error)
- func (s *Store) Reply(ctx context.Context, peerID, messageID string, payload json.RawMessage, ...) (Message, error)
- func (s *Store) RepositoryInfoForSession(ctx context.Context, sessionID string) (RepositoryInfo, error)
- func (s *Store) RetryCallback(ctx context.Context, peerID, id string, sequence int64) error
- func (s *Store) ReviewRequest(ctx context.Context, peerID string, in ReviewRequestInput) (ReviewRequestResult, error)
- func (s *Store) RevokePeerCredential(ctx context.Context, anchorSession, targetSession, token string) error
- func (s *Store) RotateCallbackKey(ctx context.Context, peerID, id string) (string, error)
- func (s *Store) RuntimePresenceForPeers(ctx context.Context, ids []string) (map[string]RuntimePresence, error)
- func (s *Store) Send(ctx context.Context, fromPeer string, input SendInput) (Message, error)
- func (s *Store) SendWithBudget(ctx context.Context, peer string, input SendInput, limits UsageLimits) (Message, error)
- func (s *Store) SessionTransport(ctx context.Context, sessionID string) (SessionTransport, error)
- func (s *Store) SubscribeCallback(ctx context.Context, peerID, destination string, after int64) (CallbackSubscription, string, error)
- func (s *Store) Transition(ctx context.Context, peerID, messageID string, expectedRevision int64, ...) (Message, error)
- func (s *Store) UpdateContract(ctx context.Context, peerID, id string, expectedRevision int64, ...) (Contract, error)
- func (s *Store) UsageForMessage(ctx context.Context, peer, messageID string) (TaskUsage, error)
- func (s *Store) UsageReconciliationCandidates(ctx context.Context, peerID, messageID, afterID string, limit int) (UsageReconciliationCandidatePage, error)
- func (s *Store) UsageReconciliationForMessage(ctx context.Context, peerID, messageID string) (UsageReconciliationSnapshot, error)
- func (s *Store) WithOwnedPaths(ctx context.Context, peerID string, paths []string, ...) error
- func (s *Store) WithUnrestrictedWorkspace(ctx context.Context, peerID string, fn func(context.Context) error) error
- func (s *Store) WorkerTransition(ctx context.Context, lease Lease, messageID string, expectedRevision int64, ...) (Message, error)
- type TaskUsage
- type TransportExecution
- type UsageJournalRun
- type UsageLimits
- type UsageReconciliationCandidate
- type UsageReconciliationCandidatePage
- type UsageReconciliationRecord
- type UsageReconciliationSnapshot
- type UsageReconciliationTotals
- type UsageSample
- type UsageSampleEvidence
Constants ¶
const ( MaxRequestDepth = 8 MaxConversationRequests = 32 MaxPeerQueue = 128 MaxProjectQueue = 512 MaxExecutionAttempts = 3 )
These protocol limits bound autonomous work, not provider token or cost use.
const ( MinPeerCredentialTTL = time.Minute MaxPeerCredentialTTL = 30 * 24 * time.Hour DefaultPeerCredentialTTL = 24 * time.Hour )
const MaxDependencies = 32
const RuntimePresenceTTL = 20 * time.Second
Variables ¶
var ( ErrQueueFull = errors.New("coordination: queue admission blocked") ErrRequestBudget = errors.New("coordination: request budget exhausted") )
var ( ErrOwnershipConflict = errors.New("coordination: path owned by another contract") ErrDependencyCycle = errors.New("coordination: contract dependency cycle") ErrContractValidation = errors.New("coordination: invalid handoff contract") )
var ( ErrRequestContracts = errors.New("coordination: required contract agreement unavailable") ErrNotFound = errors.New("coordination: not found") ErrConflict = errors.New("coordination: revision conflict") ErrIdempotency = errors.New("coordination: idempotency key reused for a different request") ErrBusy = errors.New("coordination: peer has active work") ErrLeaseLost = errors.New("coordination: worker lease lost") ErrRecoveryRequired = errors.New("coordination: interrupted work needs explicit recovery") )
var ErrPeerCredentialUnconfirmed = errors.New("coordination: credential commit unconfirmed; retain private credential file for inspection")
ErrPeerCredentialUnconfirmed preserves the delivered private file when commit acknowledgement is uncertain. Operators can inspect/revoke without losing it.
var ErrUsageBudget = errors.New("coordination: task usage requires review")
Functions ¶
func CallbackSignature ¶
func CallbackSignature(secret []byte, id string, sequence int64, timestamp string, body []byte) string
CallbackSignature signs version, stable event ID, sequence, attempt timestamp and exact body bytes. The secret is hex encoded in the one-time setup result.
func LocalProjectID ¶
LocalProjectID groups explicitly registered local peers in one canonical workspace. Callers cannot choose a foreign project through model metadata.
func NewPeerHTTPClient ¶
NewPeerHTTPClient admits explicit loopback HTTP for local agents. HTTPS uses the callback transport's public-IP validation, DNS pinning and TLS policy. Advertised discovery endpoints are never dialled automatically.
func NormalizeOwnedPath ¶
NormalizeOwnedPath returns the portable project-relative reservation key. Conservative Unicode folding also reserves case-distinct Linux spellings; this prevents macOS case/normalization aliases from obtaining two owners.
func ValidateCallbackDestinations ¶
ValidateCallbackDestinations validates operator configuration, never model input.
func ValidatePeerEndpoint ¶
ValidatePeerEndpoint validates advertised ingress metadata. Discovery never dials this value; an outbound caller must independently apply URL policy.
func WithTransportExecution ¶
Types ¶
type CallbackDelivery ¶
type CallbackSubscription ¶
type CallbackWorker ¶
type CallbackWorker struct {
Store *Store
Destinations map[string]string
// Transport is an explicit application/test injection. Production leaves nil
// to enforce public pinned DNS, HTTPS verification and no proxy/redirects.
Transport http.RoundTripper
PollInterval time.Duration
AttemptTimeout time.Duration
MaxAttempts int
OnError func(error)
}
CallbackWorker only delivers durable events. It never reserves or executes agent work. HTTP acknowledgement and a DB commit cannot be atomic: receivers must deduplicate X-Overkill-Event-ID, which is stable through every retry.
type CompatibilityChange ¶
type ContractAcknowledgement ¶
type ContractArtifact ¶
type ContractBlocker ¶
type ContractDependency ¶
type ContractReadiness ¶
type ContractSpec ¶
type ContractSpec struct {
Name string `json:"name"`
Endpoint string `json:"endpoint"`
SchemaVersion string `json:"schema_version"`
Schema json.RawMessage `json:"schema"`
AcceptanceCriteria []string `json:"acceptance_criteria"`
Artifacts []ContractArtifact `json:"artifacts"`
Workspace string `json:"workspace"`
Worktree string `json:"worktree,omitempty"`
OwnedPaths []string `json:"owned_paths"`
Dependencies []ContractDependency `json:"dependencies"`
CompatibilityChanges []CompatibilityChange `json:"compatibility_changes"`
TaskID string `json:"task_id,omitempty"`
}
ContractSpec is an interface agreement, not a task completion assertion. TaskID is a reference only: internal/tasks has no transactional dependency graph or PostgreSQL execution state to infer acceptance from.
type CorrespondencePage ¶
type CredentialMetadata ¶
type DependencyBlocker ¶
type DependencyGraph ¶
type DependencyGraph struct {
RootID string `json:"root_id"`
Nodes []DependencyNode `json:"nodes"`
Truncated bool `json:"truncated"`
HiddenDependencies bool `json:"hidden_dependencies"`
}
type DependencyNode ¶
type DependencyNode struct {
ContractBlockers []ContractBlocker `json:"contract_blockers"`
Message Message `json:"message"`
Readiness string `json:"readiness"`
Blockers []DependencyBlocker `json:"blockers"`
}
type DispatchOptions ¶
type Dispatcher ¶
type Dispatcher struct {
Store *Store
Executor Executor
Options DispatchOptions
}
Dispatcher owns background executions until Run returns. Delivery remains queued while a session is busy, and interrupted work requires review.
type Escalation ¶
type Escalation struct {
Sequence int64 `json:"sequence"`
ProjectID string `json:"project_id"`
From string `json:"from"`
To string `json:"to"`
ParentMessageID string `json:"parent_message_id,omitempty"`
ConversationID string `json:"conversation_id,omitempty"`
Reason string `json:"reason"`
State State `json:"state"`
RequiresReview bool `json:"requires_review"`
CreatedAt time.Time `json:"created_at"`
}
type Executor ¶
Executor reserves the same session admission used by interactive clients. Reservation must not execute work; a busy session leaves messages accepted.
type Message ¶
type Message struct {
RequiredContracts []ContractDependency `json:"required_contracts,omitempty"`
DependsOn []string `json:"depends_on,omitempty"`
ID string `json:"id"`
ProjectID string `json:"project_id"`
From string `json:"from"`
To string `json:"to"`
Kind string `json:"kind"`
ConversationID string `json:"conversation_id"`
TaskID string `json:"task_id,omitempty"`
InReplyTo string `json:"in_reply_to,omitempty"`
Payload json.RawMessage `json:"payload"`
State State `json:"state"`
Revision int64 `json:"revision"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
Deadline time.Time `json:"deadline"`
ParentMessageID string `json:"parent_message_id,omitempty"`
RequestDepth int `json:"request_depth"`
ExecutionAttempts int `json:"execution_attempts"`
}
type ReconcileTaskUsageInput ¶
type ReconcileTaskUsageInput struct {
MessageID string `json:"message_id"`
ExpectedMessageRevision int64 `json:"expected_message_revision"`
ExpectedUsageRevision int64 `json:"expected_usage_revision"`
ExpectedJournalFingerprint string `json:"expected_journal_fingerprint"`
ReconciliationID string `json:"reconciliation_id"`
InputTokens int64 `json:"input_tokens"`
OutputTokens int64 `json:"output_tokens"`
CachedInputTokens int64 `json:"cached_input_tokens"`
CostUSD float64 `json:"cost_usd"`
UsageKnown bool `json:"usage_known"`
PriceKnown bool `json:"price_known"`
Reason string `json:"reason"`
Evidence string `json:"evidence"`
Basis string `json:"basis"`
AcknowledgeUncertainty bool `json:"acknowledge_uncertainty"`
}
type ReconcileTaskUsageResult ¶
type ReconcileTaskUsageResult struct {
Usage TaskUsage `json:"usage"`
Reconciliation UsageReconciliationRecord `json:"reconciliation"`
Snapshot UsageReconciliationSnapshot `json:"snapshot"`
}
type RepositoryInfo ¶
type RepositoryInfo struct {
Scope string `json:"scope"`
Root string `json:"root"`
CommonDir string `json:"common_dir"`
Head string `json:"head,omitempty"`
Branch string `json:"branch,omitempty"`
}
RepositoryInfo describes a local, explicitly opted-in repository binding. HEAD and Branch are observations, not immutable identity or an ownership claim.
type ReviewRequestInput ¶
type ReviewRequestInput struct {
MessageID string `json:"message_id"`
ExpectedRevision int64 `json:"expected_revision"`
ExpectedUsageRevision int64 `json:"expected_usage_revision"`
ReviewID string `json:"review_id"`
Note string `json:"note"`
Limits UsageLimits `json:"limits"`
Requeue bool `json:"requeue"`
}
ReviewRequestInput is a trusted application control, never a model tool. Requeue explicitly acknowledges that replay may repeat earlier side effects.
type ReviewRequestResult ¶
type RuntimeObservation ¶
type RuntimePresence ¶
type RuntimePresence struct {
State string `json:"state"`
Source string `json:"source"`
Observers int `json:"observers"`
ObservedAt *time.Time `json:"observed_at,omitempty"`
ExpiresAt *time.Time `json:"expires_at,omitempty"`
}
RuntimePresence describes an observed application runtime, not a client connection, delivery guarantee, or exclusive execution lease.
type SendInput ¶
type SendInput struct {
RequiredContracts []ContractDependency `json:"required_contracts,omitempty"`
DependsOn []string `json:"depends_on,omitempty"`
To string `json:"to"`
Kind string `json:"kind"`
ConversationID string `json:"conversation_id,omitempty"`
TaskID string `json:"task_id,omitempty"`
InReplyTo string `json:"in_reply_to,omitempty"`
Payload json.RawMessage `json:"payload"`
Deadline time.Time `json:"deadline,omitempty"`
IdempotencyKey string `json:"idempotency_key"`
}
type SessionPeer ¶
type SessionPeer struct {
Presence RuntimePresence `json:"presence"`
Peer
SessionID string `json:"session_id"`
Scope string `json:"scope"`
Repository *RepositoryInfo `json:"repository,omitempty"`
}
type SessionTransport ¶
type SessionTransport struct {
SessionID string
PeerID string
ProjectID string
Workspace string
Endpoint string
CredentialFile string `json:"-"`
Revision int64
}
SessionTransport is trusted application configuration. CredentialFile is a private local reference and must never be returned in peer/model metadata.
type Store ¶
type Store struct {
// contains filtered or unexported fields
}
func (*Store) AcknowledgeContract ¶
func (*Store) AcquireLease ¶
func (s *Store) AcquireLease(ctx context.Context, peerID, ownerID string, ttl time.Duration) (Lease, error)
AcquireLease serializes one peer's executor across processes. Expired work becomes blocked for explicit recovery; acquiring never replays a started run.
func (*Store) Authenticate ¶
func (*Store) AuthenticateScoped ¶
func (s *Store) AuthenticateScoped(ctx context.Context, token string) (Peer, context.Context, error)
AuthenticateScoped binds only the authenticated actor and credential hash to request context. Token bytes never enter downstream metadata or errors.
func (*Store) Await ¶
func (s *Store) Await(ctx context.Context, peerID, messageID string, afterRevision int64) (Message, error)
Await waits for a newer durable revision or a terminal result. The caller supplies a bounded context; cancellation never claims or cancels the task.
func (*Store) BeginTaskUsage ¶
func (*Store) BindSession ¶
BindSession is a trusted application operation. Both records must exist and identify the same canonical workspace. A live peer cannot be retargeted to another conversation by changing model-visible metadata.
func (*Store) BindSessionTransport ¶
func (s *Store) BindSessionTransport(ctx context.Context, sessionID string, remote Peer, endpoint, credentialFile string) (SessionTransport, error)
BindSessionTransport requires an already verified same-hub authenticated peer snapshot. Application caller owns session admission and rebuilds its cache.
func (*Store) CallbackDeliveries ¶
func (*Store) CallbackSubscriptions ¶
func (*Store) CancelCallback ¶
CancelCallback revokes delivery; it never cancels the underlying agent work.
func (*Store) CheckOwnedPaths ¶
func (*Store) CheckTaskUsage ¶
CheckTaskUsage revalidates the live execution and records review evidence once per exhausted/unknown budget. Limits gate subsequent calls, not provider bills or requests already in flight on another peer.
func (*Store) Claim ¶
Claim atomically starts one pending message. Started messages are not automatically reclaimed after a crash: replaying a partially executed tool task could duplicate its side effects. Recovery inspects its durable state.
func (*Store) ClaimLease ¶
func (*Store) ClearSessionTransport ¶
func (*Store) CompleteLease ¶
func (s *Store) CompleteLease(ctx context.Context, lease Lease, messageID string, payload json.RawMessage) (Message, error)
CompleteLease atomically finishes a claimed run and, for a request, accepts its correlated answer. Failure cannot publish an answer without completion. Notification messages finish without generating an endless reply cycle.
func (*Store) ConfigureSessionPeer ¶
func (s *Store) ConfigureSessionPeer(ctx context.Context, anchorSession, targetSession, endpoint string, capabilities []string, deliver func(string) error) (Peer, error)
ConfigureSessionPeer is a trusted operator control, never a model tool. Both identities must already have validated persisted session bindings in the same project. Delivery of the new credential must succeed before its hash commits. The callback must keep the credential private and remove its file on error.
func (*Store) ConfigureSessionPeerWithTTL ¶
func (s *Store) ConfigureSessionPeerWithTTL(ctx context.Context, anchorSession, targetSession, endpoint string, capabilities []string, ttl time.Duration, deliver func(string) error) (Peer, CredentialMetadata, error)
ConfigureSessionPeerWithTTL is trusted provisioning. TTL uses database time; legacy credentials remain NULL-expiry, never silently shortened or deleted.
func (*Store) ContractReadiness ¶
func (s *Store) ContractReadiness(ctx context.Context, peerID, id string) (ContractReadiness, error)
ContractReadiness reports protocol agreement, never task execution or shipped acceptance. The caller must acknowledge the queried revision; each dependency is pinned and acknowledged by its dependent contract owner, recursively.
func (*Store) ContractRevision ¶
func (s *Store) ContractRevision(ctx context.Context, peerID, id string, revision int64) (ContractSpec, error)
ContractRevision reads an immutable prior agreement under the same project authorization as the current contract, for explicit compatibility review.
func (*Store) Correspondence ¶
func (s *Store) Correspondence(ctx context.Context, peerID, beforeID string, limit int) (CorrespondencePage, error)
Correspondence pages all durable states, newest first. The immutable creation-time/UUID cursor prevents status updates from moving items between pages. A cursor outside this peer's correspondence is rejected.
func (*Store) CreateContract ¶
func (*Store) DeleteContract ¶
func (*Store) DisablePeer ¶
DisablePeer revokes every credential and prevents further reads/changes. This is an application/admin operation, not a model-visible operation.
func (*Store) DispatchBindings ¶
DispatchBindings pages only peers with outstanding work. The keyset stays stable while another worker finishes messages or creates new peer bindings.
func (*Store) Events ¶
Events replays only this peer's correspondence after a project cursor. A cursor remains valid over restart and does not acknowledge execution.
func (*Store) ExternalClaim ¶
ExternalClaim/ExternalTransition are manual ingress controls, not remote worker leases. Any existing worker ownership requires its explicit release or recovery before manual processing. Callers hold admission then peer lock, which also fences AcquireLease; no check-then-mutate race is introduced.
func (*Store) ExternalReply ¶
func (*Store) ExternalSend ¶
func (*Store) ExternalTransition ¶
func (*Store) FinishTaskUsage ¶
func (*Store) Graph ¶
func (s *Store) Graph(ctx context.Context, viewerPeerID, messageID string, limit int) (DependencyGraph, error)
Graph returns the root and its prerequisite ancestry from one database snapshot. Payload-free envelopes are participant-only. For a prerequisite named by a visible envelope, its state is intentionally available as blocker metadata; inaccessible envelopes and their ancestry are never traversed or returned. Readiness is dependency readiness, not execution admission or provider health.
func (*Store) Inbox ¶
Inbox includes started/blocked work so a restarted worker can present an interrupted task for recovery instead of silently executing it again.
func (*Store) ListContracts ¶
func (*Store) LocalPeersForSession ¶
LocalPeersForSession lists explicitly configured peers in the bound scope. Only opted-in repository sessions can inventory across linked worktrees; unregistered and default sessions retain the canonical workspace boundary.
func (*Store) MessageEvents ¶
func (*Store) PeerForSession ¶
func (*Store) Peers ¶
Peers exposes only enabled peers from the caller's project. Credentials and their hashes never enter this result or model-visible discovery metadata.
func (*Store) PendingCount ¶
PendingCount can drive application wakeups without claiming or replaying work.
func (*Store) PublishRuntimePresence ¶
func (s *Store) PublishRuntimePresence(ctx context.Context, observer string, observations []RuntimeObservation) error
PublishRuntimePresence is application-only. Models and RPC clients cannot supply observations. The caller serializes snapshots for its unique observer. Snapshot replacement and expiry cleanup commit together using database time.
func (*Store) Read ¶
Read deliberately returns not-found for messages outside the authenticated peer's correspondence so arbitrary IDs reveal no other project's activity.
func (*Store) ReadContract ¶
func (*Store) ReadEscalations ¶
func (*Store) ReconcileExecutionContracts ¶
func (s *Store) ReconcileExecutionContracts(ctx context.Context, lease Lease, messageID string) error
ReconcileExecutionContracts records agreement invalidation even when a run ended with a tool error, cancellation, or another failure rather than output. Existing blocked/terminal decisions are preserved; repeated finalization does not duplicate their events or review escalations.
func (*Store) ReconcileTaskUsage ¶
func (s *Store) ReconcileTaskUsage(ctx context.Context, peerID string, in ReconcileTaskUsageInput) (ReconcileTaskUsageResult, error)
ReconcileTaskUsage is a trusted application control. Its values are manual attestations, never provider reports or independently verified invoices.
func (*Store) RecordTaskUsage ¶
func (*Store) RecoverExternal ¶
RecoverExternal uses existing fenced recovery: live owners refuse admission, expired started work becomes blocked exactly once and is never replayed. An operator must stop local delivery before switching to manual processing.
func (*Store) RegisterPeer ¶
func (*Store) RegisterRepositorySessionPeer ¶
func (s *Store) RegisterRepositorySessionPeer(ctx context.Context, sessionID, name, role string) (Peer, error)
RegisterRepositorySessionPeer explicitly joins peers in linked worktrees of the same canonical Git common directory. Existing bindings never change scope.
func (*Store) RegisterSessionPeer ¶
func (s *Store) RegisterSessionPeer(ctx context.Context, sessionID, name, role string) (Peer, error)
RegisterSessionPeer is an authenticated application operation. Peer creation and immutable session binding commit together, including concurrent retries. Local tools need no bearer credential; no unused external credential is made.
func (*Store) RemoveRuntimeObserver ¶
func (*Store) RenewLease ¶
func (*Store) RepositoryInfoForSession ¶
func (s *Store) RepositoryInfoForSession(ctx context.Context, sessionID string) (RepositoryInfo, error)
RepositoryInfoForSession returns validated trusted local metadata only for an explicitly repository-scoped binding. Unregistered/workspace chats are absent.
func (*Store) RetryCallback ¶
RetryCallback explicitly resumes a dead-letter with the same stable identity.
func (*Store) ReviewRequest ¶
func (s *Store) ReviewRequest(ctx context.Context, peerID string, in ReviewRequestInput) (ReviewRequestResult, error)
ReviewRequest changes limits and requeues one blocked request atomically. It never starts execution, resets usage, erases uncertainty, or renews deadlines. The next worker claim still applies dependency, agreement and attempt gates.
func (*Store) RevokePeerCredential ¶
func (s *Store) RevokePeerCredential(ctx context.Context, anchorSession, targetSession, token string) error
RevokePeerCredential is trusted operator administration, not peer ingress or a model tool. Retiring one key never disables the peer or its replacement.
func (*Store) RotateCallbackKey ¶
RotateCallbackKey recovers a lost setup response without replaying agent work. Generation fencing prevents an old in-flight worker from acknowledging after rotation; retries preserve the exact delivery ID and body. Receivers should install the new secret then explicitly retry any authentication dead-letter.
func (*Store) RuntimePresenceForPeers ¶
func (s *Store) RuntimePresenceForPeers(ctx context.Context, ids []string) (map[string]RuntimePresence, error)
RuntimePresenceForPeers is a bounded internal read. Callers derive IDs from their authenticated workspace inventory, never an arbitrary client argument.
func (*Store) Send ¶
Send persists acceptance before returning a handle. fromPeer comes from the authenticated application boundary, not a user-supplied payload field.
func (*Store) SendWithBudget ¶
func (s *Store) SendWithBudget(ctx context.Context, peer string, input SendInput, limits UsageLimits) (Message, error)
SendWithBudget is an application control, deliberately absent from model SendInput. Limits are committed in the same transaction as the first request.
func (*Store) SessionTransport ¶
func (*Store) SubscribeCallback ¶
func (*Store) Transition ¶
func (s *Store) Transition(ctx context.Context, peerID, messageID string, expectedRevision int64, eventType string, payload json.RawMessage) (Message, error)
Transition records status or progress together with its replayable event. Only the recipient reports work; either correspondent may cancel. Revisions prevent a delayed progress report from undoing completion or cancellation.
func (*Store) UpdateContract ¶
func (*Store) UsageForMessage ¶
UsageForMessage is participant-filtered, even when a task spans conversations.
func (*Store) UsageReconciliationCandidates ¶
func (s *Store) UsageReconciliationCandidates(ctx context.Context, peerID, messageID, afterID string, limit int) (UsageReconciliationCandidatePage, error)
UsageReconciliationCandidates discovers metadata only. A known root message selects the scope; callers cannot supply a project or arbitrary task owner.
func (*Store) UsageReconciliationForMessage ¶
func (*Store) WithOwnedPaths ¶
func (s *Store) WithOwnedPaths(ctx context.Context, peerID string, paths []string, fn func(context.Context) error) error
WithOwnedPaths holds the same project advisory lock as contract mutation until fn returns. Callback side effects are not rolled back by PostgreSQL; the lock prevents claim changes during this synchronous operation. Callbacks must not recursively call contract APIs on another database connection.
func (*Store) WithUnrestrictedWorkspace ¶
func (s *Store) WithUnrestrictedWorkspace(ctx context.Context, peerID string, fn func(context.Context) error) error
WithUnrestrictedWorkspace permits opaque effectful tools when every foreign project reservation is in a physically disjoint registered workspace. Same or nested roots remain blocked, including disabled owners' reservations. This application-level guard holds the project lock through fn; it does not sandbox arbitrary commands or prevent filesystem changes outside that lock.
type TaskUsage ¶
type TaskUsage struct {
OwnerPeerID string `json:"owner_peer_id,omitempty"`
PendingExecutions int64 `json:"pending_executions"`
UnconfirmedExecutions int64 `json:"unconfirmed_executions"`
Scope string `json:"scope"`
TaskID string `json:"task_id,omitempty"`
Limits UsageLimits `json:"limits"`
InputTokens int64 `json:"input_tokens"`
OutputTokens int64 `json:"output_tokens"`
CachedInputTokens int64 `json:"cached_input_tokens"`
EstimatedCostUSD float64 `json:"estimated_cost_usd"`
UnknownUsage int64 `json:"unknown_usage"`
UnknownPrice int64 `json:"unknown_price"`
Revision int64 `json:"revision"`
RequiresReview bool `json:"requires_review"`
Reason string `json:"reason,omitempty"`
}
type TransportExecution ¶
type TransportExecution struct {
MessageID string `json:"message_id"`
OwnerID string `json:"owner_id"`
Capability string `json:"capability"`
}
TransportExecution is a private runtime envelope, never a model tool field or response. The random capability is stored only as a hash beside the live lease.
func ExecutionTransportProof ¶
func ExecutionTransportProof(ctx context.Context) *TransportExecution
type UsageJournalRun ¶
type UsageLimits ¶
type UsageReconciliationCandidate ¶
type UsageReconciliationCandidate struct {
UnknownUsage int64 `json:"unknown_usage"`
UnknownPrice int64 `json:"unknown_price"`
MessageID string `json:"message_id"`
MessageRevision int64 `json:"message_revision"`
State State `json:"state"`
PendingExecutions int64 `json:"pending_executions"`
UnconfirmedExecutions int64 `json:"unconfirmed_executions"`
CanReconcile bool `json:"can_reconcile"`
Reason string `json:"reason"`
}
type UsageReconciliationCandidatePage ¶
type UsageReconciliationCandidatePage struct {
Scope string `json:"scope"`
Candidates []UsageReconciliationCandidate `json:"candidates"`
NextCursor string `json:"next_cursor"`
Truncated bool `json:"truncated"`
}
type UsageReconciliationRecord ¶
type UsageReconciliationRecord struct {
ReconciliationID string `json:"reconciliation_id"`
MessageID string `json:"message_id"`
ActorPeerID string `json:"actor_peer_id"`
Basis string `json:"basis"`
Reason string `json:"reason"`
Evidence string `json:"evidence"`
Provenance string `json:"provenance"`
Before UsageReconciliationTotals `json:"before"`
After UsageReconciliationTotals `json:"after"`
CreatedAt time.Time `json:"created_at"`
}
type UsageReconciliationSnapshot ¶
type UsageReconciliationSnapshot struct {
MessageID string `json:"message_id"`
MessageRevision int64 `json:"message_revision"`
UsageRevision int64 `json:"usage_revision"`
Scope string `json:"scope"`
OwnerPeerID string `json:"owner_peer_id"`
JournalFingerprint string `json:"journal_fingerprint"`
CanReconcile bool `json:"can_reconcile"`
Reason string `json:"reason"`
Runs []UsageJournalRun `json:"runs"`
RunCount int64 `json:"run_count"`
RunsTruncated bool `json:"runs_truncated"`
Samples []UsageSampleEvidence `json:"samples"`
SampleCount int64 `json:"sample_count"`
SamplesTruncated bool `json:"samples_truncated"`
Observed UsageReconciliationTotals `json:"observed"`
Contribution UsageReconciliationTotals `json:"contribution"`
KnownCostFloorUSD float64 `json:"known_cost_floor_usd"`
Previous []UsageReconciliationRecord `json:"previous"`
PreviousCount int64 `json:"previous_count"`
PreviousTruncated bool `json:"previous_truncated"`
// contains filtered or unexported fields
}
type UsageReconciliationTotals ¶
type UsageReconciliationTotals struct {
InputTokens int64 `json:"input_tokens"`
OutputTokens int64 `json:"output_tokens"`
CachedInputTokens int64 `json:"cached_input_tokens"`
EstimatedCostUSD float64 `json:"estimated_cost_usd"`
UnknownUsage int64 `json:"unknown_usage"`
UnknownPrice int64 `json:"unknown_price"`
}
type UsageSample ¶
type UsageSampleEvidence ¶
type UsageSampleEvidence struct {
Key string `json:"key"`
InputTokens int64 `json:"input_tokens"`
OutputTokens int64 `json:"output_tokens"`
CachedInputTokens int64 `json:"cached_input_tokens"`
EstimatedCostUSD float64 `json:"estimated_cost_usd"`
UsageKnown bool `json:"usage_known"`
PriceKnown bool `json:"price_known"`
}
Source Files
¶
- budgets.go
- callback_store.go
- callback_transport.go
- callback_worker.go
- contract_guards.go
- contract_readiness.go
- contracts.go
- credential_expiry.go
- dependencies.go
- dispatcher.go
- execution.go
- external.go
- lease.go
- lifecycle.go
- local_peers.go
- peer_metadata.go
- peer_transport.go
- presence.go
- query.go
- repository_identity_unix.go
- repository_scope.go
- request_contracts.go
- request_review.go
- session.go
- session_transport.go
- store.go
- transport_execution.go
- types.go
- usage.go
- usage_reconciliation.go
- usage_reconciliation_candidates.go
- usage_reconciliation_types.go