workspace

package
v0.7.3 Latest Latest
Warning

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

Go to latest
Published: Nov 16, 2026 License: MIT Imports: 26 Imported by: 0

Documentation

Overview

Package workspace defines workspace domain models, sentinel errors, and resolver contracts used across Compozy runtime packages.

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrWorkspaceReserved            = errors.New("workspace_reserved")
	ErrWorkspaceNameReserved        = errors.New("workspace_name_reserved")
	ErrUserScopeUnsupported         = errors.New("user_scope_unsupported")
	ErrUserScopeWorktreeUnsupported = errors.New("user_scope_worktree_unsupported")
	ErrUserScopeWorkDirInvalid      = errors.New("user_scope_work_dir_invalid")
)
View Source
var (
	// ErrWorkspaceNotFound reports that no registered workspace matched the lookup.
	ErrWorkspaceNotFound = errors.New("workspace not found")
	// ErrWorkspaceRootMissing reports that the registered workspace root no longer exists on disk.
	ErrWorkspaceRootMissing = errors.New("workspace root directory no longer exists")
	// ErrAgentNotAvailable reports that the requested agent cannot be resolved in the workspace.
	ErrAgentNotAvailable = errors.New("agent not available in workspace")
	// ErrWorkspaceResolverUnavailable reports that workspace resolution cannot run because its dependency is absent.
	ErrWorkspaceResolverUnavailable = errors.New("workspace resolver unavailable")
	// ErrWorkspaceNameTaken reports that a workspace name is already registered.
	ErrWorkspaceNameTaken = errors.New("workspace name already in use")
	// ErrWorkspacePathTaken reports that a workspace root path is already registered.
	ErrWorkspacePathTaken = errors.New("workspace path already registered")
	// ErrWorkspaceHasSessions reports that a workspace cannot be deleted because sessions still reference it.
	ErrWorkspaceHasSessions = errors.New("workspace has sessions")
	// ErrWorkspaceHasActiveSessions reports that a workspace cannot be deleted because active sessions are running.
	ErrWorkspaceHasActiveSessions = errors.New("workspace has active sessions")
	// ErrWorkspaceIdentityInvalid reports a malformed .compozy/workspace.toml identity file.
	ErrWorkspaceIdentityInvalid = errors.New("workspace identity invalid")
	// ErrWorkspaceIdentityPermissionDenied reports a fail-closed identity file permission failure.
	ErrWorkspaceIdentityPermissionDenied = errors.New("workspace identity permission denied")
	// ErrWorkspaceValidation reports an invalid mutable workspace field.
	ErrWorkspaceValidation = errors.New("workspace validation failed")
	// ErrWorkspaceDeletionIntentNotFound reports that no pending deletion owns the workspace id.
	ErrWorkspaceDeletionIntentNotFound = errors.New("workspace deletion intent not found")
	// ErrWorkspaceDeletionPending reports that workspace deletion still owns external resources.
	ErrWorkspaceDeletionPending = errors.New("workspace deletion is pending")
	// ErrOperatorHomeWorkspace reports that the operator home cannot be registered as a workspace.
	ErrOperatorHomeWorkspace = errors.New("the home folder cannot be registered as a workspace")
)

Functions

func IsRegistrationID

func IsRegistrationID(value string) bool

IsRegistrationID reports whether value is a public workspace registration id.

func IsWorkspaceID

func IsWorkspaceID(value string) bool

IsWorkspaceID reports whether value is a canonical workspace ULID.

func IsWorkspaceIdentifier

func IsWorkspaceIdentifier(value string) bool

IsWorkspaceIdentifier reports whether value is exactly a workspace identifier this package issues: a durable workspace ULID, a registration id, or a legacy `ws-` registration id.

func NewWorkspaceID

func NewWorkspaceID() (string, error)

NewWorkspaceID returns a ULID formatted for durable workspace identity.

func UniqueWorkspaceName

func UniqueWorkspaceName(rootDir string, taken map[string]struct{}) string

UniqueWorkspaceName derives a stable workspace name from the root path and appends numeric suffixes until it no longer collides with the taken set.

func ValidatePersonalProfileRoot

func ValidatePersonalProfileRoot(workspaceRoot, homeRoot, profilesRoot, profileName string) error

ValidatePersonalProfileRoot prevents personal resource layers from aliasing workspace data.

func ValidateWorkspaceName

func ValidateWorkspaceName(name string) error

Types

type AgentDiagnostic

type AgentDiagnostic struct {
	Name      string
	Path      string
	ErrorKind string
	Message   string
}

AgentDiagnostic reports one workspace-visible AGENT.md file that could not be loaded.

