Metadata-Version: 2.4
Name: continuity-guard
Version: 0.5.3
Summary: See how much of your Claude Code, Codex or Grok subscription window is left, and get a handoff before a plan limit ends the run
Author: Ak2tx LLC
License: MIT License
        
        Copyright (c) 2026 Ak2tx LLC
        
        Permission is hereby granted, free of charge, to any person obtaining a copy
        of this software and associated documentation files (the "Software"), to deal
        in the Software without restriction, including without limitation the rights
        to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
        copies of the Software, and to permit persons to whom the Software is
        furnished to do so, subject to the following conditions:
        
        The above copyright notice and this permission notice shall be included in all
        copies or substantial portions of the Software.
        
        THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
        OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
        SOFTWARE.
        
Project-URL: Homepage, https://github.com/ak2tx/continuity-guard
Project-URL: Source, https://github.com/ak2tx/continuity-guard
Project-URL: Issues, https://github.com/ak2tx/continuity-guard/issues
Project-URL: Changelog, https://github.com/ak2tx/continuity-guard/blob/main/CHANGELOG.md
Keywords: ai-agents,llm,claude,chatgpt,codex,grok,usage-limits,rate-limits,quota,plan-window,token-budget,watchdog,monitoring,observability,agent-loop,cost-control
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: POSIX :: Linux
Classifier: Operating System :: MacOS :: MacOS X
Classifier: Operating System :: Microsoft :: Windows
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Topic :: System :: Monitoring
Classifier: Topic :: Software Development :: Quality Assurance
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE
Dynamic: license-file

# Continuity Guard

Don't lose another agent run to a plan limit.

Continuity Guard shows how much of your Claude Code, Codex or Grok
subscription window is left, warns your agent before it runs out, and writes a
handoff for the next run. It reads usage the official CLIs already record on
your machine — no provider credentials, no proxy, no account access.

Codex and Grok usage appears immediately. Claude publishes its percentage only
during a non-interactive run, so wrap one Claude command to start tracking it.

Zero dependencies. Python 3.11+. Linux, macOS, Windows, or a container.

```bash
pipx install continuity-guard

cg quota                                    # read-only, nothing to configure
cg wrap -- claude -p "continue the migration"
```

`cg wrap` runs your command unchanged and observes it; it terminates nothing
unless you separately arm the daemon. For `claude -p` it adds
`--output-format stream-json --verbose` and renders the answer back to plain
text, because that event stream is the only place Claude's percentage exists —
it is never written to disk. It says so on stderr when it does this rather
than silently rewriting your command line.

Put it where you already look, instead of remembering to ask:

```bash
cg statusline                      # -> cg 48%   (or "cg -" when it cannot see)

# bash/zsh prompt
PS1='$(cg statusline) '"$PS1"

# tmux
set -g status-right '#(cg statusline)'
```

`statusline` reads no config, contacts no daemon and always exits 0, so it
cannot break the prompt it is added to. It prints `-` rather than a stale
percentage: a number that was true an hour ago is the failure this tool
exists to prevent.

```
PROVIDER   WINDOW         USED  RESETS               AGE  STATUS
openai     primary       97.0%  Sat 11:19            2m   ok
grok       weekly        63.0%  Sat 23:21           23m   ok
anthropic  five_hour     94.0%  Sat 12:30            0m   ok     <- after one wrapped Claude job
           seven_day     73.0%  Mon 02:00            0m   ok
```

A browser-only subscription is not a user of this tool: the reading comes from
what a CLI writes locally, and a browser writes nothing here.

Those numbers come from files the official clients already write, and from
stream events passing through `cg wrap`. Each adapter was checked against the
provider's own usage screen; the working is in
[docs/quota-accuracy.md](docs/quota-accuracy.md).

## What you will actually see

Those three sentences are the claim. This table is the evidence for them, and
it belongs here rather than in a footnote.

| you | `cg quota` shows |
|---|---|
| use the `codex` or `grok` CLI | their windows immediately. Those clients write usage to disk themselves. |
| use the `claude` CLI | nothing, until you wrap one session |
| use claude.ai or ChatGPT in a browser | nothing, ever |

