> built 2026-12-05 17:44 UTC from 9bd6639 (main) · openloops 0.1.84. Details: build_info.json

# index.html.md

<!-- generated by epythet -->

# openloops

An **open loop** is a commitment that outlived the session that made it and that
nothing is watching. An agent said it would come back to something and the message
scrolled away. An agent got blocked on you and filed an issue you never re-read. An
agent found the real fix belonged in another repository, filed it there, wrote a
workaround here, and nobody ever told this repository the blocker was closed.

`openloops` finds those and re-checks them. It answers three questions. It never writes
to GitHub: it does not close, reopen, relabel or comment on anything, anywhere — the
transcript, the label and the dependency edge *are* the records.

The one loop it keeps itself is the one you ask for: `ol remind "Review the draft" --when 3h` makes a reminder that pushes to your phone at that time even if your laptop is asleep (see [`ol remind`]()).

**The surface most people want is not a command.** If you delegate development to
agents, what you want is an agent that runs the commands and tells you what matters.
That is what to install first; the `ol` command underneath it is plumbing, and it is
documented further down for when you want it directly.

## Start here: install the skills, then ask your agent

```bash
pip install openloops        # Python 3.10+. Puts an `ol` command on your PATH.
ol install-skills            # link the skills and the subagent into ~/.claude
                             # --only openloops,openloops-sweep to skip the capture skill
```

```default
installed into ~/.claude
  method: symlink   install: 4   ok: 0   conflict: 0

install  skill  openloops                 not present
                  -> ~/.claude/skills/openloops
install  skill  openloops-needs-human     not present
                  -> ~/.claude/skills/openloops-needs-human
install  skill  openloops-phone-board     not present
                  -> ~/.claude/skills/openloops-phone-board
install  agent  openloops-sweep           not present
                  -> ~/.claude/agents/openloops-sweep.md
```

Then open a coding session and ask, in whatever words you would have used anyway:

> **what needs my attention?**
```default
## Needs you now
- CI secrets are not provisioned on acme/widget — acme/widget#1, 23 days old. One
  `gh secret set PYPI_PASSWORD --repo acme/widget` and the publish job stops
  failing on merge.
- Decide whether the parser ships in 2.0 or waits — acme/parser#4, 2 days old.
  A judgement call, so no check can ever discharge it; it sits here until you answer.
- Unchecked: acme/widget#9. Its predicate runs the doctests against a live
  third-party fetch and timed out at 20s. Not open, not done — nothing observed it.

## Free to proceed
- acme/widget#109 — every blocker closed. acme/engine#15 has been closed for 5 days
  and nothing has said so. The rename workaround in widget can come out.
- acme/engine#7 — the deploy key is there and the check now passes. The issue is
  merely still open. I have not closed it.

## In flight
- widget: two sessions, the 2.0 parser and an egress scrubbing pass.
- parser, infra, engine: one session each, none of them waiting on you.
- Two widget issues wait on acme/engine and widgets/aix. Nothing for you there.

2 need you, 2 are free to start, 1 could not be checked.
```

That answer is a **synthesis, not a paste** — the skill asks for exactly that, and an
agent that hands you three screens of command output has failed to use it. Every row
behind it is one the `ol` commands printed; you can see the same rows raw, in the
plumbing sections below.

Ask again tomorrow and it is a different answer, because `ol owed` and `ol blocked`
re-run each obligation’s check and re-resolve each blocker edge before answering. That
re-check is the whole product; everything else is a list you could have got from `gh`.

### Two things to set up once

**The GitHub CLI, logged in.** Two of the three questions are answered out of GitHub, so
they need `gh` on your PATH and authenticated. The session-digest half needs nothing at
all — no model, no network, no account, no configuration.

**Which repositories you mean.** Left alone, the fleet is whatever login `gh` is
authenticated as. If you work across an organisation, that is a count that looks clean
and is wrong, so say so once:

```bash
export OPENLOOPS_OWNERS="your-login some-org another-org"
```

Every result prints the owners it used, and the read skill is told to check that line
and tell you when it looks too narrow. More on the resolution order below.

### What got installed

| Name                    | Kind     | What it is for                                                                                                                                                                                   |
|-------------------------|----------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `openloops`             | skill    | **the read side.** Teaches an agent which of the three commands answers which question, how to synthesise the three into one page, and — most of all — never to round a `?` into a clean answer. |
| `openloops-needs-human` | skill    | **the capture side.** Teaches an agent to file a `manual-task` issue, with a re-checkable predicate, at the moment it gets blocked on you. Without it, `ol owed` has nothing to read.            |
| `openloops-phone-board` | skill    | **the phone board.** Gather, classify, build and publish the task board, and the receiver procedure that turns its taps into comments, closes and dispatched workers.                            |
| `openloops-sweep`       | subagent | the same sweep, run in a fresh context, returning a page instead of three screens. For the session you keep open all day.                                                                        |

`~/.claude` is Claude Code’s config directory, and `CLAUDE_CONFIG_DIR` is honoured if
you have moved it. Any other agent host: `ol install-skills --target DIR`. They are
plain markdown files with YAML front matter; nothing about them is Claude-specific
except where they get installed.

**Re-running it changes nothing.** Each asset is a symlink into the installed package,
so `pip install -U openloops` upgrades the skills too, and a second `ol install-skills`
reads `ok: 4`. Where symlinks are unavailable — Windows without Developer Mode — it
copies instead, and the report says which happened rather than pretending they are the
same thing.

**Nothing already there is ever overwritten.** A destination holding something that is
not ours is reported and left exactly as it was:

```default
installed into ~/.claude
  method: symlink   install: 2   ok: 0   conflict: 1

conflict skill  openloops                 something else with this name is already there
                  -> ~/.claude/skills/openloops
install  skill  openloops-needs-human     not present
                  -> ~/.claude/skills/openloops-needs-human
install  agent  openloops-sweep           not present
                  -> ~/.claude/agents/openloops-sweep.md

conflict means nothing was written there. Look at the file, then re-run with --force to replace it.
```

```bash
ol install-skills --dry-run     # print the plan, touch nothing
ol install-skills --copy        # copy instead of link (stops tracking upgrades)
ol install-skills --force       # replace what is there — after you have looked at it
ol install-skills --target DIR  # some other agent host's config directory
```

## The sweep subagent, for the session you keep open all day

The session you want to have this conversation in is a long one: the master session you
leave open and come back to. Running the sweep inline fills that session’s context with
command output that is stale ten minutes later, and does it again every time you ask.

`openloops-sweep` is the fix, and it is one file. It runs the three commands in its own
fresh context and returns only the synthesis, so the tenth “what needs my attention?” of
the day costs the main session the same as the first — about a page — no matter how long
the conversation has run.

The read skill dispatches to it when it is installed. Inline is still right for a one-off
question, or when you are about to drill into one row.

## The capture skill, and why `ol owed` has anything to read

`ol owed` reads open issues labelled `manual-task`. On a fresh machine there are none,
and there is no amount of reading that will produce any: **something has to file them.**

That something is `openloops-needs-human`, installed above. It fires at the moment an
agent gets blocked on you — a secret it cannot write, a permission it does not have, a
decision that is yours, a recorded decision that now looks wrong — and files the blocker
as a labelled issue in the affected repository *before* writing the hand-back message
you were never going to re-read.

> **Did openloops file this issue?** No. **openloops never writes to GitHub.** The
> `manual-task` issues it reads are filed by whatever you have told your coding agents to
> do when they get blocked on you, running under your own `gh` credentials; the capture
> skill is one such thing and you can point yours at anything else. If an issue appeared
> that you did not write, an agent wrote it, and that is the system working. openloops
> only reads them back.

The label is the whole storage design. It outlives the session, it is queryable from a
terminal or a phone with every session stopped, and it needs no database to disagree
with:

```bash
gh search issues --owner acme --label manual-task --state open
```

What `openloops` adds to that one-liner is the re-check — and the re-check only works if
the issue carries something to run.

### The field that decides whether an obligation can ever be closed

**An obligation without a predicate can never be re-checked.** It will sit at `open`
forever, correctly, because nothing openloops can run would ever observe it as done. The
capture skill writes these; it is worth two minutes to know what a good one looks like,
because you are the one who will read the count.

Obligations get discharged **out of band.** Somebody adds a deploy key in a web UI,
pays an invoice, answers in chat. None of that emits an event anyone is listening to,
so the issue sits open for months describing something that was done in five minutes.
A stale row annoys; a phantom row destroys the count, and the count is the whole
product.

So each obligation carries its own answer, in its body, as a shell command whose **exit
status is the question**:

```markdown
**Verify:** `gh secret list --repo OWNER/REPO --json name -q '.[].name' | grep -qx PYPI_PASSWORD`
```

The rules the parser actually applies, in the order they bite:

- The field is `Verify:` at the start of a line. The `**` bold markers are optional —
  the field is the contract, not its markup.
- **The predicate is the first backtick code span in the field.** Everything outside it
  is prose.
- **Fenced and indented code blocks are ignored** when looking for the field, so an
  issue that quotes this format in a `<details>` block does not get the example run
  instead of its own predicate.
- **A field that begins `none possible`, `none`, `n/a`, `no predicate` or `not possible` yields no command, even if the prose that follows contains a code span.**
  This matters: the natural way to write that sentence mentions ``gh`` or
  ``true``, and both exit `0`, which would report a live obligation as done. Use it
  for genuine judgement calls.
  Such a field reads `open`, with its prose as the reason. A field that merely *starts
  like* one — `nonexistent: …`, `none of the files remain: …`, `n/a until …` — followed
  by a code span is ambiguous: nothing in it is run, and it reads `?`.
- Otherwise, a field with a backtick but no closed code span is *malformed*, and reads
  `?` rather than `open` — a typo should not look like an answer.

What makes a good one:

- **It observes the world, not the issue.** `gh secret list …`, `curl -fsS https://…`,
  `gh api repos/…`. Never something that reads the issue itself: closing an issue is not
  doing the thing.
- **`0` means done and nothing else.** Non-zero for anything short of done.
- **It fails loudly when it cannot check.** openloops already catches the common
  shapes — exit `126`/`127`, death by signal, and stderr saying `command not found`,
  `bad credentials`, `HTTP 401`, `could not resolve host` and friends — and turns them
  into `?` rather than `open`, because a check that never reached the world has not
  observed anything. Write yours so it lands in one of those rather than silently
  exiting `1`.
- **It finishes fast.** Every evaluation is time-bounded (20s by default) and a timeout
  is `?`, not an answer.

One honest limit: predicates are POSIX shell. On a shell that cannot parse one, the
command exits non-zero and the row reads `open`. That is the safe direction to be wrong
in, and it is why the exit status is always on screen.

## `?` means nothing was checked — read this once

`ol owed` and `ol blocked` each report **three** states, never two, and the third is
`unknown`, printed `?`.

`?` is not a rounding error. A tool that says “nothing owed” because `gh` was missing,
or “nothing is waiting” because the network was down, is worse than no tool: it hands
you a clean board you did not earn, and you stop looking. So `unknown` is never
collapsed into either of the other states — not into the alarming one, not into the
reassuring one — and every row that reads `?` prints *why* on the next line: a timeout,
a missing `gh`, an untrusted owner, a malformed predicate.

When the listing itself fails there are no rows to mark, so the whole command says so
and refuses to print a count:

```default
owed ?  could not check - gh: not logged in
```

That refusal is the single most important design decision in the package, and the read
skill spends more words on it than on anything else: an agent that answers “nothing
owed” when rows read `?` has told the exact lie this package exists to prevent.

One disambiguation, because the character appears in two places: the `?` in the second
column of `ol`’s own output is **not** this. It means low confidence — the session
never said it was finished — and it is explained under `ol` below. The digest half
checks nothing against the world by design, so it has nothing to be unable to check.

## Before you run it: this executes text from an issue body

Evaluating a predicate means **running a command that came out of a GitHub issue** —
whether you typed `ol owed` or an agent did. That is a real capability, and it is
bounded in five ways, all of them visible:

- **Only owners you configured.** A predicate runs only when the issue’s repository
  owner is trusted, which defaults to exactly the owners you searched — so widening the
  search never quietly widens what runs. A row outside that set reads `?`: never
  `open`, because nothing checked it, and never `done`, because nothing ran. In Python
  it is `trusted_owners=`; on the CLI it follows `--owners`.
- **The command is always printed next to its verdict**, in full and never abbreviated,
  so nothing executes invisibly and you can disagree with the answer.
- **`ol owed --no-verify` lists without executing anything.** Every row that has a
  predicate then reads `?`, because that is what is true about it. The read skill is
  told to reach for it on a machine that is not yours, or after you have just added an
  owner whose issues neither of you has read.
- **Every evaluation is time-bounded**, and a timeout is `?` rather than an answer. On
  POSIX the predicate runs in its own process group and the timeout kills the group, so
  anything it started dies with it. On Windows only the shell itself is killed — a
  predicate that backgrounds work can outlive its timeout there. That is a platform
  limit worth knowing rather than a promise broken quietly.
- **`run_predicate=` replaces the evaluator entirely**, and `issues_source=` the reader.

The default is to check, and that is deliberate rather than an oversight: not checking
has a silent failure mode (a count quietly full of things you finished weeks ago) and
checking has a loud one (a command you can see on screen).

---

## The plumbing: the `ol` command

This is what the skills call. It is a perfectly good thing to type yourself — it is how
the author uses it half the time — but if you came here wanting an overview of what your
agents are doing, the section at the top is the one you want.

### Which command answers which question

| You want to know                                            | Run            | Needs `gh`?   |
|-------------------------------------------------------------|----------------|---------------|
| What did my sessions leave open?                            | `ol`           | no            |
| What do I still owe my agents?                              | `ol owed`      | yes           |
| What is waiting on another repo — and what is not any more? | `ol blocked`   | yes           |
| What did my agents hand me lately?                          | `ol published` | yes           |

Everything else is a variation on those:

```bash
ol ls --state all           # every digest, newest first
ol ls --confidence high     # drop the ones open only because nothing said otherwise
ol show 2b1f                # one digest, by session id or a unique prefix
ol status                   # where the digests are, how many, how stale the cache is
ol who-made owner/repo#12   # which session opened this PR (or a branch name): likeliest first
ol dashboard --out b.html   # all three answers as one self-contained HTML page
ol install-job              # run the digest sync every 15 minutes (macOS launchd)
```

Every block of command output below came out of the shipped renderers. Repository,
project and machine names have been replaced with generic ones; nothing else has been
touched.

## `ol` — what your sessions left open

Claude Code keeps a full JSONL transcript of every session, then garbage-collects it
after about a month. Meanwhile the thing you actually wanted from that session — what
it did, what it left for you, how to get back to it — was one paragraph at the end.
`ol` reads the transcripts, writes one short dated markdown digest per session, and
keeps the digests. It is a **retention** device, not a dashboard.

Bare `ol` syncs and then prints what is open:

```default
2026-08-27 10:05   015dcf33  widget                ship the 2.0 parser
2026-08-27 09:53   f8c0b9e2  engine                cross-repo blocker harvest
2026-08-27 09:47 ? 7f400fcb  parser                skill_management
2026-08-26 21:42 ? 8437d111  infra                 sync the staging box
2026-08-26 12:35   8cad34f9  widget                egress scrubbing pass

acme-laptop: 170 sessions scanned, 0 digests written, 170 unchanged, 0 moved; 170 digests in store.
```

Columns: the session’s last turn, a `?` for low confidence, the session id (`ol show`
takes any unique prefix), the project directory, and the session’s own title for
itself.

**The gotcha: `open` here is loop state, never process state.** A `?` in the second
column does not mean the session is running or crashed. It means the session’s own
closing words never said it was finished, so the classifier defaulted to `open`. Five
rules decide it, and the digest always prints which one fired and what cues it saw, so
you can disagree:

| Rule                                                       | Reads as                      |
|------------------------------------------------------------|-------------------------------|
| the last turn is a usage-limit or API-error notice         | `open` — it was cut off       |
| the transcript stops before the assistant’s turn completed | `open`                        |
| the closing line is a question put to you                  | `open`                        |
| the latest cue in the closing lines defers something       | `open`                        |
| the latest cue in the closing lines declares it finished   | `archive`                     |
| nothing decided it, but the session’s own recap does       | either                        |
| nothing decided it at all                                  | `open`, marked low confidence |

**`archive` is earned, `open` is the default.** A session only reaches `archive` by
saying it finished. Against hand-labelled sessions the cue rules never produced a false
`archive` but caught only about half the genuinely finished ones — and that is the right
direction to be wrong in, because a false `archive` buries a loop this tool exists to
surface, while a false `open` only lengthens a list already sorted by recency.

**Conflicts resolve at sentence granularity, and inside a sentence an open cue always
beats a close cue.** Real closing paragraphs carry both kinds:  *“say the word and I’ll
remove it. Nothing is blocking; safe to close”* is finished, and  *“you’re safe to exit …
the two threads waiting for you are”* is not — the last cue-bearing sentence decides
those. But  *“**Needs you** (nothing blocking, all tracked): the #146 decision”* puts the
close cue inside a parenthetical of the sentence that hands work back, so within one
sentence the asymmetry decides instead of position.

Expect most sessions to land in `open/`. That is what agentic sessions do, and a split
that came out balanced would be a split that was lying. `ol ls --confidence high` drops
the ones that are open only because nothing said otherwise — which is also why the read
skill is told to prefer those rows when it summarises what is in flight.

If `open` ever came to mean “a process is running”, this would be a session dashboard.
It is not one, and `claude` already has that view.

**For the live half, there is [crowsnest](https://github.com/thorwhalen/crowsnest).** It reads the session registry and the tail of the same transcripts to say which sessions are running right now and which of them is busy, idle, or stopped waiting on you — and it uses openloops’ own `parse_session` to read them, so the two agree about what a session said. The split is the one this section is about: crowsnest answers *what is running now*, openloops answers *what sessions left open and what you owe them*. A session crowsnest calls idle may still be carrying three open loops, and a loop openloops surfaces may belong to a session that exited a week ago.

### What a digest says — and what it never says

A digest is a dated record of **what one session said**. It carries the session’s last
turn, the prompt that provoked it, a context-compaction summary if the session made
one, and any pull-request links the session recorded for itself. Every heading carries
the timestamp of the thing under it.

It never says that anything is *currently* true. There is no “still open”, no “more to
do”, no “waiting on you” — because `ol` has checked nothing against the world, and a
snapshot presented as a live fact is worse than no snapshot at all. The front matter
says `verified: false` for exactly that reason.

This is the constraint the whole design is arranged around. A tool that quietly tells
you a loop is open when you closed it out of band destroys the count, and the count is
the product. It is also why the other two commands exist: they are the ones that *can*
re-check, and they do.

### Where the digests are stored

```default
~/.local/share/openloops/digests/{source}/open/{session}.md
                                          /archive/{session}.md
~/.local/state/openloops/sync-state.json      ← a cache, not data
```

`{source}` is this machine. Two machines syncing digests into one git repository never
write the same path, so there is no merge to reconcile — the directory layout *is* the
answer to cross-machine sync. The label seeds from the machine’s short hostname and is
then **sticky**, remembered in the state directory: macOS renames a host that collides on
a network, and a label that drifted would silently fork the store into two copies. Every
sync prints the label it is writing under, and `OPENLOOPS_SOURCE` overrides it.

The cache is deliberately somewhere else. Deleting it re-reads every transcript and
must produce byte-identical digests; deleting the digests loses whatever the
transcripts no longer hold. Those are very different operations and they should not
live in the same folder.

Override with `OPENLOOPS_DATA_DIR`, `OPENLOOPS_STATE_DIR`, `OPENLOOPS_SOURCE`.

### Keeping it up to date

```bash
ol install-job              # every 15 minutes: a whenthen job when whenthen is installed (it takes over from the launchd agent), else a launchd StartInterval agent
ol job-status               # scheduled by whom? loaded? when did it last actually write?
ol uninstall-job
```

It is a periodic job, not a daemon, and that is a decision rather than an
implementation detail: a tick that crashes is repaired by the next one, whereas a
resident process that dies leaves its last output behind with nothing scheduled to
correct it. `ol job-status` reports when a tick last *wrote*, because “the job is
registered” and “the job is working” are not the same claim.

The installer is macOS-only. On Linux, put `ol sync` in a systemd user timer or a
crontab line — `openloops` itself is cross-platform.

---

## `ol owed` — what you still owe your agents

When an agent gets blocked on something only you can do — a secret it cannot write, a
permission it does not have, a decision that is yours — the ask usually dies in a final
message nobody re-reads. The fix is not a new database: it is a `manual-task` label on
an issue in the affected repo, filed by the capture skill above.

`ol owed` lists those issues, and runs each one’s check before printing it:

```default
2 open, 1 discharged, 1 unknown
  owners: acme  |  predicates: 3 of 4

open   23d  acme/widget#1              CI secrets are not provisioned on this repo
          verify: gh secret list --repo acme/widget --json name -q '.[].name' | grep -qx PYPI_PASSWORD
                  -> exit 1
open    2d  acme/parser#4              Decide whether the parser ships in 2.0 or waits
          verify: (none)
                  -> none possible - a judgement call.
?      23d  acme/widget#9              Doctests depend on a live third-party HTTP fetch
          verify: python3 -m pytest -q --doctest-modules --pyargs widget.remote
                  -> the predicate timed out after 20s
done   30d  acme/engine#7              Add a deploy key so CI can clone the fixture repo
          verify: [ "$(gh api repos/acme/engine/keys --jq length)" -gt 0 ]
                  -> exit 0
```

| Printed   | State        | Means                                                                                               |
|-----------|--------------|-----------------------------------------------------------------------------------------------------|
| `open`    | `open`       | no predicate at all, or the predicate ran and returned non-zero                                     |
| `done`    | `discharged` | the predicate returned `0` — the ask is finished, the issue is merely still open                    |
| `?`       | `unknown`    | nothing could be checked: no `gh`, no network, a timeout, an untrusted owner, a malformed predicate |

`done` rows are reported, never acted on. A passing predicate is evidence, not
authority; you close the issue, or you don’t. The read skill is told the same thing in
the same words, because a model that closes an issue on a shell exit status has written
a record nobody can audit back.

```bash
ol owed                     # list them, and re-check each one against the world
ol owed --no-verify         # list them, executing nothing — every predicate row reads ?
ol owed --owners acme,widgets
ol owed --limit 100
```

Writing the `**Verify:**` predicate is covered above, under the capture skill; so is
what it means that running one executes text out of an issue body.

---

## `ol blocked` — what is waiting on another repo, and what is not any more

The same shape, pointed at a repository instead of at a person.

An agent working in repo X finds that the real fix belongs in repo Y. It files in Y,
writes a workaround in X, and moves on. Y gets fixed. **X is never told.** Nobody was
blocking, nothing waited on a human, so the loop is invisible to `ol owed` — and the
workaround in X quietly becomes architecture, noticed months later only when somebody
asks why the code looks like that.

GitHub already models the edge, and it already crosses repositories: an issue’s
**blocked-by dependencies** name each blocker’s own repository, number and state. They
are a first-class GitHub field, set on the issue itself in GitHub’s own UI, not a
convention openloops invented — the representation costs nothing and exists today.
**What is missing is the harvest**: nothing notices when a blocker closes, because the
edge is queryable, not eventful.

`ol blocked` is that harvest:

```default
1 unblocked, 2 blocked, 0 unknown
  scope: acme, widgets  |  candidates: 4  |  1 had no dependency edge at all

ready    8d  acme/widget#109              Drop the rename workaround once the engine lands it
        blocked by: acme/engine#15 [closed]
                    -> free for 5d, and nothing has said so
waits    8d  acme/widget#27               Criteria carry a structured definition, not free text
        blocked by: acme/engine#61 [open]
waits    8d  acme/widget#34               Track the six facade gaps, and which phase each one blocks
        blocked by: widgets/aix#40 [open] widgets/aix#41 [open]
```

| Printed   | State       | Means                                                                                                                                                                       |
|-----------|-------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `ready`   | `unblocked` | every blocker is closed. The work can proceed and nobody has been told — **this is the row the command exists for.** It sorts first and says how many days it has been free |
| `waits`   | `blocked`   | at least one blocker is still open, and the row names which, with the foreign repository                                                                                    |
| `?`       | `unknown`   | the edges could not be resolved                                                                                                                                             |

`ready` is a finding, not an instruction. The workaround in X may still be the right
code; only you know that.

```bash
ol blocked                                  # search a fleet, resolve every edge
ol blocked --owners acme,widgets
ol blocked --repos acme/widget,acme/engine  # the audit path: enumerate these exactly
ol blocked --no-resolve                     # spend nothing; every row reads ?
ol blocked --limit 100
```

### The gotcha: discovery is a candidate list, not an answer

Finding the blocked issues has two implementations, and which one runs depends on
whether you passed `--repos`.

**Across a fleet** (the default): one `gh search issues` call carrying GitHub’s own
`is:blocked` qualifier. One request answers for every repository, which is what makes
this cheap enough to run at the start of a session. But the qualifier is a *search
index*, and a search index is not the dependency graph. Measured on one real fleet on
2026-08-27, scoped to three owners: `is:blocked` returned 15 open issues, of which **10
carried a blocked-by edge and 5 carried no dependency edge of any kind** — not a stale
edge, and four of the five carry no sub-issue relation either, simply none. Recall was perfect
on that fleet: all 10 were found, checked against a full per-repository enumeration of
821 open issues across 148 repositories. Precision was 10/15.

So every candidate is re-resolved against the dependency graph itself, and one with no
edge is dropped and *counted* — that is the `1 had no dependency edge at all` note in
the header. A discovery step that quietly disagrees with reality is the same class of
defect as a count that cannot say `?`.

**Per repository** (`--repos owner/name,owner/other`): one paginated listing per
repository, filtered on the dependency counts GitHub already returns on every row of
it. This reads the counts themselves rather than an index of them, so it cannot
over-report and cannot miss. It is the audit, not the daily command.

### What it costs

Resolving edges is **one API call per candidate** — there is no batch form. `--limit`
is that bound and it defaults to 50; one more than it is requested, so a candidate list
that saturates its own cap comes back marked `TRUNCATED` and the counts are then a
**floor**, never a total. At the default that is at most 51 requests against a
5000/hour limit. A 15-candidate fleet run took 41-48 s wall-clock across several runs here.

`--no-resolve` skips all of it and every row reads `?`, which is honest and free.

---

## `ol dashboard` — the same four registers as one page

```bash
ol dashboard --out board.html
```

All three answers rendered as one self-contained HTML document: no stylesheet, no
script, no font, no request to anywhere. It is the page you leave open on a second
monitor, or publish somewhere your phone can reach.

Being self-contained is what makes it publishable, and it is also its one limit: **a
page cannot re-check anything.** So it stamps the moment it was made and says
“snapshot” in its largest type, and its fourth register is `Unknown` — every `?`, with
why, including the envelope-level failures. An `owed` that could not list is not
“nothing owed”, and rendering that as a `0` would make the page worse than no page.
When the count really is zero the section names which checks earned it.

Everything printed goes through the same scrubber that guards the digests, plus HTML
escaping and a scheme allowlist on every link. `--fragment` drops the document scaffold
for a host that supplies its own `<head>`.

---

## `ol board-*` — a task board you can clear from a phone

```bash
ol board-gather --all-kinds --out work/candidates.json
ol board-classify work/candidates.json --out work/records.json
ol board-build work/board work/records.json -c work/candidates.json --session my-desk
```

Every open item across your owners that asks something of you (the `manual-task` issues, issues titled “Decide…”, PRs waiting on your review) becomes a task record: what to do in one line, where (`tap`, `browser`, `session`, `physical`, `mac-only`), how long, the exact settings page to open, and a paste-ready prompt when a session should do it. Repeated chores are grouped into runs (the same npm form for twelve packages is one sitting), and the result is a static page with its data files, meant to be published as a claude.ai Artifact with a `db` capability.

`board-gather` queries each owner separately with no 50-row cap and reports a query that hits the search API’s ceiling as `saturated` rather than truncating it; `--exclude-repos 'org/*'` (or `OPENLOOPS_EXCLUDE_REPOS`) keeps repositories off the board. `board-classify` is a deterministic heuristic with no model; `--enriched 'batches/out_*.json'` lays records written by the shipped classifier brief over it. `board-build` writes only into the directory you name: the board holds titles from your repositories, so keep it out of any repo.

The taps on the page become GitHub comments, closed issues and dispatched workers only through a Claude session following the `openloops-phone-board` skill. openloops code never does it ([ADR-008]()).

**On your own website.** `ol board-build --store http --api /your/prefix/board-store` wires the page to a small document-store API instead of the Artifact store. `pip install openloops[server]` adds `openloops.board_server.mk_app`, a FastAPI app serving the board files and that API under the store rules of `openloops.board_store` (events immutable, drafts newest-wins, receipts written only by the receiver, which never writes events outside a migration import). It authenticates nobody: put it behind your own login and map each identity to `viewer` (you) or `receiver` (the receiving session’s account) in its `role_of` ([ADR-009]()).

**A receiver on a timer (macOS).** `ol install-receiver-job WORK_DIR` installs a job (a whenthen job when whenthen is installed, else a launchd agent) that, every five minutes, asks a self-hosted board store over HTTPS, with no model, whether any tap is waiting, and when none is, writes the board’s heartbeat. Only when something is waiting does it start `claude -p` with the receiver procedure, capped at `--max-budget-usd` (that tick’s session only, not the workers it dispatches). Credentials stay in `~/.config/openloops/board-receiver.env` (mode 600), never in the job. Check with `python3 -m openloops.receiver_tick --check-only` and `ol receiver-job-status`; remove with `ol uninstall-receiver-job`. This is the one part of openloops that reaches the network or starts a model, and only once you install it ([ADR-011]()).

## `ol remind` — a reminder that fires while your laptop sleeps

```bash
pip install 'openloops[remind]'            # adds correspond, which delivers through ntfy (Python 3.11+)
ol remind "Stretch" --when 20m --reveal    # a duration: 20m, 3h, 2d, 1h30m
ol remind "Call back" --when 15:30         # a time today (tomorrow if passed), an ISO date (09:00) or date-time
ol loops                                   # open reminders, soonest first
ol snooze <id> 1h                          # or: ol snooze <id> 18:00
ol done <id>                               # close it (see the note below on early cancels)
ol install-remind-job                      # macOS: the hourly tick (needed for reminders more than 3 days out)
```

A reminder is a **loop**: one record per commitment, kept as a JSON file under `~/.local/share/openloops/loops/`. Its lifecycle uses the same seven A2A state names as the equerry desk’s items (scheduled is `submitted`, fired is `input-required`, done is `completed`), and it has the fields of a Getting Things Done item (list, contexts, project, energy, waiting-for). The design is [ADR-013]().

### Organising your loops: GTD, behind a seam

How loops are organised is a **method**, passed as one keyword argument (`method=`); the record does not know which one is in use ([ADR-017]()). Every method studied (GTD, PARA, Zettelkasten, the Bullet Journal, Personal Kanban, the Eisenhower matrix) does some of five things: capture, clarify, organise, review, engage ([the comparison]()). The default, and the only method built, is Getting Things Done:

```bash
ol method                                            # GTD's lists and its clarify questions
ol remind "Learn the cello" --place someday          # file on a list other than Next
ol clarify '{"actionable": true, "delegate_to": "Ann"}'   # where GTD's decision tree sends it (stores nothing)
ol organise <id> waiting --waiting-on Ann --chase 3d # move a loop, by the method's rules
ol capture "Book the dentist" --by my-agent          # an agent's capture: a proposal on In, never pushed
ol organise <id> next --accept                       # accept a proposal (your yes)
ol cancel <id>                                       # trash: withdrawn, not done
ol review                                            # the weekly review as exceptions: in, overdue, to chase, stalled projects, someday
ol engage --context @phone --minutes 20 --energy low # what to do now: context, time, energy, then priority
```

Agents do the clerical half (capture with a source, a proposed clarification, the review prepared in advance); a loop an agent made is a proposal until you accept it (`--accept`), and a proposal never pushes. Another method is a class with the same five operations (`openloops.method.Method`), passed as `method=`.

How it survives a sleeping machine: a reminder due within three days is handed to ntfy at once as a *scheduled* message, whose sequence id is the loop’s id. ntfy delivers it at the time whatever your laptop is doing. `ol done` and `ol snooze` cancel or replace it under the same id, but ntfy.sh does not honour that today (measured 2026-11-19): the original push may still arrive, and both commands say so when it can. The hourly tick arms reminders as they come within three days (ntfy’s limit), records the ones that fired, and delivers late, saying how late, anything that was never armed.

**What the push says.** The topic is correspond’s default ntfy topic (`NTFY_TOPIC`, else the Keychain). ntfy.sh is a public relay, so a push says only “A reminder you set is due” unless the reminder was made with `--reveal`; then the title travels too. Reveal short labels only.

Settings come from the environment: `OPENLOOPS_TZ` (an IANA zone for reading and echoing times; default this machine’s), `OPENLOOPS_REMIND_CHANNEL` (a correspond reference, default `ntfy:`), `OPENLOOPS_REMIND_HORIZON_HOURS` (default 72). The seams (`store=`, `deliver=`, `settings=`) are keyword arguments of `openloops.remind`’s functions.

## The pile — capture anywhere, clarify later

The GTD *In* list, kept as one GitHub issue per capture in a private repo of yours (default `<your login>/_pile`, or `OPENLOOPS_PILE_REPO`). Anything that can send a request to the GitHub issues API can capture: an Apple Shortcut (“Hey Siri, add to my pile”), the `gh` CLI, a script. Each capture carries the label `pile` and, optionally, a routing hint label. Nothing in openloops runs on capture: no Action, no webhook.

```bash
ol pile                     # what is on it, oldest first (read-only)
ol pile-show 12             # one item with its comments: who handled it and where it went
ol pile-propose             # a free first guess per item: loop, idea, issue or ask
ol pile-plan 12 drop --reading-file r.md --reason "not a capture"  # the signed steps, as JSON
ol pile-sign --text-file note.md --by my-session --to-repo o/r      # a signed progress note
ol pile-nudge               # keep one reminder pending while items wait over 3 days
ol install-pile-nudge-job   # macOS: run the nudge every six hours
```

**openloops reads and plans; it never writes to GitHub** ([ADR-014]()). `ol pile-plan` returns the steps that carry out one decision (make a loop, add an idea, open an issue, comment, change labels, close), and the caller runs them with its own tools: `gh` in an agent session, the connector’s own tools on a voice surface. Every comment in a plan is signed with the agent’s name and, on a private repo of the pile’s owner, its session link, so an item’s development can be traced back to who did it. Anything else (a public, internal or someone else’s repo, or one whose visibility cannot be read) gets only the text the caller wrote for it. The pile itself must be private.

Emptying the pile is on demand. Ask your agent “what’s on my pile”, “go through my pile” or “take care of pile item 12”: the `openloops-pile` skill (installed by `ol install-skills`) proposes where each item belongs, acts after your one “yes”, and closes each pile item with a signed comment linking where it went. A pile item is never edited and never closed without a comment.

## Turning it off

Nothing here runs unless you type it, or an agent you installed a skill for does. There
are two exceptions, both opt-in: `ol install-job` puts the digest sync on a timer, and
`ol install-receiver-job` runs a phone board’s receiver on one. Check with
`ol job-status` and `ol receiver-job-status`; if both say the plist is absent, nothing
of openloops is running in the background at all.

```bash
ol uninstall-job            # stop the timer, if you ever installed it
ol uninstall-receiver-job   # stop the board receiver, likewise
rm -rf ~/.claude/skills/openloops ~/.claude/skills/openloops-needs-human \
       ~/.claude/agents/openloops-sweep.md      # the skills are three symlinks
pip uninstall openloops     # remove the package
```

`pip uninstall` leaves your digests where they are — `~/.local/share/openloops/` by
default, or wherever `OPENLOOPS_DATA_DIR` points — because deleting a record is not part
of removing a tool. Delete that directory yourself if you want the data gone too.

Nothing needs undoing on GitHub. openloops never wrote anything there: no issue was
created, closed, relabelled or commented on, and the `**Verify:**` lines in your issue
bodies were put there by whoever wrote them, not by this package.

## Which repositories all this is about

`ol owed` and `ol blocked` answer about the same fleet, resolved the same way, so the
two can never quietly disagree about which repositories exist. Three sources, first one
wins:

1. `OPENLOOPS_OWNERS` — comma- or space-separated (or `--owners` on either command).
2. The owners named by a `gh` alias called `owe`, if you have one. A fleet of several
   organisations is usually already written down there, and disagreeing with the thing
   you actually type is how a count goes quietly wrong.
3. The login `gh` is authenticated as.

Whichever it was is printed on every result, so a partial answer is a visible one. It is
worth setting explicitly: the fallback is your personal login, and if you work across an
organisation, a count that only ever saw your own repositories looks clean and is wrong.
The read skill is told to check that line and say so.

## Python API

```python
import openloops

openloops.sync()  # read transcripts → write digests
for row in openloops.ls(state="open"):  # what your sessions left open
    print(row["session"], row["title"])

print(openloops.show("2b1f")["text"])  # one digest, in full

report = openloops.owed()  # open `manual-task` issues, each re-checked
print(report["counts"])  # {'open': 2, 'discharged': 1, 'unknown': 1, ...}

report = openloops.blocked()  # cross-repo blocker edges, every one resolved
print(
    [
        r["repo"] + "#" + str(r["number"])
        for r in report["rows"]
        if r["state"] == "unblocked"
    ]
)

openloops.install_skills(dry_run=True)  # the plan, having touched nothing
```

`owed()` and `blocked()` return an **envelope, never a bare list** — because a caller
has to be able to tell “nothing is owed” from “I could not find out”:

```python
{
    "listed": True,  # False ⇒ the listing/discovery itself failed; the counts mean nothing
    "checked": True,  # blocked() calls this "resolved"
    "error": "",
    "truncated": False,  # the result set hit its cap: the counts are a floor
    "owners": [...],
    "counts": {...},
    "rows": [...],
}  # every row carries every documented key, present and empty if unset
```

Check `listed` before you read `counts`. That is the whole contract.

What a person asked, and what came back, is read out of a transcript as facts, with no model:

```python
from openloops.exchanges import exchanges, load_records

for e in exchanges(load_records(path)):  # one per prompt, in time order
    if e.questions:  # the sentences of a person's prompt that ask something
        print(e.questions, "->", e.reply[:80])  # the reply its turn ended with
```

`origin` says who started the turn: `human`, `peer` (another session’s message, `sender` names it) or `system` (a notification or a headless run). Only a human prompt is searched for questions, and requests phrased as questions (“can you fix it?”), tags, headings, quotes and code are skipped. Three more facts say where the answer is and whether anyone came back to it: `reply_uuid` (the id of the record `reply` came from), `texts` (every text of the turn in order, `reply` being the last, so an answer given before further work is not lost) and `followed_up_at` (when a typed prompt next arrived in that session, empty if none did; a notification or another session’s message does not count). All three default to empty and `as_dict()` carries them. Deciding what a doubtful sentence means, or finding an answer given in another session, is left to the consumer ([crowsnest](https://github.com/thorwhalen/crowsnest) does both).

### A session as a page

`ol page <session> [--focus <turn>] [--out FILE]` renders one session as a single readable page (ADR-016); `openloops.session_page.session_page(records, focus=None, sanitizer=...)` is the pure function behind it (no file read, none written).

- One block per turn of the main thread: the prompt (typed, from another session by name, or from tooling; the sentences that ask something are marked), then every text the session wrote, and each tool call as one line. Tool results, thinking, sub-agent threads and injected text are left out; a compaction summary is labelled.
- **Anchor format: `t-<id of the prompt record>`** (`Exchange.uuid`; characters outside `A-Za-z0-9_-` become `_`). `openloops.session_page.turn_anchor(uuid)` builds it, so a link is `<page address>#t-<id>`. The turn the address points at is highlighted by the browser’s `:target` rule; `--focus <id>` also gives that turn the class `focus`.
- No script, no external request, no event handler: the page can be served under the strictest content policy.
- Credential-shaped text is withheld per field, before anything is cut, and the page says “N passages withheld”. Over a size bound the page keeps the turns around `--focus` (the latest turns without one) and counts what it left out.
- **A page is private data**: the words of a session, for the person who ran it. Keep it where only you can read it. The package writes it only where you say, never publishes or uploads it, and a page is never a fixture, a docs example or an attachment to an issue.

`openloops.tools` is the single dispatch list every surface goes through — the `ol`
command today, an MCP server or an HTTP endpoint later. Operations go there, never
straight into the CLI, which is what stops two surfaces from drifting apart.
`install_skills` is deliberately *not* in it: “symlink files into this machine’s agent
config” is not an operation a remote surface could honestly offer.

## The seams

Each is one keyword argument, and each defaults to a real implementation rather than a
stub wearing a keyword argument as a disguise:

```python
openloops.sync(
    transcript_source=my_sessions,  # any Mapping[str, Session]
    digests_store=my_store,  # any MutableMapping[str, str]
)

openloops.owed(
    issues_source=[...],  # a list of dicts, or any callable
    run_predicate=lambda cmd: 0,  # any callable from command to exit status
)

openloops.blocked(
    issues_source=[...],
    blockers_source={"acme/widget#12": [...]},  # or any callable of (repo, number)
)
```

`transcript_source=` defaults to a direct reader of Claude Code’s on-disk layout.
`digests_store=` defaults to a `dol` store over a directory of markdown files, with its
encoding pinned to UTF-8 and its delete made a real delete. Point it at an S3-backed
store, or at a git-synced directory shared between machines, and nothing else changes.

`issues_source=` and `run_predicate=` default to a `gh` search and a time-bounded
subshell; `blockers_source=` to the dependency-graph call. **With them injected, the
GitHub half needs no network and no `gh` on PATH** — which is how the whole of it is
tested.

Pass `state_dir=` too when you swap a digest seam in a test: the change-detection cache
is separate from both, and left alone it would record your fixture’s revisions in the
real one.

## Nothing leaves without being scrubbed

Transcripts are the highest-entropy secret source on a developer machine: pasted
tokens, `.env` contents, tracebacks full of absolute paths. A digest store can be a
synced git repository, so **a written digest is an export surface**, and the discipline
belongs before the first byte is written rather than before the first push.

- Absolute paths under your home directory are rewritten to `~`-relative.
- Credential-shaped text **raises**. It is never silently redacted, because a silent
  redaction teaches nobody that a secret was there. That session is skipped, the run
  says so and exits non-zero, and the error names the pattern class and offset without
  ever quoting the match.

The same two rules are what the capture skill applies to an issue title and body before
it files anything, through the same `openloops.egress` functions — so an agent that
gets blocked while holding a token in its context cannot publish it by accident, and
cannot mask it and file anyway either.

## Why not just read the transcripts, or use `gh` directly?

For the digests: `claude` shows you your live sessions, which is a different question —
and a better answer to it than this could be. The transcripts themselves answer the
question `ol` answers, right up until they are deleted. A digest is a few hundred bytes
and outlives the megabyte it came from.

For the other two: the query is one line of `gh` and always was. The whole of what
openloops adds is **the re-check** — running the predicate, resolving the edge — and
the refusal to round an unchecked row into an answer. That is the entire difference
between a list and a count you can act on.

There is one caveat worth knowing before you read a digest as a diary: a Claude Code
*session* is not a sitting. Sessions get resumed, so a single session can span days,
and a digest keyed on one is a digest of a thread of work rather than of an afternoon.

## The name

Two live collisions, both deliberate, both worth knowing before you search for it:

- **OpenLoops** is an established particle-physics one-loop amplitude library
  ([openloops.hepforge.org](https://openloops.hepforge.org)). It is not on PyPI, and it
  is what a web search will find first.
- **openloops** is also [a browser-history tool](https://github.com/sholajegede/openloops)
  that groups your browsing into what you were trying to do — an adjacent product using
  the same metaphor, in a different distribution channel.

Neither blocks `pip install openloops`. The command is `ol` because a read path that
costs eighteen characters to reach is a read path that does not get reached.

## Design tests

These are tests in the suite, not aspirations:

- **A digest is derived, never authored.** Delete the digest store and the cache, sync
  again, and every digest whose transcript still exists comes back byte-for-byte.
  Digests whose transcripts have since been collected are *retained* — that is the
  point of the tool — and `ol status` counts them separately.
- **The suite passes with no network, no credentials, and no `~/.claude` present.**
- **`import openloops` does not import the CLI library**, and opens no socket. The core
  has no opinion about how it is called, and a job on a plane still has to run.
- **Nothing in this repository carries an absolute home path or credential-shaped
  text** — checked mechanically, by the same code that scrubs your digests. The shipped
  skills are in the repository, so they are checked by it too.
- **No surface exposes an operation that writes.** Enforcement is by omission: there is
  no `close`, no `comment`, no `POST`. A test walks the source and fails the build if a
  mutating verb or a mutating `gh` argument appears anywhere in the package.
- **`ol install-skills` never overwrites anything.** An occupied destination reads
  `conflict` and is left exactly as it was; a second run of a clean install reads `ok`
  and writes nothing.
- **`unknown` never becomes `open`, `discharged`, `blocked` or `unblocked`**, and a
  listing that failed prints `?` rather than a count. Both are tested directly, because
  they are the two ways a tool like this becomes a liar.

## License

Apache-2.0.

## Scheduling: whenthen first

The five installers (`ol install-job`, `install-remind-job`, `install-pile-nudge-job`, `install-receiver-job`, `install-refresh-job`) register a [whenthen](https://pypi.org/project/whenthen/) job named after the launchd label (`openloops-remind-tick` for `openloops.remind-tick`) when `python -m whenthen --help` works, and remove the launchd agent first (it is installed again if the add fails). Without whenthen, or with `--use-whenthen false`, they install the launchd agent as before. Secret-like variables (`NTFY_TOPIC`) go to `~/.config/openloops/job.env` (mode 600) and are read with `--env-file`, never stored in the job. The receiver job runs `python -m openloops.receiver_tick --session`, which builds the packaged `claude -p` command itself. `ol job-status` and `ol receiver-job-status` report the whenthen job first; the uninstall verbs remove it.

<p class="epythet-aggregates">This documentation as a single file: <a href="openloops.md">openloops.md</a> (Markdown, for agents).</p>


# _autosummary/openloops.base.html.md

# openloops.base

Data structures shared across openloops: what a session is, and what a digest is.

Nothing here does I/O and nothing here makes a judgement. [`openloops.transcripts`](_autosummary/openloops.transcripts.html.md#module-openloops.transcripts)
reads sessions, `openloops._classify` judges them, [`openloops.digest`](_autosummary/openloops.digest.html.md#module-openloops.digest) renders
them, and all three speak in the types defined here.

The types are deliberately flat and JSON-shaped. A session read from Claude Code’s
on-disk state and a session supplied by some other reader are the same object to the
rest of the package — that is what makes `transcript_source=` a one-argument swap.

### Module Attributes

| [`OPEN`](_autosummary/openloops.base.html.md#openloops.base.OPEN)    | the session's own last word left something for the human.   |
|----------------------------------------------------------|-------------------------------------------------------------|
| [`ARCHIVE`](_autosummary/openloops.base.html.md#openloops.base.ARCHIVE) | the session's own last word closed out.                     |
| [`STATES`](_autosummary/openloops.base.html.md#openloops.base.STATES)  | The two loop states, in the order they are shown.           |

### Classes

| [`Digest`](_autosummary/openloops.base.html.md#openloops.base.Digest)(key, text, session_key, source, state)   | One rendered digest: its store key and its markdown text.                   |
|--------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------|
| [`Locator`](_autosummary/openloops.base.html.md#openloops.base.Locator)(type[, url, text, at])                  | A typed, human-readable pointer to something outside the digest.            |
| [`Session`](_autosummary/openloops.base.html.md#openloops.base.Session)(key[, title, ai_title, cwd, ...])       | What one Claude Code session's persisted state says, parsed but not judged. |
| [`Verdict`](_autosummary/openloops.base.html.md#openloops.base.Verdict)(state, reason[, cues, at, confidence])  | A loop-state judgement, with the rule that produced it and the cues it saw. |

### openloops.base.ARCHIVE *= 'archive'*

the session’s own last word closed out.

* **Type:**
  Loop state

### *class* openloops.base.Digest(key, text, session_key, source, state, verdict=<factory>)

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

One rendered digest: its store key and its markdown text.

`text` is a pure function of the [`Session`](_autosummary/openloops.base.html.md#openloops.base.Session) it was built from. It carries
no generation timestamp, which is what lets the regeneration test in
`tests/test_sync.py` compare bytes rather than fields.

#### as_dict()

JSON-ready form (without the markdown body).

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]

### *class* openloops.base.Locator(type, url='', text='', at='')

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

A typed, human-readable pointer to something outside the digest.

The exportable half of ADR-015’s evidence split: a short typed reference that
another tool (or a person) can resolve, never a content hash and never a byte
offset into a file that is garbage-collected after thirty days.

```pycon
>>> Locator("pr", url="https://github.com/o/r/pull/1").as_dict()["type"]
'pr'
```

#### as_dict()

JSON-ready form.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]

### openloops.base.OPEN *= 'open'*

the session’s own last word left something for the human.

* **Type:**
  Loop state

### openloops.base.STATES *= ('open', 'archive')*

The two loop states, in the order they are shown.

### *class* openloops.base.Session(key, title='', ai_title='', cwd='', project='', git_branches=(), started_at='', ended_at='', last_turn_at='', last_user_prompt='', last_prompt_at='', last_assistant_text='', recap='', recap_at='', compaction='', compaction_at='', turn_count=0, model='', ended_mid_turn=False, ended_with_error=False, locators=(), refs=())

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

What one Claude Code session’s persisted state says, parsed but not judged.

Every field is a *fact read from the transcript*, never an inference about the
world. `last_assistant_text` is what the session said last; it is not a claim
that the thing it describes is still true.

`key` is the session id. It is the only identifier openloops uses, and per
ADR-014 nothing in the model hangs off it: a digest is a view keyed by session,
not a record owned by one.

#### as_dict()

JSON-ready form (`asdict` already flattens the nested locators).

`refs` is left out: it is unbounded and belongs to the provenance index, not
to anything rendered from a session.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]

#### compaction *: [str](https://docs.python.org/3/builtins/stdtypes.html#str)* *= ''*

The context-compaction summary, a different and much longer thing than the recap,
covering only the part of the session that preceded it.

#### ended_mid_turn *: [bool](https://docs.python.org/3/builtins/functions.html#bool)* *= False*

The transcript’s final conversational record is an unanswered human prompt, or an
assistant tool call whose result never arrived — i.e. the session stopped mid-turn.

#### ended_with_error *: [bool](https://docs.python.org/3/builtins/functions.html#bool)* *= False*

The last thing the session said is a usage-limit or API-error banner rather than
the assistant’s own words: it was cut off, not finished.

#### *property* git_branch *: [str](https://docs.python.org/3/builtins/stdtypes.html#str)*

The branch the session opened on — the one that names it, when several ran.

A third of sessions touch more than one branch, so a single value is a summary
rather than a fact; `git_branches` is what carries the truth.

#### *property* heading *: [str](https://docs.python.org/3/builtins/stdtypes.html#str)*

its description, else its label.

* **Type:**
  What to call this session in prose

#### recap *: [str](https://docs.python.org/3/builtins/stdtypes.html#str)* *= ''*

Claude Code’s own end-of-turn recap (its `away_summary` record) — one to three
sentences it wrote itself, usually naming what it thought came next. Reading it
is retention, not duplication: it was generated and billed once already, and it
disappears with the transcript.

#### refs *: [tuple](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[Any](https://docs.python.org/3/library/typing.html#typing.Any), ...]* *= ()*

Every pull request and branch the transcript refers to, unbounded, for the
reverse index in [`openloops.provenance`](_autosummary/openloops.provenance.html.md#module-openloops.provenance). Not rendered into the digest.

### *class* openloops.base.Verdict(state, reason, cues=(), at='', confidence='high')

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

A loop-state judgement, with the rule that produced it and the cues it saw.

`reason` and `cues` exist so a reader can disagree. A classification whose
grounds are not shown is an assertion, and openloops does not make assertions
about sessions — it reports what they said and why it read them that way.

#### as_dict()

JSON-ready form.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]

#### at *: [str](https://docs.python.org/3/builtins/stdtypes.html#str)* *= ''*

When the text this verdict was read from was written. Usually the closing turn,
but the recap rule reads text written later, and a heading dated to the wrong
moment is exactly the thing ADR-005 forbids.

#### confidence *: [str](https://docs.python.org/3/builtins/stdtypes.html#str)* *= 'high'*

`"high"` when a rule actually fired, `"low"` when the state is the default
and nothing in the transcript supported it. A classifier that hides which of the
two it did is claiming knowledge it does not have.


# _autosummary/openloops.blockers.html.md

# openloops.blockers

The other kind of open loop: the one that points at a repository, not at a person.

An agent working in repo X finds that the real fix belongs in repo Y. It files in Y,
writes a workaround in X, and moves on. Y gets fixed. **X is never told.** Nobody was
blocking, nothing waited on a human, so the loop is invisible to [`openloops.owed()`](_autosummary/openloops.html.md#openloops.owed)
— and the workaround in X quietly becomes architecture, noticeable months later only
when somebody asks why the code looks like that.

GitHub already models the edge, and it is already cross-repo: the
`dependencies/blocked_by` collection on an issue answers with each blocker’s own
repository, number and state. The representation costs nothing and exists today.
**What is missing is the harvest** — nothing notices when a blocker is resolved,
because the edge is queryable, not eventful. Closing an issue in Y emits no event that
anything in X is listening to, exactly as setting a secret emits none that
[`openloops.obligations`](_autosummary/openloops.obligations.html.md#module-openloops.obligations) could hear. This module is that harvest and nothing else.

[`blocked()`](_autosummary/openloops.blockers.html.md#openloops.blockers.blocked) lists the open issues across a fleet that carry a `blocked_by` edge,
resolves every edge, and reports **three** states — never two:

| `unblocked`   | every blocker is closed. *This is the row that matters*: the work<br/>can proceed and nobody has been told. It sorts first, and it<br/>carries `unblocked_days` — how long it has been free.   |
|---------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `blocked`     | at least one blocker is still open. The row names which, with the<br/>foreign repository, because “who am I waiting on” is the second<br/>question a reader has.                               |
| `unknown`     | the edges could not be resolved. Displayed as `?`.                                                                                                                                             |

`?` is not a rounding error, it is the whole point. A run that could not reach the
dependency graph must not report a clean board, so nothing here is allowed to collapse
`unknown` into `unblocked` or into `blocked`.

**Nothing here mutates anything.** An `unblocked` row is a finding, not an
instruction: the workaround in X may still be the right code, and only a human knows.
You are shown the edge, the blocker’s state and the date it closed, and you decide.

## Discovery is a candidate list, not an answer

Finding the blocked issues in the first place has two implementations here, and which
runs is decided by whether `repos=` is given.

**Across a fleet** (`owners=`, the default): one `gh search issues` call carrying
GitHub’s own `is:blocked` qualifier. One request answers for every repository, which
is what makes this cheap enough to run at the start of a session. But the qualifier is
a *search index*, and a search index is not the dependency graph. Measured on one real
fleet on 2026-08-27, scoped to three owners: `is:blocked` returned 15 open issues, of
which \*\*10 carried a `blocked_by` edge and 5 carried no dependency edge of any kind\*\*
— not a stale edge, and four of the five carry no sub-issue relation either (the fifth, checked, has two sub-issues, which is a correlation rather than an explanation, since its parent has no dependency edges), simply none. Recall
was perfect on that fleet: all 10 were found, checked against a full per-repository
enumeration of 821 open issues across 148 repositories. Precision was 10/15.

So a candidate is a *candidate*. Every one is re-resolved against
`dependencies/blocked_by`, which is the graph rather than an index of it, and one
with no edge is dropped and counted as `without_edges` — visible in the envelope and
printed by the CLI, because a discovery step that quietly disagrees with reality is the
same class of defect as a count that cannot say `?`. The recall figure is one
measurement on one fleet on one day and nothing here treats it as a guarantee, which
is what the second implementation is for.

**Per repository** (`repos=`): one paginated REST listing per repository, filtered on
the `issue_dependencies_summary` GitHub already returns on every row of it — its
`blocked_by` count is the blockers still open and `total_blocked_by` is all of
them. This reads the dependency counts themselves rather than an index of them, so it
cannot over-report and cannot miss; it is the per-repo enumeration ADR-005
`github-authoritative` requires of anything that must not lose a row, since the
search API is hard-capped at 1000 results. It costs one request per hundred open
issues in each repository you name, so it is the audit, not the daily command.

## The N+1, and what bounds it

Resolving edges is **one API call per candidate** — there is no batch form. `limit=`
is that bound and it defaults to `DFLT_CANDIDATE_LIMIT`; one more than it is
requested, so a candidate list that saturates its own cap comes back `truncated:
True` and every surface says so. When the bound is hit the count is a **floor**, never
a total: rows past the cap are not resolved, not guessed at, and not counted. At the
default that is at most 51 requests against a 5000/hour core limit, which per ADR-005
is read from each response’s own `X-Ratelimit-*` headers rather than from the
rate-limit endpoint — a claim this module keeps by never asking for the number at all.

**Kill criterion** (this ships on an argument, so it names in advance what would retire
it): if, ninety days after this ships, `counts['unblocked']` has never once been
non-zero on a real run, delete it. Its entire reason to exist over `gh search issues
-- 'is:blocked'` is finding the row that became free while nobody watched; with no
such row it is a slower alias that draws a table. Removal is one command — delete this
module and `tests/test_blockers.py`, and drop `blocked` from
`openloops.tools._dispatch_funcs`, from `openloops.__main__._commands` and from
`openloops.__init__`. Nothing imports it, nothing persists, and no other module
changes.

**What this is not.** It is a *reader*, like everything else here. No store, no schema,
no history, no event log, no local copy of the dependency graph: the edge on GitHub
**is** the record. Deleting this module loses no data.

```pycon
>>> from datetime import datetime, timezone
>>> candidates = [
...     {'number': 12, 'title': 'Drop the workaround once the engine lands',
...      'url': 'https://github.com/acme/widget/issues/12',
...      'createdAt': '2026-07-01T00:00:00Z',
...      'repository': {'nameWithOwner': 'acme/widget'}},
...     {'number': 13, 'title': 'Waiting on the parser rewrite',
...      'url': 'https://github.com/acme/widget/issues/13',
...      'createdAt': '2026-08-01T00:00:00Z',
...      'repository': {'nameWithOwner': 'acme/widget'}},
... ]
>>> edges = {
...     'acme/widget#12': [{'number': 15, 'state': 'closed',
...                         'closed_at': '2026-08-20T00:00:00Z',
...                         'repository': {'full_name': 'acme/engine'}}],
...     'acme/widget#13': [{'number': 7, 'state': 'open',
...                         'repository': {'full_name': 'acme/parser'}}],
... }
>>> report = blocked(                    # a dict and a dict: no gh, no network
...     issues_source=candidates,
...     blockers_source=edges,
...     now=datetime(2026, 8, 27, tzinfo=timezone.utc),
... )
>>> report['counts']['unblocked'], report['counts']['blocked']
(1, 1)
>>> for row in report['rows']:
...     print(row['state'], f"{row['repo']}#{row['number']}",
...           ' '.join(b['ref'] for b in row['blockers']))
unblocked acme/widget#12 acme/engine#15 [closed]
blocked acme/widget#13 acme/parser#7 [open]
```

The unblocked row says how long it has been free — the number nobody currently has:

```pycon
>>> report['rows'][0]['unblocked_days']
7
```

A candidate the dependency graph does not agree with is dropped, and the disagreement
is counted rather than hidden:

```pycon
>>> quiet = blocked(issues_source=candidates, blockers_source={},
...                 now=datetime(2026, 8, 27, tzinfo=timezone.utc))
>>> quiet['counts']['without_edges'], quiet['counts']['total']
(2, 0)
```

A run that could not resolve is never a clean board:

```pycon
>>> def unreachable(repo, number):
...     raise GhUnavailable('gh: not logged in')
>>> dark = blocked(issues_source=candidates, blockers_source=unreachable,
...                now=datetime(2026, 8, 27, tzinfo=timezone.utc))
>>> dark['counts']['unknown'], dark['counts']['unblocked']
(2, 0)
```

### Module Attributes

| [`UNBLOCKED`](_autosummary/openloops.blockers.html.md#openloops.blockers.UNBLOCKED)      | every blocker is closed.                                            |
|-----------------------------------------------------------------|---------------------------------------------------------------------|
| [`BLOCKED`](_autosummary/openloops.blockers.html.md#openloops.blockers.BLOCKED)        | at least one blocker is still open, and the row names which.        |
| [`BLOCKER_STATES`](_autosummary/openloops.blockers.html.md#openloops.blockers.BLOCKER_STATES) | The three states, in the order a reader cares about them.           |
| [`BLOCKED_FIELDS`](_autosummary/openloops.blockers.html.md#openloops.blockers.BLOCKED_FIELDS) | Every key on every row, whatever the issue's edges happened to say. |

### Functions

| [`blocked`](_autosummary/openloops.blockers.html.md#openloops.blockers.blocked)(\*[, resolve, owners, repos, query, ...])   | Open issues that carry a blocker edge, with every edge resolved.          |
|------------------------------------------------------------------------------------------------------|---------------------------------------------------------------------------|
| [`gh_blocked_by`](_autosummary/openloops.blockers.html.md#openloops.blockers.gh_blocked_by)(repo, number, \*[, timeout])          | The default `blockers_source`: the blocker edges out of one issue.        |
| [`gh_blocked_candidates`](_autosummary/openloops.blockers.html.md#openloops.blockers.gh_blocked_candidates)(\*[, owners, repos, ...])     | The default `issues_source`: open issues that *may* carry a blocker edge. |

### Classes

| [`BlockedIssue`](_autosummary/openloops.blockers.html.md#openloops.blockers.BlockedIssue)(repo, number, title, url, ...)    | One open issue that carries blocker edges, with the verdict those edges imply.   |
|-------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------|
| [`Blocker`](_autosummary/openloops.blockers.html.md#openloops.blockers.Blocker)(repo, number[, state, url, closed_at]) | One edge: the issue, in whatever repository it lives, that blocks another.       |

### Exceptions

| [`GhUnavailable`](_autosummary/openloops.blockers.html.md#openloops.blockers.GhUnavailable)   | The world could not be read: no `gh`, no credentials, no network, a timeout.   |
|------------------------------------------------------------------|--------------------------------------------------------------------------------|

### openloops.blockers.BLOCKED *= 'blocked'*

at least one blocker is still open, and the row names which.

* **Type:**
  Loop state

### openloops.blockers.BLOCKED_FIELDS *= ('repo', 'number', 'title', 'url', 'created', 'age_days', 'state', 'blockers', 'cross_repo', 'unblocked_days', 'evidence')*

Every key on every row, whatever the issue’s edges happened to say. A row shape that
varies by issue makes `row["blockers"]` a coin flip and a JSON schema a lie.

### openloops.blockers.BLOCKER_STATES *= ('unblocked', 'blocked', 'unknown')*

The three states, in the order a reader cares about them. `unknown` is
[`openloops.obligations.UNKNOWN`](_autosummary/openloops.obligations.html.md#openloops.obligations.UNKNOWN): not-checked means the same thing either way.

### *class* openloops.blockers.BlockedIssue(repo, number, title, url, created, age_days, state='unknown', blockers=(), cross_repo=False, unblocked_days=0, evidence='')

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

One open issue that carries blocker edges, with the verdict those edges imply.

`blockers` is carried in full next to `state` so a reader can disagree with the
verdict rather than absorb it — the same rule `openloops.obligations.
Obligation` follows for its predicate.

```pycon
>>> BlockedIssue('acme/widget', 12, 't', 'u', '2026-01-01T00:00:00Z', 3).state
'unknown'
```

#### as_dict()

JSON-ready form, blockers included.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]

#### cross_repo *: [bool](https://docs.python.org/3/builtins/functions.html#bool)* *= False*

At least one blocker lives in another repository — the shape this module is for.

#### unblocked_days *: [int](https://docs.python.org/3/builtins/functions.html#int)* *= 0*

how long the work
has been free while nobody was told. `0` for every other state.

* **Type:**
  Days since the last blocker closed, for an `unblocked` row

### *class* openloops.blockers.Blocker(repo, number, state='', url='', closed_at='')

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

One edge: the issue, in whatever repository it lives, that blocks another.

`repo` is the *blocker’s* repository, and carrying it is the whole point — an
edge that did not name it would answer only the easy half of the question.

```pycon
>>> Blocker('acme/engine', 15, 'closed').ref
'acme/engine#15 [closed]'
>>> Blocker('acme/engine', 15).ref
'acme/engine#15 [?]'
>>> Blocker('', 15, 'closed').ref
'?#15 [closed]'
```

#### as_dict()

JSON-ready form, with [`ref`](_autosummary/openloops.blockers.html.md#openloops.blockers.Blocker.ref) materialised for surfaces that print it.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]

#### *property* ref *: [str](https://docs.python.org/3/builtins/stdtypes.html#str)*

`owner/name#number [state]` — how a blocker is written down.

A `?` in either half is a fact about what could be read, never a shrug: an
edge whose repository the payload did not name says so rather than borrowing
the blocked issue’s own repository and inventing a same-repo dependency.

### *exception* openloops.blockers.GhUnavailable

Bases: [`RuntimeError`](https://docs.python.org/3/builtins/exceptions.html#RuntimeError)

The world could not be read: no `gh`, no credentials, no network, a timeout.

Raised only by the listing path, and never propagated to a caller of `owed()` —
it becomes `listed: False` plus an `error`, which every surface must render as
`?`. Turning it into an empty list would be the one unrecoverable bug here.

### openloops.blockers.UNBLOCKED *= 'unblocked'*

every blocker is closed. The work can proceed and nobody has been told.

* **Type:**
  Loop state

### openloops.blockers.blocked(, resolve=True, owners=None, repos=(), query='is:blocked', limit=50, timeout=30.0, now=None, issues_source=None, blockers_source=None)

Open issues that carry a blocker edge, with every edge resolved.

The row that matters sorts first: `unblocked` — every blocker closed, the work
free to proceed, and nothing anywhere has said so. `blocked` rows name what they
are waiting on, foreign repository included. `unknown` means the edges could not
be read, and it is never rounded into either of the others.

`owners=` scopes the fleet-wide search (default: `openloops.obligations.
configured_owners()`, the same fleet `ol owed` answers about, so two commands never
quietly disagree about which repositories exist). `repos=` instead enumerates the
repositories you name exactly, which is the audit path.

`resolve=False` lists candidates without spending one API call each; every row
then reads `unknown`, because that is what is true about it.

Two seams, each one keyword argument, each defaulting to a real implementation:
`issues_source=` (defaults to [`gh_blocked_candidates()`](_autosummary/openloops.blockers.html.md#openloops.blockers.gh_blocked_candidates); a list of dicts
substitutes) and `blockers_source=` (defaults to [`gh_blocked_by()`](_autosummary/openloops.blockers.html.md#openloops.blockers.gh_blocked_by); a mapping
from `'owner/name#number'` to edges, or any callable of `(repo, number)`,
substitutes). With both injected this reaches no network and needs no `gh`.

Returns one envelope, never a bare list, because a reader has to be able to tell
“nothing is waiting” from “I could not find out”:

`listed`
: `False` when *discovery itself* failed. Every surface must render that as
  `?`. The counts are zeros and they mean nothing.

`resolved`
: whether edges were resolved at all.

`truncated`
: the candidate list saturated `limit`, so the counts are a floor.

`counts`
: `unblocked` / `blocked` / `unknown`, plus `cross_repo`, `candidates`
  (how many discovery offered), `without_edges` (how many of those the
  dependency graph disagreed about) and `total` (how many rows).

`rows`
: one dict per issue, with every key in [`BLOCKED_FIELDS`](_autosummary/openloops.blockers.html.md#openloops.blockers.BLOCKED_FIELDS).

```pycon
>>> report = blocked(issues_source=[], blockers_source={})
>>> report['listed'], report['counts']['total'], report['rows']
(True, 0, [])
```

Discovery that could not run is not “nothing is waiting”:

```pycon
>>> def broken(**query):
...     raise GhUnavailable('gh: not logged in')
>>> report = blocked(issues_source=broken)
>>> report['listed'], report['error'], report['counts']['total']
(False, 'gh: not logged in', 0)
```

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]

### openloops.blockers.gh_blocked_by(repo, number, , timeout=30.0)

The default `blockers_source`: the blocker edges out of one issue.

One request per issue — the N+1 [`blocked()`](_autosummary/openloops.blockers.html.md#openloops.blockers.blocked) bounds with `limit=`. Returns the
rows GitHub sends, unparsed and unjudged; `_verdict()` is what reads a state
out of them. An issue with no edges answers `[]`, which is an answer.

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]]

### openloops.blockers.gh_blocked_candidates(, owners=(), repos=(), query='is:blocked', limit=50, timeout=30.0)

The default `issues_source`: open issues that *may* carry a blocker edge.

`repos=` chooses the exact per-repository enumeration; otherwise `owners=`
drives one fleet-wide search. Both return rows shaped the way `gh search issues`
shapes them — `createdAt`, `number`, `repository`, `title`, `url` — so
everything downstream reads one shape. Which one to use, and what each costs and
misses, is the “Discovery is a candidate list” section of this module’s docstring.

A large repository can take longer than `timeout` to paginate; that is a
[`GhUnavailable`](_autosummary/openloops.blockers.html.md#openloops.blockers.GhUnavailable), which reads `?`, not an empty answer.

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]]


# _autosummary/openloops.board.html.md

# openloops.board

The phone task board: task records in, a static page and its data files out.

[`build_board()`](_autosummary/openloops.board.html.md#openloops.board.build_board) writes five files into a directory the caller names:

The page is meant to be published as a claude.ai Artifact with a `db` capability.
Its persistence model (immutable `outbox/<eventId>` events written by the page,
`receipts/<eventId>` written only by the receiving session) is documented at the
top of its `<script>`.

**What openloops does not do** (ADR-008): post the comments, close the issues or
dispatch the workers that the board’s events ask for. That write side is a
procedure a Claude session follows, shipped as the `openloops-phone-board` skill.
This module writes files into `out_dir` and nothing else, and it never puts the
data anywhere near the repository: where the board lives is the caller’s choice.

```pycon
>>> tasks = [
...     {'id': 'a/x#1', 'tier': 'browser', 'pattern': 'api-key', 'minutes': 3},
...     {'id': 'a/y#2', 'tier': 'browser', 'pattern': 'api-key', 'minutes': 5},
...     {'id': 'a/z#3', 'tier': 'tap', 'pattern': 'other', 'status': 'likely-done'},
... ]
>>> [(r['key'], r['ids']) for r in group_runs(tasks)]
[('cleanup', ['a/z#3']), ('api-key', ['a/x#1', 'a/y#2'])]
```

### Functions

| [`as_document`](_autosummary/openloops.board.html.md#openloops.board.as_document)(fragment)                    | The page as a full HTML document, for hosting outside a claude.ai Artifact.         |
|-------------------------------------------------------------------------------------------|-------------------------------------------------------------------------------------|
| [`board_dir`](_autosummary/openloops.board.html.md#openloops.board.board_dir)()                              | Where the page template and the default run specs ship, inside the package.         |
| [`build_board`](_autosummary/openloops.board.html.md#openloops.board.build_board)(records, out_dir, \*[, ...]) | Write the board's five files into `out_dir` and say what went in.                   |
| [`group_runs`](_autosummary/openloops.board.html.md#openloops.board.group_runs)(tasks, \*[, specs, extras])   | Repeated chores grouped into runs, ordered as the specs are.                        |
| [`join_created`](_autosummary/openloops.board.html.md#openloops.board.join_created)(tasks, candidates)          | Fill each record's missing `created` from the gathered candidate with its URL.      |
| [`run_extras`](_autosummary/openloops.board.html.md#openloops.board.run_extras)([path])                       | The deployment's run extras (a JSON object keyed by run), or `None` without a path. |
| [`run_specs`](_autosummary/openloops.board.html.md#openloops.board.run_specs)([path])                        | The run specs: one per pattern, in display order.                                   |
| [`sort_tasks`](_autosummary/openloops.board.html.md#openloops.board.sort_tasks)(tasks)                        | Cheapest first: by tier, then by minutes per thing the item unblocks.               |

### openloops.board.as_document(fragment)

The page as a full HTML document, for hosting outside a claude.ai Artifact.

The page template is a fragment, because the Artifact host supplies the document
skeleton; anywhere else the skeleton has to be in the file. The page’s own styles
come after this reset, so its dark theme still wins.

```pycon
>>> doc = as_document('<title>t</title><p>hi</p>')
>>> doc.startswith('<!doctype html>') and 'name="viewport"' in doc
True
>>> as_document(doc) == doc
True
```

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### openloops.board.board_dir()

Where the page template and the default run specs ship, inside the package.

* **Return type:**
  [`Path`](https://docs.python.org/3/library/pathlib.html#pathlib.Path)

### openloops.board.build_board(records, out_dir, , candidates=(), specs=None, extras=None, title='Phone Task Board', session=None, read_only_orgs=(), machine=None, store='artifact', api=None, moved_to=None, links=None)

Write the board’s five files into `out_dir` and say what went in.

`links` (see `normalise_links()`) puts a row of name-and-address links in the
page’s header and keeps them in `board.json`. Links only: no card, no fetched
count. Without links the page and `board.json` are exactly what they were.

`session` is the name of the Claude session that receives the board’s events (the
page names it in the prompts it copies); `read_only_orgs` are organisations whose
items the page never offers to close or comment on; `machine` is the default
machine named by a run’s “have an agent start this run”.

`store` picks where the page keeps its state: `artifact` (the claude.ai
Artifact `db` capability) or `http` (a self-hosted board store API at `api`,
same origin as the page, served by anything wrapping [`openloops.board_store`](_autosummary/openloops.board_store.html.md#module-openloops.board_store)).
`moved_to` (an `https://` URL) builds the page as a forwarding notice: it
flushes what a phone already queued and takes no new taps.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]

### openloops.board.group_runs(tasks, , specs=None, extras=None)

Repeated chores grouped into runs, ordered as the specs are.

Open items go to their pattern’s run (a `mac-only` tier goes to `mac-only`);
`likely-done` and `stale` items go to `cleanup`. A pattern with no spec, or
with fewer items than its `min_items`, has no run.

`extras` overlays a run by key, for what only this deployment knows (a prompt, a
package table, a better title). Its `absorb` names other runs whose items move
into this one, and those runs disappear: two chores done in one session run.

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]]

### openloops.board.join_created(tasks, candidates)

Fill each record’s missing `created` from the gathered candidate with its URL.

```pycon
>>> join_created([{'url': 'u', 'created': None}], [{'url': 'u', 'created': '2026-01-02'}])
[{'url': 'u', 'created': '2026-01-02'}]
```

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]]

### openloops.board.run_extras(path=None)

The deployment’s run extras (a JSON object keyed by run), or `None` without a path.

```pycon
>>> run_extras() is None
True
```

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)] | [`None`](https://docs.python.org/3/builtins/constants.html#None)

### openloops.board.run_specs(path=None)

The run specs: one per pattern, in display order. Packaged ones by default.

Each spec is `{key, title, why, steps, tier?, min_items?, prompt?, machine?}`;
`key` is a pattern from [`openloops.tasks.PATTERNS`](_autosummary/openloops.tasks.html.md#openloops.tasks.PATTERNS), or `cleanup`.

```pycon
>>> run_specs()[0]['key']
'cleanup'
```

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]]

### openloops.board.sort_tasks(tasks)

Cheapest first: by tier, then by minutes per thing the item unblocks.

```pycon
>>> [t['id'] for t in sort_tasks([{'id': 'b', 'tier': 'session'}, {'id': 'a', 'tier': 'tap'}])]
['a', 'b']
```

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]]


# _autosummary/openloops.board_refresh.html.md

# openloops.board_refresh

Keep the phone board within a day of GitHub, without a session remembering to.

The board ([`openloops.board`](_autosummary/openloops.board.html.md#module-openloops.board)) is built by hand once: gather, classify, build. Left
alone it goes stale (a board built 2026-10-27 was still that build on 2026-11-09, with
210 of its 420 cards closed and 222 new items missing). [`refresh_board()`](_autosummary/openloops.board_refresh.html.md#openloops.board_refresh.refresh_board) is the
rebuild as one deterministic, model-free step meant to run from a timer (`ol
install-refresh-job`) or by hand (`ol board-refresh WORK`):

1. gather the open items ([`openloops.tasks.gather()`](_autosummary/openloops.tasks.html.md#openloops.tasks.gather)) over the scope saved in
   `WORK/refresh.json` (flags given on the command line are saved there first, and
   what `OPENLOOPS_OWNERS`/`OPENLOOPS_EXCLUDE_REPOS` or the default owners resolve
   to is saved as explicit lists, so a timer without that environment sweeps the same
   scope: [`pin_env_scope()`](_autosummary/openloops.board_refresh.html.md#openloops.board_refresh.pin_env_scope));
2. merge them with the live `WORK/board/tasks.json` ([`merge_refresh()`](_autosummary/openloops.board_refresh.html.md#openloops.board_refresh.merge_refresh), pure):
   the earlier record of every id still open is kept, with its title and url
   refreshed from GitHub and nothing re-classified; each new id gets the free
   heuristic record;
3. if nothing opened, closed or was retitled, stop (`rebuilt: False`);
4. otherwise rebuild into a temporary directory and move each file into place
   (`os.replace`: the receiver job reads `tasks.json` at any moment); the new ids
   accumulate in `WORK/new-items.json` for a session’s classifier brief;
5. publish (a directory, or `host:dir` through `scp`) whenever the local board’s
   files differ from the last ones published, and only then record it.

Guards, because a wrong rebuild is worse than a stale one:

* an incomplete sweep (`listed: false`) never rebuilds;
* a saturated sweep (some search hit its cap) adds but never closes;
* closing more than `max_close_fraction` of a board of at least
  [`GUARD_MIN_LIVE`](_autosummary/openloops.board_refresh.html.md#openloops.board_refresh.GUARD_MIN_LIVE) cards is refused unless `force`: those closes are withheld
  > (and named in `refresh.json`), while additions and retitles still go through, so
  > a refusal never freezes the board;
* a `tasks.json`, `board.json` or `refresh.json` that exists but does not parse
  (or, for `refresh.json`, holds a value of the wrong shape) raises rather than being
  read as empty, and a first run with no `board.json` raises rather than publishing
  default settings;
* an owner-edited `kit.html` (one that differs from the packaged template) is kept.

A board whose page keeps its state in a claude.ai Artifact cannot be republished from
here: the result says `needs_republish: True` and a session republishes it.

What it touches: GitHub through `gather` (read-only); files under `WORK`; and, when
publishing, the destination directory or the remote host (`scp` with the user’s own
keys). It never calls a model.

### Module Attributes

| [`NEW_ITEMS_FILE`](_autosummary/openloops.board_refresh.html.md#openloops.board_refresh.NEW_ITEMS_FILE)          | Where the items that got only the heuristic record are listed, for a classifier brief.                 |
|--------------------------------------------------------------------------|--------------------------------------------------------------------------------------------------------|
| [`STATE_FILE`](_autosummary/openloops.board_refresh.html.md#openloops.board_refresh.STATE_FILE)              | the gather scope, run specs/extras, where to publish, and the hash of the `tasks.json` last published. |
| [`DFLT_MAX_CLOSE_FRACTION`](_autosummary/openloops.board_refresh.html.md#openloops.board_refresh.DFLT_MAX_CLOSE_FRACTION) | A rebuild may close at most this fraction of the live cards without `force`...                         |
| [`GUARD_MIN_LIVE`](_autosummary/openloops.board_refresh.html.md#openloops.board_refresh.GUARD_MIN_LIVE)          | ...once the board has at least this many cards (a small board may empty legitimately).                 |

### Functions

| [`dir_publisher`](_autosummary/openloops.board_refresh.html.md#openloops.board_refresh.dir_publisher)(destination, \*[, timeout])   | A publisher that copies the board's files to `destination`.                                                                  |
|----------------------------------------------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------|
| [`is_remote_destination`](_autosummary/openloops.board_refresh.html.md#openloops.board_refresh.is_remote_destination)(destination)          | Whether `destination` names `host:dir` (for `scp`) rather than a local path.                                                 |
| [`load_state`](_autosummary/openloops.board_refresh.html.md#openloops.board_refresh.load_state)(work_dir)                        | `WORK/refresh.json`: `{}` when missing, an error when it exists but is unreadable or holds a scope value of the wrong shape. |
| [`merge_refresh`](_autosummary/openloops.board_refresh.html.md#openloops.board_refresh.merge_refresh)(live, candidates, \*[, ...])  | The rebuild's records, the new candidates, and the plan.                                                                     |
| [`pin_env_scope`](_autosummary/openloops.board_refresh.html.md#openloops.board_refresh.pin_env_scope)(work_dir, \*[, environ, ...]) | Save what the environment makes the sweep's scope into `WORK/refresh.json`.                                                  |
| [`plan_refresh`](_autosummary/openloops.board_refresh.html.md#openloops.board_refresh.plan_refresh)(current, previous)             | Diff the ids now open against the ids on the live board.                                                                     |
| [`refresh_board`](_autosummary/openloops.board_refresh.html.md#openloops.board_refresh.refresh_board)(work_dir, \*[, owners, ...])  | Rebuild `WORK/board` when the set of open items changed.                                                                     |
| [`remember_scope`](_autosummary/openloops.board_refresh.html.md#openloops.board_refresh.remember_scope)(work_dir, \*\*given)         | Save the `given` scope values (`None` = not given) into `WORK/refresh.json`.                                                 |

### Classes

| [`RefreshPlan`](_autosummary/openloops.board_refresh.html.md#openloops.board_refresh.RefreshPlan)(kept, added, closed[, withheld, ...])   | What a fresh sweep changes relative to the live board.   |
|------------------------------------------------------------------------------------------------------|----------------------------------------------------------|

### Exceptions

| [`PublishError`](_autosummary/openloops.board_refresh.html.md#openloops.board_refresh.PublishError)   | Publishing the rebuilt board failed.   |
|-----------------------------------------------------------------|----------------------------------------|

### openloops.board_refresh.DFLT_MAX_CLOSE_FRACTION *= 0.5*

A rebuild may close at most this fraction of the live cards without `force`…

### openloops.board_refresh.GUARD_MIN_LIVE *= 10*

…once the board has at least this many cards (a small board may empty legitimately).

### openloops.board_refresh.NEW_ITEMS_FILE *= 'new-items.json'*

Where the items that got only the heuristic record are listed, for a classifier brief.

### *exception* openloops.board_refresh.PublishError

Bases: [`RuntimeError`](https://docs.python.org/3/builtins/exceptions.html#RuntimeError)

Publishing the rebuilt board failed. The local board is in place; the next run
retries, because the published marker is recorded only after a success.

### *class* openloops.board_refresh.RefreshPlan(kept, added, closed, withheld=(), updated=())

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

What a fresh sweep changes relative to the live board.

`withheld` are ids missing from a saturated sweep, kept rather than closed;
`updated` are kept ids whose title or url changed on GitHub.

### openloops.board_refresh.STATE_FILE *= 'refresh.json'*

the gather scope, run specs/extras, where to publish, and
the hash of the `tasks.json` last published.

* **Type:**
  The refresh’s own state

### openloops.board_refresh.dir_publisher(destination, , timeout=300)

A publisher that copies the board’s files to `destination`.

`destination` is a directory, or `host:dir` (see
[`is_remote_destination()`](_autosummary/openloops.board_refresh.html.md#openloops.board_refresh.is_remote_destination)), which goes through `scp -o BatchMode=yes` (never a
password prompt that would hang a timer) with `timeout` seconds. A local copy
replaces each file atomically; the remote copy does not (`scp` writes in place),
so a reader on the host can, for a moment, see a partly written file. A failure
raises, so a timer’s log says the board did not move.

* **Return type:**
  [`Callable`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable)[[[`Path`](https://docs.python.org/3/library/pathlib.html#pathlib.Path)], [`None`](https://docs.python.org/3/builtins/constants.html#None)]

### openloops.board_refresh.is_remote_destination(destination)

Whether `destination` names `host:dir` (for `scp`) rather than a local path.

Remote only when the text before the first colon is a plausible host (non-empty, no
`/` or `\`, not a one-letter Windows drive such as `C:`) and the whole thing
is not an existing local path.

```pycon
>>> [is_remote_destination(d) for d in ('tw:/srv/board', 'me@host:board')]
[True, True]
>>> [is_remote_destination(d) for d in (r'C:\Users\x\dest', '/tmp/a:b', 'board')]
[False, False, False]
```

* **Return type:**
  [`bool`](https://docs.python.org/3/builtins/functions.html#bool)

### openloops.board_refresh.load_state(work_dir)

`WORK/refresh.json`: `{}` when missing, an error when it exists but is
unreadable or holds a scope value of the wrong shape.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]

### openloops.board_refresh.merge_refresh(live, candidates, , saturated=(), withhold_closes=False)

The rebuild’s records, the new candidates, and the plan. No I/O.

Every id still open keeps its earlier record (never re-classified), with
`REFRESHED_FIELDS` taken from the sweep; new ids get the heuristic record. A
`saturated` sweep did not list everything, so an id it did not see is kept
(`withheld`), never closed; `withhold_closes` does the same for a sweep whose
closes were refused.

```pycon
>>> live = [{'id': 'a/b#1', 'title': 'Old', 'ask': 'ENRICHED'}, {'id': 'a/b#2'}]
>>> seen = [{'id': 'a/b#1', 'title': 'New', 'url': 'https://github.com/a/b/issues/1'}]
>>> records, fresh, plan = merge_refresh(live, seen)
>>> [(r['id'], r['title'], r['ask']) for r in records], plan.closed, plan.updated
([('a/b#1', 'New', 'ENRICHED')], ('a/b#2',), ('a/b#1',))
>>> records, _, plan = merge_refresh(live, seen, saturated=['label:manual-task'])
>>> [r['id'] for r in records], plan.closed, plan.withheld
(['a/b#1', 'a/b#2'], (), ('a/b#2',))
```

* **Return type:**
  [`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]], [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]], [`RefreshPlan`](_autosummary/openloops.board_refresh.html.md#openloops.board_refresh.RefreshPlan)]

### openloops.board_refresh.pin_env_scope(work_dir, , environ=None, resolve_owners=None)

Save what the environment makes the sweep’s scope into `WORK/refresh.json`.

A launchd timer does not get the shell’s `OPENLOOPS_OWNERS` or
`OPENLOOPS_EXCLUDE_REPOS`, so a scope that lives only there would make the timer
sweep a different set of repositories than a run by hand (and could put an excluded
client repo on the board). Each is written as an explicit list, but only where
`refresh.json` has no value yet (a flag given earlier, or an earlier pin, wins).
With no `OPENLOOPS_OWNERS`, `resolve_owners` (e.g.
[`openloops.obligations.configured_owners()`](_autosummary/openloops.obligations.html.md#openloops.obligations.configured_owners)) supplies the default owners; when
it is not given they stay unset here and the first sweep’s resolved owners are
pinned instead. Returns what was saved.

```pycon
>>> import tempfile
>>> with tempfile.TemporaryDirectory() as tmp:
...     env = {'OPENLOOPS_OWNERS': 'me, org', 'OPENLOOPS_EXCLUDE_REPOS': 'org/x-*'}
...     first = pin_env_scope(tmp, environ=env)
...     second = pin_env_scope(tmp, environ={'OPENLOOPS_OWNERS': 'other'})
>>> first, second
({'owners': ['me', 'org'], 'exclude_repos': ['org/x-*']}, {})
```

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]]

### openloops.board_refresh.plan_refresh(current, previous)

Diff the ids now open against the ids on the live board.

```pycon
>>> plan = plan_refresh(['a#1', 'a#2', 'a#4'], ['a#1', 'a#3'])
>>> plan.kept, plan.added, plan.closed, plan.changed
(('a#1',), ('a#2', 'a#4'), ('a#3',), True)
>>> plan_refresh(['a#1'], ['a#1']).changed
False
```

* **Return type:**
  [`RefreshPlan`](_autosummary/openloops.board_refresh.html.md#openloops.board_refresh.RefreshPlan)

### openloops.board_refresh.refresh_board(work_dir, \*, owners=None, exclude_owners=None, exclude_repos=None, searches=None, review_prs=None, run_specs=None, run_extras=None, publish_to=None, force=False, max_close_fraction=0.5, publish=None, gather=<function gather>, settings=None, edges=None)

Rebuild `WORK/board` when the set of open items changed. Returns what happened.

The scope keywords (`owners` to `publish_to`) are saved into
`WORK/refresh.json` when given and read from it when not ([`remember_scope()`](_autosummary/openloops.board_refresh.html.md#openloops.board_refresh.remember_scope));
their defaults are every kind of item and PRs awaiting review, like
`board-gather --all-kinds`. `run_specs`/`run_extras` are passed to every
rebuild, as `board-build` takes them. `force` rebuilds even when nothing
changed and overrides the close guard (never the incomplete-sweep one). What the
environment sets (`OPENLOOPS_OWNERS`, `OPENLOOPS_EXCLUDE_REPOS`) and, failing
that, the owners the sweep resolved, are pinned into `refresh.json` where it has no
value yet ([`pin_env_scope()`](_autosummary/openloops.board_refresh.html.md#openloops.board_refresh.pin_env_scope)).
`publish` replaces the publisher built from `publish_to` (see
[`dir_publisher()`](_autosummary/openloops.board_refresh.html.md#openloops.board_refresh.dir_publisher)); `gather` replaces the sweep; `edges` replaces the read
of the dependency edges (default `openloops.blockers.blocked_edges()`, one search
plus one call per blocked issue), which fills each record’s `blocked_by`; `settings` override the
existing `board.json` (and are required when there is none).

`status` is `rebuilt`, `unchanged`, `incomplete`, `partial` (rebuilt with
additions/retitles while a mass close was refused) or `refused` (a mass close was
refused and nothing else changed). Refused closes are withheld, never dropped:
`refused_closes` (a count) and `refused_close_ids` are returned and kept in
`refresh.json` until a run no longer refuses, and `remedy` is the command that
applies them. A publish failure raises [`PublishError`](_autosummary/openloops.board_refresh.html.md#openloops.board_refresh.PublishError) after the local rebuild
is in place.

```pycon
>>> import tempfile
>>> item = {'id': 'a/b#1', 'url': 'https://github.com/a/b/issues/1',
...         'repo': 'a/b', 'title': 'Add a key', 'src': 'label:manual-task'}
>>> sweep = lambda **kw: {'listed': True, 'candidates': [item], 'error': None}
>>> with tempfile.TemporaryDirectory() as tmp:
...     first = refresh_board(tmp, gather=sweep, settings={'title': 'Mine'})
...     again = refresh_board(tmp, gather=sweep)
>>> first['rebuilt'], first['added'], again['status']
(True, 1, 'unchanged')
```

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]

### openloops.board_refresh.remember_scope(work_dir, \*\*given)

Save the `given` scope values (`None` = not given) into `WORK/refresh.json`.

Returns the full scope: what was saved, then defaults. Both `ol board-refresh`
and `ol install-refresh-job` go through here, so the timer needs only `WORK`.

```pycon
>>> import tempfile
>>> with tempfile.TemporaryDirectory() as tmp:
...     _ = remember_scope(tmp, owners=['me'])
...     scope = remember_scope(tmp, exclude_repos=None)
>>> scope['owners'], scope['review_prs']
(['me'], True)
```

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]


# _autosummary/openloops.board_server.html.md

# openloops.board_server

An optional web app for a self-hosted phone board: the page, its files, its store API.

`pip install openloops[server]` adds FastAPI; nothing else in openloops imports this
module, so the core still never reaches the network. [`mk_app()`](_autosummary/openloops.board_server.html.md#openloops.board_server.mk_app) returns a FastAPI
app with two route groups:

- `GET /board/` and `GET /board/{file}`: the board directory written by
  `ol board-build --store http --api <prefix>/board-store` (`index.html`, `tasks.json`,
  `runs.json`, `board.json`, `kit.html`, nothing else).
- `/board-store/...`: the board store API of [`openloops.board_store`](_autosummary/openloops.board_store.html.md#module-openloops.board_store). Not
  `/store`: a host may already own that path (enlace_auth mounts its own per-user
  store at `/api/<app>/store`), and the page sends no CSRF token, so the API must sit
  where the host exempts an app’s own routes from CSRF.

**It does not authenticate anyone.** It asks `role_of(request)` for `"viewer"` (the
owner’s browser) or `"receiver"` (the receiving session) and refuses every request,
reads included, for which it gets anything else. Put it behind your platform’s login
and derive the role from the identity that login established, never from anything the
client sends. The board’s task titles come from private repositories.

**Imports** (moving a board here, see the skill’s `migrate.md`) are possible only
while a file named `.import-open` exists in `store_root`: create it on the server
for the migration, delete it after. The receiver’s credentials cannot open it.

> app = mk_app(
> : board_dir=”~/.local/share/openloops/board”,
>   store_root=”~/.local/share/openloops/board-store”,
>   role_of=lambda request: “viewer” if request.state.user_email == OWNER else None,

> )

### Module Attributes

| [`IMPORT_FLAG`](_autosummary/openloops.board_server.html.md#openloops.board_server.IMPORT_FLAG)   | Its presence in the store root allows imports; see the module docstring.   |
|----------------------------------------------------------------|----------------------------------------------------------------------------|

### Functions

| [`file_lock`](_autosummary/openloops.board_server.html.md#openloops.board_server.file_lock)(path, \*[, shared])                     | A lock on `path` across processes (POSIX `flock`): shared to read, else exclusive.   |
|----------------------------------------------------------------------------------------------------|--------------------------------------------------------------------------------------|
| [`mk_app`](_autosummary/openloops.board_server.html.md#openloops.board_server.mk_app)(\*, board_dir, store_root, role_of[, ...]) | The board's FastAPI app.                                                             |

### openloops.board_server.IMPORT_FLAG *= '.import-open'*

Its presence in the store root allows imports; see the module docstring.

### openloops.board_server.file_lock(path, , shared=False)

A lock on `path` across processes (POSIX `flock`): shared to read, else exclusive.

A web server usually runs several worker processes; without this, two of them can
both see an event as absent and both “create” it. Where `fcntl` is missing the
lock is process-local only, which is right for a single-process server.

* **Return type:**
  [`Iterator`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Iterator)[[`None`](https://docs.python.org/3/builtins/constants.html#None)]

### openloops.board_server.mk_app(, board_dir, store_root, role_of, max_bytes=65536, title='openloops board', files=('tasks.json', 'runs.json', 'board.json', 'index.html', 'kit.html'))

The board’s FastAPI app. `role_of` is the only authorisation it has.

`files` names the only files `GET /board/{name}` hands out (default: what
`ol board-build` writes). Another page that wants the same store rules over its own
published files (a desk serving `snapshot.json`) passes its own names; `index.html`
is always one of them, since `GET /board/` serves it.


# _autosummary/openloops.board_store.html.md

# openloops.board_store

The board store’s rules, for a self-hosted phone board: who may write what, and how.

The phone board page (`openloops/data/board/index.html`) keeps its state in a small
document store: collections of JSON documents. On claude.ai that store is the
Artifact `db` capability. On your own server it is whatever serves the \*\*board store
API\*\* below, and this module is that API’s logic, written once so every server that
hosts a board enforces the same rules:

The rules ([`WRITERS`](_autosummary/openloops.board_store.html.md#openloops.board_store.WRITERS), [`put_doc()`](_autosummary/openloops.board_store.html.md#openloops.board_store.put_doc)) are the page’s persistence model, enforced
rather than trusted:

- `outbox` events are **immutable**: the first write creates, an identical retry is
  a no-op success, anything else is 409. Only the page (role `viewer`) creates them.
- `drafts` are newest-wins by their own `at`: an older write is acknowledged and
  ignored, so a slow phone cannot overwrite a newer note.
- `receipts`, `meta`, `questions` (and the legacy `state`/`answers`) are
  written only by the receiving session (role `receiver`), never by the page.
- **Imports** (moving a board here: `allow_import=True`) additionally let the
  `receiver` create `outbox` events and write `drafts`. Off by default, and meant
  to be on only while a migration runs: otherwise the receiver’s credentials would be
  as powerful as the owner’s taps, since the receiver acts on events.

**Roles are the server’s job, not this module’s.** A server maps each request to
`viewer` (the owner’s browser login) or `receiver` (the receiving session’s account)
and refuses everything else before calling in here. Like the rest of openloops this
module never reaches the network: it reads and writes a `MutableMapping` (a `dict`,
a files store, anything with the same interface).

```pycon
>>> store = {}
>>> put_doc(store, 'outbox', 'e1', {'action': 'done'}, role='viewer')['created']
True
>>> put_doc(store, 'outbox', 'e1', {'action': 'done'}, role='viewer')['created']
False
>>> put_doc(store, 'outbox', 'e1', {'action': 'undo'}, role='viewer')
Traceback (most recent call last):
  ...
openloops.board_store.BoardStoreError: 409: outbox/e1 exists and events never change
>>> put_doc(store, 'receipts', 'e1', {'status': 'posted'}, role='viewer')
Traceback (most recent call last):
  ...
openloops.board_store.BoardStoreError: 403: role 'viewer' may not write receipts
>>> [d['id'] for d in list_docs(store, 'outbox')['docs']]
['e1']
```

### Module Attributes

| [`WRITERS`](_autosummary/openloops.board_store.html.md#openloops.board_store.WRITERS)        | Who may write each collection.                                           |
|-----------------------------------------------------------------|--------------------------------------------------------------------------|
| [`IMPORT_WRITERS`](_autosummary/openloops.board_store.html.md#openloops.board_store.IMPORT_WRITERS) | What an import may additionally write, and by whom (see `allow_import`). |

### Functions

| [`get_doc`](_autosummary/openloops.board_store.html.md#openloops.board_store.get_doc)(store, collection, doc_id)                 | One document, or a 404 [`BoardStoreError`](_autosummary/openloops.board_store.html.md#openloops.board_store.BoardStoreError).   |
|-----------------------------------------------------------------------------------------------------|--------------------------------------------------------------------------------------------|
| [`list_docs`](_autosummary/openloops.board_store.html.md#openloops.board_store.list_docs)(store, collection, \*[, max_docs])       | Every document of `collection`, sorted by id.                                              |
| [`parse_body`](_autosummary/openloops.board_store.html.md#openloops.board_store.parse_body)(raw)                                    | A request body as JSON, refusing `NaN`/`Infinity`, which JSON does not have.               |
| [`put_doc`](_autosummary/openloops.board_store.html.md#openloops.board_store.put_doc)(store, collection, doc_id, data, \*, role) | Write one document under the collection's rules; return its id and version.                |

### Exceptions

| [`BoardStoreError`](_autosummary/openloops.board_store.html.md#openloops.board_store.BoardStoreError)(status, message)   | A refused request, carrying the HTTP status a server should answer with.   |
|-------------------------------------------------------------------------------------|----------------------------------------------------------------------------|

### *exception* openloops.board_store.BoardStoreError(status, message)

Bases: [`Exception`](https://docs.python.org/3/builtins/exceptions.html#Exception)

A refused request, carrying the HTTP status a server should answer with.

### openloops.board_store.IMPORT_WRITERS *: [Mapping](https://docs.python.org/3/library/collections.abc.html#collections.abc.Mapping)[[str](https://docs.python.org/3/builtins/stdtypes.html#str), [frozenset](https://docs.python.org/3/builtins/stdtypes.html#frozenset)[[str](https://docs.python.org/3/builtins/stdtypes.html#str)]]* *= {'drafts': frozenset({'receiver'}), 'outbox': frozenset({'receiver'})}*

What an import may additionally write, and by whom (see `allow_import`).

### openloops.board_store.WRITERS *: [Mapping](https://docs.python.org/3/library/collections.abc.html#collections.abc.Mapping)[[str](https://docs.python.org/3/builtins/stdtypes.html#str), [frozenset](https://docs.python.org/3/builtins/stdtypes.html#frozenset)[[str](https://docs.python.org/3/builtins/stdtypes.html#str)]]* *= {'answers': frozenset({'receiver'}), 'drafts': frozenset({'viewer'}), 'meta': frozenset({'receiver'}), 'outbox': frozenset({'viewer'}), 'questions': frozenset({'receiver'}), 'receipts': frozenset({'receiver'}), 'state': frozenset({'receiver'})}*

Who may write each collection. Every role may read every collection.

### openloops.board_store.get_doc(store, collection, doc_id)

One document, or a 404 [`BoardStoreError`](_autosummary/openloops.board_store.html.md#openloops.board_store.BoardStoreError).

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]

### openloops.board_store.list_docs(store, collection, , max_docs=20000)

Every document of `collection`, sorted by id.

A file that is not valid JSON (a hand edit, a write cut short by a store that does
not write atomically) is counted in `skipped` rather than failing the listing.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]

### openloops.board_store.parse_body(raw)

A request body as JSON, refusing `NaN`/`Infinity`, which JSON does not have.

```pycon
>>> parse_body(b'{"a": 1}')
{'a': 1}
>>> parse_body(b'{"a": NaN}')
Traceback (most recent call last):
  ...
openloops.board_store.BoardStoreError: 400: body is not JSON
```

* **Return type:**
  [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)

### openloops.board_store.put_doc(store, collection, doc_id, data, , role, if_match=None, if_none_match=False, max_bytes=65536, allow_import=False)

Write one document under the collection’s rules; return its id and version.

`created` is `False` for an idempotent repeat of an event and for an unpinned
draft older than the one stored, both of which change nothing. A *pinned* draft
write that loses to a newer one is a 412, so a caller who pinned learns it lost.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]


# _autosummary/openloops.closer.html.md

# openloops.closer

The one module that writes to GitHub: a manual task closes on its passing check.

ADR-015 §4. Everything else in openloops reads. This module may, for one issue at a
time, post **one comment**, **close** the issue, and add or remove the `attempted`
label, and only when all five conditions hold ([`refusal()`](_autosummary/openloops.closer.html.md#openloops.closer.refusal)):

1. the issue is open;
2. it carries the `manual-task` label;
3. its repository’s owner is one the person configured as trusted (`closer.owners` in
   the config file, [`close_settings()`](_autosummary/openloops.closer.html.md#openloops.closer.close_settings); `OPENLOOPS_CLOSE_OWNERS` overrides it for one
   run; neither set means the `gh` login alone);
4. it was filed under the person’s own `gh` login;
5. its repository is not shared: it has no outside collaborators (a client’s or a team’s
   repository inside a trusted organisation), unless the person listed it under
   `closer.shared_repos`. When the collaborators cannot be read, it counts as shared.

A close needs a **passing check**: a read-only command (`write_effect` finds nothing)
whose exit status is 0. The check is the issue’s `**Verify:**` field, or one the owner
approved with a run plan (ADR-018). A report alone (“I ran it”) never closes; a model’s
reading of an output never closes. With no check, nothing is closed: only the person’s
own tap does that. A run with no check is still reported in one comment.

Every comment ends with a hidden marker carrying the attempt id, so a retry never posts
twice. Comments say what ran and what the check returned; they never carry command
output, and their text goes through [`openloops.egress.scrub()`](_autosummary/openloops.egress.html.md#openloops.egress.scrub) first (an issue in a
public repository is public).

Nothing in the core imports this module: `import openloops` still reaches no network
and writes nothing. Its callers are the run-plan executor ([`openloops.runbook_run`](_autosummary/openloops.runbook_run.html.md#module-openloops.runbook_run))
and, later, `ol do` (ADR-015 §2).

Two seams (ADR-015’s table): `gh=` reads, `(args, *, input=None) -> (status, stdout)`;
`deliver=` writes, a [`Deliver`](_autosummary/openloops.closer.html.md#openloops.closer.Deliver) (default [`GhDeliver`](_autosummary/openloops.closer.html.md#openloops.closer.GhDeliver), the `gh` CLI the
person already authenticated; a spool or the board store can take its place).

Outcomes use the run vocabulary: `done` (it ran as expected), `failed` (it ran and
did not), `check-only` (nothing ran). ADR-015 §1’s `blocked` and `needs-owner` are
reports that close nothing; a caller maps them to `failed` with its own note.

### Functions

| [`close_settings`](_autosummary/openloops.closer.html.md#openloops.closer.close_settings)(\*[, environ, path])               | The closer's settings: the `closer` section of [`config_path()`](_autosummary/openloops.closer.html.md#openloops.closer.config_path), e.g. `{"closer": {"owners": ["me", "my-org"], "shared_repos": ["my-org/a-shared-repo"]}}`.   |
|----------------------------------------------------------------------------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| [`config_path`](_autosummary/openloops.closer.html.md#openloops.closer.config_path)(\*[, environ])                        | The person's openloops settings file: `OPENLOOPS_CONFIG`, else `$XDG_CONFIG_HOME/openloops/config.json` (`~/.config/openloops/config.json`).                                                                |
| [`read_issue`](_autosummary/openloops.closer.html.md#openloops.closer.read_issue)(ref, \*[, gh])                         | The issue's state, labels, author and body, plus its comments' last lines.                                                                                                                                  |
| [`refusal`](_autosummary/openloops.closer.html.md#openloops.closer.refusal)(issue, \*, owners, login[, shared_repos]) | Why this module must not write to *issue*, or `""`.                                                                                                                                                         |
| [`report`](_autosummary/openloops.closer.html.md#openloops.closer.report)(ref, \*, attempt[, ran, ran_label, ...])   | Report an outcome for one manual task; close it only if its check passes.                                                                                                                                   |
| [`trusted_owners`](_autosummary/openloops.closer.html.md#openloops.closer.trusted_owners)(\*[, gh, environ, settings])       | Whose trackers this module may write to: the configured owners, else the login.                                                                                                                             |
| [`who`](_autosummary/openloops.closer.html.md#openloops.closer.who)(\*[, gh, settings])                           | `(trusted owners, login, shared repos allowed)`, resolved once per run.                                                                                                                                     |

### Classes

| [`CloseSettings`](_autosummary/openloops.closer.html.md#openloops.closer.CloseSettings)([owners, shared_repos])   | Where the closer may write.                                                                             |
|------------------------------------------------------------------------------------------|---------------------------------------------------------------------------------------------------------|
| [`Deliver`](_autosummary/openloops.closer.html.md#openloops.closer.Deliver)(\*args, \*\*kwargs)             | Where this module's writes go.                                                                          |
| [`GhDeliver`](_autosummary/openloops.closer.html.md#openloops.closer.GhDeliver)([gh])                         | The default [`Deliver`](_autosummary/openloops.closer.html.md#openloops.closer.Deliver): the `gh` CLI, one call per write. |

### *class* openloops.closer.CloseSettings(owners=(), shared_repos=())

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

Where the closer may write. `owners` empty means the `gh` login alone.

`shared_repos` (`owner/name`) are repositories with outside collaborators that
the person still lets it close issues in; every other shared repository is refused.

### *class* openloops.closer.Deliver(\*args, \*\*kwargs)

Bases: [`Protocol`](https://docs.python.org/3/library/typing.html#typing.Protocol)

Where this module’s writes go. Each returns `(ok, detail)`.

### *class* openloops.closer.GhDeliver(gh=<function \_gh_cli>)

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

The default [`Deliver`](_autosummary/openloops.closer.html.md#openloops.closer.Deliver): the `gh` CLI, one call per write.

### openloops.closer.close_settings(, environ=environ({'SHELL': '/bin/bash', 'SELENIUM_JAR_PATH': '/usr/share/java/selenium-server.jar', 'GITHUB_WORKSPACE': '/home/runner/work/openloops/openloops', 'JAVA_HOME_11_X64': '/usr/lib/jvm/temurin-11-jdk-amd64', 'JAVA_HOME_25_X64': '/usr/lib/jvm/temurin-25-jdk-amd64', 'PROJECT_NAME': 'openloops', 'PKG_CONFIG_PATH': '/opt/hostedtoolcache/Python/3.12.16/x64/lib/pkgconfig', 'GITHUB_PATH': '/home/runner/work/_temp/_runner_file_commands/add_path_d26455fb-372c-4670-899e-a670aadab12f', 'GITHUB_ACTION': '_\_i2mint_epythet', 'JAVA_HOME': '/usr/lib/jvm/temurin-25-jdk-amd64', 'GITHUB_RUN_NUMBER': '353', 'RUNNER_NAME': 'GitHub Actions 1000004762', 'GRADLE_HOME': '/usr/share/gradle-9.9.3', 'GITHUB_REPOSITORY_OWNER_ID': '159425785', 'ACTIONS_RUNNER_ACTION_ARCHIVE_CACHE': '/opt/actionarchivecache', 'XDG_CONFIG_HOME': '/home/runner/.config', 'Python_ROOT_DIR': '/opt/hostedtoolcache/Python/3.12.16/x64', 'MEMORY_PRESSURE_WRITE': 'c29tZSAyMDAwMDAgMjAwMDAwMAA=', 'DOTNET_SKIP_FIRST_TIME_EXPERIENCE': '1', 'ANT_HOME': '/usr/share/ant', 'GITHUB_TRIGGERING_ACTOR': 'thorwhalen', 'pythonLocation': '/opt/hostedtoolcache/Python/3.12.16/x64', 'GITHUB_REF_TYPE': 'branch', 'HOMEBREW_CLEANUP_PERIODIC_FULL_DAYS': '3650', 'ACTIONS_RUNNER_RETURN_JOB_RESULT_FOR_HOSTED': '1', 'ANDROID_NDK': '/usr/local/lib/android/sdk/ndk/27.3.13750724', 'BOOTSTRAP_HASKELL_NONINTERACTIVE': '1', 'PWD': '/home/runner/work/openloops/openloops', 'PIPX_BIN_DIR': '/opt/pipx_bin', 'LOGNAME': 'runner', 'GITHUB_ARTIFACTS_LIST': '/home/runner/work/_temp/_runner_file_commands/artifacts_list_d26455fb-372c-4670-899e-a670aadab12f', 'GITHUB_REPOSITORY_ID': '1346350581', 'GITHUB_ACTIONS': 'true', 'USE_BAZEL_FALLBACK_VERSION': 'silent:', 'ANDROID_NDK_LATEST_HOME': '/usr/local/lib/android/sdk/ndk/30.0.16248370', 'SYSTEMD_EXEC_PID': '2153', 'GITHUB_SHA': '9bd66390e112947c9241b3e2908ab0dda2173703', 'GITHUB_WORKFLOW_REF': 'addaix/openloops/.github/workflows/ci.yml@refs/heads/main', 'POWERSHELL_DISTRIBUTION_CHANNEL': 'GitHub-Actions-Linux', 'RUNNER_ENVIRONMENT': 'github-hosted', 'DOTNET_MULTILEVEL_LOOKUP': '0', 'GOROOT_1_27_X64': '/opt/hostedtoolcache/go/1.27.4/x64', 'GITHUB_REF': 'refs/heads/main', 'RUNNER_OS': 'Linux', 'GITHUB_REF_PROTECTED': 'false', 'HOME': '/home/runner', 'GITHUB_API_URL': 'https://api.github.com', 'LANG': 'C.UTF-8', 'GOROOT_1_25_X64': '/opt/hostedtoolcache/go/1.25.14/x64', 'RUNNER_TRACKING_ID': 'github_d9e82dac-9ed8-476b-98ec-5be564bcae08', 'RUNNER_ARCH': 'X64', 'MEMORY_PRESSURE_WATCH': '/sys/fs/cgroup/system.slice/hosted-compute-agent.service/memory.pressure', 'RUNNER_TEMP': '/home/runner/work/_temp', 'GITHUB_STATE': '/home/runner/work/_temp/_runner_file_commands/save_state_d26455fb-372c-4670-899e-a670aadab12f', 'EDGEWEBDRIVER': '/usr/local/share/edge_driver', 'JAVA_HOME_21_X64': '/usr/lib/jvm/temurin-21-jdk-amd64', 'GITHUB_ENV': '/home/runner/work/_temp/_runner_file_commands/set_env_d26455fb-372c-4670-899e-a670aadab12f', 'GITHUB_EVENT_PATH': '/home/runner/work/_temp/_github_workflow/event.json', 'INVOCATION_ID': 'f2e4fc20649d403d8534d6c314f76312', 'GITHUB_EVENT_NAME': 'push', 'GITHUB_RUN_ID': '47549397045', 'JAVA_HOME_17_X64': '/usr/lib/jvm/temurin-17-jdk-amd64', 'ANDROID_NDK_HOME': '/usr/local/lib/android/sdk/ndk/27.3.13750724', 'GITHUB_STEP_SUMMARY': '/home/runner/work/_temp/_runner_file_commands/step_summary_d26455fb-372c-4670-899e-a670aadab12f', 'HOMEBREW_NO_AUTO_UPDATE': '1', 'GITHUB_ACTOR': 'thorwhalen', 'NVM_DIR': '/home/runner/.nvm', 'SGX_AESM_ADDR': '1', 'GITHUB_RUN_ATTEMPT': '1', 'ANDROID_HOME': '/usr/local/lib/android/sdk', 'GITHUB_GRAPHQL_URL': 'https://api.github.com/graphql', 'ACCEPT_EULA': 'Y', 'USER': 'runner', 'PSModulePath': '/root/.local/share/powershell/Modules:/usr/local/share/powershell/Modules:/opt/microsoft/powershell/7/Modules:/usr/share/az_15.6.1', 'GITHUB_ACTION_PATH': '/home/runner/work/_actions/i2mint/epythet/master/actions/publish-github-pages', 'GITHUB_SERVER_URL': 'https://github.com', 'PIPX_HOME': '/opt/pipx', 'GECKOWEBDRIVER': '/usr/local/share/gecko_driver', 'CHROMEWEBDRIVER': '/usr/local/share/chromedriver-linux64', 'SHLVL': '1', 'ANDROID_SDK_ROOT': '/usr/local/lib/android/sdk', 'VCPKG_INSTALLATION_ROOT': '/usr/local/share/vcpkg', 'GITHUB_ACTOR_ID': '1906276', 'ACTIONS_ORCHESTRATION_ID': 'b4a8399a-e2dd-813b-b879-38dd06e1f012.ci.github-pages._\_default', 'RUNNER_TOOL_CACHE': '/opt/hostedtoolcache', 'ImageVersion': '20261129.15.1', 'Python3_ROOT_DIR': '/opt/hostedtoolcache/Python/3.12.16/x64', 'DOTNET_NOLOGO': '1', 'GITHUB_ARTIFACTS': '/home/runner/work/_temp/_runner_file_commands/artifacts_d26455fb-372c-4670-899e-a670aadab12f', 'GITHUB_WORKFLOW_SHA': '9bd66390e112947c9241b3e2908ab0dda2173703', 'GITHUB_REF_NAME': 'main', 'GITHUB_JOB': 'github-pages', 'LD_LIBRARY_PATH': '/opt/hostedtoolcache/Python/3.12.16/x64/lib', 'XDG_RUNTIME_DIR': '/run/user/1001', 'AZURE_EXTENSION_DIR': '/opt/az/azcliextensions', 'GOROOT_1_26_X64': '/opt/hostedtoolcache/go/1.26.11/x64', 'GITHUB_REPOSITORY': 'addaix/openloops', 'Python2_ROOT_DIR': '/opt/hostedtoolcache/Python/3.12.16/x64', 'CHROME_BIN': '/usr/bin/google-chrome', 'ANDROID_NDK_ROOT': '/usr/local/lib/android/sdk/ndk/27.3.13750724', 'GITHUB_RETENTION_DAYS': '90', 'JOURNAL_STREAM': '10:15580', 'RUNNER_WORKSPACE': '/home/runner/work/openloops', 'GITHUB_ACTION_REPOSITORY': '', 'HCA_CLOUD_PROVIDER': 'azure', 'PATH': '/opt/hostedtoolcache/Python/3.12.16/x64/bin:/opt/hostedtoolcache/Python/3.12.16/x64:/snap/bin:/home/runner/.local/bin:/opt/pipx_bin:/home/runner/.cargo/bin:/home/runner/.config/composer/vendor/bin:/usr/local/.ghcup/bin:/home/runner/.dotnet/tools:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin', 'GITHUB_BASE_REF': '', 'GHCUP_INSTALL_BASE_PREFIX': '/usr/local', 'CI': 'true', 'SWIFT_PATH': '/usr/share/swift/usr/bin', 'ImageOS': 'ubuntu26', 'GITHUB_REPOSITORY_OWNER': 'addaix', 'GITHUB_HEAD_REF': '', 'GITHUB_ACTION_REF': '', 'ENABLE_RUNNER_TRACING': 'true', 'GITHUB_WORKFLOW': 'Continuous Integration', 'DEBIAN_FRONTEND': 'noninteractive', 'GITHUB_OUTPUT': '/home/runner/work/_temp/_runner_file_commands/set_output_d26455fb-372c-4670-899e-a670aadab12f', 'AGENT_TOOLSDIRECTORY': '/opt/hostedtoolcache', '_': '/opt/hostedtoolcache/Python/3.12.16/x64/bin/epythet', 'EPYTHET_PROJECT_DIR': '/home/runner/work/openloops/openloops', 'EPYTHET_OVERRIDES': '{"api_generator": "autosummary", "ignore": ["tests/", "scrap/", "examples/"]}', 'EPYTHET_BUILD_INFO': '{"schema_version": 1, "built_at": "2026-12-05T17:44:35Z", "package": {"name": "openloops", "version": "0.1.84", "display_name": "openloops", "source": "pyproject.toml"}, "git": {"available": true, "commit": "9bd66390e112947c9241b3e2908ab0dda2173703", "short_commit": "9bd6639", "branch": "main", "tags": [], "dirty": false, "remote_url": "https://github.com/addaix/openloops", "commit_url": "https://github.com/addaix/openloops/commit/9bd66390e112947c9241b3e2908ab0dda2173703", "error": null}, "ci": {"provider": "github", "repository": "addaix/openloops", "sha": "9bd66390e112947c9241b3e2908ab0dda2173703", "sha_in_history": true, "ref": "refs/heads/main", "ref_name": "main", "run_id": "47549397045", "run_url": "https://github.com/addaix/openloops/actions/runs/47549397045", "server_url": "https://github.com"}, "tools": {"epythet": "0.2.26", "sphinx": "9.1.1", "docutils": "0.22.4", "python": "3.12.16"}, "config": {"theme": "auto", "html_theme": "pydata_sphinx_theme", "accent": "#006d67", "mode": "auto", "api_generator": "autosummary", "ignore": ["tests/", "scrap/", "examples/"], "agent_outputs": true, "aggregates": ["md"], "ai_artifacts": true, "provenance": true, "docs_dir": "docsrc"}, "site": {"modules_documented": null, "objects_documented": null}, "pypi": {"checked": true, "latest": "0.1.84", "relation": "same", "error": null}, "reproduce": "git clone https://github.com/addaix/openloops && cd openloops\\\\ngit checkout 9bd66390e112947c9241b3e2908ab0dda2173703\\\\npip install \\\\"epythet==0.2.26\\\\"\\\\nepythet quickstart . --ignore tests/ scrap/ examples/", "warnings": [], "alignment": {"aligned": true, "notes": []}}', 'DOCUTILSCONFIG': '/home/runner/work/openloops/openloops/docsrc/docutils.conf'}), path=None)

The closer’s settings: the `closer` section of [`config_path()`](_autosummary/openloops.closer.html.md#openloops.closer.config_path), e.g.
`{"closer": {"owners": ["me", "my-org"], "shared_repos": ["my-org/a-shared-repo"]}}`.

`OPENLOOPS_CLOSE_OWNERS` (comma-separated), when set, replaces `owners` for one
run. A missing file means no settings; an unreadable one is an error, never a silent
default.

```pycon
>>> close_settings(environ={'OPENLOOPS_CLOSE_OWNERS': 'acme, widgets'},
...                path=Path('/nonexistent/c.json'))
CloseSettings(owners=('acme', 'widgets'), shared_repos=())
```

* **Return type:**
  [`CloseSettings`](_autosummary/openloops.closer.html.md#openloops.closer.CloseSettings)

### openloops.closer.config_path(, environ=None)

The person’s openloops settings file: `OPENLOOPS_CONFIG`, else
`$XDG_CONFIG_HOME/openloops/config.json` (`~/.config/openloops/config.json`).

```pycon
>>> config_path(environ={'OPENLOOPS_CONFIG': '/x/c.json'}).as_posix()
'/x/c.json'
>>> config_path(environ={'XDG_CONFIG_HOME': '/cfg'}).as_posix()
'/cfg/openloops/config.json'
```

* **Return type:**
  [`Path`](https://docs.python.org/3/library/pathlib.html#pathlib.Path)

### openloops.closer.read_issue(ref, \*, gh=<function \_gh_cli>)

The issue’s state, labels, author and body, plus its comments’ last lines.

Only each comment’s last line is read (where the marker lives), never whole
comments: they are other people’s text.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]

### openloops.closer.refusal(issue, , owners, login, shared_repos=())

Why this module must not write to *issue*, or `""`. The five conditions.

```pycon
>>> ok = {'ref': 'me/r#1', 'state': 'OPEN', 'labels': [{'name': 'manual-task'}],
...       'author': {'login': 'me'}}
>>> refusal(ok, owners=('me',), login='me')
''
>>> refusal({**ok, 'state': 'CLOSED'}, owners=('me',), login='me')
'the issue is not open'
>>> refusal(ok, owners=('client',), login='me')
"owner 'me' is not one this module may write to (closer.owners)"
>>> refusal({**ok, 'author': {'login': 'someone'}}, owners=('me',), login='me')
"filed by 'someone', not by the person's own login 'me'"
>>> refusal({**ok, 'outside_collaborators': 2}, owners=('me',), login='me')
'me/r is shared (2 outside collaborators): add it to closer.shared_repos to allow'
>>> refusal({**ok, 'outside_collaborators': 2}, owners=('me',), login='me',
...         shared_repos=('me/r',))
''
```

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### openloops.closer.report(ref, \*, attempt, ran='', ran_label='', outcome='done', check=None, check_source='', gh=<function \_gh_cli>, deliver=None, run_check=<function default_run_check>, owners=None, login=None, shared_repos=None, dry_run=False)

Report an outcome for one manual task; close it only if its check passes.

`outcome` is `done`, `failed` or `check-only` (nothing ran; the check is run to
see whether it is already done). `ran` is a one-line description of what ran (it is
scrubbed before it is posted); `ran_label` names it without its text (`"step s3 of
run plan p (ab12cd34)"`), and is what a comment on a repository that is not private
says instead of the command and the check. `check` overrides the issue’s own `**Verify:**`
command; `check_source` says where it came from (`"run plan <hash8>"`).

Returns `{ref, action, reason, check, check_status, commented}` where `action` is
one of `closed`, `attempted`, `open` (nothing ran and the check fails: nothing
written), `no-check` (reported in a comment when something ran; never closed) or
`refused` (a condition failed: nothing written). `dry_run` decides as usual and
writes nothing.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]

### openloops.closer.trusted_owners(\*, gh=<function \_gh_cli>, environ=environ({'SHELL': '/bin/bash', 'SELENIUM_JAR_PATH': '/usr/share/java/selenium-server.jar', 'GITHUB_WORKSPACE': '/home/runner/work/openloops/openloops', 'JAVA_HOME_11_X64': '/usr/lib/jvm/temurin-11-jdk-amd64', 'JAVA_HOME_25_X64': '/usr/lib/jvm/temurin-25-jdk-amd64', 'PROJECT_NAME': 'openloops', 'PKG_CONFIG_PATH': '/opt/hostedtoolcache/Python/3.12.16/x64/lib/pkgconfig', 'GITHUB_PATH': '/home/runner/work/_temp/_runner_file_commands/add_path_d26455fb-372c-4670-899e-a670aadab12f', 'GITHUB_ACTION': '_\_i2mint_epythet', 'JAVA_HOME': '/usr/lib/jvm/temurin-25-jdk-amd64', 'GITHUB_RUN_NUMBER': '353', 'RUNNER_NAME': 'GitHub Actions 1000004762', 'GRADLE_HOME': '/usr/share/gradle-9.9.3', 'GITHUB_REPOSITORY_OWNER_ID': '159425785', 'ACTIONS_RUNNER_ACTION_ARCHIVE_CACHE': '/opt/actionarchivecache', 'XDG_CONFIG_HOME': '/home/runner/.config', 'Python_ROOT_DIR': '/opt/hostedtoolcache/Python/3.12.16/x64', 'MEMORY_PRESSURE_WRITE': 'c29tZSAyMDAwMDAgMjAwMDAwMAA=', 'DOTNET_SKIP_FIRST_TIME_EXPERIENCE': '1', 'ANT_HOME': '/usr/share/ant', 'GITHUB_TRIGGERING_ACTOR': 'thorwhalen', 'pythonLocation': '/opt/hostedtoolcache/Python/3.12.16/x64', 'GITHUB_REF_TYPE': 'branch', 'HOMEBREW_CLEANUP_PERIODIC_FULL_DAYS': '3650', 'ACTIONS_RUNNER_RETURN_JOB_RESULT_FOR_HOSTED': '1', 'ANDROID_NDK': '/usr/local/lib/android/sdk/ndk/27.3.13750724', 'BOOTSTRAP_HASKELL_NONINTERACTIVE': '1', 'PWD': '/home/runner/work/openloops/openloops', 'PIPX_BIN_DIR': '/opt/pipx_bin', 'LOGNAME': 'runner', 'GITHUB_ARTIFACTS_LIST': '/home/runner/work/_temp/_runner_file_commands/artifacts_list_d26455fb-372c-4670-899e-a670aadab12f', 'GITHUB_REPOSITORY_ID': '1346350581', 'GITHUB_ACTIONS': 'true', 'USE_BAZEL_FALLBACK_VERSION': 'silent:', 'ANDROID_NDK_LATEST_HOME': '/usr/local/lib/android/sdk/ndk/30.0.16248370', 'SYSTEMD_EXEC_PID': '2153', 'GITHUB_SHA': '9bd66390e112947c9241b3e2908ab0dda2173703', 'GITHUB_WORKFLOW_REF': 'addaix/openloops/.github/workflows/ci.yml@refs/heads/main', 'POWERSHELL_DISTRIBUTION_CHANNEL': 'GitHub-Actions-Linux', 'RUNNER_ENVIRONMENT': 'github-hosted', 'DOTNET_MULTILEVEL_LOOKUP': '0', 'GOROOT_1_27_X64': '/opt/hostedtoolcache/go/1.27.4/x64', 'GITHUB_REF': 'refs/heads/main', 'RUNNER_OS': 'Linux', 'GITHUB_REF_PROTECTED': 'false', 'HOME': '/home/runner', 'GITHUB_API_URL': 'https://api.github.com', 'LANG': 'C.UTF-8', 'GOROOT_1_25_X64': '/opt/hostedtoolcache/go/1.25.14/x64', 'RUNNER_TRACKING_ID': 'github_d9e82dac-9ed8-476b-98ec-5be564bcae08', 'RUNNER_ARCH': 'X64', 'MEMORY_PRESSURE_WATCH': '/sys/fs/cgroup/system.slice/hosted-compute-agent.service/memory.pressure', 'RUNNER_TEMP': '/home/runner/work/_temp', 'GITHUB_STATE': '/home/runner/work/_temp/_runner_file_commands/save_state_d26455fb-372c-4670-899e-a670aadab12f', 'EDGEWEBDRIVER': '/usr/local/share/edge_driver', 'JAVA_HOME_21_X64': '/usr/lib/jvm/temurin-21-jdk-amd64', 'GITHUB_ENV': '/home/runner/work/_temp/_runner_file_commands/set_env_d26455fb-372c-4670-899e-a670aadab12f', 'GITHUB_EVENT_PATH': '/home/runner/work/_temp/_github_workflow/event.json', 'INVOCATION_ID': 'f2e4fc20649d403d8534d6c314f76312', 'GITHUB_EVENT_NAME': 'push', 'GITHUB_RUN_ID': '47549397045', 'JAVA_HOME_17_X64': '/usr/lib/jvm/temurin-17-jdk-amd64', 'ANDROID_NDK_HOME': '/usr/local/lib/android/sdk/ndk/27.3.13750724', 'GITHUB_STEP_SUMMARY': '/home/runner/work/_temp/_runner_file_commands/step_summary_d26455fb-372c-4670-899e-a670aadab12f', 'HOMEBREW_NO_AUTO_UPDATE': '1', 'GITHUB_ACTOR': 'thorwhalen', 'NVM_DIR': '/home/runner/.nvm', 'SGX_AESM_ADDR': '1', 'GITHUB_RUN_ATTEMPT': '1', 'ANDROID_HOME': '/usr/local/lib/android/sdk', 'GITHUB_GRAPHQL_URL': 'https://api.github.com/graphql', 'ACCEPT_EULA': 'Y', 'USER': 'runner', 'PSModulePath': '/root/.local/share/powershell/Modules:/usr/local/share/powershell/Modules:/opt/microsoft/powershell/7/Modules:/usr/share/az_15.6.1', 'GITHUB_ACTION_PATH': '/home/runner/work/_actions/i2mint/epythet/master/actions/publish-github-pages', 'GITHUB_SERVER_URL': 'https://github.com', 'PIPX_HOME': '/opt/pipx', 'GECKOWEBDRIVER': '/usr/local/share/gecko_driver', 'CHROMEWEBDRIVER': '/usr/local/share/chromedriver-linux64', 'SHLVL': '1', 'ANDROID_SDK_ROOT': '/usr/local/lib/android/sdk', 'VCPKG_INSTALLATION_ROOT': '/usr/local/share/vcpkg', 'GITHUB_ACTOR_ID': '1906276', 'ACTIONS_ORCHESTRATION_ID': 'b4a8399a-e2dd-813b-b879-38dd06e1f012.ci.github-pages._\_default', 'RUNNER_TOOL_CACHE': '/opt/hostedtoolcache', 'ImageVersion': '20261129.15.1', 'Python3_ROOT_DIR': '/opt/hostedtoolcache/Python/3.12.16/x64', 'DOTNET_NOLOGO': '1', 'GITHUB_ARTIFACTS': '/home/runner/work/_temp/_runner_file_commands/artifacts_d26455fb-372c-4670-899e-a670aadab12f', 'GITHUB_WORKFLOW_SHA': '9bd66390e112947c9241b3e2908ab0dda2173703', 'GITHUB_REF_NAME': 'main', 'GITHUB_JOB': 'github-pages', 'LD_LIBRARY_PATH': '/opt/hostedtoolcache/Python/3.12.16/x64/lib', 'XDG_RUNTIME_DIR': '/run/user/1001', 'AZURE_EXTENSION_DIR': '/opt/az/azcliextensions', 'GOROOT_1_26_X64': '/opt/hostedtoolcache/go/1.26.11/x64', 'GITHUB_REPOSITORY': 'addaix/openloops', 'Python2_ROOT_DIR': '/opt/hostedtoolcache/Python/3.12.16/x64', 'CHROME_BIN': '/usr/bin/google-chrome', 'ANDROID_NDK_ROOT': '/usr/local/lib/android/sdk/ndk/27.3.13750724', 'GITHUB_RETENTION_DAYS': '90', 'JOURNAL_STREAM': '10:15580', 'RUNNER_WORKSPACE': '/home/runner/work/openloops', 'GITHUB_ACTION_REPOSITORY': '', 'HCA_CLOUD_PROVIDER': 'azure', 'PATH': '/opt/hostedtoolcache/Python/3.12.16/x64/bin:/opt/hostedtoolcache/Python/3.12.16/x64:/snap/bin:/home/runner/.local/bin:/opt/pipx_bin:/home/runner/.cargo/bin:/home/runner/.config/composer/vendor/bin:/usr/local/.ghcup/bin:/home/runner/.dotnet/tools:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin', 'GITHUB_BASE_REF': '', 'GHCUP_INSTALL_BASE_PREFIX': '/usr/local', 'CI': 'true', 'SWIFT_PATH': '/usr/share/swift/usr/bin', 'ImageOS': 'ubuntu26', 'GITHUB_REPOSITORY_OWNER': 'addaix', 'GITHUB_HEAD_REF': '', 'GITHUB_ACTION_REF': '', 'ENABLE_RUNNER_TRACING': 'true', 'GITHUB_WORKFLOW': 'Continuous Integration', 'DEBIAN_FRONTEND': 'noninteractive', 'GITHUB_OUTPUT': '/home/runner/work/_temp/_runner_file_commands/set_output_d26455fb-372c-4670-899e-a670aadab12f', 'AGENT_TOOLSDIRECTORY': '/opt/hostedtoolcache', '_': '/opt/hostedtoolcache/Python/3.12.16/x64/bin/epythet', 'EPYTHET_PROJECT_DIR': '/home/runner/work/openloops/openloops', 'EPYTHET_OVERRIDES': '{"api_generator": "autosummary", "ignore": ["tests/", "scrap/", "examples/"]}', 'EPYTHET_BUILD_INFO': '{"schema_version": 1, "built_at": "2026-12-05T17:44:35Z", "package": {"name": "openloops", "version": "0.1.84", "display_name": "openloops", "source": "pyproject.toml"}, "git": {"available": true, "commit": "9bd66390e112947c9241b3e2908ab0dda2173703", "short_commit": "9bd6639", "branch": "main", "tags": [], "dirty": false, "remote_url": "https://github.com/addaix/openloops", "commit_url": "https://github.com/addaix/openloops/commit/9bd66390e112947c9241b3e2908ab0dda2173703", "error": null}, "ci": {"provider": "github", "repository": "addaix/openloops", "sha": "9bd66390e112947c9241b3e2908ab0dda2173703", "sha_in_history": true, "ref": "refs/heads/main", "ref_name": "main", "run_id": "47549397045", "run_url": "https://github.com/addaix/openloops/actions/runs/47549397045", "server_url": "https://github.com"}, "tools": {"epythet": "0.2.26", "sphinx": "9.1.1", "docutils": "0.22.4", "python": "3.12.16"}, "config": {"theme": "auto", "html_theme": "pydata_sphinx_theme", "accent": "#006d67", "mode": "auto", "api_generator": "autosummary", "ignore": ["tests/", "scrap/", "examples/"], "agent_outputs": true, "aggregates": ["md"], "ai_artifacts": true, "provenance": true, "docs_dir": "docsrc"}, "site": {"modules_documented": null, "objects_documented": null}, "pypi": {"checked": true, "latest": "0.1.84", "relation": "same", "error": null}, "reproduce": "git clone https://github.com/addaix/openloops && cd openloops\\\\ngit checkout 9bd66390e112947c9241b3e2908ab0dda2173703\\\\npip install \\\\"epythet==0.2.26\\\\"\\\\nepythet quickstart . --ignore tests/ scrap/ examples/", "warnings": [], "alignment": {"aligned": true, "notes": []}}', 'DOCUTILSCONFIG': '/home/runner/work/openloops/openloops/docsrc/docutils.conf'}), settings=None)

Whose trackers this module may write to: the configured owners, else the login.

```pycon
>>> trusted_owners(settings=CloseSettings(owners=('acme', 'widgets')))
('acme', 'widgets')
>>> trusted_owners(gh=lambda args, **kw: (0, 'me\n'), settings=CloseSettings())
('me',)
```

* **Return type:**
  [`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`...`](https://docs.python.org/3/builtins/constants.html#Ellipsis)]

### openloops.closer.who(\*, gh=<function \_gh_cli>, settings=None)

`(trusted owners, login, shared repos allowed)`, resolved once per run.

* **Return type:**
  [`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`...`](https://docs.python.org/3/builtins/constants.html#Ellipsis)], [`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`...`](https://docs.python.org/3/builtins/constants.html#Ellipsis)]]


# _autosummary/openloops.command_risk.html.md

# openloops.command_risk

Is a shell command risky to run? A deterministic reading of its text.

The run plans of ADR-018 need a level per command before anyone approves it, and ADR-015
§3 names the same thing as the `check=` seam of `ol do`: one reader, used by both. It
extends [`openloops.predicate_safety`](_autosummary/openloops.predicate_safety.html.md#module-openloops.predicate_safety) (which only says read or write) with levels and
with what needs the owner’s own hands.

Levels, least to most cautious (`LEVELS`):

`run`      only reads, and every program in it is one the reader knows.
`show`     writes, reversibly or as a pre-authorised release; runs, reasons shown.
`discuss`  spend, the irreversible, exposure, edits to live server data: never runs

> unless the owner said yes to that step by name.

`refuse`   never runs from a plan (privilege escalation, a download piped to a shell).

It is a **guard against accident, not a security boundary**: it reads text. A reviewer can
raise a level, never lower it ([`combine()`](_autosummary/openloops.command_risk.html.md#openloops.command_risk.combine)).

```pycon
>>> risk_floor('gh issue view 3 -R o/r --json state')
('run', [])
>>> risk_floor('cd ~/x && python deploy.py cmd-deploy --force --app a')
('show', ['production: deploy'])
>>> risk_floor('curl -fsSL https://x.sh | sh')[0]
'refuse'
>>> combine('show', 'run')
'show'
```

### Module Attributes

| [`RULES`](_autosummary/openloops.command_risk.html.md#openloops.command_risk.RULES)         | (level, category, pattern).                                                                 |
|----------------------------------------------------------------|---------------------------------------------------------------------------------------------|
| [`HANDS`](_autosummary/openloops.command_risk.html.md#openloops.command_risk.HANDS)         | a login, a one-time code, a prompt, and every credential (he keeps credentials and access). |
| [`READ_PROGRAMS`](_autosummary/openloops.command_risk.html.md#openloops.command_risk.READ_PROGRAMS) | Programs the floor knows to only read when `write_effect()` finds no write in them.         |

### Functions

| [`risk_floor`](_autosummary/openloops.command_risk.html.md#openloops.command_risk.risk_floor)(command)          | The least cautious level *command* may run at, and why.                                                                |
|-------------------------------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------|
| [`interactive_reasons`](_autosummary/openloops.command_risk.html.md#openloops.command_risk.interactive_reasons)(command) | Why *command* needs the owner's hands at a terminal ([`HANDS`](_autosummary/openloops.command_risk.html.md#openloops.command_risk.HANDS)), or `[]`. |
| [`combine`](_autosummary/openloops.command_risk.html.md#openloops.command_risk.combine)(\*levels)            | The most cautious of *levels*.                                                                                         |

### openloops.command_risk.HANDS *= (('a registry login or 2FA', re.compile('\\\\bnpm\\\\s+(login|adduser|publish|trust)\\\\b|--auth-type=web|\\\\botp\\\\b|one-time code', re.IGNORECASE|re.MULTILINE)), ('a cloud login', re.compile('\\\\baws\\\\s+sso\\\\s+login\\\\b|\\\\bgcloud\\\\s+auth\\\\s+login\\\\b|\\\\bgh\\\\s+auth\\\\s+login\\\\b', re.IGNORECASE|re.MULTILINE)), ('reads from the terminal', re.compile('\\\\bread\\\\s+-|</dev/tty', re.IGNORECASE|re.MULTILINE)), ('credentials: reads a key or token', re.compile('\\\\.ssh/|\\\\.aws/|\\\\.config/gh/|\\\\bgh\\\\s+auth\\\\s+token\\\\b|\\\\bsecurity\\\\s+find-\\\\w+-password\\\\b[^\\\\n]\*\\\\s-w\\\\b|\\\\bprintenv\\\\b', re.IGNORECASE|re.MULTILINE)), ('opens a browser', re.compile('(^|[\\\\s;&|])open\\\\s+(https?:|~|/|\\\\S+\\\\.html)', re.IGNORECASE|re.MULTILINE)), ('credentials: sets a secret', re.compile('\\\\bgh\\\\s+secret\\\\s+set\\\\b|\\\\bsecurity\\\\s+add-(generic|internet)-password\\\\b|tw-edit-secret|\\\\bset-repo-secrets\\\\b', re.IGNORECASE|re.MULTILINE)), ('credentials: creates or adds a key', re.compile('\\\\bssh-keygen\\\\b|\\\\bdeploy-key\\\\s+add\\\\b|rotate-ssh-key', re.IGNORECASE|re.MULTILINE)), ('credentials: reads a key file or key variable', re.compile('(^|[\\\\s\\'\\\\"=/])\\\\.(keys|env|netrc|npmrc|pypirc)\\\\b|\\\\$\\\\{?[A-Z_]\*(API_KEY|TOKEN|PASSWORD|SECRET)\\\\b', re.IGNORECASE|re.MULTILINE)))*

a login, a one-time code, a prompt,
and every credential (he keeps credentials and access). Such a step is marked
`interactive` and runs only in a run he starts from a terminal (`--tty`).

* **Type:**
  What needs the owner’s own hands at a terminal

### openloops.command_risk.READ_PROGRAMS *= frozenset({'[', '[[', 'awk', 'basename', 'brew', 'cat', 'cd', 'cmp', 'curl', 'cut', 'date', 'diff', 'dirname', 'echo', 'egrep', 'env', 'exit', 'false', 'fgrep', 'file', 'find', 'gh', 'git', 'grep', 'head', 'jq', 'ls', 'md5', 'npm', 'pip', 'pip3', 'pnpm', 'printf', 'pwd', 'realpath', 'rg', 'sed', 'sha256sum', 'shasum', 'sleep', 'sort', 'stat', 'tail', 'test', 'tr', 'true', 'type', 'uniq', 'uv', 'wc', 'which'})*

Programs the floor knows to only read when `write_effect()` finds no write in
them. `gh`, `git`, `curl`, `find`, `sed` and the package managers are judged
by their arguments there. Any other program is one the floor cannot read: `show`.

### openloops.command_risk.RULES *: [tuple](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[tuple](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[str](https://docs.python.org/3/builtins/stdtypes.html#str), [str](https://docs.python.org/3/builtins/stdtypes.html#str), [Pattern](https://docs.python.org/3/library/re.html#re.Pattern)], ...]* *= (('refuse', 'privilege escalation (sudo/su/doas)', re.compile('(^|[\\\\s;&|(\`\\'\\\\"])(sudo|su|doas)\\\\s', re.IGNORECASE|re.MULTILINE)), ('refuse', 'unreadable execution (download piped to a shell)', re.compile('(curl|wget)\\\\b[^|\\\\n]\*\\\\|\\\\s\*(sudo\\\\s+)?(ba|z|da|k)?sh\\\\b', re.IGNORECASE|re.MULTILINE)), ('refuse', 'disk or filesystem write (mkfs/dd of=/diskutil)', re.compile('\\\\bmkfs|\\\\bdd\\\\b[^\\\\n]\*\\\\bof=|\\\\bdiskutil\\\\s+(erase|partition)', re.IGNORECASE|re.MULTILINE)), ('refuse', "empties the agents' recycle bin", re.compile('agent-trash\\\\s+empty', re.IGNORECASE|re.MULTILINE)), ('discuss', 'money: cloud account or paid API', re.compile('\\\\baws\\\\s+(?!sso\\\\s+login)|\\\\bgcloud\\\\s|\\\\baz\\\\s|api\\\\.(elevenlabs|openai|anthropic)\\\\.|\\\\$\\\\{?(ANTHROPIC|OPENAI|ELEVENLABS|FAL)_API_KEY|--judge\\\\s+anthropic', re.IGNORECASE|re.MULTILINE)), ('discuss', 'irreversible: deletes through an API', re.compile('-X\\\\s\*DELETE\\\\b|--method\\\\s+DELETE\\\\b', re.IGNORECASE|re.MULTILINE)), ('discuss', 'irreversible: deletes files', re.compile('(^|[\\\\s;&|(\`\\'\\\\"])(rm|unlink|shred|rmdir)\\\\s|\\\\bfind\\\\b[^\\\\n]\*-delete\\\\b|\\\\bgit\\\\s+clean\\\\s+-\\\\w\*f', re.IGNORECASE|re.MULTILINE)), ('discuss', 'irreversible: discards git history or work', re.compile('\\\\bgit\\\\s+(reset\\\\s+--hard|push\\\\s+[^\\\\n]\*(--force|-f)\\\\b|branch\\\\s+-D\\\\b|checkout\\\\s+--\\\\s|restore\\\\s)|rsync\\\\b[^\\\\n]\*--delete', re.IGNORECASE|re.MULTILINE)), ('discuss', 'irreversible: deletes a repo or release', re.compile('\\\\bgh\\\\s+(repo|release)\\\\s+delete\\\\b', re.IGNORECASE|re.MULTILINE)), ('discuss', 'exposure: makes a site or repo public', re.compile('/pages\\\\b[^\\\\n]\*-X\\\\s\*POST|-X\\\\s\*POST[^\\\\n]\*/pages\\\\b|--visibility\\\\s+public|\\\\bgh\\\\s+repo\\\\s+edit\\\\b[^\\\\n]\*visibility', re.IGNORECASE|re.MULTILINE)), ('discuss', 'production: edits server files outside a checkout', re.compile('\\\\bssh\\\\s+\\\\S+\\\\s(?=[^\\\\n]\*(/opt/|/etc/|/var/))(?=[^\\\\n]\*(\\\\bsed\\\\s+-i|>|\\\\bmv\\\\b|\\\\bcp\\\\b|\\\\bln\\\\b|\\\\btee\\\\b))', re.IGNORECASE|re.MULTILINE)), ('show', 'production: deploy', re.compile('cmd\\\\-deploy|deploy\\\\.py|deploy\\\\.sh|tw\\\\-deploy|tw\\\\-edit\\\\-secret', re.IGNORECASE|re.MULTILINE)), ('show', 'production: service restart', re.compile('\\\\bsystemctl\\\\s+(restart|reload)\\\\b|\\\\blaunchctl\\\\s+(kickstart|bootout|load|unload)\\\\b', re.IGNORECASE|re.MULTILINE)), ('show', 'publication: registry publish', re.compile('\\\\b(npm|pnpm|yarn)\\\\s+publish\\\\b|\\\\btwine\\\\s+upload\\\\b|\\\\buv\\\\s+publish\\\\b|\\\\bcargo\\\\s+publish\\\\b|\\\\bgh\\\\s+release\\\\s+create\\\\b|\\\\bnpm\\\\s+trust\\\\s+github\\\\b', re.IGNORECASE|re.MULTILINE)), ('show', 'merges a pull request', re.compile('\\\\bgh\\\\s+pr\\\\s+merge\\\\b', re.IGNORECASE|re.MULTILINE)), ('show', 'changes GitHub settings', re.compile('\\\\bgh\\\\s+api\\\\s+[^\\\\n]\*-X\\\\s\*(PUT|PATCH|POST)\\\\b|\\\\bgh\\\\s+api\\\\s+-X\\\\s\*(PUT|PATCH|POST)\\\\b', re.IGNORECASE|re.MULTILINE)), ('show', 'pushes git commits', re.compile('\\\\bgit\\\\s+push\\\\b', re.IGNORECASE|re.MULTILINE)), ('show', 'starts a CI workflow', re.compile('\\\\bgh\\\\s+(workflow|run)\\\\s+(run|rerun)\\\\b', re.IGNORECASE|re.MULTILINE)), ('show', 'writes on another machine', re.compile('\\\\bssh\\\\s+\\\\S+\\\\s+[\\'\\\\"]?[^\\\\n]\*(>|\\\\bmv\\\\b|\\\\bmkdir\\\\b|\\\\bsed\\\\s+-i|\\\\bln\\\\b)|\\\\bscp\\\\b|\\\\brsync\\\\b', re.IGNORECASE|re.MULTILINE)), ('show', "moves files to the agents' bin (agent-trash restore undoes it)", re.compile('\\\\bagent-trash\\\\s+put\\\\b', re.IGNORECASE|re.MULTILINE)), ('refuse', 'unreadable execution (a shell given a download)', re.compile('\\\\b(ba|z|da|k)?sh\\\\b[^\\\\n]\*(\\\\$\\\\(|<\\\\()\\\\s\*(curl|wget)\\\\b', re.IGNORECASE|re.MULTILINE)), ('refuse', 'unreadable execution (download piped to an interpreter)', re.compile('(curl|wget)\\\\b[^|\\\\n]\*\\\\|\\\\s\*(sudo\\\\s+)?(python\\\\d?(\\\\.\\\\d+)?|perl|ruby|node)\\\\b', re.IGNORECASE|re.MULTILINE)), ('discuss', 'irreversible: discards git history or work', re.compile('\\\\bgit(\\\\s+(-C|-c|--git-dir|--work-tree)\\\\s+\\\\S+)\*\\\\s+(reset\\\\s+--hard|clean\\\\s+(-\\\\w+\\\\s+)\*-\\\\w\*f|branch\\\\s+(-D|--delete\\\\s+--force)|push\\\\s+[^\\\\n]\*(--force|\\\\s-f\\\\b|--delete|\\\\s\\\\+\\\\S|\\\\s:\\\\S)|chec, re.IGNORECASE|re.MULTILINE)), ('discuss', 'irreversible: deletes through an API', re.compile('--method[=\\\\s]+DELETE\\\\b|--request[=\\\\s]+DELETE\\\\b', re.IGNORECASE|re.MULTILINE)), ('discuss', 'irreversible: deletes a GitHub object', re.compile('\\\\bgh\\\\s+(issue|secret|variable|gist|label|cache|run)\\\\s+delete\\\\b', re.IGNORECASE|re.MULTILINE)), ('discuss', 'irreversible: withdraws a published release', re.compile('\\\\bnpm\\\\s+(unpublish|deprecate)\\\\b|\\\\bcargo\\\\s+yank\\\\b', re.IGNORECASE|re.MULTILINE)), ('discuss', 'irreversible: deletes data or volumes', re.compile('\\\\bdown\\\\s+(-\\\\w\*v\\\\w\*|--volumes)\\\\b|\\\\bsystem\\\\s+prune\\\\b|\\\\bvolume\\\\s+(rm|prune)\\\\b|\\\\bDROP\\\\s+(TABLE|DATABASE|SCHEMA)\\\\b|\\\\bTRUNCATE\\\\s+TABLE\\\\b', re.IGNORECASE|re.MULTILINE)), ('discuss', 'irreversible: deletes files', re.compile('(^|[\\\\s;&|(\`\\'\\\\"])(\\\\\\\\rm|/bin/rm|/usr/bin/rm)\\\\s|\\\\bxargs\\\\s+(-\\\\S+\\\\s+)\*rm\\\\b', re.IGNORECASE|re.MULTILINE)), ('discuss', 'exposure: makes a site or repo public', re.compile('\\\\bgh\\\\s+(repo|gist)\\\\s+create\\\\b[^\\\\n]\*--public|private=false|\\\\bgh\\\\s+api\\\\s+[^\\\\n]\*/pages\\\\b[^\\\\n]\*\\\\s-(f|F|-field|-raw-field)\\\\s', re.IGNORECASE|re.MULTILINE)), ('show', 'writes a file (awk system, curl -o, sort -o)', re.compile('\\\\bawk\\\\b[^\\\\n]\*system\\\\(|\\\\bcurl\\\\b[^\\\\n]\*\\\\s(-o|--output)\\\\s|\\\\bsort\\\\b[^\\\\n]\*\\\\s-o\\\\s', re.IGNORECASE|re.MULTILINE)))*

(level, category, pattern). The first column is the floor for a match. The list
follows what the owner keeps (spend, the irreversible, exposure) rather than generic
danger words: deploying merged code and publishing are pre-authorised releases, so
they run at `show`; a credential or a login is not a level but needs his hands
([`HANDS`](_autosummary/openloops.command_risk.html.md#openloops.command_risk.HANDS)).

### openloops.command_risk.combine(\*levels)

The most cautious of *levels*. An unknown level counts as `discuss`.

```pycon
>>> combine('run', 'refuse', 'show')
'refuse'
>>> combine('run', 'banana')
'discuss'
```

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### openloops.command_risk.interactive_reasons(command)

Why *command* needs the owner’s hands at a terminal ([`HANDS`](_autosummary/openloops.command_risk.html.md#openloops.command_risk.HANDS)), or `[]`.

```pycon
>>> interactive_reasons('npm login && npm publish --access public')
['a registry login or 2FA']
>>> interactive_reasons('gh issue view 1')
[]
```

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]

### openloops.command_risk.risk_floor(command)

The least cautious level *command* may run at, and why. Deterministic.

A command that only reads (openloops’ predicate guard finds no write) is `run`. A
write that matches no category is `show`: the floor never calls an unread write
harmless. Text the guard cannot parse is `discuss`.

```pycon
>>> risk_floor('git -C ~/r log -1')
('run', [])
>>> risk_floor('cd ~/r && git pull -q --ff-only')
('show', ['writes: git pull'])
>>> risk_floor('agent-trash put ~/x --reason old')
('show', ["moves files to the agents' bin (agent-trash restore undoes it)"])
>>> risk_floor('cd ~/p && python scripts/x.py --apply')
('show', ['runs programs the floor cannot read: python'])
>>> risk_floor("echo 'unbalanced")
('discuss', ['unreadable: unparseable'])
>>> risk_floor('rm -rf ~/build')[0]
'discuss'
```

* **Return type:**
  [`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]]


# _autosummary/openloops.command_syntax.html.md

# openloops.command_syntax

Does each command of a run plan use only flags its program knows? (ADR-018)

A plan is checked before it is saved, so a step that would die on its first word
(`unrecognized arguments: --trust`) is caught by the planner, not by the owner at run
time. The check is cheap and read-only: for every simple command that passes long flags,
it asks the program for its help text (`<program> [<subcommand>...] --help`, no stdin,
pagers off, a short timeout) and reports the long flags the help never mentions.

It is a warning, not a proof. Help text that cannot be had (a program that does not
answer `--help`, BSD tools) is reported as such, and a program whose help omits some
flags gives false alarms; the planner reads each one. What it cannot see at all is a
requirement that depends on run-time state (“revive requires –cwd” when there is
nothing to resume): the runbook skill covers that by asking for every argument the
fallback path needs.

One seam: `help_of=`, `(argv) -> str` (empty when no help could be had), default
[`help_text()`](_autosummary/openloops.command_syntax.html.md#openloops.command_syntax.help_text).

### Module Attributes

| [`SKIP_PROGRAMS`](_autosummary/openloops.command_syntax.html.md#openloops.command_syntax.SKIP_PROGRAMS)   | Shell builtins and small tools whose flags are not worth a `--help` round trip (and whose BSD versions answer `--help` with an error).   |
|------------------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------|
| [`LEAD_OPTIONS`](_autosummary/openloops.command_syntax.html.md#openloops.command_syntax.LEAD_OPTIONS)    | Options a program takes before its subcommand, each with how many values follow it.                                                      |
| [`LAUNCHERS`](_autosummary/openloops.command_syntax.html.md#openloops.command_syntax.LAUNCHERS)       | Programs that run a script or module named next, whose own subcommands follow it.                                                        |

### Functions

| [`help_text`](_autosummary/openloops.command_syntax.html.md#openloops.command_syntax.help_text)(argv[, cwd, timeout])                  | `argv --help`'s output (run in *cwd*), or `""` when the program gives none (missing, an error without a usage line, a timeout, no option named) or when asking could run it (`_answers_help()`).   |
|---------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| [`long_flags`](_autosummary/openloops.command_syntax.html.md#openloops.command_syntax.long_flags)(words)                                | The `--long` options in *words* (values after `=` dropped), in order, once each.                                                                                                                   |
| [`subcommand_path`](_autosummary/openloops.command_syntax.html.md#openloops.command_syntax.subcommand_path)(words, \*[, depth])              | The program and up to *depth* subcommand-looking words after it.                                                                                                                                   |
| [`unknown_flags`](_autosummary/openloops.command_syntax.html.md#openloops.command_syntax.unknown_flags)(command, \*[, cwd, help_of, skip]) | Per simple command with long flags: the flags its help text never mentions.                                                                                                                        |

### openloops.command_syntax.LAUNCHERS *= frozenset({'bun', 'deno', 'node', 'python', 'python3'})*

Programs that run a script or module named next, whose own subcommands follow it.

### openloops.command_syntax.LEAD_OPTIONS *: [dict](https://docs.python.org/3/builtins/stdtypes.html#dict)[[str](https://docs.python.org/3/builtins/stdtypes.html#str), [dict](https://docs.python.org/3/builtins/stdtypes.html#dict)[[str](https://docs.python.org/3/builtins/stdtypes.html#str), [int](https://docs.python.org/3/builtins/functions.html#int)]]* *= {'gh': {'--repo': 1, '-R': 1}, 'git': {'--no-pager': 0, '-C': 1, '-P': 0, '-c': 1}}*

Options a program takes before its subcommand, each with how many values follow it.

### openloops.command_syntax.SKIP_PROGRAMS *= frozenset({'.', '[', '[[', 'awk', 'basename', 'cat', 'cd', 'chmod', 'command', 'cp', 'cut', 'date', 'dirname', 'echo', 'env', 'eval', 'exec', 'exit', 'export', 'false', 'find', 'grep', 'head', 'ln', 'ls', 'mkdir', 'mv', 'printf', 'read', 'return', 'rmdir', 'sed', 'seq', 'set', 'shift', 'sleep', 'sort', 'source', 'stat', 'tail', 'tee', 'test', 'touch', 'tr', 'true', 'type', 'uniq', 'unset', 'wait', 'wc', 'xargs'})*

Shell builtins and small tools whose flags are not worth a `--help` round trip
(and whose BSD versions answer `--help` with an error).

### openloops.command_syntax.help_text(argv, cwd=None, , timeout=20.0)

`argv --help`’s output (run in *cwd*), or `""` when the program gives none
(missing, an error without a usage line, a timeout, no option named) or when asking
could run it (`_answers_help()`).

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### openloops.command_syntax.long_flags(words)

The `--long` options in *words* (values after `=` dropped), in order, once each.

```pycon
>>> long_flags(['crowsnest', 'revive', 'x', '--trust', '--cwd=/a', '--', '--not'])
['--trust', '--cwd']
```

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]

### openloops.command_syntax.subcommand_path(words, , depth=2)

The program and up to *depth* subcommand-looking words after it.

```pycon
>>> subcommand_path(['crowsnest', 'revive', 'yoga', '--trust'])
['crowsnest', 'revive', 'yoga']
>>> subcommand_path(['gh', 'issue', 'comment', '46', '-R', 'o/r'])
['gh', 'issue', 'comment']
>>> subcommand_path(['git', '-C', 'x', 'pull', '-q', '--ff-only'])
['git', 'pull']
>>> subcommand_path(['python', '-m', 'desk', 'pin-passkeys', '--name', 'jobs'])
['python', '-m', 'desk', 'pin-passkeys']
>>> subcommand_path(['python', 'deploy.py', 'cmd-deploy', '--app', 'x'])
['python', 'deploy.py', 'cmd-deploy']
```

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]

### openloops.command_syntax.unknown_flags(command, \*, cwd=None, help_of=<function help_text>, skip=frozenset({'.', '[', '[[', 'awk', 'basename', 'cat', 'cd', 'chmod', 'command', 'cp', 'cut', 'date', 'dirname', 'echo', 'env', 'eval', 'exec', 'exit', 'export', 'false', 'find', 'grep', 'head', 'ln', 'ls', 'mkdir', 'mv', 'printf', 'read', 'return', 'rmdir', 'sed', 'seq', 'set', 'shift', 'sleep', 'sort', 'source', 'stat', 'tail', 'tee', 'test', 'touch', 'tr', 'true', 'type', 'uniq', 'unset', 'wait', 'wc', 'xargs'}))

Per simple command with long flags: the flags its help text never mentions.

Help is asked in the folder the command would be in: *cwd*, then each `cd DIR`
met along the way (a `cd` to a computed path leaves the folder unknown).

Each finding is `{"command": "<program subcommand>", "unknown": [...]}`, or
`{"command": ..., "unknown": [], "no_help": True}` when no help could be had.

```pycon
>>> helps = {('crowsnest', 'revive', 'yoga'): 'usage: revive [--cwd CWD] [--home HOME]'}
>>> unknown_flags('crowsnest revive yoga --trust', help_of=lambda a, c: helps.get(tuple(a), ''))
[{'command': 'crowsnest revive yoga', 'unknown': ['--trust']}]
>>> unknown_flags('crowsnest revive yoga --cwd x', help_of=lambda a, c: helps.get(tuple(a), ''))
[]
>>> unknown_flags('cd ~/x && ls --color', help_of=lambda a, c: '')
[]
```

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]]


# _autosummary/openloops.dashboard.html.md

# openloops.dashboard

One page you can look at instead of reading three command outputs.

[`render_dashboard()`](_autosummary/openloops.dashboard.html.md#openloops.dashboard.render_dashboard) takes what [`openloops.owed()`](_autosummary/openloops.html.md#openloops.owed), [`openloops.blocked()`](_autosummary/openloops.html.md#openloops.blocked)
and `openloops.ls()` returned and renders a single self-contained HTML document —
no stylesheet, no script, no font and no request to anywhere. That is not decoration:
the page is meant to be published, and a published page runs no `gh`, shells out to
nothing and reaches no network.

So **the page is a snapshot, and it says so in its largest type.** This module inverts
the one rule [`openloops.digest`](_autosummary/openloops.digest.html.md#module-openloops.digest) holds to — a digest deliberately stamps no
generation time so that regenerating it is byte-stable — because here the generation
time is the whole claim. `made_at` is a required-in-practice argument rather than a
hidden `now()`, which is also what lets a test compare bytes.

The four registers are ordered the way a person needs them, and the fourth is the one
the package exists for:

1. **Needs you now** — obligations still open, each printing the predicate that decided
   it, unabbreviated, so a reader can disagree with the verdict rather than absorb it.
2. **Free to proceed** — blocker edges that have all closed, led by how many days the
   work has been free while nothing anywhere said so.
3. **In flight** — what the sessions left open, newest last turn first.
4. **Unknown** — every `?`, with why. It carries the envelope-level failures too: an
   `owed` that could not list is not “nothing owed”, and rendering it as `0` would
   make this page worse than no page. When the count really is zero the section says
   which checks earned that, because a clean board with no provenance is the same lie
   told quietly.

Everything this module prints goes through [`Sanitizer`](_autosummary/openloops.dashboard.html.md#openloops.dashboard.Sanitizer), which is
[`openloops.egress.scrub()`](_autosummary/openloops.egress.html.md#openloops.egress.scrub) plus HTML escaping plus a scheme allowlist on every link.
The one carve-out is the shared kit below: [`register()`](_autosummary/openloops.dashboard.html.md#openloops.dashboard.register) and [`rail()`](_autosummary/openloops.dashboard.html.md#openloops.dashboard.rail) \*\*escape
nothing\*\*. Every argument they take is markup, interpolated as given and some of it into
an unquoted attribute, because that is what a markup builder is; a caller that passes
anything it did not write itself puts it through [`Sanitizer`](_autosummary/openloops.dashboard.html.md#openloops.dashboard.Sanitizer) first. This module
passes literals. A page that carries a
repository name and an issue title is fine; one that carries a home path or a token is
the failure `openloops.egress` exists to prevent, and this renderer scrubs its input
rather than trusting it. A credential-shaped field is *withheld and counted*, never
silently dropped — the count is printed in the footer.

`CSS`, [`Sanitizer`](_autosummary/openloops.dashboard.html.md#openloops.dashboard.Sanitizer), [`register()`](_autosummary/openloops.dashboard.html.md#openloops.dashboard.register) and [`rail()`](_autosummary/openloops.dashboard.html.md#openloops.dashboard.rail) are public for
sibling renderers — a tool that shows a different half of the same picture and wants to
look like this page — so that the look, the egress rule and the markup the stylesheet
dresses stay in one place instead of being copied and drifting. They are the shared kit:
the stylesheet here is what makes `register--needs` a colour and `rail` a column, so
a package that writes those class names by hand is one rename away from a broken page.

```pycon
>>> html = render_dashboard({}, {}, [], made_at='2026-01-01T00:00:00Z')
>>> '<title>' in html and 'snapshot' in html
True
```

### Module Attributes

| [`DFLT_TITLE`](_autosummary/openloops.dashboard.html.md#openloops.dashboard.DFLT_TITLE)                 | What the page is called — in the tab, in a gallery, and in its own masthead.   |
|-----------------------------------------------------------------------------|--------------------------------------------------------------------------------|
| [`DFLT_MAX_SESSIONS`](_autosummary/openloops.dashboard.html.md#openloops.dashboard.DFLT_MAX_SESSIONS)          | How many session rows are printed.                                             |
| [`DFLT_PUBLISHED_PER_SESSION`](_autosummary/openloops.dashboard.html.md#openloops.dashboard.DFLT_PUBLISHED_PER_SESSION) | How many documents each session shows in the "Handed to you" register.         |
| [`GAUGE_FULL_DAYS`](_autosummary/openloops.dashboard.html.md#openloops.dashboard.GAUGE_FULL_DAYS)            | Where the age gauge tops out.                                                  |

### Functions

| [`headline_counts`](_autosummary/openloops.dashboard.html.md#openloops.dashboard.headline_counts)(owed, blocked, sessions)           | The four figures across the top of the page.                                    |
|-----------------------------------------------------------------------------------------------------|---------------------------------------------------------------------------------|
| [`rail`](_autosummary/openloops.dashboard.html.md#openloops.dashboard.rail)(chip, tone, age[, unit, extra])               | The fixed left column of every row: what state it is in, and for how long.      |
| [`register`](_autosummary/openloops.dashboard.html.md#openloops.dashboard.register)(\*, ident, name, figure, tone, rule, ...) | One band: a heading, the count in the largest figure on the page, and its rule. |
| [`render_dashboard`](_autosummary/openloops.dashboard.html.md#openloops.dashboard.render_dashboard)(owed, blocked, sessions, \*)      | The three envelopes as one self-contained HTML page.                            |
| [`unchecked_count`](_autosummary/openloops.dashboard.html.md#openloops.dashboard.unchecked_count)(owed, blocked)                     | How many OBLIGATIONS could not be checked against the world.                    |
| [`unknown_count`](_autosummary/openloops.dashboard.html.md#openloops.dashboard.unknown_count)(owed, blocked, sessions)             | How many things read `?`, or `None` when even that cannot be counted.           |

### Classes

| [`Sanitizer`](_autosummary/openloops.dashboard.html.md#openloops.dashboard.Sanitizer)([aliases])   | Scrub, then escape.   |
|-------------------------------------------------------------------------|-----------------------|

### openloops.dashboard.DFLT_MAX_SESSIONS *= 40*

How many session rows are printed. The register states the true total either way; a
page that showed all 150-odd would bury the two registers above it.

### openloops.dashboard.DFLT_PUBLISHED_PER_SESSION *= 3*

How many documents each session shows in the “Handed to you” register.

### openloops.dashboard.DFLT_TITLE *= 'Open Loops Board'*

What the page is called — in the tab, in a gallery, and in its own masthead.

### openloops.dashboard.GAUGE_FULL_DAYS *= 90*

Where the age gauge tops out. Ninety days is the point past which the length of the
bar stops being informative and the number beside it is doing all the work.

### *class* openloops.dashboard.Sanitizer(aliases=None)

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

Scrub, then escape. The single path from an envelope to the document.

Two failures are possible and they are treated differently, exactly as
[`openloops.egress`](_autosummary/openloops.egress.html.md#module-openloops.egress) prescribes. A home path is *rewritten* — it is an identifier
and the tail is the part a reader needs. A credential is *withheld and counted*: the
field is replaced by a visible notice naming the pattern class, never the text, and
`withheld` is printed in the footer so the run reports it rather than quietly
losing a field.

```pycon
>>> s = Sanitizer()
>>> s.text('a < b')
'a &lt; b'
>>> s.text('token=' + 'ghp_' + 'A' * 36)
'[withheld: credential-shaped text (github_token)]'
>>> s.withheld
['github_token']
```

#### text(value)

One field, safe to place in the document.

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

#### url(value)

A link target, or `''` when it is not one this page will follow.

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### openloops.dashboard.headline_counts(owed, blocked, sessions)

The four figures across the top of the page. `None` is `?`, never a zero.

Shared by the masthead and by [`openloops.tools.dashboard()`](_autosummary/openloops.tools.html.md#openloops.tools.dashboard), so the number a
caller reads back is the number the page printed.

```pycon
>>> headline_counts({'listed': True, 'counts': {'open': 2}, 'rows': []},
...                 {'listed': False}, [])['free_to_proceed'] is None
True
```

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`int`](https://docs.python.org/3/builtins/functions.html#int) | [`None`](https://docs.python.org/3/builtins/constants.html#None)]

### openloops.dashboard.rail(chip, tone, age, unit='d', , extra='')

The fixed left column of every row: what state it is in, and for how long.

Shared kit (see the module docstring): `CSS` styles `rail`, `chip`,
`chip--<tone>` and `age`, so a sibling renderer that builds this by hand breaks
the next time a class name here changes.

`age` is the figure beside the unit — a number, or `None` for the `?` that
means nobody knows. It is not required to be a day count: pass a string and a
`unit` of your own for a page whose durations run from seconds to days.

`extra` is further markup placed between the state chip and the age — a second
chip a sibling page needs and this one has no equivalent of.

Nothing here is escaped, `extra` least of all: see the module docstring.

```pycon
>>> rail("owed", "needs", 3)
'<div class="rail"><span class="chip chip--needs">owed</span><span class="age"><b>3</b><i>d</i></span></div>'
```

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### openloops.dashboard.register(, ident, name, figure, tone, rule, body, folds=False, start_open=False, extra='')

One band: a heading, the count in the largest figure on the page, and its rule.

Shared kit (see the module docstring): `CSS` styles `register`,
`register--<tone>` and `register-head`, laying the head out as `auto 1fr` —
the figure in the first column, the heading and the rule in the second.

`folds` renders the band as a `<details>` a person can close, `start_open`
opening it anyway; both default off, which is the plain `<section>` this page has
always rendered. A `<summary>` may hold phrasing content and a heading only, so
the folding head carries the figure and the rule as `<span>``s rather than
``<p>``s. :data:`CSS` places those three flat children into the same ``auto 1fr`
grid a plain section’s head uses (figure down column one across both rows, heading
and rule down column two) and restores the disclosure affordance a
`display:grid` summary would otherwise cost it (#13).
`start_open` is ignored when `folds` is false — there is no disclosure to open —
because a caller decides `folds` from whether it has rows and passes both.

A band with nothing in it is not worth folding — there is nothing to hide — so that
decision belongs to the caller, which knows whether its body is rows.

`extra` is markup that heads the band’s body. A `<summary>` may not hold
interactive content and what a caller puts here is usually a control, so in the
`<details>` it goes inside the body; in the `<section>` it stays in the head,
under the rule. That is above the head’s hairline in one form and below it in the
other, which is how the caller that needs it already reads.

Nothing here is escaped: see the module docstring. `ident` and `tone` reach an
unquoted attribute, so they are the two that must be literals or already safe.

```pycon
>>> register(ident="x", name="Needs you", figure="2", tone="needs", rule="now", body="")
'<section class="register register--needs" id="x"><div class="register-head"><p class="figure">2</p><div><h2>Needs you</h2><p class="rule">now</p></div></div></section>'
>>> register(ident="x", name="Quiet", figure="9", tone="done", rule="why", body="",
...          folds=True, start_open=True)
'<details class="register register--done" id="x" open><summary class="register-head"><span class="figure">9</span><h2>Quiet</h2><span class="rule">why</span></summary></details>'
```

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### openloops.dashboard.render_dashboard(owed, blocked, sessions, , made_at=None, source='', title='Open Loops Board', max_sessions=40, standalone=True, aliases=None, published=None, published_per_session=3)

The three envelopes as one self-contained HTML page. No network, no script.

`owed` and `blocked` are the envelopes [`openloops.owed()`](_autosummary/openloops.html.md#openloops.owed) and
[`openloops.blocked()`](_autosummary/openloops.html.md#openloops.blocked) return; `sessions` is the list `openloops.ls()`
returns. All three may be empty mappings, and an envelope whose `listed` is
`False` renders as `?` throughout rather than as zero.

`made_at` is the moment the snapshot was taken and is printed in the largest type
on the page. It defaults to now, but a caller that wants a byte-stable page passes
it — this is the one module in openloops that stamps a generation time, and it does
so because the whole claim of the page is *when*.

`standalone` wraps the output in a document scaffold for a file you open yourself.
Pass `False` for a host that supplies its own `<head>` — a published artifact
does — and the same page comes back as title, styles and content only.

`max_sessions` bounds the in-flight register; the true total is stated either way.

`published` is the envelope `openloops.published()` returns. When given, a
“Handed to you” register lists each session’s most recent documents
(`published_per_session` of them, with the true total stated); an envelope that
never listed renders as unknown, not as “nothing published”. When omitted the
register is left out, so the page is the one it always was.

```pycon
>>> page = render_dashboard(
...     {'listed': False, 'error': 'gh: not logged in', 'counts': {}},
...     {'listed': True, 'counts': {'unblocked': 0, 'total': 0}, 'rows': []},
...     [], made_at='2026-01-01T00:00:00Z')
>>> 'gh: not logged in' in page and 'could not' in page
True
```

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### openloops.dashboard.unchecked_count(owed, blocked)

How many OBLIGATIONS could not be checked against the world. `None` if unknowable.

Deliberately narrower than [`unknown_count()`](_autosummary/openloops.dashboard.html.md#openloops.dashboard.unknown_count), and the two must not be merged in
the masthead. A `?` on an obligation means *the world could not be reached* — a
timeout, a missing `gh`, an untrusted owner. A low-confidence session digest means
something else entirely: the digest half checks nothing against the world by design,
so it has nothing it was unable to check. Rolling forty of the second into the first
reports a crisis of forty when the real number is one, and in the alarming direction.

```pycon
>>> unchecked_count({'listed': True, 'rows': [{'state': 'unknown'}]},
...                 {'listed': True, 'rows': []})
1
>>> unchecked_count({'listed': False}, {'listed': True, 'rows': []}) is None
True
```

* **Return type:**
  [`int`](https://docs.python.org/3/builtins/functions.html#int) | [`None`](https://docs.python.org/3/builtins/constants.html#None)

### openloops.dashboard.unknown_count(owed, blocked, sessions)

How many things read `?`, or `None` when even that cannot be counted.

A register that never listed could be hiding any number of unknown rows, so the
headline figure for unknowns is itself unknown. Reporting `2` there — the two
failures we happen to know about — is the exact shape of the lie this page is
against, and it is a lie a reader has no way to spot.

It counts the rows that read `?`, not the entries in the list below: one entry
can stand for forty sessions, and reporting `1` for those would be the tidier
number rather than the true one.

```pycon
>>> unknown_count({'listed': True, 'rows': []}, {'listed': True, 'rows': []}, [{}])
0
>>> lows = [{'confidence': 'low'}] * 5
>>> unknown_count({'listed': True, 'rows': []}, {'listed': True, 'rows': []}, lows)
5
>>> unknown_count({'listed': False}, {'listed': True, 'rows': []}, [{}]) is None
True
```

* **Return type:**
  [`int`](https://docs.python.org/3/builtins/functions.html#int) | [`None`](https://docs.python.org/3/builtins/constants.html#None)


# _autosummary/openloops.digest.html.md

# openloops.digest

Rendering one session into one dated markdown digest. No model, no network.

The whole of the release’s honesty rule lives in this module:

> **A digest states what the session said, dated — never what is currently true.**

So every heading here carries the timestamp of the thing under it, the loop state is
phrased as a reading of the transcript rather than a claim about the world, and the
front matter says `verified: false` because nothing has been checked against
anything. ADR-015’s failure mode — a snapshot of local state that was already wrong on
two of four fields, published and handed to a consumer that acted on it — is what these
rules exist to prevent, and the way to prevent it is to never make the claim.

[`render()`](_autosummary/openloops.digest.html.md#openloops.digest.render) is a pure function of its [`Session`](_autosummary/openloops.base.html.md#openloops.base.Session) and
[`Verdict`](_autosummary/openloops.base.html.md#openloops.base.Verdict). It stamps no generation time, which is what allows
`tests/test_sync.py` to delete the entire store, regenerate, and compare bytes.

### Module Attributes

| [`SECTION_LIMITS`](_autosummary/openloops.digest.html.md#openloops.digest.SECTION_LIMITS)   | How much of each section is kept.   |
|-------------------------------------------------------------------|-------------------------------------|

### Functions

| [`render`](_autosummary/openloops.digest.html.md#openloops.digest.render)(session, verdict, \*, source)             | The markdown for one digest.       |
|---------------------------------------------------------------------------------------------------|------------------------------------|
| [`make_digest`](_autosummary/openloops.digest.html.md#openloops.digest.make_digest)(session, verdict, \*, source[, ...]) | Render, scrub, and key one digest. |

### openloops.digest.SECTION_LIMITS *: [Mapping](https://docs.python.org/3/library/collections.abc.html#collections.abc.Mapping)[[str](https://docs.python.org/3/builtins/stdtypes.html#str), [int](https://docs.python.org/3/builtins/functions.html#int)]* *= {'compaction': 3000, 'last_assistant_text': 4000, 'last_user_prompt': 1200, 'recap': 1500}*

How much of each section is kept. Bounds are deterministic so regeneration is
byte-stable; they exist because a digest is meant to be read, not archived whole.

### openloops.digest.make_digest(session, verdict, , source, aliases=None)

Render, scrub, and key one digest.

Raises [`CredentialFound`](_autosummary/openloops.egress.html.md#openloops.egress.CredentialFound) when the rendered text matches a
credential pattern — deliberately, so the caller skips that session loudly rather
than writing a secret into a store that may be synced.

```pycon
>>> from openloops.base import Session, Verdict
>>> d = make_digest(Session(key='s1'), Verdict('open', 'why'), source='demo')
>>> d.key
'demo/open/s1.md'
```

* **Return type:**
  [`Digest`](_autosummary/openloops.base.html.md#openloops.base.Digest)

### openloops.digest.render(session, verdict, , source)

The markdown for one digest. Pure, dated, and bounded.

```pycon
>>> from openloops.base import Session, Verdict
>>> s = Session(key='s1', project='proj', started_at='T0', last_turn_at='T1',
...             last_assistant_text='Shipped it.', turn_count=3)
>>> verdict = Verdict('archive', 'its closing lines declare it finished')
>>> text = render(s, verdict, source='demo')
>>> text.splitlines()[0]
'---'
>>> 'state: archive' in text
True
>>> render(s, verdict, source='demo') == text     # pure: same in, same out
True
```

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)


# _autosummary/openloops.egress.html.md

# openloops.egress

The egress choke point: nothing leaves openloops carrying a home path or a secret.

A digest is derived from a transcript, and transcripts are the highest-entropy secret
source on a developer’s machine — pasted tokens, `.env` contents, tracebacks full of
absolute paths. A digest store can be a git-synced private repository, so \*\*a written
digest is an export surface\*\*, and the moment to apply that discipline is before the
first byte is written rather than before the first push.

Two rules, and they are deliberately asymmetric:

- **Paths are rewritten**, never raised on. A path is an identifier, not a secret, and
  the tail of it is the part a reader needs. This machine’s home becomes `~`; \*any
  other\* home — a server’s root home, a colleague’s, a CI runner’s — becomes
  `~other`, keeping the tail and dropping the identity.
- **Credentials raise.** [`scrub()`](_autosummary/openloops.egress.html.md#openloops.egress.scrub) never silently redacts a secret, because a silent
  redaction teaches nobody that a secret was there. It raises [`CredentialFound`](_autosummary/openloops.egress.html.md#openloops.egress.CredentialFound),
  the caller skips that one session, and the run reports it — loudly, and without ever
  quoting the matched text.

Two shapes are easy to miss and both were, at first. Claude Code encodes a working
directory into a directory name by turning `/`, `_` and `.` into `-`, so a home
path appears throughout transcripts in a dashed form — trivially reversible and just
as identifying. And a transcript from an ssh session names *that* machine’s home,
not this one’s, so rewriting only `$HOME` leaves every foreign home intact. Both forms
are handled here, and [`scrub()`](_autosummary/openloops.egress.html.md#openloops.egress.scrub) asserts its own postcondition afterwards rather than
trusting that it did.

The same rules apply to openloops’ own repository, which is why
`tests/test_egress_repo.py` runs [`scan_files()`](_autosummary/openloops.egress.html.md#openloops.egress.scan_files) over everything the build ships.
One implementation, two configurations.

```pycon
>>> scrub("see /nowhere/at/all/x.py", aliases={"/nowhere/at/all": "~/code"})
'see ~/code/x.py'
>>> scrub("token=" + "ghp_" + "A" * 36)
Traceback (most recent call last):
    ...
openloops.egress.CredentialFound: credential-shaped text (github_token) at offset 6
```

### Module Attributes

| [`CREDENTIAL_PATTERNS`](_autosummary/openloops.egress.html.md#openloops.egress.CREDENTIAL_PATTERNS)   | Named credential patterns, checked in order.   |
|------------------------------------------------------------------------|------------------------------------------------|

### Functions

| [`apply_aliases`](_autosummary/openloops.egress.html.md#openloops.egress.apply_aliases)(text[, aliases])       | Replace each alias at a path boundary, longest key first.                                                             |
|---------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------------|
| [`default_aliases`](_autosummary/openloops.egress.html.md#openloops.egress.default_aliases)()                    | The rewrites applied when a caller supplies none: this machine's home → `~`.                                          |
| [`find_credentials`](_autosummary/openloops.egress.html.md#openloops.egress.find_credentials)(text)               | Every credential-pattern hit, as `(pattern_name, offset)` pairs.                                                      |
| [`find_absolute_paths`](_autosummary/openloops.egress.html.md#openloops.egress.find_absolute_paths)(text[, aliases]) | Home paths — literal or encoded — still present after rewriting, with offsets.                                        |
| [`rewrite_paths`](_autosummary/openloops.egress.html.md#openloops.egress.rewrite_paths)(text[, aliases])       | Apply the aliases, then rewrite every home path they did not cover.                                                   |
| [`scan`](_autosummary/openloops.egress.html.md#openloops.egress.scan)(text, \*[, aliases, where])     | Report egress violations instead of raising — for auditing many files at once.                                        |
| [`scan_files`](_autosummary/openloops.egress.html.md#openloops.egress.scan_files)(paths, \*[, aliases])     | Run [`scan()`](_autosummary/openloops.egress.html.md#openloops.egress.scan) over each readable text file, accumulating every problem. |
| [`scrub`](_autosummary/openloops.egress.html.md#openloops.egress.scrub)(text, \*[, aliases, where])    | Rewrite paths and raise on credentials.                                                                               |

### Exceptions

| [`CredentialFound`](_autosummary/openloops.egress.html.md#openloops.egress.CredentialFound)(pattern_name, offset, \*[, where])   | Raised when text about to be written matches a credential pattern.   |
|-------------------------------------------------------------------------------------------------------|----------------------------------------------------------------------|

### openloops.egress.CREDENTIAL_PATTERNS *: [tuple](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[tuple](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[str](https://docs.python.org/3/builtins/stdtypes.html#str), [Pattern](https://docs.python.org/3/library/re.html#re.Pattern)], ...]* *= (('aws_access_key_id', re.compile('(?<![A-Z0-9])(?:AKIA|ASIA)[0-9A-Z]{16}(?![A-Z0-9])')), ('aws_secret_access_key', re.compile('(?i)aws_secret_access_key\\\\s\*[:=]\\\\s\*\\\\S{20,}', re.IGNORECASE)), ('github_token', re.compile('\\\\bgh[pousr]_[A-Za-z0-9]{36,}\\\\b')), ('github_pat', re.compile('\\\\bgithub_pat_[A-Za-z0-9_]{22,}\\\\b')), ('gitlab_token', re.compile('\\\\bglpat-[A-Za-z0-9_\\\\-]{20,}\\\\b')), ('anthropic_api_key', re.compile('\\\\bsk-ant-[A-Za-z0-9_\\\\-]{20,}\\\\b')), ('openai_api_key', re.compile('\\\\bsk-(?!ant-)[A-Za-z0-9_\\\\-]{20,}\\\\b')), ('stripe_key', re.compile('\\\\b[srp]k_(?:live|test)_[A-Za-z0-9]{16,}\\\\b')), ('npm_token', re.compile('\\\\bnpm_[A-Za-z0-9]{30,}\\\\b')), ('pypi_token', re.compile('\\\\bpypi-[A-Za-z0-9_\\\\-]{32,}')), ('huggingface_token', re.compile('\\\\bhf_[A-Za-z0-9]{30,}\\\\b')), ('sendgrid_key', re.compile('\\\\bSG\\\\.[A-Za-z0-9_\\\\-]{20,}\\\\.[A-Za-z0-9_\\\\-]{20,}\\\\b')), ('slack_token', re.compile('\\\\bxox[baprs]-[A-Za-z0-9\\\\-]{10,}\\\\b')), ('google_api_key', re.compile('\\\\bAIza[0-9A-Za-z_\\\\-]{35}\\\\b')), ('google_oauth_refresh_token', re.compile('\\\\b1//0[A-Za-z0-9_\\\\-]{20,}\\\\b')), ('json_web_token', re.compile('\\\\beyJ[A-Za-z0-9_\\\\-]{10,}\\\\.eyJ[A-Za-z0-9_\\\\-]{10,}\\\\.')), ('private_key_block', re.compile('-----BEGIN [A-Z ]\*PRIVATE KEY-----')), ('url_inline_password', re.compile('\\\\b[a-z][a-z0-9+.\\\\-]\*://[^/\\\\s:@]+:[^/\\\\s@]{6,}@')), ('secret_assignment', re.compile('(?i)(?<![A-Za-z0-9])(?:[A-Za-z0-9]+[_-])\*(?:api[_-]?key|secret[_-]?\\\\w\*|passwd|password|access[_-]?token|auth[_-]?token|token|credential\\\\w\*)\\\\b\\\\s\*[:=]\\\\s\*[\\'\\\\"]?((?=[^\\'\\\\"\\\\s]\*[A-Za-z])(?=[^\\'\\\\", re.IGNORECASE)))*

Named credential patterns, checked in order. Most are well-known vendor prefixes,
which give near-zero false positives; the assignment rule at the end is the only
heuristic among them, and the URL rule catches the shape a prefix list cannot.

### *exception* openloops.egress.CredentialFound(pattern_name, offset, , where='')

Bases: [`ValueError`](https://docs.python.org/3/builtins/exceptions.html#ValueError)

Raised when text about to be written matches a credential pattern.

The message names the pattern class and the offset. It never contains the matched
text: an exception that quotes a secret has moved the secret into a log file.

### openloops.egress.apply_aliases(text, aliases=None)

Replace each alias at a path boundary, longest key first. Nothing else.

Longest-first matters: a home directory and a projects directory beneath it are both
aliases, and the more specific one must win. Boundary-anchoring matters for the
opposite reason: a bare `str.replace` turns a *longer* sibling name into a
half-rewritten mess — a home of `…/bob` would mangle `…/bobby` into `~by`,
corrupting the path and leaving half the other name behind.

Separate from [`rewrite_paths()`](_autosummary/openloops.egress.html.md#openloops.egress.rewrite_paths) because auditing and scrubbing want different
things: an audit must still be able to *see* a foreign home path in order to report
it, which it could not if every caller had already rewritten one away.

```pycon
>>> apply_aliases("/a/b/c and /a", {"/a": "~", "/a/b": "$B"})
'$B/c and ~'
>>> apply_aliases("/a2/x", {"/a": "~"})
'/a2/x'
```

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### openloops.egress.default_aliases()

The rewrites applied when a caller supplies none: this machine’s home → `~`.

Both spellings of it, because the encoded form appears in transcripts as often as
the literal one.

```pycon
>>> sorted(set(default_aliases().values()))
['~']
```

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]

### openloops.egress.find_absolute_paths(text, aliases=None)

Home paths — literal or encoded — still present after rewriting, with offsets.

The example builds its path by concatenation and compares rather than printing,
because this module’s own source is scanned by the rule it implements: a literal
home-rooted path in a docstring would violate the thing being documented.

```pycon
>>> home = "/Us" + "ers/someone"
>>> [p for p, _ in find_absolute_paths(home + "/x", aliases={})] == [home]
True
>>> find_absolute_paths(home + "/x", aliases={home: "~"})
[]
```

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`int`](https://docs.python.org/3/builtins/functions.html#int)]]

### openloops.egress.find_credentials(text)

Every credential-pattern hit, as `(pattern_name, offset)` pairs.

The matched text is never returned — only where it is and what it looked like.

```pycon
>>> find_credentials("nothing to see here")
[]
>>> find_credentials("AKIA" + "B" * 16)
[('aws_access_key_id', 0)]
```

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`int`](https://docs.python.org/3/builtins/functions.html#int)]]

### openloops.egress.rewrite_paths(text, aliases=None)

Apply the aliases, then rewrite every home path they did not cover.

A transcript from an ssh session names *that* machine’s home, and a CI traceback
names a runner’s; neither is covered by an alias derived from this process. They are
rewritten to `FOREIGN_HOME`, which keeps the tail of the path and drops the
part that identifies somebody.

```pycon
>>> rewrite_paths("/ro" + "ot/py/x", aliases={})
'~other/py/x'
>>> rewrite_paths("-Us" + "ers-someone-proj", aliases={})
'~other-proj'
```

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### openloops.egress.scan(text, , aliases=None, where='')

Report egress violations instead of raising — for auditing many files at once.

Returns a list of human-readable problem descriptions, empty when the text is clean.
[`scrub()`](_autosummary/openloops.egress.html.md#openloops.egress.scrub) is what production code calls; this is what the repository’s own egress
test calls, because a test that stopped at the first violation would take one run per
problem to converge.

```pycon
>>> scan("all clear")
[]
```

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]

### openloops.egress.scan_files(paths, , aliases=None)

Run [`scan()`](_autosummary/openloops.egress.html.md#openloops.egress.scan) over each readable text file, accumulating every problem.

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]

### openloops.egress.scrub(text, , aliases=None, where='')

Rewrite paths and raise on credentials. The only way text leaves openloops.

`where` is a caller-supplied label (a session id, a file name) carried into the
exception so a failed run can say *which* input tripped, without quoting it.

The path check runs on the **output**, not the input, because `aliases` is
caller-supplied: a rewrite can in principle produce a home path as easily as remove
one, and a postcondition that is only true of benign inputs is not a postcondition.

```pycon
>>> scrub("built /nowhere/proj/x", aliases={"/nowhere/proj": "$PROJ"})
'built $PROJ/x'
```

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)


# _autosummary/openloops.facets.html.md

# openloops.facets

The board’s facet families: how a task is categorised, computed from what it is.

Every value is derived, never typed by hand: from the task’s `command` (through the
same deterministic reading the run plans use, [`openloops.command_risk`](_autosummary/openloops.command_risk.html.md#module-openloops.command_risk)), its
`org`, its `minutes` and its open `blocked_by` edges. The page draws its filter
from [`FAMILIES`](_autosummary/openloops.facets.html.md#openloops.facets.FAMILIES) (labels, help, value labels, order) and from each task’s
`facets`, so a family added here appears on the board with no page change.

Families, in the order the page shows them:

* `presence`: runs without you, or needs you at the terminal (a login, 2FA, a paste,
  a browser): the split the owner launches by.
* `ready`: every prerequisite done, waiting on an open issue, or unknown (the edges
  could not be read: never rounded into either).
* `where`: the Mac, the twb server, the iqb server.
* `risk`: the floor’s level (run, show, discuss, refuse).
* `touches`: what it changes (deploy, publish, secret, money, server, GitHub, deletes,
  exposure, local files).
* `org`: whose repository the task is in.
* `time`: the estimate’s bucket.

A task without a command gets `presence: by-hand` and no command-derived values.
Pure: no I/O.

### Module Attributes

| [`FAMILIES`](_autosummary/openloops.facets.html.md#openloops.facets.FAMILIES)   | (key, label, help, ((value, label), ...)).   |
|-------------------------------------------------------------|----------------------------------------------|

### Functions

| [`task_facets`](_autosummary/openloops.facets.html.md#openloops.facets.task_facets)(task)   | Each family's values for one task record (lists: a task can run on two machines).                                                 |
|----------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------------------------|
| [`families_payload`](_autosummary/openloops.facets.html.md#openloops.facets.families_payload)()  | [`FAMILIES`](_autosummary/openloops.facets.html.md#openloops.facets.FAMILIES) as JSON for the page: `[{key, label, help, values: [{value, label}]}]`. |

### openloops.facets.FAMILIES *: [tuple](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[tuple](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[str](https://docs.python.org/3/builtins/stdtypes.html#str), [str](https://docs.python.org/3/builtins/stdtypes.html#str), [str](https://docs.python.org/3/builtins/stdtypes.html#str), [tuple](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[tuple](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[str](https://docs.python.org/3/builtins/stdtypes.html#str), [str](https://docs.python.org/3/builtins/stdtypes.html#str)], ...]], ...]* *= (('presence', 'You needed', 'Whether a step needs you at the terminal: a login, 2FA, a paste, a browser.', (('unattended', 'Without you'), ('attended', 'Needs you'), ('by-hand', 'No command'))), ('ready', 'Ready', 'Waiting means an issue it depends on is still open.', (('ready', 'Ready'), ('waiting', 'Waiting on another'), ('unknown', 'Not read'))), ('where', 'Runs on', 'The machine the command acts on.', (('mac', 'Mac'), ('twb', 'twb server'), ('iqb', 'iqb server'))), ('risk', 'Risk', 'Shows first and Asks you by name wait for your yes.', (('run', 'Runs'), ('show', 'Shows first'), ('discuss', 'Asks you by name'), ('refuse', "Won't run"))), ('touches', 'Changes', 'What the command changes.', (('deploy', 'A deploy'), ('publish', 'A publish'), ('secret', 'A secret'), ('money', 'Money'), ('server', 'A server'), ('github', 'GitHub'), ('deletes', 'Deletes'), ('exposure', 'Makes public'), ('local', 'Local only'))), ('org', 'Org', 'Whose repository the task is in.', ()), ('time', 'Time', 'The estimate.', (('short', 'Under 5 min'), ('medium', '5 to 15 min'), ('long', 'Over 15 min'))))*

(key, label, help, ((value, label), …)). Values not listed (an org) are shown as is.

### openloops.facets.families_payload()

[`FAMILIES`](_autosummary/openloops.facets.html.md#openloops.facets.FAMILIES) as JSON for the page: `[{key, label, help, values: [{value, label}]}]`.

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]]

### openloops.facets.task_facets(task)

Each family’s values for one task record (lists: a task can run on two machines).

```pycon
>>> f = task_facets({'command': "ssh tw 'python3 x.py --apply'", 'org': 'acme',
...                  'minutes': 3, 'blocked_by': []})
>>> f['presence'], f['where'], f['ready'], f['time'], f['org']
(['unattended'], ['twb'], ['ready'], ['short'], ['acme'])
>>> task_facets({'command': 'npm login && npm publish', 'blocked_by': None})['presence']
['attended']
>>> task_facets({'command': None, 'blocked_by': ['o/r#2']})['ready']
['waiting']
```

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]]


# _autosummary/openloops.gtd.html.md

# openloops.gtd

Getting Things Done (David Allen) as an organising method: the default, and the only one.

It implements [`openloops.method.Method`](_autosummary/openloops.method.html.md#openloops.method.Method) with GTD’s own vocabulary, for the
owner’s commitments:

- **Capture** lands on `in`, GTD’s In list.
- **Clarify** is GTD’s workflow decision tree: is it actionable? If not: trash,
  incubate (`someday`, optionally with a date to come back) or `reference`. If it
  is: someone else should do it, delegate it (`waiting`, on whom); under two minutes,
  do it now; a specific day, defer it (`next` with a `remind_at`, the tickler);
  otherwise `next`. More than one step makes it part of a `project`.
- **Organise** moves a loop between `in`, `next`, `waiting`, `someday` and
  `reference`. Waiting For says on whom; reference is not actionable, so it carries
  no reminder.
- **Review** is the Weekly Review as an exceptions packet, in GTD’s three phases:
  *get clear* (In to zero, proposals to accept), *get current* (overdue, fired and
  unanswered, coming up, Waiting For to chase, projects with no next action), \*get
  creative\* (a sample of Someday/Maybe). Everything else is counted, not listed, so the
  owner’s attention goes only where a decision is needed.
- **Engage** is GTD’s four-criteria model: context, time available and energy filter
  the Next list; priority (a real deadline first, then what already fired, then the
  oldest) orders what is left.

Delegating to an agent is GTD’s delegate step: the loop goes on the owner’s Waiting
For, `waiting={"on": "<session>"}`, and the review lists it when it is due a chase.
That is how agents’ (cheaper) attention takes a loop off the owner’s mind.

```pycon
>>> gtd = GTD()
>>> gtd.clarify({"actionable": False, "keep": "someday"})["place"]
'someday'
>>> gtd.clarify({"actionable": "yes", "delegate_to": "openloops session"})["place"]
'waiting'
>>> gtd.clarify({"actionable": True, "minutes": 2})["do_now"]
True
```

### Module Attributes

| [`PLACES`](_autosummary/openloops.gtd.html.md#openloops.gtd.PLACES)   | GTD's lists, as the places a loop can sit on.                                |
|-----------------------------------------------------------|------------------------------------------------------------------------------|
| [`ENERGY`](_autosummary/openloops.gtd.html.md#openloops.gtd.ENERGY)   | Energy levels, lowest first (engage keeps what needs no more than you have). |

### Classes

| [`GTD`](_autosummary/openloops.gtd.html.md#openloops.gtd.GTD)([two_minutes, coming_up, chase_after, ...])   | Getting Things Done.   |
|----------------------------------------------------------------------------------------------------|------------------------|

### openloops.gtd.ENERGY *= ('low', 'medium', 'high')*

Energy levels, lowest first (engage keeps what needs no more than you have).

### *class* openloops.gtd.GTD(two_minutes=2, coming_up=datetime.timedelta(days=7), chase_after=datetime.timedelta(days=7), someday_sample=5, engage_limit=5, name='gtd', places=('in', 'next', 'waiting', 'someday', 'reference'), inbox='in', default_place='next', questions=(Question(key='actionable', ask='Is it actionable: is there something to do about it?', kind='bool', choices=(), when=None), Question(key='keep', ask='Not actionable: throw it away, incubate it for later, or keep it as reference?', kind='choice', choices=('trash', 'someday', 'reference'), when='actionable=false'), Question(key='project', ask='Does the outcome take more than one action? Name the project.', kind='text', choices=(), when='actionable=true'), Question(key='minutes', ask='How many minutes does the next action take?', kind='minutes', choices=(), when='actionable=true'), Question(key='delegate_to', ask='Should someone else (a person or an agent session) do it? Who?', kind='text', choices=(), when='actionable=true'), Question(key='remind_at', ask='Must it happen on a specific day or time? When should it come back?', kind='time', choices=(), when=None), Question(key='contexts', ask='Where or with what can it be done (e.g. @mac, @phone, @errands)?', kind='words', choices=(), when='actionable=true')), criteria=('context', 'minutes', 'energy'))

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

Getting Things Done. The keyword fields are the method’s tunable rules.

`two_minutes`: the two-minute rule’s threshold. `coming_up`: how far ahead the
review looks for dates. `chase_after`: a Waiting For item with no `chase_at`
is due a chase once untouched this long. `someday_sample`: how many Someday/Maybe
items the review shows (oldest first). `engage_limit`: candidates `engage`
returns by default.

#### clarify(answers)

GTD’s decision tree over `answers` (keys: `questions`), as data.

```pycon
>>> GTD().clarify({"actionable": "no", "keep": "trash"})["close"]
'canceled'
>>> d = GTD().clarify({"actionable": True, "project": "Move flat", "remind_at": "2026-12-01T09:00Z"})
>>> d["place"], d["changes"]["project"], d["changes"]["remind_at"]
('next', 'Move flat', '2026-12-01T09:00Z')
```

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]

#### engage(loops, now, , limit=None, context=None, minutes=None, energy=None)

What to do now: Next Actions available now, filtered by context, time and energy.

A loop deferred to a later `remind_at` is not available yet (the tickler), and
a proposal never shows. Priority orders what is left.

```pycon
>>> from datetime import timezone
>>> now = datetime(2026, 11, 28, 12, tzinfo=timezone.utc)
>>> a = _loops.new_loop("Call", now=now, id="loop-1", contexts=["@phone"], minutes=10)
>>> b = _loops.new_loop("Write", now=now, id="loop-2", contexts=["@mac"], minutes=90)
>>> [r["id"] for r in GTD().engage([a, b], now, minutes=30)]
['loop-1']
```

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]]

#### organise(loop, place, now, , others=(), \*\*fields)

The changes a move of `loop` to `place` makes, checked against GTD’s rules.

Waiting For merges what is given into what was there, and restarts its clock
only when it now waits on someone else. Reference is not actionable: it keeps
no reminder, and refuses one.

```pycon
>>> from datetime import timezone
>>> now = datetime(2026, 11, 28, 12, tzinfo=timezone.utc)
>>> loop = _loops.new_loop("Ask the bank", now=now, id="loop-b")
>>> GTD().organise(loop, "waiting", now, waiting={"on": "the bank"})["waiting"]
{'on': 'the bank', 'since': '2026-11-28T12:00:00Z'}
```

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]

#### review(loops, now)

The Weekly Review as exceptions: only what needs a decision is listed.

```pycon
>>> from datetime import timezone
>>> now = datetime(2026, 11, 28, 12, tzinfo=timezone.utc)
>>> stuck = _loops.new_loop("Draft", now=now, id="loop-s", list="in", project="Book")
>>> packet = GTD().review([stuck], now)
>>> [(s["name"], [r["id"] for r in s["rows"]]) for s in packet["sections"] if s["rows"]]
[('in', ['loop-s']), ('stalled_projects', ['Book'])]
```

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]

### openloops.gtd.PLACES *= ('in', 'next', 'waiting', 'someday', 'reference')*

GTD’s lists, as the places a loop can sit on. “Scheduled” (the tickler) is not a
list: it is a loop on Next with a future `remind_at`.


# _autosummary/openloops.html.md

# openloops

What your Claude Code sessions were doing — kept after the transcripts are gone.

Claude Code writes a JSONL transcript for every session and deletes it after about a
month. openloops reads those transcripts, writes one short dated markdown digest per
session, and keeps the digests. Nothing here calls a model, reaches the network, or
needs an account: it reads files you already have and writes files you already own.
(One opt-in exception: `openloops.receiver_tick`, run only by the board-receiver job
you install with `ol install-receiver-job`, signs in to your own board store and may
start a `claude` session. Nothing imports it, so `import openloops` never loads it.)

```pycon
>>> import openloops
>>> report = openloops.sync()
>>> for row in openloops.ls(state='open'):
...     print(row['session'], row['ai_title'] or row['title'])
```

The whole design rests on one sentence, and everything else follows from it:

> **A digest says what a session said, dated. It never says what is true now.**

So a digest is filed under `open/` or `archive/` by what the session’s own last
turn *read* like — not by whether a process is running, which would make this a session
dashboard rather than a record of open loops. Nothing is asserted to be still
outstanding, because openloops has checked nothing against the world.

The two modules whose primary export shares their name — the sync engine and the
classifier — are private (`openloops._sync`, `openloops._classify`), because a
module and a function cannot both answer to `openloops.sync`. Everything they export
is re-exported here, including the classifier’s cue tables.

Two seams, both one keyword argument, both defaulting to something that works out of
the box: `transcript_source=` (a reader of Claude Code’s on-disk layout) and
`digests_store=` (a directory of markdown files under `~/.local/share/openloops/`).
Swap either for a test fixture, a git-synced directory, or blob storage without
touching anything else.

There is a second thing here, added later and kept deliberately small:
`openloops.owed()` lists the open `manual-task` issues your agents filed when they
got blocked on you, and — this is its whole reason to exist — re-runs the shell
predicate each issue carries before showing it, so an obligation discharged out of band
reads *discharged* rather than sitting open for months. It reads and reports; it never
closes, relabels or writes anything, and it keeps no copy of anything: the label is the
record. Its trust boundary (evaluating a predicate executes text from an issue body)
and its kill criterion are both written out in [`openloops.obligations`](_autosummary/openloops.obligations.html.md#module-openloops.obligations).

```pycon
>>> report = openloops.owed()
>>> report['counts']
{'open': 6, 'discharged': 1, 'unknown': 2, 'with_predicate': 7, 'total': 9}
```

And a third thing, which is the same thing pointed at a repository instead of at a
person: `openloops.blocked()`. When an agent working in repo X finds the real fix
belongs in repo Y, it files in Y and moves on — and X is never told when Y is fixed, so
the workaround in X quietly becomes architecture. GitHub’s issue dependencies already
record that edge across repositories; what nothing does is notice when the blocker
closes, because the edge is queryable rather than eventful. `blocked()` resolves every
edge and reports `unblocked` (every blocker resolved: the work is free and nobody has
been told), `blocked` (naming the foreign repository) and `unknown`. It reads and
reports; it writes nothing. What its discovery step is measured to over-report, what
bounds its one-call-per-issue resolution, and its kill criterion are all in
[`openloops.blockers`](_autosummary/openloops.blockers.html.md#module-openloops.blockers).

```pycon
>>> report = openloops.blocked()
>>> [r['repo'] + '#' + str(r['number'])
...  for r in report['rows'] if r['state'] == 'unblocked']
['acme/widget#109']
```

All three of those are plumbing, and the surface most people actually want is an agent
that knows how to use the plumbing and tells them what matters. So the package also
ships that agent, as files: a `openloops` skill that answers “what is being done, and
what needs my attention?”, a `openloops-needs-human` skill that files the
`manual-task` issues `owed()` later reads back, and an `openloops-sweep` subagent
that runs the whole sweep in a fresh context. `install_skills()` links them into an
agent host; see [`openloops.skills`](_autosummary/openloops.skills.html.md#module-openloops.skills) for why it links rather than copies and why it
never overwrites.

```pycon
>>> plan = openloops.install_skills(dry_run=True)
>>> [row['name'] for row in plan['actions']]
['openloops', 'openloops-needs-human', 'openloops-sweep']
```

And a page to look at instead of reading three command outputs:
`openloops.render_dashboard()` turns those same three answers into one self-contained
HTML document — no stylesheet, no script, no font, nothing fetched from anywhere.
Because it fetches nothing it also *checks* nothing, so it is a **snapshot**: it stamps
the moment it was made and says so in its largest type, and any figure it could not
establish reads `?` rather than `0`. `ol dashboard` writes one.

```pycon
>>> page = openloops.render_dashboard(
...     openloops.owed(), openloops.blocked(), openloops.ls(limit=0))
```

**Still not here, and deliberately:** a ledger. No store, no schema, no history, no
event log, no cross-repo links, no session model, and no write path of any kind.

### Functions

| [`exchanges`](_autosummary/openloops.html.md#openloops.exchanges)(records, \*[, key])                      | Every prompt of a transcript's main thread, in order, each with its turn's reply.                                     |
|-----------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------------|
| [`question_sentences`](_autosummary/openloops.html.md#openloops.question_sentences)(text)                           | The sentences of a person's prompt that ask something, in order, at most `MAX_QUESTIONS`.                             |
| [`agents_dir`](_autosummary/openloops.html.md#openloops.agents_dir)()                                       | The bundled subagent definitions, inside the installed package.                                                       |
| [`asks_the_human`](_autosummary/openloops.html.md#openloops.asks_the_human)(text, \*[, ask_cues, chars])        | The ask cues in the closing lines, if those lines put a question to the reader.                                       |
| [`blocked`](_autosummary/openloops.html.md#openloops.blocked)(\*[, resolve, owners, repos, query, ...])  | Open issues that carry a blocker edge, with every edge resolved.                                                      |
| [`classify`](_autosummary/openloops.html.md#openloops.classify)(session, \*[, ask_cues, defer_cues, ...]) | Read a session's loop state from its own last turn.                                                                   |
| [`data_dir`](_autosummary/openloops.html.md#openloops.data_dir)()                                         | The project's data root.                                                                                              |
| [`default_source`](_autosummary/openloops.html.md#openloops.default_source)([directory])                        | This machine's label for its digest folder.                                                                           |
| [`digest_key`](_autosummary/openloops.html.md#openloops.digest_key)(source, state, session_key)             | The store key for one session's digest.                                                                               |
| [`digests_store`](_autosummary/openloops.html.md#openloops.digests_store)([rootdir])                           | The default `digests_store`: markdown files under the data root.                                                      |
| [`gh_blocked_by`](_autosummary/openloops.html.md#openloops.gh_blocked_by)(repo, number, \*[, timeout])         | The default `blockers_source`: the blocker edges out of one issue.                                                    |
| [`gh_blocked_candidates`](_autosummary/openloops.html.md#openloops.gh_blocked_candidates)(\*[, owners, repos, ...])    | The default `issues_source`: open issues that *may* carry a blocker edge.                                             |
| [`gh_issues`](_autosummary/openloops.html.md#openloops.gh_issues)(\*, owners[, label, state, limit, ...])  | The default `issues_source`: the open `manual-task` issues, from `gh`.                                                |
| [`headline_counts`](_autosummary/openloops.html.md#openloops.headline_counts)(owed, blocked, sessions)           | The four figures across the top of the page.                                                                          |
| [`install_skills`](_autosummary/openloops.html.md#openloops.install_skills)(\*[, target, only, copy, ...])      | Make the bundled skills and subagent visible to an agent host.                                                        |
| `ls`(\*[, state, source, project, confidence, ...])                                                 | The digests in the store, newest last-turn first.                                                                     |
| [`make_digest`](_autosummary/openloops.html.md#openloops.make_digest)(session, verdict, \*, source[, ...])   | Render, scrub, and key one digest.                                                                                    |
| [`owed`](_autosummary/openloops.html.md#openloops.owed)(\*[, verify, owners, trusted_owners, ...])    | The open `manual-task` obligations, each re-checked against the world.                                                |
| [`held_prs`](_autosummary/openloops.html.md#openloops.held_prs)(\*[, owners, stale_days, now, ...])       | The open PRs you opened that are held, or stalled for `stale_days`, in one envelope.                                  |
| [`hold_reason`](_autosummary/openloops.html.md#openloops.hold_reason)(pr)                                    | Why `pr` is held, or `""` when it is not: a `Held:` line, a draft, a title starting "Held".                           |
| [`parse_session`](_autosummary/openloops.html.md#openloops.parse_session)(records, \*[, key])                  | Read one transcript's records into a [`Session`](_autosummary/openloops.base.html.md#openloops.base.Session). |
| [`parse_verify`](_autosummary/openloops.html.md#openloops.parse_verify)(body)                                 | `(predicate, verify_text)` for an issue body.                                                                         |
| [`render`](_autosummary/openloops.html.md#openloops.render)(session, verdict, \*, source)               | The markdown for one digest.                                                                                          |
| [`render_dashboard`](_autosummary/openloops.html.md#openloops.render_dashboard)(owed, blocked, sessions, \*)      | The three envelopes as one self-contained HTML page.                                                                  |
| [`retained`](_autosummary/openloops.html.md#openloops.retained)(store, sessions, \*[, source])            | Digest keys whose session no longer has a transcript — the retention surplus.                                         |
| [`scrub`](_autosummary/openloops.html.md#openloops.scrub)(text, \*[, aliases, where])                  | Rewrite paths and raise on credentials.                                                                               |
| [`shell_predicate`](_autosummary/openloops.html.md#openloops.shell_predicate)(command, \*[, timeout])            | The default `run_predicate`: run the command in a subshell, bounded in time.                                          |
| `show`(session, \*[, source, digests_store])                                                        | One digest in full, found by session id or by a unique prefix of one.                                                 |
| [`skills_dir`](_autosummary/openloops.html.md#openloops.skills_dir)()                                       | The bundled skills directory, inside the installed package.                                                           |
| [`state_dir`](_autosummary/openloops.html.md#openloops.state_dir)()                                        | Where per-machine caches and job logs go.                                                                             |
| `status`(\*[, source, since_days, ...])                                                             | Where everything is, how much of it there is, and how stale the cache is.                                             |
| [`sync`](_autosummary/openloops.html.md#openloops.sync)(\*[, transcript_source, digests_store, ...])  | Bring the digest store up to date with the sessions, and say what changed.                                            |

### Classes

| [`Exchange`](_autosummary/openloops.html.md#openloops.Exchange)(session, uuid, origin, asked_at, prompt)   | One prompt a session received and the reply its turn ended with.               |
|------------------------------------------------------------------------------------------------------|--------------------------------------------------------------------------------|
| [`BlockedIssue`](_autosummary/openloops.html.md#openloops.BlockedIssue)(repo, number, title, url, ...)         | One open issue that carries blocker edges, with the verdict those edges imply. |
| [`Blocker`](_autosummary/openloops.html.md#openloops.Blocker)(repo, number[, state, url, closed_at])      | One edge: the issue, in whatever repository it lives, that blocks another.     |
| [`ClaudeCodeTranscripts`](_autosummary/openloops.html.md#openloops.ClaudeCodeTranscripts)([root, since_days, ...])      | Claude Code's persisted sessions, as a `Mapping[str, Session]`.                |
| [`Digest`](_autosummary/openloops.html.md#openloops.Digest)(key, text, session_key, source, state)       | One rendered digest: its store key and its markdown text.                      |
| [`Locator`](_autosummary/openloops.html.md#openloops.Locator)(type[, url, text, at])                      | A typed, human-readable pointer to something outside the digest.               |
| [`Obligation`](_autosummary/openloops.html.md#openloops.Obligation)(repo, number, title, url, ...[, ...])    | One open `manual-task` issue, with the verdict its own predicate returned.     |
| [`PredicateOutcome`](_autosummary/openloops.html.md#openloops.PredicateOutcome)(status[, output])                  | What evaluating one predicate produced.                                        |
| [`Session`](_autosummary/openloops.html.md#openloops.Session)(key[, title, ai_title, cwd, ...])           | What one Claude Code session's persisted state says, parsed but not judged.    |
| [`Verdict`](_autosummary/openloops.html.md#openloops.Verdict)(state, reason[, cues, at, confidence])      | A loop-state judgement, with the rule that produced it and the cues it saw.    |

### Exceptions

| [`CredentialFound`](_autosummary/openloops.html.md#openloops.CredentialFound)(pattern_name, offset, \*[, where])   | Raised when text about to be written matches a credential pattern.           |
|-------------------------------------------------------------------------------------------------------|------------------------------------------------------------------------------|
| [`GhUnavailable`](_autosummary/openloops.html.md#openloops.GhUnavailable)                                        | The world could not be read: no `gh`, no credentials, no network, a timeout. |

### *class* openloops.BlockedIssue(repo, number, title, url, created, age_days, state='unknown', blockers=(), cross_repo=False, unblocked_days=0, evidence='')

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

One open issue that carries blocker edges, with the verdict those edges imply.

`blockers` is carried in full next to `state` so a reader can disagree with the
verdict rather than absorb it — the same rule `openloops.obligations.
Obligation` follows for its predicate.

```pycon
>>> BlockedIssue('acme/widget', 12, 't', 'u', '2026-01-01T00:00:00Z', 3).state
'unknown'
```

#### as_dict()

JSON-ready form, blockers included.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]

#### cross_repo *: [bool](https://docs.python.org/3/builtins/functions.html#bool)* *= False*

At least one blocker lives in another repository — the shape this module is for.

#### unblocked_days *: [int](https://docs.python.org/3/builtins/functions.html#int)* *= 0*

how long the work
has been free while nobody was told. `0` for every other state.

* **Type:**
  Days since the last blocker closed, for an `unblocked` row

### *class* openloops.Blocker(repo, number, state='', url='', closed_at='')

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

One edge: the issue, in whatever repository it lives, that blocks another.

`repo` is the *blocker’s* repository, and carrying it is the whole point — an
edge that did not name it would answer only the easy half of the question.

```pycon
>>> Blocker('acme/engine', 15, 'closed').ref
'acme/engine#15 [closed]'
>>> Blocker('acme/engine', 15).ref
'acme/engine#15 [?]'
>>> Blocker('', 15, 'closed').ref
'?#15 [closed]'
```

#### as_dict()

JSON-ready form, with [`ref`](_autosummary/openloops.html.md#openloops.Blocker.ref) materialised for surfaces that print it.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]

#### *property* ref *: [str](https://docs.python.org/3/builtins/stdtypes.html#str)*

`owner/name#number [state]` — how a blocker is written down.

A `?` in either half is a fact about what could be read, never a shrug: an
edge whose repository the payload did not name says so rather than borrowing
the blocked issue’s own repository and inventing a same-repo dependency.

### *class* openloops.ClaudeCodeTranscripts(root=None, , since_days=None, projects=None, skip_scratchpads=True)

Bases: [`Mapping`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Mapping)

Claude Code’s persisted sessions, as a `Mapping[str, Session]`.

`since_days` bounds the scan by file modification time (`None` scans
everything); `projects` keeps only project directories whose name contains one of
the given substrings; `skip_scratchpads` drops the throwaway directories the CLI
creates under a temp root, which hold agent scratch sessions rather than work.

ADR-010’s revision shape lives here: [`revision()`](_autosummary/openloops.html.md#openloops.ClaudeCodeTranscripts.revision) returns an opaque token —
a file’s modification time for one session, a hash over all of them for the
collection — and [`changed_since()`](_autosummary/openloops.html.md#openloops.ClaudeCodeTranscripts.changed_since) compares against it. mtime is a coarse
signal that both misses content-preserving rewrites and fires on touches; that
trade is accepted rather than reprocessing several thousand transcripts a tick.

```pycon
>>> src = ClaudeCodeTranscripts(root='/nonexistent-dir-for-doctest')
>>> list(src), src.changed_since('0')
([], False)
```

#### changed_since(token, key=None)

Whether the current [`revision()`](_autosummary/openloops.html.md#openloops.ClaudeCodeTranscripts.revision) differs from *token*.

* **Return type:**
  [`bool`](https://docs.python.org/3/builtins/functions.html#bool)

#### path_of(key)

The transcript file backing *key*.

* **Return type:**
  [`Path`](https://docs.python.org/3/library/pathlib.html#pathlib.Path)

#### refresh()

Forget the cached index; the next access walks the projects tree again.

The index is a snapshot, built once per pass: iterating (or `len`) starts a
new pass and refreshes it, while `in`, `[]`, [`revision()`](_autosummary/openloops.html.md#openloops.ClaudeCodeTranscripts.revision) and
[`path_of()`](_autosummary/openloops.html.md#openloops.ClaudeCodeTranscripts.path_of) read the snapshot rather than walking the tree per key (issue
#33: that made one `sync` cost a full directory walk per session). Call this
to see transcripts written since the snapshot without iterating.

* **Return type:**
  [`None`](https://docs.python.org/3/builtins/constants.html#None)

#### revision(key=None)

An opaque change token: for one session, or for the whole collection.

For a single key it is the transcript’s modification time in nanoseconds. For
the collection it is a hash over every `(key, mtime)` pair, so a token can
be compared without holding the whole index.

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

#### scratchpad_marker *= '-private-tmp'*

Project-directory names starting with this are scratchpads, not work.

### *exception* openloops.CredentialFound(pattern_name, offset, , where='')

Bases: [`ValueError`](https://docs.python.org/3/builtins/exceptions.html#ValueError)

Raised when text about to be written matches a credential pattern.

The message names the pattern class and the offset. It never contains the matched
text: an exception that quotes a secret has moved the secret into a log file.

### *class* openloops.Digest(key, text, session_key, source, state, verdict=<factory>)

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

One rendered digest: its store key and its markdown text.

`text` is a pure function of the [`Session`](_autosummary/openloops.html.md#openloops.Session) it was built from. It carries
no generation timestamp, which is what lets the regeneration test in
`tests/test_sync.py` compare bytes rather than fields.

#### as_dict()

JSON-ready form (without the markdown body).

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]

### *class* openloops.Exchange(session, uuid, origin, asked_at, prompt, reply='', replied_at='', sender='', message_id='', questions=(), reply_uuid='', texts=(), followed_up_at='')

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

One prompt a session received and the reply its turn ended with.

`uuid` is the prompt record’s own id, stable for the life of the transcript.
`origin` is `HUMAN`, `PEER` (`sender` names the session) or
`SYSTEM` (a notification, a headless `-p` run, or nothing typed).
`reply` is the last assistant text before the next prompt, `''` while the turn
is still running or ended without words. `message_id` is the CLI’s id for a peer message (`origin.msg_id`), `''` otherwise.
`questions` is filled for a human
prompt only.

Three further facts let a reader point at an answer and tell a read one from an
unread one (ADR-016, decision 5): `reply_uuid` is the id of the record `reply`
came from; `texts` is every text of the turn, in order, `reply` being the last
of them; `followed_up_at` is when a typed prompt next arrived in the session, `''`
if none did. All three default to empty.

#### as_dict()

JSON-ready form.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)

### *exception* openloops.GhUnavailable

Bases: [`RuntimeError`](https://docs.python.org/3/builtins/exceptions.html#RuntimeError)

The world could not be read: no `gh`, no credentials, no network, a timeout.

Raised only by the listing path, and never propagated to a caller of [`owed()`](_autosummary/openloops.html.md#openloops.owed) —
it becomes `listed: False` plus an `error`, which every surface must render as
`?`. Turning it into an empty list would be the one unrecoverable bug here.

### *class* openloops.Locator(type, url='', text='', at='')

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

A typed, human-readable pointer to something outside the digest.

The exportable half of ADR-015’s evidence split: a short typed reference that
another tool (or a person) can resolve, never a content hash and never a byte
offset into a file that is garbage-collected after thirty days.

```pycon
>>> Locator("pr", url="https://github.com/o/r/pull/1").as_dict()["type"]
'pr'
```

#### as_dict()

JSON-ready form.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]

### *class* openloops.Obligation(repo, number, title, url, created, age_days, state='open', verify='', predicate='', evidence='', documents=(), session='', run='')

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

One open `manual-task` issue, with the verdict its own predicate returned.

`run` is `runbook_line()` when the body carries a shell block, else `''`.
`session` is the optional `**Session:**` field (the id or link of the session that
opened the issue), `''` when absent. `verify` is the `**Verify:**` field exactly as the issue wrote it and
`predicate` is the runnable command extracted from it — both are carried so a
reader can disagree with `state` rather than absorb it.

```pycon
>>> Obligation('acme/widget', 7, 't', 'u', '2026-01-01T00:00:00Z', 3).state
'open'
```

#### as_dict()

JSON-ready form.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]

### *class* openloops.PredicateOutcome(status, output='')

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

What evaluating one predicate produced.

`status` is the shell exit status, or `None` for “could not be run” — the
difference between an answer and the absence of one.

```pycon
>>> PredicateOutcome(0).status, PredicateOutcome(None, 'timed out').output
(0, 'timed out')
```

### *class* openloops.Session(key, title='', ai_title='', cwd='', project='', git_branches=(), started_at='', ended_at='', last_turn_at='', last_user_prompt='', last_prompt_at='', last_assistant_text='', recap='', recap_at='', compaction='', compaction_at='', turn_count=0, model='', ended_mid_turn=False, ended_with_error=False, locators=(), refs=())

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

What one Claude Code session’s persisted state says, parsed but not judged.

Every field is a *fact read from the transcript*, never an inference about the
world. `last_assistant_text` is what the session said last; it is not a claim
that the thing it describes is still true.

`key` is the session id. It is the only identifier openloops uses, and per
ADR-014 nothing in the model hangs off it: a digest is a view keyed by session,
not a record owned by one.

#### as_dict()

JSON-ready form (`asdict` already flattens the nested locators).

`refs` is left out: it is unbounded and belongs to the provenance index, not
to anything rendered from a session.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]

#### compaction *: [str](https://docs.python.org/3/builtins/stdtypes.html#str)* *= ''*

The context-compaction summary, a different and much longer thing than the recap,
covering only the part of the session that preceded it.

#### ended_mid_turn *: [bool](https://docs.python.org/3/builtins/functions.html#bool)* *= False*

The transcript’s final conversational record is an unanswered human prompt, or an
assistant tool call whose result never arrived — i.e. the session stopped mid-turn.

#### ended_with_error *: [bool](https://docs.python.org/3/builtins/functions.html#bool)* *= False*

The last thing the session said is a usage-limit or API-error banner rather than
the assistant’s own words: it was cut off, not finished.

#### *property* git_branch *: [str](https://docs.python.org/3/builtins/stdtypes.html#str)*

The branch the session opened on — the one that names it, when several ran.

A third of sessions touch more than one branch, so a single value is a summary
rather than a fact; `git_branches` is what carries the truth.

#### *property* heading *: [str](https://docs.python.org/3/builtins/stdtypes.html#str)*

its description, else its label.

* **Type:**
  What to call this session in prose

#### recap *: [str](https://docs.python.org/3/builtins/stdtypes.html#str)* *= ''*

Claude Code’s own end-of-turn recap (its `away_summary` record) — one to three
sentences it wrote itself, usually naming what it thought came next. Reading it
is retention, not duplication: it was generated and billed once already, and it
disappears with the transcript.

#### refs *: [tuple](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[Any](https://docs.python.org/3/library/typing.html#typing.Any), ...]* *= ()*

Every pull request and branch the transcript refers to, unbounded, for the
reverse index in [`openloops.provenance`](_autosummary/openloops.provenance.html.md#module-openloops.provenance). Not rendered into the digest.

### *class* openloops.Verdict(state, reason, cues=(), at='', confidence='high')

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

A loop-state judgement, with the rule that produced it and the cues it saw.

`reason` and `cues` exist so a reader can disagree. A classification whose
grounds are not shown is an assertion, and openloops does not make assertions
about sessions — it reports what they said and why it read them that way.

#### as_dict()

JSON-ready form.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]

#### at *: [str](https://docs.python.org/3/builtins/stdtypes.html#str)* *= ''*

When the text this verdict was read from was written. Usually the closing turn,
but the recap rule reads text written later, and a heading dated to the wrong
moment is exactly the thing ADR-005 forbids.

#### confidence *: [str](https://docs.python.org/3/builtins/stdtypes.html#str)* *= 'high'*

`"high"` when a rule actually fired, `"low"` when the state is the default
and nothing in the transcript supported it. A classifier that hides which of the
two it did is claiming knowledge it does not have.

### openloops.agents_dir()

The bundled subagent definitions, inside the installed package.

* **Return type:**
  [`Path`](https://docs.python.org/3/library/pathlib.html#pathlib.Path)

### openloops.asks_the_human(text, , ask_cues=('want me to', 'do you want', 'would you like', 'shall i', 'should i', 'let me know', 'say the word', 'your call', 'up to you', 'over to you', 'which would you', 'tell me which', "if you'd prefer", 'if you would prefer', 'needs your input', 'needs your review', 'needs your decision', 'needs your go-ahead', 'needs your call'), chars=1200)

The ask cues in the closing lines, if those lines put a question to the reader.

The primitive a retrospective measurement uses to ask “did this session end with a
question directed at the human” — defined once, here, rather than twice.

```pycon
>>> asks_the_human('I fixed it. Want me to open the PR?')
('want me to',)
>>> asks_the_human('Was it broken? Yes, and I fixed it.')
()
>>> asks_the_human('All done.')
()
```

* **Return type:**
  [`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`...`](https://docs.python.org/3/builtins/constants.html#Ellipsis)]

### openloops.blocked(, resolve=True, owners=None, repos=(), query='is:blocked', limit=50, timeout=30.0, now=None, issues_source=None, blockers_source=None)

Open issues that carry a blocker edge, with every edge resolved.

The row that matters sorts first: `unblocked` — every blocker closed, the work
free to proceed, and nothing anywhere has said so. `blocked` rows name what they
are waiting on, foreign repository included. `unknown` means the edges could not
be read, and it is never rounded into either of the others.

`owners=` scopes the fleet-wide search (default: `openloops.obligations.
configured_owners()`, the same fleet `ol owed` answers about, so two commands never
quietly disagree about which repositories exist). `repos=` instead enumerates the
repositories you name exactly, which is the audit path.

`resolve=False` lists candidates without spending one API call each; every row
then reads `unknown`, because that is what is true about it.

Two seams, each one keyword argument, each defaulting to a real implementation:
`issues_source=` (defaults to [`gh_blocked_candidates()`](_autosummary/openloops.html.md#openloops.gh_blocked_candidates); a list of dicts
substitutes) and `blockers_source=` (defaults to [`gh_blocked_by()`](_autosummary/openloops.html.md#openloops.gh_blocked_by); a mapping
from `'owner/name#number'` to edges, or any callable of `(repo, number)`,
substitutes). With both injected this reaches no network and needs no `gh`.

Returns one envelope, never a bare list, because a reader has to be able to tell
“nothing is waiting” from “I could not find out”:

`listed`
: `False` when *discovery itself* failed. Every surface must render that as
  `?`. The counts are zeros and they mean nothing.

`resolved`
: whether edges were resolved at all.

`truncated`
: the candidate list saturated `limit`, so the counts are a floor.

`counts`
: `unblocked` / `blocked` / `unknown`, plus `cross_repo`, `candidates`
  (how many discovery offered), `without_edges` (how many of those the
  dependency graph disagreed about) and `total` (how many rows).

`rows`
: one dict per issue, with every key in `BLOCKED_FIELDS`.

```pycon
>>> report = blocked(issues_source=[], blockers_source={})
>>> report['listed'], report['counts']['total'], report['rows']
(True, 0, [])
```

Discovery that could not run is not “nothing is waiting”:

```pycon
>>> def broken(**query):
...     raise GhUnavailable('gh: not logged in')
>>> report = blocked(issues_source=broken)
>>> report['listed'], report['error'], report['counts']['total']
(False, 'gh: not logged in', 0)
```

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]

### openloops.classify(session, , ask_cues=('want me to', 'do you want', 'would you like', 'shall i', 'should i', 'let me know', 'say the word', 'your call', 'up to you', 'over to you', 'which would you', 'tell me which', "if you'd prefer", 'if you would prefer', 'needs your input', 'needs your review', 'needs your decision', 'needs your go-ahead', 'needs your call'), defer_cues=('still open', 'still owed', 'still outstanding', 'still pending', 'next step', 'next session', 'left off', 'waiting for you', 'waiting on', 'blocked on', 'blocked by', 'handoff', 'hand-off', 'pick it up', 'pick this up', 'pick that up', 'i left it', 'not yet done', 'not yet merged', 'not yet posted', 'open question', 'unresolved', 'i could not', "i couldn't", 'was unable to', 'were unable to', 'did not finish', "didn't finish", 'needs a human', 'needs you', 'still needs', "you'll need to", 'you will need to', 'requires you to'), close_cues=('nothing half-finished', 'nothing pending', 'nothing is pending', 'nothing left', 'nothing is blocking', 'nothing blocking', 'nothing to clean', 'nothing else outstanding', 'nothing outstanding', 'nothing further', 'no next action', 'no further action', 'no action needed', 'safe to close', 'safe to exit', "you're all set", 'you are all set', 'all done', 'everything is done', 'everything is green', 'everything is verified', 'not unfinished business', 'ready to close'), chars=1200)

Read a session’s loop state from its own last turn.

```pycon
>>> from openloops.base import Session
>>> classify(Session(key='s', ended_with_error=True)).state
'open'
>>> v = classify(Session(key='s', last_assistant_text='Blocked on your deploy key.'))
>>> v.state, v.cues, v.confidence
('open', ('blocked on',), 'high')
```

* **Return type:**
  [`Verdict`](_autosummary/openloops.base.html.md#openloops.base.Verdict)

### openloops.data_dir()

The project’s data root. Override with `OPENLOOPS_DATA_DIR`.

Per-kind subdirectories hang off this; nothing is written directly into it, so a
later kind of data needs no second migration.

* **Return type:**
  [`Path`](https://docs.python.org/3/library/pathlib.html#pathlib.Path)

### openloops.default_source(directory=None)

This machine’s label for its digest folder. Override with `OPENLOOPS_SOURCE`.

A short, filename-safe name. It exists so several machines can sync digests into one
place without colliding — not to identify anybody, though on a machine whose
hostname was never changed it may well do; every `ol sync` prints it, and
`OPENLOOPS_SOURCE` overrides it.

**It is sticky.** The hostname is a *seed*, written once to a file under the state
directory and read thereafter. macOS rewrites the hostname when it joins a network
where the name collides — appending `-2`, `-3` — and a label that moved would
fork the store into two complete copies with no dedup and no warning.

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### openloops.digest_key(source, state, session_key)

The store key for one session’s digest.

Both segments are validated, not just the state. `transcript_source=` is a seam
whose documented purpose is “another machine’s synced transcripts”, so a session id
can come from a listing this process did not produce — and a key containing `..`
would make a file-backed store write outside its own root while `sync` reported
success. Validating here means every backend inherits the check.

```pycon
>>> digest_key('mac', 'archive', 's1')
'mac/archive/s1.md'
>>> digest_key('mac', 'open', '../../etc/passwd')
Traceback (most recent call last):
    ...
ValueError: session key must be a single safe path segment, got '../../etc/passwd'
```

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### openloops.digests_store(rootdir=None)

The default `digests_store`: markdown files under the data root.

Any `MutableMapping[str, str]` works in its place — a plain `dict` for tests,
a git-synced directory, an S3-backed store. The keys are what carry the layout, so
a different backend gets the same `{source}/{state}/{session}.md` structure for
free.

```pycon
>>> store = digests_store(rootdir='/tmp/openloops-doctest-store')
>>> store['demo/open/s1.md'] = '# hi'
>>> sorted(store)
['demo/open/s1.md']
>>> del store['demo/open/s1.md']
```

* **Return type:**
  [`MutableMapping`](https://docs.python.org/3/library/collections.abc.html#collections.abc.MutableMapping)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]

### openloops.exchanges(records, , key='')

Every prompt of a transcript’s main thread, in order, each with its turn’s reply.

Records are ordered by timestamp (a transcript’s lines are not always written in
order), ties kept in file order. Sub-agent sidechains are left out: their “prompts”
were written by the session, not to it.

```pycon
>>> recs = [
...     {"type": "user", "sessionId": "s", "uuid": "u1", "timestamp": "T1",
...      "message": {"content": "Ship it. Is the cache still warm?"}},
...     {"type": "assistant", "timestamp": "T2", "message": {"content": [
...         {"type": "text", "text": "Shipped. Yes, warm for an hour."}]}},
... ]
>>> [(e.uuid, e.questions, e.reply) for e in exchanges(recs)]
[('u1', ('Is the cache still warm?',), 'Shipped. Yes, warm for an hour.')]
```

* **Return type:**
  [`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[`Exchange`](_autosummary/openloops.html.md#openloops.Exchange), [`...`](https://docs.python.org/3/builtins/constants.html#Ellipsis)]

### openloops.gh_blocked_by(repo, number, , timeout=30.0)

The default `blockers_source`: the blocker edges out of one issue.

One request per issue — the N+1 [`blocked()`](_autosummary/openloops.html.md#openloops.blocked) bounds with `limit=`. Returns the
rows GitHub sends, unparsed and unjudged; `_verdict()` is what reads a state
out of them. An issue with no edges answers `[]`, which is an answer.

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]]

### openloops.gh_blocked_candidates(, owners=(), repos=(), query='is:blocked', limit=50, timeout=30.0)

The default `issues_source`: open issues that *may* carry a blocker edge.

`repos=` chooses the exact per-repository enumeration; otherwise `owners=`
drives one fleet-wide search. Both return rows shaped the way `gh search issues`
shapes them — `createdAt`, `number`, `repository`, `title`, `url` — so
everything downstream reads one shape. Which one to use, and what each costs and
misses, is the “Discovery is a candidate list” section of this module’s docstring.

A large repository can take longer than `timeout` to paginate; that is a
[`GhUnavailable`](_autosummary/openloops.html.md#openloops.GhUnavailable), which reads `?`, not an empty answer.

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]]

### openloops.gh_issues(, owners, label='manual-task', state='open', limit=1000, timeout=30.0)

The default `issues_source`: the open `manual-task` issues, from `gh`.

This is a *filtered* search, not an enumeration — the label is applied server-side
and the result is capped — which is the only form of search this package is allowed
to use. Walking a whole fleet’s issues through the search API silently returns wrong
answers past its first thousand results; that job belongs to per-repo listing.

One query per owner, each asking for up to `limit` rows (clamped to GitHub’s
`SEARCH_CEILING`), so the ceiling applies to an owner, not to the whole fleet.
An owner whose query returns as many rows as it asked for is named in the result’s
`saturated` attribute: its count is a floor.

Returns whatever `gh` returned, unparsed and unjudged: a list of dicts with
`createdAt`, `number`, `repository`, `title`, `url` and `body`.

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]]

### openloops.headline_counts(owed, blocked, sessions)

The four figures across the top of the page. `None` is `?`, never a zero.

Shared by the masthead and by [`openloops.tools.dashboard()`](_autosummary/openloops.tools.html.md#openloops.tools.dashboard), so the number a
caller reads back is the number the page printed.

```pycon
>>> headline_counts({'listed': True, 'counts': {'open': 2}, 'rows': []},
...                 {'listed': False}, [])['free_to_proceed'] is None
True
```

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`int`](https://docs.python.org/3/builtins/functions.html#int) | [`None`](https://docs.python.org/3/builtins/constants.html#None)]

### openloops.held_prs(, owners=None, stale_days=7, now=None, prs_source=None)

The open PRs you opened that are held, or stalled for `stale_days`, in one envelope.

`prs_source` is the seam: a callable taking `owners=` (default:
`openloops.obligations.gh_open_prs()`) or the rows themselves. As with
[`openloops.obligations.owed()`](_autosummary/openloops.obligations.html.md#openloops.obligations.owed), a listing that failed is `listed: False` with
an `error`, never an empty list. Rows are held first, then stalled, oldest first.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]

### openloops.hold_reason(pr)

Why `pr` is held, or `""` when it is not: a `Held:` line, a draft, a title starting “Held”.

```pycon
>>> hold_reason({'body': 'Adds X.\n\nHeld: waits on the owner (a design call)'})
'waits on the owner (a design call)'
>>> hold_reason({'isDraft': True}), hold_reason({'title': 'Fix y'})
('draft', '')
```

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### openloops.install_skills(, target=None, only=None, copy=False, force=False, dry_run=False)

Make the bundled skills and subagent visible to an agent host. Idempotent.

Links each one into `target` (default: `CLAUDE_CONFIG_DIR` or `~/.claude`) so
that upgrading the package upgrades the skill. `copy=True` takes a copy instead,
which is also what happens by itself where symlinks are unavailable.

Returns the plan it carried out – one row per asset, each carrying its verdict and
the reason for it. `dry_run=True` returns the same plan having touched nothing,
which is the only way to see what a run would do *before* it does it.

Nothing that is already there is overwritten: an occupied destination reads
`conflict` and is left exactly as it was until `force=True`.

`only=` installs a subset by name. The case it exists for: you already have your
own capture skill, adapted to your own fleet, and a second one competing for the same
triggers is worse than either alone – so take the reader and the subagent and leave
the capture skill out.

The plan’s `shadowed` list names any bare-named skill (`needs-human`) that
resolves somewhere other than the shipped copy, and whether its text matches ours;
nothing is changed on its account.

```pycon
>>> plan = install_skills(target='/nonexistent/host', only=['openloops'], dry_run=True)
>>> [row['name'] for row in plan['actions']]
['openloops']
```

```pycon
>>> plan = install_skills(target='/nonexistent/host', dry_run=True)
>>> plan['counts']['install'] == len(list(bundled())), plan['dry_run']
(True, True)
>>> sorted({row['action'] for row in plan['actions']})
['install']
```

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]

### openloops.make_digest(session, verdict, , source, aliases=None)

Render, scrub, and key one digest.

Raises [`CredentialFound`](_autosummary/openloops.egress.html.md#openloops.egress.CredentialFound) when the rendered text matches a
credential pattern — deliberately, so the caller skips that session loudly rather
than writing a secret into a store that may be synced.

```pycon
>>> from openloops.base import Session, Verdict
>>> d = make_digest(Session(key='s1'), Verdict('open', 'why'), source='demo')
>>> d.key
'demo/open/s1.md'
```

* **Return type:**
  [`Digest`](_autosummary/openloops.base.html.md#openloops.base.Digest)

### openloops.owed(\*, verify=True, owners=None, trusted_owners=None, label='manual-task', limit=1000, timeout=30.0, predicate_timeout=20.0, now=None, issues_source=None, run_predicate=None, write_guard=<function write_effect>)

The open `manual-task` obligations, each re-checked against the world.

`verify=False` lists without executing anything; every row that carries a
predicate then reads `unknown`, because that is what is true about it.

`owners=` scopes the search (default: `configured_owners()`).
`trusted_owners=` scopes what may *execute* and defaults to `owners`, so
widening the search never quietly widens what runs — pass it explicitly to search
wider than you trust.

A predicate that *looks like a write* (`gh workflow run`, a `curl` write, `git
push`… see [`openloops.predicate_safety`](_autosummary/openloops.predicate_safety.html.md#module-openloops.predicate_safety)) is not run: the row reads
`unknown` with `unverified: predicate not read-only`, because asking what is owed
must not start a deploy (openloops#43). `write_guard=` is the seam: any callable
from command to a non-empty reason (refuse) or `""` (run); `lambda c: ""`
restores the old behaviour.

Two seams, each one keyword argument, each defaulting to a real implementation:
`issues_source=` (defaults to [`gh_issues()`](_autosummary/openloops.html.md#openloops.gh_issues); a list of dicts substitutes) and
`run_predicate=` (defaults to [`shell_predicate()`](_autosummary/openloops.html.md#openloops.shell_predicate); any callable from command
to exit status substitutes). With both injected this reaches no network and needs no
`gh`.

Returns one envelope, never a bare list, because a reader has to be able to tell
“nothing is owed” from “I could not find out”:

`listed`
: `False` when the *listing itself* failed. Every surface must render that as
  `?`. The counts are zeros and they mean nothing.

`checked`
: whether predicates were evaluated at all.

`truncated`
: the result set saturated its own cap, so the count is a floor.

`counts`
: `open` / `discharged` / `unknown` / `with_predicate` / `total`.

`rows`
: one dict per obligation, with every key in `OBLIGATION_FIELDS`.

```pycon
>>> report = owed(issues_source=[], run_predicate=lambda command: 0)
>>> report['listed'], report['counts']['total'], report['rows']
(True, 0, [])
```

A listing that could not run is not “nothing owed”:

```pycon
>>> def broken(**query):
...     raise GhUnavailable('gh: not logged in')
>>> report = owed(issues_source=broken)
>>> report['listed'], report['error'], report['counts']['total']
(False, 'gh: not logged in', 0)
```

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]

### openloops.parse_session(records, , key='')

Read one transcript’s records into a [`Session`](_autosummary/openloops.base.html.md#openloops.base.Session).

Pure: same records in, same session out. Everything it reports is a fact about the
document — no inference, no judgement, and nothing about running processes.

Three details are corpus-driven rather than obvious, and getting them wrong
mislabels a large fraction of real sessions:

- \*\*Start and end come from `min`/`max` over every timestamp\*\*, not from the
  first and last line. Transcript lines are not written in timestamp order; on real
  data the first line holds the earliest timestamp only about four times in five.
- \*\*The project comes from the *first* record’s `cwd`.\*\* Four sessions in five
  visit more than one working directory (scratchpads, sibling repos, task dirs), and
  the last or most-frequent one names a different repository about half the time.
- **Branches are a tuple.** A third of sessions touch more than one.

```pycon
>>> recs = [
...     {"type": "user", "sessionId": "s1", "cwd": "/w/proj", "timestamp": "T1",
...      "gitBranch": "main",
...      "message": {"role": "user", "content": [{"type": "text", "text": "do it"}]}},
...     {"type": "assistant", "sessionId": "s1", "timestamp": "T2",
...      "message": {"role": "assistant", "model": "m",
...                  "content": [{"type": "text", "text": "done"}]}},
... ]
>>> s = parse_session(recs)
>>> s.key, s.project, s.turn_count, s.last_assistant_text
('s1', 'proj', 1, 'done')
>>> s.started_at, s.ended_at, s.git_branch, s.ended_mid_turn
('T1', 'T2', 'main', False)
```

* **Return type:**
  [`Session`](_autosummary/openloops.base.html.md#openloops.base.Session)

### openloops.parse_verify(body)

`(predicate, verify_text)` for an issue body. Both are `''` when absent.

The predicate is the first code span in the field. Prose with no code span – the
documented “no predicate is possible here” answer – yields no command, and the
prose is kept so the row can say *why* rather than merely say nothing.

```pycon
>>> parse_verify('**Verify:** `test -f x`')
('test -f x', '`test -f x`')
>>> parse_verify('no such field here')
('', '')
```

A field that says no predicate is possible yields no command \*\*even when its prose
contains a code span\*\* – the documented wording mentions `gh` and `true` naturally,
and both exit 0, which would report a live obligation as done:

```pycon
>>> parse_verify('**Verify:** none possible - no `gh` query observes a decision.')
('', 'none possible - no `gh` query observes a decision.')
```

A quoted example of the format is not this issue’s own predicate:

```pycon
>>> body = chr(10).join(['```', '**Verify:** `quoted`', '```', '**Verify:** `real`'])
>>> parse_verify(body)[0]
'real'
```

An unterminated code span is not a command – it is a malformed field, and saying so
is the difference between a row that reads `?` and one that silently reads open:

```pycon
>>> parse_verify('**Verify:** `echo one &&' + chr(10) + 'echo two`')
('', '`echo one &&')
```

* **Return type:**
  [`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]

### openloops.question_sentences(text)

The sentences of a person’s prompt that ask something, in order, at most
`MAX_QUESTIONS`.

A sentence asks when it ends with `?` or opens the way a question does (“why”,
“is there”, “I wonder”), and is not a request phrased as one (“can you fix it?”).
Code blocks, quoted lines and table rows are skipped.

```pycon
>>> question_sentences("Can you add a test? Could you explain why it failed?")
('Could you explain why it failed?',)
>>> question_sentences("> Why is it slow?\nok?\nwhy does the page load twice")
('why does the page load twice',)
```

* **Return type:**
  [`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`...`](https://docs.python.org/3/builtins/constants.html#Ellipsis)]

### openloops.render(session, verdict, , source)

The markdown for one digest. Pure, dated, and bounded.

```pycon
>>> from openloops.base import Session, Verdict
>>> s = Session(key='s1', project='proj', started_at='T0', last_turn_at='T1',
...             last_assistant_text='Shipped it.', turn_count=3)
>>> verdict = Verdict('archive', 'its closing lines declare it finished')
>>> text = render(s, verdict, source='demo')
>>> text.splitlines()[0]
'---'
>>> 'state: archive' in text
True
>>> render(s, verdict, source='demo') == text     # pure: same in, same out
True
```

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### openloops.render_dashboard(owed, blocked, sessions, , made_at=None, source='', title='Open Loops Board', max_sessions=40, standalone=True, aliases=None, published=None, published_per_session=3)

The three envelopes as one self-contained HTML page. No network, no script.

`owed` and `blocked` are the envelopes [`openloops.owed()`](_autosummary/openloops.html.md#openloops.owed) and
[`openloops.blocked()`](_autosummary/openloops.html.md#openloops.blocked) return; `sessions` is the list `openloops.ls()`
returns. All three may be empty mappings, and an envelope whose `listed` is
`False` renders as `?` throughout rather than as zero.

`made_at` is the moment the snapshot was taken and is printed in the largest type
on the page. It defaults to now, but a caller that wants a byte-stable page passes
it — this is the one module in openloops that stamps a generation time, and it does
so because the whole claim of the page is *when*.

`standalone` wraps the output in a document scaffold for a file you open yourself.
Pass `False` for a host that supplies its own `<head>` — a published artifact
does — and the same page comes back as title, styles and content only.

`max_sessions` bounds the in-flight register; the true total is stated either way.

`published` is the envelope `openloops.published()` returns. When given, a
“Handed to you” register lists each session’s most recent documents
(`published_per_session` of them, with the true total stated); an envelope that
never listed renders as unknown, not as “nothing published”. When omitted the
register is left out, so the page is the one it always was.

```pycon
>>> page = render_dashboard(
...     {'listed': False, 'error': 'gh: not logged in', 'counts': {}},
...     {'listed': True, 'counts': {'unblocked': 0, 'total': 0}, 'rows': []},
...     [], made_at='2026-01-01T00:00:00Z')
>>> 'gh: not logged in' in page and 'could not' in page
True
```

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### openloops.retained(store, sessions, , source=None)

Digest keys whose session no longer has a transcript — the retention surplus.

These are what makes openloops a retention device rather than a view: Claude Code
garbage-collects transcripts, and a digest outlives the thing it was derived from.
[`sync()`](_autosummary/openloops.html.md#openloops.sync) never removes them, and they are the one part of the store that a
from-scratch rebuild does not reproduce.

```pycon
>>> retained({'m/open/a.md': '', 'm/open/b.md': ''}, {'a': None})
['m/open/b.md']
```

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]

### openloops.scrub(text, , aliases=None, where='')

Rewrite paths and raise on credentials. The only way text leaves openloops.

`where` is a caller-supplied label (a session id, a file name) carried into the
exception so a failed run can say *which* input tripped, without quoting it.

The path check runs on the **output**, not the input, because `aliases` is
caller-supplied: a rewrite can in principle produce a home path as easily as remove
one, and a postcondition that is only true of benign inputs is not a postcondition.

```pycon
>>> scrub("built /nowhere/proj/x", aliases={"/nowhere/proj": "$PROJ"})
'built $PROJ/x'
```

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### openloops.shell_predicate(command, , timeout=20.0)

The default `run_predicate`: run the command in a subshell, bounded in time.

The exit status is the answer and nothing else is interpreted. Anything that is not
an exit status — a timeout, a shell that would not start — comes back as
`status=None`, which is `unknown`, which is `?`.

```pycon
>>> shell_predicate('exit 0').status
0
>>> shell_predicate('exit 3').status
3
>>> shell_predicate('   ').status is None
True
```

* **Return type:**
  [`PredicateOutcome`](_autosummary/openloops.obligations.html.md#openloops.obligations.PredicateOutcome)

### openloops.skills_dir()

The bundled skills directory, inside the installed package.

`Path(__file__).parent` rather than a configured root, so this answers correctly
from a wheel, an editable install, a zip and a virtualenv without being told which.

* **Return type:**
  [`Path`](https://docs.python.org/3/library/pathlib.html#pathlib.Path)

### openloops.state_dir()

Where per-machine caches and job logs go. Override with `OPENLOOPS_STATE_DIR`.

Deliberately not under [`data_dir()`](_autosummary/openloops.html.md#openloops.data_dir): everything here is disposable, and keeping
it elsewhere means “clear the cache” can never be mistyped into “delete the digests”.

* **Return type:**
  [`Path`](https://docs.python.org/3/library/pathlib.html#pathlib.Path)

### openloops.sync(, transcript_source=None, digests_store=None, source=None, since_days=None, state_dir=None, force=False, provenance_store=None)

Bring the digest store up to date with the sessions, and say what changed.

`force` ignores the cache and re-derives everything; the result must be identical,
which is what makes it safe to suggest when someone suspects a stale digest.

`provenance_store` receives each session’s pull requests and branches (the reverse
index [`openloops.provenance.who_made()`](_autosummary/openloops.provenance.html.md#openloops.provenance.who_made) reads). It defaults to the real store only
when `digests_store` does too, so a caller that redirects the digests (a test, a
fixture) never writes provenance into the real data directory by accident.

```pycon
>>> from openloops.base import STATES, Session
>>> sessions = {'s1': Session(key='s1',
...                               last_assistant_text='Shipped it. Nothing is pending.')}
>>> store = {}
>>> r = sync(transcript_source=sessions, digests_store=store, source='demo',
...          state_dir='/tmp/openloops-doctest-state', force=True)
>>> r['written'], sorted(store)
(1, ['demo/archive/s1.md'])
>>> sync(transcript_source=sessions, digests_store=store, source='demo',
...      state_dir='/tmp/openloops-doctest-state', force=True)['written']
0
```

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]

### Modules

| [`base`](_autosummary/openloops.base.html.md#module-openloops.base)                         | Data structures shared across openloops: what a session is, and what a digest is.         |
|-----------------------------------------------------------------------------------------------------|-------------------------------------------------------------------------------------------|
| [`blockers`](_autosummary/openloops.blockers.html.md#module-openloops.blockers)                 | The other kind of open loop: the one that points at a repository, not at a person.        |
| [`board`](_autosummary/openloops.board.html.md#module-openloops.board)                       | The phone task board: task records in, a static page and its data files out.              |
| [`board_refresh`](_autosummary/openloops.board_refresh.html.md#module-openloops.board_refresh)       | Keep the phone board within a day of GitHub, without a session remembering to.            |
| [`board_server`](_autosummary/openloops.board_server.html.md#module-openloops.board_server)         | An optional web app for a self-hosted phone board: the page, its files, its store API.    |
| [`board_store`](_autosummary/openloops.board_store.html.md#module-openloops.board_store)           | The board store's rules, for a self-hosted phone board: who may write what, and how.      |
| [`closer`](_autosummary/openloops.closer.html.md#module-openloops.closer)                     | The one module that writes to GitHub: a manual task closes on its passing check.          |
| [`command_risk`](_autosummary/openloops.command_risk.html.md#module-openloops.command_risk)         | Is a shell command risky to run? A deterministic reading of its text.                     |
| [`command_syntax`](_autosummary/openloops.command_syntax.html.md#module-openloops.command_syntax)     | Does each command of a run plan use only flags its program knows? (ADR-018)               |
| [`dashboard`](_autosummary/openloops.dashboard.html.md#module-openloops.dashboard)               | One page you can look at instead of reading three command outputs.                        |
| [`digest`](_autosummary/openloops.digest.html.md#module-openloops.digest)                     | Rendering one session into one dated markdown digest.                                     |
| [`egress`](_autosummary/openloops.egress.html.md#module-openloops.egress)                     | The egress choke point: nothing leaves openloops carrying a home path or a secret.        |
| [`facets`](_autosummary/openloops.facets.html.md#module-openloops.facets)                     | The board's facet families: how a task is categorised, computed from what it is.          |
| [`gtd`](_autosummary/openloops.gtd.html.md#module-openloops.gtd)                           | Getting Things Done (David Allen) as an organising method: the default, and the only one. |
| [`job`](_autosummary/openloops.job.html.md#module-openloops.job)                           | The periodic job: launchd runs `ol sync`, writes, and exits.                              |
| [`loops`](_autosummary/openloops.loops.html.md#module-openloops.loops)                       | Loops: the one record of a commitment, and the pure function that says what is due.       |
| [`method`](_autosummary/openloops.method.html.md#module-openloops.method)                     | The organising method: the seam between the loop record and the system that organises it. |
| [`obligations`](_autosummary/openloops.obligations.html.md#module-openloops.obligations)           | What you still owe your agents — re-checked against the world before it is shown.         |
| [`pile`](_autosummary/openloops.pile.html.md#module-openloops.pile)                         | The pile: GTD's In list, kept as GitHub issues in a private repo, and its clarify step.   |
| [`predicate_safety`](_autosummary/openloops.predicate_safety.html.md#module-openloops.predicate_safety) | Is a `manual-task` verify predicate a pure read?                                          |
| [`provenance`](_autosummary/openloops.provenance.html.md#module-openloops.provenance)             | Which session made this pull request or branch? A reverse index, kept by `ol sync`.       |
| [`publications`](_autosummary/openloops.publications.html.md#module-openloops.publications)         | What your agents handed you lately: recently published annals documents, per session.     |
| [`receiver_tick`](_autosummary/openloops.receiver_tick.html.md#module-openloops.receiver_tick)       | One tick of the board-receiver job: check for work without a model, then hand over.       |
| [`remind`](_autosummary/openloops.remind.html.md#module-openloops.remind)                     | Reminders: loops kept in a store and delivered through a channel that holds the time.     |
| [`runbook`](_autosummary/openloops.runbook.html.md#module-openloops.runbook)                   | Run plans: the owner's command-line manual tasks, planned by an agent, run without one.   |
| [`runbook_issue`](_autosummary/openloops.runbook_issue.html.md#module-openloops.runbook_issue)       | One manual-task issue, from its number to a reviewed run plan, with no agent in between.  |
| [`runbook_run`](_autosummary/openloops.runbook_run.html.md#module-openloops.runbook_run)           | Run an approved run plan: exactly the approved commands, no model, close on the check.    |
| [`session_page`](_autosummary/openloops.session_page.html.md#module-openloops.session_page)         | A session, rendered as one page a person can read: pure, script-free, private by rule.    |
| [`skills`](_autosummary/openloops.skills.html.md#module-openloops.skills)                     | The agent-facing surface: two skills, one subagent, and the command that installs them.   |
| [`store`](_autosummary/openloops.store.html.md#module-openloops.store)                       | Where digests live, and where the change-detection cache lives — two different things.    |
| [`tasks`](_autosummary/openloops.tasks.html.md#module-openloops.tasks)                       | Everything you could act on, as one list of task records: gather, classify, merge.        |
| [`tools`](_autosummary/openloops.tools.html.md#module-openloops.tools)                       | The package's single list of operations: plain functions, JSON-ready dicts.               |
| [`transcripts`](_autosummary/openloops.transcripts.html.md#module-openloops.transcripts)           | The default `transcript_source`: a direct reader of Claude Code's on-disk state.          |
| [`whenthen_job`](_autosummary/openloops.whenthen_job.html.md#module-openloops.whenthen_job)         | Handing the periodic jobs to whenthen: register a job, take over from the launchd agent.  |
| [`word_close`](_autosummary/openloops.word_close.html.md#module-openloops.word_close)             | Close one issue on the owner's own word, relayed by an assistant (voice, a chat).         |


# _autosummary/openloops.job.html.md

# openloops.job

The periodic job: launchd runs `ol sync`, writes, and exits. No daemon.

ADR-003’s decision, applied to digests. A resident process would have to be kept alive,
and when it dies its output latches at whatever it last wrote — a confident, months-old
answer with nothing scheduled to correct it. A `StartInterval` job is self-healing by
construction: a tick that crashes is repaired by the next one, and the only thing to
supervise is launchd itself.

The environment is captured at install time and pinned into the plist, because launchd
hands a job a nearly empty environment. The interpreter is invoked directly rather than
by console-script name, for the same reason: a name resolved against a minimal `PATH`
is a lottery whose losing ticket is a job that dies instantly, every tick, silently.

macOS only. On Linux the equivalent is a systemd user timer or a crontab line running
the same command, and [`install()`](_autosummary/openloops.job.html.md#openloops.job.install) says so rather than pretending.

### Module Attributes

| [`DFLT_LABEL`](_autosummary/openloops.job.html.md#openloops.job.DFLT_LABEL)        | launchd job label.                                                                                                                                     |
|--------------------------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------|
| [`DFLT_INTERVAL`](_autosummary/openloops.job.html.md#openloops.job.DFLT_INTERVAL)     | Seconds between ticks.                                                                                                                                 |
| [`RECEIVER_LABEL`](_autosummary/openloops.job.html.md#openloops.job.RECEIVER_LABEL)    | launchd label of the board-receiver job (ADR-011).                                                                                                     |
| [`RECEIVER_INTERVAL`](_autosummary/openloops.job.html.md#openloops.job.RECEIVER_INTERVAL) | Seconds between receiver ticks.                                                                                                                        |
| [`REMIND_LABEL`](_autosummary/openloops.job.html.md#openloops.job.REMIND_LABEL)      | no model, so it can run often; six hours keeps the board within a day of GitHub with margin.                                                           |
| [`REMIND_INTERVAL`](_autosummary/openloops.job.html.md#openloops.job.REMIND_INTERVAL)   | a reminder is armed on the channel up to three days ahead, so the tick only needs to catch loops entering that horizon and record the ones that fired. |
| [`SECRET_ENV`](_autosummary/openloops.job.html.md#openloops.job.SECRET_ENV)        | Variables a job needs that are secret-like.                                                                                                            |

### Functions

| [`install`](_autosummary/openloops.job.html.md#openloops.job.install)(\*[, label, interval, dry_run, ...])     | Install (or replace) the periodic sync job.                                      |
|---------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------|
| [`install_remind`](_autosummary/openloops.job.html.md#openloops.job.install_remind)(\*[, dry_run, use_whenthen, ...]) | Install (or replace) the reminder tick job.                                      |
| [`remind_job_spec`](_autosummary/openloops.job.html.md#openloops.job.remind_job_spec)(\*[, interval, label])           | The reminder tick as data: `python -m openloops remind-tick` every `interval` s. |
| [`install_receiver`](_autosummary/openloops.job.html.md#openloops.job.install_receiver)(work_dir, \*[, dry_run, ...])   | Install (or replace) the board-receiver job.                                     |
| [`receiver_job_spec`](_autosummary/openloops.job.html.md#openloops.job.receiver_job_spec)(work_dir, \*[, claude, ...])   | The receiver job as data: program arguments, environment, plist.                 |
| [`uninstall`](_autosummary/openloops.job.html.md#openloops.job.uninstall)(\*[, label])                           | Unload the job and remove its plist and its whenthen job, whichever exist.       |
| [`job_status`](_autosummary/openloops.job.html.md#openloops.job.job_status)(\*[, label, env_file])                | Installed? loaded? and — the question that matters — when did it last write?     |
| [`plist_xml`](_autosummary/openloops.job.html.md#openloops.job.plist_xml)(\*, label, program_args, env, ...)     | The launchd property list, as text.                                              |

### openloops.job.DFLT_INTERVAL *= 900*

Seconds between ticks. A digest is a record of what a session said, so being a
quarter of an hour behind costs nothing; running every few seconds would cost a
full scan of the transcript directory for no gain.

### openloops.job.DFLT_LABEL *= 'openloops.sync'*

launchd job label. Also the plist filename and the log filename.

### openloops.job.RECEIVER_INTERVAL *= 300*

Seconds between receiver ticks. A tick that finds nothing pending costs a few HTTP
calls and no model, so this can be as short as the phone board’s latency wants.

### openloops.job.RECEIVER_LABEL *= 'openloops.board-receiver'*

launchd label of the board-receiver job (ADR-011).

### openloops.job.REMIND_INTERVAL *= 3600*

a reminder is armed on the channel up to three days ahead, so the tick only
needs to catch loops entering that horizon and record the ones that fired.

* **Type:**
  Hourly

### openloops.job.REMIND_LABEL *= 'openloops.remind-tick'*

no model, so it can
run often; six hours keeps the board within a day of GitHub with margin.

* **Type:**
  The board-rebuild job (`ol board-refresh` on a timer; issue #39)

### openloops.job.SECRET_ENV *= ('NTFY_TOPIC',)*

Variables a job needs that are secret-like. On a whenthen job they never go on the
command line (the job record would hold them): they are written to `JOB_ENV_FILE`,
which only the owner can read, and the job reads it with `--env-file`.

### openloops.job.install(, label='openloops.sync', interval=900, dry_run=False, use_whenthen=None, source='ol install-job', quote='')

Install (or replace) the periodic sync job. Returns the paths it wrote.

A whenthen job when whenthen is installed (`use_whenthen=None` asks), taking over
from the launchd agent; else the launchd agent, with a smoke run after the bootstrap,
because a job that cannot start produces exactly the same silence as a job with
nothing to do.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]

### openloops.job.install_receiver(work_dir, , dry_run=False, use_whenthen=None, source='ol install-receiver-job', quote='', \*\*kwargs)

Install (or replace) the board-receiver job. Returns the paths it wrote.

`kwargs` are those of [`receiver_job_spec()`](_autosummary/openloops.job.html.md#openloops.job.receiver_job_spec). A dry run builds and returns the
plist without touching launchd and without requiring the credentials file. As a
whenthen job it runs `receiver_tick --session` (the packaged `claude -p` command)
in the working folder, with the same environment, env file and limits.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]

### openloops.job.install_remind(, dry_run=False, use_whenthen=None, source='ol install-remind-job', quote='', \*\*kwargs)

Install (or replace) the reminder tick job. `kwargs` are [`remind_job_spec()`](_autosummary/openloops.job.html.md#openloops.job.remind_job_spec)’s.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]

### openloops.job.job_status(, label='openloops.sync', env_file=PosixPath('~/.config/openloops/board-receiver.env'))

Installed? loaded? and — the question that matters — when did it last write?

`launchctl list` says the job is registered, which is not the same as the job
doing anything. The cache’s modification time is the only evidence that a tick
completed, so it is reported alongside. For the receiver, `last_check` is the
last tick whose check succeeded (a stamp beside *env_file*) and `last_write` the
last tick that had work (its log).

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`object`](https://docs.python.org/3/builtins/functions.html#object)]

### openloops.job.plist_xml(, label, program_args, env, interval, log_path, working_dir=None)

The launchd property list, as text. Pure, so it can be tested on any platform.

```pycon
>>> xml = plist_xml(label='x', program_args=['a'], env={'HOME': '/h'},
...                 interval=60, log_path=Path('/tmp/x.log'))
>>> '<key>StartInterval</key>' in xml and '<integer>60</integer>' in xml
True
```

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### openloops.job.receiver_job_spec(work_dir, , claude=None, model='sonnet', max_budget_usd=1.0, allowed_tools='Bash(gh:\*) Bash(curl:\*) Bash(python3:\*) Bash(crowsnest:\*) Bash(mkdir:\*) Bash(date:\*) Bash(set:\*) Bash(umask:\*) Bash(source:\*) Bash(jq:\*) Bash(cat:\*) Bash(ls:\*) Bash(shasum:\*) Bash(vm_stat:\*) Bash(sysctl:\*) Read Write Edit Glob Grep Skill', env_file=PosixPath('~/.config/openloops/board-receiver.env'), interval=300, label='openloops.board-receiver', require_claude=True)

The receiver job as data: program arguments, environment, plist. Pure but for
looking up where `claude` and `node` are, so it can be tested anywhere.

The job runs `python -m openloops.receiver_tick`, which asks the board store
whether anything is pending and only then replaces itself with `claude -p` and the
packaged receiver prompt. The credentials stay in *env_file*; nothing about them
is in the plist, the arguments or the environment (`PASSED_THROUGH` names none).
With `require_claude=False` (a dry run) a missing `claude` is shown as a bare
name instead of refused.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`object`](https://docs.python.org/3/builtins/functions.html#object)]

### openloops.job.remind_job_spec(, interval=3600, label='openloops.remind-tick')

The reminder tick as data: `python -m openloops remind-tick` every `interval` s.

Pure, so it tests anywhere. The job carries no credential: the ntfy topic is resolved
by correspond (`NTFY_TOPIC`, else the Keychain), and the owner’s zone by
`OPENLOOPS_TZ` when set in the job’s environment.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`object`](https://docs.python.org/3/builtins/functions.html#object)]

### openloops.job.uninstall(, label='openloops.sync')

Unload the job and remove its plist and its whenthen job, whichever exist. Idempotent.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]


# _autosummary/openloops.loops.html.md

# openloops.loops

Loops: the one record of a commitment, and the pure function that says what is due.

A **loop** is an open loop in David Allen’s sense: one of the owner’s commitments, held
somewhere other than their head. It is one record whatever place it sits on, so every
list a method keeps (GTD’s In, Next, Waiting For, Someday, the tickler) is a view over
loops rather than a separate store.

Two vocabularies, kept apart on purpose (ADR-013):

- `state` is the **lifecycle**, in A2A’s seven names, the same ones equerry’s desk
  `Item` uses, so a loop is a desk item without translation. A reminder that is
  scheduled is `submitted` with a `remind_at`; once it fires it is
  `input-required`; done is `completed`; dismissed is `rejected`; withdrawn is
  `canceled`.
- `list` is the **place** the organising method put it in. The record does not know
  the method (ADR-017): the vocabulary and the rules for moving between places belong
  to [`openloops.method`](_autosummary/openloops.method.html.md#module-openloops.method), whose default is Getting Things Done
  ([`openloops.gtd.GTD`](_autosummary/openloops.gtd.html.md#openloops.gtd.GTD): `in`, `next`, `waiting`, `someday`,
  `reference`; “scheduled”, the tickler, is a loop on `next` with a future
  `remind_at`).

Three times, never conflated: `remind_at` (when it comes back to you: the tickler,
GTD’s defer date), `due` (a deadline, a promise to someone) and `created`. All are
stored as UTC ISO strings.

Nothing here reads a clock, a file or the network: [`evaluate()`](_autosummary/openloops.loops.html.md#openloops.loops.evaluate) takes `now` and
returns the actions a runner should take ([`openloops.remind`](_autosummary/openloops.remind.html.md#module-openloops.remind) is that runner).

```pycon
>>> now = datetime(2026, 11, 19, 12, 0, tzinfo=timezone.utc)
>>> loop = new_loop("Send the signed draft", remind_at=now + timedelta(hours=3), now=now, id="loop-a")
>>> loop.state, loop.list
('submitted', 'next')
>>> [a["action"] for a in evaluate([loop], now)]
['arm']
```

### Module Attributes

| [`STATES`](_autosummary/openloops.loops.html.md#openloops.loops.STATES)            | The lifecycle, in A2A's names (the same as equerry's desk Item).                   |
|--------------------------------------------------------------------|------------------------------------------------------------------------------------|
| [`TERMINAL`](_autosummary/openloops.loops.html.md#openloops.loops.TERMINAL)          | Nothing leaves these.                                                              |
| [`MAX_HORIZON`](_autosummary/openloops.loops.html.md#openloops.loops.MAX_HORIZON)       | How far ahead a reminder is handed to the delivery channel's own scheduler.        |
| [`MIN_SCHEDULE_LEAD`](_autosummary/openloops.loops.html.md#openloops.loops.MIN_SCHEDULE_LEAD) | Below this lead a scheduled delivery is refused by ntfy (10 s), so it is sent now. |

### Functions

| [`new_loop`](_autosummary/openloops.loops.html.md#openloops.loops.new_loop)(title, \*[, remind_at, due, reveal, ...])   | A new loop, logged as created.                                                                                                             |
|-------------------------------------------------------------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------|
| [`evaluate`](_autosummary/openloops.loops.html.md#openloops.loops.evaluate)(loops, now, \*[, horizon])                  | What a runner should do now, as data.                                                                                                      |
| [`complete`](_autosummary/openloops.loops.html.md#openloops.loops.complete)(loop, now, \*[, by, note])                  | Done.                                                                                                                                      |
| [`snooze`](_autosummary/openloops.loops.html.md#openloops.loops.snooze)(loop, until, now, \*[, by])                   | Bring it back at `until`: scheduled again, one more snooze counted.                                                                        |
| [`cancel`](_autosummary/openloops.loops.html.md#openloops.loops.cancel)(loop, now, \*[, by, note])                    | Withdrawn: it will not fire.                                                                                                               |
| [`mark`](_autosummary/openloops.loops.html.md#openloops.loops.mark)(loop, now, event, \*[, by])                     | A copy with `changes` applied and one log entry appended.                                                                                  |
| [`to_utc`](_autosummary/openloops.loops.html.md#openloops.loops.to_utc)(when)                                         | A timezone-aware UTC datetime; a naive one is read as the machine's local time.                                                            |
| [`iso`](_autosummary/openloops.loops.html.md#openloops.loops.iso)(when)                                            | UTC ISO with a `Z`, to the second.                                                                                                         |
| [`repeat_gap_days`](_autosummary/openloops.loops.html.md#openloops.loops.repeat_gap_days)(repeat, \*, since_start)             | Days until a repeating reminder comes back: `every_days` for its first `after_days`, then `then_every_days` (it keeps asking, less often). |

### Classes

| [`Loop`](_autosummary/openloops.loops.html.md#openloops.loops.Loop)(id, title, created[, state, list, ...])   | One commitment.   |
|-------------------------------------------------------------------------------------------------|-------------------|

### *class* openloops.loops.Loop(id, title, created, state='submitted', list=<factory>, remind_at=None, due=None, reveal=False, source=None, proposed_by=None, project=None, area=None, contexts=(), energy=None, minutes=None, waiting=None, available_when=None, done_when=None, snoozes=0, carried=0, armed=None, repeat=None, log=tuple(), extra=dict())

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

One commitment. Most fields are optional; GTD-complete, so the default method has
every field it needs, and a method that needs fewer ignores the rest.

`source` is where it came from (`{kind, ref, quote, said_by}`): every loop an
agent makes is traceable. `proposed_by` is set when an agent proposed it and the
person has not accepted it; a proposal never pushes. `reveal` says whether a push
may carry the title (pushes cross a public relay by default). `armed` records the
delivery the channel holds (`{sequence_id, at}`), so it can be replaced or
cancelled. `log` is append-only.

`repeat` makes a reminder come back until it is closed (“remind me until I do it
or say drop”): `{at, every_days, after_days, then_every_days, started, asked}`,
each push counted in `asked` (see [`repeat_gap_days()`](_autosummary/openloops.loops.html.md#openloops.loops.repeat_gap_days)). `done_when` closes it
on a fact: `{issue: "owner/repo#N"}` is done when that issue is closed.

#### extra *: [Mapping](https://docs.python.org/3/library/collections.abc.html#collections.abc.Mapping)[[str](https://docs.python.org/3/builtins/stdtypes.html#str), [Any](https://docs.python.org/3/library/typing.html#typing.Any)]*

kept and written back.

* **Type:**
  Keys a newer writer added that this version does not know

#### *classmethod* from_dict(data)

Read a stored loop; keys this version does not know are kept in `extra`.

* **Return type:**
  [`Loop`](_autosummary/openloops.loops.html.md#openloops.loops.Loop)

### openloops.loops.MAX_HORIZON *= datetime.timedelta(days=2, seconds=82800)*

How far ahead a reminder is handed to the delivery channel’s own scheduler. ntfy
holds a scheduled message for at most three days; an hour’s margin absorbs a clock
that runs ahead of the server’s.

### openloops.loops.MIN_SCHEDULE_LEAD *= datetime.timedelta(seconds=15)*

Below this lead a scheduled delivery is refused by ntfy (10 s), so it is sent now.

### openloops.loops.STATES *= ('submitted', 'working', 'input-required', 'completed', 'failed', 'canceled', 'rejected')*

The lifecycle, in A2A’s names (the same as equerry’s desk Item).

### openloops.loops.TERMINAL *= frozenset({'canceled', 'completed', 'failed', 'rejected'})*

Nothing leaves these.

### openloops.loops.cancel(loop, now, , by='owner', note=None)

Withdrawn: it will not fire. A reason belongs in `note`.

* **Return type:**
  [`Loop`](_autosummary/openloops.loops.html.md#openloops.loops.Loop)

### openloops.loops.complete(loop, now, , by='owner', note=None)

Done. Refused on a loop already closed, so a second `done` is visible, not silent.

* **Return type:**
  [`Loop`](_autosummary/openloops.loops.html.md#openloops.loops.Loop)

### openloops.loops.evaluate(loops, now, , horizon=datetime.timedelta(days=2, seconds=82800))

What a runner should do now, as data. Pure: same loops and `now`, same actions.

For each open, accepted loop with a `remind_at`:

- `arm`: due within `horizon` and not yet handed to the channel at that time.
  The channel delivers it at `remind_at` even if this machine is asleep then.
- `deliver`: due and never armed (created late, or arming failed, or the machine
  slept past the horizon). Sent now, saying how late.
- `woke`: due and armed, so the channel has delivered it; the loop now needs its
  owner (`input-required`).
- `disarm`: closed but still armed, or moved (snoozed) outside the horizon while
  armed at its old time: cancel the channel’s copy.

Proposals (`proposed_by` set) never produce a delivery.

```pycon
>>> now = datetime(2026, 11, 19, 12, 0, tzinfo=timezone.utc)
>>> far = new_loop("x", remind_at=now + timedelta(days=5), now=now, id="far")
>>> late = new_loop("y", remind_at=now - timedelta(minutes=5), now=now, id="late")
>>> [(a["action"], a["id"]) for a in evaluate([far, late], now)]
[('deliver', 'late')]
```

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]]

### openloops.loops.iso(when)

UTC ISO with a `Z`, to the second.

```pycon
>>> iso(datetime(2026, 11, 19, 12, 0, 30, 999, tzinfo=timezone.utc))
'2026-11-19T12:00:30Z'
```

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str) | [`None`](https://docs.python.org/3/builtins/constants.html#None)

### openloops.loops.mark(loop, now, event, , by='tick', \*\*changes)

A copy with `changes` applied and one log entry appended.

* **Return type:**
  [`Loop`](_autosummary/openloops.loops.html.md#openloops.loops.Loop)

### openloops.loops.new_loop(title, , remind_at=None, due=None, reveal=False, source=None, by='owner', now=None, id=None, method=None, \*\*extra)

A new loop, logged as created. `extra` takes any other [`Loop`](_autosummary/openloops.loops.html.md#openloops.loops.Loop) field.

`method` (default [`openloops.method.default_method()`](_autosummary/openloops.method.html.md#openloops.method.default_method), GTD) says where it
goes: by default its `default_place`, where an item the owner asked for directly
lands (GTD: `next`). `list` in `extra` overrides that and must be one of the
method’s places; to move a loop *with* the method’s rules, use
[`openloops.method.organise()`](_autosummary/openloops.method.html.md#openloops.method.organise).

```pycon
>>> new_loop("x", now=datetime(2026, 11, 28, tzinfo=timezone.utc), list="nowhere")
Traceback (most recent call last):
...
ValueError: gtd has no list 'nowhere'; its lists are in, next, waiting, someday, reference
```

* **Return type:**
  [`Loop`](_autosummary/openloops.loops.html.md#openloops.loops.Loop)

### openloops.loops.repeat_gap_days(repeat, , since_start)

Days until a repeating reminder comes back: `every_days` for its first
`after_days`, then `then_every_days` (it keeps asking, less often).

```pycon
>>> r = {"every_days": 1, "after_days": 7, "then_every_days": 3}
>>> repeat_gap_days(r, since_start=timedelta(days=2)), repeat_gap_days(r, since_start=timedelta(days=8))
(1, 3)
```

* **Return type:**
  [`int`](https://docs.python.org/3/builtins/functions.html#int)

### openloops.loops.snooze(loop, until, now, , by='owner')

Bring it back at `until`: scheduled again, one more snooze counted.

* **Return type:**
  [`Loop`](_autosummary/openloops.loops.html.md#openloops.loops.Loop)

### openloops.loops.to_utc(when)

A timezone-aware UTC datetime; a naive one is read as the machine’s local time.

```pycon
>>> to_utc("2026-11-19T12:00:00Z").isoformat()
'2026-11-19T12:00:00+00:00'
```

* **Return type:**
  [`datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime)


# _autosummary/openloops.method.html.md

# openloops.method

The organising method: the seam between the loop record and the system that organises it.

A loop ([`openloops.loops.Loop`](_autosummary/openloops.loops.html.md#openloops.loops.Loop)) records one of the owner’s commitments and stays
neutral about how commitments are organised: its `list` field is a *place* whose
vocabulary belongs to a method. A **method** supplies that vocabulary and the five
operations that personal organising methods share (Getting Things Done, Personal
Kanban, PARA, the Bullet Journal, the Eisenhower matrix and the apps that implement
them; the comparison is in `docs/research/organising-methods-seam.md`):

- **capture**: where an unclarified item lands (`inbox`);
- **clarify**: which questions an item is asked, and where the answers send it
  (`questions`, `clarify`);
- **organise**: the places, and the rules for moving a loop to one (`places`,
  `default_place`, `organise`);
- **review**: what is surfaced for a decision, as exceptions (`review`);
- **engage**: how the next thing to do is chosen (`criteria`, `engage`).

The method only decides. The rules that hold whatever the method, and so live here
rather than in each method, are applied by [`organise()`](_autosummary/openloops.method.html.md#openloops.method.organise): a move is logged; only an
explicit acceptance turns an agent’s proposal into a commitment; a loop the owner has
attended to, or given a new time, is scheduled again rather than left as fired.

Every function in openloops that needs a method takes it as one keyword argument,
`method=`, defaulting to [`default_method()`](_autosummary/openloops.method.html.md#openloops.method.default_method) (Getting Things Done,
[`openloops.gtd.GTD`](_autosummary/openloops.gtd.html.md#openloops.gtd.GTD)), the only method implemented. A second one is a class with
the same attributes, passed in; nothing else changes.

```pycon
>>> m = default_method()
>>> m.name, m.inbox, m.default_place
('gtd', 'in', 'next')
>>> isinstance(m, Method)
True
>>> sorted(describe(m))
['criteria', 'default_place', 'inbox', 'name', 'places', 'questions']
```

### Functions

| [`default_method`](_autosummary/openloops.method.html.md#openloops.method.default_method)()                                  | The method used wherever `method=` is not given: Getting Things Done.             |
|----------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------|
| [`describe`](_autosummary/openloops.method.html.md#openloops.method.describe)([method])                                | A method's vocabulary as flat JSON: what an agent reads before clarifying for it. |
| [`check_place`](_autosummary/openloops.method.html.md#openloops.method.check_place)(method, place)                        | `place` if the method has it, else a `ValueError` naming its places.              |
| [`organise`](_autosummary/openloops.method.html.md#openloops.method.organise)(loop, place, now, \*[, method, by, ...]) | `loop` moved to `place`, with what the method's rules make of `fields`.           |
| [`capture`](_autosummary/openloops.method.html.md#openloops.method.capture)(title, \*, by[, source, method, now, id]) | A capture made by `by`, on the method's inbox; an agent's is a proposal.          |

### Classes

| [`Question`](_autosummary/openloops.method.html.md#openloops.method.Question)(key, ask[, kind, choices, when])   | One question a method's clarify step asks of an item.   |
|----------------------------------------------------------------------------------------------|---------------------------------------------------------|
| [`Method`](_autosummary/openloops.method.html.md#openloops.method.Method)(\*args, \*\*kwargs)                  | What an organising method supplies.                     |

### *class* openloops.method.Method(\*args, \*\*kwargs)

Bases: [`Protocol`](https://docs.python.org/3/library/typing.html#typing.Protocol)

What an organising method supplies. Pure: no clock, file or network.

- `name`: a short id (`gtd`).
- `places`: the values a loop’s `list` may take under this method.
- `inbox`: where an unclarified capture lands; `default_place`: where an
  item the owner asked for directly lands (both among `places`).
- `questions`: what `clarify` asks, in order. `criteria`: the keyword
  filters `engage` understands.
- `clarify(answers)`: where the answers send the item, as data:
  `{place, changes, do_now, close, why}`. `place` is `None` when the item
  leaves the system (`close` then names the lifecycle state, e.g. `canceled`).
- `organise(loop, place, now, *, others, **fields)`: the field changes a move to
  `place` makes, as a dict, after checking them; `ValueError` when the method
  refuses the move. `others` are the other loops, for a rule that counts
  (a work-in-progress limit). The move itself is applied by [`organise()`](_autosummary/openloops.method.html.md#openloops.method.organise).
- `review(loops, now)`: `{method, at, sections: [{name, group, rows}], counts}`;
  only rows that need a decision, each `{id, title, list, why}`.
- `engage(loops, now, *, limit, **criteria)`: the candidates to do now, best
  first, each a row with `why`.

### *class* openloops.method.Question(key, ask, kind='bool', choices=(), when=None)

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

One question a method’s clarify step asks of an item.

`key` is the answer’s name in the mapping given to `clarify`; `kind` is one of
`bool`, `choice` (then `choices` lists them), `text`, `minutes`, `time`,
`words` (a list, or a comma/space separated string). `when` names the answer
this question depends on (`"actionable=false"`), so an agent or a form can skip
what does not apply.

#### read(value)

`value` as this question’s kind, or `ValueError` saying what was expected.

```pycon
>>> Question("a", "?").read("No"), Question("m", "?", kind="minutes").read("15")
(False, 15)
```

* **Return type:**
  [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)

### openloops.method.capture(title, , by, source=None, method=None, now=None, id=None)

A capture made by `by`, on the method’s inbox; an agent’s is a proposal.

It never pushes and never reaches `engage` until the owner accepts it. `source`
(`{kind, ref, quote, said_by}`) is what makes it traceable; keep the owner’s words.

```pycon
>>> loop = capture("Call the notary", by="bosun", source={"kind": "voice", "quote": "call the notary"},
...                now=datetime(2026, 11, 28, tzinfo=timezone.utc), id="loop-c")
>>> loop.list, loop.proposed_by, loop.remind_at
('in', 'bosun', None)
```

* **Return type:**
  [`Loop`](_autosummary/openloops.loops.html.md#openloops.loops.Loop)

### openloops.method.check_place(method, place)

`place` if the method has it, else a `ValueError` naming its places.

```pycon
>>> check_place(default_method(), "later")
Traceback (most recent call last):
...
ValueError: gtd has no list 'later'; its lists are in, next, waiting, someday, reference
```

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### openloops.method.default_method()

The method used wherever `method=` is not given: Getting Things Done.

* **Return type:**
  [`Method`](_autosummary/openloops.method.html.md#openloops.method.Method)

### openloops.method.describe(method=None)

A method’s vocabulary as flat JSON: what an agent reads before clarifying for it.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]

### openloops.method.organise(loop, place, now, , method=None, by='owner', accepted=False, others=(), \*\*fields)

`loop` moved to `place`, with what the method’s rules make of `fields`.

The rules that hold whatever the method:

- the loop must be open, and the place one of the method’s;
- `accepted=True` means the owner said yes to this move, in their own words. It
  turns a proposal into a commitment, and settles a loop that came back
  (`input-required`): it is open again (`submitted`), with no second push for a
  time already past. Anyone’s move otherwise leaves both as they were, so an agent
  never reschedules the owner’s commitments;
- a loop given a new time in the future is scheduled again, whoever moved it;
- one `organised` entry is logged, by `by`.

```pycon
>>> now = datetime(2026, 11, 28, 12, tzinfo=timezone.utc)
>>> from openloops.loops import new_loop
>>> loop = capture("Ask the bank", by="bosun", now=now, id="loop-b")
>>> moved = organise(loop, "waiting", now, by="bosun", waiting={"on": "the bank"})
>>> moved.list, moved.proposed_by, moved.waiting["since"]
('waiting', 'bosun', '2026-11-28T12:00:00Z')
>>> organise(moved, "waiting", now, accepted=True).proposed_by is None
True
```

* **Return type:**
  [`Loop`](_autosummary/openloops.loops.html.md#openloops.loops.Loop)


# _autosummary/openloops.obligations.html.md

# openloops.obligations

What you still owe your agents — re-checked against the world before it is shown.

When an agent gets blocked on something only you can do — a secret it cannot write, a
permission it does not have, a decision that is yours — it files a `manual-task` issue
in the affected repo and says so in its closing message. The closing message dies with
the session. The issue does not, and one query lists every one of them across a fleet.

That query has one failure mode, and it is the one that matters: \*\*obligations get
discharged out of band.\*\* Someone adds a deploy key in a web UI, pays an invoice,
answers in chat. None of that emits an event anyone is listening to, so the issue sits
open for months describing something that was done in five minutes. A stale increment
annoys; a phantom row destroys the count, and the count is the product.

So each obligation carries its own answer, in its body, as a shell command whose \*\*exit
status is the question\*\*:

```default
**Verify:** `gh secret list --repo OWNER/REPO --json name -q '.[].name' | grep -qx NAME`
```

[`owed()`](_autosummary/openloops.obligations.html.md#openloops.obligations.owed) lists the open ones, runs each predicate, and reports **three** states —
never two:

| `open`       | no predicate at all, or the predicate ran and returned non-zero                                   |
|--------------|---------------------------------------------------------------------------------------------------|
| `discharged` | the predicate ran and returned `0`: the ask is done, the issue<br/>is merely still open           |
| `unknown`    | the predicate could *not* be run, or errored in a way that is not<br/>an answer. Displayed as `?` |

`?` is not a rounding error, it is the whole point. A surface that says “nothing
owed” because it failed to check is worse than no surface at all, so nothing here is
ever allowed to collapse `unknown` into `open` or into `discharged`.

**Nothing here mutates anything.** A passing predicate is evidence, not authority: it
never closes, reopens or relabels an issue, and it never will — the standing rule is
that a human obligation is not closed on a model’s judgement. You are shown the
command, its exit status and what it printed, and you decide.

## Trust boundary — stated here because it should be read, not discovered

Evaluating a predicate means **executing text that came from a GitHub issue body**.
That is a real capability and it is bounded here in six ways, each of them visible:

1. **Only owners you named.** A predicate is run only when the issue’s repository owner
   is in `trusted_owners=`, which defaults to the same `owners=` the search was
   scoped to. A row outside that set reads `?` — never `open`, because nothing
   checked it, and never `discharged`, because nothing ran.
2. **The command is always shown next to its verdict.** Every row carries the predicate
   verbatim, so nothing executes invisibly and you can disagree with the answer.
3. **An explicit way not to execute at all.** `owed(verify=False)` (`ol owed
   --no-verify`) lists without running anything; every row that has a predicate then
   reads `?`, because that is the truth about it.
4. **Every evaluation is time-bounded**, by `predicate_timeout=`. A timeout is
   `unknown`, never an answer. On POSIX the predicate runs in its own process group
   and the timeout kills the group, so anything it started dies with it. On Windows only
   the shell itself is killed — a predicate that backgrounds work can outlive its
   timeout there, which is a platform limit worth knowing rather than a promise broken
   quietly.
5. **A predicate that looks like a write is not run.** `gh workflow run`, a `curl`
   with a write method, `git push` and the like read `?` with `unverified: predicate not
   read-only` ([`openloops.predicate_safety`](_autosummary/openloops.predicate_safety.html.md#module-openloops.predicate_safety); `write_guard=` is the seam). Asking
   what is owed must not start a deploy.
6. **The whole thing is one keyword argument away from being someone else’s code.**
   `run_predicate=` replaces the evaluator; `issues_source=` replaces the reader.

One honest limit: predicates are POSIX shell. On a shell that cannot parse one, the
command exits non-zero and the row reads `open`. That is the safe direction to be
wrong in — a stale increment annoys, a wrong decrement destroys the count — and it is
why the exit status and the command text are always on screen.

**Kill criterion** (this module ships on an argument, so it names in advance what would
retire it): if, ninety days after this ships, `counts['with_predicate']` is below half
of `counts['total']` on a normal run, or nobody has run `ol owed` in a fortnight,
delete it. Its entire reason to exist over a one-line `gh search issues` alias is the
predicate; with no predicates to run it is a slower alias that draws a table. Removal is
one command — delete this module and `tests/test_obligations.py`, and drop `owed`
from `openloops.tools._dispatch_funcs` and `openloops.__main__._commands`. Nothing
imports it, nothing persists, and no other module changes.

**What this is not.** It is a *reader*. There is no store, no schema, no history, no
event log, no cross-repo linking, no session model and no local copy of anything: the
`manual-task` label **is** the record, and a second writable home for the same record
type is the drift this deliberately does not build. State lives in first-class GitHub
fields that a plain `gh` command can query, so deleting this module loses no data.

```pycon
>>> from datetime import datetime, timezone
>>> issues = [
...     {'number': 7, 'title': 'Add a deploy key so CI can clone',
...      'url': 'https://github.com/acme/widget/issues/7',
...      'createdAt': '2026-08-01T00:00:00Z',
...      'repository': {'nameWithOwner': 'acme/widget'},
...      'body': '**Verify:** `[ "$(gh api repos/acme/widget/keys --jq length)" -gt 0 ]`'},
...     {'number': 8, 'title': 'Decide whether to publish this at all',
...      'url': 'https://github.com/acme/widget/issues/8',
...      'createdAt': '2026-08-10T00:00:00Z',
...      'repository': {'nameWithOwner': 'acme/widget'},
...      'body': '**Verify:** none possible - a judgement call.'},
... ]
>>> report = owed(
...     issues_source=issues,               # a list of dicts: no gh, no network
...     run_predicate=lambda command: 0,    # canned: the ask turns out to be done
...     trusted_owners=('acme',),
...     now=datetime(2026, 8, 20, tzinfo=timezone.utc),
... )
>>> report['counts']['discharged'], report['counts']['open']
(1, 1)
>>> for row in report['rows']:
...     print(row['state'], row['age_days'], f"{row['repo']}#{row['number']}")
open 10 acme/widget#8
discharged 19 acme/widget#7
```

The discharged row is reported, not closed:

```pycon
>>> report['rows'][1]['predicate']
'[ "$(gh api repos/acme/widget/keys --jq length)" -gt 0 ]'
```

An owner you did not name is never executed, and never silently believed:

```pycon
>>> quiet = owed(issues_source=issues, run_predicate=lambda command: 0,
...              trusted_owners=(), now=datetime(2026, 8, 20, tzinfo=timezone.utc))
>>> [(row['number'], row['state']) for row in quiet['rows']]
[(8, 'open'), (7, 'unknown')]
>>> next(r['evidence'] for r in quiet['rows'] if r['number'] == 7)
"not evaluated: owner 'acme' is not in trusted_owners"
```

### Module Attributes

| [`DISCHARGED`](_autosummary/openloops.obligations.html.md#openloops.obligations.DISCHARGED)        | The predicate ran and returned 0.                           |
|--------------------------------------------------------------------|-------------------------------------------------------------|
| [`UNKNOWN`](_autosummary/openloops.obligations.html.md#openloops.obligations.UNKNOWN)           | Nothing could be checked.                                   |
| [`OBLIGATION_STATES`](_autosummary/openloops.obligations.html.md#openloops.obligations.OBLIGATION_STATES) | The three states, in the order a reader cares about them.   |
| [`OBLIGATION_FIELDS`](_autosummary/openloops.obligations.html.md#openloops.obligations.OBLIGATION_FIELDS) | Every key on every row, whatever the issue happened to say. |

### Functions

| [`configured_owners`](_autosummary/openloops.obligations.html.md#openloops.obligations.configured_owners)(\*[, timeout])                  | Whose repositories to search, resolved once.                                 |
|----------------------------------------------------------------------------------------------------|------------------------------------------------------------------------------|
| [`gh_issues`](_autosummary/openloops.obligations.html.md#openloops.obligations.gh_issues)(\*, owners[, label, state, limit, ...]) | The default `issues_source`: the open `manual-task` issues, from `gh`.       |
| [`owed`](_autosummary/openloops.obligations.html.md#openloops.obligations.owed)(\*[, verify, owners, trusted_owners, ...])   | The open `manual-task` obligations, each re-checked against the world.       |
| [`parse_session`](_autosummary/openloops.obligations.html.md#openloops.obligations.parse_session)(body)                               | The `**Session:**` field of an issue body, `''` when absent.                 |
| [`parse_verify`](_autosummary/openloops.obligations.html.md#openloops.obligations.parse_verify)(body)                                | `(predicate, verify_text)` for an issue body.                                |
| [`shell_predicate`](_autosummary/openloops.obligations.html.md#openloops.obligations.shell_predicate)(command, \*[, timeout])           | The default `run_predicate`: run the command in a subshell, bounded in time. |

### Classes

| [`Obligation`](_autosummary/openloops.obligations.html.md#openloops.obligations.Obligation)(repo, number, title, url, ...[, ...])   | One open `manual-task` issue, with the verdict its own predicate returned.   |
|-----------------------------------------------------------------------------------------------------|------------------------------------------------------------------------------|
| [`PredicateOutcome`](_autosummary/openloops.obligations.html.md#openloops.obligations.PredicateOutcome)(status[, output])                 | What evaluating one predicate produced.                                      |

### Exceptions

| [`GhRateLimited`](_autosummary/openloops.obligations.html.md#openloops.obligations.GhRateLimited)   | `gh` was refused for GitHub's rate limit: an answer to try again later.      |
|------------------------------------------------------------------|------------------------------------------------------------------------------|
| [`GhUnavailable`](_autosummary/openloops.obligations.html.md#openloops.obligations.GhUnavailable)   | The world could not be read: no `gh`, no credentials, no network, a timeout. |

### openloops.obligations.DISCHARGED *= 'discharged'*

The predicate ran and returned 0. The ask is done; the issue is just still open.

### *exception* openloops.obligations.GhRateLimited

Bases: [`GhUnavailable`](_autosummary/openloops.obligations.html.md#openloops.obligations.GhUnavailable)

`gh` was refused for GitHub’s rate limit: an answer to try again later.

A subclass, so every `except GhUnavailable` keeps treating it as `?`; a caller
that can wait ([`openloops.tasks.gather()`](_autosummary/openloops.tasks.html.md#openloops.tasks.gather)) catches it first.

### *exception* openloops.obligations.GhUnavailable

Bases: [`RuntimeError`](https://docs.python.org/3/builtins/exceptions.html#RuntimeError)

The world could not be read: no `gh`, no credentials, no network, a timeout.

Raised only by the listing path, and never propagated to a caller of [`owed()`](_autosummary/openloops.obligations.html.md#openloops.obligations.owed) —
it becomes `listed: False` plus an `error`, which every surface must render as
`?`. Turning it into an empty list would be the one unrecoverable bug here.

### openloops.obligations.OBLIGATION_FIELDS *= ('repo', 'number', 'title', 'url', 'created', 'age_days', 'state', 'verify', 'predicate', 'evidence', 'documents', 'session', 'run')*

Every key on every row, whatever the issue happened to say. A row shape that varies
by issue makes `row["predicate"]` a coin flip and makes a JSON schema a lie.

### openloops.obligations.OBLIGATION_STATES *= ('open', 'discharged', 'unknown')*

The three states, in the order a reader cares about them. `open` is
[`openloops.base.OPEN`](_autosummary/openloops.base.html.md#openloops.base.OPEN): a loop that is still open is the same idea either way.

### *class* openloops.obligations.Obligation(repo, number, title, url, created, age_days, state='open', verify='', predicate='', evidence='', documents=(), session='', run='')

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

One open `manual-task` issue, with the verdict its own predicate returned.

`run` is `runbook_line()` when the body carries a shell block, else `''`.
`session` is the optional `**Session:**` field (the id or link of the session that
opened the issue), `''` when absent. `verify` is the `**Verify:**` field exactly as the issue wrote it and
`predicate` is the runnable command extracted from it — both are carried so a
reader can disagree with `state` rather than absorb it.

```pycon
>>> Obligation('acme/widget', 7, 't', 'u', '2026-01-01T00:00:00Z', 3).state
'open'
```

#### as_dict()

JSON-ready form.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]

### *class* openloops.obligations.PredicateOutcome(status, output='')

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

What evaluating one predicate produced.

`status` is the shell exit status, or `None` for “could not be run” — the
difference between an answer and the absence of one.

```pycon
>>> PredicateOutcome(0).status, PredicateOutcome(None, 'timed out').output
(0, 'timed out')
```

### openloops.obligations.UNKNOWN *= 'unknown'*

Nothing could be checked. Rendered `?`. Never collapsed into either other state.

### openloops.obligations.configured_owners(, timeout=30.0)

Whose repositories to search, resolved once.

Three sources, in order, first one wins: `OPENLOOPS_OWNERS` (comma- or
space-separated); the owners named by the `gh owe` alias if one is installed,
because a fleet is usually already written down there and disagreeing with it is
how a count goes quietly wrong; and failing both, the login `gh` is authenticated
as. The resolved list is reported back on every result, so a partial answer is a
visible one rather than a silent one.

```pycon
>>> import os
>>> os.environ['OPENLOOPS_OWNERS'] = 'acme, widgets co'
>>> configured_owners()
('acme', 'widgets', 'co')
>>> del os.environ['OPENLOOPS_OWNERS']
```

* **Return type:**
  [`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`...`](https://docs.python.org/3/builtins/constants.html#Ellipsis)]

### openloops.obligations.gh_issues(, owners, label='manual-task', state='open', limit=1000, timeout=30.0)

The default `issues_source`: the open `manual-task` issues, from `gh`.

This is a *filtered* search, not an enumeration — the label is applied server-side
and the result is capped — which is the only form of search this package is allowed
to use. Walking a whole fleet’s issues through the search API silently returns wrong
answers past its first thousand results; that job belongs to per-repo listing.

One query per owner, each asking for up to `limit` rows (clamped to GitHub’s
`SEARCH_CEILING`), so the ceiling applies to an owner, not to the whole fleet.
An owner whose query returns as many rows as it asked for is named in the result’s
`saturated` attribute: its count is a floor.

Returns whatever `gh` returned, unparsed and unjudged: a list of dicts with
`createdAt`, `number`, `repository`, `title`, `url` and `body`.

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]]

### openloops.obligations.owed(\*, verify=True, owners=None, trusted_owners=None, label='manual-task', limit=1000, timeout=30.0, predicate_timeout=20.0, now=None, issues_source=None, run_predicate=None, write_guard=<function write_effect>)

The open `manual-task` obligations, each re-checked against the world.

`verify=False` lists without executing anything; every row that carries a
predicate then reads `unknown`, because that is what is true about it.

`owners=` scopes the search (default: [`configured_owners()`](_autosummary/openloops.obligations.html.md#openloops.obligations.configured_owners)).
`trusted_owners=` scopes what may *execute* and defaults to `owners`, so
widening the search never quietly widens what runs — pass it explicitly to search
wider than you trust.

A predicate that *looks like a write* (`gh workflow run`, a `curl` write, `git
push`… see [`openloops.predicate_safety`](_autosummary/openloops.predicate_safety.html.md#module-openloops.predicate_safety)) is not run: the row reads
`unknown` with `unverified: predicate not read-only`, because asking what is owed
must not start a deploy (openloops#43). `write_guard=` is the seam: any callable
from command to a non-empty reason (refuse) or `""` (run); `lambda c: ""`
restores the old behaviour.

Two seams, each one keyword argument, each defaulting to a real implementation:
`issues_source=` (defaults to [`gh_issues()`](_autosummary/openloops.obligations.html.md#openloops.obligations.gh_issues); a list of dicts substitutes) and
`run_predicate=` (defaults to [`shell_predicate()`](_autosummary/openloops.obligations.html.md#openloops.obligations.shell_predicate); any callable from command
to exit status substitutes). With both injected this reaches no network and needs no
`gh`.

Returns one envelope, never a bare list, because a reader has to be able to tell
“nothing is owed” from “I could not find out”:

`listed`
: `False` when the *listing itself* failed. Every surface must render that as
  `?`. The counts are zeros and they mean nothing.

`checked`
: whether predicates were evaluated at all.

`truncated`
: the result set saturated its own cap, so the count is a floor.

`counts`
: `open` / `discharged` / `unknown` / `with_predicate` / `total`.

`rows`
: one dict per obligation, with every key in [`OBLIGATION_FIELDS`](_autosummary/openloops.obligations.html.md#openloops.obligations.OBLIGATION_FIELDS).

```pycon
>>> report = owed(issues_source=[], run_predicate=lambda command: 0)
>>> report['listed'], report['counts']['total'], report['rows']
(True, 0, [])
```

A listing that could not run is not “nothing owed”:

```pycon
>>> def broken(**query):
...     raise GhUnavailable('gh: not logged in')
>>> report = owed(issues_source=broken)
>>> report['listed'], report['error'], report['counts']['total']
(False, 'gh: not logged in', 0)
```

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]

### openloops.obligations.parse_session(body)

The `**Session:**` field of an issue body, `''` when absent.

Quoted code blocks are ignored, as for `Verify:`.

```pycon
>>> parse_session('**Session:** 0a1b2c3d')
'0a1b2c3d'
>>> parse_session('**Verify:** `true`')
''
```

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### openloops.obligations.parse_verify(body)

`(predicate, verify_text)` for an issue body. Both are `''` when absent.

The predicate is the first code span in the field. Prose with no code span – the
documented “no predicate is possible here” answer – yields no command, and the
prose is kept so the row can say *why* rather than merely say nothing.

```pycon
>>> parse_verify('**Verify:** `test -f x`')
('test -f x', '`test -f x`')
>>> parse_verify('no such field here')
('', '')
```

A field that says no predicate is possible yields no command \*\*even when its prose
contains a code span\*\* – the documented wording mentions `gh` and `true` naturally,
and both exit 0, which would report a live obligation as done:

```pycon
>>> parse_verify('**Verify:** none possible - no `gh` query observes a decision.')
('', 'none possible - no `gh` query observes a decision.')
```

A quoted example of the format is not this issue’s own predicate:

```pycon
>>> body = chr(10).join(['```', '**Verify:** `quoted`', '```', '**Verify:** `real`'])
>>> parse_verify(body)[0]
'real'
```

An unterminated code span is not a command – it is a malformed field, and saying so
is the difference between a row that reads `?` and one that silently reads open:

```pycon
>>> parse_verify('**Verify:** `echo one &&' + chr(10) + 'echo two`')
('', '`echo one &&')
```

* **Return type:**
  [`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]

### openloops.obligations.shell_predicate(command, , timeout=20.0)

The default `run_predicate`: run the command in a subshell, bounded in time.

The exit status is the answer and nothing else is interpreted. Anything that is not
an exit status — a timeout, a shell that would not start — comes back as
`status=None`, which is `unknown`, which is `?`.

```pycon
>>> shell_predicate('exit 0').status
0
>>> shell_predicate('exit 3').status
3
>>> shell_predicate('   ').status is None
True
```

* **Return type:**
  [`PredicateOutcome`](_autosummary/openloops.obligations.html.md#openloops.obligations.PredicateOutcome)


# _autosummary/openloops.pile.html.md

# openloops.pile

The pile: GTD’s In list, kept as GitHub issues in a private repo, and its clarify step.

A capture (an Apple Shortcut, the `gh` CLI, anything that can send a request to the issues
API) is one open issue labelled `pile` in the owner’s pile repo. This module is the one
place that reads and changes that pile, so the agent skill (`openloops-pile`), the
`ol pile-*` commands and a voice surface (bosun) all do the same thing:

- [`items()`](_autosummary/openloops.pile.html.md#openloops.pile.items) / [`show()`](_autosummary/openloops.pile.html.md#openloops.pile.show): what is on the pile, read-only;
- [`propose()`](_autosummary/openloops.pile.html.md#openloops.pile.propose): a first proposal per item, from a model-free heuristic by default
  (`proposer=` is the seam an agent’s own reading replaces);
- [`plan()`](_autosummary/openloops.pile.html.md#openloops.pile.plan): the steps that carry out one decision the owner said yes to (a loop, an
  idea, an issue in another repo, work handed to a session, done, dropped), ending with
  a signed comment on the pile item saying where it went. \*\*openloops never writes to
  GitHub\*\* (ADR-008, ADR-014): the caller runs the steps with its own tools;
- [`signed()`](_autosummary/openloops.pile.html.md#openloops.pile.signed): a signed progress note, for a session working on an item;
- [`nudge()`](_autosummary/openloops.pile.html.md#openloops.pile.nudge): keep one reminder loop pending while items wait too long. It never
  acts on an item.

**Every write is signed** ([`signature()`](_autosummary/openloops.pile.html.md#openloops.pile.signature)): the agent’s name and, on private repos, a
link to its session, so an idea’s development can always be traced back to who did it.
**Public destinations get no private content**: an issue filed in a public repo carries
only the text the caller wrote for it, no dictation, no pile link and no session link.

Nothing here runs on capture and nothing acts without being called: no Action, no
webhook (the owner’s rule). GitHub is only read, through `gh` (`run_gh=`); the one
write is [`nudge()`](_autosummary/openloops.pile.html.md#openloops.pile.nudge)’s reminder loop, through openloops’ own reminder runner.

```pycon
>>> parse_item({"number": 7, "title": "call about zodal", "body": "call about zodal\n\n— pile: inbox",
...             "labels": [{"name": "pile"}, {"name": "inbox"}], "createdAt": "2026-11-20T10:00:00Z",
...             "url": "https://github.com/o/_pile/issues/7"}).hint
'inbox'
```

### Module Attributes

| [`PILE_LABEL`](_autosummary/openloops.pile.html.md#openloops.pile.PILE_LABEL)      | The label every untriaged capture carries.                                                                                |
|------------------------------------------------------------------|---------------------------------------------------------------------------------------------------------------------------|
| [`KINDS`](_autosummary/openloops.pile.html.md#openloops.pile.KINDS)           | What `apply()` can do with an item.                                                                                       |
| [`DFLT_STALE_DAYS`](_autosummary/openloops.pile.html.md#openloops.pile.DFLT_STALE_DAYS) | An item older than this many days makes [`nudge()`](_autosummary/openloops.pile.html.md#openloops.pile.nudge) keep a reminder pending. |
| [`NUDGE_SOURCE`](_autosummary/openloops.pile.html.md#openloops.pile.NUDGE_SOURCE)    | one per pile, found again by this.                                                                                        |
| [`RESULT`](_autosummary/openloops.pile.html.md#openloops.pile.RESULT)          | The placeholder a plan's later steps carry for what the first step produced (an issue URL, a loop id, an idea id).        |

### Functions

| [`pile_repo`](_autosummary/openloops.pile.html.md#openloops.pile.pile_repo)([repo, run_gh])                        | The pile repo: `repo`, else `OPENLOOPS_PILE_REPO`, else `<gh login>/_pile`.                                  |
|---------------------------------------------------------------------------------------------------|--------------------------------------------------------------------------------------------------------------|
| [`parse_item`](_autosummary/openloops.pile.html.md#openloops.pile.parse_item)(raw)                                  | A [`PileItem`](_autosummary/openloops.pile.html.md#openloops.pile.PileItem) from `gh`'s JSON for one issue.                  |
| [`items`](_autosummary/openloops.pile.html.md#openloops.pile.items)(\*[, repo, label, run_gh])                 | The open items carrying `label` (default: untriaged), oldest first.                                          |
| [`show`](_autosummary/openloops.pile.html.md#openloops.pile.show)(number, \*[, repo, run_gh])                 | One item with its comments (any state).                                                                      |
| [`heuristic_propose`](_autosummary/openloops.pile.html.md#openloops.pile.heuristic_propose)(item)                          | A first guess from the words alone.                                                                          |
| [`propose`](_autosummary/openloops.pile.html.md#openloops.pile.propose)(found, \*[, proposer])                   | One proposal per item.                                                                                       |
| [`signature`](_autosummary/openloops.pile.html.md#openloops.pile.signature)(by[, session, public])                 | The last lines of every comment an agent writes here.                                                        |
| [`agent_identity`](_autosummary/openloops.pile.html.md#openloops.pile.agent_identity)([by, session, env])               | Who is writing: `by` (an agent or session name) and `session` (a URL or address).                            |
| [`signed`](_autosummary/openloops.pile.html.md#openloops.pile.signed)(text, \*[, by, session, to_repo, run_gh]) | `text` with the writer's signature, for a comment on `to_repo` (default: the pile).                          |
| [`plan`](_autosummary/openloops.pile.html.md#openloops.pile.plan)(number, kind, \*[, reading, by, ...])       | The steps that carry out one decision the owner said yes to, as data.                                        |
| [`is_own_private`](_autosummary/openloops.pile.html.md#openloops.pile.is_own_private)(repo, \*, owner[, run_gh])        | True only for a `PRIVATE` repo of `owner` with no outside collaborators: anything else is treated as public. |
| [`nudge`](_autosummary/openloops.pile.html.md#openloops.pile.nudge)(\*[, stale_days, at, repo, run_gh, ...])   | Keep one reminder coming while any pile item waits longer than `stale_days`.                                 |

### Classes

| [`PileItem`](_autosummary/openloops.pile.html.md#openloops.pile.PileItem)(number, title, said, hint, labels, ...)   | One capture.   |
|-----------------------------------------------------------------------------------------------------|----------------|

### openloops.pile.DFLT_STALE_DAYS *= 3.0*

An item older than this many days makes [`nudge()`](_autosummary/openloops.pile.html.md#openloops.pile.nudge) keep a reminder pending.

### openloops.pile.KINDS *= ('loop', 'idea', 'issue', 'work', 'done', 'drop', 'ask')*

What `apply()` can do with an item.

### openloops.pile.NUDGE_SOURCE *= 'pile-nudge'*

one per pile, found again by this.

* **Type:**
  The `source` of the nudge loop

### openloops.pile.PILE_LABEL *= 'pile'*

The label every untriaged capture carries.

### *class* openloops.pile.PileItem(number, title, said, hint, labels, created, url, state='open', comments=tuple())

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

One capture. `said` is the dictation, with the Shortcut’s hint line removed.

### openloops.pile.RESULT *= '{result}'*

The placeholder a plan’s later steps carry for what the first step produced (an
issue URL, a loop id, an idea id). The caller substitutes it.

### openloops.pile.agent_identity(by=None, session=None, , env=None)

Who is writing: `by` (an agent or session name) and `session` (a URL or address).

Defaults: `OPENLOOPS_AGENT`; then Claude Code’s own variables, the Remote Control
session (`https://claude.ai/code/<CLAUDE_CODE_BRIDGE_SESSION_ID>`) or the local
session id (`claude-code:<CLAUDE_CODE_SESSION_ID>`). `session="none"` signs with
the name alone (a surface that is not this Claude Code session, such as a connector
started from one, passes it rather than borrow the session it inherited).

```pycon
>>> agent_identity(env={"CLAUDE_CODE_BRIDGE_SESSION_ID": "session_01X"})["session"]
'https://claude.ai/code/session_01X'
>>> agent_identity("bosun@tw", "none", env={"CLAUDE_CODE_SESSION_ID": "abc"})
{'by': 'bosun@tw', 'session': None}
```

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`str`](https://docs.python.org/3/builtins/stdtypes.html#str) | [`None`](https://docs.python.org/3/builtins/constants.html#None)]

### openloops.pile.heuristic_propose(item)

A first guess from the words alone. An agent’s reading replaces it (`proposer=`).

```pycon
>>> it = parse_item({"number": 3, "title": "x", "body": "Remind me to call Ana tomorrow",
...                  "labels": [], "createdAt": "2026-11-20T10:00:00Z", "url": "u"})
>>> heuristic_propose(it)["kind"]
'loop'
```

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]

### openloops.pile.is_own_private(repo, , owner, run_gh=None)

True only for a `PRIVATE` repo of `owner` with no outside collaborators:
anything else is treated as public.

Fails closed: an internal repo, another owner’s private repo (a client’s, shared with
other people), a private repo of the owner that has outside collaborators, or a
visibility or collaborator list that cannot be read all get the public treatment.

* **Return type:**
  [`bool`](https://docs.python.org/3/builtins/functions.html#bool)

### openloops.pile.items(, repo=None, label='pile', run_gh=None)

The open items carrying `label` (default: untriaged), oldest first. Read-only.

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`PileItem`](_autosummary/openloops.pile.html.md#openloops.pile.PileItem)]

### openloops.pile.nudge(, stale_days=3.0, at='09:00', repo=None, run_gh=None, loops_api=None, now=None)

Keep one reminder coming while any pile item waits longer than `stale_days`.

Idempotent; run it from a timer. An item counts while it is on the pile (`pile`)
or handed to a session (`working`): a session that died leaves it there. When
something is stale, no nudge is still to come, and none was made in the last
`NUDGE_EVERY_HOURS`, it closes the nudges that already fired and makes one loop
(source `pile-nudge`) for the next `at` in the owner’s zone. The push says only the
count and the oldest age (it crosses a public relay). When nothing is stale, every
open nudge is withdrawn. It never touches a pile item.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]

### openloops.pile.parse_item(raw)

A [`PileItem`](_autosummary/openloops.pile.html.md#openloops.pile.PileItem) from `gh`’s JSON for one issue. Pure.

The hint is the first label that is not a status label, else the body’s
`— pile: <hint>` line (kept by the Shortcut in case a label is dropped).

```pycon
>>> parse_item({"number": 1, "title": "t", "body": "no hint here", "labels": [],
...             "createdAt": "2026-11-20T10:00:00Z", "url": "u"}).hint is None
True
```

* **Return type:**
  [`PileItem`](_autosummary/openloops.pile.html.md#openloops.pile.PileItem)

### openloops.pile.pile_repo(repo=None, , run_gh=None)

The pile repo: `repo`, else `OPENLOOPS_PILE_REPO`, else `<gh login>/_pile`.

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### openloops.pile.plan(number, kind, , reading=None, by=None, session=None, title=None, when=None, reveal=False, place=None, target_repo=None, issue_body=None, tags=None, reason=None, force=False, repo=None, run_gh=None, method=None)

The steps that carry out one decision the owner said yes to, as data. Changes nothing.

openloops never writes to GitHub (ADR-008, ADR-014): the caller runs the steps in
order, with its own tools (`gh` in a Claude Code session, the connector’s comment
and create tools on a voice surface), substituting [`RESULT`](_autosummary/openloops.pile.html.md#openloops.pile.RESULT) in later steps
with what the first step produced. `reading` is the agent’s interpretation, and
opens the signed comment. Per `kind`:

- `loop`: `remind` (`ol remind`; source = the item’s URL), then close as routed;
  `title` is required with `reveal` (the push crosses a public relay);
- `idea`: `idea` (`ideadump add` with the dictation verbatim), then close as routed;
- `issue`: `create_issue` in `target_repo` (`title` + `issue_body`
  required); anything but a private repo of the pile’s owner gets that text only,
  no pile link and no session link;
- `work`: hand-off to a session; labelled `working` and left open; the session
  posts [`signed()`](_autosummary/openloops.pile.html.md#openloops.pile.signed) notes and finishes with `done`;
- `done`: close as routed, `reason` = the evidence;
- `drop`: close as not planned, `reason` required (never silent);
- `ask`: stays on the pile, labelled `needs-owner`, `reason` = the question.

A destination already recorded on the item (a `→ issue/loop/idea` line from an
earlier, half-run plan) refuses a second one unless `force`: finish that plan’s
remaining steps instead. The pile itself must be a private repo of its owner.

Step ops: `remind`, `idea`, `create_issue`, `comment`, `labels`, `close`
(`reason` in `gh`’s spelling, `rest_reason` in the REST API’s).

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]

### openloops.pile.propose(found, \*, proposer=<function heuristic_propose>)

One proposal per item. Proposals change nothing; `apply()` acts on a yes.

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]]

### openloops.pile.show(number, , repo=None, run_gh=None)

One item with its comments (any state).

* **Return type:**
  [`PileItem`](_autosummary/openloops.pile.html.md#openloops.pile.PileItem)

### openloops.pile.signature(by, session=None, , public=False)

The last lines of every comment an agent writes here.

On a public repo only the name: a session link is private context.

```pycon
>>> print(signature("gtd-capture@mac", "https://claude.ai/code/session_01X"))

—
Agent: gtd-capture@mac
Claude-Session: https://claude.ai/code/session_01X
>>> signature("gtd-capture@mac", "https://claude.ai/code/session_01X", public=True).splitlines()[-1]
'Agent: gtd-capture@mac'
```

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### openloops.pile.signed(text, , by=None, session=None, to_repo=None, run_gh=None)

`text` with the writer’s signature, for a comment on `to_repo` (default: the pile).

The session link is kept only when `to_repo` is a private repo of the pile’s owner;
anywhere else (public, internal, a client’s, unreadable) the name alone.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]


# _autosummary/openloops.predicate_safety.html.md

# openloops.predicate_safety

Is a `manual-task` verify predicate a pure read?

`ol owed` *executes* the shell command an issue carries, to see whether the ask has
been done since. A question (“what do I owe?”) must not have a write effect, but a
predicate is free text from an issue body: one ran `gh workflow run` and every
`ol owed` started a deploy (openloops#43).

[`write_effect()`](_autosummary/openloops.predicate_safety.html.md#openloops.predicate_safety.write_effect) is the guard. It returns the reason a command is refused, or
`""` for one that reads. It is a **guard against honest mistakes, not a sandbox**: a
predicate that hides a write behind a script it calls still runs. What it does see, it
sees as the shell would: the command is split into shell words ([`shlex`](https://docs.python.org/3/library/shlex.html#module-shlex)), then
into simple commands at unquoted `|`, `;`, `&&`, `||`, `&` and newlines, and
`bash -c`, `ssh host '...'`, `eval` and `$(...)` are read by recursing into the
command they carry. So `--jq 'length > 0'` is an argument, not a redirect, and
`ssh tw 'rm -rf x'` is an `rm`.

`gh` and `git` are **allowlisted** (`GH_READS`, `GIT_READS`): a verb
not known to read is refused. Everything else is denylisted by name
(`MUTATORS`, `SUBCOMMAND_WRITES`, `DEPLOY_MARKERS`). Ambiguity is
refused, never run: the cost of a wrong refusal is one `?` row in `ol owed`; the
cost of a wrong run is a write nobody asked for.

```pycon
>>> write_effect('gh workflow run deploy.yml --repo o/r')
'gh workflow run'
>>> write_effect('gh pr view 3 --json state -q .state | grep -q MERGED')
''
>>> write_effect('curl -s -d a=b https://example.com/x')
'curl with a request body (-d)'
>>> write_effect('test -f ~/.config/x && echo ok > /dev/null')
''
>>> write_effect("gh run list --created '>2026-09-10' -q length")
''
>>> write_effect("ssh tw 'rm -rf /srv/x'")
'rm'
```

### Functions

| [`write_effect`](_autosummary/openloops.predicate_safety.html.md#openloops.predicate_safety.write_effect)(command)    | Why *command* is refused as a predicate, or `""` if it only reads.                                                              |
|---------------------------------------------------------------------------|---------------------------------------------------------------------------------------------------------------------------------|
| [`command_names`](_autosummary/openloops.predicate_safety.html.md#openloops.predicate_safety.command_names)(command)   | The program name of every simple command in *command*, `$(...)` included.                                                       |
| [`simple_commands`](_autosummary/openloops.predicate_safety.html.md#openloops.predicate_safety.simple_commands)(command) | The words of every simple command in *command*, `$(...)` bodies included, with shell keywords and `VAR=value` prefixes dropped. |

### openloops.predicate_safety.command_names(command)

The program name of every simple command in *command*, `$(...)` included.

Shell keywords and `VAR=value` prefixes are skipped. Text that does not parse
gives `[]`: a caller that needs certainty treats that as unknown.

```pycon
>>> command_names('cd ~/x && FOO=1 git pull -q | tee log; echo "$(date)"')
['date', 'cd', 'git', 'tee', 'echo']
>>> command_names("echo 'unbalanced")
[]
```

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]

### openloops.predicate_safety.simple_commands(command)

The words of every simple command in *command*, `$(...)` bodies included, with
shell keywords and `VAR=value` prefixes dropped. Text that does not parse gives `[]`.

```pycon
>>> simple_commands('cd ~/x && FOO=1 git pull -q; echo "$(date -u)"')
[['date', '-u'], ['cd', '~/x'], ['git', 'pull', '-q'], ['echo', '$(date -u)']]
```

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]]

### openloops.predicate_safety.write_effect(command)

Why *command* is refused as a predicate, or `""` if it only reads.

```pycon
>>> write_effect('gh pr -R o/r merge 3')
'gh pr merge'
>>> write_effect('gh api repos/o/r/pulls/3 --jq "length > 0"')
''
>>> write_effect('echo x 2>err.log')
'redirect into err.log'
>>> write_effect('git -C ~/x log -1')
''
>>> write_effect("echo 'unbalanced")
'unparseable'
```

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)


# _autosummary/openloops.provenance.html.md

# openloops.provenance

Which session made this pull request or branch? A reverse index, kept by `ol sync`.

A digest keeps a dozen pull-request links per session, because a digest is meant to be
read. Tracing a pull request back to the session that opened it needs the opposite: every
link and every pushed branch, none dropped, and a lookup that reads no transcript. This
module is that index.

Three facts about real transcripts shape it.

- \*\*Claude Code’s own `pr-link` record is not written for every pull request.\*\* A PR
  opened by `gh pr create` inside a script, a loop or a background shell reaches the
  transcript only as text in a tool result, sometimes minutes later, when the session
  reads the script’s log. So every GitHub pull-request URL in a tool result or in the
  assistant’s text is collected, not only the `pr-link` records.
- **Many sessions mention a PR; one made it.** Each reference carries a `role`:
  `created` (the URL printed by the very command that ran `gh pr create`, quoted text
  and heredocs ignored), `linked` (Claude Code’s `pr-link` record, which it writes for
  any session that works on a PR, a merge included, so it is not evidence of making it),
  `pushed` / `branched` for branches, and `seen` for anything else.
  [`who_made()`](_autosummary/openloops.provenance.html.md#openloops.provenance.who_made) ranks `created` first and then the earliest sighting, whatever its
  > role, which for a PR opened by a script is the session that ran the script.
- **The public-repo trailer is stripped.** `Claude-Session:` is removed from commits
  and PR bodies on public repositories, so the transcript is the only link left.

The store is a `MutableMapping[str, str]` of JSON documents keyed
`{source}/{session}.json` (one per session, derived and rebuildable, like a digest), so
several machines write into one place without colliding and a lookup is a scan of small
files.

```pycon
>>> recs = [
...     {"type": "assistant", "timestamp": "T1", "cwd": "/w/r", "message": {"content": [
...         {"type": "tool_use", "id": "u1", "name": "Bash", "input": {"command":
...          "git push -u origin fix-x && gh pr create --head fix-x --title t"}}]}},
...     {"type": "user", "timestamp": "T2", "message": {"content": [
...         {"type": "tool_result", "tool_use_id": "u1",
...          "content": "https://github.com/o/r/pull/7"}]}},
... ]
>>> [(r.kind, r.ref, r.role) for r in extract_refs(recs)]
[('branch', 'fix-x', 'pushed'), ('pr', 'o/r#7', 'created')]
>>> store = {}
>>> record_refs(store, 'mac', 's1', extract_refs(recs))
True
>>> [(h['session'], h['role']) for h in who_made('https://github.com/o/r/pull/7', store=store)]
[('s1', 'created')]
>>> [(h['session'], h['role']) for h in who_made('fix-x', store=store)]
[('s1', 'pushed')]
```

A command that only searches for the words does not make a PR:

```pycon
>>> recs[0]["message"]["content"][0]["input"]["command"] = 'rg -l "gh pr create" .'
>>> [(r.kind, r.ref, r.role) for r in extract_refs(recs)]
[('pr', 'o/r#7', 'seen')]
```

### Module Attributes

| [`ROLE_RANK`](_autosummary/openloops.provenance.html.md#openloops.provenance.ROLE_RANK)   | Lower ranks first.   |
|--------------------------------------------------------------|----------------------|

### Functions

| [`extract_refs`](_autosummary/openloops.provenance.html.md#openloops.provenance.extract_refs)(records)                        | Every PR and branch the transcript refers to, first sighting each, by strongest role.   |
|-----------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------|
| [`normalize_pr`](_autosummary/openloops.provenance.html.md#openloops.provenance.normalize_pr)(text)                           | `owner/repo#N` from a PR URL or a short reference, lower-cased; else `""`.              |
| [`provenance_key`](_autosummary/openloops.provenance.html.md#openloops.provenance.provenance_key)(source, session)              | The store key for one session's refs.                                                   |
| [`provenance_store`](_autosummary/openloops.provenance.html.md#openloops.provenance.provenance_store)([rootdir])                  | The default store: `{source}/{session}.json` files under the data root.                 |
| [`record_refs`](_autosummary/openloops.provenance.html.md#openloops.provenance.record_refs)(store, source, session, refs)    | Add one session's refs to the index; returns whether the stored document changed.       |
| [`who_made`](_autosummary/openloops.provenance.html.md#openloops.provenance.who_made)(target, \*[, store, source, limit]) | The sessions that referred to a PR (URL or `owner/repo#N`) or a branch name.            |

### Classes

| [`Ref`](_autosummary/openloops.provenance.html.md#openloops.provenance.Ref)(kind, ref, role[, at, cwd, origin])   | One thing a session referred to: a pull request or a branch, and how.   |
|--------------------------------------------------------------------------------------------|-------------------------------------------------------------------------|

### openloops.provenance.ROLE_RANK *= {'branched': 2, 'created': 0, 'linked': 3, 'on': 5, 'pushed': 1, 'seen': 4}*

Lower ranks first. `created` is the strongest evidence a session made the thing.

### *class* openloops.provenance.Ref(kind, ref, role, at='', cwd='', origin='')

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

One thing a session referred to: a pull request or a branch, and how.

`ref` is normalized: `owner/repo#N` (lower-cased) for a PR, the bare name for a
branch. `at` is the first time the session referred to it, `cwd` where it was.

#### as_dict()

JSON-ready form.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]

#### origin *: [str](https://docs.python.org/3/builtins/stdtypes.html#str)* *= ''*

a live hook writes
e.g. `hook:<account>@<host>` here. Passed through by [`who_made()`](_autosummary/openloops.provenance.html.md#openloops.provenance.who_made).

* **Type:**
  Who recorded it, when not `ol sync` reading a transcript

### openloops.provenance.extract_refs(records)

Every PR and branch the transcript refers to, first sighting each, by strongest role.

Pure: the same records give the same refs. Order is by first sighting.

* **Return type:**
  [`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[`Ref`](_autosummary/openloops.provenance.html.md#openloops.provenance.Ref), [`...`](https://docs.python.org/3/builtins/constants.html#Ellipsis)]

### openloops.provenance.normalize_pr(text)

`owner/repo#N` from a PR URL or a short reference, lower-cased; else `""`.

```pycon
>>> normalize_pr('https://github.com/Addaix/aix/pull/70/files')
'addaix/aix#70'
>>> normalize_pr('addaix/aix#70'), normalize_pr('fix-x')
('addaix/aix#70', '')
```

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### openloops.provenance.provenance_key(source, session)

The store key for one session’s refs.

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### openloops.provenance.provenance_store(rootdir=None)

The default store: `{source}/{session}.json` files under the data root.

Any `MutableMapping[str, str]` works in its place (a `dict` in tests).

* **Return type:**
  [`MutableMapping`](https://docs.python.org/3/library/collections.abc.html#collections.abc.MutableMapping)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]

### openloops.provenance.record_refs(store, source, session, refs)

Add one session’s refs to the index; returns whether the stored document changed.

Merges with what is stored rather than replacing it, so a ref recorded by another
writer (a live hook) or read from an earlier, longer copy of the transcript is never
lost, and an empty read never erases a good one.

```pycon
>>> store = {}
>>> record_refs(store, 'm', 's', [Ref('pr', 'o/r#1', 'created', 'T2', origin='hook')])
True
>>> record_refs(store, 'm', 's', [Ref('pr', 'o/r#1', 'seen', 'T1')])
True
>>> record_refs(store, 'm', 's', [])
False
>>> json.loads(store['m/s.json'])['refs'][0]['role'], json.loads(store['m/s.json'])['refs'][0]['at']
('created', 'T1')
```

* **Return type:**
  [`bool`](https://docs.python.org/3/builtins/functions.html#bool)

### openloops.provenance.who_made(target, , store=None, source=None, limit=10)

The sessions that referred to a PR (URL or `owner/repo#N`) or a branch name.

Ranked: `created` rows first, then every other row by its first sighting, earliest
first. The first row is the likeliest maker; a row other than `created` at the top
means no session recorded making it, and the earliest sighting is the best guess (a
PR opened by a script is first seen when its log is read; later sessions that merge
or fix it come after).

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]]


# _autosummary/openloops.publications.html.md

# openloops.publications

What your agents handed you lately: recently published annals documents, per session.

openloops answers “what do I owe?”; this answers its sibling, “what did my agents hand
me?”, from the documents sessions published with `annals publish --session <name>`.
It is read-only and does not depend on annals being installed: the list of documents
comes through one seam, `source=`, which is either the documents themselves (the
`docs` of `annals ls`) or a zero-argument callable returning them. The default seam
runs `annals ls` and says so, as an unlisted report, when annals is absent – an
empty list would read as “nothing was published”.

```pycon
>>> docs = [{'id': 'a1', 'title': 'Report', 'created': '2026-01-02T00:00:00Z',
...          'source': {'session': 'sweep'}}]
>>> report = published(source=docs)
>>> report['listed'], report['rows'][0]['session'], report['rows'][0]['url']
(True, 'sweep', 'https://apps.thorwhalen.com/annals/d/a1')
```

### Module Attributes

| [`DFLT_DOCUMENT_BASE`](_autosummary/openloops.publications.html.md#openloops.publications.DFLT_DOCUMENT_BASE)   | Where a published document's page lives (the prefix of `DFLT_DOCUMENT_URL` in [`openloops.obligations`](_autosummary/openloops.obligations.html.md#module-openloops.obligations)).   |
|-----------------------------------------------------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| [`DFLT_LIMIT`](_autosummary/openloops.publications.html.md#openloops.publications.DFLT_LIMIT)           | How many recent documents to read.                                                                                                                                                    |
| [`DFLT_TIMEOUT`](_autosummary/openloops.publications.html.md#openloops.publications.DFLT_TIMEOUT)         | Seconds to wait for `annals ls`.                                                                                                                                                      |

### Functions

| [`published`](_autosummary/openloops.publications.html.md#openloops.publications.published)(\*[, limit, session, source, ...])   | Recently published documents, newest first, each with its session and link.   |
|-------------------------------------------------------------------------------------------------|-------------------------------------------------------------------------------|

### openloops.publications.DFLT_DOCUMENT_BASE *= 'https://apps.thorwhalen.com/annals/d/'*

Where a published document’s page lives (the prefix of `DFLT_DOCUMENT_URL` in
[`openloops.obligations`](_autosummary/openloops.obligations.html.md#module-openloops.obligations)).

### openloops.publications.DFLT_LIMIT *= 50*

How many recent documents to read.

### openloops.publications.DFLT_TIMEOUT *= 20.0*

Seconds to wait for `annals ls`.

### openloops.publications.published(, limit=50, session=None, source=None, base_url='https://apps.thorwhalen.com/annals/d/', timeout=20.0)

Recently published documents, newest first, each with its session and link.

`session` keeps one session’s documents. The result is an envelope:
`listed=False` with an `error` means the documents could not be read, which
must not be mistaken for “none were published”.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]


# _autosummary/openloops.receiver_tick.html.md

# openloops.receiver_tick

One tick of the board-receiver job: check for work without a model, then hand over.

ADR-011. A launchd `StartInterval` job runs this every few minutes. Starting a Claude
session on every tick would cost money while nothing is pending, so the tick first asks
the board store, with plain HTTP and no model, whether anything needs the receiver.
Only if something does (or the question cannot be answered) does it replace itself with
the real command, `claude -p <the receiver prompt>`.

**Liveness.** Every successful check writes the board’s `meta/receiver` heartbeat
(the receiver’s own document, under the session name from `board/board.json`), so an
idle board stays green and a dead job turns it amber after 20 minutes. It also touches a
local `board-receiver.lastcheck` stamp, which `ol receiver-job-status` reports as
“last check”, separately from “last work” (the log, written only by ticks with work).

**Fail closed on configuration, open on anything else.** A configuration error (no
credentials file, a missing key, a cleartext origin, a refused sign-in, a 403 from the
store) cannot be fixed by a session, so the tick starts none and says so in the log on
every tick; the stale heartbeat turns the board amber. Any other failure (the store
down, a malformed answer, a bug here) starts the session anyway, because a check that
silently suppressed the receiver would be the failure this package exists to prevent.
Repeated failures back off exponentially: one hour, then two, four, capped at six.

This is the one module that talks to the network, to the owner’s own board store (the
HTTP API of ADR-009). Nothing imports it; `import openloops` never loads it.

The work set is the one `references/receiver.md` defines: events with no receipt,
`processing` receipts older than 15 minutes, and `queued` receipts and `failed`
receipts marked transient. Those last two are retried only once they are an hour old
([`RETRY_AFTER`](_autosummary/openloops.receiver_tick.html.md#openloops.receiver_tick.RETRY_AFTER)): a receipt that waits on another machine, a busy worker or a
lasting GitHub error would otherwise start a paid session every tick, all day, to change
nothing. The sign-in is the one in `references/receiver-http.md`.

### Module Attributes

| [`STALE_CLAIM`](_autosummary/openloops.receiver_tick.html.md#openloops.receiver_tick.STALE_CLAIM)       | A `processing` receipt older than this is a sweep that died (receiver.md, section 0).                                                                                                             |
|--------------------------------------------------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| [`RETRY_AFTER`](_autosummary/openloops.receiver_tick.html.md#openloops.receiver_tick.RETRY_AFTER)       | A `queued` or transiently `failed` receipt is retried only once it is this old.                                                                                                                   |
| [`FAIL_OPEN_BACKOFF`](_autosummary/openloops.receiver_tick.html.md#openloops.receiver_tick.FAIL_OPEN_BACKOFF) | After a failed check starts a session, the next one waits this long, doubling with each further failure up to `FAIL_OPEN_CAP`: a lasting fault must not start a paid session every tick, all day. |

### Functions

| [`check`](_autosummary/openloops.receiver_tick.html.md#openloops.receiver_tick.check)([env_file, heartbeat_by, now, plans])    | Ask the store whether anything needs the receiver.                              |
|-------------------------------------------------------------------------------------------------|---------------------------------------------------------------------------------|
| [`pending_work`](_autosummary/openloops.receiver_tick.html.md#openloops.receiver_tick.pending_work)(outbox, receipts, \*[, now, ...]) | What needs the receiver, from the store's two collections (`id -> data`).       |
| [`read_env_file`](_autosummary/openloops.receiver_tick.html.md#openloops.receiver_tick.read_env_file)(path)                            | `KEY=VALUE` / `export KEY=VALUE` lines of an env file, parsed, never executed.  |
| [`plan_receipts`](_autosummary/openloops.receiver_tick.html.md#openloops.receiver_tick.plan_receipts)(outbox, receipts, plans)         | The receipts of run-plan requests that a saved plan now answers, as new values. |
| [`main`](_autosummary/openloops.receiver_tick.html.md#openloops.receiver_tick.main)([argv])                                   | `python -m openloops.receiver_tick [--check-only] [--env-file F] [-- CMD ...]`. |

### Classes

| [`Pending`](_autosummary/openloops.receiver_tick.html.md#openloops.receiver_tick.Pending)([iterable])   | The reasons the receiver is needed; empty means nothing to do.   |
|------------------------------------------------------------------------|------------------------------------------------------------------|

### Exceptions

| [`ConfigError`](_autosummary/openloops.receiver_tick.html.md#openloops.receiver_tick.ConfigError)   | The check cannot run as configured, and a session could not fix that either.   |
|----------------------------------------------------------------|--------------------------------------------------------------------------------|

### *exception* openloops.receiver_tick.ConfigError

Bases: [`RuntimeError`](https://docs.python.org/3/builtins/exceptions.html#RuntimeError)

The check cannot run as configured, and a session could not fix that either.

### openloops.receiver_tick.FAIL_OPEN_BACKOFF *= datetime.timedelta(seconds=3600)*

After a failed check starts a session, the next one waits this long, doubling with
each further failure up to `FAIL_OPEN_CAP`: a lasting fault must not start a
paid session every tick, all day.

### *class* openloops.receiver_tick.Pending(iterable=(),)

Bases: [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)

The reasons the receiver is needed; empty means nothing to do.

`total` counts the items behind those reasons (the heartbeat’s `pending`);
`heartbeat` says what [`check()`](_autosummary/openloops.receiver_tick.html.md#openloops.receiver_tick.check) did with the heartbeat.

#### keys *: [frozenset](https://docs.python.org/3/builtins/stdtypes.html#frozenset)* *= frozenset({})*

The ids behind the reasons, so a start that would see the same set again backs off.

#### other_live *: [str](https://docs.python.org/3/builtins/stdtypes.html#str) | [None](https://docs.python.org/3/builtins/constants.html#None)* *= None*

a session started now would stop at once.

* **Type:**
  Another receiver whose heartbeat is live

#### plans *: [str](https://docs.python.org/3/builtins/stdtypes.html#str)* *= ''*

What [`check()`](_autosummary/openloops.receiver_tick.html.md#openloops.receiver_tick.check) did with the run-plan requests’ receipts (`plan_receipts`).

### openloops.receiver_tick.RETRY_AFTER *= datetime.timedelta(seconds=3600)*

A `queued` or transiently `failed` receipt is retried only once it is this old.

### openloops.receiver_tick.STALE_CLAIM *= datetime.timedelta(seconds=900)*

A `processing` receipt older than this is a sweep that died (receiver.md, section 0).

### openloops.receiver_tick.check(env_file=PosixPath('~/.config/openloops/board-receiver.env'), , heartbeat_by=None, now=None, plans=None)

Ask the store whether anything needs the receiver. Raises if it cannot ask:
[`ConfigError`](_autosummary/openloops.receiver_tick.html.md#openloops.receiver_tick.ConfigError) when no session could fix it, anything else otherwise.

With *heartbeat_by* (the board’s session name) it also writes the `meta/receiver`
heartbeat, and says what happened in the result’s `heartbeat`. A failed heartbeat
never fails the check: the board turning amber is how that shows.

* **Return type:**
  [`Pending`](_autosummary/openloops.receiver_tick.html.md#openloops.receiver_tick.Pending)

### openloops.receiver_tick.main(argv=None)

`python -m openloops.receiver_tick [--check-only] [--env-file F] [-- CMD ...]`.

* **Return type:**
  [`int`](https://docs.python.org/3/builtins/functions.html#int)

### openloops.receiver_tick.pending_work(outbox, receipts, , now=None, retry_after=datetime.timedelta(seconds=3600))

What needs the receiver, from the store’s two collections (`id -> data`).

`queued` and transiently `failed` receipts count only once their `at` (or,
lacking one, `claimedAt`) is older than *retry_after*; one with neither counts.

```pycon
>>> pending_work({'e1': {}}, {})
['1 event(s) without a receipt']
>>> pending_work({'e1': {}}, {'e1': {'status': 'posted'}})
[]
```

* **Return type:**
  [`Pending`](_autosummary/openloops.receiver_tick.html.md#openloops.receiver_tick.Pending)

### openloops.receiver_tick.plan_receipts(outbox, receipts, plans)

The receipts of run-plan requests that a saved plan now answers, as new values.

A plan answers the board’s `runbook` event it shares an issue with and was made
after, the latest such event (the receiver dispatched a planner for it). The receipt
becomes `ready` while a plan waits for the owner, `approved` once approved and
`ran` once run, and carries each plan’s id, page, state and approve line in
`result.plans`. Only receipts already `dispatched` (or later) move; an unchanged
one is left out. Pure: the caller reads and writes the store.

```pycon
>>> ev = {"e1": {"action": "runbook", "task_ids": ["o/r#1", "o/r#2"], "createdAt": "2026-12-05T16:00:00Z"}}
>>> rc = {"e1": {"status": "dispatched", "result": {"worker": "runbook-1"}}}
>>> pl = [{"plan": "p", "state": "waiting", "issues": ["o/r#2"], "created": "2026-12-05T16:30:00Z",
...        "page": "https://x/p", "approve": "cd ~ && ol runbook-run p --tty --approve h", "counts": {}}]
>>> new = plan_receipts(ev, rc, pl)["e1"]
>>> new["status"], new["result"]["worker"], new["result"]["plans"][0]["page"]
('ready', 'runbook-1', 'https://x/p')
>>> plan_receipts(ev, {"e1": new}, pl)
{}
```

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]]

### openloops.receiver_tick.read_env_file(path)

`KEY=VALUE` / `export KEY=VALUE` lines of an env file, parsed, never executed.

```pycon
>>> import tempfile, pathlib
>>> f = pathlib.Path(tempfile.mkdtemp()) / 'e'
>>> _ = f.write_text("# c\nexport A='x y'\nB=2\n\nbad line\n")
>>> read_env_file(f)
{'A': 'x y', 'B': '2'}
```

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]


# _autosummary/openloops.remind.html.md

# openloops.remind

Reminders: loops kept in a store and delivered through a channel that holds the time.

The runner over [`openloops.loops`](_autosummary/openloops.loops.html.md#module-openloops.loops) (ADR-013). The core modules never import this
one: it is where a store, a clock and a delivery channel are composed, and it is the
only openloops code that sends anything for a reminder.

How a reminder survives a sleeping machine: when a loop comes within the horizon (three
days, ntfy’s limit), it is **armed**, handed to ntfy as a scheduled message whose
sequence id is the loop’s id. ntfy delivers it at `remind_at` whether or not this
machine is awake. Done or snoozed first, the scheduled copy is cancelled or replaced
by the same id, but ntfy.sh does not honour that today ([`UNCANCELLABLE_NOTE`](_autosummary/openloops.remind.html.md#openloops.remind.UNCANCELLABLE_NOTE)), so
the result carries a `warning` that the original push may still arrive. A tick (`ol remind-tick`, hourly from a launchd job) arms loops that
came within the horizon, records the ones that fired, and delivers late, saying so,
anything that was never armed.

Three seams, each one keyword argument with a default that works:

- `store`: a `MutableMapping[str, Loop]`; default JSON files under
  `~/.local/share/openloops/loops/` ([`loops_store()`](_autosummary/openloops.remind.html.md#openloops.remind.loops_store)).
- `deliver`: an object with `schedule`, `now` and `cancel`; default
  [`NtfyDelivery`](_autosummary/openloops.remind.html.md#openloops.remind.NtfyDelivery), through correspond’s ntfy channel (

  ```
  ``
  ```

  pip install
  > openloops[remind]\`\`). Another one is named without code: `module:factory` in
  > `OPENLOOPS_REMIND_DELIVER` or in the `remind.deliver` key of the openloops settings
  > file ([`load_deliver()`](_autosummary/openloops.remind.html.md#openloops.remind.load_deliver)). Two optional parts of that protocol: `redacts = True`
  > (it decides per channel what a push may show, so it is handed the real title and
  > `loop.reveal`), and `replies()` / `ack(keys)` (what the person tapped on a push:

  Done, Snooze, Drop), which [`tick()`](_autosummary/openloops.remind.html.md#openloops.remind.tick) applies to the loops ([`apply_replies()`](_autosummary/openloops.remind.html.md#openloops.remind.apply_replies)).
- `settings`: [`RemindSettings`](_autosummary/openloops.remind.html.md#openloops.remind.RemindSettings); default from the environment.

**Privacy.** ntfy.sh is a public relay: anyone holding the topic reads the push. A
push says only that a reminder is due unless the loop was made with `reveal=True`;
the title then travels too. Reveal short labels only, never names, clients or secrets.

### Module Attributes

| [`DFLT_REPEAT`](_autosummary/openloops.remind.html.md#openloops.remind.DFLT_REPEAT)        | daily for a week, then every 3 days.                                                                                                                                            |
|---------------------------------------------------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| [`UNCANCELLABLE_NOTE`](_autosummary/openloops.remind.html.md#openloops.remind.UNCANCELLABLE_NOTE) | a DELETE (or a replacement under the same sequence id) of a *scheduled* message is acknowledged with a `message_delete` event, yet the original is still delivered at its time. |
| [`REPLY_TYPES`](_autosummary/openloops.remind.html.md#openloops.remind.REPLY_TYPES)        | What a reply may ask, and the loop operation that carries it out.                                                                                                               |

### Functions

| [`loops_store`](_autosummary/openloops.remind.html.md#openloops.remind.loops_store)([rootdir])                             | The default store: `~/.local/share/openloops/loops/<id>.json`.                                                                                |
|-----------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------|
| [`parse_in`](_autosummary/openloops.remind.html.md#openloops.remind.parse_in)(text)                                     | A duration such as `20m`, `3h`, `2d` or `1h30m`.                                                                                              |
| [`parse_at`](_autosummary/openloops.remind.html.md#openloops.remind.parse_at)(text, \*, now, zone)                      | An ISO date-time (naive means `zone`), an ISO date (09:00 that day) or `HH:MM` (the next one).                                                |
| [`parse_when`](_autosummary/openloops.remind.html.md#openloops.remind.parse_when)(text, \*, now, zone)                    | A duration from `now` (`3h`, `1h30m`) or a time ([`parse_at()`](_autosummary/openloops.remind.html.md#openloops.remind.parse_at)): the one form a CLI flag takes. |
| [`attach`](_autosummary/openloops.remind.html.md#openloops.remind.attach)(naive, zone)                                | `naive` read in `zone`; `None` means this machine's zone, DST rules included.                                                                 |
| [`local`](_autosummary/openloops.remind.html.md#openloops.remind.local)(when, zone)                                  | `when` shown in `zone`, or in this machine's zone (DST-aware) when `None`.                                                                    |
| [`remind`](_autosummary/openloops.remind.html.md#openloops.remind.remind)(title, \*[, at, in_, due, reveal, ...])     | Make a loop that comes back at `at` (or after `in_`), arm it, and say when.                                                                   |
| [`list_loops`](_autosummary/openloops.remind.html.md#openloops.remind.list_loops)(\*[, state, store])                     | Loops as summaries, soonest first.                                                                                                            |
| [`done`](_autosummary/openloops.remind.html.md#openloops.remind.done)(ref, \*[, note, by, only_source, store, ...]) | Close a loop as done and cancel its scheduled push, if any.                                                                                   |
| [`snooze`](_autosummary/openloops.remind.html.md#openloops.remind.snooze)(ref, \*[, until, for_, by, ...])            | Bring a loop back later (`until` a time, or `for_` a duration); re-arms its push.                                                             |
| [`until_done`](_autosummary/openloops.remind.html.md#openloops.remind.until_done)(ref, \*[, issue, by, only_source, ...]) | Make an open loop come back until it is done (or `issue` closes), keeping its time.                                                           |
| [`issue_closed`](_autosummary/openloops.remind.html.md#openloops.remind.issue_closed)(ref)                                  | Whether a GitHub issue is closed (`gh`); `None` when that cannot be told.                                                                     |
| [`tick`](_autosummary/openloops.remind.html.md#openloops.remind.tick)(\*[, is_closed, store, deliver, ...])         | Apply replies, arm what came within the horizon, record what fired, deliver late what was missed.                                             |
| [`find`](_autosummary/openloops.remind.html.md#openloops.remind.find)(store, ref, \*[, only_source])                | A loop by id, by a unique prefix (with or without `loop-`), or by its hex suffix.                                                             |
| [`organise`](_autosummary/openloops.remind.html.md#openloops.remind.organise)(ref, place, \*[, by, accepted, ...])      | Move loop `ref` to `place` under `method` (default GTD), setting `fields`.                                                                    |
| [`review`](_autosummary/openloops.remind.html.md#openloops.remind.review)(\*[, method, store, now])                   | The method's review packet over every stored loop: the exceptions to decide on.                                                               |
| [`engage`](_autosummary/openloops.remind.html.md#openloops.remind.engage)(\*[, limit, method, store, now])            | What to do now, best first, under `method`; `criteria` are the method's filters.                                                              |
| [`load_deliver`](_autosummary/openloops.remind.html.md#openloops.remind.load_deliver)(ref)                                  | The `deliver` a `module:factory` reference names: the factory, called with no arguments.                                                      |
| [`configured_deliver`](_autosummary/openloops.remind.html.md#openloops.remind.configured_deliver)(\*[, path])                     | The `remind.deliver` reference in the openloops settings file, if any.                                                                        |
| [`apply_replies`](_autosummary/openloops.remind.html.md#openloops.remind.apply_replies)(deliver, \*, store, settings, now)   | Apply what the person tapped on a push (`deliver.replies()`), then `ack` it.                                                                  |

### Classes

| [`RemindSettings`](_autosummary/openloops.remind.html.md#openloops.remind.RemindSettings)([channel, horizon_hours, ...])   | What the owner sets once.                                                   |
|--------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------|
| [`NtfyDelivery`](_autosummary/openloops.remind.html.md#openloops.remind.NtfyDelivery)([ref, send, get_channel])          | The default `deliver`: correspond's ntfy channel, one sequence id per loop. |
| [`LoopsStore`](_autosummary/openloops.remind.html.md#openloops.remind.LoopsStore)(files)                               | `Loop` records as `<id>.json` files, each write atomic.                     |

### Exceptions

| [`DeliveryError`](_autosummary/openloops.remind.html.md#openloops.remind.DeliveryError)   | The channel refused or could not be reached; the loop is left to the next tick.   |
|------------------------------------------------------------------|-----------------------------------------------------------------------------------|

### openloops.remind.DFLT_REPEAT *= {'after_days': 7, 'every_days': 1, 'then_every_days': 3}*

daily for a week, then every 3 days.

* **Type:**
  How a reminder that repeats until done comes back

### *exception* openloops.remind.DeliveryError

Bases: [`RuntimeError`](https://docs.python.org/3/builtins/exceptions.html#RuntimeError)

The channel refused or could not be reached; the loop is left to the next tick.

### *class* openloops.remind.LoopsStore(files)

Bases: [`MutableMapping`](https://docs.python.org/3/library/collections.abc.html#collections.abc.MutableMapping)

`Loop` records as `<id>.json` files, each write atomic.

### *class* openloops.remind.NtfyDelivery(ref='ntfy:', , send=None, get_channel=None)

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

The default `deliver`: correspond’s ntfy channel, one sequence id per loop.

`send` and `get_channel` default to correspond’s, imported when first used, so
`import openloops.remind` costs nothing and tests inject fakes.

### openloops.remind.REPLY_TYPES *= ('done', 'snooze', 'cancel', 'dismissed')*

What a reply may ask, and the loop operation that carries it out.

### *class* openloops.remind.RemindSettings(channel='ntfy:', horizon_hours=71.0, generic_title='Reminder', generic_text='A reminder you set is due.', tz=None, morning='09:00', deliver=None)

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

What the owner sets once. `from_env` reads `OPENLOOPS_REMIND_*` and `OPENLOOPS_TZ`.

`channel` is a correspond reference (`ntfy:` is the default topic). `tz` is an
IANA zone for reading and echoing times; `None` uses the machine’s own, with its
daylight-saving rules applied per instant. `horizon_hours` is capped at 71 (ntfy
schedules three days ahead at most).

#### *property* channel_label *: [str](https://docs.python.org/3/builtins/stdtypes.html#str)*

a topic in the reference is a bearer secret.

* **Type:**
  The channel’s name only

#### deliver *: [str](https://docs.python.org/3/builtins/stdtypes.html#str) | [None](https://docs.python.org/3/builtins/constants.html#None)* *= None*

Another `deliver`, as `module:factory` (`OPENLOOPS_REMIND_DELIVER`; see [`load_deliver()`](_autosummary/openloops.remind.html.md#openloops.remind.load_deliver)).

#### morning *: [str](https://docs.python.org/3/builtins/stdtypes.html#str)* *= '09:00'*

When a reminder that repeats until done comes back, local time (`OPENLOOPS_REMIND_MORNING`).

#### *property* zone

A `ZoneInfo`, or `None` for the machine’s own zone (see [`attach()`](_autosummary/openloops.remind.html.md#openloops.remind.attach)).

### openloops.remind.UNCANCELLABLE_NOTE *= 'ntfy.sh still delivers a scheduled push that was cancelled or replaced, so the original push may arrive at {at} anyway'*

a DELETE (or a replacement under the same sequence
id) of a *scheduled* message is acknowledged with a `message_delete` event, yet the
original is still delivered at its time. ntfy’s documentation says otherwise; until
the server honours it, an early `done` or `snooze` is said, not hidden.

* **Type:**
  Measured on ntfy.sh, 2026-11-19

### openloops.remind.apply_replies(deliver, , store, settings, now)

Apply what the person tapped on a push (`deliver.replies()`), then `ack` it.

Each reply is a mapping `{key, type, loop, value}`: `type` one of
[`REPLY_TYPES`](_autosummary/openloops.remind.html.md#openloops.remind.REPLY_TYPES), `loop` the loop id, `value` a snooze length (`1h`,
`tomorrow`). A reply whose key a loop’s log already holds is acknowledged without
acting again, so a crash between applying and acknowledging repeats nothing. A reply
that cannot be applied is not acknowledged and comes back next time; one for a loop
that is gone, already closed or of an unknown type is acknowledged and counted.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]

### openloops.remind.attach(naive, zone)

`naive` read in `zone`; `None` means this machine’s zone, DST rules included.

```pycon
>>> attach(datetime(2026, 7, 1, 9, 0), timezone.utc).isoformat()
'2026-07-01T09:00:00+00:00'
```

* **Return type:**
  [`datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime)

### openloops.remind.configured_deliver(, path=None)

The `remind.deliver` reference in the openloops settings file, if any.

A missing file or key means none; an unreadable file is an error, never a silent
default (a reminder sent the wrong way is worse than one refused).

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str) | [`None`](https://docs.python.org/3/builtins/constants.html#None)

### openloops.remind.done(ref, , note=None, by='owner', only_source=None, store=None, deliver=None, settings=None, now=None)

Close a loop as done and cancel its scheduled push, if any.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]

### openloops.remind.engage(, limit=None, method=None, store=None, now=None, \*\*criteria)

What to do now, best first, under `method`; `criteria` are the method’s filters.

A criterion the method does not list (GTD: context, minutes, energy) is refused, and
an empty one ignored.

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]]

### openloops.remind.find(store, ref, , only_source=None)

A loop by id, by a unique prefix (with or without `loop-`), or by its hex suffix.

`only_source` narrows the search to loops whose `source.ref` is exactly that: a
surface that may only touch what it set itself (a voice connector) passes its own
name, and every other loop is, for it, not there.

* **Return type:**
  [`Loop`](_autosummary/openloops.loops.html.md#openloops.loops.Loop)

### openloops.remind.issue_closed(ref)

Whether a GitHub issue is closed (`gh`); `None` when that cannot be told.

* **Return type:**
  [`bool`](https://docs.python.org/3/builtins/functions.html#bool) | [`None`](https://docs.python.org/3/builtins/constants.html#None)

### openloops.remind.list_loops(, state='open', store=None)

Loops as summaries, soonest first. `state`: `open`, `closed`, `all` or one A2A state.

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]]

### openloops.remind.load_deliver(ref)

The `deliver` a `module:factory` reference names: the factory, called with no
arguments. The module is imported only here, so openloops depends on none of them.

```pycon
>>> load_deliver("collections:OrderedDict")
OrderedDict()
>>> load_deliver("no-colon")
Traceback (most recent call last):
  ...
ValueError: a deliver reference is module:factory, not 'no-colon'
```

* **Return type:**
  [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)

### openloops.remind.local(when, zone)

`when` shown in `zone`, or in this machine’s zone (DST-aware) when `None`.

* **Return type:**
  [`datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime)

### openloops.remind.loops_store(rootdir=None)

The default store: `~/.local/share/openloops/loops/<id>.json`.

* **Return type:**
  [`LoopsStore`](_autosummary/openloops.remind.html.md#openloops.remind.LoopsStore)

### openloops.remind.organise(ref, place, , by='owner', accepted=False, only_source=None, method=None, store=None, deliver=None, settings=None, now=None, \*\*fields)

Move loop `ref` to `place` under `method` (default GTD), setting `fields`.

`fields` are the method’s (GTD: project, area, contexts, energy, minutes,
waiting, remind_at, due); a `remind_at` or `due` may be a duration or a time, as
for [`remind()`](_autosummary/openloops.remind.html.md#openloops.remind.remind). `accepted=True` (only on the owner’s own yes) turns an agent’s
proposal into a commitment. The loop is then settled: a new time is armed, a cleared
one disarmed.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]

### openloops.remind.parse_at(text, , now, zone)

An ISO date-time (naive means `zone`), an ISO date (09:00 that day) or `HH:MM`
(the next one). Natural language is the calling agent’s job, not this function’s.

```pycon
>>> z = timezone.utc
>>> now = datetime(2026, 11, 19, 12, 0, tzinfo=z)
>>> parse_at("09:30", now=now, zone=z).isoformat()
'2026-11-20T09:30:00+00:00'
>>> parse_at("2026-11-21", now=now, zone=z).isoformat()
'2026-11-21T09:00:00+00:00'
```

* **Return type:**
  [`datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime)

### openloops.remind.parse_in(text)

A duration such as `20m`, `3h`, `2d` or `1h30m`.

```pycon
>>> parse_in("1h30m")
datetime.timedelta(seconds=5400)
```

* **Return type:**
  [`timedelta`](https://docs.python.org/3/library/datetime.html#datetime.timedelta)

### openloops.remind.parse_when(text, , now, zone)

A duration from `now` (`3h`, `1h30m`) or a time ([`parse_at()`](_autosummary/openloops.remind.html.md#openloops.remind.parse_at)): the one form a CLI flag takes.

```pycon
>>> now = datetime(2026, 11, 19, 12, 0, tzinfo=timezone.utc)
>>> parse_when("3h", now=now, zone=timezone.utc).isoformat()
'2026-11-19T15:00:00+00:00'
```

* **Return type:**
  [`datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime)

### openloops.remind.remind(title, , at=None, in_=None, due=None, reveal=False, source=None, by='owner', daily_cap=None, place=None, waiting=None, method=None, until_done=False, issue=None, is_closed=None, store=None, deliver=None, settings=None, now=None)

Make a loop that comes back at `at` (or after `in_`), arm it, and say when.

`until_done` makes it come back after each push ([`DFLT_REPEAT`](_autosummary/openloops.remind.html.md#openloops.remind.DFLT_REPEAT): daily at the
first push’s time of day, every 3 days after a week) until it is closed: `ol done`,
a cancel, or, with `issue` (`owner/repo#N`), that issue closing. With neither
`at` nor `in_` it first comes back at the next `settings.morning`.

`place` is where the organising `method` (default GTD) files it; by default,
where it sends an actionable item (GTD: `next`). A loop on `someday` with a time
is an incubated item that comes back on that date; one on `waiting` needs
`waiting={"on": <whom>}`.

Give at most one of `at` and `in_`; with neither, the loop is listed but never
pushed. Returns the loop’s summary and `echo`, the one line to repeat to the owner.

`daily_cap` refuses a new loop once that many loops from the same `source.ref`
were created in the last 24 hours: a surface driven by a model that reads other
people’s text pins it, so a steered loop cannot flood the phone or the push quota.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]

### openloops.remind.review(, method=None, store=None, now=None)

The method’s review packet over every stored loop: the exceptions to decide on.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]

### openloops.remind.snooze(ref, , until=None, for_=None, by='owner', only_source=None, max_ahead=None, store=None, deliver=None, settings=None, now=None)

Bring a loop back later (`until` a time, or `for_` a duration); re-arms its push.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]

### openloops.remind.tick(, is_closed=None, store=None, deliver=None, settings=None, now=None)

Apply replies, arm what came within the horizon, record what fired, deliver late
what was missed.

Replies first ([`apply_replies()`](_autosummary/openloops.remind.html.md#openloops.remind.apply_replies), when `deliver` has `replies`), so a loop
marked Done on the phone is not pushed again this tick. Model-free and idempotent: run it as often as you like (the launchd job runs it
hourly). Returns counts per action and the loops whose channel call failed.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]

### openloops.remind.until_done(ref, , issue=None, by='owner', only_source=None, is_closed=None, store=None, deliver=None, settings=None, now=None)

Make an open loop come back until it is done (or `issue` closes), keeping its time.

Its next push stays where it is; each push re-arms it on [`DFLT_REPEAT`](_autosummary/openloops.remind.html.md#openloops.remind.DFLT_REPEAT) at the
same time of day. `ol done` (or a cancel) drops it.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]


# _autosummary/openloops.runbook.html.md

# openloops.runbook

Run plans: the owner’s command-line manual tasks, planned by an agent, run without one.

A `manual-task` issue often ends in a shell command the owner is asked to paste. With
dozens of them, pasting becomes mindless, and the safety of running a command yourself
is lost. A **run plan** puts the judgement back (ADR-018):

- an agent (the `openloops-runbook` skill) re-checks each issue, orders the commands,
  has an independent reviewer rate each one, rewrites them to lower the risk, and
  writes a [`Plan`](_autosummary/openloops.runbook.html.md#openloops.runbook.Plan);
- the owner approves the plan **once**, by its [`plan_hash()`](_autosummary/openloops.runbook.html.md#openloops.runbook.plan_hash);
- [`openloops.runbook_run`](_autosummary/openloops.runbook_run.html.md#module-openloops.runbook_run) runs exactly the approved commands, with no model in the
  loop, and closes each issue only on its passing check (ADR-015).

This module is the pure part: the plan record, its hash, the one grammar of an issue
reference ([`parse_ref()`](_autosummary/openloops.runbook.html.md#openloops.runbook.parse_ref)), and the checks a plan must pass before it can be approved
([`validate()`](_autosummary/openloops.runbook.html.md#openloops.runbook.validate)). The risk reading of a command is [`openloops.command_risk`](_autosummary/openloops.command_risk.html.md#module-openloops.command_risk). No I/O,
no network, no model.

```pycon
>>> p = Plan('p', '2026-11-30', steps=[Step('s1', 'o/r/1', 'gh issue view 1 -R o/r')])
>>> validate(p), p.steps[0].issue
([], 'o/r#1')
```

### Functions

| [`parse_ref`](_autosummary/openloops.runbook.html.md#openloops.runbook.parse_ref)(ref)                         | `(owner, repo, number)` from `o/r#3`, `o/r/3` or an issue URL.                           |
|-----------------------------------------------------------------------------------------|------------------------------------------------------------------------------------------|
| [`plan_hash`](_autosummary/openloops.runbook.html.md#openloops.runbook.plan_hash)(plan)                        | sha256 over what runs: each step's `HASHED_FIELDS`, in order.                            |
| [`validate`](_autosummary/openloops.runbook.html.md#openloops.runbook.validate)(plan, \*[, discussed, check]) | What is wrong with *plan*, as messages; `[]` when it may be approved and run.            |
| [`placeholders`](_autosummary/openloops.runbook.html.md#openloops.runbook.placeholders)(plan)                     | Each step whose note or command still holds a value to fill in (`<public-url>`).         |
| [`counts`](_autosummary/openloops.runbook.html.md#openloops.runbook.counts)(plan)                           | The one-line summary: steps that run unattended, need hands, wait for a yes; held items. |
| [`split`](_autosummary/openloops.runbook.html.md#openloops.runbook.split)(plan)                            | The plan as two: what runs without the owner, then what needs him at the terminal.       |

### Classes

| [`Step`](_autosummary/openloops.runbook.html.md#openloops.runbook.Step)(id, issue, command[, cwd, check, ...])       | One command of a plan, for one issue.                                 |
|----------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------|
| [`Plan`](_autosummary/openloops.runbook.html.md#openloops.runbook.Plan)(id, created[, steps, discuss, skipped, ...]) | A run plan: the steps that will run, and everything kept out of them. |

### *class* openloops.runbook.Plan(id, created, steps=list(), discuss=list(), skipped=list(), made_by='', title='', page='', schema=1)

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

A run plan: the steps that will run, and everything kept out of them.

`discuss` holds what is not in `steps` because it needs the owner’s word
(`{issue, why, recommendation, command}`); `skipped` holds what needs nothing
(`{issue, why}`: already done, closed, no command). `page` is where the owner reads
it (a link). Only `steps` is hashed: the approval binds to what runs.

### *class* openloops.runbook.Step(id, issue, command, cwd=None, check=None, expect=None, after=list(), close=True, timeout=900, interactive=False, level='show', reasons=list(), review=None, rewrites=list(), note='')

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

One command of a plan, for one issue.

`command` runs as written, in `cwd` (`~` expanded), with `bash`. `check` is
the read-only command whose exit 0 means the issue’s ask is done (the issue’s
`**Verify:**` field, or one the planner wrote, which the owner approves with the
plan); it is run before the command (already done: skip it) and after. `expect` is
a regular expression the command’s output must contain. `after` names the steps
that must have succeeded first. `close` says this is the issue’s last step, so a
passing check closes the issue. `rewrites` records each risk-lowering change as
`{before, after, why}`. `review` is the independent reviewer’s
`{level, reasons}`; `level` and `reasons` are the combined verdict.

### openloops.runbook.counts(plan)

The one-line summary: steps that run unattended, need hands, wait for a yes; held items.

```pycon
>>> counts(Plan('p', 'd', steps=[Step('s1', 'o/r#1', 'npm login', interactive=True)], skipped=[{}]))
{'runs': 0, 'hands': 1, 'decide': 0, 'skipped': 1}
```

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`int`](https://docs.python.org/3/builtins/functions.html#int)]

### openloops.runbook.parse_ref(ref)

`(owner, repo, number)` from `o/r#3`, `o/r/3` or an issue URL. One grammar.

```pycon
>>> parse_ref('acme/widget#12'), parse_ref('acme/widget/12')
(('acme', 'widget', 12), ('acme', 'widget', 12))
>>> parse_ref('https://github.com/acme/widget/issues/12')
('acme', 'widget', 12)
```

* **Return type:**
  [`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`int`](https://docs.python.org/3/builtins/functions.html#int)]

### openloops.runbook.placeholders(plan)

Each step whose note or command still holds a value to fill in (`<public-url>`).

A placeholder in what the owner reads before a step means its prerequisite may not
exist yet (a URL nobody has made): the planner gives the real value, or holds the
step as blocked on that prerequisite. In a command, single-quoted text is literal
and not searched.

```pycon
>>> p = Plan('p', 'd', steps=[Step('t1', 'o/r#1', 'true',
...     note='Callback <public-url>/auth/callback.')])
>>> placeholders(p)
['t1: the note has <public-url>: give the real value, or hold the step until it exists']
>>> p.steps[0].note = ''; p.steps[0].command = "cat <<EOF > f; echo '<b>'"
>>> placeholders(p)
[]
```

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]

### openloops.runbook.plan_hash(plan)

sha256 over what runs: each step’s `HASHED_FIELDS`, in order.

```pycon
>>> p = Plan('p', '2026-11-30', steps=[Step('s1', 'o/r#1', 'true')])
>>> h = plan_hash(p); len(h)
64
>>> p.steps[0].note = 'reworded'; plan_hash(p) == h
True
>>> p.steps[0].command = 'true && false'; plan_hash(p) == h
False
```

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### openloops.runbook.split(plan)

The plan as two: what runs without the owner, then what needs him at the terminal.

A step goes to the terminal plan when it is `interactive` or waits (`after`,
transitively) on a step that is, so nothing unattended ever waits on a 2FA prompt.
The unattended plan runs first: a terminal step’s `after` on an unattended step is
satisfied by that order and is dropped from the terminal plan, and its `note` says
so. `discuss` and `skipped` stay with the unattended plan. Ids are the plan’s
with `-auto` and `-terminal`; each half is hashed and approved on its own.

```pycon
>>> p = Plan('p', '2026-12-03', steps=[
...     Step('a', 'o/r#1', 'true'), Step('b', 'o/r#2', 'npm login', interactive=True),
...     Step('c', 'o/r#3', 'true', after=['b']), Step('d', 'o/r#4', 'true', after=['a'])])
>>> auto, term = split(p)
>>> [s.id for s in auto.steps], [s.id for s in term.steps]
(['a', 'd'], ['b', 'c'])
>>> auto.id, term.id
('p-auto', 'p-terminal')
```

* **Return type:**
  [`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[`Plan`](_autosummary/openloops.runbook.html.md#openloops.runbook.Plan), [`Plan`](_autosummary/openloops.runbook.html.md#openloops.runbook.Plan)]

### openloops.runbook.validate(plan, \*, discussed=(), check=<function risk_floor>)

What is wrong with *plan*, as messages; `[]` when it may be approved and run.

The floor is recomputed here, from the text, by `check` (ADR-015 §3’s seam; the
default reads the text, [`openloops.command_risk.risk_floor()`](_autosummary/openloops.command_risk.html.md#openloops.command_risk.risk_floor)), so a plan that
claims `run` for a deploy is caught. A `discuss` step is allowed only if its id is in *discussed*
(the owner said yes to that step by name); `refuse` never is.

```pycon
>>> ok = Plan('p', 'd', steps=[Step('s1', 'o/r#1', 'gh issue view 1 -R o/r', check='true')])
>>> validate(ok)
[]
>>> bad = Plan('p', 'd', steps=[Step('s1', 'o/r#1', 'rm -rf ~/x', after=['s9'])])
>>> for m in validate(bad): print(m)
s1: needs the owner's yes by name (irreversible: deletes files)
s1: runs after s9, which is not an earlier step
```

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]


# _autosummary/openloops.runbook_issue.html.md

# openloops.runbook_issue

One manual-task issue, from its number to a reviewed run plan, with no agent in between.

ADR-018 amendment (2026-12-04). The `openloops-runbook` skill plans many issues at once
and rewrites their commands; for **one** issue whose body already carries the command, an
agent in between costs the owner more attention than it saves. `ol runbook-issue REF`
does the planner’s mechanical part in code and keeps the parts that matter:

- **still needed?** the issue must be open, a `manual-task`, filed by the owner’s own
  login, and waiting on no open issue; and every step’s check is the issue’s own
  `**Verify:**` line, so a task that is already done runs nothing;
- **safe?** the deterministic floor ([`openloops.command_risk.risk_floor()`](_autosummary/openloops.command_risk.html.md#openloops.command_risk.risk_floor)), then the
  independent reviewer (the shipped `openloops-risk-reviewer` agent, run as
  `claude -p`), which can only raise a level; a weak check means the issue is not closed;
- **run, watched**: the plan is shown, the owner’s one yes approves it at its hash, and
  [`openloops.runbook_run`](_autosummary/openloops.runbook_run.html.md#module-openloops.runbook_run) runs it at his terminal;
- **done?** the Verify line is run again, and [`openloops.closer`](_autosummary/openloops.closer.html.md#module-openloops.closer) closes the issue only
  when it passes.

Pure: [`plan_from_issue()`](_autosummary/openloops.runbook_issue.html.md#openloops.runbook_issue.plan_from_issue), [`apply_review()`](_autosummary/openloops.runbook_issue.html.md#openloops.runbook_issue.apply_review), [`review_prompt()`](_autosummary/openloops.runbook_issue.html.md#openloops.runbook_issue.review_prompt),
[`parse_review()`](_autosummary/openloops.runbook_issue.html.md#openloops.runbook_issue.parse_review). I/O: [`gather_facts()`](_autosummary/openloops.runbook_issue.html.md#openloops.runbook_issue.gather_facts), [`claude_reviewer()`](_autosummary/openloops.runbook_issue.html.md#openloops.runbook_issue.claude_reviewer). Imported by
nothing in the core; `tools.runbook_issue` loads it lazily. [`claude_reviewer()`](_autosummary/openloops.runbook_issue.html.md#openloops.runbook_issue.claude_reviewer) is
the one place openloops asks a model, and only when the owner runs this command.

### Module Attributes

| [`DFLT_REVIEW_MODEL`](_autosummary/openloops.runbook_issue.html.md#openloops.runbook_issue.DFLT_REVIEW_MODEL)   | The reviewer runs on the strongest tier (the agent definition says `model: opus`).   |
|----------------------------------------------------------------------|--------------------------------------------------------------------------------------|
| [`DFLT_REVIEW_TIMEOUT`](_autosummary/openloops.runbook_issue.html.md#openloops.runbook_issue.DFLT_REVIEW_TIMEOUT) | Seconds the reviewer may take before the plan is refused for want of a review.       |

### Functions

| [`plan_id`](_autosummary/openloops.runbook_issue.html.md#openloops.runbook_issue.plan_id)(ref)                                  | The plan id for an issue: one plan per issue, replaced when planned again.                                                                                           |
|------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| [`plan_from_issue`](_autosummary/openloops.runbook_issue.html.md#openloops.runbook_issue.plan_from_issue)(issue, \*[, keep_open, ...])  | A plan of one step per shell block of *issue*'s body, in order, each checked first by the issue's own `**Verify:**` line.                                            |
| [`gather_facts`](_autosummary/openloops.runbook_issue.html.md#openloops.runbook_issue.gather_facts)(plan, \*[, run])                 | Facts a tool gathered for each step, for the reviewer: the hosts it reaches by `ssh` and, for each folder it works in that is a git checkout, its status and remote. |
| [`review_prompt`](_autosummary/openloops.runbook_issue.html.md#openloops.runbook_issue.review_prompt)(plan, facts)                    | What the reviewer is given: each step's command, folder and check, and the facts.                                                                                    |
| [`parse_review`](_autosummary/openloops.runbook_issue.html.md#openloops.runbook_issue.parse_review)(text, \*, ids)                   | The reviewer's JSON list, one object per step id in *ids*; an error otherwise.                                                                                       |
| [`apply_review`](_autosummary/openloops.runbook_issue.html.md#openloops.runbook_issue.apply_review)(plan, reviews)                   | *plan* with each step's `review` stored and its level raised to the reviewer's.                                                                                      |
| [`claude_reviewer`](_autosummary/openloops.runbook_issue.html.md#openloops.runbook_issue.claude_reviewer)(\*[, claude, model, timeout]) | The default reviewer: the shipped `openloops-risk-reviewer` instructions, run as `claude -p` with no tools and no saved session.                                     |
| [`newer_commands`](_autosummary/openloops.runbook_issue.html.md#openloops.runbook_issue.newer_commands)(body, comments)                | Each shell block a comment gives that the body does not, oldest first.                                                                                               |
| [`comment_bodies`](_autosummary/openloops.runbook_issue.html.md#openloops.runbook_issue.comment_bodies)(ref, \*[, gh])                 | The comments of issue *ref* posted after its body was last edited, oldest first.                                                                                     |

### openloops.runbook_issue.DFLT_REVIEW_MODEL *= 'opus'*

The reviewer runs on the strongest tier (the agent definition says `model: opus`).

### openloops.runbook_issue.DFLT_REVIEW_TIMEOUT *= 300*

Seconds the reviewer may take before the plan is refused for want of a review.

### openloops.runbook_issue.apply_review(plan, reviews)

*plan* with each step’s `review` stored and its level raised to the reviewer’s.

A review can only raise a level. No undo named means `discuss`. A weak check on the
issue’s last step means the issue is not closed by this run (`close: false`).

```pycon
>>> p = Plan('p', 'now', steps=[Step('s1', 'o/r#1', 'echo hi', level='run')])
>>> q = apply_review(p, [{'id': 's1', 'level': 'show', 'undo': 'none',
...                       'weak_check': True}])
>>> q.steps[0].level, q.steps[0].close
('discuss', False)
```

* **Return type:**
  [`Plan`](_autosummary/openloops.runbook.html.md#openloops.runbook.Plan)

### openloops.runbook_issue.claude_reviewer(, claude='claude', model='opus', timeout=300)

The default reviewer: the shipped `openloops-risk-reviewer` instructions, run as
`claude -p` with no tools and no saved session. Raises when it cannot run or its
answer cannot be read: a plan without its review is refused, never run on the floor
alone unless the owner says so (`--no-review`).

* **Return type:**
  [`Callable`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable)[[[`Plan`](_autosummary/openloops.runbook.html.md#openloops.runbook.Plan), [`Mapping`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Mapping)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]]], [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]]]

### openloops.runbook_issue.comment_bodies(ref, , gh=None)

The comments of issue *ref* posted after its body was last edited, oldest first.

Read only to find shell blocks in them ([`newer_commands()`](_autosummary/openloops.runbook_issue.html.md#openloops.runbook_issue.newer_commands)). A comment older than
the body’s last edit was already folded into it, or superseded by it.

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]

### openloops.runbook_issue.gather_facts(plan, , run=None)

Facts a tool gathered for each step, for the reviewer: the hosts it reaches by
`ssh` and, for each folder it works in that is a git checkout, its status and remote.
Reads only.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]]

### openloops.runbook_issue.newer_commands(body, comments)

Each shell block a comment gives that the body does not, oldest first.

A plan runs the body’s blocks only. An agent that refreshed the ask in a comment (a
corrected command, a new Verify) left the body stale: running it would run the old
command. Whitespace is ignored when comparing.

```pycon
>>> body = "```bash\nnpm trust github x\n```"
>>> newer_commands(body, ["Fixed:\n```bash\nnpm publish && npm trust github x\n```"])
['npm publish && npm trust github x']
>>> newer_commands(body, ["Same:\n```bash\nnpm  trust github x\n```", "no code"])
[]
```

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]

### openloops.runbook_issue.parse_review(text, , ids)

The reviewer’s JSON list, one object per step id in *ids*; an error otherwise.

```pycon
>>> parse_review('```json\n[{"id": "s1", "level": "show"}]\n```', ids=['s1'])
[{'id': 's1', 'level': 'show'}]
```

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]]

### openloops.runbook_issue.plan_from_issue(issue, , keep_open='', made_by='ol runbook-issue', now=None)

A plan of one step per shell block of *issue*’s body, in order, each checked first
by the issue’s own `**Verify:**` line. Pure.

`issue` is what [`openloops.closer.read_issue()`](_autosummary/openloops.closer.html.md#openloops.closer.read_issue) returns (`ref`, `title`,
`body`). `keep_open` is a reason the issue must stay open after the run (the
closer would refuse it, or it has no Verify line); the last step then has
`close: false` and the reason in its note.

```pycon
>>> body = '**Verify:** `test -f done`\n\n```bash\ntouch done\n```'
>>> p = plan_from_issue({'ref': 'o/r#3', 'title': 'Make it', 'body': body})
>>> [(s.id, s.command, s.check, s.close) for s in p.steps]
[('s1', 'touch done', 'test -f done', True)]
```

* **Return type:**
  [`Plan`](_autosummary/openloops.runbook.html.md#openloops.runbook.Plan)

### openloops.runbook_issue.plan_id(ref)

The plan id for an issue: one plan per issue, replaced when planned again.

```pycon
>>> plan_id('thorwhalen/_private-issues#202')
'issue-thorwhalen-_private-issues-202'
```

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### openloops.runbook_issue.review_prompt(plan, facts)

What the reviewer is given: each step’s command, folder and check, and the facts.
Not the issue’s text, not the floor’s levels: a second opinion has not read the first.

```pycon
>>> p = Plan('p', 'now', steps=[Step('s1', 'o/r#1', 'echo hi', cwd='~')])
>>> text = review_prompt(p, {'s1': ['clean checkout']})
>>> 'echo hi' in text, 'clean checkout' in text, 'o/r#1' in text
(True, True, False)
```

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)


# _autosummary/openloops.runbook_run.html.md

# openloops.runbook_run

Run an approved run plan: exactly the approved commands, no model, close on the check.

ADR-018. A plan ([`openloops.runbook.Plan`](_autosummary/openloops.runbook.html.md#openloops.runbook.Plan)) is written by an agent and approved by
the owner once, by its hash. This module is the executor, and it holds no judgement:

- it refuses a plan with no approval for its **current** hash, an approval older than
  `DFLT_APPROVAL_HOURS`, or a plan [`openloops.runbook.validate()`](_autosummary/openloops.runbook.html.md#openloops.runbook.validate) rejects (the
  > risk floor is recomputed from the text, so a plan cannot talk its way past it);
- it runs each step’s command exactly as written, in order, with a time limit, its
  output captured to a local log (mode 0600) and never posted anywhere;
- before a step it runs the step’s check, and skips the command when the check already
  passes, so running a plan twice is harmless;
- a step whose dependencies did not succeed is skipped; a step that needs a person at a
  terminal (`Step.interactive`) runs only when the owner started the run from one
  (`tty=True`), on his own terminal and with no time limit
  (`DFLT_ATTENDED_TIMEOUT`): he is there, and Ctrl-C stops the run (what
  succeeded stays done; the same line resumes);
- at a terminal, `say=` is told what each step is before it runs (its id, issue and
  note: what to have ready) and how it ended after, and `ask=` is asked before going
  on past a step that failed, so no step’s end runs silently into the next one’s prompt;
- after an issue’s last step it hands the outcome to [`openloops.closer`](_autosummary/openloops.closer.html.md#module-openloops.closer), which
  closes the issue only on a passing check (ADR-015).

`ol runbook run PLAN --only-checks` needs no approval: it runs no command, only the
checks, and closes what already passes (the closer’s four conditions still apply).

Nothing in the core imports this module. [`run_step()`](_autosummary/openloops.runbook_run.html.md#openloops.runbook_run.run_step) is the one place a step’s
command is run; `ol do` (ADR-015 §2) is meant to call it too.

### Functions

| [`runbooks_store`](_autosummary/openloops.runbook_run.html.md#openloops.runbook_run.runbooks_store)([root])                            | `~/.local/share/openloops/runbooks/`: `plans/`, `approvals/`, `reports/`.                                                                                                                                                  |
|----------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| [`save_plan`](_autosummary/openloops.runbook_run.html.md#openloops.runbook_run.save_plan)(plan, \*, store)                        | Write *plan* under `plans/<id>.json`; returns its hash.                                                                                                                                                                    |
| [`load_plan`](_autosummary/openloops.runbook_run.html.md#openloops.runbook_run.load_plan)(ref, \*, store)                         | A plan by id, or by the path of a plan file.                                                                                                                                                                               |
| [`approve`](_autosummary/openloops.runbook_run.html.md#openloops.runbook_run.approve)(plan, \*, via[, discussed, now])          | Record the owner's approval of *plan*'s current hash.                                                                                                                                                                      |
| [`approval_of`](_autosummary/openloops.runbook_run.html.md#openloops.runbook_run.approval_of)(plan, \*, store[, now, hours])        | The live approval of *plan*'s current hash, or `None`.                                                                                                                                                                     |
| [`plans`](_autosummary/openloops.runbook_run.html.md#openloops.runbook_run.plans)(\*, store[, now, include_ran])              | The stored plans, newest first, each `{plan, title, hash12, state, counts, page, created, issues, approve}` (`issues`: every issue it covers; `approve`: [`approve_line()`](_autosummary/openloops.runbook_run.html.md#openloops.runbook_run.approve_line)). |
| [`run_step`](_autosummary/openloops.runbook_run.html.md#openloops.runbook_run.run_step)(step, \*[, runner, tty, log_path, ...])  | Run one step's command; `ok` when it exits 0 and its output matches `expect`.                                                                                                                                              |
| [`run_task`](_autosummary/openloops.runbook_run.html.md#openloops.runbook_run.run_task)(step, \*[, runner, run_check, tty, ...]) | One task step end to end, short of reporting: check first, then run.                                                                                                                                                       |
| [`run_plan`](_autosummary/openloops.runbook_run.html.md#openloops.runbook_run.run_plan)(plan, \*, store[, runner, ...])          | Run *plan*'s approved steps, in order; return the run report (also stored).                                                                                                                                                |
| [`shell_runner`](_autosummary/openloops.runbook_run.html.md#openloops.runbook_run.shell_runner)(command, \*, cwd, timeout, tty, ...) | Run *command* with `bash`; return `(exit status, output)`.                                                                                                                                                                 |
| [`approve_line`](_autosummary/openloops.runbook_run.html.md#openloops.runbook_run.approve_line)(plan_id, hash12)                     | The one command that approves a plan's current text and runs it at the terminal.                                                                                                                                           |

### openloops.runbook_run.approval_of(plan, , store, now=None, hours=48)

The live approval of *plan*’s current hash, or `None`.

`None` too for an approval of another plan with the same steps, one dated in the
future or without a time zone, and one older than `hours`.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)] | [`None`](https://docs.python.org/3/builtins/constants.html#None)

### openloops.runbook_run.approve(plan, , via, discussed=(), store, now=None)

Record the owner’s approval of *plan*’s current hash.

`via` says how the owner approved (`"terminal"`, `"board:<event id>"`,
`"session: <the owner's words>"`); `discussed` names the `discuss`-level steps
the owner said yes to by name. A plan that does not validate is not approvable.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]

### openloops.runbook_run.approve_line(plan_id, hash12)

The one command that approves a plan’s current text and runs it at the terminal.

```pycon
>>> approve_line("p1", "abc123def456")
'cd ~ && ol runbook-run p1 --tty --approve abc123def456'
```

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### openloops.runbook_run.load_plan(ref, , store)

A plan by id, or by the path of a plan file.

* **Return type:**
  [`Plan`](_autosummary/openloops.runbook.html.md#openloops.runbook.Plan)

### openloops.runbook_run.plans(, store, now=None, include_ran=False)

The stored plans, newest first, each `{plan, title, hash12, state, counts, page,
created, issues, approve}` (`issues`: every issue it covers; `approve`:
[`approve_line()`](_autosummary/openloops.runbook_run.html.md#openloops.runbook_run.approve_line)).

`state` is `waiting` (no live approval for its current hash: it needs the owner),
`approved` (approved, no run since), or `ran` (a report exists since the
approval). `ran` plans are left out unless `include_ran`.

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]]

### openloops.runbook_run.run_plan(plan, \*, store, runner=<function shell_runner>, run_check=<function default_run_check>, close=None, log_dir=None, tty=False, only_checks=False, only=None, dry_run=False, now=None, say=None, ask=None, attended_timeout=None)

Run *plan*’s approved steps, in order; return the run report (also stored).

`say` (the owner’s terminal) is told what each step is before it runs and how it
ended after; `ask` is asked, after a step fails, whether to go on: `q` holds the
rest (rerun the same line later: what succeeded does not run twice).

`only` limits the run to some step ids (a pilot): the others are `held`, and an
issue with a held step is not reported (it closes when its last step has run).
`only_checks` runs no command, needs no approval, and closes only on the issue’s
**own** Verify line (a check the planner wrote needs the owner’s approval of the plan).
`dry_run` runs nothing and writes nothing. `close` defaults to
[`openloops.closer.report()`](_autosummary/openloops.closer.html.md#openloops.closer.report) with the owners and login resolved once per run;
`log_dir` to `~/.local/share/openloops/runbooks/logs`.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]

### openloops.runbook_run.run_step(step, \*, runner=<function shell_runner>, tty=False, log_path=None, attended_timeout=None)

Run one step’s command; `ok` when it exits 0 and its output matches `expect`.

Returns `{status, ok, why, tail}`; `tail` is the end of the output, for the local
report only. A step that needs the owner’s hands, run at his terminal, gets
`attended_timeout` instead of its own limit (default: none).

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]

### openloops.runbook_run.run_task(step, \*, runner=<function shell_runner>, run_check=<function default_run_check>, tty=False, log_path=None, checks_only=False, attended_timeout=None)

One task step end to end, short of reporting: check first, then run.

`result` is `already-done` (its check passes: the command did not run),
`not-run` (`checks_only`), `needs-terminal` (an interactive step without
`tty`), `ok` or `failed`. ADR-015 §2’s `ol do` is this plus
[`openloops.closer.report()`](_autosummary/openloops.closer.html.md#openloops.closer.report).

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]

### openloops.runbook_run.runbooks_store(root=None)

`~/.local/share/openloops/runbooks/`: `plans/`, `approvals/`, `reports/`.

* **Return type:**
  [`MutableMapping`](https://docs.python.org/3/library/collections.abc.html#collections.abc.MutableMapping)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]

### openloops.runbook_run.save_plan(plan, , store)

Write *plan* under `plans/<id>.json`; returns its hash.

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### openloops.runbook_run.shell_runner(command, , cwd, timeout, tty, log_path)

Run *command* with `bash`; return `(exit status, output)`.

Output goes to *log_path* (created 0600). With `tty` the step runs on the owner’s
own terminal, as if he had typed it: his keys reach it (a paste, a one-time code, a
`y`), and his Ctrl-C reaches it and this process (which then stops the run). Its
output is shown there and not kept. Without `tty` input is closed, so a step that
waits for input fails instead of hanging, and its output is captured. `None` is a
step that could not run, ran out of time, or was stopped with Ctrl-C
(`timeout=None` waits for as long as it takes).

* **Return type:**
  [`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[`int`](https://docs.python.org/3/builtins/functions.html#int) | [`None`](https://docs.python.org/3/builtins/constants.html#None), [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]


# _autosummary/openloops.session_page.html.md

# openloops.session_page

A session, rendered as one page a person can read: pure, script-free, private by rule.

ADR-016. [`session_page()`](_autosummary/openloops.session_page.html.md#openloops.session_page.session_page) takes the records of one transcript (already loaded) and
returns one self-contained HTML document: one block per turn of the main thread, the
prompt and then every text the session wrote in that turn. It reads no file and writes
none; [`openloops.tools.page()`](_autosummary/openloops.tools.html.md#openloops.tools.page) and `ol page` do the reading and the writing.

**The anchor.** Every turn is an element whose `id` is `t-<id of the prompt record>`
(the id `openloops.exchanges.Exchange.uuid` carries), with any character outside
`A-Za-z0-9_-` replaced by `_`. [`turn_anchor()`](_autosummary/openloops.session_page.html.md#openloops.session_page.turn_anchor) builds it, so a consumer links to
`<page address>#t-<id>` without guessing. The turn the address points at is
highlighted by the browser’s own `:target` rule; `focus=` additionally gives that
turn the class `focus`, for a page opened without a fragment.

**What the page holds.** The prompt (who it came from: a person, another session by
name, or tooling; the sentences that ask something are marked), then the session’s texts
in order, and each tool call as one line (the tool’s name and what it was pointed at).
Left out: tool results, thinking, sub-agent threads and text the tooling injected. A
compaction summary is shown and labelled as one.

**Credentials.** Text is cleaned *before* anything is cut: a field holding a
credential-shaped string is replaced whole by a notice naming the pattern class, never
the text, and the page says how many passages were withheld. That is
[`openloops.dashboard.Sanitizer`](_autosummary/openloops.dashboard.html.md#openloops.dashboard.Sanitizer)’s behaviour, not [`openloops.egress.scrub()`](_autosummary/openloops.egress.html.md#openloops.egress.scrub)’s
(which refuses a whole document on the first match, wrong for a long session).

**A rendered session is private data** (ADR-016, rule 4): the words of a session, for the
person who ran it. Nothing here publishes or uploads a page, and a page is never a
fixture, a docs example or an attachment to an issue.

```pycon
>>> records = [
...     {"type": "user", "uuid": "p1", "timestamp": "T1",
...      "message": {"content": "Why is CI slow?"}},
...     {"type": "assistant", "uuid": "a1", "timestamp": "T2",
...      "message": {"content": [{"type": "text", "text": "The cache was cold."}]}},
... ]
>>> html = session_page(records, focus="p1")
>>> turn_anchor("p1"), 'id="t-p1"' in html, "<script" in html
('t-p1', True, False)
```

### Module Attributes

| [`ANCHOR_PREFIX`](_autosummary/openloops.session_page.html.md#openloops.session_page.ANCHOR_PREFIX)        | What every turn's `id` starts with; the rest is the prompt record's id.               |
|-----------------------------------------------------------------------|---------------------------------------------------------------------------------------|
| [`DFLT_MAX_BYTES`](_autosummary/openloops.session_page.html.md#openloops.session_page.DFLT_MAX_BYTES)       | Over this many characters of rendered turns, the page keeps the turns around `focus`. |
| [`DFLT_MAX_FIELD_CHARS`](_autosummary/openloops.session_page.html.md#openloops.session_page.DFLT_MAX_FIELD_CHARS) | A single text, prompt or tool line longer than this is cut (after it is cleaned).     |

### Functions

| [`session_page`](_autosummary/openloops.session_page.html.md#openloops.session_page.session_page)(records, \*[, focus, sanitizer, ...])   | One self-contained HTML document for a transcript's records.    |
|-------------------------------------------------------------------------------------------------------|-----------------------------------------------------------------|
| [`turn_anchor`](_autosummary/openloops.session_page.html.md#openloops.session_page.turn_anchor)(prompt_uuid)                             | The `id` of the turn whose prompt record has this id: `t-<id>`. |

### openloops.session_page.ANCHOR_PREFIX *= 't-'*

What every turn’s `id` starts with; the rest is the prompt record’s id.

### openloops.session_page.DFLT_MAX_BYTES *= 400000*

Over this many characters of rendered turns, the page keeps the turns around `focus`.

### openloops.session_page.DFLT_MAX_FIELD_CHARS *= 20000*

A single text, prompt or tool line longer than this is cut (after it is cleaned).

### openloops.session_page.session_page(records, , focus=None, sanitizer=None, key='', max_bytes=400000, max_field_chars=20000)

One self-contained HTML document for a transcript’s records. Pure.

`focus` is the id of a turn’s prompt record (`Exchange.uuid`; a leading `t-` is
accepted too). That turn gets the class `focus` and, when the page is over
`max_bytes` of rendered turns, is the centre of the turns kept: the rest are
replaced by a count of what was left out. With no `focus` the latest turns are
kept. `key` names the session in the header.

`sanitizer=` is the seam (default: a fresh [`openloops.dashboard.Sanitizer`](_autosummary/openloops.dashboard.html.md#openloops.dashboard.Sanitizer),
so each page counts its own withheld passages); any object with `text(str) -> str`
(escaped) and a `withheld` list substitutes.

No script, no external request, no event handler. See the module docstring for the
anchor format, what is left out, and why a rendered session is private data.

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### openloops.session_page.turn_anchor(prompt_uuid)

The `id` of the turn whose prompt record has this id: `t-<id>`.

A consumer’s link is `<page address>#` + this. Characters outside `A-Za-z0-9_-`
become `_` (a record id is a UUID in practice, so nothing changes).

```pycon
>>> turn_anchor("0f3a-91")
't-0f3a-91'
```

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)


# _autosummary/openloops.skills.html.md

# openloops.skills

The agent-facing surface: two skills, one subagent, and the command that installs them.

The `ol` command is plumbing. What most people actually want is an agent that knows
how to use the plumbing and tells them what matters – “what is being done, and what
needs my attention?” – without their ever typing `ol owed`. That agent is a file:
a `SKILL.md` an agent host loads when the question comes up. So openloops ships three
of them, inside the package, and this module is how they get from the wheel to the host.

| `openloops`             | the **read** skill. Runs the three commands, and<br/>synthesises rather than pastes. The one to load.                                                                  |
|-------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `openloops-needs-human` | the **capture** skill. Without something filing<br/>`manual-task` issues, `ol owed` reads an empty<br/>list forever – which is the state a stranger<br/>installs into. |
| `openloops-sweep`       | a subagent: the same sweep in a fresh context,<br/>returning a page instead of three screens of output.                                                                |

**Nothing here is openloops-specific machinery.** A skill is a markdown file in a
directory an agent host reads; installing one is a symlink. The whole module is a
hundred lines because that is genuinely all it is, and the alternative – a copy of
each skill pasted into every user’s config – is a copy that goes stale the first time
`pip install -U openloops` lands.

Two decisions worth stating, because both are the kind that get quietly reversed:

**A symlink, not a copy.** The point is that upgrading the package upgrades the skill.
Copying is the *fallback*, taken only where symlinks are unavailable (Windows without
Developer Mode, where creating one needs a privilege an ordinary process lacks), and
the plan says which happened rather than pretending they are the same thing.

**Nothing already there is ever overwritten.** A destination holding something that is
not ours reads `conflict`: it is reported, not replaced, and `force=True` is the
only way past. Someone’s hand-written skill of the same name is theirs, and silently
eating it would be a worse failure than not installing at all.

This is deliberately *not* in [`openloops.tools`](_autosummary/openloops.tools.html.md#module-openloops.tools). That module is the list every
surface dispatches from – an MCP server, an HTTP endpoint – and “symlink files into
this machine’s agent config” is not an operation a remote surface could honestly offer.
It belongs beside [`openloops.job`](_autosummary/openloops.job.html.md#module-openloops.job), the other installer, which the CLI also wraps
directly.

```pycon
>>> skills_dir().name, agents_dir().name
('skills', 'agents')
>>> sorted(asset.name for asset in bundled())
['openloops', 'openloops-needs-human', 'openloops-phone-board', 'openloops-pile', 'openloops-remind', 'openloops-risk-reviewer', 'openloops-runbook', 'openloops-sweep']
```

### Module Attributes

| [`HOST_ENV_VAR`](_autosummary/openloops.skills.html.md#openloops.skills.HOST_ENV_VAR)   | Where Claude Code keeps skills and subagents, and the variable that relocates it.                         |
|-----------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------|
| [`ALIASES`](_autosummary/openloops.skills.html.md#openloops.skills.ALIASES)        | Bare names that standing instructions point at, mapped from the shipped skill that should answer to them. |

### Functions

| [`agents_dir`](_autosummary/openloops.skills.html.md#openloops.skills.agents_dir)()                                  | The bundled subagent definitions, inside the installed package.                   |
|------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------|
| [`bundled`](_autosummary/openloops.skills.html.md#openloops.skills.bundled)()                                     | Every skill and subagent this package ships, sorted by name.                      |
| [`host_dir`](_autosummary/openloops.skills.html.md#openloops.skills.host_dir)([target])                            | The agent host's config directory: `target`, `CLAUDE_CONFIG_DIR`, or `~/.claude`. |
| [`install_skills`](_autosummary/openloops.skills.html.md#openloops.skills.install_skills)(\*[, target, only, copy, ...]) | Make the bundled skills and subagent visible to an agent host.                    |
| [`skills_dir`](_autosummary/openloops.skills.html.md#openloops.skills.skills_dir)()                                  | The bundled skills directory, inside the installed package.                       |

### Classes

| [`Asset`](_autosummary/openloops.skills.html.md#openloops.skills.Asset)(kind, name, source)   | One installable thing: a skill directory or a subagent file.   |
|------------------------------------------------------------------------------|----------------------------------------------------------------|

### openloops.skills.ALIASES *= {'openloops-needs-human': 'needs-human'}*

Bare names that standing instructions point at, mapped from the shipped skill that
should answer to them. Nothing else installs these, so an older copy of the same rule
(a research checkout predating this package) silently wins when a session loads
`needs-human` – [`install_skills()`](_autosummary/openloops.skills.html.md#openloops.skills.install_skills) reports that. It does not install the alias:
a second folder over one SKILL.md would give two skills the same triggers.

### *class* openloops.skills.Asset(kind, name, source)

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

One installable thing: a skill directory or a subagent file.

`name` is what the host will call it, and it is the file or folder name too –
the agent-skill spec requires the folder name to equal the skill’s `name:`, so
deriving one from the other cannot drift.

#### destination(host)

Where this asset goes under *host*.

* **Return type:**
  [`Path`](https://docs.python.org/3/library/pathlib.html#pathlib.Path)

### openloops.skills.HOST_ENV_VAR *= 'CLAUDE_CONFIG_DIR'*

Where Claude Code keeps skills and subagents, and the variable that relocates it.
Honoured rather than reimplemented: a user who has moved their config has done so
for a reason, and an installer that ignores it writes to a directory nobody reads.

### openloops.skills.agents_dir()

The bundled subagent definitions, inside the installed package.

* **Return type:**
  [`Path`](https://docs.python.org/3/library/pathlib.html#pathlib.Path)

### openloops.skills.bundled()

Every skill and subagent this package ships, sorted by name.

Discovered from the directories rather than listed here: a list would be a second
place to update, and the one that gets forgotten.

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`Asset`](_autosummary/openloops.skills.html.md#openloops.skills.Asset)]

### openloops.skills.host_dir(target=None)

The agent host’s config directory: `target`, `CLAUDE_CONFIG_DIR`, or `~/.claude`.

```pycon
>>> import os
>>> host_dir('/somewhere/else').name
'else'
```

* **Return type:**
  [`Path`](https://docs.python.org/3/library/pathlib.html#pathlib.Path)

### openloops.skills.install_skills(, target=None, only=None, copy=False, force=False, dry_run=False)

Make the bundled skills and subagent visible to an agent host. Idempotent.

Links each one into `target` (default: `CLAUDE_CONFIG_DIR` or `~/.claude`) so
that upgrading the package upgrades the skill. `copy=True` takes a copy instead,
which is also what happens by itself where symlinks are unavailable.

Returns the plan it carried out – one row per asset, each carrying its verdict and
the reason for it. `dry_run=True` returns the same plan having touched nothing,
which is the only way to see what a run would do *before* it does it.

Nothing that is already there is overwritten: an occupied destination reads
`conflict` and is left exactly as it was until `force=True`.

`only=` installs a subset by name. The case it exists for: you already have your
own capture skill, adapted to your own fleet, and a second one competing for the same
triggers is worse than either alone – so take the reader and the subagent and leave
the capture skill out.

The plan’s `shadowed` list names any bare-named skill (`needs-human`) that
resolves somewhere other than the shipped copy, and whether its text matches ours;
nothing is changed on its account.

```pycon
>>> plan = install_skills(target='/nonexistent/host', only=['openloops'], dry_run=True)
>>> [row['name'] for row in plan['actions']]
['openloops']
```

```pycon
>>> plan = install_skills(target='/nonexistent/host', dry_run=True)
>>> plan['counts']['install'] == len(list(bundled())), plan['dry_run']
(True, True)
>>> sorted({row['action'] for row in plan['actions']})
['install']
```

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]

### openloops.skills.skills_dir()

The bundled skills directory, inside the installed package.

`Path(__file__).parent` rather than a configured root, so this answers correctly
from a wheel, an editable install, a zip and a virtualenv without being told which.

* **Return type:**
  [`Path`](https://docs.python.org/3/library/pathlib.html#pathlib.Path)


# _autosummary/openloops.store.html.md

# openloops.store

Where digests live, and where the change-detection cache lives — two different things.

The digest store is **data**: a local directory of markdown files under
`~/.local/share/openloops/digests/`, addressed as a `MutableMapping[str, str]` so
that swapping it for a git-synced directory or an S3-backed store is one keyword
argument rather than a rewrite. Nothing in openloops opens a file by path.

The sync cache is **not data**: it is a per-machine record of which transcript
revisions have already been read, and deleting it is a distinct operation from deleting
digests. That separation is ADR-010’s rule — a cache purge must not be able to reach
the thing being cached — and it is what makes the regeneration test meaningful: wipe
both, sync again, and every digest comes back byte-identical.

Keys are `{source}/{state}/{session}.md`. The source segment is the machine (or
person) that wrote the digest, so two machines syncing into one git repository never
write the same path and there is nothing to reconcile. The state segment is `open` or
`archive` — **loop state, not process state**. If it ever came to mean “a process is
running”, this would be a session dashboard rather than a record of what sessions said.

```pycon
>>> digest_key('laptop', 'open', 'abc-123')
'laptop/open/abc-123.md'
>>> parse_digest_key('laptop/open/abc-123.md')
('laptop', 'open', 'abc-123')
```

### Functions

| [`data_dir`](_autosummary/openloops.store.html.md#openloops.store.data_dir)()                             | The project's data root.                                                              |
|-----------------------------------------------------------------------------------------|---------------------------------------------------------------------------------------|
| [`state_dir`](_autosummary/openloops.store.html.md#openloops.store.state_dir)()                            | Where per-machine caches and job logs go.                                             |
| [`default_source`](_autosummary/openloops.store.html.md#openloops.store.default_source)([directory])            | This machine's label for its digest folder.                                           |
| [`digests_store`](_autosummary/openloops.store.html.md#openloops.store.digests_store)([rootdir])               | The default `digests_store`: markdown files under the data root.                      |
| [`board_docs_store`](_autosummary/openloops.store.html.md#openloops.store.board_docs_store)(rootdir)              | A self-hosted board's documents: `<root>/<collection>/<id>.json`, written atomically. |
| [`digest_key`](_autosummary/openloops.store.html.md#openloops.store.digest_key)(source, state, session_key) | The store key for one session's digest.                                               |
| [`parse_digest_key`](_autosummary/openloops.store.html.md#openloops.store.parse_digest_key)(key)                  | Split a store key back into `(source, state, session_key)`.                           |
| [`load_sync_state`](_autosummary/openloops.store.html.md#openloops.store.load_sync_state)([directory])           | Session id → the transcript revision last read.                                       |
| [`save_sync_state`](_autosummary/openloops.store.html.md#openloops.store.save_sync_state)(state[, directory])    | Write the mtime cache, creating its directory.                                        |
| [`sync_state_path`](_autosummary/openloops.store.html.md#openloops.store.sync_state_path)([directory])           | Where the mtime cache lives.                                                          |

### Classes

| [`Utf8TextFiles`](_autosummary/openloops.store.html.md#openloops.store.Utf8TextFiles)(\*args[, delete_func, ...])   | `dol`'s text-file store with the encoding pinned rather than inherited.   |
|----------------------------------------------------------------------------------------------|---------------------------------------------------------------------------|
| [`AtomicTextFiles`](_autosummary/openloops.store.html.md#openloops.store.AtomicTextFiles)(root)                       | `<root>/<key>` text files, each write atomic: temp file, `fsync`, rename. |

### *class* openloops.store.AtomicTextFiles(root)

Bases: [`MutableMapping`](https://docs.python.org/3/library/collections.abc.html#collections.abc.MutableMapping)

`<root>/<key>` text files, each write atomic: temp file, `fsync`, rename.

A self-hosted board’s store is read by every poll while it is written, by several
server processes. A plain `open(path, "w")` leaves a truncated file behind when a
worker is killed mid-write or the disk fills, and readers can see a half-written one;
a rename never shows either. Keys are POSIX relative paths (`outbox/e1.json`);
a key that would leave `root` is refused.

### *class* openloops.store.Utf8TextFiles(\*args, delete_func=None, write_open_kwargs=None, write_func=None, atomic=False, \*\*kwargs)

Bases: `PrefixRelativizationMixin`, `Store`

`dol`’s text-file store with the encoding pinned rather than inherited.

`dol` opens text with `encoding=None`, i.e. whatever the locale says. Every
digest contains an em dash, so on a machine where the locale resolves to ASCII — a
container or a cron job with `LANG` unset, an Alpine image — writing one raises,
and in a store two machines share it is worse: one writes bytes the other cannot
read back. Pinning UTF-8 is the whole fix.

#### is_valid_key(k, \*args, \_\_name='is_valid_key', \*\*kwargs)

`is_valid_key` on the inner key – see `mk_relative_path_store`.

#### validate_key(k, \*args, \_\_name='validate_key', \*\*kwargs)

`validate_key` on the inner key – see `mk_relative_path_store`.

### openloops.store.board_docs_store(rootdir)

A self-hosted board’s documents: `<root>/<collection>/<id>.json`, written atomically.

```pycon
>>> import tempfile
>>> store = board_docs_store(tempfile.mkdtemp())
>>> store['outbox/e1.json'] = '{}'
>>> list(store), store['outbox/e1.json']
(['outbox/e1.json'], '{}')
```

* **Return type:**
  [`MutableMapping`](https://docs.python.org/3/library/collections.abc.html#collections.abc.MutableMapping)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]

### openloops.store.data_dir()

The project’s data root. Override with `OPENLOOPS_DATA_DIR`.

Per-kind subdirectories hang off this; nothing is written directly into it, so a
later kind of data needs no second migration.

* **Return type:**
  [`Path`](https://docs.python.org/3/library/pathlib.html#pathlib.Path)

### openloops.store.default_source(directory=None)

This machine’s label for its digest folder. Override with `OPENLOOPS_SOURCE`.

A short, filename-safe name. It exists so several machines can sync digests into one
place without colliding — not to identify anybody, though on a machine whose
hostname was never changed it may well do; every `ol sync` prints it, and
`OPENLOOPS_SOURCE` overrides it.

**It is sticky.** The hostname is a *seed*, written once to a file under the state
directory and read thereafter. macOS rewrites the hostname when it joins a network
where the name collides — appending `-2`, `-3` — and a label that moved would
fork the store into two complete copies with no dedup and no warning.

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### openloops.store.digest_key(source, state, session_key)

The store key for one session’s digest.

Both segments are validated, not just the state. `transcript_source=` is a seam
whose documented purpose is “another machine’s synced transcripts”, so a session id
can come from a listing this process did not produce — and a key containing `..`
would make a file-backed store write outside its own root while `sync` reported
success. Validating here means every backend inherits the check.

```pycon
>>> digest_key('mac', 'archive', 's1')
'mac/archive/s1.md'
>>> digest_key('mac', 'open', '../../etc/passwd')
Traceback (most recent call last):
    ...
ValueError: session key must be a single safe path segment, got '../../etc/passwd'
```

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### openloops.store.digests_store(rootdir=None)

The default `digests_store`: markdown files under the data root.

Any `MutableMapping[str, str]` works in its place — a plain `dict` for tests,
a git-synced directory, an S3-backed store. The keys are what carry the layout, so
a different backend gets the same `{source}/{state}/{session}.md` structure for
free.

```pycon
>>> store = digests_store(rootdir='/tmp/openloops-doctest-store')
>>> store['demo/open/s1.md'] = '# hi'
>>> sorted(store)
['demo/open/s1.md']
>>> del store['demo/open/s1.md']
```

* **Return type:**
  [`MutableMapping`](https://docs.python.org/3/library/collections.abc.html#collections.abc.MutableMapping)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]

### openloops.store.load_sync_state(directory=None)

Session id → the transcript revision last read. Missing or corrupt reads empty.

A corrupt cache is treated as an absent one on purpose: the only cost of being
wrong here is re-deriving digests that were already correct.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]

### openloops.store.parse_digest_key(key)

Split a store key back into `(source, state, session_key)`.

Both separators are accepted. A file-backed store hands keys back joined with the
platform’s separator, so on Windows every key would fail to parse and every read
path would quietly return nothing while `sync` reported digests written.

```pycon
>>> parse_digest_key('mac/archive/s1.md')
('mac', 'archive', 's1')
>>> parse_digest_key('mac' + chr(92) + 'archive' + chr(92) + 's1.md')
('mac', 'archive', 's1')
```

* **Return type:**
  [`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]

### openloops.store.save_sync_state(state, directory=None)

Write the mtime cache, creating its directory. Returns the path written.

* **Return type:**
  [`Path`](https://docs.python.org/3/library/pathlib.html#pathlib.Path)

### openloops.store.state_dir()

Where per-machine caches and job logs go. Override with `OPENLOOPS_STATE_DIR`.

Deliberately not under [`data_dir()`](_autosummary/openloops.store.html.md#openloops.store.data_dir): everything here is disposable, and keeping
it elsewhere means “clear the cache” can never be mistyped into “delete the digests”.

* **Return type:**
  [`Path`](https://docs.python.org/3/library/pathlib.html#pathlib.Path)

### openloops.store.sync_state_path(directory=None)

Where the mtime cache lives. Deleting this file forces a full re-read.

* **Return type:**
  [`Path`](https://docs.python.org/3/library/pathlib.html#pathlib.Path)


# _autosummary/openloops.tasks.html.md

# openloops.tasks

Everything you could act on, as one list of task records: gather, classify, merge.

[`openloops.owed()`](_autosummary/openloops.html.md#openloops.owed) answers  *“what do I owe, and is it still owed?”* for one label.
A task board needs a wider net and a different answer: every open item across a fleet
that asks something of the human (the `manual-task` issues, the issues titled
“Decide…”, the PRs waiting on their review), each turned into a **task record** saying
what to do, where to do it, how long it takes and on which device.

Three steps, each a plain function:

1. [`gather()`](_autosummary/openloops.tasks.html.md#openloops.tasks.gather) sweeps several owners with `gh search`, one query per owner and
   kind so no owner’s results crowd out another’s, with no 50-row cap (the search
   API’s own ceiling of 1000 per query is the limit, and a query that reaches it is
   *reported* as saturated, never truncated quietly). Exclusions are keyword arguments.
2. [`classify()`](_autosummary/openloops.tasks.html.md#openloops.tasks.classify) turns each candidate into a record through a `classifier=`. The
   default, [`heuristic_classify()`](_autosummary/openloops.tasks.html.md#openloops.tasks.heuristic_classify), is deterministic: label, title and body
   patterns decide the tier, the pattern and the minutes, and the deep-link builders
   point at the exact settings page. No model is called, here or anywhere in
   openloops. The richer path is the classifier brief shipped with the
   `openloops-phone-board` skill: a subagent reads each item and writes records in
   the same schema, which [`merge_records()`](_autosummary/openloops.tasks.html.md#openloops.tasks.merge_records) lays over the heuristic ones.
3. [`merge_records()`](_autosummary/openloops.tasks.html.md#openloops.tasks.merge_records) combines record sources by URL, later sources winning, and
   normalises every record to [`TASK_FIELDS`](_autosummary/openloops.tasks.html.md#openloops.tasks.TASK_FIELDS).

The record schema is [`Task`](_autosummary/openloops.tasks.html.md#openloops.tasks.Task), defined once, here. The board page, the build
step and the classifier brief all read it; a field added anywhere else is a field the
others do not know about.

**Read-only, like the rest of openloops.** Gathering runs `gh search`; nothing here
comments, closes, labels or approves anything.

```pycon
>>> candidate = {
...     'url': 'https://github.com/acme/widget/issues/7', 'repo': 'acme/widget',
...     'number': 7, 'title': 'Add the NPM_TOKEN secret so CI can publish',
...     'body': '', 'labels': ['manual-task'], 'created': '2026-08-01',
... }
>>> record = heuristic_classify(candidate)
>>> record['tier'], record['pattern'], record['id']
('browser', 'github-settings', 'acme/widget#7')
>>> [link['label'] for link in record['links']]
['GitHub: Actions secrets', 'Issue']
```

### Module Attributes

| [`TIERS`](_autosummary/openloops.tasks.html.md#openloops.tasks.TIERS)         | Where the human does the thing, cheapest first.    |
|----------------------------------------------------------------|----------------------------------------------------|
| [`STATUSES`](_autosummary/openloops.tasks.html.md#openloops.tasks.STATUSES)      | Whether the item still asks anything of the human. |
| [`PATTERNS`](_autosummary/openloops.tasks.html.md#openloops.tasks.PATTERNS)      | The controlled vocabulary of repeated chores.      |
| [`TASK_FIELDS`](_autosummary/openloops.tasks.html.md#openloops.tasks.TASK_FIELDS)   | Every key on every record, in schema order.        |
| [`DFLT_SEARCHES`](_autosummary/openloops.tasks.html.md#openloops.tasks.DFLT_SEARCHES) | (search terms, the field they match).              |

### Functions

| [`apply_reviews`](_autosummary/openloops.tasks.html.md#openloops.tasks.apply_reviews)(records, reviews)                 | Set only `review` on records, from `{id, review}` overlays; nothing else changes.   |
|--------------------------------------------------------------------------------------------------|-------------------------------------------------------------------------------------|
| [`classify`](_autosummary/openloops.tasks.html.md#openloops.tasks.classify)(candidates, \*[, classifier])          | One normalised record per candidate, through `classifier`.                          |
| [`gather`](_autosummary/openloops.tasks.html.md#openloops.tasks.gather)(\*[, owners, exclude_owners, ...])       | Every open item that asks something of the human, across `owners`, deduplicated.    |
| [`github_settings_url`](_autosummary/openloops.tasks.html.md#openloops.tasks.github_settings_url)(repo, section)              | A repository settings page (a key of `GITHUB_SETTINGS`).                            |
| [`heuristic_classify`](_autosummary/openloops.tasks.html.md#openloops.tasks.heuristic_classify)(candidate, \*[, rules, ...]) | A task record from a gathered candidate, by patterns alone.                         |
| [`load_records`](_autosummary/openloops.tasks.html.md#openloops.tasks.load_records)(paths)                             | The records in JSON files (each a list, or an envelope with `candidates`).          |
| [`merge_records`](_autosummary/openloops.tasks.html.md#openloops.tasks.merge_records)(\*sources)                        | Records from several sources, one per item, later sources winning.                  |
| [`npm_access_url`](_autosummary/openloops.tasks.html.md#openloops.tasks.npm_access_url)(package)                         | npm package settings: trusted publisher, publishing access, 2FA requirement.        |
| [`pypi_publishing_url`](_autosummary/openloops.tasks.html.md#openloops.tasks.pypi_publishing_url)([project])                  | PyPI trusted publishers: a project's page, or the pending-publisher page.           |

### Classes

| [`Rule`](_autosummary/openloops.tasks.html.md#openloops.tasks.Rule)(pattern, tier, minutes, regex)               | A heuristic: when `regex` matches title + body, the item is this pattern.   |
|----------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------|
| [`Task`](_autosummary/openloops.tasks.html.md#openloops.tasks.Task)(id[, url, kind, org, repo, title, ask, ...]) | One thing the human could act on.                                           |

### openloops.tasks.DFLT_SEARCHES *= {'agent-decided': ('agent-decided', 'label'), 'decide': ('Decide', 'title'), 'needs-user': ('"Needs the user"', 'body')}*

(search terms, the field they match).
A `label` match is a label name rather than text: `agent-decided` issues are the
record of a decision an agent made and the owner can veto (ADR-010).

* **Type:**
  Extra searches beyond the label, by name

### openloops.tasks.PATTERNS *= ('npm-trusted-publisher', 'npm-first-publish', 'npm-scope', 'npm-other', 'pypi-trusted-publisher', 'pypi-release', 'api-key', 'github-settings', 'server-chore', 'decision', 'review-pr', 'merge-bot-pr', 'record', 'device-test', 'listen-look', 'live-check', 'purchase', 'mac-only', 'other')*

The controlled vocabulary of repeated chores. A run on the board groups one pattern.

### *class* openloops.tasks.Rule(pattern, tier, minutes, regex)

Bases: [`NamedTuple`](https://docs.python.org/3/library/typing.html#typing.NamedTuple)

A heuristic: when `regex` matches title + body, the item is this pattern.

#### minutes *: [int](https://docs.python.org/3/builtins/functions.html#int)*

Alias for field number 2

#### pattern *: [str](https://docs.python.org/3/builtins/stdtypes.html#str)*

Alias for field number 0

#### regex *: [str](https://docs.python.org/3/builtins/stdtypes.html#str)*

Alias for field number 3

#### tier *: [str](https://docs.python.org/3/builtins/stdtypes.html#str)*

Alias for field number 1

### openloops.tasks.STATUSES *= ('open', 'likely-done', 'not-for-user', 'stale')*

Whether the item still asks anything of the human.

### openloops.tasks.TASK_FIELDS *= ('id', 'url', 'kind', 'org', 'repo', 'title', 'ask', 'tier', 'minutes', 'links', 'decision', 'prompt', 'machine', 'unblocks', 'pattern', 'pattern_key', 'status', 'note', 'source', 'created', 'review', 'command', 'run', 'blocked_by', 'facets')*

Every key on every record, in schema order.

### openloops.tasks.TIERS *= ('tap', 'browser', 'session', 'physical', 'mac-only')*

Where the human does the thing, cheapest first. The board sorts and filters on it.

### *class* openloops.tasks.Task(id, url=None, kind='issue', org=None, repo=None, title='', ask='', tier='session', minutes=None, links=list(), decision=None, prompt=None, machine=None, unblocks=list(), pattern='other', pattern_key=None, status='open', note=None, source=None, created=None, review=None, command=None, run=None, blocked_by=None, facets=dict())

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

One thing the human could act on. Every record carries every field.

`decision` is `{question, options, recommendation}` or `None`; `links` are
`{label, url}` with the item itself last; `prompt` is a paste-ready request for
a coding session (session tier). `source` says how the item was found and
`created` when it was opened (`YYYY-MM-DD`). `command` is the issue’s shell
command (its first shell code block outside “What I found”, at most
`MAX_COMMAND_CHARS`), or `None`: the board’s “Runnable by command” filter
and the run plans of ADR-018 key on it. `run` is derived from it: the
`ol runbook-issue` line for an issue that carries a command
(`openloops.obligations.runbook_line()`), which a card offers before the command.

`blocked_by` lists the open issues this one waits on (GitHub’s `blocked_by`
edges, `owner/name#number`): `[]` when none, `None` when they were not read
(never rounded into “ready”). `facets` is computed at board build
([`openloops.facets.task_facets()`](_autosummary/openloops.facets.html.md#openloops.facets.task_facets)); a source’s value is replaced there.

`review` is `{verdict, disagreement_risk, reason, concerns}` or `None`:
`verdict` one of `REVIEW_VERDICTS` (the gate’s route),
`disagreement_risk` one of `REVIEW_RISKS`, `reason` a string and
`concerns` a list of `{concern, stance, severity, reason}` with `stance` in
`REVIEW_STANCES` and `severity` in `REVIEW_SEVERITIES`. It is written
by a separate, external preference step at board-build time; this package only
carries it (normalised, never raising) and the board page shows it.

```pycon
>>> Task.from_mapping({'id': 'a/b#1', 'tier': 'nope', 'pattern': 'x'}).tier
'session'
```

#### as_dict()

JSON-ready form.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]

#### *classmethod* from_mapping(record)

Normalise a record from any source: unknown keys dropped, bad vocabulary fixed.

A value outside its vocabulary becomes the field’s safe default (`session`
tier, `other` pattern, `open` status) rather than an error, because one
sloppy classifier record must not sink a board of three hundred.

* **Return type:**
  [`Task`](_autosummary/openloops.tasks.html.md#openloops.tasks.Task)

### openloops.tasks.apply_reviews(records, reviews)

Set only `review` on records, from `{id, review}` overlays; nothing else changes.

Overlays match by `id` or by GitHub URL (ids derived as [`Task`](_autosummary/openloops.tasks.html.md#openloops.tasks.Task) does); an
overlay for an id no record has is ignored. The review is normalised.

```pycon
>>> recs = [{'id': 'a/b#1', 'tier': 'tap'}]
>>> out = apply_reviews(recs, [{'url': 'https://github.com/a/b/issues/1',
...                             'review': {'disagreement_risk': 'low'}},
...                            {'id': 'x/y#9', 'review': {'disagreement_risk': 'high'}}])
>>> [(r['tier'], r['review']['disagreement_risk']) for r in out]
[('tap', 'low')]
```

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]]

### openloops.tasks.classify(candidates, \*, classifier=<function heuristic_classify>)

One normalised record per candidate, through `classifier`.

```pycon
>>> classify([{'url': 'https://github.com/a/b/issues/1', 'title': 'Decide the name'}])[0]['tier']
'tap'
```

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]]

### openloops.tasks.gather(\*, owners=None, exclude_owners=(), exclude_repos=None, label='manual-task', searches=(), review_prs=False, limit=1000, timeout=30.0, run_gh=None, rate_limit_retries=2, rate_limit_backoff=65.0, sleep=<built-in function sleep>)

Every open item that asks something of the human, across `owners`, deduplicated.

One query per owner and per kind: the `label` (`manual-task`), each named
search in `searches` (keys of [`DFLT_SEARCHES`](_autosummary/openloops.tasks.html.md#openloops.tasks.DFLT_SEARCHES)), and with `review_prs` the
open PRs requesting your review. `owners` defaults to
[`openloops.obligations.configured_owners()`](_autosummary/openloops.obligations.html.md#openloops.obligations.configured_owners); `exclude_repos` (owner/name
globs) defaults to `OPENLOOPS_EXCLUDE_REPOS`. `run_gh` replaces the `gh`
runner (`run_gh(args, timeout=...) -> stdout`).

The result is an envelope: `listed` is `False` with an `error` when any query
failed, because a partial sweep presented as a whole one is the failure that
matters. `saturated` names the queries that hit `limit`.

A query GitHub refuses for the search rate limit (30 a minute) waits
`rate_limit_backoff` seconds and is retried up to `rate_limit_retries` times
before it counts as failed, so a many-owner sweep completes in one call.

```pycon
>>> def fake(args, *, timeout):
...     return json.dumps([{'number': 1, 'title': 'Add a key',
...         'url': 'https://github.com/acme/w/issues/1',
...         'repository': {'nameWithOwner': 'acme/w'}, 'labels': [], 'body': ''}])
>>> report = gather(owners=['acme'], run_gh=fake)
>>> report['listed'], [c['id'] for c in report['candidates']]
(True, ['acme/w#1'])
```

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]

### openloops.tasks.github_settings_url(repo, section)

A repository settings page (a key of `GITHUB_SETTINGS`).

```pycon
>>> github_settings_url('acme/widget', 'pages')
'https://github.com/acme/widget/settings/pages'
```

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### openloops.tasks.heuristic_classify(candidate, , rules=(('mac-only', 'mac-only', 10, '\\\\b(macos|mac app|keychain|xcode|launchd|on the mac)\\\\b'), ('npm-first-publish', 'session', 10, 'npm.\*(first publish|not (yet )?on npm|does not exist)|first publish.\*npm'), ('npm-trusted-publisher', 'browser', 3, 'npm.\*trusted publish|trusted publish.\*npm'), ('npm-scope', 'browser', 3, 'npm (org|scope)|claim .\*scope'), ('pypi-trusted-publisher', 'browser', 3, 'pypi.\*(trusted|pending) publish|(trusted|pending) publish.\*pypi'), ('pypi-release', 'session', 5, 'pypi.\*(release|upload)|(release|upload).\*pypi'), ('decision', 'tap', 2, '\\\\A\\\\s\*(decision|decide|confirm|should|reopen|choose|pick)\\\\b|\\\\A[^\\\\n]\*\\\\?|\\\\A[^\\\\n]\*\\\\bdecide\\\\b'), ('github-settings', 'browser', 3, '\\\\b(secret|deploy key|github pages|environment|actions settings|repo(sitory)? settings)\\\\b'), ('api-key', 'browser', 5, '\\\\b(api key|api token|access token|create (an )?account|sign up)\\\\b'), ('purchase', 'browser', 5, '\\\\b(purchase|buy|paid plan|subscription|invoice|billing)\\\\b'), ('record', 'physical', 15, '\\\\brecord (yourself|a|an|audio|video|your)\\\\b|\\\\bvoice sample\\\\b'), ('device-test', 'physical', 10, '\\\\b(on (a|your) (phone|device)|test on (ios|android|a device))\\\\b'), ('listen-look', 'physical', 10, '\\\\b(listen to|look at|judge|eyeball)\\\\b'), ('live-check', 'session', 5, '\\\\blive (check|test|run)\\\\b|\\\\breal (api )?key\\\\b'), ('server-chore', 'session', 5, '\\\\b(deploy|install|ssh|sudo|server|cron|systemd)\\\\b'), ('decision', 'tap', 2, '\\\\b(go-ahead|which option|options?:|recommend(ation|ed)?:?\\\\\*\\\\\*)')), machines=None)

A task record from a gathered candidate, by patterns alone. No model, no network.

`rules` are tried in order against the title and body; `machines` maps an owner
to the machine its session-tier prompts name. Status is always `open`: whether an
ask was already done is a judgement only a reader of the thread can make (the
classifier brief’s job).

```pycon
>>> pr = {'url': 'https://github.com/acme/w/pull/3', 'repo': 'acme/w',
...       'title': 'Bump lodash from 4.17.20 to 4.17.21', 'body': ''}
>>> heuristic_classify(pr)['pattern'], heuristic_classify(pr)['links'][0]['url']
('merge-bot-pr', 'https://github.com/acme/w/pull/3/files')
```

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]

### openloops.tasks.load_records(paths)

The records in JSON files (each a list, or an envelope with `candidates`).

Globs are expanded, in sorted order, so `out_*.json` reads a batch directory. A
glob that matches nothing raises: the batches a subagent failed to write must not
quietly turn into a board built from the heuristic alone.

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]]

### openloops.tasks.merge_records(\*sources)

Records from several sources, one per item, later sources winning.

Keyed by `id` (derived from the URL for a GitHub item, so the two sources agree);
a record with no id and no URL is dropped. A later record replaces the
earlier one whole, except that an empty `url` or `created` is filled from it:
the classifier brief reads threads, the gatherer knows dates; a `command` is kept
when the later record has no `command` key. A `review` is kept
when the later record has no `review` key and the same `decision`; a later
record with the key (even `null`) replaces it, and a changed decision drops it.

```pycon
>>> heuristic = [{'id': 'a/b#1', 'url': 'u1', 'tier': 'browser', 'created': '2026-01-02'}]
>>> enriched = [{'id': 'a/b#1', 'url': 'u1', 'tier': 'tap', 'ask': 'Say yes'}]
>>> [(r['tier'], r['ask'], r['created']) for r in merge_records(heuristic, enriched)]
[('tap', 'Say yes', '2026-01-02')]
>>> kept = [{'id': 'a/b#1', 'url': 'u1', 'review': {'disagreement_risk': 'low'}}]
>>> merge_records(kept, enriched)[0]['review']['disagreement_risk']
'low'
>>> newer = [{'id': 'a/b#1', 'url': 'u1', 'review': {'disagreement_risk': 'high'}}]
>>> merge_records(kept, newer)[0]['review']['disagreement_risk']
'high'
```

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]]

### openloops.tasks.npm_access_url(package)

npm package settings: trusted publisher, publishing access, 2FA requirement.

```pycon
>>> npm_access_url('@acme/widget')
'https://www.npmjs.com/package/@acme/widget/access'
```

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### openloops.tasks.pypi_publishing_url(project=None)

PyPI trusted publishers: a project’s page, or the pending-publisher page.

```pycon
>>> pypi_publishing_url()
'https://pypi.org/manage/account/publishing/'
```

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)


# _autosummary/openloops.tools.html.md

# openloops.tools

The package’s single list of operations: plain functions, JSON-ready dicts.

Every surface openloops has or might grow — the `ol` command today, an MCP server or
an HTTP endpoint later — dispatches from this module and nothing else. The functions
here know nothing about argument parsers, transports or agent hosts; they take flat
serialisable arguments and return flat serialisable results, and printing is somebody
else’s job.

Keeping one list is what stops two surfaces from drifting apart. A parity test between
two surfaces is a sign that there are two implementations, and there is one here.

### Module Attributes

| [`ROW_FIELDS`](_autosummary/openloops.tools.html.md#openloops.tools.ROW_FIELDS)   | The keys every [`ls()`](_autosummary/openloops.tools.html.md#openloops.tools.ls) row carries, whatever the digest happens to record.   |
|---------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------|

### Functions

| [`sync`](_autosummary/openloops.tools.html.md#openloops.tools.sync)(\*[, source, since_days, force, ...])         | Read what changed in the sessions and write the digests.                                                                                |
|-----------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------|
| [`ls`](_autosummary/openloops.tools.html.md#openloops.tools.ls)(\*[, state, source, project, confidence, ...])  | The digests in the store, newest last-turn first.                                                                                       |
| [`show`](_autosummary/openloops.tools.html.md#openloops.tools.show)(session, \*[, source, digests_store])         | One digest in full, found by session id or by a unique prefix of one.                                                                   |
| [`status`](_autosummary/openloops.tools.html.md#openloops.tools.status)(\*[, source, since_days, ...])              | Where everything is, how much of it there is, and how stale the cache is.                                                               |
| [`owed`](_autosummary/openloops.tools.html.md#openloops.tools.owed)(\*[, verify, owners, trusted_owners, ...])    | What you still owe your agents, with each obligation re-checked against the world.                                                      |
| [`blocked`](_autosummary/openloops.tools.html.md#openloops.tools.blocked)(\*[, resolve, owners, repos, query, ...])  | What your repositories are waiting on — and what is no longer waiting.                                                                  |
| [`dashboard`](_autosummary/openloops.tools.html.md#openloops.tools.dashboard)(\*[, verify, resolve, owners, ...])      | All three answers as one self-contained HTML page, for looking at rather than reading.                                                  |
| [`published`](_autosummary/openloops.tools.html.md#openloops.tools.published)(\*[, limit, session, source])            | What your agents handed you lately: recently published annals documents, per session.                                                   |
| [`board_gather`](_autosummary/openloops.tools.html.md#openloops.tools.board_gather)(\*[, owners, exclude_owners, ...])    | Every open item that asks something of you, across owners: the board's input.                                                           |
| [`board_classify`](_autosummary/openloops.tools.html.md#openloops.tools.board_classify)(\*, candidates[, enriched, out])    | Task records: the heuristic classifier over gathered candidates, overlaid by richer ones.                                               |
| [`board_build`](_autosummary/openloops.tools.html.md#openloops.tools.board_build)(\*, records, out_dir[, ...])           | Write the phone task board (page, `tasks.json`, `runs.json`) into `out_dir`.                                                            |
| [`remind`](_autosummary/openloops.tools.html.md#openloops.tools.remind)(title, \*[, when, due, reveal, ...])        | Make a loop that comes back at `when` and push it to the phone then.                                                                    |
| [`loops`](_autosummary/openloops.tools.html.md#openloops.tools.loops)(\*[, state])                                 | The loops, soonest first.                                                                                                               |
| [`done`](_autosummary/openloops.tools.html.md#openloops.tools.done)(ref, \*[, note, only_source])                 | Close a loop (by id or a unique prefix) as done, cancelling its scheduled push.                                                         |
| [`snooze`](_autosummary/openloops.tools.html.md#openloops.tools.snooze)(ref, \*, when[, only_source, max_days])     | Bring a loop back at `when` (a duration or a time, as for [`remind()`](_autosummary/openloops.tools.html.md#openloops.tools.remind)); re-arms its push. |
| [`until_done`](_autosummary/openloops.tools.html.md#openloops.tools.until_done)(ref, \*[, issue])                       | Make open loop `ref` come back until it is done or `issue` closes.                                                                      |
| [`remind_tick`](_autosummary/openloops.tools.html.md#openloops.tools.remind_tick)()                                      | Arm loops that came within three days, record those that fired, deliver late any missed one.                                            |
| [`method`](_autosummary/openloops.tools.html.md#openloops.tools.method)()                                           | The organising method in use: its name, places (lists), inbox, clarify questions and engage criteria.                                   |
| [`clarify`](_autosummary/openloops.tools.html.md#openloops.tools.clarify)(answers)                                   | Where the method sends an item, given `answers` to its questions ({key: answer}).                                                       |
| [`organise`](_autosummary/openloops.tools.html.md#openloops.tools.organise)(ref, place, \*[, project, contexts, ...]) | Move loop `ref` to `place` (one of the method's lists), setting what is given.                                                          |
| [`review`](_autosummary/openloops.tools.html.md#openloops.tools.review)()                                           | The review packet: only the loops that need a decision, in the method's sections.                                                       |
| [`engage`](_autosummary/openloops.tools.html.md#openloops.tools.engage)(\*[, context, minutes, energy, limit])      | What to do now: the method's best candidates (GTD: for this context, time and energy).                                                  |
| [`capture`](_autosummary/openloops.tools.html.md#openloops.tools.capture)(title, \*[, by, source, quote])            | Capture an item for the owner as a proposal on the method's inbox (GTD: In).                                                            |
| [`cancel`](_autosummary/openloops.tools.html.md#openloops.tools.cancel)(ref, \*[, note, by, only_source])           | Withdraw a loop (GTD's trash: not done, no longer wanted), cancelling its scheduled push.                                               |
| [`page`](_autosummary/openloops.tools.html.md#openloops.tools.page)(session, \*[, focus, out, ...])               | One session rendered as a single page (ADR-016): read here, written only to `out`.                                                      |
| [`who_made`](_autosummary/openloops.tools.html.md#openloops.tools.who_made)(target, \*[, source, limit, ...])         | The sessions that made, pushed or mentioned a pull request or branch, likeliest first.                                                  |

### openloops.tools.ROW_FIELDS *= ('session', 'source', 'state', 'title', 'ai_title', 'project', 'branches', 'started', 'ended', 'last_turn', 'turns', 'model', 'confidence', 'verified')*

The keys every [`ls()`](_autosummary/openloops.tools.html.md#openloops.tools.ls) row carries, whatever the digest happens to record.

### openloops.tools.blocked(, resolve=True, owners=None, repos=None, query='is:blocked', limit=50, timeout=30.0, issues_source=None, blockers_source=None)

What your repositories are waiting on — and what is no longer waiting.

The sibling of [`owed()`](_autosummary/openloops.tools.html.md#openloops.tools.owed): an obligation points at a person, a blocker edge
points at another repository, and both are commitments nothing is watching. Lists
the open issues carrying a `blocked_by` dependency across `owners` (or exactly
the `repos` you name), resolves every edge, and reports three states:
`unblocked` (every blocker closed — the work is free and nobody has been told),
`blocked` (naming the foreign repository it waits on) and `unknown` (nothing
could be resolved). Nothing is ever closed, relabelled or written; see
[`openloops.blockers`](_autosummary/openloops.blockers.html.md#module-openloops.blockers) for what discovery costs and what it is measured to miss.

The result is an envelope rather than a list, because `listed=False` — discovery
itself failed — must not be readable as “nothing is waiting”.

```pycon
>>> report = blocked(issues_source=[], blockers_source={})
>>> report['listed'], report['counts']['total']
(True, 0)
```

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]

### openloops.tools.board_build(, records, out_dir, candidates=None, reviews=None, run_specs=None, run_extras=None, title='Phone Task Board', session=None, read_only_orgs=None, machine=None, store='artifact', api=None, moved_to=None, links=None)

Write the phone task board (page, `tasks.json`, `runs.json`) into `out_dir`.

`records` are task-record JSON files (globs allowed); `candidates` supply the
creation dates; `reviews` are `{id, review}` record files (globs allowed) that
set only each matching record’s `review`; `run_specs` replaces the packaged run specs and `run_extras` (a
JSON object keyed by run) overlays deployment-specific prompts and tables. Writes
only into `out_dir`; publishing and the receiving side are the skill’s job.
`store='http'` with `api` wires the page to a self-hosted board store API
instead of the claude.ai Artifact store; `moved_to` builds a forwarding page.
`links` is a JSON file of name-and-address pairs shown as a row in the page’s
header (and kept in `board.json`); without it the page is unchanged.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]

### openloops.tools.board_classify(, candidates, enriched=None, out=None)

Task records: the heuristic classifier over gathered candidates, overlaid by richer ones.

`candidates` are JSON files from [`board_gather()`](_autosummary/openloops.tools.html.md#openloops.tools.board_gather); `enriched` are record
files written by the classifier brief (globs allowed), which win over the heuristic
record for the same item. `out` writes the merged records there.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]

### openloops.tools.board_gather(, owners=None, exclude_owners=None, exclude_repos=None, label='manual-task', searches=None, review_prs=False, limit=1000, timeout=30.0, out=None, run_gh=None)

Every open item that asks something of you, across owners: the board’s input.

Sweeps the `label` (`manual-task`) per owner with no 50-row cap, plus the named
`searches` (`decide`, `needs-user`, `agent-decided`) and, with `review_prs`, the PRs waiting
on your review. `out` also writes the envelope there as JSON. Read-only.

```pycon
>>> board_gather(owners=['acme'], run_gh=lambda args, *, timeout: '[]')['listed']
True
```

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]

### openloops.tools.cancel(ref, , note=None, by=None, only_source=None)

Withdraw a loop (GTD’s trash: not done, no longer wanted), cancelling its scheduled push.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]

### openloops.tools.capture(title, , by=None, source=None, quote=None)

Capture an item for the owner as a proposal on the method’s inbox (GTD: In). Never pushed.

`source` is where it came from (a URL or a session name), `quote` the owner’s
words. It stays a proposal until the owner accepts it (`organise --accept`).

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]

### openloops.tools.clarify(answers)

Where the method sends an item, given `answers` to its questions ({key: answer}).

Pure: nothing is stored. Returns `{place, changes, do_now, close, why}`; apply it
with [`organise()`](_autosummary/openloops.tools.html.md#openloops.tools.organise), or [`cancel()`](_autosummary/openloops.tools.html.md#openloops.tools.cancel) when `close` is `canceled` (trash).

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]

### openloops.tools.dashboard(, verify=True, resolve=True, owners=None, repos=None, limit=1000, candidate_limit=50, max_sessions=40, title='Open Loops Board', standalone=True, path=None, made_at=None, owed_report=None, blocked_report=None, sessions=None, digests_store=None, published_report=None, published_limit=50)

All three answers as one self-contained HTML page, for looking at rather than reading.

Runs [`owed()`](_autosummary/openloops.tools.html.md#openloops.tools.owed), [`blocked()`](_autosummary/openloops.tools.html.md#openloops.tools.blocked) and [`ls()`](_autosummary/openloops.tools.html.md#openloops.tools.ls), then renders
[`openloops.dashboard.render_dashboard()`](_autosummary/openloops.dashboard.html.md#openloops.dashboard.render_dashboard) over what they returned. The page is a
**snapshot**: it stamps the moment it was made and states, in its largest type, that
it has checked nothing since — because a published page cannot. Nothing is written
to GitHub, here or anywhere in openloops.

`path` also writes the page there, scrubbed, and reports where it went.
`standalone=False` returns the same page without the document scaffold, for a host
that supplies its own `<head>`.

Each read is a seam: pass `owed_report=`, `blocked_report=`, `sessions=` or
`published_report=` and that one is not performed. With all four passed this
reaches no network and needs no `gh` or `annals`, which is how the tests run.
The “Handed to you” register (recent annals documents per session) comes from
[`published()`](_autosummary/openloops.tools.html.md#openloops.tools.published); pass `published_report=False` to leave it off the page.

`counts` comes back alongside the page and carries `null` — not `0` — for any
figure that could not be established, so a caller reading the JSON is held to the
same three-state rule as a reader looking at the page.

```pycon
>>> result = dashboard(owed_report={'listed': True, 'counts': {'open': 0}, 'rows': []},
...                    blocked_report={'listed': False, 'error': 'no gh'},
...                    sessions=[], made_at='2026-01-01T00:00:00Z')
>>> result['counts']['free_to_proceed'] is None, result['counts']['unknown'] is None
(True, True)
```

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]

### openloops.tools.done(ref, , note=None, only_source=None)

Close a loop (by id or a unique prefix) as done, cancelling its scheduled push.

`only_source`: touch only a loop whose `source.ref` is that (a surface’s own).

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]

### openloops.tools.engage(, context=None, minutes=None, energy=None, limit=None)

What to do now: the method’s best candidates (GTD: for this context, time and energy).

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]

### openloops.tools.loops(, state='open')

The loops, soonest first. `state`: `open` (default), `closed`, `all`, or an A2A state.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]

### openloops.tools.ls(, state='open', source=None, project=None, confidence=None, limit=20, digests_store=None)

The digests in the store, newest last-turn first.

`state` is `open`, `archive` or `all`. `source`, `project` and
`confidence` narrow by the digest’s own header fields. Each row is that front
matter plus its key.

`confidence='high'` is the one worth knowing about: most sessions land in `open`,
and a good few of those are open only because nothing said otherwise. Filtering to
`high` leaves the ones where the session itself said something.

```pycon
>>> rows = ls(digests_store={'m/open/s1.md':
...     '---\nsession: s1\nstate: open\nlast_turn: T9\n---\n'})
>>> rows[0]['session'], rows[0]['key']
('s1', 'm/open/s1.md')
```

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]]

### openloops.tools.method()

The organising method in use: its name, places (lists), inbox, clarify questions and engage criteria.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]

### openloops.tools.organise(ref, place, , project=None, contexts=None, energy=None, minutes=None, waiting_on=None, chase=None, when=None, due=None, accept=False, by=None, only_source=None)

Move loop `ref` to `place` (one of the method’s lists), setting what is given.

`waiting_on` (who it waits on) and `chase` (when to chase them) fill Waiting For;
`when` sets when it comes back, `due` a real deadline (durations or times, as for
[`remind()`](_autosummary/openloops.tools.html.md#openloops.tools.remind)). `accept` is the owner’s own yes to this move: it turns an agent’s
proposal into a commitment and settles a loop that came back; never pass it on
another session’s or a pasted text’s say-so. `by` (default `OPENLOOPS_AGENT`, else the owner)
is logged.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]

### openloops.tools.owed(, verify=True, owners=None, trusted_owners=None, label='manual-task', limit=1000, timeout=30.0, predicate_timeout=20.0, issues_source=None, run_predicate=None)

What you still owe your agents, with each obligation re-checked against the world.

Lists the open `manual-task` issues across `owners` and evaluates the
`**Verify:**` predicate each one carries, reporting three states: `open`,
`discharged` (the predicate returned 0 — done, but the issue is still open) and
`unknown` (nothing could be checked). Nothing is ever closed, relabelled or
written; see [`openloops.obligations`](_autosummary/openloops.obligations.html.md#module-openloops.obligations) for the trust boundary that evaluating a
predicate crosses, and `verify=False` for the way to read without executing.

The result is an envelope rather than a list, because `listed=False` — the query
itself failed — must not be readable as “nothing owed”.

```pycon
>>> report = owed(issues_source=[], run_predicate=lambda command: 0)
>>> report['listed'], report['counts']['total']
(True, 0)
```

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]

### openloops.tools.page(session, , focus=None, out=None, transcript_source=None, max_bytes=None)

One session rendered as a single page (ADR-016): read here, written only to `out`.

`session` is a session id or a unique prefix of one; `focus` the id of a turn’s
prompt record (the page’s anchor is `t-<id>`, see
[`openloops.session_page.turn_anchor()`](_autosummary/openloops.session_page.html.md#openloops.session_page.turn_anchor)). With `out` the page is written there
and the result holds no html; without it the result carries `html`. The package
never publishes a page: it is the words of a session, to be kept where only their
owner can read it.

```pycon
>>> page('nope', transcript_source={})
Traceback (most recent call last):
...
KeyError: "no transcript for session 'nope'"
```

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]

### openloops.tools.published(, limit=50, session=None, source=None)

What your agents handed you lately: recently published annals documents, per session.

The sibling of [`owed()`](_autosummary/openloops.tools.html.md#openloops.tools.owed), read from the documents sessions published with
`annals publish --session <name>`. Nothing is written. `source` is the seam: the
documents themselves, or a callable returning them; by default `annals ls` is run,
and when annals is absent the result says `listed=False` rather than listing nothing.

```pycon
>>> published(source=[])['listed']
True
```

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]

### openloops.tools.remind(title, , when=None, due=None, reveal=False, source=None, daily_cap=None, place=None, waiting_on=None, until_done=False, issue=None)

Make a loop that comes back at `when` and push it to the phone then.

`until_done` (or `issue`, `owner/repo#N`) makes it come back after each push,
daily at that time of day, every 3 days after a week, until `ol done` drops it or
the issue is closed; without `when` it first comes at the owner’s morning time.

`when` is a duration (`20m`, `3h`, `2d`) or a time (`15:30`, an ISO date or
date-time; naive means the owner’s zone). Within three days it is scheduled on ntfy at
once, so it fires even if this machine sleeps. Without `when` the loop is only
listed. `reveal` lets the title travel in the push (ntfy.sh is a public relay: short
labels only). `source` is where the ask came from (a URL or a session name). The
result’s `echo` is the line to repeat to the owner. `place` files it on one of
the organising method’s lists (GTD: `next` by default, or `someday`, `waiting`…;
see [`method()`](_autosummary/openloops.tools.html.md#openloops.tools.method)); on `waiting`, `waiting_on` says on whom.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]

### openloops.tools.remind_tick()

Arm loops that came within three days, record those that fired, deliver late any missed one.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]

### openloops.tools.review()

The review packet: only the loops that need a decision, in the method’s sections.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]

### openloops.tools.show(session, , source=None, digests_store=None)

One digest in full, found by session id or by a unique prefix of one.

An exact id always wins over a prefix, so a session whose id happens to be a prefix
of another stays reachable. `source` narrows a store that several machines write
into, where the same session can legitimately appear more than once.

```pycon
>>> store = {'m/open/abcdef.md': '---\nsession: abcdef\n---\nbody'}
>>> show('abc', digests_store=store)['key']
'm/open/abcdef.md'
```

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]

### openloops.tools.snooze(ref, , when, only_source=None, max_days=None)

Bring a loop back at `when` (a duration or a time, as for [`remind()`](_autosummary/openloops.tools.html.md#openloops.tools.remind)); re-arms its push.

`only_source` as for [`done()`](_autosummary/openloops.tools.html.md#openloops.tools.done); `max_days` refuses a time further ahead than that.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]

### openloops.tools.status(, source=None, since_days=None, digests_store=None, transcript_source=None)

Where everything is, how much of it there is, and how stale the cache is.

Reports the cache’s age because a read served from a cache that nothing has
refreshed is the failure openloops is built to avoid — a periodic job that died
leaves a confident, months-old answer behind, and the only defence is saying how
old the answer is.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]

### openloops.tools.sync(, source=None, since_days=None, force=False, transcript_source=None, digests_store=None, state_dir=None)

Read what changed in the sessions and write the digests. Returns a summary.

`since_days` bounds the scan to recently-modified transcripts; `force`
re-derives everything, which must produce an identical store.

`state_dir` scopes the change-detection cache. It matters because the seams do
not isolate on their own: swapping `transcript_source` for a fixture and leaving
the cache alone writes the fixture’s revisions into the caller’s real one.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]

### openloops.tools.until_done(ref, , issue=None)

Make open loop `ref` come back until it is done or `issue` closes.

Its next push keeps its time; after each push it re-arms (daily at that time of day,
every 3 days after a week), the push counting how often it has asked. `ol done REF`
drops it.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]

### openloops.tools.who_made(target, , source=None, limit=10, provenance_store=None, digests_store=None)

The sessions that made, pushed or mentioned a pull request or branch, likeliest first.

`target` is a PR URL, `owner/repo#N`, or a branch name. Each row adds the
session’s digest title when there is one, so the answer reads without a second call.
Reads no transcript: the index is what `ol sync` wrote.

```pycon
>>> prov = {'m/s1.json': '{"session": "s1", "source": "m", "refs": '
...         '[{"kind": "pr", "ref": "o/r#7", "role": "created", "at": "T", "cwd": ""}]}'}
>>> [r['session'] for r in who_made('o/r#7', provenance_store=prov, digests_store={})]
['s1']
```

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]]


# _autosummary/openloops.transcripts.html.md

# openloops.transcripts

The default `transcript_source`: a direct reader of Claude Code’s on-disk state.

Claude Code persists one JSONL transcript per session under
`~/.claude/projects/<encoded-cwd>/<session-uuid>.jsonl`. [`ClaudeCodeTranscripts`](_autosummary/openloops.transcripts.html.md#openloops.transcripts.ClaudeCodeTranscripts)
is a `Mapping` from session id to [`Session`](_autosummary/openloops.base.html.md#openloops.base.Session), so a caller who
wants a different reader — a test fixture, a copy synced from another machine, an
in-house parser — passes any mapping of the same shape and nothing downstream changes.

Two things this reader deliberately does not do.

It never reverses a project directory name back into a working directory. The encoding
is lossy (`/`, `_` and `.` all become `-`), so `cwd` is read from the records
themselves or left empty.

It never looks at whether a process is running. A session’s transcript is a document;
what openloops reports is what the document says. Liveness is a different tool’s job,
and mixing the two is how a digest store becomes a session dashboard. That tool is
[crowsnest](https://github.com/thorwhalen/crowsnest), which reads the session registry
and the tail of these same transcripts to say who is busy, idle or waiting on you.

```pycon
>>> src = ClaudeCodeTranscripts(root='/nonexistent-dir-for-doctest')
>>> len(src)
0
>>> src.revision()
'0'
```

### Functions

| [`claude_projects_dir`](_autosummary/openloops.transcripts.html.md#openloops.transcripts.claude_projects_dir)([root])       | Where Claude Code keeps per-session transcripts.                                                                      |
|------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------------|
| [`parse_session`](_autosummary/openloops.transcripts.html.md#openloops.transcripts.parse_session)(records, \*[, key]) | Read one transcript's records into a [`Session`](_autosummary/openloops.base.html.md#openloops.base.Session). |

### Classes

| [`ClaudeCodeTranscripts`](_autosummary/openloops.transcripts.html.md#openloops.transcripts.ClaudeCodeTranscripts)([root, since_days, ...])   | Claude Code's persisted sessions, as a `Mapping[str, Session]`.         |
|---------------------------------------------------------------------------------------------------|-------------------------------------------------------------------------|
| [`Revisioned`](_autosummary/openloops.transcripts.html.md#openloops.transcripts.Revisioned)(source)                               | Give any mapping of sessions a total `revision` / `changed_since` pair. |

### *class* openloops.transcripts.ClaudeCodeTranscripts(root=None, , since_days=None, projects=None, skip_scratchpads=True)

Bases: [`Mapping`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Mapping)

Claude Code’s persisted sessions, as a `Mapping[str, Session]`.

`since_days` bounds the scan by file modification time (`None` scans
everything); `projects` keeps only project directories whose name contains one of
the given substrings; `skip_scratchpads` drops the throwaway directories the CLI
creates under a temp root, which hold agent scratch sessions rather than work.

ADR-010’s revision shape lives here: [`revision()`](_autosummary/openloops.transcripts.html.md#openloops.transcripts.ClaudeCodeTranscripts.revision) returns an opaque token —
a file’s modification time for one session, a hash over all of them for the
collection — and [`changed_since()`](_autosummary/openloops.transcripts.html.md#openloops.transcripts.ClaudeCodeTranscripts.changed_since) compares against it. mtime is a coarse
signal that both misses content-preserving rewrites and fires on touches; that
trade is accepted rather than reprocessing several thousand transcripts a tick.

```pycon
>>> src = ClaudeCodeTranscripts(root='/nonexistent-dir-for-doctest')
>>> list(src), src.changed_since('0')
([], False)
```

#### changed_since(token, key=None)

Whether the current [`revision()`](_autosummary/openloops.transcripts.html.md#openloops.transcripts.ClaudeCodeTranscripts.revision) differs from *token*.

* **Return type:**
  [`bool`](https://docs.python.org/3/builtins/functions.html#bool)

#### path_of(key)

The transcript file backing *key*.

* **Return type:**
  [`Path`](https://docs.python.org/3/library/pathlib.html#pathlib.Path)

#### refresh()

Forget the cached index; the next access walks the projects tree again.

The index is a snapshot, built once per pass: iterating (or `len`) starts a
new pass and refreshes it, while `in`, `[]`, [`revision()`](_autosummary/openloops.transcripts.html.md#openloops.transcripts.ClaudeCodeTranscripts.revision) and
[`path_of()`](_autosummary/openloops.transcripts.html.md#openloops.transcripts.ClaudeCodeTranscripts.path_of) read the snapshot rather than walking the tree per key (issue
#33: that made one `sync` cost a full directory walk per session). Call this
to see transcripts written since the snapshot without iterating.

* **Return type:**
  [`None`](https://docs.python.org/3/builtins/constants.html#None)

#### revision(key=None)

An opaque change token: for one session, or for the whole collection.

For a single key it is the transcript’s modification time in nanoseconds. For
the collection it is a hash over every `(key, mtime)` pair, so a token can
be compared without holding the whole index.

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

#### scratchpad_marker *= '-private-tmp'*

Project-directory names starting with this are scratchpads, not work.

### *class* openloops.transcripts.Revisioned(source)

Bases: [`Mapping`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Mapping)

Give any mapping of sessions a total `revision` / `changed_since` pair.

ADR-010’s rule is that no caller may branch on whether a backend happens to
implement change detection — capability probing is backend leakage by another name.
So the probe happens exactly once, here, at the boundary: a wrapped source that
supplies its own cheap revision token keeps it, and one that does not gets a total
default (a hash of the value). `sync()` therefore always has
the methods and never asks.

The default is honest rather than fast: hashing requires loading the session, so a
source with no cheap token gains correctness and no speed. That is the right way
round — a plain `dict` of sessions in a test costs nothing to hash, and the
on-disk reader supplies mtime.

```pycon
>>> from openloops.base import Session
>>> src = Revisioned({'a': Session(key='a')})
>>> src.revision('a') == Revisioned({'a': Session(key='a')}).revision('a')
True
>>> src.changed_since(src.revision('a'), 'a')
False
```

#### changed_since(token, key=None)

Whether the current [`revision()`](_autosummary/openloops.transcripts.html.md#openloops.transcripts.Revisioned.revision) differs from *token*.

* **Return type:**
  [`bool`](https://docs.python.org/3/builtins/functions.html#bool)

#### revision(key=None)

An opaque token that changes when the underlying session changes.

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### openloops.transcripts.claude_projects_dir(root=None)

Where Claude Code keeps per-session transcripts.

Resolution order: the *root* argument, then `CLAUDE_PROJECTS_DIR`, then
`~/.claude/projects`.

```pycon
>>> claude_projects_dir('/tmp/x').name
'x'
```

* **Return type:**
  [`Path`](https://docs.python.org/3/library/pathlib.html#pathlib.Path)

### openloops.transcripts.parse_session(records, , key='')

Read one transcript’s records into a [`Session`](_autosummary/openloops.base.html.md#openloops.base.Session).

Pure: same records in, same session out. Everything it reports is a fact about the
document — no inference, no judgement, and nothing about running processes.

Three details are corpus-driven rather than obvious, and getting them wrong
mislabels a large fraction of real sessions:

- \*\*Start and end come from `min`/`max` over every timestamp\*\*, not from the
  first and last line. Transcript lines are not written in timestamp order; on real
  data the first line holds the earliest timestamp only about four times in five.
- \*\*The project comes from the *first* record’s `cwd`.\*\* Four sessions in five
  visit more than one working directory (scratchpads, sibling repos, task dirs), and
  the last or most-frequent one names a different repository about half the time.
- **Branches are a tuple.** A third of sessions touch more than one.

```pycon
>>> recs = [
...     {"type": "user", "sessionId": "s1", "cwd": "/w/proj", "timestamp": "T1",
...      "gitBranch": "main",
...      "message": {"role": "user", "content": [{"type": "text", "text": "do it"}]}},
...     {"type": "assistant", "sessionId": "s1", "timestamp": "T2",
...      "message": {"role": "assistant", "model": "m",
...                  "content": [{"type": "text", "text": "done"}]}},
... ]
>>> s = parse_session(recs)
>>> s.key, s.project, s.turn_count, s.last_assistant_text
('s1', 'proj', 1, 'done')
>>> s.started_at, s.ended_at, s.git_branch, s.ended_mid_turn
('T1', 'T2', 'main', False)
```

* **Return type:**
  [`Session`](_autosummary/openloops.base.html.md#openloops.base.Session)


# _autosummary/openloops.whenthen_job.html.md

# openloops.whenthen_job

Handing the periodic jobs to whenthen: register a job, take over from the launchd agent.

whenthen is the fleet’s scheduler (one clock, run records, `whenthen status`). Each job
this package used to install as a launchd agent (the digest sync, the reminder tick, the
pile nudge, the board receiver, the board refresh) can instead be a whenthen job; this
module is the one place that knows how. It is used when `python -m whenthen --help`
works under the interpreter openloops runs in, and never required: without it the
installers behave as before.

A job’s name is its launchd label with the dots turned into dashes
(`openloops.remind-tick` -> `openloops-remind-tick`), so the label still names it.

### Functions

| [`job_name`](_autosummary/openloops.whenthen_job.html.md#openloops.whenthen_job.job_name)(label)                              | The whenthen job for a launchd label.                                                   |
|-----------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------|
| [`every_flag`](_autosummary/openloops.whenthen_job.html.md#openloops.whenthen_job.every_flag)(seconds)                          | An interval as whenthen's `--every` value.                                              |
| [`whenthen`](_autosummary/openloops.whenthen_job.html.md#openloops.whenthen_job.whenthen)(\*args)                             | `python -m whenthen <args>` under this interpreter: `(exit code, parsed JSON or text)`. |
| [`available`](_autosummary/openloops.whenthen_job.html.md#openloops.whenthen_job.available)()                                  | Whether whenthen can be run under this interpreter (never a hard dependency).           |
| [`register`](_autosummary/openloops.whenthen_job.html.md#openloops.whenthen_job.register)(\*, label, intent_file, intent_key) | Add the job for `label` and stop its launchd agent (`take_over`).                       |
| [`status`](_autosummary/openloops.whenthen_job.html.md#openloops.whenthen_job.status)(label)                                | The whenthen job's state for `label`; `None` when whenthen or the job is absent.        |
| [`remove`](_autosummary/openloops.whenthen_job.html.md#openloops.whenthen_job.remove)(label)                                | Remove the whenthen job for `label` if there is one.                                    |

### openloops.whenthen_job.available()

Whether whenthen can be run under this interpreter (never a hard dependency).

* **Return type:**
  [`bool`](https://docs.python.org/3/builtins/functions.html#bool)

### openloops.whenthen_job.every_flag(seconds)

An interval as whenthen’s `--every` value.

```pycon
>>> every_flag(900), every_flag(21600), every_flag(60)
('15m', '6h', '1m')
```

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### openloops.whenthen_job.job_name(label)

The whenthen job for a launchd label.

```pycon
>>> job_name("openloops.remind-tick")
'openloops-remind-tick'
```

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### openloops.whenthen_job.register(, label, intent_file, intent_key, params=None, interval, env=None, cwd=None, env_file=None, timeout='30m', delay=None, source, quote='', take_over, restore, dry_run=False, run_once=False)

Add the job for `label` and stop its launchd agent (`take_over`).

Order: vocabulary entry, dry run, `take_over`, add. A failed add calls `restore`
(the old agent installed again) and raises. Returns `scheduler`, `job`, `echo`,
`interval` and, with `run_once`, `first_run` (its status).

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]

### openloops.whenthen_job.remove(label)

Remove the whenthen job for `label` if there is one. True when one was removed.

* **Return type:**
  [`bool`](https://docs.python.org/3/builtins/functions.html#bool)

### openloops.whenthen_job.status(label)

The whenthen job’s state for `label`; `None` when whenthen or the job is absent.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`object`](https://docs.python.org/3/builtins/functions.html#object)] | [`None`](https://docs.python.org/3/builtins/constants.html#None)

### openloops.whenthen_job.whenthen(\*args)

`python -m whenthen <args>` under this interpreter: `(exit code, parsed JSON or text)`.

* **Return type:**
  [`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[`int`](https://docs.python.org/3/builtins/functions.html#int), [`object`](https://docs.python.org/3/builtins/functions.html#object)]


# _autosummary/openloops.word_close.html.md

# openloops.word_close

Close one issue on the owner’s own word, relayed by an assistant (voice, a chat).

The owner says “close issue 207 in my private issues, not planned” to an assistant that
cannot be at his terminal. A close is reversible (reopen), but a wrong one is easy to miss:
an obligation drops out of `ol owed` and nobody notices. So every guard here is in code,
not in the assistant’s promise, and every close is visible afterwards.

For one issue per call, [`close_on_word()`](_autosummary/openloops.word_close.html.md#openloops.word_close.close_on_word) refuses unless all of these hold:

1. the repository is PRIVATE, has no outside collaborators (unreadable counts as shared),
   and its owner is a trusted one (`closer.owners`, [`openloops.closer.close_settings()`](_autosummary/openloops.closer.html.md#openloops.closer.close_settings));
2. the number is an open issue, not a pull request, filed under the person’s own login;
3. `expect_title` (a few words of the title the assistant read back) is in the title,
   compared without case, punctuation or extra spaces: a misheard number fails here;
4. fewer than `cap` closes were made this way today (UTC), counted in a local ledger;
5. a `manual-task` whose `**Verify:**` check does not pass is not closed as
   `completed` (`not planned` still is): a report alone never closes an owed task as
   done, as in [`openloops.closer`](_autosummary/openloops.closer.html.md#module-openloops.closer).

The close carries the owner’s comment (scrubbed of home paths and credentials, capped),
a fixed last line saying how it was closed, and the label `WORD_LABEL`, so
[`word_closes()`](_autosummary/openloops.word_close.html.md#openloops.word_close.word_closes) (`ol voice-log`) lists every one for a brief, with how to reopen it.

Seams: `gh=` (`(args, *, input=None) -> (status, stdout)`, the `gh` CLI by
default), `settings=` ([`CloseSettings`](_autosummary/openloops.closer.html.md#openloops.closer.CloseSettings)), `ledger=` (a JSONL
file under `~/.local/share/openloops/`), `run_check=`, `now=`.

### Functions

| [`close_on_word`](_autosummary/openloops.word_close.html.md#openloops.word_close.close_on_word)(repo, number, \*, reason, ...)   | Close issue *number* of *repo* if every guard in the module docstring holds.                                                                       |
|-------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------|
| [`split_ref`](_autosummary/openloops.word_close.html.md#openloops.word_close.split_ref)(ref)                                 | `(repo, number)` from `OWNER/REPO#NUMBER` only: a URL is refused, since `gh issue close <url>` would ignore the repository it was checked against. |
| [`default_ledger`](_autosummary/openloops.word_close.html.md#openloops.word_close.default_ledger)()                               | Where closes made this way are counted: `~/.local/share/openloops/word-closes.jsonl`.                                                              |
| [`title_matches`](_autosummary/openloops.word_close.html.md#openloops.word_close.title_matches)(expect, title)                   | Whether the words read back are in the title (case, punctuation, spacing ignored).                                                                 |
| [`word_closes`](_autosummary/openloops.word_close.html.md#openloops.word_close.word_closes)(\*[, owners, days, gh, now])       | Issues closed on the owner's word in the last *days*, newest first, from GitHub (the label is the record, so any machine can list them).           |

### openloops.word_close.close_on_word(repo, number, \*, reason, comment, expect_title, by='bosun', cap=5, gh=<function \_gh_cli>, settings=None, ledger=None, run_check=<function default_run_check>, now=None, dry_run=False)

Close issue *number* of *repo* if every guard in the module docstring holds.

Returns `{ref, action, reason, title, say}`: `action` is `closed`, `would-close`
(`dry_run`) or `refused`; `say` is one line to read back to the owner.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]

### openloops.word_close.default_ledger()

Where closes made this way are counted: `~/.local/share/openloops/word-closes.jsonl`.

* **Return type:**
  [`Path`](https://docs.python.org/3/library/pathlib.html#pathlib.Path)

### openloops.word_close.split_ref(ref)

`(repo, number)` from `OWNER/REPO#NUMBER` only: a URL is refused, since
`gh issue close <url>` would ignore the repository it was checked against.

```pycon
>>> split_ref('me/_private#207')
('me/_private', 207)
>>> split_ref('https://github.com/me/x/issues/1')
Traceback (most recent call last):
...
ValueError: not OWNER/REPO#NUMBER: 'https://github.com/me/x/issues/1'
```

* **Return type:**
  [`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`int`](https://docs.python.org/3/builtins/functions.html#int)]

### openloops.word_close.title_matches(expect, title)

Whether the words read back are in the title (case, punctuation, spacing ignored).

```pycon
>>> title_matches('Bosun: close #207', '[tp] Bosun -- close #207 now')
True
>>> title_matches('wrong issue', 'Bosun close 207')
False
```

* **Return type:**
  [`bool`](https://docs.python.org/3/builtins/functions.html#bool)

### openloops.word_close.word_closes(\*, owners=(), days=1, gh=<function \_gh_cli>, now=None)

Issues closed on the owner’s word in the last *days*, newest first, from GitHub
(the label is the record, so any machine can list them).

Each row: `{ref, title, closedAt, url, undo}` (`undo`: the command that reopens it).

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`Mapping`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Mapping)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]]


# about-this-build.html.md

<!-- generated by epythet -->

# About this build

This documentation was built on **2026-12-05 17:44 UTC** from commit <a href="https://github.com/addaix/openloops/commit/9bd66390e112947c9241b3e2908ab0dda2173703"><code>9bd6639</code></a> on branch <code>main</code>, for **openloops 0.1.84** (from <code>pyproject.toml</code>).

#### NOTE
Nothing suggests a mismatch: the tree was clean at the commit above, and the documented version is the one on PyPI.

## Source

|                     |                                                                                                                                                         |
|---------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------|
| Commit              | <a href="https://github.com/addaix/openloops/commit/9bd66390e112947c9241b3e2908ab0dda2173703"><code>9bd66390e112947c9241b3e2908ab0dda2173703</code></a> |
| Branch              | <code>main</code>                                                                                                                                       |
| Tags at this commit | none                                                                                                                                                    |
| Working tree        | clean                                                                                                                                                   |
| Remote              | <code>https://github.com/addaix/openloops</code>                                                                                                        |

## Continuous integration

|              |                                                                                            |
|--------------|--------------------------------------------------------------------------------------------|
| Repository   | <code>addaix/openloops</code>                                                              |
| Run          | <a href="https://github.com/addaix/openloops/actions/runs/47549397045">47549397045</a>     |
| Ref          | <code>refs/heads/main</code>                                                               |
| Event commit | <code>9bd66390e112947c9241b3e2908ab0dda2173703</code> (in the history of the built commit) |

## Tools

|          |         |
|----------|---------|
| epythet  | 0.2.26  |
| Sphinx   | 9.1.1   |
| docutils | 0.22.4  |
| Python   | 3.12.16 |

## Configuration as resolved

|               |                                                                   |
|---------------|-------------------------------------------------------------------|
| theme         | <code>auto</code> (Sphinx theme <code>pydata_sphinx_theme</code>) |
| accent        | <code>#006d67</code>                                              |
| api_generator | <code>autosummary</code>                                          |
| ignore        | <code>tests/</code>, <code>scrap/</code>, <code>examples/</code>  |
| agent_outputs | <code>true</code>                                                 |
| aggregates    | <code>md</code>                                                   |
| ai_artifacts  | <code>true</code>                                                 |

## Package on PyPI

Latest release: <a href="https://pypi.org/project/openloops/0.1.84/">0.1.84</a>, the same as the documented version.

## Reproduce

```bash
git clone https://github.com/addaix/openloops && cd openloops
git checkout 9bd66390e112947c9241b3e2908ab0dda2173703
pip install "epythet==0.2.26"
epythet quickstart . --ignore tests/ scrap/ examples/
```

The same data, for machines: <a href="build_info.json"><code>build_info.json</code></a> (schema version 1).


# ai-agents.html.md

<!-- generated by epythet -->

# For AI agents

`openloops` ships artifacts for coding agents alongside its code. This page lists
them, says where each lives in the repository, and points at the
machine-readable copies of this documentation.

## Skills

Skills are folders holding a `SKILL.md` (the [Agent Skills](https://agentskills.io) format): a description that tells an agent when to use it and a body with the procedure. Install one into your agent with `gh skill` (any host: `--agent claude-code`, `copilot`, `cursor`, `codex`, `gemini`), or use the copy bundled in the wheel.

### `openloops`

Answer “what is being done, and what needs my attention?” across every coding session and every repository, by running the `ol` command and synthesising its answers rather than pasting them. Use when the user asks what needs their attention, what their agents have been doing or left unfinished, what they missed while they were away, what they still owe an agent, what is blocked or waiting on another repo, or what quietly became unblocked and nobody noticed. Triggers on: ‘what needs my attention’, ‘anything waiting on me’, ‘catch me up’, ‘what did I miss’, ‘where are we’, ‘status across my sessions’, ‘what are my agents doing’, ‘what did my sessions leave open’, ‘what do I owe’, ‘what am I blocked on’, ‘what can I start now’, ‘give me the overview’, ‘morning briefing’, ‘what should I look at first’, ‘is anything stuck’. Also use before planning a day’s work, so the plan starts from what is outstanding rather than from memory. Read-only: it never closes, reopens or relabels anything.

```bash
gh skill install addaix/openloops openloops --agent claude-code
```

Source: [`openloops/data/skills/openloops`](https://github.com/addaix/openloops/tree/HEAD/openloops/data/skills/openloops) (bundled with the pip package).

### `openloops-needs-human`

Use the moment you are blocked on the human and cannot finish on your own: a secret or API key only they can set; a command only they can run (a deploy, a `sudo`, a step your permissions refuse); access you do not have; a purchase, an approval, a decision only they can make; or a RECORDED decision (an ADR, a convention, a default) that is now in your way or looks wrong. Files the blocker as a `manual-task` GitHub issue in the affected repo, with a shell predicate, so the obligation outlives the session and `ol owed` can re-check it. Triggers on: ‘I can’t do this without you’, ‘you’ll need to run this’, ‘this needs your credentials’, ‘blocked on’, ‘someone has to decide’, ‘I don’t have access to’, ‘the ADR says X but’, or any honest hand-back. File it BEFORE writing the hand-back message, not instead of it. Skip only when you could do it yourself. Before handing back a decision, load this to check whether you may decide it yourself and record it as an `agent-decided` issue.

```bash
gh skill install addaix/openloops openloops-needs-human --agent claude-code
```

Source: [`openloops/data/skills/openloops-needs-human`](https://github.com/addaix/openloops/tree/HEAD/openloops/data/skills/openloops-needs-human) (bundled with the pip package).

### `openloops-phone-board`

Build, publish and run a phone task board: every open item across the owner’s repositories that asks something of them (manual-task issues, ‘Decide…’ issues, PRs waiting on their review), classified by where they can do it (tap, browser, session, physical, mac-only), grouped into runs of repeated chores, published as a claude.ai Artifact they can act on from a phone, with a receiving Claude session that turns their taps into GitHub comments, closes and dispatched workers. Use when the owner will be away from their desk, on a phone, and wants to clear what they owe; when they ask for ‘a board’, ‘a phone task list’, ‘what can I do from my phone’, ‘turn my manual-tasks into something I can tap through’; or when an existing board needs rebuilding or its outbox processed (‘process the board’, ‘post my desk answers’). The `ol board-*` commands build it read-only; the write side is this skill’s procedure.

```bash
gh skill install addaix/openloops openloops-phone-board --agent claude-code
```

Source: [`openloops/data/skills/openloops-phone-board`](https://github.com/addaix/openloops/tree/HEAD/openloops/data/skills/openloops-phone-board) (bundled with the pip package).

### `openloops-pile`

The owner’s capture pile (one GitHub issue per thing they said to Siri, ‘Add to My Pile’, in a private pile repo): say what is on it, clarify each item into where it belongs (a loop via `ol remind`, an idea via `ideadump`, an issue in the repo that owns it, work handed to a session, or dropped with a reason), and take care of one item end to end. Proposes first, acts only on the owner’s yes, signs every comment with the agent’s name and session link. Use on ‘what’s on my pile’, ‘tell me about my pile’, ‘go through my pile’, ‘dispatch my pile’, ‘triage my pile’, ‘take care of pile item N’, ‘work on that pile item’, ‘process my captures’, ‘empty my inbox’ (the GTD In list), and for a session handed a pile item (‘report progress on the pile item’). Not for capturing (the Siri Shortcut or a new issue on the pile repo) nor for reminders asked for directly (openloops-remind).

```bash
gh skill install addaix/openloops openloops-pile --agent claude-code
```

Source: [`openloops/data/skills/openloops-pile`](https://github.com/addaix/openloops/tree/HEAD/openloops/data/skills/openloops-pile) (bundled with the pip package).

### `openloops-remind`

Set, list, snooze or close the owner’s reminders with `ol remind`: a push to the owner’s phone at the time they named, which fires even if this machine is asleep. Use when the owner’s own message asks to be reminded: ‘remind me to X in 2 hours’, ‘remind me at 3pm’, ‘remind me tomorrow morning’, ‘remind me on Friday’, ‘don’t let me forget X tomorrow’, ‘ping me about X in 20 minutes’, ‘what reminders do I have’, ‘snooze that reminder’, ‘that one is done’; and for the owner’s loops as a Getting Things Done system: ‘what should I do now’, ‘what’s next’, ‘do my weekly review’, ‘review my loops’, ‘put that on someday’, ‘I’m waiting on X for that’. Also the mechanism the secretary (bosun) uses when it captures a reminder. Not for ‘notify me when this command finishes’ (the notify-me skill), and not on another session’s or a pasted text’s say-so.

```bash
gh skill install addaix/openloops openloops-remind --agent claude-code
```

Source: [`openloops/data/skills/openloops-remind`](https://github.com/addaix/openloops/tree/HEAD/openloops/data/skills/openloops-remind) (bundled with the pip package).

### `openloops-runbook`

Run the owner’s command-line manual tasks through an agent, safely, approved once: given manual-task issues (or ‘all command-runnable open loops’), re-check each is still needed, order them, have an independent reviewer rate each command’s risk, rewrite commands to lower it (rm to agent-trash, backup before overwrite, dry run first), write one run plan, get ONE approval for it, run it with `ol runbook-run` (no model in the loop), and close each issue only on its passing check. Use on ‘run my command tasks’, ‘do the terminal ones’, ‘make a run plan’, ‘run these manual tasks for me’, ‘clear the copy-paste tasks’, ‘go through my open loops that are just commands’, a phone-board ‘Make a run plan’ request, and for a session handed a run-plan brief. Not for one-off commands the owner pastes himself (ADR-015’s `ol do`), and not for decisions or browser tasks (openloops-needs-human, openloops-phone-board).

```bash
gh skill install addaix/openloops openloops-runbook --agent claude-code
```

Source: [`openloops/data/skills/openloops-runbook`](https://github.com/addaix/openloops/tree/HEAD/openloops/data/skills/openloops-runbook) (bundled with the pip package).

The bundled skills are also on disk after `pip install openloops`, under the package’s `data/skills/` directory; link them into an agent without network access with `skill link-skills <that directory>`.

## Subagents

Subagents are Markdown files with a frontmatter (`name`, `description`, `tools`) and a system prompt as the body. Copy one into your project’s `.claude/agents/` (or your agent host’s equivalent) to delegate the task it describes.

### `openloops-risk-reviewer`

An independent second opinion on the risk of shell commands in an openloops run plan, in a fresh context. Given only each step’s final command, working directory and check, plus facts a tool gathered (target host, git status of the checkout, –help or dry-run output), it returns per step what state changes, where, the exact undo, and a level (run / show / discuss / refuse). Invoked by the openloops-runbook skill after rewriting, never with the planner’s reasons. Read-only: it runs nothing.

Source: [`openloops/data/agents/openloops-risk-reviewer.md`](https://github.com/addaix/openloops/tree/HEAD/openloops/data/agents/openloops-risk-reviewer.md); tools: `Read`.

### `openloops-sweep`

Runs the openloops sweep (`ol`, `ol owed`, `ol blocked`) in a fresh context and returns a short synthesis of what needs the user’s attention, what is now free to proceed, and what is in flight — never the raw command output. Invoke whenever the user asks what needs their attention, what their agents left open, what they owe, what is blocked or newly unblocked, or for a catch-up across their sessions. Read-only: it never closes, reopens, relabels or comments on anything.

Source: [`openloops/data/agents/openloops-sweep.md`](https://github.com/addaix/openloops/tree/HEAD/openloops/data/agents/openloops-sweep.md); tools: `Bash`.

## Instruction files

Files agents read before working in this repository.

- [`.claude/CLAUDE.md`](https://github.com/addaix/openloops/tree/HEAD/.claude/CLAUDE.md): read by Claude Code

## Machine-readable documentation

This site publishes the same documentation in forms that fit an agent’s context window:

- [`llms.txt`](https://addaix.github.io/openloops/llms.txt): an index of every page with a one-line description ([llms.txt](https://llmstxt.org) format)
- [`openloops.md`](https://addaix.github.io/openloops/openloops.md): the whole documentation as one Markdown file
- `<page>.html.md`: a rendered Markdown twin of every page, advertised from each page’s `<head>` with `<link rel="alternate" type="text/markdown">`
- [`objects.inv`](https://addaix.github.io/openloops/objects.inv): the Sphinx inventory: a symbol-to-URL index (`sphobjinv convert plain objects.inv -`)


# api.html.md

# API reference

| [`openloops`](_autosummary/openloops.html.md#module-openloops)   | What your Claude Code sessions were doing — kept after the transcripts are gone.   |
|-------------------------------------------------------------------------------|------------------------------------------------------------------------------------|


