Skip to content

Projects, workspaces and invocation resources

octomate.managers.project

Database-backed project lookup and native working-directory resolution.

ProjectManager

Bases: Manager

Read persisted projects without retaining a process-local catalog.

Source code in octomate/managers/project.py
class ProjectManager(Manager):
    """Read persisted projects without retaining a process-local catalog."""

    async def get(
        self,
        owner_id: UUID7,
        *,
        project_id: UUID7 | None = None,
        name: str | None = None,
        thread: Thread | None = None,
    ) -> Project | None:
        """The owner's project matching all supplied filters; at least one is required.

        ID and name lookups include disabled projects. A thread lookup uses its
        stored project ID, refuses missing or foreign bindings, and returns None
        for unbound threads or disabled projects.
        """
        if project_id is None and name is None and thread is None:
            raise ValueError("Project lookup requires an ID, name, or thread")
        if thread is not None and thread.project_id is None:
            return None
        expressions = [Project["owner_id"] == owner_id]
        if project_id is not None:
            expressions.append(Project["id"] == project_id)
        if name is not None:
            expressions.append(Project["name"] == name)
        if thread is not None:
            expressions.append(Project["id"] == thread.project_id)
        async with async_session() as session:
            project = await session.one_or_none(Project, expressions=expressions)
        if thread is None:
            return project
        if project is None:
            raise FileNotFoundError("Project not found")
        return project if project.enabled else None

    async def list(
        self,
        owner_id: UUID7,
        *,
        cursor: str | None = None,
        limit: int = 20,
        enabled: bool | None = None,
        query: str = "",
    ) -> Page[Project]:
        """An owner-scoped page in stable ID order, optionally filtered by enabled state."""
        if not 1 <= limit <= 100:
            raise ValueError("Project page size must be between 1 and 100")
        scope = [Project["owner_id"] == owner_id]
        if enabled is not None:
            scope.append(Project["enabled"].is_(enabled))
        if query := query.strip():
            scope.append(
                Project["name"].icontains(query)
                | Project["description"].icontains(query)
            )
        bookmark = None if cursor is None else Cursor[Project](cursor).bookmark
        after = (
            []
            if bookmark is None or bookmark.expression is None
            else [bookmark.expression]
        )
        ordering = (Project["id"].asc(),)
        async with async_session() as session:
            rows = await session.list(
                Project,
                expressions=[*scope, *after],
                order_bys=ordering,
                limit=limit + 1,
            )
            total = await session.count(Project, expressions=scope)
        items = tuple(rows[:limit])
        return Page(
            items=items,
            total=total,
            next_cursor=str(
                Cursor[Project].from_expressions(
                    bookmark=Project["id"] > items[-1].id if items else None,
                    order_bys=ordering,
                    limit=limit,
                )
            ),
            has_more=len(rows) > limit,
        )

    async def resolve(self, owner_id: UUID7, cwd: Path) -> Project | None:
        """The owner's enabled project whose root most closely contains ``cwd``.

        Resolve paths before comparing so symlinks and alternate spellings of the
        same directory match. Roots are read anew on each call.
        """
        resolved = await AsyncPath(cwd).resolve()
        async with async_session() as session:
            projects = await session.list(
                Project,
                expressions=[
                    Project["owner_id"] == owner_id,
                    Project["enabled"].is_(True),
                ],
                limit=None,
            )
        roots = [
            (await AsyncPath(root).resolve(), project)
            for project in projects
            for root in project.roots
        ]
        roots.sort(key=lambda pair: len(pair[0].parts), reverse=True)
        for root, project in roots:
            if resolved.is_relative_to(root):
                return project
        return None

get async

get(
    owner_id: UUID7,
    *,
    project_id: UUID7 | None = None,
    name: str | None = None,
    thread: Thread | None = None,
) -> Project | None

The owner's project matching all supplied filters; at least one is required.

ID and name lookups include disabled projects. A thread lookup uses its stored project ID, refuses missing or foreign bindings, and returns None for unbound threads or disabled projects.

Source code in octomate/managers/project.py
async def get(
    self,
    owner_id: UUID7,
    *,
    project_id: UUID7 | None = None,
    name: str | None = None,
    thread: Thread | None = None,
) -> Project | None:
    """The owner's project matching all supplied filters; at least one is required.

    ID and name lookups include disabled projects. A thread lookup uses its
    stored project ID, refuses missing or foreign bindings, and returns None
    for unbound threads or disabled projects.
    """
    if project_id is None and name is None and thread is None:
        raise ValueError("Project lookup requires an ID, name, or thread")
    if thread is not None and thread.project_id is None:
        return None
    expressions = [Project["owner_id"] == owner_id]
    if project_id is not None:
        expressions.append(Project["id"] == project_id)
    if name is not None:
        expressions.append(Project["name"] == name)
    if thread is not None:
        expressions.append(Project["id"] == thread.project_id)
    async with async_session() as session:
        project = await session.one_or_none(Project, expressions=expressions)
    if thread is None:
        return project
    if project is None:
        raise FileNotFoundError("Project not found")
    return project if project.enabled else None

list async

list(
    owner_id: UUID7,
    *,
    cursor: str | None = None,
    limit: int = 20,
    enabled: bool | None = None,
    query: str = "",
) -> Page[Project]

An owner-scoped page in stable ID order, optionally filtered by enabled state.

Source code in octomate/managers/project.py
async def list(
    self,
    owner_id: UUID7,
    *,
    cursor: str | None = None,
    limit: int = 20,
    enabled: bool | None = None,
    query: str = "",
) -> Page[Project]:
    """An owner-scoped page in stable ID order, optionally filtered by enabled state."""
    if not 1 <= limit <= 100:
        raise ValueError("Project page size must be between 1 and 100")
    scope = [Project["owner_id"] == owner_id]
    if enabled is not None:
        scope.append(Project["enabled"].is_(enabled))
    if query := query.strip():
        scope.append(
            Project["name"].icontains(query)
            | Project["description"].icontains(query)
        )
    bookmark = None if cursor is None else Cursor[Project](cursor).bookmark
    after = (
        []
        if bookmark is None or bookmark.expression is None
        else [bookmark.expression]
    )
    ordering = (Project["id"].asc(),)
    async with async_session() as session:
        rows = await session.list(
            Project,
            expressions=[*scope, *after],
            order_bys=ordering,
            limit=limit + 1,
        )
        total = await session.count(Project, expressions=scope)
    items = tuple(rows[:limit])
    return Page(
        items=items,
        total=total,
        next_cursor=str(
            Cursor[Project].from_expressions(
                bookmark=Project["id"] > items[-1].id if items else None,
                order_bys=ordering,
                limit=limit,
            )
        ),
        has_more=len(rows) > limit,
    )

resolve async

resolve(owner_id: UUID7, cwd: Path) -> Project | None

The owner's enabled project whose root most closely contains cwd.

Resolve paths before comparing so symlinks and alternate spellings of the same directory match. Roots are read anew on each call.

Source code in octomate/managers/project.py
async def resolve(self, owner_id: UUID7, cwd: Path) -> Project | None:
    """The owner's enabled project whose root most closely contains ``cwd``.

    Resolve paths before comparing so symlinks and alternate spellings of the
    same directory match. Roots are read anew on each call.
    """
    resolved = await AsyncPath(cwd).resolve()
    async with async_session() as session:
        projects = await session.list(
            Project,
            expressions=[
                Project["owner_id"] == owner_id,
                Project["enabled"].is_(True),
            ],
            limit=None,
        )
    roots = [
        (await AsyncPath(root).resolve(), project)
        for project in projects
        for root in project.roots
    ]
    roots.sort(key=lambda pair: len(pair[0].parts), reverse=True)
    for root, project in roots:
        if resolved.is_relative_to(root):
            return project
    return None

octomate.managers.workspaces.base

Compose thread workspaces from logical volumes and their host storage.

logger module-attribute

logger = logging.getLogger(__name__)

WorkspaceManager

Bases: Manager

Every run's workspace. A registered user's run gets a tree volume in that user's root, volumes_dir/<owner>/tree/<volume>, recorded by a row and checked out on the thread's own branch; an unregistered sender's run gets an empty temporary directory.

A fork is a complete, independent repository — its own .git, its own object store — containing only project history and this tree's saved snapshot. The mirror's private refs, unreachable objects and host metadata stay on the host; no hardlinks or object alternates connect the two repositories.

A project's tree is a cache rather than the only copy: each turn's tree is snapshotted and pushed to the mirror under the tree's own ref, so releasing one is a disk decision and resuming lays that ref back over a fresh fork. Releasing deletes the folder and keeps the row. What the agent did with git in there is the agent's — nothing here commits.

A registered user's thread in no project gets a tree too, forked from the blank mirror and thrown away when the run that made it ends. Same mechanism, opposite ending: there is no project to keep it for.

A turn enters open to prepare its workspace and scope its lifetime. Project exit checkpoints its exact volume; chat exit releases its temporary directory. resolve records a volume and settles its path without preparing it. Explicit save and dismiss resolve an owner's existing tree for graph finalization and handoffs. The registry identifies the project and the mirrors hold its checkpoints.

