store

package
v0.0.0-...-b842323 Latest Latest
Warning

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

Go to latest
Published: Nov 10, 2026 License: Apache-2.0 Imports: 30 Imported by: 0

README

Factory PostgreSQL store

store owns Factory's PostgreSQL schema and typed row operations, including retained appliance compatibility. Native startup uses OpenStandaloneContext: new schema-94 profiles contain Factory/collaboration records and native workspace references, without appliance users, development keys, Projects, memberships, identity custody or application hosting. Open/OpenContext create the appliance composition and refuse a standalone database. Supported retained databases keep their recorded components and rows; opening never removes legacy data. Product APIs own user actions and Go owns the transactions; Rust owns PostgreSQL lifetime.

In new standalone profiles, setup decisions, heads and preparations reference factory_native_workspaces directly and require native ownership. Appliance maintenance holds apply only to appliance Projects; native preparation admission checks the current native decision heads and captured setup. Feed observations resolve the recorded workspace to the canonical repository. Read-only observers load the same component selection and integrity verification.

In retained shared profiles, the preparation journal's generated appliance_project_id reference enforces the Project foreign key only for appliance preparations; a native preparation carries its captured workspace owner instead of fabricating an appliance Project. Existing immutable-kind/ owner/retirement guards still apply. Opening retained databases upgrades the reference under the existing schema lock without rewriting preparation records. This reference establishes storage ownership, not runtime readiness or dispatch authority; current capability/preparation/placement gates remain independent.

Application administration uses canonical application.Record references. CreateApplication persists an operator-admitted administrator grant and an unknown initial native state. ReplaceApplication serializes revision CAS and retains immutable prior specs for recovery. ObserveApplication requires both the exact current references and the expected prior observation; a nil result records uncertainty. The store reserves distinct app hostnames, loopback ports and private data identities. Canlang keeps its descriptor, application users, credentials and binding configuration; none are copied into these records.

Open the production store

The dashboard loads the DSN from its restricted database_dsn_file and uses:

db, err := store.Open(dsn)

Handle the error before using db and call db.Close() when its owner shuts down. Opening connects through the PostgreSQL driver, initializes an empty database, or validates an existing current schema. It refuses an unversioned nonempty database or an incompatible schema; it does not silently migrate those states. The identity broker exclusively owns the separately provisioned encryption key and encrypted credentials.

The database role needs access to the selected database and permission to create the schema on first initialization. OpenEncrypted is reserved for isolated Go encrypted credential fixtures; the production identity broker uses its separate Rust store. SchemaVersion() reports the source's current schema format without connecting.

Format 104 preserves explicit review-only continuations and completed-review submission retries. Its transactional 103→104 migration extends only the retry-unsent-review command's payload bound to 2 MiB; fresh databases use the same constraint. Historical constraints are checked before replacement. Command payloads, outcomes, dispatch reservations and uncertain effects are not rewritten, and an older application must refuse the new marker before opening adapters.

Consume typed records

API area Examples
Users and saved keys UpsertUser, User, key inventory and confirmed removal.
Projects and members CreateProject, Project, ProjectByRepository, Join.
Preparation and grants Recorded input decisions, approvals and revision-checked authority.
Factory ledger FactoryRun, FactoryRuns, FactoryCommand, assignments, reservations, usage and publication/merge records.
Collaboration registry PutCollaborationHost, ObserveCollaborationRepository, ObserveCollaborationActor, ObserveCollaborationTeam, account/profile/runtime bindings; canonical records in internal/collaboration.

The collaboration registry is added transactionally without rewriting workflow history or changing its core schema version. Storage opening does not initialize a provider namespace. New native composition explicitly initializes an empty ledger before numeric mapping; retained Fountain ledgers use AdoptFountainLedger with their configured source, preserving IDs/history and reserving the new allocator ranges atomically. The running appliance's neutral identity/admission cutover remains T02/T03 work. Registry records and repository/connection associations do not grant authority. Team identities occupy their own host-scoped namespace, with opaque external IDs and mutable names. Opening an existing registry adds its team table and identity/ allocation guards under the existing schema-marker lock; workflow format and retained identities/commands stay intact. An existing table with missing or disabled guards refuses opening. Team observation requires ledger adoption; host-scoped lookups never allocate or infer membership/permission.

For example, an integration reads a recorded run with run, err := db.FactoryRun(ctx, runID). Use errors.Is(err, store.ErrNotFound) for an absent row. ErrCommandConflict signals a reused command identity with different content; ErrGrantKey signals missing or incorrect encryption input. ErrLastKeyConfirmationRequired preserves the explicit final-key removal gate.

Persistence boundaries

OwnContributions reserves a dedicated PostgreSQL session and advisory lock for a contribution producer. Its ContributionOwner claims and settles on that same session, retaining a private owner ID beside the existing assessment. Always close the owner before closing Store; closing discards its session rather than returning a held session lock to the pool. Session loss fences late settlement. RecoverContributionReviews(ctx, after) traverses at most 32 owned pending rows per page, returning Next, Complete and a recovered count. Acquiring the released producer's lock permits only an unavailable assessment, preserving its receipt without invitation or replay. Live owners and historical claims without ownership evidence remain unchanged. This requires no schema migration or second journal; server startup/progress composition owns when recovery runs.

Typed methods enforce record validity, transactions and their stated revision conditions. Store writes do not provision accounts, start containers, retire native processes or prove Forgejo effects. The coordinator and host boundaries perform those operations and persist their evidence here. Keep product SQL in this package; consumers use its exported records and methods.

CaptureHumanIssueCreate saves plain human issue intent and its exact provider preparation in factory_commands before dispatch. It requires an adopted ledger and canonical repository/actor mappings from the captured host. Concurrent equal requests return the winning original capture; callers dispatch that returned capture, retaining its namespace, operation and preparation rather than refreshing them on retry. HumanIssueCreateCapture recovers by the exact admitted request; changed title/body/scope or a reused command of another kind conflicts. These capture methods perform no provider I/O and record no outcome. Current human admission and receipt interpretation belong to the adapter/shared application. ObserveHumanIssueCreate locks the existing command row, checks exact capture binding and advances validated observations through the shared atomic-command outcome rules. Stale absence cannot erase terminal evidence; a changed receipt or contradictory terminal primary refuses. Only a known primary with complete bookkeeping finishes; committed completion needing intervention stays open. CaptureHumanLock and HumanLockCapture retain the exact issue/PR target, requested lock state and reason with the original opaque provider preparation. They use the same adopted-ledger, same-host repository/actor binding and immutable command journal. Identical requests converge on the winning capture; changed state/reason/scope or another command kind conflicts. Capture performs no provider I/O and records no outcome. ObserveHumanLock now saves validated adapter observations under the same command row lock, checking complete capture binding and reusing the shared monotonic outcome rules. Stale absence cannot erase terminal facts; contradictory primary evidence or changed receipt refuses. Only a proved completed primary/no-effect finishes the command. Live admission and provider source authentication remain the adapter/application boundary. Schema 74 transactionally extends the existing 2 MiB capture allowance to discussion.lock.apply; comment/edit/issue-creation bounds, ordinary 8192-character command bounds, immutable command guards and retained records are preserved. Known upgrades chain through 73-to-74 under the existing open transaction. The development-copy SQL emitter consumes the same owning DDL without connecting to a database.

CaptureHumanState and HumanStateCapture retain the admitted issue/PR target and desired closed state with byte-exact opaque preparation, authority namespace and operation ID. They require an adopted ledger and same-host repository/actor mapping. Concurrent identical requests return the original winning capture; changed intent/scope and command-kind collisions conflict. They perform no provider I/O and record no outcome. State capture uses the existing ordinary 8192-byte command bound and needs no additional schema allowance. Native PostgreSQL checks cover full 4096-byte preparation, the SDK-produced maximal request shape, retained prior command kinds, clean restart and actual process-death/WAL recovery. ObserveHumanState now saves validated adapter observations under the existing command row lock, checking exact capture binding and shared monotonic outcome rules. Stale unknown/absence cannot erase terminal facts; contradictory primary evidence or replaced receipt refuses. A committed primary needing completion intervention stays unfinished, including after Store reopen. Live authority and provider evidence authentication remain with the Application and adapter.

CaptureHumanReview and HumanReviewCapture retain canonical PR draft/final intent with exact prose and opaque provider preparation. They require the adopted same-host ledger and reuse the existing immutable journal; identical concurrent requests return the original winning capture, while changed event/prose/scope or command kind conflicts. Capture performs no provider I/O or outcome inference. Schema 75 transactionally adds pull_request.review.submit to the existing 2 MiB capture allowance, with 64 KiB canonical prose and 512 KiB provider preparation. Older command limits and guards stay intact. Native PostgreSQL checks qualify schema-74 upgrade, exact large captures, retained previous commands, restart and actual process-death/WAL recovery. The development-copy SQL consumes the same DDL and qualifies real upgrade/replay plus refusal to run on the native database.

ObserveHumanReview now saves validated adapter observations under the existing command row lock, checks exact capture equality and advances shared monotonic outcomes. Stale unknown/absence/pending cannot erase terminal evidence; changed receipt or contradictory terminal effect refuses. Only a proved completed primary or no-effect finishes the command; native completion needing intervention stays open across Store reopen. Current admission and provider authentication remain the Application and adapter responsibility.

CaptureHumanInline and HumanInlineCapture retain draft/immediate PR inline intent, the complete immutable base/head/path/side/scope/range anchor, exact prose and opaque provider preparation. They require the adopted same-host ledger and reuse the immutable command journal. Concurrent identical requests return the original winning capture; changed intent or anchors and command-kind collisions refuse. Capture performs no provider I/O and infers no outcome. Dispatch must use the returned capture; current admission remains the caller's responsibility. Schema 76 transactionally adds pull_request.review.comment.create to the explicit 2 MiB capture allowance, with 64 KiB canonical prose and 512 KiB provider preparation. Prior command limits and retained captures remain intact. Real native PostgreSQL checks cover upgrade from 75, concurrent winners, exact replay, restart and process-death/WAL recovery. The development-copy emitter uses the same DDL; its generated SQL upgrades/replays only on soda_dev and refuses the native database.

CaptureHumanThread and HumanThreadCapture retain human resolve/unresolve intent, an opaque thread ID and the full original anchor or explicit unknown context. The adopted same-host ledger and immutable command journal enforce canonical identity binding. Concurrent identical requests return the original winning preparation; changed thread/state/context/scope or command kinds refuse. Capture performs no provider I/O and infers no outcome. Schema 77 transactionally adds a 128 KiB allowance only for pull_request.review.thread.resolve, with 64 KiB opaque preparation; previous large/small command limits remain intact. Native PostgreSQL checks qualify schema-76 upgrade, exact replay/concurrent winners, restart and WAL recovery. The development-copy emitter uses the same DDL and qualifies upgrade/replay on its isolated soda_dev database while refusing the native database.

ObserveHumanThread now persists validated adapter observations under the existing command row lock, checks the exact immutable capture and advances shared monotonic outcomes. Stale unknown/absence/pending cannot erase terminal evidence; changed receipt bytes, binding or contradictory terminal effects refuse. Only proved complete primary/no-effect results finish a command. A committed native primary awaiting bookkeeping retains its exact receipt across Store reopen and finishes only after admitted completion read-back. No network runs inside SQL.

CaptureHumanReviewRequest and HumanReviewRequestCapture retain user/team reviewer desired state, exact opaque preparation, authority namespace and operation ID. The ledger must be adopted; operator, repository and selected user/team must resolve on the same host. This proves identity binding, never membership or access. Concurrent identical requests return the original winning capture. Changed scope, reviewer kind/identity or desired state conflicts; no provider I/O or outcome is inferred. Schema 78 extends the 128 KiB allowance to pull_request.review.request while retaining all earlier command limits and immutable update guards. The transactional schema-77 upgrade and development-copy emitter share the defining DDL. Native PostgreSQL checks cover exact bytes, maximal SDK evidence and 64 KiB preparation, concurrent winners, wide user/team IDs, retained commands, restart and WAL recovery. The admitted Fountain adapter consumes this capture.

CaptureHumanMerge and HumanMergeCapture retain canonical merge/manual-mark method, message/selected commit and exact opaque preparation in the same command ledger. Adoption and same-host repository/operator bindings are required. A retry returns the winning authority/operation/preparation without refreshing it; changed human intent or command-kind reuse conflicts. No provider I/O or outcome is inferred. Schema 79 extends the 2 MiB command allowance to pull_request.merge for the 64 KiB message plus 1 MiB opaque preparation, preserving prior bounds and immutable guards. The schema-78 upgrade and development-copy SQL share one DDL owner. Actual PostgreSQL checks cover wide string IDs, exact bytes, concurrency, rollback, retained commands, restart and owned-server WAL recovery.

CaptureHumanPullCreate and HumanPullCreateCapture retain exact human PR creation intent and opaque provider preparation in the same command ledger. Adoption and same-host base/source repository and actor bindings are required. Repeated/concurrent requests recover the original winning authority, operation and preparation; changed intent or command kind conflicts. Capture performs no provider I/O and infers no outcome. Schema 80 extends the existing 2 MiB payload allowance to pull_request.create, preserving prior bounds and immutable guards. The schema-79 upgrade and development-copy emitter share one DDL owner. Actual PostgreSQL checks cover wide IDs, exact writing, concurrency, rollback, retained merge captures, restart, WAL recovery and development-copy replay/refusal. ObserveHumanPullCreate now validates the exact capture under the command-row lock and saves bounded monotonic results with the existing atomic human-command ordering. Confirmed effects and receipt bytes survive stale/overlapping replies; contradictory effects or changed bindings/receipts refuse. Only known effects with complete native bookkeeping finish the command. Actual admitted SDK results, including pending/intervention and early cancellation, survive PostgreSQL restart and WAL recovery. The admitted Fountain adapter now authenticates provider preparation/receipts before projection and persistence. Application now composes the admitted writer with capture-before-dispatch and this outcome owner, recovering original source/writing for scoped cleanup without another preparation. Shared HTTP now consumes this Application path; installed UI follows. No network runs in SQL.

ObserveHumanMerge validates the exact immutable capture and saves canonical merge/manual outcomes under the existing command-row lock, using the shared atomic human-command ordering. Stale absence/unknown/pending replies cannot erase known effects or receipts; changed bindings, receipt bytes and contradictory terminal effects refuse. Outcomes remain bounded to 64 KiB. Only known effects with complete native bookkeeping finish the command; pending completion and intervention remain open. Actual admitted native SDK results and receipts survive PostgreSQL restart and owned-server WAL recovery. The admitted Fountain adapter now authenticates provider evidence before projection. Application composes that admitted writer with capture-before-dispatch and monotonic observation persistence. Shared HTTP now consumes this Application path; installed UI remains subsequent work. No network runs in SQL.

ObserveHumanReviewRequest now saves validated adapter observations under the existing command-row lock, requiring the exact immutable capture. It retains terminal evidence against stale absence/unknown/pending replies, rejects changed receipt bytes/bindings and contradictory terminal effects, and bounds the saved outcome to 64 KiB. A committed effect awaiting native completion or intervention remains unfinished; only proved complete primary/no-effect results finish the command. Real native user/team/no-op/remove outcomes, complete 1,000-record receipts, overlapping replies and exact retained captures/outcomes survive native PostgreSQL restart and WAL recovery. The store validates journal binding; admitted provider evidence authentication and current human access remain adapter/Application responsibilities. No network runs inside SQL. Application.HumanReviewRequests now consumes capture/observation persistence, reconciling saved commands under live admission and recovering original selection for scoped cleanup. Shared HTTP/Product and Fountain composition now consume this service; installed UI follows.

ObserveHumanInline saves validated adapter observations under the existing command row lock, requiring the complete capture and canonical intent binding. It reuses the shared human-command ordering: stale unknown/absence/pending cannot erase terminal facts, changed receipt or contradictory terminal effect refuses, and completion needing intervention remains unfinished. Only proved complete primary/no-effect outcomes finish a command. Provider authentication and current admission remain with the adapter and Application.

SavedIntentRevision reads the existing immutable revision row through its current request owner and exact intent/revision identity. It returns the captured record independently of head position and bounded history without changing rows or introducing another journal. Service/HTTP callers own current admission and comparison with their retained save input; absence cannot exclude an in-flight save.

OpenEphemeral creates a disposable PostgreSQL database for integration fixtures and returns its cleanup function. It requires a suitable fixture superuser DSN; it is separate from opening the appliance store.

See service configuration, operator setup, database backup/restore, and Go persistence ownership.

Issue-intake grants are bounded opaque provider JSON bound to an admitted source scope. The store owns exact semantic issue-maker retries/slots, not provider claim parsing or bearer attachment. Its production dependency closure is now SDK-free. See the intake boundary and evidence.

RetryIssueMakerFeedPostCommand atomically records the exact retry identity and scoped receipt in factory_commands with the existing post/intake transition. Its replay flag distinguishes a historical receipt from a newly committed retry; replay never resets later attempts or replaces newer writing. Changed command reuse conflicts, and refused transitions leave no new command row. This includes the applied-draft retry that deliberately retains its post revision. Serving callers must check current visibility and authorship before either first dispatch or replay. The receipt covers only storage, not proof capture or external work. The shared service/HTTP consumes this journal and serves read-only scoped receipt lookup. NotePostContextWait binds capture-failure metadata to its exact current revision and refuses when context already exists. Shared UI pending-command recovery follows in the implementation queue.

Documentation

Overview

Package store owns Factory's PostgreSQL schema and retained appliance row operations. It is not an HTTP API, host runtime or generic SQL escape hatch for other packages.

Index

Constants

View Source
const (
	// SetupRenewTTLSeconds re-arms an expired reservation for one fresh
	// creation window, the same length the initial admission grants.
	SetupRenewTTLSeconds = 30 * 60
	// SetupRenewGraceSeconds bounds renewal after expiry. Past this window
	// the reservation stays retained but unrecoverable by design: no
	// supported path resets it onto a fresh setup.
	SetupRenewGraceSeconds = 24 * 60 * 60
	// MaxSetupRenews finitely bounds operator re-arms per setup.
	MaxSetupRenews = 3
)
View Source
const (
	// TableFactoryCompletions is the unique completion-event owner.
	TableFactoryCompletions = "factory_completions"
	// TableFactoryReassessments is the immutable-cycle owner.
	TableFactoryReassessments = "factory_reassessments"
)
View Source
const (
	ConsultationStatusPending     = "pending"
	ConsultationStatusReturned    = "returned"
	ConsultationStatusFailed      = "failed"
	ConsultationStatusUnavailable = "unavailable"
	ConsultationStatusUncertain   = "uncertain"
)
View Source
const (
	PlanTaskPending     = "pending"
	PlanTaskRunning     = "running"
	PlanTaskOutputReady = "output_ready"
	PlanTaskCompleted   = "completed"
	PlanTaskFailed      = "failed"
	PlanTaskCancelled   = "cancelled"
)

Admitted plan task states. Tasks advance pending → running → output_ready → completed, or stop as failed/cancelled; FW14 executes against these.

View Source
const ApplicationBuildsDDL = `` /* 414-byte string literal not displayed */

Packaging owns bytes; setup and replacement own app identity and data. A verified build can therefore exist before any application claims its origin.

View Source
const ApplicationRestoresDDL = `` /* 263-byte string literal not displayed */
View Source
const ApplicationSetupRenewalsDDL = `` /* 292-byte string literal not displayed */

ApplicationSetupRenewalsDDL audits every expired-setup renewal. Each row re-arms the retained reservation once; the row count finitely bounds renewals per setup without touching the canonical setup record.

View Source
const ApplicationSetupsDDL = `` /* 390-byte string literal not displayed */
View Source
const DefaultPriorityComparisons = 5

DefaultPriorityComparisons is the comparison page size when the caller names no bound.

View Source
const FactoryCompletionDeleteTrigger = `` /* 141-byte string literal not displayed */
View Source
const FactoryCompletionTriggers = `` /* 141-byte string literal not displayed */

FactoryCompletionTriggers freezes recorded history: completion events never change, and cycle rows are never deleted. FW31 owns the reassessment state guard; no trigger here invents it.

View Source
const FactoryCompletionsDDL = `` /* 531-byte string literal not displayed */

FactoryCompletionsDDL creates the unique completion-event table. The (repository, generation) primary key orders events per repository for the pending-event fence; data carries the factory.CompletionEvent.

View Source
const FactoryMCPCapabilitiesDDL = `` /* 522-byte string literal not displayed */

FactoryMCPCapabilitiesDDL creates the capability table. data carries the factory.MCPCapability; authority_digest binds the scope without storing secret bytes.

View Source
const FactoryMCPCapabilityDeleteTrigger = `` /* 143-byte string literal not displayed */

FactoryMCPCapabilityDeleteTrigger preserves capability history: revocation and retirement move state, rows are never deleted.

View Source
const FactoryReassessmentDeleteTrigger = `` /* 145-byte string literal not displayed */
View Source
const FactoryReassessmentsDDL = `` /* 373-byte string literal not displayed */

FactoryReassessmentsDDL creates the bounded-cycle table. One row per cycle keeps sealed evidence, decision receipts, the report and the adoption cursor; data carries the factory.ReassessmentCycle plus its sealed inventory digest. Cycle rows are append-only with explicit Retry succession: updates never rewrite a sealed row, deletes never run. FW31 adds the state-transition guard its fence needs.

View Source
const FactoryStallEventsDDL = `` /* 406-byte string literal not displayed */

FactoryStallEventsDDL creates the bound-observation table. The (repository, generation, fingerprint) primary key replays a redetected round to the identical row; episode identity stays (repository, generation) by construction of the stored event. The seq column records true observation order for the standing query; R37 advances progress on verified delivery rather than reading recency into a content hash.

View Source
const FeedSummaryLimit = 512

FeedSummaryLimit bounds one record's served summary preview in runes; the full recorded content stays with its canonical owner.

View Source
const MaxHeldReservations = 1024

MaxHeldReservations bounds one held-reservation listing for dispatch occupancy and crash recovery.

View Source
const MaxIntakeDeliveries = 1024

MaxIntakeDeliveries bounds the durable webhook-delivery dedup log. Intake records each assessed delivery ID; redelivered native webhooks reuse their task UUID, so the log suppresses duplicates until pruned.

View Source
const MaxIssueControls = 2048

MaxIssueControls bounds one repository's control listing for queue views.

View Source
const MaxPriorityComparisons = 20

MaxPriorityComparisons bounds one priority comparison page; receipts can carry large candidate sets, so pages stay small.

View Source
const MaxPriorityInventorySubjects = 4096

MaxPriorityInventorySubjects keeps the D02 4,096-item ceiling. A larger membership refuses capture instead of truncating the set.

View Source
const MaxQueuedDispatch = 2048

MaxQueuedDispatch bounds one global queued-issue listing for dispatch visits. The dispatch pass visits oldest first under its own tighter bound; the store only caps the read.

View Source
const PostProductStateUnavailable = "unavailable"

PostProductChange is a read projection of the explicit review handoff. Accepted describes product scope only, not generation, verification or release; the build request it opens shows those.

PostProductStateUnavailable names an explicit unknown projection: the comment sits on the same-product lane but the read behind product_change failed.

View Source
const PriorityInventoryScanID = "current"

PriorityInventoryScanID is the single current scan. Replacement, not versioning: a changed revision or digest replaces this row and drops its candidate rows. Spent judgment receipts stay in the existing judgment ledger.

View Source
const RepositoryOpeningQuestion = "What would you like this repository to do?"
View Source
const (
	// TableFactoryStallEvents is the unique stall-event owner.
	TableFactoryStallEvents = "factory_stall_events"
)

Variables

View Source
var (
	ErrAttemptRunsPending  = errors.New("attempt runs or preparations are not confirmed settled")
	ErrAttemptRootMismatch = errors.New("assignment does not match the recorded attempt root")
)
View Source
var (
	ErrCandidatePreparationPending  = errors.New("candidate preparation retirement is not confirmed")
	ErrCandidatePreparationConflict = errors.New("candidate preparation immutable input changed")
)
View Source
var (
	ErrDispatchControlStale = errors.New("queued issue control changed during dispatch")
	ErrCapacityFull         = errors.New("appliance runs at its limit")
	ErrRepositoryFull       = errors.New("repository runs at its limit")
	ErrAllowanceExhausted   = errors.New("sponsorship allowance is exhausted")
	ErrAdmissionChanged     = errors.New("admission grants changed during dispatch")
)

Admission refusals from the atomic dispatch gate. The packet records first and the limits are rechecked inside the same transaction, so a refusal means a concurrent admission consumed the room this attempt planned against; the dispatcher waits instead of launching.

View Source
var (
	// ErrMCPCapabilityConflict reports a staged capability whose
	// immutable identity or scope differs from the recorded row.
	ErrMCPCapabilityConflict = errors.New("factory capability conflicts with the recorded scope")
	// ErrMCPCapabilityState reports a transition the recorded state
	// refuses: only staged activates, only active revokes/retires.
	ErrMCPCapabilityState = errors.New("factory capability state refuses the transition")
)
View Source
var (
	ErrMCPSubmissionFrozen             = errors.New("assignment already submitted its result; read factory.status")
	ErrMCPSubmissionCapabilityInactive = errors.New("factory capability is not active for this assignment")
	ErrMCPSubmissionCapabilityExpired  = errors.New("factory capability is expired")
	ErrMCPSubmissionAssignmentFinished = errors.New("assignment already finished")
	ErrMCPSubmissionConflict           = errors.New("submission_id already records different work; use a new identity for a different tool or payload")
)
View Source
var (
	ErrReadinessCapacity = errors.New("readiness work capacity exhausted")
	ErrReadinessPending  = errors.New("readiness work is deferred or capacity is occupied")
)
View Source
var CommandDispatchUpgradeDDL = []string{
	`ALTER TABLE factory_commands ADD COLUMN dispatch_state TEXT NOT NULL DEFAULT 'legacy_unknown' CHECK(dispatch_state IN ('unclaimed','reserved','legacy_unknown'))`,
	`ALTER TABLE factory_commands ALTER COLUMN dispatch_state SET DEFAULT 'unclaimed'`,
	commandGuardDDL,
	`UPDATE schema_version SET version=81`,
}

Existing captures have no reliable dispatch history. Conservatively fence all of them without changing their payloads or claiming an actual dispatch time.

View Source
var ErrAssignmentActive = errors.New("issue already carries an unfinished assignment")

ErrAssignmentActive reports a dispatch packet for an issue that already carries an unfinished assignment. One issue runs at most one assignment at a time; a concurrent dispatcher won this issue.

View Source
var ErrCommandConflict = errors.New("command identity reused for different content")

ErrCommandConflict reports a reused command identity with changed content.

View Source
var ErrCommandDispatchNotReady = errors.New("command dispatch requires a saved not-observed lookup")
View Source
var ErrCompletionAuthorityChanged = errors.New("completion source context no longer matches its authority")

ErrCompletionAuthorityChanged reports a source-qualified capture whose projected authority no longer equals the context the caller opened: a head, policy or verdict moved between the context read and the capture. The capture refuses with no fallback and no sealed output.