type ArchiveBlocker

type ArchiveBlocker struct {
	Kind string `json:"kind"`
	ID   string `json:"id"`
	Name string `json:"name"`
}

type BusyError

type BusyError struct {
	Blockers []ArchiveBlocker `json:"blockers"`
}

func (*BusyError) Error

func (e *BusyError) Error() string

type ChangeHook

type ChangeHook func(context.Context) error

ChangeHook runs after persisted workspace mutations that affect resolved runtime state.

type ConfigLoader

type ConfigLoader func(rootDir string) (compozyconfig.Config, error)

ConfigLoader loads the effective configuration for a workspace root.

type DeletionIntent

type DeletionIntent struct {
	Workspace   Workspace
	RequestedAt time.Time
}

DeletionIntent preserves the registration snapshot required to finish external cleanup.

type EnclosingRootCandidate

type EnclosingRootCandidate struct {
	ID   string
	Root string
}

EnclosingRootCandidate identifies a canonical workspace root for nearest-root selection.

func SelectNearestEnclosingRoot

func SelectNearestEnclosingRoot(
	canonicalPath string,
	candidates []EnclosingRootCandidate,
) (EnclosingRootCandidate, bool)

SelectNearestEnclosingRoot returns the deepest enclosing root, breaking ties by ID.

type Identity

type Identity struct {
	WorkspaceID        string
	CreatedAt          time.Time
	RealpathAtCreation string
	Path               string
}

Identity is the stable workspace identity stored in <workspace>/.compozy/workspace.toml.

func EnsureIdentity

func EnsureIdentity(ctx context.Context, rootDir string) (Identity, error)

EnsureIdentity loads or creates <workspace>/.compozy/workspace.toml.

type Option

type Option func(*resolverOptions)

Option customizes a Resolver instance.

func WithCacheTTL

func WithCacheTTL(ttl time.Duration) Option

WithCacheTTL overrides the idle cache eviction window.

func WithChangeHook

func WithChangeHook(hook ChangeHook) Option

WithChangeHook installs a post-mutation hook for derived runtime projections.

func WithConfigLoader

func WithConfigLoader(loader ConfigLoader) Option

WithConfigLoader overrides the configuration loader used during workspace resolution.

func WithHomePaths

func WithHomePaths(homePaths compozyconfig.HomePaths) Option

WithHomePaths overrides the global Compozy home layout used for agent and skill discovery.

func WithIDGenerator

func WithIDGenerator(generator idGenerator) Option

WithIDGenerator overrides workspace ID generation; errors abort registration.

func WithLogger

func WithLogger(logger *slog.Logger) Option

WithLogger overrides the structured logger used for resolver diagnostics.

func WithOperatorHomeDir

func WithOperatorHomeDir(operatorHomeDir string) Option

WithOperatorHomeDir overrides the canonical operator home rejected by workspace registration.

func WithProfileAvailabilityChecker

func WithProfileAvailabilityChecker(checker ProfileAvailabilityChecker) Option

WithProfileAvailabilityChecker installs the lifecycle availability gate used before profile-aware discovery reads any profile-owned resource roots.

func WithProfileConfigLoader

func WithProfileConfigLoader(loader ProfileConfigLoader) Option

WithProfileConfigLoader overrides profile-aware config loading during workspace resolution.

func WithSnapshotTTL

func WithSnapshotTTL(ttl time.Duration) Option

WithSnapshotTTL bounds discovery staleness; zero retains synchronous filesystem validation.

type ProfileAvailabilityChecker

type ProfileAvailabilityChecker interface {
	EnsureAvailableName(context.Context, string) error
	AvailableProfileID(context.Context, string) (string, error)
}

ProfileAvailabilityChecker rejects profile-owned resource discovery while a lifecycle operation has exclusive ownership of that profile.

type ProfileConfigLoader

type ProfileConfigLoader func(rootDir string, profileName string) (compozyconfig.Config, error)

ProfileConfigLoader loads the five-layer effective config for one active profile.

type ProfileDeclaration

type ProfileDeclaration struct {
	Name string
	Path string
}

ProfileDeclaration identifies committed workspace content bound by profile name.

type ProfileRegistrationResolver

type ProfileRegistrationResolver interface {
	ProfileRuntimeResolver
	ResolveOrRegisterForProfile(ctx context.Context, path string, profileName string) (ResolvedWorkspace, error)
}

ProfileRegistrationResolver resolves or registers a workspace path while applying profile-bound resource layers in the same resolution pass.

type ProfileRuntimeResolver

