From 39b4594c22ce6f95d9e3e48798c988ff02ad6214 Mon Sep 17 00:00:00 2001 From: Johannes Kresner Date: Sun, 23 Aug 2026 14:59:01 +0200 Subject: [PATCH] feat: update skills & update hyprland --- agents/skills/cavecrew/SKILL.md | 82 - agents/skills/caveman-commit/SKILL.md | 65 - agents/skills/caveman-compress/README.md | 163 -- agents/skills/caveman-compress/SECURITY.md | 31 - agents/skills/caveman-compress/SKILL.md | 111 -- .../caveman-compress/scripts/__init__.py | 9 - .../caveman-compress/scripts/__main__.py | 3 - .../caveman-compress/scripts/benchmark.py | 78 - agents/skills/caveman-compress/scripts/cli.py | 73 - .../caveman-compress/scripts/compress.py | 176 --- .../skills/caveman-compress/scripts/detect.py | 121 -- .../caveman-compress/scripts/validate.py | 189 --- agents/skills/caveman-help/SKILL.md | 59 - agents/skills/caveman-review/SKILL.md | 55 - agents/skills/caveman-stats/SKILL.md | 10 - agents/skills/caveman/SKILL.md | 67 - agents/skills/check-compiler-errors/SKILL.md | 23 + agents/skills/code-review/SKILL.md | 87 + agents/skills/code-review/agents/openai.yaml | 3 + .../DEEPENING.md | 8 +- .../DESIGN-IT-TWICE.md} | 24 +- agents/skills/codebase-design/SKILL.md | 114 ++ .../skills/codebase-design/agents/openai.yaml | 3 + agents/skills/compress/SKILL.md | 111 -- agents/skills/compress/scripts/__init__.py | 9 - agents/skills/compress/scripts/__main__.py | 3 - agents/skills/compress/scripts/benchmark.py | 78 - agents/skills/compress/scripts/cli.py | 85 - agents/skills/compress/scripts/compress.py | 254 --- agents/skills/compress/scripts/detect.py | 121 -- agents/skills/compress/scripts/validate.py | 213 --- agents/skills/continual-learning/SKILL.md | 24 + agents/skills/deslop/SKILL.md | 22 + .../{diagnose => diagnosing-bugs}/SKILL.md | 79 +- .../skills/diagnosing-bugs/agents/openai.yaml | 3 + .../scripts/hitl-loop.template.sh | 3 + .../ADR-FORMAT.md | 22 +- .../CONTEXT-FORMAT.md | 29 +- agents/skills/domain-modeling/SKILL.md | 74 + .../skills/domain-modeling/agents/openai.yaml | 3 + agents/skills/find-skills/SKILL.md | 5 +- agents/skills/graphify/.graphify_version | 1 - agents/skills/graphify/SKILL.md | 1031 ------------ agents/skills/grill-me/SKILL.md | 9 +- agents/skills/grill-me/agents/openai.yaml | 5 + agents/skills/grill-with-docs/SKILL.md | 87 +- .../skills/grill-with-docs/agents/openai.yaml | 5 + agents/skills/grilling/SKILL.md | 28 + agents/skills/grilling/agents/openai.yaml | 3 + agents/skills/how/SKILL.md | 134 ++ agents/skills/how/references/critic-prompt.md | 59 + .../skills/how/references/critique-rubric.md | 58 + .../skills/how/references/explainer-prompt.md | 55 + .../skills/how/references/explorer-prompt.md | 52 + .../HTML-REPORT.md | 123 ++ .../improve-codebase-architecture/LANGUAGE.md | 53 - .../improve-codebase-architecture/SKILL.md | 76 +- .../agents/openai.yaml | 5 + agents/skills/oh-my-mermaid | 1 - agents/skills/ponytail-audit/SKILL.md | 41 - agents/skills/ponytail-debt/SKILL.md | 44 - agents/skills/ponytail-gain/SKILL.md | 50 - agents/skills/ponytail-help/SKILL.md | 69 - agents/skills/ponytail-review/SKILL.md | 57 - agents/skills/ponytail/SKILL.md | 117 -- agents/skills/prototype/LOGIC.md | 67 + agents/skills/prototype/SKILL.md | 26 + agents/skills/prototype/UI.md | 112 ++ agents/skills/prototype/agents/openai.yaml | 3 + agents/skills/research/SKILL.md | 12 + agents/skills/research/agents/openai.yaml | 3 + .../skills/resolving-merge-conflicts/SKILL.md | 14 + .../agents/openai.yaml | 3 + agents/skills/tdd/SKILL.md | 119 +- agents/skills/tdd/deep-modules.md | 33 - agents/skills/tdd/interface-design.md | 31 - agents/skills/tdd/mocking.md | 59 - agents/skills/tdd/refactoring.md | 10 - agents/skills/tdd/tests.md | 61 - agents/skills/teach/SKILL.md | 21 + agents/skills/technical-writing/SKILL.md | 130 ++ .../SKILL.md | 192 +++ agents/skills/thermo-nuclear-review/SKILL.md | 51 + agents/skills/thermos/SKILL.md | 21 + agents/skills/to-issues/SKILL.md | 81 - agents/skills/to-prd/SKILL.md | 74 - agents/skills/typst-author/SKILL.md | 56 +- .../typst-author/docs/changelog/0.1.0.md | 126 +- .../typst-author/docs/changelog/0.10.0.md | 203 ++- .../typst-author/docs/changelog/0.11.0.md | 465 ++++-- .../typst-author/docs/changelog/0.11.1.md | 93 +- .../typst-author/docs/changelog/0.12.0.md | 689 ++++++-- .../typst-author/docs/changelog/0.13.0.md | 597 +++++-- .../typst-author/docs/changelog/0.13.1.md | 30 +- .../typst-author/docs/changelog/0.14.0.md | 1098 +++++++++---- .../typst-author/docs/changelog/0.14.1.md | 138 +- .../typst-author/docs/changelog/0.14.2.md | 33 +- .../typst-author/docs/changelog/0.15.0.md | 1177 ++++++++++++++ .../typst-author/docs/changelog/0.2.0.md | 75 +- .../typst-author/docs/changelog/0.3.0.md | 112 +- .../typst-author/docs/changelog/0.4.0.md | 164 +- .../typst-author/docs/changelog/0.5.0.md | 99 +- .../typst-author/docs/changelog/0.6.0.md | 89 +- .../typst-author/docs/changelog/0.7.0.md | 247 ++- .../typst-author/docs/changelog/0.8.0.md | 208 ++- .../typst-author/docs/changelog/0.9.0.md | 311 +++- .../typst-author/docs/changelog/earlier.md | 555 +++++-- .../typst-author/docs/changelog/index.md | 35 +- .../typst-author/docs/changelog/utils.md | 1 + .../typst-author/docs/guides/accessibility.md | 815 ++++++++-- .../docs/guides/for-latex-users.md | 651 +++++--- .../skills/typst-author/docs/guides/index.md | 17 +- .../typst-author/docs/guides/page-setup.md | 357 +++-- .../skills/typst-author/docs/guides/tables.md | 948 ++++++++--- agents/skills/typst-author/docs/index.md | 10 +- agents/skills/typst-author/docs/overview.md | 54 + .../docs/reference/export/bundle.md | 115 ++ .../docs/reference/export/html.md | 105 ++ .../docs/reference/export/index.md | 12 + .../typst-author/docs/reference/export/pdf.md | 271 ++++ .../typst-author/docs/reference/export/png.md | 77 + .../typst-author/docs/reference/export/svg.md | 60 + .../typst-author/docs/reference/index.md | 79 +- .../docs/reference/language/context.md | 243 +++ .../docs/reference/language/index.md | 10 + .../docs/reference/language/scripting.md | 393 +++++ .../docs/reference/language/styling.md | 156 ++ .../docs/reference/language/syntax.md | 200 +++ .../docs/reference/library/data-loading.md | 18 + .../docs/reference/library/emoji.md | 1396 +++++++++++++++++ .../docs/reference/library/foundations.md | 80 + .../docs/reference/library/index.md | 22 + .../docs/reference/library/introspection.md | 13 + .../docs/reference/library/layout.md | 6 + .../docs/reference/library/math.md | 224 +++ .../docs/reference/library/model.md | 7 + .../docs/reference/library/sym.md | 1195 ++++++++++++++ .../docs/reference/library/text.md | 5 + .../docs/reference/library/visualize.md | 19 + .../typst-author/docs/tutorial/1-writing.md | 318 ++++ .../docs/tutorial/2-formatting.md | 290 ++++ .../typst-author/docs/tutorial/3-advanced.md | 733 +++++++++ .../typst-author/docs/tutorial/4-template.md | 535 +++++++ .../typst-author/docs/tutorial/index.md | 54 +- agents/skills/unslop/SKILL.md | 80 + agents/skills/verify-this/SKILL.md | 74 + agents/skills/wayfinder/SKILL.md | 128 ++ agents/skills/wayfinder/agents/openai.yaml | 5 + agents/skills/why/SKILL.md | 229 +++ agents/skills/why/references/epistemics.md | 144 ++ .../why/references/investigator-prompt.md | 103 ++ .../skills/why/references/source-playbook.md | 17 + .../references/sources/code-archaeology.md | 88 ++ .../why/references/sources/databricks.md | 70 + .../skills/why/references/sources/datadog.md | 99 ++ .../references/sources/incident-postmortem.md | 15 + .../skills/why/references/sources/linear.md | 48 + .../skills/why/references/sources/notion.md | 55 + .../skills/why/references/sources/sentry.md | 100 ++ agents/skills/why/references/sources/slack.md | 54 + .../why/references/synthesizer-prompt.md | 135 ++ agents/skills/zoom-out/SKILL.md | 7 - config/nushell/env.nu | 2 +- home.nix | 2 + {config => mutable_config}/hypr/.luarc.json | 0 .../hypr/empty_workspaces.conf | 0 {config => mutable_config}/hypr/hypridle.conf | 0 mutable_config/hypr/hyprland-gui.lua | 53 + {config => mutable_config}/hypr/hyprland.lua | 4 +- {config => mutable_config}/hypr/hyprlock.conf | 0 {config => mutable_config}/hypr/mocha.conf | 0 {config => mutable_config}/hypr/theme.conf | 0 172 files changed, 17215 insertions(+), 6364 deletions(-) delete mode 100644 agents/skills/cavecrew/SKILL.md delete mode 100644 agents/skills/caveman-commit/SKILL.md delete mode 100644 agents/skills/caveman-compress/README.md delete mode 100644 agents/skills/caveman-compress/SECURITY.md delete mode 100644 agents/skills/caveman-compress/SKILL.md delete mode 100644 agents/skills/caveman-compress/scripts/__init__.py delete mode 100644 agents/skills/caveman-compress/scripts/__main__.py delete mode 100644 agents/skills/caveman-compress/scripts/benchmark.py delete mode 100644 agents/skills/caveman-compress/scripts/cli.py delete mode 100644 agents/skills/caveman-compress/scripts/compress.py delete mode 100644 agents/skills/caveman-compress/scripts/detect.py delete mode 100644 agents/skills/caveman-compress/scripts/validate.py delete mode 100644 agents/skills/caveman-help/SKILL.md delete mode 100644 agents/skills/caveman-review/SKILL.md delete mode 100644 agents/skills/caveman-stats/SKILL.md delete mode 100644 agents/skills/caveman/SKILL.md create mode 100644 agents/skills/check-compiler-errors/SKILL.md create mode 100644 agents/skills/code-review/SKILL.md create mode 100644 agents/skills/code-review/agents/openai.yaml rename agents/skills/{improve-codebase-architecture => codebase-design}/DEEPENING.md (80%) rename agents/skills/{improve-codebase-architecture/INTERFACE-DESIGN.md => codebase-design/DESIGN-IT-TWICE.md} (56%) create mode 100644 agents/skills/codebase-design/SKILL.md create mode 100644 agents/skills/codebase-design/agents/openai.yaml delete mode 100644 agents/skills/compress/SKILL.md delete mode 100644 agents/skills/compress/scripts/__init__.py delete mode 100644 agents/skills/compress/scripts/__main__.py delete mode 100644 agents/skills/compress/scripts/benchmark.py delete mode 100644 agents/skills/compress/scripts/cli.py delete mode 100644 agents/skills/compress/scripts/compress.py delete mode 100644 agents/skills/compress/scripts/detect.py delete mode 100644 agents/skills/compress/scripts/validate.py create mode 100644 agents/skills/continual-learning/SKILL.md create mode 100644 agents/skills/deslop/SKILL.md rename agents/skills/{diagnose => diagnosing-bugs}/SKILL.md (52%) create mode 100644 agents/skills/diagnosing-bugs/agents/openai.yaml rename agents/skills/{diagnose => diagnosing-bugs}/scripts/hitl-loop.template.sh (88%) rename agents/skills/{grill-with-docs => domain-modeling}/ADR-FORMAT.md (59%) rename agents/skills/{grill-with-docs => domain-modeling}/CONTEXT-FORMAT.md (58%) create mode 100644 agents/skills/domain-modeling/SKILL.md create mode 100644 agents/skills/domain-modeling/agents/openai.yaml delete mode 100644 agents/skills/graphify/.graphify_version delete mode 100644 agents/skills/graphify/SKILL.md create mode 100644 agents/skills/grill-me/agents/openai.yaml create mode 100644 agents/skills/grill-with-docs/agents/openai.yaml create mode 100644 agents/skills/grilling/SKILL.md create mode 100644 agents/skills/grilling/agents/openai.yaml create mode 100644 agents/skills/how/SKILL.md create mode 100644 agents/skills/how/references/critic-prompt.md create mode 100644 agents/skills/how/references/critique-rubric.md create mode 100644 agents/skills/how/references/explainer-prompt.md create mode 100644 agents/skills/how/references/explorer-prompt.md create mode 100644 agents/skills/improve-codebase-architecture/HTML-REPORT.md delete mode 100644 agents/skills/improve-codebase-architecture/LANGUAGE.md create mode 100644 agents/skills/improve-codebase-architecture/agents/openai.yaml delete mode 120000 agents/skills/oh-my-mermaid delete mode 100644 agents/skills/ponytail-audit/SKILL.md delete mode 100644 agents/skills/ponytail-debt/SKILL.md delete mode 100644 agents/skills/ponytail-gain/SKILL.md delete mode 100644 agents/skills/ponytail-help/SKILL.md delete mode 100644 agents/skills/ponytail-review/SKILL.md delete mode 100644 agents/skills/ponytail/SKILL.md create mode 100644 agents/skills/prototype/LOGIC.md create mode 100644 agents/skills/prototype/SKILL.md create mode 100644 agents/skills/prototype/UI.md create mode 100644 agents/skills/prototype/agents/openai.yaml create mode 100644 agents/skills/research/SKILL.md create mode 100644 agents/skills/research/agents/openai.yaml create mode 100644 agents/skills/resolving-merge-conflicts/SKILL.md create mode 100644 agents/skills/resolving-merge-conflicts/agents/openai.yaml delete mode 100644 agents/skills/tdd/deep-modules.md delete mode 100644 agents/skills/tdd/interface-design.md delete mode 100644 agents/skills/tdd/mocking.md delete mode 100644 agents/skills/tdd/refactoring.md delete mode 100644 agents/skills/tdd/tests.md create mode 100644 agents/skills/teach/SKILL.md create mode 100644 agents/skills/technical-writing/SKILL.md create mode 100644 agents/skills/thermo-nuclear-code-quality-review/SKILL.md create mode 100644 agents/skills/thermo-nuclear-review/SKILL.md create mode 100644 agents/skills/thermos/SKILL.md delete mode 100644 agents/skills/to-issues/SKILL.md delete mode 100644 agents/skills/to-prd/SKILL.md create mode 100644 agents/skills/typst-author/docs/changelog/0.15.0.md create mode 100644 agents/skills/typst-author/docs/changelog/utils.md create mode 100644 agents/skills/typst-author/docs/overview.md create mode 100644 agents/skills/typst-author/docs/reference/export/bundle.md create mode 100644 agents/skills/typst-author/docs/reference/export/html.md create mode 100644 agents/skills/typst-author/docs/reference/export/index.md create mode 100644 agents/skills/typst-author/docs/reference/export/pdf.md create mode 100644 agents/skills/typst-author/docs/reference/export/png.md create mode 100644 agents/skills/typst-author/docs/reference/export/svg.md create mode 100644 agents/skills/typst-author/docs/reference/language/context.md create mode 100644 agents/skills/typst-author/docs/reference/language/index.md create mode 100644 agents/skills/typst-author/docs/reference/language/scripting.md create mode 100644 agents/skills/typst-author/docs/reference/language/styling.md create mode 100644 agents/skills/typst-author/docs/reference/language/syntax.md create mode 100644 agents/skills/typst-author/docs/reference/library/data-loading.md create mode 100644 agents/skills/typst-author/docs/reference/library/emoji.md create mode 100644 agents/skills/typst-author/docs/reference/library/foundations.md create mode 100644 agents/skills/typst-author/docs/reference/library/index.md create mode 100644 agents/skills/typst-author/docs/reference/library/introspection.md create mode 100644 agents/skills/typst-author/docs/reference/library/layout.md create mode 100644 agents/skills/typst-author/docs/reference/library/math.md create mode 100644 agents/skills/typst-author/docs/reference/library/model.md create mode 100644 agents/skills/typst-author/docs/reference/library/sym.md create mode 100644 agents/skills/typst-author/docs/reference/library/text.md create mode 100644 agents/skills/typst-author/docs/reference/library/visualize.md create mode 100644 agents/skills/typst-author/docs/tutorial/1-writing.md create mode 100644 agents/skills/typst-author/docs/tutorial/2-formatting.md create mode 100644 agents/skills/typst-author/docs/tutorial/3-advanced.md create mode 100644 agents/skills/typst-author/docs/tutorial/4-template.md create mode 100644 agents/skills/unslop/SKILL.md create mode 100644 agents/skills/verify-this/SKILL.md create mode 100644 agents/skills/wayfinder/SKILL.md create mode 100644 agents/skills/wayfinder/agents/openai.yaml create mode 100644 agents/skills/why/SKILL.md create mode 100644 agents/skills/why/references/epistemics.md create mode 100644 agents/skills/why/references/investigator-prompt.md create mode 100644 agents/skills/why/references/source-playbook.md create mode 100644 agents/skills/why/references/sources/code-archaeology.md create mode 100644 agents/skills/why/references/sources/databricks.md create mode 100644 agents/skills/why/references/sources/datadog.md create mode 100644 agents/skills/why/references/sources/incident-postmortem.md create mode 100644 agents/skills/why/references/sources/linear.md create mode 100644 agents/skills/why/references/sources/notion.md create mode 100644 agents/skills/why/references/sources/sentry.md create mode 100644 agents/skills/why/references/sources/slack.md create mode 100644 agents/skills/why/references/synthesizer-prompt.md delete mode 100644 agents/skills/zoom-out/SKILL.md rename {config => mutable_config}/hypr/.luarc.json (100%) rename {config => mutable_config}/hypr/empty_workspaces.conf (100%) rename {config => mutable_config}/hypr/hypridle.conf (100%) create mode 100644 mutable_config/hypr/hyprland-gui.lua rename {config => mutable_config}/hypr/hyprland.lua (99%) rename {config => mutable_config}/hypr/hyprlock.conf (100%) rename {config => mutable_config}/hypr/mocha.conf (100%) rename {config => mutable_config}/hypr/theme.conf (100%) diff --git a/agents/skills/cavecrew/SKILL.md b/agents/skills/cavecrew/SKILL.md deleted file mode 100644 index efa413f..0000000 --- a/agents/skills/cavecrew/SKILL.md +++ /dev/null @@ -1,82 +0,0 @@ ---- -name: cavecrew -description: > - Decision guide for delegating to caveman-style subagents. Tells the main - thread WHEN to spawn `cavecrew-investigator` (locate code), `cavecrew-builder` - (1-2 file edit), or `cavecrew-reviewer` (diff review) instead of doing the - work inline or using vanilla `Explore`. Subagent output is caveman-compressed - so the tool-result injected back into main context is ~60% smaller — main - context lasts longer across long sessions. - Trigger: "delegate to subagent", "use cavecrew", "spawn investigator/builder/reviewer", - "save context", "compressed agent output". ---- - -Cavecrew = three subagent presets that emit caveman output. Same job as Anthropic defaults (`Explore`, edit-style agents, reviewer); difference is the tool-result they return is compressed, so main context shrinks per delegation. - -## When to use cavecrew vs alternatives - -| Task | Use | -|---|---| -| "Where is X defined / what calls Y / list uses of Z" | `cavecrew-investigator` | -| Same but you also want suggestions/architecture commentary | `Explore` (vanilla) | -| Surgical edit, ≤2 files, scope obvious | `cavecrew-builder` | -| New feature / 3+ files / cross-cutting refactor | Main thread or `feature-dev:code-architect` | -| Review diff, branch, or file for bugs | `cavecrew-reviewer` | -| Deep code review with rationale + alternatives | `Code Reviewer` (vanilla) | -| One-line answer you already know | Main thread, no subagent | - -Rule of thumb: **if you'd want the subagent's output in 1/3 the tokens, pick cavecrew. If you'd want prose, pick vanilla.** - -## Why this exists (the real win) - -Subagent tool results get injected into main context verbatim. A vanilla `Explore` that returns 2k tokens of prose costs 2k tokens of main-context budget every time. The same finding from `cavecrew-investigator` returns ~700 tokens. Across 20 delegations in one session that's the difference between context exhaustion and finishing the task. - -## Output contracts - -What main thread can rely on per agent: - -**`cavecrew-investigator`** -``` -
: -- path:line — `symbol` — short note -totals: . -``` -Or `No match.` Always file-path-first, line-number-attached, backticked symbols. Safe to grep with `path:\d+`. - -**`cavecrew-builder`** -``` - — . -verified: . -``` -Or one of: `too-big.` / `needs-confirm.` / `ambiguous.` / `regressed.` (terminal first token). - -**`cavecrew-reviewer`** -``` -path:line: : . . -totals: N🔴 N🟡 N🔵 N❓ -``` -Or `No issues.` Findings sorted file → line ascending. - -## Chaining patterns - -**Locate → fix → verify** (most common): -1. `cavecrew-investigator` returns site list. -2. Main thread picks 1-2 sites, hands paths to `cavecrew-builder`. -3. `cavecrew-reviewer` audits the diff. - -**Parallel scout** (when investigation is broad): -Spawn 2-3 `cavecrew-investigator` calls in one message (different angles: defs vs callers vs tests). Aggregate in main thread. - -**Single-shot edit** (when site is already known): -Skip investigator. Hand exact path:line to `cavecrew-builder` directly. - -## What NOT to do - -- Don't use `cavecrew-builder` when you don't already know the file. Spawn investigator first or main thread will eat tokens passing context. -- Don't chain `cavecrew-investigator → cavecrew-builder` for a 5-file refactor. Builder will return `too-big.` and you'll have wasted a turn. -- Don't ask `cavecrew-reviewer` for "general feedback" — it returns findings only, no architecture opinions. Use `Code Reviewer` for that. -- Don't expect prose. Cavecrew output is structured, sometimes terse to the point of cryptic. If a human will read it directly, paraphrase. - -## Auto-clarity (inherited) - -Subagents drop caveman → normal English for security warnings, irreversible-action confirmations, and any output where fragment ambiguity could be misread. Resume caveman after. diff --git a/agents/skills/caveman-commit/SKILL.md b/agents/skills/caveman-commit/SKILL.md deleted file mode 100644 index 729318c..0000000 --- a/agents/skills/caveman-commit/SKILL.md +++ /dev/null @@ -1,65 +0,0 @@ ---- -name: caveman-commit -description: > - Ultra-compressed commit message generator. Cuts noise from commit messages while preserving - intent and reasoning. Conventional Commits format. Subject ≤50 chars, body only when "why" - isn't obvious. Use when user says "write a commit", "commit message", "generate commit", - "/commit", or invokes /caveman-commit. Auto-triggers when staging changes. ---- - -Write commit messages terse and exact. Conventional Commits format. No fluff. Why over what. - -## Rules - -**Subject line:** -- `(): ` — `` optional -- Types: `feat`, `fix`, `refactor`, `perf`, `docs`, `test`, `chore`, `build`, `ci`, `style`, `revert` -- Imperative mood: "add", "fix", "remove" — not "added", "adds", "adding" -- ≤50 chars when possible, hard cap 72 -- No trailing period -- Match project convention for capitalization after the colon - -**Body (only if needed):** -- Skip entirely when subject is self-explanatory -- Add body only for: non-obvious *why*, breaking changes, migration notes, linked issues -- Wrap at 72 chars -- Bullets `-` not `*` -- Reference issues/PRs at end: `Closes #42`, `Refs #17` - -**What NEVER goes in:** -- "This commit does X", "I", "we", "now", "currently" — the diff says what -- "As requested by..." — use Co-authored-by trailer -- "Generated with Claude Code" or any AI attribution -- Emoji (unless project convention requires) -- Restating the file name when scope already says it - -## Examples - -Diff: new endpoint for user profile with body explaining the why -- ❌ "feat: add a new endpoint to get user profile information from the database" -- ✅ - ``` - feat(api): add GET /users/:id/profile - - Mobile client needs profile data without the full user payload - to reduce LTE bandwidth on cold-launch screens. - - Closes #128 - ``` - -Diff: breaking API change -- ✅ - ``` - feat(api)!: rename /v1/orders to /v1/checkout - - BREAKING CHANGE: clients on /v1/orders must migrate to /v1/checkout - before 2026-06-01. Old route returns 410 after that date. - ``` - -## Auto-Clarity - -Always include body for: breaking changes, security fixes, data migrations, anything reverting a prior commit. Never compress these into subject-only — future debuggers need the context. - -## Boundaries - -Only generates the commit message. Does not run `git commit`, does not stage files, does not amend. Output the message as a code block ready to paste. "stop caveman-commit" or "normal mode": revert to verbose commit style. \ No newline at end of file diff --git a/agents/skills/caveman-compress/README.md b/agents/skills/caveman-compress/README.md deleted file mode 100644 index 7c0e8ba..0000000 --- a/agents/skills/caveman-compress/README.md +++ /dev/null @@ -1,163 +0,0 @@ -

- -

- -

caveman-compress

- -

- shrink memory file. save token every session. -

