Compare commits
2 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 22c035984e | |||
| d35037df01 |
@@ -1,119 +0,0 @@
|
||||
"""add profile resolver fields to config profiles and mounts
|
||||
|
||||
Revision ID: 0014_add_profile_resolver_fields
|
||||
Revises: 0013_add_config_profiles
|
||||
Create Date: 2026-05-24 14:00:00.000000
|
||||
|
||||
"""
|
||||
from typing import Sequence, Union
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
from sqlalchemy.dialects import postgresql
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision: str = "0014_add_profile_resolver_fields"
|
||||
down_revision: Union[str, None] = "0013_add_config_profiles"
|
||||
branch_labels: Union[str, Sequence[str], None] = None
|
||||
depends_on: Union[str, Sequence[str], None] = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
# Add fields to config_profiles
|
||||
op.add_column(
|
||||
"config_profiles",
|
||||
sa.Column("project_id", postgresql.UUID(as_uuid=True), nullable=True),
|
||||
)
|
||||
op.add_column(
|
||||
"config_profiles",
|
||||
sa.Column("tool_type_id", postgresql.UUID(as_uuid=True), nullable=True),
|
||||
)
|
||||
op.add_column(
|
||||
"config_profiles",
|
||||
sa.Column("environment_variables", sa.JSON(), nullable=True),
|
||||
)
|
||||
op.add_column(
|
||||
"config_profiles",
|
||||
sa.Column("start_command", sa.Text(), nullable=True),
|
||||
)
|
||||
op.add_column(
|
||||
"config_profiles",
|
||||
sa.Column("working_directory", sa.Text(), nullable=True),
|
||||
)
|
||||
op.add_column(
|
||||
"config_profiles",
|
||||
sa.Column("port", sa.Integer(), nullable=True),
|
||||
)
|
||||
op.add_column(
|
||||
"config_profiles",
|
||||
sa.Column("is_default", sa.Boolean(), nullable=False, server_default="false"),
|
||||
)
|
||||
|
||||
# Add foreign keys for project and tool_type
|
||||
op.create_foreign_key(
|
||||
"fk_config_profiles_project",
|
||||
"config_profiles",
|
||||
"projects",
|
||||
["project_id"],
|
||||
["id"],
|
||||
ondelete="CASCADE",
|
||||
)
|
||||
op.create_foreign_key(
|
||||
"fk_config_profiles_tool_type",
|
||||
"config_profiles",
|
||||
"tool_types",
|
||||
["tool_type_id"],
|
||||
["id"],
|
||||
ondelete="CASCADE",
|
||||
)
|
||||
|
||||
# Create indices
|
||||
op.create_index("idx_config_profiles_project", "config_profiles", ["project_id"])
|
||||
op.create_index("idx_config_profiles_tool_type", "config_profiles", ["tool_type_id"])
|
||||
|
||||
# Alter config_mounts: rename mount_path to target_path, add mode, change content to files JSON
|
||||
op.alter_column("config_mounts", "mount_path", new_column_name="target_path")
|
||||
op.add_column(
|
||||
"config_mounts",
|
||||
sa.Column("mode", sa.String(length=10), nullable=False, server_default="rw"),
|
||||
)
|
||||
op.add_column(
|
||||
"config_mounts",
|
||||
sa.Column("files", sa.JSON(), nullable=True),
|
||||
)
|
||||
# Drop the source_profile foreign key if it exists
|
||||
op.drop_constraint(
|
||||
"config_mounts_source_profile_id_fkey",
|
||||
"config_mounts",
|
||||
type_="foreignkey",
|
||||
)
|
||||
op.drop_column("config_mounts", "content")
|
||||
op.drop_column("config_mounts", "source_profile_id")
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
# Restore config_mounts
|
||||
op.add_column(
|
||||
"config_mounts",
|
||||
sa.Column("source_profile_id", postgresql.UUID(as_uuid=True), nullable=True),
|
||||
)
|
||||
op.add_column(
|
||||
"config_mounts",
|
||||
sa.Column("content", sa.Text(), nullable=True),
|
||||
)
|
||||
op.drop_column("config_mounts", "files")
|
||||
op.drop_column("config_mounts", "mode")
|
||||
op.alter_column("config_mounts", "target_path", new_column_name="mount_path")
|
||||
|
||||
# Restore config_profiles
|
||||
op.drop_index("idx_config_profiles_tool_type", table_name="config_profiles")
|
||||
op.drop_index("idx_config_profiles_project", table_name="config_profiles")
|
||||
op.drop_constraint("fk_config_profiles_tool_type", "config_profiles", type_="foreignkey")
|
||||
op.drop_constraint("fk_config_profiles_project", "config_profiles", type_="foreignkey")
|
||||
op.drop_column("config_profiles", "is_default")
|
||||
op.drop_column("config_profiles", "port")
|
||||
op.drop_column("config_profiles", "working_directory")
|
||||
op.drop_column("config_profiles", "start_command")
|
||||
op.drop_column("config_profiles", "environment_variables")
|
||||
op.drop_column("config_profiles", "tool_type_id")
|
||||
op.drop_column("config_profiles", "project_id")
|
||||
@@ -18,7 +18,6 @@ from src.auth.dependencies import get_current_user_id
|
||||
from src.auth.dependencies import get_db_session
|
||||
from src.models.git_repository import GitRepository
|
||||
from src.models.project import Project
|
||||
from src.models.config_profile import ConfigProfile
|
||||
from src.models.tool_config import ToolConfig
|
||||
from src.models.tool_instance import ToolInstance
|
||||
from src.models.tool_type import ToolType
|
||||
@@ -42,7 +41,6 @@ from src.services.docker import (
|
||||
write_config_folder_files,
|
||||
)
|
||||
from src.services.docker_build import build_image
|
||||
from src.services.profile_resolver import resolve_profile
|
||||
from src.services.readiness_probe import execute_probe
|
||||
|
||||
router = APIRouter(prefix="/projects", tags=["tool-instances"])
|
||||
@@ -55,7 +53,6 @@ class CreateInstanceRequest(BaseModel):
|
||||
|
||||
tool_type_id: str = Field(description="UUID of the tool type to instantiate")
|
||||
display_name: str | None = Field(default=None, description="Optional display name for the instance")
|
||||
config_profile_id: str | None = Field(default=None, description="Optional config profile ID to apply to the instance")
|
||||
|
||||
|
||||
def _modify_compose_file(
|
||||
@@ -110,68 +107,6 @@ def _modify_compose_file(
|
||||
compose_file.write_text(yaml.dump(compose_data, default_flow_style=False))
|
||||
|
||||
|
||||
async def _apply_resolved_profile(
|
||||
profile: ConfigProfile,
|
||||
instance_dir: str,
|
||||
env_vars: dict[str, str],
|
||||
port_override: int | None,
|
||||
start_command: str | None,
|
||||
working_directory: str | None,
|
||||
extra_volumes: list[dict],
|
||||
) -> tuple[dict[str, str], int | None, str | None, str | None, list[dict]]:
|
||||
"""Resolve a profile and apply its output to instance configuration.
|
||||
|
||||
Merges resolved profile env vars (profile wins), applies runtime hints,
|
||||
stages mount files to the instance directory, and adds Docker bind mounts.
|
||||
|
||||
Args:
|
||||
profile: The config profile to resolve and apply.
|
||||
instance_dir: Path to the instance directory.
|
||||
env_vars: Current environment variables dict (will be updated).
|
||||
port_override: Current port override (may be updated).
|
||||
start_command: Current start command (may be updated).
|
||||
working_directory: Current working directory (may be updated).
|
||||
extra_volumes: Current extra volumes list (will be extended).
|
||||
|
||||
Returns:
|
||||
Updated (env_vars, port_override, start_command, working_directory, extra_volumes).
|
||||
"""
|
||||
from pathlib import Path
|
||||
|
||||
resolved = resolve_profile(profile)
|
||||
|
||||
# Merge env vars from resolved profile (profile wins over tool configs)
|
||||
if resolved.environment_variables:
|
||||
env_vars.update(resolved.environment_variables)
|
||||
|
||||
# Apply runtime hints
|
||||
if resolved.runtime_hints.start_command is not None:
|
||||
start_command = resolved.runtime_hints.start_command
|
||||
if resolved.runtime_hints.working_directory is not None:
|
||||
working_directory = resolved.runtime_hints.working_directory
|
||||
if resolved.runtime_hints.port is not None:
|
||||
port_override = resolved.runtime_hints.port
|
||||
|
||||
# Stage mount files and add volume mounts
|
||||
for target_path, mount in resolved.mounts.items():
|
||||
safe_name = target_path.strip("/").replace("/", "_")
|
||||
mount_dir = Path(instance_dir) / "mounts" / safe_name
|
||||
mount_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
for rel_path, content in mount.files.items():
|
||||
file_path = mount_dir / rel_path
|
||||
file_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
file_path.write_text(content)
|
||||
|
||||
extra_volumes.append({
|
||||
"source": str(mount_dir),
|
||||
"target": target_path,
|
||||
"type": mount.mode,
|
||||
})
|
||||
|
||||
return env_vars, port_override, start_command, working_directory, extra_volumes
|
||||
|
||||
|
||||
async def _get_user(session: AsyncSession, user_id: uuid.UUID) -> User:
|
||||
"""Fetch a user by ID or raise 404 if not found."""
|
||||
user = await session.get(User, user_id)
|
||||
@@ -254,29 +189,6 @@ async def create_instance(
|
||||
status_code=status.HTTP_404_NOT_FOUND, detail="tool type not found"
|
||||
)
|
||||
|
||||
# Validate config_profile_id if provided
|
||||
selected_profile_id: uuid.UUID | None = None
|
||||
if data.config_profile_id:
|
||||
try:
|
||||
selected_profile_id = uuid.UUID(data.config_profile_id)
|
||||
except ValueError:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="invalid config_profile_id format",
|
||||
)
|
||||
|
||||
config_profile = await session.get(ConfigProfile, selected_profile_id)
|
||||
if config_profile is None:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail="config profile not found",
|
||||
)
|
||||
if config_profile.user_id != user_id:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="config profile does not belong to user",
|
||||
)
|
||||
|
||||
try:
|
||||
# Generate unique name
|
||||
instance_name = f"{tool_type.name}-{repo.name}-{uuid.uuid4().hex[:8]}"
|
||||
@@ -350,7 +262,6 @@ services:
|
||||
status="pending",
|
||||
compose_path=compose_path,
|
||||
port=tool_port,
|
||||
selected_profile_id=selected_profile_id,
|
||||
)
|
||||
session.add(instance)
|
||||
await session.commit()
|
||||
@@ -362,7 +273,6 @@ services:
|
||||
"display_name": instance.display_name,
|
||||
"tool_type_id": str(instance.tool_type_id),
|
||||
"status": instance.status,
|
||||
"config_profile_id": str(instance.selected_profile_id) if instance.selected_profile_id else None,
|
||||
"created_at": instance.created_at.isoformat(),
|
||||
}
|
||||
except Exception as exc:
|
||||
@@ -425,7 +335,6 @@ async def list_instances(
|
||||
"status": i.status,
|
||||
"url": i.url,
|
||||
"port": i.port,
|
||||
"config_profile_id": str(i.selected_profile_id) if i.selected_profile_id else None,
|
||||
"created_at": i.created_at.isoformat(),
|
||||
})
|
||||
|
||||
@@ -486,7 +395,6 @@ async def get_instance(
|
||||
"compose_path": instance.compose_path,
|
||||
"url": instance.url,
|
||||
"port": instance.port,
|
||||
"config_profile_id": str(instance.selected_profile_id) if instance.selected_profile_id else None,
|
||||
"last_started_at": instance.last_started_at.isoformat() if instance.last_started_at else None,
|
||||
"last_stopped_at": instance.last_stopped_at.isoformat() if instance.last_stopped_at else None,
|
||||
"created_at": instance.created_at.isoformat(),
|
||||
@@ -544,7 +452,6 @@ async def start_instance(
|
||||
extra_env_vars = {}
|
||||
extra_volumes = []
|
||||
|
||||
# Fetch all matching configs for this tool type
|
||||
config_query = select(ToolConfig).where(
|
||||
ToolConfig.user_id == user_id,
|
||||
ToolConfig.tool_type_id == instance.tool_type_id,
|
||||
@@ -577,31 +484,6 @@ async def start_instance(
|
||||
# Merge extra env vars
|
||||
env_vars.update(extra_env_vars)
|
||||
|
||||
# Apply resolved profile output if a profile is selected
|
||||
if instance.selected_profile_id:
|
||||
selected_profile = await session.get(ConfigProfile, instance.selected_profile_id)
|
||||
if selected_profile is None:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail="config profile not found",
|
||||
)
|
||||
if selected_profile.user_id != user_id:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="config profile does not belong to user",
|
||||
)
|
||||
instance_dir = os.path.dirname(instance.compose_path)
|
||||
env_vars, port_override, start_command, working_directory, extra_volumes = await _apply_resolved_profile(
|
||||
selected_profile,
|
||||
instance_dir,
|
||||
env_vars,
|
||||
port_override,
|
||||
start_command,
|
||||
working_directory,
|
||||
extra_volumes,
|
||||
)
|
||||
logger.info("Applied resolved profile %s for instance %s", selected_profile.name, instance.id)
|
||||
|
||||
# Fetch active config folders for this user
|
||||
folder_query = select(ConfigFolder).where(
|
||||
ConfigFolder.user_id == user_id,
|
||||
@@ -873,105 +755,8 @@ async def restart_instance(
|
||||
logger.warning("Failed to stop old tunnel for instance %s: %s", instance.id, exc)
|
||||
|
||||
if instance.compose_path and os.path.exists(instance.compose_path):
|
||||
# Re-apply configuration using stored profile instead of current defaults
|
||||
env_vars = {}
|
||||
config_files = {}
|
||||
port_override = None
|
||||
start_command = None
|
||||
working_directory = None
|
||||
extra_env_vars = {}
|
||||
extra_volumes = []
|
||||
|
||||
# Fetch all matching configs for this tool type
|
||||
config_query = select(ToolConfig).where(
|
||||
ToolConfig.user_id == user_id,
|
||||
ToolConfig.tool_type_id == instance.tool_type_id,
|
||||
).where(
|
||||
(ToolConfig.project_id == project_id) | (ToolConfig.project_id.is_(None))
|
||||
)
|
||||
|
||||
config_result = await session.execute(config_query)
|
||||
configs = config_result.scalars().all()
|
||||
logger.info("Found %d tool configs for restart of instance %s", len(configs), instance.id)
|
||||
|
||||
for config in configs:
|
||||
if config.config_type == "env":
|
||||
env_vars[config.key] = config.value
|
||||
elif config.config_type == "file" and config.file_path:
|
||||
config_files[config.file_path] = config.value
|
||||
|
||||
if config.port_override:
|
||||
port_override = config.port_override
|
||||
if config.start_command:
|
||||
start_command = config.start_command
|
||||
if config.working_directory:
|
||||
working_directory = config.working_directory
|
||||
if config.environment_variables:
|
||||
extra_env_vars.update(config.environment_variables)
|
||||
if config.volumes:
|
||||
extra_volumes.extend(config.volumes)
|
||||
|
||||
# Merge extra env vars
|
||||
env_vars.update(extra_env_vars)
|
||||
|
||||
# Apply stored profile on restart instead of current defaults
|
||||
if instance.selected_profile_id:
|
||||
stored_profile = await session.get(ConfigProfile, instance.selected_profile_id)
|
||||
if stored_profile is None:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail="config profile not found",
|
||||
)
|
||||
if stored_profile.user_id != user_id:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="config profile does not belong to user",
|
||||
)
|
||||
instance_dir = os.path.dirname(instance.compose_path)
|
||||
env_vars, port_override, start_command, working_directory, extra_volumes = await _apply_resolved_profile(
|
||||
stored_profile,
|
||||
instance_dir,
|
||||
env_vars,
|
||||
port_override,
|
||||
start_command,
|
||||
working_directory,
|
||||
extra_volumes,
|
||||
)
|
||||
logger.info("Re-applied stored profile %s for restart of instance %s", stored_profile.name, instance.id)
|
||||
|
||||
# Fetch active config folders for this user
|
||||
folder_query = select(ConfigFolder).where(
|
||||
ConfigFolder.user_id == user_id,
|
||||
ConfigFolder.is_active == True,
|
||||
)
|
||||
folder_result = await session.execute(folder_query)
|
||||
config_folders = folder_result.scalars().all()
|
||||
|
||||
# Write env file and config files
|
||||
instance_dir = os.path.dirname(instance.compose_path)
|
||||
env_file_path = None
|
||||
|
||||
if env_vars:
|
||||
env_file_path = write_env_file(instance_dir, env_vars)
|
||||
logger.info("Wrote env file for restart of instance %s: %s", instance.id, env_file_path)
|
||||
|
||||
if config_files:
|
||||
write_config_files(instance_dir, config_files)
|
||||
logger.info("Wrote %d config files for restart of instance %s", len(config_files), instance.id)
|
||||
|
||||
# Write config folder files
|
||||
if config_folders:
|
||||
folder_volumes = write_config_folder_files(instance_dir, config_folders, str(project_id))
|
||||
extra_volumes.extend(folder_volumes)
|
||||
logger.info("Wrote config folders with %d volume mounts for restart of instance %s", len(folder_volumes), instance.id)
|
||||
|
||||
# Modify compose file if needed
|
||||
if port_override or start_command or working_directory or extra_volumes:
|
||||
_modify_compose_file(instance.compose_path, port_override, start_command, working_directory, extra_volumes)
|
||||
logger.info("Modified compose file for restart of instance %s", instance.id)
|
||||
|
||||
returncode, stdout, stderr = execute_compose_command(
|
||||
instance.compose_path, "restart", env_file=env_file_path
|
||||
instance.compose_path, "restart"
|
||||
)
|
||||
|
||||
if returncode == 0:
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import uuid
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from sqlalchemy import ForeignKey, Integer, JSON, String
|
||||
from sqlalchemy import ForeignKey, Integer, String, Text
|
||||
from sqlalchemy import Uuid as UUID
|
||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
|
||||
@@ -17,10 +17,10 @@ class ConfigMount(UUIDPrimaryKeyMixin, TimestampMixin, Base):
|
||||
profile_id: Mapped[uuid.UUID] = mapped_column(
|
||||
UUID(), ForeignKey("config_profiles.id", ondelete="CASCADE"), nullable=False
|
||||
)
|
||||
target_path: Mapped[str] = mapped_column(String(1024), nullable=False)
|
||||
mode: Mapped[str] = mapped_column(String(10), nullable=False, default="rw")
|
||||
files: Mapped[dict[str, str] | None] = mapped_column(
|
||||
JSON, default=dict, nullable=True
|
||||
mount_path: Mapped[str] = mapped_column(String(1024), nullable=False)
|
||||
content: Mapped[str | None] = mapped_column(Text, nullable=True)
|
||||
source_profile_id: Mapped[uuid.UUID | None] = mapped_column(
|
||||
UUID(), ForeignKey("config_profiles.id", ondelete="SET NULL"), nullable=True
|
||||
)
|
||||
order_index: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
|
||||
|
||||
@@ -29,3 +29,7 @@ class ConfigMount(UUIDPrimaryKeyMixin, TimestampMixin, Base):
|
||||
foreign_keys=[profile_id],
|
||||
back_populates="mounts",
|
||||
)
|
||||
source_profile: Mapped["ConfigProfile | None"] = relationship(
|
||||
"ConfigProfile",
|
||||
foreign_keys=[source_profile_id],
|
||||
)
|
||||
|
||||
@@ -1,17 +1,13 @@
|
||||
import uuid
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from sqlalchemy import ForeignKey, Integer, JSON, String, Text, UniqueConstraint
|
||||
from sqlalchemy import ForeignKey, String, Text, UniqueConstraint
|
||||
from sqlalchemy import Uuid as UUID
|
||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
|
||||
from src.models.base import Base, TimestampMixin, UUIDPrimaryKeyMixin
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from src.models.config_include import ConfigInclude
|
||||
from src.models.config_mount import ConfigMount
|
||||
from src.models.project import Project
|
||||
from src.models.tool_type import ToolType
|
||||
from src.models.user import User
|
||||
|
||||
|
||||
@@ -24,25 +20,10 @@ class ConfigProfile(UUIDPrimaryKeyMixin, TimestampMixin, Base):
|
||||
user_id: Mapped[uuid.UUID] = mapped_column(
|
||||
UUID(), ForeignKey("users.id", ondelete="CASCADE"), nullable=False
|
||||
)
|
||||
project_id: Mapped[uuid.UUID | None] = mapped_column(
|
||||
UUID(), ForeignKey("projects.id", ondelete="CASCADE"), nullable=True
|
||||
)
|
||||
tool_type_id: Mapped[uuid.UUID | None] = mapped_column(
|
||||
UUID(), ForeignKey("tool_types.id", ondelete="CASCADE"), nullable=True
|
||||
)
|
||||
name: Mapped[str] = mapped_column(String(255), nullable=False)
|
||||
description: Mapped[str | None] = mapped_column(Text, nullable=True)
|
||||
environment_variables: Mapped[dict[str, str] | None] = mapped_column(
|
||||
JSON, default=dict, nullable=True
|
||||
)
|
||||
start_command: Mapped[str | None] = mapped_column(Text, nullable=True)
|
||||
working_directory: Mapped[str | None] = mapped_column(Text, nullable=True)
|
||||
port: Mapped[int | None] = mapped_column(Integer, nullable=True)
|
||||
is_default: Mapped[bool] = mapped_column(default=False, nullable=False)
|
||||
|
||||
user: Mapped["User"] = relationship()
|
||||
project: Mapped["Project | None"] = relationship()
|
||||
tool_type: Mapped["ToolType | None"] = relationship()
|
||||
includes: Mapped[list["ConfigInclude"]] = relationship(
|
||||
"ConfigInclude",
|
||||
foreign_keys="ConfigInclude.profile_id",
|
||||
|
||||
@@ -1,251 +0,0 @@
|
||||
"""Profile resolver service for recursive ordered include resolution.
|
||||
|
||||
Provides deterministic merge rules, save-independent cycle protection,
|
||||
and resolved output structures for env vars, runtime hints, mounts,
|
||||
file trees, and override metadata.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
from dataclasses import dataclass, field
|
||||
|
||||
from src.models.config_include import ConfigInclude
|
||||
from src.models.config_mount import ConfigMount
|
||||
from src.models.config_profile import ConfigProfile
|
||||
|
||||
|
||||
@dataclass
|
||||
class ResolvedMount:
|
||||
"""A resolved mount with merged file tree and final mode."""
|
||||
|
||||
target_path: str
|
||||
mode: str # "ro" or "rw"
|
||||
files: dict[str, str] = field(default_factory=dict)
|
||||
"""Relative file paths to UTF-8 text content."""
|
||||
overridden_files: dict[str, list[str]] = field(default_factory=dict)
|
||||
"""Map of relative file path to list of profile names that contributed
|
||||
(latest is the winner)."""
|
||||
mode_overridden_by: str | None = None
|
||||
"""Name of the profile that set the final mode, if different from first."""
|
||||
|
||||
|
||||
@dataclass
|
||||
class ResolvedRuntimeHints:
|
||||
"""Resolved runtime hints from profile layers."""
|
||||
|
||||
start_command: str | None = None
|
||||
working_directory: str | None = None
|
||||
port: int | None = None
|
||||
overridden_hints: dict[str, str] = field(default_factory=dict)
|
||||
"""Map of hint key to profile name that provided the winning value."""
|
||||
|
||||
|
||||
@dataclass
|
||||
class ResolvedProfileOutput:
|
||||
"""Complete resolved output for a config profile."""
|
||||
|
||||
profile_id: uuid.UUID
|
||||
profile_name: str
|
||||
environment_variables: dict[str, str] = field(default_factory=dict)
|
||||
"""Final merged env vars (later layers win)."""
|
||||
env_var_sources: dict[str, list[str]] = field(default_factory=dict)
|
||||
"""Map of env var key to ordered list of contributing profile names
|
||||
(latest is the winner)."""
|
||||
runtime_hints: ResolvedRuntimeHints = field(
|
||||
default_factory=lambda: ResolvedRuntimeHints()
|
||||
)
|
||||
mounts: dict[str, ResolvedMount] = field(default_factory=dict)
|
||||
"""Map of target_path to ResolvedMount."""
|
||||
resolution_order: list[str] = field(default_factory=list)
|
||||
"""Ordered list of profile names as they were resolved."""
|
||||
cycle_detected: bool = False
|
||||
cycle_path: list[str] | None = None
|
||||
|
||||
|
||||
class ProfileResolutionError(Exception):
|
||||
"""Raised when profile resolution fails."""
|
||||
|
||||
pass
|
||||
|
||||
|
||||
class ProfileCycleError(ProfileResolutionError):
|
||||
"""Raised when a cycle is detected during profile resolution."""
|
||||
|
||||
def __init__(self, cycle_path: list[str]) -> None:
|
||||
self.cycle_path = cycle_path
|
||||
path_str = " -> ".join(cycle_path)
|
||||
super().__init__(f"Profile include cycle detected: {path_str}")
|
||||
|
||||
|
||||
def _merge_env_vars(
|
||||
current: dict[str, str],
|
||||
sources: dict[str, list[str]],
|
||||
profile: ConfigProfile,
|
||||
) -> None:
|
||||
"""Merge a profile's env vars into the current dict, tracking sources."""
|
||||
if not profile.environment_variables:
|
||||
return
|
||||
for key, value in profile.environment_variables.items():
|
||||
current[key] = value
|
||||
if key not in sources:
|
||||
sources[key] = []
|
||||
sources[key].append(profile.name)
|
||||
|
||||
|
||||
def _merge_runtime_hints(
|
||||
hints: ResolvedRuntimeHints,
|
||||
profile: ConfigProfile,
|
||||
) -> None:
|
||||
"""Merge a profile's runtime hints, tracking overrides."""
|
||||
if profile.start_command is not None:
|
||||
hints.start_command = profile.start_command
|
||||
hints.overridden_hints["start_command"] = profile.name
|
||||
if profile.working_directory is not None:
|
||||
hints.working_directory = profile.working_directory
|
||||
hints.overridden_hints["working_directory"] = profile.name
|
||||
if profile.port is not None:
|
||||
hints.port = profile.port
|
||||
hints.overridden_hints["port"] = profile.name
|
||||
|
||||
|
||||
def _merge_mounts(
|
||||
mounts: dict[str, ResolvedMount],
|
||||
profile_mounts: list[ConfigMount],
|
||||
profile: ConfigProfile,
|
||||
) -> None:
|
||||
"""Merge a profile's mounts into the current mounts dict."""
|
||||
for mount in profile_mounts:
|
||||
target = mount.target_path
|
||||
if target not in mounts:
|
||||
mounts[target] = ResolvedMount(
|
||||
target_path=target,
|
||||
mode=mount.mode,
|
||||
files={},
|
||||
overridden_files={},
|
||||
)
|
||||
resolved = mounts[target]
|
||||
|
||||
# Mode override: later wins
|
||||
if resolved.mode != mount.mode:
|
||||
resolved.mode = mount.mode
|
||||
resolved.mode_overridden_by = profile.name
|
||||
|
||||
# File tree merge: later wins for same relative path
|
||||
if mount.files:
|
||||
for rel_path, content in mount.files.items():
|
||||
if rel_path not in resolved.files:
|
||||
resolved.overridden_files[rel_path] = []
|
||||
else:
|
||||
if rel_path not in resolved.overridden_files:
|
||||
resolved.overridden_files[rel_path] = []
|
||||
resolved.overridden_files[rel_path].append(profile.name)
|
||||
resolved.files[rel_path] = content
|
||||
|
||||
|
||||
def _resolve_profile_recursive(
|
||||
profile: ConfigProfile,
|
||||
visited: set[uuid.UUID],
|
||||
path: list[str],
|
||||
resolution_order: list[str],
|
||||
env_vars: dict[str, str],
|
||||
env_var_sources: dict[str, list[str]],
|
||||
runtime_hints: ResolvedRuntimeHints,
|
||||
mounts: dict[str, ResolvedMount],
|
||||
) -> None:
|
||||
"""Recursively resolve a profile and its includes.
|
||||
|
||||
Args:
|
||||
profile: The profile to resolve
|
||||
visited: Set of already-resolved profile IDs to avoid duplicates
|
||||
path: Current recursion path for cycle detection
|
||||
resolution_order: Ordered list of profile names being resolved
|
||||
env_vars: Accumulated environment variables
|
||||
env_var_sources: Tracking of which profiles contributed each env var
|
||||
runtime_hints: Accumulated runtime hints
|
||||
mounts: Accumulated mounts
|
||||
|
||||
Raises:
|
||||
ProfileCycleError: If a cycle is detected
|
||||
"""
|
||||
if profile.name in path:
|
||||
# Cycle detected
|
||||
cycle_start = path.index(profile.name)
|
||||
cycle_path = path[cycle_start:] + [profile.name]
|
||||
raise ProfileCycleError(cycle_path)
|
||||
|
||||
if profile.id in visited:
|
||||
# Already resolved in another branch (diamond graph)
|
||||
return
|
||||
|
||||
visited.add(profile.id)
|
||||
path.append(profile.name)
|
||||
resolution_order.append(profile.name)
|
||||
|
||||
# Resolve includes first (in order)
|
||||
includes: list[ConfigInclude] = list(profile.includes)
|
||||
includes.sort(key=lambda inc: inc.order_index)
|
||||
for include in includes:
|
||||
included_profile = include.included_profile
|
||||
if included_profile is not None:
|
||||
_resolve_profile_recursive(
|
||||
included_profile,
|
||||
visited,
|
||||
path,
|
||||
resolution_order,
|
||||
env_vars,
|
||||
env_var_sources,
|
||||
runtime_hints,
|
||||
mounts,
|
||||
)
|
||||
|
||||
# Apply this profile's values (later layers win)
|
||||
_merge_env_vars(env_vars, env_var_sources, profile)
|
||||
_merge_runtime_hints(runtime_hints, profile)
|
||||
_merge_mounts(mounts, list(profile.mounts), profile)
|
||||
|
||||
path.pop()
|
||||
|
||||
|
||||
def resolve_profile(profile: ConfigProfile) -> ResolvedProfileOutput:
|
||||
"""Resolve a config profile with all its includes.
|
||||
|
||||
Processes included profiles in configured order, then applies the
|
||||
selected profile itself. Later layers override earlier layers.
|
||||
|
||||
Args:
|
||||
profile: The root profile to resolve
|
||||
|
||||
Returns:
|
||||
ResolvedProfileOutput with merged env vars, runtime hints, mounts,
|
||||
and override metadata
|
||||
|
||||
Raises:
|
||||
ProfileCycleError: If a cycle is detected in the include graph
|
||||
"""
|
||||
env_vars: dict[str, str] = {}
|
||||
env_var_sources: dict[str, list[str]] = {}
|
||||
runtime_hints = ResolvedRuntimeHints()
|
||||
mounts: dict[str, ResolvedMount] = {}
|
||||
resolution_order: list[str] = []
|
||||
|
||||
_resolve_profile_recursive(
|
||||
profile,
|
||||
set(),
|
||||
[],
|
||||
resolution_order,
|
||||
env_vars,
|
||||
env_var_sources,
|
||||
runtime_hints,
|
||||
mounts,
|
||||
)
|
||||
|
||||
return ResolvedProfileOutput(
|
||||
profile_id=profile.id,
|
||||
profile_name=profile.name,
|
||||
environment_variables=env_vars,
|
||||
env_var_sources=env_var_sources,
|
||||
runtime_hints=runtime_hints,
|
||||
mounts=mounts,
|
||||
resolution_order=resolution_order,
|
||||
)
|
||||
@@ -1,463 +0,0 @@
|
||||
"""Unit tests for the profile resolver service."""
|
||||
|
||||
import uuid
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
import pytest
|
||||
|
||||
from src.services.profile_resolver import (
|
||||
ProfileCycleError,
|
||||
ResolvedProfileOutput,
|
||||
resolve_profile,
|
||||
)
|
||||
|
||||
|
||||
def _make_profile(
|
||||
name: str,
|
||||
env_vars: dict[str, str] | None = None,
|
||||
start_command: str | None = None,
|
||||
working_directory: str | None = None,
|
||||
port: int | None = None,
|
||||
mounts: list[MagicMock] | None = None,
|
||||
includes: list[MagicMock] | None = None,
|
||||
) -> MagicMock:
|
||||
"""Create a mock ConfigProfile for testing."""
|
||||
profile = MagicMock()
|
||||
profile.id = uuid.uuid4()
|
||||
profile.name = name
|
||||
profile.environment_variables = env_vars or {}
|
||||
profile.start_command = start_command
|
||||
profile.working_directory = working_directory
|
||||
profile.port = port
|
||||
profile.mounts = mounts or []
|
||||
profile.includes = includes or []
|
||||
return profile
|
||||
|
||||
|
||||
def _make_include(included_profile: MagicMock, order_index: int = 0) -> MagicMock:
|
||||
"""Create a mock ConfigInclude for testing."""
|
||||
include = MagicMock()
|
||||
include.included_profile = included_profile
|
||||
include.order_index = order_index
|
||||
return include
|
||||
|
||||
|
||||
def _make_mount(
|
||||
target_path: str,
|
||||
mode: str = "rw",
|
||||
files: dict[str, str] | None = None,
|
||||
order_index: int = 0,
|
||||
) -> MagicMock:
|
||||
"""Create a mock ConfigMount for testing."""
|
||||
mount = MagicMock()
|
||||
mount.target_path = target_path
|
||||
mount.mode = mode
|
||||
mount.files = files or {}
|
||||
mount.order_index = order_index
|
||||
return mount
|
||||
|
||||
|
||||
class TestResolveProfileBasic:
|
||||
"""Tests for basic profile resolution without includes."""
|
||||
|
||||
def test_empty_profile(self) -> None:
|
||||
"""Resolving an empty profile returns empty output."""
|
||||
profile = _make_profile("empty")
|
||||
result = resolve_profile(profile)
|
||||
|
||||
assert isinstance(result, ResolvedProfileOutput)
|
||||
assert result.profile_name == "empty"
|
||||
assert result.environment_variables == {}
|
||||
assert result.runtime_hints.start_command is None
|
||||
assert result.runtime_hints.working_directory is None
|
||||
assert result.runtime_hints.port is None
|
||||
assert result.mounts == {}
|
||||
assert result.resolution_order == ["empty"]
|
||||
|
||||
def test_env_vars_only(self) -> None:
|
||||
"""Profile with env vars resolves correctly."""
|
||||
profile = _make_profile(
|
||||
"env-only",
|
||||
env_vars={"FOO": "bar", "BAZ": "qux"},
|
||||
)
|
||||
result = resolve_profile(profile)
|
||||
|
||||
assert result.environment_variables == {"FOO": "bar", "BAZ": "qux"}
|
||||
assert result.env_var_sources == {
|
||||
"FOO": ["env-only"],
|
||||
"BAZ": ["env-only"],
|
||||
}
|
||||
|
||||
def test_runtime_hints_only(self) -> None:
|
||||
"""Profile with runtime hints resolves correctly."""
|
||||
profile = _make_profile(
|
||||
"hints-only",
|
||||
start_command="python app.py",
|
||||
working_directory="/app",
|
||||
port=8080,
|
||||
)
|
||||
result = resolve_profile(profile)
|
||||
|
||||
assert result.runtime_hints.start_command == "python app.py"
|
||||
assert result.runtime_hints.working_directory == "/app"
|
||||
assert result.runtime_hints.port == 8080
|
||||
assert result.runtime_hints.overridden_hints == {
|
||||
"start_command": "hints-only",
|
||||
"working_directory": "hints-only",
|
||||
"port": "hints-only",
|
||||
}
|
||||
|
||||
def test_mounts_only(self) -> None:
|
||||
"""Profile with mounts resolves correctly."""
|
||||
profile = _make_profile(
|
||||
"mounts-only",
|
||||
mounts=[
|
||||
_make_mount(
|
||||
"/config",
|
||||
mode="ro",
|
||||
files={"settings.json": '{"key": "value"}'},
|
||||
),
|
||||
],
|
||||
)
|
||||
result = resolve_profile(profile)
|
||||
|
||||
assert "/config" in result.mounts
|
||||
mount = result.mounts["/config"]
|
||||
assert mount.target_path == "/config"
|
||||
assert mount.mode == "ro"
|
||||
assert mount.files == {"settings.json": '{"key": "value"}'}
|
||||
|
||||
|
||||
class TestResolveProfileIncludes:
|
||||
"""Tests for profile resolution with includes."""
|
||||
|
||||
def test_single_include(self) -> None:
|
||||
"""Profile with one include resolves in correct order."""
|
||||
base = _make_profile("base", env_vars={"FOO": "base"})
|
||||
derived = _make_profile(
|
||||
"derived",
|
||||
env_vars={"BAR": "derived"},
|
||||
includes=[_make_include(base, order_index=0)],
|
||||
)
|
||||
result = resolve_profile(derived)
|
||||
|
||||
assert result.resolution_order == ["derived", "base"]
|
||||
assert result.environment_variables == {
|
||||
"FOO": "base",
|
||||
"BAR": "derived",
|
||||
}
|
||||
|
||||
def test_multiple_includes_ordered(self) -> None:
|
||||
"""Multiple includes are resolved in order_index order."""
|
||||
first = _make_profile("first", env_vars={"KEY": "first"})
|
||||
second = _make_profile("second", env_vars={"KEY": "second"})
|
||||
main = _make_profile(
|
||||
"main",
|
||||
includes=[
|
||||
_make_include(first, order_index=0),
|
||||
_make_include(second, order_index=1),
|
||||
],
|
||||
)
|
||||
result = resolve_profile(main)
|
||||
|
||||
assert result.resolution_order == ["main", "first", "second"]
|
||||
# second overrides first
|
||||
assert result.environment_variables == {"KEY": "second"}
|
||||
assert result.env_var_sources["KEY"] == ["first", "second"]
|
||||
|
||||
def test_include_order_matters(self) -> None:
|
||||
"""Changing include order changes resolution."""
|
||||
a = _make_profile("a", env_vars={"KEY": "a"})
|
||||
b = _make_profile("b", env_vars={"KEY": "b"})
|
||||
main1 = _make_profile(
|
||||
"main",
|
||||
includes=[
|
||||
_make_include(a, order_index=0),
|
||||
_make_include(b, order_index=1),
|
||||
],
|
||||
)
|
||||
main2 = _make_profile(
|
||||
"main",
|
||||
includes=[
|
||||
_make_include(b, order_index=0),
|
||||
_make_include(a, order_index=1),
|
||||
],
|
||||
)
|
||||
|
||||
result1 = resolve_profile(main1)
|
||||
result2 = resolve_profile(main2)
|
||||
|
||||
assert result1.environment_variables["KEY"] == "b"
|
||||
assert result2.environment_variables["KEY"] == "a"
|
||||
|
||||
def test_nested_includes(self) -> None:
|
||||
"""Deeply nested includes resolve recursively."""
|
||||
deep = _make_profile("deep", env_vars={"DEEP": "value"})
|
||||
mid = _make_profile(
|
||||
"mid",
|
||||
env_vars={"MID": "value"},
|
||||
includes=[_make_include(deep, order_index=0)],
|
||||
)
|
||||
top = _make_profile(
|
||||
"top",
|
||||
env_vars={"TOP": "value"},
|
||||
includes=[_make_include(mid, order_index=0)],
|
||||
)
|
||||
result = resolve_profile(top)
|
||||
|
||||
assert result.resolution_order == ["top", "mid", "deep"]
|
||||
assert result.environment_variables == {
|
||||
"TOP": "value",
|
||||
"MID": "value",
|
||||
"DEEP": "value",
|
||||
}
|
||||
|
||||
|
||||
class TestResolveProfileOverrides:
|
||||
"""Tests for deterministic override rules."""
|
||||
|
||||
def test_env_var_override(self) -> None:
|
||||
"""Later layers override earlier env vars."""
|
||||
base = _make_profile("base", env_vars={"KEY": "base"})
|
||||
override = _make_profile("override", env_vars={"KEY": "override"})
|
||||
main = _make_profile(
|
||||
"main",
|
||||
includes=[
|
||||
_make_include(base, order_index=0),
|
||||
_make_include(override, order_index=1),
|
||||
],
|
||||
)
|
||||
result = resolve_profile(main)
|
||||
|
||||
assert result.environment_variables["KEY"] == "override"
|
||||
assert result.env_var_sources["KEY"] == ["base", "override"]
|
||||
|
||||
def test_main_profile_wins_over_includes(self) -> None:
|
||||
"""The main profile itself wins over all includes."""
|
||||
base = _make_profile("base", env_vars={"KEY": "base"})
|
||||
main = _make_profile(
|
||||
"main",
|
||||
env_vars={"KEY": "main"},
|
||||
includes=[_make_include(base, order_index=0)],
|
||||
)
|
||||
result = resolve_profile(main)
|
||||
|
||||
assert result.environment_variables["KEY"] == "main"
|
||||
assert result.env_var_sources["KEY"] == ["base", "main"]
|
||||
|
||||
def test_runtime_hint_override(self) -> None:
|
||||
"""Later layers override earlier runtime hints."""
|
||||
base = _make_profile("base", start_command="python old.py")
|
||||
override = _make_profile("override", start_command="python new.py")
|
||||
main = _make_profile(
|
||||
"main",
|
||||
includes=[
|
||||
_make_include(base, order_index=0),
|
||||
_make_include(override, order_index=1),
|
||||
],
|
||||
)
|
||||
result = resolve_profile(main)
|
||||
|
||||
assert result.runtime_hints.start_command == "python new.py"
|
||||
assert result.runtime_hints.overridden_hints["start_command"] == "override"
|
||||
|
||||
def test_mount_file_override(self) -> None:
|
||||
"""Later layers override earlier files in the same mount."""
|
||||
base = _make_profile(
|
||||
"base",
|
||||
mounts=[
|
||||
_make_mount(
|
||||
"/config",
|
||||
files={"app.json": '{"v": 1}'},
|
||||
),
|
||||
],
|
||||
)
|
||||
override = _make_profile(
|
||||
"override",
|
||||
mounts=[
|
||||
_make_mount(
|
||||
"/config",
|
||||
files={"app.json": '{"v": 2}'},
|
||||
),
|
||||
],
|
||||
)
|
||||
main = _make_profile(
|
||||
"main",
|
||||
includes=[
|
||||
_make_include(base, order_index=0),
|
||||
_make_include(override, order_index=1),
|
||||
],
|
||||
)
|
||||
result = resolve_profile(main)
|
||||
|
||||
mount = result.mounts["/config"]
|
||||
assert mount.files["app.json"] == '{"v": 2}'
|
||||
assert mount.overridden_files["app.json"] == ["override"]
|
||||
|
||||
def test_mount_mode_override(self) -> None:
|
||||
"""Later layers override mount mode."""
|
||||
base = _make_profile(
|
||||
"base",
|
||||
mounts=[_make_mount("/data", mode="ro")],
|
||||
)
|
||||
override = _make_profile(
|
||||
"override",
|
||||
mounts=[_make_mount("/data", mode="rw")],
|
||||
)
|
||||
main = _make_profile(
|
||||
"main",
|
||||
includes=[
|
||||
_make_include(base, order_index=0),
|
||||
_make_include(override, order_index=1),
|
||||
],
|
||||
)
|
||||
result = resolve_profile(main)
|
||||
|
||||
assert result.mounts["/data"].mode == "rw"
|
||||
assert result.mounts["/data"].mode_overridden_by == "override"
|
||||
|
||||
def test_mount_file_merge(self) -> None:
|
||||
"""Different files in the same mount are merged."""
|
||||
base = _make_profile(
|
||||
"base",
|
||||
mounts=[
|
||||
_make_mount(
|
||||
"/config",
|
||||
files={"a.json": "1"},
|
||||
),
|
||||
],
|
||||
)
|
||||
override = _make_profile(
|
||||
"override",
|
||||
mounts=[
|
||||
_make_mount(
|
||||
"/config",
|
||||
files={"b.json": "2"},
|
||||
),
|
||||
],
|
||||
)
|
||||
main = _make_profile(
|
||||
"main",
|
||||
includes=[
|
||||
_make_include(base, order_index=0),
|
||||
_make_include(override, order_index=1),
|
||||
],
|
||||
)
|
||||
result = resolve_profile(main)
|
||||
|
||||
mount = result.mounts["/config"]
|
||||
assert mount.files == {"a.json": "1", "b.json": "2"}
|
||||
|
||||
|
||||
class TestResolveProfileCycles:
|
||||
"""Tests for cycle detection during resolution."""
|
||||
|
||||
def test_direct_cycle(self) -> None:
|
||||
"""A -> B -> A is detected."""
|
||||
a = _make_profile("a")
|
||||
b = _make_profile("b", includes=[_make_include(a, order_index=0)])
|
||||
a.includes = [_make_include(b, order_index=0)]
|
||||
|
||||
with pytest.raises(ProfileCycleError) as exc_info:
|
||||
resolve_profile(a)
|
||||
|
||||
assert "a" in exc_info.value.cycle_path
|
||||
assert "b" in exc_info.value.cycle_path
|
||||
|
||||
def test_indirect_cycle(self) -> None:
|
||||
"""A -> B -> C -> A is detected."""
|
||||
a = _make_profile("a")
|
||||
c = _make_profile("c")
|
||||
b = _make_profile("b", includes=[_make_include(c, order_index=0)])
|
||||
a.includes = [_make_include(b, order_index=0)]
|
||||
c.includes = [_make_include(a, order_index=0)]
|
||||
|
||||
with pytest.raises(ProfileCycleError) as exc_info:
|
||||
resolve_profile(a)
|
||||
|
||||
assert "a" in exc_info.value.cycle_path
|
||||
assert "b" in exc_info.value.cycle_path
|
||||
assert "c" in exc_info.value.cycle_path
|
||||
|
||||
def test_self_cycle(self) -> None:
|
||||
"""A -> A is detected."""
|
||||
a = _make_profile("a")
|
||||
a.includes = [_make_include(a, order_index=0)]
|
||||
|
||||
with pytest.raises(ProfileCycleError) as exc_info:
|
||||
resolve_profile(a)
|
||||
|
||||
assert exc_info.value.cycle_path == ["a", "a"]
|
||||
|
||||
def test_cycle_does_not_partially_resolve(self) -> None:
|
||||
"""Cycle detection prevents any partial resolution."""
|
||||
a = _make_profile("a", env_vars={"A": "a"})
|
||||
b = _make_profile("b", env_vars={"B": "b"})
|
||||
a.includes = [_make_include(b, order_index=0)]
|
||||
b.includes = [_make_include(a, order_index=0)]
|
||||
|
||||
with pytest.raises(ProfileCycleError):
|
||||
resolve_profile(a)
|
||||
|
||||
|
||||
class TestResolveProfileDiamond:
|
||||
"""Tests for diamond-shaped include graphs."""
|
||||
|
||||
def test_diamond_resolution(self) -> None:
|
||||
"""Diamond graph resolves correctly without duplication issues."""
|
||||
base = _make_profile("base", env_vars={"BASE": "base"})
|
||||
left = _make_profile(
|
||||
"left",
|
||||
env_vars={"LEFT": "left"},
|
||||
includes=[_make_include(base, order_index=0)],
|
||||
)
|
||||
right = _make_profile(
|
||||
"right",
|
||||
env_vars={"RIGHT": "right"},
|
||||
includes=[_make_include(base, order_index=0)],
|
||||
)
|
||||
top = _make_profile(
|
||||
"top",
|
||||
env_vars={"TOP": "top"},
|
||||
includes=[
|
||||
_make_include(left, order_index=0),
|
||||
_make_include(right, order_index=1),
|
||||
],
|
||||
)
|
||||
result = resolve_profile(top)
|
||||
|
||||
# base should appear once (via left, then right skips because visited)
|
||||
assert result.resolution_order == ["top", "left", "base", "right"]
|
||||
assert result.environment_variables == {
|
||||
"TOP": "top",
|
||||
"LEFT": "left",
|
||||
"RIGHT": "right",
|
||||
"BASE": "base",
|
||||
}
|
||||
|
||||
def test_diamond_override(self) -> None:
|
||||
"""Diamond graph with conflicting overrides resolves correctly."""
|
||||
base = _make_profile("base", env_vars={"KEY": "base"})
|
||||
left = _make_profile(
|
||||
"left",
|
||||
env_vars={"KEY": "left"},
|
||||
includes=[_make_include(base, order_index=0)],
|
||||
)
|
||||
right = _make_profile(
|
||||
"right",
|
||||
env_vars={"KEY": "right"},
|
||||
includes=[_make_include(base, order_index=0)],
|
||||
)
|
||||
top = _make_profile(
|
||||
"top",
|
||||
includes=[
|
||||
_make_include(left, order_index=0),
|
||||
_make_include(right, order_index=1),
|
||||
],
|
||||
)
|
||||
result = resolve_profile(top)
|
||||
|
||||
# right wins because it's later
|
||||
assert result.environment_variables["KEY"] == "right"
|
||||
assert result.env_var_sources["KEY"] == ["base", "left", "right"]
|
||||
# Note: base appears once because visited set skips duplicate resolution in diamond graphs
|
||||
@@ -0,0 +1,2 @@
|
||||
schema: spec-driven
|
||||
created: 2026-05-24
|
||||
@@ -0,0 +1,45 @@
|
||||
## Context
|
||||
|
||||
The current system uses `config_folders` with a flat `files` JSONB and an `is_active` flag for auto-mounting at tool launch time. This design is inflexible: only one folder can be active, there's no ordering of includes, no explicit per-tool-instance selection, and mount definitions are mixed with file contents in a single blob.
|
||||
|
||||
## Goals / Non-Goals
|
||||
|
||||
**Goals:**
|
||||
- Provide structured config profiles with named collections of mounts and includes
|
||||
- Support ordered include lists so profiles can reference other profiles in sequence
|
||||
- Allow per-tool-instance profile selection with fallback to user/tool-type defaults
|
||||
- Remove implicit auto-mounting behavior at launch time
|
||||
- Maintain backward compatibility for existing `config_folders` data during migration
|
||||
|
||||
**Non-Goals:**
|
||||
- Frontend UI for profile management (separate change)
|
||||
- Real-time profile switching on running instances
|
||||
- Profile versioning or history
|
||||
|
||||
## Decisions
|
||||
|
||||
### 1. New `config_profiles` table replaces the semantic role of `config_folders`
|
||||
- Rationale: A profile is a higher-level concept than a folder; it includes mounts, includes, and metadata
|
||||
- `config_folders` remains for data migration but is no longer used for auto-mounting
|
||||
|
||||
### 2. `config_includes` provides ordered many-to-many self-reference on `config_profiles`
|
||||
- Rationale: Profiles need to include other profiles (e.g., a "base" profile included by "project-specific")
|
||||
- `order_index` column controls application order
|
||||
|
||||
### 3. `config_mounts` stores individual mount/file entries
|
||||
- Rationale: Normalizing mounts allows querying, ordering, and validation per mount
|
||||
- Each mount has a `mount_path`, optional `content` text, and optional `source_profile_id` for transitive includes
|
||||
|
||||
### 4. Default profile stored on `user_configs.config` JSONB
|
||||
- Rationale: Avoids schema changes to `users`; the existing `user_configs` table already stores per-user JSON
|
||||
- Key: `default_profile_id` (global default) and `default_profiles` map for per-tool-type defaults
|
||||
|
||||
### 5. `tool_instances.selected_profile_id` for explicit selection
|
||||
- Rationale: Clear, direct foreign key; nullable to allow fallback to defaults
|
||||
- Null means "use default resolution"
|
||||
|
||||
## Risks / Trade-offs
|
||||
|
||||
- [Risk] Existing `config_folders` data becomes orphaned if not migrated → Mitigation: keep table, stop auto-mount behavior only
|
||||
- [Risk] Profile include cycles could cause infinite loops → Mitigation: validate at write time, detect cycles in include graph
|
||||
- [Risk] Multiple includes with overlapping mount paths → Mitigation: last-include-wins based on order_index
|
||||
@@ -0,0 +1,30 @@
|
||||
## Why
|
||||
|
||||
The current `config_folders` table provides basic file mounting but lacks structured profile management, ordering, and per-tool-instance selection. We need a proper config profile system that supports ordered includes, mount/file definitions, default selection, and explicit profile assignment per tool instance.
|
||||
|
||||
## What Changes
|
||||
|
||||
- Add `ConfigProfile` model to replace the legacy `config_folders` concept with structured profiles
|
||||
- Add `ConfigInclude` model for ordered include lists within profiles
|
||||
- Add `ConfigMount` model for mount/file definitions (replacing the flat `files` JSONB on `config_folders`)
|
||||
- Add default profile selection per user and tool type
|
||||
- Add `selected_profile_id` to `ToolInstance` for per-instance profile selection
|
||||
- Remove launch-time reliance on legacy active config folder auto-mounting (mark `config_folders.is_active` as deprecated, stop auto-mounting at launch)
|
||||
- Create database migrations for all new tables
|
||||
- **BREAKING**: Legacy `config_folders` auto-mounting behavior will be removed; tool instances must explicitly select a profile
|
||||
|
||||
## Capabilities
|
||||
|
||||
### New Capabilities
|
||||
- `config-profile-management`: CRUD operations for config profiles, includes, and mounts
|
||||
- `tool-instance-profile-selection`: Assign and switch config profiles per tool instance
|
||||
|
||||
### Modified Capabilities
|
||||
- `tool-instance-launch`: Change launch behavior to use explicit profile selection instead of auto-mounting active config folder
|
||||
|
||||
## Impact
|
||||
|
||||
- New database tables: `config_profiles`, `config_includes`, `config_mounts`
|
||||
- Modified tables: `tool_instances` (add `selected_profile_id`), `users` or `user_configs` (add default profile selection)
|
||||
- API endpoints for profile management and instance profile assignment
|
||||
- Tool launch logic changes (remove auto-mount, use explicit profile)
|
||||
@@ -0,0 +1,29 @@
|
||||
## ADDED Requirements
|
||||
|
||||
### Requirement: User can create config profiles
|
||||
The system SHALL allow users to create named config profiles containing mounts and includes.
|
||||
|
||||
#### Scenario: Successful profile creation
|
||||
- **WHEN** user creates a profile with name, description, and mount list
|
||||
- **THEN** the profile is stored with a unique ID and associated mounts
|
||||
|
||||
### Requirement: Profile includes are ordered
|
||||
The system SHALL support ordered includes where profiles can reference other profiles with a defined application sequence.
|
||||
|
||||
#### Scenario: Include with order
|
||||
- **WHEN** user adds an include to a profile with order_index 1
|
||||
- **THEN** the included profile's mounts are applied after order_index 0 includes
|
||||
|
||||
### Requirement: Config mounts define files and paths
|
||||
The system SHALL store individual mount entries with mount_path, optional content, and optional source profile reference.
|
||||
|
||||
#### Scenario: Add mount to profile
|
||||
- **WHEN** user adds a mount with mount_path "/app/config.json" and content "{}"
|
||||
- **THEN** the mount is stored and linked to the profile
|
||||
|
||||
### Requirement: Cycle detection in includes
|
||||
The system SHALL prevent creation of include cycles.
|
||||
|
||||
#### Scenario: Attempt cyclic include
|
||||
- **WHEN** user tries to include profile B in profile A where A is already included in B
|
||||
- **THEN** the system rejects the request with an error
|
||||
@@ -0,0 +1,22 @@
|
||||
## ADDED Requirements
|
||||
|
||||
### Requirement: Tool instance can have selected profile
|
||||
The system SHALL allow setting an explicit config profile on a tool instance.
|
||||
|
||||
#### Scenario: Assign profile to instance
|
||||
- **WHEN** user sets selected_profile_id on a tool instance
|
||||
- **THEN** the instance stores the profile ID and uses it at launch time
|
||||
|
||||
### Requirement: Tool instance uses default profile when none selected
|
||||
The system SHALL resolve a default profile for a tool instance when no explicit profile is selected.
|
||||
|
||||
#### Scenario: Fallback to user default
|
||||
- **WHEN** a tool instance has no selected_profile_id
|
||||
- **THEN** the system uses the user's default profile for that tool type, or the global default
|
||||
|
||||
### Requirement: Remove legacy auto-mount behavior
|
||||
The system SHALL no longer auto-mount the active config folder at tool launch time.
|
||||
|
||||
#### Scenario: Launch without active folder
|
||||
- **WHEN** a tool instance launches with no selected profile and no default
|
||||
- **THEN** the instance starts without mounting any config folder
|
||||
@@ -0,0 +1,15 @@
|
||||
## 1. Data Models and Migrations
|
||||
|
||||
- [x] 1.1 Create ConfigProfile model with user ownership, name, description
|
||||
- [x] 1.2 Create ConfigInclude model for ordered profile self-references
|
||||
- [x] 1.3 Create ConfigMount model for mount/file definitions
|
||||
- [x] 1.4 Add selected_profile_id to ToolInstance model
|
||||
- [x] 1.5 Add default profile fields to UserConfig model
|
||||
- [x] 1.6 Create Alembic migration for new tables and columns
|
||||
- [x] 1.7 Register new models in models/__init__.py
|
||||
- [x] 1.8 Add migration metadata and test
|
||||
|
||||
## 2. Legacy Deprecation
|
||||
|
||||
- [x] 2.1 Mark config_folders.is_active as deprecated in model
|
||||
- [ ] 2.2 Remove auto-mounting logic from tool launch (separate change)
|
||||
@@ -0,0 +1,213 @@
|
||||
# OpenSpec Status and Implementation Checklist Review
|
||||
|
||||
**Review Date:** 2026-05-24
|
||||
**Reviewer:** Worker el-2i1s
|
||||
**Task:** 6.3 Final OpenSpec status and checklist review
|
||||
|
||||
---
|
||||
|
||||
## Executive Summary
|
||||
|
||||
This review covers all active OpenSpec changes in the `openspec/changes/` directory. Out of **11 active changes** with **345 total tasks**, **66 tasks (19.1%) are complete** and **279 tasks remain**.
|
||||
|
||||
### Key Findings
|
||||
|
||||
- **2 changes are near completion** (git-repo-working-clones at 87.5%, opencode-web-terminal at 72.7%)
|
||||
- **2 changes have partial progress** (session-management-fixes at 32%, tool-workshop at 24.6%)
|
||||
- **7 changes have not started** (0% complete)
|
||||
- **1 new change was recently created** (add-config-profiles) with initial model work already implemented
|
||||
|
||||
---
|
||||
|
||||
## Active Changes Status
|
||||
|
||||
### Near Completion (>50%)
|
||||
|
||||
#### 1. git-repo-working-clones (87.5% complete)
|
||||
- **Completed:** 7/8 tasks
|
||||
- **Remaining:** Task 4.1 (Run targeted API tests)
|
||||
- **Status:** All implementation complete, only testing remains
|
||||
- **Recommendation:** Complete the remaining test task and archive
|
||||
|
||||
#### 2. opencode-web-terminal (72.7% complete)
|
||||
- **Completed:** 16/22 tasks
|
||||
- **Remaining:** Tasks 6.1-6.4 (testing and quality gates)
|
||||
- **Status:** Phases 1-5 complete (models, API, frontend, migrations)
|
||||
- **Recommendation:** Run backend tests, typecheck, and lint to complete
|
||||
|
||||
### In Progress (20-50%)
|
||||
|
||||
#### 3. session-management-fixes (32% complete)
|
||||
- **Completed:** 8/25 tasks
|
||||
- **Remaining:** All frontend work (phases 3-4, 5.3-5.6) and quality gates
|
||||
- **Status:** Backend tunnel work complete; frontend confirmation dialogs, health polling, and UI updates pending
|
||||
- **Blockers:** Frontend tasks depend on backend being deployed
|
||||
|
||||
#### 4. tool-workshop (24.6% complete)
|
||||
- **Completed:** 35/142 tasks
|
||||
- **Remaining:** 107 tasks across phases 2-5
|
||||
- **Status:** Phase 1 (Backend Foundation) nearly complete (35/37 tasks)
|
||||
- **Blockers:** Phase 2 (Instance Creation Enhancement) not started; includes docker build service, compose generation, config folder mounting, readiness probes
|
||||
|
||||
### Not Started (0%)
|
||||
|
||||
#### 5. cloudflare-tunnel-instances (0% complete)
|
||||
- **Tasks:** 28 across 6 phases
|
||||
- **Status:** No work started
|
||||
- **Dependencies:** May depend on instance-proxy being complete
|
||||
|
||||
#### 6. git-repo-ssh-clone-check (0% complete)
|
||||
- **Tasks:** 11 across 4 phases
|
||||
- **Status:** No work started
|
||||
- **Relationship:** Related to git-repo-working-clones
|
||||
|
||||
#### 7. instance-proxy (0% complete)
|
||||
- **Tasks:** 15 across 4 phases
|
||||
- **Status:** No work started
|
||||
- **Note:** May be superseded by cloudflare-tunnel-instances approach
|
||||
|
||||
#### 8. sessions-hub (0% complete)
|
||||
- **Tasks:** 18 across 6 phases
|
||||
- **Status:** No work started
|
||||
- **Dependencies:** Frontend foundation, session management APIs
|
||||
|
||||
#### 9. tool-config-management (0% complete)
|
||||
- **Tasks:** 22 across 7 phases
|
||||
- **Status:** No work started
|
||||
- **Relationship:** Related to tool-config-ui-rework and tool-workshop
|
||||
|
||||
#### 10. tool-config-ui-rework (0% complete)
|
||||
- **Tasks:** 36 across 8 phases
|
||||
- **Status:** No work started
|
||||
- **Relationship:** Related to tool-config-management
|
||||
|
||||
#### 11. ui-redesign-home-settings (0% complete)
|
||||
- **Tasks:** 18 across 5 phases
|
||||
- **Status:** No work started
|
||||
- **Dependencies:** Sessions hub, settings pages
|
||||
|
||||
### Newly Created
|
||||
|
||||
#### 12. add-config-profiles (partially implemented, not tracked)
|
||||
- **Tasks:** 10 across 2 sections
|
||||
- **Completed:** ~5/10 tasks (models created, migrations pending)
|
||||
- **Status:** Models implemented but not checked off in tasks.md
|
||||
- **Work Done:**
|
||||
- ConfigProfile model created with user ownership, name, description
|
||||
- ConfigInclude model created for ordered profile self-references
|
||||
- ConfigMount model created for mount/file definitions
|
||||
- selected_profile_id added to ToolInstance model
|
||||
- default profile fields added to UserConfig model
|
||||
- Models registered in models/__init__.py
|
||||
- **Remaining:**
|
||||
- Alembic migration
|
||||
- Migration metadata and testing
|
||||
- Legacy deprecation markings
|
||||
|
||||
---
|
||||
|
||||
## Archived Changes
|
||||
|
||||
**25 changes** have been successfully archived in `openspec/changes/archive/`, including:
|
||||
- auth-oauth, database-models, frontend-foundation
|
||||
- tool-instances, tool-terminal, git-control
|
||||
- api-documentation, workspace-visual-overhaul
|
||||
- And others
|
||||
|
||||
---
|
||||
|
||||
## Implementation Checklist
|
||||
|
||||
### Immediate Actions (This Sprint)
|
||||
|
||||
- [ ] **Complete git-repo-working-clones**: Run task 4.1 (targeted API tests)
|
||||
- [ ] **Complete opencode-web-terminal**: Run tasks 6.1-6.4 (tests and quality gates)
|
||||
- [ ] **Archive completed changes**: Move git-repo-working-clones and opencode-web-terminal to archive once tests pass
|
||||
|
||||
### Short-Term (Next 1-2 Sprints)
|
||||
|
||||
- [ ] **session-management-fixes frontend**: Implement confirmation dialogs, health polling, recreate tunnel button
|
||||
- [ ] **tool-workshop Phase 2**: Begin docker build service, compose generation, config folder mounting
|
||||
- [ ] **add-config-profiles**: Create Alembic migration, test models, mark legacy deprecation
|
||||
|
||||
### Medium-Term (Next 3-4 Sprints)
|
||||
|
||||
- [ ] **cloudflare-tunnel-instances**: Evaluate dependency on instance-proxy; decide approach
|
||||
- [ ] **sessions-hub**: Implement after session-management-fixes is complete
|
||||
- [ ] **ui-redesign-home-settings**: Coordinate with sessions-hub completion
|
||||
|
||||
### Backlog / Needs Prioritization
|
||||
|
||||
- [ ] **git-repo-ssh-clone-check**: Determine if still needed after git-repo-working-clones
|
||||
- [ ] **instance-proxy**: Determine if superseded by cloudflare-tunnel-instances
|
||||
- [ ] **tool-config-management**: Evaluate overlap with tool-workshop and tool-config-ui-rework
|
||||
- [ ] **tool-config-ui-rework**: Evaluate overlap with tool-config-management
|
||||
|
||||
---
|
||||
|
||||
## Quality Gates Status
|
||||
|
||||
### Backend
|
||||
|
||||
| Gate | Status | Notes |
|
||||
|------|--------|-------|
|
||||
| ruff (linting) | Unknown | Not run in this review |
|
||||
| mypy (type checking) | Unknown | Not run in this review |
|
||||
| pytest (tests) | Unknown | Not run in this review |
|
||||
| bandit (security) | Unknown | Not run in this review |
|
||||
|
||||
### Frontend
|
||||
|
||||
| Gate | Status | Notes |
|
||||
|------|--------|-------|
|
||||
| TypeScript typecheck | Unknown | Not run in this review |
|
||||
| ESLint | Unknown | Not run in this review |
|
||||
| Build | Unknown | Not run in this review |
|
||||
| Vitest tests | Unknown | Not run in this review |
|
||||
|
||||
**Note:** Tasks 6.1 (Backend quality gates) and 6.2 (Frontend quality gates) are dependencies for this review but are currently blocked. A follow-up task should run these gates and report results.
|
||||
|
||||
---
|
||||
|
||||
## Risks and Blockers
|
||||
|
||||
1. **Testing Bottleneck**: Both near-complete changes are blocked on test execution
|
||||
2. **Frontend Lag**: session-management-fixes has complete backend but all frontend work pending
|
||||
3. **Massive Scope**: tool-workshop is 41% of all active tasks with most work not started
|
||||
4. **Parallel Unstarted Work**: 7 of 11 changes have 0% progress
|
||||
5. **Dependency Confusion**: instance-proxy and cloudflare-tunnel-instances may be competing approaches
|
||||
6. **Legacy Migration**: add-config-profiles introduces breaking changes to config_folders behavior
|
||||
|
||||
---
|
||||
|
||||
## Recommendations
|
||||
|
||||
1. **Focus on completions**: Finish git-repo-working-clones and opencode-web-terminal first
|
||||
2. **Archive promptly**: Move completed changes to archive to reduce cognitive load
|
||||
3. **Clarify proxy approach**: Decide between instance-proxy and cloudflare-tunnel-instances
|
||||
4. **Merge overlapping changes**: Consider consolidating tool-config-management, tool-config-ui-rework, and tool-workshop
|
||||
5. **Run quality gates**: Execute tasks 6.1 and 6.2 before claiming any change is complete
|
||||
6. **Document breaking changes**: Ensure add-config-profiles migration plan is well-documented
|
||||
|
||||
---
|
||||
|
||||
## Appendix: Task Count by Change
|
||||
|
||||
| Change | Total | Complete | Remaining | % |
|
||||
|--------|-------|----------|-----------|---|
|
||||
| cloudflare-tunnel-instances | 28 | 0 | 28 | 0.0% |
|
||||
| git-repo-ssh-clone-check | 11 | 0 | 11 | 0.0% |
|
||||
| git-repo-working-clones | 8 | 7 | 1 | 87.5% |
|
||||
| instance-proxy | 15 | 0 | 15 | 0.0% |
|
||||
| opencode-web-terminal | 22 | 16 | 6 | 72.7% |
|
||||
| session-management-fixes | 25 | 8 | 17 | 32.0% |
|
||||
| sessions-hub | 18 | 0 | 18 | 0.0% |
|
||||
| tool-config-management | 22 | 0 | 22 | 0.0% |
|
||||
| tool-config-ui-rework | 36 | 0 | 36 | 0.0% |
|
||||
| tool-workshop | 142 | 35 | 107 | 24.6% |
|
||||
| ui-redesign-home-settings | 18 | 0 | 18 | 0.0% |
|
||||
| **TOTAL** | **345** | **66** | **279** | **19.1%** |
|
||||
|
||||
---
|
||||
|
||||
*Review completed. Recommend archiving this document in the workspace documentation.*
|
||||
Reference in New Issue
Block a user