diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json index 026f552..0b32fac 100644 --- a/.claude-plugin/plugin.json +++ b/.claude-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "analysis-workflow", - "version": "0.9.2", + "version": "0.10.0", "description": "Conventions for analysis repos where humans and coding agents work side by side: versioned task directories for both, one session, worktree and PR per agent task; worktree-safe output paths; additive write-back to AnnData and SpatialData stores, which record which task wrote what. Ships a skill, guard hooks and the analysis_workflow Python package.", "author": { "name": "quadbio" diff --git a/README.md b/README.md index 2f621f4..87de735 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,7 @@ only. The plugin adds what only agents do: one task per session, git worktree an | --- | --- | | `skills/analysis-workflow/` | The agent's side: task lifecycle in a worktree, sign-off, PRs, environments, setting up repos. Loaded on demand. | | `skills/declare-inputs/`, `skills/trace-lineage/` | What a task consumed, written to its `inputs.yaml` from its code; and how an artifact was made, as a graph and a summary. | -| `hooks/` | Always-on core rules and the main checkout's environment at session start; guards that stop a rule being broken by accident. | +| `hooks/` | Always-on core rules and the main checkout's environment at session start; guards that stop a rule being broken by accident, each of which you can lift for a session. | | `src/analysis_workflow/` | The Python package and its `analysis-workflow` command: task paths, writes to shared stores and their records, tracing, layout checks; the task template. | It assumes analysis repos made from [analysis_template](https://github.com/quadbio/analysis_template) @@ -35,6 +35,10 @@ claude --worktree 4. It opens a PR whose body holds the details; the task README summarizes each PR. Once it is merged and its batch jobs have finished, leave with `/exit` and remove the worktree. +A rule is broken only with your approval. When a guard refuses something you want done, the agent passes on the +command that lifts it for that session, `/analysis-workflow:allow `, which only you can run; the PR notes +the exception (the template's `CONVENTIONS.md`). + You work the same way, in `human_` task directories in the main checkout (the template's `CONVENTIONS.md`). A task that changes the environment locks, installs and tests it in a temporary checkout beside the main one; after its merge you pull and run `pixi install` there. With no analysis repo yet, ask Claude to start an analysis project: the skill sets one up. diff --git a/hooks/_repo.py b/hooks/_repo.py index ecf6bbe..afe4300 100644 --- a/hooks/_repo.py +++ b/hooks/_repo.py @@ -8,12 +8,37 @@ from __future__ import annotations import json +import os import shlex import subprocess from pathlib import Path PLUGIN = "analysis-workflow" +#: The guards the human can lift for a session, by the name they type after `/analysis-workflow:allow`. +GUARDS = ("layout", "paths", "pixi", "shared-writes") +ALLOW = f"{PLUGIN}:allow" + + +def marker(payload: dict) -> Path | None: + """The file listing the guards lifted for the payload's session, one per line; None if it has no home.""" + data, session = os.environ.get("CLAUDE_PLUGIN_DATA"), Path(str(payload.get("session_id") or "")).name + return Path(data) / "exceptions" / session if data and session else None + + +def lifted(payload: dict) -> list[str]: + """The guards the human lifted for the payload's session, subagents included; `allow_exception.py` records them.""" + try: + return marker(payload).read_text().split() + except (OSError, AttributeError): + return [] + + +def how_to_lift(guard: str) -> str: + """The last line of a guard's refusal.""" + return f"Only the human can lift this guard, for this session, by typing `/{ALLOW} {guard}`." + + #: `pixi` subcommands that change the workspace environment, or use it and so install it first if it is missing. PIXI_ENV_COMMANDS = frozenset( {"install", "add", "lock", "upgrade", "update", "reinstall", "remove", "run", "shell", "shell-hook"} diff --git a/hooks/allow_exception.py b/hooks/allow_exception.py new file mode 100644 index 0000000..ed1c701 --- /dev/null +++ b/hooks/allow_exception.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +"""Lift one guard for this session when the human types `/analysis-workflow:allow `. + +UserPromptExpansion fires for a command the human types, and not for a skill the model loads, a scheduled prompt +or a message from a subagent or another session: only the human lifts a guard. The guard is recorded in the +session's marker (`_repo.py`), which the guards read and which outlives resume and compaction. + +It acts only in a repo that has adopted the plugin. An unknown guard blocks the command and names the guards to +the human; otherwise stdout tells the agent what was lifted. +Standard library only: it runs on whatever `python3` is on PATH. +""" + +from __future__ import annotations + +import json +import sys +from pathlib import Path + +from _repo import ALLOW, GUARDS, adopted, checkouts, lifted, marker + + +def main() -> int: + """Read the hook payload from stdin; return the exit code.""" + payload = json.load(sys.stdin) + if payload.get("command_name") != ALLOW: + return 0 + found = checkouts(Path(payload.get("cwd") or ".").resolve()) + if not (found and adopted(found[0])): + return 0 + guard, path = str(payload.get("command_args") or "").strip(), marker(payload) + if guard not in GUARDS or path is None: + why = f"no guard named `{guard}`; one of {', '.join(GUARDS)}." if path else "nowhere to record it." + print(json.dumps({"decision": "block", "reason": f"analysis-workflow: {why}"})) + return 0 + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text("".join(f"{g}\n" for g in dict.fromkeys([*lifted(payload), guard]))) + print( + f"The human lifted the `{guard}` guard for this session. What it now lets through is an exception to " + "these conventions: note it as the repo's `CONVENTIONS.md` says." + ) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/hooks/guard_shared_writes.py b/hooks/guard_shared_writes.py index b16a783..c4679c1 100644 --- a/hooks/guard_shared_writes.py +++ b/hooks/guard_shared_writes.py @@ -18,7 +18,7 @@ import sys from pathlib import Path -from _repo import adopted, checkouts, shell_calls +from _repo import adopted, checkouts, how_to_lift, lifted, shell_calls COMMANDS = frozenset({"cp", "mv", "rsync"}) #: Options of `cp` and `mv` that name the destination directory, in place of the last operand. To `rsync`, `-t` @@ -66,13 +66,15 @@ def main() -> int: target = destination(name, args) if target is None or any(c in target for c in "$`") or not into_shared_storage(target, cwd, found): continue + if "shared-writes" in lifted(payload): + return 0 print( f"Refused: `{name}` into shared storage ({target}).\n" "An object enters `data//processed/` from Python, inside a `writes` block, so the store\n" "records which task wrote it, and only after the human approved the write:\n" " with writes(dest):\n" " shutil.copytree(src, dest)\n" - "See the analysis-workflow skill (Tasks, Finish).", + f"See the analysis-workflow skill (Tasks, Finish). {how_to_lift('shared-writes')}", file=sys.stderr, ) return 2 diff --git a/hooks/guard_task_layout.py b/hooks/guard_task_layout.py index 8a0c372..4c2e88b 100644 --- a/hooks/guard_task_layout.py +++ b/hooks/guard_task_layout.py @@ -22,7 +22,7 @@ import sys from pathlib import Path -from _repo import adopted, checkouts +from _repo import adopted, checkouts, how_to_lift, lifted PLUGIN = Path(__file__).parents[1] PACKAGE = PLUGIN / "src" / "analysis_workflow" @@ -168,11 +168,11 @@ def main() -> int: problems = check_changes(Path(payload.get("cwd") or ".")) else: problems = check_write(payload.get("tool_input", {})) - if not problems: + if not problems or "layout" in lifted(payload): return 0 for why in problems: print(f"Off the task layout: {why}", file=sys.stderr) - print("See the analysis-workflow skill (Tasks) and its task template.", file=sys.stderr) + print(f"See the analysis-workflow skill (Tasks) and its task template. {how_to_lift('layout')}", file=sys.stderr) return 2 diff --git a/hooks/guard_task_paths.py b/hooks/guard_task_paths.py index 99ce127..42c730d 100644 --- a/hooks/guard_task_paths.py +++ b/hooks/guard_task_paths.py @@ -27,7 +27,9 @@ adopted, as_is, checkouts, + how_to_lift, is_root_of_worktree, + lifted, manifest_arg, nearest_manifest, pixi_calls, @@ -78,7 +80,8 @@ def _rules(repo: str) -> list[tuple[re.Pattern, str, str]]: def main() -> int: """Read the hook payload from stdin; return the exit code.""" - tool_input = json.load(sys.stdin).get("tool_input", {}) + payload = json.load(sys.stdin) + tool_input = payload.get("tool_input", {}) file_path = Path(tool_input.get("file_path") or tool_input.get("notebook_path") or "") if "analysis" not in file_path.parts or file_path.suffix not in CODE_SUFFIXES: return 0 @@ -102,13 +105,13 @@ def main() -> int: "with MAIN passed in at submit", ) ) - if not hits: + if not hits or "paths" in lifted(payload): return 0 print(f"Refused: {file_path.name} would contain {', and '.join(what for what, _ in hits)}.", file=sys.stderr) for _, fix in hits: print(f" -> {fix}", file=sys.stderr) - print("See the analysis-workflow skill (task outputs).", file=sys.stderr) + print(f"See the analysis-workflow skill (task outputs). {how_to_lift('paths')}", file=sys.stderr) return 2 diff --git a/hooks/guard_worktree_pixi.py b/hooks/guard_worktree_pixi.py index b5b21dc..d0681d9 100644 --- a/hooks/guard_worktree_pixi.py +++ b/hooks/guard_worktree_pixi.py @@ -31,7 +31,9 @@ adopted, as_is, checkouts, + how_to_lift, is_root_of_worktree, + lifted, manifest_arg, nearest_manifest, pixi_calls, @@ -75,19 +77,20 @@ def main() -> int: if found and adopted(found[0]): main_manifest = (found[1] / "pixi.toml").resolve() on_main = any(_manifest(args, cwd) == main_manifest and not as_is(args) for args in calls) - if on_main and not blocked: + if not (on_main or blocked) or "pixi" in lifted(payload): + return 0 + if not blocked: print( "Refused: a `pixi` call on the main checkout's environment without `--as-is`, from a worktree.\n" "It would relock or install into main whenever main's manifest or lock is ahead of its environment.\n" " - to run something: python