facade4datatug

package
v0.61.1 Latest Latest
Warning

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

Go to latest
Published: Oct 31, 2026 License: MIT Imports: 76 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Copyright 2026 Sneat.co

Package facade4datatug holds the DataTug extension's application commands.

It is storage-agnostic by construction: the only persistence API it uses is dal-go, so it never learns whether the host backs it with Firestore, an in-memory database (tests), or anything else. Platform needs arrive through ports declared in ports.go.

Copyright 2026 Sneat.co

Index

Constants

View Source
const (
	BusinessProjectProductID   = "datatug-business-usage"
	BusinessProjectServiceID   = "datatug"
	BusinessProjectOwnerFamily = "datatug"
	BusinessProjectAccountKind = "space"
	BusinessMonthlyPlanID      = "datatug-business-usage-monthly"
	BusinessAnnualPlanID       = "datatug-business-usage-annual"
)
View Source
const (
	MaxGitHubCloneBytes          = 600 * 1024
	MaxGitHubSetupProofBytes     = 850 * 1024
	MaxGitHubSetupOperationBytes = 900 * 1024
)

Clone and setup proofs remain below Firestore's document limit, with room reserved for generated setup files, operation metadata and field overhead.

View Source
const (
	HTTPRunMaxRequestBodyBytes  = 256 * 1024
	HTTPRunMaxResponseBodyBytes = 5 * 1024 * 1024
	HTTPRunMaxRedirects         = 5
	HTTPRunTimeout              = 30 * time.Second
)

Limits of the HTTP run proxy (POST /v0/datatug/http/run).

View Source
const BusinessUsageCloseGrace = 48 * time.Hour
View Source
const BusinessUsageLifecycleMaxPageSize = 100
View Source
const CloudProjectEnvironmentID = "dev"

CloudProjectEnvironmentID is the environment every cloud project is born with. It matches the pinned connection entries' environments: ["dev"].

View Source
const GitHubProjectCreateMergedReady = "merged_ready"
View Source
const HostedEmbeddedDemoOrigin = "https://detective-demo.internal"
View Source
const MaxProjectFavorites = 500
View Source
const QueryActivityMaxDrainBatchSize = 100
View Source
const QueryActivityWatermarkBatchSize = 128
View Source
const WorkPostmortemRefsCollection = "workPostmortemRefs"

WorkPostmortemRefsCollection holds one document per parent Work item that has an attached postmortem. The reference is denormalised from the postmortem in the same transaction, but it is deliberately NOT stored on the parent item: postmortem evidence includes the parent Work item, so bumping the parent version would invalidate a submitted report whenever its own state changed. Reads project the reference onto the parent item for the API.

Variables

View Source
var (
	ErrAccessControlUnavailable = errors.New("access control unavailable")
	ErrAccessControlDenied      = errors.New("access control denied")
	ErrAccessControlInvalid     = errors.New("invalid access control request")
	ErrAccessControlConflict    = errors.New("access control revision conflict")
)
View Source
var (
	ErrBusinessServiceUnproved = errors.New("business space service access is unproved")
	ErrBusinessServiceEnded    = errors.New("business space service has ended")
)
View Source
var (
	// ErrUnsupportedDemoDB refuses any demoDb other than the pinned entries
	// that carry a browserFixture.
	ErrUnsupportedDemoDB = errors.New("unsupported_demo_db")
	// ErrProjectConnectionsUnsupported refuses save_connection on a project
	// that does not serve its own connection catalog.
	ErrProjectConnectionsUnsupported = errors.New("project does not serve its own connection catalog")
)
View Source
var (
	// ErrProjectIDRequired is returned when a lifecycle command names no project.
	ErrProjectIDRequired = errors.New("project id is required")

	// ErrProjectNotFound is returned for a project that does not exist or that
	// the caller is not a member of: the two are not told apart, so a lifecycle
	// call never reveals that someone else's project exists.
	ErrProjectNotFound = errors.New("project not found")

	// ErrProjectNotEmpty is returned when deleting a project that holds content.
	// Such a project can be archived instead.
	ErrProjectNotEmpty = errors.New("project is not empty")
)
View Source
var (
	ErrCloudProjectSharingUnavailable      = errors.New("cloud project sharing is unavailable")
	ErrCloudProjectSharingInvalid          = errors.New("invalid cloud project sharing request")
	ErrCloudProjectUnavailable             = errors.New("cloud project is deleted or archived")
	ErrCloudProjectPlanRequired            = errors.New("joining this cloud project needs a Pro plan")
	ErrCloudProjectInviteInvalid           = errors.New("cloud project invite is invalid")
	ErrCloudProjectEmailInvitesUnavailable = errors.New("email invites are unavailable")
	// ErrCloudProjectInviteAttemptsExceeded refuses a caller who used up their
	// pin attempts on an invite, whatever pin this call carries.
	ErrCloudProjectInviteAttemptsExceeded = errors.New("too many pin attempts on this cloud project invite")
)

Share-and-join errors (first-cloud-project-endpoints REQ share-and-join).

View Source
var (
	// ErrCloudProjectNotOwner refuses a project member who is not its owner.
	ErrCloudProjectNotOwner = errors.New("only the project owner can archive or delete it")
	// ErrCloudProjectConfirmTitleMismatch refuses a delete whose confirmTitle
	// is not the project title.
	ErrCloudProjectConfirmTitleMismatch = errors.New("confirmTitle does not match the project title")
	// ErrCloudProjectDeleted answers a replayed create_cloud_project command
	// whose project was deleted.
	ErrCloudProjectDeleted = errors.New("cloud project was deleted")
)

Whole-project archive and delete of Space-backed cloud projects (first-cloud-project-endpoints REQ space-project-delete-archive).

View Source
var (
	ErrDetectiveUnavailable  = errors.New("hosted Detective unavailable")
	ErrDetectiveUnauthorized = errors.New("hosted Detective access denied")
	ErrDetectiveInvalid      = errors.New("invalid hosted Detective request")
	ErrDetectiveConflict     = errors.New("hosted Detective operation conflict")
	ErrDetectiveCapacity     = errors.New("hosted Detective capacity reached")
	ErrDetectiveSnapshot     = errors.New("hosted execution snapshot unavailable")
	ErrDetectiveInterrupted  = errors.New("hosted execution interrupted; start a new authorized operation")
)
View Source
var (
	ErrEnvironmentInvalid           = errors.New("INVALID_REQUEST")
	ErrEnvironmentConflict          = errors.New("ENVIRONMENT_REVISION_CONFLICT")
	ErrEnvironmentOperationConflict = errors.New("OPERATION_CONFLICT")
	ErrEnvironmentExpired           = errors.New("OPERATION_EXPIRED")
	ErrEnvironmentDuplicate         = errors.New("DUPLICATE_NAME")
	ErrEnvironmentUncertain         = errors.New("OUTCOME_UNCERTAIN")
)
View Source
var (
	ErrGitHubProjectConflict              = errors.New("GitHub project create conflict")
	ErrGitHubOutcomeUncertain             = errors.New("GitHub project create outcome uncertain")
	ErrGitHubSetupFilesMismatch           = errors.New("GitHub setup files do not match the approved project")
	ErrGitHubSetupVerificationUnavailable = errors.New("GitHub setup verification is temporarily unavailable")
	ErrGitHubProjectInvalid               = errors.New("invalid GitHub project create command")
)
View Source
var (
	// ErrOrgRequired is returned when a GitHub project is registered without
	// its repository owner.
	ErrOrgRequired = errors.New("github org is required")

	// ErrRepoRequired is returned when a GitHub project is registered without
	// its repository name.
	ErrRepoRequired = errors.New("github repo is required")
)
View Source
var (
	// ErrHTTPRunInvalid marks a malformed request or a blocked target (HTTP 400).
	ErrHTTPRunInvalid = errors.New("invalid HTTP run request")
	// ErrHTTPRunUpstream marks an upstream failure: DNS, connect, TLS, timeout (HTTP 502).
	ErrHTTPRunUpstream = errors.New("HTTP run upstream failure")
)
View Source
var (
	ErrPersonalAccountUnavailable = errors.New("personal account unavailable")
	ErrForeignAccount             = errors.New("account is not the caller's personal account")
	ErrPlanUnavailable            = errors.New("plan response unavailable")
)
View Source
var (
	// ErrUserIDRequired is returned when a command is called without a user.
	ErrUserIDRequired = errors.New("user id is required")

	// ErrTitleRequired is returned when a project is created without a title.
	ErrTitleRequired = errors.New("project title is required")

	// ErrUnsupportedStore is returned for a store this API does not serve. A
	// project in a GitHub repo is created by the client holding the user's
	// GitHub credential, and a local filesystem project by the datatug CLI
	// agent — only the DataTug cloud store is created here.
	ErrUnsupportedStore = errors.New("store is not served by the DataTug cloud API")
)
View Source
var (
	ErrQueryActivityUnavailable  = errors.New("query activity is unavailable")
	ErrQueryActivityUnauthorized = errors.New("query activity is unauthorized")
	ErrQueryActivityInvalid      = errors.New("invalid query activity request")
	ErrQueryActivityConflict     = errors.New("query activity identity conflicts")
	ErrQueryActivityRateLimited  = errors.New("query activity rate limit exceeded")
)
View Source
var (
	ErrSharedProjectUnavailable  = errors.New("shared project creation is unavailable")
	ErrSharedProjectUnauthorized = errors.New("shared project creation is unauthorized")
	ErrSharedProjectConflict     = errors.New("shared project create command conflicts")
	ErrSharedProjectInvalid      = errors.New("invalid shared project create command")
)
View Source
var (
	ErrSharedProjectQueryInvalid     = errors.New("invalid shared project query")
	ErrSharedProjectQueryConflict    = errors.New("shared project query conflict")
	ErrSharedProjectQueryUnavailable = errors.New("shared project query unavailable")
)
View Source
var ErrBusinessActivityBindingUnavailable = errors.New("business activity binding is unavailable")
View Source
var ErrBusinessUsageLifecycleUnavailable = errors.New("business usage lifecycle worker is unavailable")
View Source
var ErrBusinessUsagePeriodUnavailable = errors.New("business usage period is unavailable")
View Source
var ErrBusinessUsageRuntimeUnavailable = errors.New("business usage runtime is unavailable")
View Source
var ErrFavoriteLimit = errors.New("project favorites limit reached")
View Source
var ErrFavoriteTargetUnavailable = errors.New("favorite target access could not be verified")
View Source
var ErrGitHubProjectNotRegistered = errors.New("GitHub project is not registered")
View Source
var ErrGitHubQueryConflict = errors.New("GitHub query mutation conflict")
View Source
var ErrGitHubQueryInvalid = errors.New("invalid GitHub query mutation")
View Source
var ErrGitHubQueryOutcomeUncertain = errors.New("GitHub query mutation outcome uncertain")
View Source
var ErrGitHubSourceTooLarge = errors.New("private GitHub clone source exceeds 32 files")
View Source
var ErrPlanEffectUnproved = errors.New("plan effect is not proved")
View Source
var ErrPostmortemUnconfirmed = errors.New("native catalog receipt is not confirmed")
View Source
var ErrProjectAIEligibilityUnavailable = errors.New("project AI eligibility unavailable")
View Source
var ErrProjectAssetReadOnly = errors.New("copied asset contains source fields this editor cannot preserve")
View Source
var ErrProjectContactLimit = errors.New("protected project contact limit unavailable or exhausted")
View Source
var ErrProtectedProjectInventory = errors.New("protected project inventory could not be proved complete")
View Source
var ErrProtectedProjectQuota = errors.New("protected project quota unavailable or exhausted")
View Source
var ErrSharedProjectActivationUnavailable = errors.New("shared project activation is unavailable")
View Source
var ErrWorkMigrationRequired = fmt.Errorf("%w: work migration or canonical work mutation required", ErrDetectiveConflict)
View Source
var ErrWorkNotFound = errors.New("work item unavailable")

Functions

func BuildGitHubEnvironmentState added in v0.59.1

func BuildGitHubEnvironmentState(actor string, scope dto.EnvironmentScope, head string, saved []string, envs []dto.EnvironmentBrief, write bool) (*dto.EnvironmentState, error)

func ChangeGitHubProjectMeanings added in v0.59.1

func ChangeGitHubProjectMeanings(ctx context.Context, authority GitHubMeaningAuthority, actor string, repositoryID int64, owner, name, folder, branch string, request datatug.ProjectMeaningWrite, repository GitHubMeaningRepository) (datatug.ProjectMeaningAck, error)

func ClassifyGitHubProjectCreateError added in v0.59.1

func ClassifyGitHubProjectCreateError(stage string, classification, cause error) error

ClassifyGitHubProjectCreateError retains the replaced cause without allowing it to override the outward classification established at this boundary.

func CloudProjectDemoConnectionID added in v0.60.6

func CloudProjectDemoConnectionID(demoDB string) (string, error)

CloudProjectDemoConnectionID returns the pinned entry id of a v1 pick.

func CloudProjectID added in v0.60.6

func CloudProjectID(actorID, commandID string) string

CloudProjectID derives a cloud project's id from its create command, so a replay resolves the same project.

func CloudProjectInviteMessage added in v0.60.6

func CloudProjectInviteMessage(owner, projectTitle string) string

CloudProjectInviteMessage is the DataTug invite text.

func DecodeIncidentCriterionAction added in v0.59.1

func DecodeIncidentCriterionAction(raw []byte, out *HostedIncidentAction) (bool, error)

DecodeIncidentCriterionAction owns the strict disjoint action dispatch.

func EmbeddedDemoSessionScope added in v0.30.0

func EmbeddedDemoSessionScope(space, project, environment string) (sessioncontext.Scope, sessioncontext.Subject, error)

EmbeddedDemoSessionScope names the real immutable native invoice source. It deliberately differs from Chinook even when both contain invoice ID 1. Fixture, template and reviewed catalog changes invalidate this identity.

func EnvironmentMarkerID added in v0.59.1

func EnvironmentMarkerID(operationID string) string

func EnvironmentOperationMarker added in v0.59.1

func EnvironmentOperationMarker(result dto.EnvironmentOperationResult, binding string) []byte

func EnvironmentScopeBinding added in v0.59.1

func EnvironmentScopeBinding(actor string, scope dto.EnvironmentScope) string

func EnvironmentStateDigest added in v0.59.1

func EnvironmentStateDigest(state *dto.EnvironmentState) string

func FavoriteMeaningExists added in v0.60.0

func FavoriteMeaningExists(document datatug.ProjectMeaningsDocument, id string) bool

func GitHubProjectCreatePublicError added in v0.59.1

func GitHubProjectCreatePublicError(err error) error

GitHubProjectCreatePublicError is only for HTTP classification. Diagnostics and errors.Is/As keep using the complete original error chain.

func InitializeProtectedProjectQuota added in v0.11.0

func InitializeProtectedProjectQuota(ctx context.Context, db dal.DB, options PaidSharedProjectOptions, actor, payer string, basis InitialProtectedProjectBasis, authority ProtectedProjectBasisAuthority) error

InitializeProtectedProjectQuota is one-time and transaction fenced. A host must bind an actual empty/import proof source before calling it; a caller or operator claim alone is insufficient. All creates refuse absent quota, so concurrent initialization cannot race an uncounted admission. Deletion and quota release require a future atomic allocation-retirement command; this count is not reset on payment renewal or subscription replacement.

func MeaningActorOperationID added in v0.59.1

func MeaningActorOperationID(actor, operation string, scope ...string) string

func NativeSessionAccountReader added in v0.59.1

func NativeSessionAccountReader(ctx context.Context, actor string, db dal.DB) (dal.ReadTransaction, bool)

NativeSessionAccountReader exposes only the exact reader installed by the existing private native fence boundary. Ordinary/foreign ambient transactions are not account authority, even if their database IDs happen to match.

func PrepareProjectReferenceWrite added in v0.60.0

func PrepareProjectReferenceWrite(ctx context.Context, tx dal.ReadwriteTransaction, scope datatug.ProjectLifecycleScope, source datatug.ProjectObjectRef, targets []datatug.ProjectObjectRef, at time.Time) (func() error, error)

PrepareProjectReferenceWrite is the shared admission boundary for a provider's definition/reference writes and execution reservations. The caller must first authorize the exact source/targets. It must call the returned closure once, after ALL transaction reads, in the SAME transaction as its reference write. A successful read alone is never a reservation. Every reference-bearing writer must participate before that provider may report complete lifecycle coverage. This helper establishes no completeness certificate for an existing project.

func ResolvedProjectVisibilityOwner added in v0.61.1

func ResolvedProjectVisibilityOwner(ctx context.Context) (space, project string, ok bool)

ResolvedProjectVisibilityOwner is a source routing hint supplied only after the main inventory resolves its immutable provider binding. Owning adapters must still perform their ordinary current-actor ACL checks in the transaction.

func SessionNativeRepository added in v0.30.0

func SessionNativeRepository(mounted sessioncontext.MountedDatabase, scope SessionOperationScope) (*sessioncontext.DALRepository, error)

SessionNativeRepository reconstructs only the declared operational parent. The caller still authenticates its actor and matches accepted stored identity.

func SpaceDataCleanupParticipant added in v0.60.6

func SpaceDataCleanupParticipant() contract4spaceus.SpaceDataCleanupParticipant

SpaceDataCleanupParticipant is DataTug's participant in Core's delete_space (contract4spaceus). Its cleanup is empty only when the Space's DataTug root holds no records but the create receipts of projects that were deleted and fully purged; those receipts are kept as deletion tombstones, so a replayed create can never re-create the project or its Space. DeleteSpaceData deletes only the root document spaces/{spaceID}/ext/datatug. It reads only in PrepareSpaceDataCleanup and writes only in DeleteSpaceData.

func ValidatePlanConfig added in v0.7.0

func ValidatePlanConfig(config PlanConfig) error

ValidatePlanConfig checks the shared plan settings before they are used for plan reads, purchase readiness, or checkout activation.

func WorkLegacyID added in v0.59.1

func WorkLegacyID(kind, legacyID string) string

WorkLegacyID is stable, bounded and valid under the backend identifier grammar.

func WrapGitHubProjectCreateError added in v0.59.1

func WrapGitHubProjectCreateError(stage string, cause error) error

Types

type AccessActor added in v0.60.11

type AccessActor struct {
	Subject          dataaccess.Subject
	CredentialFamily AccessCredentialFamily
	ClientID         string
	ValidUntil       time.Time
	Decision         *AccessDecisionProof
}

AccessActor contains host-verified facts, never fields decoded from a public request. A delegated user may request/revoke but has no Decision proof.

type AccessConnectionBindingPort added in v0.60.11

type AccessConnectionBindingPort interface {
	ResolveAccessConnection(context.Context, dal.ReadTransaction, models4datatug.SharedProjectRef, string) (dataaccess.ConnectionRef, error)
}

AccessConnectionBindingPort reads the CURRENT real catalog/identity binding using the supplied transaction. It must neither write nor use a cached or caller-supplied fingerprint. The returned ID is AccessProtectionID(project, catalogConnectionID), and its Space is the supplied project's Space.

type AccessConnectionScope added in v0.60.11

type AccessConnectionScope struct {
	AccessProjectScope
	ConnectionID string `json:"connectionId"`
}

type AccessControlOptions added in v0.60.11

type AccessControlOptions struct {
	Project               *SharedProjectService
	IDs                   IDGenerator
	Connections           AccessConnectionBindingPort
	Realm                 string
	MaxReadSeconds        int
	DecisionsEnabled      bool
	OwnerBootstrapEnabled bool
	AllowSelfApproval     bool
}

type AccessControlService added in v0.60.11

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

AccessControlService is an additive, dormant connection-read control plane. Its independent decision gate is off unless explicitly configured by a host.

func NewAccessControlService added in v0.60.11

func NewAccessControlService(options AccessControlOptions) (*AccessControlService, error)

func (*AccessControlService) DecideAccess added in v0.60.11

func (*AccessControlService) ListAccessRequests added in v0.60.11

func (s *AccessControlService) ListAccessRequests(ctx context.Context, actor AccessActor, scope AccessConnectionScope) (AccessGrantList, error)

func (*AccessControlService) ReadAccessProtection added in v0.60.11

func (s *AccessControlService) ReadAccessProtection(ctx context.Context, actor AccessActor, scope AccessConnectionScope) (AccessProtectionView, error)

func (*AccessControlService) RequestAccess added in v0.60.11

func (*AccessControlService) ResolveAccess added in v0.60.11

ResolveAccess remains available when new decisions are disabled. It reads current role, connection, policy and own grants in one fresh transaction.

func (*AccessControlService) SetAccessProtection added in v0.60.11

func (s *AccessControlService) SetAccessProtection(ctx context.Context, actor AccessActor, command AccessProtectionCommand) (AccessProtectionView, error)

type AccessCredentialFamily added in v0.60.11

type AccessCredentialFamily string
const (
	AccessCredentialFirebase          AccessCredentialFamily = "firebase"
	AccessCredentialProductDelegation AccessCredentialFamily = "product-delegation.v1"
)

type AccessDecisionCommand added in v0.60.11

type AccessDecisionCommand struct {
	AccessProjectScope
	GrantID          string     `json:"-"`
	ExpectedRevision int64      `json:"expectedRevision"`
	Note             string     `json:"note"`
	ExpiresAt        *time.Time `json:"expiresAt,omitempty"`
}

type AccessDecisionProof added in v0.60.11

type AccessDecisionProof struct {
	AuthTime        time.Time
	ValidUntil      time.Time
	BindingID       string
	BindingRevision int64
}

AccessDecisionProof identifies the independent binding checked by the host. SDK/provider verification belongs to that adapter, not this domain package.

type AccessGrantList added in v0.60.11

type AccessGrantList struct {
	Grants     []AccessGrantView `json:"grants"`
	ServerTime time.Time         `json:"serverTime"`
}

type AccessGrantView added in v0.60.11

type AccessGrantView struct {
	Grant           dataaccess.Grant      `json:"grant"`
	EffectiveState  dataaccess.GrantState `json:"effectiveState"`
	CanApprove      bool                  `json:"canApprove"`
	CanRevoke       bool                  `json:"canRevoke"`
	CanRequestAgain bool                  `json:"canRequestAgain"`
}

type AccessProjectScope added in v0.60.11

type AccessProjectScope struct {
	SpaceID   string `json:"spaceID"`
	ProjectID string `json:"projectId"`
}

type AccessProtectionCommand added in v0.60.11

type AccessProtectionCommand struct {
	AccessConnectionScope
	ExpectedRevision  int64                             `json:"expectedRevision"`
	ReadPosture       dataaccess.ReadPosture            `json:"readPosture"`
	MaxReadSeconds    int                               `json:"maxReadSeconds"`
	AllowSelfApproval bool                              `json:"allowSelfApproval"`
	Delegations       []models4datatug.AccessDelegation `json:"delegations"`
}

type AccessProtectionView added in v0.60.11

type AccessProtectionView struct {
	Connection             dataaccess.ConnectionRef          `json:"connection"`
	Protection             dataaccess.ConnectionProtection   `json:"protection"`
	CatalogConnectionID    string                            `json:"catalogConnectionId"`
	CanRequest             bool                              `json:"canRequest"`
	CanApprove             bool                              `json:"canApprove"`
	CanConfigure           bool                              `json:"canConfigure"`
	MaxReadSeconds         int                               `json:"maxReadSeconds"`
	AllowedPermissions     []dataaccess.Permission           `json:"allowedPermissions"`
	DurationChoicesSeconds []int                             `json:"durationChoicesSeconds"`
	RoleChoices            []string                          `json:"roleChoices"`
	Delegations            []models4datatug.AccessDelegation `json:"delegations"`
	AllowSelfApproval      bool                              `json:"allowSelfApproval"`
	ServerTime             time.Time                         `json:"serverTime"`
}

type AccessRecordReadCommand added in v0.60.11

type AccessRecordReadCommand struct {
	AccessConnectionScope
	Collection string `json:"collection"`
	ID         string `json:"id"`
}

AccessRecordReadCommand selects one record; host-owned source binding and Core authorization remain entirely inside the injected read port.

type AccessRecordReadResult added in v0.60.11

type AccessRecordReadResult struct {
	Record map[string]any `json:"record"`
}

type AccessRequestCommand added in v0.60.11

type AccessRequestCommand struct {
	AccessProjectScope
	Request dataaccess.AccessRequest `json:"request"`
}

type AccountPlanEffect added in v0.5.0

type AccountPlanEffect struct {
	Fence                    PlanOwnerFence
	BuyerID                  string
	AccountKind              string
	PlanID                   string
	PlaceID                  string `json:",omitempty"`
	Tier                     string
	Period                   string
	Status                   string
	LastPaidEnd              time.Time
	ScheduledEnd             time.Time
	EffectiveEnd             time.Time
	PaidService              bool
	AppliedPercent           int
	LaunchGrant              bool
	Grants                   PlanEffectGrants
	Payments                 []PlanPayment
	CashBasisKnown           bool
	MoneyIngestEpoch         int64
	ObservedAt               time.Time
	CheckoutStartedAt        time.Time
	QuoteKey                 string
	PaidServiceProofID       string
	BasisOnly                bool
	SourceSubscriptionID     string
	SourceRevision           int64
	SourcePaidService        bool
	SourceQuoteKey           string
	SourcePaidServiceProofID string
	LastServiceRefund        *ServiceRefundProof
	TerminalFullRefund       bool `json:"terminalFullRefund,omitempty"`
}

AccountPlanEffect is a provider-neutral copy of the accepted payment fact. The host passes the *complete* source fact to VerifyCurrentEffect and ReconcileMoney; this type never substitutes for paymentus's accepted digest.

type AccountPlanWriter added in v0.5.0

type AccountPlanWriter struct {
	DB        dal.DB
	Owner     PlanEffectOwnerPort
	Personal  PersonalPlanOwnerPort
	Allocator PaidMonthAllocator
	Limits    ProLimitsResolver
	Clock     PlanClock
}

AccountPlanWriter is the DataTug domain writer. Its ports are bound by the host to one DAL database; no provider or cross-extension package is imported.

func (AccountPlanWriter) Apply added in v0.5.0

type AdmissionReader added in v0.4.0

type AdmissionReader interface {
	ReadAdmission(context.Context, string, time.Time) (AdmissionState, error)
}

type AdmissionState added in v0.4.0

type AdmissionState struct {
	TodayUsed int64
	Blocked   string
}

AdmissionState supplies guards that are authoritative outside this module. Blocked is empty, daily, free_budget, or unverified.

type BusinessActivityActorVerifier added in v0.23.0

type BusinessActivityActorVerifier interface {
	VerifyBusinessActivityActor(context.Context, dal.ReadTransaction, string) error
}

BusinessActivityActorVerifier must bind actorID to the authenticated server identity for this request. Implementations must use only the supplied transaction and must not trust an actor ID copied from a request body.

type BusinessActivityBinding added in v0.20.0

type BusinessActivityBinding struct {
	Period                                                  contract4paymentus.UsagePeriodRef
	PeriodStartUTC, PeriodEndUTC, PaidUntilUTC              time.Time
	PaidBindingProofID, PayerBindingDigest, QueryUseProofID string
	QueryUseAllowed                                         bool
}

BusinessActivityBinding is returned only by the host's transaction-bound financial and membership authority. It contains canonical paid-period facts, not caller claims. QueryUseAllowed includes current actor/project query-use access; publish/contributor permission is deliberately not required.

type BusinessActivityBindingReader added in v0.20.0

type BusinessActivityBindingReader interface {
	ReadCurrentBusinessActivityBinding(context.Context, dal.ReadTransaction, string, string, string, time.Time) (BusinessActivityBinding, error)
}

BusinessActivityBindingReader must validate current reciprocal membership, query-use permission and paid service binding using the supplied transaction. It must not start a transaction or call a provider.

type BusinessProjectAccessPolicy added in v0.21.0

type BusinessProjectAccessPolicy struct {
	GrantVersion string
	// Mode is fixed by trusted server composition. Request values never select
	// the Paymentus environment.
	Mode contract4paymentus.Mode
}

BusinessProjectAccessPolicy is server configuration. Unlimited project and contact grants come from this versioned product policy, never from a money field or the absence of Pro limits.

type BusinessProjectAccessVerifier added in v0.19.0

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

BusinessProjectAccessVerifier contains no provider or mutation handle. The Paymentus reader can only inspect the caller's transaction; paid end and evidence expiry are both enforced before DataTug uses this result.

func NewBusinessProjectAccessVerifier added in v0.19.0

func NewBusinessProjectAccessVerifier(reader contract4paymentus.CurrentSpaceServiceReader, policy BusinessProjectAccessPolicy, now func() time.Time) (*BusinessProjectAccessVerifier, error)

func (*BusinessProjectAccessVerifier) Mode added in v0.23.3

func (*BusinessProjectAccessVerifier) ReadCurrent added in v0.19.0

ReadCurrent verifies the selected Space's explicitly configured DataTug Business service. Current contact membership and action-specific roles are separate checks. Same-Space owner replacement is allowed: the admission's original proof remains provenance, while this read verifies the current owner.

type BusinessQueryActivityService added in v0.23.2

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

BusinessQueryActivityService is the thin route composition used by the host. It opens and verifies the current server-owned period before issuing a query activity context; Report continues through the existing authority and checkpoint fences.

func NewBusinessQueryActivityService added in v0.23.2

func NewBusinessQueryActivityService(periods BusinessUsagePeriodOpener, activity QueryActivityContextService) (*BusinessQueryActivityService, error)

func (*BusinessQueryActivityService) IssueContext added in v0.23.2

func (s *BusinessQueryActivityService) IssueContext(ctx context.Context, actorID, spaceID, projectID string) (QueryActivityContextResponse, error)

func (*BusinessQueryActivityService) Report added in v0.23.2

type BusinessSharedProjectOptions added in v0.21.0

type BusinessSharedProjectOptions struct {
	EvidenceEnsurer BusinessSpaceEvidenceEnsurer
	AccessPolicy    BusinessProjectAccessPolicy
	ServiceReader   contract4paymentus.CurrentSpaceServiceReader
	ContactLinks    *PaidProjectOwnerLinksOptions
}

type BusinessSpaceEvidenceEnsurer added in v0.59.1

type BusinessSpaceEvidenceEnsurer interface {
	EnsureCurrentSpaceEvidence(context.Context, contract4paymentus.ServicePurchaseScope) error
}

BusinessSharedProjectOptions are trusted host composition. The caller's existing Space authority remains required for each create command; current paid access is separately read from Paymentus in that same transaction. BusinessSpaceEvidenceEnsurer refreshes only server-resolved current evidence. It is separate from the transaction-only reader and is called after create authority.

type BusinessUsageCloseTerms added in v0.23.1

type BusinessUsageCloseTerms struct {
	Capacity           contract4paymentus.UsageCapacityEvidence
	BaseEvent          contract4paymentus.UsageBaseEvent
	BillMonthlyOverage bool
	DiscountPercent    int
}

BusinessUsageCloseTerms is server-derived close authority. A request's capacity digest and pricing choices are not accepted unless this port independently resolves the same frozen terms from the caller's transaction.

type BusinessUsageCloseTermsReader added in v0.23.1

type BusinessUsageCloseTermsReader interface {
	ReadBusinessUsageCloseTerms(context.Context, dal.ReadTransaction, contract4paymentus.UsagePeriodSnapshot) (BusinessUsageCloseTerms, error)
}

BusinessUsageCloseTermsReader must verify all capacity and pricing inputs from the supplied transaction. It must not use a provider or open a nested transaction. The native implementation refuses any non-empty prepaid basis until DataTug's partial-window coverage policy is approved.

type BusinessUsageLifecycleResult added in v0.23.2

type BusinessUsageLifecycleResult struct {
	CheckpointsScanned int
	PeriodsOpened      int
	PeriodsClosed      int
	InvoicesProcessed  int
	ActivitySpaces     int
	ActivityScanned    int
	ActivityDelivered  int
	Failures           int
	CheckpointAfter    string
	PendingAfter       string
	CheckpointHasMore  bool
	PendingHasMore     bool
}

BusinessUsageLifecycleResult reports bounded progress. Cursors are durable scan positions and carry no authority; candidates are re-read from their Space-scoped records before any lifecycle operation.

type BusinessUsageLifecycleWorker added in v0.23.2

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

BusinessUsageLifecycleWorker is an owning-module scheduler port. It uses collection-group queries only to discover bounded pages of Space-owned records; all financial authority and writes remain in the native services.

func NewBusinessUsageLifecycleWorker added in v0.23.2

func NewBusinessUsageLifecycleWorker(db dal.DB, query dal.QueryExecutor, periods *BusinessUsagePeriodService, activity *QueryActivityService, now func() time.Time) (*BusinessUsageLifecycleWorker, error)

func NewBusinessUsageLifecycleWorkerWithInvoices added in v0.23.3

func NewBusinessUsageLifecycleWorkerWithInvoices(mode contract4paymentus.Mode, db dal.DB, query dal.QueryExecutor, periods *BusinessUsagePeriodService, activity *QueryActivityService, invoices contract4paymentus.UsageInvoiceService, now func() time.Time) (*BusinessUsageLifecycleWorker, error)

func (*BusinessUsageLifecycleWorker) Run added in v0.23.2

Run performs at most one page from each collection group. Failed candidates are counted and skipped for this pass; cursors wrap on a later pass so a single held Space cannot starve other Spaces. The underlying operations are idempotent and safe to retry after interruption.

type BusinessUsagePeriodAuthorityOptions added in v0.23.1

type BusinessUsagePeriodAuthorityOptions struct {
	Mode          contract4paymentus.Mode
	Access        *BusinessProjectAccessVerifier
	InitialStarts contract4paymentus.InitialServiceStartReader
	Periods       contract4paymentus.UsagePeriodReader
	CloseTerms    BusinessUsageCloseTermsReader
	// Pricing resolves the current server-approved config for new periods. It
	// is a server-owned dependency, never request input. Existing periods keep
	// the config frozen in their native snapshot.
	Pricing func() contract4paymentus.UsagePricingConfig
	Now     func() time.Time
}

type BusinessUsagePeriodOpener added in v0.23.2

type BusinessUsagePeriodOpener interface {
	OpenCurrent(context.Context, string) (contract4paymentus.UsagePeriodSnapshot, error)
}

type BusinessUsagePeriodService added in v0.23.1

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

BusinessUsagePeriodService makes the staged open/close sequence externally idempotent. A partial stage leaves a non-ready checkpoint that cannot admit reports or close; retry completes only after the native ledger confirms the exact stored period.

func NewBusinessUsagePeriodService added in v0.23.1

func NewBusinessUsagePeriodService(db dal.DB, authority *NativeBusinessUsagePeriodAuthority, ledger contract4paymentus.UsageLedger, now func() time.Time) (*BusinessUsagePeriodService, error)

func (*BusinessUsagePeriodService) Close added in v0.23.1

func (*BusinessUsagePeriodService) CloseDue added in v0.23.2

CloseDue derives the close request from the server clock, the stored completeness checkpoint, the frozen native period, and server-verified close terms. Callers cannot select a close time, capacity, or price inputs. A previously staged or completed close reuses its immutable request.

func (*BusinessUsagePeriodService) OpenCurrent added in v0.23.1

func (*BusinessUsagePeriodService) ResumeOpening added in v0.23.2

ResumeOpening recovers an Opening checkpoint without granting current access. If the native Open never committed, it may retry only while the exact same anchored period is still current and independently authorized.

type BusinessUsageRuntime added in v0.23.3

BusinessUsageRuntime exposes the server-owned composition used by project activity intake and the bounded lifecycle scheduler.

func NewBusinessUsageRuntime added in v0.23.3

func NewBusinessUsageRuntime(options BusinessUsageRuntimeOptions) (*BusinessUsageRuntime, error)

type BusinessUsageRuntimeOptions added in v0.23.3

type BusinessUsageRuntimeOptions struct {
	DB              dal.DB
	Query           dal.QueryExecutor
	Mode            contract4paymentus.Mode
	CurrentService  contract4paymentus.CurrentSpaceServiceReader
	InitialStarts   contract4paymentus.InitialServiceStartReader
	Contacts        CurrentProjectContactPort
	Actors          BusinessActivityActorVerifier
	AccessPolicy    BusinessProjectAccessPolicy
	TaxPolicies     []BusinessUsageTaxPolicyRegistration
	InvoiceProvider contract4paymentus.UsageInvoiceProvider
	Pricing         func() contract4paymentus.UsagePricingConfig
	Now             func() time.Time
	// contains filtered or unexported fields
}

BusinessUsageRuntimeOptions binds a complete usage runtime to one fixed provider mode. Every authority and worker created here uses that same mode. The invoice provider is supplied through the published Paymentus contract; callers do not pass provider IDs or tax choices in activity requests.

type BusinessUsageTaxPolicyRegistration added in v0.23.3

type BusinessUsageTaxPolicyRegistration struct {
	Policy  contract4paymentus.UsageInvoiceStripeTaxPolicy
	Current bool
}

BusinessUsageTaxPolicyRegistration is immutable server configuration. One entry is selected for new periods; non-current entries remain available to validate historical closed periods after a tax policy revision.

type BusinessUsageTestClockRuntime added in v0.24.0

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

BusinessUsageTestClockRuntime is a Space-scoped TEST harness surface. It deliberately omits the global lifecycle worker and refreshes its provider capability before every exposed operation.

func NewBusinessUsageTestClockRuntime added in v0.24.0

func NewBusinessUsageTestClockRuntime(options BusinessUsageRuntimeOptions, clock *contract4paymentus.ServiceTestClockCapability, spaceID string) (*BusinessUsageTestClockRuntime, error)

NewBusinessUsageTestClockRuntime composes the normal native runtime with a verified, exact-Space TEST clock. Caller-provided clocks are never accepted.

func (*BusinessUsageTestClockRuntime) CloseDue added in v0.24.0

func (*BusinessUsageTestClockRuntime) Drain added in v0.26.0

Drain delivers one bounded page from this Space's native activity outbox. It never invokes the global lifecycle worker or scans another Space.

func (*BusinessUsageTestClockRuntime) IssueContext added in v0.24.0

func (r *BusinessUsageTestClockRuntime) IssueContext(ctx context.Context, actorID, spaceID, projectID string) (QueryActivityContextResponse, error)

IssueContext and Report are the only activity operations exposed to the harness; the server refreshes the clock before entering existing authority.

func (*BusinessUsageTestClockRuntime) OpenCurrent added in v0.24.0

func (*BusinessUsageTestClockRuntime) PrepareInvoice added in v0.24.0

func (*BusinessUsageTestClockRuntime) ProcessInvoice added in v0.24.0

func (*BusinessUsageTestClockRuntime) ReadInvoice added in v0.24.0

func (*BusinessUsageTestClockRuntime) ReadPeriod added in v0.26.0

ReadPeriod returns only the native verified ledger state for this exact TEST Space. The period service validates its original anchor and checkpoint in one read-only transaction; it does not reacquire current paid access.

func (*BusinessUsageTestClockRuntime) ReplayPendingInvoicePaid added in v0.26.0

func (r *BusinessUsageTestClockRuntime) ReplayPendingInvoicePaid(ctx context.Context, spaceID, eventID string, signed *contract4paymentus.ServiceSignedEventService) error

ReplayPendingInvoicePaid retries one previously verified signed invoice event through Paymentus' opaque capability-bound invoice replay. The signed service constructs its native router internally; this wrapper never exposes or mutates that router.

func (*BusinessUsageTestClockRuntime) Report added in v0.24.0

func (*BusinessUsageTestClockRuntime) UsageInvoiceBuyerLookup added in v0.26.1

UsageInvoiceBuyerLookup exposes only the Paymentus read-only actor lookup bound to this runtime's native invoice service and exact TEST capability. It accepts no scope or buyer selectors from callers.

type CallerAdmissionReader added in v0.6.0

type CallerAdmissionReader interface {
	ReadAdmissionForCaller(context.Context, string, string, time.Time) (AdmissionState, error)
}

CallerAdmissionReader lets the host read admission for the authenticated caller and the personal account already proved by PersonalAccountDirectory. The implementation must supply the actual daily count, not a placeholder.

type CloudProjectAccess added in v0.60.6

type CloudProjectAccess struct {
	You     string                      `json:"you"`
	Members []CloudProjectAccessMember  `json:"members,omitempty"`
	Pending []CloudProjectAccessPending `json:"pending,omitempty"`
}

CloudProjectAccess is the project_access response. Members and Pending are returned to an owner only; any other member sees only You.

type CloudProjectAccessMember added in v0.60.6

type CloudProjectAccessMember struct {
	ContactID string `json:"contactID"`
	Title     string `json:"title"`
	Role      string `json:"role"`
	Basis     string `json:"basis"`
}

type CloudProjectAccessPending added in v0.60.6

type CloudProjectAccessPending struct {
	InviteID  string    `json:"inviteID"`
	ContactID string    `json:"contactID"`
	Title     string    `json:"title"`
	Role      string    `json:"role"`
	CreatedAt time.Time `json:"createdAt"`
	// WouldJoin is computed when read, for a joiner without a plan, from the
	// owner's current plan and quota: allowed, needs_pro or owner_quota_full.
	WouldJoin string `json:"wouldJoin"`
}

type CloudProjectArchiveCommand added in v0.60.6

type CloudProjectArchiveCommand struct {
	SpaceID, ProjectID string
	Archived           bool
}

CloudProjectArchiveCommand archives (Archived) or restores a cloud project.

type CloudProjectClone added in v0.61.1

type CloudProjectClone struct {
	Source    m.GitHubProjectCloneSource
	ReadFiles func(context.Context) (map[string][]byte, error)
}

CloudProjectClone is server supplied: Files comes from the source provider's immutable, verified tree reader. It cannot be supplied through JSON.

type CloudProjectCreateCommand added in v0.60.6

type CloudProjectCreateCommand struct {
	ActorID, CommandID, Title string
	Clone                     *CloudProjectClone
}

CloudProjectCreateCommand is create_cloud_project's command. The command id is client-minted when the form opens and resent by every retry.

func (CloudProjectCreateCommand) Validate added in v0.60.6

func (c CloudProjectCreateCommand) Validate() error

type CloudProjectDeleteCommand added in v0.60.6

type CloudProjectDeleteCommand struct {
	SpaceID, ProjectID, ConfirmTitle string
}

CloudProjectDeleteCommand deletes a cloud project. ConfirmTitle must equal the project title.

type CloudProjectDeleteResult added in v0.60.6

type CloudProjectDeleteResult struct {
	// SpaceDeleted: the project's dedicated Space was deleted with it.
	SpaceDeleted bool `json:"spaceDeleted"`
	// SpaceKept: the dedicated Space still holds another DataTug project or
	// live DataTug data, so it is treated as shared: no invite is revoked, no
	// member removed, and the Space stays.
	SpaceKept bool `json:"spaceKept"`
	// PurgePending: some of the project's records remain; calling
	// delete_project again resumes the purge.
	PurgePending bool `json:"purgePending"`
	// InvitesRevokePending: the dedicated Space's invitus invites are not yet
	// revoked (the host has not wired the port, or revoking failed).
	InvitesRevokePending bool `json:"invitesRevokePending"`
	// MembersRemovePending: some of the dedicated Space's other members are
	// not yet removed from it, so the Space stays.
	MembersRemovePending bool `json:"membersRemovePending"`
	// SpaceDeletePending: the dedicated Space is not yet deleted (the port is
	// unwired, an earlier step is pending, or delete_space refused).
	SpaceDeletePending bool `json:"spaceDeletePending"`
	// ResumeQueued: a server follow-up is queued for the pending steps. When a
	// step is pending and none is queued, calling delete_project again is the
	// only way to advance it.
	ResumeQueued bool `json:"resumeQueued"`
}

CloudProjectDeleteResult is delete_project's 200 response on the Space path. Every *Pending flag names a step that is left; the server resumes it.

func (CloudProjectDeleteResult) Pending added in v0.60.6

func (r CloudProjectDeleteResult) Pending() bool

Pending reports whether any step is left.

type CloudProjectDeleteResumeQueue added in v0.60.6

type CloudProjectDeleteResumeQueue interface {
	EnqueueCloudProjectDeleteResume(ctx context.Context, spaceID, projectID string, delay time.Duration) error
}

CloudProjectDeleteResumeQueue is a PORT for the event-driven follow-up of a delete that could not finish in its request. The host binds it to its Cloud Tasks delayed work (as it does for watch changes) and, when the task runs, calls SharedProjectService.ResumeCloudProjectDelete with the same ids.

ResumeCloudProjectDelete acts as the owner recorded on the receipt without any proof of its caller, so the host's task handler must be internal only: reachable solely by Cloud Tasks with its OIDC token verified, never as a public route. The handler's context must carry the Sneat DB (facade.WithSneatDB), which Core's facades read from it.

type CloudProjectInviteCommand added in v0.60.6

type CloudProjectInviteCommand struct {
	SpaceID, ProjectID, OperationID string
	Role, Channel, Email            string
}

CloudProjectInviteCommand is the create_invite request. The actor comes from the verified request context.

type CloudProjectInvitePort added in v0.60.6

type CloudProjectInvitePort interface {
	// CreateMemberInvite writes the Space contact request.ContactID, with no
	// user linked, and a personal link invite to it. It runs its own
	// transactions. Called again for the same contact it writes nothing new and
	// returns the same pending invite.
	CreateMemberInvite(ctx facade.ContextWithUser, request CloudProjectInviteRequest) (CloudProjectInviteTicket, error)
	// ReadInvite reads one invite of the Space without changing anything. It
	// returns ErrCloudProjectInviteInvalid for an unknown or foreign invite.
	ReadInvite(ctx context.Context, spaceID, inviteID string) (CloudProjectInviteState, error)
	// ClaimInvite claims the invite for the caller, who becomes a Space member
	// linked to the invited contact. Claiming an invite the caller already
	// accepted is a no-op.
	ClaimInvite(ctx facade.ContextWithUser, spaceID, inviteID, pin string) error
	// LeaveSpace ends the caller's Space membership through contactID, the
	// contact the caller claimed, when a join is refused after its claim. It
	// is a no-op when the caller is no longer a member through that contact,
	// so a refused join that is retried repeats it safely.
	LeaveSpace(ctx facade.ContextWithUser, spaceID, contactID string) error
}

CloudProjectInvitePort is satisfied in the host by the Sneat contactus and invitus facades, called in-process. No method grants project access: read authority needs a role edge, which only this domain writes.

type CloudProjectInviteRequest added in v0.60.6

type CloudProjectInviteRequest struct {
	SpaceID, ProjectID, ProjectTitle string
	// ContactID is the contact to write, derived from the operation. When it
	// already exists the port adopts it and reuses its pending invite.
	ContactID string
	// Message is the DataTug invite text.
	Message string
}

CloudProjectInviteRequest is built by the domain, never from request fields other than the validated Space and project IDs.

type CloudProjectInviteResult added in v0.60.6