View Source
var ErrCompletionFenced = errors.New("repository completion fence is closed")

ErrCompletionFenced reports a dispatch packet for a repository whose completion fence is closed: at least one completion event has no released cycle yet. New issue investigation/implementation waits with reassessment_pending; already-running work, review/correction, cancellation and reconciliation are unaffected. Other repositories continue normally: a fence never turns the global tournament into a wait.

View Source
var ErrCompletionRetryIneligible = errors.New("completion retry is no longer admissible")
View Source
var ErrCompletionSourceHold = errors.New("completion source lacks its approved proof")

ErrCompletionSourceHold reports a source-qualified capture without its approved source proof: no standing ready preparation matches the current heads, the changed tip carries no exact approved input selection, or the changed tip has no reconciled successful coder publication and merge. The capture holds; it never seals from an unproven source.

View Source
var ErrContextResolutionIneligible = errors.New("current context resolution is no longer admissible")
View Source
var ErrDispatchClosed = errors.New("factory dispatch is closed")

ErrDispatchClosed reports a registration against withdrawn dispatch. The caller waits for an authorized resume instead of dispatching around it.

View Source
var ErrExplicitRetryIneligible = errors.New("explicit retry is no longer dispatchable")

ErrExplicitRetryIneligible identifies a refused retry, rather than a storage failure.

View Source
var ErrInvalidPostDraft = errors.New("invalid issue draft")
View Source
var ErrLastKeyConfirmationRequired = errors.New("final saved key removal requires confirmation")

ErrLastKeyConfirmationRequired means this removal would delete the user's final saved development key and its current mutation did not confirm that.

View Source
var ErrMCPAccountingTimeUnavailable = errors.New("confirmed retired run accounting time unavailable")
View Source
var ErrMergeConflict = errors.New("merge immutable input changed")

ErrMergeConflict rejects replacement of a recorded merge intent.

View Source
var ErrNativeJudgmentSource = errors.New("selected judgment source is unavailable or exhausted")
View Source
var ErrNotFound = sql.ErrNoRows

ErrNotFound is returned when a looked-up row is absent. Prefer this sentinel over importing database/sql solely for sql.ErrNoRows.

View Source
var ErrPlanConflict = errors.New("plan revision identity reused for different content")

ErrPlanConflict reports a reused (attempt_root, plan_id) identity carrying different content. Plan revisions are immutable: a replacement uses a new plan ID and moves the head pointer, so the consumed original always survives. Replaying identical content is idempotent, never a conflict.

View Source
var ErrPlanTaskTransition = errors.New("invalid plan task state transition")

ErrPlanTaskTransition reports a task state change outside the admitted lifecycle. Terminal states accept only identical replays.

View Source
var ErrPriorityInventoryTooLarge = errors.New("priority inventory exceeds its bound")

ErrPriorityInventoryTooLarge reports a membership beyond the ceiling. The pass reports an incomplete inventory; it never elects a subset.

View Source
var ErrProjectAccessHeld = errors.New("project access is held; restoration and explicit Join are required")
View Source
var ErrPublicationConflict = errors.New("publication immutable input changed")

ErrPublicationConflict rejects replacement of a recorded publication intent.

View Source
var ErrRetainedPublicationIneligible = errors.New("retained candidate publication is no longer eligible")
View Source
var ErrRunViewConflict = errors.New("run view identity reused for different content")

ErrRunViewConflict reports a reused run view identity with changed content.

View Source
var ErrStalePlanBindings = errors.New("plan bindings are stale for implementation")

ErrStalePlanBindings reports an admit against a head whose recorded source, prerequisite or preparation bindings no longer match the presented current values. The caller re-investigates instead of launching implementation from the stale plan.

View Source
var ErrStaleRevision = errors.New("stale record revision")

ErrStaleRevision reports a CAS write against a superseded grant, dispatch or decision revision. Callers refresh and retry with a new command.

View Source
var ErrTakeoverConflict = errors.New("takeover identity reused for different content")

ErrTakeoverConflict reports a reused takeover identity with changed content. The same run and destination with identical content replays.

View Source
var ErrUnknownPlanTask = errors.New("plan task is not part of the stored plan revision")

ErrUnknownPlanTask reports a task receipt for a task key the stored plan revision does not declare, or check evidence naming an unknown plan check.

View Source
var FeedPostsUpgradeDDL = []string{
	`ALTER TABLE factory_feed_comments RENAME TO factory_feed_posts`,
	`ALTER INDEX factory_feed_comments_repository RENAME TO factory_feed_posts_repository`,
	`ALTER TABLE factory_feed_comment_requests RENAME TO factory_post_intakes`,
	`ALTER TABLE factory_post_intakes RENAME COLUMN comment TO post`,
	`CREATE FUNCTION pg_temp.soda_post_data(value JSONB) RETURNS JSONB LANGUAGE plpgsql AS $$
DECLARE result JSONB;
BEGIN
 IF jsonb_typeof(value)='object' THEN
  SELECT COALESCE(jsonb_object_agg(CASE key WHEN 'comment' THEN 'source_post' WHEN 'comment_id' THEN 'post_id' WHEN 'reply_to' THEN 'parent_id' ELSE key END, pg_temp.soda_post_data(item)), '{}'::jsonb)
   INTO result FROM jsonb_each(value) fields(key,item);
  RETURN result;
 ELSIF jsonb_typeof(value)='array' THEN
  SELECT COALESCE(jsonb_agg(pg_temp.soda_post_data(item) ORDER BY position), '[]'::jsonb)
   INTO result FROM jsonb_array_elements(value) WITH ORDINALITY fields(item,position);
  RETURN result;
 END IF;
 RETURN value;
END $$`,
	`UPDATE factory_feed_posts SET data=pg_temp.soda_post_data(data)`,
	`UPDATE factory_feed_posts SET data=jsonb_set(data,'{parent_id}',to_jsonb(COALESCE(NULLIF(data->>'parent_id',''), data->'communication'->>'parent_id', data->'source'->>'id','')))`,
	`UPDATE factory_post_intakes SET data=pg_temp.soda_post_data(data)`,
	`DROP FUNCTION pg_temp.soda_post_data(JSONB)`,
	`CREATE INDEX factory_feed_posts_parent ON factory_feed_posts(repository,(data->>'parent_id'),seq)`,
	`UPDATE schema_version SET version=70`,
}

FeedPostsUpgradeDDL replaces the old communication store in place. Stable identities, revisions, budgets and native-effect receipts survive the rename. Only current feed data is converted; captured run artifacts remain unchanged.

View Source
var HumanBranchCreateDispatchUpgradeDDL = []string{
	`ALTER TABLE factory_commands DROP CONSTRAINT factory_commands_payload_check`,
	`ALTER TABLE factory_commands ADD CONSTRAINT factory_commands_payload_check CHECK((type IN ('discussion.comment.create','discussion.edit','issue.create','discussion.lock.apply','pull_request.review.submit','pull_request.review.comment.create','pull_request.merge','pull_request.create') AND octet_length(payload)<=2097152) OR (type IN ('pull_request.review.thread.resolve','pull_request.review.request') AND octet_length(payload)<=131072) OR (type='git.branch.create' AND octet_length(payload)<=32768) OR (type NOT IN ('discussion.comment.create','discussion.edit','issue.create','discussion.lock.apply','pull_request.review.submit','pull_request.review.comment.create','pull_request.merge','pull_request.create','pull_request.review.thread.resolve','pull_request.review.request','git.branch.create') AND char_length(payload)<=8192))`,
	commandGuardDDL,
	`UPDATE factory_commands SET dispatch_state='legacy_unknown' WHERE type='git.branch.create' AND dispatch_state='unclaimed' AND EXISTS(SELECT 1 FROM schema_version WHERE version=89)`,
	`UPDATE schema_version SET version=90 WHERE version=89`,
}

Preserve any earlier branch-shaped command history without inferring local dispatch ownership. A stale opener cannot fence new schema-90 captures.

View Source
var HumanCommentJournalUpgradeDDL = []string{
	`ALTER TABLE factory_commands DROP CONSTRAINT factory_commands_payload_check`,
	`ALTER TABLE factory_commands ADD CONSTRAINT factory_commands_payload_check CHECK((type='discussion.comment.create' AND octet_length(payload)<=2097152) OR (type<>'discussion.comment.create' AND char_length(payload)<=8192))`,
	`UPDATE schema_version SET version=71`,
}

HumanCommentJournalUpgradeDDL retains prepared comment JSON in the existing command journal, including base64 provider bytes and escaped 64 KiB Markdown. Other command limits and existing immutability guards remain unchanged.

View Source
var HumanEditDispatchUpgradeDDL = []string{
	commandGuardDDL,
	`UPDATE factory_commands SET dispatch_state='legacy_unknown' WHERE type='discussion.edit' AND dispatch_state='unclaimed' AND EXISTS(SELECT 1 FROM schema_version WHERE version=83)`,
	`UPDATE schema_version SET version=84 WHERE version=83`,
}

Existing edit captures have no reliable history under this local protocol. Preserve all content/conditions/outcomes while fencing that history unknown.

View Source
var HumanEditJournalUpgradeDDL = []string{
	`ALTER TABLE factory_commands DROP CONSTRAINT factory_commands_payload_check`,
	`ALTER TABLE factory_commands ADD CONSTRAINT factory_commands_payload_check CHECK((type IN ('discussion.comment.create','discussion.edit') AND octet_length(payload)<=2097152) OR (type NOT IN ('discussion.comment.create','discussion.edit') AND char_length(payload)<=8192))`,
	`UPDATE schema_version SET version=72`,
}

HumanEditJournalUpgradeDDL retains full human edit captures in the existing immutable command journal. Other commands keep their existing payload bounds.

View Source
var HumanInlineDispatchUpgradeDDL = []string{
	commandGuardDDL,
	`UPDATE factory_commands SET dispatch_state='legacy_unknown' WHERE type='pull_request.review.comment.create' AND dispatch_state='unclaimed' AND EXISTS(SELECT 1 FROM schema_version WHERE version=90)`,
	`UPDATE schema_version SET version=91 WHERE version=90`,
}

Earlier inline captures may already have reached an adapter. Preserve exact writing/selection and outcomes while fencing unknown local dispatch history.

View Source
var HumanInlineJournalUpgradeDDL = []string{
	`ALTER TABLE factory_commands DROP CONSTRAINT factory_commands_payload_check`,
	`ALTER TABLE factory_commands ADD CONSTRAINT factory_commands_payload_check CHECK((type IN ('discussion.comment.create','discussion.edit','issue.create','discussion.lock.apply','pull_request.review.submit','pull_request.review.comment.create') AND octet_length(payload)<=2097152) OR (type NOT IN ('discussion.comment.create','discussion.edit','issue.create','discussion.lock.apply','pull_request.review.submit','pull_request.review.comment.create') AND char_length(payload)<=8192))`,
	`UPDATE schema_version SET version=76`,
}

Only bounded human inline captures gain the existing large-command allowance. Older immutable captures and every other command's limit remain unchanged.

View Source
var HumanIssueCreateJournalUpgradeDDL = []string{
	`ALTER TABLE factory_commands DROP CONSTRAINT factory_commands_payload_check`,
	`ALTER TABLE factory_commands ADD CONSTRAINT factory_commands_payload_check CHECK((type IN ('discussion.comment.create','discussion.edit','issue.create') AND octet_length(payload)<=2097152) OR (type NOT IN ('discussion.comment.create','discussion.edit','issue.create') AND char_length(payload)<=8192))`,
	`UPDATE schema_version SET version=73`,
}

HumanIssueCreateJournalUpgradeDDL permits full plain human issue captures in the existing immutable command journal. Other command limits are unchanged.

View Source
var HumanLockDispatchUpgradeDDL = []string{
	commandGuardDDL,
	`UPDATE factory_commands SET dispatch_state='legacy_unknown' WHERE type='discussion.lock.apply' AND dispatch_state='unclaimed' AND EXISTS(SELECT 1 FROM schema_version WHERE version=84)`,
	`UPDATE schema_version SET version=85 WHERE version=84`,
}

Lock captures predating this protocol may already have reached a provider. Retain exact intent/reason/outcomes while conservatively fencing that history.

View Source
var HumanLockJournalUpgradeDDL = []string{
	`ALTER TABLE factory_commands DROP CONSTRAINT factory_commands_payload_check`,
	`ALTER TABLE factory_commands ADD CONSTRAINT factory_commands_payload_check CHECK((type IN ('discussion.comment.create','discussion.edit','issue.create','discussion.lock.apply') AND octet_length(payload)<=2097152) OR (type NOT IN ('discussion.comment.create','discussion.edit','issue.create','discussion.lock.apply') AND char_length(payload)<=8192))`,
	`UPDATE schema_version SET version=74`,
}

HumanLockJournalUpgradeDDL permits full human discussion lock captures in the existing immutable command journal. Other command limits are unchanged.

View Source
var HumanMergeDispatchUpgradeDDL = []string{
	commandGuardDDL,
	`UPDATE factory_commands SET dispatch_state='legacy_unknown' WHERE type='pull_request.merge' AND dispatch_state='unclaimed' AND EXISTS(SELECT 1 FROM schema_version WHERE version=91)`,
	`UPDATE schema_version SET version=92 WHERE version=91`,
}

Earlier merge captures have no reliable local one-shot dispatch history.

View Source
var HumanMergeJournalUpgradeDDL = []string{
	`ALTER TABLE factory_commands DROP CONSTRAINT factory_commands_payload_check`,
	`ALTER TABLE factory_commands ADD CONSTRAINT factory_commands_payload_check CHECK((type IN ('discussion.comment.create','discussion.edit','issue.create','discussion.lock.apply','pull_request.review.submit','pull_request.review.comment.create','pull_request.merge') AND octet_length(payload)<=2097152) OR (type IN ('pull_request.review.thread.resolve','pull_request.review.request') AND octet_length(payload)<=131072) OR (type NOT IN ('discussion.comment.create','discussion.edit','issue.create','discussion.lock.apply','pull_request.review.submit','pull_request.review.comment.create','pull_request.merge','pull_request.review.thread.resolve','pull_request.review.request') AND char_length(payload)<=8192))`,
	`UPDATE schema_version SET version=79`,
}

Human merge captures retain a bounded message and opaque provider preparation.

View Source
var HumanPullCreateDispatchUpgradeDDL = []string{
	commandGuardDDL,
	`UPDATE factory_commands SET dispatch_state='legacy_unknown' WHERE type='pull_request.create' AND dispatch_state='unclaimed' AND EXISTS(SELECT 1 FROM schema_version WHERE version=87)`,
	`UPDATE schema_version SET version=88 WHERE version=87`,
}

Earlier PR creation captures may already have reached an adapter. Preserve exact head/base repositories, branches, writing and outcomes while fencing that unknown dispatch history. Stale openers cannot fence new captures.

View Source
var HumanPullCreateJournalUpgradeDDL = []string{
	`ALTER TABLE factory_commands DROP CONSTRAINT factory_commands_payload_check`,
	`ALTER TABLE factory_commands ADD CONSTRAINT factory_commands_payload_check CHECK((type IN ('discussion.comment.create','discussion.edit','issue.create','discussion.lock.apply','pull_request.review.submit','pull_request.review.comment.create','pull_request.merge','pull_request.create') AND octet_length(payload)<=2097152) OR (type IN ('pull_request.review.thread.resolve','pull_request.review.request') AND octet_length(payload)<=131072) OR (type NOT IN ('discussion.comment.create','discussion.edit','issue.create','discussion.lock.apply','pull_request.review.submit','pull_request.review.comment.create','pull_request.merge','pull_request.create','pull_request.review.thread.resolve','pull_request.review.request') AND char_length(payload)<=8192))`,
	`UPDATE schema_version SET version=80`,
}

Human PR captures retain full writing, explicit source and opaque preparation.

View Source
var HumanReviewDispatchUpgradeDDL = []string{
	commandGuardDDL,
	`UPDATE factory_commands SET dispatch_state='legacy_unknown' WHERE type='pull_request.review.submit' AND dispatch_state='unclaimed' AND EXISTS(SELECT 1 FROM schema_version WHERE version=88)`,
	`UPDATE schema_version SET version=89 WHERE version=88`,
}

Earlier draft/submitted review captures may already have reached a provider. Preserve exact event, writing and outcomes while fencing unknown history. The version predicate protects new captures from stale concurrent openers.

View Source
var HumanReviewJournalUpgradeDDL = []string{
	`ALTER TABLE factory_commands DROP CONSTRAINT factory_commands_payload_check`,
	`ALTER TABLE factory_commands ADD CONSTRAINT factory_commands_payload_check CHECK((type IN ('discussion.comment.create','discussion.edit','issue.create','discussion.lock.apply','pull_request.review.submit') AND octet_length(payload)<=2097152) OR (type NOT IN ('discussion.comment.create','discussion.edit','issue.create','discussion.lock.apply','pull_request.review.submit') AND char_length(payload)<=8192))`,
	`UPDATE schema_version SET version=75`,
}

HumanReviewJournalUpgradeDDL permits bounded human draft/final review captures in the existing immutable journal. Other command limits stay intact.

View Source
var HumanReviewRequestDispatchUpgradeDDL = []string{
	commandGuardDDL,
	`UPDATE factory_commands SET dispatch_state='legacy_unknown' WHERE type='pull_request.review.request' AND dispatch_state='unclaimed' AND EXISTS(SELECT 1 FROM schema_version WHERE version=86)`,
	`UPDATE schema_version SET version=87 WHERE version=86`,
}

Reviewer-request captures from earlier adapters have unknown local dispatch history. Preserve exact user/team intent and outcomes while fencing that history; a stale opener cannot fence captures made after this upgrade.

View Source
var HumanReviewRequestJournalUpgradeDDL = []string{
	`ALTER TABLE factory_commands DROP CONSTRAINT factory_commands_payload_check`,
	`ALTER TABLE factory_commands ADD CONSTRAINT factory_commands_payload_check CHECK((type IN ('discussion.comment.create','discussion.edit','issue.create','discussion.lock.apply','pull_request.review.submit','pull_request.review.comment.create') AND octet_length(payload)<=2097152) OR (type IN ('pull_request.review.thread.resolve','pull_request.review.request') AND octet_length(payload)<=131072) OR (type NOT IN ('discussion.comment.create','discussion.edit','issue.create','discussion.lock.apply','pull_request.review.submit','pull_request.review.comment.create','pull_request.review.thread.resolve','pull_request.review.request') AND char_length(payload)<=8192))`,
	`UPDATE schema_version SET version=78`,
}

Reviewer-request captures share the bounded 128 KiB allowance with threads.

View Source
var HumanStateDispatchUpgradeDDL = []string{
	commandGuardDDL,
	`UPDATE factory_commands SET dispatch_state='legacy_unknown' WHERE type='discussion.state.apply' AND dispatch_state='unclaimed' AND EXISTS(SELECT 1 FROM schema_version WHERE version=82)`,
	`UPDATE schema_version SET version=83 WHERE version=82`,
}

Earlier state captures may have been dispatched without this local fence. Retain their exact records and conservatively fence unknown dispatch history. A stale concurrent opener must not fence captures created after the upgrade.

View Source
var HumanThreadDispatchUpgradeDDL = []string{
	commandGuardDDL,
	`UPDATE factory_commands SET dispatch_state='legacy_unknown' WHERE type='pull_request.review.thread.resolve' AND dispatch_state='unclaimed' AND EXISTS(SELECT 1 FROM schema_version WHERE version=85)`,
	`UPDATE schema_version SET version=86 WHERE version=85`,
}

Earlier thread captures may already have reached an idempotent remote host. Retain their exact scope, full/unknown anchor and outcomes; no local retry permission can be inferred from an old unclaimed default.

View Source
var HumanThreadJournalUpgradeDDL = []string{
	`ALTER TABLE factory_commands DROP CONSTRAINT factory_commands_payload_check`,
	`ALTER TABLE factory_commands ADD CONSTRAINT factory_commands_payload_check CHECK((type IN ('discussion.comment.create','discussion.edit','issue.create','discussion.lock.apply','pull_request.review.submit','pull_request.review.comment.create') AND octet_length(payload)<=2097152) OR (type='pull_request.review.thread.resolve' AND octet_length(payload)<=131072) OR (type NOT IN ('discussion.comment.create','discussion.edit','issue.create','discussion.lock.apply','pull_request.review.submit','pull_request.review.comment.create','pull_request.review.thread.resolve') AND char_length(payload)<=8192))`,
	`UPDATE schema_version SET version=77`,
}

Bounded human thread captures use 128 KiB; previous command limits are retained.

View Source
var IssueCreateDispatchUpgradeDDL = []string{
	commandGuardDDL,
	`UPDATE factory_commands SET dispatch_state='legacy_unknown' WHERE type='issue.create' AND dispatch_state='unclaimed' AND EXISTS(SELECT 1 FROM schema_version WHERE version=81)`,
	`UPDATE schema_version SET version=82 WHERE version=81`,
}

Schema 81 issue captures predate this one-shot protocol and may already have been sent by another adapter. Preserve all payload/outcome bytes while fencing that history. The version predicate prevents a concurrent stale opener from fencing new schema-82 rows after another opener has committed the upgrade.

View Source
var IssueDependencyDispatchUpgradeDDL = []string{
	commandGuardDDL,
	`UPDATE factory_commands SET dispatch_state='legacy_unknown' WHERE type='issue.graph.mutate' AND dispatch_state='unclaimed' AND EXISTS(SELECT 1 FROM schema_version WHERE version=95)`,
	`UPDATE schema_version SET version=96 WHERE version=95`,
}

A single dependency effect now shares the one-shot command reservation. Older graph-shaped rows cannot acquire dispatch ownership retroactively.

Functions

func DropFactoryRunViews

func DropFactoryRunViews(ctx context.Context, dsn string) error

DropFactoryRunViews removes the run-view table so view-read failure paths can be exercised against a live database.

func InjectCorruptFactoryRun

func InjectCorruptFactoryRun(ctx context.Context, dsn, id string, active, settled bool, data string) error

InjectCorruptFactoryRun inserts one factory_runs row with caller-supplied bytes, bypassing every validation the store API applies.

func PostStatus

func PostStatus(pipe *factory.PostIntake) string

PostStatus derives one post's feed status from its pipeline row: the separate states stay distinguishable instead of collapsing into one generic marker.

func PrioritySubjectKey

func PrioritySubjectKey(repository, issue int64) string

PrioritySubjectKey names one member. Ordering uses the stored subject list; the key is only a row identity.

func ReadSchemaVersion

func ReadSchemaVersion(ctx context.Context, dsn string) (int, error)

ReadSchemaVersion connects to an existing database without migrating and returns the single schema_version row. Callers that need the current schema must use OpenObserve or Open instead.

func RecordAuthor

func RecordAuthor(phase, role string) (actor, author string)

RecordAuthor derives one record's actor/author pair from its recorded phase through the canonical MCP profiles: actor is the profile that serves the phase (the Strategist serves both reassess and repair), author its persona name. An unknown-phase record falls back to its recorded execution role as actor and leaves the author empty instead of inventing a persona.

func RecordStatus

func RecordStatus(phase, stage, outcome, verdict string, extra []string) string

RecordStatus derives one record's feed status from its recorded phase, stage, outcome and verdict segment (review verdict or verification outcome) plus its extra recorded segments, e.g. "review:finished:succeeded:request-changes>findings:3" or "implement:finished:succeeded>published>merged>completed". Every segment is a recorded value; a missing phase, outcome or verdict simply drops its segment. The result stays within the wire status bound: extra segments drop first, then verdict, then outcome.

func SchemaVersion

func SchemaVersion() int

SchemaVersion is a format identifier. Adopted upgrades from 68 through the current format run inside the open transaction; foreign formats are refused.

func TestFixtureDSN

func TestFixtureDSN() (dsn string, ok bool)

TestFixtureDSN builds a superuser connection URL from the A10 disposable fixture environment: SODA_PG_HOST, SODA_PG_PORT and SODA_PG_SUPER_PASSWORD_FILE, as printed by soda-pg-fixture start, or the SODA_NATIVE_PG_DSN_FILE supplied by the native fixture driver. It reports ok=false when the fixture is absent; tests skip instead of guessing a database. The password travels from its restricted file into the returned URL only; it is never logged.

func TruncateFeedSummary

func TruncateFeedSummary(summary string) string

TruncateFeedSummary cuts one served summary preview to its rune bound. The untruncated recorded text stays with its owner.

Types

type ApplicationBuild

type ApplicationBuild struct {
	ID         string                     `json:"id"`
	Repository int64                      `json:"repository"`
	Delivery   ApplicationFactoryDelivery `json:"delivery"`
	Artifact   application.BuildArtifact  `json:"artifact"`
	SetupID    string                     `json:"setup_id,omitempty"`
}

type ApplicationFactoryDelivery

type ApplicationFactoryDelivery struct {
	State            string `json:"state"`
	Environment      string `json:"environment"`
	Intent           string `json:"intent"`
	Revision         string `json:"revision"`
	DeliveryID       string `json:"delivery_id"`
	Run              string `json:"run"`
	SourceCommit     string `json:"source_commit"`
	BundleFileSHA256 string `json:"bundle_file_sha256"`
}

ApplicationFactoryDelivery is a spend-free projection of two native byte observations and the canonical F10 event. It grants no release or app access.

type ApplicationProjectLink struct {
	ApplicationID string
	Repository    int64
}

ApplicationProjectLink pairs one application with one linked repository.

type CandidatePreparationRecord

type CandidatePreparationRecord struct {
	RetireClosed bool `json:"-"`
	Preparation  execution.PreparationRecord
	Admission    CandidatePreparationRegistration
	NotAfter     int64
	Stopped      bool
	Retirement   string
}

CandidatePreparationRecord joins the public preparation view with its Store-owned admission and native-stop receipt.

type CandidatePreparationRegistration

type CandidatePreparationRegistration struct {
	Repository        int64
	Issue             int64
	ActorID           int64
	Project           string
	OwnerAssignment   string
	ChildAssignment   string
	AttemptRoot       string
	PublicationID     string
	Connection        string
	Authority         factory.AuthorityRef
	GateRevision      int64
	Control           factory.IssueControl
	RequestedNotAfter int64
	SourceRun         *project.FactoryExport
	SourceMerge       *project.FactoryMergedSource
	SourcePull        *project.FactoryPullSource
}

CandidatePreparationRegistration is the Store admission request for one reviewer/correction checkout or an accepted explicit coder Retry. The owner and deadline are recorded beside the ordinary preparation record before the host is called.

type ContributionOwner

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

ContributionOwner holds a dedicated PostgreSQL session while a producer claims and settles assessments. Losing this session fences its later writes; another connection can prove ownership ended without trusting a timestamp. The private owner identity is not a worker capability or provider credential.

func (*ContributionOwner) ClaimContributionReview

func (o *ContributionOwner) ClaimContributionReview(ctx context.Context, review factory.ContributionReview) (bool, error)

ClaimContributionReview publishes the real pending assessment before calls. The source revision lock and existing comment idempotency key make a repeated service wake, model timeout or browser refresh unable to dispatch twice. Record sources retain the resolved source snapshot beside the assessment. Every assessment uses the normal parent_id thread link.

