analysis-workflow 0.13.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. analysis_workflow-0.13.0/.claude-plugin/plugin.json +19 -0
  2. analysis_workflow-0.13.0/.github/workflows/lint.yaml +20 -0
  3. analysis_workflow-0.13.0/.github/workflows/release.yaml +72 -0
  4. analysis_workflow-0.13.0/.github/workflows/test.yaml +23 -0
  5. analysis_workflow-0.13.0/.gitignore +9 -0
  6. analysis_workflow-0.13.0/.pre-commit-config.yaml +26 -0
  7. analysis_workflow-0.13.0/LICENSE +21 -0
  8. analysis_workflow-0.13.0/PKG-INFO +104 -0
  9. analysis_workflow-0.13.0/README.md +82 -0
  10. analysis_workflow-0.13.0/hooks/_repo.py +178 -0
  11. analysis_workflow-0.13.0/hooks/allow_exception.py +45 -0
  12. analysis_workflow-0.13.0/hooks/guard_shared_writes.py +85 -0
  13. analysis_workflow-0.13.0/hooks/guard_task_layout.py +181 -0
  14. analysis_workflow-0.13.0/hooks/guard_task_paths.py +119 -0
  15. analysis_workflow-0.13.0/hooks/guard_worktree_pixi.py +110 -0
  16. analysis_workflow-0.13.0/hooks/hooks.json +70 -0
  17. analysis_workflow-0.13.0/hooks/session_context.md +21 -0
  18. analysis_workflow-0.13.0/hooks/session_start.py +81 -0
  19. analysis_workflow-0.13.0/pyproject.toml +50 -0
  20. analysis_workflow-0.13.0/skills/allow/SKILL.md +12 -0
  21. analysis_workflow-0.13.0/skills/analysis-workflow/SKILL.md +106 -0
  22. analysis_workflow-0.13.0/skills/analysis-workflow/references/repos.md +41 -0
  23. analysis_workflow-0.13.0/skills/analysis-workflow/references/storage.md +23 -0
  24. analysis_workflow-0.13.0/skills/declare-inputs/SKILL.md +49 -0
  25. analysis_workflow-0.13.0/skills/trace-lineage/SKILL.md +44 -0
  26. analysis_workflow-0.13.0/src/analysis_workflow/__init__.py +22 -0
  27. analysis_workflow-0.13.0/src/analysis_workflow/cli.py +318 -0
  28. analysis_workflow-0.13.0/src/analysis_workflow/graph.py +242 -0
  29. analysis_workflow-0.13.0/src/analysis_workflow/paths.py +179 -0
  30. analysis_workflow-0.13.0/src/analysis_workflow/provenance.py +334 -0
  31. analysis_workflow-0.13.0/src/analysis_workflow/size.py +87 -0
  32. analysis_workflow-0.13.0/src/analysis_workflow/task_template/README.md +54 -0
  33. analysis_workflow-0.13.0/src/analysis_workflow/task_template/scripts/_common.py +14 -0
  34. analysis_workflow-0.13.0/src/analysis_workflow/trace.py +263 -0
  35. analysis_workflow-0.13.0/src/analysis_workflow/working.py +142 -0
  36. analysis_workflow-0.13.0/tests/conftest.py +47 -0
  37. analysis_workflow-0.13.0/tests/test_cli.py +169 -0
  38. analysis_workflow-0.13.0/tests/test_hooks.py +506 -0
  39. analysis_workflow-0.13.0/tests/test_paths.py +75 -0
  40. analysis_workflow-0.13.0/tests/test_plugin.py +14 -0
  41. analysis_workflow-0.13.0/tests/test_provenance.py +389 -0
  42. analysis_workflow-0.13.0/tests/test_size.py +70 -0
  43. analysis_workflow-0.13.0/tests/test_trace.py +367 -0
  44. analysis_workflow-0.13.0/tests/test_working.py +174 -0
  45. analysis_workflow-0.13.0/uv.lock +1192 -0