Source code in octomate/managers/workspaces/base.py
class WorkspaceManager(Manager):
    """Every run's workspace. A registered user's run gets a tree volume in that
    user's root, ``volumes_dir/<owner>/tree/<volume>``, recorded by a row and
    checked out on the thread's own branch; an unregistered sender's run gets an
    empty temporary directory.

    A fork is a complete, independent repository — its own `.git`, its own object
    store — containing only project history and this tree's saved snapshot.
    The mirror's private refs, unreachable objects and host metadata stay on
    the host; no hardlinks or object alternates connect the two repositories.

    A project's tree is a cache rather than the only copy: each turn's tree is
    snapshotted and pushed to the mirror under the tree's own ref, so releasing
    one is a disk decision and resuming lays that ref back over a fresh fork.
    Releasing deletes the folder and keeps the row. What the agent did with git in
    there is the agent's — nothing here commits.

    A registered user's thread in no project gets a tree too, forked from the blank
    mirror and thrown away when the run that made it ends. Same mechanism, opposite
    ending: there is no project to keep it for.

    A turn enters `open` to prepare its workspace and scope its lifetime.
    Project exit checkpoints its exact volume; chat exit releases its temporary
    directory. `resolve` records a volume and settles its path without preparing it.
    Explicit `save` and `dismiss` resolve an owner's existing tree for
    graph finalization and handoffs. The registry identifies the project and the
    mirrors hold its checkpoints.
    """

    def __init__(
        self,
        *,
        projects: ProjectManager,
        volumes: VolumeManager,
        mirrors: MirrorManager,
        config: WorkspacesConfig | None = None,
    ) -> None:
        self.projects: ProjectManager = projects
        self.volumes: VolumeManager = volumes
        self.mirrors: MirrorManager = mirrors
        self.config = config if config is not None else WorkspacesConfig()

    @property
    def host_storage(self) -> HostStorageManager:
        return self.volumes.host_storage

    @property
    def volumes_dir(self) -> Path:
        return self.host_storage.volumes_dir

    @property
    def identity(self) -> GitIdentity:
        """Who the machine is when it writes a snapshot — the `mirrors:` block's,
        read rather than copied, so a turn's work and a folder sync into a mirror
        carry one name and cannot drift into two."""
        return self.mirrors.config.identity

    def root(self, owner_id: UUID7) -> Path:
        """The owner's storage directory; volumes select individual host directories.

        Resolving it creates neither files nor database rows.
        """
        return self.volumes_dir / str(owner_id)

    async def resolve(
        self,
        thread_id: UUID7,
        project: Project | None,
        owner_id: UUID7 | None,
        ref: str | None = None,
    ) -> Workspace:
        """Record the owner's volumes and settle their paths without making files.

        A registered owner's tree comes with their package cache and their agent
        configuration. Unregistered
        senders receive a temporary chat path alone and cannot resolve project
        workspaces. This writes or stamps registered volume rows; use
        `volumes.find` for read-only inspection.
        """
        if owner_id is None and project is not None:
            raise UnregisteredProjectError(
                f"project {project.name!r} needs a registered user"
            )
        if project is not None and project.owner_id != owner_id:
            raise FileNotFoundError("Project not found")
        if owner_id is None:
            volumes: WorkspaceVolumes = {
                "work": Volume(
                    storage=self.host_storage.temporary(thread_id), ephemeral=True
                )
            }
        else:
            # The owner's own volumes need nothing from the mirror or the tree,
            # so they are settled while those are.
            async with asyncio.TaskGroup() as tasks:
                cache = tasks.create_task(self.volumes.slot(owner_id, "cache"))
                config = tasks.create_task(self.volumes.slot(owner_id, "config"))
                work = await self.volumes.tree(
                    owner_id,
                    thread_id,
                    project.id if project else None,
                    ref,
                    mirror=await self.mirrors.resolve(project),
                )
            volumes = {
                "work": work,
                "cache": cache.result(),
                "config": config.result(),
            }
        return Workspace(
            thread_id=thread_id,
            project=project,
            volumes=volumes,
            identity=self.identity,
        )

    @asynccontextmanager
    async def open(
        self,
        thread_id: UUID7,
        project: Project | None,
        owner_id: UUID7 | None,
        ref: str | None = None,
    ) -> AsyncGenerator[Workspace]:
        """Prepare a workspace and own its checkpoint or release when the run ends."""
        workspace = await self.resolve(thread_id, project, owner_id, ref)
        async with self.enter(workspace):
            yield workspace

    @asynccontextmanager
    async def enter(self, workspace: Workspace) -> AsyncGenerator[Workspace]:
        """Prepare the working tree's source, then enter the volume composition."""
        if isinstance(workspace.volume, GitVolume):
            if workspace.project is None:
                await self.mirrors.create()
            elif not workspace.path.is_dir():
                await self.mirrors.sync(workspace.project)
        async with workspace():
            yield workspace

    async def prepare(self, workspace: Workspace) -> Path:
        """Prepare a persistent project tree for a handoff outside an invocation."""
        volume = workspace.volume
        if workspace.project is None or not isinstance(volume, GitVolume):
            raise ValueError("A project handoff requires a Git working volume")
        if workspace.path.is_dir():
            return workspace.path
        mirror = await self.mirrors.sync(workspace.project)
        return await volume.materialize(mirror)

    async def save(self, thread: Thread, owner_id: UUID7) -> None:
        """Leave this owner's finished turn where losing their tree cannot cost it:
        a validated snapshot imported into the project's mirror as the tree's
        own ref.

        A fork owns its objects outright — nothing in a tree survives its
        removal — so without the import the tree is the only copy of
        what the turn did, and releasing it would be losing work rather than
        evicting a cache. That is what makes a tree disposable, and why the sweep
        is a disk decision.

        A thread with no tree for this owner — in no project, or one whose turn
        never forked one — has nothing to leave.

        The ref records what the tree holds rather than a history to protect.
        Imports update only that ref in the mirror and never reach the upstream.

        A failure is logged rather than raised. The turn has already happened and
        already answered; failing it now would report a delivered answer as an
        error, and the next turn saves the same work again.
        """
        project = await self.projects.get(owner_id, thread=thread)
        if project is None:
            return
        volume = await self.volumes.find(owner_id, thread.id, project.id)
        if volume is not None:
            await volume.checkpoint(
                await self.mirrors.resolve(project),
                self.identity,
            )

    async def saved(self, volume: GitVolume) -> bool:
        """Whether this volume matches its canonical snapshot in the host mirror.

        Workspace markers are writable by the harness and cannot authorize
        reclamation. Invalid or unreadable captures leave the tree unsaved.
        """
        if volume.project_id is None or volume.owner_id is None:
            return False
        project = await self.projects.get(volume.owner_id, project_id=volume.project_id)
        if project is None:
            return False
        mirror = (await self.mirrors.resolve(project)).path
        if not mirror.is_dir():
            return False
        ref = volume.snapshot_ref
        try:
            if not await run_git(
                "for-each-ref", "--format=%(objectname)", ref, cwd=mirror, isolated=True
            ):
                return False
            async with Snapshot.capture(volume.path, self.identity) as snapshot:
                return await snapshot.matches(mirror, ref)
        except (GitCommandError, OSError):
            logger.exception(
                "The tree %s could not be verified; keeping its work", volume.id
            )
            return False

    async def reclaim(self, volume: GitVolume) -> bool:
        """Delete a tree's folder only while nothing uses it and the mirror has
        its work, and answer whether it went.

        The storage lock is held from the first check to the deletion. A turn
        that arrives meanwhile waits and forks afresh, instead of starting in a
        folder that is about to go or leaving work there after it was verified.
        """
        storage = volume.storage
        async with storage.lock:
            if storage.uses:
                return False
            if not await self.saved(volume):
                logger.warning(
                    "the tree %s for thread %s holds work the mirror does not "
                    "have; keeping it",
                    volume.id,
                    volume.thread_id,
                )
                return False
            await storage.release()
        return True

    async def prune(self, idle: float) -> list[UUID7]:
        """Release every project tree nothing has used for `idle` seconds, and
        answer with the volumes that lost their folder.

        Eviction, not a decision about whether a thread is over: abandonment is
        unobservable, so rather than guessing, being wrong here costs the next turn
        a fork instead of costing anyone their work. Which is only true of a tree
        the mirror already has, so one holding anything unsaved is kept and said
        out loud. Idleness is read from the row's `last_used_at`, which every
        `open` stamps.

        A folder in a user's root that no row owns is reported and never deleted:
        the row is written before the folder, so such a folder is something this
        manager did not make.
        """
        released: list[UUID7] = []
        # Three counts, because "why is that tree still there" has three answers
        # and the disk cannot tell them apart.
        kept_busy = kept_unsaved = 0
        cutoff = datetime.now(UTC) - timedelta(seconds=idle)
        with workspace_logfire.span("workspace.prune", idle=idle) as span:
            trees = await self.volumes.project_trees()
            for volume in trees:
                path = volume.path
                if not path.is_dir():
                    continue
                if volume.last_used_at > cutoff:
                    kept_busy += 1
                elif await self.reclaim(volume):
                    released.append(volume.id)
                # Read before anything else can run: `reclaim` refused under the
                # lock a moment ago, so the use count still says which refusal.
                elif volume.storage.uses:
                    kept_busy += 1
                else:
                    kept_unsaved += 1
            span.set_attribute("released", len(released))
            span.set_attribute("kept_busy", kept_busy)
            span.set_attribute("kept_unsaved", kept_unsaved)
            span.set_attribute("unowned", await self.report_unowned())
            if released:
                logger.info("released %d idle tree(s)", len(released))
            return released

    async def report_unowned(self) -> int:
        """Warn about every tree folder no row owns, and answer how many there
        are. Hidden folders are forks in progress, and are skipped."""
        named: dict[uuid.UUID, Path] = {}
        unowned: list[Path] = []
        for path in self.volumes_dir.glob("*/tree/[!.]*"):
            try:
                named[uuid.UUID(path.name)] = path
            except ValueError:
                unowned.append(path)
        if named:
            owned_ids = await self.volumes.owned(list(named))
            unowned += [path for key, path in named.items() if key not in owned_ids]
        for path in unowned:
            logger.warning("%s has no volume row; leaving it", path)
        return len(unowned)

    async def sweep(self) -> None:
        """Prune on the interval, for as long as the host runs.

        A sweep that fails is logged and the next one still happens: reclaiming
        disk is maintenance, and a host that stops serving because it could not
        tidy up has the priority backwards.
        """
        while True:
            await asyncio.sleep(self.config.sweep_interval)
            try:
                await self.prune(self.config.idle_window)
            except Exception:
                logger.exception("the workspace sweep failed")

    async def carry(self, source: Thread, thread: Thread, owner_id: UUID7) -> None:
        """Give `thread`, landed in `source`'s project, a tree holding this owner's
        work as `source` left it — what a conversation moving to another thread
        takes of its work — and fork it.

        Saved first: the source's last turn may not have been, and what it left
        uncommitted has to travel as uncommitted. The snapshot is filed under the
        new tree's ref too, so its first fork resumes into it the way a released
        tree does; on a branch of its own when the source was on its own, since
        two trees pushing one branch would overwrite each other. A source with no
        snapshot leaves `thread` to fork the project fresh.

        Ignored files are copied across, an `.env` among them, since a snapshot
        never holds them. Ignored directories are not: they are dependencies and
        build output, which whatever runs in the landed tree makes again.
        """
        project = await self.projects.get(owner_id, thread=source)
        if project is None:
            return
        await self.save(source, owner_id)
        origin = await self.volumes.find(owner_id, source.id, project.id)
        landing = await self.resolve(thread.id, project, owner_id)
        volume = landing.volume
        if not isinstance(volume, GitVolume):
            raise ValueError("A project handoff requires a Git working volume")
        mirror = (await self.mirrors.resolve(project)).path
        if origin is not None and await run_git(
            "ls-remote", str(mirror), origin.snapshot_ref, isolated=True
        ):
            saved = origin.snapshot_ref
            subject = await run_git(
                "show", "-s", "--format=%s", saved, cwd=mirror, isolated=True
            )
            filed = saved
            if subject.strip() == f"{SNAPSHOT_PREFIX}{origin.branch}":
                filed = await run_git(
                    *self.identity.commit_flags,
                    "commit-tree",
                    f"{saved}^{{tree}}",
                    "-p",
                    f"{saved}^",
                    "-m",
                    f"{SNAPSHOT_PREFIX}{volume.branch}",
                    cwd=mirror,
                    isolated=True,
                )
            await run_git(
                "update-ref",
                volume.snapshot_ref,
                filed.strip(),
                cwd=mirror,
                isolated=True,
            )
        landed = await self.prepare(landing)
        if origin is None or not origin.path.is_dir():
            return
        await copy_ignored(origin.path, landed)

    async def dismiss(self, thread: Thread, owner_id: UUID7) -> bool:
        """Release this owner's tree on their agent's word that the work in it is
        done — the one release that is asked for rather than swept up — and answer
        whether it went.

        Saved first, and released only when the save took: the sweep's rule, that
        a tree holding work the mirror has not seen is never thrown away, does not
        bend for being asked. So what this costs is what a prune costs, a fork on
        the thread's next turn with the ref laid back over it.
        """
        with workspace_logfire.span(
            "workspace.dismiss", thread_id=str(thread.id), released=False
        ) as span:
            await self.save(thread, owner_id)
            project = await self.projects.get(owner_id, thread=thread)
            if project is None:
                return False
            volume = await self.volumes.find(owner_id, thread.id, project.id)
            if volume is None or not volume.path.is_dir():
                return False
            released = await self.reclaim(volume)
            span.set_attribute("released", released)
            return released

projects instance-attribute

projects: ProjectManager = projects

volumes instance-attribute

volumes: VolumeManager = volumes

mirrors instance-attribute

mirrors: MirrorManager = mirrors

config instance-attribute

config = (
    config if config is not None else WorkspacesConfig()
)

host_storage property

host_storage: HostStorageManager

volumes_dir property

volumes_dir: Path

identity property

identity: GitIdentity

Who the machine is when it writes a snapshot — the mirrors: block's, read rather than copied, so a turn's work and a folder sync into a mirror carry one name and cannot drift into two.

root

root(owner_id: UUID7) -> Path

The owner's storage directory; volumes select individual host directories.

Resolving it creates neither files nor database rows.

Source code in octomate/managers/workspaces/base.py
def root(self, owner_id: UUID7) -> Path:
    """The owner's storage directory; volumes select individual host directories.

    Resolving it creates neither files nor database rows.
    """
    return self.volumes_dir / str(owner_id)

resolve async

resolve(
    thread_id: UUID7,
    project: Project | None,
    owner_id: UUID7 | None,
    ref: str | None = None,
) -> Workspace

Record the owner's volumes and settle their paths without making files.

A registered owner's tree comes with their package cache and their agent configuration. Unregistered senders receive a temporary chat path alone and cannot resolve project workspaces. This writes or stamps registered volume rows; use volumes.find for read-only inspection.

Source code in octomate/managers/workspaces/base.py
async def resolve(
    self,
    thread_id: UUID7,
    project: Project | None,
    owner_id: UUID7 | None,
    ref: str | None = None,
) -> Workspace:
    """Record the owner's volumes and settle their paths without making files.

    A registered owner's tree comes with their package cache and their agent
    configuration. Unregistered
    senders receive a temporary chat path alone and cannot resolve project
    workspaces. This writes or stamps registered volume rows; use
    `volumes.find` for read-only inspection.
    """
    if owner_id is None and project is not None:
        raise UnregisteredProjectError(
            f"project {project.name!r} needs a registered user"
        )
    if project is not None and project.owner_id != owner_id:
        raise FileNotFoundError("Project not found")
    if owner_id is None:
        volumes: WorkspaceVolumes = {
            "work": Volume(
                storage=self.host_storage.temporary(thread_id), ephemeral=True
            )
        }
    else:
        # The owner's own volumes need nothing from the mirror or the tree,
        # so they are settled while those are.
        async with asyncio.TaskGroup() as tasks:
            cache = tasks.create_task(self.volumes.slot(owner_id, "cache"))
            config = tasks.create_task(self.volumes.slot(owner_id, "config"))
            work = await self.volumes.tree(
                owner_id,
                thread_id,
                project.id if project else None,
                ref,
                mirror=await self.mirrors.resolve(project),
            )
        volumes = {
            "work": work,
            "cache": cache.result(),
            "config": config.result(),
        }
    return Workspace(
        thread_id=thread_id,
        project=project,
        volumes=volumes,
        identity=self.identity,
    )

open async

open(
    thread_id: UUID7,
    project: Project | None,
    owner_id: UUID7 | None,
    ref: str | None = None,
) -> AsyncGenerator[Workspace]

Prepare a workspace and own its checkpoint or release when the run ends.

Source code in octomate/managers/workspaces/base.py
@asynccontextmanager
async def open(
    self,
    thread_id: UUID7,
    project: Project | None,
    owner_id: UUID7 | None,
    ref: str | None = None,
) -> AsyncGenerator[Workspace]:
    """Prepare a workspace and own its checkpoint or release when the run ends."""
    workspace = await self.resolve(thread_id, project, owner_id, ref)
    async with self.enter(workspace):
        yield workspace

enter async

enter(workspace: Workspace) -> AsyncGenerator[Workspace]

Prepare the working tree's source, then enter the volume composition.

Source code in octomate/managers/workspaces/base.py
@asynccontextmanager
async def enter(self, workspace: Workspace) -> AsyncGenerator[Workspace]:
    """Prepare the working tree's source, then enter the volume composition."""
    if isinstance(workspace.volume, GitVolume):
        if workspace.project is None:
            await self.mirrors.create()
        elif not workspace.path.is_dir():
            await self.mirrors.sync(workspace.project)
    async with workspace():
        yield workspace

prepare async

prepare(workspace: Workspace) -> Path

Prepare a persistent project tree for a handoff outside an invocation.

Source code in octomate/managers/workspaces/base.py
async def prepare(self, workspace: Workspace) -> Path:
    """Prepare a persistent project tree for a handoff outside an invocation."""
    volume = workspace.volume
    if workspace.project is None or not isinstance(volume, GitVolume):
        raise ValueError("A project handoff requires a Git working volume")
    if workspace.path.is_dir():
        return workspace.path
    mirror = await self.mirrors.sync(workspace.project)
    return await volume.materialize(mirror)

save async

save(thread: Thread, owner_id: UUID7) -> None

Leave this owner's finished turn where losing their tree cannot cost it: a validated snapshot imported into the project's mirror as the tree's own ref.

A fork owns its objects outright — nothing in a tree survives its removal — so without the import the tree is the only copy of what the turn did, and releasing it would be losing work rather than evicting a cache. That is what makes a tree disposable, and why the sweep is a disk decision.

A thread with no tree for this owner — in no project, or one whose turn never forked one — has nothing to leave.

The ref records what the tree holds rather than a history to protect. Imports update only that ref in the mirror and never reach the upstream.

A failure is logged rather than raised. The turn has already happened and already answered; failing it now would report a delivered answer as an error, and the next turn saves the same work again.

Source code in octomate/managers/workspaces/base.py
async def save(self, thread: Thread, owner_id: UUID7) -> None:
    """Leave this owner's finished turn where losing their tree cannot cost it:
    a validated snapshot imported into the project's mirror as the tree's
    own ref.

    A fork owns its objects outright — nothing in a tree survives its
    removal — so without the import the tree is the only copy of
    what the turn did, and releasing it would be losing work rather than
    evicting a cache. That is what makes a tree disposable, and why the sweep
    is a disk decision.

    A thread with no tree for this owner — in no project, or one whose turn
    never forked one — has nothing to leave.

    The ref records what the tree holds rather than a history to protect.
    Imports update only that ref in the mirror and never reach the upstream.

    A failure is logged rather than raised. The turn has already happened and
    already answered; failing it now would report a delivered answer as an
    error, and the next turn saves the same work again.
    """
    project = await self.projects.get(owner_id, thread=thread)
    if project is None:
        return
    volume = await self.volumes.find(owner_id, thread.id, project.id)
    if volume is not None:
        await volume.checkpoint(
            await self.mirrors.resolve(project),
            self.identity,
        )

saved async

saved(volume: GitVolume) -> bool

Whether this volume matches its canonical snapshot in the host mirror.

Workspace markers are writable by the harness and cannot authorize reclamation. Invalid or unreadable captures leave the tree unsaved.

Source code in octomate/managers/workspaces/base.py
async def saved(self, volume: GitVolume) -> bool:
    """Whether this volume matches its canonical snapshot in the host mirror.

    Workspace markers are writable by the harness and cannot authorize
    reclamation. Invalid or unreadable captures leave the tree unsaved.
    """
    if volume.project_id is None or volume.owner_id is None:
        return False
    project = await self.projects.get(volume.owner_id, project_id=volume.project_id)
    if project is None:
        return False
    mirror = (await self.mirrors.resolve(project)).path
    if not mirror.is_dir():
        return False
    ref = volume.snapshot_ref
    try:
        if not await run_git(
            "for-each-ref", "--format=%(objectname)", ref, cwd=mirror, isolated=True
        ):
            return False
        async with Snapshot.capture(volume.path, self.identity) as snapshot:
            return await snapshot.matches(mirror, ref)
    except (GitCommandError, OSError):
        logger.exception(
            "The tree %s could not be verified; keeping its work", volume.id
        )
        return False

reclaim async

reclaim(volume: GitVolume) -> bool

Delete a tree's folder only while nothing uses it and the mirror has its work, and answer whether it went.

The storage lock is held from the first check to the deletion. A turn that arrives meanwhile waits and forks afresh, instead of starting in a folder that is about to go or leaving work there after it was verified.

Source code in octomate/managers/workspaces/base.py
async def reclaim(self, volume: GitVolume) -> bool:
    """Delete a tree's folder only while nothing uses it and the mirror has
    its work, and answer whether it went.

    The storage lock is held from the first check to the deletion. A turn
    that arrives meanwhile waits and forks afresh, instead of starting in a
    folder that is about to go or leaving work there after it was verified.
    """
    storage = volume.storage
    async with storage.lock:
        if storage.uses:
            return False
        if not await self.saved(volume):
            logger.warning(
                "the tree %s for thread %s holds work the mirror does not "
                "have; keeping it",
                volume.id,
                volume.thread_id,
            )
            return False
        await storage.release()
    return True

prune async

prune(idle: float) -> list[UUID7]

Release every project tree nothing has used for idle seconds, and answer with the volumes that lost their folder.

