tasks
tasks
¶
Task metadata, lifecycle, and query operations.
This package is the single import surface for task operations —
from terok.lib.orchestration.tasks import … resolves every public
name below. The implementation is split into focused submodules:
meta— the on-disk I/O boundary: the dossier/bookkeeping split-write protocol, path helpers, and the directories task state lives in.identity— task ID generation, validation, and prefix resolution.naming— task name sanitization and random-name generation.query— theTaskMetaread model and the functions that hydrate it from disk + live container state.lifecycle— create, rename, delete (with archive-on-delete), stop, login, and status.archive— reading the immutable snapshots a deletion leaves behind.
Container runner functions (task_run_cli, task_run_headless,
task_restart) live in the companion task_runners module.
Status computation and domain value objects live in task_state;
their presentation tables live in task_display. Log viewing lives
in task_logs.
CONTAINER_MODES = ('cli', 'web', 'run', 'toad')
module-attribute
¶
All valid container mode suffixes used in container naming.
CONTAINER_TEROK_CONFIG = '/home/dev/.terok'
module-attribute
¶
In-container mount point for the per-task agent-config dir.
TASK_NAME_MAX_LEN = 60
module-attribute
¶
Maximum length of a sanitized task name.
__all__ = ['ArchivedTask', 'CONTAINER_MODES', 'CONTAINER_TEROK_CONFIG', 'TASK_NAME_MAX_LEN', 'ContainerEventStream', 'TaskDeleteResult', 'TaskMeta', 'agent_config_dir', 'capture_task_logs', 'container_event_stream', 'container_name', 'dossier_path', 'generate_task_name', 'get_all_task_states', 'get_login_command', 'get_task_container_state', 'get_task_meta', 'get_tasks', 'is_task_id', 'iter_task_ids', 'list_archived_tasks', 'load_task_meta', 'lookup_container_by_pt', 'mark_task_deleting', 'meta_path', 'normalize_task_id_input', 'read_task_meta', 'resolve_task_id', 'sanitize_task_name', 'task_archive_list', 'task_archive_logs', 'task_delete', 'task_exists', 'task_list', 'task_login', 'task_new', 'task_rename', 'task_status', 'task_stop', 'tasks_archive_dir', 'tasks_meta_dir', 'update_task_exit_code', 'validate_task_name', 'wait_for_container_exit', 'write_task_meta', 'write_task_state']
module-attribute
¶
ArchivedTask(archive_dir, archived_at, task_id, name, mode, exit_code)
dataclass
¶
TaskDeleteResult(task_id, warnings)
dataclass
¶
Outcome of a task deletion — always completes, collects warnings.
The task is considered deleted regardless (metadata and workspace
removed), but individual cleanup steps may fail. warnings
carries human-readable descriptions of any steps that did not
complete cleanly.
ContainerEventStream
¶
Bases: Protocol
Structural type for a podman container-event subscription.
Matches terok_sandbox's PodmanEventStream: a closable iterator of
container lifecycle events. Declared here so consumers (the TUI poller)
needn't import the backend type, and so the contract is the minimum a
consumer relies on — iterate, then close() to terminate the child.
__iter__()
¶
TaskMeta(container_state=None, exit_code=None, deleting=False, initialized=False, starting=False, *, task_id, project_name='', mode, workspace, web_port, web_token=None, backend=None, name='', agent=None, unrestricted=None, debug=False, work_status=None, work_message=None, shield_state=None, dns_tier=None, bypass_closes_at=None, prompts=None, rotation_lines=(), created_at=None)
dataclass
¶
Bases: TaskState
Lightweight metadata snapshot for a single task.
Inherits lifecycle fields (container_state, exit_code,
deleting, initialized) from TaskState.
task_id
instance-attribute
¶
project_name = ''
class-attribute
instance-attribute
¶
Project the task belongs to.
Carried in the meta JSON so consumers that don't already know the
project (e.g. terok-shield's host-side dossier resolver, which only
has the meta-path pointer) can render full project/task identity
without re-deriving it from the on-disk path. Empty string for
pre-this-release meta files; the lifecycle backfills it on the
next mutation.
mode
instance-attribute
¶
workspace
instance-attribute
¶
web_port
instance-attribute
¶
web_token = None
class-attribute
instance-attribute
¶
backend = None
class-attribute
instance-attribute
¶
name = ''
class-attribute
instance-attribute
¶
agent = None
class-attribute
instance-attribute
¶
unrestricted = None
class-attribute
instance-attribute
¶
debug = False
class-attribute
instance-attribute
¶
Whether the task was launched with the hardening floor relaxed
(terok task run --debug): its supervisor children stay ptrace-able
so a debugger can attach. Drives the read-only
DEBUG_BADGE in the TUI —
there is no TUI control to toggle it (the trigger is CLI-only).
work_status = None
class-attribute
instance-attribute
¶
work_message = None
class-attribute
instance-attribute
¶
shield_state = None
class-attribute
instance-attribute
¶
dns_tier = None
class-attribute
instance-attribute
¶
The DNS tier this task launched with, or None when not yet known.
Populated at runtime by the TUI's shield-state worker, never persisted — like
shield_state.
bypass_closes_at = None
class-attribute
instance-attribute
¶
When the task's open bypass window closes, by the local wall clock;
None when none is open. The kernel counts the window down and keeps
no deadline anywhere else, so the TUI's shield-state worker reads the
seconds left once and anchors them here — the task pane then counts down
without asking the kernel again. Runtime-only, like shield_state.
prompts = None
class-attribute
instance-attribute
¶
Whether a refusal in this task is put to the operator: asking,
muted, off (it started with clearance off and runs no hub), or
unknown (its clearance hub did not say). None when not read — the
task is not running, so no hub holds a mute. Runtime-only, like
shield_state.
rotation_lines = ()
class-attribute
instance-attribute
¶
The degraded-DNS-tier warning for the task — the policy names its tier
pins to the addresses they resolved to — worded for the posture it was
read in; empty when nothing is at risk. Runtime-only, like
shield_state.
created_at = None
class-attribute
instance-attribute
¶
status
property
¶
Compute effective status from live container state + metadata.
adopt_live_state(fresh)
¶
Copy disk-derived live fields from a fresher snapshot, in place.
The TUI's container-state poll re-reads every task each tick but keeps
the displayed row objects. Those rows carry more than a container
state: the ready_at init marker, work status and exit code all
drift while a row stays put — so a container that is already
running still needs its initialized flag synced to move from
init to running. This refreshes exactly those fields and
leaves identity and the TUI-local starting launch flag untouched.
Source code in src/terok/lib/orchestration/tasks/query.py
load(project_name, task_id)
classmethod
¶
Load a TaskMeta from disk, with live container state hydrated.
Raises SystemExit if the task metadata file is not found.
Equivalent to the free-fn
get_task_meta,
kept as the canonical entry point so callers reach the class
through its own factory.
Source code in src/terok/lib/orchestration/tasks/query.py
container_name(project_name, mode, task_id)
¶
list_archived_tasks(project_name)
¶
Return archived tasks for project_name, sorted newest-first.
Source code in src/terok/lib/orchestration/tasks/archive.py
task_archive_list(project_name)
¶
Print archived tasks for project_name.
Source code in src/terok/lib/orchestration/tasks/archive.py
task_archive_logs(project_name, archive_id)
¶
Return the log file path for an archived task identified by archive_id.
archive_id is matched against archive directory names (prefix match).
Returns the log file path if found, or None.
Source code in src/terok/lib/orchestration/tasks/archive.py
is_task_id(text)
¶
normalize_task_id_input(raw)
¶
Collapse user-input variants to the canonical lowercase form.
Strips hyphens, lowercases, and applies the Crockford
I/L → 1, O → 0 substitutions. The result is still subject
to _TASK_ID_PREFIX_RE downstream — this only widens what
we accept, never what we emit.
Call-site discipline: only call this at user-interactive CLI
boundaries — argparse dispatch handlers and argcomplete completers.
Internal code paths (lib/*, tui/*, TUI pickers, clearance,
anything reading task IDs from disk, OCI annotations, or runtime
state) always work with canonical lowercase IDs and must never
re-normalise. Leaking this tolerance inward quietly defeats the
"we encode only in canonical form" invariant.
Source code in src/terok/lib/orchestration/tasks/identity.py
resolve_task_id(project_name, prefix)
¶
Resolve a (possibly partial) task ID to its full form.
The prefix is first run through normalize_task_id_input,
so callers may pass uppercase, hyphenated, or ambiguous-letter
variants (K3-V8H, k3v8I) — they collapse to the canonical
lowercase form before validation and lookup.
Raises SystemExit with an actionable message on zero or multiple matches.
Source code in src/terok/lib/orchestration/tasks/identity.py
capture_task_logs(project, task_id, mode)
¶
Capture container logs to the task's logs/ directory on the host.
Writes stdout/stderr from podman logs to
<tasks_root>/<task_id>/logs/container.log. Returns the log file
path on success, or None if the container doesn't exist or podman
fails.
project may be a ProjectConfig or a project name string
(the string form loads the config internally for backward compat).
Source code in src/terok/lib/orchestration/tasks/lifecycle.py
get_login_command(project_name, task_id)
¶
Return the podman exec command to log into a task container.
task_delete(project_name, task_id)
¶
Delete a task's workspace, metadata, and any associated containers.
Before removal, captures container logs and archives the task metadata
and logs to archive/<project_name>/tasks/. Containers are stopped
best-effort via podman using the <project.name>-<mode>-<task_id>
naming scheme. Returns a TaskDeleteResult so the caller can
present any warnings from cleanup steps that failed.
Source code in src/terok/lib/orchestration/tasks/lifecycle.py
task_login(project_name, task_id)
¶
task_new(project_name, *, name=None)
¶
Create a new task with a fresh workspace for a project.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
project_name
|
str
|
The project to create the task under. |
required |
name
|
str | None
|
Optional human-readable name. Allowed characters are
lowercase letters, digits, hyphens, and underscores.
If |
None
|
Workspace Initialization Protocol:¶
Each task gets its own workspace directory that persists across container runs. When a container starts, the init script (init-ssh-and-repo.sh) needs to know whether this is:
- A NEW task that should be reset to the latest remote HEAD
- A RESTARTED task where local changes should be preserved
We use a marker file (.new-task-marker) to signal intent:
- task_new() creates the marker in the workspace directory
- init-ssh-and-repo.sh checks for the marker:
- If marker exists: reset to origin/HEAD, then delete marker
- If no marker: fetch only, preserve local state
- Subsequent container runs on the same task won't see the marker, so local work is preserved
This handles edge cases like: - Stale workspace from incompletely deleted previous task with same ID - Ensuring new tasks always start with latest code
Source code in src/terok/lib/orchestration/tasks/lifecycle.py
task_rename(project_name, task_id, new_name)
¶
Rename a task by updating its metadata file.
Sanitizes new_name and writes the result to the task's metadata file.
Raises SystemExit if the task is unknown or the sanitized name is invalid.
Source code in src/terok/lib/orchestration/tasks/lifecycle.py
task_status(project_name, task_id, *, verbose=False)
¶
Show live task status with container state diagnostics.
With verbose, append the on-host debug locations — container ID,
bind mounts, and the supervisor log / wrapper / PID / sidecar paths
— so an operator can point a human at the right file to send back
instead of hand-rolling a podman inspect incantation.
Source code in src/terok/lib/orchestration/tasks/lifecycle.py
590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 | |
task_stop(project_name, task_id, *, timeout=None)
¶
Gracefully stop a running task container.
Uses podman stop --time <N> to give the container timeout seconds
before SIGKILL. When timeout is None the project's
run.shutdown_timeout setting is used (default 10 s).
Source code in src/terok/lib/orchestration/tasks/lifecycle.py
wait_for_container_exit(container_name, project_name, task_id, timeout=7200)
¶
Wait for container_name to exit and record its code in task metadata.
Returns (exit_code, error_message). On a successful wait
error_message is None and the real exit code is persisted
— including a legitimate exit code of 124, which is no longer
conflated with the watcher's own timeout. On timeout exit_code
is None and the error message describes it.
Source code in src/terok/lib/orchestration/tasks/lifecycle.py
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
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
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
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
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
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
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
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
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
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
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
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
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
generate_task_name(project_name=None)
¶
Generate a random human-readable task name (e.g. talented-toucan).
When project_name is given, name categories are resolved from config:
project tasks.name_categories → global tasks.name_categories
→ deterministic 3-category selection based on project name hash.
Source code in src/terok/lib/orchestration/tasks/naming.py
sanitize_task_name(raw)
¶
Sanitize a raw task name into a slug-style identifier.
Strips whitespace, lowercases, replaces spaces with hyphens,
removes characters outside [a-z0-9_-], collapses consecutive
hyphens, strips trailing hyphens, and truncates to
TASK_NAME_MAX_LEN. Returns None if the result is empty.
Leading hyphens are preserved so callers can detect and reject them
(a name starting with - looks like a CLI flag).
Source code in src/terok/lib/orchestration/tasks/naming.py
validate_task_name(sanitized)
¶
Return an error message if sanitized is not a valid task name, else None.
A name is invalid if it starts with a hyphen (looks like a CLI flag).
Callers should first check for None from sanitize_task_name
(which indicates the name was empty after sanitization).
Source code in src/terok/lib/orchestration/tasks/naming.py
container_event_stream(project_name)
¶
Subscribe to live podman container events for project_name, or None.
The push-based companion to
get_all_task_states:
a closable iterator of lifecycle events for the project's containers, so a
watcher reacts to a container starting / dying instead of polling
podman ps. Returns None when the subscription can't be opened (no
podman on PATH, or a non-podman runtime); the caller then leans on the
periodic resync.
Source code in src/terok/lib/orchestration/tasks/query.py
get_all_task_states(project_name, tasks)
¶
Map each task to its live container state via a single batch query.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
project_name
|
str
|
The project whose containers to query. |
required |
tasks
|
list[TaskMeta]
|
List of |
required |
Returns:
| Type | Description |
|---|---|
dict[str, str | None] | None
|
|
dict[str, str | None] | None
|
batch query itself failed (podman missing, or |
dict[str, str | None] | None
|
on storage-lock contention with a concurrent build). A failure must |
dict[str, str | None] | None
|
stay distinguishable from "these containers don't exist", or every |
dict[str, str | None] | None
|
task degrades to "not found" while the runtime is busy (#1134). |
Source code in src/terok/lib/orchestration/tasks/query.py
get_task_container_state(project_name, task_id, mode)
¶
Get actual container state for a task (TUI helper).
Container state queries are runtime-agnostic — podman inspect
returns the same shape regardless of OCI runtime — so this short
cuts to PodmanRuntime rather than walking through the
per-project resolver (which would force a load_project for a
one-shot state probe).
Source code in src/terok/lib/orchestration/tasks/query.py
get_task_meta(project_name, task_id)
¶
Return metadata for a single task with live container state.
Hydrates container_state from the running container so that
TaskMeta.status reflects current reality rather than stale YAML.
Raises SystemExit if the task metadata file is not found.
Source code in src/terok/lib/orchestration/tasks/query.py
get_tasks(project_name, reverse=False)
¶
Return all task metadata for project_name, sorted by task ID.
lookup_container_by_pt(project_name, task_id)
¶
Resolve a project/task pair to the current container name, or None.
Powers the slash-form identity acceptance on per-container
terok executor * verbs (stop, future exec / logs /
state / login). Reads the recorded mode from the task's
meta file; returns None when the task is unknown or has never
been launched (no mode recorded), or when either input would
escape the project task store (path-traversal guard). The caller
decides whether to treat None as "pass the input through
verbatim" (raw container id) or "fail with an actionable error"
(unknown project/task).
Source code in src/terok/lib/orchestration/tasks/query.py
task_list(project_name, *, status=None, mode=None)
¶
List tasks for a project, optionally filtered by status or mode.
Status is computed live from podman container state + task metadata.