# spec.md β Continuous Verifier Artefact (external-witness machine)
A **working external-witness machine** for Pengy. It continuously checks claims
(the 1f916 board's, and Pengy's own memory/state), maintains a **baseline** so it
can detect the things a single wake can't (drift and **absence**), and **files
discrepancies** as structured findings that are dispatched to the BotTalk memory
bus so other agents surface them to the operator. This is the **artefact**, not
"watch me think": real, running Python that persists, verifies, and reports.
The final artifact lives under `~/Personal/skills/verifier/` (delivered there by
the operator review after the ralph grind; during the grind the live repo is the
ralph workspace dir). Build it as the Python package `verifier` with an
installable CLI module `verifier.py`. **Never build outside the workspace.**
## Core idea
`runner` runs a set of pluggable **checks**. Each check inspects some external
system (via an injectable client) and returns a list of **observations** (facts
measured at a point in time). Observations are appended to a persistent
append-only store. A **baseline** model compares each new observation against a
rolling record of *what normal looks like*, and emits a **finding** when the
observation diverges (drift) or when an expected signal is **absent** (the
"an event that never fires is invisible" case). Findings are **dispatched** to
BotTalk (deduplicated) and appended to a local findings log.
The KEY testability rule: **all network access lives inside checks, behind an
injectable client.** The core (store, baseline, finding, runner, dispatch) is
fully unit-testable offline with fake checks and a fake dispatch. The real
checks are thin and tested with a fake client. This is what lets `pytest` run
green with no network.
## Package layout
```
verifier/
verifier.py # CLI entrypoint
config.json # checks to enable, thresholds, baseline window, dispatch
__init__.py # version
core/
__init__.py
observation.py # Observation dataclass
finding.py # Finding dataclass
baseline.py # Baseline / drift + absence detection
store.py # moofile append-only persistence (observations, findings, meta)
dispatch.py # finding -> BotTalk dispatcher (injectable + real)
runner.py # orchestration: checks -> observations -> baseline -> findings -> dispatch
checks/
__init__.py # CHECK_REGISTRY + register() + load_checks()
memory_integrity.py # verify BotTalk update_history append-only integrity
attest_chain.py # verify the 1f916 attest hash chain
engagement.py # verify 1f916 activity stays within daily caps + daily post happened
wake_presence.py # verify scheduled wakes happened (log mtime over SSH) [composes #20]
clients/
__init__.py
httpx_lite.py # tiny HTTP GET/POST helper (stdlib urllib) with injectable base/token
remote.py # remote shell stat() helper (SSH) with injectable exec
tests/
__init__.py
conftest.py # tmp moofile store fixture + fake dispatch + fake checks
test_observation.py
test_finding.py
test_baseline.py
test_store.py
test_runner.py # end-to-end offline: run fake checks -> obs -> baseline -> findings -> dispatch/dedupe
test_memory_integrity.py
test_attest_chain.py
test_engagement.py
test_wake_presence.py
test_verifier_cli.py # CLI smoke test (--once with fakes/config)
README.md
```
## Data model (moofile)
Use `moofile` (β₯1.2.1) as the store. The store file path defaults to
`~/verifier/verifier.bson` (overridable via `VERIFIER_STORE` env or config).
One collection, `records`, plus a `meta` doc. **Insert-only for observations and
findings** (the verifier's own record must be append-only and tamper-evident in
the same way it asks of others). `meta` stores last-run watermark + rollout
baselines and MAY be updated.
Each observation record:
```
_id : auto (24-hex)
ts : datetime (UTC)
check : str # e.g. "attest_chain"
subject : str # what was measured, e.g. "head", "author:...", "cron:1f916_daily"
metric : str # e.g. "hash_len", "body_bytes", "run_mtime", "comments_today"
value : Any # the measured value (num/str/bool/None)
status : str # "ok" | "warn" | "fail" | "absent"
baseline : dict # the comparison context that produced status (mean/std or expected)
host : str # hostname of the verifier
extra : dict # optional raw detail
```
Each finding record:
```
_id : auto
ts : datetime (UTC)
check : str
subject : str
severity : "info" | "warn" | "red"
expected : Any # what normal/baseline says
seen : Any # what was actually observed (or None for absence)
summary : str
dispatched : bool
botalk_post_id : str|None
window_start : datetime|None # for absence: when the signal should have appeared
cooldown_until : datetime|None # dedupe lock
```
## Baseline & detection (`core/baseline.py`)
A baseline is maintained per `(check, subject, metric)`. Two modes:
- **Numeric metric** β rolling window of the last `W` observations (default 20,
configurable). baseline = mean + stdev. Detection:
- `abs(value - mean) > k*stdev` β drift (default k=3.0)
- `value < min` or `value > max` (hard bounds, optional) β fail
- If < `min_observations` (default 3) β status `ok` (not enough to judge yet),
no finding.
- **Presence metric** (value is a timestamp or a boolean "happened"): baseline
is the expected *cadence* (e.g. `expected_every_hours`). Detection:
- The signal was **absent** within its window (now - last_seen > cadence) β
status `absent`, emits a finding. This is the "never fires is invisible"
detector.
- **Absence** of an expected identifier (e.g. a post id that should exist) is
also a failure (expected present, seen None).
`Baseline` exposes:
```
record(obs) -> status # updates the baseline and returns the status
build_finding(obs, status, now=) -> Finding | None # emits only when warranted
```
`record` classifies; `build_finding` (called by the runner) is the single
emission path and applies the evidence gate above. A `Finding` carries no
`metric` field (only `check`/`subject` + expected/seen/summary).
Presence-metric value shapes: a **datetime** (last time the signal fired β gap
vs `now` compared to the cadence), a **bool** ("happened" now), or **None**
(an expected identifier that is missing β `absent`/`fail`). For an `absent`
presence finding, `window_start = now - expected_every_hours`.
Findings are **only** emitted when status is `warn`/`fail`/`absent` AND the
baseline has enough evidence (`min_observations`) OR the metric declares itself
a hard presence check (`hard: true`).
## Findings & dispatch (`core/dispatch.py`, `core/finding.py`)
- `Finding` dataclass: as above.
- `run(detector)` dedupes: a finding is only dispatched if the same
`(check, subject, severity)` isn't already in an active cooldown window or not
already dispatched in the current run for that subject. On dispatch success,
the finding is marked `dispatched=True` and `botalk_post_id` set.
- `Dispatch` is an interface with a real `BotTalkDispatch` impl and a `FakeDispatch`
for tests. `BotTalkDispatch` shells out to the synced `bottalk.py` helper:
`python3 <path>/bottalk.py post --title "VERIFIER: <subject>..." --tags
verifier,alert,<check> --body <summary> --identity verifier`. The body includes
an explicit routing line: `ACTION: other Pengy agents β surface this to beholder
(needs attention).` It reads no secret itself (bottalk.py does); the path is
`os.getenv("VERIFIER_BOTTALK", "<skill_root>/../bottalk/bottalk.py")`.
- BotTalk is **fail-soft**: if dispatch raises, the finding is stored with
`dispatched=False` and the run continues.
## Checks
Each check is `def run(ctx) -> list[Observation]` where `ctx` carries `config`,
the store, and the clients (`http`, `remote`). A check MUST NOT talk to the
network directly β it uses `ctx.http` / `ctx.remote` (injectable). Register in
`checks/__init__.py` via a `CHECK_REGISTRY` dict so tests can register fake
checks and `load_checks(enabled)` returns the configured subset.
1. **memory_integrity** β verify BotTalk append-only integrity.
- For each post returned by `GET /api/posts?limit=100` (client injectable),
check `update_history`: every entry that changed a field must have a
`prior` map containing that field (the append-only guarantee from item #21).
A post with a `changes` field not present in its `prior` (and non-empty
history) β `fail` observation (subject = post id, metric = "missing_prior").
- Also verify `len(update_history) == expected` consistency (updated_at set
iff history non-empty).
- Emit one observation per post (status ok/fail) and/or per-discrepancy.
2. **attest_chain** β verify the 1f916 attest hash chain.
- `GET /api/attest` (client). Parse the chain of blocks; verify each block's
hash is the SHA-256 of its declared content (block links to previous hash).
The exact wire shape is determined at implementation from a sample response
(documented in AGENTS.md); the check must at minimum verify: (a) the head
hash equals the hash of the head content, (b) consecutive blocks chain so
`prev_hash` matches the prior block's hash, (c) each hash has the expected
fixed length. Any mismatch β `fail` observation (subject = block index,
metric = "chain_integrity").
3. **engagement** β verify Pengy's 1f916 activity stays within caps and the
daily post happened.
- From `/api/me` (PKI-authed client) read today's `posts_used`,
`comments_used`, `votes_used`, `tags_used` vs caps (1/20/50/20). Over cap β
`fail`. The daily post metric: if `posts_used == 0` and local state says a
post was expected today β `absent` (presence metric, cadence=24h).
4. **wake_presence** β verify scheduled wakes happened (composes item #20).
- For each cron source in config (e.g. `1f916_daily`, `1f916_heartbeat`),
use `remote.stat_mtime(logpath)` to get last-write epoch; if
`now - mtime > red_window` β `absent` (subject = cron id, metric =
"run_mtime"). This is the "an event that never fires is invisible"
detector, and is `hard: true`.
## CLI (`verifier.py`)
```
python verifier.py --once # run all enabled checks once, record obs,
# update baseline, dispatch new findings, exit
python verifier.py --check NAME # run a single check
python verifier.py --dry-run # same as --once but no dispatch (print findings)
python verifier.py --status # print latest stored status per check/subject
python verifier.py --findings --since HOURS # list stored findings in the window
```
`--once` is the default cron mode; the runner is scheduled externally (cron /
systemd timer), it does NOT self-loop. Exit code 0 unless a `fail`/`absent`
finding was emitted in `--once` in which case exit 1 (so cron can be monitored).
## Conventions
- Python 3.11+, stdlib + `moofile` only (`pytest` for tests). No FastAPI, no
Flask, no requests (use urllib for the tiny HTTP client).
- `datetime` always timezone-aware UTC.
- `config.json` (loaded by the CLI): `{ "store": ..., "host": ..., "window": {n},
"k": 3.0, "min_observations": 3, "checks": {name: {enabled, params}},
"dispatch": {"enabled": true, "identity": "verifier"} }`.
- Atomic writes: store operations must be safe under a single process (the CLI is
single-process; no lock needed, but read-modify-write on `meta` must be
confined to one check run).
## Non-goals
- No web UI, no daemon loop inside the artifact (scheduling is external).
- No auto-embedding / semantic search / ONNX (moofile search not required).
- No self-modification or self-healing of Pengy β the verifier observes, records,
reports; it never changes what it verifies (report-only, consistent with item
#23).
- No DB migrations / no hard dependency on a specific 1f916 schema beyond what
the sample response shows (document any assumption in AGENTS.md).
## Verification (the objective function)
Tests are first-class and run via `python -m pytest -q`. They MUST all pass with
**no network**. Core coverage:
- `test_baseline.py` β numeric drift triggers at kΒ·stdev; absence triggers on a
hard presence metric when the signal is missing; too-few-observations stays ok.
- `test_store.py` β append observation, read back, filters by check/subject/ts,
meta read/update.
- `test_runner.py` β register two fake checks: one returns a stable value (no
finding), one returns a drifting/absent value (emits a finding); verify the
finding is dispatched once, deduped on second run, and BotTalk is fail-soft.
- `test_memory_integrity.py` / `test_attest_chain.py` / `test_engagement.py` /
`test_wake_presence.py` β using fake clients, verify the check builds the
right request and parses a canned response into correct observations (including
the failing cases).
- `test_verifier_cli.py` β `--once` with a config pointing at fake checks runs
without error and populates the store.
The spec says "docs, code, tests" β a `README.md` documenting the architecture,
the config, how to run `--once`, and how checks are registered. The deliverable
must be a clean, self-contained repo the operator can drop into
`~/Personal/skills/verifier/`.