chore: 升级 Trellis 并精简规则(09-05-trellis-upgrade-rule-cleanup)

这个提交包含在:
2026-09-06 11:14:41 +08:00
父节点 ab82fe30c0
当前提交 c3cef5cfc4
共修改 48 个文件,包含 4588 行新增和 1053 行删除
+2
查看文件
@@ -66,6 +66,8 @@ from .paths import (
FILE_CURRENT_TASK,
FILE_TASK_JSON,
FILE_JOURNAL_PREFIX,
ENV_DEVELOPER,
DEVELOPER_HINT,
get_repo_root,
get_developer,
check_developer,
+255 -60
查看文件
@@ -9,7 +9,6 @@ session key there is no active task.
from __future__ import annotations
import hashlib
import json
import os
import re
import sys
@@ -19,12 +18,21 @@ from datetime import datetime, timezone
from pathlib import Path
from typing import Any
from .io import read_json as _io_read_json, write_json as _io_write_json
DIR_WORKFLOW = ".trellis"
DIR_TASKS = "tasks"
DIR_RUNTIME = ".runtime"
DIR_SESSIONS = "sessions"
DIR_CURSOR_SHELL = "cursor-shell"
CURSOR_SHELL_TICKET_TTL_SECONDS = 30
DIR_SHELL_TICKETS = "shell-tickets"
# Pre-0.6.13 name, when the bridge was Cursor-only. Still read so a session that
# was mid-command across an upgrade does not silently degrade; never written.
# Tickets are 30-second ephemera, so the old directory ages out by itself —
# there is nothing to migrate, only a glob on a directory that is normally
# absent. The alternative (ignore it) would land its one lost command on the
# platform that works today.
DIR_LEGACY_CURSOR_SHELL_TICKETS = "cursor-shell"
SHELL_TICKET_TTL_SECONDS = 30
TASK_SESSION_COMMANDS = {"start", "current", "finish"}
_SESSION_KEYS = ("session_id", "sessionId", "sessionID")
@@ -48,37 +56,87 @@ _KNOWN_PLATFORMS = {
"kimi",
"zcode",
"snow",
"dsh",
}
# Every name below records how it was checked. Do NOT add a name by analogy
# with a neighbour: a 2026-08-05 audit of all 21 platforms found 12 of the 21
# declared names had never existed anywhere — they were pattern-guessed from a
# `<PLATFORM>_SESSION_ID` shape no vendor agreed to, and the uniformity was the
# only "evidence" behind them. A platform with no verified name belongs in no
# table; it resolves through TRELLIS_CONTEXT_ID or its hook/plugin bridge.
_ENV_SESSION_KEYS: tuple[tuple[str, tuple[str, ...]], ...] = (
("claude", ("CLAUDE_SESSION_ID", "CLAUDE_CODE_SESSION_ID")),
("codex", ("CODEX_SESSION_ID", "CODEX_THREAD_ID")),
("cursor", ("CURSOR_SESSION_ID",)),
("opencode", ("OPENCODE_SESSION_ID", "OPENCODE_SESSIONID", "OPENCODE_RUN_ID")),
# REAL (reported 2026-08-13 against DSH 0.1.0-rc.6 by @SajoLuo, from a live
# run: DSH exports DSH_SESSION_ID plus DSH_SHELL=1 into its managed shell).
# MUST STAY FIRST. A DSH session can inherit an outer host's identity — a
# DSH launched from Codex still carries CODEX_THREAD_ID — and the untargeted
# lookup below walks this table in order, so any earlier entry would claim
# the session and write a foreign `codex_<thread>` pointer for DSH work.
# DSH_SESSION_ID is the only name here no other vendor sets, so first place
# is safe: it cannot mis-claim a non-DSH session.
("dsh", ("DSH_SESSION_ID",)),
# REAL, undocumented (verified 2026-08-05 in a live Claude Code 2.1.221 bash
# child; absent from code.claude.com/docs/en/env-vars). CLAUDE_SESSION_ID
# was removed here — verified absent from that same live environment.
("claude", ("CLAUDE_CODE_SESSION_ID",)),
# REAL, undocumented (verified 2026-08-05: injected by codex-cli 0.146.0
# into shell children, absent from the parent env; openai/codex#19937).
# CODEX_SESSION_ID was removed — absent from a live `codex exec` env.
("codex", ("CODEX_THREAD_ID",)),
# REAL but HOOK-SCOPE ONLY (verified 2026-08-05): set by Gemini's
# hookRunner.ts. Its shell tool builds the child env in
# shellExecutionService.ts and adds only GEMINI_CLI/TERM/PAGER/GIT_PAGER, so
# this never reaches a bash child — it resolves only inside a hook process.
("gemini", ("GEMINI_SESSION_ID",)),
("droid", ("FACTORY_SESSION_ID", "DROID_SESSION_ID")),
# REAL but HOOK-SCOPE ONLY (verified 2026-08-05): docs.qoder.com/zh/
# extensions/hooks documents it as injected during hook execution by the
# Qoder *IDE plugin*. Absent from the Qoder CLI hook docs and from Lingma.
("qoder", ("QODER_SESSION_ID",)),
("codebuddy", ("CODEBUDDY_SESSION_ID",)),
# UNVERIFIED (2026-08-05): absent from kiro.dev/docs/hooks/, but Dynatrace
# dtctl, oh-my-agent and gastown all key agent detection on it and one notes
# it is "set in both interactive and --no-interactive". Kept because that is
# absence of evidence, not evidence of absence. To settle: run
# `env | grep KIRO` from a Kiro shell-tool call on a machine with Kiro.
("kiro", ("KIRO_SESSION_ID",)),
# UNVERIFIED (2026-08-05): absent from docs.github.com/en/copilot/reference/
# hooks-reference and from the CLI programmatic reference. To settle: run
# `copilot help environment` (the authoritative list per those docs) — not
# runnable here, the CLI is not installed and copilot-cli ships no source.
("copilot", ("COPILOT_SESSION_ID", "COPILOT_SESSIONID")),
("pi", ("PI_SESSION_ID", "PI_SESSIONID")),
("trae", ("TRAE_SESSION_ID",)),
# ZCode reuses CLAUDE_SESSION_ID (it does not document a ZCODE_SESSION_ID).
# Platform-scoped lookup (_iter_env_keys filters by platform name), so this
# only fires when the resolver already detected "zcode" — no collision with
# REASONED, UNVERIFIED (2026-08-05): ZCode is closed-source and not
# installable here. It mirrors Claude's naming elsewhere (CLAUDE_PLUGIN_ROOT
# / CLAUDE_PLUGIN_DATA compat aliases are in its docs), and the previously
# declared CLAUDE_SESSION_ID does not exist on Claude Code either — so the
# name ZCode would actually reuse is CLAUDE_CODE_SESSION_ID. Try that first,
# keep the historical name as a fallback: if neither exists nothing changes.
# Platform-scoped lookup (_iter_env_keys filters by platform name), so the
# entry only fires once the resolver detected "zcode" — no collision with
# the claude entry above.
("zcode", ("CLAUDE_SESSION_ID",)),
# Snow CLI exports SNOW_SESSION_ID into hook/terminal/sub-agent children.
# TRELLIS_CONTEXT_ID remains the preferred override when present.
("zcode", ("CLAUDE_CODE_SESSION_ID", "CLAUDE_SESSION_ID")),
# REAL by vendor design (verified 2026-08-05): Snow's sessionIdentityEnv.ts
# exports SNOW_SESSION_ID into hook/terminal/sub-agent children and names
# Trellis in its source header. TRELLIS_CONTEXT_ID stays the preferred
# override — Snow sets that too.
("snow", ("SNOW_SESSION_ID",)),
)
_ENV_CONVERSATION_KEYS: tuple[tuple[str, tuple[str, ...]], ...] = (
# REAL in cursor-agent (CLI), undocumented (verified 2026-08-05: the value
# matches ~/.cursor/chats/<ws>/<id>). The Cursor *IDE* is unverified — a
# 2026-05 forum request for it drew no staff reply. The invented
# CURSOR_SESSION_ID was removed from the session table: empty in a live
# cursor-agent shell. Cursor's other path is the shell ticket below
# (_lookup_shell_ticket_context_key), which is not Cursor-specific.
("cursor", ("CURSOR_CONVERSATION_ID", "CURSOR_CONVERSATIONID")),
)
_ENV_TRANSCRIPT_KEYS: tuple[tuple[str, tuple[str, ...]], ...] = (
("claude", ("CLAUDE_TRANSCRIPT_PATH",)),
("codex", ("CODEX_TRANSCRIPT_PATH",)),
# REAL but HOOK-SCOPE ONLY (verified 2026-08-05): documented for Cursor hook
# scripts; empty in the agent's own shell env.
("cursor", ("CURSOR_TRANSCRIPT_PATH",)),
# UNVERIFIED — never researched. The 2026-08-05 audit covered the session
# table only, so do not infer these are real *or* fake from that work
# (CLAUDE_/CODEX_TRANSCRIPT_PATH were removed because those two *were*
# checked: absent from docs and from live envs). To settle each: run
# `env | grep _TRANSCRIPT_PATH` inside a hook and inside a shell-tool call.
("gemini", ("GEMINI_TRANSCRIPT_PATH",)),
("droid", ("FACTORY_TRANSCRIPT_PATH", "DROID_TRANSCRIPT_PATH")),
("qoder", ("QODER_TRANSCRIPT_PATH",)),
@@ -90,11 +148,15 @@ _ENV_PLATFORM_ALIASES = {
"factory-ai": "droid",
"github-copilot": "copilot",
}
# ZCode intentionally reuses CLAUDE_SESSION_ID. Hooks know the host is ZCode,
# while later shell commands see only the shared env name and resolve it through
# the Claude entry. Canonicalize both paths to one runtime filename.
# ZCode intentionally reuses Claude's session env var name. Hooks know the host
# is ZCode, while later shell commands see only the shared env name and resolve
# it through the claude entry. Canonicalize both paths to one runtime filename.
_CONTEXT_KEY_PLATFORM_ALIASES = {
"zcode": "claude",
# Factory Droid's config directory is `.factory/`, so a hook that names its
# platform after the directory it was installed in reports "factory". Its
# sibling hooks report "droid". One runtime filename either way.
"factory": "droid",
}
@@ -138,19 +200,54 @@ def normalize_task_ref(task_ref: str) -> str:
def resolve_task_ref(task_ref: str, repo_root: Path) -> Path | None:
"""Resolve a task ref to an absolute task directory."""
"""Resolve a task ref to an absolute task directory inside the repo.
Mirrors `paths.resolve_task_ref` (same containment check). Duplicated
rather than imported because this module is loaded standalone — hooks add
it to `sys.path` directly — so it stays zero-relative-import on purpose.
"""
normalized = normalize_task_ref(task_ref)
if not normalized:
return None
try:
root = repo_root.resolve()
except OSError:
return None
path_obj = Path(normalized)
if path_obj.is_absolute():
return path_obj
candidate = path_obj
elif normalized.startswith(f"{DIR_WORKFLOW}/"):
candidate = root / path_obj
else:
candidate = root / DIR_WORKFLOW / DIR_TASKS / path_obj
if normalized.startswith(f"{DIR_WORKFLOW}/"):
return repo_root / path_obj
# Both sides are resolved because repo_root itself may sit behind a
# symlink (/tmp on macOS does), and resolve() is what collapses `..`
# instead of leaving it for a lexical relative_to() to wave through.
try:
resolved = candidate.resolve()
workflow_real = (root / DIR_WORKFLOW).resolve()
except OSError:
return None
return repo_root / DIR_WORKFLOW / DIR_TASKS / path_obj
try:
resolved.relative_to(root)
return resolved
except ValueError:
pass
# `.trellis` may itself be a symlink into a store outside the repo (#567).
# The workflow dir's own real location is then a second legitimate
# containment base; a ref that escapes BOTH bases is still refused. Map
# back to the in-repo (lexical) form so callers store a repo-relative ref.
try:
rel = resolved.relative_to(workflow_real)
except ValueError:
return None
return root / DIR_WORKFLOW / rel
def _runtime_sessions_dir(repo_root: Path) -> Path:
@@ -222,6 +319,12 @@ def _iter_env_keys(
env_keys: tuple[tuple[str, tuple[str, ...]], ...],
platform_name: str | None,
) -> tuple[tuple[str, tuple[str, ...]], ...]:
"""Narrow an env-key table to one platform, or return all of it.
A platform with no entry yields an empty tuple, and the caller's `for` loop
simply does not run. That is the normal case, not an error: platforms with
no verified env var name are deliberately absent from these tables.
"""
if not platform_name:
return env_keys
matched = tuple((name, keys) for name, keys in env_keys if name == platform_name)
@@ -275,8 +378,12 @@ def _find_repo_root_from_cwd() -> Path | None:
current = current.parent
def _cursor_shell_ticket_dir(repo_root: Path) -> Path:
return repo_root / DIR_WORKFLOW / DIR_RUNTIME / DIR_CURSOR_SHELL
def _shell_ticket_dirs(repo_root: Path) -> tuple[Path, ...]:
runtime_dir = repo_root / DIR_WORKFLOW / DIR_RUNTIME
return (
runtime_dir / DIR_SHELL_TICKETS,
runtime_dir / DIR_LEGACY_CURSOR_SHELL_TICKETS,
)
def _remove_file(path: Path) -> bool:
@@ -334,7 +441,7 @@ def _ticket_is_fresh(ticket: dict[str, Any], ticket_path: Path, now: float) -> b
created_at = ticket.get("created_at_epoch")
if isinstance(created_at, (int, float)):
if now - created_at <= CURSOR_SHELL_TICKET_TTL_SECONDS:
if now - created_at <= SHELL_TICKET_TTL_SECONDS:
return True
_remove_file(ticket_path)
return False
@@ -352,13 +459,18 @@ def _ticket_cwd_matches_repo(ticket: dict[str, Any], repo_root: Path) -> bool:
return True
def _matching_cursor_ticket_context_key(
def _matching_ticket_context_key(
ticket_path: Path,
repo_root: Path,
now: float,
) -> str | None:
"""Accept a ticket on its merits, never on which platform wrote it.
The `platform` field a ticket carries is debugging metadata; gating on it
was what kept this bridge invisible to every platform but Cursor.
"""
ticket = _read_json(ticket_path)
if ticket is None or ticket.get("platform") != "cursor":
if ticket is None:
return None
if not _ticket_is_fresh(ticket, ticket_path, now):
return None
@@ -369,29 +481,30 @@ def _matching_cursor_ticket_context_key(
return _string_value(ticket.get("context_key"))
def _lookup_cursor_shell_ticket_context_key() -> str | None:
"""Resolve Cursor conversation identity from a short-lived shell ticket.
def _lookup_shell_ticket_context_key() -> str | None:
"""Resolve session identity from a short-lived shell ticket.
Cursor exposes `conversation_id` to `beforeShellExecution`, but does not
export it into the shell command environment. The Cursor hook writes a
short-lived ticket just before `task.py` runs. We accept a ticket only when
the current `task.py` subcommand matches and exactly one fresh context key
matches, which avoids cross-window pointer contamination.
No researched platform exports its session id into a shell child, but every
hook-capable one hands that id to a hook. So the hook that runs just before
a shell command writes a ticket, and this reads it back. A ticket counts
only when it is fresh, was written for this repo, and matches the `task.py`
subcommand now running — and only when exactly one fresh context key
matches. Two concurrent windows therefore both degrade rather than one
inheriting the other's pointer.
"""
repo_root = _find_repo_root_from_cwd()
if repo_root is None:
return None
ticket_dir = _cursor_shell_ticket_dir(repo_root)
if not ticket_dir.is_dir():
return None
now = time.time()
candidates: set[str] = set()
for ticket_path in ticket_dir.glob("*.json"):
context_key = _matching_cursor_ticket_context_key(ticket_path, repo_root, now)
if context_key:
candidates.add(context_key)
for ticket_dir in _shell_ticket_dirs(repo_root):
if not ticket_dir.is_dir():
continue
for ticket_path in ticket_dir.glob("*.json"):
context_key = _matching_ticket_context_key(ticket_path, repo_root, now)
if context_key:
candidates.add(context_key)
if len(candidates) == 1:
return next(iter(candidates))
@@ -435,29 +548,32 @@ def resolve_context_key(
if env_context_key:
return env_context_key
if allow_environment_context and platform_name in (None, "session", "cursor"):
return _lookup_cursor_shell_ticket_context_key()
# Last in the chain on purpose: a platform that genuinely exports identity
# into the shell outranks a ticket, and no platform name gates the lookup.
if allow_environment_context:
return _lookup_shell_ticket_context_key()
return None
def _read_json(path: Path) -> dict[str, Any] | None:
try:
data = json.loads(path.read_text(encoding="utf-8"))
except (FileNotFoundError, json.JSONDecodeError, OSError):
return None
"""Tolerant read of a session runtime file, non-objects included."""
data = _io_read_json(path)
return data if isinstance(data, dict) else None
def _write_json(path: Path, data: dict[str, Any]) -> bool:
"""Write a session runtime file atomically, creating the runtime dir.
Routes through io.write_json so session pointers get the same
temp-file-then-rename treatment as task.json (#429). A plain write_text
truncates the target first, so a crash mid-write would leave a session
file that reads back as no active task.
"""
try:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(
json.dumps(data, indent=2, ensure_ascii=False) + "\n",
encoding="utf-8",
)
return True
except OSError:
return False
return _io_write_json(path, data)
def _canonical_task_ref(task_path: str, repo_root: Path) -> str | None:
@@ -468,9 +584,46 @@ def _canonical_task_ref(task_path: str, repo_root: Path) -> str | None:
if full_path is None or not full_path.is_dir():
return None
try:
return full_path.relative_to(repo_root).as_posix()
return full_path.relative_to(repo_root.resolve()).as_posix()
except ValueError:
return str(full_path)
# resolve_task_ref already refused everything outside the repo, so this
# is unreachable. Refuse rather than fall back to an absolute path —
# that fallback is how an out-of-repo ref used to reach the session
# pointer and get replayed on every later turn.
return None
def _relative_task_ref(task_path: str, repo_root: Path) -> str:
"""Repo-relative posix ref for a task path that need not exist.
`_canonical_task_ref` resolves through the filesystem and so refuses a task
directory that has been moved away. Rename needs to name both sides of the
move, one of which is always absent.
"""
normalized = normalize_task_ref(task_path)
if not normalized:
return ""
candidate = Path(normalized)
if not candidate.is_absolute():
return normalized
try:
resolved = candidate.resolve()
root = repo_root.resolve()
workflow_real = (root / DIR_WORKFLOW).resolve()
except OSError:
return ""
try:
return resolved.relative_to(root).as_posix()
except ValueError:
pass
# Same dual-base containment as resolve_task_ref: a path through a
# symlinked `.trellis` (#567) maps back to its in-repo form; anything
# outside both bases is refused rather than stored as an absolute pointer.
try:
rel = resolved.relative_to(workflow_real)
except ValueError:
return ""
return (Path(DIR_WORKFLOW) / rel).as_posix()
def _active_from_ref(
@@ -652,6 +805,48 @@ def clear_task_from_sessions(task_path: str, repo_root: Path) -> int:
return cleared
def repoint_task_in_sessions(old_path: str, new_path: str, repo_root: Path) -> int:
"""Move every session pointer from `old_path` to `new_path`.
Rename is the one lifecycle step where the task survives under a different
name, so clearing the pointers (what archive does) would be wrong: the user
would silently lose their active task and have to run `task.py start`
again to get context injection back. Repointing keeps the session valid
across the rename.
"""
# Not `_canonical_task_ref`: the caller repoints *after* moving the
# directory, so `old_path` no longer exists and canonicalization — which
# requires an existing directory — would return None for exactly the ref we
# need to match.
target = _relative_task_ref(old_path, repo_root)
replacement = _relative_task_ref(new_path, repo_root)
if not target or not replacement:
return 0
moved = 0
sessions_dir = _runtime_sessions_dir(repo_root)
if not sessions_dir.is_dir():
return moved
for session_path in sorted(sessions_dir.glob("*.json")):
context = _read_json(session_path)
if not context:
continue
current = _string_value(context.get("current_task"))
if not current:
continue
current_ref = _canonical_task_ref(current, repo_root) or _relative_task_ref(
current, repo_root
)
if current_ref != target:
continue
context["current_task"] = replacement
if _write_json(session_path, context):
moved += 1
return moved
def get_current_task_source(
repo_root: Path,
platform_input: dict[str, Any] | None = None,
+82 -169
查看文件
@@ -11,157 +11,11 @@ import sys
from pathlib import Path
from .paths import DIR_WORKFLOW, get_repo_root
from .trellis_config import parse_simple_yaml
# =============================================================================
# YAML Simple Parser (no dependencies)
# =============================================================================
def _unquote(s: str) -> str:
"""Remove exactly one layer of matching surrounding quotes.
Unlike str.strip('"'), this only removes the outermost pair,
preserving any nested quotes inside the value.
Examples:
_unquote('"hello"') -> 'hello'
_unquote("'hello'") -> 'hello'
_unquote('"echo \\'hi\\'"') -> "echo 'hi'"
_unquote('hello') -> 'hello'
_unquote('"hello\\'') -> '"hello\\'' (mismatched, unchanged)
"""
if len(s) >= 2 and s[0] == s[-1] and s[0] in ('"', "'"):
return s[1:-1]
return s
def _strip_inline_comment(value: str) -> str:
"""Strip ` # …` inline comments while preserving `#` inside quoted strings.
YAML treats ` #` (space-hash) as a comment opener; bare `#` inside a token
is part of the value. Quoted strings are immune.
Mirrors :func:`common.trellis_config._strip_inline_comment` so both
parsers handle ``key: value # comment`` identically.
"""
in_quote: str | None = None
for idx, ch in enumerate(value):
if in_quote:
if ch == in_quote:
in_quote = None
continue
if ch in ('"', "'"):
in_quote = ch
continue
if ch == "#" and (idx == 0 or value[idx - 1].isspace()):
return value[:idx]
return value
def parse_simple_yaml(content: str) -> dict:
"""Parse simple YAML with nested dict support (no dependencies).
Supports:
- key: value (string)
- key: (followed by list items)
- item1
- item2
- key: (followed by nested dict)
nested_key: value
nested_key2:
- item
Uses indentation to detect nesting (2+ spaces deeper = child).
Args:
content: YAML content string.
Returns:
Parsed dict (values can be str, list[str], or dict).
"""
lines = content.splitlines()
result: dict = {}
_parse_yaml_block(lines, 0, 0, result)
return result
def _parse_yaml_block(
lines: list[str], start: int, min_indent: int, target: dict
) -> int:
"""Parse a YAML block into target dict, returning next line index."""
i = start
current_list: list | None = None
while i < len(lines):
line = lines[i]
stripped = line.strip()
# Skip empty lines and comments
if not stripped or stripped.startswith("#"):
i += 1
continue
# Calculate indentation
indent = len(line) - len(line.lstrip())
# If dedented past our block, we're done
if indent < min_indent:
break
if stripped.startswith("- "):
if current_list is not None:
current_list.append(_unquote(stripped[2:].strip()))
i += 1
elif ":" in stripped:
key, _, value = stripped.partition(":")
key = key.strip()
value = _strip_inline_comment(value).strip()
was_quoted = len(value) >= 2 and value[0] == value[-1] and value[0] in ('"', "'")
value = _unquote(value)
current_list = None
if value or was_quoted:
# key: value (an explicit quoted "" is a value, not "no value")
target[key] = value
i += 1
else:
# key: (no value) — peek ahead to determine list vs nested dict
next_i, next_line = _next_content_line(lines, i + 1)
if next_i >= len(lines):
target[key] = {}
i = next_i
elif next_line.strip().startswith("- "):
# It's a list
current_list = []
target[key] = current_list
i += 1
else:
next_indent = len(next_line) - len(next_line.lstrip())
if next_indent > indent:
# It's a nested dict
nested: dict = {}
target[key] = nested
i = _parse_yaml_block(lines, i + 1, next_indent, nested)
else:
# Empty value, same or less indent follows
target[key] = {}
i += 1
else:
i += 1
return i
def _next_content_line(lines: list[str], start: int) -> tuple[int, str]:
"""Find the next non-empty, non-comment line."""
i = start
while i < len(lines):
stripped = lines[i].strip()
if stripped and not stripped.startswith("#"):
return i, lines[i]
i += 1
return i, ""
# The YAML subset parser lives in trellis_config.py — it imports nothing from
# this package, so hooks can load it as a single standalone file. Two byte-
# equivalent copies is a drift hazard, not a feature.
# Defaults
@@ -173,13 +27,46 @@ DEFAULT_CODEX_DISPATCH_MODE = "auto"
CONFIG_FILE = "config.yaml"
def _is_true_config_value(value: object) -> bool:
"""Return True when a config value represents an enabled flag."""
TRUE_CONFIG_VALUES = ("true", "yes", "1", "on")
FALSE_CONFIG_VALUES = ("false", "no", "0", "off")
def coerce_config_bool(
value: object,
default: bool,
label: str,
) -> bool:
"""Coerce a config value to a bool, warning on anything unrecognized.
The parser stores every value as a string, so ``git: yes`` arrives as
``"yes"``. Every boolean config key goes through this one helper: an
accepted-here/rejected-there split means a user writing a perfectly
reasonable YAML boolean silently gets the opposite branch.
Args:
value: Raw value from the parsed config.
default: Returned when the value is unrecognized.
label: Config key name, used in the warning.
"""
if isinstance(value, bool):
return value
if isinstance(value, str):
return value.strip().lower() == "true"
return False
s = str(value).strip().lower()
if s in TRUE_CONFIG_VALUES:
return True
if s in FALSE_CONFIG_VALUES:
return False
print(
f"[WARN] invalid {label} value: {value!r}; using {str(default).lower()} (default)",
file=sys.stderr,
)
return default
def _is_true_config_value(value: object, label: str = "config flag") -> bool:
"""Return True when a config value represents an enabled flag."""
if value is None:
return False
return coerce_config_bool(value, False, label)
def _get_config_path(repo_root: Path | None = None) -> Path:
@@ -189,13 +76,27 @@ def _get_config_path(repo_root: Path | None = None) -> Path:
def _load_config(repo_root: Path | None = None) -> dict:
"""Load and parse config.yaml. Returns empty dict on any error."""
"""Load and parse config.yaml. Returns empty dict on any error.
Fail-open, matching ``trellis_config.read_trellis_config``: a malformed
config must not take down ``task.py create``. A parse failure is reported
once on stderr so it is not invisible.
"""
config_file = _get_config_path(repo_root)
try:
content = config_file.read_text(encoding="utf-8")
return parse_simple_yaml(content)
except (OSError, IOError):
return {}
try:
parsed = parse_simple_yaml(content, source=str(config_file))
except Exception as e:
print(
f"[WARN] could not parse {config_file}: {type(e).__name__}: {e}; "
"using defaults",
file=sys.stderr,
)
return {}
return parsed if isinstance(parsed, dict) else {}
def get_session_commit_message(repo_root: Path | None = None) -> str:
@@ -231,18 +132,9 @@ def get_session_auto_commit(repo_root: Path | None = None) -> bool:
"""
config = _load_config(repo_root)
raw = config.get("session_auto_commit", DEFAULT_SESSION_AUTO_COMMIT)
if isinstance(raw, bool):
return raw
s = str(raw).strip().lower()
if s in ("true", "yes", "1", "on"):
return True
if s in ("false", "no", "0", "off"):
return False
print(
f"[WARN] invalid session_auto_commit value: {raw!r}; using true (default)",
file=sys.stderr,
return coerce_config_bool(
raw, DEFAULT_SESSION_AUTO_COMMIT, "session_auto_commit"
)
return DEFAULT_SESSION_AUTO_COMMIT
def get_codex_dispatch_mode(repo_root: Path | None = None) -> str:
@@ -374,16 +266,37 @@ def get_hooks(event: str, repo_root: Path | None = None) -> list[str]:
event: Event name (e.g. "after_create", "after_archive").
repo_root: Repository root path.
A hook the user believes is installed and which silently never runs is the
worst outcome for this feature, so a declared-but-unusable shape warns
instead of returning an empty list quietly.
Returns:
List of shell commands to execute, empty if none configured.
"""
config = _load_config(repo_root)
hooks = config.get("hooks")
if hooks is None:
return []
if not isinstance(hooks, dict):
print(
f"[WARN] ignoring `hooks` in config.yaml: expected a mapping of "
f"event -> list of commands, got {hooks!r}",
file=sys.stderr,
)
return []
commands = hooks.get(event)
if commands is None:
return []
if isinstance(commands, list):
return [str(c) for c in commands]
# `after_create: echo hi` instead of a `- ` list — parses fine, registers
# nothing.
print(
f"[WARN] ignoring hook `{event}` in config.yaml: expected a list of "
f"commands, got {commands!r}. Write it as:\n"
f" hooks:\n {event}:\n - {commands}",
file=sys.stderr,
)
return []
@@ -471,7 +384,7 @@ def get_git_packages(repo_root: Path | None = None) -> dict[str, str]:
return {
name: cfg.get("path", name)
for name, cfg in packages.items()
if _is_true_config_value(cfg.get("git"))
if _is_true_config_value(cfg.get("git"), f"packages.{name}.git")
}
+2
查看文件
@@ -15,6 +15,7 @@ from datetime import datetime
from pathlib import Path
from .paths import (
DEVELOPER_HINT,
DIR_WORKFLOW,
DIR_WORKSPACE,
DIR_TASKS,
@@ -160,6 +161,7 @@ def ensure_developer(repo_root: Path | None = None) -> None:
if not check_developer(repo_root):
print("Error: Developer not initialized.", file=sys.stderr)
print(f"Run: python3 ./{DIR_WORKFLOW}/scripts/init_developer.py <your-name>", file=sys.stderr)
print(DEVELOPER_HINT, file=sys.stderr)
sys.exit(1)
+129
查看文件
@@ -7,9 +7,25 @@ Single source of truth for running git commands across all Trellis scripts.
from __future__ import annotations
import subprocess
import time
from pathlib import Path
# Bounded retry for transient `.git/index.lock` contention. Another process
# (IDE git integration, status daemon, a concurrent Trellis session) can hold
# the lock for a fraction of a second; three attempts spread over ~1.5s ride
# that out without making a genuinely stuck lock hang the command. One sleep
# per retry, so the attempt count follows the backoff tuple.
INDEX_LOCK_RETRY_BACKOFF = (0.5, 1.0)
INDEX_LOCK_RETRY_ATTEMPTS = len(INDEX_LOCK_RETRY_BACKOFF) + 1
# Whether a checkout is a linked worktree cannot change while a script runs, and
# the answer costs two subprocesses. Developer-identity resolution asks several
# times per command whenever the local `.developer` file is absent, so memoize.
_CACHE_MISS = object()
_MAIN_WORKTREE_CACHE: dict[Path, Path | None] = {}
def run_git(
args: list[str],
cwd: Path | None = None,
@@ -38,6 +54,49 @@ def run_git(
return 1, "", str(e)
def stderr_indicates_index_lock(stderr: str) -> bool:
"""git failed because another process holds `.git/index.lock`."""
if not stderr:
return False
return "index.lock" in stderr.lower()
def run_git_retry_index_lock(
args: list[str],
cwd: Path | None = None,
timeout: float | None = None,
) -> tuple[int, str, str]:
"""Run a git command, retrying only while `.git/index.lock` is held.
Any other non-zero exit returns immediately — a retry loop around real
failures (bad path, nothing to commit, hook rejection) just delays the
error. Returns the last (returncode, stdout, stderr).
"""
rc, out, err = run_git(args, cwd=cwd, timeout=timeout)
attempt = 1
while (
rc != 0
and attempt < INDEX_LOCK_RETRY_ATTEMPTS
and stderr_indicates_index_lock(err)
):
time.sleep(INDEX_LOCK_RETRY_BACKOFF[attempt - 1])
attempt += 1
rc, out, err = run_git(args, cwd=cwd, timeout=timeout)
return rc, out, err
def index_lock_path(repo_root: Path) -> str:
"""Path of the lock file git is contending on, for diagnostics.
Asks git so worktrees and `GIT_DIR` setups name the real file rather
than a `.git/` guess that does not exist there.
"""
rc, out, _ = run_git(["rev-parse", "--git-path", "index.lock"], cwd=repo_root)
if rc == 0 and out.strip():
return out.strip()
return ".git/index.lock"
def resolve_default_branch(repo_root: Path) -> str | None:
"""Resolve the repository's default branch (origin/HEAD target).
@@ -63,6 +122,76 @@ def resolve_default_branch(repo_root: Path) -> str | None:
return None
def current_branch_name(repo_root: Path) -> str | None:
"""Return the checked-out branch name, or None when there isn't one.
Empty output covers detached HEAD and "not a git repository" alike, and
callers treat both the same way: there is no branch worth recording.
"""
rc, out, _ = run_git(["branch", "--show-current"], cwd=repo_root)
if rc != 0:
return None
return out.strip() or None
def has_git_remote(repo_root: Path) -> bool:
"""Whether the repository has at least one configured remote."""
rc, out, _ = run_git(["remote"], cwd=repo_root)
return rc == 0 and bool(out.strip())
def main_worktree_root(repo_root: Path) -> Path | None:
"""Root of the main working tree when `repo_root` is a linked worktree.
Returns None in the main working tree itself, outside a git repository, and
for a linked worktree of a bare repository (no main checkout to point at).
`git worktree list --porcelain` reports the main working tree as its first
record, so git identifies it rather than this code deriving it from the
`.git` layout. Deriving it — taking the parent of `--git-common-dir` — is
wrong for a bare repository that happens to sit inside an unrelated
checkout (`~/repos/project.git` under a `~/repos` that is itself a repo):
the parent is a real checkout with a real `.developer`, so the guess is
indistinguishable from a hit and identity leaks across repositories.
"""
cached = _MAIN_WORKTREE_CACHE.get(repo_root, _CACHE_MISS)
if cached is not _CACHE_MISS:
return cached # type: ignore[return-value]
result = _probe_main_worktree_root(repo_root)
_MAIN_WORKTREE_CACHE[repo_root] = result
return result
def _probe_main_worktree_root(repo_root: Path) -> Path | None:
rc_list, listing, _ = run_git(["worktree", "list", "--porcelain"], cwd=repo_root)
rc_top, toplevel, _ = run_git(["rev-parse", "--show-toplevel"], cwd=repo_root)
if rc_list != 0 or rc_top != 0:
return None
lines = listing.splitlines()
if not lines or not lines[0].startswith("worktree "):
return None
# Records are blank-line separated; a `bare` attribute on the first one
# means the "main working tree" is a bare repo with nothing to inherit.
for line in lines[1:]:
if not line.strip():
break
if line.strip() == "bare":
return None
try:
main_root = Path(lines[0][len("worktree ") :].strip()).resolve()
current_root = Path(toplevel.strip()).resolve()
except (OSError, ValueError):
return None
if main_root == current_root:
return None
return main_root
def branch_exists_locally(branch: str, repo_root: Path) -> bool:
"""Check whether a local branch ref exists in the repository."""
if not branch:
+105 -6
查看文件
@@ -1,8 +1,9 @@
"""
JSON file I/O utilities.
File I/O utilities.
Provides read_json and write_json as the single source of truth
for JSON file operations across all Trellis scripts.
Provides read_json / write_json as the single source of truth for JSON file
operations, plus write_text_atomic for the Markdown state files (journal,
index.md) that carry durable session state.
"""
from __future__ import annotations
@@ -13,17 +14,96 @@ import tempfile
from pathlib import Path
JSON_READ_MISSING = "missing"
JSON_READ_INVALID = "invalid"
JSON_READ_UNREADABLE = "unreadable"
JSON_READ_NOT_OBJECT = "not-object"
JSON_READ_EMPTY = "empty"
JSON_READ_UNDECODABLE = "undecodable"
def read_json(path: Path) -> dict | None:
"""Read and parse a JSON file.
Returns None if the file doesn't exist, is invalid JSON, or can't be read.
Use this for optional reads only — a caller that is about to overwrite the
file, or that must tell a parse error from a permissions error, wants
read_json_checked instead.
"""
try:
return json.loads(path.read_text(encoding="utf-8"))
except (FileNotFoundError, json.JSONDecodeError, OSError):
except (FileNotFoundError, json.JSONDecodeError, OSError, UnicodeDecodeError):
# UnicodeDecodeError is not an OSError. Without it here a non-UTF-8
# session file raises out of a tolerant read, so the hook path fails
# instead of degrading to "no active task".
return None
def read_json_checked(path: Path) -> tuple[dict | None, str | None]:
"""Read a JSON object, keeping the ways it can fail distinguishable.
Returns ``(data, None)`` on success, or ``(None, reason)`` where reason is
one of the ``JSON_READ_*`` constants. An empty object counts as a failure:
a state file that parses to ``{}`` carries none of the fields callers read,
and treating it as success would silently rebuild it from defaults.
"""
try:
text = path.read_text(encoding="utf-8")
except FileNotFoundError:
return None, JSON_READ_MISSING
except UnicodeDecodeError:
# Not an OSError, so it escaped both handlers and surfaced as a
# traceback. The point of this reader is that every failure mode stays
# nameable, and "not valid UTF-8" is a different repair from
# "not valid JSON".
return None, JSON_READ_UNDECODABLE
except OSError:
return None, JSON_READ_UNREADABLE
try:
data = json.loads(text)
except json.JSONDecodeError:
return None, JSON_READ_INVALID
if not isinstance(data, dict):
return None, JSON_READ_NOT_OBJECT
if not data:
return None, JSON_READ_EMPTY
return data, None
def describe_json_read_failure(path: Path, reason: str | None) -> tuple[str, str]:
"""Return ``(what happened, what to do)`` for a read_json_checked reason."""
if reason == JSON_READ_MISSING:
return (f"{path}: file not found", "Pass an existing task directory, or create the task first.")
if reason == JSON_READ_UNREADABLE:
return (
f"{path}: could not be read (permission denied or I/O error)",
"Check the file and directory permissions, then retry.",
)
if reason == JSON_READ_INVALID:
return (
f"{path}: not valid JSON",
f"Fix the syntax (e.g. `python3 -m json.tool {path}`), then retry.",
)
if reason == JSON_READ_NOT_OBJECT:
return (
f"{path}: top level is not a JSON object",
"Restore the file to a JSON object ({ ... }), then retry.",
)
if reason == JSON_READ_EMPTY:
return (
f"{path}: contains an empty JSON object",
"Restore the task fields (or recreate the task), then retry.",
)
if reason == JSON_READ_UNDECODABLE:
return (
f"{path}: not valid UTF-8 text",
"Re-save the file as UTF-8 (or restore it from git), then retry.",
)
return (f"{path}: could not be loaded", "Inspect the file, then retry.")
def write_json(path: Path, data: dict) -> bool:
"""Write dict to JSON file with pretty formatting.
@@ -34,7 +114,19 @@ def write_json(path: Path, data: dict) -> bool:
Returns True on success, False on error.
"""
payload = json.dumps(data, indent=2, ensure_ascii=False)
return write_text_atomic(path, json.dumps(data, indent=2, ensure_ascii=False))
def write_text_atomic(path: Path, text: str) -> bool:
"""Write text to a file atomically (temp in same dir, then replace).
The same never-truncate-in-place guarantee as :func:`write_json`, for the
Markdown state files that hold durable session state (journal files,
index.md). A crash or Ctrl-C mid-write leaves the previous content intact
instead of a half-written record that no retry can classify.
Returns True on success, False on error.
"""
try:
fd, tmp = tempfile.mkstemp(
dir=str(path.parent), prefix=f".{path.name}.", suffix=".tmp"
@@ -50,7 +142,7 @@ def write_json(path: Path, data: dict) -> bool:
os.close(fd)
raise
with f:
f.write(payload)
f.write(text)
os.replace(tmp, path)
return True
except OSError:
@@ -59,3 +151,10 @@ def write_json(path: Path, data: dict) -> bool:
except OSError:
pass
return False
except BaseException:
# Ctrl-C mid-write: drop the temp file, then let the interrupt through.
try:
os.unlink(tmp)
except OSError:
pass
raise
+113 -17
查看文件
@@ -12,10 +12,13 @@ Provides:
from __future__ import annotations
import os
import re
from datetime import datetime
from pathlib import Path
from .git import main_worktree_root
# =============================================================================
# Path Constants (change here to rename directories)
@@ -35,6 +38,17 @@ FILE_CURRENT_TASK = ".current-task"
FILE_TASK_JSON = "task.json"
FILE_JOURNAL_PREFIX = "journal-"
# Environment override for the developer identity, ahead of the .developer file.
ENV_DEVELOPER = "TRELLIS_DEVELOPER"
# Appended to every "no developer set" error so the two non-obvious sources are
# discoverable from the failure itself.
DEVELOPER_HINT = (
f" Or set {ENV_DEVELOPER}=<your-name> in the environment.\n"
f" A linked git worktree inherits {DIR_WORKFLOW}/{FILE_DEVELOPER} from its "
f"main checkout — run init_developer.py there to cover every worktree."
)
# =============================================================================
# Repository Root
@@ -66,8 +80,40 @@ def get_repo_root(start_path: Path | None = None) -> Path:
# Developer
# =============================================================================
def _read_developer_file(dev_file: Path) -> str | None:
"""Read the `name=` field out of a .developer file, or None."""
if not dev_file.is_file():
return None
try:
content = dev_file.read_text(encoding="utf-8")
except (OSError, IOError):
return None
for line in content.splitlines():
if line.startswith("name="):
return line.split("=", 1)[1].strip() or None
return None
def get_developer(repo_root: Path | None = None) -> str | None:
"""Get developer name from .developer file.
"""Get the developer name for this checkout.
Resolution order, first hit wins (a CLI `--assignee` flag overrides all of
it, before this function is ever called):
1. The ``TRELLIS_DEVELOPER`` environment variable.
2. ``.trellis/.developer`` in this checkout.
3. ``.trellis/.developer`` in the main checkout, when this checkout is a
linked git worktree.
Step 3 exists because `.developer` is gitignored on purpose — it carries a
personal identity and no tracked file should. A fresh `git worktree add`
therefore starts with no identity file of its own, which used to make every
task.py command fail until init_developer.py was re-run per worktree. The
main checkout's file is read, never copied: a copy would go stale and shadow
later changes made in the main checkout.
Args:
repo_root: Repository root path. Defaults to auto-detected.
@@ -75,23 +121,22 @@ def get_developer(repo_root: Path | None = None) -> str | None:
Returns:
Developer name or None if not initialized.
"""
env_name = os.environ.get(ENV_DEVELOPER, "").strip()
if env_name:
return env_name
if repo_root is None:
repo_root = get_repo_root()
dev_file = repo_root / DIR_WORKFLOW / FILE_DEVELOPER
local = _read_developer_file(repo_root / DIR_WORKFLOW / FILE_DEVELOPER)
if local:
return local
if not dev_file.is_file():
main_root = main_worktree_root(repo_root)
if main_root is None:
return None
try:
content = dev_file.read_text(encoding="utf-8")
for line in content.splitlines():
if line.startswith("name="):
return line.split("=", 1)[1].strip()
except (OSError, IOError):
pass
return None
return _read_developer_file(main_root / DIR_WORKFLOW / FILE_DEVELOPER)
def check_developer(repo_root: Path | None = None) -> bool:
@@ -233,7 +278,25 @@ def normalize_task_ref(task_ref: str) -> str:
def resolve_task_ref(task_ref: str, repo_root: Path | None = None) -> Path | None:
"""Resolve a task ref to an absolute task directory path."""
"""Resolve a task ref to an absolute task directory path inside the repo.
Returns None when the ref resolves outside `repo_root`. Every reader of the
active task — `task.py`, the shared hooks, the platform extensions — comes
through here, so containment is enforced at this one point rather than at
each call site.
It matters because a ref is not always something the user typed. It round
trips through the session pointer under `.trellis/.runtime/sessions/`, and
`..` segments used to survive that trip intact: `_canonical_task_ref`
compares lexically, and a lexical `relative_to` accepts
`<root>/.trellis/tasks/../../../elsewhere` because the string does start
with the root. The ref was then stored verbatim and replayed on every later
turn, so `task.py start .trellis/tasks/../../../elsewhere` both rewrote that
directory's `task.json` and fed its files to the model.
Resolving here also normalises the path, so callers get a ref without `..`
to store.
"""
if repo_root is None:
repo_root = get_repo_root()
@@ -241,14 +304,47 @@ def resolve_task_ref(task_ref: str, repo_root: Path | None = None) -> Path | Non
if not normalized:
return None
try:
root = repo_root.resolve()
except OSError:
return None
path_obj = Path(normalized)
if path_obj.is_absolute():
return path_obj
candidate = path_obj
elif normalized.startswith(f"{DIR_WORKFLOW}/"):
candidate = root / path_obj
else:
candidate = root / DIR_WORKFLOW / DIR_TASKS / path_obj
if normalized.startswith(f"{DIR_WORKFLOW}/"):
return repo_root / path_obj
# resolve() collapses `..` and follows symlinks, so a task directory that
# links outside the repo is refused too. Both sides are resolved because
# repo_root itself may sit behind a symlink (/tmp on macOS does).
try:
resolved = candidate.resolve()
workflow_real = (root / DIR_WORKFLOW).resolve()
except OSError:
return None
return repo_root / DIR_WORKFLOW / DIR_TASKS / path_obj
try:
resolved.relative_to(root)
return resolved
except ValueError:
pass
# `.trellis` may itself be a symlink into a store outside the repo (#567).
# The workflow dir's own real location is then a second legitimate
# containment base: a ref through that link never left the workflow tree.
# A ref that escapes BOTH bases (traversal, absolute path elsewhere, a
# task dir symlinked out of the tree) is still refused.
try:
rel = resolved.relative_to(workflow_real)
except ValueError:
return None
# Map back to the in-repo (lexical) form so callers store the same
# repo-relative ref as in the non-symlinked layout.
return root / DIR_WORKFLOW / rel
def get_current_task(
+10 -3
查看文件
@@ -35,7 +35,7 @@ from __future__ import annotations
import sys
from pathlib import Path
from .git import run_git
from .git import run_git, run_git_retry_index_lock
from .paths import (
DIR_ARCHIVE,
DIR_TASKS,
@@ -208,7 +208,7 @@ def _stderr_indicates_ignored(stderr: str) -> bool:
def safe_git_add(
paths: list[str], repo_root: Path
paths: list[str], repo_root: Path, retry_on_index_lock: bool = False
) -> tuple[bool, bool, str]:
"""Run `git add` on specific paths; never retry with -f.
@@ -222,11 +222,18 @@ def safe_git_add(
- Plain fails (any reason — ignored or otherwise) → return failure with
the stderr. Callers should inspect the stderr (see
:func:`print_gitignore_warning`) and skip the auto-commit.
``retry_on_index_lock`` opts into the bounded backoff-retry for a held
``.git/index.lock`` (see :func:`~.git.run_git_retry_index_lock`). It is
off by default: only the archive path, which has already moved the task
directory on disk by the time it stages, needs to wait out a transient
lock rather than fail.
"""
if not paths:
return True, False, ""
rc, _, err = run_git(["add", "--", *paths], cwd=repo_root)
runner = run_git_retry_index_lock if retry_on_index_lock else run_git
rc, _, err = runner(["add", "--", *paths], cwd=repo_root)
if rc == 0:
return True, False, ""
return False, False, err
+26 -8
查看文件
@@ -9,6 +9,7 @@ Provides:
get_context_text_record - Text for record mode
output_json - Print JSON
output_text - Print text
get_update_hint - Once-per-session "update available" line
"""
from __future__ import annotations
@@ -417,8 +418,16 @@ def _compare_versions(left: str, right: str) -> int | None:
return _compare_prerelease(left_prerelease, right_prerelease)
def _update_marker_path(repo_root: Path) -> Path:
context_key = resolve_context_key()
def _update_marker_path(repo_root: Path, context_key: str | None = None) -> Path:
"""Path of the once-per-session marker that throttles the update check.
`context_key` lets a caller that already resolved session identity pass it
in — the SessionStart hook reads the session id from hook stdin, which is
more reliable than this function's environment-only fallback chain. Shell
entry points leave it None and keep the previous behavior.
"""
if not context_key:
context_key = resolve_context_key()
if not context_key:
terminal_key = os.environ.get("TERM_SESSION_ID", "").strip()
context_key = terminal_key or f"ppid-{os.getppid()}"
@@ -433,8 +442,11 @@ def _update_marker_path(repo_root: Path) -> Path:
)
def _mark_update_check_attempted(repo_root: Path) -> bool:
marker_path = _update_marker_path(repo_root)
def _mark_update_check_attempted(
repo_root: Path,
context_key: str | None = None,
) -> bool:
marker_path = _update_marker_path(repo_root, context_key)
if marker_path.exists():
return False
try:
@@ -445,8 +457,14 @@ def _mark_update_check_attempted(repo_root: Path) -> bool:
return True
def _get_update_hint(repo_root: Path) -> str | None:
marker_path = _update_marker_path(repo_root)
def get_update_hint(repo_root: Path, context_key: str | None = None) -> str | None:
"""Return the "update available" line for this session, at most once.
Public because the SessionStart hook imports it: the text-mode CLI path
(`get_context.py`) used to be the only caller, so hook-driven platforms —
Claude Code included — never saw the reminder at all.
"""
marker_path = _update_marker_path(repo_root, context_key)
if marker_path.exists():
return None
@@ -458,7 +476,7 @@ def _get_update_hint(repo_root: Path) -> str | None:
if not latest_version:
return None
_mark_update_check_attempted(repo_root)
_mark_update_check_attempted(repo_root, context_key)
comparison = _compare_versions(current_version, latest_version)
if comparison is None or comparison >= 0:
return None
@@ -867,7 +885,7 @@ def output_text(repo_root: Path | None = None) -> None:
"""
if repo_root is None:
repo_root = get_repo_root()
update_hint = _get_update_hint(repo_root)
update_hint = get_update_hint(repo_root)
if update_hint:
print(update_hint)
print("")
+186 -22
查看文件
@@ -9,10 +9,13 @@ Provides:
Note:
``cmd_init_context`` was removed in v0.5.0-beta.12. JSONL context files
are now seeded at ``task.py create`` time with a self-describing
``_example`` line; the AI agent curates real entries during planning when
the task needs sub-agent/spec context. See ``.trellis/workflow.md`` for the
current planning artifact contract.
are created empty at ``task.py create`` time; the AI agent curates real
entries during planning when the task needs sub-agent/spec context. See
``.trellis/workflow.md`` for the current planning artifact contract.
Older Trellis versions seeded those files with a ``{"_example": ...}``
placeholder row. Sub-agent validation rejects that row; explicit inline
mode accepts historical seed-only rows without counting them as context.
"""
from __future__ import annotations
@@ -21,11 +24,11 @@ import argparse
import json
from pathlib import Path
from .config import get_context_injection_limits
from .config import get_codex_dispatch_mode, get_context_injection_limits
from .git import branch_exists_locally
from .io import read_json
from .log import Colors, colored
from .paths import FILE_TASK_JSON, get_repo_root
from .paths import DIR_ARCHIVE, DIR_TASKS, DIR_WORKFLOW, FILE_TASK_JSON, get_repo_root
from .task_utils import resolve_task_dir
# Extensions that look like code rather than spec/research docs. Entries with
@@ -60,15 +63,26 @@ def cmd_add_context(args: argparse.Namespace) -> int:
"""Add entry to JSONL context file."""
repo_root = get_repo_root()
target_dir = resolve_task_dir(args.dir, repo_root)
if target_dir is None:
return 1
jsonl_name = args.file
path = args.path
reason = args.reason or "Added manually"
if not target_dir.is_dir():
if not target_dir or not target_dir.is_dir():
print(colored(f"Error: Directory not found: {target_dir}", Colors.RED))
return 1
# The JSONL name is user input joined onto the task dir — keep it a plain
# filename so it cannot create files elsewhere.
if "/" in jsonl_name or "\\" in jsonl_name or jsonl_name in (".", ".."):
print(colored(
f"Error: context file must be a plain name (e.g. implement, check): {jsonl_name}",
Colors.RED,
))
return 1
# Support shorthand
if not jsonl_name.endswith(".jsonl"):
jsonl_name = f"{jsonl_name}.jsonl"
@@ -110,12 +124,41 @@ def cmd_add_context(args: argparse.Namespace) -> int:
# Command: validate
# =============================================================================
def curated_entry_count(jsonl_file: Path) -> int | None:
"""Count curated entries in a jsonl context manifest.
Returns None when the file does not exist — `task.py create` seeds the
manifests only on sub-agent-capable platforms, so an absent file means no
sub-agent will ever read it and callers should not gate on it. A curated
entry is a JSON object row carrying a truthy ``file`` (or legacy ``path``)
value: the same rows the sub-agent injection hook materializes.
"""
if not jsonl_file.is_file():
return None
try:
lines = jsonl_file.read_text(encoding="utf-8").splitlines()
except OSError:
return 0
count = 0
for line in lines:
line = line.strip()
if not line:
continue
try:
data = json.loads(line)
except json.JSONDecodeError:
continue
if isinstance(data, dict) and (data.get("file") or data.get("path")):
count += 1
return count
def cmd_validate(args: argparse.Namespace) -> int:
"""Validate JSONL context files."""
repo_root = get_repo_root()
target_dir = resolve_task_dir(args.dir, repo_root)
if not target_dir.is_dir():
if target_dir is None or not target_dir.is_dir():
print(colored("Error: task directory required", Colors.RED))
return 1
@@ -170,11 +213,69 @@ def _is_exempt_from_code_file_warning(file_path: str, task_rel: str) -> bool:
return False
def _resolve_context_entry_path(
file_path: str, repo_root: Path, task_dir: Path | None
) -> Path | None:
"""Resolve a JSONL entry, binding archived self-references to the archive copy.
Exact historical self-references are remapped only for archived tasks.
``None`` means the remapped path traversed or resolved outside that archive.
"""
repo_path = repo_root / file_path
try:
repo_path.resolve().relative_to(repo_root.resolve())
except (OSError, RuntimeError, ValueError):
return None
if task_dir is None:
return repo_path
try:
task_parts = task_dir.resolve().relative_to(repo_root.resolve()).parts
except ValueError:
return repo_path
archive_prefix = (DIR_WORKFLOW, DIR_TASKS, DIR_ARCHIVE)
if len(task_parts) != 5 or task_parts[:3] != archive_prefix:
return repo_path
year_month = task_parts[3]
if (
len(year_month) != 7
or year_month[4] != "-"
or not year_month[:4].isdigit()
or not year_month[5:].isdigit()
):
return repo_path
historical_root = f"{DIR_WORKFLOW}/{DIR_TASKS}/{task_dir.name}"
posix_path = file_path.replace("\\", "/")
if posix_path == historical_root:
relative_parts: tuple[str, ...] = ()
elif posix_path.startswith(f"{historical_root}/"):
relative_path = posix_path[len(historical_root) + 1 :]
if relative_path.endswith("/"):
relative_path = relative_path[:-1]
relative_parts = tuple(relative_path.split("/")) if relative_path else ()
if any(part in ("", ".", "..") for part in relative_parts):
return None
else:
return repo_path
try:
archive_root = task_dir.resolve()
resolved_path = task_dir.joinpath(*relative_parts).resolve()
resolved_path.relative_to(archive_root)
except (OSError, RuntimeError, ValueError):
return None
return resolved_path
def _validate_jsonl(jsonl_file: Path, repo_root: Path, task_dir: Path | None = None) -> int:
"""Validate a single JSONL file.
Seed rows (no ``file`` field — typically ``{"_example": "..."}``) are
skipped silently; they are self-describing comments, not real entries.
Historical seed-only rows are accepted in explicit inline mode. Sub-agent
mode rejects scaffolding and empty manifests. Real entries are validated
in both modes.
Beyond hard errors (missing file/dir, invalid JSON), this also prints
non-blocking hygiene warnings (never counted in ``errors``, never change
@@ -184,6 +285,7 @@ def _validate_jsonl(jsonl_file: Path, repo_root: Path, task_dir: Path | None = N
"""
file_name = jsonl_file.name
errors = 0
inline = get_codex_dispatch_mode(repo_root) == "inline"
if not jsonl_file.is_file():
print(f" {colored(f'{file_name}: not found (skipped)', Colors.YELLOW)}")
@@ -212,22 +314,59 @@ def _validate_jsonl(jsonl_file: Path, repo_root: Path, task_dir: Path | None = N
errors += 1
continue
if not isinstance(data, dict):
print(
f" {colored(f'{file_name}:{line_num}: Expected a JSON object', Colors.RED)}"
)
errors += 1
continue
if inline and set(data) == {"_example"}:
continue
if "_example" in data:
error_message = (
f"{file_name}:{line_num}: Placeholder `_example` row left by an older "
"task.py create — delete this line, or replace it with "
'{"file": "<path>", "reason": "<why>"}'
)
print(f" {colored(error_message, Colors.RED)}")
errors += 1
continue
file_path = data.get("file")
entry_type = data.get("type", "file")
if not file_path:
# Seed / comment row — skip silently
if "file" in data or "path" in data or "reason" in data:
print(colored(f"{file_name}:{line_num}: file must be a non-empty string path", Colors.RED))
errors += 1
continue
if not isinstance(file_path, str):
# A truthy non-string (e.g. {"file": 1}) reached path joining and
# raised TypeError, so validation crashed on the row it exists to
# report.
print(
f" {colored(f'{file_name}:{line_num}: `file` must be a string path', Colors.RED)}"
)
errors += 1
continue
if not isinstance(data.get("reason"), str) or not data["reason"].strip():
print(colored(f"{file_name}:{line_num}: reason must be a non-empty string", Colors.RED))
errors += 1
continue
real_entries += 1
full_path = repo_root / file_path
full_path = _resolve_context_entry_path(file_path, repo_root, task_dir)
if entry_type == "directory":
if not full_path.is_dir():
if full_path is None or not full_path.is_dir():
print(f" {colored(f'{file_name}:{line_num}: Directory not found: {file_path}', Colors.RED)}")
errors += 1
continue
if not full_path.is_file():
if full_path is None or not full_path.is_file():
print(f" {colored(f'{file_name}:{line_num}: File not found: {file_path}', Colors.RED)}")
errors += 1
continue
@@ -244,8 +383,14 @@ def _validate_jsonl(jsonl_file: Path, repo_root: Path, task_dir: Path | None = N
print(f" {colored(warning_message, Colors.YELLOW)}")
if max_file_bytes:
size = full_path.stat().st_size
if size > max_file_bytes:
# Advisory hygiene warning, so it must never be what fails
# `validate`. `stat()` can still raise after the `is_file()` check
# above — a permission change, or the file removed in between.
try:
size: int | None = full_path.stat().st_size
except OSError:
size = None
if size is not None and size > max_file_bytes:
warning_message = (
f"{file_name}:{line_num}: Warning: {file_path} is {size} bytes, "
f"exceeds context_injection.max_file_bytes ({max_file_bytes}); "
@@ -253,6 +398,22 @@ def _validate_jsonl(jsonl_file: Path, repo_root: Path, task_dir: Path | None = N
)
print(f" {colored(warning_message, Colors.YELLOW)}")
if errors == 0 and real_entries == 0 and not inline:
# Seed-only / empty manifest: sub-agents dispatched for this task
# would run with zero spec context (#573). Silent-green here is how
# more than half the tasks in the report ended up uncurated.
action = file_name.split(".", 1)[0]
print(
f" {colored(f'{file_name}: ✗ (0 curated entries — sub-agents would get zero spec context)', Colors.RED)}"
)
print(
f" Curate it: python3 .trellis/scripts/task.py add-context <task> {action} <path> \"<why>\""
)
print(
" Intentionally empty? Bypass at start: task.py start <task> --allow-empty-context"
)
return 1
if errors == 0:
print(f" {colored(f'{file_name}: ✓ ({real_entries} entries)', Colors.GREEN)}")
else:
@@ -270,7 +431,7 @@ def cmd_list_context(args: argparse.Namespace) -> int:
repo_root = get_repo_root()
target_dir = resolve_task_dir(args.dir, repo_root)
if not target_dir.is_dir():
if target_dir is None or not target_dir.is_dir():
print(colored("Error: task directory required", Colors.RED))
return 1
@@ -285,7 +446,7 @@ def cmd_list_context(args: argparse.Namespace) -> int:
print(colored(f"[{jsonl_name}]", Colors.CYAN))
count = 0
seed_only = True
curated = False
for line in jsonl_file.read_text(encoding="utf-8").splitlines():
if not line.strip():
continue
@@ -295,11 +456,14 @@ def cmd_list_context(args: argparse.Namespace) -> int:
except json.JSONDecodeError:
continue
if not isinstance(data, dict):
continue
file_path = data.get("file")
if not file_path:
# Seed / comment row — don't count as a real entry
# Placeholder / comment row — don't count as a real entry
continue
seed_only = False
curated = True
count += 1
entry_type = data.get("type", "file")
@@ -311,8 +475,8 @@ def cmd_list_context(args: argparse.Namespace) -> int:
print(f" {colored(f'{count}.', Colors.GREEN)} {file_path}")
print(f" {colored('→', Colors.YELLOW)} {reason}")
if seed_only:
print(f" {colored('(no curated entries yet — only seed row)', Colors.YELLOW)}")
if not curated:
print(f" {colored('(no curated entries yet)', Colors.YELLOW)}")
print()
文件差异内容过多而无法显示 加载差异
+290 -90
查看文件
@@ -3,9 +3,10 @@
Task utility functions.
Provides:
is_safe_task_path - Validate task path is safe to operate on
is_within_tasks_dir - Check a resolved path is a task directly under tasks/
find_task_by_name - Find task directory by name
resolve_task_dir - Resolve task directory from name, relative, or absolute path
archive_destination_for - Path a task would be archived to
archive_task_dir - Archive task to monthly directory
run_task_hooks - Run lifecycle hooks for task events
"""
@@ -16,70 +17,28 @@ import shutil
import sys
from datetime import datetime
from pathlib import Path
from typing import TYPE_CHECKING
from .paths import get_repo_root, get_tasks_dir
if TYPE_CHECKING:
import subprocess
# =============================================================================
# Path Safety
# =============================================================================
def is_safe_task_path(task_path: str, repo_root: Path | None = None) -> bool:
"""Check if a relative task path is safe to operate on.
Args:
task_path: Task path (relative to repo_root).
repo_root: Repository root path. Defaults to auto-detected.
Returns:
True if safe, False if dangerous.
"""
if repo_root is None:
repo_root = get_repo_root()
normalized = task_path.replace("\\", "/")
# Check empty or null
if not normalized or normalized == "null":
print("Error: empty or null task path", file=sys.stderr)
return False
# Reject absolute paths
if Path(task_path).is_absolute():
print(f"Error: absolute path not allowed: {task_path}", file=sys.stderr)
return False
# Reject ".", "..", paths starting with "./" or "../", or containing ".."
if normalized in (".", "..") or normalized.startswith("./") or normalized.startswith("../") or ".." in normalized:
print(f"Error: path traversal not allowed: {task_path}", file=sys.stderr)
return False
# Final check: ensure resolved path is not the repo root
abs_path = repo_root / Path(normalized)
if abs_path.exists():
try:
resolved = abs_path.resolve()
root_resolved = repo_root.resolve()
if resolved == root_resolved:
print(f"Error: path resolves to repo root: {task_path}", file=sys.stderr)
return False
except (OSError, IOError):
pass
return True
def is_within_tasks_dir(task_dir_abs: Path, repo_root: Path | None = None) -> bool:
"""Check that a resolved task directory really is a task under the tasks dir.
A real task lives directly at ``.trellis/tasks/<name>``. This returns True
only when ``task_dir_abs`` is an immediate child of the tasks directory.
Guards archive: ``resolve_task_dir`` falls back to ``repo_root/<name>`` for
an unknown name, so a mistyped ``task.py archive src`` resolves to the real
``src/`` source directory. Without this check archive would ``shutil.move``
it out of the repo. Also rejects the tasks dir itself and anything nested
under ``archive/`` (already-archived tasks).
Narrows ``resolve_task_dir``'s containment for archive: that chokepoint
accepts anything under the tasks dir, including a task already in
``archive/<YYYY-MM>/``. This rejects those, plus the tasks dir itself, so
``shutil.move`` never re-archives an archived task into a nested copy.
"""
if repo_root is None:
repo_root = get_repo_root()
@@ -100,25 +59,46 @@ def is_within_tasks_dir(task_dir_abs: Path, repo_root: Path | None = None) -> bo
def find_task_by_name(task_name: str, tasks_dir: Path) -> Path | None:
"""Find task directory by name (exact or suffix match).
A task name is a single directory name under ``tasks_dir``, never a path:
names carrying a separator or a dot segment are rejected before the join,
so ``".."`` cannot hand back the tasks dir's own parent.
An ambiguous suffix (two tasks created on different days with the same
slug) is a failure, not a coin flip — ``iterdir()`` order is filesystem
order, so silently picking the first match picks a different task on a
different machine.
Args:
task_name: Task name to find.
tasks_dir: Tasks directory path.
Returns:
Absolute path to task directory, or None if not found.
Absolute path to task directory, or None if not found or ambiguous.
"""
if not task_name or not tasks_dir or not tasks_dir.is_dir():
return None
if "/" in task_name or "\\" in task_name or task_name in (".", ".."):
print(f"Error: invalid task name: {task_name}", file=sys.stderr)
return None
# Try exact match first
exact_match = tasks_dir / task_name
if exact_match.is_dir():
return exact_match
# Try suffix match (e.g., "my-task" matches "01-21-my-task")
for d in tasks_dir.iterdir():
if d.is_dir() and d.name.endswith(f"-{task_name}"):
return d
matches = sorted(
d for d in tasks_dir.iterdir()
if d.is_dir() and d.name.endswith(f"-{task_name}")
)
if len(matches) == 1:
return matches[0]
if matches:
print(f"Error: ambiguous task name '{task_name}' matches:", file=sys.stderr)
for match in matches:
print(f" - {match.name}", file=sys.stderr)
print("Pass the full task directory name.", file=sys.stderr)
return None
@@ -127,6 +107,13 @@ def find_task_by_name(task_name: str, tasks_dir: Path) -> Path | None:
# Archive Operations
# =============================================================================
def archive_destination_for(task_dir_abs: Path) -> Path:
"""Path a task would be archived to: <tasks>/archive/<YYYY-MM>/<name>."""
tasks_dir = task_dir_abs.parent
year_month = datetime.now().strftime("%Y-%m")
return tasks_dir / "archive" / year_month / task_dir_abs.name
def archive_task_dir(task_dir_abs: Path, repo_root: Path | None = None) -> Path | None:
"""Archive a task directory to archive/{YYYY-MM}/.
@@ -141,11 +128,8 @@ def archive_task_dir(task_dir_abs: Path, repo_root: Path | None = None) -> Path
print(f"Error: task directory not found: {task_dir_abs}", file=sys.stderr)
return None
# Get tasks directory (parent of the task)
tasks_dir = task_dir_abs.parent
archive_dir = tasks_dir / "archive"
year_month = datetime.now().strftime("%Y-%m")
month_dir = archive_dir / year_month
dest = archive_destination_for(task_dir_abs)
month_dir = dest.parent
# Create archive directory
try:
@@ -154,9 +138,22 @@ def archive_task_dir(task_dir_abs: Path, repo_root: Path | None = None) -> Path
print(f"Error: Failed to create archive directory: {e}", file=sys.stderr)
return None
# Move task to archive
task_name = task_dir_abs.name
dest = month_dir / task_name
# shutil.move into an existing directory moves the source *inside* it,
# producing archive/<month>/<task>/<task>/ and returning a path that is not
# where the task actually landed. That wrong path then flows into the
# printed result, the after_archive hook's TASK_JSON_PATH, and auto-commit
# staging, so refuse before the move instead.
if dest.exists():
print(
f"Error: refusing to archive {task_dir_abs}: "
f"archive destination already exists: {dest}",
file=sys.stderr,
)
print(
"Move or rename the existing archived task, then retry.",
file=sys.stderr,
)
return None
try:
shutil.move(str(task_dir_abs), str(dest))
@@ -195,53 +192,210 @@ def archive_task_complete(
# Task Directory Resolution
# =============================================================================
def resolve_task_dir(target_dir: str, repo_root: Path) -> Path:
"""Resolve task directory to absolute path.
def resolve_task_dir(target_dir: str, repo_root: Path) -> Path | None:
"""Resolve task directory to an absolute path inside the tasks directory.
Supports:
- Absolute path: /path/to/task
- Relative path: .trellis/tasks/01-31-my-task
- Task name: my-task (uses find_task_by_name for lookup)
This is the containment chokepoint for every command that accepts a task
directory argument. The candidate is resolved (following symlinks) and must
land strictly under ``.trellis/tasks/``; archived tasks under
``archive/<YYYY-MM>/`` qualify. Traversal (``../victim``), absolute paths
outside the repo, a task dir symlinked out of the tasks tree, and the
tasks directory itself are all rejected here so no caller has to re-check.
The containment base is the tasks dir's own real location, so a
``.trellis`` that is itself a symlink into a shared store (#567) works.
Args:
target_dir: Task directory specification.
repo_root: Repository root path.
Returns:
Resolved absolute path.
Absolute path spelled through the repo's own tasks dir (in-repo
lexical form), or None when it is not a location inside the tasks
directory (an error naming the path is printed to stderr).
"""
if not target_dir:
return Path()
print("Error: task directory is required", file=sys.stderr)
return None
normalized = target_dir.replace("\\", "/")
while normalized.startswith("./"):
normalized = normalized[2:]
# Absolute path
if Path(target_dir).is_absolute():
return Path(target_dir)
# Relative path (contains path separator or starts with .trellis)
if "/" in normalized or normalized.startswith(".trellis"):
return repo_root / Path(normalized)
# Task name - try to find in tasks directory
tasks_dir = get_tasks_dir(repo_root)
found = find_task_by_name(target_dir, tasks_dir)
if found:
return found
# Fallback to treating as relative path
return repo_root / Path(normalized)
if Path(target_dir).is_absolute():
candidate = Path(target_dir)
elif "/" in normalized or normalized.startswith(".trellis"):
# Relative path (contains path separator or starts with .trellis)
candidate = repo_root / Path(normalized)
else:
# Task name - must resolve inside the tasks directory. The historical
# fallback to repo_root/<name> only ever produced a path the check
# below rejects, so a miss ends here instead.
candidate = find_task_by_name(target_dir, tasks_dir)
if candidate is None:
# find_task_by_name reports invalid names and ambiguity itself.
print(
f"Error: could not resolve task '{target_dir}' under {tasks_dir}",
file=sys.stderr,
)
return None
try:
resolved = candidate.resolve()
tasks_lexical = get_tasks_dir(repo_root.resolve())
tasks_resolved = tasks_lexical.resolve()
except (OSError, RuntimeError) as e:
print(f"Error: could not resolve task directory '{target_dir}': {e}", file=sys.stderr)
return None
if resolved == tasks_resolved:
print(
f"Error: refusing to use '{target_dir}': {tasks_resolved} is the tasks "
"directory itself, not a task",
file=sys.stderr,
)
return None
if tasks_resolved not in resolved.parents:
print(
f"Error: refusing to use '{target_dir}': {resolved} is outside {tasks_resolved}",
file=sys.stderr,
)
return None
# Hand back the path spelled through the repo's own tasks dir rather than
# `resolved`: `.trellis` may be a symlink into a store outside the repo
# (#567), in which case `resolved` sits outside the repo even though the
# task is legitimate, and callers converting to a repo-relative ref for
# storage would refuse it.
return tasks_lexical / resolved.relative_to(tasks_resolved)
# =============================================================================
# Lifecycle Hooks
# =============================================================================
HOOK_TIMEOUT_SECONDS = 60
HOOK_KILL_GRACE_SECONDS = 5
HOOK_OUTPUT_LIMIT = 2000
def _kill_hook_tree(proc: subprocess.Popen[str]) -> None:
"""Kill a timed-out hook's whole process tree, not just the shell.
With ``shell=True`` the direct child is the shell; the actual work runs in
its children. Killing only the shell leaves grandchildren alive holding the
inherited stdout/stderr pipes, and collecting output afterwards then blocks
until those orphans exit — the exact "command that never returns" the
timeout exists to prevent.
POSIX: the hook is started with ``start_new_session=True``, so the shell and
every descendant share one fresh process group; SIGKILL the group.
Windows: ``taskkill /F /T`` walks the tree (best effort).
Either way ``proc.kill()`` is the fallback.
Limitation: a hook that calls ``setsid`` itself leaves the group and
survives this. Accepted and out of scope — a hook is arbitrary code, and the
timeout is a liveness guarantee, not a containment boundary.
"""
import os
import signal
import subprocess
if os.name == "posix":
try:
os.killpg(os.getpgid(proc.pid), signal.SIGKILL)
return
except (ProcessLookupError, PermissionError, OSError):
pass
else:
try:
subprocess.run(
["taskkill", "/F", "/T", "/PID", str(proc.pid)],
capture_output=True,
)
except (OSError, ValueError):
pass
try:
proc.kill()
except OSError:
pass
def _release_hook_process(proc: subprocess.Popen[str]) -> None:
"""Close our pipe ends and reap a finished hook under a bound.
``Popen`` used as a context manager calls ``wait()`` with no timeout when
the block exits. That is the one place the liveness guarantee could still
be lost: if ``_kill_hook_tree`` failed outright — both the process-group
kill and the direct kill raising — the lifecycle command would block there
forever, which is the exact hang the timeout exists to prevent.
"""
import subprocess
for stream in (proc.stdout, proc.stderr, proc.stdin):
if stream is not None:
try:
stream.close()
except OSError:
pass
try:
proc.wait(timeout=HOOK_KILL_GRACE_SECONDS)
except (subprocess.TimeoutExpired, OSError, ValueError):
# Leaves a zombie until this process exits. Fail-open and bounded beats
# a task command that never returns.
pass
def _decode_hook_output(raw: object) -> str:
"""TimeoutExpired carries bytes or str depending on the platform."""
if raw is None:
return ""
if isinstance(raw, bytes):
return raw.decode("utf-8", errors="replace")
return str(raw)
def _print_hook_stream(name: str, text: str) -> None:
"""Print a captured hook stream to stderr, truncated."""
text = text.strip()
if not text:
return
if len(text) > HOOK_OUTPUT_LIMIT:
text = (
text[:HOOK_OUTPUT_LIMIT]
+ f"\n… ({len(text) - HOOK_OUTPUT_LIMIT} more characters truncated)"
)
print(f" {name}:", file=sys.stderr)
for line in text.splitlines():
print(f" {line}", file=sys.stderr)
def run_task_hooks(event: str, task_json_path: Path, repo_root: Path) -> None:
"""Run lifecycle hooks for a task event.
Hooks are shell commands read from ``.trellis/config.yaml`` and executed
with ``shell=True`` from the repo root — see the trust boundary note in
``.trellis/spec/cli/backend/script-conventions.md``.
Fail-open by design: a broken hook warns and the lifecycle command
continues. The warning names the event, command, exit status, and both
captured streams, because a hook whose only symptom is "nothing happened"
is undebuggable. A hook that hangs is bounded by
``HOOK_TIMEOUT_SECONDS``; output is captured, so without the timeout the
user sees a task command that never returns and prints nothing. On timeout
the hook's entire process tree is killed (see ``_kill_hook_tree``) and
output is collected under a bounded grace, so a surviving grandchild
holding the pipes cannot re-create that same hang. Cleanup is bounded for
the same reason — see ``_release_hook_process``.
Args:
event: Event name (e.g. "after_create").
task_json_path: Absolute path to the task's task.json.
@@ -259,28 +413,74 @@ def run_task_hooks(event: str, task_json_path: Path, repo_root: Path) -> None:
env = {**os.environ, "TASK_JSON_PATH": str(task_json_path)}
# POSIX only: a fresh session puts the shell and every descendant in one
# process group, which is what makes the timeout kill the whole tree.
popen_kwargs: dict = {}
if os.name == "posix":
popen_kwargs["start_new_session"] = True
for cmd in commands:
proc = None
try:
result = subprocess.run(
proc = subprocess.Popen(
cmd,
shell=True,
cwd=repo_root,
env=env,
capture_output=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
encoding="utf-8",
errors="replace",
**popen_kwargs,
)
if result.returncode != 0:
try:
stdout, stderr = proc.communicate(timeout=HOOK_TIMEOUT_SECONDS)
except subprocess.TimeoutExpired as e:
_kill_hook_tree(proc)
stdout = _decode_hook_output(e.stdout)
stderr = _decode_hook_output(e.stderr)
try:
# Bounded: an orphan that escaped the kill still holds
# the pipes, and waiting on it forever here would be
# the very hang the timeout prevents.
rest_out, rest_err = proc.communicate(
timeout=HOOK_KILL_GRACE_SECONDS
)
stdout = rest_out or stdout
stderr = rest_err or stderr
except (subprocess.TimeoutExpired, OSError, ValueError):
pass
print(
colored(f"[WARN] Hook failed ({event}): {cmd}", Colors.YELLOW),
colored(
f"[WARN] Hook timed out ({event}) after "
f"{HOOK_TIMEOUT_SECONDS}s: {cmd}",
Colors.YELLOW,
),
file=sys.stderr,
)
if result.stderr.strip():
print(f" {result.stderr.strip()}", file=sys.stderr)
print(f" cwd: {repo_root}", file=sys.stderr)
_print_hook_stream("stdout", stdout)
_print_hook_stream("stderr", stderr)
continue
if proc.returncode != 0:
print(
colored(
f"[WARN] Hook failed ({event}): exit {proc.returncode}: {cmd}",
Colors.YELLOW,
),
file=sys.stderr,
)
print(f" cwd: {repo_root}", file=sys.stderr)
_print_hook_stream("stdout", stdout or "")
_print_hook_stream("stderr", stderr or "")
except Exception as e:
print(
colored(f"[WARN] Hook error ({event}): {cmd} — {e}", Colors.YELLOW),
colored(
f"[WARN] Hook error ({event}): {cmd} — {type(e).__name__}: {e}",
Colors.YELLOW,
),
file=sys.stderr,
)
@@ -294,5 +494,5 @@ if __name__ == "__main__":
tasks = get_tasks_dir(repo)
print(f"Tasks dir: {tasks}")
print(f"is_safe_task_path('.trellis/tasks/test'): {is_safe_task_path('.trellis/tasks/test', repo)}")
print(f"is_safe_task_path('../test'): {is_safe_task_path('../test', repo)}")
print(f"resolve_task_dir('.trellis/tasks/test'): {resolve_task_dir('.trellis/tasks/test', repo)}")
print(f"resolve_task_dir('../test'): {resolve_task_dir('../test', repo)}")
+13 -3
查看文件
@@ -12,10 +12,11 @@ Provides:
from __future__ import annotations
import sys
from collections.abc import Iterator
from pathlib import Path
from .io import read_json
from .io import describe_json_read_failure, read_json_checked
from .paths import FILE_TASK_JSON
from .types import TaskInfo
@@ -28,13 +29,22 @@ def load_task(task_dir: Path) -> TaskInfo | None:
Returns:
TaskInfo if task.json exists and is valid, None otherwise.
A directory without task.json is not a task, so it is skipped silently.
A task.json that exists but cannot be loaded is different: the task
disappears from `task.py list` and from every context the iterator feeds.
Callers stay tolerant, but the skip is announced on stderr so a task
cannot vanish from the workflow with no diagnostic anywhere.
"""
task_json = task_dir / FILE_TASK_JSON
if not task_json.is_file():
return None
data = read_json(task_json)
if not data:
data, reason = read_json_checked(task_json)
if data is None:
problem, hint = describe_json_read_failure(task_json, reason)
print(f"[WARN] Skipping task '{task_dir.name}': {problem}", file=sys.stderr)
print(f" {hint}", file=sys.stderr)
return None
return TaskInfo(
+116 -9
查看文件
@@ -2,13 +2,23 @@
"""
Standalone reader for .trellis/config.yaml.
Mirrors a minimal subset of common.config so callers (hooks, workflow_phase)
can read configuration without importing the full task/repo helpers. Returns
an empty dict on missing/malformed files so callers stay simple.
Owns the minimal YAML parser used across Trellis. ``common.config`` imports
``parse_simple_yaml`` from here rather than keeping its own copy: this module
imports nothing from the package, so hooks can load it as a single file, and
one parser cannot drift from another. Returns an empty dict on
missing/malformed files so callers stay simple.
Supported subset: ``key: value`` scalars (everything is a string), nested
mappings by indentation, ``- `` lists of scalars, ``#`` comments (whole-line
and inline outside quotes), and one layer of matching surrounding quotes.
Constructs outside that subset — block scalars, anchors, aliases, merge keys,
flow collections, and mappings nested inside a list — are reported on stderr
and skipped rather than parsed into a plausible-looking wrong value.
"""
from __future__ import annotations
import sys
from pathlib import Path
from typing import Optional
@@ -52,11 +62,62 @@ def _next_content_line(lines: list[str], start: int) -> tuple[int, str]:
return i, ""
def _warn_unsupported(source: str, lineno: int, line: str, reason: str) -> None:
"""Report a YAML construct this parser cannot represent, and move on."""
print(
f"[WARN] {source}:{lineno}: {reason}; ignoring: {line.strip()}",
file=sys.stderr,
)
def _is_block_scalar(value: str) -> bool:
"""True for ``|``, ``>`` and their chomping/indent indicators (``|-``, ``>2``)."""
if not value or value[0] not in ("|", ">"):
return False
return all(ch in "+-0123456789" for ch in value[1:])
def _unsupported_value(key: str, value: str) -> str | None:
"""Name the unsupported construct in an unquoted scalar value, else None.
Only unquoted values are inspected: ``cmd: "[a] | b"`` is a string the user
wrote deliberately, while a bare ``notes: |`` or ``base: *anchor`` would
otherwise be stored as the literal marker with the real content dropped.
"""
if key == "<<":
return "YAML merge keys are not supported"
if _is_block_scalar(value):
return "block scalars are not supported"
if value.startswith("&"):
return "YAML anchors are not supported"
if value.startswith("*"):
return "YAML aliases are not supported"
if value.startswith("["):
return "flow sequences are not supported (use `- ` list items)"
if value.startswith("{"):
return "flow mappings are not supported (use an indented mapping)"
return None
def _skip_indented_body(lines: list[str], start: int, indent: int) -> int:
"""Skip the continuation lines of a rejected key (block scalar body etc.)."""
i = start
while i < len(lines):
stripped = lines[i].strip()
if stripped and len(lines[i]) - len(lines[i].lstrip()) <= indent:
break
i += 1
return i
def _parse_yaml_block(
lines: list[str], start: int, min_indent: int, target: dict
lines: list[str], start: int, min_indent: int, target: dict, source: str
) -> int:
i = start
current_list: list | None = None
# Indent of the key that opened current_list, so a deeper `key: value`
# can be recognized as a mapping inside that list.
list_owner_indent = 0
while i < len(lines):
line = lines[i]
@@ -75,10 +136,33 @@ def _parse_yaml_block(
current_list.append(_unquote(stripped[2:].strip()))
i += 1
elif ":" in stripped:
if current_list is not None and indent > list_owner_indent:
# `- name: cli` / ` path: x`: the second key belongs to a
# mapping inside the list. Storing it would hoist it into the
# parent dict as a sibling of the list — a nested key silently
# becoming a root key.
_warn_unsupported(
source,
i + 1,
line,
"mappings inside a list are not supported",
)
i += 1
continue
key, _, value = stripped.partition(":")
key = key.strip()
value = _strip_inline_comment(value).strip()
was_quoted = len(value) >= 2 and value[0] == value[-1] and value[0] in ('"', "'")
if not was_quoted:
reason = _unsupported_value(key, value)
if reason is not None:
_warn_unsupported(source, i + 1, line, reason)
current_list = None
i = _skip_indented_body(lines, i + 1, indent)
continue
value = _unquote(value)
current_list = None
@@ -92,6 +176,7 @@ def _parse_yaml_block(
i = next_i
elif next_line.strip().startswith("- "):
current_list = []
list_owner_indent = indent
target[key] = current_list
i += 1
else:
@@ -99,7 +184,7 @@ def _parse_yaml_block(
if next_indent > indent:
nested: dict = {}
target[key] = nested
i = _parse_yaml_block(lines, i + 1, next_indent, nested)
i = _parse_yaml_block(lines, i + 1, next_indent, nested, source)
else:
target[key] = {}
i += 1
@@ -109,11 +194,33 @@ def _parse_yaml_block(
return i
def parse_simple_yaml(content: str) -> dict:
"""Parse a small subset of YAML. See common.config for full doc."""
def parse_simple_yaml(content: str, source: str = "config.yaml") -> dict:
"""Parse simple YAML with nested dict support (no dependencies).
Supports:
- key: value (string)
- key: (followed by list items)
- item1
- item2
- key: (followed by nested dict)
nested_key: value
nested_key2:
- item
Uses indentation to detect nesting (2+ spaces deeper = child). Every value
is a string; consumers coerce. Unsupported constructs are reported on
stderr against ``source`` and skipped — see the module docstring.
Args:
content: YAML content string.
source: Label used in warnings, normally the config file path.
Returns:
Parsed dict (values can be str, list[str], or dict).
"""
lines = content.splitlines()
result: dict = {}
_parse_yaml_block(lines, 0, 0, result)
_parse_yaml_block(lines, 0, 0, result, source)
return result
@@ -126,7 +233,7 @@ def read_trellis_config(repo_root: Optional[Path] = None) -> dict:
except (FileNotFoundError, OSError):
return {}
try:
parsed = parse_simple_yaml(content)
parsed = parse_simple_yaml(content, source=str(config_file))
except Exception:
return {}
return parsed if isinstance(parsed, dict) else {}
+24 -1
查看文件
@@ -141,6 +141,25 @@ def _platform_matches(platform: str, block_names: list[str]) -> bool:
return False
_PLATFORM_MARKER_LABELS: dict[str, str] = {
# workflow.md marker blocks label platforms with their product names, but
# every caller passes the stable id instead (`--platform {{CLI_FLAG}}` in
# the start / continue commands). `_platform_matches` only strips
# punctuation, so an id that is not its label-minus-spaces never matches and
# `filter_platform` drops the block WITHOUT error — the section just comes
# back empty. Four platforms shipped that way before this table existed.
#
# Add an entry whenever a platform's id is not its marker label with the
# separators removed. `test/registry-invariants.test.ts` asserts every
# registry id keeps a non-empty routing section, so a missing entry fails
# there rather than silently blanking that platform's routing.
"claude": "Claude Code",
"kimi": "Kimi Code",
"omp": "Oh My Pi",
"dsh": "DeepSeek Harness",
}
def resolve_effective_platform(platform: str, config: dict) -> str:
"""Map ``codex`` to a dispatch-mode-namespaced virtual platform name.
@@ -155,8 +174,12 @@ def resolve_effective_platform(platform: str, config: dict) -> str:
explicit values fall back to ``inline`` safely; this renderer deliberately
does not warn because it can run in normal CLI output flows.
Other platforms are returned unchanged.
Platforms whose marker label differs from their id resolve through
``_PLATFORM_MARKER_LABELS``. Everything else is returned unchanged.
"""
label = _PLATFORM_MARKER_LABELS.get(platform.strip().lower())
if label:
return label
if platform == "codex":
mode = "auto"
codex_cfg = config.get("codex") if isinstance(config, dict) else None