Skip to content

oliverweissl/context-garden / skills/seedbank

seedbank

Verified

Maintain a small, generated AGENTS.md of repository facts (build commands, conventions, invariants, past mistakes) that were rediscovered often or were costly to get wrong. Use at task start to check cached facts, and at task end to log and promote what you had to dig for.

scripts/sb_compile.py

View on GitHub
"""Compile promoted, non-stale facts: hot facts inline in AGENTS.md, warm facts
in .seedbank/warm/<scope>.md with a one-line pointer each.

Only the region between BEGIN/END markers is ever replaced; user content
outside them must be preserved.
"""

from __future__ import annotations

from pathlib import Path

from sb_store import atomic_write_text, safe_scope

BEGIN = "<!-- seedbank:begin -->"
END = "<!-- seedbank:end -->"
STALE_MARK = " (source changed \u2014 verify)"


class CompileRefused(Exception):
    pass

HEADER = (
    "<!-- Generated by seedbank. Do not hand-edit -- run `seedbank promote`"
    "/`demote` then `seedbank compile` to regenerate. -->\n"
    "<!-- Source of truth: .seedbank/facts.json -->\n"
)


def active_facts(facts: dict, tier: str) -> list[dict]:
    # --critical facts stay published when stale (marked, see render_rep):
    # dropping an invariant exactly when its protected file was regenerated
    # is the worst time to forget it.
    return [
        f
        for f in facts["facts"].values()
        if f["tier"] == tier and (not f.get("stale") or f.get("protected"))
    ]


def render_rep(f: dict) -> str:
    """One line, no sequences that could open/close an HTML comment (and so
    break the seedbank markers) or start a new heading."""
    rep = " ".join(str(f["representation"]).split())
    rep = rep.replace("<!--", "<! --").replace("-->", "-- >")
    if f.get("stale"):
        rep += STALE_MARK
    return rep


def render_agents_md(facts: dict) -> str:
    hot = active_facts(facts, "hot")
    warm = active_facts(facts, "warm")
    warm_scopes = sorted({safe_scope(f.get("scope")) for f in warm})

    lines = [BEGIN, HEADER, "## Hot context (always loaded)", ""]
    if hot:
        for f in sorted(hot, key=lambda f: safe_scope(f.get("scope"))):
            lines.append(f"- {render_rep(f)}  [{safe_scope(f.get('scope'))}]")
    else:
        lines.append("_(none yet -- run `seedbank candidates` then `seedbank promote`)_")
    lines.append("")

    lines.append("## Warm context (load only when relevant to the current task)")
    lines.append("")
    if warm_scopes:
        for scope in warm_scopes:
            lines.append(f"- **{scope}**: see `.seedbank/warm/{scope}.md`")
    else:
        lines.append("_(none yet)_")
    lines.append(END)
    return "\n".join(lines)


def _split_block(text: str) -> tuple[str, str, str] | None:
    """(before, block, after) around the seedbank markers, or None."""
    b = text.find(BEGIN)
    e = text.find(END, b + len(BEGIN)) if b != -1 else -1
    if b == -1 or e == -1:
        return None
    return text[:b], text[b : e + len(END)], text[e + len(END) :]


def _block_has_facts(text: str) -> bool:
    parts = _split_block(text)
    return bool(parts) and any(ln.startswith("- ") for ln in parts[1].splitlines())


def merge_into(existing: str, block: str) -> str:
    parts = _split_block(existing)
    if parts:
        return parts[0] + block + parts[2]
    if existing.strip():
        return existing.rstrip("\n") + "\n\n" + block + "\n"
    return block + "\n"


def render_warm_scope_md(scope: str, facts_for_scope: list[dict]) -> str:
    lines = [HEADER, "", f"## Warm context: {scope}", ""]
    for f in facts_for_scope:
        conf = f.get("confidence", 0.8)
        lines.append(f"- {render_rep(f)}  (confidence={conf:.2f})")
    lines.append("")
    return "\n".join(lines)


def compile_outputs(
    facts: dict, repo_root: Path, targets: list[str], force: bool = False
) -> dict:
    """Write AGENTS.md-equivalent file(s) + warm/*.md. Returns a report dict.

    Raises CompileRefused if the store is empty but a target already carries
    a populated seedbank block (e.g. fresh clone: facts.json is gitignored),
    unless force=True.
    """
    agents_md = render_agents_md(facts)
    paths = [repo_root / t for t in targets]
    existing = {p: (p.read_text(errors="replace") if p.exists() else "") for p in paths}
    if not facts["facts"] and not force:
        populated = [str(p) for p in paths if _block_has_facts(existing[p])]
        if populated:
            raise CompileRefused(
                f"store has 0 facts but {', '.join(populated)} already has a populated "
                f"seedbank block; compiling would wipe it. Run `seedbank import <file>` "
                f"and re-promote, or pass --force to overwrite."
            )
    written = []
    for path in paths:
        atomic_write_text(path, merge_into(existing[path], agents_md))
        written.append(str(path))

    warm = active_facts(facts, "warm")
    by_scope: dict[str, list[dict]] = {}
    for f in warm:
        by_scope.setdefault(safe_scope(f.get("scope")), []).append(f)

    warm_dir = repo_root / ".seedbank" / "warm"
    if by_scope:
        warm_dir.mkdir(parents=True, exist_ok=True)
    for scope, flist in by_scope.items():
        atomic_write_text(warm_dir / f"{scope}.md", render_warm_scope_md(scope, flist))
        written.append(str(warm_dir / f"{scope}.md"))

    # A scope with no warm facts left must not keep its old .md: unlinked but
    # still readable, it would serve stale facts silently.
    if warm_dir.is_dir():
        for stale_file in warm_dir.glob("*.md"):
            if stale_file.stem not in by_scope:
                stale_file.unlink()

    hot_tokens = sum(f["persistent_token_cost"] for f in active_facts(facts, "hot"))
    stale_excluded = [
        f["id"] for f in facts["facts"].values() if f.get("stale") and not f.get("protected")
    ]

    return {
        "written": written,
        "hot_fact_count": len(active_facts(facts, "hot")),
        "warm_fact_count": len(warm),
        "hot_tokens": hot_tokens,
        "stale_excluded": stale_excluded,
    }
reverse-engineer-anythingmorluto/reaReverse engineer native, managed, Electron/JavaScript, packaged, firmware, and browser targets with REA, and build agent environments (AgentEnv bundles) of web applications from a live instance or a capture, and of Linux desktop apps with a task from a request. Use shipped-artifact or requested runtime evidence to explain features, compare versions, decompile code, or guide a reconstruction. Skip REA for ordinary source-repository architecture analysis.Stars: 472kUpdated Claude CodeCodexVerifiedInstall
diagnosing-superpowersobra/superpowersUse when a superpowers session went wrong and your human partner wants to know why — repeated work, ignored plans, stumbles, poor results, a skill that didn't fire, "it took too long", "why is it so expensive", "what is it doing" — or wants to build a bug report for the superpowers maintainers, for the current session or a past one identified by id or path, on any harness.Stars: 322kUpdated Claude CodeCodexVerifiedInstall
dispatching-parallel-agentsobra/superpowersUse when facing 2+ independent tasks that can be worked on without shared state or sequential dependenciesStars: 322kUpdated Claude CodeCodexVerifiedInstall
executing-plansobra/superpowersUse when executing an implementation plan in the current session as the implementer yourself — your human partner chose inline execution, or no subagent tool is availableStars: 322kUpdated Claude CodeCodexVerifiedInstall