Eviction, not a decision about whether a thread is over: abandonment is unobservable, so rather than guessing, being wrong here costs the next turn a fork instead of costing anyone their work. Which is only true of a tree the mirror already has, so one holding anything unsaved is kept and said out loud. Idleness is read from the row's last_used_at, which every open stamps.

A folder in a user's root that no row owns is reported and never deleted: the row is written before the folder, so such a folder is something this manager did not make.

Source code in octomate/managers/workspaces/base.py
async def prune(self, idle: float) -> list[UUID7]:
    """Release every project tree nothing has used for `idle` seconds, and
    answer with the volumes that lost their folder.

    Eviction, not a decision about whether a thread is over: abandonment is
    unobservable, so rather than guessing, being wrong here costs the next turn
    a fork instead of costing anyone their work. Which is only true of a tree
    the mirror already has, so one holding anything unsaved is kept and said
    out loud. Idleness is read from the row's `last_used_at`, which every
    `open` stamps.

    A folder in a user's root that no row owns is reported and never deleted:
    the row is written before the folder, so such a folder is something this
    manager did not make.
    """
    released: list[UUID7] = []
    # Three counts, because "why is that tree still there" has three answers
    # and the disk cannot tell them apart.
    kept_busy = kept_unsaved = 0
    cutoff = datetime.now(UTC) - timedelta(seconds=idle)
    with workspace_logfire.span("workspace.prune", idle=idle) as span:
        trees = await self.volumes.project_trees()
        for volume in trees:
            path = volume.path
            if not path.is_dir():
                continue
            if volume.last_used_at > cutoff:
                kept_busy += 1
            elif await self.reclaim(volume):
                released.append(volume.id)
            # Read before anything else can run: `reclaim` refused under the
            # lock a moment ago, so the use count still says which refusal.
            elif volume.storage.uses:
                kept_busy += 1
            else:
                kept_unsaved += 1
        span.set_attribute("released", len(released))
        span.set_attribute("kept_busy", kept_busy)
        span.set_attribute("kept_unsaved", kept_unsaved)
        span.set_attribute("unowned", await self.report_unowned())
        if released:
            logger.info("released %d idle tree(s)", len(released))
        return released

report_unowned async

report_unowned() -> int

Warn about every tree folder no row owns, and answer how many there are. Hidden folders are forks in progress, and are skipped.

Source code in octomate/managers/workspaces/base.py
async def report_unowned(self) -> int:
    """Warn about every tree folder no row owns, and answer how many there
    are. Hidden folders are forks in progress, and are skipped."""
    named: dict[uuid.UUID, Path] = {}
    unowned: list[Path] = []
    for path in self.volumes_dir.glob("*/tree/[!.]*"):
        try:
            named[uuid.UUID(path.name)] = path
        except ValueError:
            unowned.append(path)
    if named:
        owned_ids = await self.volumes.owned(list(named))
        unowned += [path for key, path in named.items() if key not in owned_ids]
    for path in unowned:
        logger.warning("%s has no volume row; leaving it", path)
    return len(unowned)

sweep async

sweep() -> None

Prune on the interval, for as long as the host runs.

A sweep that fails is logged and the next one still happens: reclaiming disk is maintenance, and a host that stops serving because it could not tidy up has the priority backwards.

Source code in octomate/managers/workspaces/base.py
async def sweep(self) -> None:
    """Prune on the interval, for as long as the host runs.

    A sweep that fails is logged and the next one still happens: reclaiming
    disk is maintenance, and a host that stops serving because it could not
    tidy up has the priority backwards.
    """
    while True:
        await asyncio.sleep(self.config.sweep_interval)
        try:
            await self.prune(self.config.idle_window)
        except Exception:
            logger.exception("the workspace sweep failed")

carry async

carry(
    source: Thread, thread: Thread, owner_id: UUID7
) -> None

Give thread, landed in source's project, a tree holding this owner's work as source left it — what a conversation moving to another thread takes of its work — and fork it.

Saved first: the source's last turn may not have been, and what it left uncommitted has to travel as uncommitted. The snapshot is filed under the new tree's ref too, so its first fork resumes into it the way a released tree does; on a branch of its own when the source was on its own, since two trees pushing one branch would overwrite each other. A source with no snapshot leaves thread to fork the project fresh.

Ignored files are copied across, an .env among them, since a snapshot never holds them. Ignored directories are not: they are dependencies and build output, which whatever runs in the landed tree makes again.

Source code in octomate/managers/workspaces/base.py
async def carry(self, source: Thread, thread: Thread, owner_id: UUID7) -> None:
    """Give `thread`, landed in `source`'s project, a tree holding this owner's
    work as `source` left it — what a conversation moving to another thread
    takes of its work — and fork it.

    Saved first: the source's last turn may not have been, and what it left
    uncommitted has to travel as uncommitted. The snapshot is filed under the
    new tree's ref too, so its first fork resumes into it the way a released
    tree does; on a branch of its own when the source was on its own, since
    two trees pushing one branch would overwrite each other. A source with no
    snapshot leaves `thread` to fork the project fresh.

    Ignored files are copied across, an `.env` among them, since a snapshot
    never holds them. Ignored directories are not: they are dependencies and
    build output, which whatever runs in the landed tree makes again.
    """
    project = await self.projects.get(owner_id, thread=source)
    if project is None:
        return
    await self.save(source, owner_id)
    origin = await self.volumes.find(owner_id, source.id, project.id)
    landing = await self.resolve(thread.id, project, owner_id)
    volume = landing.volume
    if not isinstance(volume, GitVolume):
        raise ValueError("A project handoff requires a Git working volume")
    mirror = (await self.mirrors.resolve(project)).path
    if origin is not None and await run_git(
        "ls-remote", str(mirror), origin.snapshot_ref, isolated=True
    ):
        saved = origin.snapshot_ref
        subject = await run_git(
            "show", "-s", "--format=%s", saved, cwd=mirror, isolated=True
        )
        filed = saved
        if subject.strip() == f"{SNAPSHOT_PREFIX}{origin.branch}":
            filed = await run_git(
                *self.identity.commit_flags,
                "commit-tree",
                f"{saved}^{{tree}}",
                "-p",
                f"{saved}^",
                "-m",
                f"{SNAPSHOT_PREFIX}{volume.branch}",
                cwd=mirror,
                isolated=True,
            )
        await run_git(
            "update-ref",
            volume.snapshot_ref,
            filed.strip(),
            cwd=mirror,
            isolated=True,
        )
    landed = await self.prepare(landing)
    if origin is None or not origin.path.is_dir():
        return
    await copy_ignored(origin.path, landed)

dismiss async

dismiss(thread: Thread, owner_id: UUID7) -> bool

Release this owner's tree on their agent's word that the work in it is done — the one release that is asked for rather than swept up — and answer whether it went.

Saved first, and released only when the save took: the sweep's rule, that a tree holding work the mirror has not seen is never thrown away, does not bend for being asked. So what this costs is what a prune costs, a fork on the thread's next turn with the ref laid back over it.

Source code in octomate/managers/workspaces/base.py
async def dismiss(self, thread: Thread, owner_id: UUID7) -> bool:
    """Release this owner's tree on their agent's word that the work in it is
    done — the one release that is asked for rather than swept up — and answer
    whether it went.

    Saved first, and released only when the save took: the sweep's rule, that
    a tree holding work the mirror has not seen is never thrown away, does not
    bend for being asked. So what this costs is what a prune costs, a fork on
    the thread's next turn with the ref laid back over it.
    """
    with workspace_logfire.span(
        "workspace.dismiss", thread_id=str(thread.id), released=False
    ) as span:
        await self.save(thread, owner_id)
        project = await self.projects.get(owner_id, thread=thread)
        if project is None:
            return False
        volume = await self.volumes.find(owner_id, thread.id, project.id)
        if volume is None or not volume.path.is_dir():
            return False
        released = await self.reclaim(volume)
        span.set_attribute("released", released)
        return released

octomate.managers.workspaces.mirrors

Project mirrors: the pristine checkouts workspaces fork from, and the git plumbing that syncs them.

logger module-attribute

logger = logging.getLogger(__name__)

BATCH_GIT_ENV module-attribute

BATCH_GIT_ENV = {
    "GIT_TERMINAL_PROMPT": "0",
    "GIT_SSH_COMMAND": "ssh -o BatchMode=yes",
}

BLANK_MIRROR module-attribute

BLANK_MIRROR = '.blank'

MirrorManager

Bases: Manager, Locks[str]

Every project's mirror: a pristine git checkout at mirrors_dir/<project>, made from the project's upstream and kept current by syncing from it.

A remote upstream is cloned and freshened by fetching; a directory upstream is git init'd and freshened by staging the folder's state and committing when anything changed — the same job with a directory in place of a URL, so the default branch becomes a history of the folder. The folder stays authoritative: carrying reviewed work back out to it is a deliberate step, not part of syncing.

A mirror stays on its default branch and no run ever writes to it; workspaces fork from it and are disposable.