func (*ContributionOwner) Close

func (o *ContributionOwner) Close() error

Close discards the session rather than returning a session-level advisory lock to the pool. PostgreSQL releases ownership when that connection actually ends. A still-running model response cannot settle through a closed owner.

func (*ContributionOwner) SettleContributionReview

func (o *ContributionOwner) SettleContributionReview(ctx context.Context, review factory.ContributionReview) error

type ContributionRecovery

type ContributionRecovery struct {
	Next      int64
	Recovered int
	Complete  bool
}

ContributionRecovery is one bounded traversal of owned pending assessments. Next is a feed sequence cursor; live owners do not starve later lost owners. Unowned historical pending rows remain unknown and are never guessed dead.

type DeliveredIntentCandidate

type DeliveredIntentCandidate struct {
	Revision   factory.IntentRevision
	FirstIssue int64
}

type DeliveryRepairRecord

type DeliveryRepairRecord struct {
	Revision int64                         `json:"revision"`
	Cause    factory.DeliveryRepairCause   `json:"cause"`
	Subject  factory.DeliveryRepairSubject `json:"subject"`
	Cycle    factory.StallRepairCycle      `json:"cycle"`
}

Delivery repair uses the existing internal command journal. The immutable payload binds its failed cause; only this owner advances the bounded outcome under the record revision. Human request receipts remain separate commands.

func (DeliveryRepairRecord) Validate

func (r DeliveryRepairRecord) Validate() error

type FeedPostDetail

type FeedPostDetail struct {
	Consultation  *factory.FeedConsultation
	Contribution  *factory.ContributionReview
	Actor         string
	Assignment    string
	EventIdentity string
	Payload       *factory.FeedPayload
	Record        factory.PostRecord
	Body          string
	AuthorName    string
	At            int64
	Status        string
	Source        *factory.PostSource
}

FeedPostDetail carries one stored comment with its serving fields. Source is the persisted resolved snapshot of the feed entry the comment was submitted against, when it named one. Consultation carries actual tool inputs/results, distinct from agent prose.

type FeedRecordDetail

type FeedRecordDetail struct {
	ID      string
	Actor   string
	Author  string
	At      int64
	Status  string
	Issue   int64
	PR      int64
	Ref     string
	Summary string
	Payload *factory.FeedPayload
}

FeedRecordDetail carries one stored assignment record's serving fields.

type IntentExecutionAggregate

type IntentExecutionAggregate struct {
	Intent      string
	Owner       int64
	ConsumedMs  int64
	Roots       []string
	Issues      []string
	LimitMs     int64
	LimitActive bool
}

IntentExecutionAggregate is the stable active-time aggregate for one origin intent: every attempt root of every issue bound to any of the intent's revisions, each root charged once. New attempts, decomposition revisions, split or replacement issues and verification add rows; they never reset consumption.

type JourneyAdoption

type JourneyAdoption struct {
	Intent   string
	Revision string
	Binding  factory.IntentTaskBinding
}

JourneyAdoption is one recorded intent adoption behind an issue: the intent and revision whose generated task binding adopted the native issue, with the binding itself. A binding exists only after native readback confirmed the issue, so its presence is the adoption proof; its absence means no intent ever adopted this issue.

type JourneyVerifiedApp

type JourneyVerifiedApp struct {
	Intent       string
	Revision     string
	SourceCommit string
	Manifest     string
}

JourneyVerifiedApp names the verified application revision behind one adopted intent revision: the latest finished verify assignment whose delivery subject binds this intent revision, with the source commit and verification manifest digest from its recorded F10 verified evidence. Only the trusted application check renders here; worker journey observations and receipts alone never do. No recorded verification is ErrNotFound, never an unverified claim.

type Key

type Key struct {
	ID                  int64
	Public, Fingerprint string
}

type Member

type Member struct {
	UserID int64
	Login  string
}

type MemberAccess

type MemberAccess struct {
	Revision     int64                      `json:"revision"`
	Held         bool                       `json:"held"`
	RequiresJoin bool                       `json:"requires_join"`
	Action       string                     `json:"action"`
	Complete     bool                       `json:"complete"`
	Native       *project.MemberAccessState `json:"native"`
}

type NativeRecoveryCandidate

type NativeRecoveryCandidate struct {
	BrokerRun string `json:"broker_run"`
	SourceSHA string `json:"source_sha256"`
}

type PhaseAttempt

type PhaseAttempt struct {
	Assignment factory.Assignment
	Seq        int64
}

PhaseAttempt carries one phase group's newest recorded assignment behind the selected owner AttemptRoot, with its stable seq order. The read layer classifies the recorded phase value (canonical or unknown); the store only scopes and orders.

type PlanBindings

type PlanBindings struct {
	SourceCommit  string
	Prerequisites []string
	Preparation   string
}

PlanBindings carries the current source, prerequisite and preparation values an implementation launch checks against the recorded head plan. FW12 supplies live values; the store refuses the launch when they differ.

func (PlanBindings) Validate

func (b PlanBindings) Validate() error

Validate checks the binding shapes. Every prerequisite must be a digest; the match against the recorded plan happens in AdmitPlanHead.

type PlanTaskReceipt

type PlanTaskReceipt struct {
	AttemptRoot  string   `json:"attempt_root"`
	PlanID       string   `json:"plan_id"`
	TaskID       string   `json:"task_id"`
	Revision     int64    `json:"revision"`
	State        string   `json:"state"`
	Child        string   `json:"child,omitempty"`
	Parent       bool     `json:"parent,omitempty"`
	InputDigest  string   `json:"input_digest,omitempty"`
	OutputDigest string   `json:"output_digest,omitempty"`
	Events       []string `json:"events,omitempty"`
	Checks       []string `json:"checks,omitempty"`
	Tree         string   `json:"tree,omitempty"`
	Commit       string   `json:"commit,omitempty"`
	Reason       string   `json:"reason,omitempty"`
}

PlanTaskReceipt is the persisted state and evidence for one planned task under one immutable plan revision. Revision is the CAS base: the first save uses zero and each accepted advance stores one more. An identical replay commits nothing and reports success.

func (PlanTaskReceipt) Validate

func (r PlanTaskReceipt) Validate() error

Validate checks the receipt shape and bounds. Task membership and check references are verified against the stored plan revision on save.

type PostProductChange

type PostProductChange struct {
	Intent           string `json:"intent"`
	AcceptedRevision string `json:"accepted_revision"`
	DraftRevision    string `json:"draft_revision,omitempty"`
	State            string `json:"state"`
	CanReview        bool   `json:"can_review"`
}

func UnavailablePostProductChange

func UnavailablePostProductChange(intent, acceptedRevision string) *PostProductChange

UnavailablePostProductChange projects an explicit unknown for a same-product comment whose read failed.

type PriorityCandidateObservation

type PriorityCandidateObservation struct {
	Subject     string `json:"subject"`
	Repository  int64  `json:"repository"`
	Issue       int64  `json:"issue"`
	Candidate   []byte `json:"candidate,omitempty"`
	Exclusion   string `json:"exclusion,omitempty"`
	Fingerprint string `json:"fingerprint"`
}

PriorityCandidateObservation is one observed member: either a complete candidate for the tournament or an exclusion with its rule reason. Partial prerequisite observations land here as complete per-member records; members before the cursor are observed, members after it are not.

type PriorityComparisonCursor

type PriorityComparisonCursor struct {
	BeforeSnapshot string
	BeforeUnix     int64
}

PriorityComparisonCursor pages completed priority receipts newest-first. The zero cursor reads the first page; later pages echo the previous page's trailing (created_unix, snapshot).

type PriorityInventory

type PriorityInventory struct {
	LocalDigest string                     `json:"local_digest"`
	Subjects    []PriorityInventorySubject `json:"subjects"`
}

PriorityInventory is one captured membership plus its local digest. The native revision is observed by control and compared alongside.

type PriorityInventorySubject

type PriorityInventorySubject struct {
	Repository    int64 `json:"repository"`
	Issue         int64 `json:"issue"`
	FirstSeenUnix int64 `json:"first_seen_unix"`
}

PriorityInventorySubject is one ordered scan member.

type PriorityScanState

type PriorityScanState struct {
	ScanID         string
	NativeRevision int64
	LocalDigest    string
	Subjects       []PriorityInventorySubject
	Cursor         int
	Observations   map[string]PriorityCandidateObservation
}

PriorityScanState is the loaded current scan with its observations.

type Project

type Project struct {
	Profile               *project.Profile
	ID, Name              string
	RepositoryID, OwnerID int64
	Repository, IP        string
	Ready                 bool
}

type ReadinessWork

type ReadinessWork struct {
	ID, Delivery                          string
	Root                                  factory.DependenceRef
	Generation                            int64
	CreationVerified                      bool
	CreatorID, NativeIssueID, CreatedUnix int64
	CreatorWrite                          bool
	TitleDigest, ContentDigest            string
}

type ReadinessWorkNode

type ReadinessWorkNode struct {
	Ref, Cursor factory.DependenceRef
	State       string
}

type ReassessmentRecord

type ReassessmentRecord struct {
	Cycle               factory.ReassessmentCycle         `json:"cycle"`
	Completion          factory.CompletionEvent           `json:"completion,omitempty"`
	Local               factory.CompletionLocal           `json:"local,omitempty"`
	Evidence            []factory.CompletionIssueEvidence `json:"evidence"`
	InventoryDigest     string                            `json:"inventory_digest,omitempty"`
	EvidenceFingerprint string                            `json:"evidence_fingerprint,omitempty"`
	ProposalFingerprint string                            `json:"proposal_fingerprint,omitempty"`
	WaitReason          string                            `json:"wait_reason,omitempty"`
	CollectorProgress   json.RawMessage                   `json:"collector_progress,omitempty"`
	AdoptionProgress    json.RawMessage                   `json:"adoption_progress,omitempty"`
	Issue               int64                             `json:"issue,omitempty"`
	EvidenceIssues      int                               `json:"evidence_issues,omitempty"`
	EvidenceRevision    int64                             `json:"evidence_revision,omitempty"`
}

ReassessmentRecord is one persisted bounded cycle: the FW30 domain cycle plus the sealed completion event, the complete sealed issue bodies with their inventory digest and native revision bracket, the funded-decision evidence fingerprint, the wait/retry reason for read models and the opaque resumable collector progress. Sealed evidence never changes: once an inventory digest is recorded, later writes must carry it with its bodies unchanged.

func (ReassessmentRecord) Validate

func (r ReassessmentRecord) Validate() error

type Session

type Session struct {
	User User
	CSRF string
	// ContextID binds a native request to its current Forgejo session.
	ContextID string
	Expires   int64
}

type SetupRenewClaim

type SetupRenewClaim string

SetupRenewClaim is the read-only committed-claim reconciliation outcome for a setup renewal. It names only durable owner-claim states the store can prove; it never mints, extends, or releases anything.

const (
	// SetupRenewClaimUnclaimed is the Soda-side unproven outcome: no
	// committed owner binding is visible in Soda's database for this
	// application context and no other durable holder claims its
	// namespace there. That proves nothing about the native owner state,
	// which lives outside Soda's database — interim fail-closed, this
	// outcome authorizes no rotation or replacement. Callers must refuse
	// rotation on it exactly as on committed/conflict, until the queued
	// native reconciliation seam can prove the durable claim.
	SetupRenewClaimUnclaimed SetupRenewClaim = "unclaimed"
	// SetupRenewClaimCommitted means a committed owner binding already
	// exists for this exact application context. Expiry never uncommits
	// it: the setup reservation expiry is handled by the receipt path
	// (complete with a validated Canlang receipt), never by re-admission.
	SetupRenewClaimCommitted SetupRenewClaim = "committed"
	// SetupRenewClaimConflict means a different durable holder claims the
	// same namespace (data, origin, hostname, or port).
	SetupRenewClaimConflict SetupRenewClaim = "conflict"
)

type StallRepairRecord

type StallRepairRecord struct {
	factory.StallEvent
	Repair factory.StallRepairEpisode `json:"repair"`
}

type StandingStallEvent

type StandingStallEvent struct {
	Repository int64
	Generation int64
	EventID    string
	Digest     string
}

StandingStallEvent is the latest bound observation for one repository: the generation its next detection round must reuse until verified delivery advances progress, with the event identity and sealed digest a fresh round compares for staleness.

type Store

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

func Open

func Open(dsn string) (*Store, error)

Open connects to the PostgreSQL store, creating the current schema in an empty database, applying supported retained upgrades and refusing unknown schemas. dsn is a PostgreSQL connection URL; callers read it from a restricted secret file, never from configuration text.

func OpenContext

func OpenContext(ctx context.Context, dsn string) (*Store, error)

OpenContext opens the appliance composition with the caller's startup lifetime.

func OpenEphemeral

func OpenEphemeral(ctx context.Context, superDSN string) (s *Store, dsn string, cleanup func(), err error)

OpenEphemeral creates a uniquely-named database on the given server and opens a Store on it for one test. The returned cleanup closes the store and drops the database. Tests resolve the server URL through TestFixtureDSN and skip when it is absent.

The database is cloned from a per-process migrated template instead of running the full DDL per test; any template failure falls back to the plain create path.

func OpenObserve

func OpenObserve(ctx context.Context, dsn string) (*Store, error)

OpenObserve connects to an existing database without migrating. It refuses unless the stored schema exactly matches SchemaVersion(). Observation performs reads only; it never initializes or repairs the schema.

func OpenStandaloneContext

func OpenStandaloneContext(ctx context.Context, dsn string) (*Store, error)

OpenStandaloneContext creates a native Factory database without appliance Projects, identity custody or application hosting. Retained shared databases keep their compatibility obligations. It never removes tables or converts a retained database to a smaller schema.

func (*Store) AcceptanceAssignmentsAfter

func (s *Store) AcceptanceAssignmentsAfter(ctx context.Context, repository, issue int64, decision, after string, limit int) ([]factory.Assignment, string, error)

AcceptanceAssignmentsAfter pages assignment lineage for one withdrawn acceptance. All stages remain relevant because RunHistory includes retries.

func (*Store) AcceptanceDecision

func (s *Store) AcceptanceDecision(ctx context.Context, id string) (factory.Acceptance, error)

AcceptanceDecision returns one recorded issue acceptance.

func (*Store) AcceptanceDependantsPage

func (s *Store) AcceptanceDependantsPage(ctx context.Context, repository, issue int64, after factory.DependenceRef) ([]factory.DependenceRef, factory.DependenceRef, bool, error)

AcceptanceDependantsPage returns one bounded, stable page of acceptance heads that name the endpoint as a prerequisite. Cursor advances over every scanned head, including heads that do not match, so sparse pages can resume without rescanning. HasMore describes candidate heads after Cursor, not whether this page contained any matches.

func (*Store) AcceptanceDepth

func (s *Store) AcceptanceDepth(ctx context.Context, repository, issue int64) (int64, error)

AcceptanceDepth counts the recorded acceptance chain for one native issue.

func (*Store) AcceptanceHead

func (s *Store) AcceptanceHead(ctx context.Context, repository, issue int64) (string, error)

AcceptanceHead returns the current acceptance decision for one native issue.

func (*Store) AcceptanceWithdrawn

func (s *Store) AcceptanceWithdrawn(ctx context.Context, repository, issue int64, decision string) (bool, int64, error)

AcceptanceWithdrawn reports whether the named decision was withdrawn and, when so, the withdrawing maintainer.

func (*Store) AccountFinishedMCPRun

func (s *Store) AccountFinishedMCPRun(ctx context.Context, id string) error

AccountFinishedMCPRun records usage and consumes its reservation in one transaction. It never writes the finished assignment or its MCP result.

func (*Store) ActivateDeliveryRepairIntent

func (s *Store) ActivateDeliveryRepairIntent(ctx context.Context, repository int64, failedRun, cycleID string, expected, next json.RawMessage, revision factory.IntentRevision, generation factory.IntentGeneration) error

ActivateDeliveryRepairIntent retains the same graph-operation journal as stall/completion adoption. Withdrawal fences new activation while already active operations retain their exact reconciliation owner.

func (*Store) ActivateMCPCapability

func (s *Store) ActivateMCPCapability(ctx context.Context, id string, generation int64, runID, assignmentID, authority string, nowUnix int64, stopped bool) error

ActivateMCPCapability moves a staged capability to active under an observed-binding guard: the recorded run, assignment and authority must match the host observation, the deadline must still hold and stop intent must be absent. Only staged rows activate, so a revoked or retired capability never returns.

func (*Store) ActivateObservedMCPCapability

func (s *Store) ActivateObservedMCPCapability(ctx context.Context, observed factory.MCPCapability) error

ActivateObservedMCPCapability is the production activation joint. The caller has just observed the matching live native run; current stored stop intent is rechecked under the same transaction that activates the capability.

func (*Store) ActivateReassessmentIntent

func (s *Store) ActivateReassessmentIntent(ctx context.Context, cycleID string, expected, next json.RawMessage, revision factory.IntentRevision, generation factory.IntentGeneration) error

ActivateReassessmentIntent commits one preflighted current journal step, its accepted successor head, immutable generation and copied bindings together. A crash cannot expose an activated head without the exact operation that recovery must resume. The controller owns typed journal preflight; this boundary compares its exact persisted progress under the cycle lock before any head changes.

func (*Store) ActivateStallRepairIntent

func (s *Store) ActivateStallRepairIntent(ctx context.Context, repository int64, event, cycleID string, expected, next json.RawMessage, revision factory.IntentRevision, generation factory.IntentGeneration) error

ActivateStallRepairIntent uses the same serial successor and native generation owners as completion adoption. Its genuine stall cycle and journal CAS are committed in the same transaction as the head, operation and copied bindings.

func (*Store) ActivePublishedPublications

func (s *Store) ActivePublishedPublications(ctx context.Context, limit int) ([]factory.Publication, error)

ActivePublishedPublications returns published candidates whose exact assignment root still owns an open issue allowance and has not merged. An idle accounting clock does not withdraw its bounded later phases. The active-attempt cap keeps this bounded without walking settled history.

func (*Store) ActiveRunCounts

func (s *Store) ActiveRunCounts(ctx context.Context) (int, map[string]int, error)

ActiveRunCounts counts active recorded runs with no dispatch assignment: human and fixture runs that still occupy appliance and repository slots. Attributed runs count through their held reservations instead, never twice.

func (*Store) ActivitySettings

func (s *Store) ActivitySettings(ctx context.Context, repository int64) (factory.ActivitySettings, int64, error)

func (*Store) AddKey

func (s *Store) AddKey(ctx context.Context, uid int64, public, fingerprint string) error

func (*Store) AdmitAcceptanceDecision

func (s *Store) AdmitAcceptanceDecision(ctx context.Context, d factory.Acceptance, policyRevision ...int64) error

func (*Store) AdmitApprovalDecision

func (s *Store) AdmitApprovalDecision(ctx context.Context, d project.ApprovalDecision) error

AdmitApprovalDecision records the administrator's privileged-effect approval.

func (*Store) AdmitCandidatePreparation

func (s *Store) AdmitCandidatePreparation(ctx context.Context, preparation execution.PreparationRecord, registration CandidatePreparationRegistration) (CandidatePreparationRecord, bool, error)

func (*Store) AdmitDeliveryJudgment

func (s *Store) AdmitDeliveryJudgment(ctx context.Context, repository, issue int64, root string) (bool, error)

AdmitDeliveryJudgment checks the open attempt's actual remaining allowance.

func (*Store) AdmitDeliveryRepairInvestigation

func (s *Store) AdmitDeliveryRepairInvestigation(ctx context.Context, repository int64, failedRun string, charge factory.RepairCharge, now time.Time) (bool, error)

func (*Store) AdmitDeliveryRepairJudgment

func (s *Store) AdmitDeliveryRepairJudgment(ctx context.Context, repository int64, failedRun, cycleID, fingerprint string, now time.Time) (bool, error)

AdmitDeliveryRepairJudgment charges the repair grant and binds the cycle's judgment fingerprint before the first call. A call that failed without a receipt retries under the same fingerprint; a recorded receipt is reused (false).

func (*Store) AdmitPlanHead

func (s *Store) AdmitPlanHead(ctx context.Context, attemptRoot string, current PlanBindings) (factory.InvestigationPlan, error)

AdmitPlanHead returns the current head revision when it is executable and its recorded source, prerequisite and preparation bindings still match the presented current values. Stale or incomplete plans never admit here: launching implementation from them is refused at this boundary.

func (*Store) AdmitPreparation

AdmitPreparation records one preparation identity with its immutable requirement/admin references. Repeating the same identity returns the recorded row; changed references for that identity conflict.

func (*Store) AdmitReassessmentCall

func (s *Store) AdmitReassessmentCall(ctx context.Context, cycleID, expectedState, callID, purpose, decision, fingerprint string) (bool, error)

AdmitReassessmentCall charges a cycle call once through its existing ledger. Callers derive the call ID from the judgment key, so another attempt at the same question uses that charge. A full cycle refuses new calls.

func (*Store) AdmitRequirementDecision

func (s *Store) AdmitRequirementDecision(ctx context.Context, d project.RequirementDecision) error

AdmitRequirementDecision records the maintainer's requirement acceptance.

func (*Store) AdmitStallInvestigation

func (s *Store) AdmitStallInvestigation(ctx context.Context, repository int64, charge factory.RepairCharge, now time.Time) (bool, error)

AdmitStallInvestigation admits one repair run or proposal judgment against the repository's explicit grant. The grant must exist and be active; episode cycles, run, judgment and active-minute bounds come from the immutable charge history, so duplicate ticks, restarts, hash changes, issue replacement, graph reshuffles and retries never replenish room. The charge persists before the caller launches; the result reports whether this call admitted a new charge.

func (*Store) AdmitStallRepairJudgment

func (s *Store) AdmitStallRepairJudgment(ctx context.Context, repository int64, event, cycleID, fingerprint string, now time.Time) (bool, error)

AdmitStallRepairJudgment consumes one deterministic cycle charge before the first external call. A crashed or failed call retries under the same fingerprint without a new charge; a saved receipt is replayed by the existing purpose journal before this method is reached.

func (*Store) AdmitStandingPreparation

func (s *Store) AdmitStandingPreparation(ctx context.Context, record execution.PreparationRecord) (execution.PreparationRecord, bool, error)

AdmitStandingPreparation records an explicit initial preparation against the current separate human decisions. No caller observation can seed readiness.

func (*Store) AdoptFountainLedger

func (s *Store) AdoptFountainLedger(ctx context.Context, host collaboration.HostID, sourceAPIBase string) error

AdoptFountainLedger is an explicit, pre-admission composition step. The caller supplies the already verified source locator from the retained appliance's configuration, not an endpoint supplied by a browser or inferred from rows. Nothing here discovers a provider, grants authority or rewrites workflow data.

func (*Store) AdvanceMCPWork

func (s *Store) AdvanceMCPWork(ctx context.Context, assignmentID, submissionID, expectedState string, result factory.MCPWorkStatus) error

AdvanceMCPWork updates processing state on the original post. It never writes another status envelope or copies the submitted payload.

func (*Store) AdvancePlanHead

func (s *Store) AdvancePlanHead(ctx context.Context, attemptRoot, expectedPlanID, nextPlanID string) error

AdvancePlanHead moves the current plan pointer from the expected plan to the next one, which must already persist. An empty expected plan creates the pointer; a mismatched one fails without moving it. A replay that already reached the next plan succeeds.

func (*Store) AdvancePostIntake

func (s *Store) AdvancePostIntake(ctx context.Context, expected, next factory.PostIntake) error

AdvancePostIntake moves one request row through CAS: every state column must still hold its expected value or the write refuses with ErrStaleRevision instead of dropping a concurrent advance.

func (*Store) AllIssueControls

func (s *Store) AllIssueControls(ctx context.Context, limit int) ([]factory.IssueControl, bool, error)

AllIssueControls returns every recorded issue control in deterministic order for the D15 complete-inventory detector. Unlike the dispatch queue listing, blocked and unauthorized controls are included: a stall classifier must see the whole sealed set, never a runnable subset. AllIssueControls returns every recorded issue control up to limit and reports whether the inventory is complete. A set past the bound fails closed to incomplete: the extra probe row is discarded and no truncated set is returned, so callers can never prove deadlock from a partial inventory. Bounded cost is preserved: at most limit+1 rows are read.

func (*Store) AppVerificationAllowance

func (s *Store) AppVerificationAllowance(ctx context.Context, intent string, owner int64, now time.Time) (factory.AppVerificationAllowance, error)

func (*Store) AppVerificationAllowanceScope

func (s *Store) AppVerificationAllowanceScope(ctx context.Context, intent string, owner int64) (int64, error)

Mutation authorization reads the current owner and repository.

func (*Store) Application

func (s *Store) Application(ctx context.Context, id string, actorID int64) (application.Record, error)

Application returns only records covered by the explicit administrator grant.

func (*Store) ApplicationBuild

func (s *Store) ApplicationBuild(ctx context.Context, repository int64, id string) (ApplicationBuild, error)

func (*Store) ApplicationBuildImageProof

func (s *Store) ApplicationBuildImageProof(ctx context.Context, image string) string

func (*Store) ApplicationBuilds

func (s *Store) ApplicationBuilds(ctx context.Context, repository int64, delivery string) ([]ApplicationBuild, error)

func (*Store) ApplicationEnvironment

func (s *Store) ApplicationEnvironment(ctx context.Context, id string) (string, error)

ApplicationEnvironment belongs to the completed setup/build association, independent of the latest delivery. Legacy manual admissions are company apps.

func (*Store) ApplicationProject

func (s *Store) ApplicationProject(ctx context.Context, id string) (int64, error)
func (s *Store) ApplicationProjectLinks(ctx context.Context) ([]ApplicationProjectLink, error)

ApplicationProjectLinks lists every application-to-project association for launch-projection filtering. Visibility is decided by the caller against native repository access; this inventory alone grants nothing.

func (*Store) ApplicationRestore

func (s *Store) ApplicationRestore(ctx context.Context, app, id string) (application.RestoreOperation, error)

func (*Store) ApplicationRevision

func (s *Store) ApplicationRevision(ctx context.Context, id string, actorID, revision int64) (application.Spec, error)

ApplicationRevision retains exact prior bytes references for recovery. A desired replacement does not erase the image/configuration that preceded it.

func (*Store) ApplicationSetup

func (s *Store) ApplicationSetup(ctx context.Context, id string) (application.SetupRecord, error)

func (*Store) ApplicationSetups

func (s *Store) ApplicationSetups(ctx context.Context) ([]application.SetupRecord, error)

func (*Store) ApplicationVerificationEvidenceInputs

func (s *Store) ApplicationVerificationEvidenceInputs(ctx context.Context, a factory.Assignment) (factory.IntentRevision, factory.VerificationDeliveryPrerequisites, error)

ApplicationVerificationEvidenceInputs uses the same current accepted head and canonical completion join as admission, without executing checks or writing.

func (*Store) ApplicationVerificationInputs

func (s *Store) ApplicationVerificationInputs(ctx context.Context, a factory.Assignment) (factory.IntentRevision, int64, error)

func (*Store) Applications

