martin1847/evolab / skills/cto-orchestration
cto-orchestration
Unverified以 CTO/orchestrator 模式管理多 agent 软件交付。用户要求“你做 CTO/编排者”“派 omp/codex 去做”“goal 模式派发”、管理多会话开发或接入这套工作流时使用;“复盘/收口/retro/retrospective”“工作盘点/盘点候选/stocktake”也必须触发,盘点只提案不动工。新项目先用 repo-governance-bootstrap 建治理骨架。不用于单 agent 小任务、无需评审循环的局部改动或纯文档初始化。
references/agentctl/cto-guard-edit.py
View on GitHub#!/usr/bin/env python3
# cto-guard-edit — PreToolUse·Edit|Write|MultiEdit enforcement for cto-orchestration. ONE rule:
# (E1) the ORCHESTRATOR writing product code by hand, IN A REPO THIS BOX IS ORCHESTRATING
# -> WARN (iron law ①, 车道分工, field n=2: two batches where the seat hand-coded the very
# thing it had just briefed a worker for, and paid for it with the review lane it thereby
# lost). The rule existed only in prose (SKILL.md §0) and prose does not reach the moment
# a `Write` tool call is issued — same conclusion as cto-guard-bash/agent, promoted to a
# tool-call hook.
# WHY IT ONLY WARNS (owner ruling 2026-09-30, this rule and its bash twin (20) together): the
# verdict used to be a DENY liftable by a one-shot marker, and the field price of that shape is
# a dispatched ROUND per false stop — downstream 2026-09-29, a 3-line forensic script was
# stopped twice. "Is this product code" is not mechanically decidable from an extension, which
# is why the five blind branches below already ALLOW+WARN; the judged branch now joins them.
# The line still names the disease and the target, so a retro can COUNT the slips; what is gone
# is the block, and with it the marker that only existed to lift the block.
#
# WHICH REPO IS THIS GATE'S BUSINESS — the clause added 2026-09-06 (audit §1). Until then the
# rule fired in EVERY git work tree, so a single-agent session editing an unrelated checkout was
# denied (probed at rc 2) — i.e. the gate dragged exactly the "small single-agent task" the SKILL
# excludes into the dispatch flow. The target repo must now be one agentctl is ORCHESTRATING
# (`identity.orchestrated`: a LIVE seat, or a phase-ledger `start` row of today/yesterday, in the
# SAME repo by git common dir). `not` ⇒ silent allow, zero output: an unrelated session must not
# even be told a gate exists. `undecidable` ⇒ the same ALLOW+WARN every other blind branch takes.
#
# WHAT IS JUDGED: the WRITE TARGET, not the caller's location. `file_path` decides the repo face
# (the git work tree enclosing it) and the run-dir census decides who owns that face. Judging the
# caller's `cwd` instead was the R1 shape and it was wrong in both directions (cold review §1.1,
# both counter-probed): a live seat could write an absolute `.py` into ANOTHER checkout and pass,
# while an orchestrator sitting in a git cwd was denied for `/tmp/outside.py`, a path no repo
# governs at all. The predicate now stands on the target's work tree; `cwd` only answers "is the
# caller itself a seat", which decides whether a FOREIGN repo is this gate's business.
#
# HOW A WORKER IS TOLD APART FROM THE ORCHESTRATOR — the whole difficulty of this gate.
# A worker seat's worktree is the `cwd=` line of its `<session>.duplex.meta` in the run dir, and a
# LIVE seat licenses every write inside its own WORK TREE — compared by ROOT, so a seat launched
# in a subdirectory still covers its repo root (R1 denied that legal worker: review §1.4), and a
# SIBLING worktree of the same repo is deliberately NOT covered: that is the orchestrator's own
# checkout seen from a seat. The seat set, its liveness rule and the repo-identity predicate all
# live in `identity.py` next to this file and are IMPORTED, never copied — three gates read the
# same fact (E1, Stop, the compaction reminder) and a second copy would drift on the first move.
# DEGRADE DIRECTION, deliberately ALLOW+WARN (never checker-error): an unlistable run dir, a meta
# that cannot be OPENED (a listable directory is not a readable census — review §1.3), or a target
# no governed work tree owns all mean the question is UNANSWERABLE, and a guard that cannot answer
# must not brick the Edit tool. The WARN says so out loud instead of passing in silence.
#
# THE CALLER MAY BE A SUB AGENT — the 2026-09-18 clause (GATE-AUDIT slug `e1-subagent-warn`).
# A settings-level hook fires for a sub agent's tool calls too, and dispatching a worker to WRITE
# is the SKILL §0 shape this rule exists to protect: field 2026-09-18, a read-back sub agent whose
# whole task was `scripts/fe-verify/probes/*.probe.ts` was denied here (and once more by rule (20)
# on a heredoc), on the strength of ANOTHER worktree's ledger row, and could only proceed through
# the one-shot override plus a self-report. So the gate was firing on the wrong caller.
# JUDGED: the payload's top-level `agent_id`, non-empty STRING only — the field Claude Code sends
# ONLY inside a sub agent's tool call. Present ⇒ the CALLER-CLASS line instead of the 编排位 one
# (both rc 0 since 2026-09-30; the two texts stay distinct because only one of them is a
# 车道分工 slip worth counting); absent, empty, or not a string ⇒ the 编排位 line.
# NOT JUDGED, deliberately: `agent_type` is a LABEL for the warn text and never part of the
# predicate (a name is not an identity); `transcript_path` is not read; there is no "product
# directory" exemption — the target face is unchanged. A FORK sub agent is undocumented on this
# field: carrying `agent_id` it draws the sub-agent line, without it the 编排位 line — this
# clause reads what the payload says and guesses nothing.
# KILL CRITERION (slug `e1-orchestrator-warn`, replacing the fork-routing one the DENY carried):
# a retro that reads 30 days of these WARNs and finds every one of them a write the orchestrator
# was right to make ⇒ delete the branch, it is ceremony. Raising it back to a block is the
# owner's call on the counted 车道分工 slips, never this file's.
# Deny = exit 2 + stderr (shown to the agent). Warn = exit 0 + JSON
# hookSpecificOutput.additionalContext (the only channel that reaches the agent at exit 0).
import sys, json, os, re, subprocess
# The shared seat/identity facts. Loaded from THIS script's own directory, which is what keeps an
# installed copy self-contained; a module that cannot be loaded at all is one more UNANSWERABLE
# case, so it degrades to ALLOW+WARN like the others rather than bricking the Edit tool.
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
try:
import identity
except Exception: # noqa: BLE001 — a broken sibling must not deny
identity = None
# The source face, by extension. Docs and data (md/json/yaml/toml/txt/csv/…) are NOT product code
# and never reach the rule: the orchestrator writes goals, records and briefs all day, and a gate
# that argued with that would be off within the hour. `/test/|/tests/` catches only the shape the
# extension list cannot see — an EXTENSION-LESS fixture or runner under a test dir. It is NOT
# OR-ed over the extension test any more: that OR denied `test/fixtures/data.json` and
# `tests/config.yaml`, i.e. exactly the non-source faces the contract puts through (review §1.2,
# counter-probed at rc=2).
_SRC_EXT = {"py", "sh", "bash", "ts", "js", "tsx", "jsx", "go", "rs", "java", "kt", "rb"}
_TEST_DIR = re.compile(r"/tests?/")
# The six ALLOW+WARN texts, as module-level literals emitted through an INLINE json.dumps at
# each branch. Not a style choice: the injected-text ratchet (test/loc-budget.test.sh)
# weighs literals AT the sink and resolves one local per sink, so a message routed through a
# `warn(text)` helper's parameter would be spent entirely unweighed — the exact blind spot that
# gate's header warns about. Keeping the literal at the sink keeps every byte on the meter.
_W_NO_CWD = (
"WARN (cto-guard E1): this payload carries no `cwd`, so which seat is writing %s could not "
"be attributed and the 车道分工 rule stayed silent. If you are the orchestrator, dispatch "
"the edit instead of making it (SKILL.md §0 铁律①)."
)
_W_RUN_DIR = (
"WARN (cto-guard E1): run dir %s could not be read as a census, so the LIVE seat set is "
"unknown and the write to %s was allowed unjudged. 车道分工 (SKILL.md §0 铁律①) still holds: "
"the orchestrator dispatches product code, it does not type it."
)
_W_TARGET = (
"WARN (cto-guard E1): write target %s is not inside a git work tree governed by this call's "
"cwd %s or by any LIVE seat, so 车道分工 (SKILL.md §0 铁律①) had no repo face to judge and "
"the write was allowed unjudged."
)
_W_IDENTITY = (
"WARN (cto-guard E1): whether this repo is being ORCHESTRATED could not be established (%s), "
"so the write to %s was allowed unjudged. If a batch is running here, 车道分工 (SKILL.md §0 "
"铁律①) holds: dispatch product code, do not type it."
)
_W_SUBAGENT = (
"WARN (cto-guard E1): 子 agent %s 写源码面 %s——派出去写的产物放行留痕;若这是编排位借子 agent "
"绕道,按 SKILL 铁律① 自查。"
)
_W_ORCH = (
"WARN (cto-guard E1): 编排位直写源码面 %s——该仓正在被编排(%s)且无活体席位持有这棵树"
"(call cwd %s)。留痕不阻断:按 SKILL.md §0 铁律① 车道分工,实现派出去"
"写——`agentctl start <engine> <session> <cwd> --goal <abs>`。"
)
def checker_error(message):
sys.stderr.write(f"CHECKER-ERROR: {message}\n")
return 2
def _is_source(path):
norm = path.replace(os.sep, "/")
ext = norm.rsplit("/", 1)[-1].rsplit(".", 1)
if len(ext) == 2 and ext[1]:
return ext[1].lower() in _SRC_EXT
return bool(_TEST_DIR.search(norm))
def _under(child, parent):
"""True when `child` IS `parent` or sits inside it. A seat that cd's deeper into its own
worktree is still that seat — the generous direction, same reason as the liveness default."""
try:
child = os.path.realpath(child)
parent = os.path.realpath(parent)
except OSError:
return False
return child == parent or child.startswith(parent.rstrip(os.sep) + os.sep)
def _worktree_root(path):
"""(realpath of the enclosing work tree, decided). `decided` False also covers "git
unavailable" and "no such directory": all three mean nobody can attribute this path to a
repo, so the rule has nothing to stand on."""
try:
proc = subprocess.run(["git", "-C", path, "rev-parse", "--show-toplevel"],
stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, timeout=10)
except Exception:
return None, False
if proc.returncode != 0:
return None, False
root = proc.stdout.decode("utf-8", "replace").strip()
if not root:
return None, False
try:
return os.path.realpath(root), True
except OSError:
return None, False
def _seat_holds(node, seat, node_root, node_decided):
"""True when `node` belongs to `seat`'s work tree: inside the seat's directory, or — the
decisive half — the SAME git work tree root. Root equality is what closes review §1.4 (a
seat launched from a repo subdirectory owns its repo root too); a reversed containment test
would have done it by handing the seat's PARENT checkout write rights, which is the
orchestrator's own tree and the direction this gate exists to judge."""
if _under(node, seat):
return True
seat_root, decided = _worktree_root(seat)
return bool(node_decided and decided and seat_root == node_root)
def _target_dir(path, cwd):
"""The nearest EXISTING directory at or above the write target — the only place a repo
question can be asked, because the target file (and its parents) may not exist yet."""
node = path if os.path.isabs(path) else os.path.join(cwd, path)
node = os.path.dirname(node) or os.sep
while True:
if os.path.isdir(node):
return node
parent = os.path.dirname(node)
if parent == node:
return node
node = parent
def main():
try:
data = json.load(sys.stdin)
except Exception:
return checker_error("invalid hook JSON.")
if not isinstance(data, dict):
return checker_error("hook payload must be an object.")
event = data.get("hook_event_name")
tool = data.get("tool_name")
if event is not None and not isinstance(event, str):
return checker_error("hook_event_name must be a string.")
if tool is not None and not isinstance(tool, str):
return checker_error("tool_name must be a string.")
if event != "PreToolUse" or tool not in ("Edit", "Write", "MultiEdit"):
return 0
ti = data.get("tool_input")
if not isinstance(ti, dict):
return checker_error("PreToolUse Edit|Write|MultiEdit requires object tool_input.")
path = ti.get("file_path")
if not isinstance(path, str) or not path:
return checker_error(
"PreToolUse Edit|Write|MultiEdit requires string tool_input.file_path.")
if path.endswith("test/loc-budget.limits"):
sys.stderr.write("DENY: owner-only ceiling: raise it by hand. Read: cto-orchestration/SKILL.md.\n")
return 2
if not _is_source(path):
return 0
cwd = data.get("cwd")
if not isinstance(cwd, str) or not cwd:
print(json.dumps({"hookSpecificOutput": {
"hookEventName": "PreToolUse", "additionalContext": _W_NO_CWD % path}}))
return 0
if identity is None:
print(json.dumps({"hookSpecificOutput": {
"hookEventName": "PreToolUse", "additionalContext": _W_IDENTITY % (
"identity.py could not be loaded from this script's own directory", path)}}))
return 0
run_dir = identity.run_dir()
seats, listed, complete = identity.live_seat_cwds(run_dir)
if not (listed and complete):
print(json.dumps({"hookSpecificOutput": {
"hookEventName": "PreToolUse", "additionalContext": _W_RUN_DIR % (run_dir, path)}}))
return 0
# THE TARGET decides: which work tree is being written, and does a LIVE seat hold it. One
# `git rev-parse` for the target, one for the cwd, and one per seat only until a holder is
# found — paid solely on the source face, where the alternative is a wrong verdict.
tdir = _target_dir(path, cwd)
troot, tdecided = _worktree_root(tdir)
if any(_seat_holds(tdir, seat, troot, tdecided) for seat in seats):
return 0 # a live seat writing inside its own worktree
# Out of the governed face entirely: a target no work tree owns (`/tmp/x.py`) is not the
# orchestrator typing product code, and R1 denied it (review §1.1). A FOREIGN repo stays in
# scope only when the caller is itself a live seat — a seat writing source into another
# checkout is the same disease, and R1 let it through.
croot, cdecided = _worktree_root(cwd)
caller_seat = any(_seat_holds(cwd, seat, croot, cdecided) for seat in seats)
if not (tdecided and (caller_seat or (cdecided and croot == troot))):
print(json.dumps({"hookSpecificOutput": {
"hookEventName": "PreToolUse", "additionalContext": _W_TARGET % (path, cwd)}}))
return 0
# IS THIS REPO EVEN BEING ORCHESTRATED? Asked LAST, because the branches above are the ones
# that end in an ALLOW anyway, and asked at all because without it this rule fires in every
# git work tree on the box (audit §1: the single-agent lane the SKILL excludes was denied).
# The question is about the TARGET's repo, the same face the rule judges — not about the
# caller, who may legitimately sit in another checkout.
state, why = identity.orchestrated(tdir, run_dir)
if state == identity.NOT_ORCHESTRATED:
return 0 # nobody is orchestrating here: not this gate's face
if state != identity.ORCHESTRATED:
print(json.dumps({"hookSpecificOutput": {
"hookEventName": "PreToolUse", "additionalContext": _W_IDENTITY % (why, path)}}))
return 0
# THE CALLER IS A SUB AGENT (header clause, owner ruling 2026-09-18): a payload carrying a
# non-empty `agent_id` is a worker that was DISPATCHED to write — the shape 铁律① protects,
# not the shape it forbids. Placed HERE, at the judged point, so every branch above keeps
# its own verdict and no case draws two WARN lines. `agent_type` is the label only.
sub = data.get("agent_id")
if isinstance(sub, str) and sub:
kind = data.get("agent_type")
print(json.dumps({"hookSpecificOutput": {
"hookEventName": "PreToolUse", "additionalContext": _W_SUBAGENT % (
kind if isinstance(kind, str) and kind else sub, path)}}))
return 0
# THE JUDGED BRANCH (owner ruling 2026-09-30, header): an orchestrated work tree, no LIVE
# seat holding it, no sub-agent field — the orchestrator typing product code. One WARN line
# at rc 0, the same channel the five blind branches use, so the slip is countable in retro
# without costing a dispatched round when the extension guessed wrong.
print(json.dumps({"hookSpecificOutput": {
"hookEventName": "PreToolUse", "additionalContext": _W_ORCH % (path, why, cwd)}}))
return 0
if __name__ == "__main__":
try:
sys.exit(main())
except Exception:
sys.exit(checker_error("internal guard failure."))
Related skills
| Skill | Stars | Updated | Works with | Status | Install |
|---|---|---|---|---|---|
| reverse-engineer-anythingmorluto/reaReverse engineer native, managed, Electron/JavaScript, packaged, firmware, and browser targets with REA, and build agent environments (AgentEnv bundles) of web applications from a live instance or a capture, and of Linux desktop apps with a task from a request. Use shipped-artifact or requested runtime evidence to explain features, compare versions, decompile code, or guide a reconstruction. Skip REA for ordinary source-repository architecture analysis. | Stars: 472k | Updated | Claude CodeCodex | Verified | Install |
| diagnosing-superpowersobra/superpowersUse when a superpowers session went wrong and your human partner wants to know why — repeated work, ignored plans, stumbles, poor results, a skill that didn't fire, "it took too long", "why is it so expensive", "what is it doing" — or wants to build a bug report for the superpowers maintainers, for the current session or a past one identified by id or path, on any harness. | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |
| dispatching-parallel-agentsobra/superpowersUse when facing 2+ independent tasks that can be worked on without shared state or sequential dependencies | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |
| executing-plansobra/superpowersUse when executing an implementation plan in the current session as the implementer yourself — your human partner chose inline execution, or no subagent tool is available | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |