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

这个提交包含在:
2026-09-06 11:14:41 +08:00
父节点 ab82fe30c0
当前提交 c3cef5cfc4
共修改 48 个文件,包含 4588 行新增和 1053 行删除
+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,