Metadata-Version: 2.5
Name: poisson-graph
Version: 0.1.0
Summary: One change record from git, GitHub and deploy jobs; a map of the agent and its services; what is downstream of a change.
Project-URL: Homepage, https://github.com/poisson-labs/graph
Project-URL: Source, https://github.com/poisson-labs/graph
Project-URL: Changelog, https://github.com/poisson-labs/graph/blob/main/CHANGELOG.md
Project-URL: Issues, https://github.com/poisson-labs/graph/issues
Author-email: Poisson Labs <work@poissonlabs.ai>
Maintainer-email: Poisson Labs <work@poissonlabs.ai>
License-Expression: MIT
License-File: LICENSE
License-File: NOTICE
Keywords: agents,change-tracking,dependency-graph,deployments,git,llm
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Software Development :: Quality Assurance
Classifier: Topic :: Software Development :: Version Control :: Git
Classifier: Typing :: Typed
Requires-Python: >=3.11
Provides-Extra: dev
Requires-Dist: hypothesis>=6.170.15; extra == 'dev'
Requires-Dist: mypy>=2.4.1; extra == 'dev'
Requires-Dist: pytest>=9.2.0; extra == 'dev'
Requires-Dist: ruff>=0.17.4; extra == 'dev'
Description-Content-Type: text/markdown

# Poisson Graph