func (s *Store) Applications(ctx context.Context, actorID int64) ([]application.Record, error)

Applications returns the inventory for one admitted administrator.

func (*Store) ApplyCollaborationObservation

ApplyCollaborationObservation binds and maps one bounded nonsecret native observation atomically. No provider HTTP, credential or product authorization runs inside this transaction. A late conflict rolls back the complete batch.

func (*Store) ApplyFactoryGrant

func (s *Store) ApplyFactoryGrant(ctx context.Context, principal string, change any) (factory.GrantResult, error)

ApplyFactoryGrant saves a settings change under its expected revision. Any dispatch closure and native cancellation intents commit in this transaction.

func (*Store) ApplyIntentExecutionLimitCommand

func (s *Store) ApplyIntentExecutionLimitCommand(ctx context.Context, cmd factory.Command, limit factory.IntentExecutionAllowance, now time.Time) (factory.Command, bool, error)

ApplyIntentExecutionLimitCommand records one origin intent's explicit active-time aggregate bound. The predecessor must name the currently finished limit command, empty for the first. Consumption derives from existing attempt rows, so the bound never refills: an increase retains spent time by construction.

func (*Store) ApplyRepairGrantCommand

func (s *Store) ApplyRepairGrantCommand(ctx context.Context, cmd factory.Command, grant factory.RepairGrant, now time.Time) (factory.Command, bool, error)

ApplyRepairGrantCommand records one explicit repository repair grant revision. The predecessor must name the currently finished grant command, empty for the first grant. A limit increase above the predecessor must state its effect; consumption and history carry forward in the separate charge rows, so an increase never refills.

func (*Store) ApprovalDecision

func (s *Store) ApprovalDecision(ctx context.Context, id string) (project.ApprovalDecision, error)

ApprovalDecision returns one recorded privileged-effect approval.

func (*Store) ApprovalDepth

func (s *Store) ApprovalDepth(ctx context.Context, projectID string) (int64, error)

ApprovalDepth counts the recorded approval chain for preparation references.

func (*Store) ApprovalHead

func (s *Store) ApprovalHead(ctx context.Context, projectID string) (string, error)

ApprovalHead returns the current privileged-effect approval for one project.

func (*Store) AssignedAssignments

func (s *Store) AssignedAssignments(ctx context.Context, limit int) ([]factory.Assignment, error)

AssignedAssignments lists every unfinished dispatch assignment, oldest first, for crash recovery. Recovery resolves each one to consumed, released or finished; deferred work waits for a later pass.

func (*Store) Assignment

func (s *Store) Assignment(ctx context.Context, id string) (factory.Assignment, error)

Assignment returns one dispatch assignment by identity.

func (*Store) AssignmentByRun

func (s *Store) AssignmentByRun(ctx context.Context, runID string) (factory.Assignment, error)

AssignmentByRun returns the assignment whose latest attempt runs under the given run identity. A missing run reports ErrNotFound like the other assignment readers, never a raw driver miss: callers outside the store must not import database/sql for this lookup.

func (*Store) AssociateCollaborationRepository

func (s *Store) AssociateCollaborationRepository(ctx context.Context, repository collaboration.RepositoryID, connection collaboration.ConnectionID) error

AssociateCollaborationRepository records which connection observed a repo. The relation is not an access grant; current provider permissions are separate.

func (*Store) AttemptAllowance

func (s *Store) AttemptAllowance(ctx context.Context, repository, issue int64) (factory.AttemptAllowance, error)

AttemptAllowance returns the newest attempt allowance for the issue. Explicit maintainer retries keep earlier allowance rows in history. Unscoped issue-zero lookups refuse: completion roots are read only through the typed ReassessmentAttemptAllowance getter, never through the latest-per-issue path.

func (*Store) AttemptAllowanceHistory

func (s *Store) AttemptAllowanceHistory(ctx context.Context, repository, issue int64) ([]factory.AttemptAllowance, error)

AttemptAllowanceHistory returns every attempt allowance row for one issue, oldest root first. Explicit retries keep earlier rows, so the origin aggregate sums them instead of refilling.

func (*Store) AuthorizeCandidatePreparation

func (s *Store) AuthorizeCandidatePreparation(ctx context.Context, id string) (int64, error)

func (*Store) AuthorizeFactoryLaunch

func (s *Store) AuthorizeFactoryLaunch(ctx context.Context, request execution.LaunchRequest) (factory.MCPCapability, error)

AuthorizeFactoryLaunch rechecks the recorded packet and current grants at the native effect boundary. This grants no process observation or MCP activation.

func (*Store) AuthorizeStandingPreparation

func (s *Store) AuthorizeStandingPreparation(ctx context.Context, record execution.PreparationRecord) error

AuthorizeStandingPreparation rechecks the admission immediately before a native effect. Authority reads remain the caller's separate native callback.

func (*Store) AutomaticIssueOrigin

func (s *Store) AutomaticIssueOrigin(ctx context.Context, repository, issue int64) (generated, pending bool, err error)

AutomaticIssueOrigin uses causal journals, never the creator's account. The two answers share one database snapshot: an unbound operation must not vanish between its pending and recorded-result reads. Human issue commands are absent from these journals. Unresolved creates hold new intake until reconciliation; without a returned issue identity they cannot safely be called unrelated.

func (*Store) BeginApplicationRestore

func (s *Store) BeginApplicationRestore(ctx context.Context, administrator int64, operation application.RestoreOperation) error

func (*Store) BeginIntentGeneration

func (s *Store) BeginIntentGeneration(ctx context.Context, g factory.IntentGeneration, packet factory.GraphPacketFacts) error

BeginIntentGeneration persists the captured operation before submission. Delivered-history checks consume decoded facts bound to the opaque packet; provider field names and decoding belong to the adapter.

func (*Store) BeginMemberAccess

func (s *Store) BeginMemberAccess(ctx context.Context, pid string, uid, revision int64, action string) (MemberAccess, error)

BeginMemberAccess records the hold before any native dispatch. A retry of an unfinished operation preserves its revision and reconciles the same effects.

func (*Store) BeginNativeJudgment

func (s *Store) BeginNativeJudgment(ctx context.Context, c factory.NativeJudgmentCapture) (factory.Command, bool, error)

BeginNativeJudgment atomically captures the selected source, checks its shared minute allowance and reserves one bounded call. Only fresh=true may dispatch. Unknown sends stay reserved; restart never turns a missing receipt into a call.

func (*Store) BeginPostIssueCreation

func (s *Store) BeginPostIssueCreation(ctx context.Context, post string, revision int64) error

BeginPostIssueCreation retains the source revision before a remote create. Unlike the current intake draft, this journal survives edits and revocation. A missing result means unknown, never proof that the operation had no effect.

func (*Store) BeginReadinessWork

func (s *Store) BeginReadinessWork(ctx context.Context, id string, now time.Time) (ReadinessWork, error)

BeginReadinessWork allocates the root node on demand and restarts a source whose saved progress predates an acceptance-head mutation.

func (*Store) BindCollaborationConnection

func (s *Store) BindCollaborationConnection(ctx context.Context, observed collaboration.ConnectionObservation) (collaboration.ConnectionBinding, error)

BindCollaborationConnection commits an observed account as one registry unit. The connector must first verify the remote identity and current native scope; this method does no network I/O and grants no authority. Reconnect preserves IDs and existing profile names, while fresh observed account labels may change. A retained unadopted ledger is never implicitly assigned to this provider.

func (*Store) BindConfiguredFountainLedger

func (s *Store) BindConfiguredFountainLedger(ctx context.Context, sourceAPIBase string) (collaboration.Host, error)

BindConfiguredFountainLedger composes the appliance Factory from its trusted configuration. The configured public instance locator selects the initial host, never a browser URL or inferred ledger label. Once bound, a changed locator must already have been recorded against that same stable host; this call cannot silently select another source. Registration and adoption commit together, so a refused composition leaves no new host or allocator changes.

func (*Store) BindContextBundleSelection

func (s *Store) BindContextBundleSelection(ctx context.Context, capability factory.MCPCapability, fingerprint string) (bool, error)

BindContextBundleSelection records which input the staged run is consulting. A completed selection stays fixed for the run. Required work and current capability authority are checked before binding a new input.

func (*Store) BindFactoryExecutionManifest

func (s *Store) BindFactoryExecutionManifest(ctx context.Context, launch project.FactoryLaunch) error

BindFactoryExecutionManifest retains the exact admitted launch bytes before native execution. Supervisor observations preserve this immutable snapshot; retries may recover it but cannot replace it with a different plan or profile.

func (*Store) BindIntentTaskAcceptance

func (s *Store) BindIntentTaskAcceptance(ctx context.Context, b factory.IntentTaskBinding) error

func (*Store) CancelHumanBranchCreateDispatch

func (s *Store) CancelHumanBranchCreateDispatch(ctx context.Context, c factory.HumanBranchCreateCapture) (collaboration.OperationLookup, error)

CancelHumanBranchCreateDispatch uses the reservation row lock. Call only after current admission and when this fence guards every native creation attempt. A remote host's idempotent journal retains its own cancellation protocol.

func (*Store) CancelHumanCommentDispatch

func (s *Store) CancelHumanCommentDispatch(ctx context.Context, c factory.HumanCommentCapture) (collaboration.OperationLookup, error)

CancelHumanCommentDispatch shares reservation's row lock. Call only after current admission, for adapters using this fence for EVERY send. It does not cancel a remote idempotent provider journal or erase possibly sent effects.

func (*Store) CancelHumanEditDispatch

func (s *Store) CancelHumanEditDispatch(ctx context.Context, c factory.HumanEditCapture) (collaboration.OperationLookup, error)

CancelHumanEditDispatch shares the reservation lock. Use after current admission and only for adapters using this protocol for EVERY effect attempt.

func (*Store) CancelHumanInlineDispatch

func (s *Store) CancelHumanInlineDispatch(ctx context.Context, c factory.HumanInlineCapture) (collaboration.OperationLookup, error)

CancelHumanInlineDispatch uses the reservation row lock. Call only after current admission and when this fence guards every native inline attempt. A remote host's idempotent journal retains its own cancellation protocol.

func (*Store) CancelHumanIssueCreateDispatch

func (s *Store) CancelHumanIssueCreateDispatch(ctx context.Context, c factory.HumanIssueCreateCapture) (collaboration.OperationLookup, error)

CancelHumanIssueCreateDispatch shares the reservation row lock. Call only after current admission and only for adapters using this fence for EVERY send.

func (*Store) CancelHumanLockDispatch

func (s *Store) CancelHumanLockDispatch(ctx context.Context, c factory.HumanLockCapture) (collaboration.OperationLookup, error)

CancelHumanLockDispatch shares the reservation lock. Use after current caller admission and only when this fence guards EVERY native effect attempt.

func (*Store) CancelHumanMergeDispatch

func (s *Store) CancelHumanMergeDispatch(ctx context.Context, c factory.HumanMergeCapture) (collaboration.OperationLookup, error)

CancelHumanMergeDispatch uses the reservation row lock. Call only after current admission and when this fence guards every native merge attempt. A remote host's idempotent journal retains its own cancellation protocol.

func (*Store) CancelHumanPullCreateDispatch

func (s *Store) CancelHumanPullCreateDispatch(ctx context.Context, c factory.HumanPullCreateCapture) (collaboration.OperationLookup, error)

CancelHumanPullCreateDispatch uses the reservation row lock. Call only after current admission and when this fence guards every native creation attempt. A remote host's idempotent journal retains its own cancellation protocol.

func (*Store) CancelHumanReviewDispatch

func (s *Store) CancelHumanReviewDispatch(ctx context.Context, c factory.HumanReviewCapture) (collaboration.OperationLookup, error)

CancelHumanReviewDispatch uses the reservation row lock. Call only after current admission and when this fence guards every native review attempt. A remote host's idempotent journal retains its own cancellation protocol.

func (*Store) CancelHumanReviewRequestDispatch

func (s *Store) CancelHumanReviewRequestDispatch(ctx context.Context, c factory.HumanReviewRequestCapture) (collaboration.OperationLookup, error)

CancelHumanReviewRequestDispatch shares the reservation row lock. Use only after current caller admission and when this fence guards EVERY native attempt. A remote host's idempotent journal retains its own cancellation protocol.

func (*Store) CancelHumanStateDispatch

func (s *Store) CancelHumanStateDispatch(ctx context.Context, c factory.HumanStateCapture) (collaboration.OperationLookup, error)

CancelHumanStateDispatch shares the reservation lock. Call after current admission and only for adapters using this protocol for EVERY effect attempt.

func (*Store) CancelHumanThreadDispatch

func (s *Store) CancelHumanThreadDispatch(ctx context.Context, c factory.HumanThreadCapture) (collaboration.OperationLookup, error)

CancelHumanThreadDispatch uses the same row lock as reservation. Call only after current caller admission and when this fence guards EVERY native attempt. A remote host's idempotent journal retains its own cancellation protocol.

func (*Store) CancelRefPublicationDispatch

func (s *Store) CancelRefPublicationDispatch(ctx context.Context, c factory.RefPublicationCapture) (collaboration.OperationLookup, error)

func (*Store) CandidatePreparation

func (s *Store) CandidatePreparation(ctx context.Context, id string) (CandidatePreparationRecord, error)

CandidatePreparation reads the exact custody owner, including retirement.

func (*Store) CandidatePreparations

func (s *Store) CandidatePreparations(ctx context.Context, repository int64, projectID string, issue int64, root, after string, limit int, expiredBefore int64) ([]CandidatePreparationRecord, error)

CandidatePreparations pages exact pending admissions for one repository. A zero issue/root scope includes every pending preparation in the project.

func (*Store) CapAttemptDeadline

func (s *Store) CapAttemptDeadline(ctx context.Context, assignmentID string, requested int64) (int64, error)

CapAttemptDeadline returns the earlier of the requested absolute expiry and the exact assignment root's time bound. Issue attempts use a fresh per-run limit; issue-zero time-only grants retain their aggregate expiry. Native operations are admitted against this immutable wall-clock bound; existing intents are always replayed from their recorded NotAfter instead of calling this again.

func (*Store) Capacity

func (s *Store) Capacity(ctx context.Context) (factory.Capacity, error)

Capacity returns the appliance capacity record.

func (*Store) CaptureCompletionLocal

func (s *Store) CaptureCompletionLocal(ctx context.Context, repository int64) (factory.CompletionLocal, error)

CaptureCompletionLocal reads the local half of D13 sealed evidence for one repository in a single repeatable-read transaction: the requirement source commit (reused from the projected material's current-head authority, no redundant head read), the approved-preparation digest, the canonical material digest as the accepted-scope digest, and the authority fingerprint, carrying the complete validated material alongside. It is the production CompletionLocalCapture behind the completion drive: stable while nothing material changes, sensitive to source, preparation, scope and authority changes, and honest about gaps — a repository without a project or requirement source refuses instead of sealing from partial bindings. Private per-issue candidate custody and runtime preparation state stay out: they are volatile execution detail, not the approved local bindings the seal interprets the inventory against.

func (*Store) CaptureCompletionLocalAtSource

func (s *Store) CaptureCompletionLocalAtSource(ctx context.Context, repository int64, expected factory.CompletionAuthority, tip string) (factory.CompletionLocal, error)

func (*Store) CaptureHumanBranchCreate

func (s *Store) CaptureHumanBranchCreate(ctx context.Context, capture factory.HumanBranchCreateCapture) (factory.HumanBranchCreateCapture, bool, error)

func (*Store) CaptureHumanComment

func (s *Store) CaptureHumanComment(ctx context.Context, capture factory.HumanCommentCapture) (factory.HumanCommentCapture, bool, error)

func (*Store) CaptureHumanEdit

func (s *Store) CaptureHumanEdit(ctx context.Context, capture factory.HumanEditCapture) (factory.HumanEditCapture, bool, error)

func (*Store) CaptureHumanInline

func (s *Store) CaptureHumanInline(ctx context.Context, capture factory.HumanInlineCapture) (factory.HumanInlineCapture, bool, error)

func (*Store) CaptureHumanIssueCreate

func (s *Store) CaptureHumanIssueCreate(ctx context.Context, capture factory.HumanIssueCreateCapture) (factory.HumanIssueCreateCapture, bool, error)

func (*Store) CaptureHumanLock

func (s *Store) CaptureHumanLock(ctx context.Context, capture factory.HumanLockCapture) (factory.HumanLockCapture, bool, error)

func (*Store) CaptureHumanMerge

func (s *Store) CaptureHumanMerge(ctx context.Context, capture factory.HumanMergeCapture) (factory.HumanMergeCapture, bool, error)

func (*Store) CaptureHumanPullCreate

func (s *Store) CaptureHumanPullCreate(ctx context.Context, capture factory.HumanPullCreateCapture) (factory.HumanPullCreateCapture, bool, error)

func (*Store) CaptureHumanReview

func (s *Store) CaptureHumanReview(ctx context.Context, capture factory.HumanReviewCapture) (factory.HumanReviewCapture, bool, error)

func (*Store) CaptureHumanReviewRequest

func (s *Store) CaptureHumanReviewRequest(ctx context.Context, capture factory.HumanReviewRequestCapture) (factory.HumanReviewRequestCapture, bool, error)

func (*Store) CaptureHumanState

func (s *Store) CaptureHumanState(ctx context.Context, capture factory.HumanStateCapture) (factory.HumanStateCapture, bool, error)

func (*Store) CaptureHumanThread

func (s *Store) CaptureHumanThread(ctx context.Context, capture factory.HumanThreadCapture) (factory.HumanThreadCapture, bool, error)

func (*Store) CapturePriorityInventory

func (s *Store) CapturePriorityInventory(ctx context.Context) (PriorityInventory, error)

CapturePriorityInventory captures the complete ordered membership and the normalized local-input digest in one repeatable-read transaction. Assessment timestamps, observation counters, exact balances, remaining allowances and deadlines are excluded: refreshing a control or ticking a clock cannot invalidate its own scan. Time-dependent budget eligibility enters as booleans evaluated now; exact balances are rechecked in the final packet admission.

func (*Store) CasReassessmentRecord

func (s *Store) CasReassessmentRecord(ctx context.Context, cycleID, expectedState string, record ReassessmentRecord) error

func (*Store) ChargeReviewDispatch

func (s *Store) ChargeReviewDispatch(ctx context.Context, repository, issue int64, root, reviewerAssignment, head string, policy bool) (consumed, exhausted bool, err error)

ChargeReviewDispatch charges one independent reviewer dispatch against the attempt-root review allowance before its child packet commits, in one row-locked transaction. The charge keys on the immutable reviewer assignment identity: replays of the same assignment are idempotent and never consume a second round or pass, even after exhaustion. The first inspection of a new head consumes one ReviewRound but never the unchanged-head extra pass; a discretionary re-review of an inspected head additionally spends that head's single extra pass; a policy-required review consumes one ReviewRound and stays separately caused (D08).

It reports (consumed=true) only when this call spent budget. A replay of an already charged assignment reports (consumed=false, exhausted=false) so the caller still dispatches. An exhausted, closed or time-spent root reports (consumed=false, exhausted=true) without an error so the caller waits with review_allowance_exhausted instead of launching a run it cannot cover.

func (*Store) CheckAssessment

func (s *Store) CheckAssessment(ctx context.Context, repository, prNumber int64) (factory.CheckAssessment, error)

CheckAssessment returns the latest check assessment for one native PR. Absence reports ErrNotFound: no verdict exists yet for this PR.

func (*Store) CheckIntentJudgment

func (s *Store) CheckIntentJudgment(ctx context.Context, revision factory.IntentRevision) error

CheckIntentJudgment checks that a new consultation uses the current owned intent revision. Completed decisions are read by their input key separately.

func (*Store) CheckMCPWorkActive

func (s *Store) CheckMCPWorkActive(ctx context.Context, capability factory.MCPCapability) error

CheckMCPWorkActive validates current stored work on every authenticated read. Mutations repeat this guard inside their insert transaction when the capability has been activated through the production observation joint.

func (*Store) CheckNativeJudgmentSource

func (s *Store) CheckNativeJudgmentSource(ctx context.Context, c factory.NativeJudgmentCapture) error

func (*Store) CheckablePublications

func (s *Store) CheckablePublications(ctx context.Context, limit int) ([]factory.Publication, error)

CheckablePublications includes finite merge-only continuations. They can refresh CI observations while their inference root remains closed; child dispatch deliberately keeps the narrower active-allowance enumeration.

func (*Store) CheckpointReadinessAssessment

func (s *Store) CheckpointReadinessAssessment(ctx context.Context, work ReadinessWork, node ReadinessWorkNode, skip bool) error

CheckpointReadinessAssessment advances one evaluated node atomically.

func (*Store) CheckpointReadinessPage

func (s *Store) CheckpointReadinessPage(ctx context.Context, work ReadinessWork, node ReadinessWorkNode) (bool, error)

CheckpointReadinessPage scans and stores one bounded page in one transaction.

func (*Store) ClearProjectStop

func (s *Store) ClearProjectStop(ctx context.Context, repository, expectedRevision int64) (bool, int64, error)

ClearProjectStop removes only the Project lifecycle cause after verified start and run quiescence. First-closure attribution remains a receipt.

func (*Store) Close

func (s *Store) Close() error

func (*Store) CloseAttempt

func (s *Store) CloseAttempt(ctx context.Context, assignmentID string) (bool, error)

CloseAttempt closes the current exact root for an explicit Retry, which then starts a fresh attempt. It is safe to replay.

func (*Store) CloseExpiredAttempt

func (s *Store) CloseExpiredAttempt(ctx context.Context, assignmentID string) (bool, error)

CloseExpiredAttempt deactivates an already closed root once its last descendant run is confirmed settled. Attempts no longer expire on time, so an open root stays open. It is safe to replay.

func (*Store) CollaborationActor

func (s *Store) CollaborationActor(ctx context.Context, id collaboration.ActorID) (collaboration.ActorRef, error)

func (*Store) CollaborationActorByExternalID

func (s *Store) CollaborationActorByExternalID(ctx context.Context, host collaboration.HostID, externalID string) (collaboration.ActorRef, error)

func (*Store) CollaborationActorOnHost

func (s *Store) CollaborationActorOnHost(ctx context.Context, host collaboration.HostID, id collaboration.ActorID) (collaboration.ActorRef, error)

func (*Store) CollaborationConnection

func (s *Store) CollaborationConnection(ctx context.Context, id collaboration.ConnectionID) (collaboration.ConnectionRef, error)

func (*Store) CollaborationHost

func (s *Store) CollaborationHost(ctx context.Context, id collaboration.HostID) (collaboration.Host, error)

func (*Store) CollaborationHostByAPIBase

func (s *Store) CollaborationHostByAPIBase(ctx context.Context, provider collaboration.Provider, base string) (collaboration.Host, error)

Resolve an already configured instance during account connection. This is a lookup of its locator, not permission to merge or recreate its stable HostID.

func (*Store) CollaborationProfile

func (s *Store) CollaborationProfile(ctx context.Context, id collaboration.ProfileID) (collaboration.Profile, error)

func (*Store) CollaborationRepository

func (s *Store) CollaborationRepository(ctx context.Context, id collaboration.RepositoryID) (collaboration.RepositoryRef, error)

func (*Store) CollaborationRepositoryByExternalID

func (s *Store) CollaborationRepositoryByExternalID(ctx context.Context, host collaboration.HostID, externalID string) (collaboration.RepositoryRef, error)

func (*Store) CollaborationRepositoryForNativeProject

func (s *Store) CollaborationRepositoryForNativeProject(ctx context.Context, projectID string) (collaboration.RepositoryRef, error)

func (*Store) CollaborationRepositoryOnHost

func (s *Store) CollaborationRepositoryOnHost(ctx context.Context, host collaboration.HostID, id collaboration.RepositoryID) (collaboration.RepositoryRef, error)

These are lookups of existing observations, never allocations, permission checks or credential selection. Both directions require the provider host; numeric equality, repository names and account logins cannot select it.

func (*Store) CollaborationRepositoryWindow

func (s *Store) CollaborationRepositoryWindow(ctx context.Context, after collaboration.RepositoryID, limit int) ([]collaboration.RepositoryRef, error)

CollaborationRepositoryWindow lists existing observations, never remote discovery or access grants. The extra row lets callers advance over denied observations without inventing a complete provider inventory.

func (*Store) CollaborationRuntime

func (s *Store) CollaborationRuntime(ctx context.Context, id collaboration.RuntimeID) (collaboration.RuntimeRef, error)

func (*Store) CollaborationTeam

func (s *Store) CollaborationTeam(ctx context.Context, id collaboration.TeamID) (collaboration.TeamRef, error)

func (*Store) CollaborationTeamByExternalID

func (s *Store) CollaborationTeamByExternalID(ctx context.Context, host collaboration.HostID, externalID string) (collaboration.TeamRef, error)

func (*Store) CollaborationTeamOnHost

func (s *Store) CollaborationTeamOnHost(ctx context.Context, host collaboration.HostID, id collaboration.TeamID) (collaboration.TeamRef, error)

func (*Store) CompleteNativeJudgment

func (s *Store) CompleteNativeJudgment(ctx context.Context, c factory.NativeJudgmentCapture, outcome json.RawMessage, usage factory.Usage) error

CompleteNativeJudgment records actual retired-process usage and its bounded result together. Withdrawal cannot suppress accounting for an original call.

func (*Store) CompleteReadinessWork

func (s *Store) CompleteReadinessWork(ctx context.Context, work ReadinessWork, now time.Time) (bool, error)

CompleteReadinessWork removes a completed source and records critical delivery acknowledgement in the same commit. false means nodes remain.

func (*Store) CompletionIntentRevision

func (s *Store) CompletionIntentRevision(ctx context.Context, scope factory.CompletionIntentScope) (factory.IntentRevision, error)

CompletionIntentRevision resolves the immutable accepted revision already exported in a sealed completion inventory. It supplies the owning controller's full revision for successor CAS; no private head or unaccepted draft is selected by this read.

func (*Store) CompletionPending

func (s *Store) CompletionPending(ctx context.Context, repository int64) ([]int64, error)

CompletionPending lists the pending completion generations for one repository in processing order: every generation whose cycle has not reached a terminal state. An empty list means the fence is open.

func (*Store) CompletionSourceContext

func (s *Store) CompletionSourceContext(ctx context.Context, repository int64) (factory.CompletionAuthority, error)

CompletionSourceContext projects the standing completion authority for one repository in a single repeatable-read transaction: the repo project plus the existing authority/head/policy projection, validated before commit. Only the safe authority value is returned.

func (*Store) ConnectionGeneration

func (s *Store) ConnectionGeneration(ctx context.Context, connectionID string, ownerID int64) (int64, error)

ConnectionGeneration returns the recorded generation for one identity connection bound to its owner. It reports a generic failure unless the row exists, the owner matches, the generation is at least 1 and the state is ready. It never selects credential columns.

func (*Store) ConsumeReservation

func (s *Store) ConsumeReservation(ctx context.Context, assignmentID string) error

ConsumeReservation marks one held reservation consumed by its recorded run. Consuming is the only transition a settled run takes; usage is recorded before this call so a crash replays through the held state.

func (*Store) ContributionContext

func (s *Store) ContributionContext(ctx context.Context, id string) (factory.ContributionReview, error)

func (*Store) ContributionSources

func (s *Store) ContributionSources(ctx context.Context) ([]string, error)

ContributionSources is a bounded read for the existing service continuation. System receipts, consultation comments and worker replies cannot recursively trigger invitations. Assignment records with a recorded result are eligible alongside human and worker posts. Submitted work posts stay in their assignment's discussion; completed results are invited through the record leg. A record whose reassessment cycle was superseded by an accepted successor retry is replaced history, never a source; that currentness predicate, the role-scope predicate and the source-profile exclusion (the record's own serving profile can never be its invited role, mirroring the post leg) all apply before the per-leg limits, and the merged window keeps each non-empty leg's newest so neither leg starves. Reading the feed itself never invokes this driver.

