Skip to content

meta

meta

TaskMeta on-disk I/O — the persistence boundary for task state.

On disk each task is two sibling files keyed on its ID:

  • <task_id>_dossier.json — the wire-dossier file shield consumers read, in wire shape ({project, task, name}).
  • <task_id>_meta.yml — terok's internal bookkeeping (mode, workspace, web port, hooks_fired, exit_code, lifecycle state).

Format-as-contract: the JSON file's filename says "dossier" and its audience is "anyone consuming shield events", so its shape is the wire dossier — no projection, no key translation. The YAML file's filename says "meta" and its audience is terok-internal; ruamel keeps comments and round-trip ergonomics cheap.

The split is reconciled at the I/O boundary: read_task_meta returns one merged dict in internal-storage shape (project_name, task_id, …), write_task_meta splits a single dict back to both files atomically. Name edits and lifecycle updates can write their own file independently without overwriting each other.

CONTAINER_TEROK_CONFIG = '/home/dev/.terok' module-attribute

In-container mount point for the per-task agent-config dir.

__all__ = ['CONTAINER_TEROK_CONFIG', 'agent_config_dir', 'dossier_path', 'iter_task_ids', 'load_task_meta', 'mark_task_deleting', 'meta_path', 'read_task_meta', 'task_exists', 'tasks_archive_dir', 'tasks_meta_dir', 'update_task_exit_code', 'write_task_dossier', 'write_task_meta', 'write_task_state'] module-attribute

dossier_path(meta_dir, task_id)

Path to the wire-dossier JSON file — what shield consumers read.

The OCI dossier.meta_path annotation points operators at this file. Companion bookkeeping lives at the _meta.yml sibling.

Source code in src/terok/lib/orchestration/tasks/meta.py
def dossier_path(meta_dir: Path, task_id: str) -> Path:
    """Path to the wire-dossier JSON file — what shield consumers read.

    The OCI ``dossier.meta_path`` annotation points operators at *this*
    file.  Companion bookkeeping lives at the ``_meta.yml`` sibling.
    """
    _reject_unsafe_id(task_id, "task_id")
    return meta_dir / f"{task_id}{_DOSSIER_SUFFIX}"

meta_path(meta_dir, task_id)

Path to the orchestrator-bookkeeping YAML — terok-internal state.

Holds everything except the wire-dossier triple. Single consumer (terok itself), so ruamel round-tripping is fine.

Source code in src/terok/lib/orchestration/tasks/meta.py
def meta_path(meta_dir: Path, task_id: str) -> Path:
    """Path to the orchestrator-bookkeeping YAML — terok-internal state.

    Holds everything except the wire-dossier triple.  Single consumer
    (terok itself), so ruamel round-tripping is fine.
    """
    _reject_unsafe_id(task_id, "task_id")
    return meta_dir / f"{task_id}{_META_SUFFIX}"

read_task_meta(meta_dir, task_id)

Compose the orchestrator's logical task-meta dict from the on-disk pair.

Reads the wire-dossier JSON and the internal YAML, translates the JSON's wire keys back to internal storage names, and returns the union. Either file may be absent. Returns None only when neither file is on disk.

Source code in src/terok/lib/orchestration/tasks/meta.py
def read_task_meta(meta_dir: Path, task_id: str) -> dict | None:
    """Compose the orchestrator's logical task-meta dict from the on-disk pair.

    Reads the wire-dossier JSON and the internal YAML, translates the
    JSON's wire keys back to internal storage names, and returns the
    union.  Either file may be absent.  Returns ``None`` only when
    neither file is on disk.
    """
    json_path = dossier_path(meta_dir, task_id)
    yml_path = meta_path(meta_dir, task_id)

    if not (json_path.is_file() or yml_path.is_file()):
        return None

    return _merge_dossier_into(_read_yml_meta(yml_path), _read_json_meta(json_path))

write_task_meta(dossier_handle, meta)

Atomic split-write: _dossier.json + _meta.yml in one atomic step each.

