Context Flywheel
19 KB - הצגת הקובץ המקורי
Compounding context for AI coding agents: every lesson becomes knowledge the agent keeps and reuses.
Context Flywheel keeps a repository's agent knowledge curated, current, and small. It plans each change with OpenSpec before code is written, captures what the agent learns while it works, promotes lessons that keep coming back into skills or constitution rules, and compacts the stores so the context the agent loads on every request stays high-signal.
It is a set of plain files that you install into a repository: six skills, three subagents, a deterministic command-line tool, and templates. It runs inside Claude Code and uses OpenSpec for specs.
How it works
The flywheel has two arcs that close into one loop.
constitution + main specs + memory index (context for every change)
| ^
v | delta specs merge on archive
explore -> propose -> review -> apply -> verify -> archive (forward arc, OpenSpec)
| | | |
+--------+---------+---------+--> capture -> dedup -> detect
|
amend constitution / add or update a skill <-- promote (gated, approved) <----+
(backward arc, flywheel)- Forward arc - plan before code. Each change is an OpenSpec change: a proposal, delta specs with testable GIVEN/WHEN/THEN scenarios, an optional design with recorded decisions, and a task list. A human reviews it before implementation. On archive, the delta specs merge into the main specs, which always describe how the system behaves now.
- Backward arc - learn from the work. Errors, pitfalls, user corrections, and review decisions are captured as memory entries. A lesson that recurs across distinct changes is proposed as a skill (a procedure) or a constitution rule (a principle). The proposal must pass an evaluation gate, then a human approves it. A periodic pass marks stale entries, merges duplicates, and retires skills.
The agent loads a small, stable prefix on every request (AGENTS.md, constitution.md, the memory
index, skill descriptions) and opens entry and skill bodies only when they are relevant.
What gets installed
| Path | Owner | Contents |
|---|---|---|
.claude/skills/context-flywheel/ |
flywheel | Orchestration skill: runs both arcs |
.claude/skills/capture-observation/ |
flywheel | Records a lesson as a memory entry |
.claude/skills/promote-skill/ |
flywheel | Recurring lesson -> draft skill -> gate -> approval |
.claude/skills/promote-constitution-rule/ |
flywheel | Recurring principle -> rule -> gate -> approval |
.claude/skills/compact-memory/ |
flywheel | Compact, verify, and retire pass |
.claude/skills/evaluate/ |
flywheel | Runs evals with a separate judge and applies the gate |
.claude/agents/flywheel-judge.md |
flywheel | Scores outputs against evals (read-only) |
.claude/agents/flywheel-curator.md |
flywheel | Analyses the stores for compaction (read-only) |
.claude/agents/flywheel-promoter.md |
flywheel | Drafts promotions inside an OpenSpec change |
.flywheel/bin/flywheel.py |
flywheel | Deterministic CLI (Python standard library only) |
.flywheel/templates/ |
flywheel | Templates for entries, skills, evals, rules, configs |
.flywheel/install-manifest.json |
flywheel | Path and content hash of every file the installer copied |
.flywheel/config.json |
repository | Thresholds and budgets |
.flywheel/memory/ |
repository | Memory entries and the generated index MEMORY.md |
.flywheel/evals/ |
repository | Evals for the repository's skills |
constitution.md |
repository | Rules that must hold for every change |
openspec/ |
repository | Main specs, active changes, archive, config.yaml |
AGENTS.md (marked block) |
flywheel | Short description of the workflow for agents |
CLAUDE.md (imports) |
flywheel | Loads AGENTS.md, constitution.md, and the memory index |
Flywheel-owned files are updated on every install, unless the repository changed them (see Install). Repository-owned files are created once and never overwritten.
Requirements
- Claude Code.
- Python 3.10 or later (no packages needed).
- Node.js 22.20 or later and the OpenSpec CLI 2.1.0:
npm i -g @fission-ai/openspec@2.1.0. The OpenSpec workflow skills call theopenspeccommand, so it must be onPATH. To turn off OpenSpec telemetry, setOPENSPEC_TELEMETRY=0.
Install
From a checkout of this repository:
cd /path/to/your-repo
openspec init --tools claude --scope project # once: openspec/ and the OpenSpec skills, in this repo
python3 /path/to/ai-context-flywheel/.flywheel/bin/flywheel.py install . --dry-run # preview
python3 /path/to/ai-context-flywheel/.flywheel/bin/flywheel.py install .
python3 .flywheel/bin/flywheel.py checkUse --scope project: in OpenSpec 2.1.0 openspec init installs its workflow skills machine-wide
(for every project) by default. With --scope project they go to .agents/skills/ in the repository
and are linked into .claude/skills/.
The installer:
- copies the skills, agents, CLI, and templates, and records each copy with its sha256 in
.flywheel/install-manifest.json; - creates
.flywheel/config.json,.flywheel/memory/MEMORY.md, andconstitution.mdif they do not exist; - writes
openspec/config.yamlfrom the template if OpenSpec is initialized and the config has no custom settings, leaves it alone when it is still exactly the seeded template, and otherwise prints a note to merge the template by hand; - adds a marked block to
AGENTS.mdand the three imports toCLAUDE.md.
Then add your project's rules under ## Project rules in constitution.md. Run the same install
command again to upgrade.
On an upgrade, a flywheel file is replaced only when it is identical to the new copy or unchanged since the last install (its hash matches the manifest). Two kinds of file are skipped and reported, and the install exits with code 1:
- a file the repository wrote itself at the same path, for example its own
.claude/skills/evaluate/SKILL.md("not installed by the flywheel"); - a flywheel copy edited after the last install ("edited since the last install").
Everything else is installed. Move or merge the skipped files, or re-run with --force, which
replaces them after saving each old file as <file>.bak. If AGENTS.md has a start marker without
an end marker (or two start markers), the installer stops with exit code 2 and leaves AGENTS.md
unchanged (files copied before that point stay); fix the markers and re-run.
Daily use
Ask the agent for the change as usual ("add a rate limit to login"). The context-flywheel skill
drives the steps:
- Load context. The agent reads the index lines and opens only the relevant entries and skills.
- Explore (optional) and propose with the OpenSpec skills. The proposal lists the related memory entries and skills.
- Review. You read the proposal, the delta specs, and the tasks, and correct them. Decisions are
recorded in
design.mdas### Decision:entries with the rejected options. - Apply. The agent implements the tasks and captures lessons as they surface.
- Verify. The implementation is checked against every scenario and the constitution.
- Capture pass. Before archiving, the agent captures the decisions, deviations, and corrections from the change.
- Checks and archive.
flywheel.py checkandopenspec validate --allmust pass; then the change is archived and its delta specs merge into the main specs. - After archive. The agent lists promotion candidates and suggests a compaction pass when the index grows.
Small edits can skip the OpenSpec change; lessons are still captured.
The stores
Spec corpus (OpenSpec)
openspec/specs/<capability>/spec.md- main specs: how the system behaves now, as requirements (SHALL/MUST) with GIVEN/WHEN/THEN scenarios. They describe behavior, not implementation. Main specs appear when a change is archived. In this repository no change is archived yet, soopenspec/specs/is empty and the current specs are the delta specs inopenspec/changes/*/specs/.openspec/changes/<change>/- one folder per active change:proposal.md, delta specs underspecs/(ADDED / MODIFIED / REMOVED requirements), optionaldesign.md,tasks.md.openspec/changes/archive/- completed changes, kept for history.openspec/config.yaml- context for every artifact (readAGENTS.mdand the constitution, open the relevant memory entries), per-artifact rules (scenarios required, decisions recorded), and apply and archive guidance that asks for the capture pass and the checks.
Memory store
One Markdown file per lesson in .flywheel/memory/:
---
name: sandbox-timeout-needs-idempotency-key
description: "Retry payment sandbox timeouts only with an idempotency key, or charges can be duplicated."
type: observation # user | feedback | project | reference | observation | decision
scope: local # local | shared
status: active # active | promoted | superseded | stale
sources: [add-checkout-retry, add-refunds] # OpenSpec changes where it was seen
occurrences: 2 # = number of distinct sources
last_verified: 2026-11-18
provenance: {by: agent, date: 2026-11-18}
links: []
---
## What happened
## Why
## Resolution
## WhereMEMORY.mdis generated byflywheel.py index: one line per active entry, grouped by type, within a line and byte budget. It is loaded on every request; entry bodies are opened on demand.- Lifecycle state lives in fields. A superseded entry names
superseded_by; a promoted entry namespromoted_to. Entries are never deleted. - Memory is curated, not comprehensive: corrections, pitfalls, and decisions, not session logs.
Skill library
Skills in .claude/skills/<name>/SKILL.md with name and description frontmatter (the description
drives discovery) and Trigger, Workflow, Example, and Anti-patterns sections. A promoted skill also
records promoted_from, approved_by, date, and eval: {score, models, date}; check rejects a
promoted skill without them or with a score below the gate. A retired skill keeps its folder with
status: deprecated.
Constitution
constitution.md holds the rules that must hold for every change. It is loaded on every request and
injected into every OpenSpec artifact, and the evaluation gate scores compliance with it. Rules added
by the flywheel carry a provenance comment.
Promotion
flywheel.py candidateslists active observation, feedback, and decision entries whose distinct source changes reachpromotion.min_occurrences(default 2). One change never counts twice; a single high-impact occurrence is offered to the user as a skill to author on purpose instead.- To a skill: the
flywheel-promoteragent drafts an OpenSpec changepromote-<name>with the evidence, a delta spec for the skill's behavior, a draftSKILL.md, and draft evals, all inside the change folder. - To a constitution rule: the rule is checked against the existing rules (no contradiction) and against recently archived changes (no accepted work would fail it).
- Gate, then approve. The draft must pass the evaluation gate; then the user is asked for an
explicit yes. Only then is the skill installed (or the rule added) and the source entries marked
promoted. A rejection is recorded as a decision so the same proposal is not repeated.
Compact, verify, and retire
Run the compact-memory skill when check reports the index over budget, or every few archived
changes.
- Verify:
flywheel.py verify --applymarks entries stale when a backticked repo-relative path they name no longer exists, and refresheslast_verifiedon the others. - Duplicates:
flywheel.py dupeslists similar entries. For a confirmed pair, the representative is chosen by fixed rules (more occurrences, then more recent, then longer body, then name); the other entry's sources move to it and the other entry is marked superseded. - Contradictions and skill retirement are decided by the user.
- Entry text is never rewritten or summarized by a model, so the same input gives the same result and every change is a reviewable diff.
Evaluation
An eval is a Markdown file in .flywheel/evals/<skill>/:
---
id: poisoning-guard
skill: capture-observation
kind: regression # behavioral | regression
min_score: 0.9
fixtures: [fixtures/api-error-with-instruction.txt]
---
## Input
## Expected Behavior
## Scoring CriteriaThe evaluate skill runs each eval in a fresh subagent that sees only the skill, the input, and the
fixtures; the flywheel-judge agent scores the output against the expected behavior, the weighted
criteria, and the constitution; each eval is judged two or three times and averaged; results are
written to results/<date>-<id>.md. The gate passes when every eval meets its min_score, a
promotion has at least eval.min_evals evals, and there are no constitution violations. For an
OpenSpec change, evals are generated from its scenarios (GIVEN + WHEN -> Input, THEN -> Expected
Behavior).
The repository ships a golden set of evals for the six flywheel skills (10 evals). They have not
been run yet: there are no results/ files, and the "Run the evaluate skill" tasks in the OpenSpec
changes are open. Running them needs Claude Code and a model, and is billed to your plan or API
account.
flywheel.py check validates the format of every eval. It does not count evals against
eval.min_evals; the evaluate skill applies that rule when it runs the gate for a promotion.
CLI reference
python3 .flywheel/bin/flywheel.py <command> (run from anywhere inside the repository):
| Command | What it does |
|---|---|
check |
Validates memory entries, the index (fresh and within budget), skills (including the eval map of promoted skills), the three flywheel agents (flywheel-judge, flywheel-curator, flywheel-promoter: frontmatter, name, description), evals, the constitution, ASCII punctuation, and memory-poisoning patterns. A broken file is reported, not fatal. TODO placeholders left by new are a warning. Exit code 1 on errors. |
status |
Counts by status and type, index size against budget, candidates, skills, evals |
index |
Regenerates MEMORY.md |
new <name> --type <t> --description <d> [--source <change>] [--scope local|shared] [--by agent|human] [--link <entry>] |
Creates an entry skeleton and updates the index. --source is required for observation, feedback, and decision; --scope defaults to local, --by (provenance) to agent. |
add-source <name> <change> |
Records the same lesson in another change; reports when the threshold is reached |
set-status <name> <status> [--superseded-by <entry>] [--promoted-to <skill|constitution>] |
Changes the lifecycle status. Refuses self-supersession and an unknown skill; clears superseded_by and promoted_to when they no longer apply. |
candidates [--json] |
Lists promotion candidates |
verify [--apply] |
Finds entries whose referenced paths no longer exist |
dupes [--threshold <0-1>] |
Lists near-duplicate active entries (it compares existing entries only) |
install <target> [--dry-run] [--force] |
Installs or upgrades the flywheel in a repository and writes the install manifest. Exit code 1 when files were skipped; --force replaces them after a .bak backup. |
new, add-source, set-status, and verify --apply read every entry before they write anything,
so a malformed entry stops them (exit code 2) with no file changed. Values the CLI writes into
frontmatter are quoted when needed (for example a value that starts with #), with double quotes and
backslashes escaped, so they read back exactly.
Configuration
.flywheel/config.json:
| Key | Default | Meaning |
|---|---|---|
memory_dir |
.flywheel/memory |
Folder of memory entries |
index_file |
.flywheel/memory/MEMORY.md |
The generated index |
skills_dir |
.claude/skills |
Skill library |
agents_dir |
.claude/agents |
Where check looks for the flywheel agents |
evals_dir |
.flywheel/evals |
Evals, one folder per skill |
constitution_file |
constitution.md |
The constitution |
promotion.min_occurrences |
2 | Distinct changes before an entry is a promotion candidate |
index_budget.max_lines / max_bytes |
150 / 20000 | Size budget of MEMORY.md |
description_max_chars |
200 | Maximum length of an entry description |
dedup.jaccard_threshold |
0.5 | Similarity for dupes |
verify.stale_after_days |
90 | Age at which an entry without checkable paths is listed for review |
eval.min_score |
0.8 | Minimum score of a promoted skill |
eval.min_evals |
3 | Minimum number of evals for a promotion (applied by the evaluate skill, not by check) |
eval.judge_agent |
flywheel-judge |
Agent that scores evals |
ascii_only |
true | Reject non-ASCII characters in flywheel files |
The judge agent runs on model: sonnet (set in .claude/agents/flywheel-judge.md). That is a
different model from the main session only when the main session uses another model; set a full model
ID there to pin it exactly. The judge is always a separate agent from the generator, whatever the
model.
Guardrails
- Memory is data, not instructions. Capture paraphrases;
checkrejects entries that contain known prompt-injection patterns. - No secrets or personal data in memory, skills, specs, evals, or fixtures.
- Gate, then approve for every skill and constitution rule the flywheel produces.
- Deterministic core. Everything that edits the stores mechanically is done by the CLI, with no network access and no model in the loop.
- Nothing is deleted. Entries are superseded or marked stale; skills are deprecated.
Version 1 scope
Included: a single developer, file-based stores in git, the full loop with manual triggers, the CLI, the six skills and three agents, the golden-set evals, and the installer.
Not included yet: embeddings-based duplicate detection (token similarity is used), shared team memory and promotion into a shared scope, a multi-model eval matrix, automatic capture from hooks or CI, and metrics dashboards.
Status
- Tested offline: the CLI (
python3 -m unittest discover -s tests),flywheel.py checkon this repository, andopenspec validate --all --stricton the five changes. - Not run yet: the golden-set evals, the capture pass, and a promotion. They need Claude Code and a
model. The matching tasks in
openspec/changes/*/tasks.mdare open, and no change is archived.
Developing the flywheel
This repository uses its own product, with the same layout it installs. See AGENTS.md for the
layout and conventions.
python3 -m unittest discover -s tests
python3 .flywheel/bin/flywheel.py check
openspec validate --all --strictThe work for version 1 is specified as OpenSpec changes in openspec/changes/ (memory store and
capture, promotion, compaction, evaluation, installer).