func (*Store) CreateApplication

func (s *Store) CreateApplication(ctx context.Context, r application.Record) error

CreateApplication persists an operator-admitted initial reference and its explicit administrator grant. The caller admits the operator; this store never manufactures a native installation observation or app identity.

func (*Store) CreateApplicationBuildSetup

func (s *Store) CreateApplicationBuildSetup(ctx context.Context, repository int64, id string, administrator int64) (application.SetupRecord, error)

One durable setup per build. A lost response returns the same reservation, preserving its data, expiry and owner; it cannot create a second identity.

func (*Store) CreateApplicationSetup

func (s *Store) CreateApplicationSetup(ctx context.Context, record application.SetupRecord) error

func (*Store) CreateDepartment

func (s *Store) CreateDepartment(ctx context.Context, d factory.Department) error

func (*Store) CreateProject

func (s *Store) CreateProject(ctx context.Context, p Project) error

func (*Store) CreationRecoveryCursor

func (s *Store) CreationRecoveryCursor(ctx context.Context, repository int64) (int64, error)

func (*Store) CreationRecoveryRepositories

func (s *Store) CreationRecoveryRepositories(ctx context.Context, after int64, limit int) ([]int64, error)

CreationRecoveryRepositories pages configured repositories without changing their policy revisions or treating the global work capacity as a product limit.

func (*Store) DeferReadinessWork

func (s *Store) DeferReadinessWork(ctx context.Context, id string, now time.Time) error

DeferReadinessWork drops partial node state, rotates the source, and applies capped exponential retry delay so failures cannot monopolize node capacity.

func (*Store) DeleteFeedPost

func (s *Store) DeleteFeedPost(ctx context.Context, id, author string, expected int64) (int64, error)

DeleteFeedPost tombstones one comment: the row and its bound pipeline still resolve, but the feed projection hides the body.

func (*Store) DeletePriorityScan

func (s *Store) DeletePriorityScan(ctx context.Context) error

DeletePriorityScan drops the current scan and its observations after completion or proven invalidation.

func (*Store) DeliveredIntentCandidates

func (s *Store) DeliveredIntentCandidates(ctx context.Context, after string, limit int) ([]DeliveredIntentCandidate, string, error)

DeliveredIntentCandidates examines one bounded accepted-head page. The cursor advances even when every intent is verified, undelivered or waiting, so the controller can rotate past it without dropping retained state.

func (*Store) DeliveryAlreadyAssigned

func (s *Store) DeliveryAlreadyAssigned(ctx context.Context, repository int64, delivery string) (bool, error)

func (*Store) DeliveryJudgment

func (s *Store) DeliveryJudgment(ctx context.Context, fingerprint string) (factory.DeliveryReceipt, error)

DeliveryJudgment reads one recorded delivery receipt by its evidence fingerprint. Missing fingerprints and non-delivery journal rows report ErrNotFound.

func (*Store) DeliveryJudgmentsForPublication

func (s *Store) DeliveryJudgmentsForPublication(ctx context.Context, publicationID, attemptRoot string, limit int) ([]factory.DeliveryReceipt, bool, error)

DeliveryJudgmentsForPublication returns up to limit recorded funded delivery receipts whose fingerprinted input names one publication and attempt root. Delivery acceptances carry the funded call identity rather than the evidence fingerprint, so the receipt join is over the recorded input scope (publication, attempt root); the caller binds the exact round and tuple. Every returned receipt revalidates, which recomputes its evidence fingerprint. The truncated flag mirrors the other journey readers.

func (*Store) DeliveryRepairCycle

func (s *Store) DeliveryRepairCycle(ctx context.Context, cycleID string) (DeliveryRepairRecord, factory.StallRepairCycle, error)

func (*Store) DeliveryRepairRecord

func (s *Store) DeliveryRepairRecord(ctx context.Context, repository int64, failedRun string) (DeliveryRepairRecord, error)

func (*Store) DeliveryRepairRequestAvailable

func (s *Store) DeliveryRepairRequestAvailable(ctx context.Context, cause factory.DeliveryRepairCause, now time.Time) (bool, error)

DeliveryRepairRequestAvailable is advisory, spend-free eligibility. The explicit owner request still repeats authority/native checks and records any missing default origin limit; charge/packet transactions remain authoritative.

func (*Store) DeliveryRetryAvailable

func (s *Store) DeliveryRetryAvailable(ctx context.Context, runID string) (bool, error)

DeliveryRetryAvailable projects the same retirement/accounting/version checks without recording a command or spending. The action rechecks them.

func (*Store) Departments

func (s *Store) Departments(ctx context.Context, owner int64) ([]factory.Department, error)

func (*Store) DispatchControlsAfter

func (s *Store) DispatchControlsAfter(ctx context.Context, limit int, firstSeen, repository, issue int64, hasCursor bool) ([]factory.IssueControl, error)

DispatchControlsAfter continues the deterministic oldest-first dispatch listing after one exclusive (first_seen_unix, repository, issue) cursor. Accepted controls blocked by authority join queued controls so reopening authority can resume them without a new native issue delivery. Dispatch rotation advances the cursor so a waiting prefix cannot starve later runnable work across repeated passes.

func (*Store) DispatchState

func (s *Store) DispatchState(ctx context.Context, repository int64) (bool, int64, factory.Withdrawal, error)

DispatchState returns the dispatch gate for one repository. A missing row means dispatch was never withdrawn: open at revision zero.

func (*Store) EditFeedPost

func (s *Store) EditFeedPost(ctx context.Context, id, author, body string, expected int64, at int64) (int64, error)

EditFeedPost records one new comment revision under CAS: the expected revision must match and the author must own the comment. Deleted or revoked sources refuse the edit.

func (*Store) EnqueueExternalPullEvent

func (s *Store) EnqueueExternalPullEvent(ctx context.Context, repository, number int64, head, delivery string) (bool, error)

EnqueueExternalPullEvent maps a provider locator to explicit, retained adoption commands. Factory-created PRs and unselected PRs never recurse into this path. Existing readiness work supplies dedupe, bounds and restart cursor; neither webhook content nor lookup absence creates another execution root.

func (*Store) EnqueueReadinessCreation

func (s *Store) EnqueueReadinessCreation(ctx context.Context, work ReadinessWork) error

EnqueueReadinessCreation retains original creation authority until admission and assessment complete. Redelivery may enrich an incomplete hint, but cannot replace authenticated original facts.

func (*Store) EnqueueReadinessCreationPage

func (s *Store) EnqueueReadinessCreationPage(ctx context.Context, repository, expected, next int64, works []ReadinessWork, policyRevision ...int64) error

EnqueueReadinessCreationPage advances native history only after every original observation is durable. Capacity, identity conflicts and stale cursors roll back the whole page, so a later serving pass can retry the same native tasks.

func (*Store) EnqueueReadinessRootEvent

func (s *Store) EnqueueReadinessRootEvent(ctx context.Context, repository, issue int64) error

EnqueueReadinessRootEvent coalesces one best-effort readiness root outside a domain transaction: after a continue release it forces a fresh assessment pass instead of reusing a stale snapshot.

func (*Store) EnqueueReadinessWork

func (s *Store) EnqueueReadinessWork(ctx context.Context, id, delivery string, root factory.DependenceRef) error

EnqueueReadinessWork durably admits or coalesces one root. A nonempty delivery makes the source critical and therefore subject to intake acknowledgement only by CompleteReadinessWork. An explicit redelivery wakes that source without changing its fair turn or saved progress.

func (*Store) EnvironmentGrant

func (s *Store) EnvironmentGrant(ctx context.Context, repository int64) (project.EnvironmentGrant, error)

EnvironmentGrant returns the standing environment permission for one repository.

func (*Store) ExecutionWorkspace

func (s *Store) ExecutionWorkspace(ctx context.Context, repository collaboration.RepositoryID) (string, *project.NativeEnvironment, error)

ExecutionWorkspace resolves the configured runtime without interpreting a native workspace ID as an appliance Project. Dispatch rechecks it atomically.

func (*Store) ExternalIssuePlan

func (s *Store) ExternalIssuePlan(ctx context.Context, repository, issue int64, base string) (factory.Assignment, error)

ExternalIssuePlan resolves actual planning provenance under the current accepted issue and exact base. Caller text, a previous PR description and another issue's plan are not substitutes for an admitted plan.

func (*Store) FactoryAuthorityInput

func (s *Store) FactoryAuthorityInput(ctx context.Context, repository int64) (factory.AuthorityInput, error)

FactoryAuthorityInput returns the current grant and preparation inputs used by both visible authority reads and atomic grant changes.

func (*Store) FactoryCommand

func (s *Store) FactoryCommand(ctx context.Context, id string) (factory.Command, error)

func (*Store) FactoryCurrentContext

func (s *Store) FactoryCurrentContext(ctx context.Context, cap factory.MCPCapability, now time.Time) (factory.CurrentContext, error)

FactoryCurrentContext reads one coherent current snapshot. Every join starts with the recorded capability and assignment; no repository inventory, parent prompt or historical sibling becomes readable through this method.

func (*Store) FactoryRoleAuthorityInput

func (s *Store) FactoryRoleAuthorityInput(ctx context.Context, repository int64, role string) (factory.AuthorityInput, error)

func (*Store) FactoryRun

func (s *Store) FactoryRun(ctx context.Context, id string) (factory.Run, error)

func (*Store) FactoryRunView

func (s *Store) FactoryRunView(ctx context.Context, runID string) (factory.RunView, error)

FactoryRunView returns the display binding for one run.

func (*Store) FactoryRunViews

func (s *Store) FactoryRunViews(ctx context.Context, limit int) ([]factory.RunView, error)

FactoryRunViews returns recorded display bindings, newest first, bounded for the Spaces collection read. Callers join runs to bindings in memory; absence of a binding leaves the run unbound, never hidden.

func (*Store) FactoryRuns

func (s *Store) FactoryRuns(ctx context.Context, limit int) ([]factory.Run, error)

FactoryRuns returns recorded runs, newest first, bounded for the private operator status read. Reconciliation never adopts host state it did not record; unknown runs stay invisible until recorded.

func (*Store) FactoryUnsettledRuns

func (s *Store) FactoryUnsettledRuns(ctx context.Context, limit int) ([]factory.Run, error)

FactoryUnsettledRuns returns recorded runs that reconcile has not settled, oldest first. Callers page until a short batch: settled history never displaces live work no matter how many settled rows exist.

func (*Store) FeedArtifact

func (s *Store) FeedArtifact(ctx context.Context, repo int64, id string) (factory.FeedArtifact, []byte, error)

func (*Store) FeedEntryByID

func (s *Store) FeedEntryByID(ctx context.Context, id string) (factory.FeedEntry, error)

FeedEntryByID addresses the same post identity from the timeline, parent link or reply action, including posts projected from canonical workflow records.

func (*Store) FeedMilestoneDetails

func (s *Store) FeedMilestoneDetails(ctx context.Context, entries []factory.FeedEntry) (map[string]FeedRecordDetail, error)

FeedMilestoneDetails reads the serving fields behind a window's milestone entries from their canonical owners: confirmed merges and verified completions authored by Factory, recorded Jev judgments authored by Jev. Entries whose milestone record cannot be read stay absent from the result rather than guessed.

func (*Store) FeedPost

func (s *Store) FeedPost(ctx context.Context, id string) (FeedPostDetail, error)

FeedPost reads one durable comment with its serving fields.

func (*Store) FeedPostDetails

func (s *Store) FeedPostDetails(ctx context.Context, ids []string) (map[string]FeedPostDetail, error)

FeedPostDetails reads the serving fields behind a set of post entries: author, time and the pipeline-derived status. Comments without a pipeline row report status open; deleted or revoked sources never reach the feed.

func (*Store) FeedPostSubmission

func (s *Store) FeedPostSubmission(ctx context.Context, repository int64, author, key string) (string, int64, error)

FeedPostSubmission recovers the existing command's current identity and revision from the same author/repository/idempotency index used by submission. It does not resolve a live parent or rewrite the captured body/source.

func (*Store) FeedRecordDetails

func (s *Store) FeedRecordDetails(ctx context.Context, ids []string) (map[string]FeedRecordDetail, error)

FeedRecordDetails reads the serving fields behind a set of record entries: the phase's canonical MCP profile as actor, its persona name as author, the recorded creation/finish time, a status composed from recorded phase/stage/outcome plus review verdict, verification outcome, finding/failure counts and any bound publication, merge and verified completion stages, the bound issue and PR, the produced candidate ref, and the recorded result summary (phase summary, plan approach, review summary or result summary, in that order). Fields the record does not supply stay empty; nothing is inferred beyond the recorded rows.

func (*Store) FeedReplyIDs

func (s *Store) FeedReplyIDs(ctx context.Context, repository int64, kind, source string, before int64) ([]string, int64, error)

FeedReplyIDs lists the actual conversation, including replies from other browsers. The caller authorizes the repository and source before this read. Posts retain direct-reply paging; work records include their discussion threads.

func (*Store) FeedSubscription

func (s *Store) FeedSubscription(ctx context.Context, subscriber string) (factory.FeedSubscription, int64, error)

FeedSubscription reads one subscriber's combined-feed preferences. A missing row reports revision 0 with an empty scope: the serving layer treats no preference as no subscribed repositories, never as the widest scope.

func (*Store) FinishAssignment

func (s *Store) FinishAssignment(ctx context.Context, a factory.Assignment) error

FinishAssignment stores one assignment's terminal outcome exactly once. Only an assigned assignment at its recorded revision finishes; anything else reports stale instead of overwriting a concurrent finish.

func (*Store) FinishMemberAccess

func (s *Store) FinishMemberAccess(ctx context.Context, pid string, uid int64, record MemberAccess, native project.MemberAccessState) error

func (*Store) FinishedMCPAccountingRuns

func (s *Store) FinishedMCPAccountingRuns(ctx context.Context, limit int) ([]factory.Run, error)

FinishedMCPAccountingRuns visits only held accounting behind a retired run whose immutable MCP terminal already finished its exact assignment.

func (*Store) FountainLedgerHost

func (s *Store) FountainLedgerHost(ctx context.Context) (collaboration.Host, error)

FountainLedgerHost returns the explicitly adopted appliance namespace. An empty native profile or unadopted retained ledger has no such association.

func (*Store) FreezeAttemptAllowances

func (s *Store) FreezeAttemptAllowances(ctx context.Context, repository, expectedGateRevision int64, now time.Time) error

func (*Store) FundRetainedCandidate

func (s *Store) FundRetainedCandidate(ctx context.Context, command, principal string, f factory.RetainedCandidateFunding, now time.Time) (factory.RetainedCandidateFundingReceipt, error)

func (*Store) GeneratedIntentCurrent

func (s *Store) GeneratedIntentCurrent(ctx context.Context, acceptance string) (bool, bool, error)

GeneratedIntentCurrent revalidates the accepted product revision behind a derived acceptance. Ordinary human issue acceptances have no generated link. FW32 (T37): this tests for existence of a current accepted-head binding, never an arbitrary LIMIT 1 row over historical bindings. A copied frozen acceptance appears in several revisions at once; only a binding whose revision is still the accepted head counts as current.

func (*Store) GetMCPCapability

func (s *Store) GetMCPCapability(ctx context.Context, id string) (factory.MCPCapability, error)

GetMCPCapability reads the recorded capability for admission. The row carries scope, never secret bytes.

func (*Store) HeldReservations

func (s *Store) HeldReservations(ctx context.Context, limit int) ([]factory.Reservation, error)

HeldReservations lists every held dispatch reservation, oldest first.

func (*Store) HumanBranchCreateDispatchState

func (s *Store) HumanBranchCreateDispatchState(ctx context.Context, c factory.HumanBranchCreateCapture) (factory.CommandDispatchState, error)

HumanBranchCreateDispatchState reads the exact capture's local fence. It proves neither current branch/permission facts nor ownership of an earlier claim.

func (*Store) HumanCommentCapture

func (*Store) HumanCommentDispatchState

func (s *Store) HumanCommentDispatchState(ctx context.Context, c factory.HumanCommentCapture) (factory.CommandDispatchState, error)

HumanCommentDispatchState reads the exact capture's local fence. It proves neither remote absence nor current authority. Absence is ErrNotFound.

func (*Store) HumanEditCapture

func (s *Store) HumanEditCapture(ctx context.Context, q factory.HumanEditCommand) (factory.HumanEditCapture, error)

func (*Store) HumanEditDispatchState

func (s *Store) HumanEditDispatchState(ctx context.Context, c factory.HumanEditCapture) (factory.CommandDispatchState, error)

HumanEditDispatchState reads an exact capture's local fence, not authority, remote absence or an atomic provider content condition.

func (*Store) HumanInlineCapture

func (*Store) HumanInlineDispatchState

func (s *Store) HumanInlineDispatchState(ctx context.Context, c factory.HumanInlineCapture) (factory.CommandDispatchState, error)

HumanInlineDispatchState reads the exact capture's local fence. It proves neither current head/permission facts nor ownership of an earlier claim.

func (*Store) HumanIssueCreateDispatchState

func (s *Store) HumanIssueCreateDispatchState(ctx context.Context, c factory.HumanIssueCreateCapture) (factory.CommandDispatchState, error)

HumanIssueCreateDispatchState reads the exact capture's local fence; it proves neither remote absence nor current authority. Absence is ErrNotFound.

func (*Store) HumanLockCapture

func (s *Store) HumanLockCapture(ctx context.Context, q factory.HumanLockCommand) (factory.HumanLockCapture, error)

func (*Store) HumanLockDispatchState

func (s *Store) HumanLockDispatchState(ctx context.Context, c factory.HumanLockCapture) (factory.CommandDispatchState, error)

HumanLockDispatchState reads the exact capture's local fence, not current authority, remote absence or proof that a lock can be safely replayed.

func (*Store) HumanMergeCapture

func (s *Store) HumanMergeCapture(ctx context.Context, q factory.HumanMergeCommand) (factory.HumanMergeCapture, error)

func (*Store) HumanMergeDispatchState

func (s *Store) HumanMergeDispatchState(ctx context.Context, c factory.HumanMergeCapture) (factory.CommandDispatchState, error)

HumanMergeDispatchState reads the exact capture's local fence. It proves neither current head/permission facts nor ownership of an earlier claim.

func (*Store) HumanPullCreateDispatchState

func (s *Store) HumanPullCreateDispatchState(ctx context.Context, c factory.HumanPullCreateCapture) (factory.CommandDispatchState, error)

HumanPullCreateDispatchState reads the exact capture's local fence. It proves neither current branch/permission facts nor ownership of an earlier claim.

func (*Store) HumanReviewCapture

func (*Store) HumanReviewDispatchState

func (s *Store) HumanReviewDispatchState(ctx context.Context, c factory.HumanReviewCapture) (factory.CommandDispatchState, error)

HumanReviewDispatchState reads the exact capture's local fence. It proves neither current head/permission facts nor ownership of an earlier claim.

func (*Store) HumanReviewRequestDispatchState

func (s *Store) HumanReviewRequestDispatchState(ctx context.Context, c factory.HumanReviewRequestCapture) (factory.CommandDispatchState, error)

HumanReviewRequestDispatchState reads the exact local capture's fence. It does not prove current permission, provider absence or ownership of a prior claim.

func (*Store) HumanStateCapture

func (s *Store) HumanStateCapture(ctx context.Context, q factory.HumanStateCommand) (factory.HumanStateCapture, error)

func (*Store) HumanStateDispatchState

func (s *Store) HumanStateDispatchState(ctx context.Context, c factory.HumanStateCapture) (factory.CommandDispatchState, error)

HumanStateDispatchState reads the exact capture's local fence; neither a retained row nor its absence establishes remote state or current authority.

func (*Store) HumanThreadCapture

func (*Store) HumanThreadDispatchState

func (s *Store) HumanThreadDispatchState(ctx context.Context, c factory.HumanThreadCapture) (factory.CommandDispatchState, error)

HumanThreadDispatchState reads the exact capture's local fence. It does not prove current authority, provider absence or safe replay of a resolution.

func (*Store) IncreaseAppVerificationAllowance

func (s *Store) IncreaseAppVerificationAllowance(ctx context.Context, intent string, owner, repository int64, principal string, change factory.AppVerificationAllowanceChange, now time.Time) (factory.AppVerificationAllowance, error)

IncreaseAppVerificationAllowance admits one finite limit increase. The grant command owns its identity and limits; responses read current limits and usage. Owner is canonical; principal is supplied by the authenticated admission adapter and retains its original audit meaning on command replay. repository is the canonical scope whose current authority was checked. It is compared under the head lock before recording or replaying any command.

func (*Store) InitializeEmptyCollaborationLedger

func (s *Store) InitializeEmptyCollaborationLedger(ctx context.Context) error

InitializeEmptyCollaborationLedger is an explicit composition step, not a side effect of opening storage. Retained provider-numbered rows require the separate Fountain adoption path; they must never share an unseeded allocator.

func (*Store) InspectSetupRenewClaim

func (s *Store) InspectSetupRenewClaim(ctx context.Context, setup application.SetupRecord) (SetupRenewClaim, error)

InspectSetupRenewClaim reconciles the durable owner claim for the exact setup BEFORE any token rotation or replacement. The check binds the same generation the renew acts on (setup identity and observed generation), the same owner (administrator), and the same application context (application references and namespace). It is read-only: interim fail-closed, the caller must refuse rotation and perform no renewal-audit mutation on EVERY outcome — committed, conflicting, unclaimed (Soda-side unproven), and uncertain alike — until the queued native reconciliation seam exists. A read failure is uncertain and returns an error; the caller must refuse without mutating, never guess. The same-operation holder generation is not a competing claim here: it is pinned by the caller's expected-container check and the host's own credential guards, which stay authoritative for host-side uncertainty.

func (*Store) IntakeDeliverySeen

func (s *Store) IntakeDeliverySeen(ctx context.Context, delivery string) (bool, error)

IntakeDeliverySeen reports whether a native webhook delivery ID was already assessed. Delivery IDs are native task UUIDs; redeliveries reuse them, so a seen ID suppresses duplicate intake work.

func (*Store) IntegrityCheck

func (s *Store) IntegrityCheck(ctx context.Context) error

IntegrityCheck verifies the opened store's schema version, required columns and immutability guards in a read-only transaction.

func (*Store) IntentAttemptAllowance

func (s *Store) IntentAttemptAllowance(ctx context.Context, repository int64, scope factory.IntentAttemptScope, root string) (factory.AttemptAllowance, error)

IntentAttemptAllowance returns the recorded time-only allowance for one exact intent root. The root assignment row must still match the requested scope; a wrong root, intent or owner refuses, as does any positive-issue spoof of the same root.

func (*Store) IntentExecutionAggregateForIntent

func (s *Store) IntentExecutionAggregateForIntent(ctx context.Context, intent string, owner int64) (IntentExecutionAggregate, error)

IntentExecutionAggregateForIntent computes the aggregate over the intent's revision history and their bound issues.

func (*Store) IntentExecutionLimit

func (s *Store) IntentExecutionLimit(ctx context.Context, intent string) (factory.IntentExecutionAllowance, error)

IntentExecutionLimit returns the currently recorded aggregate bound for one origin intent.

func (*Store) IntentExplorationReview

func (s *Store) IntentExplorationReview(ctx context.Context, intent, basis string, owner int64) (factory.SavedReview, error)

IntentExplorationReview finds the atomic exploration transition from one original draft. Head CAS permits at most one saved successor; ordinary saves have no review and cannot confirm exploration. Ambiguity refuses disclosure.

func (*Store) IntentGeneration

func (s *Store) IntentGeneration(ctx context.Context, revision string) (factory.IntentGeneration, error)

func (*Store) IntentGenerationHead

func (s *Store) IntentGenerationHead(ctx context.Context, revision string) (factory.IntentRevision, error)

IntentGenerationHead is an internal recovery lookup of the current accepted head behind an already registered generation. It supplies its recorded owner.

func (*Store) IntentGenerationOperation

func (s *Store) IntentGenerationOperation(ctx context.Context, operation string) (factory.IntentGeneration, error)

IntentGenerationOperation resolves only an original recorded workflow identity.

func (*Store) IntentHistory

func (s *Store) IntentHistory(ctx context.Context, intent string, owner int64, limit int) ([]factory.IntentRevision, error)

IntentHistory returns immutable revisions for one owner-private request, newest first, bounded to 50 entries. It follows the head backwards through recorded predecessors; a repository change after commitment creates a separate intent identity and never appears here.

func (*Store) IntentPlanAttempt

func (s *Store) IntentPlanAttempt(ctx context.Context, intentID, revisionID string) (factory.Assignment, error)

IntentPlanAttempt returns the latest decompose assignment recorded for one intent revision, or ErrNotFound when no planning run exists yet. The draft planning status read uses it to show pending/reported results without exposing any other assignment.

func (*Store) IntentReview

func (s *Store) IntentReview(ctx context.Context, resultRevision string, owner int64) (factory.SavedReview, error)

IntentReview returns the exact stored presentation for one result revision. Another owner's reviews and missing presentations both report ErrNotFound, so callers cannot distinguish them.

func (*Store) IntentRevision

func (s *Store) IntentRevision(ctx context.Context, intent string, owner int64) (factory.IntentRevision, error)

func (*Store) IntentTaskBindings

func (s *Store) IntentTaskBindings(ctx context.Context, revision string) ([]factory.IntentTaskBinding, error)

func (*Store) InvestigationPlan

func (s *Store) InvestigationPlan(ctx context.Context, attemptRoot, planID string) (factory.InvestigationPlan, error)

InvestigationPlan returns one persisted plan revision.

func (*Store) IssueControl

func (s *Store) IssueControl(ctx context.Context, repository, issue int64) (factory.IssueControl, error)

IssueControl returns the current readiness record for one native issue.

func (*Store) IssueControls

func (s *Store) IssueControls(ctx context.Context, repository int64, limit int) ([]factory.IssueControl, error)

IssueControls lists one repository's current readiness records oldest first: native issue indexes increase with creation, so index order is oldest-ready-first queue order. At most limit records are returned.

func (*Store) IssueIntakeGrant

func (s *Store) IssueIntakeGrant(ctx context.Context, id string, revision int64) (json.RawMessage, error)

func (*Store) IssueMergeCompletion

func (s *Store) IssueMergeCompletion(ctx context.Context, repository, issue int64) (factory.Merge, error)

