context-purge
Compress the fleet's markdown context files — CLAUDE.md files and SKILL.md files — removing prose while preserving every directive, gotcha, and trigger, then prove it with a validation harness. Use to
Files9
View on GitHubSKILL.md.claude/skills/context-purge/SKILL.md
GitHubcontext-purge
Goal: cut the always-on context tax by rewriting the fleet's markdown context files — the compression counterpart to /context-audit (which only measures and flags). Contract is lossless in directives: nothing the LLM is told to do (or forbidden from doing) may disappear; only the prose around it does. Every purge run must pass the validation harness before it merges.
Fleet-only tier by design: a global skill's description would load into every session of every repo — self-defeating for a skill shrinking that surface. One home, executed from fleet-config.
Modes
/context-purge(default) — fleet-config-owned surface:global-CLAUDE.md,fleet-config/CLAUDE.md, andSKILL.mdfiles in both tiers (skills/,.claude/skills/). One branch/PR in this repo./context-purge fleet— fleet-wide sweep: default surface plus every sister git repo underE:\automation\(skip linked worktrees —.gitmust be a directory): each repo'sCLAUDE.md+ any.claude/skills/*/SKILL.md. Compress only where real savings; skip clean/lean files. One branch + PR per repo, each with its own validation report. Respect the model-tier policy (docs/model-tiers.md) if fanning out sub-agents.
Both modes merge their own validated rewrites (fleet-config#1312); nobody is waited on. A repo's PR is marked ready and squash-merged only when digest.py merge-check passes (Validation harness, item 5). A rewrite that fails validation is never merged: fix and re-probe it, or leave the PR a draft (or don't open one) and report it as failed. The owner reviews afterwards from the digest and reverts anything he dislikes with one git revert.
Skip-unchanged ledger (reconcile, then gate — always, in that order)
A file is re-assessed only when its bytes changed since it was last assessed — never rewrite the same unchanged file week after week. gate.py keys on content hashes (sha256/12) recorded in one kind=context-purge ledger issue in fleet-config (title context-purge ledger, label audit-meta, managed via audit_issue.py).
Reconcile first (fleet-config#757): a purge PR that was never merged must not go on suppressing its files forever. reconcile syncs the ledger against what actually happened to every chore/context-purge-* PR — a merged PR's file is filled with its content at that PR's own merge commit (never main's ever-moving tip) only when the ledger has no entry for it — an existing entry may be a later advance and is never overwritten; a closed-unmerged PR's ledger entry is dropped only when it equals the hash that PR's branch produced, so the never-landed assessment re-enters to_purge while a newer entry stays (an unresolvable branch hash is reported as not verifiable, never folded into clean); a still-open PR is left untouched and reported in the backlog instead — the safe default is to re-offer, never silently suppress:
E:/automation/fleet-config/.venv/Scripts/python.exe .claude/skills/context-purge/gate.py reconcile [--fleet] --json > <scratch>/reconcile.json
Then gate:
E:/automation/fleet-config/.venv/Scripts/python.exe .claude/skills/context-purge/gate.py gate [--fleet]
Prints TO_PURGE lines + a SUMMARY: — only those files are read at all. With --fleet, dormant repos (docs/fleet-scope.md) are skipped and named on SKIPPED_DORMANT=: not assessed, so the surface is not clean for them. to_purge=0 → report "surface unchanged since last run" and stop (a valid, successful run). After the run, record every assessed file — both the rewritten ones and the ones judged already-lean (both count; neither should re-surface until edited):
E:/automation/fleet-config/.venv/Scripts/python.exe .claude/skills/context-purge/gate.py advance [--fleet] --only <path> [<path> ...]
advance merges over the existing ledger (entries outside the scanned surface are preserved) and upserts the issue. Pass --only with the files you actually assessed. A fleet run is normally partial (large surface, lean files skipped by design, per-repo failures reported and skipped), so a bare advance would record files nobody read and silently suppress them from every future run until edited. Bare advance (whole surface) is correct only when the run genuinely assessed every gated file. Unknown paths are a hard error, not a silent no-op.
advance runs after the merge, so a rewritten file's hash is recorded only for content that landed. A draft left behind by a failed validation is not advanced; the next run's reconcile drops a stray entry that equals the abandoned branch's hash, and the backlog section in every digest (below) makes a waiting PR visible before it goes stale.
Priorities (highest value first)
- Skill
description:frontmatter — always-on in every session; hold to the ≤ ~50-word prose cap (quoted trigger examples exempt and untouchable). global-CLAUDE.md— always-on in every session of every repo.- Project
CLAUDE.mdfiles — always-on in that project's sessions. SKILL.mdbodies — load only on invocation; compress conservatively (they are procedural — a lost step is a broken workflow) and only where prose dominates.
Compression contract (per file)
- Measure before:
.claude/skills/context-audit/audit.py(whole surface) orcheck.pybelow (per file). - Extract the directive inventory first — before touching the file, list every imperative rule, prohibition, gotcha, path, command, port, threshold, and quoted trigger it carries. Save it (scratchpad is fine). This checklist is the contract; the rewrite must satisfy 100% of it.
- Branch-disclosure test (
SKILL.mdbodies). Every branch needs the inline material; material only some branches reach goes in a linked sibling file. A branch is a distinct case the skill handles: a mode, a harness, a repo shape, a failure path. For each section ask whether every invocation reaches it. If not, move it verbatim to<skill dir>/<topic>.md, which opens with one line naming the branch that loads it. In the main file, leave what every run needs: the trigger that selects the branch, the no-op case, what to report. Then add a pointer whose wording names the branch, e.g.**`TOUCHED=yes`** → read [`ux-conformance.md`](E:/automation/fleet-config/skills/issue-finish/ux-conformance.md). In fleet-config's junctioned tiers, link a sibling by its absoluteE:/automation/fleet-config/...path, which resolves under the junction, with the file name backticked in the link text so the instruction ratchet lints the sibling too. A sister repo's project skill links a sibling relatively. Make the move its own commit, before any compression, and prove it withcheck.py --moved-to(Validation harness, item 1). Compress afterwards, under item 4. - Rewrite. Move history, never delete it:
history.py scanlists it;history.py relocateposts a span verbatim on the issue it cites, reads it back, then leaves a pointer ((#N);<!-- history: repo#N -->indocs/). Remove: repeated rationale, hedging, restatements of what code/README already records, anything single-homed elsewhere (per the/context-auditstandard). Keep: every inventory item; a load-bearing why compressed to one clause when it prevents re-litigating a decision; issue references (#N) as pointers. - Never touch (byte-identical):
- Marked machine-managed blocks — any
<!-- name:part:start/end -->pair (regenerated by the skill that owns it;check.pyfails on drift). - Quoted trigger examples in skill descriptions (the routing surface).
- Agent-neutrality markers in
global-CLAUDE.md— (Claude Code only — skip on other agents) etc.; it is read by four agents.
- Marked machine-managed blocks — any
- Measure after; record per-file before/after tokens.
Validation harness (go/no-go, per run)
- Deterministic — for every touched file:
must exit 0 (marked blocks byte-identical, quoted triggers preserved, frontmatter still parses as YAML) and prints the token delta. A branch-disclosure split addsgit show HEAD:<file> > <scratch>/before && E:/automation/fleet-config/.venv/Scripts/python.exe .claude/skills/context-purge/check.py <scratch>/before <file>--moved-to <sibling>...: every sentence of the original must be in the main file or a sibling (reflow- and link-target-insensitive), each missing one printsLOSTand exits 2, andWORDS:gives the main file's before/after word count for the PR body.check.py --base origin/mainruns the same check over every instruction file the branch changed (what aprompt-driftcleanup lane runs; exit 3 = the diff could not be taken, never a pass).history.py verify --base origin/mainmust also exit 0 (removed history found on a cited issue; 3 = unknown). Then re-runaudit.py: totals down, no new over-cap descriptions, no new single-home leaks. Then the repo gate (py_compile+tests/run_acceptance.py). - Directive inventory — walk each file's saved inventory item by item against the rewrite; every item must still be discharged (verbatim or semantically intact).
- Agent-based before/after probe — for each substantially rewritten file: derive ~10–20 behavioral questions from the original ("what must never appear in a commit message?", "which Python do you invoke?"). Spawn fresh Haiku sub-agents (weaker model = stricter clarity test, cheap; Sonnet acceptable) whose only context is the compressed file; same questions to a control agent reading the original. Grade both against original-derived expected answers. A split file's compressed agent starts from the main file and opens a sibling only where a pointer sends it, and some questions must have answers that live only in a sibling. Pass = compressed score ≥ control score. Any question the compressed file fails but the control passes → restore that content and re-probe.
- Report — the PR body carries the per-file before/after token table, probe scores (compressed vs control), and the inventory result. No screenshots.
- Merge gate — write the repo's entry to
<scratch>/run/<repo>.json(risk.checked: trueonly after items 1–3 passed), then runE:/automation/fleet-config/.venv/Scripts/python.exe .claude/skills/context-purge/digest.py merge-check <scratch>/run/<repo>.json. Exit 0 → may merge. Exit 2 (MERGE=blocked: …) → do not merge; anything unrecorded blocks (unknown is not a pass).digest.py validatere-applies the same rule to every repo recorded as merged, so the digest rejects a merge the gate would have blocked. fleet-config's own PR clears the identical bar — no weaker gate for the repo whosehooks/andskills/are junctioned live into~/.claude.
Steps (default mode)
- Reconcile, then gate:
gate.py reconcile --json > <scratch>/reconcile.json, thengate.py gate—to_purge=0→ report "surface unchanged" and stop. Otherwise only the listed files proceed. Keep<scratch>/reconcile.json— step 8 reuses it for the digest's backlog section. - Branch off fresh
main(normal issue workflow; never purge onmain). - Snapshot originals +
audit.py --jsonbaseline to the scratchpad. - Purge the gated files in priority order per the compression contract.
- Run the validation harness; restore-and-re-probe on any regression.
- Open the PR (draft) with the validation report. Run
merge-check; on exit 0,gh pr readythengh pr merge --squash --delete-branch, and recordmerge(below). Exit 2 → leave the draft, recordmerge.state: not-mergedwith the reason. - Advance the ledger (
gate.py advance --only …) for the merged rewrites and the files judged lean — never for a rewrite left unmerged, which must re-enterto_purge. - Sync the live checkout (below), then publish the run digest. Not optional, and not only on the happy path.
Fleet mode is the same loop with --fleet on both reconcile/gate/advance, grouping the to-purge files by repo (one branch + PR per repo). Designed to degrade, not block — a per-repo failure is reported and skipped so the scheduled run always finishes. Merge fleet-config's own PR last.
Live checkout. After a merge, fast-forward that repo's primary checkout only via skills/_lib/untrack_guard.py fast-forward <repo-dir> — never a bare git pull (fleet-config#1086) — and only when it is clean, on its default branch, has no .git/index.lock and no live session (skills/_lib/chief_ops.py sessions). Otherwise leave it and record why. fleet-config's primary is the live junction: same rules. No tray restarts (markdown only). Never force-push.
Run data — what every worker reports back
The digest renders the run's own data, never the PR bodies — the PR body and the digest are two renderings of one structure, so the numbers cannot disagree. Each per-repo worker writes <scratch>/run/<repo>.json; the orchestrator concatenates them into one run.json:
{ "run_id": "<YYYYMMDDThhmmss>", "mode": "fleet", "status": "complete|partial",
"gate": {"to_purge": 41, "unchanged": 12, "surface": 53},
"unreached": [{"repo": "life-os", "reason": "gh auth failed"}],
"repos": [{
"repo": "project-scaffolding", "status": "shipped|skipped|failed", "pr": "<url>|null",
"merge": {"state": "merged|not-merged", "sha": "<squash sha>", "reason": "<why not>",
"primary": {"state": "fast-forwarded|left", "reason": "<why left>"}},
"risk": {"always_on": true, "shape_change": "large|medium|small", "checked": true},
"files": [{"path": "CLAUDE.md", "action": "rewritten|assessed-lean|untouched",
"tokens_before": 4210, "tokens_after": 3120, "lines_before": 160, "lines_after": 118,
"inventory_items": 57, "inventory_discharged": 57,
"probe": {"ran": true, "questions": 14, "compressed": 13, "control": 13}}],
"descriptions": [{"path": "…/SKILL.md", "words_before": 62, "words_after": 44,
"before": "…", "after": "…"}],
"decisions": [{"summary": "…", "detail": "…", "where": "PR #123"}],
"not_fixed": [{"summary": "…", "reason": "…"}]
}] }
Token counts come straight from check.py's TOKENS: line; gate from gate.py gate's SUMMARY:.
status: shipped means merged. A shipped repo carries merge (null = not recorded); merged needs sha, not-merged needs reason, a primary left behind needs reason. A rewrite that failed validation is failed, never shipped.
A figure the run could not establish is reported as unknown, never as zero. "probe": null means not recorded; "probe": {"ran": false} means deliberately not probed; these are different facts and the digest renders them differently. Omit a token or inventory field you did not measure rather than writing 0. Every rewritten file must carry a probe key — null is a valid answer, silence is not.
action is three-valued on purpose. assessed-lean and untouched files are listed in the digest so "not in the diff" cannot read as "not looked at".
Step 8 — publish the digest
The digest is the review surface for what the run already merged: per file the token and line delta, the blast radius (global file → every agent fleet-wide; repo CLAUDE.md → that repo's sessions; SKILL.md → whoever invokes it), and per repo the merged PR + SHA with its git revert and whether the live checkout was fast-forwarded. The Telegram ping leads with merged/not-merged counts.
Run from the fleet-config repo root. Validate first: run data that would make the digest lie is a hard stop, not something to render around.
E:/automation/fleet-config/.venv/Scripts/python.exe .claude/skills/context-purge/digest.py validate <scratch>/run.json
E:/automation/fleet-config/.venv/Scripts/python.exe .claude/skills/context-purge/digest.py render <scratch>/run.json \
--md <scratch>/digest.md --html <scratch>/digest.html --chat-text <scratch>/digest.txt \
--reconcile-json <scratch>/reconcile.json
--reconcile-json points at step 1's reconcile --json output (fleet-config#757) — it carries the live open-purge-PR backlog into the digest's "Open purge PR backlog" section. Omit it (or lose the file) and the section renders "not recorded", never a silently-clean backlog.
Then publish the durable copy — a comment on the managed [ledger] context-purge run digests issue — and ping Telegram. Order matters: publish first so the Telegram message has a link, then record whether the ping landed.
E:/automation/fleet-config/.venv/Scripts/python.exe .claude/skills/context-purge/digest.py publish <scratch>/run.json --md <scratch>/digest.md --delivery-state unknown
cat <scratch>/digest.txt | E:/automation/fleet-config/.venv/Scripts/python.exe hooks/notify_send.py --category log
notify_send.py is the fleet's one Telegram transport — never add a second notifier. It never raises and reports failure through its exit code, so check it: re-run publish with --delivery-state posted or --delivery-state failed to stamp the outcome. unknown is treated as not-confirmed downstream, which is the correct default if you cannot tell.
Optionally publish digest.html as a private Artifact and re-render with --url <artifact-url> so the durable copy references it. This is best effort — an Artifact publish is unproven from a headless run (see /fleet-health's SKILL.md), so it may never be the only link. A failure here is a line in the digest, not a failed run.
A run that fails partway still publishes a digest. Set "status": "partial" and name every repo in unreached with a reason; the digest renders a banner and the Telegram message leads with it. A missing Telegram message is indistinguishable from a run that never started.
Delivery is asserted, not assumed. Every published comment carries <!-- context-purge-digest run=… status=… unreached=N delivery=… -->. delivery_check.py — wired into run-weekly.bat via claude_progress.py --delivery-check — exits non-zero unless a fresh digest comment exists and reports status=complete and delivery=posted, so a partial run and a silently failed ping both turn the scheduled job red. It is strict when invoked with no arguments because that is exactly how the adapter invokes it.
Wiring the weekly schedule
An app-launcher Job (Windows Task Scheduler \AppLauncher\) runs the fleet sweep weekly — Saturdays 01:00, on Opus — via the co-located launcher .claude/skills/context-purge/run-weekly.bat (per this repo's scheduled-skill convention).
The wrapper preserves /context-purge fleet, Opus, and bypass permissions while streaming filtered milestones through claude_progress.py, and passes --delivery-check so the job cannot exit 0 having published nothing (fleet-config#627).
The scheduled run merges unattended (--permission-mode bypassPermissions); the owner reviews the digest afterwards.
The ledger gate makes the scheduled run cheap: an unchanged week costs one gh read and stops. A to_purge=0 run still publishes a digest — "surface unchanged since last run" is a result, and a silent week is indistinguishable from a job that never fired.