dossier_handle is a dossier-file handle — what dossier_path returns and what load_task_meta hands back. The companion bookkeeping path is derived by swapping the suffix. Atomic-rename writes (.tmp + os.replace) on each file mean a partial write under EINTR / power loss can leave one stale and the other fresh, but never a half-written file — readers always get a parseable shape.

Source code in src/terok/lib/orchestration/tasks/meta.py
def write_task_meta(dossier_handle: Path, meta: dict) -> None:
    """Atomic split-write: ``_dossier.json`` + ``_meta.yml`` in one atomic step each.

    *dossier_handle* is a dossier-file handle — what
    [`dossier_path`][terok.lib.orchestration.tasks.dossier_path] returns
    and what [`load_task_meta`][terok.lib.orchestration.tasks.load_task_meta]
    hands back.  The companion bookkeeping path is derived by swapping
    the suffix.  Atomic-rename writes (``.tmp`` + ``os.replace``) on each
    file mean a partial write under EINTR / power loss can leave one
    stale and the other fresh, but never a half-written file — readers
    always get a parseable shape.
    """
    write_task_dossier(dossier_handle, meta)
    write_task_state(dossier_handle, meta)

write_task_dossier(dossier_handle, meta)

Write task identity and name without replacing lifecycle state.

Accepts the merged metadata shape; ignores all bookkeeping fields.

Source code in src/terok/lib/orchestration/tasks/meta.py
def write_task_dossier(dossier_handle: Path, meta: dict) -> None:
    """Write task identity and name without replacing lifecycle state.

    Accepts the merged metadata shape; ignores all bookkeeping fields.
    """
    meta_dir, task_id = _dossier_handle_to_dir_and_id(dossier_handle)
    meta_dir.mkdir(parents=True, exist_ok=True)

    dossier = {
        wire_key: str(meta[internal_key])
        for internal_key, wire_key in _DOSSIER_TO_WIRE.items()
        if meta.get(internal_key)
    }
    _atomic_write(
        dossier_path(meta_dir, task_id),
        json.dumps(dossier, indent=2, ensure_ascii=False, default=str) + "\n",
    )

write_task_state(dossier_handle, meta)

Write lifecycle state without replacing task identity or name.

Accepts the merged metadata shape; ignores all dossier fields.

Source code in src/terok/lib/orchestration/tasks/meta.py
def write_task_state(dossier_handle: Path, meta: dict) -> None:
    """Write lifecycle state without replacing task identity or name.

    Accepts the merged metadata shape; ignores all dossier fields.
    """
    meta_dir, task_id = _dossier_handle_to_dir_and_id(dossier_handle)
    meta_dir.mkdir(parents=True, exist_ok=True)
    state = {k: v for k, v in meta.items() if k not in _DOSSIER_INTERNAL_KEYS}
    _atomic_write(meta_path(meta_dir, task_id), _yaml_dump(state))

iter_task_ids(meta_dir)

Yield every task ID with at least one meta file in meta_dir.

Source code in src/terok/lib/orchestration/tasks/meta.py
def iter_task_ids(meta_dir: Path) -> Iterator[str]:
    """Yield every task ID with at least one meta file in *meta_dir*."""
    if not meta_dir.is_dir():
        return
    seen: set[str] = set()
    for path in meta_dir.iterdir():
        if not path.is_file() or path.name.endswith(".tmp"):
            continue
        tid = _task_id_from_filename(path.name)
        if tid and tid not in seen:
            seen.add(tid)
            yield tid

task_exists(project_name, task_id)

Return True if any task-meta file exists for (project_name, task_id).

Source code in src/terok/lib/orchestration/tasks/meta.py
def task_exists(project_name: str, task_id: str) -> bool:
    """Return ``True`` if any task-meta file exists for ``(project_name, task_id)``."""
    meta_dir = tasks_meta_dir(project_name)
    return dossier_path(meta_dir, task_id).is_file() or meta_path(meta_dir, task_id).is_file()

tasks_meta_dir(project_name)

Return the directory containing task metadata files for project_name.

Source code in src/terok/lib/orchestration/tasks/meta.py
def tasks_meta_dir(project_name: str) -> Path:
    """Return the directory containing task metadata files for *project_name*."""
    _reject_unsafe_id(project_name, "project_name")
    return core_state_dir() / "projects" / project_name / "tasks"