IssueMergeCompletion returns the latest completed merge for one repository issue: the attributable factory completion behind code prerequisite satisfaction. Absence reports ErrNotFound.

func (*Store) Join

func (s *Store) Join(ctx context.Context, pid string, uid int64, login string) error

func (*Store) JourneyAdoptions

func (s *Store) JourneyAdoptions(ctx context.Context, repository, issue int64, limit int) ([]JourneyAdoption, bool, error)

JourneyAdoptions returns up to limit recorded adoptions naming one repository issue, oldest binding first. The join is canonical: factory_intent_tasks bindings by issue index, joined to their intent revision, whose recorded repository must match the journey scope. The truncated flag mirrors the other journey readers. Rows that decode, validate or scope-check refuse as storage errors.

func (*Store) JourneyDeliveredCompletion

func (s *Store) JourneyDeliveredCompletion(ctx context.Context, repository, issue int64, acceptance string) (factory.CompletionEvent, error)

JourneyDeliveredCompletion returns the latest canonical completion event behind one adopted native binding: the exact delivered-task evidence for the adopted task. Completions are immutable history, so the newest generation is the delivery proof; older generations stay out. No recorded completion is ErrNotFound, never an empty event.

func (*Store) JourneyReassignmentCycles

func (s *Store) JourneyReassignmentCycles(ctx context.Context, repository, issue int64, limit int) ([]ReassessmentRecord, bool, error)

JourneyReassignmentCycles returns up to limit reassessment cycles for one issue, including released and superseded decision history. Unresolved cycles take precedence over recent history at the bound. The result has stable generation/terminal-state/identity order, with current cycles last within each generation; explicit cycle lineage remains authoritative. The truncated flag reports whether more cycles name the issue than the limit carries, so the caller marks its read incomplete instead of rendering a cut set as the whole lineage. Rows that decode or validate refuse as storage errors: a corrupt recorded row is an explicit failure, never a skipped candidate.

func (*Store) JourneyVerifiedApp

func (s *Store) JourneyVerifiedApp(ctx context.Context, repository int64, intent, revision string) (JourneyVerifiedApp, error)

JourneyVerifiedApp returns the verified application evidence for one adopted intent revision. The read is spend-free and write-free: it joins the recorded verify assignment to its recorded F10 feed event under the same canonical identity, outcome and scope the delivery admission owns (finished verify, succeeded outcome, trusted verification outcome verified, exact intent, revision and scope digest, with the F10 event bound to both the delivery and the assignment). The observed manifest must equal the admitted VerificationManifestDigest, matching the delivery admission and the journey observation contract. A worker finish, another revision, a foreign scope, a foreign manifest, a non-verified result or an F10 event naming the wrong assignment never qualifies. Rows that decode, validate or scope-check refuse as storage errors; a missing assignment or event is ErrNotFound.

func (*Store) Keys

func (s *Store) Keys(ctx context.Context, uid int64) ([]Key, error)

func (*Store) LatestIssueAssignment

func (s *Store) LatestIssueAssignment(ctx context.Context, repository, issue int64) (factory.Assignment, error)

LatestIssueAssignment reads the newest issue root, which owns its publication. Child history cannot hide a newer active or terminal root.

func (*Store) LatestIssueAttempt

func (s *Store) LatestIssueAttempt(ctx context.Context, repository, issue int64) (factory.Assignment, error)

LatestIssueAttempt returns the newest recorded assignment for one repository issue, whatever its ownership. The newest row may be a child correction or review attempt: callers keep its AttemptRoot as the lineage root instead of implicitly re-rooting the journey on the child.

func (*Store) LatestPhaseAttempts

func (s *Store) LatestPhaseAttempts(ctx context.Context, repository, issue int64, acceptance, attemptRoot string) ([]PhaseAttempt, bool, error)

LatestPhaseAttempts returns the newest recorded assignment per distinct recorded phase value for one repository issue under the selected owner AttemptRoot and acceptance, newest first per group by stable seq order. One current state per phase means an old capped prefix can never stand in for a newer failed or current row, and a sibling AttemptRoot sharing the acceptance cannot leak in. The truncated flag reports whether more phase groups name the scope than the limit carries, so the caller marks its read incomplete instead of rendering a cut group set as the whole lineage. Rows that decode or scope-check refuse as storage errors: a corrupt recorded row is an explicit failure, never a skipped candidate.

func (*Store) LaunchApplicationRecord

func (s *Store) LaunchApplicationRecord(ctx context.Context, id string) (application.Record, error)

LaunchApplicationRecord is the authorization-free read backing the launch-only projection. The caller must admit the reader: administrator grant, operator scope, or a visible linked project. It never grants lifecycle or administration authority on its own.

func (*Store) LibraryRead

func (s *Store) LibraryRead(ctx context.Context, repository int64, id string, includeRemoved bool) (factory.LibraryRead, error)

func (*Store) LibrarySearch

func (s *Store) LibrarySearch(ctx context.Context, repository int64, query, kind, cursor string, includeRemoved, currentOnly bool) (factory.LibraryPage, error)

func (*Store) LifecycleGrant

func (s *Store) LifecycleGrant(ctx context.Context, projectID string) (project.LifecycleGrant, error)

LifecycleGrant returns the standing create/start grant for one project.

func (*Store) ListIntentRevisions

func (s *Store) ListIntentRevisions(ctx context.Context, owner int64, f factory.IntentListFilter) ([]factory.IntentSummary, string, error)

ListIntentRevisions returns bounded owner-private resume summaries with a stable intent-ID cursor. It lists only the caller's current heads; another actor's drafts and inaccessible private details never appear. Empty returns an empty slice, never a null; database failures return an error for 503.

func (*Store) LoadPriorityScan

func (s *Store) LoadPriorityScan(ctx context.Context) (PriorityScanState, error)

LoadPriorityScan returns the current scan with its observations, or ErrNotFound when no scan is retained.

func (*Store) LookupHumanCommandDispatch

func (s *Store) LookupHumanCommandDispatch(ctx context.Context, cmd factory.Command) (collaboration.OperationLookup, error)

LookupHumanCommandDispatch reads local dispatch history only. The adapter must admit its current account and decode the saved provider intent before calling; neither an unclaimed row nor an absent reply grants provider authority.

func (*Store) MCPDiscussion

func (s *Store) MCPDiscussion(ctx context.Context, capability factory.MCPCapability, postID, cursor string) (factory.MCPFeedPage, error)

func (*Store) MCPInbox

func (s *Store) MCPInbox(ctx context.Context, capability factory.MCPCapability, cursor string) (factory.MCPFeedPage, error)

func (*Store) MCPRunWasObserved

func (s *Store) MCPRunWasObserved(ctx context.Context, run, assignment, project string) (bool, error)

MCPRunWasObserved retains execution history after capability retirement. Staging, revocation and confirmed-unused settlement do not set this fact.

func (*Store) MCPSubmissionCount

func (s *Store) MCPSubmissionCount(ctx context.Context, assignmentID string) (int, error)

func (*Store) MCPTaskOutputSubmissions

func (s *Store) MCPTaskOutputSubmissions(ctx context.Context, assignment string) ([]factory.MCPSubmission, error)

MCPTaskOutputSubmissions reads the immutable authenticated parent proposals. Journal sequence, rather than submission identity, orders their checkpoints.

func (*Store) MCPWorkStatus

func (s *Store) MCPWorkStatus(ctx context.Context, assignmentID, submissionID string) (factory.MCPWorkStatus, error)

func (*Store) MaintenanceHold

func (s *Store) MaintenanceHold(ctx context.Context, projectID string) (project.MaintenanceHold, error)

MaintenanceHold returns the current maintenance hold for one project. A missing row means no hold was ever recorded.

func (*Store) MarkFeedPostRevoked

func (s *Store) MarkFeedPostRevoked(ctx context.Context, id string) error

MarkFeedPostRevoked records access loss on one comment: bound effects block instead of applying against a source the caller can no longer see.

func (*Store) MarkReady

func (s *Store) MarkReady(ctx context.Context, id, ip string) error

func (*Store) MemberAccess

func (s *Store) MemberAccess(ctx context.Context, pid string, uid int64) (MemberAccess, error)

func (*Store) MemberIdentity

func (s *Store) MemberIdentity(ctx context.Context, pid string, uid int64) (string, error)

func (*Store) MemberLogin

func (s *Store) MemberLogin(ctx context.Context, pid string, uid int64) (string, error)

func (*Store) Members

func (s *Store) Members(ctx context.Context, project string) ([]Member, error)

Members is a bounded scan of project membership for the administrator listing, mirroring the SpaceProjects cap: callers must authorize every returned row and must not treat the cap as an exact roster.

func (*Store) MergeByOperation

func (s *Store) MergeByOperation(ctx context.Context, id string) (factory.Merge, error)

MergeByOperation resolves only the current canonical operation. Superseded generations never gain permission to send through this lookup.

func (*Store) MergeByPublication

func (s *Store) MergeByPublication(ctx context.Context, publicationID string) (factory.Merge, error)

MergeByPublication returns one publication's merge.

func (*Store) MergeForIssue

func (s *Store) MergeForIssue(ctx context.Context, repository, issue int64) (factory.Merge, error)

MergeForIssue returns the latest merge for one repository issue, any stage. Absence reports ErrNotFound: no merge exists yet for it.

func (*Store) MergeSendDeadline

func (s *Store) MergeSendDeadline(ctx context.Context, m factory.Merge, candidate int64) (int64, error)

MergeSendDeadline admits only the finite merge grant. It never opens an inference allowance, changes its counters or makes an assignment executable.

func (*Store) MergeablePublications

func (s *Store) MergeablePublications(ctx context.Context, limit int) ([]factory.Publication, error)

MergeablePublications lists published publications that carry no merge yet, oldest first. Only natively completed exact PRs merge; anything else never reaches this listing.

func (*Store) MergedPreparationSource

func (s *Store) MergedPreparationSource(ctx context.Context, repository int64, projectID, target, tip string) (project.FactoryMergedSource, error)

MergedPreparationSource addresses only an exact successfully completed publication whose attributable merge is the selected current target tip. Its export remains the reviewed coder candidate, which can differ from a squash/rebase/merge result. It does not manufacture export bytes for that result.

func (*Store) NativeFactoryRun

func (s *Store) NativeFactoryRun(ctx context.Context, profile collaboration.ProfileID, brokerRun string) (factory.Run, error)

NativeFactoryRun resolves a broker selector through retained canonical data. It reads settled history too: a leftover native root is not necessarily an unsettled product run. No match, invalid data and ambiguous selectors supply no recovery authority. This read neither admits launch nor settles a run.

func (*Store) NativeJudgmentReady

func (s *Store) NativeJudgmentReady(ctx context.Context, c factory.NativeJudgmentCapture, requiredMinutes int) error

NativeJudgmentReady is a read-only preflight. BeginNativeJudgment repeats it under the repository grant lock before reserving any source or dispatch.

func (*Store) NativeJudgmentRetry

func (s *Store) NativeJudgmentRetry(ctx context.Context, parent string) (factory.Command, error)

NativeJudgmentRetry discovers the last explicit retry before considering a new command. A lost client identity never permits repeating pending inference.

func (*Store) NativeProjectForCollaborationRepository

func (s *Store) NativeProjectForCollaborationRepository(ctx context.Context, repository collaboration.RepositoryID) (Project, error)

NativeProjectForCollaborationRepository resolves an existing association. A missing/unadopted/foreign mapping returns ErrNotFound; it does not prove remote absence, deny provider access, or authorize execution on the returned Project.

func (*Store) NativeRecoveryCandidates

func (s *Store) NativeRecoveryCandidates(ctx context.Context, profile collaboration.ProfileID, after int64) ([]NativeRecoveryCandidate, string, error)

NativeRecoveryCandidates includes observed processes even when Go missed the final native receipt before root removal. Native recovery must still verify retained terminal/custody facts and acknowledge exact root retirement. An unobserved intent alone does not establish that a worker existed.

func (*Store) NextReadinessWork

func (s *Store) NextReadinessWork(ctx context.Context, now time.Time) (ReadinessWork, error)

NextReadinessWork chooses the next due source and advances the round-robin turn. Node allocation remains deferred until BeginReadinessWork.

func (*Store) NextReadinessWorkNode

func (s *Store) NextReadinessWorkNode(ctx context.Context, id string) (ReadinessWorkNode, error)

NextReadinessWorkNode returns a scanning node before an unvisited queued node. The caller assesses queued nodes and resumes scanning nodes by cursor.

func (*Store) NoteAllowanceExhausted

func (s *Store) NoteAllowanceExhausted(ctx context.Context, repository, issue int64, at int64) error

NoteAllowanceExhausted records one durable allowance-exhausted notice for an issue waiting on coder-time sponsorship. Identity is per issue, so repeated dispatch passes replay it without duplicating the card; a later launch's assignment event marks resumption. Unlike the transient dispatch observation (owner/admin-only until restart), the Feed card is visible to every authorized reader until the wait clears.

func (*Store) NotePostAttempt

func (s *Store) NotePostAttempt(ctx context.Context, postID string) error

NotePostAttempt records one funded judgment, draft or native retry against the bounded attempt count. Exhaustion refuses instead of spending blindly.

func (*Store) NotePostAuthoring

func (s *Store) NotePostAuthoring(ctx context.Context, id string, revision int64, progress factory.PostAuthoring, now int64) error

func (*Store) NotePostContextWait

func (s *Store) NotePostContextWait(ctx context.Context, id string, revision int64, reason, detail string) error

NotePostContextWait cannot attach a late capture failure to newer writing or overwrite successfully captured context. The caller owns this exact revision.

func (*Store) NotePostProgress

func (s *Store) NotePostProgress(ctx context.Context, id, detail string) error

NotePostProgress retains a safe user-facing reason and rotates waiting requests through the continuation queue without consuming model attempts.

func (*Store) NotePostRouting

func (s *Store) NotePostRouting(ctx context.Context, id string, routing factory.PostRouting) error

NotePostRouting keeps JEV's routing Choice beside the request.

func (*Store) NotePostStall

func (s *Store) NotePostStall(ctx context.Context, id, reason string) error

NotePostStall records why a request cannot move on its own (empty clears).

func (*Store) ObserveApplication

func (s *Store) ObserveApplication(ctx context.Context, id string, actorID, revision int64, expected, next *application.Observation) error

ObserveApplication publishes a matching native result with both reference revision and prior-observation CAS. Pass nil after an uncertain native call; nil remains unknown and cannot become readiness from desired references.

func (*Store) ObserveApplicationSetup

func (s *Store) ObserveApplicationSetup(ctx context.Context, before application.SetupRecord, next *application.SetupObservation) error

func (*Store) ObserveCollaborationActor

func (s *Store) ObserveCollaborationActor(ctx context.Context, host collaboration.HostID, externalID, login string) (collaboration.ActorRef, error)

An empty login records identity-only evidence without replacing a known login.

func (*Store) ObserveCollaborationConnectionRepository

func (s *Store) ObserveCollaborationConnectionRepository(ctx context.Context, connection collaboration.ConnectionRef, externalID, name string) (collaboration.RepositoryRef, error)

ObserveCollaborationConnectionRepository atomically records a provider repo and which exact account binding observed it. The caller must supply current remotely observed metadata; this association is never an access grant or a complete inventory, and it must not survive as cached permission evidence.

func (*Store) ObserveCollaborationRepository

func (s *Store) ObserveCollaborationRepository(ctx context.Context, host collaboration.HostID, externalID, name string) (collaboration.RepositoryRef, error)

Empty display metadata ensures the observed identity with an external-ID placeholder, preserving any existing label even across concurrent observers.

func (*Store) ObserveCollaborationTeam

func (s *Store) ObserveCollaborationTeam(ctx context.Context, host collaboration.HostID, externalID, name string) (collaboration.TeamRef, error)

ObserveCollaborationTeam records an observed provider team, not membership or current access. An empty display name preserves known metadata. The shared allocation gate runs before evaluating the independent team's ID sequence.

func (*Store) ObserveFountainPlacement

func (s *Store) ObserveFountainPlacement(ctx context.Context, p factory.Placement, profile collaboration.ProfileID) error

ObserveFountainPlacement retains a fresh central observation for this native profile. It never selects a host runtime or grants execution/publication. The native connector verifies the exact enrollment owner before calling it; dispatch still needs an original host claim and current operation grant.

func (*Store) ObserveHumanBranchCreate

func (s *Store) ObserveHumanBranchCreate(ctx context.Context, capture factory.HumanBranchCreateCapture, observation collaboration.OperationLookup) (collaboration.OperationLookup, error)

func (*Store) ObserveHumanComment

func (s *Store) ObserveHumanComment(ctx context.Context, capture factory.HumanCommentCapture, observation collaboration.OperationLookup) (collaboration.OperationLookup, error)

func (*Store) ObserveHumanEdit

func (*Store) ObserveHumanInline

func (s *Store) ObserveHumanInline(ctx context.Context, capture factory.HumanInlineCapture, observation collaboration.OperationLookup) (collaboration.OperationLookup, error)

func (*Store) ObserveHumanIssueCreate

func (s *Store) ObserveHumanIssueCreate(ctx context.Context, capture factory.HumanIssueCreateCapture, observation collaboration.OperationLookup) (collaboration.OperationLookup, error)

func (*Store) ObserveHumanLock

func (*Store) ObserveHumanMerge

func (*Store) ObserveHumanPullCreate

func (s *Store) ObserveHumanPullCreate(ctx context.Context, capture factory.HumanPullCreateCapture, observation collaboration.OperationLookup) (collaboration.OperationLookup, error)

func (*Store) ObserveHumanReview

func (s *Store) ObserveHumanReview(ctx context.Context, capture factory.HumanReviewCapture, observation collaboration.OperationLookup) (collaboration.OperationLookup, error)

func (*Store) ObserveHumanReviewRequest

func (s *Store) ObserveHumanReviewRequest(ctx context.Context, capture factory.HumanReviewRequestCapture, observation collaboration.OperationLookup) (collaboration.OperationLookup, error)

func (*Store) ObserveHumanState

func (*Store) ObserveHumanThread

func (s *Store) ObserveHumanThread(ctx context.Context, capture factory.HumanThreadCapture, observation collaboration.OperationLookup) (collaboration.OperationLookup, error)

func (*Store) ObserveNativeChecks

func (s *Store) ObserveNativeChecks(ctx context.Context, repository, pull int64, digest string) (int64, error)

ObserveNativeChecks versions the exact paired PR/CI observation. This is local observation identity, not a global GitHub revision or merge authority.

func (*Store) ObserveNativeIssueInputs

func (s *Store) ObserveNativeIssueInputs(ctx context.Context, repository, issue int64, digest string, occurrences []string) (int64, map[string]string, error)

ObserveNativeIssueInputs maps provider history IDs and versions the observed issue/edge snapshot. Selected comments and branch tips are checked separately; reading another selected subset must not change an issue's canonical revision. This records observations only, without admitting acceptance or execution.

func (*Store) ObserveNativeRecovery

func (s *Store) ObserveNativeRecovery(ctx context.Context, profile collaboration.ProfileID, intent string, receipt execution.NativeReceiptObservation, custody *execution.NativeCustodyObservation, desktopUID int) error

ObserveNativeRecovery locks and advances only native facts against the exact retained Go intent. It neither admits work nor settles outcome/accounting. Replays and concurrent observations use the same immutable advance checks.

func (*Store) ObserveNativeReview

func (s *Store) ObserveNativeReview(ctx context.Context, repository, pull int64, digest string) (int64, error)

func (*Store) ObservePreparation

func (s *Store) ObservePreparation(ctx context.Context, p execution.PreparationRecord) error

func (*Store) OpenMerges

func (s *Store) OpenMerges(ctx context.Context, limit int) ([]factory.Merge, error)

OpenMerges lists every open or fenced merge across repositories, oldest first, for pass recovery. Deferred work waits for a later pass; nothing here submits without reconciling first.

func (*Store) OpenPublications

func (s *Store) OpenPublications(ctx context.Context, limit int) ([]factory.Publication, error)

func (*Store) OperatorApplication

func (s *Store) OperatorApplication(ctx context.Context, id string) (application.Record, error)

OperatorApplication requires operator admission by its caller. Ordinary administrators use Application, which checks the stored stable grant.

func (*Store) OperatorApplications

func (s *Store) OperatorApplications(ctx context.Context) ([]application.Record, error)

OperatorApplications requires operator admission by its caller.

func (*Store) OperatorGrant

func (s *Store) OperatorGrant(ctx context.Context, repository int64) (factory.OperatorGrant, error)

OperatorGrant returns the operator permission for one repository.

func (*Store) OutstandingMerges

func (s *Store) OutstandingMerges(ctx context.Context, repository int64, limit int) ([]factory.Merge, error)

OutstandingMerges lists every open or fenced merge for one repository, oldest first. Recovery reconciles each one against native state; withdrawal cancels each one's outstanding operation.

func (*Store) OutstandingPublications

func (s *Store) OutstandingPublications(ctx context.Context, repository int64, limit int) ([]factory.Publication, error)

OutstandingPublications lists every open or fenced publication and each published record with an unresolved correction for one repository, oldest first. Recovery reconciles each one against native state; withdrawal cancels each one's outstanding operations.

func (*Store) OwnContributions

func (s *Store) OwnContributions(ctx context.Context) (*ContributionOwner, error)

func (*Store) PendingAppVerifications

func (s *Store) PendingAppVerifications(ctx context.Context, after int64, limit int) ([]factory.Assignment, int64, error)

PendingAppVerifications includes finished Test Pilot reports until a trusted whole-app completion is recorded. Worker receipts alone never remove them. The exclusive sequence cursor lets the controller revisit stale reports without keeping later adoptable reports behind the same waiting prefix.

func (*Store) PendingApplicationRestore

func (s *Store) PendingApplicationRestore(ctx context.Context, app string) (*application.RestoreOperation, error)

func (*Store) PendingCandidatePreparations

func (s *Store) PendingCandidatePreparations(ctx context.Context, limit int) ([]CandidatePreparationRecord, error)

PendingCandidatePreparations includes untransferred coder setup and closed roots whose model runs have settled. Transferred native preparations with settled consumers are also observed for original retirement receipts; an open root never authorizes actively retiring their checkout.

func (*Store) PendingCompletionRepositories

func (s *Store) PendingCompletionRepositories(ctx context.Context) ([]int64, error)

PendingCompletionRepositories lists every repository with at least one unresolved cycle, so the completion driver fences and releases per repository without scanning unrelated work.

func (*Store) PendingDeliveryRepairRecords

func (s *Store) PendingDeliveryRepairRecords(ctx context.Context, after string, limit int) ([]DeliveryRepairRecord, string, error)

func (*Store) PendingDeliveryRetry

func (s *Store) PendingDeliveryRetry(ctx context.Context, repository int64, subject factory.DeliverySubject) (factory.RetryDecision, error)

PendingDeliveryRetry selects only an explicit unconsumed command for the same immutable version. Normal polling never retries an incomplete report.

func (*Store) PendingExplicitRetry

func (s *Store) PendingExplicitRetry(ctx context.Context, repository, issue int64, acceptance string) (factory.RetryDecision, error)

PendingExplicitRetry returns one finished retry command for the latest finished assignment on the issue's unchanged acceptance. Its command ID becomes the fresh assignment identity, so a recorded packet consumes it. Its exact coder preparation's confirmed native stop also ends that command's admission; retained command/preparation history cannot hide a later Retry.

func (*Store) PendingImplementationRetry

func (s *Store) PendingImplementationRetry(ctx context.Context, repository, issue int64, acceptance string) (factory.RetryDecision, error)

func (*Store) PendingIntentGenerations

func (s *Store) PendingIntentGenerations(ctx context.Context, after string, limit int) ([]factory.IntentRevision, error)

PendingIntentGenerations recovers accepted heads that lack confirmed graph adoption. Refused terminal operations await a newly reviewed revision.

func (*Store) PendingNativeJudgments

func (s *Store) PendingNativeJudgments(ctx context.Context) ([]factory.Command, error)

func (*Store) PendingPostIntakes

func (s *Store) PendingPostIntakes(ctx context.Context, limit int) ([]factory.PostIntake, error)

PendingPostIntakes lists durable comment requests the service-side driver may still advance: judgment pending, or a new_issue route whose draft or native effect is unsettled. Closed (deleted/revoked) sources never list. Settled routes (discussion, existing work, clarify), failed judgments, invalid drafts and settled effects are final and stay off the list, so a restart resumes each stored request instead of re-deriving it.

func (*Store) PendingPublicationChildren

func (s *Store) PendingPublicationChildren(ctx context.Context, afterAssignment string, limit int) ([]factory.Assignment, error)

PendingPublicationChildren lists finished child results awaiting their first native registration. Registered operations retain their existing recovery path. Only the current published head is eligible for a new effect. The assignment cursor bounds each pass without letting a waiting child permanently displace later work; a missing cursor starts at the oldest row.

func (*Store) PendingReassessmentCycles

func (s *Store) PendingReassessmentCycles(ctx context.Context, repository int64) ([]ReassessmentRecord, error)

PendingReassessmentCycles lists every unresolved cycle for one repository in generation order so the completion driver processes the oldest event first. Released and superseded cycles are history, not work.

func (*Store) PendingReviewPublications

func (s *Store) PendingReviewPublications(ctx context.Context, limit int) ([]factory.Publication, error)

PendingReviewPublications excludes settled review history from the bounded pass.

func (*Store) PendingStallRepairRecords

func (s *Store) PendingStallRepairRecords(ctx context.Context, limit int) ([]StallRepairRecord, error)

func (*Store) PendingStandingPreparations

func (s *Store) PendingStandingPreparations(ctx context.Context, after string, limit int) ([]execution.PreparationRecord, error)

PendingStandingPreparations rotates a bounded observation page across Projects. Private candidate preparation keeps its existing custody owner.

func (*Store) Ping

func (s *Store) Ping(ctx context.Context) error

Ping verifies the PostgreSQL connection is live without touching product rows. Readiness probes use it; a failed ping means the dashboard cannot serve admitted work.

func (*Store) Placement

func (s *Store) Placement(ctx context.Context, repository collaboration.RepositoryID) (factory.Placement, error)

func (*Store) PlanHead

func (s *Store) PlanHead(ctx context.Context, attemptRoot string) (string, int64, error)

PlanHead returns the current plan pointer for one attempt root.

func (*Store) PlanTaskReceipt

func (s *Store) PlanTaskReceipt(ctx context.Context, attemptRoot, planID, taskID string) (PlanTaskReceipt, error)

PlanTaskReceipt returns the persisted state and evidence for one task.

func (*Store) PlanTaskReceipts

func (s *Store) PlanTaskReceipts(ctx context.Context, attemptRoot, planID string) ([]PlanTaskReceipt, error)

PlanTaskReceipts lists the persisted receipts under one plan revision in task-key order, so a restart observes task evidence instead of redoing it.

func (*Store) PostAuthoring

func (s *Store) PostAuthoring(ctx context.Context, id string) (*factory.PostAuthoring, error)

func (*Store) PostDraft

func (s *Store) PostDraft(ctx context.Context, postID string, revision int64) (factory.IssueDraft, error)