- ---- - -A Claude Code skill that compresses your project memory files (`CLAUDE.md`, todos, preferences) into caveman format — so every session loads fewer tokens automatically. - -Claude read `CLAUDE.md` on every session start. If file big, cost big. Caveman make file small. Cost go down forever. - -## What It Do - -``` -/caveman:compress CLAUDE.md -``` - -``` -CLAUDE.md ← compressed (Claude reads this — fewer tokens every session) -CLAUDE.original.md ← human-readable backup (you edit this) -``` - -Original never lost. You can read and edit `.original.md`. Run skill again to re-compress after edits. - -## Benchmarks - -Real results on real project files: - -| File | Original | Compressed | Saved | -|------|----------:|----------:|------:| -| `claude-md-preferences.md` | 706 | 285 | **59.6%** | -| `project-notes.md` | 1145 | 535 | **53.3%** | -| `claude-md-project.md` | 1122 | 636 | **43.3%** | -| `todo-list.md` | 627 | 388 | **38.1%** | -| `mixed-with-code.md` | 888 | 560 | **36.9%** | -| **Average** | **898** | **481** | **46%** | - -All validations passed ✅ — headings, code blocks, URLs, file paths preserved exactly. - -## Before / After - - - - - - -
- -### 📄 Original (706 tokens) - -> "I strongly prefer TypeScript with strict mode enabled for all new code. Please don't use `any` type unless there's genuinely no way around it, and if you do, leave a comment explaining the reasoning. I find that taking the time to properly type things catches a lot of bugs before they ever make it to runtime." - - - -### 🪨 Caveman (285 tokens) - -> "Prefer TypeScript strict mode always. No `any` unless unavoidable — comment why if used. Proper types catch bugs early." - -
- -**Same instructions. 60% fewer tokens. Every. Single. Session.** - -## Security - -`caveman-compress` is flagged as Snyk High Risk due to subprocess and file I/O patterns detected by static analysis. This is a false positive — see [SECURITY.md](./SECURITY.md) for a full explanation of what the skill does and does not do. - -## Install - -Compress is built in with the `caveman` plugin. Install `caveman` once, then use `/caveman:compress`. - -If you need local files, the compress skill lives at: - -```bash -caveman-compress/ -``` - -**Requires:** Python 3.10+ - -## Usage - -``` -/caveman:compress -``` - -Examples: -``` -/caveman:compress CLAUDE.md -/caveman:compress docs/preferences.md -/caveman:compress todos.md -``` - -### What files work - -| Type | Compress? | -|------|-----------| -| `.md`, `.txt`, `.rst` | ✅ Yes | -| Extensionless natural language | ✅ Yes | -| `.py`, `.js`, `.ts`, `.json`, `.yaml` | ❌ Skip (code/config) | -| `*.original.md` | ❌ Skip (backup files) | - -## How It Work - -``` -/caveman:compress CLAUDE.md - ↓ -detect file type (no tokens) - ↓ -Claude compresses (tokens — one call) - ↓ -validate output (no tokens) - checks: headings, code blocks, URLs, file paths, bullets - ↓ -if errors: Claude fixes cherry-picked issues only (tokens — targeted fix) - does NOT recompress — only patches broken parts - ↓ -retry up to 2 times - ↓ -write compressed → CLAUDE.md -write original → CLAUDE.original.md -``` - -Only two things use tokens: initial compression + targeted fix if validation fails. Everything else is local Python. - -## What Is Preserved - -Caveman compress natural language. It never touch: - -- Code blocks (` ``` ` fenced or indented) -- Inline code (`` `backtick content` ``) -- URLs and links -- File paths (`/src/components/...`) -- Commands (`npm install`, `git commit`) -- Technical terms, library names, API names -- Headings (exact text preserved) -- Tables (structure preserved, cell text compressed) -- Dates, version numbers, numeric values - -## Why This Matter - -`CLAUDE.md` loads on **every session start**. A 1000-token project memory file costs tokens every single time you open a project. Over 100 sessions that's 100,000 tokens of overhead — just for context you already wrote. - -Caveman cut that by ~46% on average. Same instructions. Same accuracy. Less waste. - -``` -┌────────────────────────────────────────────┐ -│ TOKEN SAVINGS PER FILE █████ 46% │ -│ SESSIONS THAT BENEFIT ██████████ 100% │ -│ INFORMATION PRESERVED ██████████ 100% │ -│ SETUP TIME █ 1x │ -└────────────────────────────────────────────┘ -``` - -## Part of Caveman - -This skill is part of the [caveman](https://github.com/JuliusBrussee/caveman) toolkit — making Claude use fewer tokens without losing accuracy. - -- **caveman** — make Claude *speak* like caveman (cuts response tokens ~65%) -- **caveman-compress** — make Claude *read* less (cuts context tokens ~46%) diff --git a/agents/skills/caveman-compress/SECURITY.md b/agents/skills/caveman-compress/SECURITY.md deleted file mode 100644 index 693108c..0000000 --- a/agents/skills/caveman-compress/SECURITY.md +++ /dev/null @@ -1,31 +0,0 @@ -# Security - -## Snyk High Risk Rating - -`caveman-compress` receives a Snyk High Risk rating due to static analysis heuristics. This document explains what the skill does and does not do. - -### What triggers the rating - -1. **subprocess usage**: The skill calls the `claude` CLI via `subprocess.run()` as a fallback when `ANTHROPIC_API_KEY` is not set. The subprocess call uses a fixed argument list — no shell interpolation occurs. User file content is passed via stdin, not as a shell argument. - -2. **File read/write**: The skill reads the file the user explicitly points it at, compresses it, and writes the result back to the same path. A `.original.md` backup is saved alongside it. No files outside the user-specified path are read or written. - -### What the skill does NOT do - -- Does not execute user file content as code -- Does not make network requests except to Anthropic's API (via SDK or CLI) -- Does not access files outside the path the user provides -- Does not use shell=True or string interpolation in subprocess calls -- Does not collect or transmit any data beyond the file being compressed - -### Auth behavior - -If `ANTHROPIC_API_KEY` is set, the skill uses the Anthropic Python SDK directly (no subprocess). If not set, it falls back to the `claude` CLI, which uses the user's existing Claude desktop authentication. - -### File size limit - -Files larger than 500KB are rejected before any API call is made. - -### Reporting a vulnerability - -If you believe you've found a genuine security issue, please open a GitHub issue with the label `security`. diff --git a/agents/skills/caveman-compress/SKILL.md b/agents/skills/caveman-compress/SKILL.md deleted file mode 100644 index 7b3e3aa..0000000 --- a/agents/skills/caveman-compress/SKILL.md +++ /dev/null @@ -1,111 +0,0 @@ ---- -name: caveman-compress -description: > - Compress natural language memory files (CLAUDE.md, todos, preferences) into caveman format - to save input tokens. Preserves all technical substance, code, URLs, and structure. - Compressed version overwrites the original file. Human-readable backup saved as FILE.original.md. - Trigger: /caveman:compress or "compress memory file" ---- - -# Caveman Compress - -## Purpose - -Compress natural language files (CLAUDE.md, todos, preferences) into caveman-speak to reduce input tokens. Compressed version overwrites original. Human-readable backup saved as `.original.md`. - -## Trigger - -`/caveman:compress ` or when user asks to compress a memory file. - -## Process - -1. The compression scripts live in `caveman-compress/scripts/` (adjacent to this SKILL.md). If the path is not immediately available, search for `caveman-compress/scripts/__main__.py`. - -2. Run: - -cd caveman-compress && python3 -m scripts - -3. The CLI will: -- detect file type (no tokens) -- call Claude to compress -- validate output (no tokens) -- if errors: cherry-pick fix with Claude (targeted fixes only, no recompression) -- retry up to 2 times -- if still failing after 2 retries: report error to user, leave original file untouched - -4. Return result to user - -## Compression Rules - -### Remove -- Articles: a, an, the -- Filler: just, really, basically, actually, simply, essentially, generally -- Pleasantries: "sure", "certainly", "of course", "happy to", "I'd recommend" -- Hedging: "it might be worth", "you could consider", "it would be good to" -- Redundant phrasing: "in order to" → "to", "make sure to" → "ensure", "the reason is because" → "because" -- Connective fluff: "however", "furthermore", "additionally", "in addition" - -### Preserve EXACTLY (never modify) -- Code blocks (fenced ``` and indented) -- Inline code (`backtick content`) -- URLs and links (full URLs, markdown links) -- File paths (`/src/components/...`, `./config.yaml`) -- Commands (`npm install`, `git commit`, `docker build`) -- Technical terms (library names, API names, protocols, algorithms) -- Proper nouns (project names, people, companies) -- Dates, version numbers, numeric values -- Environment variables (`$HOME`, `NODE_ENV`) - -### Preserve Structure -- All markdown headings (keep exact heading text, compress body below) -- Bullet point hierarchy (keep nesting level) -- Numbered lists (keep numbering) -- Tables (compress cell text, keep structure) -- Frontmatter/YAML headers in markdown files - -### Compress -- Use short synonyms: "big" not "extensive", "fix" not "implement a solution for", "use" not "utilize" -- Fragments OK: "Run tests before commit" not "You should always run tests before committing" -- Drop "you should", "make sure to", "remember to" — just state the action -- Merge redundant bullets that say the same thing differently -- Keep one example where multiple examples show the same pattern - -CRITICAL RULE: -Anything inside ``` ... ``` must be copied EXACTLY. -Do not: -- remove comments -- remove spacing -- reorder lines -- shorten commands -- simplify anything - -Inline code (`...`) must be preserved EXACTLY. -Do not modify anything inside backticks. - -If file contains code blocks: -- Treat code blocks as read-only regions -- Only compress text outside them -- Do not merge sections around code - -## Pattern - -Original: -> You should always make sure to run the test suite before pushing any changes to the main branch. This is important because it helps catch bugs early and prevents broken builds from being deployed to production. - -Compressed: -> Run tests before push to main. Catch bugs early, prevent broken prod deploys. - -Original: -> The application uses a microservices architecture with the following components. The API gateway handles all incoming requests and routes them to the appropriate service. The authentication service is responsible for managing user sessions and JWT tokens. - -Compressed: -> Microservices architecture. API gateway route all requests to services. Auth service manage user sessions + JWT tokens. - -## Boundaries - -- ONLY compress natural language files (.md, .txt, extensionless) -- NEVER modify: .py, .js, .ts, .json, .yaml, .yml, .toml, .env, .lock, .css, .html, .xml, .sql, .sh -- If file has mixed content (prose + code), compress ONLY the prose sections -- If unsure whether something is code or prose, leave it unchanged -- Original file is backed up as FILE.original.md before overwriting -- Never compress FILE.original.md (skip it) diff --git a/agents/skills/caveman-compress/scripts/__init__.py b/agents/skills/caveman-compress/scripts/__init__.py deleted file mode 100644 index 16b8c53..0000000 --- a/agents/skills/caveman-compress/scripts/__init__.py +++ /dev/null @@ -1,9 +0,0 @@ -"""Caveman compress scripts. - -This package provides tools to compress natural language markdown files -into caveman format to save input tokens. -""" - -__all__ = ["cli", "compress", "detect", "validate"] - -__version__ = "1.0.0" diff --git a/agents/skills/caveman-compress/scripts/__main__.py b/agents/skills/caveman-compress/scripts/__main__.py deleted file mode 100644 index 4e28416..0000000 --- a/agents/skills/caveman-compress/scripts/__main__.py +++ /dev/null @@ -1,3 +0,0 @@ -from .cli import main - -main() diff --git a/agents/skills/caveman-compress/scripts/benchmark.py b/agents/skills/caveman-compress/scripts/benchmark.py deleted file mode 100644 index eac927d..0000000 --- a/agents/skills/caveman-compress/scripts/benchmark.py +++ /dev/null @@ -1,78 +0,0 @@ -#!/usr/bin/env python3 -from pathlib import Path -import sys - -# Support both direct execution and module import -try: - from .validate import validate -except ImportError: - sys.path.insert(0, str(Path(__file__).parent)) - from validate import validate - -try: - import tiktoken - _enc = tiktoken.get_encoding("o200k_base") -except ImportError: - _enc = None - - -def count_tokens(text): - if _enc is None: - return len(text.split()) # fallback: word count - return len(_enc.encode(text)) - - -def benchmark_pair(orig_path: Path, comp_path: Path): - orig_text = orig_path.read_text() - comp_text = comp_path.read_text() - - orig_tokens = count_tokens(orig_text) - comp_tokens = count_tokens(comp_text) - saved = 100 * (orig_tokens - comp_tokens) / orig_tokens if orig_tokens > 0 else 0.0 - result = validate(orig_path, comp_path) - - return (comp_path.name, orig_tokens, comp_tokens, saved, result.is_valid) - - -def print_table(rows): - print("\n| File | Original | Compressed | Saved % | Valid |") - print("|------|----------|------------|---------|-------|") - for r in rows: - print(f"| {r[0]} | {r[1]} | {r[2]} | {r[3]:.1f}% | {'✅' if r[4] else '❌'} |") - - -def main(): - # Direct file pair: python3 benchmark.py original.md compressed.md - if len(sys.argv) == 3: - orig = Path(sys.argv[1]).resolve() - comp = Path(sys.argv[2]).resolve() - if not orig.exists(): - print(f"❌ Not found: {orig}") - sys.exit(1) - if not comp.exists(): - print(f"❌ Not found: {comp}") - sys.exit(1) - print_table([benchmark_pair(orig, comp)]) - return - - # Glob mode: repo_root/tests/caveman-compress/ - tests_dir = Path(__file__).parent.parent.parent / "tests" / "caveman-compress" - if not tests_dir.exists(): - print(f"❌ Tests dir not found: {tests_dir}") - sys.exit(1) - - rows = [] - for orig in sorted(tests_dir.glob("*.original.md")): - comp = orig.with_name(orig.stem.removesuffix(".original") + ".md") - if comp.exists(): - rows.append(benchmark_pair(orig, comp)) - - if not rows: - print("No compressed file pairs found.") - return - - print_table(rows) - - -if __name__ == "__main__": - main() diff --git a/agents/skills/caveman-compress/scripts/cli.py b/agents/skills/caveman-compress/scripts/cli.py deleted file mode 100644 index 428fd86..0000000 --- a/agents/skills/caveman-compress/scripts/cli.py +++ /dev/null @@ -1,73 +0,0 @@ -#!/usr/bin/env python3 -""" -Caveman Compress CLI - -Usage: - caveman -""" - -import sys -from pathlib import Path - -from .compress import compress_file -from .detect import detect_file_type, should_compress - - -def print_usage(): - print("Usage: caveman ") - - -def main(): - if len(sys.argv) != 2: - print_usage() - sys.exit(1) - - filepath = Path(sys.argv[1]) - - # Check file exists - if not filepath.exists(): - print(f"❌ File not found: {filepath}") - sys.exit(1) - - if not filepath.is_file(): - print(f"❌ Not a file: {filepath}") - sys.exit(1) - - filepath = filepath.resolve() - - # Detect file type - file_type = detect_file_type(filepath) - - print(f"Detected: {file_type}") - - # Check if compressible - if not should_compress(filepath): - print("Skipping: file is not natural language (code/config)") - sys.exit(0) - - print("Starting caveman compression...\n") - - try: - success = compress_file(filepath) - - if success: - print("\nCompression completed successfully") - backup_path = filepath.with_name(filepath.stem + ".original.md") - print(f"Compressed: {filepath}") - print(f"Original: {backup_path}") - sys.exit(0) - else: - print("\n❌ Compression failed after retries") - sys.exit(2) - - except KeyboardInterrupt: - print("\nInterrupted by user") - sys.exit(130) - - except Exception as e: - print(f"\n❌ Error: {e}") - sys.exit(1) - - -if __name__ == "__main__": - main() diff --git a/agents/skills/caveman-compress/scripts/compress.py b/agents/skills/caveman-compress/scripts/compress.py deleted file mode 100644 index 1622a7a..0000000 --- a/agents/skills/caveman-compress/scripts/compress.py +++ /dev/null @@ -1,176 +0,0 @@ -#!/usr/bin/env python3 -""" -Caveman Memory Compression Orchestrator - -Usage: - python scripts/compress.py -""" - -import os -import re -import subprocess -from pathlib import Path -from typing import List - -OUTER_FENCE_REGEX = re.compile( - r"\A\s*(`{3,}|~{3,})[^\n]*\n(.*)\n\1\s*\Z", re.DOTALL -) - - -def strip_llm_wrapper(text: str) -> str: - """Strip outer ```markdown ... ``` fence when it wraps the entire output.""" - m = OUTER_FENCE_REGEX.match(text) - if m: - return m.group(2) - return text - -from .detect import should_compress -from .validate import validate - -MAX_RETRIES = 2 - - -# ---------- Claude Calls ---------- - - -def call_claude(prompt: str) -> str: - api_key = os.environ.get("ANTHROPIC_API_KEY") - if api_key: - try: - import anthropic - - client = anthropic.Anthropic(api_key=api_key) - msg = client.messages.create( - model=os.environ.get("CAVEMAN_MODEL", "claude-sonnet-4-5"), - max_tokens=8192, - messages=[{"role": "user", "content": prompt}], - ) - return strip_llm_wrapper(msg.content[0].text.strip()) - except ImportError: - pass # anthropic not installed, fall back to CLI - # Fallback: use claude CLI (handles desktop auth) - try: - result = subprocess.run( - ["claude", "--print"], - input=prompt, - text=True, - capture_output=True, - check=True, - ) - return strip_llm_wrapper(result.stdout.strip()) - except subprocess.CalledProcessError as e: - raise RuntimeError(f"Claude call failed:\n{e.stderr}") - - -def build_compress_prompt(original: str) -> str: - return f""" -Compress this markdown into caveman format. - -STRICT RULES: -- Do NOT modify anything inside ``` code blocks -- Do NOT modify anything inside inline backticks -- Preserve ALL URLs exactly -- Preserve ALL headings exactly -- Preserve file paths and commands -- Return ONLY the compressed markdown body — do NOT wrap the entire output in a ```markdown fence or any other fence. Inner code blocks from the original stay as-is; do not add a new outer fence around the whole file. - -Only compress natural language. - -TEXT: -{original} -""" - - -def build_fix_prompt(original: str, compressed: str, errors: List[str]) -> str: - errors_str = "\n".join(f"- {e}" for e in errors) - return f"""You are fixing a caveman-compressed markdown file. Specific validation errors were found. - -CRITICAL RULES: -- DO NOT recompress or rephrase the file -- ONLY fix the listed errors — leave everything else exactly as-is -- The ORIGINAL is provided as reference only (to restore missing content) -- Preserve caveman style in all untouched sections - -ERRORS TO FIX: -{errors_str} - -HOW TO FIX: -- Missing URL: find it in ORIGINAL, restore it exactly where it belongs in COMPRESSED -- Code block mismatch: find the exact code block in ORIGINAL, restore it in COMPRESSED -- Heading mismatch: restore the exact heading text from ORIGINAL into COMPRESSED -- Do not touch any section not mentioned in the errors - -ORIGINAL (reference only): -{original} - -COMPRESSED (fix this): -{compressed} - -Return ONLY the fixed compressed file. No explanation. -""" - - -# ---------- Core Logic ---------- - - -def compress_file(filepath: Path) -> bool: - # Resolve and validate path - filepath = filepath.resolve() - MAX_FILE_SIZE = 500_000 # 500KB - if not filepath.exists(): - raise FileNotFoundError(f"File not found: {filepath}") - if filepath.stat().st_size > MAX_FILE_SIZE: - raise ValueError(f"File too large to compress safely (max 500KB): {filepath}") - - print(f"Processing: {filepath}") - - if not should_compress(filepath): - print("Skipping (not natural language)") - return False - - original_text = filepath.read_text(errors="ignore") - backup_path = filepath.with_name(filepath.stem + ".original.md") - - # Check if backup already exists to prevent accidental overwriting - if backup_path.exists(): - print(f"⚠️ Backup file already exists: {backup_path}") - print("The original backup may contain important content.") - print("Aborting to prevent data loss. Please remove or rename the backup file if you want to proceed.") - return False - - # Step 1: Compress - print("Compressing with Claude...") - compressed = call_claude(build_compress_prompt(original_text)) - - # Save original as backup, write compressed to original path - backup_path.write_text(original_text) - filepath.write_text(compressed) - - # Step 2: Validate + Retry - for attempt in range(MAX_RETRIES): - print(f"\nValidation attempt {attempt + 1}") - - result = validate(backup_path, filepath) - - if result.is_valid: - print("Validation passed") - break - - print("❌ Validation failed:") - for err in result.errors: - print(f" - {err}") - - if attempt == MAX_RETRIES - 1: - # Restore original on failure - filepath.write_text(original_text) - backup_path.unlink(missing_ok=True) - print("❌ Failed after retries — original restored") - return False - - print("Fixing with Claude...") - compressed = call_claude( - build_fix_prompt(original_text, compressed, result.errors) - ) - filepath.write_text(compressed) - - return True diff --git a/agents/skills/caveman-compress/scripts/detect.py b/agents/skills/caveman-compress/scripts/detect.py deleted file mode 100644 index 5f50fd3..0000000 --- a/agents/skills/caveman-compress/scripts/detect.py +++ /dev/null @@ -1,121 +0,0 @@ -#!/usr/bin/env python3 -"""Detect whether a file is natural language (compressible) or code/config (skip).""" - -import json -import re -from pathlib import Path - -# Extensions that are natural language and compressible -COMPRESSIBLE_EXTENSIONS = {".md", ".txt", ".markdown", ".rst"} - -# Extensions that are code/config and should be skipped -SKIP_EXTENSIONS = { - ".py", ".js", ".ts", ".tsx", ".jsx", ".json", ".yaml", ".yml", - ".toml", ".env", ".lock", ".css", ".scss", ".html", ".xml", - ".sql", ".sh", ".bash", ".zsh", ".go", ".rs", ".java", ".c", - ".cpp", ".h", ".hpp", ".rb", ".php", ".swift", ".kt", ".lua", - ".dockerfile", ".makefile", ".csv", ".ini", ".cfg", -} - -# Patterns that indicate a line is code -CODE_PATTERNS = [ - re.compile(r"^\s*(import |from .+ import |require\(|const |let |var )"), - re.compile(r"^\s*(def |class |function |async function |export )"), - re.compile(r"^\s*(if\s*\(|for\s*\(|while\s*\(|switch\s*\(|try\s*\{)"), - re.compile(r"^\s*[\}\]\);]+\s*$"), # closing braces/brackets - re.compile(r"^\s*@\w+"), # decorators/annotations - re.compile(r'^\s*"[^"]+"\s*:\s*'), # JSON-like key-value - re.compile(r"^\s*\w+\s*=\s*[{\[\(\"']"), # assignment with literal -] - - -def _is_code_line(line: str) -> bool: - """Check if a line looks like code.""" - return any(p.match(line) for p in CODE_PATTERNS) - - -def _is_json_content(text: str) -> bool: - """Check if content is valid JSON.""" - try: - json.loads(text) - return True - except (json.JSONDecodeError, ValueError): - return False - - -def _is_yaml_content(lines: list[str]) -> bool: - """Heuristic: check if content looks like YAML.""" - yaml_indicators = 0 - for line in lines[:30]: - stripped = line.strip() - if stripped.startswith("---"): - yaml_indicators += 1 - elif re.match(r"^\w[\w\s]*:\s", stripped): - yaml_indicators += 1 - elif stripped.startswith("- ") and ":" in stripped: - yaml_indicators += 1 - # If most non-empty lines look like YAML - non_empty = sum(1 for l in lines[:30] if l.strip()) - return non_empty > 0 and yaml_indicators / non_empty > 0.6 - - -def detect_file_type(filepath: Path) -> str: - """Classify a file as 'natural_language', 'code', 'config', or 'unknown'. - - Returns: - One of: 'natural_language', 'code', 'config', 'unknown' - """ - ext = filepath.suffix.lower() - - # Extension-based classification - if ext in COMPRESSIBLE_EXTENSIONS: - return "natural_language" - if ext in SKIP_EXTENSIONS: - return "code" if ext not in {".json", ".yaml", ".yml", ".toml", ".ini", ".cfg", ".env"} else "config" - - # Extensionless files (like CLAUDE.md, TODO) — check content - if not ext: - try: - text = filepath.read_text(errors="ignore") - except (OSError, PermissionError): - return "unknown" - - lines = text.splitlines()[:50] - - if _is_json_content(text[:10000]): - return "config" - if _is_yaml_content(lines): - return "config" - - code_lines = sum(1 for l in lines if l.strip() and _is_code_line(l)) - non_empty = sum(1 for l in lines if l.strip()) - if non_empty > 0 and code_lines / non_empty > 0.4: - return "code" - - return "natural_language" - - return "unknown" - - -def should_compress(filepath: Path) -> bool: - """Return True if the file is natural language and should be compressed.""" - if not filepath.is_file(): - return False - # Skip backup files - if filepath.name.endswith(".original.md"): - return False - return detect_file_type(filepath) == "natural_language" - - -if __name__ == "__main__": - import sys - - if len(sys.argv) < 2: - print("Usage: python detect.py [file2] ...") - sys.exit(1) - - for path_str in sys.argv[1:]: - p = Path(path_str).resolve() - file_type = detect_file_type(p) - compress = should_compress(p) - print(f" {p.name:30s} type={file_type:20s} compress={compress}") diff --git a/agents/skills/caveman-compress/scripts/validate.py b/agents/skills/caveman-compress/scripts/validate.py deleted file mode 100644 index 3c4d4c1..0000000 --- a/agents/skills/caveman-compress/scripts/validate.py +++ /dev/null @@ -1,189 +0,0 @@ -#!/usr/bin/env python3 -import re -from pathlib import Path - -URL_REGEX = re.compile(r"https?://[^\s)]+") -FENCE_OPEN_REGEX = re.compile(r"^(\s{0,3})(`{3,}|~{3,})(.*)$") -HEADING_REGEX = re.compile(r"^(#{1,6})\s+(.*)", re.MULTILINE) -BULLET_REGEX = re.compile(r"^\s*[-*+]\s+", re.MULTILINE) - -# crude but effective path detection -# Requires either a path prefix (./ ../ / or drive letter) or a slash/backslash within the match -PATH_REGEX = re.compile(r"(?:\./|\.\./|/|[A-Za-z]:\\)[\w\-/\\\.]+|[\w\-\.]+[/\\][\w\-/\\\.]+") - - -class ValidationResult: - def __init__(self): - self.is_valid = True - self.errors = [] - self.warnings = [] - - def add_error(self, msg): - self.is_valid = False - self.errors.append(msg) - - def add_warning(self, msg): - self.warnings.append(msg) - - -def read_file(path: Path) -> str: - return path.read_text(errors="ignore") - - -# ---------- Extractors ---------- - - -def extract_headings(text): - return [(level, title.strip()) for level, title in HEADING_REGEX.findall(text)] - - -def extract_code_blocks(text): - """Line-based fenced code block extractor. - - Handles ``` and ~~~ fences with variable length (CommonMark: closing - fence must use same char and be at least as long as opening). Supports - nested fences (e.g. an outer 4-backtick block wrapping inner 3-backtick - content). - """ - blocks = [] - lines = text.split("\n") - i = 0 - n = len(lines) - while i < n: - m = FENCE_OPEN_REGEX.match(lines[i]) - if not m: - i += 1 - continue - fence_char = m.group(2)[0] - fence_len = len(m.group(2)) - open_line = lines[i] - block_lines = [open_line] - i += 1 - closed = False - while i < n: - close_m = FENCE_OPEN_REGEX.match(lines[i]) - if ( - close_m - and close_m.group(2)[0] == fence_char - and len(close_m.group(2)) >= fence_len - and close_m.group(3).strip() == "" - ): - block_lines.append(lines[i]) - closed = True - i += 1 - break - block_lines.append(lines[i]) - i += 1 - if closed: - blocks.append("\n".join(block_lines)) - # Unclosed fences are silently skipped — they indicate malformed markdown - # and including them would cause false-positive validation failures. - return blocks - - -def extract_urls(text): - return set(URL_REGEX.findall(text)) - - -def extract_paths(text): - return set(PATH_REGEX.findall(text)) - - -def count_bullets(text): - return len(BULLET_REGEX.findall(text)) - - -# ---------- Validators ---------- - - -def validate_headings(orig, comp, result): - h1 = extract_headings(orig) - h2 = extract_headings(comp) - - if len(h1) != len(h2): - result.add_error(f"Heading count mismatch: {len(h1)} vs {len(h2)}") - - if h1 != h2: - result.add_warning("Heading text/order changed") - - -def validate_code_blocks(orig, comp, result): - c1 = extract_code_blocks(orig) - c2 = extract_code_blocks(comp) - - if c1 != c2: - result.add_error("Code blocks not preserved exactly") - - -def validate_urls(orig, comp, result): - u1 = extract_urls(orig) - u2 = extract_urls(comp) - - if u1 != u2: - result.add_error(f"URL mismatch: lost={u1 - u2}, added={u2 - u1}") - - -def validate_paths(orig, comp, result): - p1 = extract_paths(orig) - p2 = extract_paths(comp) - - if p1 != p2: - result.add_warning(f"Path mismatch: lost={p1 - p2}, added={p2 - p1}") - - -def validate_bullets(orig, comp, result): - b1 = count_bullets(orig) - b2 = count_bullets(comp) - - if b1 == 0: - return - - diff = abs(b1 - b2) / b1 - - if diff > 0.15: - result.add_warning(f"Bullet count changed too much: {b1} -> {b2}") - - -# ---------- Main ---------- - - -def validate(original_path: Path, compressed_path: Path) -> ValidationResult: - result = ValidationResult() - - orig = read_file(original_path) - comp = read_file(compressed_path) - - validate_headings(orig, comp, result) - validate_code_blocks(orig, comp, result) - validate_urls(orig, comp, result) - validate_paths(orig, comp, result) - validate_bullets(orig, comp, result) - - return result - - -# ---------- CLI ---------- - -if __name__ == "__main__": - import sys - - if len(sys.argv) != 3: - print("Usage: python validate.py ") - sys.exit(1) - - orig = Path(sys.argv[1]).resolve() - comp = Path(sys.argv[2]).resolve() - - res = validate(orig, comp) - - print(f"\nValid: {res.is_valid}") - - if res.errors: - print("\nErrors:") - for e in res.errors: - print(f" - {e}") - - if res.warnings: - print("\nWarnings:") - for w in res.warnings: - print(f" - {w}") diff --git a/agents/skills/caveman-help/SKILL.md b/agents/skills/caveman-help/SKILL.md deleted file mode 100644 index 078e487..0000000 --- a/agents/skills/caveman-help/SKILL.md +++ /dev/null @@ -1,59 +0,0 @@ ---- -name: caveman-help -description: > - Quick-reference card for all caveman modes, skills, and commands. - One-shot display, not a persistent mode. Trigger: /caveman-help, - "caveman help", "what caveman commands", "how do I use caveman". ---- - -# Caveman Help - -Display this reference card when invoked. One-shot — do NOT change mode, write flag files, or persist anything. Output in caveman style. - -## Modes - -| Mode | Trigger | What change | -|------|---------|-------------| -| **Lite** | `/caveman lite` | Drop filler. Keep sentence structure. | -| **Full** | `/caveman` | Drop articles, filler, pleasantries, hedging. Fragments OK. Default. | -| **Ultra** | `/caveman ultra` | Extreme compression. Bare fragments. Tables over prose. | -| **Wenyan-Lite** | `/caveman wenyan-lite` | Classical Chinese style, light compression. | -| **Wenyan-Full** | `/caveman wenyan` | Full 文言文. Maximum classical terseness. | -| **Wenyan-Ultra** | `/caveman wenyan-ultra` | Extreme. Ancient scholar on a budget. | - -Mode stick until changed or session end. - -## Skills - -| Skill | Trigger | What it do | -|-------|---------|-----------| -| **caveman-commit** | `/caveman-commit` | Terse commit messages. Conventional Commits. ≤50 char subject. | -| **caveman-review** | `/caveman-review` | One-line PR comments: `L42: bug: user null. Add guard.` | -| **caveman-compress** | `/caveman:compress ` | Compress .md files to caveman prose. Saves ~46% input tokens. | -| **caveman-help** | `/caveman-help` | This card. | - -## Deactivate - -Say "stop caveman" or "normal mode". Resume anytime with `/caveman`. - -## Configure Default Mode - -Default mode = `full`. Change it: - -**Environment variable** (highest priority): -```bash -export CAVEMAN_DEFAULT_MODE=ultra -``` - -**Config file** (`~/.config/caveman/config.json`): -```json -{ "defaultMode": "lite" } -``` - -Set `"off"` to disable auto-activation on session start. User can still activate manually with `/caveman`. - -Resolution: env var > config file > `full`. - -## More - -Full docs: https://github.com/JuliusBrussee/caveman diff --git a/agents/skills/caveman-review/SKILL.md b/agents/skills/caveman-review/SKILL.md deleted file mode 100644 index 48f4adb..0000000 --- a/agents/skills/caveman-review/SKILL.md +++ /dev/null @@ -1,55 +0,0 @@ ---- -name: caveman-review -description: > - Ultra-compressed code review comments. Cuts noise from PR feedback while preserving - the actionable signal. Each comment is one line: location, problem, fix. Use when user - says "review this PR", "code review", "review the diff", "/review", or invokes - /caveman-review. Auto-triggers when reviewing pull requests. ---- - -Write code review comments terse and actionable. One line per finding. Location, problem, fix. No throat-clearing. - -## Rules - -**Format:** `L: . .` — or `:L: ...` when reviewing multi-file diffs. - -**Severity prefix (optional, when mixed):** -- `🔴 bug:` — broken behavior, will cause incident -- `🟡 risk:` — works but fragile (race, missing null check, swallowed error) -- `🔵 nit:` — style, naming, micro-optim. Author can ignore -- `❓ q:` — genuine question, not a suggestion - -**Drop:** -- "I noticed that...", "It seems like...", "You might want to consider..." -- "This is just a suggestion but..." — use `nit:` instead -- "Great work!", "Looks good overall but..." — say it once at the top, not per comment -- Restating what the line does — the reviewer can read the diff -- Hedging ("perhaps", "maybe", "I think") — if unsure use `q:` - -**Keep:** -- Exact line numbers -- Exact symbol/function/variable names in backticks -- Concrete fix, not "consider refactoring this" -- The *why* if the fix isn't obvious from the problem statement - -## Examples - -❌ "I noticed that on line 42 you're not checking if the user object is null before accessing the email property. This could potentially cause a crash if the user is not found in the database. You might want to add a null check here." - -✅ `L42: 🔴 bug: user can be null after .find(). Add guard before .email.` - -❌ "It looks like this function is doing a lot of things and might benefit from being broken up into smaller functions for readability." - -✅ `L88-140: 🔵 nit: 50-line fn does 4 things. Extract validate/normalize/persist.` - -❌ "Have you considered what happens if the API returns a 429? I think we should probably handle that case." - -✅ `L23: 🟡 risk: no retry on 429. Wrap in withBackoff(3).` - -## Auto-Clarity - -Drop terse mode for: security findings (CVE-class bugs need full explanation + reference), architectural disagreements (need rationale, not just a one-liner), and onboarding contexts where the author is new and needs the "why". In those cases write a normal paragraph, then resume terse for the rest. - -## Boundaries - -Reviews only — does not write the code fix, does not approve/request-changes, does not run linters. Output the comment(s) ready to paste into the PR. "stop caveman-review" or "normal mode": revert to verbose review style. \ No newline at end of file diff --git a/agents/skills/caveman-stats/SKILL.md b/agents/skills/caveman-stats/SKILL.md deleted file mode 100644 index a7348ac..0000000 --- a/agents/skills/caveman-stats/SKILL.md +++ /dev/null @@ -1,10 +0,0 @@ ---- -name: caveman-stats -description: > - Show real token usage and estimated savings for the current session. - Reads directly from the Claude Code session log — no AI estimation. - Triggers on /caveman-stats. Output is injected by the mode-tracker hook; - the model itself does not compute the numbers. ---- - -This skill is delivered by `hooks/caveman-stats.js` (read by `hooks/caveman-mode-tracker.js` on `/caveman-stats`). The model does not need to do anything when this skill fires — the hook returns `decision: "block"` with the formatted stats as the reason. The user sees the numbers immediately. diff --git a/agents/skills/caveman/SKILL.md b/agents/skills/caveman/SKILL.md deleted file mode 100644 index 2ab498b..0000000 --- a/agents/skills/caveman/SKILL.md +++ /dev/null @@ -1,67 +0,0 @@ ---- -name: caveman -description: > - Ultra-compressed communication mode. Cuts token usage ~75% by speaking like caveman - while keeping full technical accuracy. Supports intensity levels: lite, full (default), ultra, - wenyan-lite, wenyan-full, wenyan-ultra. - Use when user says "caveman mode", "talk like caveman", "use caveman", "less tokens", - "be brief", or invokes /caveman. Also auto-triggers when token efficiency is requested. ---- - -Respond terse like smart caveman. All technical substance stay. Only fluff die. - -## Persistence - -ACTIVE EVERY RESPONSE. No revert after many turns. No filler drift. Still active if unsure. Off only: "stop caveman" / "normal mode". - -Default: **full**. Switch: `/caveman lite|full|ultra`. - -## Rules - -Drop: articles (a/an/the), filler (just/really/basically/actually/simply), pleasantries (sure/certainly/of course/happy to), hedging. Fragments OK. Short synonyms (big not extensive, fix not "implement a solution for"). Technical terms exact. Code blocks unchanged. Errors quoted exact. - -Pattern: `[thing] [action] [reason]. [next step].` - -Not: "Sure! I'd be happy to help you with that. The issue you're experiencing is likely caused by..." -Yes: "Bug in auth middleware. Token expiry check use `<` not `<=`. Fix:" - -## Intensity - -| Level | What change | -|-------|------------| -| **lite** | No filler/hedging. Keep articles + full sentences. Professional but tight | -| **full** | Drop articles, fragments OK, short synonyms. Classic caveman | -| **ultra** | Abbreviate (DB/auth/config/req/res/fn/impl), strip conjunctions, arrows for causality (X → Y), one word when one word enough | -| **wenyan-lite** | Semi-classical. Drop filler/hedging but keep grammar structure, classical register | -| **wenyan-full** | Maximum classical terseness. Fully 文言文. 80-90% character reduction. Classical sentence patterns, verbs precede objects, subjects often omitted, classical particles (之/乃/為/其) | -| **wenyan-ultra** | Extreme abbreviation while keeping classical Chinese feel. Maximum compression, ultra terse | - -Example — "Why React component re-render?" -- lite: "Your component re-renders because you create a new object reference each render. Wrap it in `useMemo`." -- full: "New object ref each render. Inline object prop = new ref = re-render. Wrap in `useMemo`." -- ultra: "Inline obj prop → new ref → re-render. `useMemo`." -- wenyan-lite: "組件頻重繪,以每繪新生對象參照故。以 useMemo 包之。" -- wenyan-full: "物出新參照,致重繪。useMemo .Wrap之。" -- wenyan-ultra: "新參照→重繪。useMemo Wrap。" - -Example — "Explain database connection pooling." -- lite: "Connection pooling reuses open connections instead of creating new ones per request. Avoids repeated handshake overhead." -- full: "Pool reuse open DB connections. No new connection per request. Skip handshake overhead." -- ultra: "Pool = reuse DB conn. Skip handshake → fast under load." -- wenyan-full: "池reuse open connection。不每req新開。skip handshake overhead。" -- wenyan-ultra: "池reuse conn。skip handshake → fast。" - -## Auto-Clarity - -Drop caveman for: security warnings, irreversible action confirmations, multi-step sequences where fragment order risks misread, user asks to clarify or repeats question. Resume caveman after clear part done. - -Example — destructive op: -> **Warning:** This will permanently delete all rows in the `users` table and cannot be undone. -> ```sql -> DROP TABLE users; -> ``` -> Caveman resume. Verify backup exist first. - -## Boundaries - -Code/commits/PRs: write normal. "stop caveman" or "normal mode": revert. Level persist until changed or session end. \ No newline at end of file diff --git a/agents/skills/check-compiler-errors/SKILL.md b/agents/skills/check-compiler-errors/SKILL.md new file mode 100644 index 0000000..585f4bb --- /dev/null +++ b/agents/skills/check-compiler-errors/SKILL.md @@ -0,0 +1,23 @@ +--- +name: check-compiler-errors +description: Run compile and type-check commands and report failures +--- + +# Check compiler errors + +## Trigger + +Compile or type-check failures are blocking local validation or CI. + +## Workflow + +1. Run the repo's compile and type-check commands. +2. Summarize errors by file and type. +3. Fix the highest-confidence issues first. +4. Re-run checks until clean or blocked. + +## Output + +- Current compile and type-check status +- Error summary grouped by file and category +- Fixes applied and remaining blockers diff --git a/agents/skills/code-review/SKILL.md b/agents/skills/code-review/SKILL.md new file mode 100644 index 0000000..e28d7ac --- /dev/null +++ b/agents/skills/code-review/SKILL.md @@ -0,0 +1,87 @@ +--- +name: code-review +description: "Review the changes since a fixed point (commit, branch, tag, or merge-base) along two axes: Standards (does the code follow this repo's documented coding standards?) and Spec (does the code match what the originating issue/spec asked for?). Runs both reviews in parallel sub-agents and reports them side by side. Use when the user wants to review a branch, a PR, work-in-progress changes, or asks to \"review since X\"." +--- + +Two-axis review of the diff between `HEAD` and a fixed point the user supplies: + +- **Standards**: does the code conform to this repo's documented coding standards? +- **Spec**: does the code faithfully implement the originating issue / spec? + +Both axes run as **parallel sub-agents** so they don't pollute each other's context, then this skill aggregates their findings. + +The issue tracker should have been provided to you. If `docs/agents/issue-tracker.md` is missing, tell the user to run `/setup-matt-pocock-skills`. + +## Process + +### 1. Pin the fixed point + +Whatever the user said is the fixed point (a commit SHA, branch name, tag, `main`, `HEAD~5`, etc.). If they didn't specify one, ask for it. + +Capture the diff command once: `git diff ...HEAD` (three-dot, so the comparison is against the merge-base). Also note the list of commits via `git log ..HEAD --oneline`. + +Before going further, confirm the fixed point resolves (`git rev-parse `) and the diff is non-empty. A bad ref or empty diff should fail here, not inside two parallel sub-agents. + +### 2. Identify the spec source + +Look for the originating spec, in this order: + +1. Issue references in the commit messages (`#123`, `Closes #45`, GitLab `!67`, etc.), fetched via the workflow in `docs/agents/issue-tracker.md`. +2. A path the user passed as an argument. +3. A spec file under `docs/`, `specs/`, or `.scratch/` matching the branch name or feature. +4. If nothing is found, ask the user where the spec is. If they say there isn't one, the **Spec** sub-agent will skip and report "no spec available". + +### 3. Identify the standards sources + +Anything in the repo that documents how code should be written, such as `CODING_STANDARDS.md` or `CONTRIBUTING.md`. + +On top of whatever the repo documents, the Standards axis always carries the **smell baseline** below: a fixed set of Fowler code smells (_Refactoring_, ch.3) that applies even when a repo documents nothing. Two rules bind it: + +- **The repo overrides.** A documented repo standard always wins; where it endorses something the baseline would flag, suppress the smell. +- **Always a judgement call.** Each smell is a labelled heuristic ("possible Feature Envy"), never a hard violation. Like any standard here, skip anything tooling already enforces. + +Each smell reads *what it is* → *how to fix*; match it against the diff: + +- **Mysterious Name**: a function, variable, or type whose name doesn't reveal what it does or holds. → rename it; if no honest name comes, the design's murky. +- **Duplicated Code**: the same logic shape appears in more than one hunk or file in the change. → extract the shared shape, call it from both. +- **Feature Envy**: a method that reaches into another object's data more than its own. → move the method onto the data it envies. +- **Data Clumps**: the same few fields or params keep travelling together (a type wanting to be born). → bundle them into one type, pass that. +- **Primitive Obsession**: a primitive or string standing in for a domain concept that deserves its own type. → give the concept its own small type. +- **Repeated Switches**: the same `switch`/`if`-cascade on the same type recurs across the change. → replace with polymorphism, or one map both sites share. +- **Shotgun Surgery**: one logical change forces scattered edits across many files in the diff. → gather what changes together into one module. +- **Divergent Change**: one file or module is edited for several unrelated reasons. → split so each module changes for one reason. +- **Speculative Generality**: abstraction, parameters, or hooks added for needs the spec doesn't have. → delete it; inline back until a real need shows. +- **Message Chains**: long `a.b().c().d()` navigation the caller shouldn't depend on. → hide the walk behind one method on the first object. +- **Middle Man**: a class or function that mostly just delegates onward. → cut it, call the real target direct. +- **Refused Bequest**: a subclass or implementer that ignores or overrides most of what it inherits. → drop the inheritance, use composition. + +### 4. Spawn both sub-agents in parallel + +**Standards sub-agent prompt** should include: + +- The full diff command and commit list. +- The list of standards-source files you found in step 3, **plus the smell baseline from step 3** pasted in full (the sub-agent has no other access to it). +- The brief: "Report, per file/hunk where relevant, (a) every place the diff violates a documented standard: cite the standard (file + the rule); and (b) any baseline smell you spot: name it and quote the hunk. Distinguish hard violations from judgement calls: documented-standard breaches can be hard, but baseline smells are always judgement calls, and a documented repo standard overrides the baseline. Skip anything tooling enforces. Under 400 words." + +**Spec sub-agent prompt** should include: + +- The diff command and commit list. +- The path or fetched contents of the spec. +- The brief: "Report: (a) requirements the spec asked for that are missing or partial; (b) behaviour in the diff that wasn't asked for (scope creep); (c) requirements that look implemented but where the implementation looks wrong. Quote the spec line for each finding. Under 400 words." + +If the spec is missing, skip the Spec sub-agent and note this in the final report. + +### 5. Aggregate + +Present the two reports under `## Standards` and `## Spec` headings, verbatim or lightly cleaned. Do **not** merge or rerank findings, because the two axes are deliberately separate (see _Why two axes_). + +End with a one-line summary: total findings per axis, and the worst issue _within each axis_ (if any). Don't pick a single winner across axes: that's the reranking the separation exists to prevent. + +## Why two axes + +A change can pass one axis and fail the other: + +- Code that follows every standard but implements the wrong thing → **Standards pass, Spec fail.** +- Code that does exactly what the issue asked but breaks the project's conventions → **Spec pass, Standards fail.** + +Reporting them separately stops one axis from masking the other. diff --git a/agents/skills/code-review/agents/openai.yaml b/agents/skills/code-review/agents/openai.yaml new file mode 100644 index 0000000..9076774 --- /dev/null +++ b/agents/skills/code-review/agents/openai.yaml @@ -0,0 +1,3 @@ +interface: + display_name: "Code Review" + short_description: "Review a diff on standards and spec" diff --git a/agents/skills/improve-codebase-architecture/DEEPENING.md b/agents/skills/codebase-design/DEEPENING.md similarity index 80% rename from agents/skills/improve-codebase-architecture/DEEPENING.md rename to agents/skills/codebase-design/DEEPENING.md index ecaf5d7..cd94075 100644 --- a/agents/skills/improve-codebase-architecture/DEEPENING.md +++ b/agents/skills/codebase-design/DEEPENING.md @@ -1,6 +1,6 @@ # Deepening -How to deepen a cluster of shallow modules safely, given its dependencies. Assumes the vocabulary in [LANGUAGE.md](LANGUAGE.md) — **module**, **interface**, **seam**, **adapter**. +How to deepen a cluster of shallow modules safely, given its dependencies. Assumes the vocabulary in [SKILL.md](SKILL.md): **module**, **interface**, **seam**, **adapter**. ## Dependency categories @@ -8,7 +8,7 @@ When assessing a candidate for deepening, classify its dependencies. The categor ### 1. In-process -Pure computation, in-memory state, no I/O. Always deepenable — merge the modules and test through the new interface directly. No adapter needed. +Pure computation, in-memory state, no I/O. Always deepenable: merge the modules and test through the new interface directly. No adapter needed. ### 2. Local-substitutable @@ -31,7 +31,7 @@ Third-party services (Stripe, Twilio, etc.) you don't control. The deepened modu ## Testing strategy: replace, don't layer -- Old unit tests on shallow modules become waste once tests at the deepened module's interface exist — delete them. +- Old unit tests on shallow modules become waste once tests at the deepened module's interface exist; delete them. - Write new tests at the deepened module's interface. The **interface is the test surface**. - Tests assert on observable outcomes through the interface, not internal state. -- Tests should survive internal refactors — they describe behaviour, not implementation. If a test has to change when the implementation changes, it's testing past the interface. +- Tests should survive internal refactors, since they describe behaviour, not implementation. If a test has to change when the implementation changes, it's testing past the interface. diff --git a/agents/skills/improve-codebase-architecture/INTERFACE-DESIGN.md b/agents/skills/codebase-design/DESIGN-IT-TWICE.md similarity index 56% rename from agents/skills/improve-codebase-architecture/INTERFACE-DESIGN.md rename to agents/skills/codebase-design/DESIGN-IT-TWICE.md index 3197723..7edc861 100644 --- a/agents/skills/improve-codebase-architecture/INTERFACE-DESIGN.md +++ b/agents/skills/codebase-design/DESIGN-IT-TWICE.md @@ -1,8 +1,8 @@ -# Interface Design +# Design It Twice -When the user wants to explore alternative interfaces for a chosen deepening candidate, use this parallel sub-agent pattern. Based on "Design It Twice" (Ousterhout) — your first idea is unlikely to be the best. +When the user wants to explore alternative interfaces for a chosen deepening candidate, use this parallel sub-agent pattern. Based on "Design It Twice" (Ousterhout): your first idea is unlikely to be the best. -Uses the vocabulary in [LANGUAGE.md](LANGUAGE.md) — **module**, **interface**, **seam**, **adapter**, **leverage**. +Uses the vocabulary in [SKILL.md](SKILL.md): **module**, **interface**, **seam**, **adapter**, **leverage**. ## Process @@ -12,33 +12,33 @@ Before spawning sub-agents, write a user-facing explanation of the problem space - The constraints any new interface would need to satisfy - The dependencies it would rely on, and which category they fall into (see [DEEPENING.md](DEEPENING.md)) -- A rough illustrative code sketch to ground the constraints — not a proposal, just a way to make the constraints concrete +- A rough illustrative code sketch to ground the constraints, not a proposal, just a way to make the constraints concrete Show this to the user, then immediately proceed to Step 2. The user reads and thinks while the sub-agents work in parallel. ### 2. Spawn sub-agents -Spawn 3+ sub-agents in parallel using the Agent tool. Each must produce a **radically different** interface for the deepened module. +Spawn 3+ sub-agents in parallel. Each must produce a **radically different** interface for the deepened module. Prompt each sub-agent with a separate technical brief (file paths, coupling details, dependency category from [DEEPENING.md](DEEPENING.md), what sits behind the seam). The brief is independent of the user-facing problem-space explanation in Step 1. Give each agent a different design constraint: -- Agent 1: "Minimize the interface — aim for 1–3 entry points max. Maximise leverage per entry point." -- Agent 2: "Maximise flexibility — support many use cases and extension." -- Agent 3: "Optimise for the most common caller — make the default case trivial." +- Agent 1: "Minimize the interface: aim for 1–3 entry points max. Maximise leverage per entry point." +- Agent 2: "Maximise flexibility: support many use cases and extension." +- Agent 3: "Optimise for the most common caller: make the default case trivial." - Agent 4 (if applicable): "Design around ports & adapters for cross-seam dependencies." -Include both [LANGUAGE.md](LANGUAGE.md) vocabulary and CONTEXT.md vocabulary in the brief so each sub-agent names things consistently with the architecture language and the project's domain language. +Include both [SKILL.md](SKILL.md) vocabulary and CONTEXT.md vocabulary in the brief so each sub-agent names things consistently with the architecture language and the project's domain language. Each sub-agent outputs: -1. Interface (types, methods, params — plus invariants, ordering, error modes) +1. Interface (types, methods, params, plus invariants, ordering, error modes) 2. Usage example showing how callers use it 3. What the implementation hides behind the seam 4. Dependency strategy and adapters (see [DEEPENING.md](DEEPENING.md)) -5. Trade-offs — where leverage is high, where it's thin +5. Trade-offs: where leverage is high, where it's thin ### 3. Present and compare Present designs sequentially so the user can absorb each one, then compare them in prose. Contrast by **depth** (leverage at the interface), **locality** (where change concentrates), and **seam placement**. -After comparing, give your own recommendation: which design you think is strongest and why. If elements from different designs would combine well, propose a hybrid. Be opinionated — the user wants a strong read, not a menu. +After comparing, give your own recommendation: which design you think is strongest and why. If elements from different designs would combine well, propose a hybrid. Be opinionated: the user wants a strong read, not a menu. diff --git a/agents/skills/codebase-design/SKILL.md b/agents/skills/codebase-design/SKILL.md new file mode 100644 index 0000000..3f63c81 --- /dev/null +++ b/agents/skills/codebase-design/SKILL.md @@ -0,0 +1,114 @@ +--- +name: codebase-design +description: Shared vocabulary for designing deep modules. Use when the user wants to design or improve a module's interface, find deepening opportunities, decide where a seam goes, make code more testable or AI-navigable, or when another skill needs the deep-module vocabulary. +--- + +# Codebase Design + +Design **deep modules**: a lot of behaviour behind a small interface, placed at a clean seam, testable through that interface. Use this language and these principles wherever code is being designed or restructured. The aim is leverage for callers, locality for maintainers, and testability for everyone. + +## Glossary + +Use these terms exactly: don't substitute "component," "service," "API," or "boundary." Consistent language is the whole point. + +**Module**: anything with an interface and an implementation. Deliberately scale-agnostic: a function, class, package, or tier-spanning slice. _Avoid_: unit, component, service. + +**Interface**: everything a caller must know to use the module correctly: the type signature, but also invariants, ordering constraints, error modes, required configuration, and performance characteristics. _Avoid_: API, signature (too narrow, they refer only to the type-level surface). + +**Implementation**: what's inside a module, its body of code. Distinct from **Adapter**: a thing can be a small adapter with a large implementation (a Postgres repo) or a large adapter with a small implementation (an in-memory fake). Reach for "adapter" when the seam is the topic; "implementation" otherwise. + +**Depth**: leverage at the interface. The amount of behaviour a caller (or test) can exercise per unit of interface they have to learn. A module is **deep** when a large amount of behaviour sits behind a small interface, **shallow** when the interface is nearly as complex as the implementation. + +**Seam** _(Michael Feathers)_: a place where you can alter behaviour without editing in that place; the *location* at which a module's interface lives. Where to put the seam is its own design decision, distinct from what goes behind it. _Avoid_: boundary (overloaded with DDD's bounded context). + +**Adapter**: a concrete thing that satisfies an interface at a seam. Describes *role* (what slot it fills), not substance (what's inside). + +**Leverage**: what callers get from depth. More capability per unit of interface they learn. One implementation pays back across N call sites and M tests. + +**Locality**: what maintainers get from depth. Change, bugs, knowledge, and verification concentrate in one place rather than spreading across callers. Fix once, fixed everywhere. + +## Deep vs shallow + +**Deep module** = small interface + lots of implementation: + +``` +┌─────────────────────┐ +│ Small Interface │ ← Few methods, simple params +├─────────────────────┤ +│ │ +│ Deep Implementation│ ← Complex logic hidden +│ │ +└─────────────────────┘ +``` + +**Shallow module** = large interface + little implementation (avoid): + +``` +┌─────────────────────────────────┐ +│ Large Interface │ ← Many methods, complex params +├─────────────────────────────────┤ +│ Thin Implementation │ ← Just passes through +└─────────────────────────────────┘ +``` + +When designing an interface, ask: + +- Can I reduce the number of methods? +- Can I simplify the parameters? +- Can I hide more complexity inside? + +## Principles + +- **Depth is a property of the interface, not the implementation.** A deep module can be internally composed of small, mockable, swappable parts; they just aren't part of the interface. A module can have **internal seams** (private to its implementation, used by its own tests) as well as the **external seam** at its interface. +- **The deletion test.** Imagine deleting the module. If complexity vanishes, it was a pass-through. If complexity reappears across N callers, it was earning its keep. +- **The interface is the test surface.** Callers and tests cross the same seam. If you want to test *past* the interface, the module is probably the wrong shape. +- **One adapter means a hypothetical seam. Two adapters means a real one.** Don't introduce a seam unless something actually varies across it. + +## Designing for testability + +Good interfaces make testing natural: + +1. **Accept dependencies, don't create them.** + + ```typescript + // Testable + function processOrder(order, paymentGateway) {} + + // Hard to test + function processOrder(order) { + const gateway = new StripeGateway(); + } + ``` + +2. **Return results, don't produce side effects.** + + ```typescript + // Testable + function calculateDiscount(cart): Discount {} + + // Hard to test + function applyDiscount(cart): void { + cart.total -= discount; + } + ``` + +3. **Small surface area.** Fewer methods = fewer tests needed. Fewer params = simpler test setup. + +## Relationships + +- A **Module** has exactly one **Interface** (the surface it presents to callers and tests). +- **Depth** is a property of a **Module**, measured against its **Interface**. +- A **Seam** is where a **Module**'s **Interface** lives. +- An **Adapter** sits at a **Seam** and satisfies the **Interface**. +- **Depth** produces **Leverage** for callers and **Locality** for maintainers. + +## Rejected framings + +- **Depth as ratio of implementation-lines to interface-lines** (Ousterhout): rewards padding the implementation. We use depth-as-leverage instead. +- **"Interface" as the TypeScript `interface` keyword or a class's public methods**: too narrow: interface here includes every fact a caller must know. +- **"Boundary"**: overloaded with DDD's bounded context. Say **seam** or **interface**. + +## Going deeper + +- **Deepening a cluster given its dependencies**, see [DEEPENING.md](DEEPENING.md): dependency categories, seam discipline, and replace-don't-layer testing. +- **Exploring alternative interfaces**, see [DESIGN-IT-TWICE.md](DESIGN-IT-TWICE.md): spin up parallel sub-agents to design the interface several radically different ways, then compare on depth, locality, and seam placement. diff --git a/agents/skills/codebase-design/agents/openai.yaml b/agents/skills/codebase-design/agents/openai.yaml new file mode 100644 index 0000000..3180715 --- /dev/null +++ b/agents/skills/codebase-design/agents/openai.yaml @@ -0,0 +1,3 @@ +interface: + display_name: "Codebase Design" + short_description: "Vocabulary for deep-module design" diff --git a/agents/skills/compress/SKILL.md b/agents/skills/compress/SKILL.md deleted file mode 100644 index 8537948..0000000 --- a/agents/skills/compress/SKILL.md +++ /dev/null @@ -1,111 +0,0 @@ ---- -name: compress -description: > - Compress natural language memory files (CLAUDE.md, todos, preferences) into caveman format - to save input tokens. Preserves all technical substance, code, URLs, and structure. - Compressed version overwrites the original file. Human-readable backup saved as FILE.original.md. - Trigger: /caveman:compress FILEPATH or "compress memory file" ---- - -# Caveman Compress - -## Purpose - -Compress natural language files (CLAUDE.md, todos, preferences) into caveman-speak to reduce input tokens. Compressed version overwrites original. Human-readable backup saved as `.original.md`. - -## Trigger - -`/caveman:compress ` or when user asks to compress a memory file. - -## Process - -1. This SKILL.md lives alongside `scripts/` in the same directory. Find that directory. - -2. Run: - -cd && python3 -m scripts - -3. The CLI will: -- detect file type (no tokens) -- call Claude to compress -- validate output (no tokens) -- if errors: cherry-pick fix with Claude (targeted fixes only, no recompression) -- retry up to 2 times -- if still failing after 2 retries: report error to user, leave original file untouched - -4. Return result to user - -## Compression Rules - -### Remove -- Articles: a, an, the -- Filler: just, really, basically, actually, simply, essentially, generally -- Pleasantries: "sure", "certainly", "of course", "happy to", "I'd recommend" -- Hedging: "it might be worth", "you could consider", "it would be good to" -- Redundant phrasing: "in order to" → "to", "make sure to" → "ensure", "the reason is because" → "because" -- Connective fluff: "however", "furthermore", "additionally", "in addition" - -### Preserve EXACTLY (never modify) -- Code blocks (fenced ``` and indented) -- Inline code (`backtick content`) -- URLs and links (full URLs, markdown links) -- File paths (`/src/components/...`, `./config.yaml`) -- Commands (`npm install`, `git commit`, `docker build`) -- Technical terms (library names, API names, protocols, algorithms) -- Proper nouns (project names, people, companies) -- Dates, version numbers, numeric values -- Environment variables (`$HOME`, `NODE_ENV`) - -### Preserve Structure -- All markdown headings (keep exact heading text, compress body below) -- Bullet point hierarchy (keep nesting level) -- Numbered lists (keep numbering) -- Tables (compress cell text, keep structure) -- Frontmatter/YAML headers in markdown files - -### Compress -- Use short synonyms: "big" not "extensive", "fix" not "implement a solution for", "use" not "utilize" -- Fragments OK: "Run tests before commit" not "You should always run tests before committing" -- Drop "you should", "make sure to", "remember to" — just state the action -- Merge redundant bullets that say the same thing differently -- Keep one example where multiple examples show the same pattern - -CRITICAL RULE: -Anything inside ``` ... ``` must be copied EXACTLY. -Do not: -- remove comments -- remove spacing -- reorder lines -- shorten commands -- simplify anything - -Inline code (`...`) must be preserved EXACTLY. -Do not modify anything inside backticks. - -If file contains code blocks: -- Treat code blocks as read-only regions -- Only compress text outside them -- Do not merge sections around code - -## Pattern - -Original: -> You should always make sure to run the test suite before pushing any changes to the main branch. This is important because it helps catch bugs early and prevents broken builds from being deployed to production. - -Compressed: -> Run tests before push to main. Catch bugs early, prevent broken prod deploys. - -Original: -> The application uses a microservices architecture with the following components. The API gateway handles all incoming requests and routes them to the appropriate service. The authentication service is responsible for managing user sessions and JWT tokens. - -Compressed: -> Microservices architecture. API gateway route all requests to services. Auth service manage user sessions + JWT tokens. - -## Boundaries - -- ONLY compress natural language files (.md, .txt, .typ, .typst, .tex, extensionless) -- NEVER modify: .py, .js, .ts, .json, .yaml, .yml, .toml, .env, .lock, .css, .html, .xml, .sql, .sh -- If file has mixed content (prose + code), compress ONLY the prose sections -- If unsure whether something is code or prose, leave it unchanged -- Original file is backed up as FILE.original.md before overwriting -- Never compress FILE.original.md (skip it) diff --git a/agents/skills/compress/scripts/__init__.py b/agents/skills/compress/scripts/__init__.py deleted file mode 100644 index 16b8c53..0000000 --- a/agents/skills/compress/scripts/__init__.py +++ /dev/null @@ -1,9 +0,0 @@ -"""Caveman compress scripts. - -This package provides tools to compress natural language markdown files -into caveman format to save input tokens. -""" - -__all__ = ["cli", "compress", "detect", "validate"] - -__version__ = "1.0.0" diff --git a/agents/skills/compress/scripts/__main__.py b/agents/skills/compress/scripts/__main__.py deleted file mode 100644 index 4e28416..0000000 --- a/agents/skills/compress/scripts/__main__.py +++ /dev/null @@ -1,3 +0,0 @@ -from .cli import main - -main() diff --git a/agents/skills/compress/scripts/benchmark.py b/agents/skills/compress/scripts/benchmark.py deleted file mode 100644 index eac927d..0000000 --- a/agents/skills/compress/scripts/benchmark.py +++ /dev/null @@ -1,78 +0,0 @@ -#!/usr/bin/env python3 -from pathlib import Path -import sys - -# Support both direct execution and module import -try: - from .validate import validate -except ImportError: - sys.path.insert(0, str(Path(__file__).parent)) - from validate import validate - -try: - import tiktoken - _enc = tiktoken.get_encoding("o200k_base") -except ImportError: - _enc = None - - -def count_tokens(text): - if _enc is None: - return len(text.split()) # fallback: word count - return len(_enc.encode(text)) - - -def benchmark_pair(orig_path: Path, comp_path: Path): - orig_text = orig_path.read_text() - comp_text = comp_path.read_text() - - orig_tokens = count_tokens(orig_text) - comp_tokens = count_tokens(comp_text) - saved = 100 * (orig_tokens - comp_tokens) / orig_tokens if orig_tokens > 0 else 0.0 - result = validate(orig_path, comp_path) - - return (comp_path.name, orig_tokens, comp_tokens, saved, result.is_valid) - - -def print_table(rows): - print("\n| File | Original | Compressed | Saved % | Valid |") - print("|------|----------|------------|---------|-------|") - for r in rows: - print(f"| {r[0]} | {r[1]} | {r[2]} | {r[3]:.1f}% | {'✅' if r[4] else '❌'} |") - - -def main(): - # Direct file pair: python3 benchmark.py original.md compressed.md - if len(sys.argv) == 3: - orig = Path(sys.argv[1]).resolve() - comp = Path(sys.argv[2]).resolve() - if not orig.exists(): - print(f"❌ Not found: {orig}") - sys.exit(1) - if not comp.exists(): - print(f"❌ Not found: {comp}") - sys.exit(1) - print_table([benchmark_pair(orig, comp)]) - return - - # Glob mode: repo_root/tests/caveman-compress/ - tests_dir = Path(__file__).parent.parent.parent / "tests" / "caveman-compress" - if not tests_dir.exists(): - print(f"❌ Tests dir not found: {tests_dir}") - sys.exit(1) - - rows = [] - for orig in sorted(tests_dir.glob("*.original.md")): - comp = orig.with_name(orig.stem.removesuffix(".original") + ".md") - if comp.exists(): - rows.append(benchmark_pair(orig, comp)) - - if not rows: - print("No compressed file pairs found.") - return - - print_table(rows) - - -if __name__ == "__main__": - main() diff --git a/agents/skills/compress/scripts/cli.py b/agents/skills/compress/scripts/cli.py deleted file mode 100644 index c314f87..0000000 --- a/agents/skills/compress/scripts/cli.py +++ /dev/null @@ -1,85 +0,0 @@ -#!/usr/bin/env python3 -""" -Caveman Compress CLI - -Usage: - caveman -""" - -import sys - -# Force UTF-8 on stdout/stderr before any code can print. Windows consoles -# default to cp1252 and crash on the ❌ glyphs in error/validation branches, -# masking the real error and leaving the user with a half-compressed file. -for _stream in (sys.stdout, sys.stderr): - reconfigure = getattr(_stream, "reconfigure", None) - if callable(reconfigure): - try: - reconfigure(encoding="utf-8", errors="replace") - except Exception: - pass - -from pathlib import Path - -from .compress import compress_file -from .detect import detect_file_type, should_compress - - -def print_usage(): - print("Usage: caveman ") - - -def main(): - if len(sys.argv) != 2: - print_usage() - sys.exit(1) - - filepath = Path(sys.argv[1]) - - # Check file exists - if not filepath.exists(): - print(f"❌ File not found: {filepath}") - sys.exit(1) - - if not filepath.is_file(): - print(f"❌ Not a file: {filepath}") - sys.exit(1) - - filepath = filepath.resolve() - - # Detect file type - file_type = detect_file_type(filepath) - - print(f"Detected: {file_type}") - - # Check if compressible - if not should_compress(filepath): - print("Skipping: file is not natural language (code/config)") - sys.exit(0) - - print("Starting caveman compression...\n") - - try: - success = compress_file(filepath) - - if success: - print("\nCompression completed successfully") - backup_path = filepath.with_name(filepath.stem + ".original.md") - print(f"Compressed: {filepath}") - print(f"Original: {backup_path}") - sys.exit(0) - else: - print("\n❌ Compression failed after retries") - sys.exit(2) - - except KeyboardInterrupt: - print("\nInterrupted by user") - sys.exit(130) - - except Exception as e: - print(f"\n❌ Error: {e}") - sys.exit(1) - - -if __name__ == "__main__": - main() diff --git a/agents/skills/compress/scripts/compress.py b/agents/skills/compress/scripts/compress.py deleted file mode 100644 index 7adc4fb..0000000 --- a/agents/skills/compress/scripts/compress.py +++ /dev/null @@ -1,254 +0,0 @@ -#!/usr/bin/env python3 -""" -Caveman Memory Compression Orchestrator - -Usage: - python scripts/compress.py -""" - -import os -import re -import subprocess -from pathlib import Path -from typing import List - -OUTER_FENCE_REGEX = re.compile( - r"\A\s*(`{3,}|~{3,})[^\n]*\n(.*)\n\1\s*\Z", re.DOTALL -) - -# Filenames and paths that almost certainly hold secrets or PII. Compressing -# them ships raw bytes to the Anthropic API — a third-party data boundary that -# developers on sensitive codebases cannot cross. detect.py already skips .env -# by extension, but credentials.md / secrets.txt / ~/.aws/credentials would -# slip through the natural-language filter. This is a hard refuse before read. -SENSITIVE_BASENAME_REGEX = re.compile( - r"(?ix)^(" - r"\.env(\..+)?" - r"|\.netrc" - r"|credentials(\..+)?" - r"|secrets?(\..+)?" - r"|passwords?(\..+)?" - r"|id_(rsa|dsa|ecdsa|ed25519)(\.pub)?" - r"|authorized_keys" - r"|known_hosts" - r"|.*\.(pem|key|p12|pfx|crt|cer|jks|keystore|asc|gpg)" - r")$" -) - -SENSITIVE_PATH_COMPONENTS = frozenset({".ssh", ".aws", ".gnupg", ".kube", ".docker"}) - -SENSITIVE_NAME_TOKENS = ( - "secret", "credential", "password", "passwd", - "apikey", "accesskey", "token", "privatekey", -) - - -def is_sensitive_path(filepath: Path) -> bool: - """Heuristic denylist for files that must never be shipped to a third-party API.""" - name = filepath.name - if SENSITIVE_BASENAME_REGEX.match(name): - return True - lowered_parts = {p.lower() for p in filepath.parts} - if lowered_parts & SENSITIVE_PATH_COMPONENTS: - return True - # Normalize separators so "api-key" and "api_key" both match "apikey". - lower = re.sub(r"[_\-\s.]", "", name.lower()) - return any(tok in lower for tok in SENSITIVE_NAME_TOKENS) - - -def strip_llm_wrapper(text: str) -> str: - """Strip outer ```markdown ... ``` fence when it wraps the entire output.""" - m = OUTER_FENCE_REGEX.match(text) - if m: - return m.group(2) - return text - -from .detect import should_compress -from .validate import validate - -MAX_RETRIES = 2 - - -# ---------- Claude Calls ---------- - - -def call_claude(prompt: str) -> str: - api_key = os.environ.get("ANTHROPIC_API_KEY") - if api_key: - try: - import anthropic - - client = anthropic.Anthropic(api_key=api_key) - msg = client.messages.create( - model=os.environ.get("CAVEMAN_MODEL", "claude-sonnet-4-5"), - max_tokens=8192, - messages=[{"role": "user", "content": prompt}], - ) - return strip_llm_wrapper(msg.content[0].text.strip()) - except ImportError: - pass # anthropic not installed, fall back to CLI - # Fallback: use claude CLI (handles desktop auth) - try: - result = subprocess.run( - ["claude", "--print"], - input=prompt, - text=True, - capture_output=True, - check=True, - ) - return strip_llm_wrapper(result.stdout.strip()) - except subprocess.CalledProcessError as e: - raise RuntimeError(f"Claude call failed:\n{e.stderr}") - - -def build_compress_prompt(original: str) -> str: - return f""" -Compress this markdown into caveman format. - -STRICT RULES: -- Do NOT modify anything inside ``` code blocks -- Do NOT modify anything inside inline backticks -- Preserve ALL URLs exactly -- Preserve ALL headings exactly -- Preserve file paths and commands -- Return ONLY the compressed markdown body — do NOT wrap the entire output in a ```markdown fence or any other fence. Inner code blocks from the original stay as-is; do not add a new outer fence around the whole file. - -Only compress natural language. - -TEXT: -{original} -""" - - -def build_fix_prompt(original: str, compressed: str, errors: List[str]) -> str: - errors_str = "\n".join(f"- {e}" for e in errors) - return f"""You are fixing a caveman-compressed markdown file. Specific validation errors were found. - -CRITICAL RULES: -- DO NOT recompress or rephrase the file -- ONLY fix the listed errors — leave everything else exactly as-is -- The ORIGINAL is provided as reference only (to restore missing content) -- Preserve caveman style in all untouched sections - -ERRORS TO FIX: -{errors_str} - -HOW TO FIX: -- Missing URL: find it in ORIGINAL, restore it exactly where it belongs in COMPRESSED -- Code block mismatch: find the exact code block in ORIGINAL, restore it in COMPRESSED -- Heading mismatch: restore the exact heading text from ORIGINAL into COMPRESSED -- Do not touch any section not mentioned in the errors - -ORIGINAL (reference only): -{original} - -COMPRESSED (fix this): -{compressed} - -Return ONLY the fixed compressed file. No explanation. -""" - - -# ---------- Core Logic ---------- - - -def compress_file(filepath: Path) -> bool: - # Resolve and validate path - filepath = filepath.resolve() - MAX_FILE_SIZE = 500_000 # 500KB - if not filepath.exists(): - raise FileNotFoundError(f"File not found: {filepath}") - if filepath.stat().st_size > MAX_FILE_SIZE: - raise ValueError(f"File too large to compress safely (max 500KB): {filepath}") - - # Refuse files that look like they contain secrets or PII. Compressing ships - # the raw bytes to the Anthropic API — a third-party boundary — so we fail - # loudly rather than silently exfiltrate credentials or keys. Override is - # intentional: the user must rename the file if the heuristic is wrong. - if is_sensitive_path(filepath): - raise ValueError( - f"Refusing to compress {filepath}: filename looks sensitive " - "(credentials, keys, secrets, or known private paths). " - "Compression sends file contents to the Anthropic API. " - "Rename the file if this is a false positive." - ) - - print(f"Processing: {filepath}") - - if not should_compress(filepath): - print("Skipping (not natural language)") - return False - - original_text = filepath.read_text(errors="ignore") - backup_path = filepath.with_name(filepath.stem + ".original.md") - - if not original_text.strip(): - print("❌ Refusing to compress: file is empty or whitespace-only.") - return False - - # Check if backup already exists to prevent accidental overwriting - if backup_path.exists(): - print(f"⚠️ Backup file already exists: {backup_path}") - print("The original backup may contain important content.") - print("Aborting to prevent data loss. Please remove or rename the backup file if you want to proceed.") - return False - - # Step 1: Compress - print("Compressing with Claude...") - compressed = call_claude(build_compress_prompt(original_text)) - - if compressed is None or not compressed.strip(): - print("❌ Compression aborted: Claude returned an empty response.") - print(" Original file is untouched (no backup created).") - return False - - if compressed.strip() == original_text.strip(): - print("❌ Compression aborted: output is identical to input.") - print(" Likely causes: Claude refused, returned the prompt verbatim, or the file is") - print(" already in caveman form. Original file is untouched (no backup created).") - return False - - # Save original as backup, then verify the backup readback before - # touching the input file. If the filesystem dropped bytes (encoding, - # antivirus, disk full), unlink the bad backup and abort instead of - # leaving the user with a corrupt backup + compressed primary. - backup_path.write_text(original_text) - backup_readback = backup_path.read_text(errors="ignore") - if backup_readback != original_text: - print(f"❌ Backup write verification failed: {backup_path}") - print(" In-memory original differs from on-disk backup. Aborting before touching the input file.") - try: - backup_path.unlink() - except OSError: - pass - return False - filepath.write_text(compressed) - - # Step 2: Validate + Retry - for attempt in range(MAX_RETRIES): - print(f"\nValidation attempt {attempt + 1}") - - result = validate(backup_path, filepath) - - if result.is_valid: - print("Validation passed") - break - - print("❌ Validation failed:") - for err in result.errors: - print(f" - {err}") - - if attempt == MAX_RETRIES - 1: - # Restore original on failure - filepath.write_text(original_text) - backup_path.unlink(missing_ok=True) - print("❌ Failed after retries — original restored") - return False - - print("Fixing with Claude...") - compressed = call_claude( - build_fix_prompt(original_text, compressed, result.errors) - ) - filepath.write_text(compressed) - - return True diff --git a/agents/skills/compress/scripts/detect.py b/agents/skills/compress/scripts/detect.py deleted file mode 100644 index 8d5f6d7..0000000 --- a/agents/skills/compress/scripts/detect.py +++ /dev/null @@ -1,121 +0,0 @@ -#!/usr/bin/env python3 -"""Detect whether a file is natural language (compressible) or code/config (skip).""" - -import json -import re -from pathlib import Path - -# Extensions that are natural language and compressible -COMPRESSIBLE_EXTENSIONS = {".md", ".txt", ".markdown", ".rst", ".typ", ".typst", ".tex"} - -# Extensions that are code/config and should be skipped -SKIP_EXTENSIONS = { - ".py", ".js", ".ts", ".tsx", ".jsx", ".json", ".yaml", ".yml", - ".toml", ".env", ".lock", ".css", ".scss", ".html", ".xml", - ".sql", ".sh", ".bash", ".zsh", ".go", ".rs", ".java", ".c", - ".cpp", ".h", ".hpp", ".rb", ".php", ".swift", ".kt", ".lua", - ".dockerfile", ".makefile", ".csv", ".ini", ".cfg", -} - -# Patterns that indicate a line is code -CODE_PATTERNS = [ - re.compile(r"^\s*(import |from .+ import |require\(|const |let |var )"), - re.compile(r"^\s*(def |class |function |async function |export )"), - re.compile(r"^\s*(if\s*\(|for\s*\(|while\s*\(|switch\s*\(|try\s*\{)"), - re.compile(r"^\s*[\}\]\);]+\s*$"), # closing braces/brackets - re.compile(r"^\s*@\w+"), # decorators/annotations - re.compile(r'^\s*"[^"]+"\s*:\s*'), # JSON-like key-value - re.compile(r"^\s*\w+\s*=\s*[{\[\(\"']"), # assignment with literal -] - - -def _is_code_line(line: str) -> bool: - """Check if a line looks like code.""" - return any(p.match(line) for p in CODE_PATTERNS) - - -def _is_json_content(text: str) -> bool: - """Check if content is valid JSON.""" - try: - json.loads(text) - return True - except (json.JSONDecodeError, ValueError): - return False - - -def _is_yaml_content(lines: list[str]) -> bool: - """Heuristic: check if content looks like YAML.""" - yaml_indicators = 0 - for line in lines[:30]: - stripped = line.strip() - if stripped.startswith("---"): - yaml_indicators += 1 - elif re.match(r"^\w[\w\s]*:\s", stripped): - yaml_indicators += 1 - elif stripped.startswith("- ") and ":" in stripped: - yaml_indicators += 1 - # If most non-empty lines look like YAML - non_empty = sum(1 for l in lines[:30] if l.strip()) - return non_empty > 0 and yaml_indicators / non_empty > 0.6 - - -def detect_file_type(filepath: Path) -> str: - """Classify a file as 'natural_language', 'code', 'config', or 'unknown'. - - Returns: - One of: 'natural_language', 'code', 'config', 'unknown' - """ - ext = filepath.suffix.lower() - - # Extension-based classification - if ext in COMPRESSIBLE_EXTENSIONS: - return "natural_language" - if ext in SKIP_EXTENSIONS: - return "code" if ext not in {".json", ".yaml", ".yml", ".toml", ".ini", ".cfg", ".env"} else "config" - - # Extensionless files (like CLAUDE.md, TODO) — check content - if not ext: - try: - text = filepath.read_text(errors="ignore") - except (OSError, PermissionError): - return "unknown" - - lines = text.splitlines()[:50] - - if _is_json_content(text[:10000]): - return "config" - if _is_yaml_content(lines): - return "config" - - code_lines = sum(1 for l in lines if l.strip() and _is_code_line(l)) - non_empty = sum(1 for l in lines if l.strip()) - if non_empty > 0 and code_lines / non_empty > 0.4: - return "code" - - return "natural_language" - - return "unknown" - - -def should_compress(filepath: Path) -> bool: - """Return True if the file is natural language and should be compressed.""" - if not filepath.is_file(): - return False - # Skip backup files - if filepath.name.endswith(".original.md"): - return False - return detect_file_type(filepath) == "natural_language" - - -if __name__ == "__main__": - import sys - - if len(sys.argv) < 2: - print("Usage: python detect.py [file2] ...") - sys.exit(1) - - for path_str in sys.argv[1:]: - p = Path(path_str).resolve() - file_type = detect_file_type(p) - compress = should_compress(p) - print(f" {p.name:30s} type={file_type:20s} compress={compress}") diff --git a/agents/skills/compress/scripts/validate.py b/agents/skills/compress/scripts/validate.py deleted file mode 100644 index dc07307..0000000 --- a/agents/skills/compress/scripts/validate.py +++ /dev/null @@ -1,213 +0,0 @@ -#!/usr/bin/env python3 -import re -from collections import Counter -from pathlib import Path - -URL_REGEX = re.compile(r"https?://[^\s)]+") -FENCE_OPEN_REGEX = re.compile(r"^(\s{0,3})(`{3,}|~{3,})(.*)$") -HEADING_REGEX = re.compile(r"^(#{1,6})\s+(.*)", re.MULTILINE) -BULLET_REGEX = re.compile(r"^\s*[-*+]\s+", re.MULTILINE) - -# crude but effective path detection -# Requires either a path prefix (./ ../ / or drive letter) or a slash/backslash within the match -PATH_REGEX = re.compile(r"(?:\./|\.\./|/|[A-Za-z]:\\)[\w\-/\\\.]+|[\w\-\.]+[/\\][\w\-/\\\.]+") - - -class ValidationResult: - def __init__(self): - self.is_valid = True - self.errors = [] - self.warnings = [] - - def add_error(self, msg): - self.is_valid = False - self.errors.append(msg) - - def add_warning(self, msg): - self.warnings.append(msg) - - -def read_file(path: Path) -> str: - return path.read_text(errors="ignore") - - -# ---------- Extractors ---------- - - -def extract_headings(text): - return [(level, title.strip()) for level, title in HEADING_REGEX.findall(text)] - - -def extract_code_blocks(text): - """Line-based fenced code block extractor. - - Handles ``` and ~~~ fences with variable length (CommonMark: closing - fence must use same char and be at least as long as opening). Supports - nested fences (e.g. an outer 4-backtick block wrapping inner 3-backtick - content). - """ - blocks = [] - lines = text.split("\n") - i = 0 - n = len(lines) - while i < n: - m = FENCE_OPEN_REGEX.match(lines[i]) - if not m: - i += 1 - continue - fence_char = m.group(2)[0] - fence_len = len(m.group(2)) - open_line = lines[i] - block_lines = [open_line] - i += 1 - closed = False - while i < n: - close_m = FENCE_OPEN_REGEX.match(lines[i]) - if ( - close_m - and close_m.group(2)[0] == fence_char - and len(close_m.group(2)) >= fence_len - and close_m.group(3).strip() == "" - ): - block_lines.append(lines[i]) - closed = True - i += 1 - break - block_lines.append(lines[i]) - i += 1 - if closed: - blocks.append("\n".join(block_lines)) - # Unclosed fences are silently skipped — they indicate malformed markdown - # and including them would cause false-positive validation failures. - return blocks - - -def extract_urls(text): - return set(URL_REGEX.findall(text)) - - -def extract_paths(text): - return set(PATH_REGEX.findall(text)) - - -def count_bullets(text): - return len(BULLET_REGEX.findall(text)) - - -def extract_inline_codes(text): - text_without_fences = re.sub(r"^```[\s\S]*?^```", "", text, flags=re.MULTILINE) - text_without_fences = re.sub(r"^~~~[\s\S]*?^~~~", "", text_without_fences, flags=re.MULTILINE) - return re.findall(r"`([^`]+)`", text_without_fences) - - -# ---------- Validators ---------- - - -def validate_headings(orig, comp, result): - h1 = extract_headings(orig) - h2 = extract_headings(comp) - - if len(h1) != len(h2): - result.add_error(f"Heading count mismatch: {len(h1)} vs {len(h2)}") - - if h1 != h2: - result.add_warning("Heading text/order changed") - - -def validate_code_blocks(orig, comp, result): - c1 = extract_code_blocks(orig) - c2 = extract_code_blocks(comp) - - if c1 != c2: - result.add_error("Code blocks not preserved exactly") - - -def validate_urls(orig, comp, result): - u1 = extract_urls(orig) - u2 = extract_urls(comp) - - if u1 != u2: - result.add_error(f"URL mismatch: lost={u1 - u2}, added={u2 - u1}") - - -def validate_paths(orig, comp, result): - p1 = extract_paths(orig) - p2 = extract_paths(comp) - - if p1 != p2: - result.add_warning(f"Path mismatch: lost={p1 - p2}, added={p2 - p1}") - - -def validate_bullets(orig, comp, result): - b1 = count_bullets(orig) - b2 = count_bullets(comp) - - if b1 == 0: - return - - diff = abs(b1 - b2) / b1 - - if diff > 0.15: - result.add_warning(f"Bullet count changed too much: {b1} -> {b2}") - - -def validate_inline_codes(orig, comp, result): - c1 = Counter(extract_inline_codes(orig)) - c2 = Counter(extract_inline_codes(comp)) - - if c1 != c2: - lost = set(c1.keys()) - set(c2.keys()) - added = set(c2.keys()) - set(c1.keys()) - for code, count in c1.items(): - if code in c2 and c2[code] < count: - lost.add(f"{code} (lost {count - c2[code]} of {count} occurrences)") - if lost: - result.add_error(f"Inline code lost: {lost}") - if added: - result.add_warning(f"Inline code added: {added}") - - -# ---------- Main ---------- - - -def validate(original_path: Path, compressed_path: Path) -> ValidationResult: - result = ValidationResult() - - orig = read_file(original_path) - comp = read_file(compressed_path) - - validate_headings(orig, comp, result) - validate_code_blocks(orig, comp, result) - validate_urls(orig, comp, result) - validate_paths(orig, comp, result) - validate_bullets(orig, comp, result) - validate_inline_codes(orig, comp, result) - - return result - - -# ---------- CLI ---------- - -if __name__ == "__main__": - import sys - - if len(sys.argv) != 3: - print("Usage: python validate.py ") - sys.exit(1) - - orig = Path(sys.argv[1]).resolve() - comp = Path(sys.argv[2]).resolve() - - res = validate(orig, comp) - - print(f"\nValid: {res.is_valid}") - - if res.errors: - print("\nErrors:") - for e in res.errors: - print(f" - {e}") - - if res.warnings: - print("\nWarnings:") - for w in res.warnings: - print(f" - {w}") diff --git a/agents/skills/continual-learning/SKILL.md b/agents/skills/continual-learning/SKILL.md new file mode 100644 index 0000000..f1beb5c --- /dev/null +++ b/agents/skills/continual-learning/SKILL.md @@ -0,0 +1,24 @@ +--- +name: continual-learning +description: Orchestrate continual learning by delegating transcript mining and AGENTS.md updates to `agents-memory-updater`. +disable-model-invocation: true +--- + +# Continual Learning + +Keep `AGENTS.md` current by delegating the memory update flow to one subagent. + +## Trigger + +Use when the user asks to mine prior chats, maintain `AGENTS.md`, or run the continual-learning loop. + +## Workflow + +1. Call `agents-memory-updater`. +2. Return the updater result. + +## Guardrails + +- Keep the parent skill orchestration-only. +- Do not mine transcripts or edit files in the parent flow. +- Do not bypass the subagent. diff --git a/agents/skills/deslop/SKILL.md b/agents/skills/deslop/SKILL.md new file mode 100644 index 0000000..1b3827c --- /dev/null +++ b/agents/skills/deslop/SKILL.md @@ -0,0 +1,22 @@ +--- +name: deslop +description: Remove AI-generated code slop and clean up code style +--- + +# Remove AI code slop + +Check the diff against main and remove AI-generated slop introduced in the branch. + +## Focus Areas + +- Extra comments that are unnecessary or inconsistent with local style +- Defensive checks or try/catch blocks that are abnormal for trusted code paths +- Casts to `any` used only to bypass type issues +- Deeply nested code that should be simplified with early returns +- Other patterns inconsistent with the file and surrounding codebase + +## Guardrails + +- Keep behavior unchanged unless fixing a clear bug. +- Prefer minimal, focused edits over broad rewrites. +- Keep the final summary concise (1-3 sentences). diff --git a/agents/skills/diagnose/SKILL.md b/agents/skills/diagnosing-bugs/SKILL.md similarity index 52% rename from agents/skills/diagnose/SKILL.md rename to agents/skills/diagnosing-bugs/SKILL.md index ed55bda..061c25a 100644 --- a/agents/skills/diagnose/SKILL.md +++ b/agents/skills/diagnosing-bugs/SKILL.md @@ -1,26 +1,32 @@ --- -name: diagnose -description: Disciplined diagnosis loop for hard bugs and performance regressions. Reproduce → minimise → hypothesise → instrument → fix → regression-test. Use when user says "diagnose this" / "debug this", reports a bug, says something is broken/throwing/failing, or describes a performance regression. +name: diagnosing-bugs +description: Diagnosis loop for hard bugs and performance regressions. Use when the user says "diagnose"/"debug this", or reports something broken/throwing/failing/slow. --- -# Diagnose +# Diagnosing Bugs A discipline for hard bugs. Skip phases only when explicitly justified. -When exploring the codebase, use the project's domain glossary to get a clear mental model of the relevant modules, and check ADRs in the area you're touching. +When exploring the codebase, read `CONTEXT.md` (if it exists) to get a clear mental model of the relevant modules, and check ADRs in the area you're touching. -## Phase 1 — Build a feedback loop +## Redact -**This is the skill.** Everything else is mechanical. If you have a fast, deterministic, agent-runnable pass/fail signal for the bug, you will find the cause — bisection, hypothesis-testing, and instrumentation all just consume that signal. If you don't have one, no amount of staring at code will save you. +This skill has you show commands, outputs and captured artifacts. **Redact every secret first**: write `` in its place. Build loops against env vars, so the credential stays in the environment rather than in what you show. Captured artifacts carry auth headers: quote only the lines that carry the signal. + +If the redacted output is not enough to diagnose the bug, say so and ask the user. + +## Phase 1: Build a feedback loop + +**This is the skill.** Everything else is mechanical. If you have a **tight** pass/fail signal for the bug (one that goes red on _this_ bug), you will find the cause; bisection, hypothesis-testing, and instrumentation all just consume it. If you don't have one, no amount of staring at code will save you. Spend disproportionate effort here. **Be aggressive. Be creative. Refuse to give up.** -### Ways to construct one — try them in roughly this order +### Ways to construct one, in roughly this order -1. **Failing test** at whatever seam reaches the bug — unit, integration, e2e. +1. **Failing test** at whatever seam reaches the bug: unit, integration, e2e. 2. **Curl / HTTP script** against a running dev server. 3. **CLI invocation** with a fixture input, diffing stdout against a known-good snapshot. -4. **Headless browser script** (Playwright / Puppeteer) — drives the UI, asserts on DOM/console/network. +4. **Headless browser script** (Playwright / Puppeteer) that drives the UI and asserts on DOM/console/network. 5. **Replay a captured trace.** Save a real network request / payload / event log to disk; replay it through the code path in isolation. 6. **Throwaway harness.** Spin up a minimal subset of the system (one service, mocked deps) that exercises the bug code path with a single function call. 7. **Property / fuzz loop.** If the bug is "sometimes wrong output", run 1000 random inputs and look for the failure mode. @@ -30,39 +36,56 @@ Spend disproportionate effort here. **Be aggressive. Be creative. Refuse to give Build the right feedback loop, and the bug is 90% fixed. -### Iterate on the loop itself +### Tighten the loop -Treat the loop as a product. Once you have _a_ loop, ask: +Treat the loop as a product. Once you have _a_ loop, **tighten** it: - Can I make it faster? (Cache setup, skip unrelated init, narrow the test scope.) - Can I make the signal sharper? (Assert on the specific symptom, not "didn't crash".) - Can I make it more deterministic? (Pin time, seed RNG, isolate filesystem, freeze network.) -A 30-second flaky loop is barely better than no loop. A 2-second deterministic loop is a debugging superpower. +A 30-second flaky loop is barely better than no loop; a 2-second deterministic one is tight, a debugging superpower. ### Non-deterministic bugs -The goal is not a clean repro but a **higher reproduction rate**. Loop the trigger 100×, parallelise, add stress, narrow timing windows, inject sleeps. A 50%-flake bug is debuggable; 1% is not — keep raising the rate until it's debuggable. +The goal is not a clean repro but a **higher reproduction rate**. Loop the trigger 100×, parallelise, add stress, narrow timing windows, inject sleeps. A 50%-flake bug is debuggable; 1% is not, so keep raising the rate until it's debuggable. ### When you genuinely cannot build a loop -Stop and say so explicitly. List what you tried. Ask the user for: (a) access to whatever environment reproduces it, (b) a captured artifact (HAR file, log dump, core dump, screen recording with timestamps), or (c) permission to add temporary production instrumentation. Do **not** proceed to hypothesise without a loop. +Stop and say so explicitly. List what you tried. Ask the user for: (a) access to whatever environment reproduces it, (b) a redacted captured artifact (HAR file, log dump, core dump, screen recording with timestamps), or (c) permission to add temporary production instrumentation. Do **not** proceed to hypothesise without a loop. -Do not proceed to Phase 2 until you have a loop you believe in. +### Completion criterion: a tight loop that goes red -## Phase 2 — Reproduce +Phase 1 is done when the loop is **tight** and **red-capable**: you can name **one command** (a script path, a test invocation, a curl) that you have **already run at least once** (show the invocation and its output, redacted), and that is: -Run the loop. Watch the bug appear. +- [ ] **Red-capable**: it drives the actual bug code path and asserts the **user's exact symptom**, so it can go red on this bug and green once fixed. Not "runs without erroring"; it must be able to _catch this specific bug_. +- [ ] **Deterministic**: same verdict every run (flaky bugs: a pinned, high reproduction rate, per above). +- [ ] **Fast**: seconds, not minutes. +- [ ] **Agent-runnable**: you can run it unattended; a human in the loop only via `scripts/hitl-loop.template.sh`. + +If you catch yourself reading code to build a theory before this command exists, **stop: jumping straight to a hypothesis is the exact failure this skill prevents.** No red-capable command, no Phase 2. + +## Phase 2: Reproduce + minimise + +Run the loop. Watch it go red as the bug appears. Confirm: -- [ ] The loop produces the failure mode the **user** described — not a different failure that happens to be nearby. Wrong bug = wrong fix. +- [ ] The loop produces the failure mode the **user** described, not a different failure that happens to be nearby. Wrong bug = wrong fix. - [ ] The failure is reproducible across multiple runs (or, for non-deterministic bugs, reproducible at a high enough rate to debug against). - [ ] You have captured the exact symptom (error message, wrong output, slow timing) so later phases can verify the fix actually addresses it. -Do not proceed until you reproduce the bug. +### Minimise -## Phase 3 — Hypothesise +Once it's red, shrink the repro to the **smallest scenario that still goes red**. Cut inputs, callers, config, data, and steps **one at a time**, re-running the loop after each cut, and keep only what's load-bearing for the failure. + +Why bother: a minimal repro shrinks the hypothesis space in Phase 3 (fewer moving parts left to suspect) and becomes the clean regression test in Phase 5. + +Done when **every remaining element is load-bearing**: removing any one of them makes the loop go green. + +Do not proceed until you have reproduced **and** minimised. + +## Phase 3: Hypothesise Generate **3–5 ranked hypotheses** before testing any of them. Single-hypothesis generation anchors on the first plausible idea. @@ -70,11 +93,11 @@ Each hypothesis must be **falsifiable**: state the prediction it makes. > Format: "If is the cause, then will make the bug disappear / will make it worse." -If you cannot state the prediction, the hypothesis is a vibe — discard or sharpen it. +If you cannot state the prediction, the hypothesis is a vibe: discard or sharpen it. -**Show the ranked list to the user before testing.** They often have domain knowledge that re-ranks instantly ("we just deployed a change to #3"), or know hypotheses they've already ruled out. Cheap checkpoint, big time saver. Don't block on it — proceed with your ranking if the user is AFK. +**Show the ranked list to the user before testing.** They often have domain knowledge that re-ranks instantly ("we just deployed a change to #3"), or know hypotheses they've already ruled out. Cheap checkpoint, big time saver. Don't block on it; proceed with your ranking if the user is AFK. -## Phase 4 — Instrument +## Phase 4: Instrument Each probe must map to a specific prediction from Phase 3. **Change one variable at a time.** @@ -88,9 +111,9 @@ Tool preference: **Perf branch.** For performance regressions, logs are usually wrong. Instead: establish a baseline measurement (timing harness, `performance.now()`, profiler, query plan), then bisect. Measure first, fix second. -## Phase 5 — Fix + regression test +## Phase 5: Fix + regression test -Write the regression test **before the fix** — but only if there is a **correct seam** for it. +Write the regression test **before the fix**, but only if there is a **correct seam** for it. A correct seam is one where the test exercises the **real bug pattern** as it occurs at the call site. If the only available seam is too shallow (single-caller test when the bug needs multiple callers, unit test that can't replicate the chain that triggered the bug), a regression test there gives false confidence. @@ -104,7 +127,7 @@ If a correct seam exists: 4. Watch it pass. 5. Re-run the Phase 1 feedback loop against the original (un-minimised) scenario. -## Phase 6 — Cleanup + post-mortem +## Phase 6: Cleanup Required before declaring done: @@ -112,6 +135,4 @@ Required before declaring done: - [ ] Regression test passes (or absence of seam is documented) - [ ] All `[DEBUG-...]` instrumentation removed (`grep` the prefix) - [ ] Throwaway prototypes deleted (or moved to a clearly-marked debug location) -- [ ] The hypothesis that turned out correct is stated in the commit / PR message — so the next debugger learns - -**Then ask: what would have prevented this bug?** If the answer involves architectural change (no good test seam, tangled callers, hidden coupling) hand off to the `/improve-codebase-architecture` skill with the specifics. Make the recommendation **after** the fix is in, not before — you have more information now than when you started. +- [ ] The hypothesis that turned out correct is stated in the commit / PR message, so the next debugger learns diff --git a/agents/skills/diagnosing-bugs/agents/openai.yaml b/agents/skills/diagnosing-bugs/agents/openai.yaml new file mode 100644 index 0000000..a13a755 --- /dev/null +++ b/agents/skills/diagnosing-bugs/agents/openai.yaml @@ -0,0 +1,3 @@ +interface: + display_name: "Diagnosing Bugs" + short_description: "Diagnose hard bugs and regressions" diff --git a/agents/skills/diagnose/scripts/hitl-loop.template.sh b/agents/skills/diagnosing-bugs/scripts/hitl-loop.template.sh similarity index 88% rename from agents/skills/diagnose/scripts/hitl-loop.template.sh rename to agents/skills/diagnosing-bugs/scripts/hitl-loop.template.sh index 40afc46..2431984 100644 --- a/agents/skills/diagnose/scripts/hitl-loop.template.sh +++ b/agents/skills/diagnosing-bugs/scripts/hitl-loop.template.sh @@ -11,6 +11,9 @@ # capture VAR "" → show question, read response into VAR # # At the end, captured values are printed as KEY=VALUE for the agent to parse. +# +# `capture` prints its value back to the terminal, where the agent reads it, +# so capture observations, and leave signing in to the user as a `step`. set -euo pipefail diff --git a/agents/skills/grill-with-docs/ADR-FORMAT.md b/agents/skills/domain-modeling/ADR-FORMAT.md similarity index 59% rename from agents/skills/grill-with-docs/ADR-FORMAT.md rename to agents/skills/domain-modeling/ADR-FORMAT.md index da7e78e..d7e61f3 100644 --- a/agents/skills/grill-with-docs/ADR-FORMAT.md +++ b/agents/skills/domain-modeling/ADR-FORMAT.md @@ -2,7 +2,7 @@ ADRs live in `docs/adr/` and use sequential numbering: `0001-slug.md`, `0002-slug.md`, etc. -Create the `docs/adr/` directory lazily — only when the first ADR is needed. +Create the `docs/adr/` directory lazily: only when the first ADR is needed. ## Template @@ -12,15 +12,15 @@ Create the `docs/adr/` directory lazily — only when the first ADR is needed. {1-3 sentences: what's the context, what did we decide, and why.} ``` -That's it. An ADR can be a single paragraph. The value is in recording *that* a decision was made and *why* — not in filling out sections. +That's it. An ADR can be a single paragraph. The value is in recording *that* a decision was made and *why*, not in filling out sections. ## Optional sections Only include these when they add genuine value. Most ADRs won't need them. -- **Status** frontmatter (`proposed | accepted | deprecated | superseded by ADR-NNNN`) — useful when decisions are revisited -- **Considered Options** — only when the rejected alternatives are worth remembering -- **Consequences** — only when non-obvious downstream effects need to be called out +- **Status** frontmatter (`proposed | accepted | deprecated | superseded by ADR-NNNN`): useful when decisions are revisited +- **Considered Options**: only when the rejected alternatives are worth remembering +- **Consequences**: only when non-obvious downstream effects need to be called out ## Numbering @@ -30,18 +30,18 @@ Scan `docs/adr/` for the highest existing number and increment by one. All three of these must be true: -1. **Hard to reverse** — the cost of changing your mind later is meaningful -2. **Surprising without context** — a future reader will look at the code and wonder "why on earth did they do it this way?" -3. **The result of a real trade-off** — there were genuine alternatives and you picked one for specific reasons +1. **Hard to reverse**: the cost of changing your mind later is meaningful +2. **Surprising without context**: a future reader will look at the code and wonder "why on earth did they do it this way?" +3. **The result of a real trade-off**: there were genuine alternatives and you picked one for specific reasons -If a decision is easy to reverse, skip it — you'll just reverse it. If it's not surprising, nobody will wonder why. If there was no real alternative, there's nothing to record beyond "we did the obvious thing." +If a decision is easy to reverse, skip it: you'll just reverse it. If it's not surprising, nobody will wonder why. If there was no real alternative, there's nothing to record beyond "we did the obvious thing." ### What qualifies - **Architectural shape.** "We're using a monorepo." "The write model is event-sourced, the read model is projected into Postgres." - **Integration patterns between contexts.** "Ordering and Billing communicate via domain events, not synchronous HTTP." -- **Technology choices that carry lock-in.** Database, message bus, auth provider, deployment target. Not every library — just the ones that would take a quarter to swap out. +- **Technology choices that carry lock-in.** Database, message bus, auth provider, deployment target. Not every library: just the ones that would take a quarter to swap out. - **Boundary and scope decisions.** "Customer data is owned by the Customer context; other contexts reference it by ID only." The explicit no-s are as valuable as the yes-s. - **Deliberate deviations from the obvious path.** "We're using manual SQL instead of an ORM because X." Anything where a reasonable reader would assume the opposite. These stop the next engineer from "fixing" something that was deliberate. - **Constraints not visible in the code.** "We can't use AWS because of compliance requirements." "Response times must be under 200ms because of the partner API contract." -- **Rejected alternatives when the rejection is non-obvious.** If you considered GraphQL and picked REST for subtle reasons, record it — otherwise someone will suggest GraphQL again in six months. +- **Rejected alternatives when the rejection is non-obvious.** If you considered GraphQL and picked REST for subtle reasons, record it; otherwise someone will suggest GraphQL again in six months. diff --git a/agents/skills/grill-with-docs/CONTEXT-FORMAT.md b/agents/skills/domain-modeling/CONTEXT-FORMAT.md similarity index 58% rename from agents/skills/grill-with-docs/CONTEXT-FORMAT.md rename to agents/skills/domain-modeling/CONTEXT-FORMAT.md index ddfa247..79bbb32 100644 --- a/agents/skills/grill-with-docs/CONTEXT-FORMAT.md +++ b/agents/skills/domain-modeling/CONTEXT-FORMAT.md @@ -10,7 +10,7 @@ ## Language **Order**: -{A concise description of the term} +{A one or two sentence description of the term} _Avoid_: Purchase, transaction **Invoice**: @@ -20,31 +20,14 @@ _Avoid_: Bill, payment request **Customer**: A person or organization that places orders. _Avoid_: Client, buyer, account - -## Relationships - -- An **Order** produces one or more **Invoices** -- An **Invoice** belongs to exactly one **Customer** - -## Example dialogue - -> **Dev:** "When a **Customer** places an **Order**, do we create the **Invoice** immediately?" -> **Domain expert:** "No — an **Invoice** is only generated once a **Fulfillment** is confirmed." - -## Flagged ambiguities - -- "account" was used to mean both **Customer** and **User** — resolved: these are distinct concepts. ``` ## Rules -- **Be opinionated.** When multiple words exist for the same concept, pick the best one and list the others as aliases to avoid. -- **Flag conflicts explicitly.** If a term is used ambiguously, call it out in "Flagged ambiguities" with a clear resolution. -- **Keep definitions tight.** One sentence max. Define what it IS, not what it does. -- **Show relationships.** Use bold term names and express cardinality where obvious. +- **Be opinionated.** When multiple words exist for the same concept, pick the best one and list the others under `_Avoid_`. +- **Keep definitions tight.** One or two sentences max. Define what it IS, not what it does. - **Only include terms specific to this project's context.** General programming concepts (timeouts, error types, utility patterns) don't belong even if the project uses them extensively. Before adding a term, ask: is this a concept unique to this context, or a general programming concept? Only the former belongs. - **Group terms under subheadings** when natural clusters emerge. If all terms belong to a single cohesive area, a flat list is fine. -- **Write an example dialogue.** A conversation between a dev and a domain expert that demonstrates how the terms interact naturally and clarifies boundaries between related concepts. ## Single vs multi-context repos @@ -57,9 +40,9 @@ _Avoid_: Client, buyer, account ## Contexts -- [Ordering](./src/ordering/CONTEXT.md) — receives and tracks customer orders -- [Billing](./src/billing/CONTEXT.md) — generates invoices and processes payments -- [Fulfillment](./src/fulfillment/CONTEXT.md) — manages warehouse picking and shipping +- [Ordering](./src/ordering/CONTEXT.md): receives and tracks customer orders +- [Billing](./src/billing/CONTEXT.md): generates invoices and processes payments +- [Fulfillment](./src/fulfillment/CONTEXT.md): manages warehouse picking and shipping ## Relationships diff --git a/agents/skills/domain-modeling/SKILL.md b/agents/skills/domain-modeling/SKILL.md new file mode 100644 index 0000000..9b97707 --- /dev/null +++ b/agents/skills/domain-modeling/SKILL.md @@ -0,0 +1,74 @@ +--- +name: domain-modeling +description: Build and sharpen a project's domain model. Use when discussing codebase terminology, writing or editing a CONTEXT.md, or recording or editing an ADR. +--- + +# Domain Modeling + +Actively build and sharpen the project's domain model as you design. This is the *active* discipline: challenging terms, inventing edge-case scenarios, and writing the glossary and decisions down the moment they crystallise. (Merely *reading* `CONTEXT.md` for vocabulary is not this skill: that's a one-line habit any skill can do. This skill is for when you're changing the model, not just consuming it.) + +## File structure + +Most repos have a single context: + +``` +/ +├── CONTEXT.md +├── docs/ +│ └── adr/ +│ ├── 0001-event-sourced-orders.md +│ └── 0002-postgres-for-write-model.md +└── src/ +``` + +If a `CONTEXT-MAP.md` exists at the root, the repo has multiple contexts. The map points to where each one lives: + +``` +/ +├── CONTEXT-MAP.md +├── docs/ +│ └── adr/ ← system-wide decisions +├── src/ +│ ├── ordering/ +│ │ ├── CONTEXT.md +│ │ └── docs/adr/ ← context-specific decisions +│ └── billing/ +│ ├── CONTEXT.md +│ └── docs/adr/ +``` + +Create files lazily: only when you have something to write. If no `CONTEXT.md` exists, create one when the first term is resolved. If no `docs/adr/` exists, create it when the first ADR is needed. + +## During the session + +### Challenge against the glossary + +When the user uses a term that conflicts with the existing language in `CONTEXT.md`, call it out immediately. "Your glossary defines 'cancellation' as X, but you seem to mean Y. Which is it?" + +### Sharpen fuzzy language + +When the user uses vague or overloaded terms, propose a precise canonical term. "You're saying 'account': do you mean the Customer or the User? Those are different things." + +### Discuss concrete scenarios + +When domain relationships are being discussed, stress-test them with specific scenarios. Invent scenarios that probe edge cases and force the user to be precise about the boundaries between concepts. + +### Cross-reference with code + +When the user states how something works, check whether the code agrees. If you find a contradiction, surface it: "Your code cancels entire Orders, but you just said partial cancellation is possible. Which is right?" + +### Update CONTEXT.md inline + +When a term is resolved, update `CONTEXT.md` right there. Don't batch these up: capture them as they happen. Use the format in [CONTEXT-FORMAT.md](./CONTEXT-FORMAT.md). + +`CONTEXT.md` should be totally devoid of implementation details. Do not treat `CONTEXT.md` as a spec, a scratch pad, or a repository for implementation decisions. It is a glossary and nothing else. + +### Offer ADRs sparingly + +Only offer to create an ADR when all three are true: + +1. **Hard to reverse**: the cost of changing your mind later is meaningful +2. **Surprising without context**: a future reader will wonder "why did they do it this way?" +3. **The result of a real trade-off**: there were genuine alternatives and you picked one for specific reasons + +If any of the three is missing, skip the ADR. Use the format in [ADR-FORMAT.md](./ADR-FORMAT.md). diff --git a/agents/skills/domain-modeling/agents/openai.yaml b/agents/skills/domain-modeling/agents/openai.yaml new file mode 100644 index 0000000..7f1522d --- /dev/null +++ b/agents/skills/domain-modeling/agents/openai.yaml @@ -0,0 +1,3 @@ +interface: + display_name: "Domain Modeling" + short_description: "Build and sharpen a domain model" diff --git a/agents/skills/find-skills/SKILL.md b/agents/skills/find-skills/SKILL.md index 114c663..a41bdd0 100644 --- a/agents/skills/find-skills/SKILL.md +++ b/agents/skills/find-skills/SKILL.md @@ -24,9 +24,8 @@ The Skills CLI (`npx skills`) is the package manager for the open agent skills e **Key commands:** -- `npx skills find [query]` - Search for skills interactively or by keyword +- `npx skills find [query] [--owner ]` - Search for skills interactively or by keyword, optionally scoped to a GitHub owner - `npx skills add ` - Install a skill from GitHub or other sources -- `npx skills check` - Check for skill updates - `npx skills update` - Update all installed skills **Browse skills at:** https://skills.sh/ @@ -54,7 +53,7 @@ For example, top skills for web development include: If the leaderboard doesn't cover the user's need, run the find command: ```bash -npx skills find [query] +npx skills find [query] [--owner ] ``` For example: diff --git a/agents/skills/graphify/.graphify_version b/agents/skills/graphify/.graphify_version deleted file mode 100644 index ff70965..0000000 --- a/agents/skills/graphify/.graphify_version +++ /dev/null @@ -1 +0,0 @@ -0.7.13 \ No newline at end of file diff --git a/agents/skills/graphify/SKILL.md b/agents/skills/graphify/SKILL.md deleted file mode 100644 index 8c296b0..0000000 --- a/agents/skills/graphify/SKILL.md +++ /dev/null @@ -1,1031 +0,0 @@ ---- -name: graphify -description: "any input (code, docs, papers, images, videos) to knowledge graph. Use when user asks any question about a codebase, documents, or project content - especially if graphify-out/ exists, treat the question as a /graphify query." -trigger: /graphify ---- - -# /graphify - -Turn any folder of files into a navigable knowledge graph with community detection, an honest audit trail, and three outputs: interactive HTML, GraphRAG-ready JSON, and a plain-language GRAPH_REPORT.md. - -## Usage - -``` -/graphify # full pipeline on current directory → Obsidian vault -/graphify # full pipeline on specific path -/graphify https://github.com// # clone repo then run full pipeline on it -/graphify https://github.com// --branch # clone a specific branch -/graphify ... # clone multiple repos, build each, merge into one cross-repo graph -/graphify --mode deep # thorough extraction, richer INFERRED edges -/graphify --update # incremental - re-extract only new/changed files -/graphify --directed # build directed graph (preserves edge direction: source→target) -/graphify --whisper-model medium # use a larger Whisper model for better transcription accuracy -/graphify --cluster-only # rerun clustering on existing graph -/graphify --no-viz # skip visualization, just report + JSON -/graphify --html # (HTML is generated by default - this flag is a no-op) -/graphify --svg # also export graph.svg (embeds in Notion, GitHub) -/graphify --graphml # export graph.graphml (Gephi, yEd) -/graphify --neo4j # generate graphify-out/cypher.txt for Neo4j -/graphify --neo4j-push bolt://localhost:7687 # push directly to Neo4j -/graphify --mcp # start MCP stdio server for agent access -/graphify --watch # watch folder, auto-rebuild on code changes (no LLM needed) -/graphify --wiki # build agent-crawlable wiki (index.md + one article per community) -/graphify --obsidian --obsidian-dir ~/vaults/my-project # write vault to custom path (e.g. existing vault) -/graphify add # fetch URL, save to ./raw, update graph -/graphify add --author "Name" # tag who wrote it -/graphify add --contributor "Name" # tag who added it to the corpus -/graphify query "" # BFS traversal - broad context -/graphify query "" --dfs # DFS - trace a specific path -/graphify query "" --budget 1500 # cap answer at N tokens -/graphify path "AuthModule" "Database" # shortest path between two concepts -/graphify explain "SwinTransformer" # plain-language explanation of a node -``` - -## What graphify is for - -Drop any folder of code, docs, papers, images, or video into graphify and get a queryable knowledge graph. Persistent across sessions, honest audit trail (EXTRACTED/INFERRED/AMBIGUOUS), community detection surfaces cross-document connections you wouldn't think to ask about. - -## What You Must Do When Invoked - -If the user invoked `/graphify --help` or `/graphify -h` (with no other arguments), print the contents of the `## Usage` section above verbatim and stop. Do not run any commands, do not detect files, do not default the path to `.`. Just print the Usage block and return. - -If no path was given, use `.` (current directory). Do not ask the user for a path. - -If the path argument starts with `https://github.com/` or `http://github.com/`, treat it as a GitHub URL - run Step 0 before anything else, then continue with the resolved local path. - -Follow these steps in order. Do not skip steps. - -### Step 0 - Clone GitHub repo(s) (only if a GitHub URL was given) - -**Single repo:** -```bash -LOCAL_PATH=$(graphify clone [--branch ]) -# Use LOCAL_PATH as the target for all subsequent steps -``` - -**Multiple repos (cross-repo graph):** -```bash -# Clone each repo, run the full pipeline on each, then merge -graphify clone # → ~/.graphify/repos// -graphify clone # → ~/.graphify/repos// -# Run /graphify on each local path to produce their graph.json files -# Then merge: -graphify merge-graphs \ - ~/.graphify/repos///graphify-out/graph.json \ - ~/.graphify/repos///graphify-out/graph.json \ - --out graphify-out/cross-repo-graph.json -``` - -Graphify clones into `~/.graphify/repos//` and reuses existing clones on repeat runs. Each node in the merged graph carries a `repo` attribute so you can filter by origin. - -### Step 1 - Ensure graphify is installed - -```bash -# Detect the correct Python interpreter (handles uv tool, pipx, venv, system installs) -PYTHON="" -GRAPHIFY_BIN=$(which graphify 2>/dev/null) -# 1. uv tool installs — most reliable on modern Mac/Linux -if [ -z "$PYTHON" ] && command -v uv >/dev/null 2>&1; then - _UV_PY=$(uv tool run graphifyy python -c "import sys; print(sys.executable)" 2>/dev/null) - if [ -n "$_UV_PY" ]; then PYTHON="$_UV_PY"; fi -fi -# 2. Read shebang from graphify binary (pipx and direct pip installs) -if [ -z "$PYTHON" ] && [ -n "$GRAPHIFY_BIN" ]; then - _SHEBANG=$(head -1 "$GRAPHIFY_BIN" | tr -d '#!') - case "$_SHEBANG" in - *[!a-zA-Z0-9/_.-]*) ;; - *) "$_SHEBANG" -c "import graphify" 2>/dev/null && PYTHON="$_SHEBANG" ;; - esac -fi -# 3. Fall back to python3 -if [ -z "$PYTHON" ]; then PYTHON="python3"; fi -"$PYTHON" -c "import graphify" 2>/dev/null || "$PYTHON" -m pip install graphifyy -q 2>/dev/null || "$PYTHON" -m pip install graphifyy -q --break-system-packages 2>&1 | tail -3 -# Write interpreter path for all subsequent steps (persists across invocations) -mkdir -p graphify-out -"$PYTHON" -c "import sys; open('graphify-out/.graphify_python', 'w').write(sys.executable)" -# Save scan root so `graphify update` (no args) knows where to look next time -echo "$(cd INPUT_PATH && pwd)" > graphify-out/.graphify_root -``` - -If the import succeeds, print nothing and move straight to Step 2. - -**In every subsequent bash block, replace `python3` with `$(cat graphify-out/.graphify_python)` to use the correct interpreter.** - -### Step 2 - Detect files - -```bash -$(cat graphify-out/.graphify_python) -c " -import json -from graphify.detect import detect -from pathlib import Path -result = detect(Path('INPUT_PATH')) -print(json.dumps(result)) -" > graphify-out/.graphify_detect.json -``` - -Replace INPUT_PATH with the actual path the user provided. Do NOT cat or print the JSON - read it silently and present a clean summary instead: - -``` -Corpus: X files · ~Y words - code: N files (.py .ts .go ...) - docs: N files (.md .txt ...) - papers: N files (.pdf ...) - images: N files - video: N files (.mp4 .mp3 ...) -``` - -Omit any category with 0 files from the summary. - -Then act on it: -- If `total_files` is 0: stop with "No supported files found in [path]." -- If `skipped_sensitive` is non-empty: mention file count skipped, not the file names. -- If `total_words` > 2,000,000 OR `total_files` > 200: show the warning and the top 5 subdirectories by file count, then ask which subfolder to run on. Wait for the user's answer before proceeding. -- Otherwise: proceed directly to Step 2.5 if video files were detected, or Step 3 if not. - -### Step 2.5 - Transcribe video / audio files (only if video files detected) - -Skip this step entirely if `detect` returned zero `video` files. - -Video and audio files cannot be read directly. Transcribe them to text first, then treat the transcripts as doc files in Step 3. - -**Strategy:** Read the god nodes from `graphify-out/.graphify_detect.json` (or the analysis file if it exists from a previous run). You are already a language model — write a one-sentence domain hint yourself from those labels. Then pass it to Whisper as the initial prompt. No separate API call needed. - -**However**, if the corpus has *only* video files and no other docs/code, use the generic fallback prompt: `"Use proper punctuation and paragraph breaks."` - -**Step 1 - Write the Whisper prompt yourself.** - -Read the top god node labels from detect output or analysis, then compose a short domain hint sentence, for example: - -- Labels: `transformer, attention, encoder, decoder` → `"Machine learning research on transformer architectures and attention mechanisms. Use proper punctuation and paragraph breaks."` -- Labels: `kubernetes, deployment, pod, helm` → `"DevOps discussion about Kubernetes deployments and Helm charts. Use proper punctuation and paragraph breaks."` - -Set it as `WHISPER_PROMPT` to use in the next command. - -**Step 2 - Transcribe:** - -```bash -GRAPHIFY_WHISPER_MODEL=base # or whatever --whisper-model the user passed -$(cat graphify-out/.graphify_python) -c " -import json, os -from pathlib import Path -from graphify.transcribe import transcribe_all - -detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text()) -video_files = detect.get('files', {}).get('video', []) -prompt = os.environ.get('GRAPHIFY_WHISPER_PROMPT', 'Use proper punctuation and paragraph breaks.') - -transcript_paths = transcribe_all(video_files, initial_prompt=prompt) -print(json.dumps(transcript_paths)) -" > graphify-out/.graphify_transcripts.json -``` - -After transcription: -- Read the transcript paths from `graphify-out/.graphify_transcripts.json` -- Add them to the docs list before dispatching semantic subagents in Step 3B -- Print how many transcripts were created: `Transcribed N video file(s) -> treating as docs` -- If transcription fails for a file, print a warning and continue with the rest - -**Whisper model:** Default is `base`. If the user passed `--whisper-model `, set `GRAPHIFY_WHISPER_MODEL=` in the environment before running the command above. - -### Step 3 - Extract entities and relationships - -**Before starting:** note whether `--mode deep` was given. You must pass `DEEP_MODE=true` to every subagent in Step B2 if it was. Track this from the original invocation - do not lose it. - -This step has two parts: **structural extraction** (deterministic, free) and **semantic extraction** (LLM, costs tokens). - -**Before dispatching subagents:** check whether `GEMINI_API_KEY` or `GOOGLE_API_KEY` is set. If neither is set, print this one-liner to the user: -> Tip: set `GEMINI_API_KEY` or `GOOGLE_API_KEY` to use Gemini for semantic extraction (`pip install 'graphifyy[gemini]'`). - -Print it once, then continue. If `GEMINI_API_KEY` or `GOOGLE_API_KEY` IS set, use `graphify.llm.extract_corpus_parallel(files, backend="gemini")` for semantic extraction instead of dispatching Claude subagents. The default Gemini model is `gemini-3-flash-preview`; set `GRAPHIFY_GEMINI_MODEL` or pass `--model` in headless CLI flows to override it. - -**Run Part A (AST) and Part B (semantic) in parallel. Dispatch all semantic subagents AND start AST extraction in the same message. Both can run simultaneously since they operate on different file types. Merge results in Part C as before.** - -Note: Parallelizing AST + semantic saves 5-15s on large corpora. AST is deterministic and fast; start it while subagents are processing docs/papers. - -#### Part A - Structural extraction for code files - -For any code files detected, run AST extraction in parallel with Part B subagents: - -```bash -$(cat graphify-out/.graphify_python) -c " -import sys, json -from graphify.extract import collect_files, extract -from pathlib import Path -import json - -code_files = [] -detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text()) -for f in detect.get('files', {}).get('code', []): - code_files.extend(collect_files(Path(f)) if Path(f).is_dir() else [Path(f)]) - -if code_files: - result = extract(code_files, cache_root=Path('.')) - Path('graphify-out/.graphify_ast.json').write_text(json.dumps(result, indent=2)) - print(f'AST: {len(result[\"nodes\"])} nodes, {len(result[\"edges\"])} edges') -else: - Path('graphify-out/.graphify_ast.json').write_text(json.dumps({'nodes':[],'edges':[],'input_tokens':0,'output_tokens':0})) - print('No code files - skipping AST extraction') -" -``` - -#### Part B - Semantic extraction (parallel subagents) - -**Fast path:** If detection found zero docs, papers, and images (code-only corpus), skip Part B entirely and go straight to Part C. AST handles code - there is nothing for semantic subagents to do. - -**MANDATORY: You MUST use the Agent tool here. Reading files yourself one-by-one is forbidden - it is 5-10x slower. If you do not use the Agent tool you are doing this wrong.** - -Before dispatching subagents, print a timing estimate: -- Load `total_words` and file counts from `graphify-out/.graphify_detect.json` -- Estimate agents needed: `ceil(uncached_non_code_files / 22)` (chunk size is 20-25) -- Estimate time: ~45s per agent batch (they run in parallel, so total ≈ 45s × ceil(agents/parallel_limit)) -- Print: "Semantic extraction: ~N files → X agents, estimated ~Ys" - -**Step B0 - Check extraction cache first** - -Before dispatching any subagents, check which files already have cached extraction results: - -```bash -$(cat graphify-out/.graphify_python) -c " -import json -from graphify.cache import check_semantic_cache -from pathlib import Path - -detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text()) -all_files = [f for files in detect['files'].values() for f in files] - -cached_nodes, cached_edges, cached_hyperedges, uncached = check_semantic_cache(all_files) - -if cached_nodes or cached_edges or cached_hyperedges: - Path('graphify-out/.graphify_cached.json').write_text(json.dumps({'nodes': cached_nodes, 'edges': cached_edges, 'hyperedges': cached_hyperedges})) -Path('graphify-out/.graphify_uncached.txt').write_text('\n'.join(uncached)) -print(f'Cache: {len(all_files)-len(uncached)} files hit, {len(uncached)} files need extraction') -" -``` - -Only dispatch subagents for files listed in `graphify-out/.graphify_uncached.txt`. If all files are cached, skip to Part C directly. - -**Step B1 - Split into chunks** - -Load files from `graphify-out/.graphify_uncached.txt`. Split into chunks of 20-25 files each. Each image gets its own chunk (vision needs separate context). When splitting, group files from the same directory together so related artifacts land in the same chunk and cross-file relationships are more likely to be extracted. - -**Step B2 - Dispatch ALL subagents in a single message** - -Call the Agent tool multiple times IN THE SAME RESPONSE - one call per chunk. This is the only way they run in parallel. If you make one Agent call, wait, then make another, you are doing it sequentially and defeating the purpose. - -**IMPORTANT - subagent type:** Always use `subagent_type="general-purpose"`. Do NOT use `Explore` - it is read-only and cannot write chunk files to disk, which silently drops extraction results. General-purpose has Write and Bash access which the subagent needs. - -Concrete example for 3 chunks: -``` -[Agent tool call 1: files 1-15, subagent_type="general-purpose"] -[Agent tool call 2: files 16-30, subagent_type="general-purpose"] -[Agent tool call 3: files 31-45, subagent_type="general-purpose"] -``` -All three in one message. Not three separate messages. - -Each subagent receives this exact prompt (substitute FILE_LIST, CHUNK_NUM, TOTAL_CHUNKS, and DEEP_MODE): - -``` -You are a graphify extraction subagent. Read the files listed and extract a knowledge graph fragment. -Output ONLY valid JSON matching the schema below - no explanation, no markdown fences, no preamble. - -Files (chunk CHUNK_NUM of TOTAL_CHUNKS): -FILE_LIST - -Rules: -- EXTRACTED: relationship explicit in source (import, call, citation, "see §3.2") -- INFERRED: reasonable inference (shared data structure, implied dependency) -- AMBIGUOUS: uncertain - flag for review, do not omit - -Code files: focus on semantic edges AST cannot find (call relationships, shared data, arch patterns). - Do not re-extract imports - AST already has those. -Doc/paper files: extract named concepts, entities, citations. For rationale (WHY decisions were made, trade-offs, design intent): store as a `rationale` attribute on the relevant concept node — do NOT create a separate rationale node or fragment node. Only create a node for something that is itself a named entity or concept. Use `file_type:"rationale"` for concept-like nodes (ideas, principles, mechanisms, design patterns). Do NOT invent file_types like `concept` — valid values are only `code|document|paper|image|rationale`. -Code files: when adding `calls` edges, source MUST be the caller (the function/class doing the calling), target MUST be the callee. Never reverse this direction. -Image files: use vision to understand what the image IS - do not just OCR. - UI screenshot: layout patterns, design decisions, key elements, purpose. - Chart: metric, trend/insight, data source. - Tweet/post: claim as node, author, concepts mentioned. - Diagram: components and connections. - Research figure: what it demonstrates, method, result. - Handwritten/whiteboard: ideas and arrows, mark uncertain readings AMBIGUOUS. - -DEEP_MODE (if --mode deep was given): be aggressive with INFERRED edges - indirect deps, - shared assumptions, latent couplings. Mark uncertain ones AMBIGUOUS instead of omitting. - -Semantic similarity: if two concepts in this chunk solve the same problem or represent the same idea without any structural link (no import, no call, no citation), add a `semantically_similar_to` edge marked INFERRED with a confidence_score reflecting how similar they are (0.6-0.95). Examples: -- Two functions that both validate user input but never call each other -- A class in code and a concept in a paper that describe the same algorithm -- Two error types that handle the same failure mode differently -Only add these when the similarity is genuinely non-obvious and cross-cutting. Do not add them for trivially similar things. - -Hyperedges: if 3 or more nodes clearly participate together in a shared concept, flow, or pattern that is not captured by pairwise edges alone, add a hyperedge to a top-level `hyperedges` array. Examples: -- All classes that implement a common protocol or interface -- All functions in an authentication flow (even if they don't all call each other) -- All concepts from a paper section that form one coherent idea -Use sparingly — only when the group relationship adds information beyond the pairwise edges. Maximum 3 hyperedges per chunk. - -If a file has YAML frontmatter (--- ... ---), copy source_url, captured_at, author, - contributor onto every node from that file. - -confidence_score is REQUIRED on every edge - never omit it, never use 0.5 as a default: -- EXTRACTED edges: confidence_score = 1.0 always -- INFERRED edges: pick exactly ONE value from this set — never 0.5: - 0.95 direct structural evidence (shared data structure, named cross-file reference). - 0.85 strong inference (clear functional alignment, no direct symbol link). - 0.75 reasonable inference (shared problem domain + similar shape, requires interpretation). - 0.65 weak inference (thematically related, no shape evidence). - 0.55 speculative but plausible (surface-level co-occurrence only). - Models follow discrete rubrics better than continuous ranges; the bimodal - distribution observed in production (>50% at 0.5, >40% at 0.85+) shows the - range guidance is being collapsed to a binary. If no value above fits, mark - the edge AMBIGUOUS rather than picking 0.4 or below. -- AMBIGUOUS edges: 0.1-0.3 - -Node ID format: lowercase, only `[a-z0-9_]`, no dots or slashes. Format: `{stem}_{entity}` where stem is the filename without extension and entity is the symbol name, both normalized (lowercase, non-alphanumeric chars replaced with `_`). Example: `src/auth/session.py` + `ValidateToken` → `session_validatetoken`. This must match the ID the AST extractor generates so cross-references between code and semantic nodes connect correctly. CRITICAL: never append chunk numbers, sequence numbers, or any suffix to an ID (no `_c1`, `_c2`, `_chunk2`, etc.). IDs must be deterministic from the label alone — the same entity must always produce the same ID regardless of which chunk processes it. - -Output exactly this JSON (no other text): -{"nodes":[{"id":"session_validatetoken","label":"Human Readable Name","file_type":"code|document|paper|image|rationale","source_file":"relative/path","source_location":null,"source_url":null,"captured_at":null,"author":null,"contributor":null}],"edges":[{"source":"node_id","target":"node_id","relation":"calls|implements|references|cites|conceptually_related_to|shares_data_with|semantically_similar_to|rationale_for","confidence":"EXTRACTED|INFERRED|AMBIGUOUS","confidence_score":1.0,"source_file":"relative/path","source_location":null,"weight":1.0}],"hyperedges":[{"id":"snake_case_id","label":"Human Readable Label","nodes":["node_id1","node_id2","node_id3"],"relation":"participate_in|implement|form","confidence":"EXTRACTED|INFERRED","confidence_score":0.75,"source_file":"relative/path"}],"input_tokens":0,"output_tokens":0} -``` - -**Step B3 - Collect, cache, and merge** - -Wait for all subagents. For each result: -- Check that `graphify-out/.graphify_chunk_NN.json` exists on disk — this is the success signal -- If the file exists and contains valid JSON with `nodes` and `edges`, include it and save to cache -- If the file is missing, the subagent was likely dispatched as read-only (Explore type) — print a warning: "chunk N missing from disk — subagent may have been read-only. Re-run with general-purpose agent." Do not silently skip. -- If a subagent failed or returned invalid JSON, print a warning and skip that chunk - do not abort - -If more than half the chunks failed or are missing, stop and tell the user to re-run and ensure `subagent_type="general-purpose"` is used. - -Merge all chunk files into `.graphify_semantic_new.json`. **After each Agent call completes, read the real token counts from the Agent tool result's `usage` field and write them back into the chunk JSON before merging** — the chunk JSON itself always has placeholder zeros. Then run: -```bash -$(cat graphify-out/.graphify_python) -c " -import json, glob -from pathlib import Path - -chunks = sorted(glob.glob('graphify-out/.graphify_chunk_*.json')) -all_nodes, all_edges, all_hyperedges = [], [], [] -total_in, total_out = 0, 0 -for c in chunks: - d = json.loads(Path(c).read_text()) - all_nodes += d.get('nodes', []) - all_edges += d.get('edges', []) - all_hyperedges += d.get('hyperedges', []) - total_in += d.get('input_tokens', 0) - total_out += d.get('output_tokens', 0) -Path('graphify-out/.graphify_semantic_new.json').write_text(json.dumps({ - 'nodes': all_nodes, 'edges': all_edges, 'hyperedges': all_hyperedges, - 'input_tokens': total_in, 'output_tokens': total_out, -}, indent=2)) -print(f'Merged {len(chunks)} chunks: {total_in:,} in / {total_out:,} out tokens') -" -``` - -Save new results to cache: -```bash -$(cat graphify-out/.graphify_python) -c " -import json -from graphify.cache import save_semantic_cache -from pathlib import Path - -new = json.loads(Path('graphify-out/.graphify_semantic_new.json').read_text()) if Path('graphify-out/.graphify_semantic_new.json').exists() else {'nodes':[],'edges':[],'hyperedges':[]} -saved = save_semantic_cache(new.get('nodes', []), new.get('edges', []), new.get('hyperedges', [])) -print(f'Cached {saved} files') -" -``` - -Merge cached + new results into `graphify-out/.graphify_semantic.json`: -```bash -$(cat graphify-out/.graphify_python) -c " -import json -from pathlib import Path - -cached = json.loads(Path('graphify-out/.graphify_cached.json').read_text()) if Path('graphify-out/.graphify_cached.json').exists() else {'nodes':[],'edges':[],'hyperedges':[]} -new = json.loads(Path('graphify-out/.graphify_semantic_new.json').read_text()) if Path('graphify-out/.graphify_semantic_new.json').exists() else {'nodes':[],'edges':[],'hyperedges':[]} - -all_nodes = cached['nodes'] + new.get('nodes', []) -all_edges = cached['edges'] + new.get('edges', []) -all_hyperedges = cached.get('hyperedges', []) + new.get('hyperedges', []) -seen = set() -deduped = [] -for n in all_nodes: - if n['id'] not in seen: - seen.add(n['id']) - deduped.append(n) - -merged = { - 'nodes': deduped, - 'edges': all_edges, - 'hyperedges': all_hyperedges, - 'input_tokens': new.get('input_tokens', 0), - 'output_tokens': new.get('output_tokens', 0), -} -Path('graphify-out/.graphify_semantic.json').write_text(json.dumps(merged, indent=2)) -print(f'Extraction complete - {len(deduped)} nodes, {len(all_edges)} edges ({len(cached[\"nodes\"])} from cache, {len(new.get(\"nodes\",[]))} new)') -" -``` -Clean up temp files: `rm -f graphify-out/.graphify_cached.json graphify-out/.graphify_uncached.txt graphify-out/.graphify_semantic_new.json` - -#### Part C - Merge AST + semantic into final extraction - -```bash -$(cat graphify-out/.graphify_python) -c " -import sys, json -from pathlib import Path - -ast = json.loads(Path('graphify-out/.graphify_ast.json').read_text()) -sem = json.loads(Path('graphify-out/.graphify_semantic.json').read_text()) - -# Merge: AST nodes first, semantic nodes deduplicated by id -seen = {n['id'] for n in ast['nodes']} -merged_nodes = list(ast['nodes']) -for n in sem['nodes']: - if n['id'] not in seen: - merged_nodes.append(n) - seen.add(n['id']) - -merged_edges = ast['edges'] + sem['edges'] -merged_hyperedges = sem.get('hyperedges', []) -merged = { - 'nodes': merged_nodes, - 'edges': merged_edges, - 'hyperedges': merged_hyperedges, - 'input_tokens': sem.get('input_tokens', 0), - 'output_tokens': sem.get('output_tokens', 0), -} -Path('graphify-out/.graphify_extract.json').write_text(json.dumps(merged, indent=2)) -total = len(merged_nodes) -edges = len(merged_edges) -print(f'Merged: {total} nodes, {edges} edges ({len(ast[\"nodes\"])} AST + {len(sem[\"nodes\"])} semantic)') -" -``` - -### Step 4 - Build graph, cluster, analyze, generate outputs - -**Before starting:** note whether `--directed` was given. If so, pass `directed=True` to `build_from_json()` in the code block below. This builds a `DiGraph` that preserves edge direction (source→target) instead of the default undirected `Graph`. - -```bash -mkdir -p graphify-out -$(cat graphify-out/.graphify_python) -c " -import sys, json -from graphify.build import build_from_json -from graphify.cluster import cluster, score_all -from graphify.analyze import god_nodes, surprising_connections, suggest_questions -from graphify.report import generate -from graphify.export import to_json -from pathlib import Path - -extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text()) -detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text()) - -G = build_from_json(extraction) -communities = cluster(G) -cohesion = score_all(G, communities) -tokens = {'input': extraction.get('input_tokens', 0), 'output': extraction.get('output_tokens', 0)} -gods = god_nodes(G) -surprises = surprising_connections(G, communities) -labels = {cid: 'Community ' + str(cid) for cid in communities} -# Placeholder questions - regenerated with real labels in Step 5 -questions = suggest_questions(G, communities, labels) - -report = generate(G, communities, cohesion, labels, gods, surprises, detection, tokens, 'INPUT_PATH', suggested_questions=questions) -Path('graphify-out/GRAPH_REPORT.md').write_text(report) -to_json(G, communities, 'graphify-out/graph.json') - -analysis = { - 'communities': {str(k): v for k, v in communities.items()}, - 'cohesion': {str(k): v for k, v in cohesion.items()}, - 'gods': gods, - 'surprises': surprises, - 'questions': questions, -} -Path('graphify-out/.graphify_analysis.json').write_text(json.dumps(analysis, indent=2)) -if G.number_of_nodes() == 0: - print('ERROR: Graph is empty - extraction produced no nodes.') - print('Possible causes: all files were skipped, binary-only corpus, or extraction failed.') - raise SystemExit(1) -print(f'Graph: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges, {len(communities)} communities') -" -``` - -If this step prints `ERROR: Graph is empty`, stop and tell the user what happened - do not proceed to labeling or visualization. - -Replace INPUT_PATH with the actual path. - -### Step 5 - Label communities - -Read `graphify-out/.graphify_analysis.json`. For each community key, look at its node labels and write a 2-5 word plain-language name (e.g. "Attention Mechanism", "Training Pipeline", "Data Loading"). - -Then regenerate the report and save the labels for the visualizer: - -```bash -$(cat graphify-out/.graphify_python) -c " -import sys, json -from graphify.build import build_from_json -from graphify.cluster import score_all -from graphify.analyze import god_nodes, surprising_connections, suggest_questions -from graphify.report import generate -from pathlib import Path - -extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text()) -detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text()) -analysis = json.loads(Path('graphify-out/.graphify_analysis.json').read_text()) - -G = build_from_json(extraction) -communities = {int(k): v for k, v in analysis['communities'].items()} -cohesion = {int(k): v for k, v in analysis['cohesion'].items()} -tokens = {'input': extraction.get('input_tokens', 0), 'output': extraction.get('output_tokens', 0)} - -# LABELS - replace these with the names you chose above -labels = LABELS_DICT - -# Regenerate questions with real community labels (labels affect question phrasing) -questions = suggest_questions(G, communities, labels) - -report = generate(G, communities, cohesion, labels, analysis['gods'], analysis['surprises'], detection, tokens, 'INPUT_PATH', suggested_questions=questions) -Path('graphify-out/GRAPH_REPORT.md').write_text(report) -Path('graphify-out/.graphify_labels.json').write_text(json.dumps({str(k): v for k, v in labels.items()})) -print('Report updated with community labels') -" -``` - -Replace `LABELS_DICT` with the actual dict you constructed (e.g. `{0: "Attention Mechanism", 1: "Training Pipeline"}`). -Replace INPUT_PATH with the actual path. - -### Step 6 - Generate Obsidian vault (opt-in) + HTML - -**Generate HTML always** (unless `--no-viz`). **Obsidian vault only if `--obsidian` was explicitly given** — skip it otherwise, it generates one file per node. - -If `--obsidian` was given: - -- If `--obsidian-dir ` was also given, pass it via `--dir`. Otherwise defaults to `graphify-out/obsidian`. - -```bash -graphify export obsidian -# or with custom dir: graphify export obsidian --dir ~/vaults/my-project -``` - -Generate the HTML graph (always, unless `--no-viz`): - -```bash -graphify export html # auto-aggregates to community view if graph > 5000 nodes -# or: graphify export html --no-viz -``` - -### Step 6b - Wiki (only if --wiki flag) - -**Only run this step if `--wiki` was explicitly given in the original command.** - -Run this before Step 9 (cleanup) so `.graphify_labels.json` is still available. - -```bash -graphify export wiki -``` - -### Step 7 - Neo4j export (only if --neo4j or --neo4j-push flag) - -**If `--neo4j`** - generate a Cypher file for manual import: - -```bash -graphify export neo4j -``` - -**If `--neo4j-push `** - push directly to a running Neo4j instance. Ask the user for credentials if not provided: - -```bash -graphify export neo4j --push bolt://localhost:7687 --user neo4j --password PASSWORD -``` - -Default URI is `bolt://localhost:7687`, default user is `neo4j`. Uses MERGE - safe to re-run without creating duplicates. - -### Step 7b - SVG export (only if --svg flag) - -```bash -graphify export svg -``` - -### Step 7c - GraphML export (only if --graphml flag) - -```bash -graphify export graphml -``` - -### Step 7d - MCP server (only if --mcp flag) - -```bash -python3 -m graphify.serve graphify-out/graph.json -``` - -This starts a stdio MCP server that exposes tools: `query_graph`, `get_node`, `get_neighbors`, `get_community`, `god_nodes`, `graph_stats`, `shortest_path`. Add to Claude Desktop or any MCP-compatible agent orchestrator so other agents can query the graph live. - -To configure in Claude Desktop, add to `claude_desktop_config.json`: -```json -{ - "mcpServers": { - "graphify": { - "command": "python3", - "args": ["-m", "graphify.serve", "/absolute/path/to/graphify-out/graph.json"] - } - } -} -``` - -### Step 8 - Token reduction benchmark (only if total_words > 5000) - -If `total_words` from `graphify-out/.graphify_detect.json` is greater than 5,000, run: - -```bash -graphify benchmark -``` - -Print the output directly in chat. If `total_words <= 5000`, skip silently - the graph value is structural clarity, not token compression, for small corpora. - ---- - -### Step 9 - Save manifest, update cost tracker, clean up, and report - -```bash -$(cat graphify-out/.graphify_python) -c " -import json -from pathlib import Path -from datetime import datetime, timezone -from graphify.detect import save_manifest - -# Save manifest for --update -detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text()) -save_manifest(detect['files']) - -# Update cumulative cost tracker -extract = json.loads(Path('graphify-out/.graphify_extract.json').read_text()) -input_tok = extract.get('input_tokens', 0) -output_tok = extract.get('output_tokens', 0) - -cost_path = Path('graphify-out/cost.json') -if cost_path.exists(): - cost = json.loads(cost_path.read_text()) -else: - cost = {'runs': [], 'total_input_tokens': 0, 'total_output_tokens': 0} - -cost['runs'].append({ - 'date': datetime.now(timezone.utc).isoformat(), - 'input_tokens': input_tok, - 'output_tokens': output_tok, - 'files': detect.get('total_files', 0), -}) -cost['total_input_tokens'] += input_tok -cost['total_output_tokens'] += output_tok -cost_path.write_text(json.dumps(cost, indent=2)) - -print(f'This run: {input_tok:,} input tokens, {output_tok:,} output tokens') -print(f'All time: {cost[\"total_input_tokens\"]:,} input, {cost[\"total_output_tokens\"]:,} output ({len(cost[\"runs\"])} runs)') -" -rm -f graphify-out/.graphify_detect.json graphify-out/.graphify_extract.json graphify-out/.graphify_ast.json graphify-out/.graphify_semantic.json graphify-out/.graphify_analysis.json graphify-out/.graphify_chunk_*.json -rm -f graphify-out/.needs_update 2>/dev/null || true -``` - -Tell the user (omit the obsidian line unless --obsidian was given): -``` -Graph complete. Outputs in PATH_TO_DIR/graphify-out/ - - graph.html - interactive graph, open in browser - GRAPH_REPORT.md - audit report - graph.json - raw graph data - obsidian/ - Obsidian vault (only if --obsidian was given) -``` - -If graphify saved you time, consider supporting it: https://github.com/sponsors/safishamsi - -Replace PATH_TO_DIR with the actual absolute path of the directory that was processed. - -Then paste these sections from GRAPH_REPORT.md directly into the chat: -- God Nodes -- Surprising Connections -- Suggested Questions - -Do NOT paste the full report - just those three sections. Keep it concise. - -Then immediately offer to explore. Pick the single most interesting suggested question from the report - the one that crosses the most community boundaries or has the most surprising bridge node - and ask: - -> "The most interesting question this graph can answer: **[question]**. Want me to trace it?" - -If the user says yes, run `/graphify query "[question]"` on the graph and walk them through the answer using the graph structure - which nodes connect, which community boundaries get crossed, what the path reveals. Keep going as long as they want to explore. Each answer should end with a natural follow-up ("this connects to X - want to go deeper?") so the session feels like navigation, not a one-shot report. - -The graph is the map. Your job after the pipeline is to be the guide. - ---- - -## Interpreter guard for subcommands - -Before running any subcommand below (`--update`, `--cluster-only`, `query`, `path`, `explain`, `add`), check that `.graphify_python` exists. If it's missing (e.g. user deleted `graphify-out/`), re-resolve the interpreter first: - -```bash -if [ ! -f graphify-out/.graphify_python ]; then - GRAPHIFY_BIN=$(which graphify 2>/dev/null) - if [ -n "$GRAPHIFY_BIN" ]; then - PYTHON=$(head -1 "$GRAPHIFY_BIN" | tr -d '#!') - case "$PYTHON" in *[!a-zA-Z0-9/_.-]*) PYTHON="python3" ;; esac - else - PYTHON="python3" - fi - mkdir -p graphify-out - "$PYTHON" -c "import sys; open('graphify-out/.graphify_python', 'w').write(sys.executable)" -fi -``` - -## For --update (incremental re-extraction) - -Use when you've added or modified files since the last run. Only re-extracts changed files - saves tokens and time. - -```bash -$(cat graphify-out/.graphify_python) -c " -import sys, json -from graphify.detect import detect_incremental, save_manifest -from pathlib import Path - -result = detect_incremental(Path('INPUT_PATH')) -new_total = result.get('new_total', 0) -print(json.dumps(result, indent=2)) -Path('graphify-out/.graphify_incremental.json').write_text(json.dumps(result)) -if new_total == 0: - print('No files changed since last run. Nothing to update.') - raise SystemExit(0) -print(f'{new_total} new/changed file(s) to re-extract.') -" -``` - -If new files exist, first check whether all changed files are code files: - -```bash -$(cat graphify-out/.graphify_python) -c " -import json -from pathlib import Path - -result = json.loads(open('graphify-out/.graphify_incremental.json').read()) if Path('graphify-out/.graphify_incremental.json').exists() else {} -code_exts = {'.py','.ts','.js','.go','.rs','.java','.cpp','.c','.rb','.swift','.kt','.cs','.scala','.php','.cc','.cxx','.hpp','.h','.kts','.lua','.toc','.f','.F','.f90','.F90','.f95','.F95','.f03','.F03','.f08','.F08'} -new_files = result.get('new_files', {}) -all_changed = [f for files in new_files.values() for f in files] -code_only = all(Path(f).suffix.lower() in code_exts for f in all_changed) -print('code_only:', code_only) -" -``` - -If `code_only` is True: print `[graphify update] Code-only changes detected - skipping semantic extraction (no LLM needed)`, run only Step 3A (AST) on the changed files, skip Step 3B entirely (no subagents), then go straight to merge and Steps 4–8. - -If `code_only` is False (any changed file is a doc/paper/image): run the full Steps 3A–3C pipeline as normal. - -Then: - -```bash -$(cat graphify-out/.graphify_python) -c " -import sys, json -from graphify.build import build_from_json -from graphify.export import to_json -from networkx.readwrite import json_graph -import networkx as nx -from pathlib import Path - -# Load existing graph -existing_data = json.loads(Path('graphify-out/graph.json').read_text()) -G_existing = json_graph.node_link_graph(existing_data, edges='links') - -# Load new extraction -new_extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text()) -G_new = build_from_json(new_extraction) - -# Prune nodes from deleted files -incremental = json.loads(Path('graphify-out/.graphify_incremental.json').read_text()) -deleted = set(incremental.get('deleted_files', [])) -if deleted: - to_remove = [n for n, d in G_existing.nodes(data=True) if d.get('source_file') in deleted] - G_existing.remove_nodes_from(to_remove) - if to_remove: - print(f'Pruned {len(to_remove)} ghost node(s) from {len(deleted)} deleted file(s) — drift detected and corrected.') - else: - print(f'{len(deleted)} file(s) deleted since last run, but no ghost nodes were present in the graph — no drift.') - -# Merge: new nodes/edges into existing graph -G_existing.update(G_new) -print(f'Merged: {G_existing.number_of_nodes()} nodes, {G_existing.number_of_edges()} edges') - -# Write merged result back to .graphify_extract.json so Step 4 sees the full graph -merged_out = { - 'nodes': [{'id': n, **d} for n, d in G_existing.nodes(data=True)], - 'edges': [{'source': u, 'target': v, **d} for u, v, d in G_existing.edges(data=True)], - 'hyperedges': new_extraction.get('hyperedges', []), - 'input_tokens': new_extraction.get('input_tokens', 0), - 'output_tokens': new_extraction.get('output_tokens', 0), -} -Path('graphify-out/.graphify_extract.json').write_text(json.dumps(merged_out)) -print(f'[graphify update] Merged extraction written ({len(merged_out[\"nodes\"])} nodes, {len(merged_out[\"edges\"])} edges)') - -# Save manifest with the CURRENT full file list so the next --update -# diffs against today's filesystem state, not the prior --update's -# baseline. Without this, deleted files get reported as ghosts again -# on every subsequent --update until a full rebuild runs. -from graphify.detect import save_manifest -save_manifest(incremental['files']) -print('[graphify update] Manifest saved.') -" -``` - -Then run Steps 4–8 on the merged graph as normal. - -After Step 4, show the graph diff: - -```bash -$(cat graphify-out/.graphify_python) -c " -import json -from graphify.analyze import graph_diff -from graphify.build import build_from_json -from networkx.readwrite import json_graph -import networkx as nx -from pathlib import Path - -# Load old graph (before update) from backup written before merge -old_data = json.loads(Path('graphify-out/.graphify_old.json').read_text()) if Path('graphify-out/.graphify_old.json').exists() else None -new_extract = json.loads(Path('graphify-out/.graphify_extract.json').read_text()) -G_new = build_from_json(new_extract) - -if old_data: - G_old = json_graph.node_link_graph(old_data, edges='links') - diff = graph_diff(G_old, G_new) - print(diff['summary']) - if diff['new_nodes']: - print('New nodes:', ', '.join(n['label'] for n in diff['new_nodes'][:5])) - if diff['new_edges']: - print('New edges:', len(diff['new_edges'])) -" -``` - -Before the merge step, save the old graph: `cp graphify-out/graph.json graphify-out/.graphify_old.json` -Clean up after: `rm -f graphify-out/.graphify_old.json` - ---- - -## For --cluster-only - -Skip Steps 1–3. Re-run clustering on the existing graph: - -```bash -graphify cluster-only . -``` - -Then run Steps 5–9 as normal (label communities, generate viz, benchmark, clean up, report). - ---- - -## For /graphify query - -Two traversal modes - choose based on the question: - -| Mode | Flag | Best for | -|------|------|----------| -| BFS (default) | _(none)_ | "What is X connected to?" - broad context, nearest neighbors first | -| DFS | `--dfs` | "How does X reach Y?" - trace a specific chain or dependency path | - -```bash -graphify query "QUESTION" -# or: graphify query "QUESTION" --dfs --budget 3000 -``` - -Replace `QUESTION` with the user's actual question. Answer using **only** what the graph output contains. Quote `source_location` when citing a specific fact. If the graph lacks enough information, say so - do not hallucinate edges. - -After writing the answer, save it back into the graph so it improves future queries: - -```bash -$(cat graphify-out/.graphify_python) -m graphify save-result --question "QUESTION" --answer "ANSWER" --type query --nodes NODE1 NODE2 -``` - -Replace `QUESTION` with the question, `ANSWER` with your full answer text, `SOURCE_NODES` with the list of node labels you cited. This closes the feedback loop: the next `--update` will extract this Q&A as a node in the graph. - ---- - -## For /graphify path - -Find the shortest path between two named concepts in the graph. - -```bash -graphify path "NODE_A" "NODE_B" -``` - -Replace `NODE_A` and `NODE_B` with the actual concept names. Then explain the path in plain language - what each hop means, why it's significant. - -After writing the explanation, save it back: - -```bash -$(cat graphify-out/.graphify_python) -m graphify save-result --question "Path from NODE_A to NODE_B" --answer "ANSWER" --type path_query --nodes NODE_A NODE_B -``` - ---- - -## For /graphify explain - -Give a plain-language explanation of a single node - everything connected to it. - -```bash -graphify explain "NODE_NAME" -``` - -Replace `NODE_NAME` with the concept the user asked about. Then write a 3-5 sentence explanation of what this node is, what it connects to, and why those connections are significant. Use the source locations as citations. - -After writing the explanation, save it back: - -```bash -$(cat graphify-out/.graphify_python) -m graphify save-result --question "Explain NODE_NAME" --answer "ANSWER" --type explain --nodes NODE_NAME -``` - ---- - -## For /graphify add - -Fetch a URL and add it to the corpus, then update the graph. - -```bash -$(cat graphify-out/.graphify_python) -c " -import sys -from graphify.ingest import ingest -from pathlib import Path - -try: - out = ingest('URL', Path('./raw'), author='AUTHOR', contributor='CONTRIBUTOR') - print(f'Saved to {out}') -except ValueError as e: - print(f'error: {e}', file=sys.stderr) - sys.exit(1) -except RuntimeError as e: - print(f'error: {e}', file=sys.stderr) - sys.exit(1) -" -``` - -Replace `URL` with the actual URL, `AUTHOR` with the user's name if provided, `CONTRIBUTOR` likewise. If the command exits with an error, tell the user what went wrong - do not silently continue. After a successful save, automatically run the `--update` pipeline on `./raw` to merge the new file into the existing graph. - -Supported URL types (auto-detected): -- YouTube / any video URL → audio downloaded via yt-dlp, transcribed to `.txt` on next run (requires `pip install 'graphifyy[video]'`) -- Twitter/X → fetched via oEmbed, saved as `.md` with tweet text and author -- arXiv → abstract + metadata saved as `.md` -- PDF → downloaded as `.pdf` -- Images (.png/.jpg/.webp) → downloaded, Claude vision extracts on next run -- Any webpage → converted to markdown via html2text - ---- - -## For --watch - -Start a background watcher that monitors a folder and auto-updates the graph when files change. - -```bash -python3 -m graphify.watch INPUT_PATH --debounce 3 -``` - -Replace INPUT_PATH with the folder to watch. Behavior depends on what changed: - -- **Code files only (.py, .ts, .go, etc.):** re-runs AST extraction + rebuild + cluster immediately, no LLM needed. `graph.json` and `GRAPH_REPORT.md` are updated automatically. -- **Docs, papers, or images:** writes a `graphify-out/needs_update` flag and prints a notification to run `/graphify --update` (LLM semantic re-extraction required). - -Debounce (default 3s): waits until file activity stops before triggering, so a wave of parallel agent writes doesn't trigger a rebuild per file. - -Press Ctrl+C to stop. - -For agentic workflows: run `--watch` in a background terminal. Code changes from agent waves are picked up automatically between waves. If agents are also writing docs or notes, you'll need a manual `/graphify --update` after those waves. - ---- - -## For git commit hook - -Install a post-commit hook that auto-rebuilds the graph after every commit. No background process needed - triggers once per commit, works with any editor. - -```bash -graphify hook install # install -graphify hook uninstall # remove -graphify hook status # check -``` - -After every `git commit`, the hook detects which code files changed (via `git diff HEAD~1`), re-runs AST extraction on those files, and rebuilds `graph.json` and `GRAPH_REPORT.md`. Doc/image changes are ignored by the hook - run `/graphify --update` manually for those. - -If a post-commit hook already exists, graphify appends to it rather than replacing it. - ---- - -## For native CLAUDE.md integration - -Run once per project to make graphify always-on in Claude Code sessions: - -```bash -graphify claude install -``` - -This writes a `## graphify` section to the local `CLAUDE.md` that instructs Claude to check the graph before answering codebase questions and rebuild it after code changes. No manual `/graphify` needed in future sessions. - -```bash -graphify claude uninstall # remove the section -``` - ---- - -## Honesty Rules - -- Never invent an edge. If unsure, use AMBIGUOUS. -- Never skip the corpus check warning. -- Always show token cost in the report. -- Never hide cohesion scores behind symbols - show the raw number. -- Never run HTML viz on a graph with more than 5,000 nodes without warning the user. diff --git a/agents/skills/grill-me/SKILL.md b/agents/skills/grill-me/SKILL.md index bd04394..3947ff9 100644 --- a/agents/skills/grill-me/SKILL.md +++ b/agents/skills/grill-me/SKILL.md @@ -1,10 +1,7 @@ --- name: grill-me -description: Interview the user relentlessly about a plan or design until reaching shared understanding, resolving each branch of the decision tree. Use when user wants to stress-test a plan, get grilled on their design, or mentions "grill me". +description: A relentless interview to sharpen a plan or design. +disable-model-invocation: true --- -Interview me relentlessly about every aspect of this plan until we reach a shared understanding. Walk down each branch of the design tree, resolving dependencies between decisions one-by-one. For each question, provide your recommended answer. - -Ask the questions one at a time. - -If a question can be answered by exploring the codebase, explore the codebase instead. +Call the Skill tool with "grilling". diff --git a/agents/skills/grill-me/agents/openai.yaml b/agents/skills/grill-me/agents/openai.yaml new file mode 100644 index 0000000..4d6fb0c --- /dev/null +++ b/agents/skills/grill-me/agents/openai.yaml @@ -0,0 +1,5 @@ +interface: + display_name: "Grill Me" + short_description: "Sharpen a plan through interview" +policy: + allow_implicit_invocation: false diff --git a/agents/skills/grill-with-docs/SKILL.md b/agents/skills/grill-with-docs/SKILL.md index 6dad6ad..62b9efb 100644 --- a/agents/skills/grill-with-docs/SKILL.md +++ b/agents/skills/grill-with-docs/SKILL.md @@ -1,88 +1,7 @@ --- name: grill-with-docs -description: Grilling session that challenges your plan against the existing domain model, sharpens terminology, and updates documentation (CONTEXT.md, ADRs) inline as decisions crystallise. Use when user wants to stress-test a plan against their project's language and documented decisions. +description: A relentless interview to sharpen a plan or design, which also creates docs (ADR's and glossary) as we go. +disable-model-invocation: true --- - - -Interview me relentlessly about every aspect of this plan until we reach a shared understanding. Walk down each branch of the design tree, resolving dependencies between decisions one-by-one. For each question, provide your recommended answer. - -Ask the questions one at a time, waiting for feedback on each question before continuing. - -If a question can be answered by exploring the codebase, explore the codebase instead. - - - - - -## Domain awareness - -During codebase exploration, also look for existing documentation: - -### File structure - -Most repos have a single context: - -``` -/ -├── CONTEXT.md -├── docs/ -│ └── adr/ -│ ├── 0001-event-sourced-orders.md -│ └── 0002-postgres-for-write-model.md -└── src/ -``` - -If a `CONTEXT-MAP.md` exists at the root, the repo has multiple contexts. The map points to where each one lives: - -``` -/ -├── CONTEXT-MAP.md -├── docs/ -│ └── adr/ ← system-wide decisions -├── src/ -│ ├── ordering/ -│ │ ├── CONTEXT.md -│ │ └── docs/adr/ ← context-specific decisions -│ └── billing/ -│ ├── CONTEXT.md -│ └── docs/adr/ -``` - -Create files lazily — only when you have something to write. If no `CONTEXT.md` exists, create one when the first term is resolved. If no `docs/adr/` exists, create it when the first ADR is needed. - -## During the session - -### Challenge against the glossary - -When the user uses a term that conflicts with the existing language in `CONTEXT.md`, call it out immediately. "Your glossary defines 'cancellation' as X, but you seem to mean Y — which is it?" - -### Sharpen fuzzy language - -When the user uses vague or overloaded terms, propose a precise canonical term. "You're saying 'account' — do you mean the Customer or the User? Those are different things." - -### Discuss concrete scenarios - -When domain relationships are being discussed, stress-test them with specific scenarios. Invent scenarios that probe edge cases and force the user to be precise about the boundaries between concepts. - -### Cross-reference with code - -When the user states how something works, check whether the code agrees. If you find a contradiction, surface it: "Your code cancels entire Orders, but you just said partial cancellation is possible — which is right?" - -### Update CONTEXT.md inline - -When a term is resolved, update `CONTEXT.md` right there. Don't batch these up — capture them as they happen. Use the format in [CONTEXT-FORMAT.md](./CONTEXT-FORMAT.md). - -Don't couple `CONTEXT.md` to implementation details. Only include terms that are meaningful to domain experts. - -### Offer ADRs sparingly - -Only offer to create an ADR when all three are true: - -1. **Hard to reverse** — the cost of changing your mind later is meaningful -2. **Surprising without context** — a future reader will wonder "why did they do it this way?" -3. **The result of a real trade-off** — there were genuine alternatives and you picked one for specific reasons - -If any of the three is missing, skip the ADR. Use the format in [ADR-FORMAT.md](./ADR-FORMAT.md). - - +Call the Skill tool twice, for "grilling" and "domain-modeling". diff --git a/agents/skills/grill-with-docs/agents/openai.yaml b/agents/skills/grill-with-docs/agents/openai.yaml new file mode 100644 index 0000000..5dbe278 --- /dev/null +++ b/agents/skills/grill-with-docs/agents/openai.yaml @@ -0,0 +1,5 @@ +interface: + display_name: "Grill with Docs" + short_description: "Grill a design and write its docs" +policy: + allow_implicit_invocation: false diff --git a/agents/skills/grilling/SKILL.md b/agents/skills/grilling/SKILL.md new file mode 100644 index 0000000..8ca78c6 --- /dev/null +++ b/agents/skills/grilling/SKILL.md @@ -0,0 +1,28 @@ +--- +name: grilling +description: Grill the user relentlessly about a plan, decision, or idea. Use when the user wants to stress-test their thinking, or uses any 'grill' trigger phrases. +--- + +Interview the user relentlessly until you reach a shared understanding. Map this as a **design tree**: every decision branches into the decisions that hang off it. + +Work the tree in **rounds**. The **frontier** is every decision whose prerequisites are already settled: the questions you can ask _now_ without guessing at answers you haven't heard yet. Ask the whole frontier in one round: number each question and give your recommended answer. Then wait for the user's answers before the next round. + +Format a round like so: + +``` +❓ **Q1** - ****: + +➡️ + +--- + +❓ **Q2** - ****: + +➡️ +``` + +Each round the user answers reshapes the tree: settled decisions push the frontier outward and unblock questions that depended on them. Recompute the frontier and ask the next round. A question whose answer depends on another question still open in this round belongs to a _later_ round, not this one. + +Finding _facts_ is your job, never the user's. When a frontier question needs a fact from the environment (filesystem, tools, etc.), dispatch a sub-agent to find it; don't ask the user for anything you could look up yourself. Don't block on it: a running exploration is an unsettled prerequisite, so only the questions downstream of it wait for the sub-agent to report; ask the rest of the frontier now. The _decisions_ are the user's: put each to them and wait. + +The session is done when the frontier is empty: every branch of the design tree visited, nothing left silently assumed. Do not act on it until the user confirms you have reached a shared understanding. diff --git a/agents/skills/grilling/agents/openai.yaml b/agents/skills/grilling/agents/openai.yaml new file mode 100644 index 0000000..ddbdb96 --- /dev/null +++ b/agents/skills/grilling/agents/openai.yaml @@ -0,0 +1,3 @@ +interface: + display_name: "Grilling" + short_description: "Stress-test thinking a round of questions at a time" diff --git a/agents/skills/how/SKILL.md b/agents/skills/how/SKILL.md new file mode 100644 index 0000000..c156b76 --- /dev/null +++ b/agents/skills/how/SKILL.md @@ -0,0 +1,134 @@ +--- +name: how +description: "Use for \"how does X work\", code walkthroughs before changing something, and placement / ownership / layering questions (\"where should this live\", \"which package owns this\", \"is this the right layer\"). Explains subsystem architecture, runtime flow, onboarding mental models. Can critique architecture. Use why for motivation." +--- + +# How + +Explore the codebase to answer "how does X work?" questions. Produce clear architectural explanations at the level of a senior engineer onboarding onto a subsystem. Enough to build a working mental model, not annotated source code. + +Two modes: + +1. **Explain** (default). Explore the codebase and produce a clear explanation +2. **Critique.** Explain first, then spawn multiple models to independently identify architectural issues + +## Explain Mode + +### Step 1. Understand the Question and Assess Complexity + +Parse what the user is asking about: + +- "How does the rate limiter work?", a subsystem +- "How do we handle billing for on-demand usage?", a feature flow +- "How is the auth service structured?", an architectural overview +- "Walk me through what happens when a user submits a form", a runtime trace + +Identify the scope. If ambiguous, state your best-guess interpretation before exploring. Don't ask. Let the user redirect if you're off. + +**Assess complexity to decide the approach:** + +- **Simple** (a single module, a small utility, a narrow question like "how does function X work"): skip explorer agents; the explainer explores and explains in a single pass. Go to Step 2b. +- **Complex** (a subsystem spanning multiple files/services, a cross-cutting feature, a full architectural overview): spawn parallel explorer agents first, then hand off to the explainer. Go to Step 2a. + +When in doubt, lean simple. You can always spawn explorers if the explainer hits a wall. + +### Step 2a. Explore (complex questions only) + +Decompose the question into 2-4 parallel exploration angles, each a distinct slice of the subsystem so explorers don't duplicate work. Example split for "how does the rate limiter work?": + +- Explorer 1: data model and state management +- Explorer 2: request path and enforcement +- Explorer 3: configuration and metrics infrastructure + +The right decomposition depends on the question. Use your judgment. Narrow questions: 2 explorers is fine. Broad subsystems: up to 4. + +Spawn all explorers in a single message: + +- `subagent_type`: `generalPurpose` +- `model`: your configured how-explorer model (default `grok-4.6-fast-xhigh`) +- `readonly`: `true` + +Each explorer gets the same base prompt from `references/explorer-prompt.md` plus a specific exploration angle naming its slice. Each explorer should: +- Start broad: Glob for relevant directories, Grep for key types/interfaces/class names +- Follow the thread: from an entry point, trace the call chain (callers, callees, data flow, type definitions) +- Read the actual code, don't guess from file names +- Stop when it can describe the full path from input to output (or trigger to effect) without hand-waving any step +- Note things that are surprising, non-obvious, or that a newcomer would get wrong + +Each explorer returns structured findings: components found, flow traced, files read, anything non-obvious. Overlap between explorers is fine; the explainer reconciles. + +Then proceed to Step 3. + +### Step 2b. Direct Explain (simple questions) + +Spawn a single Task subagent that explores and explains in one pass: + +- `subagent_type`: `generalPurpose` +- `model`: your configured how-explainer model (default `claude-fable-5-thinking-max`) +- `readonly`: `true` + +The agent does its own exploration (Glob, Grep, Read) and writes the explanation directly. Read `references/explainer-prompt.md` for the communication style and output format. Same structure, just no explorer findings as input. + +Proceed to Step 4. + +### Step 3. Synthesize (complex questions only) + +Once all explorers return, spawn a single Task subagent to synthesize their findings into one coherent explanation: + +- `subagent_type`: `generalPurpose` +- `model`: your configured how-explainer model (default `claude-fable-5-thinking-max`) +- `readonly`: `true` + +The explainer gets all explorers' findings and writes the human-facing explanation (output format below). Read `references/explainer-prompt.md` for the full prompt template. The explainer reconciles overlapping findings, resolves contradictions, and weaves the slices into a unified picture. + +### Step 4. Present + +Present the explainer's output to the user. You may lightly edit for clarity or add context from the conversation, but don't substantially rewrite. The explainer's communication is the product. + +### Output Format + +Follow this structure, adapted to the question. Not every section is needed for every question. + +**Overview.** 1-2 paragraphs. What it is, what it does, why it exists. Enough to decide whether to keep reading. + +**Key Concepts.** The important types, services, or abstractions. Brief definition of each. Not exhaustive, just the ones needed to understand the rest. + +**How It Works.** The core of the explanation. Walk through the flow: what triggers it, what happens step by step, where data goes, the decision points. Prose, not pseudocode. Reference specific files and functions so the reader can go look, but don't dump code blocks unless a snippet is genuinely necessary. + +**Where Things Live.** A brief map of the relevant files/directories. Not every file, just the ones needed to start working in this area. + +**Gotchas.** Non-obvious or surprising things that would trip someone up. Historical context that explains why something looks weird. Known sharp edges. + +## Critique Mode + +Triggered when the user asks for architectural issues, problems, or improvements, not just understanding. + +### Step 1. Explain First + +Run the full explain flow above (Steps 1-4). You must understand the architecture before critiquing it. + +### Step 2. Spawn Critics + +After the explanation is complete, spawn one architectural critic per model in your configured how-critics list (defaults `claude-fable-5-thinking-max`, `gpt-5.6-sol-max`, `grok-4.6-fast-xhigh`, `claude-opus-5-thinking-xhigh`), all in a single message. + +For each critic: +- `subagent_type`: `generalPurpose` +- `model`: one model from the configured how-critics list. These are minimum reasoning levels. The lead should escalate any model when the architecture warrants deeper analysis. +- `readonly`: `true` + +Read `references/critic-prompt.md` for the prompt template. Each critic gets: +1. The explanation from Step 1 (so they don't re-explore) +2. The relevant file paths (so they can read the actual code) +3. The architectural critique rubric from `references/critique-rubric.md` + +### Step 3. Lead Judgment + +Same framework as the interrogate skill. You're a pragmatic lead, not an aggregator. + +Categorize findings: +- **Act on.** Architectural problems worth fixing now +- **Consider.** Real concerns, but the cost/benefit is unclear +- **Noted.** Valid observations, low priority +- **Dismissed.** Wrong, missing context, or style preference + +Present the explanation first (from Step 1), then the critique verdict below it. The explanation should stand on its own; someone who just wants to understand the system shouldn't wade through critique. diff --git a/agents/skills/how/references/critic-prompt.md b/agents/skills/how/references/critic-prompt.md new file mode 100644 index 0000000..e17298e --- /dev/null +++ b/agents/skills/how/references/critic-prompt.md @@ -0,0 +1,59 @@ +# Critic Prompt Template + +Build each critic subagent's prompt from this template. Fill in the placeholders. + +--- + +You are reviewing the architecture of a codebase subsystem. An explanation of how it works has already been written. Read it to orient yourself, then read the actual code to form your own judgment. + +## Architectural Explanation + +{EXPLANATION} + +## Relevant Files + +{FILE_PATHS} + +## Critique Rubric + +{CRITIQUE_RUBRIC_CONTENTS} + +## Instructions + +Read the files listed above. Use the explanation as a map, but form your own opinions from the code itself. The explanation might miss things or frame them charitably. + +Find architectural problems, not line-level bugs or style issues. Ask whether this subsystem is built well for what it needs to do and how it will need to evolve. + +For each finding: + +1. **Severity**: `structural` | `concern` | `observation` + - `structural`: a fundamental architectural problem. Wrong abstraction boundary, broken data model, coupling that will block future work + - `concern`: a real issue that makes the system harder to work with or reason about, but not fundamentally broken + - `observation`: worth noting. A tradeoff that might not age well, a pattern inconsistent with the rest of the codebase, technical debt +2. **Finding**: the architectural issue. Be specific. Name the components, the boundary, the coupling. +3. **Evidence**: concrete code that demonstrates the problem. Don't just assert that "this is too coupled". Show the dependency chain. +4. **Impact**: what the issue costs. Harder to test? Harder to change? Performance cliff at scale? Be concrete about the consequence. + +## What to Avoid + +- Line-level code review (not your job here) +- Suggesting rewrites without demonstrating a problem with the current approach +- "This could use more abstraction" without showing what the abstraction would actually solve +- Flagging intentional tradeoffs with clear benefits as issues + +If the architecture is sound, say so. An empty critique is a valid outcome. + +## Output + +``` +## Findings + +### 1. [Severity] Short title +**Components**: Which parts of the system are involved +**Finding**: What's wrong architecturally +**Evidence**: Concrete code references +**Impact**: What this costs in practice + +### 2. [Severity] Short title +... +``` diff --git a/agents/skills/how/references/critique-rubric.md b/agents/skills/how/references/critique-rubric.md new file mode 100644 index 0000000..b4d452f --- /dev/null +++ b/agents/skills/how/references/critique-rubric.md @@ -0,0 +1,58 @@ +# Architectural Critique Rubric + +Review through whichever of these lenses are relevant. Not every lens applies to every subsystem. + +## Abstraction Fit + +Are the abstractions pulling their weight? + +- Does each abstraction represent a real concept, or is it an indirection layer "in case we need it"? +- Are the boundaries in the right place? Do they separate things that change independently? +- Is there accidental coupling where components share implementation details they shouldn't need to know about? +- Is business logic entangled with framework wiring, or cleanly separated? + +Over-abstraction is as much a problem as under-abstraction. A flat, simple design is fine when the domain is simple. + +## Data Model + +Do the data structures fit the actual usage patterns? + +- Are the data models designed for how data is actually accessed, or for how it was conceptually modeled? +- Are there impedance mismatches, places where code constantly reshapes data because the model doesn't match the access pattern? +- Are types honest? Do they represent what data actually looks like at runtime, or claim more structure than exists? + +## Boundary Discipline + +Are system boundaries clean and well-placed? + +- Is validation concentrated at entry points, or scattered through internal code? +- Are errors handled at boundaries and propagated cleanly, or caught and re-thrown at every layer? +- Does data cross boundaries in well-typed shapes, or as bags of optional fields? +- Could this subsystem be tested in isolation, or does it require the entire system to be running? + +## Evolution Readiness + +How well will this architecture handle likely changes? + +- If the most probable next requirement landed tomorrow, how much would change? "One file" or "everything"? +- Are there hardcoded assumptions that would need to be relaxed? +- Is the design bolted-on (integrated as an afterthought) or integrated (looks like it was always part of the plan)? +- Are legacy paths preserved for compatibility that no one depends on? + +Don't penalize for not handling hypothetical changes. Focus on changes plausible given the codebase's trajectory. + +## Complexity vs. Value + +Is the complexity budget spent wisely? + +- Is complexity concentrated in the parts that need it (core logic, tricky invariants) or in accidental places (boilerplate, unnecessary indirection, configuration)? +- Are there simpler ways to achieve the same behavior? +- Does every component earn its existence, or are there vestigial pieces from an earlier design? + +## Consistency + +Does this subsystem follow the patterns established elsewhere in the codebase? + +- Are similar problems solved the same way here as elsewhere, or does this area invent its own patterns? +- If the patterns differ, is there a good reason, or did it just evolve independently? +- Inconsistency isn't automatically bad. But unexplained inconsistency is a maintenance burden. diff --git a/agents/skills/how/references/explainer-prompt.md b/agents/skills/how/references/explainer-prompt.md new file mode 100644 index 0000000..868c737 --- /dev/null +++ b/agents/skills/how/references/explainer-prompt.md @@ -0,0 +1,55 @@ +# Explainer Prompt Template + +Build the explainer subagent's prompt from this template. Fill in the placeholders. + +--- + +You are writing an architectural explanation for a senior engineer. Multiple explorer agents have traced different slices of the codebase in parallel and gathered findings. Synthesize their findings into one coherent, well-structured explanation. + +## Original Question + +> {QUESTION} + +## Explorer Findings + +{EXPLORER_FINDINGS_ALL} + +## Instructions + +The explorers each investigated a different angle of the same subsystem. Their findings will overlap in places and may occasionally contradict. Reconcile them. Merge overlapping descriptions, resolve contradictions by checking the code yourself, and weave the separate slices into a unified picture. + +Write an explanation a senior engineer unfamiliar with this area could read and walk away with a solid mental model, understanding the architecture well enough to start working in it confidently. + +You have read-only access to the codebase to check anything, clarify a detail, or fill a gap. Use Read, Grep, and Glob as needed. The explorers did the heavy lifting, so you shouldn't need to re-explore from scratch. + +## Output Format + +Use this structure, adapted to what makes sense for the question. Not every section is needed for every question. + +### Overview +1-2 paragraphs. What is this thing, what does it do, why does it exist. Someone should be able to read just this and decide whether to keep reading. + +### Key Concepts +The important types, services, or abstractions needed to follow the rest. Brief definitions, not exhaustive. + +### How It Works +The core of the explanation, and the longest section. Walk through the flow: what triggers it, what happens step by step, where data goes, what the decision points are. + +Use prose, not pseudocode. Reference specific files and functions so the reader knows where to look, but don't dump large code blocks unless a snippet is genuinely essential to a point. + +When the flow involves multiple components talking to each other, or data transforming through stages, include a diagram. Use mermaid (```mermaid) for structured flows (sequence diagrams, flowcharts, component graphs) or ASCII art for simpler relationships where mermaid would be overkill. Use your judgment. A diagram should clarify, not decorate. If prose covers the flow, skip the diagram. + +### Where Things Live +A brief file/directory map. Just the ones someone would need to start working here. + +### Gotchas +Non-obvious things, surprising behavior, historical context, sharp edges. Skip this section if there's nothing worth calling out. + +## Communication Style + +- Use concrete language, not abstractions-about-abstractions +- Say "the `UserService` calls `AuthClient.refresh()`" not "the service delegates to the client" +- When something is complex, explain why it's complex. Don't just describe the complexity +- When something is simple, don't pad it out +- If there's a helpful analogy, use it; if there isn't, don't force one +- If the explorers flagged open questions or gaps, acknowledge them honestly rather than papering over them diff --git a/agents/skills/how/references/explorer-prompt.md b/agents/skills/how/references/explorer-prompt.md new file mode 100644 index 0000000..8022827 --- /dev/null +++ b/agents/skills/how/references/explorer-prompt.md @@ -0,0 +1,52 @@ +# Explorer Prompt Template + +Build each explorer subagent's prompt from this template. Fill in the placeholders. + +--- + +You are exploring a codebase to understand how something works. Gather facts: trace code paths, read implementations, map components. A separate agent will write the human-facing explanation from your findings, so favor thoroughness and accuracy over prose. + +Other explorers are investigating different slices of the same subsystem in parallel. Don't try to cover everything. Focus on your assigned angle and go deep. + +## Question + +> {QUESTION} + +## Your Exploration Angle + +{EXPLORATION_ANGLE} + +## Exploration Instructions + +Start by finding the relevant code. Use Glob to find directories and files, Grep to find key symbols, Read to understand the actual implementation. Don't guess from names. Read the code. + +Follow this pattern: +1. **Find the entry point.** What triggers this behavior? A user action, an API call, a scheduled job? Find where it starts. +2. **Trace the flow.** Follow the call chain from the entry point. Read each function. Understand what data flows through and how it transforms. +3. **Map the key abstractions.** What types, interfaces, services, or classes are central? Read their definitions. Understand what they represent and why they exist. +4. **Find the boundaries.** Where does this subsystem interface with others? What goes in, what comes out? +5. **Look for the non-obvious.** Anything surprising? Anything that looks like a historical artifact? Anything a newcomer would misunderstand? + +Keep exploring until you can describe the full picture without hand-waving. If you hit a part you can't trace, say so explicitly. "I couldn't determine how X connects to Y" is better than making something up. + +## Output + +Return your findings in this structure. Be factual and specific. Reference exact file paths, function names, type names, and line numbers where relevant. + +### Components Found +The key types, services, classes, and abstractions. For each: name, file path, and a one-sentence description of what it does. + +### Flow +The execution flow step by step. For each step: what function/method runs, what file it's in, what it does, what it calls next. Include the data that flows between steps. + +### Files Read +Every file you read during exploration, so the explainer can reference them. + +### Boundaries +Where this subsystem connects to other parts of the codebase. The inputs and outputs. + +### Non-Obvious Things +Anything surprising, historically motivated, or easy to get wrong. Things that look like they should work one way but actually work another. + +### Open Questions +Anything you couldn't fully trace or understand. Be honest about gaps. diff --git a/agents/skills/improve-codebase-architecture/HTML-REPORT.md b/agents/skills/improve-codebase-architecture/HTML-REPORT.md new file mode 100644 index 0000000..e39e825 --- /dev/null +++ b/agents/skills/improve-codebase-architecture/HTML-REPORT.md @@ -0,0 +1,123 @@ +# HTML Report Format + +The architectural review is rendered as a single self-contained HTML file in the OS temp directory. Tailwind and Mermaid both come from CDNs. Mermaid handles graph-shaped diagrams reliably; hand-built divs and inline SVG handle the more editorial visuals (mass diagrams, cross-sections). Mix the two: don't lean on Mermaid for everything, it'll start to look generic. + +## Scaffold + +```html + + + + + Architecture review for {{repo name}} + + + + + +
+
...
+
...
+
...
+
+ + +``` + +## Header + +Repo name, date, and a compact legend: solid box = module, dashed line = seam, red arrow = leakage, thick dark box = deep module. No introduction paragraph. Straight into the candidates. + +## Candidate card + +The diagrams carry the weight. Prose is sparse, plain, and uses the glossary terms (from the `/codebase-design` skill) without ceremony. + +Each candidate is one `
`: + +- **Title**: short, names the deepening (e.g. "Collapse the Order intake pipeline"). +- **Badge row**: recommendation strength (`Strong` = emerald, `Worth exploring` = amber, `Speculative` = slate), plus a tag for the dependency category (`in-process`, `local-substitutable`, `ports & adapters`, `mock`). +- **Files**: monospaced list, `font-mono text-sm`. +- **Before / After diagram**: the centrepiece. Two columns, side by side. See patterns below. +- **Problem**: one sentence. What hurts. +- **Solution**: one sentence. What changes. +- **Wins**: bullets, ≤6 words each. e.g. "Tests hit one interface", "Pricing logic stops leaking", "Delete 4 shallow wrappers". +- **ADR callout** (if applicable): one line in an amber-tinted box. + +No paragraphs of explanation. If the diagram needs a paragraph to be understood, redraw the diagram. + +## Diagram patterns + +Pick the pattern that fits the candidate. Mix them. Don't make every diagram look the same. Variety is part of the point. + +### Mermaid graph (the workhorse for dependencies / call flow) + +Use a Mermaid `flowchart` or `graph` when the point is "X calls Y calls Z, and look at the mess." Wrap it in a Tailwind-styled card so it doesn't feel parachuted in. Style with classDef to colour leakage edges red and the deep module dark. Sequence diagrams work well for "before: 6 round-trips; after: 1." + +```html +
+
+    flowchart LR
+      A[OrderHandler] --> B[OrderValidator]
+      B --> C[OrderRepo]
+      C -.leak.-> D[PricingClient]
+      classDef leak stroke:#dc2626,stroke-width:2px;
+      class C,D leak
+  
+
+``` + +### Hand-built boxes-and-arrows (when Mermaid's layout fights you) + +Modules as `
`s with borders and labels. Arrows as inline SVG `` or `` elements positioned absolutely over a relative container. Reach for this when you want the "after" diagram to feel like one thick-bordered deep module with greyed-out internals, since Mermaid won't render that with the right weight. + +### Cross-section (good for layered shallowness) + +Stack horizontal bands (`h-12 border-l-4`) to show layers a call passes through. Before: 6 thin layers each doing nothing. After: 1 thick band labelled with the consolidated responsibility. + +### Mass diagram (good for "interface as wide as implementation") + +Two rectangles per module: one for interface surface area, one for implementation. Before: interface rectangle is nearly as tall as the implementation rectangle (shallow). After: interface rectangle is short, implementation rectangle is tall (deep). + +### Call-graph collapse + +Before: a tree of function calls rendered as nested boxes. After: the same tree collapsed into one box, with the now-internal calls shown faded inside it. + +## Style guidance + +- Lean editorial, not corporate-dashboard. Generous whitespace. Serif optional for headings (`font-serif` works well with stone/slate). +- Colour sparingly: one accent (emerald or indigo) plus red for leakage and amber for warnings. +- Keep diagrams ~320px tall so before/after sits comfortably side by side without scrolling. +- Use `text-xs uppercase tracking-wider` for module labels inside diagrams, so they read as schematic, not as UI. +- The only scripts are the Tailwind CDN and the Mermaid ESM import. The report is otherwise static: no app code, no interactivity beyond Mermaid's own rendering. + +## Top recommendation section + +One larger card. Candidate name, one sentence on why, anchor link to its card. That's it. + +## Tone + +Plain English, concise, but the architectural nouns and verbs come straight from the `/codebase-design` skill. Concision is not an excuse to drift. + +**Use exactly:** module, interface, implementation, depth, deep, shallow, seam, adapter, leverage, locality. + +**Never substitute:** component, service, unit (for module) · API, signature (for interface) · boundary (for seam) · layer, wrapper (for module, when you mean module). + +**Phrasings that fit the style:** + +- "Order intake module is shallow: interface nearly matches the implementation." +- "Pricing leaks across the seam." +- "Deepen: one interface, one place to test." +- "Two adapters justify the seam: HTTP in prod, in-memory in tests." + +**Wins bullets** name the gain in glossary terms: *"locality: bugs concentrate in one module"*, *"leverage: one interface, N call sites"*, *"interface shrinks; implementation absorbs the wrappers"*. Don't write *"easier to maintain"* or *"cleaner code"*, because those terms aren't in the glossary and don't earn their place. + +No hedging, no throat-clearing, no "it's worth noting that…". If a sentence could be a bullet, make it a bullet. If a bullet could be cut, cut it. If a term isn't in the `/codebase-design` glossary, reach for one that is before inventing a new one. diff --git a/agents/skills/improve-codebase-architecture/LANGUAGE.md b/agents/skills/improve-codebase-architecture/LANGUAGE.md deleted file mode 100644 index 530c276..0000000 --- a/agents/skills/improve-codebase-architecture/LANGUAGE.md +++ /dev/null @@ -1,53 +0,0 @@ -# Language - -Shared vocabulary for every suggestion this skill makes. Use these terms exactly — don't substitute "component," "service," "API," or "boundary." Consistent language is the whole point. - -## Terms - -**Module** -Anything with an interface and an implementation. Deliberately scale-agnostic — applies equally to a function, class, package, or tier-spanning slice. -_Avoid_: unit, component, service. - -**Interface** -Everything a caller must know to use the module correctly. Includes the type signature, but also invariants, ordering constraints, error modes, required configuration, and performance characteristics. -_Avoid_: API, signature (too narrow — those refer only to the type-level surface). - -**Implementation** -What's inside a module — its body of code. Distinct from **Adapter**: a thing can be a small adapter with a large implementation (a Postgres repo) or a large adapter with a small implementation (an in-memory fake). Reach for "adapter" when the seam is the topic; "implementation" otherwise. - -**Depth** -Leverage at the interface — the amount of behaviour a caller (or test) can exercise per unit of interface they have to learn. A module is **deep** when a large amount of behaviour sits behind a small interface. A module is **shallow** when the interface is nearly as complex as the implementation. - -**Seam** _(from Michael Feathers)_ -A place where you can alter behaviour without editing in that place. The *location* at which a module's interface lives. Choosing where to put the seam is its own design decision, distinct from what goes behind it. -_Avoid_: boundary (overloaded with DDD's bounded context). - -**Adapter** -A concrete thing that satisfies an interface at a seam. Describes *role* (what slot it fills), not substance (what's inside). - -**Leverage** -What callers get from depth. More capability per unit of interface they have to learn. One implementation pays back across N call sites and M tests. - -**Locality** -What maintainers get from depth. Change, bugs, knowledge, and verification concentrate at one place rather than spreading across callers. Fix once, fixed everywhere. - -## Principles - -- **Depth is a property of the interface, not the implementation.** A deep module can be internally composed of small, mockable, swappable parts — they just aren't part of the interface. A module can have **internal seams** (private to its implementation, used by its own tests) as well as the **external seam** at its interface. -- **The deletion test.** Imagine deleting the module. If complexity vanishes, the module wasn't hiding anything (it was a pass-through). If complexity reappears across N callers, the module was earning its keep. -- **The interface is the test surface.** Callers and tests cross the same seam. If you want to test *past* the interface, the module is probably the wrong shape. -- **One adapter means a hypothetical seam. Two adapters means a real one.** Don't introduce a seam unless something actually varies across it. - -## Relationships - -- A **Module** has exactly one **Interface** (the surface it presents to callers and tests). -- **Depth** is a property of a **Module**, measured against its **Interface**. -- A **Seam** is where a **Module**'s **Interface** lives. -- An **Adapter** sits at a **Seam** and satisfies the **Interface**. -- **Depth** produces **Leverage** for callers and **Locality** for maintainers. - -## Rejected framings - -- **Depth as ratio of implementation-lines to interface-lines** (Ousterhout): rewards padding the implementation. We use depth-as-leverage instead. -- **"Interface" as the TypeScript `interface` keyword or a class's public methods**: too narrow — interface here includes every fact a caller must know. -- **"Boundary"**: overloaded with DDD's bounded context. Say **seam** or **interface**. diff --git a/agents/skills/improve-codebase-architecture/SKILL.md b/agents/skills/improve-codebase-architecture/SKILL.md index 05984a6..a578dd0 100644 --- a/agents/skills/improve-codebase-architecture/SKILL.md +++ b/agents/skills/improve-codebase-architecture/SKILL.md @@ -1,71 +1,71 @@ --- name: improve-codebase-architecture -description: Find deepening opportunities in a codebase, informed by the domain language in CONTEXT.md and the decisions in docs/adr/. Use when the user wants to improve architecture, find refactoring opportunities, consolidate tightly-coupled modules, or make a codebase more testable and AI-navigable. +description: Scan a codebase for deepening opportunities, present them as a visual HTML report, then grill through whichever one you pick. +disable-model-invocation: true --- # Improve Codebase Architecture -Surface architectural friction and propose **deepening opportunities** — refactors that turn shallow modules into deep ones. The aim is testability and AI-navigability. +Surface architectural friction and propose **deepening opportunities**: refactors that turn shallow modules into deep ones. The aim is testability and AI-navigability. -## Glossary +This command is _informed_ by the project's domain model and built on a shared design vocabulary: -Use these terms exactly in every suggestion. Consistent language is the point — don't drift into "component," "service," "API," or "boundary." Full definitions in [LANGUAGE.md](LANGUAGE.md). - -- **Module** — anything with an interface and an implementation (function, class, package, slice). -- **Interface** — everything a caller must know to use the module: types, invariants, error modes, ordering, config. Not just the type signature. -- **Implementation** — the code inside. -- **Depth** — leverage at the interface: a lot of behaviour behind a small interface. **Deep** = high leverage. **Shallow** = interface nearly as complex as the implementation. -- **Seam** — where an interface lives; a place behaviour can be altered without editing in place. (Use this, not "boundary.") -- **Adapter** — a concrete thing satisfying an interface at a seam. -- **Leverage** — what callers get from depth. -- **Locality** — what maintainers get from depth: change, bugs, knowledge concentrated in one place. - -Key principles (see [LANGUAGE.md](LANGUAGE.md) for the full list): - -- **Deletion test**: imagine deleting the module. If complexity vanishes, it was a pass-through. If complexity reappears across N callers, it was earning its keep. -- **The interface is the test surface.** -- **One adapter = hypothetical seam. Two adapters = real seam.** - -This skill is _informed_ by the project's domain model. The domain language gives names to good seams; ADRs record decisions the skill should not re-litigate. +- Call the Skill tool with "codebase-design" for the architecture vocabulary (**module**, **interface**, **depth**, **seam**, **adapter**, **leverage**, **locality**) and its principles (the deletion test, "the interface is the test surface", "one adapter = hypothetical seam, two = real"). Use these terms exactly in every suggestion, and don't drift into "component," "service," "API," or "boundary." +- The domain language in `CONTEXT.md` gives names to good seams; ADRs in `docs/adr/` record decisions this command should not re-litigate. ## Process ### 1. Explore -Read the project's domain glossary and any ADRs in the area you're touching first. +**Scope before you scan: YAGNI.** Deepening a module pays off by making future changes to it easier, so put extra weight on the parts of the codebase that have recently changed. Decide *where* to look before you look: -Then use the Agent tool with `subagent_type=Explore` to walk the codebase. Don't follow rigid heuristics — explore organically and note where you experience friction: +- If the user named a direction (a module, a subsystem, a pain point), take it, and skip the inference below. +- Otherwise, walk back a good stretch of the commit history (`git log --oneline`) to find the codebase's hot spots, the files and areas that keep coming up, and let those paths pull your attention first. If the changes are scattered with no clear hot spot, widen the net. + +Read the project's domain glossary (`CONTEXT.md`) and any ADRs in the area you're touching first. + +Then spawn a sub-agent to walk the codebase. Don't follow rigid heuristics; explore organically and note where you experience friction: - Where does understanding one concept require bouncing between many small modules? -- Where are modules **shallow** — interface nearly as complex as the implementation? +- Where are modules **shallow**, with an interface nearly as complex as the implementation? - Where have pure functions been extracted just for testability, but the real bugs hide in how they're called (no **locality**)? - Where do tightly-coupled modules leak across their seams? - Which parts of the codebase are untested, or hard to test through their current interface? Apply the **deletion test** to anything you suspect is shallow: would deleting it concentrate complexity, or just move it? A "yes, concentrates" is the signal you want. -### 2. Present candidates +### 2. Present candidates as an HTML report -Present a numbered list of deepening opportunities. For each candidate: +Write a self-contained HTML file to the OS temp directory so nothing lands in the repo. Resolve the temp dir from `$TMPDIR`, falling back to `/tmp` (or `%TEMP%` on Windows), and write to `/architecture-review-.html` so each run gets a fresh file. Open it for the user (`xdg-open ` on Linux, `open ` on macOS, `start ` on Windows) and tell them the absolute path. -- **Files** — which files/modules are involved -- **Problem** — why the current architecture is causing friction -- **Solution** — plain English description of what would change -- **Benefits** — explained in terms of locality and leverage, and also in how tests would improve +The report uses **Tailwind via CDN** for layout and styling, and **Mermaid via CDN** for diagrams where a graph/flow/sequence reliably communicates the structure. Mix Mermaid with hand-crafted CSS/SVG visuals: use Mermaid when relationships are graph-shaped (call graphs, dependencies, sequences), and hand-built divs/SVG when you want something more editorial (mass diagrams, cross-sections, collapse animations). Each candidate gets a **before/after visualisation**. Be visual. -**Use CONTEXT.md vocabulary for the domain, and [LANGUAGE.md](LANGUAGE.md) vocabulary for the architecture.** If `CONTEXT.md` defines "Order," talk about "the Order intake module" — not "the FooBarHandler," and not "the Order service." +For each candidate, render a card with: -**ADR conflicts**: if a candidate contradicts an existing ADR, only surface it when the friction is real enough to warrant revisiting the ADR. Mark it clearly (e.g. _"contradicts ADR-0007 — but worth reopening because…"_). Don't list every theoretical refactor an ADR forbids. +- **Files**: which files/modules are involved +- **Problem**: why the current architecture is causing friction +- **Solution**: plain English description of what would change +- **Benefits**: explained in terms of locality and leverage, and how tests would improve +- **Before / After diagram**: side-by-side, custom-drawn, illustrating the shallowness and the deepening +- **Recommendation strength**: one of `Strong`, `Worth exploring`, `Speculative`, rendered as a badge -Do NOT propose interfaces yet. Ask the user: "Which of these would you like to explore?" +End the report with a **Top recommendation** section: which candidate you'd tackle first and why. + +**Use CONTEXT.md vocabulary for the domain, and the `/codebase-design` vocabulary for the architecture.** If `CONTEXT.md` defines "Order," talk about "the Order intake module," not "the FooBarHandler," and not "the Order service." + +**ADR conflicts**: if a candidate contradicts an existing ADR, only surface it when the friction is real enough to warrant revisiting the ADR. Mark it clearly in the card (e.g. a warning callout: _"contradicts ADR-0007, but worth reopening because…"_). Don't list every theoretical refactor an ADR forbids. + +See [HTML-REPORT.md](HTML-REPORT.md) for the full HTML scaffold, diagram patterns, and styling guidance. + +Do NOT propose interfaces yet. After the file is written, ask the user: "Which of these would you like to explore?" ### 3. Grilling loop -Once the user picks a candidate, drop into a grilling conversation. Walk the design tree with them — constraints, dependencies, the shape of the deepened module, what sits behind the seam, what tests survive. +Once the user picks a candidate, call the Skill tool with "grilling" to walk the decision tree with them: constraints, dependencies, the shape of the deepened module, what sits behind the seam, what tests survive. -Side effects happen inline as decisions crystallize: +Side effects happen inline as decisions crystallize; call the Skill tool with "domain-modeling" to keep the domain model current as you go: -- **Naming a deepened module after a concept not in `CONTEXT.md`?** Add the term to `CONTEXT.md` — same discipline as `/grill-with-docs` (see [CONTEXT-FORMAT.md](../grill-with-docs/CONTEXT-FORMAT.md)). Create the file lazily if it doesn't exist. +- **Naming a deepened module after a concept not in `CONTEXT.md`?** Add the term to `CONTEXT.md`. Create the file lazily if it doesn't exist. - **Sharpening a fuzzy term during the conversation?** Update `CONTEXT.md` right there. -- **User rejects the candidate with a load-bearing reason?** Offer an ADR, framed as: _"Want me to record this as an ADR so future architecture reviews don't re-suggest it?"_ Only offer when the reason would actually be needed by a future explorer to avoid re-suggesting the same thing — skip ephemeral reasons ("not worth it right now") and self-evident ones. See [ADR-FORMAT.md](../grill-with-docs/ADR-FORMAT.md). -- **Want to explore alternative interfaces for the deepened module?** See [INTERFACE-DESIGN.md](INTERFACE-DESIGN.md). +- **User rejects the candidate with a load-bearing reason?** Offer an ADR, framed as: _"Want me to record this as an ADR so future architecture reviews don't re-suggest it?"_ Only offer when the reason would actually be needed by a future explorer to avoid re-suggesting the same thing; skip ephemeral reasons ("not worth it right now") and self-evident ones. +- **Want to explore alternative interfaces for the deepened module?** Call the Skill tool with "codebase-design" and use its design-it-twice parallel sub-agent pattern. diff --git a/agents/skills/improve-codebase-architecture/agents/openai.yaml b/agents/skills/improve-codebase-architecture/agents/openai.yaml new file mode 100644 index 0000000..706fdca --- /dev/null +++ b/agents/skills/improve-codebase-architecture/agents/openai.yaml @@ -0,0 +1,5 @@ +interface: + display_name: "Improve Codebase Architecture" + short_description: "Find and grill architecture improvements" +policy: + allow_implicit_invocation: false diff --git a/agents/skills/oh-my-mermaid b/agents/skills/oh-my-mermaid deleted file mode 120000 index aaba546..0000000 --- a/agents/skills/oh-my-mermaid +++ /dev/null @@ -1 +0,0 @@ -/Users/johannes/.local/share/mise/installs/node/25.6.0/lib/node_modules/oh-my-mermaid/skills \ No newline at end of file diff --git a/agents/skills/ponytail-audit/SKILL.md b/agents/skills/ponytail-audit/SKILL.md deleted file mode 100644 index 5582d10..0000000 --- a/agents/skills/ponytail-audit/SKILL.md +++ /dev/null @@ -1,41 +0,0 @@ ---- -name: ponytail-audit -description: > - Whole-repo audit for over-engineering. Like ponytail-review, but scans the - entire codebase instead of a diff: a ranked list of what to delete, simplify, - or replace with stdlib/native equivalents. Use when the user says "audit this - codebase", "audit for over-engineering", "what can I delete from this repo", - "find bloat", "ponytail-audit", or "/ponytail-audit". One-shot report, does - not apply fixes. ---- - -ponytail-review, repo-wide. Scan the whole tree instead of a diff. Rank -findings biggest cut first. - -## Tags - -Same as ponytail-review: - -- `delete:` dead code, unused flexibility, speculative feature. Replacement: nothing. -- `stdlib:` hand-rolled thing the standard library ships. Name the function. -- `native:` dependency or code doing what the platform already does. Name the feature. -- `yagni:` abstraction with one implementation, config nobody sets, layer with one caller. -- `shrink:` same logic, fewer lines. Show the shorter form. - -## Hunt - -Deps the stdlib or platform already ships, single-implementation interfaces, -factories with one product, wrappers that only delegate, files exporting one -thing, dead flags and config, hand-rolled stdlib. - -## Output - -One line per finding, ranked: ` . . [path]`. -End with `net: - lines, - deps possible.` Nothing to cut: `Lean already. Ship.` - -## Boundaries - -Scope: over-engineering and complexity only. Correctness bugs, security holes, -and performance are explicitly out of scope. Route them to a normal review -pass. Lists findings, applies nothing. One-shot. -"stop ponytail-audit" or "normal mode" to revert. diff --git a/agents/skills/ponytail-debt/SKILL.md b/agents/skills/ponytail-debt/SKILL.md deleted file mode 100644 index ecbc0ca..0000000 --- a/agents/skills/ponytail-debt/SKILL.md +++ /dev/null @@ -1,44 +0,0 @@ ---- -name: ponytail-debt -description: > - Harvest every `ponytail:` comment in the codebase into a debt ledger, so the - deliberate shortcuts and deferrals ponytail leaves behind get tracked instead - of rotting into "later means never". Use when the user says "ponytail debt", - "/ponytail-debt", "what did ponytail defer", "list the shortcuts", "ponytail - ledger", or "what did we mark to do later". One-shot report, changes nothing. ---- - -Every deliberate ponytail shortcut is marked with a `ponytail:` comment naming -its ceiling and upgrade path. This collects them into one ledger so a deferral -can't quietly become permanent. - -## Scan - -Grep the repo for comment markers, skipping `node_modules`, `.git`, and build -output: - -`grep -rnE '(#|//) ?ponytail:' .` (add other comment prefixes if your stack uses them) - -Each hit is one ledger row. The comment prefix keeps prose that merely mentions -the convention out of the ledger. - -## Output - -One row per marker, grouped by file: - -`:, . ceiling: . upgrade: .` - -The convention is `ponytail: , `, so pull the ceiling -and the trigger straight from the comment. Want an owner per row too? add -`git blame -L,`. - -Flag the rot risk: any `ponytail:` comment that names no upgrade path or -trigger gets a `no-trigger` tag, those are the ones that silently rot. - -End with ` markers, with no trigger.` Nothing found: `No ponytail: debt. Clean ledger.` - -## Boundaries - -Reads and reports only, changes nothing. To persist it, ask and it writes the -ledger to a file (e.g. `PONYTAIL-DEBT.md`). One-shot. "stop ponytail-debt" or -"normal mode" to revert. diff --git a/agents/skills/ponytail-gain/SKILL.md b/agents/skills/ponytail-gain/SKILL.md deleted file mode 100644 index 012e37b..0000000 --- a/agents/skills/ponytail-gain/SKILL.md +++ /dev/null @@ -1,50 +0,0 @@ ---- -name: ponytail-gain -description: > - Show ponytail's measured impact as a compact scoreboard: less code, less - cost, more speed, from the benchmark medians. One-shot display, not a - persistent mode, and not a per-repo number. Trigger: /ponytail-gain, - "ponytail gain", "what does ponytail save", "show ponytail impact", - "ponytail scoreboard". ---- - -# Ponytail Gain - -Display this scoreboard when invoked. One-shot: do NOT change mode, write flag -files, or persist anything. - -The figures are the published benchmark medians (5 everyday tasks: email -validator, debounce, CSV sum, countdown timer, rate limiter; three models: -Haiku, Sonnet, Opus). They are measured, not computed from the current repo. -Source: `benchmarks/` and the README. - -## Scoreboard - -Render plain ASCII bars. The bar length shows the measured range; the label -carries the exact figure: - -``` - ponytail gain benchmark median · 5 tasks · 3 models - - Lines of code no-skill ████████████████████ 100% - ponytail ██▌················· 6–20% ▼ 80–94% - Cost no-skill ████████████████████ 100% - ponytail █████▌·············· 23–53% ▼ 47–77% - Speed ponytail ▸ 3–6× faster - - This repo: /ponytail-debt (shortcuts you deferred) - /ponytail-audit (what's still cuttable) -``` - -## Honesty boundary - -These are benchmark medians, not this repo. NEVER print a per-repo savings -number ("you saved X lines/tokens here"): the unbuilt version was never -written, so there is no real baseline to subtract from in a live repo. The -only real per-repo figures come from `/ponytail-debt` (a counted ledger), and -this card points there instead of inventing one. - -## Boundaries - -One-shot display. Edits nothing, changes no mode. -"stop ponytail" or "normal mode": revert. diff --git a/agents/skills/ponytail-help/SKILL.md b/agents/skills/ponytail-help/SKILL.md deleted file mode 100644 index 7e096bf..0000000 --- a/agents/skills/ponytail-help/SKILL.md +++ /dev/null @@ -1,69 +0,0 @@ ---- -name: ponytail-help -description: > - Quick-reference card for all ponytail modes, skills, and commands. - One-shot display, not a persistent mode. Trigger: /ponytail-help, - "ponytail help", "what ponytail commands", "how do I use ponytail". ---- - -# Ponytail Help - -Display this reference card when invoked. One-shot, do NOT change mode, -write flag files, or persist anything. - -## Levels - -| Level | Trigger | What change | -|-------|---------|-------------| -| **Lite** | `/ponytail lite` | Build what's asked, name the lazier alternative in one line. | -| **Full** | `/ponytail` | The ladder enforced: YAGNI → stdlib → native → one line → minimum. Default. | -| **Ultra** | `/ponytail ultra` | YAGNI extremist. Deletion before addition. Challenges requirements before building. | - -Level sticks until changed or session end. - -## Skills - -| Skill | Trigger | What it does | -|-------|---------|--------------| -| **ponytail** | `/ponytail` | Lazy mode itself. Simplest solution that works. | -| **ponytail-review** | `/ponytail-review` | Over-engineering review: `L42: yagni: factory, one product. Inline.` | -| **ponytail-gain** | `/ponytail-gain` | Measured-impact scoreboard: less code, less cost, more speed. | -| **ponytail-help** | `/ponytail-help` | This card. | - -Codex uses `@ponytail`, `@ponytail-review`, and `@ponytail-help`; Claude Code -and OpenCode use the slash-command forms above (OpenCode ships `/ponytail` and -`/ponytail-review`). - -## Deactivate - -Say "stop ponytail" or "normal mode". Resume anytime with `/ponytail`. -`/ponytail off` also works. - -## Configure Default Mode - -Default mode = `full`, auto-active every session. Change it: - -**Environment variable** (highest priority): -```bash -export PONYTAIL_DEFAULT_MODE=ultra -``` - -**Config file** (`~/.config/ponytail/config.json`, Windows: `%APPDATA%\ponytail\config.json`): -```json -{ "defaultMode": "lite" } -``` - -Set `"off"` to disable auto-activation on session start, activate manually -with `/ponytail` when wanted. - -Resolution: env var > config file > `full`. - -## Update - -Enable auto-update once: open `/plugin`, go to Marketplaces, pick ponytail, Enable auto-update. Claude Code then pulls new versions at startup (run `/reload-plugins` when it prompts). Manual refresh: `/plugin marketplace update ponytail` then `/reload-plugins`. - -If `/plugin` is not recognized, your Claude Code is out of date. Update it (`npm install -g @anthropic-ai/claude-code@latest`, or `brew upgrade claude-code`) and restart. Other hosts use their own update flow. - -## More - -Full docs + examples: https://github.com/DietrichGebert/ponytail diff --git a/agents/skills/ponytail-review/SKILL.md b/agents/skills/ponytail-review/SKILL.md deleted file mode 100644 index e137a85..0000000 --- a/agents/skills/ponytail-review/SKILL.md +++ /dev/null @@ -1,57 +0,0 @@ ---- -name: ponytail-review -description: > - Code review focused exclusively on over-engineering. Finds what to delete: - reinvented standard library, unneeded dependencies, speculative abstractions, - dead flexibility. One line per finding: location, what to cut, what replaces - it. Use when the user says "review for over-engineering", "what can we - delete", "is this over-engineered", "simplify review", or invokes - /ponytail-review. Complements correctness-focused review, this one only - hunts complexity. ---- - -Review diffs for unnecessary complexity. One line per finding: location, what -to cut, what replaces it. The diff's best outcome is getting shorter. - -## Format - -`L: . .`, or `:L: ...` for -multi-file diffs. - -Tags: - -- `delete:` dead code, unused flexibility, speculative feature. Replacement: nothing. -- `stdlib:` hand-rolled thing the standard library ships. Name the function. -- `native:` dependency or code doing what the platform already does. Name the feature. -- `yagni:` abstraction with one implementation, config nobody sets, layer with one caller. -- `shrink:` same logic, fewer lines. Show the shorter form. - -## Examples - -❌ "This EmailValidator class might be more complex than necessary, have you -considered whether all these validation rules are needed at this stage?" - -✅ `L12-38: stdlib: 27-line validator class. "@" in email, 1 line, real validation is the confirmation mail.` - -✅ `L4: native: moment.js imported for one format call. Intl.DateTimeFormat, 0 deps.` - -✅ `repo.py:L88: yagni: AbstractRepository with one implementation. Inline it until a second one exists.` - -✅ `L52-71: delete: retry wrapper around an idempotent local call. Nothing replaces it.` - -✅ `L30-44: shrink: manual loop builds dict. dict(zip(keys, values)), 1 line.` - -## Scoring - -End with the only metric that matters: `net: - lines possible.` - -If there is nothing to cut, say `Lean already. Ship.` and stop. - -## Boundaries - -Scope: over-engineering and complexity only. Correctness bugs, security holes, -and performance are explicitly out of scope. Route them to a normal review -pass, not this one. A single smoke test or `assert`-based -self-check is the ponytail minimum, not bloat, never flag it for deletion. -Does not apply the fixes, only lists them. -"stop ponytail-review" or "normal mode": revert to verbose review style. diff --git a/agents/skills/ponytail/SKILL.md b/agents/skills/ponytail/SKILL.md deleted file mode 100644 index ee895f6..0000000 --- a/agents/skills/ponytail/SKILL.md +++ /dev/null @@ -1,117 +0,0 @@ ---- -name: ponytail -description: > - Forces the laziest solution that actually works, simplest, shortest, most - minimal. Channels a senior dev who has seen everything: question whether the - task needs to exist at all (YAGNI), reach for the standard library before - custom code, native platform features before dependencies, one line before - fifty. Supports intensity levels: lite, full (default), ultra. Use whenever - the user says "ponytail", "be lazy", "lazy mode", "simplest solution", - "minimal solution", "yagni", "do less", or "shortest path", and whenever - they complain about over-engineering, bloat, boilerplate, or unnecessary - dependencies. -argument-hint: "[lite|full|ultra]" -license: MIT ---- - -# Ponytail - -You are a lazy senior developer. Lazy means efficient, not careless. You have -seen every over-engineered codebase and been paged at 3am for one. The best -code is the code never written. - -## Persistence - -ACTIVE EVERY RESPONSE. No drift back to over-building. Still active if -unsure. Off only: "stop ponytail" / "normal mode". Default: **full**. -Switch: `/ponytail lite|full|ultra`. - -## The ladder - -Stop at the first rung that holds: - -1. **Does this need to exist at all?** Speculative need = skip it, say so in one line. (YAGNI) -2. **Already in this codebase?** A helper, util, type, or pattern that already lives here → reuse it. Look before you write; re-implementing what's a few files over is the most common slop. -3. **Stdlib does it?** Use it. -4. **Native platform feature covers it?** `` over a picker lib, CSS over JS, DB constraint over app code. -5. **Already-installed dependency solves it?** Use it. Never add a new one for what a few lines can do. -6. **Can it be one line?** One line. -7. **Only then:** the minimum code that works. - -The ladder is a reflex, not a research project — but it runs *after* you -understand the problem, not instead of it. Read the task and the code it -touches first, trace the real flow end to end, then climb. Two rungs work → -take the higher one and move on. The first lazy solution that works is the -right one — once you actually know what the change has to touch. - -**Bug fix = root cause, not symptom.** A report names a symptom. Before you -edit, grep every caller of the function you're about to touch. The lazy fix IS -the root-cause fix: one guard in the shared function is a smaller diff than a -guard in every caller — and patching only the path the ticket names leaves -every sibling caller still broken. Fix it once, where all callers route through. - -## Rules - -- No unrequested abstractions: no interface with one implementation, no factory for one product, no config for a value that never changes. -- No boilerplate, no scaffolding "for later", later can scaffold for itself. -- Deletion over addition. Boring over clever, clever is what someone decodes at 3am. -- Fewest files possible. Shortest working diff wins — but only once you understand the problem. The smallest change in the wrong place isn't lazy, it's a second bug. -- Complex request? Ship the lazy version and question it in the same response, "Did X; Y covers it. Need full X? Say so." Never stall on an answer you can default. -- Two stdlib options, same size? Take the one that's correct on edge cases. Lazy means writing less code, not picking the flimsier algorithm. -- Mark deliberate simplifications with a `ponytail:` comment (`// ponytail: this exists`), simple reads as intent, not ignorance. Shortcut with a known ceiling (global lock, O(n²) scan, naive heuristic)? The comment names the ceiling and the upgrade path: `# ponytail: global lock, per-account locks if throughput matters`. - -## Output - -Code first. Then at most three short lines: what was skipped, when to add it. -No essays, no feature tours, no design notes. If the explanation is longer -than the code, delete the explanation, every paragraph defending a -simplification is complexity smuggled back in as prose. Explanation the user -explicitly asked for (a report, a walkthrough, per-phase notes) is not debt, -give it in full, the rule is only against unrequested prose. - -Pattern: `[code] → skipped: [X], add when [Y].` - -## Intensity - -| Level | What change | -|-------|------------| -| **lite** | Build what's asked, but name the lazier alternative in one line. User picks. | -| **full** | The ladder enforced. Stdlib and native first. Shortest diff, shortest explanation. Default. | -| **ultra** | YAGNI extremist. Deletion before addition. Ship the one-liner and challenge the rest of the requirement in the same breath. | - -Example: "Add a cache for these API responses." -- lite: "Done, cache added. FYI: `functools.lru_cache` covers this in one line if you'd rather not own a cache class." -- full: "`@lru_cache(maxsize=1000)` on the fetch function. Skipped custom cache class, add when lru_cache measurably falls short." -- ultra: "No cache until a profiler says so. When it does: `@lru_cache`. A hand-rolled TTL cache class is a bug farm with a hit rate." - -## When NOT to be lazy - -Never simplify away: input validation at trust boundaries, error handling -that prevents data loss, security measures, accessibility basics, anything -explicitly requested. User insists on the full version → build it, no -re-arguing. - -Never lazy about understanding the problem. The ladder shortens the -solution, never the reading. Trace the whole thing first — every file the -change touches, the actual flow — before picking a rung. Laziness that skips -comprehension to ship a small diff is the dangerous kind: it dresses up as -efficiency and ships a confident wrong fix. Read fully, then be lazy. - -Hardware is never the ideal on paper: a real clock drifts, a real sensor -reads off, a PCA9685 runs a few percent fast. Leave the calibration knob, not -just less code, the physical world needs tuning a minimal model can't see. - -Lazy code without its check is unfinished. Non-trivial logic (a branch, a -loop, a parser, a money/security path) leaves ONE runnable check behind, the -smallest thing that fails if the logic breaks: an `assert`-based -`demo()`/`__main__` self-check or one small `test_*.py`. No frameworks, no -fixtures, no per-function suites unless asked. Trivial one-liners need no -test, YAGNI applies to tests too. - -## Boundaries - -Ponytail governs what you build, not how you talk (pair with Caveman for -terse prose). "stop ponytail" / "normal mode": revert. Level persists until -changed or session end. - -The shortest path to done is the right path. diff --git a/agents/skills/prototype/LOGIC.md b/agents/skills/prototype/LOGIC.md new file mode 100644 index 0000000..32be86a --- /dev/null +++ b/agents/skills/prototype/LOGIC.md @@ -0,0 +1,67 @@ +# Logic Prototype + +A single, self-contained HTML file (a **shareable demo**) that lets anyone drive a state model by clicking buttons. Use this when the question is about **business logic, state transitions, or data shape**: the kind of thing that looks reasonable on paper but only feels wrong once you push it through real cases. + +Because it's one file with nothing to install, you can hand it to a non-developer (a designer, a PM, a domain expert) and let them feel the model for themselves. So it speaks their language, not the code's. + +## When this is the right shape + +- "I'm not sure if this state machine handles the edge case where X then Y." +- "Does this data model actually let me represent the case where..." +- "I want to feel out what the API should look like before writing it." +- Anything where someone wants to **press buttons and watch state change**. + +If the question is "what should this look like," this is the wrong branch. Use [UI.md](UI.md). + +## Process + +### 1. State the question + +Before writing code, write down what state model and what question you're prototyping. One paragraph, at the top of the demo (in a visible intro, not just a comment). A logic prototype that answers the wrong question is pure waste, so make the question explicit so it can be checked later, whether the user is watching now or returning to it AFK. + +### 2. Isolate the logic in a portable module + +Put the actual logic (the bit that's answering the question) in a single `