Source code in octomate/managers/workspaces/mirrors.py
class MirrorManager(Manager, Locks[str]):
    """Every project's mirror: a pristine git checkout at ``mirrors_dir/<project>``,
    made from the project's upstream and kept current by syncing from it.

    A remote upstream is cloned and freshened by fetching; a directory upstream is
    `git init`'d and freshened by staging the folder's state and committing when
    anything changed — the same job with a directory in place of a URL, so the
    default branch becomes a history of the folder. The folder stays authoritative:
    carrying reviewed work back out to it is a deliberate step, not part of syncing.

    A mirror stays on its default branch and no run ever writes to it; workspaces
    fork from it and are disposable.
    """

    def __init__(
        self,
        config: MirrorsConfig | None = None,
        *,
        volumes: VolumeManager,
    ) -> None:
        self.config = config if config is not None else MirrorsConfig()
        self.synced: dict[str, float] = {}
        self.volumes: VolumeManager = volumes

    def path(self, project: Project | None = None) -> Path:
        """The initial storage location for a project's mirror or the blank mirror.

        Existing mirror records retain their stored location through `resolve`.

        Absolute, because directory sync points `GIT_DIR` here while running in the
        upstream folder, where a relative path would resolve against the wrong tree.
        """
        return self.volumes.host_storage.mirrors_dir / self.name(project)

    async def resolve(self, project: Project | None = None) -> GitVolume:
        """The service-owned mirror volume, without synchronizing its files."""
        return await self.volumes.mirror(
            project.id if project is not None else None, self.path(project)
        )

    def name(self, project: Project | None) -> str:
        """What this mirror is filed under, which is also what its lock and its
        freshness stamp are keyed by. The blank mirror is dot-prefixed, to keep it
        out of the way of the mirrors it sits among — those are named after
        projects, and so after directories people actually have."""
        return project.name if project is not None else BLANK_MIRROR

    async def sync(self, project: Project) -> GitVolume:
        """The mirror, current enough to fork from: created from the upstream when
        missing, freshened from it when the freshness window has lapsed.

        Serialized per mirror, so a burst of materializations costs one sync: the
        making of it waits inside `create`, and the freshening of it waits here, on
        the same lock. Which is why `create` is called before this takes it —
        `asyncio.Lock` is not reentrant, and both halves are the same mirror's turn.

        A freshen that fails degrades to the stale mirror with a warning rather than
        failing the caller — work continues on what the machine already has, and
        the stale stamp is not renewed, so the next sync tries again. A mirror
        that cannot be created is a hard failure: there is nothing to fall back to.
        """
        # Asked before `create`, which is where the waiting happens: a mirror this
        # call had to make is one nothing can be behind, so it is not fetched again
        # for the sync that made it.
        missing = not (await self.resolve(project)).path.is_dir()
        volume = await self.create(project)
        path = volume.path
        async with self.lock(project.name):
            if missing:
                self.synced[project.name] = time.monotonic()
                return volume
            last = self.synced.get(project.name)
            window = self.config.freshness_window
            if last is not None and time.monotonic() - last < window:
                return volume
            try:
                await self.freshen(project, path)
            except (GitCommandError, OSError) as error:
                logger.warning("mirror for %s is stale: %s", project.name, error)
                return volume
            self.synced[project.name] = time.monotonic()
        return volume

    async def create(self, project: Project | None = None) -> GitVolume:
        """The mirror, made where there is none, and where it is.

        A GitHub project is cloned onto its default branch. A local project is
        `git init`'d with its folder's contents committed. With no project at all it is the blank mirror,
        which is a `git init` and one empty commit — that commit being what makes it
        forkable rather than special, since a repository with no commit clones onto
        an unborn branch, where git refuses the ordinary things a run does with one.
        Its service-owned volume has no project association.

        Serialized per mirror and idempotent, which is what the blank one needs —
        two threads in no project starting at once both ask for it, and a mirror
        half-made is a mirror something would fork. `sync` holds the same lock for
        the freshening half, and takes it after this rather than around it.

        A partial mirror is worse than none — it would read as existing and turn
        every later sync into a stale-mirror warning — so a creation that fails or
        is cancelled removes what it left before the error travels on.
        """
        volume = await self.resolve(project)
        path = volume.path
        async with self.lock(self.name(project)):
            if path.is_dir():
                return volume
            path.parent.mkdir(parents=True, exist_ok=True)
            try:
                if isinstance(project, GithubProject):
                    await run_git(
                        "clone", project.remote_url, str(path), env=BATCH_GIT_ENV
                    )
                    return volume
                await run_git("init", "-b", "main", str(path))
                if project is None:
                    await run_git(
                        *self.config.identity.commit_flags,
                        "commit",
                        "--allow-empty",
                        "-m",
                        "empty",
                        cwd=path,
                    )
                else:
                    await self.commit_folder(project.root, path)
            except BaseException:
                shutil.rmtree(path, ignore_errors=True)
                raise
        return volume

    async def freshen(self, project: Project, path: Path) -> None:
        """Bring an existing mirror up to its upstream: fetch and move the default
        branch for a remote, stage-and-commit the folder for a directory.

        `--prune` follows upstream branch deletions; thread refs live outside the
        fetched refspec, so pruning never touches them. The hard reset is what a
        mirror allows that a working checkout would not: nothing else writes
        here, so the default branch simply follows upstream, force-pushes included.
        """
        if isinstance(project, GithubProject):
            await run_git("fetch", "--prune", "origin", cwd=path, env=BATCH_GIT_ENV)
            await run_git("reset", "--hard", "@{upstream}", cwd=path)
        else:
            await self.commit_folder(project.root, path)

    async def commit_folder(self, folder: Path, path: Path) -> None:
        """One sync of a directory upstream: stage exactly the folder's state into
        the mirror at `path`, and commit only when anything changed.

        Git's own index does the comparison. With `GIT_WORK_TREE` pointing at the
        folder, `add -A` stages additions, edits, and deletions in one pass while
        honoring the folder's own `.gitignore` — which is what keeps a served
        checkout's `.octomate/` out of its mirror — and no `.git` is ever created
        in the folder itself. The final reset materializes the commit into the
        mirror's tree; it never `git clean`s, so untracked state the mirror keeps
        survives every sync.
        """
        against = {
            "GIT_DIR": str(path / ".git"),
            "GIT_WORK_TREE": str(folder),
            # A scratch index, so the mirror's own index keeps tracking its HEAD.
            # Staging a deletion in the shared index would untrack the file, and
            # the final reset — which deletes what is tracked-but-gone and spares
            # what was never tracked — would then leave it behind in the mirror.
            "GIT_INDEX_FILE": str(path / ".git" / "sync-index"),
        }
        await run_git("add", "-A", cwd=folder, env=against)
        # An empty folder still needs an initial commit so its mirror can be forked.
        if not await run_git(
            "status", "--porcelain", cwd=folder, env=against
        ) and await run_git("rev-list", "--all", "--max-count=1", cwd=path):
            return
        await run_git(
            *self.config.identity.commit_flags,
            "commit",
            "--allow-empty",
            "-m",
            f"sync {folder}",
            cwd=folder,
            env=against,
        )
        await run_git("reset", "--hard", cwd=path)

config instance-attribute

config = config if config is not None else MirrorsConfig()

synced instance-attribute

synced: dict[str, float] = {}

volumes instance-attribute

volumes: VolumeManager = volumes

path

path(project: Project | None = None) -> Path

The initial storage location for a project's mirror or the blank mirror.

Existing mirror records retain their stored location through resolve.

Absolute, because directory sync points GIT_DIR here while running in the upstream folder, where a relative path would resolve against the wrong tree.

Source code in octomate/managers/workspaces/mirrors.py
def path(self, project: Project | None = None) -> Path:
    """The initial storage location for a project's mirror or the blank mirror.

    Existing mirror records retain their stored location through `resolve`.

    Absolute, because directory sync points `GIT_DIR` here while running in the
    upstream folder, where a relative path would resolve against the wrong tree.
    """
    return self.volumes.host_storage.mirrors_dir / self.name(project)

resolve async

resolve(project: Project | None = None) -> GitVolume

The service-owned mirror volume, without synchronizing its files.

Source code in octomate/managers/workspaces/mirrors.py
async def resolve(self, project: Project | None = None) -> GitVolume:
    """The service-owned mirror volume, without synchronizing its files."""
    return await self.volumes.mirror(
        project.id if project is not None else None, self.path(project)
    )

name

name(project: Project | None) -> str

What this mirror is filed under, which is also what its lock and its freshness stamp are keyed by. The blank mirror is dot-prefixed, to keep it out of the way of the mirrors it sits among — those are named after projects, and so after directories people actually have.

Source code in octomate/managers/workspaces/mirrors.py
def name(self, project: Project | None) -> str:
    """What this mirror is filed under, which is also what its lock and its
    freshness stamp are keyed by. The blank mirror is dot-prefixed, to keep it
    out of the way of the mirrors it sits among — those are named after
    projects, and so after directories people actually have."""
    return project.name if project is not None else BLANK_MIRROR

sync async

sync(project: Project) -> GitVolume

The mirror, current enough to fork from: created from the upstream when missing, freshened from it when the freshness window has lapsed.

Serialized per mirror, so a burst of materializations costs one sync: the making of it waits inside create, and the freshening of it waits here, on the same lock. Which is why create is called before this takes it — asyncio.Lock is not reentrant, and both halves are the same mirror's turn.

A freshen that fails degrades to the stale mirror with a warning rather than failing the caller — work continues on what the machine already has, and the stale stamp is not renewed, so the next sync tries again. A mirror that cannot be created is a hard failure: there is nothing to fall back to.

Source code in octomate/managers/workspaces/mirrors.py
async def sync(self, project: Project) -> GitVolume:
    """The mirror, current enough to fork from: created from the upstream when
    missing, freshened from it when the freshness window has lapsed.

    Serialized per mirror, so a burst of materializations costs one sync: the
    making of it waits inside `create`, and the freshening of it waits here, on
    the same lock. Which is why `create` is called before this takes it —
    `asyncio.Lock` is not reentrant, and both halves are the same mirror's turn.

    A freshen that fails degrades to the stale mirror with a warning rather than
    failing the caller — work continues on what the machine already has, and
    the stale stamp is not renewed, so the next sync tries again. A mirror
    that cannot be created is a hard failure: there is nothing to fall back to.
    """
    # Asked before `create`, which is where the waiting happens: a mirror this
    # call had to make is one nothing can be behind, so it is not fetched again
    # for the sync that made it.
    missing = not (await self.resolve(project)).path.is_dir()
    volume = await self.create(project)
    path = volume.path
    async with self.lock(project.name):
        if missing:
            self.synced[project.name] = time.monotonic()
            return volume
        last = self.synced.get(project.name)
        window = self.config.freshness_window
        if last is not None and time.monotonic() - last < window:
            return volume
        try:
            await self.freshen(project, path)
        except (GitCommandError, OSError) as error:
            logger.warning("mirror for %s is stale: %s", project.name, error)
            return volume
        self.synced[project.name] = time.monotonic()
    return volume

create async

create(project: Project | None = None) -> GitVolume

The mirror, made where there is none, and where it is.

A GitHub project is cloned onto its default branch. A local project is git init'd with its folder's contents committed. With no project at all it is the blank mirror, which is a git init and one empty commit — that commit being what makes it forkable rather than special, since a repository with no commit clones onto an unborn branch, where git refuses the ordinary things a run does with one. Its service-owned volume has no project association.

Serialized per mirror and idempotent, which is what the blank one needs — two threads in no project starting at once both ask for it, and a mirror half-made is a mirror something would fork. sync holds the same lock for the freshening half, and takes it after this rather than around it.

A partial mirror is worse than none — it would read as existing and turn every later sync into a stale-mirror warning — so a creation that fails or is cancelled removes what it left before the error travels on.