PostDraft reads the retained draft behind one comment, refusing when the bound revision moved on (edited source) or no draft exists.

func (*Store) PostFeedbackRequested

func (s *Store) PostFeedbackRequested(ctx context.Context, id string, revision int64) (bool, error)

func (*Store) PostIntake

func (s *Store) PostIntake(ctx context.Context, postID string) (factory.PostIntake, error)

PostIntake reads the durable request behind one comment.

func (*Store) PostIssueContext

func (s *Store) PostIssueContext(ctx context.Context, id string, revision int64) ([]factory.PostWorkCandidate, error)

func (*Store) PostIssueMaker

func (s *Store) PostIssueMaker(ctx context.Context, id string, revision int64) (factory.IssueMakerProgress, error)

func (*Store) PostProductChange

func (s *Store) PostProductChange(ctx context.Context, detail FeedPostDetail, pipe factory.PostIntake, actor int64) (*PostProductChange, error)

func (*Store) PostProgress

func (s *Store) PostProgress(ctx context.Context, id string) (string, error)

func (*Store) PostRouting

func (s *Store) PostRouting(ctx context.Context, id string) (*factory.PostRouting, error)

PostRouting reads the recorded routing Choice, nil before JEV answers.

func (*Store) PostStall

func (s *Store) PostStall(ctx context.Context, id string) (string, error)

func (*Store) PostUsesIssueMaker

func (s *Store) PostUsesIssueMaker(ctx context.Context, id string, revision int64) (bool, error)

PostUsesIssueMaker reads the captured intake path at its exact revision. Missing, unreadable or unsupported metadata cannot select legacy authoring.

func (*Store) Preparation

func (s *Store) Preparation(ctx context.Context, id string) (execution.PreparationRecord, error)

Preparation returns one durable preparation record by identity.

func (*Store) PrepareIssueMakerMutation

func (s *Store) PrepareIssueMakerMutation(ctx context.Context, post, operation, hash, key string, request factory.IssueMakerMutation) (factory.IssueMakerMutation, error)

PrepareIssueMakerMutation allocates bounded native slots/steps under the role-post lock and retains exact request bytes before any native effect.

func (*Store) PrepareUnsentMerge

func (s *Store) PrepareUnsentMerge(ctx context.Context, command, principal string, r factory.MergePreparation, now time.Time) (factory.MergePreparationReceipt, error)

PrepareUnsentMerge archives the exact old row in the existing command's outcome, then creates a new identity under current authority. This is only possible before any operation identity, binding, work, attempt or effect.

func (*Store) PreviousGeneratedIntent

func (s *Store) PreviousGeneratedIntent(ctx context.Context, intent, revision string) (factory.IntentRevision, error)

PreviousGeneratedIntent follows recorded predecessors rather than assuming the previous review draft already owns a native graph.

func (*Store) PriorityJudgment

func (s *Store) PriorityJudgment(ctx context.Context, snapshot string) (factory.PriorityReceipt, error)

func (*Store) PriorityReceiptsForIssue

func (s *Store) PriorityReceiptsForIssue(ctx context.Context, repository, issue int64, cursor PriorityComparisonCursor, limit int) ([]factory.PriorityReceipt, bool, error)

PriorityReceiptsForIssue returns completed priority receipts naming one native issue, newest first, with a has-more flag for cursor paging. Receipts are keyed by candidate-set snapshot in the journal; this read discovers the recent comparisons behind one issue without rebuilding the eligible set, judging options or dispatching work.

func (*Store) Project

func (s *Store) Project(ctx context.Context, id string) (Project, error)

func (*Store) ProjectByRepository

func (s *Store) ProjectByRepository(ctx context.Context, id int64) (Project, error)

ProjectByRepository takes the appliance's native repository ID. Factory local IDs must use NativeProjectForCollaborationRepository at the identity boundary.

func (*Store) ProjectFactoryRuns

func (s *Store) ProjectFactoryRuns(ctx context.Context, projectID string, limit int) ([]factory.Run, error)

ProjectFactoryRuns returns one project's recorded runs, newest first. It bounds display history; correctness paths union it with ProjectUnsettledRuns so settled history never hides live work.

func (*Store) ProjectMaintenanceWork

func (s *Store) ProjectMaintenanceWork(ctx context.Context) (factory, preparation int, err error)

ProjectMaintenanceWork returns bounded global counts of active or uncertain managed work. The sentinel 129 means at least 129, never a complete larger count. Appliance readiness can finish setup; a native preparation requires an explicit scoped retirement receipt. Ready alone does not prove native stop; missing observations and interrupted/failed setup remain explicit blockers until their exact candidate owner records confirmed native retirement.

func (*Store) ProjectPreparations

func (s *Store) ProjectPreparations(ctx context.Context, projectID string) ([]execution.PreparationRecord, error)

ProjectPreparations lists the durable preparation records for one project.

func (*Store) ProjectUnsettledRuns

func (s *Store) ProjectUnsettledRuns(ctx context.Context, projectID string, limit int) ([]factory.Run, error)

ProjectUnsettledRuns returns one project's recorded runs that reconcile has not settled, oldest first. Stop, resume and verification decisions read this instead of filtering a bounded newest-first listing.

func (*Store) PublicationByAssignment

func (s *Store) PublicationByAssignment(ctx context.Context, assignmentID string) (factory.Publication, error)

PublicationByAssignment returns one assignment's publication.

func (*Store) PublicationByID

func (s *Store) PublicationByID(ctx context.Context, id string) (factory.Publication, error)

func (*Store) PublicationExecutionOwner

func (s *Store) PublicationExecutionOwner(ctx context.Context, p factory.Publication, owner factory.Assignment) (factory.Assignment, error)

PublicationExecutionOwner reads the actual prior owner for candidate/plan provenance. It never changes the retained owner's root, run or authority.

func (*Store) PublicationOperation

func (s *Store) PublicationOperation(ctx context.Context, id string) (factory.Publication, factory.PublicationOperation, error)

Resolve only the operation frozen in the canonical publication. A provider command or matching branch name cannot invent workflow ownership.

func (*Store) PublicationReviewOperation

func (s *Store) PublicationReviewOperation(ctx context.Context, operation string) (factory.Publication, factory.ReviewOperation, error)

PublicationReviewOperation resolves only registered immutable review work. Native lookup and cancellation use this record even after authority withdrawal.

func (*Store) PublishableAssignments

func (s *Store) PublishableAssignments(ctx context.Context, limit int) ([]factory.Assignment, error)

PublishableAssignments lists finished assignments whose harness reported a completed exact candidate and that carry no publication yet, oldest first. Only succeeded work with an attributable report publishes; synthesized results never do.

func (*Store) PutCollaborationConnection

func (s *Store) PutCollaborationConnection(ctx context.Context, ref collaboration.ConnectionRef) error

func (*Store) PutCollaborationHost

func (s *Store) PutCollaborationHost(ctx context.Context, host collaboration.Host) (collaboration.Host, error)

Registry methods persist observations and bindings only. They grant no remote permission or spending, and never accept/store provider credentials.

func (*Store) PutCollaborationProfile

func (s *Store) PutCollaborationProfile(ctx context.Context, profile collaboration.Profile) error

func (*Store) PutCollaborationRuntime

func (s *Store) PutCollaborationRuntime(ctx context.Context, ref collaboration.RuntimeRef) error

func (*Store) QueuedControls

func (s *Store) QueuedControls(ctx context.Context, limit int) ([]factory.IssueControl, error)

QueuedControls lists queued readiness records across every repository, oldest first seen first with repository and issue breaking ties. The order is deterministic: the same records always visit in the same order.

func (*Store) ReadRepairObservation

func (s *Store) ReadRepairObservation(ctx context.Context, cap factory.MCPCapability, id string, offset int) (factory.RepairObservationPage, error)

ReadRepairObservation reads only this active investigator's diagnosis or draft post. A reference grants no broader read.

func (*Store) ReadinessWork

func (s *Store) ReadinessWork(ctx context.Context, id string) (ReadinessWork, error)

ReadinessWork returns one source header; absent IDs report ErrNotFound.

func (*Store) ReassessmentAttemptAllowance

func (s *Store) ReassessmentAttemptAllowance(ctx context.Context, repository int64, subject factory.CompletionSubject, root string) (factory.AttemptAllowance, error)

ReassessmentAttemptAllowance returns the recorded time-only allowance for one exact completion root. The root assignment row must still match the requested scope and completion subject; a wrong root, event, cycle or digest refuses, as does any positive-issue spoof of the same root.

func (*Store) ReassessmentRecord

func (s *Store) ReassessmentRecord(ctx context.Context, cycleID string) (ReassessmentRecord, error)

ReassessmentRecord reads one cycle by its ID for the completion driver and explicit Retry validation.

func (*Store) ReassessmentScope

func (s *Store) ReassessmentScope(ctx context.Context, cap factory.MCPCapability, after int64) (factory.RepairScopeView, error)

ReassessmentScope reads only this assignment's attributed intermediate report references. Full contents remain in the existing inbox/feed owner.

func (*Store) RecentPostWorkCandidates

func (s *Store) RecentPostWorkCandidates(ctx context.Context, repository int64, limit int) ([]factory.PostWorkCandidate, error)

RecentPostWorkCandidates lists the most recently worked native issues in one repository as existing-work candidates for comment routing: the latest assignment per issue supplies the recorded summary and status through the canonical feed record read. Issues with no recorded factory work never appear; nothing is inferred beyond the recorded rows.

func (*Store) RecordAppVerificationWait

func (s *Store) RecordAppVerificationWait(ctx context.Context, a factory.Assignment, reason string) error

func (*Store) RecordCandidatePreparationStop

func (s *Store) RecordCandidatePreparationStop(ctx context.Context, id string, state execution.PreparationState) error

func (*Store) RecordCheckAssessment

func (s *Store) RecordCheckAssessment(ctx context.Context, a factory.CheckAssessment) (factory.CheckAssessment, error)

RecordCheckAssessment stores the latest check assessment for one native PR, replacing any earlier head's verdict. The caller leaves Revision zero; the store counts records. ST12 reads the latest record and must re-verify its head/base/policy bindings before consuming it.

func (*Store) RecordCompletionRetryCommand

func (s *Store) RecordCompletionRetryCommand(ctx context.Context, cmd factory.Command, repository int64, request factory.CompletionRetryRequest, now time.Time) (factory.CompletionRetryDecision, error)

RecordCompletionRetryCommand admits the owner's request and its single successor atomically. The previous cycle and paid ledger stay intact; responses derive from the request instead of a separately saved outcome.

func (*Store) RecordConsultationRequest

func (s *Store) RecordConsultationRequest(ctx context.Context, c SystemOneConsultation) error

RecordConsultationRequest records the exact permitted input before dispatch. The canonical assignment record is the consulting worker's stable work post. A repeated snapshot retains its original request, lifecycle and timestamp.

func (*Store) RecordConsultationResult

func (s *Store) RecordConsultationResult(ctx context.Context, snapshot, model, status string, answer map[string]any) error

RecordConsultationResult advances only the recorded outcome. A returned answer cannot be overwritten by a later timeout/replay. Missing rows fail.

func (*Store) RecordDeliveryAdmissionWait

func (s *Store) RecordDeliveryAdmissionWait(ctx context.Context, revision factory.IntentRevision, reason string) error

func (*Store) RecordDeliveryJudgment

func (s *Store) RecordDeliveryJudgment(ctx context.Context, r factory.DeliveryReceipt) error

RecordDeliveryJudgment stores a completed decision without a placeholder. A completed decision for the same input key cannot be overwritten.

func (*Store) RecordDeliveryRepairCause

func (s *Store) RecordDeliveryRepairCause(ctx context.Context, cause factory.DeliveryRepairCause, now time.Time) (DeliveryRepairRecord, bool, error)

func (*Store) RecordDeliveryRetryCommand

func (s *Store) RecordDeliveryRetryCommand(ctx context.Context, cmd factory.Command, decision factory.RetryDecision, repository int64, now time.Time) (factory.Command, bool, error)

RecordDeliveryRetryCommand uses the ordinary owner Retry request for a terminal, accounted issue-zero verifier. It does not reopen its old root.

func (*Store) RecordDispatchPacket

func (s *Store) RecordDispatchPacket(ctx context.Context, expected factory.IssueControl, a factory.Assignment, r factory.Reservation, run factory.Run, view factory.RunView) error

RecordDispatchPacket checks the gate and stores one dispatch atomically: the exact current queued control, the assigned assignment, its held reservation, the recorded run and the display binding. Either the whole packet lands or nothing does, so a crash never leaves a reservation without its assignment or a run without its dispatch. A second unfinished assignment for the issue refuses with ErrAssignmentActive instead of dispatching twice. The control row is locked after the dispatch gate and before packet writes; readiness assessment takes the same row lock, so changed or missing outcome evidence refuses the whole transaction. Admission also locks the acceptance head shared with acceptance withdrawal; a replaced or withdrawn head refuses even before readiness is reassessed.

The packet is also the atomic admission gate: the limit rows are locked, the packet records, and then appliance, repository, sponsorship and spend-cap limits are rechecked inside the same transaction. Concurrent passes serialize here, so only room that actually exists is admitted; the losers wait instead of launching.

func (*Store) RecordExplicitRetryCommand

func (s *Store) RecordExplicitRetryCommand(ctx context.Context, cmd factory.Command, decision factory.RetryDecision, repository, issue int64, acceptance string, now time.Time) (factory.Command, bool, error)

func (*Store) RecordExplicitRetryPacket

func (s *Store) RecordExplicitRetryPacket(ctx context.Context, decision factory.RetryDecision, expected factory.IssueControl, a factory.Assignment, r factory.Reservation, run factory.Run, view factory.RunView) error

func (*Store) RecordExternalPlanningPublication

func (s *Store) RecordExternalPlanningPublication(ctx context.Context, a factory.Assignment, p factory.Publication, now time.Time) (factory.Publication, error)

RecordExternalPlanningPublication promotes only a real completed Architect with its paid completeness opinion and admitted plan. It reuses the original root allowance, source, policy and PR origin, including the planning charge.

func (*Store) RecordExternalPublicationCommand

func (s *Store) RecordExternalPublicationCommand(ctx context.Context, cmd factory.Command, request factory.ExternalPullAdoption, a factory.Assignment, p factory.Publication, now time.Time) (factory.Publication, error)

RecordExternalPublicationCommand admits one explicitly funded external PR. It uses the same dispatch gate, canonical publication, assignment, command journal and finite attempt allowance as own delivery. No native send is authorized by this transaction and no old authority is renewed.

func (*Store) RecordFactoryRun

func (s *Store) RecordFactoryRun(ctx context.Context, r factory.Run) error

RecordFactoryRun stores a fresh supervised run before any host call. A consumed run ID is never reused; only the supervisor mutates the record.

func (*Store) RecordFactoryRunView

func (s *Store) RecordFactoryRunView(ctx context.Context, v factory.RunView) (factory.RunView, bool, error)

RecordFactoryRunView stores the display binding for one recorded run. The same binding replays; changed content for the same run conflicts instead of rebinding the run to another issue or attempt.

func (*Store) RecordImplementationRetryCommand

func (s *Store) RecordImplementationRetryCommand(ctx context.Context, cmd factory.Command, decision factory.RetryDecision, repository, issue int64, acceptance string, now time.Time) (factory.Command, bool, error)

func (*Store) RecordImplementationRetryPacket

func (s *Store) RecordImplementationRetryPacket(ctx context.Context, decision factory.RetryDecision, expected factory.IssueControl, a factory.Assignment, r factory.Reservation, run factory.Run, view factory.RunView) error

func (*Store) RecordIntakeDelivery

func (s *Store) RecordIntakeDelivery(ctx context.Context, delivery string, repository, issue int64, kind string, now time.Time) (bool, error)

RecordIntakeDelivery logs one assessed delivery and prunes the dedup log to its bound. A duplicate ID replays without logging twice.

func (*Store) RecordIntentGeneration

func (s *Store) RecordIntentGeneration(ctx context.Context, g factory.IntentGeneration, receipt factory.GraphReceiptFacts) error

RecordIntentGeneration retains the original provider receipt and outcome. Decoded facts must match that receipt before any delivered-history check.

func (*Store) RecordIssueAssessment

func (s *Store) RecordIssueAssessment(ctx context.Context, candidate factory.IssueControl, now time.Time) (factory.IssueControl, bool, error)

RecordIssueAssessment stores one readiness assessment when its inputs changed: equal fingerprints replay the current record without advancing the revision, so unchanged blockers never trigger repeated work. The first assessment for an issue always records.

func (*Store) RecordIssueMakerIntake

func (s *Store) RecordIssueMakerIntake(ctx context.Context, postID string, revision int64) error

func (*Store) RecordIssueMakerIssue

func (s *Store) RecordIssueMakerIssue(ctx context.Context, scope factory.IssueMakerScope, key string, slot int, index int64, title, body string) error

RecordIssueMakerIssue publishes exactly one reply per native issue key. A refinement updates that reply instead of presenting another created issue.

func (*Store) RecordMCPSubmission

func (s *Store) RecordMCPSubmission(ctx context.Context, submission factory.MCPSubmission) (factory.MCPWorkStatus, error)

RecordMCPSubmission records the work on its post. The capability row serializes requests from the active run; no separate guard row is needed.

func (*Store) RecordMerge

func (s *Store) RecordMerge(ctx context.Context, m factory.Merge) error

RecordMerge stores one publication's fresh open merge. One publication merges at most once: a second record for the publication refuses instead of merging twice.

func (*Store) RecordNativeDispatchPacket

func (s *Store) RecordNativeDispatchPacket(ctx context.Context, expected factory.IssueControl, a factory.Assignment, r factory.Reservation, run factory.Run, view factory.RunView, native execution.NativeLaunch) error

RecordNativeDispatchPacket is the native producer's explicit admission entry. Retained native observations cannot enter the appliance packet by accident.

func (*Store) RecordNativeExplicitRetryPacket

func (s *Store) RecordNativeExplicitRetryPacket(ctx context.Context, decision factory.RetryDecision, expected factory.IssueControl, a factory.Assignment, r factory.Reservation, run factory.Run, view factory.RunView, native execution.NativeLaunch) error

func (*Store) RecordNativeImplementationRetryPacket

func (s *Store) RecordNativeImplementationRetryPacket(ctx context.Context, decision factory.RetryDecision, expected factory.IssueControl, a factory.Assignment, r factory.Reservation, run factory.Run, view factory.RunView, native execution.NativeLaunch) error

func (*Store) RecordNativeRootRetirement

func (s *Store) RecordNativeRootRetirement(ctx context.Context, profile collaboration.ProfileID, intent, invocation, acquisition string) error

RecordNativeRootRetirement consumes the trusted native owner's separate broker acknowledgement after process/acquisition facts are retained. This advances resources only, never product outcome, reservation or accounting.

func (*Store) RecordPostDraft

func (s *Store) RecordPostDraft(ctx context.Context, draft factory.IssueDraft) error

RecordPostDraft retains one LLM-authored issue draft bound to its exact comment source revision. A malformed draft refuses before any native effect.

func (*Store) RecordPostIntake

func (s *Store) RecordPostIntake(ctx context.Context, postID string, revision int64) error

RecordPostIntake opens the durable request behind one comment revision: intake recorded, judgment/draft/effect pending. Replaying the same comment recovers the row instead of duplicating it.

func (*Store) RecordPostIssueCreation

func (s *Store) RecordPostIssueCreation(ctx context.Context, post string, revision, issue int64) error

RecordPostIssueCreation settles that same source revision even if its author edited or revoked it during provider I/O. -1 records a provider-proved refusal; zero remains unknown. A conflicting issue cannot replace a recorded result.

func (*Store) RecordPriorityJudgment

func (s *Store) RecordPriorityJudgment(ctx context.Context, judgment factory.PriorityReceipt) error

RecordPriorityJudgment stores a completed decision directly.

func (*Store) RecordPriorityProgress

func (s *Store) RecordPriorityProgress(ctx context.Context, nativeRevision int64, localDigest string, observations []PriorityCandidateObservation, cursor int) error

RecordPriorityProgress persists observations and advances the cursor. A changed scan digest refuses: the pass must revalidate before writing.

func (*Store) RecordPublication

func (s *Store) RecordPublication(ctx context.Context, p factory.Publication) error

RecordPublication stores one assignment's fresh open publication. One assignment publishes at most once: a second record for the assignment refuses instead of publishing twice.

func (*Store) RecordRepositoryOpening

func (s *Store) RecordRepositoryOpening(ctx context.Context, repository, at int64) error

RecordRepositoryOpening consumes the signed native creation event. The repository identity, rather than the webhook delivery ID, makes redelivery harmless. A Factory question has no human intake and starts no worker.

func (*Store) RecordRetainedPublicationCommand

func (s *Store) RecordRetainedPublicationCommand(ctx context.Context, cmd factory.Command, a factory.Assignment, p factory.Publication, now time.Time) (factory.Publication, error)

RecordRetainedPublicationCommand creates only a publication owner and its branch/PR journal. Original executions, uncertain effects and allowances are immutable. The command ID is the new owner and publication identity.

func (*Store) RecordRetryPacket

func (s *Store) RecordRetryPacket(ctx context.Context, a factory.Assignment, expected factory.IssueControl, authority factory.AuthorityRef, run factory.Run, view factory.RunView, planned int) (factory.Assignment, error)

func (*Store) RecordReviewRetry

func (s *Store) RecordReviewRetry(ctx context.Context, command, principal string, r factory.ReviewRetry, w factory.ReviewWork, now time.Time) (factory.Publication, error)

RecordReviewRetry freezes the fresh five-minute submission and its command in the same publication transaction. Old work, outcomes and allowances stay exact.

func (*Store) RecordRunUsage

func (s *Store) RecordRunUsage(ctx context.Context, u factory.Usage) error

RecordRunUsage appends one settled run's confirmed consumption. The first write wins: a replayed settle replays the recorded minutes instead of charging twice.

func (*Store) RecordTakeover

func (s *Store) RecordTakeover(ctx context.Context, r factory.TakeoverRecord) (factory.TakeoverRecord, error)

RecordTakeover saves the confirmed runtime result on its attributed Feed post. The run/destination key identifies the event and its canonical result.

func (*Store) RecordVerifiedApplication

func (s *Store) RecordVerifiedApplication(ctx context.Context, a factory.Assignment, manifest factory.ApprovedAppCheck, state execution.PreparationState) error

RecordVerifiedApplication is called only after independent native observation of the approved check. Recheck current authority and delivered scope inside the same transaction as the F10 event.

func (*Store) RecordWorkerPost

func (s *Store) RecordWorkerPost(ctx context.Context, submission factory.MCPSubmission) (FeedPostDetail, error)

RecordWorkerPost records a worker message and its library effects directly in the post transaction. The post's normal idempotency key owns repeat calls; there is no second submission record or receipt to recover.

func (*Store) RecordedExecutionWorkspace

func (s *Store) RecordedExecutionWorkspace(ctx context.Context, repository collaboration.RepositoryID) (string, error)

RecordedExecutionWorkspace supplies the repository owner for observation and shutdown even after grants or placement are withdrawn. It admits no new work.

func (*Store) RecordedTerminalMCPAssignments

func (s *Store) RecordedTerminalMCPAssignments(ctx context.Context, limit int) ([]string, error)

RecordedTerminalMCPAssignments lists distinct assignments carrying a recorded terminal MCP proposal, in assignment order, bounded by limit. Non-terminal traffic and consumed receipts never list.

func (*Store) RecordedWorkspaceRepository

func (s *Store) RecordedWorkspaceRepository(ctx context.Context, workspace string, native bool) (collaboration.RepositoryID, error)

RecordedWorkspaceRepository resolves canonical history without admitting execution.

func (*Store) RecoverContributionReviews

func (s *Store) RecoverContributionReviews(ctx context.Context, after int64) (ContributionRecovery, error)

func (*Store) RecoverNativeCapabilityRetirement

func (s *Store) RecoverNativeCapabilityRetirement(ctx context.Context) error

RecoverNativeCapabilityRetirement consumes existing sealed receipts only. Unknown or unsettled native records never become confirmed retirement here.

func (*Store) ReholdReservation

func (s *Store) ReholdReservation(ctx context.Context, r factory.Reservation) error

ReholdReservation returns one released reservation to held for the next attempt of the same assignment, carrying the new plan. Only a released reservation re-holds; held and consumed capacity never double counts.

func (*Store) ReleaseReservation

func (s *Store) ReleaseReservation(ctx context.Context, assignmentID string) error

ReleaseReservation marks one held reservation released: its capacity was confirmed unused and counts against no limit anymore.

func (*Store) RemainingAppVerificationSeconds

func (s *Store) RemainingAppVerificationSeconds(ctx context.Context, repository int64, intent string, now time.Time) (int64, error)

RemainingAppVerificationSeconds is the spend-free planning view. Packet admission repeats this read while holding the stable intent head lock.

func (*Store) RemainingDeliveryRepairMinutes

func (s *Store) RemainingDeliveryRepairMinutes(ctx context.Context, repository int64, failedRun string, now time.Time) (int, error)

RemainingDeliveryRepairMinutes is a spend-free dispatch planning bound. Admission repeats the same actual origin-time join under the grant lock.

func (*Store) RemoveKey

func (s *Store) RemoveKey(ctx context.Context, uid, id int64, confirmLast bool) (bool, error)

func (*Store) RenameProfile

func (s *Store) RenameProfile(ctx context.Context, id int64, name string) error

func (*Store) RenewApplicationSetup

func (s *Store) RenewApplicationSetup(ctx context.Context, before application.SetupRecord, administratorID int64) (application.SetupRecord, error)

RenewApplicationSetup re-arms an expired pending reservation on its retained address and data. Only the expiry advances, within a bounded grace window and a finite renewal count; id, references, administrator and state are unchanged, and the namespace reservation is never released. administratorID records the renewing operator for audit. The caller re-begins the returned record through the ordinary host begin flow. Interim fail-closed: no HTTP caller may invoke this until the queued native reconciliation seam proves the durable claim (the API refuses every rotation-adjacent outcome first). The primitive is retained for that seam — and for tests staging its committed-renewal premise below the HTTP refusal — not as a currently reachable path.

func (*Store) ReopenDispatch

func (s *Store) ReopenDispatch(ctx context.Context, repository, expectedRevision int64) (bool, int64, error)

ReopenDispatch clears non-Project-stop causes under the locked dispatch row. A Project stop remains in force until a verified Project start clears it.

func (*Store) RepairCharges

func (s *Store) RepairCharges(ctx context.Context, repository int64) ([]factory.RepairCharge, error)

RepairCharges lists every recorded charge under one repository grant scope in spend order, across all grant revisions. An explicit increase preserves this history; nothing is orphaned by a raise.

func (*Store) RepairEpisodeRecord

func (s *Store) RepairEpisodeRecord(ctx context.Context, repository int64, episode string) (StallRepairRecord, error)

func (*Store) RepairEpisodeViews

func (s *Store) RepairEpisodeViews(ctx context.Context, repository int64) ([]factory.RepairEpisodeView, error)

func (*Store) RepairGrantCommand