type CloudProjectInviteResult struct {
	InviteID string `json:"inviteID"`
	Pin      string `json:"pin"`
	JoinURL  string `json:"joinUrl"`
}

CloudProjectInviteResult is the create_invite response.

type CloudProjectInviteState added in v0.60.6

type CloudProjectInviteState struct {
	ContactID, Pin, Status, FromUserID, ToUserID string
	Expires                                      time.Time
}

CloudProjectInviteState is the current invitus record of one invite.

type CloudProjectInviteTicket added in v0.60.6

type CloudProjectInviteTicket struct {
	InviteID, Pin, ContactID string
}

CloudProjectInviteTicket is the created invite. The pin leaves the domain only in the response to the inviting owner.

type CloudProjectJoinCommand added in v0.60.6

type CloudProjectJoinCommand struct {
	SpaceID, ProjectID, InviteID, Pin string
}

CloudProjectJoinCommand locates one invite to one cloud project.

type CloudProjectJoinEligibility added in v0.60.6

type CloudProjectJoinEligibility struct {
	Allowed    bool   `json:"allowed"`
	Basis      string `json:"basis,omitempty"`
	Reason     string `json:"reason,omitempty"`
	UpgradeURL string `json:"upgradeUrl,omitempty"`
	Title      string `json:"title,omitempty"`
}

CloudProjectJoinEligibility is the join_eligibility response.

type CloudProjectJoinResult added in v0.60.6

type CloudProjectJoinResult struct {
	SpaceID   string `json:"spaceID"`
	ProjectID string `json:"projectID"`
	Role      string `json:"role"`
}

CloudProjectJoinResult is the project ref join_project returns.

type CloudProjectLifecycleOptions added in v0.60.6

type CloudProjectLifecycleOptions struct {
	Invites CloudProjectSpaceInviteRevoker
	Members CloudProjectSpaceMemberRemover
	Spaces  CloudProjectSpaceDeleter
	Resume  CloudProjectDeleteResumeQueue
}

CloudProjectLifecycleOptions are the host's optional ports. Without them a delete still succeeds: it reports the step as pending, and the Space stays.

type CloudProjectPlanRequiredError added in v0.60.6

type CloudProjectPlanRequiredError struct{ UpgradeURL string }

CloudProjectPlanRequiredError is a 402 refusal that carries the plan's upgrade URL.

func (*CloudProjectPlanRequiredError) Error added in v0.60.6

func (*CloudProjectPlanRequiredError) Unwrap added in v0.60.6

type CloudProjectRef added in v0.60.6

type CloudProjectRef struct {
	SpaceID       string                                  `json:"spaceID"`
	ProjectID     string                                  `json:"projectID"`
	EnvironmentID string                                  `json:"environmentID"`
	CloneSource   *models4datatug.CloudProjectCloneSource `json:"cloneSource,omitempty"`
}

CloudProjectRef is create_cloud_project's 201 response.

type CloudProjectSharingOptions added in v0.60.6

type CloudProjectSharingOptions struct {
	Invites CloudProjectInvitePort
	// AppOrigin is the configured DataTug app origin of join links, e.g. https://datatug.app.
	AppOrigin string
	// InventoryQuery seeds an owner's missing protected-project quota from the
	// complete inventory, exactly as paid creation does.
	InventoryQuery dal.QueryExecutor
	// ReservationTTL is how long an unfinalized owner-quota reservation holds
	// its slot before the next join on the project releases it.
	ReservationTTL time.Duration
}

CloudProjectSharingOptions are trusted host composition.

type CloudProjectSpaceDeleter added in v0.60.6

type CloudProjectSpaceDeleter interface {
	DeleteCloudProjectSpace(ctx facade.ContextWithUser, spaceID string) error
}

CloudProjectSpaceDeleter is a PORT. The host binds it to Core's delete_space facade (facade4spaceus.DeleteSpace), so this module never imports Space internals. It refuses whatever delete_space refuses.

type CloudProjectSpaceInviteRevoker added in v0.60.6

type CloudProjectSpaceInviteRevoker interface {
	RevokePendingSpaceInvites(ctx facade.ContextWithUser, spaceID coretypes.SpaceID) (revoked int, err error)
}

CloudProjectSpaceInviteRevoker is a PORT. The host satisfies it with invitus' contract4invitus.SpaceInviteRevoker (facade4invitus.NewSpaceInvites()), whose method set it repeats. It revokes the dedicated Space's pending invites, acting as the authenticated owner in ctx.

type CloudProjectSpaceMemberRemover added in v0.60.6

type CloudProjectSpaceMemberRemover interface {
	RemoveSpaceMember(ctx facade.ContextWithUser, spaceID, contactID string) error
}

CloudProjectSpaceMemberRemover is a PORT. The host binds it to contactus' remove_space_member facade (facade4contactus.RemoveSpaceMember), which takes the member's Space contact. delete_space refuses while any user but the owner remains, so a dedicated Space's other members are removed first.

type CloudProjectSpacePort added in v0.60.6

type CloudProjectSpacePort interface {
	// CloudProjectSpaceID returns, without I/O, the Space id that the create
	// command (actorID, commandID) resolves to.
	CloudProjectSpaceID(actorID, commandID string) string
	// PrepareCloudProjectSpace performs only reads. It returns the creator's
	// new contact, whose linkage graph the caller may still change, and an
	// Apply that performs only writes. The caller makes all of its own reads
	// before Prepare and calls Apply once, before its own writes.
	PrepareCloudProjectSpace(ctx context.Context, tx dal.ReadwriteTransaction, request CloudProjectSpaceRequest) (PreparedCloudProjectSpace, error)
}

CloudProjectSpacePort creates the dedicated Space of a new cloud project inside the caller's DAL transaction. The host binds it to Core's CreateSpaceTxWorker, so the Space, its creator contact and the creator's spaces map commit atomically with the project.

type CloudProjectSpaceRequest added in v0.60.6

type CloudProjectSpaceRequest struct {
	ActorID, CommandID, Title string
	CreatedAt                 time.Time
}

CloudProjectSpaceRequest names the Space to create. The Space type is not part of it: the host reads it from DataTug's Space registration profile.

type CloudWatchOptions added in v0.59.1

type CloudWatchOptions struct {
	DB                  dal.DB
	Detective           *DetectiveService
	Identity            WatchIdentityReader
	Now                 func() time.Time
	Limits              watchdaemon.Limits
	AllowedOrigins      []string
	ProjectUIBase       func(WatchCloudScope) string
	CoordinatorEndpoint func(WatchCloudScope) string
	Email               watchdaemon.EmailSender
	SMS                 watchdaemon.SMSSender
	Enqueue             func(context.Context, string, time.Duration) error
}

type CloudWatchService added in v0.59.1

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

func NewCloudWatchService added in v0.59.1

func NewCloudWatchService(o CloudWatchOptions) (*CloudWatchService, error)

func (*CloudWatchService) CatchUp added in v0.59.1

CatchUp rotates a durable bounded registry cursor. It recovers due work even if a process died between a Firestore commit and Cloud Tasks publication.

func (*CloudWatchService) ChangeEnrollment added in v0.59.1

func (s *CloudWatchService) ChangeEnrollment(ctx context.Context, user string, scope WatchCloudScope, request WatchEnrollmentMutation, revoke bool) (WatchEnrollmentResult, error)

func (*CloudWatchService) EnrollRunner added in v0.59.1

func (*CloudWatchService) ForRunner added in v0.59.1

func (*CloudWatchService) ForUser added in v0.59.1

func (s *CloudWatchService) ForUser(ctx context.Context, user string, scope WatchCloudScope) (http.Handler, error)

ForUser constructs a request-owned transport/store view. It does not mutate a shared server or close the host database. Every storage transaction repeats current project checks, including replay and no-op requests.

func (*CloudWatchService) ListEnrollments added in v0.59.1

func (s *CloudWatchService) ListEnrollments(ctx context.Context, user string, scope WatchCloudScope, after string) (WatchEnrollmentPage, error)

func (*CloudWatchService) Preflight added in v0.59.1

func (s *CloudWatchService) Preflight(w http.ResponseWriter, r *http.Request)

func (*CloudWatchService) ProcessChange added in v0.59.1

func (s *CloudWatchService) ProcessChange(ctx context.Context, id string) (WatchQueueReport, error)

ProcessChange is safe after a duplicate or out-of-order queue delivery. The event supplies routing only; all truth, source pins and authority are reread.

func (*CloudWatchService) PublishChanges added in v0.59.1

func (s *CloudWatchService) PublishChanges(ctx context.Context, limit int) (WatchQueueReport, error)

func (*CloudWatchService) RunnerBundle added in v0.59.1

func (*CloudWatchService) Sources added in v0.59.1

func (s *CloudWatchService) Sources(ctx context.Context, user string, scope WatchCloudScope) ([]WatchSource, error)

type ConfiguredProLimits added in v0.5.0

type ConfiguredProLimits struct {
	ByPlanID map[string]ProLimitsSnapshot
}

ConfiguredProLimits is a pure, versioned source of complete Pro grants. Production values are supplied by the host's reviewed configuration.

func (ConfiguredProLimits) ResolveProLimits added in v0.5.0

func (c ConfiguredProLimits) ResolveProLimits(planID string, grants PlanEffectGrants) (ProLimitsSnapshot, error)

type CurrentProjectContactPort added in v0.12.0

type CurrentProjectContactPort interface {
	ReadCurrentProjectContact(context.Context, dal.ReadTransaction, contract4linkage.RelationshipEntityRef) (ProjectContactState, error)
}

type DALProtectedProjectInventory added in v0.15.0

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

DALProtectedProjectInventory uses collection-group scans but accepts records only under the exact spaces/{id}/ext/datatug/projects and spaces/{id}/ext/datatug/projectAdmissions ancestry. Group scans also find orphan subcollections whose parent Space document was deleted. The scan is intentionally unbounded by Firestore query limits; a hard local ceiling fails closed rather than returning a truncated count.

func NewDALProtectedProjectInventory added in v0.15.0

func NewDALProtectedProjectInventory(query dal.QueryExecutor) (*DALProtectedProjectInventory, error)

func (*DALProtectedProjectInventory) CompleteProtectedProjectBasis added in v0.15.0

func (i *DALProtectedProjectInventory) CompleteProtectedProjectBasis(ctx context.Context, mode, product, payer string) (InitialProtectedProjectBasis, error)

type DemoPersonalSpaceProvisioner added in v0.29.1

type DemoPersonalSpaceProvisioner interface {
	EnsurePersonalSpace(context.Context, string) (PersonalAccount, error)
}

DemoPersonalSpaceProvisioner is an owning-Core host port. It resolves or provisions the verified caller's Personal Space before any demo mutation. A browser-provided space ID is only a hint and must equal this proof.

type DetectiveDemoProjectRequest added in v0.29.1

type DetectiveDemoProjectRequest struct {
	SpaceID     string `json:"spaceID,omitempty"`
	OperationID string `json:"operationId"`
}

type DetectivePersonalActivationOptions added in v0.29.1

type DetectivePersonalActivationOptions struct {
	Activator contract4spaceus.TransactionalPersonalCapabilityActivator
}

ConfigureDemoWithActivation lets the owning host enable DataTug on a newly resolved Personal Space inside the same transaction as demo creation. It does not configure any paid project grant.

type DetectiveService added in v0.29.1

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

func NewDetectiveService added in v0.29.1

func NewDetectiveService(project *SharedProjectService, executor HostedDetectiveQueryExecutor) (*DetectiveService, error)

func (*DetectiveService) AIConfirm added in v0.29.1

func (s *DetectiveService) AIConfirm(ctx context.Context, actor string, request HostedAIConfirm) (detectiveai.Receipt, error)

func (*DetectiveService) AIGenerate added in v0.29.1

func (s *DetectiveService) AIGenerate(ctx context.Context, actor string, request HostedAIGenerate, provider ai.LLMProvider) (detectiveai.Response, error)

func (*DetectiveService) AIProposals added in v0.29.1

func (s *DetectiveService) AIProposals(ctx context.Context, actor, space, project, after string) (HostedAIPage, error)

func (*DetectiveService) AIReview added in v0.29.1

func (s *DetectiveService) AIReview(ctx context.Context, actor string, request HostedAIReview) (detectiveai.Proposal, error)

func (*DetectiveService) Action added in v0.29.1

Action applies one reviewed mutation with current project authorization, optimistic versions, immutable idempotency and metadata-only audit in the same retryable database transaction. Runs use a separate accept/execute/ finalize path so external query execution is never retried by Firestore.

func (*DetectiveService) AddNativeSemanticMapping added in v0.59.1

func (*DetectiveService) AdmitQuickSearchItem added in v0.59.1

func (s *DetectiveService) AdmitQuickSearchItem(ctx context.Context, actor, space, project string, d qs.Document) error

AdmitQuickSearchItem uses the serving asset readers and current environment bindings. Metadata categories without an equivalent admission fail closed.

func (*DetectiveService) ApplicableNativeSemantic added in v0.59.1

func (*DetectiveService) AuthorizeShippingSessionScope added in v0.59.1

func (s *DetectiveService) AuthorizeShippingSessionScope(ctx context.Context, actor, space, project string, scope sessioncontext.Scope) error

AuthorizeShippingSessionScope is the host's native content-authorizer seam. It admits a current or retained generation only after current project/source rights. Reset must not make an original authorized evidence Bag unreadable.

func (*DetectiveService) BrowseNativeSemantic added in v0.59.1

func (*DetectiveService) CaseEvents added in v0.29.1

func (s *DetectiveService) CaseEvents(ctx context.Context, actor, space, project, caseID string, before int) (detective.CaseEventsPage, error)

CaseEvents pages the append-only event records by ordinal. The Case's timeline is a recent preview only; older history remains direct-readable.

func (*DetectiveService) ChangeProjectMeanings added in v0.59.1

func (s *DetectiveService) ChangeProjectMeanings(ctx context.Context, actor, space, project string, request datatug.ProjectMeaningWrite) (datatug.ProjectMeaningAck, error)

func (*DetectiveService) ConfigureBuiltinDemoAndPaidEnvironments added in v0.59.1

func (s *DetectiveService) ConfigureBuiltinDemoAndPaidEnvironments(paid HostedProjectEnvironmentProvider) error

ConfigureBuiltinDemoAndPaidEnvironments explicitly composes the actor-proven immutable Demo catalogue with the host's paid environment provider. It must be called during service construction. Provider failure never selects Demo; only readDemoProjectAccess in the serving transaction can grant that route.

func (*DetectiveService) ConfigureDemo added in v0.29.1

func (*DetectiveService) ConfigureDemoWithActivation added in v0.29.1

func (s *DetectiveService) ConfigureDemoWithActivation(space DemoPersonalSpaceProvisioner, owner PersonalPlanOwnerPort, activation DetectivePersonalActivationOptions) error

func (*DetectiveService) ConfigureIncidents added in v0.29.1

func (s *DetectiveService) ConfigureIncidents(store incidents.APIStore, storeID string) error

ConfigureIncidents binds a dedicated Incidentius APIStore. Its durable Create/Append/Projection implementation belongs to the host's Incidentius provider; Detective only owns verified Case linkage and current-policy views.

func (*DetectiveService) ConfigurePaidEnvironments added in v0.29.1

func (s *DetectiveService) ConfigurePaidEnvironments(provider HostedProjectEnvironmentProvider) error

func (*DetectiveService) ConfigureShippingSQL added in v0.59.1

func (s *DetectiveService) ConfigureShippingSQL() error

ConfigureShippingSQL explicitly enables the bounded native training adapter. It grants no source access: every operation still requires native publication.

func (*DetectiveService) ConfigureShippingSessionContext added in v0.59.1

func (s *DetectiveService) ConfigureShippingSessionContext(service *HostedSessionDetectiveService) error

ConfigureShippingSessionContext binds the existing native session owner, not a browser-defined namespace or replacement context store.

func (*DetectiveService) CreateOrResumeDemo added in v0.29.1

func (*DetectiveService) DetectiveStateVisibilityJSON added in v0.61.1

func (s *DetectiveService) DetectiveStateVisibilityJSON(ctx context.Context, actor, space, project string, value detective.State) (json.RawMessage, error)

DetectiveStateVisibilityJSON annotates HTTP discovery copies only. State and its definitions remain complete for selected details, saved references and execution resolvers; archive metadata never enters mutation/source DTOs.

func (*DetectiveService) IncidentAction added in v0.29.1

func (s *DetectiveService) IncidentAction(ctx context.Context, actor string, request HostedIncidentAction) (HostedIncidentResponse, error)

IncidentAction uses Incidentius's durable mutation ID for a cross-store create; a retry after a crash replays Create, then safely retries the Case linkage. A private Detective operation receipt is committed with the Case.

func (*DetectiveService) IncidentEvents added in v0.59.1

func (s *DetectiveService) IncidentEvents(ctx context.Context, actor, space, project, environment, incidentRef string, after uint64, limit int) (HostedIncidentEvents, error)

IncidentEvents returns ascending immutable events. The cursor tracks scanned events, including withheld ones, so revocation cannot trap pagination.

func (*DetectiveService) InstallShippingComponent added in v0.59.1

func (*DetectiveService) KnowledgeAction added in v0.29.1

func (s *DetectiveService) KnowledgeAction(ctx context.Context, actor string, request HostedKnowledgeAction) (HostedKnowledgeResponse, error)

func (*DetectiveService) KnowledgeProposals added in v0.29.1

func (s *DetectiveService) KnowledgeProposals(ctx context.Context, actor, space, project, after string) (HostedKnowledgePage, error)

func (*DetectiveService) LinkedIncidents added in v0.29.1

func (s *DetectiveService) LinkedIncidents(ctx context.Context, actor, space, project, caseID string) (HostedIncidentLinks, error)

LinkedIncidents independently checks current project authorization, Case ownership, and each Incidentius projection before exposing a policy view.

func (*DetectiveService) ListProjectBoards added in v0.59.1

func (s *DetectiveService) ListProjectBoards(ctx context.Context, actor, space, project, environment string) ([]datatug.ProjBoardBrief, error)

func (*DetectiveService) ListProjectCards added in v0.59.1

func (s *DetectiveService) ListProjectCards(ctx context.Context, actor, space, project, environment string) ([]datatug.CardBrief, error)

func (*DetectiveService) ListProjectEntities added in v0.59.1

func (s *DetectiveService) ListProjectEntities(ctx context.Context, actor, space, project, environment string) ([]datatug.ProjEntityBrief, error)

func (*DetectiveService) OpenShippingEvidence added in v0.59.1

func (*DetectiveService) OpenShippingSourceOperation added in v0.59.1

func (*DetectiveService) ProjectIncident added in v0.59.1

func (s *DetectiveService) ProjectIncident(ctx context.Context, actor, space, project, environment, incidentRef string) (HostedProjectIncident, error)

ProjectIncident resolves one ref in the actor's current project scope.

func (*DetectiveService) ProjectIncidents added in v0.59.1

func (s *DetectiveService) ProjectIncidents(ctx context.Context, actor, space, project, environment string) (HostedProjectIncidents, error)

ProjectIncidents lists only the current actor's authorized project and environment. The provider rejects catalogs beyond its fixed 5,000-record bound rather than returning a misleading partial list.

func (*DetectiveService) PublishShippingSource added in v0.59.1

func (*DetectiveService) ReadNativeSemanticRelated added in v0.59.1

func (*DetectiveService) ReadNativeSemanticSchema added in v0.59.1

func (s *DetectiveService) ReadNativeSemanticSchema(ctx context.Context, actor, space, project, environment, source string) (models4datatug.NativeSemanticSchema, error)

ReadNativeSemanticSchema reads current source metadata only; it does not grant data access, publish a source or create native context.

func (*DetectiveService) ReadProjectBoard added in v0.59.1

func (s *DetectiveService) ReadProjectBoard(ctx context.Context, actor, space, project, environment, id string) (dto.SaveBoardResponse, error)

func (*DetectiveService) ReadProjectCard added in v0.59.1

func (s *DetectiveService) ReadProjectCard(ctx context.Context, actor, space, project, environment, id string) (dto.SaveCardResponse, error)

func (*DetectiveService) ReadProjectEntity added in v0.59.1

func (s *DetectiveService) ReadProjectEntity(ctx context.Context, actor, space, project, environment, id string) (dto.SaveEntityResponse, error)

func (*DetectiveService) ReadProjectEntityDefinition added in v0.61.1

func (s *DetectiveService) ReadProjectEntityDefinition(ctx context.Context, actor, space, project, environment, id string) (out ProjectEntityDefinition, err error)

func (*DetectiveService) ReadProjectMeanings added in v0.59.1

func (s *DetectiveService) ReadProjectMeanings(ctx context.Context, actor, space, project string) (datatug.ProjectMeaningsCatalog, error)

func (*DetectiveService) ReadQuickSearchMetadata added in v0.59.1

func (s *DetectiveService) ReadQuickSearchMetadata(ctx context.Context, actor, space, project, environment string) (qs.MetadataSnapshot, error)

ReadQuickSearchMetadata uses serving readers; source-binding existence never substitutes for a physical schema inventory.

func (*DetectiveService) ReadShippingCheckRun added in v0.59.1

func (s *DetectiveService) ReadShippingCheckRun(ctx context.Context, actor, space, project, environment string, ref incidents.CheckRunRef) (ShippingCheckRunOpenResponse, error)

func (*DetectiveService) ReadShippingComponent added in v0.59.1

func (s *DetectiveService) ReadShippingComponent(ctx context.Context, actor, space, project, source, environment string) (models4datatug.ShippingComponentState, error)

func (*DetectiveService) ReadShippingExecution added in v0.59.1

func (s *DetectiveService) ReadShippingExecution(ctx context.Context, actor, space, project, environment string, ref apicontract.ExecutionRef) (ShippingEvidenceOpenResponse, error)

ReadShippingExecution opens the exact retained ordinary execution without a row selector. It never grants a slot that the result sidecar does not admit.

func (*DetectiveService) ReadShippingPublication added in v0.59.1

func (s *DetectiveService) ReadShippingPublication(ctx context.Context, actor, space, project, source, environment string) (models4datatug.ShippingPublicationState, error)

ReadShippingPublication distinguishes authorized absence from denied or failed reads. Disabled publications remain readable without promoting their execution grant.

func (*DetectiveService) ReadShippingRevision added in v0.59.1

func (s *DetectiveService) ReadShippingRevision(ctx context.Context, actor, space, project, source string, p *models4datatug.ShippingPointer) (models4datatug.ShippingRevision, []byte, error)

ReadShippingRevision returns immutable application bytes only through current project rights. This internal host API is not an executable source admission.

func (*DetectiveService) RelatedNativeSemantic added in v0.59.1

func (*DetectiveService) ResolveNativeSemantic added in v0.59.1

func (*DetectiveService) RunSavedQuery added in v0.29.1

func (s *DetectiveService) RunSavedQuery(ctx context.Context, actor string, request HostedQueryRunRequest) (HostedQueryRunResponse, error)

func (*DetectiveService) SaveProjectBoard added in v0.59.1

func (s *DetectiveService) SaveProjectBoard(ctx context.Context, actor, space string, request dto.SaveBoardRequest) (dto.SaveBoardResponse, error)

func (*DetectiveService) SaveProjectCard added in v0.59.1

func (s *DetectiveService) SaveProjectCard(ctx context.Context, actor, space string, request dto.SaveCardRequest) (dto.SaveCardResponse, error)

func (*DetectiveService) SaveProjectEntity added in v0.59.1

func (s *DetectiveService) SaveProjectEntity(ctx context.Context, actor, space string, request dto.SaveEntityRequest) (dto.SaveEntityResponse, error)