Runs hosted inside another vendor's client spend that vendor's pool, not your
provider's. Cursor is the common case: CG does not see that ceiling. The
measurement is in [docs/quota-accuracy.md](docs/quota-accuracy.md).

Claude is the awkward case. It does publish a percentage, but only as a
`rate_limit_event` inside its `stream-json` output, and it never writes that to
disk. Polling a file will not find it. The number has to be caught in flight:

```bash
cg wrap -- claude -p "whatever you were going to run anyway"
cg quota                           # the anthropic rows are there now
```

The substitution is only applied when the child is `claude`, run with `-p`,
and you have not chosen a format yourself. A wrapper script under another name
will not be recognised, and that is deliberate: guessing at what a binary is
would be worse than missing one.

`cg wrap` terminates nothing, and says so on its first line every time.

It is not a transparent sleeve like `timeout` or `nice`, and it should not
claim to be. For `claude -p` specifically it adds `--output-format stream-json
--verbose`, because that is the only form in which the percentage exists, then
prints the answer back as plain text so the run looks the same to you. It tells
you it did that. An explicit `--output-format` of your own wins, an interactive
`claude` with no `-p` is left alone, and no other program is ever rewritten.

Browser sessions leave no local record at all. If that is how you use your
subscription, this tool has nothing to read and you should stop here.

## Warn the job before the window closes

Reading the number is useful on its own. The reason it exists is what comes
next: telling a running job that it is nearly out of room, while there is still
room to do something about it.

```python
from continuity_guard import guard

with guard("nightly-refactor", profile="overnight") as s:
    for step in agent.run():
        s.progress(step=step.name, tool=step.tool, args=step.args,
                   tokens=step.tokens, depth=step.depth)
        if s.should_wrap_up():          # cheap, non-blocking, False by default
            save_state(s.headroom())    # what to save is yours to decide
            break
```