Source code in octomate/managers/workspaces/mirrors.py
async def create(self, project: Project | None = None) -> GitVolume:
    """The mirror, made where there is none, and where it is.

    A GitHub project is cloned onto its default branch. A local project is
    `git init`'d with its folder's contents committed. With no project at all it is the blank mirror,
    which is a `git init` and one empty commit — that commit being what makes it
    forkable rather than special, since a repository with no commit clones onto
    an unborn branch, where git refuses the ordinary things a run does with one.
    Its service-owned volume has no project association.

    Serialized per mirror and idempotent, which is what the blank one needs —
    two threads in no project starting at once both ask for it, and a mirror
    half-made is a mirror something would fork. `sync` holds the same lock for
    the freshening half, and takes it after this rather than around it.

    A partial mirror is worse than none — it would read as existing and turn
    every later sync into a stale-mirror warning — so a creation that fails or
    is cancelled removes what it left before the error travels on.
    """
    volume = await self.resolve(project)
    path = volume.path
    async with self.lock(self.name(project)):
        if path.is_dir():
            return volume
        path.parent.mkdir(parents=True, exist_ok=True)
        try:
            if isinstance(project, GithubProject):
                await run_git(
                    "clone", project.remote_url, str(path), env=BATCH_GIT_ENV
                )
                return volume
            await run_git("init", "-b", "main", str(path))
            if project is None:
                await run_git(
                    *self.config.identity.commit_flags,
                    "commit",
                    "--allow-empty",
                    "-m",
                    "empty",
                    cwd=path,
                )
            else:
                await self.commit_folder(project.root, path)
        except BaseException:
            shutil.rmtree(path, ignore_errors=True)
            raise
    return volume

freshen async

freshen(project: Project, path: Path) -> None

Bring an existing mirror up to its upstream: fetch and move the default branch for a remote, stage-and-commit the folder for a directory.

--prune follows upstream branch deletions; thread refs live outside the fetched refspec, so pruning never touches them. The hard reset is what a mirror allows that a working checkout would not: nothing else writes here, so the default branch simply follows upstream, force-pushes included.

Source code in octomate/managers/workspaces/mirrors.py
async def freshen(self, project: Project, path: Path) -> None:
    """Bring an existing mirror up to its upstream: fetch and move the default
    branch for a remote, stage-and-commit the folder for a directory.

    `--prune` follows upstream branch deletions; thread refs live outside the
    fetched refspec, so pruning never touches them. The hard reset is what a
    mirror allows that a working checkout would not: nothing else writes
    here, so the default branch simply follows upstream, force-pushes included.
    """
    if isinstance(project, GithubProject):
        await run_git("fetch", "--prune", "origin", cwd=path, env=BATCH_GIT_ENV)
        await run_git("reset", "--hard", "@{upstream}", cwd=path)
    else:
        await self.commit_folder(project.root, path)

commit_folder async

commit_folder(folder: Path, path: Path) -> None

One sync of a directory upstream: stage exactly the folder's state into the mirror at path, and commit only when anything changed.

Git's own index does the comparison. With GIT_WORK_TREE pointing at the folder, add -A stages additions, edits, and deletions in one pass while honoring the folder's own .gitignore — which is what keeps a served checkout's .octomate/ out of its mirror — and no .git is ever created in the folder itself. The final reset materializes the commit into the mirror's tree; it never git cleans, so untracked state the mirror keeps survives every sync.

Source code in octomate/managers/workspaces/mirrors.py
async def commit_folder(self, folder: Path, path: Path) -> None:
    """One sync of a directory upstream: stage exactly the folder's state into
    the mirror at `path`, and commit only when anything changed.

    Git's own index does the comparison. With `GIT_WORK_TREE` pointing at the
    folder, `add -A` stages additions, edits, and deletions in one pass while
    honoring the folder's own `.gitignore` — which is what keeps a served
    checkout's `.octomate/` out of its mirror — and no `.git` is ever created
    in the folder itself. The final reset materializes the commit into the
    mirror's tree; it never `git clean`s, so untracked state the mirror keeps
    survives every sync.
    """
    against = {
        "GIT_DIR": str(path / ".git"),
        "GIT_WORK_TREE": str(folder),
        # A scratch index, so the mirror's own index keeps tracking its HEAD.
        # Staging a deletion in the shared index would untrack the file, and
        # the final reset — which deletes what is tracked-but-gone and spares
        # what was never tracked — would then leave it behind in the mirror.
        "GIT_INDEX_FILE": str(path / ".git" / "sync-index"),
    }
    await run_git("add", "-A", cwd=folder, env=against)
    # An empty folder still needs an initial commit so its mirror can be forked.
    if not await run_git(
        "status", "--porcelain", cwd=folder, env=against
    ) and await run_git("rev-list", "--all", "--max-count=1", cwd=path):
        return
    await run_git(
        *self.config.identity.commit_flags,
        "commit",
        "--allow-empty",
        "-m",
        f"sync {folder}",
        cwd=folder,
        env=against,
    )
    await run_git("reset", "--hard", cwd=path)

octomate.managers.habitat

Invocation resources and each registered user's persistent habitat.

RunInterrupted

Bases: Exception

A requested stop reached a boundary before starting or after settling a run.

Source code in octomate/managers/habitat.py
class RunInterrupted(Exception):
    """A requested stop reached a boundary before starting or after settling a run."""

Interruption dataclass

A run-owned stop request, retained until its harness is ready to handle it.

Source code in octomate/managers/habitat.py
@dataclass
class Interruption:
    """A run-owned stop request, retained until its harness is ready to handle it."""

    requested: bool = False
    handler: Callable[[], Awaitable[None]] | None = None

    async def request(self) -> None:
        if self.requested:
            return
        self.requested = True
        if self.handler is not None:
            await self.handler()

    def check(self) -> None:
        if self.requested:
            raise RunInterrupted

    @asynccontextmanager
    async def handling(
        self, handler: Callable[[], Awaitable[None]]
    ) -> AsyncGenerator[None]:
        self.handler = handler
        try:
            if self.requested:
                await handler()
            yield
        finally:
            self.handler = None

requested class-attribute instance-attribute

requested: bool = False

handler class-attribute instance-attribute

handler: Callable[[], Awaitable[None]] | None = None

request async

request() -> None
Source code in octomate/managers/habitat.py
async def request(self) -> None:
    if self.requested:
        return
    self.requested = True
    if self.handler is not None:
        await self.handler()

check

check() -> None
Source code in octomate/managers/habitat.py
def check(self) -> None:
    if self.requested:
        raise RunInterrupted

handling async

handling(
    handler: Callable[[], Awaitable[None]],
) -> AsyncGenerator[None]
Source code in octomate/managers/habitat.py
@asynccontextmanager
async def handling(
    self, handler: Callable[[], Awaitable[None]]
) -> AsyncGenerator[None]:
    self.handler = handler
    try:
        if self.requested:
            await handler()
        yield
    finally:
        self.handler = None

Invocation dataclass

Core-authorized resources, valid only inside the core's owning contexts.

Core prepares the storage and acquires any habitat before yielding this value. Adapters borrow them for the call; core owns their lifetime and the cleanup required on completion, failure, or cancellation.

Source code in octomate/managers/habitat.py
@dataclass(frozen=True, kw_only=True)
class Invocation:
    """Core-authorized resources, valid only inside the core's owning contexts.

    Core prepares the storage and acquires any habitat before yielding this
    value. Adapters borrow them for the call; core owns their lifetime and the
    cleanup required on completion, failure, or cancellation.
    """

    id: UUID7  # Allocated by core before acquisition, shared with lifecycle events.
    conversation: Conversation  # Resolved by core; the run's history and settings.
    workspace: Workspace  # Prepared volume composition, owned by core for this call.
    habitat: Habitat  # Prepared environment, owned by core for this call.
    interruption: Interruption = field(default_factory=Interruption)
    parent_run_id: str | None = None  # The parent turn commissioning this invocation.
    parent_tool_call_id: str | None = None  # The commission or whisper call it answers.

    def __post_init__(self) -> None:
        if isinstance(self.habitat, ManagedHabitat):
            if self.owner_id is None:
                raise ValueError("Habitat execution requires a registered user")
            if self.habitat.user_id != self.owner_id:
                raise ValueError("Habitat and volume owners do not match")

    @property
    def owner_id(self) -> UUID7 | None:
        return self.workspace.owner_id

    @property
    def environment(self) -> dict[str, str]:
        """Settings that point the harness at the owner's own volumes, as the
        habitat shows them.

        Package managers keep their stores beneath the cache. Codex keeps its
        memory-bearing home in the config volume in every runtime; the other
        native CLIs retain their host configuration and login.
        """
        settings: dict[str, str] = {}
        cache = self.workspace.volumes.get("cache")
        if cache is not None:
            path = self.habitat.path(cache)
            settings.update(
                UV_CACHE_DIR=str(path / "uv"),
                npm_config_cache=str(path / "npm"),
                npm_config_store_dir=str(path / "pnpm"),
            )
        config = self.workspace.volumes.get("config")
        if config is not None and isinstance(self.habitat, NativeHabitat):
            settings["CODEX_HOME"] = str(self.habitat.path(config) / ".codex")
        if config is not None and isinstance(self.habitat, ManagedHabitat):
            path = self.habitat.path(config)
            settings.update(
                CLAUDE_CONFIG_DIR=str(path / ".claude"),
                CODEX_HOME=str(path / ".codex"),
                DSH_HOME=str(path / ".dsh"),
            )
        return settings

    @property
    def cwd(self) -> Path | PurePosixPath:
        """The harness's working directory; `workspace.path` remains host-side."""
        return self.habitat.path(self.volume)

    @property
    def thread_id(self) -> UUID7:
        return self.workspace.thread_id

    @property
    def project(self) -> Project | None:
        return self.workspace.project

    @property
    def volume(self) -> Volume:
        return self.workspace.volume

id instance-attribute

id: UUID7

conversation instance-attribute

conversation: Conversation

workspace instance-attribute

workspace: Workspace

habitat instance-attribute

habitat: Habitat

interruption class-attribute instance-attribute

interruption: Interruption = field(
    default_factory=Interruption
)

parent_run_id class-attribute instance-attribute

parent_run_id: str | None = None

parent_tool_call_id class-attribute instance-attribute

parent_tool_call_id: str | None = None

owner_id property

owner_id: UUID7 | None

environment property

environment: dict[str, str]

Settings that point the harness at the owner's own volumes, as the habitat shows them.

Package managers keep their stores beneath the cache. Codex keeps its memory-bearing home in the config volume in every runtime; the other native CLIs retain their host configuration and login.

cwd property

cwd: Path | PurePosixPath

The harness's working directory; workspace.path remains host-side.

thread_id property

thread_id: UUID7

project property

project: Project | None

volume property

volume: Volume

Residence dataclass

Source code in octomate/managers/habitat.py
@dataclass
class Residence:
    user_id: UUID7
    habitat: ManagedHabitat
    status: HabitatEvent
    lock: asyncio.Lock = field(default_factory=asyncio.Lock)
    invocations: set[UUID7] = field(default_factory=set)
    # How many of the invocations inside belong to each conversation.
    conversations: Counter[UUID7] = field(default_factory=Counter)
    needs_cleanup: bool = False  # Preparation began and shutdown has not completed.
    idle: asyncio.TimerHandle | None = None
    stopping: asyncio.Task[None] | None = None

