.flywheel/bin/flywheel.py
45 KB - Открыть исходный файл
#!/usr/bin/env python3
"""Context Flywheel CLI: deterministic operations on the memory store, skills, and evals.
Stdlib only, no network access. The same input always produces the same output, so every
change this tool makes is reproducible and reviewable as a plain diff.
Usage: python3 .flywheel/bin/flywheel.py <command> [options] (run with --help for the list)
"""
from __future__ import annotations
import argparse
import datetime as _dt
import hashlib
import json
import re
import shutil
import sys
from pathlib import Path
VERSION = "0.1.0"
MEMORY_TYPES = ("user", "feedback", "project", "reference", "observation", "decision")
MEMORY_SCOPES = ("local", "shared")
MEMORY_STATUSES = ("active", "promoted", "superseded", "stale")
PROMOTABLE_TYPES = ("observation", "feedback", "decision")
SKILL_STATUSES = ("active", "deprecated")
EVAL_KINDS = ("behavioral", "regression")
EVAL_SECTIONS = ("## Input", "## Expected Behavior", "## Scoring Criteria")
PROVENANCE_BY = ("agent", "human")
# Canonical field order when a memory entry is written back to disk.
ENTRY_FIELD_ORDER = (
"name", "description", "type", "scope", "status", "sources", "occurrences",
"last_verified", "provenance", "links", "superseded_by", "promoted_to",
)
FLYWHEEL_SKILLS = (
"context-flywheel",
"capture-observation",
"promote-skill",
"promote-constitution-rule",
"compact-memory",
"evaluate",
)
FLYWHEEL_AGENTS = ("flywheel-judge.md", "flywheel-curator.md", "flywheel-promoter.md")
AGENTS_START = "<!-- context-flywheel:start -->"
AGENTS_END = "<!-- context-flywheel:end -->"
INSTALL_MANIFEST = ".flywheel/install-manifest.json"
CLAUDE_IMPORTS = ("@AGENTS.md", "@constitution.md", "@.flywheel/memory/MEMORY.md")
DEFAULT_CONFIG = {
"version": 1,
"memory_dir": ".flywheel/memory",
"index_file": ".flywheel/memory/MEMORY.md",
"skills_dir": ".claude/skills",
"agents_dir": ".claude/agents",
"evals_dir": ".flywheel/evals",
"constitution_file": "constitution.md",
"ascii_only": True,
"description_max_chars": 200,
"promotion": {"min_occurrences": 2},
"index_budget": {"max_lines": 150, "max_bytes": 20000},
"dedup": {"jaccard_threshold": 0.5},
"verify": {"stale_after_days": 90},
"eval": {"min_score": 0.8, "min_evals": 3, "judge_agent": "flywheel-judge"},
}
SLUG_RE = re.compile(r"^[a-z0-9]+(?:-[a-z0-9]+)*$")
DATE_RE = re.compile(r"^\d{4}-\d{2}-\d{2}$")
NON_ASCII_RE = re.compile(r"[^\x00-\x7f]")
BACKTICK_RE = re.compile(r"`([^`\s]+)`")
WORD_RE = re.compile(r"[a-z0-9]+")
PATH_EXTENSIONS = (
".md", ".py", ".ts", ".tsx", ".js", ".mjs", ".json", ".yaml", ".yml", ".sh", ".txt",
".toml", ".tf", ".css", ".html",
)
# Phrases that look like instructions aimed at a model. Memory must hold facts in the agent's
# own words, never instructions copied from tool output or retrieved content.
INJECTION_PATTERNS = tuple(
re.compile(p, re.IGNORECASE)
for p in (
r"ignore (?:all |any )?(?:previous|prior|above|earlier) instructions",
r"disregard (?:the |all )?(?:previous|prior|system|above)",
r"<\s*/?\s*(?:system|assistant|instructions?)\s*>",
r"\byou are now\b",
r"\bnew instructions\s*:",
r"\bdo not tell the user\b",
)
)
STOPWORDS = frozenset(
"a an and are as at be but by for from has have if in into is it its of on or that the "
"this to was were when where which while with not no do does did so then than".split()
)
class FlywheelError(Exception):
"""A user-facing error with a clear message."""
# ---------------------------------------------------------------------------
# Frontmatter parsing and serialization (a deliberately small YAML subset)
# ---------------------------------------------------------------------------
def split_frontmatter(text: str) -> tuple[str | None, str]:
"""Return (frontmatter, body). frontmatter is None when the file has none."""
if not text.startswith("---\n"):
return None, text
end = text.find("\n---\n", 4)
if end == -1:
if text.endswith("\n---"):
return text[4:-4], ""
raise FlywheelError("frontmatter is not closed with '---'")
return text[4:end], text[end + 5:]
def _strip_comment(line: str) -> str:
quote = None
i = 0
while i < len(line):
ch = line[i]
if quote:
if quote == '"' and ch == "\\":
i += 2
continue
if ch == quote:
quote = None
elif ch in "\"'":
quote = ch
elif ch == "#" and (i == 0 or line[i - 1] in " \t"):
return line[:i].rstrip()
i += 1
return line
def _split_top(s: str) -> list[str]:
parts, depth, quote, cur = [], 0, None, []
escaped = False
for ch in s:
if quote:
cur.append(ch)
if escaped:
escaped = False
elif quote == '"' and ch == "\\":
escaped = True
elif ch == quote:
quote = None
continue
if ch in "\"'":
quote = ch
elif ch in "[{":
depth += 1
elif ch in "]}":
depth -= 1
elif ch == "," and depth == 0:
parts.append("".join(cur).strip())
cur = []
continue
cur.append(ch)
tail = "".join(cur).strip()
if tail:
parts.append(tail)
return parts
def parse_scalar(raw: str):
v = raw.strip()
if v.startswith("[") and v.endswith("]"):
inner = v[1:-1].strip()
return [parse_scalar(x) for x in _split_top(inner)] if inner else []
if v.startswith("{") and v.endswith("}"):
out = {}
for part in _split_top(v[1:-1].strip()):
key, sep, val = part.partition(":")
if not sep:
raise FlywheelError(f"bad inline map entry: {part!r}")
out[key.strip()] = parse_scalar(val)
return out
if len(v) >= 2 and v[0] == v[-1] == '"':
return re.sub(r'\\(.)', r'\1', v[1:-1])
if len(v) >= 2 and v[0] == v[-1] == "'":
return v[1:-1].replace("''", "'")
if re.fullmatch(r"-?\d+", v):
return int(v)
if re.fullmatch(r"-?\d+\.\d+", v):
return float(v)
if v in ("true", "false"):
return v == "true"
if v in ("", "null", "~"):
return None
return v
def parse_frontmatter(fm: str) -> dict:
"""Parse flat keys, inline lists/maps, block lists, one level of nested maps, and
folded/literal block scalars (> and |). Enough for memory entries, SKILL.md, and evals."""
data: dict = {}
lines = fm.splitlines()
i = 0
key = None
while i < len(lines):
raw = lines[i]
line = _strip_comment(raw).rstrip()
i += 1
if not line.strip():
continue
indented = line[0] in " \t"
stripped = line.strip()
if not indented:
k, sep, v = line.partition(":")
if not sep:
raise FlywheelError(f"unsupported frontmatter line: {raw!r}")
key = k.strip()
v = v.strip()
if v in (">", "|", ">-", "|-", ">+", "|+"):
block = []
while i < len(lines) and (not lines[i].strip() or lines[i][0] in " \t"):
block.append(lines[i].strip())
i += 1
joiner = " " if v.startswith(">") else "\n"
data[key] = joiner.join(x for x in block if x).strip()
else:
data[key] = parse_scalar(v) if v else None
continue
if key is None:
raise FlywheelError(f"indented line without a parent key: {raw!r}")
if stripped.startswith("- "):
if not isinstance(data.get(key), list):
data[key] = []
data[key].append(parse_scalar(stripped[2:]))
continue
k, sep, v = stripped.partition(":")
if sep:
if not isinstance(data.get(key), dict):
data[key] = {}
data[key][k.strip()] = parse_scalar(v)
continue
raise FlywheelError(f"unsupported frontmatter line: {raw!r}")
return data
def _needs_quotes(s: str) -> bool:
return (
s == ""
or s != s.strip()
or s[0] in "[{\"'>|&*!%@`#?-"
or "\\" in s
or '"' in s
or ": " in s
or " #" in s
or s.endswith(":")
or "," in s
or s in ("true", "false", "null", "~")
or bool(re.fullmatch(r"-?\d+(\.\d+)?", s))
)
def format_scalar(v) -> str:
if v is None:
return ""
if isinstance(v, bool):
return "true" if v else "false"
if isinstance(v, (int, float)):
return str(v)
if isinstance(v, list):
return "[" + ", ".join(format_scalar(x) for x in v) + "]"
if isinstance(v, dict):
return "{" + ", ".join(f"{k}: {format_scalar(x)}" for k, x in v.items()) + "}"
s = str(v)
if _needs_quotes(s):
return '"' + s.replace("\\", "\\\\").replace('"', '\\"') + '"'
return s
def render_entry(meta: dict, body: str) -> str:
keys = [k for k in ENTRY_FIELD_ORDER if k in meta] + [k for k in meta if k not in ENTRY_FIELD_ORDER]
lines = ["---"]
for k in keys:
val = format_scalar(meta[k])
lines.append(f"{k}: {val}" if val != "" else f"{k}:")
lines.append("---")
return "\n".join(lines) + "\n" + body.lstrip("\n")
# ---------------------------------------------------------------------------
# Repository model
# ---------------------------------------------------------------------------
def today() -> str:
return _dt.date.today().isoformat()
def find_root(start: Path) -> Path:
cur = start.resolve()
for cand in (cur, *cur.parents):
if (cand / ".flywheel").is_dir():
return cand
return start.resolve()
def load_config(root: Path) -> dict:
cfg = json.loads(json.dumps(DEFAULT_CONFIG))
path = root / ".flywheel" / "config.json"
if path.exists():
try:
user = json.loads(path.read_text())
except json.JSONDecodeError as exc:
raise FlywheelError(f"{path}: invalid JSON ({exc})") from exc
for k, v in user.items():
if isinstance(v, dict) and isinstance(cfg.get(k), dict):
cfg[k].update(v)
else:
cfg[k] = v
return cfg
class Entry:
def __init__(self, path: Path, meta: dict, body: str):
self.path = path
self.meta = meta
self.body = body
@property
def name(self) -> str:
return str(self.meta.get("name", self.path.stem))
def save(self) -> None:
self.path.write_text(render_entry(self.meta, self.body))
def memory_dir(root: Path, cfg: dict) -> Path:
return root / cfg["memory_dir"]
def index_path(root: Path, cfg: dict) -> Path:
return root / cfg["index_file"]
def entry_files(root: Path, cfg: dict) -> list[Path]:
mdir = memory_dir(root, cfg)
if not mdir.is_dir():
return []
idx = index_path(root, cfg).resolve()
return sorted(p for p in mdir.glob("*.md") if p.resolve() != idx)
def load_entry(path: Path) -> Entry:
fm, body = split_frontmatter(path.read_text())
if fm is None:
raise FlywheelError("missing frontmatter")
return Entry(path, parse_frontmatter(fm), body)
def load_entries(root: Path, cfg: dict, report: "Report | None" = None) -> list[Entry]:
out = []
for p in entry_files(root, cfg):
try:
out.append(load_entry(p))
except FlywheelError as exc:
if report is None:
raise FlywheelError(f"{p}: {exc}") from exc
report.error(p, str(exc))
return out
def preflight(root: Path, cfg: dict) -> list[Entry]:
"""Load every entry before a command writes anything. A malformed entry stops the command
up front instead of after a file was written and the index could not be rebuilt."""
return load_entries(root, cfg)
def skill_names(root: Path, cfg: dict) -> set[str]:
sdir = root / cfg["skills_dir"]
return {p.parent.name for p in sdir.glob("*/SKILL.md")} if sdir.is_dir() else set()
def get_entry(root: Path, cfg: dict, name: str) -> Entry:
path = memory_dir(root, cfg) / f"{name}.md"
if not path.exists():
raise FlywheelError(f"no memory entry named {name!r} ({path})")
return load_entry(path)
# ---------------------------------------------------------------------------
# Index
# ---------------------------------------------------------------------------
def render_index(entries: list[Entry]) -> str:
lines = [
"# Memory index",
"",
"<!-- Generated by: python3 .flywheel/bin/flywheel.py index - do not edit by hand. -->",
"<!-- One line per ACTIVE entry. Open an entry file only when it is relevant. -->",
"",
]
active = [e for e in entries if e.meta.get("status") == "active"]
if not active:
lines.append("No entries yet.")
for t in MEMORY_TYPES:
group = sorted((e for e in active if e.meta.get("type") == t), key=lambda e: e.name)
if not group:
continue
lines.append(f"## {t}")
lines.append("")
for e in group:
lines.append(f"- [{e.name}]({e.path.name}) - {e.meta.get('description', '')}")
lines.append("")
return "\n".join(lines).rstrip("\n") + "\n"
def write_index(root: Path, cfg: dict) -> Path:
entries = load_entries(root, cfg)
path = index_path(root, cfg)
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(render_index(entries))
return path
# ---------------------------------------------------------------------------
# Check
# ---------------------------------------------------------------------------
class Report:
def __init__(self, root: Path):
self.root = root
self.errors: list[str] = []
self.warnings: list[str] = []
def _rel(self, path) -> str:
try:
return str(Path(path).resolve().relative_to(self.root.resolve()))
except ValueError:
return str(path)
def error(self, path, msg: str) -> None:
self.errors.append(f"ERROR {self._rel(path)}: {msg}")
def warn(self, path, msg: str) -> None:
self.warnings.append(f"WARN {self._rel(path)}: {msg}")
def check_ascii(path: Path, report: Report) -> None:
for n, line in enumerate(path.read_text().splitlines(), 1):
m = NON_ASCII_RE.search(line)
if m:
report.error(path, f"line {n}: non-ASCII character {m.group()!r} (use plain ASCII punctuation)")
return
def check_entry(e: Entry, names: set[str], skills: set[str], cfg: dict, report: Report) -> None:
m, p = e.meta, e.path
name = m.get("name")
if not isinstance(name, str) or not SLUG_RE.match(name):
report.error(p, "name must be a kebab-case slug")
elif name != p.stem:
report.error(p, f"name {name!r} does not match the file name {p.stem!r}")
desc = m.get("description")
if not isinstance(desc, str) or not desc.strip():
report.error(p, "description is required (one line, used for recall)")
elif "\n" in desc:
report.error(p, "description must be a single line")
elif len(desc) > cfg["description_max_chars"]:
report.error(p, f"description is {len(desc)} chars (max {cfg['description_max_chars']})")
if m.get("type") not in MEMORY_TYPES:
report.error(p, f"type must be one of {', '.join(MEMORY_TYPES)}")
if m.get("scope") not in MEMORY_SCOPES:
report.error(p, f"scope must be one of {', '.join(MEMORY_SCOPES)}")
status = m.get("status")
if status not in MEMORY_STATUSES:
report.error(p, f"status must be one of {', '.join(MEMORY_STATUSES)}")
sources = m.get("sources")
if not isinstance(sources, list) or not all(isinstance(s, str) for s in sources):
report.error(p, "sources must be a list of change names, e.g. [add-login]")
sources = []
occ = m.get("occurrences")
if occ != len(set(sources)):
report.error(p, f"occurrences is {occ!r} but sources has {len(set(sources))} distinct changes")
if m.get("type") in PROMOTABLE_TYPES and not sources:
report.error(p, f"type {m.get('type')} needs at least one source change")
lv = m.get("last_verified")
if not isinstance(lv, str) or not DATE_RE.match(lv):
report.error(p, "last_verified must be a date (YYYY-MM-DD)")
prov = m.get("provenance")
if not isinstance(prov, dict) or prov.get("by") not in PROVENANCE_BY or not DATE_RE.match(str(prov.get("date", ""))):
report.error(p, "provenance must be {by: agent|human, date: YYYY-MM-DD}")
links = m.get("links", [])
if not isinstance(links, list):
report.error(p, "links must be a list of entry names")
else:
for link in links:
if link not in names:
report.warn(p, f"link to unknown entry {link!r}")
if status == "superseded" and m.get("superseded_by") not in names:
report.error(p, "status superseded needs superseded_by: <existing entry name>")
if status == "promoted" and not m.get("promoted_to"):
report.error(p, "status promoted needs promoted_to: <skill name> or constitution")
elif status == "promoted" and m["promoted_to"] != "constitution" and m["promoted_to"] not in skills:
report.error(p, f"promoted_to {m['promoted_to']!r} is not a skill in {cfg['skills_dir']}")
if re.search(r"^TODO\s*$", e.body, re.M):
report.warn(p, "body still has TODO placeholders from `new`; record the lesson in your own words")
if not e.body.strip():
report.error(p, "body is empty (record what happened, why, the resolution, and where)")
for pat in INJECTION_PATTERNS:
if pat.search(e.body) or pat.search(str(desc or "")):
report.error(p, f"possible memory poisoning: text matches {pat.pattern!r}; "
"record the fact in your own words")
break
def is_flywheel_managed_skill(name: str, meta: dict) -> bool:
return name in FLYWHEEL_SKILLS or "promoted_from" in meta
def check_skills(root: Path, cfg: dict, report: Report) -> set[str]:
sdir = root / cfg["skills_dir"]
names: set[str] = set()
if not sdir.is_dir():
return names
for skill_md in sorted(sdir.glob("*/SKILL.md")):
dname = skill_md.parent.name
names.add(dname)
try:
fm, body = split_frontmatter(skill_md.read_text())
if fm is None:
raise FlywheelError("missing frontmatter")
meta = parse_frontmatter(fm)
except FlywheelError as exc:
report.error(skill_md, str(exc))
continue
if not meta.get("name"):
report.error(skill_md, "frontmatter name is required")
elif meta["name"] != dname:
report.warn(skill_md, f"name {meta['name']!r} differs from folder {dname!r}")
desc = meta.get("description")
if not isinstance(desc, str) or not desc.strip():
report.error(skill_md, "frontmatter description is required (it drives discovery)")
elif len(desc) > 1024:
report.error(skill_md, f"description is {len(desc)} chars (max 1024)")
if "status" in meta and meta["status"] not in SKILL_STATUSES:
report.error(skill_md, f"status must be one of {', '.join(SKILL_STATUSES)}")
if "promoted_from" in meta:
for field in ("approved_by", "date", "eval"):
if not meta.get(field):
report.error(skill_md, f"promoted skill needs {field}")
ev = meta.get("eval")
if ev and not isinstance(ev, dict):
report.error(skill_md, "eval must be a map: {score: <number>, models: [...], date: YYYY-MM-DD}")
elif isinstance(ev, dict):
score = ev.get("score")
if isinstance(score, bool) or not isinstance(score, (int, float)):
report.error(skill_md, f"eval.score must be a number, got {score!r}")
elif score < cfg["eval"]["min_score"]:
report.error(skill_md, f"eval score {score!r} is below the gate {cfg['eval']['min_score']}")
models = ev.get("models")
if not isinstance(models, list) or not models:
report.error(skill_md, "eval.models must list the model(s) the evals ran on")
if not DATE_RE.match(str(ev.get("date", ""))):
report.error(skill_md, "eval.date must be a date (YYYY-MM-DD)")
if not body.strip():
report.error(skill_md, "skill body is empty")
if cfg["ascii_only"] and is_flywheel_managed_skill(dname, meta):
check_ascii(skill_md, report)
return names
def check_evals(root: Path, cfg: dict, skills: set[str], report: Report) -> int:
edir = root / cfg["evals_dir"]
count = 0
if not edir.is_dir():
return count
for f in sorted(edir.glob("*/*.md")):
count += 1
try:
fm, body = split_frontmatter(f.read_text())
if fm is None:
raise FlywheelError("missing frontmatter")
meta = parse_frontmatter(fm)
except FlywheelError as exc:
report.error(f, str(exc))
continue
if meta.get("id") != f.stem:
report.error(f, f"id must equal the file name ({f.stem})")
skill = meta.get("skill")
if skill != f.parent.name:
report.error(f, f"skill must equal the folder name ({f.parent.name})")
elif skill not in skills:
report.error(f, f"skill {skill!r} does not exist in {cfg['skills_dir']}")
if meta.get("kind") not in EVAL_KINDS:
report.error(f, f"kind must be one of {', '.join(EVAL_KINDS)}")
ms = meta.get("min_score")
if not isinstance(ms, (int, float)) or not 0 < ms <= 1:
report.error(f, "min_score must be a number in (0, 1]")
for fx in meta.get("fixtures") or []:
if not (f.parent / fx).exists():
report.error(f, f"fixture not found: {fx}")
positions = [body.find(s + "\n") for s in EVAL_SECTIONS]
if any(pos < 0 for pos in positions):
missing = [s for s, pos in zip(EVAL_SECTIONS, positions) if pos < 0]
report.error(f, f"missing section(s): {', '.join(missing)}")
elif positions != sorted(positions):
report.error(f, f"sections must appear in order: {', '.join(EVAL_SECTIONS)}")
if cfg["ascii_only"]:
check_ascii(f, report)
return count
def run_check(root: Path, cfg: dict) -> Report:
report = Report(root)
entries = load_entries(root, cfg, report)
names = {e.name for e in entries}
skills = skill_names(root, cfg)
for e in entries:
check_entry(e, names, skills, cfg, report)
if cfg["ascii_only"]:
check_ascii(e.path, report)
idx = index_path(root, cfg)
expected = render_index(entries)
if not idx.exists():
report.error(idx, "memory index is missing; run: flywheel.py index")
elif idx.read_text() != expected:
report.error(idx, "memory index is out of date; run: flywheel.py index")
budget = cfg["index_budget"]
n_lines, n_bytes = len(expected.splitlines()), len(expected.encode())
if n_lines > budget["max_lines"] or n_bytes > budget["max_bytes"]:
report.error(idx, f"index is over budget ({n_lines} lines / {n_bytes} bytes; "
f"max {budget['max_lines']} / {budget['max_bytes']}); run the compact-memory skill")
skills = check_skills(root, cfg, report)
check_evals(root, cfg, skills, report)
agents_dir = root / cfg["agents_dir"]
for a in FLYWHEEL_AGENTS:
ap = agents_dir / a
if ap.exists():
try:
fm, _ = split_frontmatter(ap.read_text())
if fm is None:
raise FlywheelError("missing frontmatter")
meta = parse_frontmatter(fm)
except FlywheelError as exc:
report.error(ap, str(exc))
continue
if meta.get("name") != ap.stem or not meta.get("description"):
report.error(ap, "agent needs name (= file name) and description")
if cfg["ascii_only"]:
check_ascii(ap, report)
const = root / cfg["constitution_file"]
if not const.exists():
report.warn(const, "constitution file not found")
elif cfg["ascii_only"]:
check_ascii(const, report)
return report
# ---------------------------------------------------------------------------
# Commands
# ---------------------------------------------------------------------------
def cmd_check(args, root, cfg) -> int:
report = run_check(root, cfg)
for line in report.warnings + report.errors:
print(line)
print(f"check: {len(report.errors)} error(s), {len(report.warnings)} warning(s)")
return 1 if report.errors else 0
def cmd_index(args, root, cfg) -> int:
path = write_index(root, cfg)
print(f"wrote {path.relative_to(root)}")
return 0
BODY_TEMPLATE = """## What happened
{what}
## Why
{why}
## Resolution
{resolution}
## Where
{where}
"""
def cmd_new(args, root, cfg) -> int:
if not SLUG_RE.match(args.name):
raise FlywheelError("name must be a kebab-case slug")
path = memory_dir(root, cfg) / f"{args.name}.md"
if path.exists():
raise FlywheelError(f"{args.name} already exists; if it is the same lesson, run: "
f"flywheel.py add-source {args.name} <change>")
if args.type in PROMOTABLE_TYPES and not args.source:
raise FlywheelError(f"type {args.type} needs --source <change-name>")
preflight(root, cfg)
sources = [args.source] if args.source else []
meta = {
"name": args.name,
"description": args.description,
"type": args.type,
"scope": args.scope,
"status": "active",
"sources": sources,
"occurrences": len(sources),
"last_verified": today(),
"provenance": {"by": args.by, "date": today()},
"links": list(args.link or []),
}
body = BODY_TEMPLATE.format(what="TODO", why="TODO", resolution="TODO", where="TODO")
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(render_entry(meta, body))
write_index(root, cfg)
print(f"created {path.relative_to(root)} (fill in the TODO sections, in your own words)")
return 0
def cmd_add_source(args, root, cfg) -> int:
preflight(root, cfg)
e = get_entry(root, cfg, args.name)
sources = list(e.meta.get("sources") or [])
if args.change in sources:
print(f"{args.name}: {args.change} is already a source ({len(set(sources))} occurrence(s))")
return 0
sources.append(args.change)
e.meta["sources"] = sources
e.meta["occurrences"] = len(set(sources))
e.meta["last_verified"] = today()
e.save()
write_index(root, cfg)
n = e.meta["occurrences"]
print(f"{args.name}: added source {args.change} ({n} occurrence(s))")
if e.meta.get("type") in PROMOTABLE_TYPES and n >= cfg["promotion"]["min_occurrences"]:
print(f"{args.name}: reached the promotion threshold - run the promote-skill or "
"promote-constitution-rule skill")
return 0
def cmd_set_status(args, root, cfg) -> int:
preflight(root, cfg)
e = get_entry(root, cfg, args.name)
if args.status == "superseded":
if not args.superseded_by:
raise FlywheelError("superseded needs --superseded-by <entry>")
if args.superseded_by == args.name:
raise FlywheelError("an entry cannot supersede itself")
get_entry(root, cfg, args.superseded_by)
e.meta["superseded_by"] = args.superseded_by
else:
e.meta.pop("superseded_by", None)
if args.status == "promoted":
if not args.promoted_to:
raise FlywheelError("promoted needs --promoted-to <skill name or constitution>")
if args.promoted_to != "constitution" and args.promoted_to not in skill_names(root, cfg):
raise FlywheelError(f"no skill named {args.promoted_to!r} in {cfg['skills_dir']}; "
"install the approved skill first, or use --promoted-to constitution")
e.meta["promoted_to"] = args.promoted_to
else:
e.meta.pop("promoted_to", None)
e.meta["status"] = args.status
e.save()
write_index(root, cfg)
print(f"{args.name}: status {args.status}")
return 0
def promotion_candidates(entries: list[Entry], cfg: dict) -> list[dict]:
n = cfg["promotion"]["min_occurrences"]
out = []
for e in entries:
m = e.meta
if m.get("status") != "active" or m.get("type") not in PROMOTABLE_TYPES:
continue
if (m.get("occurrences") or 0) < n:
continue
target = "skill" if m["type"] == "observation" else "skill or constitution rule"
out.append({"name": e.name, "type": m["type"], "occurrences": m["occurrences"],
"sources": m.get("sources", []), "suggested_target": target})
return sorted(out, key=lambda c: (-c["occurrences"], c["name"]))
def cmd_candidates(args, root, cfg) -> int:
cands = promotion_candidates(load_entries(root, cfg), cfg)
if args.json:
print(json.dumps(cands, indent=2))
return 0
if not cands:
print(f"no promotion candidates (threshold: {cfg['promotion']['min_occurrences']} distinct changes)")
for c in cands:
print(f"{c['name']} type={c['type']} occurrences={c['occurrences']} "
f"target={c['suggested_target']} sources={','.join(c['sources'])}")
return 0
def referenced_paths(body: str) -> list[str]:
"""Repo-relative paths named in backticks, e.g. `src/app/page.tsx` or `docs/guides/`.
Bare file names (`SKILL.md`) are ambiguous and are not checked."""
out = []
for tok in BACKTICK_RE.findall(body):
tok = tok.rstrip(".,;:")
tok = re.sub(r":\d+(-\d+)?$", "", tok)
if tok.startswith(("http://", "https://", "~", "/", "$", "<", "-", "@")):
continue
if any(ch in tok for ch in "*|{}()=<>"):
continue
if "/" not in tok:
continue
if not (tok.endswith("/") or tok.rsplit("/", 1)[-1].endswith(PATH_EXTENSIONS)):
continue
out.append(tok[2:] if tok.startswith("./") else tok)
return sorted(set(out))
def verify_entries(root: Path, cfg: dict) -> list[dict]:
results = []
limit = cfg["verify"]["stale_after_days"]
now = _dt.date.today()
for e in load_entries(root, cfg):
if e.meta.get("status") != "active":
continue
paths = referenced_paths(e.body)
missing = [p for p in paths if not (root / p).exists()]
age = None
lv = e.meta.get("last_verified")
if isinstance(lv, str) and DATE_RE.match(lv):
age = (now - _dt.date.fromisoformat(lv)).days
results.append({"name": e.name, "paths": paths, "missing": missing,
"age_days": age, "overdue": age is not None and age > limit})
return results
def cmd_verify(args, root, cfg) -> int:
if args.apply:
preflight(root, cfg)
results = verify_entries(root, cfg)
changed = 0
for r in results:
if r["missing"]:
print(f"STALE {r['name']}: missing {', '.join(r['missing'])}")
if args.apply:
e = get_entry(root, cfg, r["name"])
e.meta["status"] = "stale"
e.save()
changed += 1
elif r["paths"]:
print(f"OK {r['name']}: {len(r['paths'])} path(s) exist")
if args.apply:
e = get_entry(root, cfg, r["name"])
if e.meta.get("last_verified") != today():
e.meta["last_verified"] = today()
e.save()
changed += 1
elif r["overdue"]:
print(f"REVIEW {r['name']}: no checkable paths, last verified {r['age_days']} days ago")
if args.apply:
write_index(root, cfg)
print(f"verify: updated {changed} entr{'y' if changed == 1 else 'ies'}")
return 0
def _tokens(text: str) -> set[str]:
return {w for w in WORD_RE.findall(text.lower()) if w not in STOPWORDS and len(w) > 2}
def find_duplicates(entries: list[Entry], threshold: float) -> list[tuple[float, str, str]]:
active = sorted((e for e in entries if e.meta.get("status") == "active"), key=lambda e: e.name)
toks = {e.name: _tokens(f"{e.name} {e.meta.get('description', '')} {e.body}") for e in active}
pairs = []
for i, a in enumerate(active):
for b in active[i + 1:]:
ta, tb = toks[a.name], toks[b.name]
if not ta or not tb:
continue
score = len(ta & tb) / len(ta | tb)
if score >= threshold:
pairs.append((round(score, 3), a.name, b.name))
return sorted(pairs, key=lambda p: (-p[0], p[1], p[2]))
def cmd_dupes(args, root, cfg) -> int:
threshold = args.threshold if args.threshold is not None else cfg["dedup"]["jaccard_threshold"]
pairs = find_duplicates(load_entries(root, cfg), threshold)
if not pairs:
print(f"no near-duplicates at threshold {threshold}")
for score, a, b in pairs:
print(f"{score:.3f} {a} {b}")
return 0
def cmd_status(args, root, cfg) -> int:
entries = load_entries(root, cfg)
by_status: dict[str, int] = {}
by_type: dict[str, int] = {}
for e in entries:
by_status[str(e.meta.get("status"))] = by_status.get(str(e.meta.get("status")), 0) + 1
by_type[str(e.meta.get("type"))] = by_type.get(str(e.meta.get("type")), 0) + 1
idx = render_index(entries)
budget = cfg["index_budget"]
sdir = root / cfg["skills_dir"]
skills = sorted(p.parent.name for p in sdir.glob("*/SKILL.md")) if sdir.is_dir() else []
edir = root / cfg["evals_dir"]
evals = sorted(edir.glob("*/*.md")) if edir.is_dir() else []
print(f"Context Flywheel {VERSION} - {root}")
print(f"memory entries: {len(entries)} by status: {json.dumps(by_status, sort_keys=True)}")
print(f" by type: {json.dumps(by_type, sort_keys=True)}")
print(f"index: {len(idx.splitlines())}/{budget['max_lines']} lines, "
f"{len(idx.encode())}/{budget['max_bytes']} bytes")
print(f"promotion candidates: {len(promotion_candidates(entries, cfg))}")
print(f"skills: {len(skills)} evals: {len(evals)}")
return 0
# ---------------------------------------------------------------------------
# Install into a target repository
# ---------------------------------------------------------------------------
def _source_root() -> Path:
return Path(__file__).resolve().parents[2]
def _sha256(data: bytes) -> str:
return hashlib.sha256(data).hexdigest()
class _Installer:
"""Copies flywheel-owned files and records them in the target's install manifest
(.flywheel/install-manifest.json: relative path -> sha256 of the copy installed).
A file that already exists is replaced only when it is identical to the flywheel copy or
unchanged since the last install. A file the repository wrote itself (a skill or agent with
the same name) or edited after installing is skipped and reported, unless force is set, in
which case it is backed up to <file>.bak first."""
def __init__(self, target: Path, dry: bool, force: bool, log: list[str]):
self.target, self.dry, self.force, self.log = target, dry, force, log
self.manifest_path = target / INSTALL_MANIFEST
self.old: dict[str, str] = {}
if self.manifest_path.exists():
try:
self.old = json.loads(self.manifest_path.read_text()).get("files", {})
except (json.JSONDecodeError, AttributeError) as exc:
raise FlywheelError(f"{self.manifest_path} is not valid JSON: {exc}") from exc
self.new: dict[str, str] = {}
self.conflicts = 0
def copy(self, src: Path, rel: str) -> None:
dst = self.target / rel
data = src.read_bytes()
if not dst.exists():
self.log.append(f"create {dst}")
self._write(src, dst)
else:
current = dst.read_bytes()
if current != data:
if self.old.get(rel) == _sha256(current):
self.log.append(f"update {dst}")
self._write(src, dst)
elif self.force:
self.log.append(f"replace {dst} (--force; old copy saved as {dst.name}.bak)")
if not self.dry:
shutil.copy2(dst, dst.with_name(dst.name + ".bak"))
self._write(src, dst)
else:
self.conflicts += 1
why = "edited since the last install" if rel in self.old else "not installed by the flywheel"
self.log.append(f"skip {dst} (exists, {why}; move it or re-run with --force)")
if rel in self.old:
self.new[rel] = self.old[rel]
return
self.new[rel] = _sha256(data)
def _write(self, src: Path, dst: Path) -> None:
if not self.dry:
dst.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(src, dst)
def save(self) -> None:
payload = {"version": VERSION, "files": dict(sorted(self.new.items()))}
text = json.dumps(payload, indent=2) + "\n"
if self.manifest_path.exists() and self.manifest_path.read_text() == text:
return
self.log.append(("update " if self.manifest_path.exists() else "create ") + str(self.manifest_path))
if not self.dry:
self.manifest_path.parent.mkdir(parents=True, exist_ok=True)
self.manifest_path.write_text(text)
def _write_if_absent(dst: Path, content: str, dry: bool, log: list[str]) -> None:
if dst.exists():
log.append(f"keep {dst} (exists)")
return
log.append(f"create {dst}")
if not dry:
dst.parent.mkdir(parents=True, exist_ok=True)
dst.write_text(content)
def _is_default_openspec_config(text: str) -> bool:
meaningful = [ln.strip() for ln in text.splitlines() if ln.strip() and not ln.strip().startswith("#")]
return meaningful in ([], ["schema: spec-driven"])
def merge_agents_block(existing: str | None, block: str) -> str:
wrapped = f"{AGENTS_START}\n{block.strip()}\n{AGENTS_END}\n"
if existing is None:
return "# AGENTS.md\n\n" + wrapped
has_start, has_end = AGENTS_START in existing, AGENTS_END in existing
if has_start != has_end or existing.count(AGENTS_START) > 1:
raise FlywheelError(f"AGENTS.md has unbalanced flywheel markers; keep exactly one "
f"{AGENTS_START} ... {AGENTS_END} pair (or none) and re-run install")
if has_start and has_end:
pre = existing.split(AGENTS_START, 1)[0]
post = existing.split(AGENTS_END, 1)[1].lstrip("\n")
return pre + wrapped + (("\n" + post) if post else "")
return existing.rstrip("\n") + "\n\n" + wrapped
def merge_claude_imports(existing: str | None) -> str:
text = existing or "# CLAUDE.md\n"
present = {ln.strip() for ln in text.splitlines()}
missing = [imp for imp in CLAUDE_IMPORTS if imp not in present]
if not missing:
return text
return text.rstrip("\n") + "\n\n" + "\n".join(missing) + "\n"
def install(target: Path, dry: bool = False, force: bool = False) -> list[str]:
src = _source_root()
target = target.resolve()
if not target.is_dir():
raise FlywheelError(f"target is not a directory: {target}")
if target == src:
raise FlywheelError("target is the flywheel source repository itself")
log: list[str] = []
inst = _Installer(target, dry, force, log)
owned = [f for skill in FLYWHEEL_SKILLS for f in sorted((src / ".claude/skills" / skill).rglob("*"))]
owned += [src / ".claude/agents" / a for a in FLYWHEEL_AGENTS]
owned += [src / ".flywheel/bin/flywheel.py"]
tdir = src / ".flywheel/templates"
owned += sorted(tdir.rglob("*"))
for f in owned:
if f.is_file() and "__pycache__" not in f.parts:
inst.copy(f, f.relative_to(src).as_posix())
inst.save()
_write_if_absent(target / ".flywheel/config.json",
(tdir / "flywheel-config.json").read_text(), dry, log)
_write_if_absent(target / ".flywheel/memory/MEMORY.md", render_index([]), dry, log)
_write_if_absent(target / "constitution.md", (tdir / "constitution.md").read_text(), dry, log)
if not dry:
(target / ".flywheel/evals").mkdir(parents=True, exist_ok=True)
oscfg = target / "openspec/config.yaml"
template = (tdir / "openspec-config.yaml").read_text()
if not (target / "openspec").is_dir():
log.append("note openspec/ not found: run `openspec init --tools claude --scope project` in the target, then "
"re-run install to seed openspec/config.yaml")
elif oscfg.exists() and oscfg.read_text() == template:
pass # seeded by an earlier install and unchanged: nothing to do
elif not oscfg.exists() or _is_default_openspec_config(oscfg.read_text()):
log.append(("update " if oscfg.exists() else "create ") + str(oscfg))
if not dry:
oscfg.write_text(template)
else:
log.append(f"note {oscfg} has custom settings: merge .flywheel/templates/openspec-config.yaml by hand")
agents_md = target / "AGENTS.md"
block = (tdir / "AGENTS.flywheel.md").read_text()
new_agents = merge_agents_block(agents_md.read_text() if agents_md.exists() else None, block)
if not agents_md.exists() or agents_md.read_text() != new_agents:
log.append(("update " if agents_md.exists() else "create ") + str(agents_md))
if not dry:
agents_md.write_text(new_agents)
claude_md = target / "CLAUDE.md"
new_claude = merge_claude_imports(claude_md.read_text() if claude_md.exists() else None)
if not claude_md.exists() or claude_md.read_text() != new_claude:
log.append(("update " if claude_md.exists() else "create ") + str(claude_md))
if not dry:
claude_md.write_text(new_claude)
return log
def cmd_install(args, root, cfg) -> int:
log = install(Path(args.target), dry=args.dry_run, force=args.force)
for line in log:
print(line)
skipped = sum(1 for line in log if line.startswith("skip "))
print(("dry run: " if args.dry_run else "") + f"install: {len(log)} action(s)")
if skipped:
print(f"install: {skipped} file(s) skipped to protect the repository's own files; "
"nothing else was overwritten")
return 1
if not args.dry_run:
print("next: python3 .flywheel/bin/flywheel.py check (run inside the target)")
return 0
# ---------------------------------------------------------------------------
# Entry point
# ---------------------------------------------------------------------------
def build_parser() -> argparse.ArgumentParser:
p = argparse.ArgumentParser(prog="flywheel.py", description="Context Flywheel deterministic operations.")
p.add_argument("--root", help="repository root (default: nearest parent with .flywheel/)")
p.add_argument("--version", action="version", version=f"%(prog)s {VERSION}")
sub = p.add_subparsers(dest="command", required=True)
sub.add_parser("check", help="validate memory, index, skills, agents, evals, constitution")
sub.add_parser("index", help="regenerate the memory index (MEMORY.md)")
sub.add_parser("status", help="summary of the stores")
n = sub.add_parser("new", help="create a memory entry skeleton")
n.add_argument("name")
n.add_argument("--type", required=True, choices=MEMORY_TYPES)
n.add_argument("--description", required=True)
n.add_argument("--source", help="OpenSpec change name where this was seen")
n.add_argument("--scope", default="local", choices=MEMORY_SCOPES)
n.add_argument("--by", default="agent", choices=PROVENANCE_BY)
n.add_argument("--link", action="append", help="related entry name (repeatable)")
a = sub.add_parser("add-source", help="record that an existing lesson was seen in another change")
a.add_argument("name")
a.add_argument("change")
s = sub.add_parser("set-status", help="change an entry's lifecycle status")
s.add_argument("name")
s.add_argument("status", choices=MEMORY_STATUSES)
s.add_argument("--superseded-by")
s.add_argument("--promoted-to")
c = sub.add_parser("candidates", help="list entries that reached the promotion threshold")
c.add_argument("--json", action="store_true")
v = sub.add_parser("verify", help="find entries that reference files that no longer exist")
v.add_argument("--apply", action="store_true", help="mark them stale and refresh last_verified")
d = sub.add_parser("dupes", help="list near-duplicate active entries (token Jaccard)")
d.add_argument("--threshold", type=float)
i = sub.add_parser("install", help="install the flywheel into a target repository")
i.add_argument("target")
i.add_argument("--dry-run", action="store_true")
i.add_argument("--force", action="store_true",
help="replace conflicting files (each is backed up to <file>.bak first)")
return p
COMMANDS = {
"check": cmd_check, "index": cmd_index, "status": cmd_status, "new": cmd_new,
"add-source": cmd_add_source, "set-status": cmd_set_status, "candidates": cmd_candidates,
"verify": cmd_verify, "dupes": cmd_dupes, "install": cmd_install,
}
def main(argv: list[str] | None = None) -> int:
args = build_parser().parse_args(argv)
root = Path(args.root).resolve() if args.root else find_root(Path.cwd())
try:
cfg = load_config(root)
return COMMANDS[args.command](args, root, cfg)
except FlywheelError as exc:
print(f"error: {exc}", file=sys.stderr)
return 2
if __name__ == "__main__":
sys.exit(main())