func (*DetectiveService) ShippingAction added in v0.59.1

ShippingAction prepares real SQLite outside the transaction, then atomically compares the exact pointer and persists a closed revision + immutable receipt.

func (*DetectiveService) ShippingContextScope added in v0.59.1

func (s *DetectiveService) ShippingContextScope(ctx context.Context, actor, space, project, environment string) (sessioncontext.Scope, sessioncontext.Subject, error)

ShippingContextScope exposes current admitted source identity for native Bag authoring. It is metadata only and confers no execution/content authority.

func (*DetectiveService) ShippingSessionCatalog added in v0.59.1

func (s *DetectiveService) ShippingSessionCatalog(ctx context.Context, actor, space, project, environment string) (sessioncontext.Scope, sessioncontext.Subject, bool, error)

ShippingSessionCatalog classifies an already declared environment under current access. Missing native binding/publication and disabled publication omit only shipping; failed access, infrastructure and corrupt metadata never do.

func (*DetectiveService) ShippingSourceOperations added in v0.59.1

func (s *DetectiveService) ShippingSourceOperations(ctx context.Context, actor, space, project, environment string) (ShippingSourceOperationsResponse, error)

func (*DetectiveService) State added in v0.29.1

func (s *DetectiveService) State(ctx context.Context, actor, space, project, runsBefore string) (detective.State, error)

type Facade

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

Facade carries the injected database and ports for the DataTug extension's application commands. The host constructs one Facade at composition time (datatug-cloud, internal/composition), wiring a real adapter per port; tests construct it over an in-memory database with fakes.

func NewFacade

func NewFacade(db dal.DB, ids IDGenerator) Facade

NewFacade returns a Facade over the given database and ports.

func (Facade) CreateProject

func (f Facade) CreateProject(
	ctx context.Context, userID, storeID, title string,
) (projectID string, err error)

CreateProject creates a DataTug project in the cloud store and registers its brief in the user's DataTug index, both in one transaction. It returns the id of the created project.

func (Facade) DeleteEmptyProject added in v0.60.3

func (f Facade) DeleteEmptyProject(ctx context.Context, userID, projectID string) error

DeleteEmptyProject permanently deletes a personal DataTug cloud project the user is a member of, together with its brief in the user's DataTug index. It refuses with ErrProjectNotEmpty when the project holds environments or any document in projectContentCollections; a project with content is archived instead (SetProjectArchived). Only the caller's own index brief is removed: a personal project has one member.

func (Facade) ReadFavorites added in v0.59.1

func (f Facade) ReadFavorites(ctx context.Context, actor string, project m.FavoriteProject) ([]m.Favorite, error)

func (Facade) RegisterGithubProject added in v0.2.0

func (f Facade) RegisterGithubProject(
	ctx context.Context, userID string, request RegisterGithubProjectRequest,
) (projectID string, err error)

RegisterGithubProject records a project that lives in a GitHub repository in the user's DataTug index, so it shows up among the user's projects.

The project files themselves are created by the client that holds the user's GitHub credential — this command only keeps the index; the cloud never talks to GitHub. It returns the project id the web client addresses the project by (`repo@org@folder`).

func (Facade) SetFavorite added in v0.59.1

func (f Facade) SetFavorite(ctx context.Context, actor string, project m.FavoriteProject, item m.Favorite, selected bool) ([]m.Favorite, error)

SetFavorite is idempotent and derives the only writable user path from the verified actor. Adding requires target authority; removal of an existing private reference remains possible after that authority is lost.

func (Facade) SetGitHubProjectArchived added in v0.61.1

func (f Facade) SetGitHubProjectArchived(ctx context.Context, userID, projectID, branch string, archived bool) error

SetGitHubProjectArchived changes visibility in the caller's existing DataTug project index. It never archives the repository or changes provider access. The saved branch must match, preventing a stale tab from changing another registered branch of the same repository folder.

func (Facade) SetProjectArchived added in v0.60.3

func (f Facade) SetProjectArchived(ctx context.Context, userID, projectID string, archived bool) error

SetProjectArchived archives (or restores) a personal DataTug cloud project the user is a member of. Archiving keeps everything; it stamps the project and flags its brief so lists can set it aside.

func (Facade) WithFavoriteTargetAdmission added in v0.60.0

func (f Facade) WithFavoriteTargetAdmission(admit FavoriteTargetAdmission) Facade

type FavoriteTargetAdmission added in v0.60.0

type FavoriteTargetAdmission func(context.Context, dal.ReadwriteTransaction, string, m.FavoriteProject, m.Favorite) (func() error, error)

Admission proves current read access and exact target existence. All reads occur before any write; the returned write-only closure participates in the same transaction. GitHub providers cannot certify project lifecycle coverage until they also fence external repository writers.

type FirstAdmittedMonthReader added in v0.4.0

type FirstAdmittedMonthReader interface {
	ReadFirstAdmittedMonth(context.Context, string, string, string) (string, error)
}

FirstAdmittedMonthReader reads the same immutable, server-only first-admission marker used by the AI meter. Empty means no question has been admitted yet. It is keyed by product and caller, with the proved personal account included so the host can reject a mismatched binding.

type GitHubActivityScope added in v0.25.0

type GitHubActivityScope struct {
	SpaceID   string `json:"spaceID"`
	ProjectID string `json:"projectID"`
}

type GitHubCreateRepository added in v0.14.0

type GitHubCreateRepository interface {
	Scope() GitHubCreateRepositoryScope
	CurrentHead(context.Context, string) (string, error)
	EnsureFolderEmpty(context.Context, string, string) error
	CreateFilesCommit(context.Context, string, string, string, map[string][]byte) (string, error)
	FindCommitByMarker(context.Context, string, string, string, map[string][]byte) (string, error)
}

GitHubCreateRepository is implemented by a per-request, actor-bound adapter around githubauth4datatug.AuthorizedGitHubRepository. Its methods never expose OAuth or installation tokens to this module or to a caller.

type GitHubCreateRepositoryScope added in v0.14.0

type GitHubCreateRepositoryScope struct {
	ActorID, Owner, Name, Permission string
	RepositoryID                     int64
}

type GitHubEnvironmentRepository added in v0.59.1

GitHubEnvironmentRepository binds one freshly authorized immutable repository. ProofCursor retains a resumable traversal frontier; a bounded batch cannot permanently turn an unresolved operation into a failed operation.

type GitHubMeaningAuthority added in v0.59.1

type GitHubMeaningAuthority interface {
	AuthorizeGitHubProjectWrite(context.Context, string, int64, string, string, string) (GitHubProjectAccess, error)
}

type GitHubMeaningRepository added in v0.59.1

type GitHubMeaningRepository interface {
	Scope() GitHubCreateRepositoryScope
	ChangeMeanings(context.Context, string, string, string, string, datatug.ProjectMeaningWrite, func() error) (datatug.ProjectMeaningAck, error)
}

type GitHubProjectAccess added in v0.14.0

type GitHubProjectAccess struct {
	SpaceID         string
	SharedProjectID string
	Binding         models4datatug.GitHubProjectBinding
	// ActivityScope is present only for a validated registered Business v2
	// admission. It is a client-side selector, not an authorization grant.
	ActivityScope *GitHubActivityScope `json:"-"`
}

type GitHubProjectCreateCommand added in v0.14.0

type GitHubProjectCreateCommand struct {
	ActorID, SpaceID, OperationID, Title string
	BillingIntent                        SharedProjectBillingIntent
	Source                               models4datatug.GitHubCreateSource
	ReadSource                           func(context.Context) (map[string][]byte, error)
}

func (GitHubProjectCreateCommand) Validate added in v0.14.0

func (c GitHubProjectCreateCommand) Validate() error

type GitHubProjectCreateResult added in v0.14.0

type GitHubProjectCreateResult struct {
	OperationID     string                               `json:"operationID"`
	ID              string                               `json:"id"`
	Storage         string                               `json:"storage"`
	Project         string                               `json:"project"`
	SpaceID         string                               `json:"spaceID"`
	SharedProjectID string                               `json:"sharedProjectID"`
	Branch          string                               `json:"branch"`
	BranchHead      string                               `json:"branchHead"`
	Revision        string                               `json:"revision"`
	TemplateID      string                               `json:"templateID"`
	TemplateCommit  string                               `json:"templateCommit"`
	Status          string                               `json:"status"`
	SetupPR         *models4datatug.GitHubProjectSetupPR `json:"setupPR,omitempty"`
}

type GitHubProjectCreateStageError added in v0.59.1

type GitHubProjectCreateStageError struct {
	Stage string
	Cause error
	// contains filtered or unexported fields
}

GitHubProjectCreateStageError keeps the original cause and public sentinels. Stage is technical context only: it never changes authorization or retry policy.

func (*GitHubProjectCreateStageError) Error added in v0.59.1

func (*GitHubProjectCreateStageError) PublicClassification added in v0.59.1

func (e *GitHubProjectCreateStageError) PublicClassification() error

func (*GitHubProjectCreateStageError) Unwrap added in v0.59.1

type GitHubProjectCreateStatus added in v0.59.1

type GitHubProjectCreateStatus struct {
	OperationID string                               `json:"operationID"`
	Status      string                               `json:"status"`
	SetupPR     *models4datatug.GitHubProjectSetupPR `json:"setupPR,omitempty"`
	ProjectID   string                               `json:"projectID,omitempty"`
}

type GitHubQueryExpectedFile added in v0.14.0

type GitHubQueryExpectedFile = models4datatug.EnvironmentExpectedFile

type GitHubQueryFileChange added in v0.14.0

type GitHubQueryFileChange struct {
	Path    string
	Content []byte
	Delete  bool
}

type GitHubQueryRepository added in v0.14.0

type GitHubQueryRepository interface {
	Scope() GitHubCreateRepositoryScope
	PrepareQuerySave(context.Context, string, string, string, dto.SaveQueryRequest) (*GitHubQuerySavePlan, error)
	CurrentHead(context.Context, string) (string, error)
	CreateQueryCommit(context.Context, string, string, string, *GitHubQuerySavePlan) (string, error)
	FindQueryCommit(context.Context, string, string, string, *GitHubQuerySavePlan) (string, error)
}

type GitHubQuerySavePlan added in v0.14.0

type GitHubQuerySavePlan struct {
	Changes      []GitHubQueryFileChange
	ExpectedTree map[string]GitHubQueryExpectedFile
	Response     dto.SaveQueryResponse
	BodyChanged  bool
}

type GitHubSetupPullRequestRepository added in v0.59.1

type GitHubSetupPullRequestRepository interface {
	RequiresWorkflowMutation(context.Context, string, string, string) (bool, error)
	CreateSetupPullRequest(context.Context, GitHubCreateRepositoryScope, string, string, string, string, bool, map[string][]byte) (models4datatug.GitHubProjectSetupPR, map[string][]byte, error)
	ReadSetupPullRequest(context.Context, models4datatug.GitHubProjectSetupPR) (string, bool, string, error)
	VerifySetupFiles(context.Context, string, map[string][]byte) error
}

GitHubSetupPullRequestRepository is the production setup flow. It creates an operation-bound branch and PR without modifying the selected base branch.

type GitHubSetupRepairRepository added in v0.59.1

type GitHubSetupRepairRepository interface {
	VerifySetupFilesOnBranch(context.Context, string, string, map[string][]byte) (string, error)
}

type HTTPRunPolicy added in v0.59.1

type HTTPRunPolicy struct {
	// LookupIP resolves a host name; nil uses the system resolver.
	LookupIP func(ctx context.Context, host string) ([]netip.Addr, error)
	// Dial opens a connection to an already-vetted ip:port; nil uses a
	// net.Dialer whose Control hook re-vets the address as a second guard.
	Dial func(ctx context.Context, network, address string) (net.Conn, error)
	// AllowAddr overrides the default address block list (tests only).
	AllowAddr func(netip.Addr) bool
	// Now is the clock for durationMs; nil uses time.Now.
	Now func() time.Time
	// Timeout overrides HTTPRunTimeout (tests only).
	Timeout time.Duration
	// TLSConfig overrides the client TLS config (tests only).
	TLSConfig *tls.Config
}

HTTPRunPolicy holds the seams of the SSRF-guarded runner. The zero value is the production policy; tests inject the dialer, resolver, clock and the address policy so no test needs the network.

type HTTPRunRequest added in v0.59.1

type HTTPRunRequest struct {
	Method     string                   `json:"method,omitempty"`
	URL        string                   `json:"url"`
	Headers    []datatug.HTTPHeaderItem `json:"headers,omitempty"`
	Body       string                   `json:"body,omitempty"`
	Parameters *[]datatug.Parameter     `json:"parameters,omitempty"`
}

HTTPRunRequest is one proxied request. Credential headers are allowed here: this is a run, not a save. Neither headers nor body are ever logged.

A request that carries Parameters, even an empty list, is in template mode (datatug-apps spec http-query-parameters REQ:server-template-endpoint): URL, headers and body are {name} templates that the server substitutes itself with datatug.SubstituteHTTPRunParameters, so the SSRF guard below always evaluates the FINAL URL and a client-substituted URL is never trusted as template output. Without Parameters the request is literal, as before: braces in its URL are sent as they are.

type HTTPRunResponse added in v0.59.1

type HTTPRunResponse struct {
	Status       int                      `json:"status"`
	StatusText   string                   `json:"statusText"`
	Headers      []datatug.HTTPHeaderItem `json:"headers"`
	Body         string                   `json:"body"`
	BodyEncoding string                   `json:"bodyEncoding"`
	Truncated    bool                     `json:"truncated"`
	SizeBytes    int                      `json:"sizeBytes"`
	DurationMs   int64                    `json:"durationMs"`
}

HTTPRunResponse is the upstream answer, whatever its status.

type HTTPRunTemplateError added in v0.59.1

type HTTPRunTemplateError struct {
	Template *datatug.HTTPTemplateError
}

HTTPRunTemplateError is a template-mode failure (HTTP 400) that keeps the core error's structure. Its text is fixed: the free-text Detail and the caller-chosen parameter and header names never reach it, so use Sanitised for anything that goes on the wire.

func (*HTTPRunTemplateError) Error added in v0.59.1

func (e *HTTPRunTemplateError) Error() string

func (*HTTPRunTemplateError) Sanitised added in v0.59.1

func (e *HTTPRunTemplateError) Sanitised() (code, parameter, position, header string)

Sanitised returns the error's wire fields. A parameter id or header name that is not plain (the caller chose it) is dropped, never echoed.

func (*HTTPRunTemplateError) Unwrap added in v0.59.1

func (e *HTTPRunTemplateError) Unwrap() []error

Unwrap lets errors.Is match ErrHTTPRunInvalid and errors.As the core error.

type HTTPRunner added in v0.59.1

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

HTTPRunner executes proxied HTTP requests behind the SSRF guard.

func NewHTTPRunner added in v0.59.1

func NewHTTPRunner(policy HTTPRunPolicy) *HTTPRunner

NewHTTPRunner builds a runner; pass HTTPRunPolicy{} for production.

func (*HTTPRunner) Run added in v0.59.1

Run executes the request. It returns ErrHTTPRunInvalid (400) for a bad request or blocked target and ErrHTTPRunUpstream (502) for upstream failures.

type HostedAIConfirm added in v0.29.1

type HostedAIConfirm struct {
	HostedAIProjectRef
	detectiveai.ConfirmRequest
}

type HostedAIGenerate added in v0.29.1

type HostedAIGenerate struct {
	HostedAIProjectRef
	OperationID    string               `json:"operationId"`
	Text           string               `json:"text"`
	CaseID         string               `json:"caseId,omitempty"`
	ExpectedCounts map[string]int       `json:"expectedCounts,omitempty"`
	Sources        []detectiveai.Source `json:"sources,omitempty"`
}

type HostedAIPage added in v0.29.1

type HostedAIPage struct {
	Proposals  []detectiveai.Proposal `json:"proposals"`
	HasMore    bool                   `json:"hasMore"`
	NextCursor string                 `json:"nextCursor,omitempty"`
}

type HostedAIProjectRef added in v0.29.1

type HostedAIProjectRef struct {
	Storage string `json:"storage"`
	SpaceID string `json:"spaceID"`
	Project string `json:"project"`
}

type HostedAIReview added in v0.29.1

type HostedAIReview struct {
	HostedAIProjectRef
	Type    string                            `json:"type"`
	Draft   *detectiveai.ReviewedDraftRequest `json:"draft,omitempty"`
	Context *detectiveai.ContextReviewRequest `json:"context,omitempty"`
}

type HostedCriterionDraft added in v0.59.1

type HostedCriterionDraft struct {
	Version       uint64 `json:"version"`
	CheckID       string `json:"checkID"`
	MaxAgeSeconds int64  `json:"maxAgeSeconds"`
}

type HostedDemoExecutor added in v0.29.1

type HostedDemoExecutor struct {
	Embedded *HostedEmbeddedDemoExecutor
	Public   *HostedOVDBExecutor
}

HostedDemoExecutor dispatches only the two operator-owned origins. The saved query's own federation URL can select a pinned adapter but cannot create a new network destination.

func (*HostedDemoExecutor) ExecuteSavedQuery added in v0.29.1

type HostedDetectiveAction added in v0.29.1

type HostedDetectiveAction struct {
	Evidence    *models4datatug.ShippingEvidenceRequest `json:"evidence,omitempty"`
	Storage     string                                  `json:"storage"`
	SpaceID     string                                  `json:"spaceID"`
	OperationID string                                  `json:"operationId"`
	IfMatch     int64                                   `json:"ifMatch,omitempty"`
	detective.ActionRequest
	// contains filtered or unexported fields
}

HostedDetectiveAction is the cloud envelope around Core's shared action contract. The actor is always supplied by verified HTTP identity, never here.

type HostedDetectiveQueryExecutor added in v0.29.1

type HostedDetectiveQueryExecutor interface {
	ExecuteSavedQuery(context.Context, HostedSavedQueryExecution) (HostedSavedQueryResult, error)
}

The host supplies an admitted read-only execution adapter. This service resolves the saved query and revision in the authorized project before the adapter sees it; the adapter must enforce its own source and row limits.

type HostedDetectiveResponse added in v0.29.1

type HostedDetectiveResponse struct {
	detective.ActionResponse
	Revision       int64  `json:"revision,omitempty"`
	Receipt        string `json:"receipt,omitempty"`
	CaseLinkStatus string `json:"caseLinkStatus,omitempty"`
}

type HostedEmbeddedDemoExecutor added in v0.29.1

type HostedEmbeddedDemoExecutor struct {
	*HostedOVDBExecutor
	// contains filtered or unexported fields
}

HostedEmbeddedDemoExecutor runs admitted TugQL against two immutable, synthetic SQLite snapshots through OpenVaultDB's actual mount and HTTP query handler. Its transport never dials: requests are dispatched to a private in-process read-only handler. The operator owns this instance and closes it at shutdown.

func NewHostedEmbeddedDemoExecutor added in v0.29.1

func NewHostedEmbeddedDemoExecutor(now func() time.Time) (_ *HostedEmbeddedDemoExecutor, err error)

func (*HostedEmbeddedDemoExecutor) Close added in v0.29.1

func (d *HostedEmbeddedDemoExecutor) Close() error

type HostedIncidentAction added in v0.29.1

type HostedIncidentAction struct {
	ExpectedWorkVersion int64                                   `json:"expectedWorkVersion,omitempty"`
	CriteriaAccepted    bool                                    `json:"criteriaAccepted,omitempty"`
	Run                 *incidents.CheckRunRef                  `json:"run,omitempty"`
	Recovery            *incidents.SourceOperationRef           `json:"recovery,omitempty"`
	HumanNote           string                                  `json:"humanNote,omitempty"`
	Criterion           *HostedCriterionDraft                   `json:"criterion,omitempty"`
	CriterionVersion    uint64                                  `json:"criterionVersion,omitempty"`
	Evidence            *models4datatug.ShippingEvidenceRequest `json:"evidence,omitempty"`
	Storage             string                                  `json:"storage"`
	SpaceID             string                                  `json:"spaceID"`
	Project             string                                  `json:"project"`
	OperationID         string                                  `json:"operationId"`
	IfMatch             int64                                   `json:"ifMatch,omitempty"`
	ExpectedSeq         *uint64                                 `json:"expectedSeq,omitempty"`
	Message             *HostedIncidentMessage                  `json:"message,omitempty"`
	Type                string                                  `json:"type"` // create | link | start-case | append-message
	CaseID              string                                  `json:"caseId,omitempty"`
	IncidentRef         string                                  `json:"incidentRef,omitempty"`
	Environment         string                                  `json:"environment"`
	Title               string                                  `json:"title,omitempty"`
	Description         string                                  `json:"description,omitempty"`
	Context             map[string]detective.InputValue         `json:"context,omitempty"`
	Case                *detective.Case                         `json:"case,omitempty"`
}

type HostedIncidentEvents added in v0.59.1

type HostedIncidentEvents struct {
	Events              []incidents.Event                  `json:"events"`
	NextAfterSeq        uint64                             `json:"nextAfterSeq"`
	HasMore             bool                               `json:"hasMore"`
	MessagePresentation *HostedIncidentMessagePresentation `json:"messagePresentation,omitempty"`
}
type HostedIncidentLinks struct {
	CaseID    string                   `json:"caseId"`
	Incidents []incidents.IncidentView `json:"incidents"`
}

type HostedIncidentMessage added in v0.59.1

type HostedIncidentMessage struct {
	Body         string                      `json:"body"`
	Assertion    incidents.AssertionKind     `json:"assertion,omitempty"`
	Refs         []incidents.ArtifactRef     `json:"refs,omitempty"`
	Presentation *incidents.NotePresentation `json:"presentation,omitempty"`
}

type HostedIncidentMessagePresentation added in v0.59.1

type HostedIncidentMessagePresentation struct {
	Status       string   `json:"status"`
	Kind         string   `json:"kind,omitempty"`
	CharacterIDs []string `json:"characterIds,omitempty"`
}

HostedIncidentMessagePresentation is an advertisement, never write authority.

type HostedIncidentResponse added in v0.29.1

type HostedIncidentResponse struct {
	Event             *incidents.Event       `json:"event,omitempty"`
	Replayed          bool                   `json:"replayed,omitempty"`
	Incident          incidents.IncidentView `json:"incident"`
	Case              *detective.Case        `json:"case,omitempty"`
	Receipt           string                 `json:"receipt"`
	CaseLinkStatus    string                 `json:"caseLinkStatus,omitempty"` // linked | already-linked | link-pending
	LinkPendingReason string                 `json:"linkPendingReason,omitempty"`
}

type HostedIncidentStore added in v0.29.1

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

HostedIncidentStore is the Firestore Incidentius provider. Each operation requires a private scope inserted by the authenticated Detective facade and rechecks the current project grant inside its own transaction. A single storeID is safe because all records are under the Space/project namespace.

func NewHostedIncidentStore added in v0.29.1

func NewHostedIncidentStore(project *SharedProjectService, storeID string) (*HostedIncidentStore, error)

func (*HostedIncidentStore) Append added in v0.29.1

Append delegates all authority, bounded stream reads and Core folding to the same transaction-local staging seam used by native criterion admission.

func (*HostedIncidentStore) Create added in v0.29.1

func (*HostedIncidentStore) Events added in v0.29.1

func (s *HostedIncidentStore) Events(ctx context.Context, ref incidents.IncidentRef, afterSeq uint64) ([]incidents.Event, error)

func (*HostedIncidentStore) List added in v0.29.1

func (*HostedIncidentStore) Merge added in v0.29.1

