Skip to content
Open
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions hermes_cli/kanban.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,8 @@ def _task_to_dict(t: kb.Task) -> dict[str, Any]:
"workspace_kind": t.workspace_kind,
"workspace_path": t.workspace_path,
"branch_name": t.branch_name,
"base_ref": t.base_ref,
"required_paths": list(t.required_paths or []),
"project_id": t.project_id,
"created_by": t.created_by,
"created_at": t.created_at,
Expand Down Expand Up @@ -338,6 +340,10 @@ def build_parser(parent_subparsers: argparse._SubParsersAction) -> argparse.Argu
"(default: scratch)")
p_create.add_argument("--branch", default=None,
help="Branch name for worktree tasks, e.g. wt/t6-wire")
p_create.add_argument("--base-ref", default=None,
help="Git revision from which a new worktree branch must start")
p_create.add_argument("--require-path", action="append", default=[],
help="Repository-relative path required before dispatch (repeatable)")
p_create.add_argument("--project", default=None,
help="Link to a project (id or slug). Anchors the task's "
"worktree under the project's primary repo with a "
Expand Down Expand Up @@ -1572,6 +1578,8 @@ def _cmd_create(args: argparse.Namespace) -> int:
workspace_kind=ws_kind,
workspace_path=ws_path,
branch_name=branch_name,
base_ref=getattr(args, "base_ref", None),
required_paths=getattr(args, "require_path", None),
project_id=getattr(args, "project", None),
tenant=args.tenant,
priority=args.priority,
Expand Down
129 changes: 120 additions & 9 deletions hermes_cli/kanban_db.py
Original file line number Diff line number Diff line change
Expand Up @@ -1069,6 +1069,8 @@ class Task:
claim_expires: Optional[int]
tenant: Optional[str]
branch_name: Optional[str] = None
base_ref: Optional[str] = None
required_paths: Optional[list[str]] = None
project_id: Optional[str] = None
result: Optional[str] = None
idempotency_key: Optional[str] = None
Expand Down Expand Up @@ -1154,6 +1156,14 @@ def from_row(cls, row: sqlite3.Row) -> "Task":
skills_value = [str(s) for s in parsed if s]
except Exception:
skills_value = None
required_paths_value: Optional[list[str]] = None
if "required_paths" in keys and row["required_paths"]:
try:
parsed = json.loads(row["required_paths"])
if isinstance(parsed, list):
required_paths_value = [str(path) for path in parsed if path]
except Exception:
required_paths_value = None
return cls(
id=row["id"],
title=row["title"],
Expand All @@ -1168,6 +1178,8 @@ def from_row(cls, row: sqlite3.Row) -> "Task":
workspace_kind=row["workspace_kind"],
workspace_path=row["workspace_path"],
branch_name=row["branch_name"] if "branch_name" in keys else None,
base_ref=row["base_ref"] if "base_ref" in keys else None,
required_paths=required_paths_value,
project_id=row["project_id"] if "project_id" in keys else None,
claim_lock=row["claim_lock"],
claim_expires=row["claim_expires"],
Expand Down Expand Up @@ -1344,6 +1356,10 @@ class Event:
workspace_kind TEXT NOT NULL DEFAULT 'scratch',
workspace_path TEXT,
branch_name TEXT,
-- Revision from which a newly materialized task branch must start.
base_ref TEXT,
-- JSON list of repository-relative paths required before dispatch.
required_paths TEXT,
-- Optional link to a first-class Project (hermes_cli/projects_db). When set,
-- the task's worktree is anchored under the project's primary repo with a
-- deterministic branch name instead of a random wt/<task-id> fallback.
Expand Down Expand Up @@ -2503,6 +2519,10 @@ def _migrate_add_optional_columns(conn: sqlite3.Connection) -> None:
_add_column_if_missing(conn, "tasks", "result", "result TEXT")
if "branch_name" not in cols:
_add_column_if_missing(conn, "tasks", "branch_name", "branch_name TEXT")
if "base_ref" not in cols:
_add_column_if_missing(conn, "tasks", "base_ref", "base_ref TEXT")
if "required_paths" not in cols:
_add_column_if_missing(conn, "tasks", "required_paths", "required_paths TEXT")
if "project_id" not in cols:
_add_column_if_missing(conn, "tasks", "project_id", "project_id TEXT")
if "idempotency_key" not in cols:
Expand Down Expand Up @@ -3128,6 +3148,8 @@ def create_task(
workspace_kind: str = "scratch",
workspace_path: Optional[str] = None,
branch_name: Optional[str] = None,
base_ref: Optional[str] = None,
required_paths: Optional[Iterable[str]] = None,
tenant: Optional[str] = None,
priority: int = 0,
parents: Iterable[str] = (),
Expand Down Expand Up @@ -3207,6 +3229,22 @@ def create_task(
branch_name = str(branch_name).strip() or None
if branch_name and workspace_kind != "worktree":
raise ValueError("branch_name is only valid for worktree workspaces")
if base_ref is not None:
base_ref = str(base_ref).strip() or None
if base_ref and workspace_kind != "worktree":
raise ValueError("base_ref is only valid for worktree workspaces")
required_paths_list: list[str] = []
for raw_path in required_paths or ():
path = str(raw_path).strip()
if not path:
continue
candidate = Path(path)
if candidate.is_absolute() or ".." in candidate.parts:
raise ValueError(f"required path must be repository-relative: {path!r}")
if path not in required_paths_list:
required_paths_list.append(path)
if required_paths_list and workspace_kind != "worktree":
raise ValueError("required_paths are only valid for worktree workspaces")

# Inherit the board's scoped project when the caller didn't name one, so a
# project-scoped board anchors every new task to that project's repo
Expand Down Expand Up @@ -3456,12 +3494,13 @@ def create_task(
INSERT INTO tasks (
id, title, body, assignee, status, priority,
created_by, created_at, workspace_kind, workspace_path,
branch_name, project_id, tenant, idempotency_key,
branch_name, base_ref, required_paths,
project_id, tenant, idempotency_key,
max_runtime_seconds,
skills, max_retries, model_override, provider_override,
reasoning_effort,
goal_mode, goal_max_turns, session_id
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
""",
(
task_id,
Expand All @@ -3475,6 +3514,8 @@ def create_task(
workspace_kind,
workspace_path,
branch_name,
base_ref,
json.dumps(required_paths_list) if required_paths_list else None,
project_id,
tenant,
idempotency_key,
Expand Down Expand Up @@ -3510,6 +3551,8 @@ def create_task(
"workspace_kind": workspace_kind,
"workspace_path": workspace_path,
"branch_name": branch_name,
"base_ref": base_ref,
"required_paths": required_paths_list or None,
"project_id": project_id,
"skills": list(skills_list) if skills_list else None,
"goal_mode": bool(goal_mode) or None,
Expand Down Expand Up @@ -7589,7 +7632,12 @@ def _repo_root_for_worktree_target(path: Path) -> Optional[Path]:
current = current.parent


def _ensure_git_worktree(repo_root: Path, target: Path, branch_name: str) -> None:
def _ensure_git_worktree(
repo_root: Path,
target: Path,
branch_name: str,
base_ref: Optional[str] = None,
) -> None:
"""Materialize ``target`` as a linked git worktree under ``repo_root``."""
target = target.expanduser()
repo_common = _git_common_dir(repo_root)
Expand All @@ -7603,7 +7651,7 @@ def _ensure_git_worktree(repo_root: Path, target: Path, branch_name: str) -> Non
else:
cmd = [
"git", "-C", str(repo_root), "worktree", "add", "-b", branch_name,
str(target), "HEAD",
str(target), base_ref or "HEAD",
]
result = subprocess.run(
cmd,
Expand Down Expand Up @@ -7659,7 +7707,7 @@ def _resolve_worktree_workspace(
f"{board_slug!r} default_workdir {board_default!r} is not inside a git repo"
)
target = repo_root / ".worktrees" / task.id
_ensure_git_worktree(repo_root, target, branch_name)
_ensure_git_worktree(repo_root, target, branch_name, task.base_ref)
return target, branch_name

requested = Path(task.workspace_path).expanduser()
Expand All @@ -7685,7 +7733,7 @@ def _resolve_worktree_workspace(
if fallback_root is not None:
fallback = fallback_root / ".worktrees" / task.id
if fallback.resolve(strict=False) != requested_resolved:
_ensure_git_worktree(fallback_root, fallback, branch_name)
_ensure_git_worktree(fallback_root, fallback, branch_name, task.base_ref)
return fallback.resolve(strict=False), branch_name
# No repo to anchor a fallback on (or the occupied path IS this
# task's own canonical worktree): keep the legacy reuse rather
Expand All @@ -7695,7 +7743,7 @@ def _resolve_worktree_workspace(
repo_root = _git_toplevel(requested)
if repo_root is not None and requested_resolved == repo_root:
target = repo_root / ".worktrees" / task.id
_ensure_git_worktree(repo_root, target, branch_name)
_ensure_git_worktree(repo_root, target, branch_name, task.base_ref)
return target, branch_name

repo_root = _repo_root_for_worktree_target(requested.parent)
Expand All @@ -7704,7 +7752,7 @@ def _resolve_worktree_workspace(
f"task {task.id} worktree path {task.workspace_path!r} is not inside a git repo "
"and does not point at a git repo root"
)
_ensure_git_worktree(repo_root, requested, branch_name)
_ensure_git_worktree(repo_root, requested, branch_name, task.base_ref)
return requested, branch_name


Expand Down Expand Up @@ -7770,6 +7818,43 @@ def resolve_workspace(task: Task, *, board: Optional[str] = None) -> Path:
raise ValueError(f"unknown workspace_kind: {kind}")


def _check_implementation_prerequisites(
task: Task, workspace: Path
) -> Optional[str]:
"""Return why a worktree task cannot dispatch at its resolved revision."""
if task.base_ref:
result = subprocess.run(
[
"git", "-C", str(workspace), "merge-base", "--is-ancestor",
task.base_ref, "HEAD",
],
capture_output=True,
text=True,
encoding="utf-8",
errors="replace",
timeout=30,
check=False,
)
if result.returncode != 0:
return f"task branch does not contain required base revision {task.base_ref!r}"
missing = []
for path in task.required_paths or []:
result = subprocess.run(
["git", "-C", str(workspace), "cat-file", "-e", f"HEAD:{path}"],
capture_output=True,
text=True,
encoding="utf-8",
errors="replace",
timeout=30,
check=False,
)
if result.returncode != 0:
missing.append(path)
if missing:
return "required implementation path(s) absent: " + ", ".join(missing)
return None


def set_workspace_path(
conn: sqlite3.Connection, task_id: str, path: Path | str
) -> None:
Expand Down Expand Up @@ -9822,12 +9907,38 @@ def _dispatch_once_locked(
_per_profile_running.get(row_assignee, 0) + 1
)
continue
prerequisite_workspace: Optional[Path] = None
prerequisite_branch: Optional[str] = None
candidate = get_task(conn, row["id"])
if candidate is not None and (candidate.base_ref or candidate.required_paths):
try:
prerequisite_workspace, prerequisite_branch = (
_resolve_worktree_workspace(candidate, board=board)
)
prerequisite_error = _check_implementation_prerequisites(
candidate, prerequisite_workspace
)
except Exception as exc:
prerequisite_error = str(exc)
if prerequisite_error:
reason = f"Dispatch prerequisite failed: {prerequisite_error}"
if block_task(conn, candidate.id, reason=reason, kind="capability"):
with write_txn(conn):
conn.execute(
"UPDATE tasks SET last_failure_error = ? WHERE id = ?",
(reason[:2000], candidate.id),
)
result.auto_blocked.append(candidate.id)
continue
claimed = claim_task(conn, row["id"], ttl_seconds=ttl_seconds)
if claimed is None:
continue
try:
resolved_branch_name = None
if claimed.workspace_kind == "worktree":
if prerequisite_workspace is not None:
workspace = prerequisite_workspace
resolved_branch_name = prerequisite_branch
elif claimed.workspace_kind == "worktree":
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
workspace, resolved_branch_name = _resolve_worktree_workspace(claimed, board=board)
else:
workspace = resolve_workspace(claimed, board=board)
Expand Down
Loading