From 3008d78f19144d943034ac0b34c9bc0728ee2048 Mon Sep 17 00:00:00 2001 From: Marius1311 Date: Wed, 18 Nov 2026 17:43:30 +0100 Subject: [PATCH] `trace --format dot|pdf`: the tasks an artifact rests on, as a graph drawn by Graphviz; release 0.12.0 One node per task: what it produced on this path, and what it consumed that no task made, by where that lives. One arrow per pair of tasks. Mermaid goes: one graph format. Co-Authored-By: Claude Fable 5.2 --- .claude-plugin/plugin.json | 2 +- README.md | 2 +- skills/trace-lineage/SKILL.md | 7 +- src/analysis_workflow/cli.py | 25 +++- src/analysis_workflow/graph.py | 242 +++++++++++++++++++++++++++++++++ src/analysis_workflow/paths.py | 8 ++ src/analysis_workflow/trace.py | 11 -- tests/test_trace.py | 88 +++++++++++- 8 files changed, 361 insertions(+), 24 deletions(-) create mode 100644 src/analysis_workflow/graph.py diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json index 477a22e..bd0325f 100644 --- a/.claude-plugin/plugin.json +++ b/.claude-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "analysis-workflow", - "version": "0.11.0", + "version": "0.12.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 87de735..3944dfd 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,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, 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. | +| `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. | It assumes analysis repos made from [analysis_template](https://github.com/quadbio/analysis_template) (pixi-managed) and code repos from the [scverse cookiecutter](https://github.com/scverse/cookiecutter-scverse) diff --git a/skills/trace-lineage/SKILL.md b/skills/trace-lineage/SKILL.md index f47d40b..c9f0a5b 100644 --- a/skills/trace-lineage/SKILL.md +++ b/skills/trace-lineage/SKILL.md @@ -19,10 +19,11 @@ One artifact per report: a key in a store, or a file. If it names tasks without declared inputs, say which, offer to run the `declare-inputs` skill on them, and stop: a trace is only as complete as the declarations it follows. -2. `--format mermaid` gives the graph: artifacts as nodes, each edge labelled with the task that made its target. - `--format tasks` lists the task directories on the path. +2. `--format pdf --output ` draws the graph: one node per task, with what it produced on this path and what + it consumed that no task made. Save it in the task's `figures/` when the report belongs to a task, else beside + the report. `--format tasks` lists the task directories on the path. 3. Read the README of each task on the path for its author, its date and its opening sentence. -4. Write the report: the graph in a `mermaid` block, then the summary, in exactly this form. +4. Write the report: the path of the graph, then the summary, in exactly this form. ```markdown ## in diff --git a/src/analysis_workflow/cli.py b/src/analysis_workflow/cli.py index 7bc4f94..cc1c191 100644 --- a/src/analysis_workflow/cli.py +++ b/src/analysis_workflow/cli.py @@ -9,6 +9,7 @@ import typer +from analysis_workflow.graph import dot, render from analysis_workflow.paths import ( ANALYSIS_DIR, LANES, @@ -248,7 +249,12 @@ def inputs( def trace_command( artifact: Path = typer.Argument(..., help="A store in shared storage, or a file such as one in a task's outputs/."), key: str | None = typer.Argument(None, help="The key in the store: obs/leiden, X, tables/table/obs/leiden."), - output: str = typer.Option("tree", "--format", help="tree, mermaid, json or tasks."), + form: str = typer.Option( + "tree", "--format", help="tree, json or tasks; dot or pdf for a graph of the tasks, drawn by Graphviz." + ), + output: Path | None = typer.Option( + None, "--output", "-o", help="Where `--format pdf` writes the graph; a .svg or .png suffix gives that type." + ), ) -> None: """Trace one artifact back through the tasks that made it.""" try: @@ -263,11 +269,20 @@ def trace_command( raise typer.Exit(1) formats = { "tree": found.as_tree, - "mermaid": found.as_mermaid, "json": found.as_json, "tasks": lambda: "\n".join(found.tasks()), + "dot": lambda: dot(found, Path.cwd()), } - if output not in formats: - typer.echo(f"Error: --format is one of {', '.join(formats)}.", err=True) + if form not in (*formats, "pdf"): + typer.echo(f"Error: --format is one of {', '.join(formats)}, pdf.", err=True) raise typer.Exit(1) - typer.echo(formats[output]()) + try: + if form != "pdf": + typer.echo(formats[form]()) + elif output is None: + raise ValueError("`--format pdf` needs `--output `.") + else: + typer.echo(f"wrote {render(dot(found, Path.cwd()), output)}") + except (ValueError, RuntimeError) as err: + typer.echo(f"Error: {err}", err=True) + raise typer.Exit(1) from err diff --git a/src/analysis_workflow/graph.py b/src/analysis_workflow/graph.py new file mode 100644 index 0000000..9160176 --- /dev/null +++ b/src/analysis_workflow/graph.py @@ -0,0 +1,242 @@ +"""A trace drawn as a graph of tasks, as DOT text for Graphviz. + +One small node per task, in three bands. The bar names the task, its author and date. The shaded band is what +the task consumed that no task made, so the trace ends there: one row per place it lives in, a coloured bar saying +which place (source data in this repo, or one colour per place outside it, the same in every figure of a repo), +then the first few items. The white band is what the task produced on this path. One arrow runs from a task to +each task that consumed what it produced. Above the graph are a title and a small legend of the bars. + +Graphviz places the nodes and routes the arrows, so the picture stays compact as tasks are added. Which files and +keys exactly is what the trace's tree lists. +""" + +import datetime +import shutil +import subprocess +from collections import defaultdict +from html import escape +from pathlib import Path + +from analysis_workflow.paths import _checkouts_of, task_field +from analysis_workflow.trace import Trace, declared, task_dirs + +#: Hues of a palette checked for colour-vision deficiencies: what a task produced; source data in this repo; +#: then, in this order, the places outside the repo sorted by name. A seventh place outside gets the neutral, +#: told apart by its name in the legend. +PRODUCED, HERE = "produced", "this repo" +PRODUCED_COLOUR, HERE_COLOUR = "#2a78d6", "#1baf7a" +OUTSIDE = ("#eb6834", "#eda100", "#e87ba4", "#6250d6", "#e34948", "#008300") +INK, SECONDARY, MUTED, BAND, SURFACE = "#0b0b0b", "#52514e", "#898781", "#efeee9", "#fcfcfb" +FONT = "Helvetica" +#: How many items a place names before counting the rest. +SHOWN = 3 +#: Point sizes: the title, a task's name, what it produced, the small print (what it consumed, author and date, +#: the legend), and the blank line above and below the legend. +TITLE, NAME, BODY, SMALL, GAP = 8, 7, 6, 5, 3 +#: Characters per line that give a node's two bands about the same width; and those of the title and legend, +#: about as wide as a node. +WRAP = {BODY: 54, SMALL: 64} +HEAD = 80 +#: The task that is not in this checkout: a branch that is not merged, or a task that was removed. +ELSEWHERE = "task not in this checkout" + + +def _origin(path: str) -> tuple[str, str]: + """Where a path that no task made lives, HERE or the name of a place outside the repo, and a short name. + + In the repo, the name is the folder under `data//` and the last two parts of the path; outside, its + last part, or its last two under the home directory. + """ + p, home = Path(path).expanduser(), Path.home() + if not p.is_absolute(): + parts = p.parts[2:] if p.parts[0] == "data" and len(p.parts) > 3 else p.parts + return HERE, "/".join(parts) if len(parts) <= 3 else f"{parts[0]}/…/{'/'.join(parts[-2:])}" + for parent in p.parents: + if (parent / ".git").exists() and not home.is_relative_to(parent): # a home directory under version control + return parent.name, p.name + return ("home directory", "/".join(p.parts[-2:])) if p.is_relative_to(home) else ("outside any repo", str(p)) + + +def _colours(roots: list[Path]) -> dict[str, str]: + """The colour of each place source data comes from, over all tasks of the repo: the same in every figure.""" + places = set() + for root in roots: + for task in task_dirs(root): + places |= {_origin(str(entry["path"]))[0] for entry in declared(task) or []} + places.discard(HERE) + outside = {place: OUTSIDE[i] if i < len(OUTSIDE) else SECONDARY for i, place in enumerate(sorted(places))} + return {HERE: HERE_COLOUR, **outside} + + +def _summary(found: Trace) -> tuple[dict[str, dict[str, list[str]]], set[tuple[str, str]]]: + """Per task on the path the names of what it produced and of what it consumed, by where that lives. + + Also which task consumed which task's work. The artifact asked about is marked by a leading ``▶``. + """ + tasks = defaultdict(lambda: defaultdict(list)) + for node, fields in found.nodes.items(): + if task := fields.get("task"): + name = Path(fields["store"]).name if "store" in fields else Path(node).name + if "store" in fields: + name += f": {fields['keys'][0]}" if len(fields["keys"]) == 1 else f" ({len(fields['keys'])} keys)" + tasks[task][PRODUCED].insert(0, "▶ " + name) if node == found.target else tasks[task][PRODUCED].append(name) + edges, keys = set(), defaultdict(lambda: defaultdict(set)) + for edge in found.edges: + source = found.nodes[edge["source"]] + if maker := source.get("task"): + if maker != edge["task"]: + edges.add((maker, edge["task"])) + continue + path, _, key = edge["source"].partition("#") + place, name = _origin(path.partition("@")[0]) # a store's write-back is named `@` + status = ELSEWHERE if source["status"].startswith(ELSEWHERE) else source["status"] + name += "" if status == "source" else f" ({status})" + if name not in tasks[edge["task"]][place]: + tasks[edge["task"]][place].append(name) + keys[edge["task"]][(place, name)] |= set(source.get("keys") or ([key] if key else [])) + for task, counted in keys.items(): # a store consumed by key shows how many + for (place, name), found_keys in counted.items(): + if found_keys: + tasks[task][place][tasks[task][place].index(name)] = f"{name} ({len(found_keys)} keys)" + return tasks, edges + + +def _listed(names: list[str], size: float) -> list[str]: + """The first names of a list, " · " between them, in lines of WRAP[size] characters; the rest counted.""" + shown, more = names[:SHOWN], len(names) - SHOWN + lines, line, used = [], "", 0 + for i, name in enumerate(shown): + text = name + (" · " if i < len(shown) - 1 else f" +{more}" if more > 0 else "") + if used and used + len(text) > WRAP[size]: + lines.append(line) + line, used = "", 0 + # the artifact asked about is the one thing set in bold + line += f"{escape(text)}" if name.startswith("▶") else escape(text) + used += len(text) + return [*lines, line] + + +def _rows(entries: list[tuple[str, list[str]]], size: float, ink: str) -> str: + """Entries of (bar colour, lines of text): a coloured bar down the left of each entry's lines.""" + text = "".join( + f'▌{line}
' for colour, lines in entries for line in lines + ) + return f'{text}' + + +def _node(task: str, header: str, about: dict[str, list[str]], colour: dict[str, str], note: str) -> str: + """A task's node as a Graphviz HTML-like label: the bar, what was consumed (shaded), what was produced.""" + bar = ( + f'{escape(Path(task).name)}' + f'   {escape(header)}' + ) + consumed = [(colour[place], _listed(about[place], SMALL)) for place in colour if about.get(place)] + if note: + band = f'{note}' + else: + band = _rows(consumed, SMALL, SECONDARY) if consumed else "" + bands = f'{bar}' + if band: + bands += f'{band}' + produced = _rows([(PRODUCED_COLOUR, _listed(about[PRODUCED], BODY))], BODY, INK) + bands += f'{produced}' + return ( + f'"{task}" [label=<' + f"{bands}
>];" + ) + + +def _legend(used: list[str], colour: dict[str, str]) -> str: + """The legend under the title: lines of small grey text, each coloured bar followed by what it marks. + + No line is longer than HEAD characters, with a little space above and below. + """ + + def bar(shade: str, text: str) -> str: + return f'▌{escape(text)}' + + lines = [f"{bar(PRODUCED_COLOUR, 'produced by the task, consumed below')}   ▶ the artifact asked about"] + if used: + lines.append("consumed by the task, not further traceable; by where it lives:") + line, length = "", 0 + for place in used: + if length and length + len(place) + 3 > HEAD: + lines.append(line) + line, length = "", 0 + line, length = line + bar(colour[place], place) + "  ", length + len(place) + 3 + lines.append(line) + gap = f'
' + text = "".join(f'{line}
' for line in lines) + return f'{gap}{text}{gap}' + + +def dot(found: Trace, start: str | Path = ".", *, today: datetime.date | None = None) -> str: + """The trace ``found`` as DOT text: the tasks its artifact rests on, back to the data no task made. + + Parameters + ---------- + start + Any path in the checkout the trace was run from; its tasks' READMEs give the authors and dates. + today + The date in the title; by default, today's. + + Raises + ------ + ValueError + If no task made the artifact: there is nothing to draw. + """ + target = found.nodes[found.target] + if target.get("task") is None: + raise ValueError(f"No task made {target['label']} ({target['status']}): there is nothing to draw.") + roots = list(dict.fromkeys(_checkouts_of(start))) + about, edges = _summary(found) + colour, consumers = _colours(roots), {consumer for _, consumer in edges} + used = [place for place in colour if any(place in lists for lists in about.values())] + + def header(task: str) -> tuple[str, str]: + """A task's author and date, from its README in the first checkout that has the task.""" + where = next((root / task for root in roots if (root / task / "README.md").exists()), roots[-1] / task) + return task_field(where, "Author") or "", task_field(where, "Date") or "" + + name = ( + Path(target["store"]).name + ": " + ", ".join(target["keys"]) if "store" in target else Path(found.target).name + ) + when = escape(f"on {today or datetime.date.today()} in {roots[-1].name}") + # a long artifact name takes the title line to itself + joint = '
' if len(name) + len(when) > HEAD else "  " + lines = [ + "digraph trace {", + f' graph [rankdir=TB, bgcolor="{SURFACE}", pad=0.06, nodesep=0.12, ranksep=0.16, fontname="{FONT}", ' + "labelloc=t, labeljust=l,", + f' label=<Tracing {escape(name)}' + f'{joint}{when}
' + f"{_legend(used, colour)}>];", + f' node [shape=plain, fontname="{FONT}"];', + f' edge [penwidth=0.7, arrowsize=0.45, color="{SECONDARY}"];', + ] + for task in sorted(about, key=lambda t: (header(t)[1], t)): # the oldest task first + sourced = any(place != PRODUCED for place in about[task]) + missing = "inputs not declared" if task in found.undeclared else "no inputs declared" + note = missing if task in found.undeclared or not (sourced or task in consumers) else "" + lines.append(" " + _node(task, " · ".join(filter(None, header(task))), about[task], colour, note)) + lines += [f' "{maker}" -> "{consumer}";' for maker, consumer in sorted(edges)] + return "\n".join([*lines, "}"]) + "\n" + + +def render(source: str, output: str | Path) -> Path: + """Draw DOT text ``source`` into ``output`` with Graphviz; the suffix picks the file type (.pdf, .svg, .png). + + Raises + ------ + RuntimeError + If Graphviz's ``dot`` is not on PATH. + """ + output = Path(output) + if shutil.which("dot") is None: + raise RuntimeError( + "Graphviz's `dot` is not on PATH. It is a conda package: in a pixi project, `pixi add graphviz`." + ) + subprocess.run( + ["dot", f"-T{output.suffix.lstrip('.') or 'pdf'}", "-o", str(output)], input=source, text=True, check=True + ) + return output diff --git a/src/analysis_workflow/paths.py b/src/analysis_workflow/paths.py index e9ca1fd..5cd97dc 100644 --- a/src/analysis_workflow/paths.py +++ b/src/analysis_workflow/paths.py @@ -140,3 +140,11 @@ def task_id(task: str | Path) -> str | None: readme = Path(task) / "README.md" found = ID_LINE.search(readme.read_text()) if readme.exists() else None return found and found[1] + + +def task_field(task: str | Path, field: str) -> str | None: + """What the header of the task directory's README says under ``field``, ``Author`` or ``Date``; None if absent.""" + readme = Path(task) / "README.md" + line = re.compile(rf"^\*\*{re.escape(field)}:\*\*[ \t]*(.+?)[ \t]*$", re.MULTILINE) + found = line.search(readme.read_text()) if readme.exists() else None + return found and found[1] diff --git a/src/analysis_workflow/trace.py b/src/analysis_workflow/trace.py index 30fddb5..9fbfe44 100644 --- a/src/analysis_workflow/trace.py +++ b/src/analysis_workflow/trace.py @@ -101,17 +101,6 @@ def walk(node_id: str, depth: int) -> None: walk(self.target, 0) return "\n".join(lines) - def as_mermaid(self) -> str: - """A flowchart: artifacts as nodes, each edge labelled with the task that made its target.""" - names = {node_id: f"n{i}" for i, node_id in enumerate(self.nodes)} - lines = ["flowchart LR"] - for node_id, node in self.nodes.items(): - note = "" if node["status"] == "traced" else f"
({node['status']})" - lines.append(f' {names[node_id]}["{node["label"]}{note}"]') - for edge in self.edges: - lines.append(f" {names[edge['source']]} -->|{Path(edge['task']).name}| {names[edge['target']]}") - return "\n".join(lines) - class _Walk: def __init__(self, start: Path): diff --git a/tests/test_trace.py b/tests/test_trace.py index a0ecdd0..fd71cc1 100644 --- a/tests/test_trace.py +++ b/tests/test_trace.py @@ -14,6 +14,7 @@ from analysis_workflow import commit_adata, credit, writes from analysis_workflow.cli import app +from analysis_workflow.graph import OUTSIDE, dot from analysis_workflow.trace import changed_since_declared, declared, missing_inputs, trace STORE = "data/ds/processed/working/a.zarr" @@ -82,7 +83,6 @@ def test_a_file_traces_back_to_the_raw_data(project): tree = found.as_tree().splitlines() assert tree[0] == "human_fig_v1/outputs/fig.parquet [human_fig_v1]" assert any(line.strip() == "a.zarr: obs/annot [agent_annot_v1]" for line in tree) - assert "-->|agent_annot_v1|" in found.as_mermaid() def Path_name(node_id): @@ -228,9 +228,91 @@ def test_trace_command_formats(project, monkeypatch): assert tasks.output.split() == [ f"analysis/ds/topic/{n}" for n in ("agent_annot_v1", "agent_build_v1", "human_fig_v1") ] - assert CliRunner().invoke(app, ["trace", STORE, "obs/annot", "--format", "mermaid"]).output.startswith("flowchart") assert '"target"' in CliRunner().invoke(app, ["trace", STORE, "obs/annot", "--format", "json"]).output - assert CliRunner().invoke(app, ["trace", FIGURE, "--format", "pdf"]).exit_code == 1 + assert CliRunner().invoke(app, ["trace", FIGURE, "--format", "mermaid"]).exit_code == 1 + + +def test_the_graph_has_a_node_per_task_and_an_arrow_per_pair(project): + """Each task says what it produced and what it consumed that no task made; the artifact asked about is marked.""" + main, tasks = project + (tasks["human_fig_v1"] / "README.md").write_text( + "# human_fig_v1\n\n**Date:** 2026-01-29\n**Author:** A. Human\n**Id:** 00000003\n" + ) + text = dot(trace(main / FIGURE, start=main), main, today=datetime.date(2026, 2, 1)) + topic = "analysis/ds/topic" + assert [line.strip() for line in text.splitlines() if "->" in line] == [ + f'"{topic}/agent_annot_v1" -> "{topic}/human_fig_v1";', + f'"{topic}/agent_build_v1" -> "{topic}/agent_annot_v1";', + ] + build, annot, fig = ( + next(line for line in text.splitlines() if line.strip().startswith(f'"{topic}/{name}" [')) + for name in ("agent_build_v1", "agent_annot_v1", "human_fig_v1") + ) + assert "raw/counts.h5ad" in build and "a.zarr (2 keys)" in build + assert "labels.parquet" in annot and "a.zarr: obs/annot" in annot and "raw/" not in annot + assert "▶ fig.parquet" in fig and "A. Human · 2026-01-29" in fig + assert "Tracing fig.parquet" in text and "on 2026-02-01 in myproject" in text + assert "▶" not in build + annot # only the artifact asked about is highlighted + + +def test_the_graph_names_and_colours_places_outside_the_repo(project, monkeypatch, tmp_path): + """A place outside the repo has its own colour, the same whichever artifact is drawn.""" + main, tasks = project + monkeypatch.setenv("HOME", str(tmp_path)) + (tmp_path / "cache").mkdir() + (tmp_path / "cache" / "model.pkl").write_text("model") + other = tmp_path / "other_repo" + (other / ".git").mkdir(parents=True) + (other / "atlas.h5ad").write_text("atlas") + declare(tasks["agent_build_v1"], [{"path": RAW}, {"path": "~/cache/model.pkl"}]) + declare(tasks["human_fig_v1"], [{"path": LABELS}, {"path": str(other / "atlas.h5ad")}]) + + whole = dot(trace(main / FIGURE, start=main), main) + home, repo = OUTSIDE[0], OUTSIDE[1] # by name: "home directory" before "other_repo" + assert f'▌cache/model.pkl' in whole + assert f'▌atlas.h5ad' in whole + assert f'▌home directory' in whole # the legend names both places + assert f'▌other_repo' in whole + + part = dot(trace(main / STORE, "X", start=main), main) # a trace that never reaches the other repo + assert f'▌cache/model.pkl' in part and "other_repo" not in part + + +def test_the_graph_counts_what_it_does_not_name(project): + main, tasks = project + raw = [f"data/ds/raw/run{i}/counts.h5ad" for i in range(5)] + for path in raw: + (main / path).parent.mkdir(parents=True) + (main / path).write_text("raw") + declare(tasks["agent_build_v1"], [{"path": path} for path in raw]) + text = dot(trace(main / STORE, "X", start=main), main) + assert "raw/run0/counts.h5ad · raw/run1/counts.h5ad · " in text and "raw/run2/counts.h5ad +2" in text + assert "run3" not in text + + +def test_no_graph_of_what_no_task_made(project, monkeypatch): + main, _ = project + with pytest.raises(ValueError, match="No task made"): + dot(trace(main / RAW, start=main), main) + monkeypatch.chdir(main) + result = CliRunner().invoke(app, ["trace", RAW, "--format", "dot"]) + assert result.exit_code == 1 and "No task made" in result.output + + +def test_the_graph_from_the_command(project, monkeypatch, tmp_path): + main, _ = project + monkeypatch.chdir(main) + text = CliRunner().invoke(app, ["trace", FIGURE, "--format", "dot"]) + assert text.exit_code == 0 and text.output.startswith("digraph trace {") + needs_output = CliRunner().invoke(app, ["trace", FIGURE, "--format", "pdf"]) + assert needs_output.exit_code == 1 and "--output" in needs_output.output + + out = tmp_path / "graph.pdf" + drawn = CliRunner().invoke(app, ["trace", FIGURE, "--format", "pdf", "--output", str(out)]) + if shutil.which("dot"): + assert drawn.exit_code == 0 and out.read_bytes().startswith(b"%PDF") + else: + assert drawn.exit_code == 1 and "pixi add graphviz" in drawn.output and not out.exists() def test_code_committed_after_the_declaration_is_noticed(project, git):