func (s *Store) RepairGrantCommand(ctx context.Context, repository int64) (factory.RepairGrant, error)

RepairGrantCommand returns the currently finished repair grant for one repository.

func (*Store) ReplaceApplication

func (s *Store) ReplaceApplication(ctx context.Context, actorID, expectedRevision int64, next application.Spec) error

ReplaceApplication atomically preserves immutable history and advances the admitted references with a revision CAS. Native success remains unknown.

func (*Store) ReplacePlanHead

func (s *Store) ReplacePlanHead(ctx context.Context, plan factory.InvestigationPlan, expectedPlanID string) error

ReplacePlanHead saves a new immutable revision and moves the head pointer to it in one transaction. A conflicting reuse of the plan identity aborts before the pointer moves, so the consumed original survives replacement.

func (*Store) RepositoryActivity

func (s *Store) RepositoryActivity(ctx context.Context, repository int64) (factory.RepositoryActivity, error)

RepositoryActivity derives bounded local facts. Pending native effects and committed merges still awaiting original issue closure never become events. Navigation is projected by the admitted host, not the durable facts reader.

func (*Store) RepositoryDispatchCounts

func (s *Store) RepositoryDispatchCounts(ctx context.Context, repository int64) (queued, active int, err error)

RepositoryDispatchCounts reports exact recorded queue/assignment states. Active means assigned dispatch work, not a claim about a live host process.

func (*Store) RepositoryPolicy

func (s *Store) RepositoryPolicy(ctx context.Context, repository int64) (factory.RepositoryPolicy, error)

RepositoryPolicy returns the standing policy for one repository.

func (*Store) RequirementDecision

func (s *Store) RequirementDecision(ctx context.Context, id string) (project.RequirementDecision, error)

RequirementDecision returns one recorded requirement acceptance.

func (*Store) RequirementDepth

func (s *Store) RequirementDepth(ctx context.Context, projectID string) (int64, error)

RequirementDepth counts the recorded requirement chain from the first decision to the head. Preparation references carry this depth.

func (*Store) RequirementHead

func (s *Store) RequirementHead(ctx context.Context, projectID string) (string, error)

RequirementHead returns the current requirement decision for one project.

func (*Store) Reservation

func (s *Store) Reservation(ctx context.Context, assignmentID string) (factory.Reservation, error)

Reservation returns one dispatch reservation by its assignment identity.

func (*Store) ReserveHumanBranchCreateDispatch

func (s *Store) ReserveHumanBranchCreateDispatch(ctx context.Context, c factory.HumanBranchCreateCapture) (bool, error)

ReserveHumanBranchCreateDispatch commits before one native creation attempt. Only receiving true permits one send. Reserved state cannot recover ownership.

func (*Store) ReserveHumanCommentDispatch

func (s *Store) ReserveHumanCommentDispatch(ctx context.Context, c factory.HumanCommentCapture) (bool, error)

ReserveHumanCommentDispatch commits before network use. Only true permits one attempt; a reserved read never recovers permission after a lost commit reply.

func (*Store) ReserveHumanEditDispatch

func (s *Store) ReserveHumanEditDispatch(ctx context.Context, c factory.HumanEditCapture) (bool, error)

ReserveHumanEditDispatch commits before dispatch. Only the caller receiving true may send once. A reserved read cannot recover lost claim ownership.

func (*Store) ReserveHumanInlineDispatch

func (s *Store) ReserveHumanInlineDispatch(ctx context.Context, c factory.HumanInlineCapture) (bool, error)

ReserveHumanInlineDispatch commits before one native inline attempt. Only receiving true permits one send. Reserved state cannot recover ownership.

func (*Store) ReserveHumanIssueCreateDispatch

func (s *Store) ReserveHumanIssueCreateDispatch(ctx context.Context, c factory.HumanIssueCreateCapture) (bool, error)

ReserveHumanIssueCreateDispatch commits a one-shot claim before network use. Only true permits one attempt; a reserved read never recovers that permission.

func (*Store) ReserveHumanLockDispatch

func (s *Store) ReserveHumanLockDispatch(ctx context.Context, c factory.HumanLockCapture) (bool, error)

ReserveHumanLockDispatch commits before native dispatch. Only receiving true grants one attempt; reserved state cannot recover lost claim ownership.

func (*Store) ReserveHumanMergeDispatch

func (s *Store) ReserveHumanMergeDispatch(ctx context.Context, c factory.HumanMergeCapture) (bool, error)

ReserveHumanMergeDispatch commits before one native merge attempt. Only receiving true permits one send. Reserved state cannot recover ownership.

func (*Store) ReserveHumanPullCreateDispatch

func (s *Store) ReserveHumanPullCreateDispatch(ctx context.Context, c factory.HumanPullCreateCapture) (bool, error)

ReserveHumanPullCreateDispatch commits before one native creation attempt. Only receiving true permits one send. Reserved state cannot recover ownership.

func (*Store) ReserveHumanReviewDispatch

func (s *Store) ReserveHumanReviewDispatch(ctx context.Context, c factory.HumanReviewCapture) (bool, error)

ReserveHumanReviewDispatch commits before one native review attempt. Only receiving true permits one send. Reserved state cannot recover ownership.

func (*Store) ReserveHumanReviewRequestDispatch

func (s *Store) ReserveHumanReviewRequestDispatch(ctx context.Context, c factory.HumanReviewRequestCapture) (bool, error)

ReserveHumanReviewRequestDispatch commits before a one-shot native effect. Only receiving true permits one send; reserved state cannot recover ownership.

func (*Store) ReserveHumanStateDispatch

func (s *Store) ReserveHumanStateDispatch(ctx context.Context, c factory.HumanStateCapture) (bool, error)

ReserveHumanStateDispatch commits before native effect dispatch. Only the caller receiving true may send once; a reserved read cannot recover ownership.

func (*Store) ReserveHumanThreadDispatch

func (s *Store) ReserveHumanThreadDispatch(ctx context.Context, c factory.HumanThreadCapture) (bool, error)

ReserveHumanThreadDispatch commits before a one-shot native effect. Only the caller receiving true may send once; observing reserved cannot recover a claim.

func (*Store) ReserveIssueDependency

func (s *Store) ReserveIssueDependency(ctx context.Context, c factory.IssueDependencyCapture) (bool, error)

func (*Store) ReserveRefPublicationDispatch

func (s *Store) ReserveRefPublicationDispatch(ctx context.Context, c factory.RefPublicationCapture) (bool, error)

func (*Store) ResolveArtifactDigest

func (s *Store) ResolveArtifactDigest(ctx context.Context, repository int64, assignment, digest string) (string, error)

ResolveArtifactDigest maps one cited content digest to a complete artifact of the assignment. A digest with no complete row here is unknown, foreign or unfinished, and the caller must refuse it.

func (*Store) ResolvePostParent

func (s *Store) ResolvePostParent(ctx context.Context, repository int64, id string) (*factory.PostSource, error)

ResolvePostSource resolves one caller-named feed entry inside the given repository into its persisted source snapshot. Unknown, closed or cross-repository entries report ErrNotFound without disclosing which: the caller already proved repository visibility, and the source must live inside that same repository. Evidence comes from the canonical owners only — the assignment row and the feed record read for records, the stored comment and its pipeline status for posts. ResolvePostParent resolves the one parent relationship for both stored messages and posts projected from canonical work records. The caller supplies no type.

func (*Store) ResolvePostSource

func (s *Store) ResolvePostSource(ctx context.Context, repository int64, kind, id string) (*factory.PostSource, error)

func (*Store) RetainedCandidateFundingOffer

func (s *Store) RetainedCandidateFundingOffer(ctx context.Context, publication string) (factory.RetainedCandidateFunding, error)

RetainedCandidateFundingOffer is a read-only snapshot. Only the explicit command below can create an allowance; neither this read nor publication does.

func (*Store) RetireMCPCapability

func (s *Store) RetireMCPCapability(ctx context.Context, id string) error

RetireMCPCapability moves an active capability to retired after terminal settlement and confirmed native retirement. Revoked rows stay revoked; retirement never reactivates.

func (*Store) RetryFeedPost

func (s *Store) RetryFeedPost(ctx context.Context, id, author string, expected int64, body string, at int64) error

RetryFeedPost preserves the original post and prior processing history. Uncertain issue writes keep their draft/identity for reconciliation; a new judgment/planning attempt gets a new source revision instead of another post.

func (*Store) RetryIssueMakerFeedPostCommand

func (s *Store) RetryIssueMakerFeedPostCommand(ctx context.Context, request factory.FeedPostRetryCommand, at int64) (receipt factory.FeedPostRetryReceipt, replayed bool, err error)

RetryIssueMakerFeedPostCommand commits the retry and its immutable receipt in one transaction. replayed is true only for an already committed command; that path never changes the current post/intake. Callers must admit current actor visibility and authorship before calling, including when recovering a receipt.

func (*Store) ReviewPostProductChange

func (s *Store) ReviewPostProductChange(ctx context.Context, id string, revision, owner, at int64) (factory.IntentRevision, error)

ReviewPostProductChange creates one same-intent successor draft and its source-comment receipt atomically. No planner, issue or acceptance is invoked.

func (*Store) ReviewRetryOffer

func (s *Store) ReviewRetryOffer(ctx context.Context, publication string) (factory.ReviewRetry, error)

ReviewRetryOffer contains only an existing terminal no-send and current policy. Reading this offer creates neither send authority nor inference funding.

func (*Store) RevokeExpiredIssueMakerRuns

func (s *Store) RevokeExpiredIssueMakerRuns(ctx context.Context, repository int64) error

RevokeExpiredIssueMakerRuns uses the existing capability revocation as the durable stop intent. No worker is reauthorized when a source is continued.

func (*Store) RevokeMCPCapability

func (s *Store) RevokeMCPCapability(ctx context.Context, id string) error

RevokeMCPCapability moves an active or staged capability to revoked: expiry, withdrawal and key rotation land here. Retired rows stay retired; revocation never reactivates.

func (*Store) RevokedFactoryRuns

func (s *Store) RevokedFactoryRuns(ctx context.Context, repository int64, limit int) ([]factory.Run, error)

func (*Store) RunUsage

func (s *Store) RunUsage(ctx context.Context, runID string) (factory.Usage, error)

RunUsage returns one settled run's confirmed consumption.

func (*Store) SaveApplicationBuild

func (s *Store) SaveApplicationBuild(ctx context.Context, repository int64, deliveryID string, artifact application.BuildArtifact) (ApplicationBuild, error)

func (*Store) SaveCapacity

func (s *Store) SaveCapacity(ctx context.Context, c factory.Capacity) error

SaveCapacity records the appliance capacity under CAS revision.

func (*Store) SaveContextCurrentResolution

func (s *Store) SaveContextCurrentResolution(ctx context.Context, expected factory.MCPCapability, request factory.ContextCurrentRequest, principal string, now time.Time) (factory.ContextCurrentResolution, error)

SaveContextCurrentResolution saves the owner's choice on its capability. Scope, deadlines, paid judgment and attempt allowances retain their owners.

func (*Store) SaveDeliveryRepairRecord

func (s *Store) SaveDeliveryRepairRecord(ctx context.Context, record DeliveryRepairRecord, expected int64) error

func (*Store) SaveEnvironmentGrant

func (s *Store) SaveEnvironmentGrant(ctx context.Context, g project.EnvironmentGrant) error

SaveEnvironmentGrant records the owner's standing environment permission under CAS revision. A withdrawn grant is an inactive row, never deleted.

func (*Store) SaveFactoryFinalCheckpoint

func (s *Store) SaveFactoryFinalCheckpoint(ctx context.Context, run factory.Run, result execution.CheckpointReceipt) error

SaveFactoryFinalCheckpoint retains only a confirmed native response. The request is immutable once reserved; terminal native evidence never changes.

func (*Store) SaveFactoryRun

func (s *Store) SaveFactoryRun(ctx context.Context, r factory.Run) error

SaveFactoryRun persists supervisor observations. Credential facts and the settled marker only advance; a terminal outcome never changes. Admission metadata belongs to the dispatch transaction and is preserved when an observation omits it; an attempted replacement refuses.

func (*Store) SaveFeedPost

func (s *Store) SaveFeedPost(ctx context.Context, req factory.PostRequest, author, authorName string, at int64) (string, int64, error)

SaveFeedPost persists one comment submission and returns its durable identity. A repeated idempotency key from the same author and repository replays the original identity instead of inserting a duplicate; the body of the replayed call is ignored.

func (*Store) SaveFeedPostWithSource

func (s *Store) SaveFeedPostWithSource(ctx context.Context, req factory.PostRequest, author, authorName string, at int64, source *factory.PostSource) (string, int64, error)

SaveFeedPostWithSource persists one comment submission with the server-resolved source snapshot its submission named (nil for a top-level comment). The snapshot is stored verbatim beside the comment so later judgment and authoring consume the authorized evidence as submitted; a replayed idempotency key recovers the original comment and its original snapshot.

func (*Store) SaveIntentRevision

func (s *Store) SaveIntentRevision(ctx context.Context, r factory.IntentRevision) error

SaveIntentRevision serializes revisions on a durable head and preserves all review history. Identity replay is exact; changed content cannot overwrite it.

func (*Store) SaveIntentRevisionWithReview

func (s *Store) SaveIntentRevisionWithReview(ctx context.Context, r factory.IntentRevision, review factory.SavedReview) error

SaveIntentRevisionWithReview saves a settled proposal revision and its exact review presentation atomically under the existing head-serialized CAS rules. Identity replay preserves immutable data; conflicting, stale or interrupted saves refuse without partial success, so a result revision never exists with a lost or substituted presentation.

func (*Store) SaveInvestigationPlan

func (s *Store) SaveInvestigationPlan(ctx context.Context, plan factory.InvestigationPlan) error

SaveInvestigationPlan persists one immutable plan revision keyed by (attempt_root, plan_id). The plan must validate as a record; unresolved mandatory facts may persist but never admit (see AdmitPlanHead). Saving the identical revision twice succeeds; saving different content under a consumed identity fails without touching the original.

func (*Store) SaveIssueIntakeGrant

func (s *Store) SaveIssueIntakeGrant(ctx context.Context, id string, revision int64, scope factory.IssueIntakeScope, proof json.RawMessage) error

SaveIssueIntakeGrant binds the trusted adapter's scope to the current source post and stores its opaque provider proof. The adapter must derive scope from that same admitted proof; the store does not authenticate or interpret it. Keep this server-side bearer out of semantic requests, prompts and client DTOs.

func (*Store) SaveIssueMakerProgress

func (s *Store) SaveIssueMakerProgress(ctx context.Context, progress factory.IssueMakerProgress) error

func (*Store) SaveLifecycleGrant

func (s *Store) SaveLifecycleGrant(ctx context.Context, g project.LifecycleGrant) error

SaveLifecycleGrant records the owner's standing create/start grant. The revision CAS rejects stale writers; a withdrawn grant is an inactive row, never a deleted one.

func (*Store) SaveMaintenanceHold

func (s *Store) SaveMaintenanceHold(ctx context.Context, m project.MaintenanceHold) error

SaveMaintenanceHold records the maintenance hold with CAS revision. Callers sync the native marker through the host; this row stays the source of truth.

func (*Store) SaveOperatorGrant

func (s *Store) SaveOperatorGrant(ctx context.Context, g factory.OperatorGrant) error

SaveOperatorGrant records the operator's repository permission under CAS.

func (*Store) SavePlanTaskReceipt

func (s *Store) SavePlanTaskReceipt(ctx context.Context, receipt PlanTaskReceipt) error

SavePlanTaskReceipt persists task state and evidence under CAS revision. The plan revision must persist and declare the task; check evidence must name its checks. The first save for a task starts at pending with revision zero. An identical replay commits nothing and succeeds; a write against a superseded revision fails without touching the stored receipt.

func (*Store) SavePlanTaskReceipts

func (s *Store) SavePlanTaskReceipts(ctx context.Context, receipts []PlanTaskReceipt) error

SavePlanTaskReceipts commits one verified journal page as a single unit. In particular run_stopped must not advance its receipt-derived cursor until every affected task cancellation has committed. Revisions are the CAS bases of each ordered transition, including repeated changes to the same task.

func (*Store) SavePostIssueContext

func (s *Store) SavePostIssueContext(ctx context.Context, id string, revision int64, candidates []factory.PostWorkCandidate) error

SavePostIssueContext retains bounded discussion context read through the author's live native admission. It contains no session or service credential.

func (*Store) SavePriorityScan

func (s *Store) SavePriorityScan(ctx context.Context, nativeRevision int64, inventory PriorityInventory) (bool, error)

SavePriorityScan stores a captured scan as current. An identical saved scan resumes with its cursor and observations; any change replaces the row and drops invalid observations.

func (*Store) SaveRepositoryPolicy

func (s *Store) SaveRepositoryPolicy(ctx context.Context, p factory.RepositoryPolicy) error

SaveRepositoryPolicy records the owner's policy under CAS revision.

func (*Store) SaveSponsorship

func (s *Store) SaveSponsorship(ctx context.Context, sp factory.Sponsorship) error

SaveSponsorship records one connection sponsorship under CAS revision.

func (*Store) SaveStallEvent

func (s *Store) SaveStallEvent(ctx context.Context, event factory.StallEvent) (bool, error)

SaveStallEvent records one bound stall observation. A redetected round carries the identical (repository, generation, fingerprint) key and replays to the stored row instead of duplicating it.

func (*Store) SaveStallRepairEpisode

func (s *Store) SaveStallRepairEpisode(ctx context.Context, event factory.StallEvent, expected int64, episode factory.StallRepairEpisode) error

func (*Store) SavedIntentRevision

func (s *Store) SavedIntentRevision(ctx context.Context, intent, revision string, owner int64) (factory.IntentRevision, error)

SavedIntentRevision returns one immutable revision under its current private request owner. It does not require that revision to remain the head or fit in a bounded history page. This is receipt lookup, never replay or head mutation.

func (*Store) SelectPlacement

SelectPlacement serializes with dispatch, grant changes and publication. The caller supplies current administration; a stored selection grants no spending or credentials and is not a cross-installation GitHub lease.

func (*Store) SetActivitySettings

func (s *Store) SetActivitySettings(ctx context.Context, repository, actor, expected int64, settings factory.ActivitySettings) error

func (*Store) SetApplicationProject

func (s *Store) SetApplicationProject(ctx context.Context, id string, administrator, repository int64) error

func (*Store) SetFeedSubscription

func (s *Store) SetFeedSubscription(ctx context.Context, subscriber string, expected int64, sub factory.FeedSubscription) error

SetFeedSubscription stores one subscriber's feed preferences under revision CAS: expected 0 inserts, otherwise the revision must match and bumps by one. A stale write refuses instead of dropping another update.

func (*Store) SettleApplicationRestore

func (s *Store) SettleApplicationRestore(ctx context.Context, administrator int64, app, id string, observed application.Observation, abort bool) error

SettleApplicationRestore changes the data binding only after matching native readback. The prior immutable revision and data remain available for recovery.

func (*Store) SettleApplicationSetup

func (s *Store) SettleApplicationSetup(ctx context.Context, before application.SetupRecord, result application.SetupResult, abort bool) error

func (*Store) SpaceProjects

func (s *Store) SpaceProjects(ctx context.Context) ([]Project, error)

SpaceProjects is a bounded scan of Soda associations, not an authorized catalog. NULL deliberately rejects oversized stored labels instead of silently truncating them or allocating arbitrary DB text. Callers must authorize every returned row.

func (*Store) SpaceProjectsAfter

func (s *Store) SpaceProjectsAfter(ctx context.Context, after string, limit int) ([]Project, error)

SpaceProjectsAfter continues the bounded Soda-association scan after one exclusive project-ID cursor. An empty cursor starts from the beginning. Like SpaceProjects this is not an authorized catalog: callers authorize every returned row. Labels keep the same oversized rejection.

func (*Store) Sponsorship

func (s *Store) Sponsorship(ctx context.Context, repository int64, connection string) (factory.Sponsorship, error)

Sponsorship returns one connection sponsorship for a repository.

func (*Store) Sponsorships

func (s *Store) Sponsorships(ctx context.Context, repository int64) ([]factory.Sponsorship, error)

Sponsorships lists the recorded connection sponsorships for a repository.

func (*Store) StageMCPCapability

func (s *Store) StageMCPCapability(ctx context.Context, capability factory.MCPCapability) error

StageMCPCapability records a staged capability. Exact restart delivery replays identically and returns the recorded row; a changed scope under the same ID conflicts instead of replacing authority.

func (*Store) StallRepairCycle

func (s *Store) StallRepairCycle(ctx context.Context, cycleID string) (StallRepairRecord, factory.StallRepairCycle, error)

func (*Store) StallRepairRecord

func (s *Store) StallRepairRecord(ctx context.Context, repository int64, event string) (StallRepairRecord, error)

func (*Store) StallRoundGeneration

func (s *Store) StallRoundGeneration(ctx context.Context) (int64, error)

StallRoundGeneration returns the standing detection round: the highest recorded progress generation, zero before the first bound event. Verified delivery alone advances progress under R37; until then every round reuses this generation and replays its episode.

func (*Store) StandingProjectPreparations

func (s *Store) StandingProjectPreparations(ctx context.Context, projectID string) ([]execution.PreparationRecord, error)

StandingProjectPreparations excludes private candidate custody: one issue's consumed checkout cannot become another issue's approved source template.

func (*Store) StandingStallEvents

func (s *Store) StandingStallEvents(ctx context.Context) (map[int64]StandingStallEvent, error)

StandingStallEvents returns the latest bound observation per repository. A fresh round feeds these back as prior events so ready work stales an obsolete investigation before any release. Latest is true observation order (the insertion sequence), never a hash of the observed bytes: R37 must advance the progress generation on verified delivery rather than read recency into this row.

func (*Store) StartPostIssueMaker

func (s *Store) StartPostIssueMaker(ctx context.Context, comment FeedPostDetail) (factory.IssueMakerProgress, error)

func (*Store) StartReassessmentRetry

func (s *Store) StartReassessmentRetry(ctx context.Context, retry factory.ReassessmentRetry) (string, error)

StartReassessmentRetry creates the one successor cycle for an attention cycle through its explicit authorized Retry. The prior cycle must still carry the expected attention state with no successor yet; command replay reuses the recorded successor instead of creating another. The successor preserves all earlier receipts and committed native effects as history via its retry lineage. Only explicit authorized Retry supersedes: no poll, input edit or policy edit creates a successor.

func (*Store) SubscribedFeed

func (s *Store) SubscribedFeed(ctx context.Context, query factory.FeedQuery) ([]factory.FeedEntry, string, bool, error)

SubscribedFeed reads canonical assignments, comments and milestones in newest-first recording order. Each milestone receives its own key from the assignment/comment sequence when recorded, including JEV selections whose issue has not dispatched. The exclusive seq cursor is shared by all kinds. Reads do not allocate keys or dispatch work. Scope filtering happens here and access is checked again by the serving layer.

func (*Store) Takeover

func (s *Store) Takeover(ctx context.Context, run, targetKey string) (factory.TakeoverRecord, error)

Takeover reads one destination's completed recovery from its Feed post.

func (*Store) TerminalMCPProposal

func (s *Store) TerminalMCPProposal(ctx context.Context, assignmentID string) (factory.MCPWorkStatus, bool, error)

func (*Store) TerminalMCPSubmission

func (s *Store) TerminalMCPSubmission(ctx context.Context, assignmentID string) (factory.MCPSubmission, bool, error)

func (*Store) UnsentMergePreparation

func (s *Store) UnsentMergePreparation(ctx context.Context, publication string) (factory.MergePreparation, error)

UnsentMergePreparation offers only a new command. The eventual command repeats these checks inside its transaction; lookup absence is not proof.

func (*Store) UpdateMerge

func (s *Store) UpdateMerge(ctx context.Context, m factory.Merge) error

func (*Store) UpdatePublication

func (s *Store) UpdatePublication(ctx context.Context, p factory.Publication) error

func (*Store) UploadWorkerArtifact

func (s *Store) UploadWorkerArtifact(ctx context.Context, bound factory.MCPCapability, payload []byte) (factory.FeedArtifact, string, error)

UploadWorkerArtifact keeps upload progress in the artifact row. Finalization publishes its post atomically; chunks never enter the submission journal.

func (*Store) UpsertUser

func (s *Store) UpsertUser(ctx context.Context, u User) error

func (*Store) UsageTotal

func (s *Store) UsageTotal(ctx context.Context, repository int64, connection string) (int, error)

UsageTotal sums confirmed consumption for one repository connection.

func (*Store) User

func (s *Store) User(ctx context.Context, id int64) (User, error)

func (*Store) VerificationScope

func (s *Store) VerificationScope(ctx context.Context, cap factory.MCPCapability, after int64) (factory.VerificationScopeView, error)

VerificationScope reads retained observations in canonical feed sequence. Keyset pages do not run models, append records, or change workflow state.

func (*Store) VerifiedApplicationDelivery

func (s *Store) VerifiedApplicationDelivery(ctx context.Context, id string) (*ApplicationFactoryDelivery, error)

VerifiedApplicationDelivery never accepts an asserted source, event or hash. The application image readback and approved-check output must already have been observed by their native owners. Its immutable accepted revision remains evidence for a running older image after the intent head advances; it grants no fresh packaging or release authority. Missing receipts remain unknown.

func (*Store) VerifiedApplicationOutcomeCount

func (s *Store) VerifiedApplicationOutcomeCount(ctx context.Context, revision factory.IntentRevision) (int, error)

VerifiedApplicationOutcomeCount is the spend-free overview read of the same controller-owned F10 fact used by delivery admission. A worker finish or a historical accepted revision never supplies current outcome evidence.

func (*Store) VerifiedFactoryBuildInput

func (s *Store) VerifiedFactoryBuildInput(ctx context.Context, repository int64, deliveryID, environment string) (application.BuildRequest, ApplicationFactoryDelivery, error)

VerifiedFactoryBuildInput admits packaging only from the canonical current F10 and its retired native check output, never a caller's claimed digest.

func (*Store) WithdrawAcceptanceDecision

func (s *Store) WithdrawAcceptanceDecision(ctx context.Context, repository, issue int64, decision string, withdrawer int64) error

WithdrawAcceptanceDecision latches one recorded head decision as withdrawn by a current maintainer. Repeating the identical withdrawal replays; withdrawing a superseded decision is stale. A later acceptance advances the head past the latch with a fresh decision.

func (*Store) WithdrawDispatch

func (s *Store) WithdrawDispatch(ctx context.Context, repository int64, cause, closedBy string) (factory.Withdrawal, error)

WithdrawDispatch atomically closes dispatch for one repository. Repeated requests retain the first closure and add any independent active cause.

type SystemOneConsultation

type SystemOneConsultation struct {
	factory.FeedConsultation
	Repository int64
	Role       factory.MCPProfile
}

Consultation comments use the existing authorized conversation store. The comment owns the displayed question and actual answer. Neither reading a comment nor refreshing its thread dispatches a call.

type User

type User struct {
	ID          int64
	Login, Name string
}

Source Files

Jump to

Keyboard shortcuts

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