Every signalled session also gets a handoff written for it, whether or not it
answers. That matters because the sessions most worth preserving are usually
the ones too wedged to preserve themselves. What that document does and does
not preserve is set out in
[what the handoff is and is not](#what-the-handoff-is-and-is-not).

## The watchdog, when you want it

Twelve detectors cover the agent failures that return HTTP 200 while nothing
useful happens: loops, oscillation, pace collapse, token burn, runaway
recursion, crash loops.

It ships observe-only. Nothing is terminated until you have watched it against
your own traffic and decided to arm it.

```bash
cg init && cg install              # scaffold config, run as a service
cg status                          # how close each session is to firing, now
```

The order of this page is the order we suggest you adopt it. Reading the quota
costs you nothing and needs no permission. The wrap-up signal costs one line in
your loop. Kill authority comes last, because it is the only part that can take
something away from you.

---

## Why a heartbeat is not enough

A heartbeat proves a thread is running. It says nothing about whether work is
happening, and the expensive failures are the ones where every request returns
200, latency sits inside the SLO, and the bill triples overnight.

So there are twelve detectors:

| Detector | Catches | Signal |
|---|---|---|
| `death` | process gone | socket EOF, free from the kernel, no timeout |
| `silence` | wedged, blocked forever | no frames at all |
| `no_progress` | the lying heartbeat: alive, not working | frames arrive, `seq` frozen |
| `decay` | pace collapse | consecutive slow gaps vs the session's **own** learned baseline |
| `repeat` | the agent loop | identical tool + identical args, repeating |
| `cycle` | oscillation / thrash | edit, test, revert, repeating |
| `burn` | the failure that never errors | tokens/min high **and** no progress |
| `budget` | all-night spend | cumulative token ceiling, progress or not |
| `deadline` | runs that never end | wall-clock cap on one session |
| `errors` | retry storms | failed tool calls over a window |
| `depth` | runaway sub-agent spawning | recursion depth exceeded |
| `flap` | crash loops | repeated death + restart of the same name |

Four of those are invisible to ordinary monitoring: `repeat`, `cycle`, `burn`
and `errors`.

Three of them are easy to confuse with each other, so:

`cycle` exists because `repeat` cannot catch thrash. The classic agent failure
is edit, run tests, revert, edit, run tests, revert. Every call differs from the
one before it, so exact-duplicate detection sees healthy variety while the agent
goes nowhere.

`budget` is not `burn`. `burn` is a rate, and an agent can stay under every rate
limit and still spend all night. An absolute ceiling is the "one stuck agent
spends $6,000 tonight" guard, and it fires whether or not work is progressing.
Enforcement happens between steps, so a real total can overshoot by roughly one
model call. Treat it as a ceiling, not a guarantee.

`decay` is the only adaptive detector. It learns a session's own pace from its
first steps, freezes that baseline, then fires if the pace collapses relative to
it. A 2s-per-step interactive agent and a 90s-per-step build agent both work
with no tuning.

Four constraints keep `decay` safe. Each was added after a measurement showed
the previous version firing on ordinary build traffic:

- The effective threshold can never fall below the `floor` you set. Adaptation
  only ever *loosens*. A detector that can tighten itself will invent false
  positives on a workload it mis-learned.
- The `warn` level is relative and sensitive (`base * warn_k`, floor `45s`).
  The `hard` level is an absolute backstop (`hard_floor`, default `200s`) set
  above the slowest gap a healthy heavy-tailed workload produces, so build and
  research sessions cannot physically reach the terminate level.
- The baseline is a central quantile of the early gaps (`baseline_q`, default
  the median). Decay asks whether the *typical* pace collapsed. The upper tail
  belongs to `silence`, which is asking a different question.
- It requires **consecutive** slow gaps. "3 of the last 7 steps were slow" just
  describes a build-heavy workload. An unbroken run is what a real collapse
  looks like.

Those defaults come from measured sweeps on build-heavy traffic, where 22% of
steps take 30 to 150 seconds. Moving `min_gaps` from 3 to 4 to 5 took
warn-level false positives from 12.5% to 1.2% to 0.4%, with detection at 100%
throughout, so `min_gaps = 5` ships. Adding `hard_floor` took the hard-level
false positive from 1.2% to 0.0% at high sample counts with recall unchanged.

Death detection costs nothing at all. The session holds one socket open; when
the process dies the kernel closes it and the daemon knows in milliseconds.
That is an OS fact rather than an inference, so there is no polling, no timeout,
and no way for it to be wrong.

`RETIRE` is not optional. Without a clean-exit signal every successful run ends
in a socket close indistinguishable from a crash, and the tool alarms on its own
users' happy path. The context manager sends it on normal exit and on exception,
because an exception is still an observed, intentional end.

## Tuning

Everything is adjustable per session, and thresholds reload live.

```
session inline overrides   >   named profile   >   defaults
```

```python
guard("agent")                                   # defaults
guard("agent", profile="tight")                  # built-in profile
guard("agent", profile="loose",
      silence={"warn": "10m", "hard": "2h"})     # inline override
```

Four profiles ship. `tight` is for interactive work where you want fast
feedback. `loose` is the false-positive-safe end, for long tool calls and
research. `overnight` is for unattended runs: it catches loops and burn early
and will kill a hard stall. `wallet` sets a low per-session token ceiling, for
when a runaway bill would hurt more than a truncated run. Define your own in
the config.

The numbers that differ from the defaults:

| | `silence` warn/hard | `no_progress` warn/hard | `budget` hard | action |
|---|---|---|---|---|
| **defaults** | 3m / 30m | 3m / 45m | 1,000,000 | `notify` |
| **tight** | 20s / 2m | 60s / 5m | 1,000,000 | `notify` |
| **loose** | 5m / 45m | 15m / 2h | 4,000,000 | `notify` |
| **overnight** | 2m / 15m | 10m / 45m | 1,500,000 | **`terminate`** |
| **wallet** | 3m / 30m | 3m / 45m | **25,000** | `notify` |

`overnight` is the only built-in profile that terminates, and even then only
once you have taken the daemon out of shadow mode. `wallet` still just
notifies: it stops the spend by telling you, not by killing. For the full
effective set including your own overrides, run `cg profiles`. It prints the
config file it read on the first line.

Thresholds reload live. Edit the config, then, on POSIX:

```bash
cg reload      # SIGHUP: live sessions re-resolve thresholds, state preserved
cg status      # how close each session is to firing, right now
cg history     # what fired, when, and whether it acted
cg profiles    # effective thresholds per profile
```

### Seeing that it is actually working

The commonest reason a watchdog gets uninstalled is that nobody can tell
whether it is awake. Here are the two commands that answer that, with real
output.

`cg status` shows what is running and how close it is to each threshold:

```
config: /home/you/.continuity-guard/config.toml
socket /run/continuity-guard/cg.sock   2 session(s)   12:29:53

SESSION                       PID   SEQ   QUIET   STUCK  TOK/MIN  REP  PROFILE   MODE
nightly-refactor           130847    26      1s      1s    19200    8  default   shadow
nightly-refactor           130889     8      2s      2s    19200    8  default   shadow
```

`cg history` shows what fired, when, and whether it acted:

```
config: /home/you/.continuity-guard/config.toml
WHEN                SESSION            DETECTOR  LEVEL ACTION   DETAIL
2026-08-29 12:30:02 nightly-refactor   repeat    warn  notify   repeated apply_patch(33d034ea) x13 (unconfirmed: 21s of 60s)  [shadow]
2026-08-29 12:29:41 nightly-refactor   repeat    warn  notify   repeated apply_patch(33d034ea) x3 (unconfirmed: 0s of 60s)  [shadow]
```

That second line contains the whole safety design. `repeat` saw the same call
thirteen times. It said so at `warn`, marked itself `unconfirmed: 21s of 60s`,
took the action `notify`, and tagged the record `[shadow]`. Nothing was killed.
A hard verdict has to hold unbroken for its confirmation window before it
escalates, and in shadow mode it never acts at all.

Both commands print the config file they read on the first line. That is not
decoration. A stale `~/.continuity-guard/config.toml` will quietly disagree
with this page, and if you cannot tell what is configured you cannot trust
what it will do.

The columns in `cg status` are the values the thresholds are compared against:
quiet time, stuck time, tokens per minute, current repeat run. Tune against
those rather than against guesses.

---

## Plan windows, and not losing a run to one

The reading is the easy half. This section is the mechanics: how the number is
kept honest, and what happens to a live session when the window runs low.

A stale reading is refused rather than trusted. Once, a Grok cache read 13.0%
while the account was actually at 63%, from a file five days old. That is the
most dangerous state a meter can be in, because it looks like knowledge. Any
snapshot older than an hour is marked `IGNORED` and cannot trigger anything,
and an unknown age counts as stale.

At `wrapup_at`, which defaults to 95% of the binding window, every live session
is told to save its state. A handoff is written for each of them whether or not
they respond. A wedged agent cannot act on the signal, and that is when the
record is worth the most.

```python
with guard("nightly-refactor", profile="overnight") as s:
    for step in agent.run():
        s.progress(...)
        if s.should_wrap_up():          # cheap, non-blocking
            write_handoff(s.headroom()) # what to save is yours to decide
            break
```

The handoff Continuity Guard writes itself is a record of what it observed:
steps, tool calls, timings, tokens, the plan window at the time. Not a summary
of intent; the agent did not write it. If your agent also acts on the signal
you get a better one on top.

Ceiling signals go to the three ceiling conditions (a plan window, a `budget`,
a `deadline`) and never to faults. Nothing is wrong with a session that is
merely running out; a wedged one cannot answer anyway.

### What the handoff is and is not

You always know what a run reached, including when the agent died without
cooperating. Enumerable progress survives: which items are done, which remain,
and the command that resumes past them. When the work is a list, and a great
deal of agent work is a list, that is most of what you needed. The next run
picks up without repeating itself.

What does not survive is the agent's understanding. The half-formed
hypothesis, the reason approach A was abandoned, the thing it had noticed but
not yet put into words: that lives in the model's context and goes when the
context goes. Writing it down is lossy, and the loss is invisible in the
result, because you cannot tell from a summary what is missing from it. This
is the context-compaction problem and nothing here solves it.

Call it a warm start rather than a continuation. A successor reads the handoff
and begins informed instead of blind. It does not resume mid-thought.

Two consequences are worth planning around.

Task shape decides how much this is worth to you. Enumerable, independent units
hand off well. Exploratory debugging hands off badly, because its value was
never in the enumeration; it was in the hypothesis space, which is the part
that does not survive.

Findings also have a shelf life. In one measured case, two of four findings in
a handoff had already been fixed a few hours later, and a third was wrong on
its own terms. A document describing a moving codebase decays. Handoffs carry
an observed-at stamp so a reader can judge for themselves, which is mitigation
rather than a fix.

---

## The socket is kill authority

An armed daemon terminates processes it is told about, and everything in a
session's announcement is that peer's claim about itself. The socket is
therefore a privileged surface and is treated as one. Four checks, each
independent, because an operator will eventually widen one of them for a good
reason:

- The Unix socket is `0600`. It used to be `0666`. Set `CG_SOCKET_MODE=660`
  with a shared group to widen it deliberately, when several accounts must
  genuinely share one daemon.
- A session may tune its own thresholds but never its own `action`. Overrides
  arriving over the socket have operator-only keys stripped, so `action` comes
  from your config file or not at all. Whatever was dropped is logged.
- Identity is verified rather than assumed. Terminating requires a
  `start_time` matching the live process. A missing one used to fall back to
  "is anything alive with this PID", which accepts every process on the box.
- The announced PID must be the connecting peer or a descendant of it, since a
  supervisor announcing its child is the normal case. Anything else disarms
  termination for that session and says so in the log. Observation continues.

TCP is not authenticated. `socket = "tcp://..."` binds `127.0.0.1` by default
and should stay there. There is no token and no TLS, and a reachable armed
daemon is a kill primitive for anything its user can signal. Peer credentials
do not exist over TCP, so termination is disarmed there deliberately.

The full threat model, and the disclosure of the local privilege issue fixed
in 0.5.0, are in [SECURITY.md](SECURITY.md).

---

## Shadow mode

The daemon ships observe-only. With `shadow = true` it evaluates every
contract and logs every action it would have taken, and kills nothing.

Run it that way against real workloads first, and measure your own
false-positive rate. Nobody should grant kill authority to a new watchdog
before they have seen that number, and shadow mode produces the only metric
worth having: N sessions observed, zero healthy terminations.

```bash
python3 -m continuity_guard.daemon -c config.toml            # config decides
python3 -m continuity_guard.daemon -c config.toml --shadow   # force observe-only
python3 -m continuity_guard.daemon -c config.toml --armed    # force enforcement
```

---

## Notifications

Every sink declares which levels and detectors it wants.

```toml
[[notifications]]
kind = "file"
path = "~/continuity-guard-alerts.log"
on   = ["warn", "hard", "dead"]

[[notifications]]
kind    = "exec"                         # event passed as CG_* env vars
command = "~/bin/cg-notify.sh"
on      = ["hard", "dead"]

[[notifications]]
kind = "webhook"
url  = "http://127.0.0.1:9000/cg"
on   = ["hard", "burn", "repeat"]
```

A broken sink is logged and swallowed. Notification failure must never stop the
daemon doing its actual job.

---

## Safety properties

**PID reuse is guarded.** A PID recorded an hour ago may belong to something
else by the time you act on it, so every kill verifies PID and process start
time as a matched pair and refuses if they disagree.

**Children are not orphaned.** Agent sessions spawn shells, tool calls and
model servers. Termination signals the process group, so nothing is left
holding ports, files or money.

**Grace before force.** `SIGTERM`, wait `grace`, then `SIGKILL`.

**Sleep is not death.** `CLOCK_BOOTTIME` and `CLOCK_MONOTONIC` are compared
every tick. A machine that suspended re-arms its deadlines with a grace window
rather than firing. After a gap you have no trustworthy information, and the
right answer to "I don't know" is to re-observe.

**Refractory is durable.** Fires are suppressed per `session::detector::level`
in SQLite, with exponential backoff, keyed per level so an escalation is never
swallowed by the warning before it. It survives daemon restart, which matters
because the restart is exactly the moment when every session looks freshly
overdue at once.

**Heartbeats are never fsynced.** Only state transitions are persisted.
Writing every progress frame to disk would dominate I/O, and wear out a Pi's
SD card, for no benefit.

**Kill authority is local, and only local.** A remote observer cannot tell "the
session died" from "I cannot currently reach the session". Silence over a
network is evidence of silence, not of death. If a hosted tier ever exists it
will send a deadman notification, which is a claim about what the observer
knows, and it will never issue a kill. That makes split-brain structurally
impossible rather than merely unlikely.

**What this does not promise.** Killing a process is not the same as making the
outcome safe. If a session already fired an API call, sent a message or charged
a card before it stalled, termination does not undo any of it. Whether a hard
kill leaves clean resumable state is a property of your application, not of
this watchdog.

---

## Works with any agent

Four ways in, in order of how much you get for the effort. All feed the same
twelve detectors.

**1. The proxy. Zero code changes, any language, richest signals.**
Nearly every agent and local runtime speaks OpenAI chat-completions: Ollama,
vLLM, llama.cpp, LM Studio, LiteLLM, OpenRouter, the xAI (Grok) API, grok-cli,
Aider, OpenHands, CrewAI, AutoGen, LangGraph. Point the base URL at the proxy:

```bash
cg-proxy --upstream http://localhost:11434 --port 8111   # Ollama
cg-proxy --upstream https://api.x.ai      --port 8111    # Grok
export OPENAI_BASE_URL=http://127.0.0.1:8111/v1
```

The wire format carries exactly what the detectors want, with no guessing:
`usage.total_tokens` → burn/budget, `tool_calls[].function` → repeat/cycle,
HTTP status → errors, request cadence → silence/decay. Streaming works, and
gives token-level liveness for free. Name sessions with an `X-CG-Session`
header, or run one proxy per agent with `--name`.

*Limitation, and it is real:* the proxy sees model traffic, not the process.
An agent that exited cleanly and one that hung look identical from there. Pair
it with the supervisor or library for process lifecycle.

**2. `instrument_openai()`. One line, for any framework using the openai SDK.**

```python
from continuity_guard.integrations import instrument_openai
client = instrument_openai(OpenAI(base_url=...), "my-agent", profile="overnight")
```

**3. `CallbackHandler`. LangChain, LangGraph, and anything that copied that
interface.** Duck-typed: this package never imports LangChain.

```python
from continuity_guard.integrations import CallbackHandler
with CallbackHandler("research-agent", profile="loose") as cb:
    graph.invoke(state, config={"callbacks": [cb]})
```

**4. `Tracker` / `@guarded`. Your own loop.**

```python
from continuity_guard.integrations import guarded

@guarded("nightly-refactor", profile="overnight")
def run(task, cg=None):
    for step in agent(task):
        cg.step(tool=step.tool, args=step.args, tokens=step.tokens, ok=step.ok)
```

And for CLI agents that offer no hooks at all, `cg wrap` wraps the
process and derives progress from output.

## Accuracy

`tests/bench_accuracy.py` drives the real detector code against a simulated
clock, which gets thousands of sessions in seconds where the realtime soak
manages about a dozen in ten minutes. The healthy workloads are adversarial by
design. Each one is a legitimate pattern chosen because it looks like a
specific fault.

| Healthy archetype | Looks like | Why it is legitimate |
|---|---|---|
| `polling` | `repeat` | re-reads the same status file forever, while progressing |
| `pipeline` | `cycle` | read → edit → test, a new file each pass |
| `flaky` | `errors` | 30% of tool calls genuinely fail (empty greps, 404s) |
| `bursty` | `decay` | fast bursts split by 4-minute thinking pauses |
| `rate_limited` | `decay` | periodic provider backoffs |
| `build` | `decay` | 22% of steps take 30–150s |
| `long_tool` | `silence` | single 20-minute test-suite runs |

Current numbers on the archetypes above (default profile):

```
overall any-level FP   0.0%      hard-level FP   0.0%
loop 100%  cycle 100%  stall 100%  burn 100%  errors 100%
depth 100%  decay 100%  budget 100%  cold_freeze 100%  cold_stall 100%
```

**That figure is not universal, and the qualifier is the honest part.** Three
workload shapes are known to produce false positives and are excluded from the
gate, measured and published rather than deleted
(`tests/bench_accuracy.py --known-fail`):

| shape | any-level FP | hard-level FP | detector |
|---|---|---|---|
| polls one endpoint forever | 100% | 0% | `repeat` |
| alternates between two queues | 100% | **100%** | `cycle` |
| fast setup, then long work | 100% | 0% | `decay` |

Together those three measure **any-level FP 25.0%, hard-level FP 8.33%, min
recall 92%** (`tests/bench_accuracy.py --known-fail`, which reports and exits
0 rather than gating).

The second is a real hard-level false positive on healthy work: an agent
doing `poll(queue-a)`, `poll(queue-b)` with `seq` advancing every frame — real,
reported progress — reaches a hard `cycle` verdict on the sixth frame. That is
what a queue worker, a CI watcher and a deploy monitor look like.

The default action for `repeat` and `cycle` is `notify`, so nothing is
terminated out of the box. **Under a terminating profile it would be.** If your
agent polls, set `repeat.action` and `cycle.action` to `notify` explicitly, or
raise their thresholds.

No fix is offered, because a healthy periodic poller and a pathological loop
emit identical frames indefinitely and no finite confirmation window separates
them. See `docs/quota-accuracy.md`. The corpus missed this for a long time
because the archetype named `polling` did not actually poll — its docstring
claimed it did.

### Against real traffic, not just the corpus

The numbers above come from an adversarial corpus: synthetic sessions with
known ground truth, which is what makes false-positive rates measurable at all.
That is the right instrument for tuning and the wrong one for the question
anyone actually asks, which is whether it will kill their work.

So it also runs in shadow mode against real agent traffic, on two hosts (a
Raspberry Pi 5 and an x86-64 NUC) across four provider paths: the `claude` CLI
under `cg wrap`, and Grok, OpenRouter and local models through `cg-proxy`.
Shadow mode records the verdict and takes no action, so every session is a free
observation of what an armed daemon would have done.

As of 2026-08-29, since the harness fix in `63d4bc8`:

| | observed | healthy | would have been terminated |
|---|---|---|---|
| real model sessions | 629 | 475 | **0** |
| including synthetic soak | — | 3,470 | **0** |

Seven distinct real models. The one healthy session ever flagged in this
pipeline (`real-1787852493-clean`, a Claude-Haiku repo-QA run) was a **harness**
defect, not a detector one: the test loop's regex did not capture tool *input*,
so every call hashed identically and `repeat` fired correctly on what it was
shown. It is annotated in the ledger rather than deleted, and `63d4bc8` fixed
the loop.

That table is a false-positive measurement, not a recall one. Faults in the real loop are injected against short sessions
that often end before a detector's window elapses, so the catch rate there says
nothing useful and is not quoted; recall comes from the corpus and the matrix,
where the ground truth is exact.

The honest summary is that in roughly 630 real sessions, across seven models and
four provider paths, an armed daemon would have terminated nothing healthy. The
run is still accumulating, so treat that as a floor rather than a final number.
It is also one operator's machines. It is not a substitute for measuring your
own traffic before you arm anything.

Three things that only showed up at these sample sizes, all now fixed:

**The decay hard level needed its own floor.** When a session's learned
baseline is small, `floor` dominates both decay levels and `warn_k`/`hard_k`
collapse to the same threshold, so any qualifying slow run fires straight to
`hard`. On build traffic that was a 1.2% hard-level false positive at
`--trials 200`+ (invisible at 60). `decay.hard_floor` (default 200s) is now an
absolute backstop above the slowest gap healthy heavy-tailed traffic
produces; warn keeps the relative `floor`. Recall unchanged.

**`silence` and `decay` need opposite statistics from the same data.** Decay asks
"has the typical pace collapsed?", which is a central quantile. Silence asks
"how long may this agent legitimately go quiet?", which is the upper tail. Sharing one baseline
made bursty workloads false-positive at 94%, because a median baseline calls the
pauses anomalies when the pauses *are* the workload.

**Before the first completed step there is no information at all.** Firing a
warning there is guessing, and it is how a 20-minute-per-call agent gets flagged
in its first three minutes. Warnings are now suppressed until a session has
produced one step; the hard ceiling still applies, widened.

## Testing with agents

See **[docs/integrating.md](docs/integrating.md)** for the safe wiring recipe per
agent (and the instrumentation footguns to avoid), and **[TESTING.md](TESTING.md)**
for the full Pi runbook. In short:

```bash
./tests/run_matrix.sh                                   # 25 rows, 26 checks
python3 tools/soak.py --sessions 8 --duration 8h        # calibrate thresholds, free
cg wrap --name nightly -- claude -p "..."                # real CLI agent
```

`tools/soak.py` runs concurrent sessions with known ground truth and scores the
daemon against reality, separating spurious notifications (noise) from
spurious *terminations* (destroyed work). Ship with the second at zero.

`cg wrap` (also `cg-supervise`) wraps any CLI agent with no changes to it, registering
the child's PID so termination reaches the agent rather than the wrapper.

## Test matrix

`./tests/run_matrix.sh` — 25 rows / 26 checks (18 realtime, a protocol fuzz, a ceiling-signal check, an authority check, a packaging check, an environment-knob check, a wrapper output/signal check, and a statusline check). Rows 1 and 5 are the ones that decide whether
anyone trusts this: a watchdog that catches every stall but occasionally kills
healthy work gets uninstalled after the first false positive, and deserves to be.

```
 1 clean completion              MUST NOT fire
 2 hard death (no retire)        socket EOF
 3 blackhole: alive but silent   SIGSTOP
 4 lying heartbeat               frames arrive, seq frozen
 5 legitimately slow work        MUST NOT fire
 6 agent loop                    identical tool+args
 7 token burn, no progress
 8 runaway recursion depth
 9 oscillation                   edit/test/revert, every call differs
10 retry storm                   tool calls failing
11 budget ceiling                spend WITH progress; burn must stay silent
12 wall-clock deadline
13 decay                         fast baseline, then a crawl
14 decay MUST NOT fire           uniformly slow but steady work
15 flap                          crash loop across sessions
16 refractory survives restart   no duplicate-fire storm
17 ARMED: group termination      children not orphaned
18 PID reuse guard               stale identity refused
19 protocol contract + fuzz      malformed/binary/partial/giant/seq/churn
20 ceiling signal reaches agent  client drain + budget/deadline delivery
21 authority + ceiling guarantees peer cannot make the daemon kill
22 installed wheel             can do what the docs say
```

`demo_agent.py` is the fault injector, one process that reproduces every mode on
demand:

```bash
python3 demo_agent.py healthy|slow|loop|cycle|stall|burn|budget|decay|errors|deep|freeze|die|children [profile]
```

---

## Install as a service

```bash
sudo mkdir -p /opt/continuity-guard /etc/continuity-guard
sudo cp -r continuity_guard /opt/continuity-guard/
sudo cp config.example.toml /etc/continuity-guard/config.toml
sudo cp systemd/continuity-guard.service /etc/systemd/system/
sudo systemctl enable --now continuity-guard
systemctl status continuity-guard
```

The unit sets `Restart=always` and `OOMScoreAdjust=-500`: the init system is what
watches the watchdog, and the daemon must outlive the memory pressure that kills
what it watches.

---

## Status

v0.5.3, reference implementation. **26/26 matrix checks across 25 rows** — 18 realtime
checks, a protocol fuzz, a ceiling-signal check, an authority check, a
packaging check, an environment-knob check, and a wrapper output/signal
check — passing on both architectures on this commit: Raspberry Pi 5
(aarch64, Python 3.13.5) and an x86-64 host (Python 3.12.3). See
docs/platform-support.md.

Pure Python so the contract semantics and thresholds can be validated fast on
real workloads. The wire protocol (`continuity_guard/protocol.py`, plus
`sanitize()` as its acceptance rule) is the durable artifact; the native daemon
reimplements against it once the semantics are proven here.

See `docs/` for the engineering history and the measurement behind each
decision.

MIT. Ak2tx LLC.