agent_config_dir(project_name, task_id)

Host path of the agent-config dir bind-mounted at CONTAINER_TEROK_CONFIG.

Source code in src/terok/lib/orchestration/tasks/meta.py
def agent_config_dir(project_name: str, task_id: str) -> Path:
    """Host path of the agent-config dir bind-mounted at `CONTAINER_TEROK_CONFIG`."""
    _reject_unsafe_id(project_name, "project_name")
    _reject_unsafe_id(task_id, "task_id")
    return load_project(project_name).tasks_root / str(task_id) / "agent-config"

tasks_archive_dir(project_name)

Return the directory containing archived task data for project_name.

Lives under the namespace archive tree (archive/<pid>/tasks/) so operators can find all archived data in one location. On project deletion the entire archive/<pid>/ subtree is bundled into the project snapshot and removed.

Source code in src/terok/lib/orchestration/tasks/meta.py
def tasks_archive_dir(project_name: str) -> Path:
    """Return the directory containing archived task data for *project_name*.

    Lives under the namespace archive tree (``archive/<pid>/tasks/``) so
    operators can find all archived data in one location.  On project
    deletion the entire ``archive/<pid>/`` subtree is bundled into the
    project snapshot and removed.
    """
    _reject_unsafe_id(project_name, "project_name")
    return archive_dir() / project_name / "tasks"

update_task_exit_code(project_name, task_id, exit_code)

Update task metadata with exit code and final status.

Parameters:

Name Type Description Default
project_name str

The project name

required
task_id str

The task ID

required
exit_code int | None

The exit code from the task, or None if unknown/failed

required
Source code in src/terok/lib/orchestration/tasks/meta.py
def update_task_exit_code(project_name: str, task_id: str, exit_code: int | None) -> None:
    """Update task metadata with exit code and final status.

    Args:
        project_name: The project name
        task_id: The task ID
        exit_code: The exit code from the task, or None if unknown/failed
    """
    meta_dir = tasks_meta_dir(project_name)
    meta = read_task_meta(meta_dir, task_id)
    if meta is None:
        return
    meta["exit_code"] = exit_code
    write_task_state(dossier_path(meta_dir, task_id), meta)

load_task_meta(project_name, task_id, expected_mode=None)

Load task metadata and optionally validate mode.

Returns (meta, dossier_path): the merged in-memory dict (in its internal storage shape — project_name / task_id / …) plus the canonical dossier-file handle for write-back via write_task_state(dossier_path, meta). Raises SystemExit if the task is unknown or its mode conflicts with expected_mode.

Source code in src/terok/lib/orchestration/tasks/meta.py
def load_task_meta(
    project_name: str, task_id: str, expected_mode: str | None = None
) -> tuple[dict, Path]:
    """Load task metadata and optionally validate mode.

    Returns ``(meta, dossier_path)``: the merged in-memory dict (in
    its internal storage shape — ``project_name`` / ``task_id`` / …)
    plus the canonical dossier-file handle for write-back via
    ``write_task_state(dossier_path, meta)``.  Raises SystemExit if
    the task is unknown or its mode conflicts with *expected_mode*.
    """
    meta_dir = tasks_meta_dir(project_name)
    meta = read_task_meta(meta_dir, task_id)
    if meta is None:
        raise SystemExit(f"Unknown task {task_id}")
    if expected_mode is not None:
        _check_mode(meta, expected_mode)
    return meta, dossier_path(meta_dir, task_id)

mark_task_deleting(project_name, task_id)

Persist deleting: true to the task's metadata file.

Source code in src/terok/lib/orchestration/tasks/meta.py
def mark_task_deleting(project_name: str, task_id: str) -> None:
    """Persist ``deleting: true`` to the task's metadata file."""
    try:
        meta_dir = tasks_meta_dir(project_name)
        meta = read_task_meta(meta_dir, task_id)
        if meta is None:
            return
        meta["deleting"] = True
        write_task_state(dossier_path(meta_dir, task_id), meta)
    except Exception as e:
        _log_debug(f"mark_task_deleting: failed project_name={project_name} task_id={task_id}: {e}")