Merge is outside the project-scoped hosted Detective admission: importing an entire second incident requires a dedicated cross-resource visibility and receipt protocol. A caller gets an explicit capability error.

func (*HostedIncidentStore) Projection added in v0.29.1

func (*HostedIncidentStore) Watch added in v0.29.1

type HostedKnowledgeAction added in v0.29.1

type HostedKnowledgeAction struct {
	Storage     string                   `json:"storage"`
	SpaceID     string                   `json:"spaceID"`
	Project     string                   `json:"project"`
	OperationID string                   `json:"operationId"`
	IfMatch     int64                    `json:"ifMatch,omitempty"`
	Type        string                   `json:"type"` // save-draft | review | reject | export
	Proposal    *HostedKnowledgeProposal `json:"proposal,omitempty"`
	ProposalID  string                   `json:"proposalId,omitempty"`
	ReviewNote  string                   `json:"reviewNote,omitempty"`
	Target      *HostedKnowledgeTarget   `json:"target,omitempty"`
}

type HostedKnowledgeHandoff added in v0.29.1

type HostedKnowledgeHandoff struct {
	Kind            string                `json:"kind"`
	Status          string                `json:"status"` // ready-for-target-review
	Target          HostedKnowledgeTarget `json:"target"`
	ProposalID      string                `json:"proposalId"`
	ProposalVersion int64                 `json:"proposalVersion"`
	CaseID          string                `json:"caseId"`
	ClaimStatus     string                `json:"claimStatus"`
	Statement       string                `json:"statement"`
	EvidenceRefs    []string              `json:"evidenceRefs"`
	FindingRefs     []string              `json:"findingRefs,omitempty"`
	PreparedAt      time.Time             `json:"preparedAt"`
	PreparedBy      string                `json:"preparedBy"`
	Receipt         string                `json:"receipt"`
}

type HostedKnowledgePage added in v0.29.1

type HostedKnowledgePage struct {
	Proposals  []HostedKnowledgeProposal `json:"proposals"`
	NextCursor string                    `json:"nextCursor,omitempty"`
	HasMore    bool                      `json:"hasMore"`
}

type HostedKnowledgeProposal added in v0.29.1

type HostedKnowledgeProposal struct {
	ID           string                   `json:"id"`
	CaseID       string                   `json:"caseId"`
	Kind         string                   `json:"kind"` // field-meaning | relationship | invariant | query | scenario
	Title        string                   `json:"title"`
	Statement    string                   `json:"statement"`
	EvidenceRefs []string                 `json:"evidenceRefs"`
	FindingRefs  []string                 `json:"findingRefs,omitempty"`
	ClaimStatus  string                   `json:"claimStatus"` // hypothesis | confirmed
	Status       string                   `json:"status"`      // draft | reviewed | rejected
	Version      int64                    `json:"version"`
	CreatedAt    time.Time                `json:"createdAt"`
	CreatedBy    string                   `json:"createdBy"`
	ReviewedAt   time.Time                `json:"reviewedAt,omitempty"`
	ReviewedBy   string                   `json:"reviewedBy,omitempty"`
	ReviewNote   string                   `json:"reviewNote,omitempty"`
	Handoffs     []HostedKnowledgeHandoff `json:"handoffs,omitempty"`
}

HostedKnowledgeProposal is a private, reviewable discovery. An exported proposal is a typed portable record; no route writes it to a public MeaningGraph or ModelSpec registry without that registry's own authority.

type HostedKnowledgeResponse added in v0.29.1

type HostedKnowledgeResponse struct {
	Proposal *HostedKnowledgeProposal `json:"proposal,omitempty"`
	Export   *HostedKnowledgeHandoff  `json:"export,omitempty"`
	Receipt  string                   `json:"receipt"`
}

type HostedKnowledgeTarget added in v0.29.1

type HostedKnowledgeTarget struct {
	System           string `json:"system"` // meaninggraph | modelspec
	Repository       string `json:"repository"`
	ResourceID       string `json:"resourceId"`
	ExpectedRevision string `json:"expectedRevision"`
}

A handoff identifies a specific external resource and the revision the reviewer expects to change. It is a private portable record, not a write to MeaningGraph or ModelSpec and not a claim that either accepted the proposal.

type HostedOVDBExecutor added in v0.29.1

type HostedOVDBExecutor struct {
	Origin         string
	AllowedSources map[string]map[string]bool
	Client         *http.Client
	Now            func() time.Time
}

HostedOVDBExecutor executes admitted, saved structured TugQL against one operator-pinned OVDB origin. AllowedSources is an operator-owned database/collection map; query federation metadata cannot expand it. A production host must provide the public origin and source list it has actually published. Stored text-form TugQL is readable but unsupported by this structured-only adapter.

func (*HostedOVDBExecutor) ExecuteSavedQuery added in v0.29.1

type HostedProjectEnvironmentBinding added in v0.29.1

type HostedProjectEnvironmentBinding struct {
	// NativeSources is an explicit host declaration, not a client grant.
	// Only the configured fixed shipping profile is supported.
	NativeSources []string
	SpaceID       string
	ProjectID     string
	Name          string
	Sources       []HostedProjectSourceBinding
}

type HostedProjectEnvironmentProvider added in v0.29.1

type HostedProjectEnvironmentProvider interface {
	ReadProjectEnvironments(context.Context, dal.ReadTransaction, string, string) ([]HostedProjectEnvironmentBinding, error)
}

type HostedProjectIncident added in v0.59.1

type HostedProjectIncident struct {
	Incident incidents.IncidentView `json:"incident"`
}

type HostedProjectIncidents added in v0.59.1

type HostedProjectIncidents struct {
	Incidents []incidents.IncidentView `json:"incidents"`
}

type HostedProjectLifecycleOptions added in v0.60.0

type HostedProjectLifecycleOptions struct {
	Project  *SharedProjectService
	Sessions sessioncontext.MountedDatabase
	// Optional existing owning service. Its configured source provider is reused
	// by immutable-body inventory and definition admission in the returned copies.
	Detective *DetectiveService
}

type HostedProjectLifecycleServices added in v0.60.0

type HostedProjectLifecycleServices struct {
	Project   *SharedProjectService
	Lifecycle *SharedProjectLifecycleStore
	Detective *DetectiveService
}

The host constructs every owning route service from Project BEFORE accepting requests. This returns a configured copy and never changes an existing service. All registered writers and the session mount must use this exact host DB. Drain binaries predating admission fences before enabling lifecycle routes.

func NewHostedProjectLifecycleServices added in v0.60.0

func NewHostedProjectLifecycleServices(options HostedProjectLifecycleOptions) (HostedProjectLifecycleServices, error)

Only NEW projects created through the configured service can acquire a birth epoch. Existing/unregistered sources cannot be certified by this constructor.

type HostedProjectSourceBinding added in v0.29.1

type HostedProjectSourceBinding struct {
	Origin     string
	Database   string
	Collection string
}

The owning host supplies admitted logical environments and physical source mappings for paid Space projects. A missing, foreign, or ambiguous mapping never becomes a runnable environment. The executor separately enforces its operator-owned origin and collection allowlist.

type HostedQueryRunRequest added in v0.29.1

type HostedQueryRunRequest struct {
	Comparison  *datatug.QueryComparison                `json:"comparison,omitempty"`
	Evidence    *models4datatug.ShippingEvidenceRequest `json:"evidence,omitempty"`
	Storage     string                                  `json:"storage"`
	SpaceID     string                                  `json:"spaceID"`
	Project     string                                  `json:"project"`
	OperationID string                                  `json:"operationId"`
	QueryID     string                                  `json:"queryId"`
	Environment string                                  `json:"environment"`
	Inputs      map[string]apicontract.TypedValueOrSet  `json:"inputs,omitempty"`
}

type HostedQueryRunResponse added in v0.29.1

type HostedQueryRunResponse struct {
	Comparison          *models4datatug.ShippingComparisonAdmission `json:"comparison,omitempty"`
	SourcePin           *models4datatug.ShippingSourcePin           `json:"sourcePin,omitempty"`
	AttachedIncidentRef string                                      `json:"attachedIncidentRef,omitempty"`
	AppliedManifestRef  string                                      `json:"appliedManifestRef,omitempty"`
	Result              apicontract.Result                          `json:"result"`
	QueryRevision       string                                      `json:"queryRevision"`
	ResultFingerprint   string                                      `json:"resultFingerprint"`
	Receipt             string                                      `json:"receipt"`
}

type HostedSavedQueryExecution added in v0.29.1

type HostedSavedQueryExecution struct {
	ActorID, SpaceID, ProjectID, QueryID, Revision, Environment string
	SourcePin                                                   *models4datatug.ShippingSourcePin
	QueryJSON                                                   []byte
	Inputs                                                      map[string]apicontract.TypedValueOrSet
	// contains filtered or unexported fields
}

type HostedSavedQueryResult added in v0.29.1

type HostedSavedQueryResult struct {
	ResultJSON  []byte
	Revision    string
	Fingerprint string
}

type HostedSessionDetectiveOptions added in v0.30.0

type HostedSessionDetectiveOptions struct {
	Mounted          sessioncontext.MountedDatabase
	Detective        *DetectiveService
	ActiveAccount    func(context.Context, string) error
	AuthorizeContent func(context.Context, string, SessionOperationScope, *sessioncontext.Scope) error
	Enabled          bool
}

HostedSessionDetectiveOptions is supplied by trusted composition only. Enabled remains false until local and hosted execution/recovery are proved.

type HostedSessionDetectiveService added in v0.30.0

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

func NewHostedSessionDetectiveService added in v0.30.0

func NewHostedSessionDetectiveService(options HostedSessionDetectiveOptions) (*HostedSessionDetectiveService, error)

func (*HostedSessionDetectiveService) AuthoringService added in v0.59.1

AuthoringService uses the same native owner/repository as evidence capture, but gives HTTP authoring no executor authority. Content is reauthorized by the configured current-authority delegate on every operation.

func (*HostedSessionDetectiveService) Dispatch added in v0.30.0

func (*HostedSessionDetectiveService) Enabled added in v0.30.0

func (s *HostedSessionDetectiveService) Enabled() bool

func (*HostedSessionDetectiveService) ProviderAvailable added in v0.30.0

func (s *HostedSessionDetectiveService) ProviderAvailable() bool

func (*HostedSessionDetectiveService) RedactAcceptedPins added in v0.30.0

func (s *HostedSessionDetectiveService) RedactAcceptedPins(ctx context.Context, actor string, scope SessionOperationScope, operation, deleteOperation, cursor string, limit int) (string, error)

RedactAcceptedPins is a bounded trusted deletion worker operation. It resumes with Core's opaque cursor and never deletes separately owned Case evidence or produced native result receipts. A first page still requires content-delete authorization; active account ownership alone cannot initiate deletion.

func (*HostedSessionDetectiveService) RequireActiveAccount added in v0.30.0

func (s *HostedSessionDetectiveService) RequireActiveAccount(ctx context.Context, actor string) error

func (*HostedSessionDetectiveService) Status added in v0.30.0

type IDGenerator

type IDGenerator interface {
	// NewID returns the id of a new record.
	NewID(ctx context.Context) (string, error)
}

IDGenerator is a PORT: extension implementation packages stay outside this module. Published contracts and their DTO aliases may be reused; behavior crosses a small interface defined here and is satisfied by an adapter in the host composition root (datatug-cloud, internal/datatug/adapters.go). Domain tests fake the port — see facade_test.go's fakeIDGenerator.

type InitialProtectedProjectBasis added in v0.11.0

type InitialProtectedProjectBasis struct {
	Digest    string
	Allocated int64
}

InitialProtectedProjectBasis must be issued by a trusted complete-inventory verifier. It includes existing allocations across ALL Spaces for this payer. It must also independently bind actor to the verified context and may only read. No runtime reset or missing-record zero inference is provided. An imported count requires the verifier to prove matching immutable allocation records.

type NativeBusinessActivityBindingReader added in v0.23.0

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

NativeBusinessActivityBindingReader composes DataTug project authorization with Paymentus' current paid-service and immutable original-start readers. Every authority read is confined to the caller's transaction.

func NewNativeBusinessActivityBindingReader added in v0.23.0

func NewNativeBusinessActivityBindingReader(options BusinessActivityBindingReaderOptions) (*NativeBusinessActivityBindingReader, error)

func (*NativeBusinessActivityBindingReader) ReadCurrentBusinessActivityBinding added in v0.23.0

func (r *NativeBusinessActivityBindingReader) ReadCurrentBusinessActivityBinding(
	ctx context.Context,
	tx dal.ReadTransaction,
	actorID, spaceID, projectID string,
	at time.Time,
) (BusinessActivityBinding, error)

type NativeBusinessUsageCloseTermsReader added in v0.23.1

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

NativeBusinessUsageCloseTermsReader composes the existing native paid-lot reader with the immutable Business anchor and exact open usage period. Empty paid-capacity basis is the only supported close today; it does not choose an unapproved lot-window rule.

func (*NativeBusinessUsageCloseTermsReader) ReadBusinessUsageCloseTerms added in v0.23.1

type NativeBusinessUsagePeriodAuthority added in v0.23.1

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

NativeBusinessUsagePeriodAuthority combines current paid access for Open, the immutable original start for both Open and historical Close, and the accepted-receipt completeness checkpoint. It never grants new query access.

func NewNativeBusinessUsagePeriodAuthority added in v0.23.1

func NewNativeBusinessUsagePeriodAuthority(options BusinessUsagePeriodAuthorityOptions) (*NativeBusinessUsagePeriodAuthority, error)

func (*NativeBusinessUsagePeriodAuthority) VerifyUsage added in v0.23.1

type NativePostmortemPromoter added in v0.59.1

type NativePostmortemPromoter struct {
	Detective *DetectiveService
	Watch     *CloudWatchService
}

func NewNativePostmortemPromoter added in v0.59.1

func NewNativePostmortemPromoter(d *DetectiveService, w *CloudWatchService) *NativePostmortemPromoter

func (*NativePostmortemPromoter) Lookup added in v0.59.1

func (p *NativePostmortemPromoter) Lookup(ctx context.Context, actor string, item m.WorkItem, proposal m.PostmortemRecommendation, operation string) (m.WorkTarget, string, bool, error)

Lookup reads native immutable operation evidence. It never invokes Save, so reconciling an interrupted effect cannot create a now-rejected recommendation.

func (*NativePostmortemPromoter) Save added in v0.59.1

func (p *NativePostmortemPromoter) Save(ctx context.Context, actor string, item m.WorkItem, proposal m.PostmortemRecommendation, operation string) (m.WorkTarget, string, error)

type NativeProjectContactRoleTarget added in v0.26.0

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

NativeProjectContactRoleTarget validates additions against the current full Contactus record. Stale assignments may only be removed as a strict subset; the linkage policy separately verifies both reciprocal records in its caller transaction before calling this port.

func NewNativeProjectContactRoleTarget added in v0.26.0

func NewNativeProjectContactRoleTarget(contacts CurrentProjectContactPort, actors BusinessActivityActorVerifier) (*NativeProjectContactRoleTarget, error)

func (*NativeProjectContactRoleTarget) AuthorizeProjectContactRoleChange added in v0.26.0

type NativeProjectRoleManager added in v0.26.0

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

NativeProjectRoleManager authorizes project assignment changes from the current versioned role catalog and a server-verified actor identity.

func NewNativeProjectRoleManager added in v0.26.0

func NewNativeProjectRoleManager(actors BusinessActivityActorVerifier) (*NativeProjectRoleManager, error)

func (*NativeProjectRoleManager) AuthorizeProjectRoleMutation added in v0.26.0

func (a *NativeProjectRoleManager) AuthorizeProjectRoleMutation(ctx context.Context, tx dal.ReadTransaction, request ProjectRoleMutationAuthorization) error

type OperationalProjectVisibilityOptions added in v0.61.1

type OperationalProjectVisibilityOptions struct {
	Project   *SharedProjectService
	Detective *DetectiveService
	Work      *WorkService
	Watch     *CloudWatchService
	Mounted   sessioncontext.MountedDatabase
	GitHub    ProjectVisibilityInventory
}

OperationalProjectVisibilityOptions supplies owning runtime services. Nil services mean that provider is not mounted; they never imply a source grant.

type PaidMonthAllocator added in v0.5.0

type PaidMonthAllocator interface {
	AllocatePaidMonths(PlanPayment, string) (map[string]int64, error)
}

PaidMonthAllocator is a narrow host translation to core's existing AllocatePaidMonths. The writer owns deduplication and aggregation.

type PaidProjectLinkageOptions added in v0.12.0

type PaidProjectLinkageOptions struct {
	Paid     PaidSharedProjectOptions
	Business *BusinessProjectAccessVerifier
	Roles    ProjectRoleCatalog
	Contacts CurrentProjectContactPort
	Manager  ProjectRoleManagerPort
	Targets  ProjectContactRoleTargetPort
	Now      func() time.Time
}

type PaidProjectLinkagePolicy added in v0.12.0

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

PaidProjectLinkagePolicy is the DataTug implementation of Core's generic transaction policy. Host activation MUST declare datatug/projects protected before binding generic routes or creating records, then bind this policy for BOTH linkage directions. A UI role list never supplies authority.

func NewPaidProjectLinkagePolicy added in v0.12.0

func NewPaidProjectLinkagePolicy(o PaidProjectLinkageOptions) (*PaidProjectLinkagePolicy, error)

func (*PaidProjectLinkagePolicy) AuthorizeRelationshipMutation added in v0.12.0

type PaidProjectOwnerLinksOptions added in v0.12.0

type PaidProjectOwnerLinksOptions struct {
	Roles    ProjectRoleCatalog
	Owner    ProjectOwnerContactPort
	Contacts CurrentProjectContactPort
}

type PaidSharedProjectOptions added in v0.11.0

type PaidSharedProjectOptions struct {
	Version, Mode, Product string
	// EnableQueryEditCandidates is an explicit host opt-in. Existing paid
	// project routes keep their current behavior until private rules and the
	// observe-only source journey are reviewed and wired by the host.
	EnableQueryEditCandidates bool
	ContactLinks              *PaidProjectOwnerLinksOptions
	Config                    PlanConfig
	Directory                 PersonalAccountDirectory
	Personal                  PersonalPlanOwnerPort
	Owner                     interface {
		ReadOwner(context.Context, dal.ReadTransaction, string, string, string) (PlanOwnerFence, error)
	}
}

PaidSharedProjectOptions are reviewed server configuration, never request fields. This slice supports current personal Pro only. Business grant/AI policy is not inferred from missing limits or historical tier fixtures. Product mutation is LIVE-only: TEST checkout projections never create real shared projects. Future TEST product isolation needs a separate ref namespace.

type PendingGitHubProjectSetup added in v0.59.1

type PendingGitHubProjectSetup struct {
	Source         *models4datatug.GitHubProjectCloneSource `json:"source,omitempty"`
	OperationID    string                                   `json:"operationID"`
	Status         string                                   `json:"status"`
	SpaceID        string                                   `json:"spaceID"`
	ProjectID      string                                   `json:"projectID"`
	Title          string                                   `json:"title"`
	RepositoryID   int64                                    `json:"repositoryID"`
	Owner          string                                   `json:"owner"`
	Name           string                                   `json:"name"`
	Folder         string                                   `json:"folder"`
	Branch         string                                   `json:"branch"`
	CIEnabled      bool                                     `json:"ciEnabled"`
	BillingIntent  SharedProjectBillingIntent               `json:"billingIntent,omitempty"`
	ExpectedHead   string                                   `json:"expectedHead"`
	TemplateID     string                                   `json:"templateID"`
	TemplateCommit string                                   `json:"templateCommit"`
	SetupPR        *models4datatug.GitHubProjectSetupPR     `json:"setupPR,omitempty"`
}

PendingGitHubProjectSetup is safe recovery metadata for the authenticated actor. It intentionally excludes the server-side setup file proof and all credential/state material.

type PendingGitHubProjectSetups added in v0.59.1

type PendingGitHubProjectSetups struct {
	Setups    []PendingGitHubProjectSetup `json:"setups"`
	Truncated bool                        `json:"truncated"`
}

type PersonalAccount added in v0.4.0

type PersonalAccount struct{ ID, Title string }

PersonalAccount is an ownership assertion made by the host directory.

func ResolvePersonalPayer added in v0.4.0

func ResolvePersonalPayer(ctx context.Context, callerID, accountHint string, directory PersonalAccountDirectory) (PersonalAccount, error)

PersonalPayer is shared by plan reads and the later AI adapter. A foreign account hint is refused before any plan or usage read for that hint.

type PersonalAccountDirectory added in v0.4.0

type PersonalAccountDirectory interface {
	PersonalAccount(context.Context, string) (PersonalAccount, error)
	PersonalAccountTransactionReader
}

PersonalAccountDirectory must prove ownership and provision the personal account through the host. This domain never infers an account from a user ID.

It also reads an existing account inside a caller's transaction: a host directory that cannot would silently disable every gate that runs in one (cloud project sharing, a joined Pro member's reads), so the requirement is part of the port and a host lacking it does not compile.

type PersonalAccountTransactionReader added in v0.60.6

type PersonalAccountTransactionReader interface {
	ReadPersonalAccount(ctx context.Context, tx dal.ReadTransaction, userID string) (PersonalAccount, error)
}

PersonalAccountTransactionReader reads a user's existing personal account inside the caller's transaction and never creates one. A gate that already runs in a transaction needs it: PersonalAccount may open a transaction of its own, which Firestore refuses to nest.

type PersonalPlanOwnerPort added in v0.5.0

type PersonalPlanOwnerPort interface {
	VerifyPersonalOwner(context.Context, dal.ReadTransaction, string, string) error
}

type PersonalPlanService added in v0.4.0

type PersonalPlanService struct {
	Directory PersonalAccountDirectory
	Plans     PlanReader
	Usage     UsageReader
	Admission AdmissionReader
	// CallerAdmission takes precedence when bound. Admission remains supported
	// for existing consumers; a new host must bind this caller-aware port.
	CallerAdmission CallerAdmissionReader
	Config          PlanConfigReader
	Clock           PlanClock
	FirstMonth      FirstAdmittedMonthReader
}

PersonalPlanService composes ports without depending on transport or store.

func (PersonalPlanService) Read added in v0.4.0

func (s PersonalPlanService) Read(ctx context.Context, callerID, accountHint, _ string) (PlanResponse, error)

type PinnedDemoConnections added in v0.60.6

type PinnedDemoConnections struct {
	Format  json.RawMessage
	Entries map[string]json.RawMessage
}

PinnedDemoConnections is the pinned demo-db.json: its top-level format and every connection entry's exact bytes, keyed by entry id.

func ReadPinnedDemoConnections added in v0.60.6

func ReadPinnedDemoConnections() (PinnedDemoConnections, error)

ReadPinnedDemoConnections parses the verified embedded catalog once.

type PlanAI added in v0.4.0

type PlanAI struct {
	Unit     string      `json:"unit"`
	Enforced bool        `json:"enforced"`
	PeriodID string      `json:"periodId"`
	Used     int64       `json:"used"`
	Limit    int64       `json:"limit"`
	Left     int64       `json:"left"`
	ResetsAt time.Time   `json:"resetsAt"`
	Today    PlanToday   `json:"today"`
	Blocked  *string     `json:"blocked"`
	Models   []PlanModel `json:"models"`
}

type PlanAccount added in v0.4.0

type PlanAccount struct {
	AccountID string `json:"accountId"`
	Kind      string `json:"kind"`
	Title     string `json:"title"`
	Plan      string `json:"plan"`
	Role      string `json:"role"`
	Pays      bool   `json:"pays"`
}