[![PyPI version](https://img.shields.io/pypi/v/poisson-graph?style=flat-square&color=3B5BDB)](https://pypi.org/project/poisson-graph/) [![Python versions](https://img.shields.io/pypi/pyversions/poisson-graph?style=flat-square&color=3B5BDB)](https://pypi.org/project/poisson-graph/) [![Licence: MIT](https://img.shields.io/pypi/l/poisson-graph?style=flat-square&color=3B5BDB)](https://github.com/poisson-labs/graph/blob/main/LICENSE)

One change record from git, GitHub and deploy jobs; a map of the agent and its services; what is
downstream of a change.

An agent sits on top of things that move: a service is deployed, a model snapshot changes, a
prompt or a tool schema is edited, an index is rebuilt, a flag flips. Poisson Graph keeps track of
those changes and of what each one reaches:

- **One change record.** Each change is one small record, whichever **change source** reported it
  (git, a deploy job, GitHub, your own adapter), and several sources' reports of the same change
  are joined into one.
- **A map of the agent and its services.** The models, prompts, tools, services, indexes and
  memory stores the agent depends on, declared in `poisson.toml`, with what your recorded runs
  show.
- **What is downstream of a change.** Given a node's name, some files, your uncommitted work or a
  pull request: which parts of the system and which of your scenarios the change reaches.

    python3 -m venv .venv && source .venv/bin/activate
    pip install poisson-graph

- The standard library only: no dependency is installed with it.
- It sends nothing anywhere on its own. Three things open a connection, each only when you set
  it: the GitHub source, a registered repo's `fetch` remote, and `deploy --to`. It runs no agent,
  no scenario and no model.
- It reports that something changed and what that can reach. It never says what a change caused.
- Python 3.11 to 3.13. The parts that read git need git 2.24 or newer. Tested on macOS and
  Linux. MIT licensed.

## A first run

This makes a small repository with an agent and one service, declares them in `poisson.toml`, and
asks what a change to the service can reach. It needs `git` and the install above.

    mkdir graph-first-run && cd graph-first-run
    git init -q
    mkdir -p agent services/pricing
    echo 'print("agent")' > agent/main.py
    echo 'print("pricing")' > services/pricing/app.py

Save this as `poisson.toml` in that folder:

```toml
[system]
name = "support-agent"
id = "support-agent"

[depends.support-agent]
kind = "agent"
repo = "support-agent"
paths = ["agent"]
version_from = "git"
deploys = "branch"
tools = ["lookup_order"]
cited = ["support-agent:agent/main.py:1"]

[depends.pricing]
kind = "service"
repo = "support-agent"
paths = ["services/pricing"]
tools = ["quote_refund"]
version_from = "git"
deploys = "branch"
cited = ["support-agent:services/pricing/app.py:1"]

[[scenarios]]
id = "refund_request"

[[scenarios]]
id = "order_status"
```

Commit it, then ask about the node `pricing`:

    git add . && git commit -q -m "first commit"
    poisson-graph downstream pricing

Standard output is one line of JSON, the document `poisson.downstream/1`. To read it, print a part
of it:

    poisson-graph downstream pricing | python3 -c "import json, sys; d = json.load(sys.stdin); print(json.dumps(d['counts']['reaches'])); print(json.dumps(d['counts']['scenarios']))"

The first line printed says the change reaches one tool (`"tool": 1`: `quote_refund`, which the
pricing service serves). The second says both scenarios read `unknown`, for the reason `no_runs`:
no run has been recorded yet, so nothing shows whether a scenario calls that tool. The answer does
not guess.

Now change a file without committing it, and ask about your uncommitted work:

    echo '# a change' >> services/pricing/app.py
    poisson-graph downstream --working-tree

The file is under the pricing service's paths, so the answer is the same walk, found from the
file this time. A deploy job reports a deploy with the other command. It prints one change record:

    poisson-graph deploy --service pricing --environment production

## The downstream command

```
poisson-graph downstream NODE [--kind KIND]
poisson-graph downstream [--file PATH ...] [--path REPO:PATH ...]
poisson-graph downstream --working-tree [--since REV]
poisson-graph downstream --pr [--base REV] [--head REV] [--in REPO]
```

One call takes one question: a node by its name, files, the working tree, or a pull request read
from the local clone. It runs nothing, opens no network connection and writes nothing.

- **The working-tree and pull-request questions need a full clone.**
- **A partial clone needs git 2.44 or newer and is refused on older git.**

Every option, the document it prints, the exit codes and the same thing as a Python function are
under [What is downstream of a change](#what-is-downstream-of-a-change) below.

## What is in it

| | |
|---|---|
| `Change`, `Sighting`, `Scope`, `Evidence`, `Pin` | the record: what moved, where, when, how precisely the time is known, and whether each side can be reproduced |
| `load_source` | finds a source by its import path, `module:Name`, and asks it what it is |
| `run_poll`, `run_receive`, `run_pin`, `run_evidence` | the only way a source is called; they hold the rules so no source has to be trusted to |
| `join` | one change from many reports of it |
| `to_json`, `from_json`, `public` | one change per line of JSON; `public` is the form that may leave your side |
| `poisson_graph.testing` | the kit for adapter authors, below |
| `poisson_graph.sets` | change sets: the changes since your agent was last measured, as one frozen list of candidates, below |
| `poisson_graph.map` | the system map: what the agent depends on, read from the `[depends]` tables of a setup file and from recorded evidence (`from_setup`, `edges_from_spans`, `merge`), and `walk`, which goes from a change to the nodes and scenarios it can reach. The downstream command is built on it |
| `poisson_graph.downstream`, and `poisson-graph downstream` | what one change can reach: a node, files, the working tree or a pull request, answered from `poisson.toml` and your recorded runs as one JSON document, below |
| `poisson-graph --version` | prints `poisson-graph` and the installed version on one line, as `poisson-graph 0.1.0` |

Three things worth knowing before you use it:

- **A source that fails is never read as "nothing changed".** A poll that raised gives an intake
  with an error and no covered interval. Only a poll that worked says "I vouch for this interval".
- **Always join from the sources' own reports.** `join` records a disagreement between two
  sources in `Joined.conflicts` and keeps neither value on the change. The joined change does not
  carry that disagreement, so do not feed an earlier join's changes back into `join`.
- **Findings stay on your side.** A source's own findings (`Evidence.detail`) are kept verbatim
  and are dropped by `public(change)`. Only the source's one word for the change leaves.

## For adapter authors

An adapter is a class, in your own module, that turns one upstream (a deploy service, a flag
service, a git host) into changes. Nothing registers it: it is found by the import path the user
writes in their settings, such as `my_package.deploys:DeployLog`.

### What a source implements

One method always, and up to four more that it declares:

| method | what it does | needed when |
|---|---|---|
| `describe()` | returns a `SourceInfo`: the source's name, the kinds of change it can report, whether it polls or takes pushes, the worst time precision it will report, and whether it can pin and judge | always |
| `poll(*, since, until)` | returns a list of every change that took effect in `[since, until)` | `"poll"` is in `modes` |
| `receive(*, headers, body)` | verifies a pushed request, then returns the list of changes it reports; raises `Rejected` when verification fails | `"push"` is in `modes` |
| `pin(*, change, side)` | returns a `Pin` saying how that side (`"before"` or `"after"`) can be reproduced, or `None` | `pins` is true |
| `evidence(*, change)` | returns the source's own judgement as an `Evidence`, or `None` if it has none yet | `judges` is true |

A source implements only what it declares. A poll-only source needs `describe` and `poll` and
nothing else.

The rules a source keeps, each of which is checked when it is called:

- **Each change has exactly one sighting, and the sighting names this source.**
- **A sighting's `id` names the event, never the version.** Use the upstream's id for this
  deploy or this push. If the upstream has none, hash the version together with the time it
  took effect. The version itself is `after`. A source that uses the version as its id loses the
  second deploy when a version is deployed, rolled back and deployed again.
- **Everything that names something is an identifier:** 1 to 200 printable ASCII characters
  with no space. A value that does not fit (a flag variant called `new checkout flow`) is hashed
  by the adapter before it goes in the record.
- **Times are timezone-aware and in UTC.** A time with no zone is refused, not guessed.
- **Say how precisely you know the time:** `"exact"`, `"minute"` or `"approximate"`. There is no
  default, and a source never reports a better precision than it declared.
- **Say what you know and nothing else.** `before=None` when you do not know the earlier
  version. `Scope(fraction=1.0, random=None)` when you do not know who got the change. An empty
  `pinnable` when you cannot reproduce either side.
- **No content in the record.** No prompt text, payload, file path, key, token or user name.
  Versions are hashes and ids.
- **Secrets are yours to read.** Take the *name* of an environment variable as a setting
  (`token_env="DEPLOYS_TOKEN"`) and read it when you need it. The core never reads one.
- **Raise when the upstream fails.** Do not return an empty list for an upstream that timed out:
  an exception becomes an instrument error, which says the measurement has a hole. An empty
  list says nothing changed.

### One worked example source

A source for a made-up deploy log. Its upstream is a list of rows; a real adapter would fetch
them from its service. It polls, takes signed pushes, and can pin the image of each side.

```python
# deploy_log.py
import hashlib
import hmac

from poisson_graph import Change, Pin, Rejected, Scope, Sighting, SourceInfo


class DeployLog:
    def __init__(self, *, rows, secret):
        # rows: dicts with "event", "service", "env", "from", "to", "at" (aware UTC datetime)
        self._rows = list(rows)
        self._secret = secret

    def describe(self):
        return SourceInfo(
            name="deploy-log",
            kinds=frozenset({"code_deploy"}),
            modes=frozenset({"poll", "push"}),
            precision="minute",   # the log stamps each deploy to the minute
            pins=True,            # it can say which image each side ran
            judges=False,         # it has no opinion on whether a deploy was good
        )

    def _change(self, row):
        return Change(
            service=row["service"],
            kind="code_deploy",
            environment=row["env"],
            before=row["from"],            # None if the log does not know
            after=row["to"],
            scope=Scope(fraction=1.0, random=None),   # all traffic, as far as the log knows
            pinnable=frozenset({"before", "after"} if row["from"] else {"after"}),
            sightings=(
                Sighting(
                    source="deploy-log",
                    id=row["event"],       # the deploy's own id, never the commit
                    effective_at=row["at"],
                    precision="minute",
                    evidence=None,
                ),
            ),
        )

    def poll(self, *, since, until):
        return [self._change(r) for r in self._rows if since <= r["at"] < until]

    def receive(self, *, headers, body):
        signed = hmac.new(self._secret.encode(), body, hashlib.sha256).hexdigest()
        if not hmac.compare_digest(headers.get("X-Deploy-Signature", ""), signed):
            raise Rejected("the signature does not match")
        event = body.decode()
        return [self._change(r) for r in self._rows if r["event"] == event]

    def pin(self, *, change, side):
        commit = change.before if side == "before" else change.after
        return Pin(side=side, kind="image", ref=f"registry.example/{change.service}:{commit}")
```

Using it:

```python
from datetime import UTC, datetime
from poisson_graph import join, load_source, run_poll

rows = [
    {"event": "dep-1", "service": "pricing", "env": "production",
     "from": "aaa1", "to": "bbb2", "at": datetime(2026, 11, 12, 14, 3, tzinfo=UTC)},
]
loaded = load_source("deploy_log:DeployLog", settings={"rows": rows, "secret": "s3cret"})

intake = run_poll(loaded, since=datetime(2026, 11, 12, tzinfo=UTC),
                  until=datetime(2026, 11, 13, tzinfo=UTC))
intake.changes    # the valid changes, in order
intake.refused    # what the source returned that was not taken, each with a one-line reason
                  # and an invariant: "not_taken" (a change that did not fit what the source
                  # declared or the interval asked for) or "not_verified" (a push that failed
                  # the source's verification)
intake.error      # set when the call itself failed
intake.covered    # the interval this intake vouches for, or None

joined = join(intake.changes)   # add other sources' reports to the list before joining
```

### How to run the kit against it

`check_source` is what your adapter's own test suite calls, with the adapter pointed at a fake of
its upstream. It runs nothing against a real service.

```python
# test_deploy_log.py
import hashlib
import hmac
from datetime import UTC, datetime

from poisson_graph import load_source
from poisson_graph.testing import check_source

SECRET = "MARKED-KEY-for-the-test"
DAY = datetime(2026, 11, 12, tzinfo=UTC)
ROWS = [
    # A version deployed, rolled back and deployed again: every adapter's fixtures need this.
    {"event": "dep-1", "service": "pricing", "env": "production",
     "from": "aaa1", "to": "bbb2", "at": DAY.replace(hour=9)},
    {"event": "dep-2", "service": "pricing", "env": "production",
     "from": "bbb2", "to": "aaa1", "at": DAY.replace(hour=11)},
    {"event": "dep-3", "service": "pricing", "env": "production",
     "from": "aaa1", "to": "bbb2", "at": DAY.replace(hour=15)},
]


def test_the_deploy_log_passes_the_kit():
    loaded = load_source("deploy_log:DeployLog", settings={"rows": ROWS, "secret": SECRET})
    body = b"dep-1"
    signature = hmac.new(SECRET.encode(), body, hashlib.sha256).hexdigest()

    report = check_source(
        loaded,
        window=(DAY, DAY.replace(hour=23)),                         # an interval the fake has changes in
        sample_push=({"X-Deploy-Signature": signature}, body),      # a request the source should accept
        markers=[SECRET],                                           # strings that must never be emitted
    )

    assert report.failed == (), report.failed
    assert set(report.passed) == {"1", "2", "3", "4", "5", "6", "7", "9", "10"}
    assert len(report.skipped) == 1   # check 8: this source does not judge
```

`report.passed` lists the checks that passed by number, `report.failed` holds a `Failure` for each
that did not (its `check` number and a one-line `reason`), and `report.skipped` says which checks
did not apply and why. The ten checks:

| # | what it checks |
|---|---|
| 1 | `describe()` gives the same answer when asked again |
| 2 | every method the source declares is there |
| 3 | a poll over the window returns only changes the source may report: declared kinds, inside the window, one sighting each naming this source |
| 4 | two polls over the same window give the same answer |
| 5 | two polls over the two halves of the window give, joined, what one poll over the whole window gives: nothing lost or doubled at the seam |
| 6 | the sample push is accepted; the same request with one byte changed is rejected; the same request sent twice does not become two changes |
| 7 | for each change returned and each side it offers, `pin` returns a `Pin` for that side or `None` |
| 8 | `evidence` returns an `Evidence` or `None` |
| 9 | none of your `markers` appears in anything that may leave: the public form of each change, each pin, each evidence word |
| 10 | an id names one event: no change comes back under the same id at two different times |

For check 9, plant marked strings (a prompt, a payload, a file path, a key) in your fake upstream
and in the environment your adapter reads, and pass the same strings as `markers`. A marker
inside a source's findings (`Evidence.detail`) is allowed, because findings never leave.

A check is skipped, with its reason, when it does not apply: no `window` given, no `sample_push`
given, no `markers` given, or a source that does not poll, take pushes, pin or judge.

### A fake source for your own tests

If you are building something that consumes changes, `ScriptedSource` is a source that returns
what you script it with:

```python
from poisson_graph import load_source, run_poll
from poisson_graph.testing import ScriptedSource

loaded = load_source(
    "poisson_graph.testing:ScriptedSource",
    settings={"info": info, "polls": [change_1, change_2]},
)
```

`polls` is the changes it holds (`poll` returns those in the interval asked for); `pushes` is
`(body, changes)` pairs (any other body is rejected); `pins` and `evidences` are
`(change key, answer)` pairs; `raises` is an exception that every call raises.

## Change sets

Between two points where your agent was measured, several things under it change. Before you pay
to find out which one mattered, you need those changes as a fixed list. That list is a **change
set**, and it lives in `poisson_graph.sets`. Its names are public there and are not at the top
of the package, so import the module:

```python
from poisson_graph import sets
```

### What a set is

A set covers one environment, from the last measurement (the **before point**) up to and
including a **close**. It is a frozen value. It holds:

| | |
|---|---|
| `candidates` | one per thing that moved and ended somewhere new. Three deploys of one service are one candidate, from the version that was measured to the last one, with the versions in between listed. A thing is a service together with a kind of change, so a service's code and its config are two things |
| `rolled_back` | things that moved and ended at the version they were measured at. Listed, and not candidates |
| `held` | changes the set cannot place, each with the reason: its time is only approximate and crosses one end of the set (`straddles_close`, `straddles_before`), or its order against another change to the same thing cannot be known (`order_unknown`). Listed, and not candidates |
| `gaps` | what was not heard: for each source you expected, the stretches of the set it did not vouch for, and why (`not_polled`, `error`, `push_only`) |
| `refusals` | per source, how many reported records were refused and so are not in the set |
| `conflicts` | where two sources disagreed about a change the set lists |
| `id` | a short name for the set, made from its two ends and what it lists. A check records it as the thing it tested |

Each candidate also says which of its two ends can be pinned for a replay (`pinnable`), where its
chain has a missing link (`breaks`: a change in between was not reported), whether any of its
steps took effect before the last measurement and was not measured (`late`), and whether any
step's time is only approximate (`approximate`).

A set decides nothing about your agent. It computes no statistic, applies no policy and starts no
check. It says what the candidates are and what you did not hear.

### The two functions

**`close_time`** says when the set that follows the last measurement stops taking changes:

```python
close = sets.close_time(reports, environment="production", before=last,
                        quiet=timedelta(minutes=10), longest_wait=timedelta(hours=1))
```

It returns a `Close` (a time, and the rule that set it), or `None` when no change has opened a
set. A set closes once no change has taken effect for the quiet period, or at the longest wait
after its first change, whichever comes first. The quiet period runs between the times changes
took effect, not the times their reports arrived. A change whose time is only approximate never
opens a set and never moves its close.

**`build`** makes the set:

```python
change_set = sets.build(reports, environment="production", before=last, close=close,
                        approximate_within=timedelta(minutes=2),
                        intakes=intakes, sources=expected)
```

`approximate_within` is how far off you take an approximate time to be, either side. `sources` is
the `SourceInfo` of every source you expected to hear from, and `intakes` is every intake you
hold. Both are required, so a set never says "no gaps" by default: pass neither and you have said
you expected no one.

Around them: `environments(reports)` lists the environments your reports name, so you can build
one set for each; `next_before(change_set)` gives the before point for the set after this one;
`to_json` and `from_json` write and read a set; and `public(change_set)` is the form that may
leave your side, with every source's findings emptied.

### What you must hold

The module reads no clock and keeps no store. Every one of these is yours:

- **The clock.** `close_time` returns a time. Compare it to your own clock, wait, ask again with
  whatever has arrived since, and call `build` only once that time has passed. The module cannot
  check that you waited. If one of your sources is slow to report, wait longer before you build.
- **The quiet period and the longest wait.** Your project sets both. Neither has a default, and
  the longest wait may not be shorter than the quiet period. The same goes for
  `approximate_within`.
- **The last measurement.** A `BeforePoint`: when the agent was last measured, a name for that
  measurement, and the version each thing was measured at, where you know it. The first one may
  know nothing. After that, take it from `next_before(change_set)` and keep it until the next
  set. When a full run measures everything again, build the close yourself:
  `sets.Close(at=<the run's time>, by="measurement", quiet=None, longest_wait=None)`.
- **Every report, every time.** Pass every report your sources gave you to every call, straight
  from the sources: never an earlier join's changes and never the changes inside a set. A change
  reported after its set was built is picked up by the next set, marked `late`, as long as the
  last measurement knows that thing's version.
- **The sets you have built.** A set is a value; once a check has started on it, keep it as it
  is. Nothing in the module alters a set or keeps one for you.
- **What is on policy.** The module tests every change you give it. Leave out the kinds and
  environments your project does not check, and keep your own record of what you left out.

### One worked example

Pricing is deployed twice, by two different sources. Search is deployed and then rolled back.

```python
from datetime import UTC, datetime, timedelta

from poisson_graph import Change, Scope, Sighting, SourceInfo, sets


def deploy(service, before, after, minute, *, source, event):
    return Change(
        service=service, kind="code_deploy", environment="production",
        before=before, after=after,
        scope=Scope(fraction=1.0, random=None), pinnable=frozenset(),
        sightings=(
            Sighting(source=source, id=event, precision="exact", evidence=None,
                     effective_at=datetime(2026, 11, 12, 14, minute, tzinfo=UTC)),
        ),
    )


# Every report you hold, as the sources gave them (the changes of your intakes).
reports = [
    deploy("pricing", "v0", "v1", 5, source="git", event="push-1"),
    deploy("pricing", "v1", "v2", 12, source="deploys", event="dep-7"),
    deploy("search", "s0", "s1", 8, source="git", event="push-2"),
    deploy("search", "s1", "s0", 14, source="git", event="push-3"),
]

# The last measurement: a full run at 14:00, against pricing v0 and search s0.
last = sets.BeforePoint(
    at=datetime(2026, 11, 12, 14, 0, tzinfo=UTC),
    ref="run-0412",
    measured=(
        sets.Measured(service="pricing", kind="code_deploy", version="v0"),
        sets.Measured(service="search", kind="code_deploy", version="s0"),
    ),
)

close = sets.close_time(reports, environment="production", before=last,
                        quiet=timedelta(minutes=10), longest_wait=timedelta(hours=1))
close.at    # 14:24: ten quiet minutes after the last change, at 14:14
close.by    # "quiet"

# Your own clock passes 14:24 and nothing new has arrived. Now build the set. You expected to
# hear from git and you hold no intake from it here, so the set will say so.
git = SourceInfo(name="git", kinds=frozenset({"code_deploy"}), modes=frozenset({"poll"}),
                 precision="exact", pins=False, judges=False)
change_set = sets.build(reports, environment="production", before=last, close=close,
                        approximate_within=timedelta(minutes=2), intakes=[], sources=[git])

(candidate,) = change_set.candidates
candidate.service, candidate.before, candidate.after   # ("pricing", "v0", "v2")
candidate.versions                                      # ("v1",): the version in between
candidate.sources                                       # ("git", "deploys")

(rolled,) = change_set.rolled_back
rolled.service, rolled.version                          # ("search", "s0"): back where it was

(gap,) = change_set.gaps
gap.source, gap.why                                     # ("git", "not_polled"), 14:00 to 14:24

change_set.id                                           # 16 characters; what a check records
text = sets.to_json(sets.public(change_set))            # the form that may leave your side

# The before point for the next set: at 14:24, named by this set's id, pricing now at v2.
last = sets.next_before(change_set)
```

One candidate comes out, so one thing is tested: pricing, from `v0` to `v2`. Search is listed as
rolled back and is not tested, because it ended where it was measured.

## Built-in sources

Five sources ship in this same distribution, in three subpackages beside the
core (`import poisson_graph` imports none of them), and one command. The git and setup
modules need the `git` program, 2.24 or later, and nothing else; the trace module needs nothing
but Python.

| import path | what it reports | time |
|---|---|---|
| `poisson_graph.git:BranchSource` | a code deploy for each movement of a watched branch that touched a service's paths | approximate: when the clone's own log recorded the movement |
| `poisson_graph.git:PipelineSource` | a code deploy for each report line a pipeline wrote to a spool directory or sent as a signed push | exact |
| `poisson_graph.git:GitHubSource` | a code deploy for each deployment status GitHub records as `success` | exact: the status's time |
| `poisson_graph.setup:SetupSource` | a prompt, tool schema, config, index id or memory id whose declared files changed between the two commits of a movement | approximate, as the branch source |
| `poisson_graph.otel:TraceSource` | a service's new `service.version`, or a new response model under the same request model, seen on imported spans | approximate |

The four git-family sources take one setting, `repos`, the list of registered repos:

```python
repos = [{
    "name": "pricing-service",                # how the repo is named in what the sources emit
    "path": "/srv/clones/pricing-service",    # the clone on this machine; never emitted
    "fetch": None,                            # None, or a remote to fetch at every poll
    "github": "acme/pricing-service",         # optional; only the GitHub source reads it
    "watch": [{"ref": "refs/remotes/origin/main", "environment": "production"}],
    "services": [{"service": "pricing", "paths": ["services/pricing"], "deploys": "branch",
                  "github_environments": {"production": "production"}}],  # GitHub's name: ours
    "declared": [{"service": "support-prompt", "kind": "prompt",
                  "files": ["prompts/system.md"], "read": "hash"}],
}]
```

A service whose deploys a hook reports says `"deploys": "recorded"`, and the branch source then
says nothing for it. The pipeline source also takes `secret_env` (the variable that holds the push
secret), `spool` (a directory of `.jsonl` files), or both. The setup source also takes
`hash_key_env`, a variable holding a key that makes every hash an HMAC.

**Register a full clone, never a partial one** (one made with `--filter`). On git older than 2.44
a partial clone may fetch an object it lacks from its remote while a poll reads it, because git
honours `GIT_NO_LAZY_FETCH` only from 2.44. A full clone never fetches anything a poll did not ask
for.

The GitHub source also takes `token_env` (the variable that holds a GitHub token, read at each
poll and never kept), `lookback_s` (how long a deploy may take, in seconds: deployments created
that long before a poll's interval are read, since one may succeed inside it) and `api` (default
`https://api.github.com`; plain `http` only to this machine). It reads the deployments of each repo
that has a `github` key, and a service gets a change when its `github_environments` names the
deployment's GitHub environment. A redirect, a rate limit or any answer GitHub could not give
whole is an instrument error for the whole poll.

**Set `lookback_s` to your slowest deploy,** counted from when the deployment is made to its
`success` status. A deployment that took longer than `lookback_s` is never taken as the commit a
later deploy replaced, and with such a deploy two adjoining polls may give something other than
one poll over both. GitHub keeps deployment statuses for 90 days, so a poll whose interval starts
more than 90 days back is an instrument error, and nothing is asked of GitHub.

The trace source takes `observations`, `settle` (how many observations in a row make a new
version a change), `environment_when_missing`, `only` (`"all"`, or the names to report) and
`names` (a span's service name to the setup's). It reads its observations from Poisson Trace,
which does not yet keep service versions and models for the spans it imports, so today every
poll of it is an instrument error. Its rules are `poisson_graph.otel.detect`, which can be
called today on a list of `Observation`s.

### The clone's log, and how far back a poll reaches

The branch source and the setup source take the time of every change from the clone's own log of
the watched ref. So:

- **Set every registered clone's ref logs never to expire** (`git config gc.reflogExpire never` and
  `git config gc.reflogExpireUnreachable never` in the clone), when it is registered. A log git has
  expired cannot answer for the time it no longer covers.
- A ref with no log, or a log that holds no entry, is an instrument error, never "nothing changed".
- A poll that starts before the oldest entry of a watched ref's log is an instrument error, unless
  that entry is the one that created the ref. A fresh clone keeps no such entry for its remote
  branch, so poll a clone from its first logged movement on.
- A log trimmed with `git reflog expire --rewrite` leaves an oldest entry with no earlier commit,
  which reads exactly as the entry that created the ref. The sources cannot tell the two apart and
  read such a log as whole. Nothing runs `--rewrite` unless a person asks for it.
- A log in which an entry other than the oldest has no earlier commit is an instrument error at
  every poll: read entry by entry, such an entry looks like the ref being created, and the clone
  cannot say what moved.

### Clones whose refs git keeps in a reftable

A clone made with `--ref-format=reftable`, or by a git whose default that is, is read the same as
one in git's usual files format: the sources read the reftable's own tables for a watched ref's
log. Three things differ, all of them git's doing:

- **A reftable clone's log keeps an entry for the clone creating its remote branch**, at the time
  of the clone. The files format keeps none. By the rule above, that log is whole, so a poll may
  start before the clone's first fetch. Poll a clone only from when it was registered.
- **`git reflog expire --rewrite` keeps the oldest entry's earlier commit in a reftable**, so the
  case of the `--rewrite` bullet above does not arise in one.
- **Never convert a registered clone with `git refs migrate`, in either direction.** In git
  2.48.1, a migration to a reftable writes every log entry with no earlier commit, so every poll
  of that clone is an instrument error from then on; a migration back to the files format writes a
  wrong earlier commit into every entry, which no source can detect. Register a fresh clone made
  in the format you want instead.

### `poisson-graph deploy`

A deploy job runs it after the step that put the new version live:

```
poisson-graph deploy --service pricing --environment production --out deploys.jsonl
```

It prints exactly one report line on standard output: one change record with one `pipeline`
sighting at an exact time, the commit as a full id. `--commit` (default `HEAD`) and `--before` are
resolved in the checkout it runs in. `--out` appends the line to a file; `--to URL --secret-env NAME`
POSTs it, signed with `Poisson-Signature: v1=<HMAC-SHA256 of the body>`. Exit codes: 0 reported
(or nothing changed), 2 wrong arguments, 3 a commit could not be resolved to one full id, 4 made
and not delivered (the line is still printed), 5 the secret's variable is unset or empty.

A job with no Python can write the same line itself. In Node:

```js
const crypto = require("crypto");
const [environment, service, kind] = ["production", "pricing", "code_deploy"];
const after = process.env.GITHUB_SHA;  // the deployed commit's full id
const key = crypto.createHash("sha256")
  .update([environment, service, kind, after].map((part) => part + "\0").join(""))
  .digest("hex").slice(0, 16);
console.log(JSON.stringify({
  schema: "poisson.change/1", key, service, kind, environment, before: null, after,
  scope: { fraction: 1, random: null }, pinnable: [],
  sightings: [{ source: "pipeline", id: "gha-" + process.env.GITHUB_RUN_ID,
                effective_at: new Date().toISOString(), precision: "exact", evidence: null }],
}));
```

## What is downstream of a change

Before you run or pay for anything, ask what a change can reach. The answer comes from what is
already on your machine: the declaration in `poisson.toml`, and your recorded runs when there are
any. It runs no agent, no scenario and no model, opens no network connection, and writes nothing.
The four forms of the command are above, under [The downstream command](#the-downstream-command).
Every form also takes:

```
    common:  [--setup FILE | --map FILE] [--environment NAME] [--as-of TIME]
             [--repo NAME=PATH ...] [--here NAME] [--layer FILE | --no-layer]
             [--core-changed-at TIME] [--min-runs N] [--json]
```

One call takes one ask:

| ask | what it is |
|---|---|
| a node | a name from the declaration, as written: a table, a tool, a model's alias. Nothing is matched by likeness; a name that matches nothing comes back with the nearest names |
| files | files on this machine (`--file`), or pairs of a repo's name and a path under its root (`--path pricing-service:app/pricing.py`), which are never looked up on disk. A renamed file is given at both paths. A folder stands for that one path, not for everything under it |
| the working tree | everything that differs from the last commit: staged, unstaged, deleted, and untracked files that are not ignored. `--since` compares the checkout the setup file sits in from another commit |
| a pull request | the paths that differ between the merge base of a base and a head, and the head, read from the local clone. With no `--base` it is the remote's default branch as the clone last recorded it. Nothing is fetched |

Standard output is exactly one line: the document `poisson.downstream/1`. It holds what was asked
and how it was resolved, the counts a sentence needs, where each node is declared, and the system
map, the walk and the walk's receipt as their own JSON. It holds no sentence: the wording is the
caller's. Exit codes: 0 answered, 1 a node's name that matches no node (the document is still
printed), 2 wrong arguments, 3 the setup file or the declaration was refused, 4 git could not
answer, 5 the run layer was refused. On 2 to 5 standard output is empty. `--json` is accepted and
changes nothing: the output is always this one line of JSON.

The same thing as a function, with no defaults and absolute paths only:

```python
from datetime import UTC, datetime

import poisson_graph.downstream as downstream_of

answer = downstream_of.downstream(
    setup="/work/cs-agents/poisson.toml", map_file=None,
    ask=downstream_of.AskFiles(paths=("/work/pricing-service/app/pricing.py",), repo_paths=()),
    environment="local", repos={"pricing-service": "/work/pricing-service"}, home="cs-agents",
    layer=None, core_changed_at=None, min_runs=30, as_of=datetime(2026, 11, 12, 10, tzinfo=UTC),
)
print(answer.counts.reaches, answer.counts.scenarios)
line = downstream_of.to_json(answer)
```

Things worth knowing before you use it:

- **Say which repo this checkout is.** `poisson.toml` names repos and holds no path. Pass the
  name of the repo the setup file sits in (`--here`, `home`), or map names to folders (`--repo`,
  `repos`). Without one, a file cannot be placed and the working-tree and pull-request asks are
  refused. Only a declaration with an agent table whose repo is the one repo every table names
  needs neither. Nothing is guessed from a folder's name or a remote's URL.
- **"Not known" is not "nothing".** A changed file in a repo no node belongs to classifies no
  scenario. The document marks it: `counts.unmatched_no_node` is above zero and that repo's entry
  in `asked.repos` has `holds_node` false. A file that could not be placed is in `asked.unplaced`,
  and a repo that was not read is in `asked.repos` with its reason.
- **Before any run exists** a change on every run's path reads `reached`, and every other
  connected change reads `unknown`, `no_runs`.
- **Recorded runs are a file you write.** `write_layer` writes `poisson.run_layer/1`: for each
  run its scenario, its time and the names of the tools it called, and no content. It keeps its
  folder out of git with an ignore file, so it takes only a folder of its own; the command looks
  for it at `.poisson/upstream/layer.json` beside the setup file. Say when the agent or any core
  part last changed (`--core-changed-at`, `core_changed_at`): runs from before it no longer show
  that a scenario does not reach something.
- **Git is only read.** The two asks that use it need git 2.24 or later, run a fixed list of
  read-only commands, start no filter and no hook of the repo's, and write nothing under `.git`.
  A tracked file saved again with the same contents may be listed as changed; that errs toward
  reaching more.
- **Use a full clone for the working-tree and pull-request asks.** A pull-request ask needs a
  clone that holds the history back to the base. A partial clone (one made with `--filter`) needs
  git 2.44 or newer and is refused on older git, because an older git could go to the network
  for a missing object.
- **A repo that is a folder inside a larger repository** is not read with git. Use the files ask
  for it.
- **The document stays on your side.** It holds names, paths and citations. The part with no
  name in it is the `receipt` inside it.

## Development

In a clone of this repository, with [uv](https://docs.astral.sh/uv/):

    uv venv && source .venv/bin/activate
    uv pip install -e ".[dev]"
    python -m pytest -q
    ruff check .
    mypy

The changes in each release are in
[CHANGELOG.md](https://github.com/poisson-labs/graph/blob/main/CHANGELOG.md).
