Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .claude-plugin/plugin.json
Original file line number Diff line number Diff line change
@@ -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"
Expand Down
6 changes: 5 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -35,6 +35,10 @@ claude --worktree <task>
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 <guard>`, 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.
Expand Down
25 changes: 25 additions & 0 deletions hooks/_repo.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"}
Expand Down
45 changes: 45 additions & 0 deletions hooks/allow_exception.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
#!/usr/bin/env python3
"""Lift one guard for this session when the human types `/analysis-workflow:allow <guard>`.
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())
6 changes: 4 additions & 2 deletions hooks/guard_shared_writes.py
Original file line number Diff line number Diff line change
Expand Up @@ -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`
Expand Down Expand Up @@ -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/<dataset>/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
Expand Down
6 changes: 3 additions & 3 deletions hooks/guard_task_layout.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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


Expand Down
9 changes: 6 additions & 3 deletions hooks/guard_task_paths.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,9 @@
adopted,
as_is,
checkouts,
how_to_lift,
is_root_of_worktree,
lifted,
manifest_arg,
nearest_manifest,
pixi_calls,
Expand Down Expand Up @@ -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
Expand All @@ -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


Expand Down
14 changes: 9 additions & 5 deletions hooks/guard_worktree_pixi.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,9 @@
adopted,
as_is,
checkouts,
how_to_lift,
is_root_of_worktree,
lifted,
manifest_arg,
nearest_manifest,
pixi_calls,
Expand Down Expand Up @@ -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 <script> (this session runs on the main checkout's environment),\n"
" or pixi run --manifest-path <main checkout>/pixi.toml --as-is python <script>\n"
" - to change the environment: lock and install it in a temporary checkout beside the main one\n"
" (skill, Environments); installing the MAIN checkout's environment is the human's.",
" (skill, Environments); installing the MAIN checkout's environment is the human's.\n"
f"{how_to_lift('pixi')}",
file=sys.stderr,
)
return 2
if not blocked:
return 0

print(
"Refused: a `pixi` command that builds or changes an environment on a worktree's root workspace.\n"
Expand All @@ -96,7 +99,8 @@ def main() -> int:
" - to run something: python <script> (this session runs on the main checkout's environment),\n"
" or pixi run --manifest-path <main checkout>/pixi.toml --as-is python <script>\n"
" - to change the environment: lock and install it in a temporary checkout beside the main one\n"
" (skill, Environments); installing the MAIN checkout's environment is the human's.",
" (skill, Environments); installing the MAIN checkout's environment is the human's.\n"
f"{how_to_lift('pixi')}",
file=sys.stderr,
)
return 2
Expand Down
13 changes: 12 additions & 1 deletion hooks/hooks.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"description": "analysis-workflow, in repos that enable it: always-on core rules, plus guards that stop a rule being broken by accident.",
"description": "analysis-workflow, in repos that enable it: always-on core rules, plus guards that stop a rule being broken by accident and that only the human lifts.",
"hooks": {
"SessionStart": [
{
Expand All @@ -12,6 +12,17 @@
]
}
],
"UserPromptExpansion": [
{
"hooks": [
{
"type": "command",
"command": "python3 \"${CLAUDE_PLUGIN_ROOT}/hooks/allow_exception.py\"",
"timeout": 10
}
]
}
],
"PreToolUse": [
{
"matcher": "Bash",
Expand Down
3 changes: 3 additions & 0 deletions hooks/session_context.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,3 +16,6 @@ analysis code, outputs or data. Always:
5. A worktree, and every batch job submitted from it, runs on the main checkout's environment; only the human
installs it, in the main checkout. The line below says whether it is active in every Bash command. Batch jobs
run `pixi run --manifest-path "$MAIN/pixi.toml" --as-is ...`.

A rule of these conventions is broken only with the human's explicit approval, and the exception is noted as the
repo's `CONVENTIONS.md` says. Only the human lifts a guard hook: pass on the command its refusal names.
7 changes: 5 additions & 2 deletions hooks/session_start.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
import sys
from pathlib import Path

from _repo import adopted, checkouts
from _repo import adopted, checkouts, lifted

BEGIN, END = "# analysis-workflow: main environment", "# analysis-workflow: end"

Expand Down Expand Up @@ -56,10 +56,13 @@ def write_block(env_file: Path, variables: dict[str, str]) -> None:

def main() -> int:
"""Read the hook payload from stdin; return the exit code."""
found = checkouts(Path(json.load(sys.stdin).get("cwd") or ".").resolve())
payload = json.load(sys.stdin)
found = checkouts(Path(payload.get("cwd") or ".").resolve())
if not (found and adopted(found[0])):
return 0
print((Path(__file__).parent / "session_context.md").read_text(), end="")
if guards := lifted(payload):
print(f"\nLifted by the human for this session: the guard(s) {', '.join(guards)}.")
toplevel, main_checkout = found
env_file = os.environ.get("CLAUDE_ENV_FILE")
variables = activation(toplevel, main_checkout) if env_file and (main_checkout / "pixi.toml").exists() else {}
Expand Down
12 changes: 12 additions & 0 deletions skills/allow/SKILL.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
---
name: allow
description: >-
Lift one guard hook of the analysis-workflow conventions for this session. Only the human runs it, by typing
`/analysis-workflow:allow <guard>` after a guard refused something they want done.
disable-model-invocation: true
argument-hint: <guard>
---

A guard is lifted only when a hook's message in this turn says so, which it does when the human typed this command
in a repo that follows these conventions. Without that message nothing changed: the guards refuse as before, and
only the human can lift one.
Loading
Loading