type ProfileRuntimeResolver interface {
	RuntimeResolver
	ResolveForProfile(ctx context.Context, idOrPath string, profileName string) (ResolvedWorkspace, error)
}

ProfileRuntimeResolver resolves a workspace with profile-bound resource layers.

type Ref

type Ref struct {
	Kind  RefKind
	Value string
}

func ParseRef

func ParseRef(raw string) Ref

type RefKind

type RefKind string
const (
	RefWorkspace RefKind = "workspace"
	RefUser      RefKind = "user"
)

type RegisterOptions

type RegisterOptions struct {
	RootDir        string
	Name           string
	AdditionalDirs []string
	DefaultAgent   string
}

RegisterOptions describes a workspace registration request.

type ResolvedAgentConfig

type ResolvedAgentConfig struct {
	Workspace
	WorkspaceID string
	ProfileID   string
	ProfileName string
	Config      compozyconfig.Config
	Agents      []compozyconfig.AgentDef
}

ResolvedAgentConfig contains workspace identity and the configuration used to resolve agents.

type ResolvedWorkspace

type ResolvedWorkspace struct {
	Scope ScopeKind
	Workspace
	WorkspaceID         string
	ProfileID           string
	ProfileName         string
	ProfileRoot         string
	ProfileDeclarations []ProfileDeclaration
	Config              compozyconfig.Config
	Agents              []compozyconfig.AgentDef
	AgentDiagnostics    []AgentDiagnostic
	Skills              []SkillPath
	ResolvedAt          time.Time
}

ResolvedWorkspace is the computed workspace snapshot returned by a resolver.

type Resolver

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

Resolver resolves persisted workspaces into runtime workspace snapshots.

func NewResolver

func NewResolver(store Store, opts ...Option) (*Resolver, error)

NewResolver constructs a workspace resolver backed by the supplied store.

func (*Resolver) DrainUnregisters

func (r *Resolver) DrainUnregisters(ctx context.Context) error

DrainUnregisters closes admission and retries every owned workspace finalization.

func (*Resolver) Get

func (r *Resolver) Get(ctx context.Context, idOrNameOrPath string) (Workspace, error)

Get resolves a persisted workspace registration without computing a full snapshot.

func (*Resolver) HoldSnapshots

func (r *Resolver) HoldSnapshots()

HoldSnapshots keeps every validated discovery snapshot fresh past the snapshot TTL until ReleaseSnapshots runs, so a bounded phase such as daemon boot discovers each workspace once instead of once per TTL window. Config inputs are still compared on every read and explicit invalidation still drops snapshots; only the age bound is suspended.

func (*Resolver) Invalidate

func (r *Resolver) Invalidate(workspaceID string)

Invalidate deletes one workspace snapshot from the in-memory cache.

func (*Resolver) InvalidateAll

func (r *Resolver) InvalidateAll()

InvalidateAll clears every cached runtime snapshot after a global dependency changes.

func (*Resolver) List

func (r *Resolver) List(ctx context.Context) ([]Workspace, error)

List returns every registered workspace in stable store order.

func (*Resolver) Register

func (r *Resolver) Register(ctx context.Context, opts RegisterOptions) (Workspace, error)

Register persists a workspace registration hint and eagerly resolves it.

func (*Resolver) ReleaseSnapshots

func (r *Resolver) ReleaseSnapshots()

ReleaseSnapshots restores the snapshot TTL. Snapshots older than the TTL are revalidated by their next read.

func (*Resolver) Resolve

func (r *Resolver) Resolve(ctx context.Context, idOrNameOrPath string) (resolved ResolvedWorkspace, err error)

Resolve loads and caches the effective runtime snapshot for a workspace.

func (*Resolver) ResolveAgentConfig

func (r *Resolver) ResolveAgentConfig(ctx context.Context, ref, profileName string) (ResolvedAgentConfig, error)

ResolveAgentConfig resolves current configuration and agents without discovering skills.

func (*Resolver) ResolveForProfile

func (r *Resolver) ResolveForProfile(
	ctx context.Context,
	idOrNameOrPath string,
	profileName string,
) (resolved ResolvedWorkspace, err error)

ResolveForProfile loads the workspace with personal and project profile roots.

func (*Resolver) ResolveOrRegister

func (r *Resolver) ResolveOrRegister(ctx context.Context, path string) (ResolvedWorkspace, error)

ResolveOrRegister resolves an existing workspace by canonical path or auto-registers it.

func (*Resolver) ResolveOrRegisterForProfile

func (r *Resolver) ResolveOrRegisterForProfile(
	ctx context.Context,
	path string,
	profileName string,
) (ResolvedWorkspace, error)

ResolveOrRegisterForProfile resolves or registers a workspace path and loads its profile-bound resource layers without a second public resolution.

func (*Resolver) ResolveRegistration

func (r *Resolver) ResolveRegistration(ctx context.Context, idOrNameOrPath string) (Workspace, error)

ResolveRegistration validates the current workspace root and identity without loading runtime resources.

func (*Resolver) ResolveUser

func (r *Resolver) ResolveUser(ctx context.Context, profileID string) (ResolvedWorkspace, error)

func (*Resolver) ResumeUnregisters

func (r *Resolver) ResumeUnregisters(ctx context.Context) error

ResumeUnregisters completes durable workspace deletions before runtime traffic is accepted.

func (*Resolver) SetArchived

func (r *Resolver) SetArchived(ctx context.Context, ref string, archived bool) (Workspace, error)

func (*Resolver) SetUnregisterPreparer

func (r *Resolver) SetUnregisterPreparer(preparer UnregisterPreparer)

SetUnregisterPreparer installs the late-bound runtime owner for workspace state that lives outside the workspace store, such as session directories.

func (*Resolver) SkillsConfig

func (r *Resolver) SkillsConfig(ws Workspace, profileName string) (compozyconfig.SkillsConfig, error)

SkillsConfig returns the effective skills settings for one registered workspace and profile. It reloads configuration only when a file the loader reads changed since the cached load, so periodic callers such as the skills watcher stat those files instead of parsing them every tick.

func (*Resolver) Unregister

func (r *Resolver) Unregister(ctx context.Context, id string) error

Unregister removes a persisted workspace registration and its cached snapshot.

func (*Resolver) Update

func (r *Resolver) Update(ctx context.Context, id string, opts UpdateOptions) error

Update mutates an existing workspace registration.

type RuntimeResolver

type RuntimeResolver interface {
	Resolve(ctx context.Context, idOrPath string) (ResolvedWorkspace, error)
	ResolveOrRegister(ctx context.Context, path string) (ResolvedWorkspace, error)
}

RuntimeResolver resolves persisted workspaces into computed runtime snapshots.

type ScopeKind

type ScopeKind string
const (
	ScopeWorkspace ScopeKind = "workspace"
	ScopeUser      ScopeKind = "user"
)

type SkillPath

type SkillPath struct {
	Name   string
	Dir    string
	Source string
}

SkillPath identifies a discovered skill directory and its origin.

type Store

type Store interface {
	SetWorkspaceArchived(ctx context.Context, id string, archived bool) (Workspace, error)
	InsertWorkspace(ctx context.Context, ws Workspace) error
	UpdateWorkspace(ctx context.Context, ws Workspace) error
	DeleteWorkspace(ctx context.Context, id string) error
	StageWorkspaceDeletion(ctx context.Context, id string) error
	GetWorkspaceDeletionIntent(ctx context.Context, id string) (DeletionIntent, error)
	ListWorkspaceDeletionIntents(ctx context.Context) ([]DeletionIntent, error)
	CompleteWorkspaceDeletion(ctx context.Context, id string) error
	GetWorkspace(ctx context.Context, id string) (Workspace, error)
	GetWorkspaceByPath(ctx context.Context, rootDir string) (Workspace, error)
	GetWorkspaceByName(ctx context.Context, name string) (Workspace, error)
	ListWorkspaces(ctx context.Context) ([]Workspace, error)
}

Store persists and looks up registered workspaces.

type UnregisterPreparation

type UnregisterPreparation interface {
	BeforeDelete(ctx context.Context) error
	Commit(ctx context.Context) error
	Rollback(ctx context.Context) error
}

UnregisterPreparation owns reversible external state around deletion of a workspace row and its database-owned children.

type UnregisterPreparer

type UnregisterPreparer func(ctx context.Context, workspace Workspace) (UnregisterPreparation, error)

UnregisterPreparer stages external state for one workspace deletion.

type UpdateOptions

type UpdateOptions struct {
	Name           *string
	AdditionalDirs *[]string
	DefaultAgent   *string
}

UpdateOptions describes mutable workspace registration fields.

type UserRuntimeResolver

type UserRuntimeResolver interface {
	ResolveUser(context.Context, string) (ResolvedWorkspace, error)
}

type Workspace

type Workspace struct {
	ID             string
	RootDir        string
	AdditionalDirs []string
	Name           string
	DefaultAgent   string
	CreatedAt      time.Time
	UpdatedAt      time.Time
	ArchivedAt     *time.Time
	RootMissing    bool // Derived from the filesystem; never persisted.
}

Workspace is the persisted workspace registration stored in the global database.

Jump to

Keyboard shortcuts

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