user_id instance-attribute

user_id: UUID7

habitat instance-attribute

habitat: ManagedHabitat

status instance-attribute

status: HabitatEvent

lock class-attribute instance-attribute

lock: Lock = field(default_factory=asyncio.Lock)

invocations class-attribute instance-attribute

invocations: set[UUID7] = field(default_factory=set)

conversations class-attribute instance-attribute

conversations: Counter[UUID7] = field(
    default_factory=Counter
)

needs_cleanup class-attribute instance-attribute

needs_cleanup: bool = False

idle class-attribute instance-attribute

idle: TimerHandle | None = None

stopping class-attribute instance-attribute

stopping: Task[None] | None = None

HabitatManager dataclass

Source code in octomate/managers/habitat.py
@dataclass
class HabitatManager:
    config: HabitatConfig
    nerve: Nerve
    workspaces: WorkspaceManager
    name: str = "default"  # Separates named habitats for the same user.
    residences: dict[UUID7, Residence] = field(default_factory=dict, init=False)
    closed: bool = field(default=False, init=False)

    @asynccontextmanager
    async def invoke(
        self,
        *,
        thread: Thread,
        conversation: Conversation,
        owner_id: UUID7 | None,
        interruption: Interruption | None = None,
    ) -> AsyncGenerator[Invocation]:
        """Own one call's resources for the full consumption of its events.

        A sandbox runs for a registered user; an unregistered sender is refused
        before anything is prepared.
        """
        invocation_id = uuid7()
        control = interruption or Interruption()
        with habitat_logfire.span(
            "habitat.invoke",
            invocation_id=invocation_id,
            thread_id=thread.id,
            conversation_id=conversation.id,
            user_id=owner_id,
            provider=self.config.provider,
        ):
            projects = self.workspaces.projects
            if isinstance(self.config, NativeHabitatConfig):
                if thread.project_id is not None and owner_id is None:
                    raise UnregisteredProjectError(
                        "A project workspace requires a registered user"
                    )
                project = (
                    await projects.get(owner_id, thread=thread)
                    if owner_id is not None
                    else None
                )
                habitat = NativeHabitat(config=self.config)
                await habitat.prepare()
                try:
                    async with (
                        habitat.resources,
                        self.workspaces.open(thread.id, project, owner_id) as workspace,
                    ):
                        yield Invocation(
                            id=invocation_id,
                            conversation=conversation,
                            workspace=workspace,
                            habitat=habitat,
                            interruption=control,
                        )
                finally:
                    await habitat.stop()
                return
            if owner_id is None:
                raise HabitatError("Running in a sandbox requires a registered user")
            project = await projects.get(owner_id, thread=thread)
            scope = InvocationScope(
                user_id=owner_id, conversation_id=conversation.id, thread_id=thread.id
            )
            # Release the sandbox lease before the workspace it mounts.
            async with (
                self.workspaces.open(thread.id, project, owner_id) as workspace,
                self.enter(scope, invocation_id) as residence,
            ):
                yield Invocation(
                    id=invocation_id,
                    conversation=conversation,
                    workspace=workspace,
                    habitat=residence.habitat,
                    interruption=control,
                )

    def residenced(self, user_id: UUID7, conversation_id: UUID7) -> bool:
        """Whether an invocation of the conversation is inside the user's sandbox now."""
        residence = self.residences.get(user_id)
        return residence is not None and conversation_id in residence.conversations

    def residence(self, scope: InvocationScope) -> Residence:
        """Internal lookup; callers must supply a core-authorized owner."""
        if scope.user_id not in self.residences:
            habitat: ManagedHabitat
            match self.config:
                case SrtHabitatConfig() as config:
                    habitat = SrtHabitat(
                        config=config,
                        user_id=scope.user_id,
                        root=self.workspaces.root(scope.user_id),
                        name=self.name,
                    )
                case SbxHabitatConfig() as config:
                    habitat = SbxHabitat(
                        config=config,
                        user_id=scope.user_id,
                        root=self.workspaces.root(scope.user_id),
                        name=self.name,
                        config_dir=self.workspaces.host_storage.slot(
                            scope.user_id, "config"
                        ),
                    )
                case NativeHabitatConfig():
                    raise HabitatError("Habitat provider is 'native'; no habitat runs")
            self.residences[scope.user_id] = Residence(
                user_id=scope.user_id,
                habitat=habitat,
                status=HabitatProgressEvent(
                    user_id=scope.user_id,
                    habitat=habitat.id,
                    name=self.name,
                    sequence=0,
                    phase="unknown",
                ),
            )
        return self.residences[scope.user_id]

    def status(self, scope: InvocationScope) -> HabitatEvent:
        return self.residence(scope).status

    def report(
        self,
        residence: Residence,
        phase: Literal[
            "unknown", "preparing", "starting", "ready", "stopping", "stopped", "failed"
        ],
        *,
        scope: InvocationScope | None = None,
        invocation_id: UUID7 | None = None,
        error: HabitatError | None = None,
    ) -> None:
        if error is not None:
            if phase != "failed":
                raise ValueError("Habitat errors require the failed phase")
            residence.status = HabitatFailedEvent(
                user_id=residence.user_id,
                habitat=residence.habitat.id,
                name=self.name,
                sequence=residence.status.sequence + 1,
                invocation_id=invocation_id,
                thread_id=scope.thread_id if scope else None,
                message=str(error),
            )
        else:
            if phase == "failed":
                raise ValueError("Failed habitat reports require an error")
            residence.status = HabitatProgressEvent(
                user_id=residence.user_id,
                habitat=residence.habitat.id,
                name=self.name,
                sequence=residence.status.sequence + 1,
                invocation_id=invocation_id,
                thread_id=scope.thread_id if scope else None,
                phase=phase,
            )
        self.nerve.deliver(HabitatTopic(residence.user_id), Impulse(residence.status))
        self.nerve.deliver(UserTopic(residence.user_id), Impulse(residence.status))
        habitat_logfire.log(
            "error" if error is not None else "info",
            "Habitat {habitat} {phase}",
            attributes={
                "habitat": residence.habitat.id,
                "phase": phase,
                "invocation_id": invocation_id,
                "thread_id": scope.thread_id if scope else None,
                "conversation_id": scope.conversation_id if scope else None,
                "error": str(error) if error is not None else None,
            },
        )

    @asynccontextmanager
    async def enter(
        self, scope: InvocationScope, invocation_id: UUID7
    ) -> AsyncGenerator[Residence]:
        residence = self.residence(scope)
        async with residence.lock:
            if self.closed:
                raise HabitatError("Habitat manager is shutting down")
            if invocation_id in residence.invocations:
                raise HabitatError("Invocation is already inside this habitat")
            if residence.idle is not None:
                residence.idle.cancel()
                residence.idle = None
            if residence.status.phase != "ready":
                await self.prepare(residence, scope, invocation_id)
            residence.invocations.add(invocation_id)
            residence.conversations[scope.conversation_id] += 1
        try:
            yield residence
        finally:
            with anyio.CancelScope(shield=True):
                async with residence.lock:
                    residence.invocations.discard(invocation_id)
                    residence.conversations[scope.conversation_id] -= 1
                    if not residence.conversations[scope.conversation_id]:
                        del residence.conversations[scope.conversation_id]
                    if not residence.invocations and not self.closed:
                        residence.idle = asyncio.get_running_loop().call_later(
                            residence.habitat.idle_timeout, self.idle_out, residence
                        )

    @habitat_logfire.instrument(
        "habitat.prepare", extract_args=["scope", "invocation_id"]
    )
    async def prepare(
        self, residence: Residence, scope: InvocationScope, invocation_id: UUID7
    ) -> None:
        if residence.needs_cleanup:
            raise HabitatError(
                "Previous habitat cleanup is incomplete; stop it before retrying"
            )
        residence.needs_cleanup = True
        try:
            self.report(
                residence, "preparing", scope=scope, invocation_id=invocation_id
            )
            await residence.habitat.prepare()
            self.report(residence, "ready", scope=scope, invocation_id=invocation_id)
        except BaseException as error:
            failure = (
                error
                if isinstance(error, HabitatError)
                else HabitatError(
                    "Habitat preparation was interrupted; no agent was dispatched"
                )
            )
            try:
                with anyio.CancelScope(shield=True):
                    await self.halt(residence)
            finally:
                self.report(
                    residence,
                    "failed",
                    scope=scope,
                    invocation_id=invocation_id,
                    error=failure,
                )
            raise

    def idle_out(self, residence: Residence) -> None:
        residence.idle = None
        residence.stopping = asyncio.create_task(self.stop(residence))
        residence.stopping.add_done_callback(self.halted)

    @staticmethod
    def halted(task: asyncio.Task[None]) -> None:
        if not task.cancelled():
            error = task.exception()
            if error is not None and not isinstance(error, HabitatError):
                task.get_loop().call_exception_handler(
                    {
                        "message": "Unexpected habitat shutdown failure",
                        "exception": error,
                    }
                )

    @habitat_logfire.instrument("habitat.stop", extract_args=False)
    async def halt(self, residence: Residence) -> None:
        await residence.habitat.resources.aclose()
        await residence.habitat.stop()
        residence.needs_cleanup = False

    async def stop(self, residence: Residence, *, shutdown: bool = False) -> None:
        async with residence.lock:
            if residence.invocations and not shutdown:
                return
            if residence.idle is not None:
                residence.idle.cancel()
                residence.idle = None
            if not residence.needs_cleanup:
                return
            self.report(residence, "stopping")
            try:
                await self.halt(residence)
            except HabitatError as error:
                self.report(residence, "failed", error=error)
                raise
            self.report(residence, "stopped")

    async def close(self) -> None:
        self.closed = True
        for residence in self.residences.values():
            if residence.idle is not None:
                residence.idle.cancel()
        results = await asyncio.gather(
            *(
                self.stop(residence, shutdown=True)
                for residence in self.residences.values()
            ),
            return_exceptions=True,
        )
        for result in results:
            if isinstance(result, BaseException):
                raise result

config instance-attribute

config: HabitatConfig

nerve instance-attribute

nerve: Nerve

workspaces instance-attribute

workspaces: WorkspaceManager

name class-attribute instance-attribute

name: str = 'default'

residences class-attribute instance-attribute

residences: dict[UUID7, Residence] = field(
    default_factory=dict, init=False
)

closed class-attribute instance-attribute

closed: bool = field(default=False, init=False)

invoke async