@@ -0,0 +1,19 @@
1
+ {
2
+ "name": "analysis-workflow",
3
+ "version": "0.13.0",
4
+ "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.",
5
+ "author": {
6
+ "name": "quadbio"
7
+ },
8
+ "homepage": "https://github.com/quadbio/analysis-workflow",
9
+ "license": "MIT",
10
+ "keywords": ["single-cell", "spatial-transcriptomics", "anndata", "zarr", "git-worktree", "pixi", "scverse"],
11
+ "userConfig": {
12
+ "deliverables": {
13
+ "type": "string",
14
+ "title": "Default deliverables",
15
+ "description": "What a task delivers unless you choose otherwise at its start, e.g. \"a figure\" or \"a figure and a report\". Blank: the agent asks.",
16
+ "default": "a figure"
17
+ }
18
+ }
19
+ }
@@ -0,0 +1,20 @@
1
+ name: Lint
2
+
3
+ on:
4
+ push:
5
+ branches: [main]
6
+ pull_request:
7
+
8
+ concurrency:
9
+ group: lint-${{ github.ref }}
10
+ cancel-in-progress: true
11
+
12
+ jobs:
13
+ pre-commit:
14
+ runs-on: ubuntu-latest
15
+ steps:
16
+ - uses: actions/checkout@v5
17
+ - uses: actions/setup-python@v6
18
+ with:
19
+ python-version: "3.12"
20
+ - uses: pre-commit/action@v3.0.1
@@ -0,0 +1,72 @@
1
+ name: Release
2
+
3
+ # A version in .claude-plugin/plugin.json without its tag v<version> is unreleased: publish it, then tag it.
4
+ on:
5
+ push:
6
+ branches: [main]
7
+
8
+ concurrency:
9
+ group: release
10
+ cancel-in-progress: false
11
+
12
+ # Use "trusted publishing", see https://docs.pypi.org/trusted-publishers/
13
+ permissions: {}
14
+
15
+ jobs:
16
+ check:
17
+ runs-on: ubuntu-latest
18
+ permissions:
19
+ contents: read
20
+ outputs:
21
+ version: ${{ steps.version.outputs.version }}
22
+ tagged: ${{ steps.version.outputs.tagged }}
23
+ steps:
24
+ - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
25
+ with:
26
+ persist-credentials: false
27
+ - id: version
28
+ run: |
29
+ version=$(jq -r .version .claude-plugin/plugin.json)
30
+ echo "version=$version" >> "$GITHUB_OUTPUT"
31
+ if git ls-remote --exit-code --tags origin "refs/tags/v$version" > /dev/null; then
32
+ echo "tagged=true" >> "$GITHUB_OUTPUT"
33
+ else
34
+ echo "tagged=false" >> "$GITHUB_OUTPUT"
35
+ fi
36
+
37
+ publish:
38
+ name: Upload release to PyPI
39
+ needs: check
40
+ if: needs.check.outputs.tagged == 'false'
41
+ runs-on: ubuntu-latest
42
+ environment:
43
+ name: pypi
44
+ url: https://pypi.org/p/analysis-workflow
45
+ permissions:
46
+ contents: read
47
+ id-token: write # IMPORTANT: this permission is mandatory for trusted publishing
48
+ steps:
49
+ - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
50
+ with:
51
+ filter: blob:none
52
+ fetch-depth: 0
53
+ persist-credentials: false
54
+ - name: Install uv
55
+ uses: astral-sh/setup-uv@11f9893b081a58869d3b5fccaea48c9e9e46f990 # v8.3.2
56
+ with:
57
+ enable-cache: false
58
+ - name: Build package
59
+ run: uv build
60
+ - name: Publish package distributions to PyPI
61
+ uses: pypa/gh-action-pypi-publish@7245906fb61fa33a13554f9d5fb856fe61758086 # v1.14.3: twine 7 reads metadata 2.5
62
+
63
+ tag:
64
+ needs: [check, publish]
65
+ runs-on: ubuntu-latest
66
+ permissions:
67
+ contents: write
68
+ steps:
69
+ - run: gh release create "v$VERSION" --repo "$GITHUB_REPOSITORY" --target "$GITHUB_SHA" --title "v$VERSION" --generate-notes
70
+ env:
71
+ GH_TOKEN: ${{ github.token }}
72
+ VERSION: ${{ needs.check.outputs.version }}
@@ -0,0 +1,23 @@
1
+ name: Test
2
+
3
+ on:
4
+ push:
5
+ branches: [main]
6
+ pull_request:
7
+
8
+ concurrency:
9
+ group: test-${{ github.ref }}
10
+ cancel-in-progress: true
11
+
12
+ jobs:
13
+ test:
14
+ runs-on: ubuntu-latest
15
+ strategy:
16
+ matrix:
17
+ python-version: ["3.12", "3.14"]
18
+ steps:
19
+ - uses: actions/checkout@v5
20
+ - uses: astral-sh/setup-uv@v6
21
+ with:
22
+ python-version: ${{ matrix.python-version }}
23
+ - run: uv run --locked --group dev pytest
@@ -0,0 +1,9 @@
1
+ .venv/
2
+ __pycache__/
3
+ *.pyc
4
+ .pytest_cache/
5
+ .ruff_cache/
6
+ dist/
7
+ .DS_Store
8
+ .claude/settings.local.json
9
+ .claude/worktrees/
@@ -0,0 +1,26 @@
1
+ exclude: ^uv\.lock$
2
+
3
+ repos:
4
+ - repo: https://github.com/astral-sh/ruff-pre-commit
5
+ rev: v0.15.19
6
+ hooks:
7
+ - id: ruff-check
8
+ args: [--fix, --exit-non-zero-on-fix]
9
+ - id: ruff-format
10
+
11
+ - repo: https://github.com/tox-dev/pyproject-fmt
12
+ rev: v2.25.0
13
+ hooks:
14
+ - id: pyproject-fmt
15
+
16
+ - repo: https://github.com/pre-commit/pre-commit-hooks
17
+ rev: v6.0.0
18
+ hooks:
19
+ - id: check-json
20
+ - id: check-yaml
21
+ - id: end-of-file-fixer
22
+ - id: mixed-line-ending
23
+ args: [--fix=lf]
24
+ - id: trailing-whitespace
25
+ - id: check-merge-conflict
26
+ - id: detect-private-key
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 quadbio
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,104 @@
1
+ Metadata-Version: 2.5
2
+ Name: analysis-workflow
3
+ Version: 0.13.0
4
+ Summary: Task paths, additive AnnData write-back and layout checks for agent-run analysis repos.
5
+ Project-URL: Source, https://github.com/quadbio/analysis-workflow
6
+ Author: quadbio
7
+ License-Expression: MIT
8
+ License-File: LICENSE
9
+ Classifier: Programming Language :: Python :: 3 :: Only
10
+ Classifier: Programming Language :: Python :: 3.12
11
+ Classifier: Programming Language :: Python :: 3.13
12
+ Classifier: Programming Language :: Python :: 3.14
13
+ Requires-Python: >=3.12
14
+ Requires-Dist: anndata>=0.12
15
+ Requires-Dist: numpy
16
+ Requires-Dist: pandas
17
+ Requires-Dist: pyyaml
18
+ Requires-Dist: scipy
19
+ Requires-Dist: typer
20
+ Requires-Dist: zarr>=3
21
+ Description-Content-Type: text/markdown
22
+
23
+ # analysis-workflow
24
+
25
+ A Claude Code plugin for computational-biology analysis repos where humans and coding agents work side by side.
26
+ Both follow the analysis template's `CONVENTIONS.md`: versioned task directories, output paths that survive a git
27
+ worktree being removed, and a shared AnnData zarr *working object* per dataset that grows by additive write-back
28
+ only. The plugin adds what only agents do: one task per session, git worktree and pull request.
29
+
30
+ | Part | What it does |
31
+ | --- | --- |
32
+ | `skills/analysis-workflow/` | The agent's side: task lifecycle in a worktree, sign-off, PRs, environments, setting up repos. Loaded on demand. |
33
+ | `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. |
34
+ | `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. |
35
+ | `src/analysis_workflow/` | The Python package and its `analysis-workflow` command: task paths, writes to shared stores and their records, tracing (as a tree, or as a graph of tasks drawn by [Graphviz](https://graphviz.org), a conda package of the analysis repo), layout checks; the task template. |
36
+
37
+ It assumes analysis repos made from [analysis_template](https://github.com/quadbio/analysis_template)
38
+ (pixi-managed) and code repos from the [scverse cookiecutter](https://github.com/scverse/cookiecutter-scverse)
39
+ (uv-managed). Nothing in it is specific to a dataset, an analysis or a compute environment.
40
+
41
+ ## Use
42
+
43
+ Start each analysis task as its own session, from the analysis repo's main checkout. Pull it first: the worktree
44
+ branches from `origin`'s default branch but runs on the main checkout's environment.
45
+
46
+ ```bash
47
+ claude --worktree <task>
48
+ ```
49
+
50
+ 1. The agent works on that worktree's branch, in a new task directory `analysis/<dataset>/<topic>/agent_<task>_vN/`;
51
+ a later answer to the same question gets the next version, in a new session. Earlier task directories are never
52
+ edited.
53
+ 2. It asks you which working object is current and agrees what the task delivers (by default your `deliverables`
54
+ setting), then works in scripts; outputs go to the task directory.
55
+ 3. Results reach shared storage only after you sign off, inside a `writes` block that records in the store which
56
+ task wrote them.
57
+ 4. It opens a PR whose body holds the details; the task README summarizes each PR. Once it is merged and its batch
58
+ jobs have finished, leave with `/exit` and remove the worktree.
59
+
60
+ A rule is broken only with your approval. When a guard refuses something you want done, the agent passes on the
61
+ command that lifts it for that session, `/analysis-workflow:allow <guard>`, which only you can run; the PR notes
62
+ the exception (the template's `CONVENTIONS.md`).
63
+
64
+ 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
65
+ it in a temporary checkout beside the main one; after its merge you pull and run `pixi install` there. With no
66
+ analysis repo yet, ask Claude to start an analysis project: the skill sets one up.
67
+
68
+ ## Install
69
+
70
+ **The plugin**, once per machine, from the [quadbio marketplace](https://github.com/quadbio/claude-plugins). The
71
+ skill is then available everywhere; the hooks and session-start rules act only in repos that enable the plugin in
72
+ their committed `.claude/settings.json`. Every repo made from
73
+ [analysis_template](https://github.com/quadbio/analysis_template) does, and depends on the PyPI package
74
+ `analysis-workflow` in its `pixi.toml`. To adopt an existing repo, ask Claude to adopt the
75
+ conventions.
76
+
77
+ **Settings**, saved with `/plugin configure analysis-workflow@quadbio`:
78
+
79
+ | Setting | Default | Meaning |
80
+ | --- | --- | --- |
81
+ | `deliverables` | `a figure` | What a task delivers unless you choose otherwise at its start; recorded in the task README. Blank: the agent asks. |
82
+
83
+ ## Develop
84
+
85
+ ```bash
86
+ uv sync --group dev
87
+ uv run pytest
88
+ uv run pre-commit run --all-files
89
+ claude plugin validate .
90
+ claude --plugin-dir . # try the skill and hooks from this checkout
91
+ ```
92
+
93
+ For live package edits in an analysis repo, depend on the checkout instead:
94
+ `analysis-workflow = { path = "../analysis-workflow", editable = true }`.
95
+
96
+ ## Release
97
+
98
+ Bump `version` in `.claude-plugin/plugin.json` and merge: the marketplace follows `main`, and users update when the
99
+ version changes. On that merge, `release.yaml` publishes the package to PyPI as `analysis-workflow`, then tags
100
+ `v<version>` and creates a GitHub Release.
101
+
102
+ ## License
103
+
104
+ MIT
@@ -0,0 +1,82 @@
1
+ # analysis-workflow
2
+
3
+ A Claude Code plugin for computational-biology analysis repos where humans and coding agents work side by side.
4
+ Both follow the analysis template's `CONVENTIONS.md`: versioned task directories, output paths that survive a git
5
+ worktree being removed, and a shared AnnData zarr *working object* per dataset that grows by additive write-back
6
+ only. The plugin adds what only agents do: one task per session, git worktree and pull request.
7
+
8
+ | Part | What it does |
9
+ | --- | --- |
10
+ | `skills/analysis-workflow/` | The agent's side: task lifecycle in a worktree, sign-off, PRs, environments, setting up repos. Loaded on demand. |
11
+ | `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. |
12
+ | `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. |
13
+ | `src/analysis_workflow/` | The Python package and its `analysis-workflow` command: task paths, writes to shared stores and their records, tracing (as a tree, or as a graph of tasks drawn by [Graphviz](https://graphviz.org), a conda package of the analysis repo), layout checks; the task template. |
14
+
15
+ It assumes analysis repos made from [analysis_template](https://github.com/quadbio/analysis_template)
16
+ (pixi-managed) and code repos from the [scverse cookiecutter](https://github.com/scverse/cookiecutter-scverse)
17
+ (uv-managed). Nothing in it is specific to a dataset, an analysis or a compute environment.
18
+
19
+ ## Use
20
+
21
+ Start each analysis task as its own session, from the analysis repo's main checkout. Pull it first: the worktree
22
+ branches from `origin`'s default branch but runs on the main checkout's environment.
23
+
24
+ ```bash
25
+ claude --worktree <task>
26
+ ```
27
+
28
+ 1. The agent works on that worktree's branch, in a new task directory `analysis/<dataset>/<topic>/agent_<task>_vN/`;
29
+ a later answer to the same question gets the next version, in a new session. Earlier task directories are never
30
+ edited.
31
+ 2. It asks you which working object is current and agrees what the task delivers (by default your `deliverables`
32
+ setting), then works in scripts; outputs go to the task directory.
33
+ 3. Results reach shared storage only after you sign off, inside a `writes` block that records in the store which
34
+ task wrote them.
35
+ 4. It opens a PR whose body holds the details; the task README summarizes each PR. Once it is merged and its batch
36
+ jobs have finished, leave with `/exit` and remove the worktree.
37
+
38
+ A rule is broken only with your approval. When a guard refuses something you want done, the agent passes on the
39
+ command that lifts it for that session, `/analysis-workflow:allow <guard>`, which only you can run; the PR notes
40
+ the exception (the template's `CONVENTIONS.md`).
41
+
42
+ 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
43
+ it in a temporary checkout beside the main one; after its merge you pull and run `pixi install` there. With no
44
+ analysis repo yet, ask Claude to start an analysis project: the skill sets one up.
45
+
46
+ ## Install
47
+
48
+ **The plugin**, once per machine, from the [quadbio marketplace](https://github.com/quadbio/claude-plugins). The
49
+ skill is then available everywhere; the hooks and session-start rules act only in repos that enable the plugin in
50
+ their committed `.claude/settings.json`. Every repo made from
51
+ [analysis_template](https://github.com/quadbio/analysis_template) does, and depends on the PyPI package
52
+ `analysis-workflow` in its `pixi.toml`. To adopt an existing repo, ask Claude to adopt the
53
+ conventions.
54
+
55
+ **Settings**, saved with `/plugin configure analysis-workflow@quadbio`:
56
+
57
+ | Setting | Default | Meaning |
58
+ | --- | --- | --- |
59
+ | `deliverables` | `a figure` | What a task delivers unless you choose otherwise at its start; recorded in the task README. Blank: the agent asks. |
60
+
61
+ ## Develop
62
+
63
+ ```bash
64
+ uv sync --group dev
65
+ uv run pytest
66
+ uv run pre-commit run --all-files
67
+ claude plugin validate .
68
+ claude --plugin-dir . # try the skill and hooks from this checkout
69
+ ```
70
+
71
+ For live package edits in an analysis repo, depend on the checkout instead:
72
+ `analysis-workflow = { path = "../analysis-workflow", editable = true }`.
73
+
74
+ ## Release
75
+
76
+ Bump `version` in `.claude-plugin/plugin.json` and merge: the marketplace follows `main`, and users update when the
77
+ version changes. On that merge, `release.yaml` publishes the package to PyPI as `analysis-workflow`, then tags
78
+ `v<version>` and creates a GitHub Release.
79
+
80
+ ## License
81
+
82
+ MIT
@@ -0,0 +1,178 @@
1
+ """The repository a hook acts on, and whether it has adopted the plugin.
2
+
3
+ The hooks act only in a checkout whose committed `.claude/settings.json` enables `analysis-workflow`, so the
4
+ plugin can be enabled for a user (which the skill's repo set-up needs) without touching their other repos.
5
+ Standard library only: it runs on whatever `python3` is on PATH.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ import os
12
+ import shlex
13
+ import subprocess
14
+ from pathlib import Path
15
+
16
+ PLUGIN = "analysis-workflow"
17
+
18
+ #: The guards the human can lift for a session, by the name they type after `/analysis-workflow:allow`.
19
+ GUARDS = ("layout", "paths", "pixi", "shared-writes")
20
+ ALLOW = f"{PLUGIN}:allow"
21
+
22
+
23
+ def marker(payload: dict) -> Path | None:
24
+ """The file listing the guards lifted for the payload's session, one per line; None if it has no home."""
25
+ data, session = os.environ.get("CLAUDE_PLUGIN_DATA"), Path(str(payload.get("session_id") or "")).name
26
+ return Path(data) / "exceptions" / session if data and session else None
27
+
28
+
29
+ def lifted(payload: dict) -> list[str]:
30
+ """The guards the human lifted for the payload's session, subagents included; `allow_exception.py` records them."""
31
+ try:
32
+ return marker(payload).read_text().split()
33
+ except (OSError, AttributeError):
34
+ return []
35
+
36
+
37
+ def how_to_lift(guard: str) -> str:
38
+ """The last line of a guard's refusal."""
39
+ return f"Only the human can lift this guard, for this session, by typing `/{ALLOW} {guard}`."
40
+
41
+
42
+ #: `pixi` subcommands that change the workspace environment, or use it and so install it first if it is missing.
43
+ PIXI_ENV_COMMANDS = frozenset(
44
+ {"install", "add", "lock", "upgrade", "update", "reinstall", "remove", "run", "shell", "shell-hook"}
45
+ )
46
+ #: The first of these after `pixi` is the command, whatever global options precede it.
47
+ PIXI_SUBCOMMANDS = PIXI_ENV_COMMANDS | {
48
+ "auth", "build", "clean", "completion", "config", "exec", "global", "import", "info", "init", "list",
49
+ "search", "self-update", "task", "tree", "upload", "workspace",
50
+ } # fmt: skip
51
+
52
+
53
+ def checkouts(directory: Path) -> tuple[Path, Path] | None:
54
+ """The checkout containing ``directory`` and the repository's main checkout; None outside git."""
55
+ while not directory.is_dir():
56
+ directory = directory.parent
57
+ try:
58
+ toplevel, common_dir = subprocess.run(
59
+ ["git", "rev-parse", "--path-format=absolute", "--show-toplevel", "--git-common-dir"],
60
+ cwd=directory,
61
+ capture_output=True,
62
+ text=True,
63
+ timeout=5,
64
+ check=True,
65
+ ).stdout.splitlines()
66
+ except (subprocess.SubprocessError, OSError, ValueError):
67
+ return None
68
+ return Path(toplevel), Path(common_dir).parent
69
+
70
+
71
+ def adopted(checkout: Path) -> bool:
72
+ """Whether the checkout's `.claude/settings.json` enables this plugin, from any marketplace."""
73
+ try:
74
+ enabled = json.loads((checkout / ".claude" / "settings.json").read_text()).get("enabledPlugins", {})
75
+ return any(key.split("@")[0] == PLUGIN and on is True for key, on in enabled.items())
76
+ except (OSError, ValueError, AttributeError):
77
+ return False
78
+
79
+
80
+ def nearest_manifest(directory: Path) -> Path:
81
+ """The `pixi.toml` pixi itself finds from ``directory``: the nearest at or above it."""
82
+ return next(
83
+ (d / "pixi.toml" for d in (directory, *directory.parents) if (d / "pixi.toml").exists()),
84
+ directory / "pixi.toml",
85
+ )
86
+
87
+
88
+ def is_root_of_worktree(manifest: Path) -> bool:
89
+ """Whether ``manifest`` is the root workspace of a worktree of an adopted repo.
90
+
91
+ Its editable self-dependency (`path = "."`) would rebase the repo's package, and every path it
92
+ resolves, into the worktree. A task-local manifest is its own workspace.
93
+ """
94
+ if ".claude/worktrees" not in str(manifest):
95
+ return False
96
+ if manifest.exists() and 'path = "."' not in manifest.read_text(errors="ignore"):
97
+ return False
98
+ found = checkouts(manifest.parent)
99
+ return found is not None and adopted(found[0])
100
+
101
+
102
+ def _is_separator(tok: str) -> bool:
103
+ """A token made only of command separators (`;`, `&&`, `|`, newlines, parentheses)."""
104
+ return bool(tok) and set(tok) <= set(";&|()\n")
105
+
106
+
107
+ def shell_calls(command: str, names: frozenset[str], comments: bool = False) -> list[tuple[str, list[str]]] | None:
108
+ """Name and argument list of each call in ``command`` to a program in ``names``; None if unparsable.
109
+
110
+ With ``comments``, an unquoted `#` starts a comment to the end of its line, as in a script. Quotes are
111
+ honoured either way, so quoted text (a PR body, an echoed message) is never read as a call.
112
+ """
113
+ tokens = []
114
+ for text in command.splitlines(keepends=True) if comments else [command]:
115
+ lexer = shlex.shlex(text, posix=True, punctuation_chars="();<>|&\n")
116
+ lexer.whitespace = " \t\r" # newlines separate commands, so keep them as tokens
117
+ lexer.commenters = "#" if comments else "" # one line at a time: a comment swallows its newline
118
+ lexer.whitespace_split = True
119
+ try:
120
+ tokens += [*lexer, "\n"]
121
+ except ValueError:
122
+ return None
123
+ calls = []
124
+ for i, tok in enumerate(tokens):
125
+ if Path(tok).name not in names:
126
+ continue
127
+ args = []
128
+ for t in tokens[i + 1 :]:
129
+ if _is_separator(t):
130
+ break
131
+ args.append(t)
132
+ calls.append((Path(tok).name, args))
133
+ return calls
134
+
135
+
136
+ def pixi_calls(command: str, comments: bool = False) -> list[list[str]] | None:
137
+ """Argument lists of the `pixi` calls in ``command`` that change or use an environment; None if unparsable."""
138
+ calls = shell_calls(command, frozenset({"pixi"}), comments)
139
+ if calls is None:
140
+ return None
141
+ return [args for _, args in calls if next((a for a in args if a in PIXI_SUBCOMMANDS), None) in PIXI_ENV_COMMANDS]
142
+
143
+
144
+ #: Options of `pixi run`, `shell` and `shell-hook` that take a value (from their `--help`).
145
+ PIXI_VALUE_OPTIONS = frozenset(
146
+ {"-e", "--environment", "-p", "--platform", "-m", "--manifest-path", "-w", "--workspace", "-s", "--script",
147
+ "--shell", "--config-file", "--auth-file", "--concurrent-downloads", "--concurrent-solves", "--pinning-strategy",
148
+ "--pypi-keyring-provider", "--tls-root-certs", "--color", "--change-ps1"}
149
+ ) # fmt: skip
150
+
151
+
152
+ def pixi_options(args: list[str]) -> tuple[str | None, list[str]]:
153
+ """A `pixi` call's subcommand and its own options. In `pixi run`, arguments after the task are the task's."""
154
+ command = next((a for a in args if a in PIXI_SUBCOMMANDS), None)
155
+ options, value_next = [], False
156
+ for a in args[args.index(command) + 1 :] if command else args:
157
+ if command == "run" and not value_next and not a.startswith("-"):
158
+ break
159
+ options.append(a)
160
+ value_next = a in PIXI_VALUE_OPTIONS
161
+ return command, options
162
+
163
+
164
+ def manifest_arg(args: list[str]) -> str | None:
165
+ """The `--manifest-path` a pixi call passes, if any."""
166
+ _, options = pixi_options(args)
167
+ for i, a in enumerate(options):
168
+ if a in ("--manifest-path", "-m"):
169
+ return options[i + 1] if i + 1 < len(options) else None
170
+ if a.startswith("--manifest-path="):
171
+ return a.split("=", 1)[1]
172
+ return None
173
+
174
+
175
+ def as_is(args: list[str]) -> bool:
176
+ """Whether a `pixi` call uses an environment as it stands: `run`, `shell` or `shell-hook` with `--as-is`."""
177
+ command, options = pixi_options(args)
178
+ return command in {"run", "shell", "shell-hook"} and "--as-is" in options
@@ -0,0 +1,45 @@
1
+ #!/usr/bin/env python3
2
+ """Lift one guard for this session when the human types `/analysis-workflow:allow <guard>`.
3
+
4
+ UserPromptExpansion fires for a command the human types, and not for a skill the model loads, a scheduled prompt
5
+ or a message from a subagent or another session: only the human lifts a guard. The guard is recorded in the
6
+ session's marker (`_repo.py`), which the guards read and which outlives resume and compaction.
7
+
8
+ It acts only in a repo that has adopted the plugin. An unknown guard blocks the command and names the guards to
9
+ the human; otherwise stdout tells the agent what was lifted.
10
+ Standard library only: it runs on whatever `python3` is on PATH.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import json
16
+ import sys
17
+ from pathlib import Path
18
+
19
+ from _repo import ALLOW, GUARDS, adopted, checkouts, lifted, marker
20
+
21
+
22
+ def main() -> int:
23
+ """Read the hook payload from stdin; return the exit code."""
24
+ payload = json.load(sys.stdin)
25
+ if payload.get("command_name") != ALLOW:
26
+ return 0
27
+ found = checkouts(Path(payload.get("cwd") or ".").resolve())
28
+ if not (found and adopted(found[0])):
29
+ return 0
30
+ guard, path = str(payload.get("command_args") or "").strip(), marker(payload)
31
+ if guard not in GUARDS or path is None:
32
+ why = f"no guard named `{guard}`; one of {', '.join(GUARDS)}." if path else "nowhere to record it."
33
+ print(json.dumps({"decision": "block", "reason": f"analysis-workflow: {why}"}))
34
+ return 0
35
+ path.parent.mkdir(parents=True, exist_ok=True)
36
+ path.write_text("".join(f"{g}\n" for g in dict.fromkeys([*lifted(payload), guard])))
37
+ print(
38
+ f"The human lifted the `{guard}` guard for this session. What it now lets through is an exception to "
39
+ "these conventions: note it as the repo's `CONVENTIONS.md` says."
40
+ )
41
+ return 0
42
+
43
+
44
+ if __name__ == "__main__":
45
+ sys.exit(main())