type PlanApplyOutcome added in v0.5.0

type PlanApplyOutcome string
const (
	PlanApplied    PlanApplyOutcome = "applied"
	PlanIdempotent PlanApplyOutcome = "idempotent"
	PlanObsolete   PlanApplyOutcome = "obsolete"
)

type PlanClock added in v0.4.0

type PlanClock interface{ Now() time.Time }

type PlanConfig added in v0.4.0

type PlanConfig struct {
	FreeFirstMonthLimits models4datatug.PlanLimits
	FreeLaterMonthLimits models4datatug.PlanLimits
	ProLimits            models4datatug.PlanLimits
	FreeModels           []PlanModel
	ProModels            []PlanModel
	DailyLimit           int64
	// Zero grace stops paid access exactly at PaidUntil. Positive values are
	// explicit legacy policy; do not configure them for strict paid-through plans.
	ActiveGrace  time.Duration
	PastDueGrace time.Duration
	Enforced     bool
	UpgradeURL   string
	ManageURL    string
	SupportEmail string
}

PlanConfig is supplied by the host, rather than encoded in plan policy. The two Free grants differ by the month of the first admitted question, which is independently read from the meter's server-only marker.

type PlanConfigReader added in v0.4.0

type PlanConfigReader interface {
	ReadPlanConfig(context.Context, string, time.Time) (PlanConfig, error)
}

PlanConfigReader receives the proved account and the one UTC instant sampled for this response; settings can change at runtime without implicit context.

type PlanEffectAuthority added in v0.5.0

type PlanEffectAuthority string
const (
	PlanEffectCurrent  PlanEffectAuthority = "current"
	PlanEffectObsolete PlanEffectAuthority = "obsolete"
	PlanEffectUnproved PlanEffectAuthority = "unproved"
)

type PlanEffectGrants added in v0.5.0

type PlanEffectGrants struct {
	Contributors, ProjectContributors, AIQuestions int64
	AIPaysFor                                      string
	ProtectedProjects                              *int64 `json:"protectedProjects,omitempty"`
	ProtectedProjectUsers                          *int64 `json:"protectedProjectUsers,omitempty"`
}

PlanEffectGrants mirrors the values frozen by the payment effect. The protected pair is optional only for accepted legacy effects; complete Pro limits still require a separately versioned server configuration.

type PlanEffectOwnerPort added in v0.5.0

PlanEffectOwnerPort is bound to paymentus's transaction-aware owner reader. Every method receives the same DAL transaction as the product writer.

type PlanFacts added in v0.4.0

type PlanFacts struct {
	AccountKind               string                     `json:"accountKind"`
	Tier                      string                     `json:"tier"`
	Period                    string                     `json:"period"`
	ProviderStatus            string                     `json:"providerStatus"`
	PaidUntil                 *time.Time                 `json:"paidUntil,omitempty"`
	EndsAt                    *time.Time                 `json:"endsAt,omitempty"`
	LastInvoiceRefundedInFull bool                       `json:"lastInvoiceRefundedInFull"`
	TerminalFullRefund        bool                       `json:"terminalFullRefund,omitempty"`
	RefundedAt                *time.Time                 `json:"refundedAt,omitempty"`
	FirstPaidAt               *time.Time                 `json:"firstPaidAt,omitempty"`
	Founding                  bool                       `json:"founding"`
	Grants                    *models4datatug.PlanLimits `json:"grants,omitempty"`
}

PlanFacts are plain, provider-independent inputs to the plan-state mapping.

type PlanModel added in v0.4.0

type PlanModel struct {
	ID      string `json:"id"`
	Class   string `json:"class"`
	Weight  int64  `json:"weight"`
	Default bool   `json:"default"`
}

type PlanMoneyFence added in v0.5.0

type PlanMoneyFence struct {
	IngestEpoch, ReconciledEpoch int64
	Unresolved                   bool
}

type PlanOwnerFence added in v0.5.0

type PlanOwnerFence struct {
	Mode, Family, AccountID, OwnerSubscriptionID string
	OwnerGeneration, SubscriptionRevision        int64
}

PlanOwnerFence is copied from the private payment owner tuple by the host.

type PlanPayment added in v0.5.0

type PlanPayment struct {
	Mode, Provider, InvoiceID, PaymentID, SubscriptionID, AccountID string
	Currency                                                        string
	ReceivedCents                                                   int64
	CashConfirmed, RefundsKnown, DisputeResolved                    bool
	Lines                                                           []PlanPaymentLine
	Refunds                                                         []PlanRefund
}

type PlanPaymentLine added in v0.5.0

type PlanPaymentLine struct {
	ID, ProductFamily           string
	StartUTC, EndUTC            time.Time
	CashCents, RetainedTaxCents int64
	RetainedTaxKnown            bool
}

type PlanReader added in v0.4.0

type PlanReader interface {
	ReadCurrentPlan(context.Context, string) (*models4datatug.PlanRecord, error)
}

PlanReader reads only plan/current; an unreadable record falls toward Free.

type PlanRefund added in v0.5.0

type PlanRefund struct {
	ID               string
	GrossCents       int64
	LineGrossCents   map[string]int64
	AttributionKnown bool
}

type PlanResponse added in v0.4.0

type PlanResponse struct {
	V             int                       `json:"v"`
	Payer         string                    `json:"payer"`
	AccountID     string                    `json:"accountId"`
	AccountTitle  string                    `json:"accountTitle"`
	Role          string                    `json:"role"`
	Plan          string                    `json:"plan"`
	EffectivePlan string                    `json:"effectivePlan"`
	Status        string                    `json:"status"`
	Period        string                    `json:"period"`
	PaidUntil     *time.Time                `json:"paidUntil,omitempty"`
	Founding      bool                      `json:"founding"`
	Limits        models4datatug.PlanLimits `json:"limits"`
	AI            PlanAI                    `json:"ai"`
	OwnKeyWorks   bool                      `json:"ownKeyWorks"`
	CanUpgrade    bool                      `json:"canUpgrade"`
	UpgradeURL    string                    `json:"upgradeUrl"`
	ManageURL     string                    `json:"manageUrl,omitempty"`
	SupportEmail  string                    `json:"supportEmail,omitempty"`
	Accounts      []PlanAccount             `json:"accounts"`
}

type PlanStateResult added in v0.4.0

type PlanStateResult struct {
	Outcome string                     `json:"outcome"`
	Reason  string                     `json:"reason,omitempty"`
	Record  *models4datatug.PlanRecord `json:"record,omitempty"`
}

PlanStateResult names a write, leave, or refusal. The writer retains the previous aiExtraQuestions and stamps updatedAt outside this pure function.

func PlanStateFor added in v0.4.0

func PlanStateFor(f PlanFacts) PlanStateResult

PlanStateFor follows the ordered precedence of the version-1 state table. This slice grants paid access only to personal Pro; ended states remain mappable even when a provider reports a now-unsupported tier.

type PlanToday added in v0.4.0

type PlanToday struct {
	Used  int64 `json:"used"`
	Limit int64 `json:"limit"`
}

type PostmortemEmailMessage added in v0.59.1

type PostmortemEmailMessage struct{ ID, To, Subject, Body string }

type PostmortemEmailSender added in v0.59.1

type PostmortemEmailSender interface {
	Send(context.Context, PostmortemEmailMessage) (string, error)
}

type PostmortemPromoter added in v0.59.1

type PostmortemPromoter interface {
	Save(context.Context, string, m.WorkItem, m.PostmortemRecommendation, string) (m.WorkTarget, string, error)
}

type PostmortemService added in v0.59.1

type PostmortemService struct {
	Detective     *DetectiveService
	Work          *WorkService
	Email         PostmortemEmailSender
	PublicBaseURL string
	Promote       PostmortemPromoter
}

func (*PostmortemService) Action added in v0.59.1

func (*PostmortemService) Evidence added in v0.59.1

func (s *PostmortemService) Evidence(ctx context.Context, actor, space, project, id string) ([]m.PostmortemEvidence, error)

func (*PostmortemService) Generate added in v0.59.1

func (*PostmortemService) Get added in v0.59.1

func (s *PostmortemService) Get(ctx context.Context, actor, space, project, id string) (m.PostmortemDetail, error)

func (*PostmortemService) Revisions added in v0.59.1

func (s *PostmortemService) Revisions(ctx context.Context, actor, space, project, id string) ([]m.PostmortemReport, error)

func (*PostmortemService) Shared added in v0.59.1

type PreparedCloudProjectSpace added in v0.60.6

type PreparedCloudProjectSpace struct {
	SpaceID string
	// OwnerContact is the creator's new Space contact.
	OwnerContact contract4linkage.RelationshipEntityRef
	// OwnerGraph is the new contact's linkage graph; Apply writes it as is.
	OwnerGraph *contract4linkage.WithRelatedAndIDs
	Apply      func(ctx context.Context, tx dal.ReadwriteTransaction) error
}

PreparedCloudProjectSpace is a planned, unwritten Space creation.

type PreparedProjectVisibilityRestore added in v0.61.1

type PreparedProjectVisibilityRestore struct {
	Target datatug.ProjectObjectUsage
	Apply  func() error
}

type PreparedSharedProjectCreate added in v0.10.0

type PreparedSharedProjectCreate struct {
	Binding   SharedProjectCreateBinding
	IssuedAt  time.Time
	Validator SharedProjectCreateTransactionAuthority
}

PreparedSharedProjectCreate is server-to-server only. Its validator privately owns the opaque Core reservation; that reservation never enters this DTO or a public response. The domain checks Binding and captures its validation clock AFTER preparation, before entering any retryable callback.

type ProBusinessSharedProjectOptions added in v0.21.0

type ProBusinessSharedProjectOptions struct {
	Pro      PaidSharedProjectOptions
	Business BusinessSharedProjectOptions
}

ProBusinessSharedProjectOptions configures both plans on one route service. Billing intent selects only which authority to prove; it never grants one.

type ProLimitsResolver added in v0.5.0

type ProLimitsResolver interface {
	ResolveProLimits(string, PlanEffectGrants) (ProLimitsSnapshot, error)
}

type ProLimitsSnapshot added in v0.5.0

type ProLimitsSnapshot struct {
	Version            string
	ProjectGuestsKnown bool
	Limits             models4datatug.PlanLimits
}

type ProjectAIEligibility added in v0.16.0

type ProjectAIEligibility struct {
	AIAllowed bool   `json:"aiAllowed"`
	Reason    string `json:"reason,omitempty"`
}

ProjectAIEligibility is a minimal, server-computed projection. Actor membership and sponsor entitlement are proved separately before it is returned; no payer or subscription identifiers leave this package.

type ProjectConnectionCatalog added in v0.60.6

type ProjectConnectionCatalog struct {
	Own      bool
	Revision int64
	Extra    map[string]json.RawMessage
	Format   json.RawMessage
	Entries  []json.RawMessage
}

ProjectConnectionCatalog is a project's own connection catalog. Own is false for a legacy Space project, which keeps the pinned demo catalog.

func (ProjectConnectionCatalog) MarshalJSON added in v0.60.6

func (c ProjectConnectionCatalog) MarshalJSON() ([]byte, error)

MarshalJSON writes {format, connections, connectionsRevision} with every entry's stored bytes. connectionsRevision repeats the ETag in the body, so a cross-origin browser can send it as save_connection's ifMatch.

type ProjectConnectionSaveCommand added in v0.60.6

type ProjectConnectionSaveCommand struct {
	ActorID, SpaceID, ProjectID, OperationID, IfMatch, DemoDB string
}

ProjectConnectionSaveCommand is save_connection's command.

func (ProjectConnectionSaveCommand) Validate added in v0.60.6

func (c ProjectConnectionSaveCommand) Validate() error

type ProjectContactRoleChange added in v0.12.0

type ProjectContactRoleChange struct {
	Contact          ProjectContactState
	Before, Proposed []string
}

type ProjectContactRoleTargetPort added in v0.12.0

type ProjectContactRoleTargetPort interface {
	AuthorizeProjectContactRoleChange(context.Context, dal.ReadTransaction, ProjectRoleMutationAuthorization, ProjectContactRoleChange) error
}

Target authority decides eligibility of adds/removals, including deliberate stale-contact cleanup; counting a stale link does not approve assigning one.

type ProjectContactState added in v0.12.0

type ProjectContactState struct {
	Ref            contract4linkage.RelationshipEntityRef
	Exists, Active bool
	UserID         string
	Title          string // Current project contact display name; never authorization evidence.
}

ProjectContactState comes from the current full contact record in the supplied transaction, never a cached active-contact brief. Missing/inactive contacts still count while linked. UserID is used for authentication only. Being a Space member is not a requirement for an assigned project contact.

type ProjectEntityDefinition added in v0.61.1

type ProjectEntityDefinition struct {
	Entity   json.RawMessage
	Revision string
}

ProjectEntityDefinition preserves the complete native declaration for HTTP readers while typed domain resolvers keep their existing Entity contract.

type ProjectLifecycleInventory added in v0.60.0

type ProjectLifecycleInventory interface {
	ReadProjectLifecycleInventory(context.Context, dal.ReadTransaction, datatug.ProjectLifecycleScope) (ProjectLifecycleInventoryView, error)
}

ProjectLifecycleInventory is supplied only by the owning server composition. It must inventory every definition, running acceptance/reservation and retained history source, across actors/environments/coordinators, through this SAME transaction. Unknown, external, unpaged or unsupported sources leave Complete false. All reference-bearing writers must commit PrepareProjectReferenceWrite with their write before this port can report Complete. Query/board scans alone are insufficient. Access is re-evaluated in the transaction for this actor and permission context, while the graph itself always covers the whole project.

The store adds permanent identity-only lifecycle audit indexes without outgoing use references; the port must not duplicate reserved project-lifecycle/* IDs. There is deliberately no client endpoint for asserting coverage/completeness.

type ProjectLifecycleInventoryView added in v0.60.0

type ProjectLifecycleInventoryView struct {
	Snapshot datatug.ProjectUsageSnapshot
	Access   map[datatug.ProjectObjectRef]ProjectLifecyclePermissions
}

type ProjectLifecyclePermissions added in v0.60.0

type ProjectLifecyclePermissions struct {
	CanRead   bool
	CanManage bool
}

type ProjectOwnerContactPort added in v0.12.0

type ProjectOwnerContactPort interface {
	ResolveProjectOwnerContact(context.Context, dal.ReadTransaction, SharedProjectCreateBinding) (contract4linkage.RelationshipEntityRef, error)
}

This port resolves an EXISTING contact in the original create transaction. It must independently bind the actor to the verified context, without writes, nested transactions, new contacts or automatic Space membership. The domain rechecks current status/UID and constructs only reciprocal linkage writes.

type ProjectRoleCatalog added in v0.12.0

type ProjectRoleCatalog struct {
	Version   string
	Roles     []string
	OwnerRole string
}

ProjectRoleCatalog is server configuration. This list approves role IDs only; it grants no operations or authority. The host's current role/permission ports separately authorize the operation. No public request may supply the list.

type ProjectRoleEvidence added in v0.12.0

type ProjectRoleEvidence struct {
	Contact ProjectContactState
	Roles   []string
}

type ProjectRoleManagerPort added in v0.12.0

type ProjectRoleManagerPort interface {
	AuthorizeProjectRoleMutation(context.Context, dal.ReadTransaction, ProjectRoleMutationAuthorization) error
}

Manager authority must independently bind ActorID to the authenticated context and authorize with CURRENT project roles and platform guards. Space role alone does not supply a project role. Multiple contacts for one UID are separate evidence: the port must not silently union their privileges.

type ProjectRoleMutationAuthorization added in v0.12.0

type ProjectRoleMutationAuthorization struct {
	ActorID       string
	Project       models4datatug.SharedProjectRef
	ActorContacts []ProjectRoleEvidence
	Changes       []ProjectContactRoleChange
}

type ProjectVisibilityInventory added in v0.61.1

type ProjectVisibilityInventory interface {
	ReadProjectVisibility(context.Context, dal.ReadTransaction, datatug.ProjectLifecycleScope) (ProjectVisibilityTargets, error)
}

ProjectVisibilityInventory enumerates current, readable definitions only. Each owning adapter rechecks its source ACL in the supplied transaction. It does not assert retained-reference completeness or grant deletion.

func NewOperationalProjectVisibilityInventory added in v0.61.1

func NewOperationalProjectVisibilityInventory(options OperationalProjectVisibilityOptions) ProjectVisibilityInventory

type ProjectVisibilityInventoryFunc added in v0.61.1

func (ProjectVisibilityInventoryFunc) ReadProjectVisibility added in v0.61.1

type ProjectVisibilityLegacyRestorer added in v0.61.1

type ProjectVisibilityLegacyRestorer interface {
	PrepareProjectVisibilityRestore(context.Context, dal.ReadwriteTransaction, datatug.ProjectLifecycleScope, datatug.ProjectObjectRef) (PreparedProjectVisibilityRestore, error)
}

ProjectVisibilityLegacyRestorer reverses an existing source-owned archive through its owning transition/CAS. It may not grant source access or remove references. Preparation performs only authorized reads; Apply writes in the same transaction as the visibility receipt after every read has completed.

type ProjectVisibilityOptions added in v0.61.1

type ProjectVisibilityOptions struct {
	Project    *SharedProjectService
	GitHub     ProjectVisibilityInventory
	Additional ProjectVisibilityInventory
	// Delete remains optional and must retain its complete inventory/writer fences.
	Delete datatug.ProjectLifecycleStore
}

type ProjectVisibilityPreparer added in v0.61.1

type ProjectVisibilityPreparer interface {
	PrepareProjectVisibility(context.Context, datatug.ProjectLifecycleScope) (context.Context, error)
}

ProjectVisibilityPreparer obtains immutable provider inputs before opening the metadata transaction. Inventory must still recheck current DataTug authority in the supplied transaction and bind prepared inputs to the exact scope.

type ProjectVisibilityStore added in v0.61.1

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

func NewProjectVisibilityStore added in v0.61.1

func NewProjectVisibilityStore(options ProjectVisibilityOptions) (*ProjectVisibilityStore, error)

func (*ProjectVisibilityStore) ChangeProjectLifecycle added in v0.61.1

func (*ProjectVisibilityStore) ListProjectLifecycle added in v0.61.1

func (*ProjectVisibilityStore) ReviewProjectLifecycle added in v0.61.1

type ProjectVisibilityTargets added in v0.61.1

type ProjectVisibilityTargets struct {
	SpaceID, ProjectID, SourceRevision string
	Objects                            []datatug.ProjectObjectUsage
	Access                             map[datatug.ProjectObjectRef]ProjectLifecyclePermissions
}

type ProtectedProjectBasisAuthority added in v0.11.0

type ProtectedProjectBasisAuthority interface {
	VerifyInitialProtectedProjectBasisInTransaction(context.Context, dal.ReadwriteTransaction, string, string, string, string, InitialProtectedProjectBasis) error
}

type PurchaseReadiness added in v0.5.0

type PurchaseReadiness struct {
	DB       dal.DB
	Owner    PlanEffectOwnerPort
	Personal PersonalPlanOwnerPort
	Config   PlanConfigReader
	Clock    PlanClock
}

PurchaseReadiness verifies the current owner, the last actual Pro plan application, and its effective public plan in one read-only transaction.

func (PurchaseReadiness) ReadyForPurchase added in v0.5.0

func (r PurchaseReadiness) ReadyForPurchase(ctx context.Context, req PurchaseReadinessRequest) (bool, error)

type PurchaseReadinessRequest added in v0.5.0

type PurchaseReadinessRequest struct {
	BuyerID, Mode, SiteID, Family, AccountID    string
	SubscriptionID, QuoteKey, SessionID, PlanID string
}

PurchaseReadinessRequest contains only server-verified session and quote identity. The host translates the authenticated payment status request.

type QueryActivityContextResponse added in v0.20.0

type QueryActivityContextResponse struct {
	ContextID    string    `json:"contextID"`
	ExpiresAtUTC time.Time `json:"expiresAtUTC"`
}

type QueryActivityContextService added in v0.23.2

type QueryActivityContextService interface {
	IssueContext(context.Context, string, string, string) (QueryActivityContextResponse, error)
	Report(context.Context, string, string, QueryActivityReport) (QueryActivityReportResult, error)
}

type QueryActivityDrainRequest added in v0.20.0

type QueryActivityDrainRequest struct {
	Limit   int
	AfterID string
}

type QueryActivityDrainResult added in v0.20.0

type QueryActivityDrainResult struct {
	Scanned     int
	Delivered   int
	Failed      int
	NextAfterID string
	HasMore     bool
}

type QueryActivityReport added in v0.20.0

type QueryActivityReport struct {
	ContextID   string                           `json:"contextID"`
	OperationID string                           `json:"operationID"`
	Kind        models4datatug.QueryActivityKind `json:"kind"`
}

type QueryActivityReportResult added in v0.20.0

type QueryActivityReportResult struct {
	Accepted  bool   `json:"accepted"`
	Coalesced bool   `json:"coalesced"`
	ReceiptID string `json:"receiptID,omitempty"`
}

type QueryActivityService added in v0.20.0

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

QueryActivityService is an opt-in server intake and outbox. Its zero value and an unbound instance fail closed; browser attribution remains reported, first-party activity rather than proof of local execution.

func NewQueryActivityService added in v0.20.0

func (*QueryActivityService) Deliver added in v0.20.0

func (s *QueryActivityService) Deliver(ctx context.Context, spaceID, receiptID string) error

Deliver replays a committed pending receipt through the Paymentus ledger. Ledger admission and late-evidence retention happen outside the acceptance transaction. A crash before marking completion is safe to replay.

func (*QueryActivityService) Drain added in v0.20.0

Drain discovers pending work from the server-owned Space subtree, then delivers one bounded page. Failures remain pending and do not block later records in this page; the returned cursor advances so a worker can finish a full pass before resetting to the beginning and retrying earlier failures. Cancellation returns the partial result and the last completed scan position, leaving the current and remaining rows eligible for continuation. The cursor is only a scan position, never an identity or authorization fact.

func (*QueryActivityService) IssueContext added in v0.20.0

func (s *QueryActivityService) IssueContext(ctx context.Context, actorID, spaceID, projectID string) (QueryActivityContextResponse, error)

IssueContext returns a reusable actor/project/period context. Repeated loads and authority refreshes update its proof snapshot in place, so they do not create unbounded rows or change an accepted receipt's original evidence.

func (*QueryActivityService) Report added in v0.20.0

Report accepts only a context, an operation identity and a closed action enum. It rechecks authority in the same transaction that commits the receipt and pending delivery outbox.

type QueryActivityUsageAuthority added in v0.20.0

type QueryActivityUsageAuthority struct{}

QueryActivityUsageAuthority proves that Paymentus is admitting or retaining the exact activity backed by DataTug's immutable accepted receipt. It reads through the ledger or inbox caller's transaction; it has no database or mutable authority dependency of its own.

func NewQueryActivityUsageAuthority added in v0.20.0

func NewQueryActivityUsageAuthority() QueryActivityUsageAuthority

NewQueryActivityUsageAuthority constructs the receipt-only activity authority. UsageOpen, UsageClose and private late-evidence reads/scans need the separately composed period authority and are always denied here.

func (QueryActivityUsageAuthority) VerifyUsage added in v0.20.0

type RegisterGithubProjectRequest added in v0.2.0

type RegisterGithubProjectRequest struct {
	Org    string `json:"org"`
	Repo   string `json:"repo"`
	Folder string `json:"folder"`
	Title  string `json:"title"`
}

RegisterGithubProjectRequest describes a project that already exists in a GitHub repository.

func (RegisterGithubProjectRequest) Validate added in v0.2.0

func (v RegisterGithubProjectRequest) Validate() error

Validate validates the request.

type ServiceRefundProof added in v0.5.0

type ServiceRefundProof struct {
	Known                 bool
	HasPaidServiceInvoice bool
	InvoiceID             string
	ServiceStartUTC       time.Time
	ServiceEndUTC         time.Time
	RefundedInFull        bool
}

ServiceRefundProof describes the current owner's service plan, even when a historical subscription caused this revision. It is never inferred from the account-wide A+C cash snapshot. Unknown and absence are distinct.

type SessionDetectiveBinding added in v0.30.0

type SessionDetectiveBinding struct {
	InputName  string `json:"inputName"`
	EntryID    string `json:"entryId"`
	RevisionID string `json:"revisionId"`
}

type SessionDetectiveRequest added in v0.30.0

type SessionDetectiveRequest struct {
	OpID                 string                          `json:"operationId"`
	SessionID            string                          `json:"sessionId"`
	ExpectedVersion      int64                           `json:"expectedVersion"`
	ExpectedContextSetID string                          `json:"expectedContextSetId"`
	Scope                sessioncontext.Scope            `json:"scope"`
	CheckID              string                          `json:"checkId"`
	CaseID               string                          `json:"caseId,omitempty"`
	Attachments          []sessioncontext.EntryRef       `json:"attachments,omitempty"`
	Bindings             []SessionDetectiveBinding       `json:"bindings,omitempty"`
	Inputs               map[string]detective.InputValue `json:"inputs,omitempty"`
}

type SessionDetectiveStatus added in v0.30.0

type SessionDetectiveStatus struct {
	OperationID    string                                 `json:"operationId"`
	Status         sessioncontext.AcceptedDetectiveStatus `json:"status"`
	OperationScope SessionOperationScope                  `json:"operationScope"`
}

type SessionOperationScope added in v0.30.0

type SessionOperationScope struct {
	Storage     string `json:"storage"`
	Project     string `json:"project"`
	SpaceID     string `json:"spaceID,omitempty"`
	DatabaseID  string `json:"databaseId"`
	ProjectID   string `json:"projectId"`
	NamespaceID string `json:"namespaceId"`
}

SessionOperationScope is public routing metadata. It grants no content or execution authority. Storage/Project name the source; the remaining identity is the private operational namespace fixed by the mounted host.

func SessionOperationScopeFor added in v0.30.0

func SessionOperationScopeFor(mounted sessioncontext.MountedDatabase, storage, source, space, project string) (SessionOperationScope, error)

type SharedProjectActivationOptions added in v0.15.0

type SharedProjectActivationOptions struct {
	Activator      contract4spaceus.TransactionalRoleCapabilityActivator
	RequiredRoles  []string
	InventoryQuery dal.QueryExecutor
}

SharedProjectActivationOptions are trusted host composition. The Core activator never runs for passive reads or precommitted reservations.

type SharedProjectBillingIntent added in v0.21.0

type SharedProjectBillingIntent string

SharedProjectBillingIntent is only a user's plan choice. It grants no access: the service still verifies current Pro or Business authority.

const (
	BillingIntentPersonalPro   SharedProjectBillingIntent = "personal_pro"
	BillingIntentSpaceBusiness SharedProjectBillingIntent = "space_business"
)

func (SharedProjectBillingIntent) Validate added in v0.21.0

func (i SharedProjectBillingIntent) Validate() error

type SharedProjectCreateAuthority added in v0.10.0

type SharedProjectCreateAuthority interface {
	PrepareSharedProjectCreate(context.Context, SharedProjectCreateBinding) (PreparedSharedProjectCreate, error)
}

SharedProjectCreateAuthority is supplied by the host using released Core Space contracts: existing DataTug capability, current ordinary active Space, and server-configured content-management roles. It must not enable a module. Core reservation labels have a narrower grammar than client command IDs: the adapter must derive a server-owned lowercase command digest (<=64 chars) and purpose/stage labels, not pass arbitrary client CommandID through Core.

type SharedProjectCreateBinding added in v0.10.0

type SharedProjectCreateBinding struct {
	ActorID, SpaceID, CommandID, RequestDigest string
	// Paid binding is server-resolved. Legacy ownership-only commands leave it empty.
	PayerID, Mode, Product string
}

SharedProjectCreateBinding contains only immutable values. ActorID must come from the verified request context, never an HTTP body. A trusted adapter must independently bind it to that context when preparing Space authority.

type SharedProjectCreateCommand added in v0.10.0

type SharedProjectCreateCommand struct {
	ActorID, SpaceID, CommandID, Title string
	BillingIntent                      SharedProjectBillingIntent
}

func (SharedProjectCreateCommand) Validate added in v0.10.0

func (c SharedProjectCreateCommand) Validate() error

type SharedProjectCreateTransactionAuthority added in v0.10.0

type SharedProjectCreateTransactionAuthority interface {
	// ValidateSharedProjectCreateInTransaction must re-read current Space,
	// membership/role, enabled module and durable reservation evidence in this
	// exact transaction on EVERY invocation, including command replay. It may
	// only read: no nested transaction, writes, provider call or clock read.
	ValidateSharedProjectCreateInTransaction(context.Context, dal.ReadwriteTransaction, SharedProjectCreateBinding, time.Time) error
}

type SharedProjectLifecycleStore added in v0.60.0

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

SharedProjectLifecycleStore persists soft archive/restore and operation receipts atomically. Archive/restore preserve definitions and execution history. The concrete hosted factory supplies typed single Query/Board/Card deletion; custom inventories cannot acquire that capability. Other hosts remain unbound until their full inventory and writer participation have been proved.

func NewSharedProjectLifecycleStore added in v0.60.0

func NewSharedProjectLifecycleStore(project *SharedProjectService, inventory ProjectLifecycleInventory) (*SharedProjectLifecycleStore, error)

func (*SharedProjectLifecycleStore) ChangeProjectLifecycle added in v0.60.0

func (*SharedProjectLifecycleStore) ListProjectLifecycle added in v0.60.0

func (*SharedProjectLifecycleStore) ReviewProjectLifecycle added in v0.60.0

type SharedProjectQueryOperationScope added in v0.27.0

type SharedProjectQueryOperationScope struct {
	ActorID, StoreID, SpaceID, ProjectID, Kind string
}

SharedProjectQueryOperationScope records the full immutable receipt scope in one value for audit and exact replay checks.

func (SharedProjectQueryOperationScope) Validate added in v0.27.0

type SharedProjectQueryReadResult added in v0.27.0

type SharedProjectQueryReadResult struct {
	Query                 json.RawMessage `json:"query"`
	Revision              string          `json:"revision"`
	SaveSupported         bool            `json:"saveSupported"`
	UnsupportedSaveReason string          `json:"unsupportedSaveReason,omitempty"`
}

type SharedProjectService added in v0.10.0

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

SharedProjectService is deliberately separate from the private-project Facade, so existing callers do not acquire shared creation implicitly.

func NewActivatingBusinessSharedProjectService added in v0.21.0

func NewActivatingBusinessSharedProjectService(
	db dal.DB,
	ids IDGenerator,
	now func() time.Time,
	options BusinessSharedProjectOptions,
	activation SharedProjectActivationOptions,
) (*SharedProjectService, error)

NewActivatingBusinessSharedProjectService composes Business access with the same explicit-submit Core capability activation used for Pro. A Space that has not enabled DataTug can therefore create its first shared project; the capability marker is still planned and applied only in the create transaction after current paid, membership, and owner-contact checks.

func NewActivatingPaidSharedProjectService added in v0.15.0

func NewActivatingPaidSharedProjectService(
	db dal.DB,
	ids IDGenerator,
	now func() time.Time,
	paid PaidSharedProjectOptions,
	activation SharedProjectActivationOptions,
) (*SharedProjectService, error)

NewActivatingPaidSharedProjectService is the explicit-create composition. It has no preflight SharedProjectCreateAuthority because a new Space may not yet have the DataTug capability. Its Create methods seed a complete paid quota basis before mutation, then plan/apply capability activation in the same transaction as project admission.

func NewActivatingProBusinessSharedProjectService added in v0.21.0

func NewActivatingProBusinessSharedProjectService(db dal.DB, ids IDGenerator, now func() time.Time, options ProBusinessSharedProjectOptions, activationOptions SharedProjectActivationOptions) (*SharedProjectService, error)

NewActivatingProBusinessSharedProjectService adds explicit-submit Core activation for first creation in a Space. Pro quota inventory remains mandatory, while Business creation does not initialize or consume it.

func NewBusinessSharedProjectService added in v0.21.0

func NewBusinessSharedProjectService(
	db dal.DB,
	ids IDGenerator,
	authority SharedProjectCreateAuthority,
	now func() time.Time,
	options BusinessSharedProjectOptions,
) (*SharedProjectService, error)

NewBusinessSharedProjectService enables only the DataTug Business shared project path. It has no Pro directory, finite quota, or AI entitlement.

func NewDetectiveSharedProjectService added in v0.29.1

func NewDetectiveSharedProjectService(db dal.DB, ids IDGenerator, now func() time.Time, links *PaidProjectOwnerLinksOptions) (*SharedProjectService, error)

NewDetectiveSharedProjectService supplies current owner/contact proof for private demo projects without granting paid project creation or admission. The demo capability must be configured separately on DetectiveService.

func NewPaidSharedProjectService added in v0.11.0

func NewPaidSharedProjectService(db dal.DB, ids IDGenerator, authority SharedProjectCreateAuthority, now func() time.Time, options PaidSharedProjectOptions) (*SharedProjectService, error)

NewPaidSharedProjectService connects admission to Create's own transaction. Activation still requires proved quota initialization/import, private rules, project contact-role guards and project-scoped hosted-write/AI enforcement. The legacy constructor remains ownership-only and must not activate paid routes.

func NewProBusinessSharedProjectService added in v0.21.0

func NewProBusinessSharedProjectService(db dal.DB, ids IDGenerator, authority SharedProjectCreateAuthority, now func() time.Time, options ProBusinessSharedProjectOptions) (*SharedProjectService, error)

NewProBusinessSharedProjectService enables both finite personal Pro and explicit Space Business access on a single shared-project route service.

func NewSharedProjectService added in v0.10.0

func NewSharedProjectService(db dal.DB, ids IDGenerator, authority SharedProjectCreateAuthority, now func() time.Time) (*SharedProjectService, error)

func (*SharedProjectService) ActiveProjectSessions added in v0.61.1

ActiveProjectSessions projects discovery after the session service has admitted this actor. It does not change session state, scopes or fences.

func (*SharedProjectService) AuthorizeGitHubProjectWrite added in v0.14.0

func (s *SharedProjectService) AuthorizeGitHubProjectWrite(ctx context.Context, actorID string, repositoryID int64, owner, name, folder string) (GitHubProjectAccess, error)

AuthorizeGitHubProjectWrite adds a current configured Pro or Business grant to registered linked-contact membership. GitHub itself independently decides whether the current actor can write; Space roles are not a second GitHub edit ACL.

func (*SharedProjectService) AuthorizeSessionContextProject added in v0.28.0

func (s *SharedProjectService) AuthorizeSessionContextProject(ctx context.Context, actor, spaceID, projectID string) error

AuthorizeSessionContextProject applies the existing assigned-contact admission to private working context. Ending a paid term does not destroy read access. Every transport request, including operation recovery, must call this anew.

func (*SharedProjectService) ChangeProjectMeanings added in v0.59.1

func (s *SharedProjectService) ChangeProjectMeanings(ctx context.Context, actor, space, project string, request datatug.ProjectMeaningWrite) (datatug.ProjectMeaningAck, error)

func (*SharedProjectService) CloudProjectJoinEligibility added in v0.60.6

func (s *SharedProjectService) CloudProjectJoinEligibility(ctx context.Context, actorID string, command CloudProjectJoinCommand) (CloudProjectJoinEligibility, error)

CloudProjectJoinEligibility answers join_eligibility. Reservations are never written and a stale one counts as free; its only write is the caller's pin attempt, because this answer tells a right pin from a wrong one just as a join does. Without the invite's valid pin it answers as for an unknown invite, so a caller who only knows the IDs learns nothing of the owner's plan or quota.

func (*SharedProjectService) ConfigureCloudProjectLifecycle added in v0.60.6

func (s *SharedProjectService) ConfigureCloudProjectLifecycle(options CloudProjectLifecycleOptions) error

ConfigureCloudProjectLifecycle binds the host's invite-revoke and Space-delete ports. Either may be nil.

func (*SharedProjectService) ConfigureCloudProjects added in v0.60.6

func (s *SharedProjectService) ConfigureCloudProjects(spaces CloudProjectSpacePort) error

ConfigureCloudProjects binds the host's Space-creation port. The service must already carry project-contact links (the owner role and contacts).

func (*SharedProjectService) Create added in v0.10.0

func (*SharedProjectService) CreateCloudProject added in v0.60.6

func (s *SharedProjectService) CreateCloudProject(ctx context.Context, command CloudProjectCreateCommand) (CloudProjectRef, error)

CreateCloudProject creates, in one transaction, a dedicated group Space, a private project in it with an owner role edge, the project's dev environment and the owner's project brief (REQ create-cloud-project). No plan or quota is read or written. Replaying the command returns the same ids; the same command id with another title is a conflict.

func (*SharedProjectService) CreateCloudProjectInvite added in v0.60.6

CreateCloudProjectInvite lets any project owner, Free or Pro, invite a friend. It writes a Space contact with no user linked, a Sneat invite and a pending invites[<inviteID>] record. It checks and consumes no plan or quota, writes no role edge and leaves the project's access unchanged. It is idempotent by operation ID across both of its transactions: the contact ID is derived from the operation, so a retry after a failed second transaction adopts the contact and invite the first attempt wrote.

func (*SharedProjectService) CreateEnvironment added in v0.59.1

func (*SharedProjectService) CreateGitHubProject added in v0.14.0

CreateGitHubProject reserves paid shared-project capacity and owner linkage before provider mutation, then commits the exact pinned files with a branch head precondition. A failed/unknown provider result leaves the hidden intent and quota reserved for safe same-operation recovery; it never creates a second commit or silently frees capacity.

func (*SharedProjectService) DeleteCloudProject added in v0.60.6

DeleteCloudProject deletes a Space-backed cloud project for its owner. One transaction removes the project record, both sides of every project-contact edge, every member's brief and the owner admission, releases the project's owner-quota slot, and marks the create receipt deleted. Then, outside it, the dedicated Space's invites are revoked, the project's remaining records are purged in bounded batches, and an emptied dedicated Space is deleted. A failure after the transaction is reported in the result, never as an error. Calling it again for a deleted project resumes what is left.

func (*SharedProjectService) EnableCloudProjectSharing added in v0.60.6

func (s *SharedProjectService) EnableCloudProjectSharing(options CloudProjectSharingOptions) error

EnableCloudProjectSharing adds the share-and-join commands to a paid service. It needs the paid options for plan reads (whose directory also reads inside a transaction, for a joined Pro member's gates) and the owner links for role edges.

func (*SharedProjectService) EnsureProtectedProjectQuotaForCreate added in v0.15.0

func (s *SharedProjectService) EnsureProtectedProjectQuotaForCreate(ctx facade.ContextWithUser, binding SharedProjectCreateBinding) error

EnsureProtectedProjectQuotaForCreate is a command-bound explicit-submit preflight. It requires current paid, owner-contact and Core Space authority before scanning or seeding a missing quota. All protected allocation writers require an existing quota in their own transaction, so absence fences target-payer writes while the complete scan runs. The seed transaction repeats the command authority checks and continued quota absence before inserting the basis.

func (*SharedProjectService) EnvironmentOperationStatus added in v0.59.1

func (*SharedProjectService) GetGitHubProjectCreateStatus added in v0.59.1

func (s *SharedProjectService) GetGitHubProjectCreateStatus(ctx context.Context, actorID, operationID string, repo GitHubCreateRepository) (GitHubProjectCreateStatus, error)

GetGitHubProjectCreateStatus rechecks the PR using the freshly authorized repository adapter. A project becomes ready only after the merge commit contains every exact setup byte recorded by the creation operation.

func (*SharedProjectService) GitHubEnvironmentOperationStatus added in v0.59.1

func (s *SharedProjectService) GitHubEnvironmentOperationStatus(ctx context.Context, actor string, request dto.EnvironmentOperationStatusRequest) (*dto.EnvironmentOperationResult, error)

func (*SharedProjectService) GuardedSessionRepository added in v0.60.0

func (s *SharedProjectService) GuardedSessionRepository(mounted sessioncontext.MountedDatabase, selected SessionOperationScope, actor string) (*sessioncontext.DALRepository, error)

GuardedSessionRepository is the application boundary for ordinary and native session commands. Legacy state transitions cannot bypass project usage review. Co-located Firestore writes share the project generation fence. This is writer participation, not complete inventory: unknown reference-bearing batches are refused once archives exist until their typed projection is installed. Cross-database/GitHub histories remain unverified for lifecycle purposes.

func (*SharedProjectService) JoinCloudProject added in v0.60.6

JoinCloudProject admits the caller through a pending invite (REQ share-and-join, Join). Before any write it refuses a deleted or archived project, validates the invite and pin, and decides eligibility: the joiner's own Pro (no owner quota), else the owner's Pro quota, else ErrCloudProjectPlanRequired with nothing written. Every step after the claim is resumable by invite ID. A join refused once the caller has claimed the invite, in this call or an earlier one, also ends the caller's Space membership and spends the pending invite (undoCloudJoinClaim), so no Space member is left without a role edge.

func (*SharedProjectService) ListPendingGitHubProjectSetups added in v0.59.1

func (s *SharedProjectService) ListPendingGitHubProjectSetups(ctx context.Context, actorID string) (PendingGitHubProjectSetups, error)

ListPendingGitHubProjectSetups queries only records owned by actorID and bounds both the provider work and the response size for lost-tab recovery.

func (*SharedProjectService) ListSharedProjectQueries added in v0.27.0

func (s *SharedProjectService) ListSharedProjectQueries(ctx context.Context, actorID, spaceID, projectID string) ([]datatug.QueryDefWithFolderPath, error)

ListSharedProjectQueries returns the bounded current query snapshot for an assigned contact. Query bodies are omitted from the folder items, matching the existing GitHub folder-tree response; bodies are loaded by revision.

func (*SharedProjectService) ListSharedProjectQueryFolders added in v0.61.1

func (s *SharedProjectService) ListSharedProjectQueryFolders(ctx context.Context, actor, space, project string) ([]string, error)

ListSharedProjectQueryFolders projects explicit declarations, including empty copied folders. It does not change direct access to contained definitions.

func (*SharedProjectService) MutateGitHubEnvironment added in v0.59.1

func (s *SharedProjectService) MutateGitHubEnvironment(ctx context.Context, actor string, request dto.EnvironmentMutation, kind, name string, order []string, repo GitHubEnvironmentRepository) (*dto.EnvironmentOperationResult, error)

func (*SharedProjectService) PlanExplicitProjectCreateActivationInTransaction added in v0.15.0

func (s *SharedProjectService) PlanExplicitProjectCreateActivationInTransaction(
	ctx facade.ContextWithUser,
	tx dal.ReadwriteTransaction,
	binding SharedProjectCreateBinding,
	observedAt time.Time,
) (contract4spaceus.PreparedRoleCapabilityActivation, error)

PlanExplicitProjectCreateActivationInTransaction binds Core's activation plan to the verified caller and immutable paid create command. The caller must run all of its authorization, quota, receipt, repository, and owner contact checks before calling Apply on the returned value in this same DAL transaction, immediately before its first write.

func (*SharedProjectService) PrepareFavoriteTarget added in v0.60.0

func (s *SharedProjectService) PrepareFavoriteTarget(ctx context.Context, tx dal.ReadwriteTransaction, actor string, project m.FavoriteProject, item m.Favorite) (func() error, error)

PrepareFavoriteTarget authorizes a project definition reference, not query execution or access to a referenced external data source. No target content is returned. The exact definition is read in the favorite transaction.

func (*SharedProjectService) ReadCloudProjectAccess added in v0.60.6

func (s *SharedProjectService) ReadCloudProjectAccess(ctx context.Context, actorID, spaceID, projectID string) (CloudProjectAccess, error)

ReadCloudProjectAccess answers project_access for a current project member.

func (*SharedProjectService) ReadEnvironmentState added in v0.59.1

func (s *SharedProjectService) ReadEnvironmentState(ctx context.Context, actor string, scope dto.EnvironmentScope) (*dto.EnvironmentState, error)

func (*SharedProjectService) ReadGitHubArchivedItems added in v0.61.1

func (s *SharedProjectService) ReadGitHubArchivedItems(ctx context.Context, actor string, access GitHubProjectAccess, externalProject, branch string) (map[datatug.ProjectObjectRef]bool, error)

ReadGitHubArchivedItems is called after the source adapter freshly authorizes GitHub read access. It rechecks DataTug membership/binding and returns only visibility flags; it cannot grant access to repository data.

func (*SharedProjectService) ReadGitHubProjectAIEligibility added in v0.16.0

func (s *SharedProjectService) ReadGitHubProjectAIEligibility(ctx context.Context, actorID string, repositoryID int64, owner, name, folder string) (ProjectAIEligibility, error)

ReadGitHubProjectAIEligibility binds the entitlement read to the registered immutable GitHub locator. The HTTP layer separately obtains fresh GitHub read permission for the exact repository before calling this method.

func (*SharedProjectService) ReadGitHubVisibilityAccess added in v0.61.1

func (s *SharedProjectService) ReadGitHubVisibilityAccess(ctx context.Context, tx dal.ReadTransaction, actor, space, project string, binding m.GitHubProjectBinding) (bool, error)

ReadGitHubVisibilityAccess rechecks current project/contact admission and the immutable repository binding in the caller's transaction. Provider authority and a pinned branch snapshot must additionally be supplied by the API adapter.

func (*SharedProjectService) ReadProjectConnectionCatalog added in v0.60.6

func (s *SharedProjectService) ReadProjectConnectionCatalog(ctx context.Context, actorID, spaceID, projectID string) (ProjectConnectionCatalog, error)

ReadProjectConnectionCatalog serves the project's own connections when its connectionCatalog is "own" (REQ per-project-connection-catalog). The field, never an empty map, tells it apart from a legacy Space project.

func (*SharedProjectService) ReadProjectMeanings added in v0.59.1

func (s *SharedProjectService) ReadProjectMeanings(ctx context.Context, actor, space, project string) (datatug.ProjectMeaningsCatalog, error)

func (*SharedProjectService) ReadQuickSearchAccess added in v0.59.1

func (s *SharedProjectService) ReadQuickSearchAccess(ctx context.Context, actor, space, project string, github bool) (manage, eligible bool, err error)

ReadQuickSearchAccess checks current roles independently of the paid term so a current owner can always revoke consent and delete retained metadata.

func (*SharedProjectService) ReadSharedProjectAIEligibility added in v0.16.0

func (s *SharedProjectService) ReadSharedProjectAIEligibility(ctx context.Context, actorID, spaceID, projectID string) (ProjectAIEligibility, error)

ReadSharedProjectAIEligibility authorizes the current linked project reader and then evaluates the payer recorded by that project's immutable admission. The client supplies a project locator only; it cannot select the payer.

func (*SharedProjectService) ReadSharedProjectQuery added in v0.27.0

func (s *SharedProjectService) ReadSharedProjectQuery(ctx context.Context, actorID, spaceID, projectID, folderPath, queryID string) (*SharedProjectQueryReadResult, error)

ReadSharedProjectQuery authorizes the current assigned project contact in the same transaction as the query read. Space membership alone grants no access. It is the Cloud counterpart of the existing selected-branch query reader and deliberately has no GitHub or provider dependency.

func (*SharedProjectService) ReadSharedProjectSummary added in v0.27.0

func (s *SharedProjectService) ReadSharedProjectSummary(ctx context.Context, actorID, spaceID, projectID string) (json.RawMessage, error)

func (*SharedProjectService) ReconcileGitHubEnvironmentStatus added in v0.59.1

ReconcileGitHubEnvironmentStatus proves an already intended effect; it never starts a provider write and remains available to a currently authorized reader.

func (*SharedProjectService) ResolveGitHubProject added in v0.14.0

func (s *SharedProjectService) ResolveGitHubProject(ctx context.Context, actorID string, repositoryID int64, owner, name, folder string) (GitHubProjectAccess, error)

ResolveGitHubProject verifies a ready immutable locator, paid admission provenance and a CURRENT active linked contact for this Firebase UID. It deliberately does not require an active paid term: reads survive a Pro plan ending. The caller also needs fresh GitHub user+App read authority for the exact immutable repository; this Space proof never replaces that check.

func (*SharedProjectService) ResumeCloudProjectDelete added in v0.60.6

func (s *SharedProjectService) ResumeCloudProjectDelete(ctx context.Context, spaceID, projectID string) (CloudProjectDeleteResult, error)

ResumeCloudProjectDelete is the event-driven follow-up of a delete: the host's task calls it with the ids it enqueued. It acts as the owner who deleted the project, as recorded on the receipt, and enqueues itself again while a step it can do is left, at most cloudDeleteResumes times.

func (*SharedProjectService) SaveEnvironmentOrder added in v0.59.1

func (*SharedProjectService) SaveGitHubQuery added in v0.14.0

func (s *SharedProjectService) SaveGitHubQuery(ctx context.Context, actorID string, repositoryID int64, owner, name, folder string, request dto.SaveQueryRequest, repo GitHubQueryRepository) (*dto.SaveQueryResponse, error)

SaveGitHubQuery is the paid, actor-bound Cloud command. The provider commit is one CAS operation containing the metadata/body pair. A durable intent precedes that commit; retries prove the original commit before finalizing.

func (*SharedProjectService) SaveProjectConnection added in v0.60.6

SaveProjectConnection copies the pinned <demoDb>-sqlite entry verbatim into the project's own connections and increments connectionsRevision (REQ project-connections). Nothing is fetched, validated or re-hashed. An entry already present changes nothing; an identical retry returns its receipt.

func (*SharedProjectService) SaveSharedProjectQuery added in v0.27.0

func (s *SharedProjectService) SaveSharedProjectQuery(ctx context.Context, actorID, spaceID string, request dto.SaveQueryRequest) (*dto.SaveQueryResponse, error)

SaveSharedProjectQuery applies Core's storage-neutral create/update contract to the Space-owned Firestore project. The query, opaque revision, and actor/scope/payload-bound operation receipt commit atomically. The caller supplies only the authenticated actor and the explicit Space/project scope.

func (*SharedProjectService) SessionContextDemoEnvironments added in v0.29.2

func (s *SharedProjectService) SessionContextDemoEnvironments(ctx context.Context, actor, spaceID, projectID string) ([]string, error)

SessionContextDemoEnvironments admits only the pinned private demo and its currently assigned actor. Ordinary shared projects still require host catalog configuration. This fresh transaction is required for every transport request.

func (*SharedProjectService) SetCloudProjectArchived added in v0.60.6

func (s *SharedProjectService) SetCloudProjectArchived(ctx context.Context, actorID string, command CloudProjectArchiveCommand) error

SetCloudProjectArchived archives or restores a Space-backed cloud project for its owner: it sets or clears the project's archived stamp and the archived flag on every member's brief. The Space, members, role edges, invites and quota stay as they are.

func (*SharedProjectService) SharedProjectQueryCapabilities added in v0.27.0

func (s *SharedProjectService) SharedProjectQueryCapabilities(ctx context.Context, actorID, spaceID, projectID string) (dto.ProjectCapabilities, error)

type ShippingCheckNodeResult added in v0.59.1

type ShippingCheckNodeResult struct {
	Inputs            map[string]detective.InputValue `json:"inputs"`
	SavedQuery        json.RawMessage                 `json:"savedQuery"`
	QueryID           string                          `json:"queryId"`
	QueryRevision     string                          `json:"queryRevision"`
	ResultFingerprint string                          `json:"resultFingerprint"`
	Result            apicontract.Result              `json:"result"`
}

type ShippingCheckRunOpenResponse added in v0.59.1

type ShippingCheckRunOpenResponse struct {
	Run       detective.CheckRun                     `json:"run"`
	SourcePin models4datatug.ShippingSourcePin       `json:"sourcePin"`
	Manifest  models4datatug.ShippingAppliedManifest `json:"manifest"`
	Results   []ShippingCheckNodeResult              `json:"results"`
}

type ShippingEvidenceOpenRequest added in v0.59.1

type ShippingEvidenceOpenRequest struct {
	SpaceID     string                          `json:"spaceID"`
	ProjectID   string                          `json:"projectId"`
	Environment string                          `json:"environment"`
	Selector    apicontract.RowEvidenceSelector `json:"selector"`
}

type ShippingEvidenceOpenResponse added in v0.59.1

type ShippingEvidenceOpenResponse struct {
	Comparison         *models4datatug.ShippingComparisonAdmission `json:"comparison,omitempty"`
	OriginalEvidence   *ShippingOriginalEvidence                   `json:"originalEvidence,omitempty"`
	Inputs             map[string]detective.InputValue             `json:"inputs"`
	Manifest           models4datatug.ShippingAppliedManifest      `json:"manifest"`
	SavedQuery         json.RawMessage                             `json:"savedQuery"`
	ActorID            string                                      `json:"actorId"`
	Result             apicontract.Result                          `json:"result"`
	SourcePin          models4datatug.ShippingSourcePin            `json:"sourcePin"`
	AppliedManifestRef string                                      `json:"appliedManifestRef"`
	QueryRevision      string                                      `json:"queryRevision"`
	Evidence           *apicontract.RowEvidenceSlot                `json:"evidence,omitempty"`
}

type ShippingOriginalEvidence added in v0.59.1

type ShippingOriginalEvidence struct {
	Version   int                              `json:"version"`
	Status    string                           `json:"status"`
	Reason    string                           `json:"reason,omitempty"`
	Selection *apicontract.RowEvidenceSelector `json:"selection,omitempty"`
	Records   []ShippingOriginalRecord         `json:"records,omitempty"`
	Log       *ShippingOriginalLog             `json:"log,omitempty"`
}

ShippingOriginalEvidence is an ephemeral direct read. It is never retained in the execution snapshot, and is not a grant to discover another source.

type ShippingOriginalLog added in v0.59.1

type ShippingOriginalLog struct {
	Artifact       string `json:"artifact"`
	ArtifactSHA256 string `json:"artifactSHA256"`
	ArtifactBytes  int64  `json:"artifactBytes"`
	ByteStart      int64  `json:"byteStart"`
	ByteEnd        int64  `json:"byteEnd"`
	SourceRef      string `json:"sourceRef"`
	Parser         string `json:"parser"`
	ParseStatus    string `json:"parseStatus"`
	RawBase64      string `json:"rawBase64"`
}

type ShippingOriginalRecord added in v0.59.1

type ShippingOriginalRecord struct {
	Collection string                            `json:"collection"`
	Key        apicontract.TypedValue            `json:"key"`
	Fields     map[string]apicontract.TypedValue `json:"fields"`
}

type ShippingSourceOperationOpenRequest added in v0.59.1

type ShippingSourceOperationOpenRequest struct {
	SpaceID     string                       `json:"spaceID"`
	ProjectID   string                       `json:"projectId"`
	Environment string                       `json:"environment"`
	Reference   incidents.SourceOperationRef `json:"reference"`
}

type ShippingSourceOperationOpenResponse added in v0.59.1

type ShippingSourceOperationOpenResponse struct {
	Reference incidents.SourceOperationRef   `json:"reference"`
	Receipt   models4datatug.ShippingReceipt `json:"receipt"`
}

type ShippingSourceOperationSummary added in v0.59.1

type ShippingSourceOperationSummary struct {
	Reference  incidents.SourceOperationRef `json:"reference"`
	Action     string                       `json:"action"`
	Outcome    string                       `json:"outcome"`
	AcceptedAt time.Time                    `json:"acceptedAt"`
}

type ShippingSourceOperationsResponse added in v0.59.1

type ShippingSourceOperationsResponse struct {
	Operations []ShippingSourceOperationSummary `json:"operations"`
}

type SpaceServiceAccess added in v0.19.0

type SpaceServiceAccess struct {
	Mode, ServiceID, PayerSpaceID, OwnerFamily, AccountKind, ProductID, PlanID string
	ProviderAccountID, CustomerID, LineageID, OwnerSubscriptionID              string
	PaidServiceProofID, GrantVersion                                           string
	OwnerGeneration, OwnerRevision                                             int64
	PaidUntilUTC                                                               time.Time
	State                                                                      string // active or ended, after complete source reconciliation
	UnlimitedProjects, UnlimitedContacts                                       bool
	// contains filtered or unexported fields
}

SpaceServiceAccess is the product-authorized current service projection. It is derived from Paymentus' read-only financial projection plus this versioned DataTug entitlement policy. The client cannot supply any field.

type UsageReader added in v0.4.0

type UsageReader interface {
	ReadUsage(context.Context, string, string) (*models4datatug.AIUsageRecord, error)
}

UsageReader reads the requested UTC month; nil means no count document.

type WatchBundleQuery added in v0.59.1

type WatchBundleQuery struct {
	Revision       string                            `json:"revision"`
	JSON           json.RawMessage                   `json:"json"`
	SourcePin      *models4datatug.ShippingSourcePin `json:"sourcePin,omitempty"`
	SourceIdentity *WatchSourceIdentity              `json:"sourceIdentity,omitempty"`
}

WatchExecutionBundle is one immutable, admitted dependency graph. The digest excludes transport leases and contains no monitored-source credentials. A receiver rebuilds Catalog with Core.LoadCatalog before Core.EvaluateCheck.

type WatchBundleRequest added in v0.59.1

type WatchBundleRequest struct {
	ClaimID string `json:"claimId"`
	Fence   int64  `json:"fence"`
}

type WatchChange added in v0.59.1

type WatchChange struct {
	SourceCursor string     `json:"sourceCursor,omitempty" firestore:"sourceCursor,omitempty"`
	ID           string     `json:"id" firestore:"id"`
	SpaceID      string     `json:"spaceID" firestore:"spaceID"`
	ProjectID    string     `json:"projectID" firestore:"projectID"`
	Environment  string     `json:"environment" firestore:"environment"`
	Kind         string     `json:"kind" firestore:"kind"`
	ResourceID   string     `json:"resourceId" firestore:"resourceId"`
	Revision     string     `json:"revision" firestore:"revision"`
	State        string     `json:"state" firestore:"state"`
	NotBefore    time.Time  `json:"notBefore" firestore:"notBefore"`
	CreatedAt    time.Time  `json:"createdAt" firestore:"createdAt"`
	PublishedAt  time.Time  `json:"publishedAt,omitempty" firestore:"publishedAt,omitempty"`
	RetryAt      time.Time  `json:"retryAt,omitempty" firestore:"retryAt,omitempty"`
	Generation   int64      `json:"generation,omitempty" firestore:"generation,omitempty"`
	ExpiresAt    *time.Time `json:"expiresAt,omitempty" firestore:"expiresAt,omitempty"`
	CompletedAt  time.Time  `json:"completedAt,omitempty" firestore:"completedAt,omitempty"`
}

type WatchCloudScope added in v0.59.1

type WatchCloudScope struct{ SpaceID, ProjectID, Environment string }

WatchCloudScope comes from the trusted API route, never a project manifest.

func (WatchCloudScope) Scope added in v0.59.1

func (s WatchCloudScope) Scope() watch.Scope

func (WatchCloudScope) Validate added in v0.59.1

func (s WatchCloudScope) Validate() error

type WatchDependency added in v0.59.1

type WatchDependency struct {
	Kind     string `json:"kind" firestore:"kind"`
	ID       string `json:"id" firestore:"id"`
	Revision string `json:"revision" firestore:"revision"`
}

type WatchEnrollmentMutation added in v0.59.1

type WatchEnrollmentMutation struct {
	ID               string `json:"id"`
	ExpectedRevision int64  `json:"expectedRevision"`
}

type WatchEnrollmentPage added in v0.59.1

type WatchEnrollmentPage struct {
	Enrollments []WatchRunnerEnrollment `json:"enrollments"`
	Next        string                  `json:"next,omitempty"`
}

type WatchEnrollmentRequest added in v0.59.1

type WatchEnrollmentRequest struct {
	OperationID   string   `json:"operationId"`
	SourceIDs     []string `json:"sourceIDs" firestore:"sourceIDs"`
	Capabilities  []string `json:"capabilities"`
	TelegramBotID string   `json:"telegramBotId,omitempty"`
}

type WatchEnrollmentResult added in v0.59.1

type WatchEnrollmentResult struct {
	Enrollment WatchRunnerEnrollment `json:"enrollment"`
	// Token is returned once. A lost response requires explicit rotation; a
	// replay does not persist or reproduce the original secret.
	Token string `json:"token,omitempty"`
}

type WatchExecutionBundle added in v0.59.1

type WatchExecutionBundle struct {
	Contract       string                      `json:"contract"`
	Scope          watch.Scope                 `json:"scope"`
	CheckID        string                      `json:"checkId"`
	CheckVersion   string                      `json:"checkVersion"`
	SourceRevision string                      `json:"sourceRevision"`
	BundleDigest   string                      `json:"bundleDigest"`
	Catalog        detective.Catalog           `json:"catalog"`
	Queries        map[string]WatchBundleQuery `json:"queries"`
	Sources        []WatchSource               `json:"sources"`
	Dependencies   []WatchDependency           `json:"dependencies"`
	Artifacts      map[string][]byte           `json:"artifacts,omitempty"`
}

type WatchIdentityReader added in v0.59.1

type WatchIdentityReader func(context.Context, dal.ReadTransaction, string) (watch.RecipientAuthority, error)

WatchIdentityReader reads current native account status and verified delivery addresses. It is a read-only port: callbacks can be retried by Firestore. Provider account verification is additional evidence, not atomic Firestore proof.

type WatchQueueReport added in v0.59.1

type WatchQueueReport struct{ Published, Processed, Examined int }

type WatchRunnerEnrollment added in v0.59.1

type WatchRunnerEnrollment struct {
	ID            string      `json:"id" firestore:"id"`
	Scope         watch.Scope `json:"scope" firestore:"scope"`
	OwnerID       string      `json:"ownerId" firestore:"ownerId"`
	SourceIDs     []string    `json:"sourceIDs" firestore:"sourceIDs"`
	Environment   string      `json:"-" firestore:"environment"`
	Capabilities  []string    `json:"capabilities" firestore:"capabilities"`
	TelegramBotID string      `json:"telegramBotId,omitempty" firestore:"telegramBotId,omitempty"`
	TokenHash     string      `json:"-" firestore:"tokenHash"`
	RequestHash   string      `json:"-" firestore:"requestHash"`
	Revision      int64       `json:"revision" firestore:"revision"`
	Revoked       bool        `json:"revoked" firestore:"revoked"`
	CreatedAt     time.Time   `json:"createdAt" firestore:"createdAt"`
	UpdatedAt     time.Time   `json:"updatedAt" firestore:"updatedAt"`
	ExpiresAt     time.Time   `json:"expiresAt" firestore:"expiresAt"`
}

WatchRunnerEnrollment is private deployment authority. Public responses omit TokenHash and never contain a Telegram bot secret or monitored credential.

type WatchSource added in v0.59.1

type WatchSource struct {
	ID         string `json:"id"`
	Kind       string `json:"kind"`
	Origin     string `json:"origin,omitempty"`
	Database   string `json:"database,omitempty"`
	Collection string `json:"collection,omitempty"`
	SourceID   string `json:"sourceId,omitempty"`
}

type WatchSourceIdentity added in v0.59.1

type WatchSourceIdentity struct {
	SourceID        string `json:"sourceId"`
	Environment     string `json:"environment"`
	BindingRevision int64  `json:"bindingRevision"`
	Generation      string `json:"generation"`
	FixtureCommit   string `json:"fixtureCommit"`
	FixtureSHA256   string `json:"fixtureSHA256"`
	SchemaSHA256    string `json:"schemaSHA256"`
}

WatchSourceIdentity describes execution semantics, not changing business rows. A shipping reset changes Generation; correction/replay within it does not.

type WorkEnvironmentCatalog added in v0.59.1

type WorkEnvironmentCatalog func(context.Context, string, string, string) ([]m.WorkEnvironment, error)

WorkEnvironmentCatalog returns admitted source scopes, not source credentials.

type WorkFilter added in v0.59.1

type WorkFilter struct {
	Type, Owner, Assignee, Status, Priority, Due, Search, Cursor string
	// Parent narrows the list to the direct children of one Work item.
	Parent string
	// Postmortem filters incident/case items by their attached postmortem:
	// none, any, or one of the postmortemRefStates values.
	Postmortem string
	Limit      int
}

type WorkMigrationEntry added in v0.59.1

type WorkMigrationEntry struct {
	Kind          string `json:"kind"`
	SourceID      string `json:"sourceId"`
	SourceVersion int64  `json:"sourceVersion"`
	SourceSHA256  string `json:"sourceSha256"`
	WorkID        string `json:"workId"`
	Environment   string `json:"environment,omitempty"`
}

type WorkMigrationReport added in v0.59.1

type WorkMigrationReport struct {
	SchemaVersion         int                  `json:"schemaVersion"`
	Digest                string               `json:"digest"`
	State                 string               `json:"state"`
	Cases                 int                  `json:"cases"`
	Incidents             int                  `json:"incidents"`
	RelatedLinks          int                  `json:"relatedLinks"`
	UnresolvedLegacyLinks int                  `json:"unresolvedLegacyLinks"`
	Imported              int                  `json:"imported"`
	Entries               []WorkMigrationEntry `json:"entries"`
}

type WorkService added in v0.59.1

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

func NewWorkService added in v0.59.1

func NewWorkService(project *SharedProjectService, mounted sessioncontext.MountedDatabase, environments WorkEnvironmentCatalog) (*WorkService, error)

func (*WorkService) Action added in v0.59.1

func (s *WorkService) Action(ctx context.Context, actor string, r m.WorkAction) (m.WorkDetail, error)

func (*WorkService) Activity added in v0.59.1

func (s *WorkService) Activity(ctx context.Context, actor, space, project, id, cursor string) (m.WorkActivityPage, error)

Activity paginates immutable history in newest-first order. New writes do not shift earlier pages; the cursor is bound to the actor and exact project/item.

func (s *WorkService) ArtifactLinks(ctx context.Context, actor, space, project, kind, id, folder string) (m.WorkArtifactLinks, error)

func (*WorkService) ConfigureWatch added in v0.59.1

func (s *WorkService) ConfigureWatch(config WorkWatchConfig) error

ConfigureWatch is called during host construction, before serving requests. An absent bridge does not disable ordinary Work; Watch operations fail closed.

func (*WorkService) ConfigureWatchArtifacts added in v0.59.1

func (s *WorkService) ConfigureWatchArtifacts(cloud *CloudWatchService)

ConfigureWatchArtifacts binds native Watch visibility and source admission. Configure only during host composition, before requests are served.

func (*WorkService) ConfigureWatchFile added in v0.59.1

func (s *WorkService) ConfigureWatchFile(path string) error

func (*WorkService) Context added in v0.59.1

func (s *WorkService) Context(ctx context.Context, actor, space, project, id string) (sessioncontext.Snapshot, error)

func (*WorkService) Get added in v0.59.1

func (s *WorkService) Get(ctx context.Context, actor, space, project, id string) (m.WorkDetail, error)

func (*WorkService) List added in v0.59.1

func (s *WorkService) List(ctx context.Context, actor, space, project string, f WorkFilter) (m.WorkPage, error)

func (*WorkService) MigrateLegacy added in v0.59.1

func (s *WorkService) MigrateLegacy(ctx context.Context, actor, space, project, digest string) (WorkMigrationReport, error)

MigrateLegacy imports at most 20 records atomically per call. The supplied plan digest binds every source version and payload. Repeated calls resume the committed cursor; changed sources fail closed. Every legacy writer MUST read workLegacyAuthority in its transaction before this method is enabled.

func (*WorkService) PlanMigration added in v0.59.1

func (s *WorkService) PlanMigration(ctx context.Context, actor, space, project string) (WorkMigrationReport, error)

PlanMigration is a non-mutating inventory. It deliberately refuses ambiguous Incident project placement instead of inventing an authoritative project.

func (*WorkService) PublishWatchCoordination added in v0.59.1

func (s *WorkService) PublishWatchCoordination(ctx context.Context, actor, space, project string) error

PublishWatchCoordination is a trusted deployment operation, subject to current project assignment-manager rights. It publishes only the configured endpoint and namespace, never credentials. Patch the existing manifest atomically so unrelated project fields and concurrent environment metadata are preserved.

func (*WorkService) WatchAction added in v0.59.1

func (s *WorkService) WatchAction(ctx context.Context, actor string, r m.WorkWatchAction) (m.WorkDetail, error)

WatchAction accepts only immutable event identities and editable work fields. Remote reads happen before the local transaction; local Work/context/links/ receipts/history commit together. Retried transactions never call the network.

func (s *WorkService) WatchArtifactLinks(ctx context.Context, actor, space, project, environment, id string) (m.WorkArtifactLinks, error)

func (*WorkService) WatchEvents added in v0.59.1

func (s *WorkService) WatchEvents(ctx context.Context, actor, space, project, watchID string) (m.WorkWatchView, error)

type WorkWatchActor added in v0.59.1

type WorkWatchActor struct {
	ActorID string `json:"actorId"`
	Token   string `json:"token"`
}

type WorkWatchBinding added in v0.59.1

type WorkWatchBinding struct {
	ID                 string                    `json:"id"`
	SpaceID            string                    `json:"spaceId"`
	ProjectID          string                    `json:"projectId"`
	Endpoint           string                    `json:"endpoint"`
	Namespace          string                    `json:"namespace"`
	CoordinatorProject string                    `json:"coordinatorProject"`
	Environment        string                    `json:"environment"`
	Actors             map[string]WorkWatchActor `json:"actors"`
	Checks             []WorkWatchCheckMapping   `json:"checks"`
}

type WorkWatchCheckMapping added in v0.59.1

type WorkWatchCheckMapping struct {
	CheckID      string                  `json:"checkId"`
	CheckVersion string                  `json:"checkVersion"`
	WorkCheckID  string                  `json:"workCheckId"`
	Scope        sessioncontext.Scope    `json:"scope"`
	Inputs       []WorkWatchInputMapping `json:"inputs"`
}

type WorkWatchConfig added in v0.59.1

type WorkWatchConfig struct {
	Bindings []WorkWatchBinding `json:"bindings"`
}

Runtime configuration is private server deployment state. In particular it must never be serialized into project files, Watch definitions or responses.

type WorkWatchInputMapping added in v0.59.1

type WorkWatchInputMapping struct {
	Name      string `json:"name"`
	Type      string `json:"type"`
	SubjectID string `json:"subjectId"`
}

Source Files

Jump to

Keyboard shortcuts

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