invoke(
    *,
    thread: Thread,
    conversation: Conversation,
    owner_id: UUID7 | None,
    interruption: Interruption | None = None,
) -> AsyncGenerator[Invocation]

Own one call's resources for the full consumption of its events.

A sandbox runs for a registered user; an unregistered sender is refused before anything is prepared.

Source code in octomate/managers/habitat.py
@asynccontextmanager
async def invoke(
    self,
    *,
    thread: Thread,
    conversation: Conversation,
    owner_id: UUID7 | None,
    interruption: Interruption | None = None,
) -> AsyncGenerator[Invocation]:
    """Own one call's resources for the full consumption of its events.

    A sandbox runs for a registered user; an unregistered sender is refused
    before anything is prepared.
    """
    invocation_id = uuid7()
    control = interruption or Interruption()
    with habitat_logfire.span(
        "habitat.invoke",
        invocation_id=invocation_id,
        thread_id=thread.id,
        conversation_id=conversation.id,
        user_id=owner_id,
        provider=self.config.provider,
    ):
        projects = self.workspaces.projects
        if isinstance(self.config, NativeHabitatConfig):
            if thread.project_id is not None and owner_id is None:
                raise UnregisteredProjectError(
                    "A project workspace requires a registered user"
                )
            project = (
                await projects.get(owner_id, thread=thread)
                if owner_id is not None
                else None
            )
            habitat = NativeHabitat(config=self.config)
            await habitat.prepare()
            try:
                async with (
                    habitat.resources,
                    self.workspaces.open(thread.id, project, owner_id) as workspace,
                ):
                    yield Invocation(
                        id=invocation_id,
                        conversation=conversation,
                        workspace=workspace,
                        habitat=habitat,
                        interruption=control,
                    )
            finally:
                await habitat.stop()
            return
        if owner_id is None:
            raise HabitatError("Running in a sandbox requires a registered user")
        project = await projects.get(owner_id, thread=thread)
        scope = InvocationScope(
            user_id=owner_id, conversation_id=conversation.id, thread_id=thread.id
        )
        # Release the sandbox lease before the workspace it mounts.
        async with (
            self.workspaces.open(thread.id, project, owner_id) as workspace,
            self.enter(scope, invocation_id) as residence,
        ):
            yield Invocation(
                id=invocation_id,
                conversation=conversation,
                workspace=workspace,
                habitat=residence.habitat,
                interruption=control,
            )

residenced

residenced(user_id: UUID7, conversation_id: UUID7) -> bool

Whether an invocation of the conversation is inside the user's sandbox now.

Source code in octomate/managers/habitat.py
def residenced(self, user_id: UUID7, conversation_id: UUID7) -> bool:
    """Whether an invocation of the conversation is inside the user's sandbox now."""
    residence = self.residences.get(user_id)
    return residence is not None and conversation_id in residence.conversations

residence

residence(scope: InvocationScope) -> Residence

Internal lookup; callers must supply a core-authorized owner.

Source code in octomate/managers/habitat.py
def residence(self, scope: InvocationScope) -> Residence:
    """Internal lookup; callers must supply a core-authorized owner."""
    if scope.user_id not in self.residences:
        habitat: ManagedHabitat
        match self.config:
            case SrtHabitatConfig() as config:
                habitat = SrtHabitat(
                    config=config,
                    user_id=scope.user_id,
                    root=self.workspaces.root(scope.user_id),
                    name=self.name,
                )
            case SbxHabitatConfig() as config:
                habitat = SbxHabitat(
                    config=config,
                    user_id=scope.user_id,
                    root=self.workspaces.root(scope.user_id),
                    name=self.name,
                    config_dir=self.workspaces.host_storage.slot(
                        scope.user_id, "config"
                    ),
                )
            case NativeHabitatConfig():
                raise HabitatError("Habitat provider is 'native'; no habitat runs")
        self.residences[scope.user_id] = Residence(
            user_id=scope.user_id,
            habitat=habitat,
            status=HabitatProgressEvent(
                user_id=scope.user_id,
                habitat=habitat.id,
                name=self.name,
                sequence=0,
                phase="unknown",
            ),
        )
    return self.residences[scope.user_id]

status

status(scope: InvocationScope) -> HabitatEvent
Source code in octomate/managers/habitat.py
def status(self, scope: InvocationScope) -> HabitatEvent:
    return self.residence(scope).status

report

report(
    residence: Residence,
    phase: Literal[
        "unknown",
        "preparing",
        "starting",
        "ready",
        "stopping",
        "stopped",
        "failed",
    ],
    *,
    scope: InvocationScope | None = None,
    invocation_id: UUID7 | None = None,
    error: HabitatError | None = None,
) -> None
Source code in octomate/managers/habitat.py
def report(
    self,
    residence: Residence,
    phase: Literal[
        "unknown", "preparing", "starting", "ready", "stopping", "stopped", "failed"
    ],
    *,
    scope: InvocationScope | None = None,
    invocation_id: UUID7 | None = None,
    error: HabitatError | None = None,
) -> None:
    if error is not None:
        if phase != "failed":
            raise ValueError("Habitat errors require the failed phase")
        residence.status = HabitatFailedEvent(
            user_id=residence.user_id,
            habitat=residence.habitat.id,
            name=self.name,
            sequence=residence.status.sequence + 1,
            invocation_id=invocation_id,
            thread_id=scope.thread_id if scope else None,
            message=str(error),
        )
    else:
        if phase == "failed":
            raise ValueError("Failed habitat reports require an error")
        residence.status = HabitatProgressEvent(
            user_id=residence.user_id,
            habitat=residence.habitat.id,
            name=self.name,
            sequence=residence.status.sequence + 1,
            invocation_id=invocation_id,
            thread_id=scope.thread_id if scope else None,
            phase=phase,
        )
    self.nerve.deliver(HabitatTopic(residence.user_id), Impulse(residence.status))
    self.nerve.deliver(UserTopic(residence.user_id), Impulse(residence.status))
    habitat_logfire.log(
        "error" if error is not None else "info",
        "Habitat {habitat} {phase}",
        attributes={
            "habitat": residence.habitat.id,
            "phase": phase,
            "invocation_id": invocation_id,
            "thread_id": scope.thread_id if scope else None,
            "conversation_id": scope.conversation_id if scope else None,
            "error": str(error) if error is not None else None,
        },
    )

enter async

enter(
    scope: InvocationScope, invocation_id: UUID7
) -> AsyncGenerator[Residence]
Source code in octomate/managers/habitat.py
@asynccontextmanager
async def enter(
    self, scope: InvocationScope, invocation_id: UUID7
) -> AsyncGenerator[Residence]:
    residence = self.residence(scope)
    async with residence.lock:
        if self.closed:
            raise HabitatError("Habitat manager is shutting down")
        if invocation_id in residence.invocations:
            raise HabitatError("Invocation is already inside this habitat")
        if residence.idle is not None:
            residence.idle.cancel()
            residence.idle = None
        if residence.status.phase != "ready":
            await self.prepare(residence, scope, invocation_id)
        residence.invocations.add(invocation_id)
        residence.conversations[scope.conversation_id] += 1
    try:
        yield residence
    finally:
        with anyio.CancelScope(shield=True):
            async with residence.lock:
                residence.invocations.discard(invocation_id)
                residence.conversations[scope.conversation_id] -= 1
                if not residence.conversations[scope.conversation_id]:
                    del residence.conversations[scope.conversation_id]
                if not residence.invocations and not self.closed:
                    residence.idle = asyncio.get_running_loop().call_later(
                        residence.habitat.idle_timeout, self.idle_out, residence
                    )

prepare async

prepare(
    residence: Residence,
    scope: InvocationScope,
    invocation_id: UUID7,
) -> None
Source code in octomate/managers/habitat.py
@habitat_logfire.instrument(
    "habitat.prepare", extract_args=["scope", "invocation_id"]
)
async def prepare(
    self, residence: Residence, scope: InvocationScope, invocation_id: UUID7
) -> None:
    if residence.needs_cleanup:
        raise HabitatError(
            "Previous habitat cleanup is incomplete; stop it before retrying"
        )
    residence.needs_cleanup = True
    try:
        self.report(
            residence, "preparing", scope=scope, invocation_id=invocation_id
        )
        await residence.habitat.prepare()
        self.report(residence, "ready", scope=scope, invocation_id=invocation_id)
    except BaseException as error:
        failure = (
            error
            if isinstance(error, HabitatError)
            else HabitatError(
                "Habitat preparation was interrupted; no agent was dispatched"
            )
        )
        try:
            with anyio.CancelScope(shield=True):
                await self.halt(residence)
        finally:
            self.report(
                residence,
                "failed",
                scope=scope,
                invocation_id=invocation_id,
                error=failure,
            )
        raise

idle_out

idle_out(residence: Residence) -> None
Source code in octomate/managers/habitat.py
def idle_out(self, residence: Residence) -> None:
    residence.idle = None
    residence.stopping = asyncio.create_task(self.stop(residence))
    residence.stopping.add_done_callback(self.halted)

halted staticmethod

halted(task: Task[None]) -> None
Source code in octomate/managers/habitat.py
@staticmethod
def halted(task: asyncio.Task[None]) -> None:
    if not task.cancelled():
        error = task.exception()
        if error is not None and not isinstance(error, HabitatError):
            task.get_loop().call_exception_handler(
                {
                    "message": "Unexpected habitat shutdown failure",
                    "exception": error,
                }
            )

halt async

halt(residence: Residence) -> None
Source code in octomate/managers/habitat.py
@habitat_logfire.instrument("habitat.stop", extract_args=False)
async def halt(self, residence: Residence) -> None:
    await residence.habitat.resources.aclose()
    await residence.habitat.stop()
    residence.needs_cleanup = False

stop async

stop(
    residence: Residence, *, shutdown: bool = False
) -> None
Source code in octomate/managers/habitat.py
async def stop(self, residence: Residence, *, shutdown: bool = False) -> None:
    async with residence.lock:
        if residence.invocations and not shutdown:
            return
        if residence.idle is not None:
            residence.idle.cancel()
            residence.idle = None
        if not residence.needs_cleanup:
            return
        self.report(residence, "stopping")
        try:
            await self.halt(residence)
        except HabitatError as error:
            self.report(residence, "failed", error=error)
            raise
        self.report(residence, "stopped")

close async

close() -> None
Source code in octomate/managers/habitat.py
async def close(self) -> None:
    self.closed = True
    for residence in self.residences.values():
        if residence.idle is not None:
            residence.idle.cancel()
    results = await asyncio.gather(
        *(
            self.stop(residence, shutdown=True)
            for residence in self.residences.values()
        ),
        return_exceptions=True,
    )
    for result in results:
        if isinstance(result, BaseException):
            raise result