From b802ff49ab2d2e095a9df7ce68450e7828c46dbf Mon Sep 17 00:00:00 2001 From: Johannes Kresner Date: Sun, 26 Jul 2026 11:42:17 +0200 Subject: [PATCH] feat: initial commit --- agents/skills/c4-model/SKILL.md | 84 + agents/skills/c4-model/references/c4-code.md | 153 + .../c4-model/references/c4-component.md | 121 + .../c4-model/references/c4-container.md | 275 ++ .../skills/c4-model/references/c4-context.md | 117 + 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/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/diagnose/SKILL.md | 117 + .../diagnose/scripts/hitl-loop.template.sh | 41 + agents/skills/find-skills/SKILL.md | 142 + agents/skills/graphify/.graphify_version | 1 + agents/skills/graphify/SKILL.md | 1031 ++++++ agents/skills/grill-me/SKILL.md | 10 + agents/skills/grill-with-docs/ADR-FORMAT.md | 47 + .../skills/grill-with-docs/CONTEXT-FORMAT.md | 77 + agents/skills/grill-with-docs/SKILL.md | 88 + .../DEEPENING.md | 37 + .../INTERFACE-DESIGN.md | 44 + .../improve-codebase-architecture/LANGUAGE.md | 53 + .../improve-codebase-architecture/SKILL.md | 71 + 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/tdd/SKILL.md | 109 + 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/to-issues/SKILL.md | 81 + agents/skills/to-prd/SKILL.md | 74 + agents/skills/touying-author/SKILL.md | 231 ++ .../docs/build-your-own-theme.md | 448 +++ .../skills/touying-author/docs/changelog.md | 321 ++ .../skills/touying-author/docs/code-styles.md | 150 + .../touying-author/docs/dynamic/complex.md | 94 + .../touying-author/docs/dynamic/cover.md | 66 + .../touying-author/docs/dynamic/equation.md | 49 + .../touying-author/docs/dynamic/handout.md | 15 + .../touying-author/docs/dynamic/other.md | 100 + .../touying-author/docs/dynamic/simple.md | 53 + .../touying-author/docs/external/pdfpc.md | 58 + .../touying-author/docs/external/pympress.md | 46 + .../docs/external/typst-preview.md | 15 + .../touying-author/docs/global-settings.md | 59 + .../touying-author/docs/integration/cetz.md | 97 + .../touying-author/docs/integration/codly.md | 37 + .../docs/integration/fletcher.md | 66 + .../touying-author/docs/integration/mitex.md | 35 + .../touying-author/docs/integration/pinit.md | 116 + .../docs/integration/theorion.md | 73 + agents/skills/touying-author/docs/intro.md | 51 + agents/skills/touying-author/docs/layout.md | 144 + .../skills/touying-author/docs/multi-file.md | 106 + .../touying-author/docs/progress/counters.md | 43 + .../touying-author/docs/progress/sections.md | 7 + agents/skills/touying-author/docs/sections.md | 84 + agents/skills/touying-author/docs/start.md | 256 ++ .../skills/touying-author/docs/themes/aqua.md | 151 + .../touying-author/docs/themes/custom.md | 20 + .../touying-author/docs/themes/dewdrop.md | 177 + .../touying-author/docs/themes/metropolis.md | 189 + .../touying-author/docs/themes/simple.md | 128 + .../touying-author/docs/themes/stargazer.md | 197 ++ .../touying-author/docs/themes/university.md | 174 + .../touying-author/docs/utilities/fit-to.md | 53 + .../touying-author/examples/aqua-zh.typ | 43 + .../skills/touying-author/examples/aqua.typ | 37 + .../touying-author/examples/default.typ | 56 + .../touying-author/examples/dewdrop.typ | 63 + .../touying-author/examples/example.typ | 220 ++ .../touying-author/examples/metropolis.typ | 68 + .../skills/touying-author/examples/simple.typ | 38 + .../touying-author/examples/stargazer.typ | 66 + .../touying-author/examples/university.typ | 46 + agents/skills/typst-author/SKILL.md | 164 + .../typst-author/docs/changelog/0.1.0.md | 64 + .../typst-author/docs/changelog/0.10.0.md | 110 + .../typst-author/docs/changelog/0.11.0.md | 203 ++ .../typst-author/docs/changelog/0.11.1.md | 55 + .../typst-author/docs/changelog/0.12.0.md | 274 ++ .../typst-author/docs/changelog/0.13.0.md | 247 ++ .../typst-author/docs/changelog/0.13.1.md | 25 + .../typst-author/docs/changelog/0.14.0.md | 311 ++ .../typst-author/docs/changelog/0.14.1.md | 56 + .../typst-author/docs/changelog/0.14.2.md | 11 + .../typst-author/docs/changelog/0.2.0.md | 37 + .../typst-author/docs/changelog/0.3.0.md | 61 + .../typst-author/docs/changelog/0.4.0.md | 84 + .../typst-author/docs/changelog/0.5.0.md | 57 + .../typst-author/docs/changelog/0.6.0.md | 54 + .../typst-author/docs/changelog/0.7.0.md | 109 + .../typst-author/docs/changelog/0.8.0.md | 95 + .../typst-author/docs/changelog/0.9.0.md | 135 + .../typst-author/docs/changelog/earlier.md | 254 ++ .../typst-author/docs/changelog/index.md | 25 + .../typst-author/docs/guides/accessibility.md | 308 ++ .../docs/guides/for-latex-users.md | 400 +++ .../skills/typst-author/docs/guides/index.md | 10 + .../typst-author/docs/guides/page-setup.md | 333 ++ .../skills/typst-author/docs/guides/tables.md | 823 +++++ agents/skills/typst-author/docs/index.md | 7 + .../typst-author/docs/reference/context.md | 149 + .../docs/reference/data-loading/cbor.md | 86 + .../docs/reference/data-loading/csv.md | 73 + .../docs/reference/data-loading/index.md | 24 + .../docs/reference/data-loading/json.md | 118 + .../docs/reference/data-loading/read.md | 40 + .../docs/reference/data-loading/toml.md | 107 + .../docs/reference/data-loading/xml.md | 82 + .../docs/reference/data-loading/yaml.md | 105 + .../docs/reference/foundations/arguments.md | 92 + .../docs/reference/foundations/array.md | 717 ++++ .../docs/reference/foundations/assert.md | 103 + .../docs/reference/foundations/auto.md | 9 + .../docs/reference/foundations/bool.md | 15 + .../docs/reference/foundations/bytes.md | 111 + .../docs/reference/foundations/calc.md | 984 ++++++ .../docs/reference/foundations/content.md | 89 + .../docs/reference/foundations/datetime.md | 231 ++ .../docs/reference/foundations/decimal.md | 69 + .../docs/reference/foundations/dictionary.md | 144 + .../docs/reference/foundations/duration.md | 85 + .../docs/reference/foundations/eval.md | 40 + .../docs/reference/foundations/float.md | 147 + .../docs/reference/foundations/function.md | 127 + .../docs/reference/foundations/index.md | 42 + .../docs/reference/foundations/int.md | 263 ++ .../docs/reference/foundations/label.md | 55 + .../docs/reference/foundations/module.md | 31 + .../docs/reference/foundations/none.md | 15 + .../docs/reference/foundations/panic.md | 30 + .../docs/reference/foundations/plugin.md | 135 + .../docs/reference/foundations/regex.md | 39 + .../docs/reference/foundations/repr.md | 44 + .../docs/reference/foundations/selector.md | 138 + .../docs/reference/foundations/std.md | 34 + .../docs/reference/foundations/str.md | 465 +++ .../docs/reference/foundations/symbol.md | 61 + .../docs/reference/foundations/sys.md | 10 + .../docs/reference/foundations/target.md | 45 + .../docs/reference/foundations/type.md | 69 + .../docs/reference/foundations/version.md | 71 + .../typst-author/docs/reference/html/elem.md | 42 + .../typst-author/docs/reference/html/frame.md | 24 + .../typst-author/docs/reference/html/index.md | 42 + .../typst-author/docs/reference/html/typed.md | 3072 +++++++++++++++++ .../typst-author/docs/reference/index.md | 13 + .../docs/reference/introspection/counter.md | 261 ++ .../docs/reference/introspection/here.md | 41 + .../docs/reference/introspection/index.md | 20 + .../docs/reference/introspection/locate.md | 35 + .../docs/reference/introspection/location.md | 52 + .../docs/reference/introspection/metadata.md | 34 + .../docs/reference/introspection/query.md | 127 + .../docs/reference/introspection/state.md | 203 ++ .../docs/reference/layout/align.md | 88 + .../docs/reference/layout/alignment.md | 69 + .../docs/reference/layout/angle.md | 27 + .../docs/reference/layout/block.md | 115 + .../typst-author/docs/reference/layout/box.md | 78 + .../docs/reference/layout/colbreak.md | 41 + .../docs/reference/layout/columns.md | 71 + .../docs/reference/layout/direction.md | 123 + .../docs/reference/layout/fraction.md | 15 + .../docs/reference/layout/grid.md | 399 +++ .../typst-author/docs/reference/layout/h.md | 48 + .../docs/reference/layout/hide.md | 35 + .../docs/reference/layout/index.md | 39 + .../docs/reference/layout/layout.md | 62 + .../docs/reference/layout/length.md | 80 + .../docs/reference/layout/measure.md | 57 + .../docs/reference/layout/move.md | 50 + .../typst-author/docs/reference/layout/pad.md | 67 + .../docs/reference/layout/page.md | 123 + .../docs/reference/layout/pagebreak.md | 42 + .../docs/reference/layout/place.md | 118 + .../docs/reference/layout/ratio.md | 29 + .../docs/reference/layout/relative.md | 54 + .../docs/reference/layout/repeat.md | 53 + .../docs/reference/layout/rotate.md | 48 + .../docs/reference/layout/scale.md | 55 + .../docs/reference/layout/skew.md | 50 + .../docs/reference/layout/stack.md | 47 + .../typst-author/docs/reference/layout/v.md | 43 + .../docs/reference/math/accent.md | 43 + .../docs/reference/math/attach.md | 120 + .../typst-author/docs/reference/math/binom.md | 32 + .../docs/reference/math/cancel.md | 55 + .../typst-author/docs/reference/math/cases.md | 48 + .../typst-author/docs/reference/math/class.md | 38 + .../docs/reference/math/equation.md | 67 + .../typst-author/docs/reference/math/frac.md | 41 + .../typst-author/docs/reference/math/index.md | 119 + .../typst-author/docs/reference/math/lr.md | 195 ++ .../typst-author/docs/reference/math/mat.md | 65 + .../typst-author/docs/reference/math/op.md | 37 + .../docs/reference/math/primes.md | 28 + .../typst-author/docs/reference/math/roots.md | 59 + .../typst-author/docs/reference/math/sizes.md | 120 + .../docs/reference/math/stretch.md | 36 + .../docs/reference/math/styles.md | 68 + .../docs/reference/math/underover.md | 257 ++ .../docs/reference/math/variants.md | 172 + .../typst-author/docs/reference/math/vec.md | 46 + .../docs/reference/model/bibliography.md | 67 + .../typst-author/docs/reference/model/cite.md | 63 + .../docs/reference/model/document.md | 51 + .../typst-author/docs/reference/model/emph.md | 40 + .../typst-author/docs/reference/model/enum.md | 141 + .../docs/reference/model/figure.md | 182 + .../docs/reference/model/footnote.md | 104 + .../docs/reference/model/heading.md | 96 + .../docs/reference/model/index.md | 31 + .../typst-author/docs/reference/model/link.md | 76 + .../typst-author/docs/reference/model/list.md | 92 + .../docs/reference/model/numbering.md | 58 + .../docs/reference/model/outline.md | 216 ++ .../typst-author/docs/reference/model/par.md | 186 + .../docs/reference/model/parbreak.md | 23 + .../docs/reference/model/quote.md | 67 + .../typst-author/docs/reference/model/ref.md | 124 + .../docs/reference/model/strong.md | 41 + .../docs/reference/model/table.md | 482 +++ .../docs/reference/model/terms.md | 83 + .../docs/reference/model/title.md | 39 + .../docs/reference/pdf/artifact.md | 35 + .../typst-author/docs/reference/pdf/attach.md | 60 + .../docs/reference/pdf/data-cell.md | 56 + .../docs/reference/pdf/header-cell.md | 70 + .../typst-author/docs/reference/pdf/index.md | 105 + .../docs/reference/pdf/table-summary.md | 54 + .../skills/typst-author/docs/reference/png.md | 38 + .../typst-author/docs/reference/scripting.md | 270 ++ .../typst-author/docs/reference/styling.md | 100 + .../skills/typst-author/docs/reference/svg.md | 29 + .../docs/reference/symbols/emoji.md | 1387 ++++++++ .../docs/reference/symbols/index.md | 13 + .../docs/reference/symbols/sym.md | 1165 +++++++ .../typst-author/docs/reference/syntax.md | 193 ++ .../docs/reference/text/highlight.md | 56 + .../typst-author/docs/reference/text/index.md | 25 + .../docs/reference/text/linebreak.md | 34 + .../typst-author/docs/reference/text/lorem.md | 32 + .../typst-author/docs/reference/text/lower.md | 28 + .../docs/reference/text/overline.md | 51 + .../typst-author/docs/reference/text/raw.md | 159 + .../docs/reference/text/smallcaps.md | 60 + .../docs/reference/text/smartquote.md | 53 + .../docs/reference/text/strike.md | 46 + .../typst-author/docs/reference/text/sub.md | 43 + .../typst-author/docs/reference/text/super.md | 43 + .../typst-author/docs/reference/text/text.md | 198 ++ .../docs/reference/text/underline.md | 51 + .../typst-author/docs/reference/text/upper.md | 28 + .../docs/reference/visualize/circle.md | 69 + .../docs/reference/visualize/color.md | 766 ++++ .../docs/reference/visualize/curve.md | 260 ++ .../docs/reference/visualize/ellipse.md | 64 + .../docs/reference/visualize/gradient.md | 406 +++ .../docs/reference/visualize/image.md | 125 + .../docs/reference/visualize/index.md | 30 + .../docs/reference/visualize/line.md | 53 + .../docs/reference/visualize/path.md | 53 + .../docs/reference/visualize/polygon.md | 93 + .../docs/reference/visualize/rect.md | 68 + .../docs/reference/visualize/square.md | 73 + .../docs/reference/visualize/stroke.md | 89 + .../docs/reference/visualize/tiling.md | 119 + .../docs/tutorial/advanced-styling.md | 328 ++ .../typst-author/docs/tutorial/formatting.md | 177 + .../typst-author/docs/tutorial/index.md | 22 + .../docs/tutorial/making-a-template.md | 312 ++ .../docs/tutorial/writing-in-typst.md | 194 ++ agents/skills/zoom-out/SKILL.md | 7 + config/aerospace/aerospace.toml | 218 ++ config/btop/btop.conf | 272 ++ config/btop/themes/catppuccin_latte.theme | 83 + config/btop/themes/catppuccin_mocha.theme | 83 + config/cursor/commands/journal.md | 8 + config/cursor/rules/auto-document.mdc | 17 + config/cursor/rules/commit-messages.mdc | 54 + config/cursor/rules/golang-errors.mdc | 10 + config/cursor/rules/golang-style.mdc | 26 + config/cursor/rules/golang-testing.mdc | 12 + config/cursor/rules/php-docs.mdc | 8 + config/cursor/rules/php-errors.mdc | 10 + config/cursor/rules/php-performance.mdc | 10 + config/cursor/rules/php-security.mdc | 10 + config/cursor/rules/php-style.mdc | 12 + config/cursor/rules/php-testing.mdc | 10 + config/fastfetch/config.jsonc | 128 + config/fastfetch/config.jsonc.bak | 61 + config/fastfetch/logo/hyprland.icon | Bin 0 -> 11701 bytes config/fastfetch/logo/loli.icon | Bin 0 -> 444402 bytes config/fastfetch/logo/pochita.icon | Bin 0 -> 116666 bytes config/ghostty/config | 9 + config/helix/config.toml | 32 + .../themes/catppuccin_latte_transparent.toml | 1 + .../themes/catppuccin_mocha_transparent.toml | 3 + config/hypr/.luarc.json | 7 + config/hypr/empty_workspaces.conf | 0 config/hypr/hypridle.conf | 10 + config/hypr/hyprland.conf | 281 ++ config/hypr/hyprland.lua | 266 ++ config/hypr/hyprlock.conf | 108 + config/hypr/mocha.conf | 78 + config/hypr/theme.conf | 1 + config/lazygit/config.yml | 127 + config/mako/config | 1 + config/mcphub/servers.json | 42 + config/niri/config.kdl | 349 ++ config/nushell/completions/pm.nu | 10 + config/nushell/config.nu | 177 + config/nushell/env.nu | 100 + config/nushell/scripts/alias-finder.nu | 46 + config/nushell/scripts/commands.nu | 84 + config/nushell/scripts/git/common.nu | 15 + config/nushell/scripts/git/complete.nu | 35 + config/nushell/scripts/git/core.nu | 544 +++ config/nushell/scripts/git/db.nu | 20 + config/nushell/scripts/git/git-flow.nu | 256 ++ config/nushell/scripts/git/histogram.nu | 76 + config/nushell/scripts/git/mod.nu | 20 + config/nushell/scripts/git/shortcut.nu | 40 + config/nushell/scripts/git/stat.nu | 226 ++ config/nushell/scripts/git/utils.nu | 102 + config/nushell/scripts/theme-switch.nu | 108 + config/nushell/scripts/wallpaper-switch.nu | 83 + config/nushell/ssh-agent.nu | 8 + config/opencode/agents/dev.md | 16 + config/opencode/agents/orchestrator.md | 49 + config/opencode/agents/pm.md | 22 + config/opencode/agents/qa.md | 25 + config/opencode/opencode.jsonc | 362 ++ config/quickshell/AGENTS.md | 32 + config/quickshell/Bar/Bar.qml | 51 + config/quickshell/Bar/BarPill.qml | 27 + config/quickshell/Bar/BarSection.qml | 7 + config/quickshell/Bar/qmldir | 4 + config/quickshell/Theme/Theme.qml | 36 + config/quickshell/Theme/qmldir | 1 + .../quickshell/Widgets/AppLauncherWindow.qml | 185 + config/quickshell/Widgets/AudioWidget.qml | 58 + .../Widgets/ClipboardPickerWindow.qml | 159 + config/quickshell/Widgets/Clock.qml | 231 ++ config/quickshell/Widgets/CpuWidget.qml | 41 + .../Widgets/HyprlandWorkspaceWidget.qml | 71 + config/quickshell/Widgets/MemoryWidget.qml | 41 + .../quickshell/Widgets/NetTrafficWidget.qml | 119 + .../Widgets/NiriWorkspaceWidget.qml | 79 + config/quickshell/Widgets/PowerMenuWindow.qml | 115 + config/quickshell/Widgets/StorageWidget.qml | 48 + .../quickshell/Widgets/TemperatureWidget.qml | 42 + .../Widgets/ThemeSwitcherWindow.qml | 383 ++ config/quickshell/Widgets/TrayWidget.qml | 58 + .../Widgets/WallpaperSwitcherWindow.qml | 285 ++ config/quickshell/Widgets/qmldir | 16 + config/quickshell/scripts/cpu-temp.sh | 82 + config/quickshell/shell.qml | 44 + config/starship.toml | 61 + config/themes/catppuccin/latte/gtk-theme-name | 1 + config/themes/catppuccin/latte/hypr.conf | 77 + config/themes/catppuccin/latte/mako.conf | 7 + .../catppuccin/latte/quickshell/Theme.qml | 36 + config/themes/catppuccin/latte/wofi.css | 61 + config/themes/catppuccin/mocha/gtk-theme-name | 1 + config/themes/catppuccin/mocha/hypr.conf | 77 + config/themes/catppuccin/mocha/mako.conf | 7 + .../catppuccin/mocha/quickshell/Theme.qml | 36 + config/themes/catppuccin/mocha/wofi.css | 61 + config/waybar/config | 337 ++ config/waybar/config.jsonc | 105 + config/waybar/mocha.css | 26 + config/waybar/modules/mail.py | 42 + config/waybar/modules/spotify.sh | 18 + config/waybar/modules/storage.sh | 24 + config/waybar/modules/weather.sh | 79 + config/waybar/style.css | 158 + config/waybar/waybar.sh | 10 + config/wlogout/layout | 36 + config/wlogout/style.css | 50 + config/wofi/config | 25 + config/wofi/launch.sh | 7 + config/wofi/style.css | 1 + .../flavors/catppuccin-latte.yazi/LICENSE | 21 + .../catppuccin-latte.yazi/LICENSE-tmtheme | 21 + .../flavors/catppuccin-latte.yazi/README.md | 36 + .../flavors/catppuccin-latte.yazi/flavor.toml | 215 ++ .../flavors/catppuccin-latte.yazi/preview.png | Bin 0 -> 734865 bytes .../flavors/catppuccin-latte.yazi/tmtheme.xml | 2112 ++++++++++++ .../flavors/catppuccin-mocha.yazi/LICENSE | 21 + .../catppuccin-mocha.yazi/LICENSE-tmtheme | 21 + .../flavors/catppuccin-mocha.yazi/README.md | 36 + .../flavors/catppuccin-mocha.yazi/flavor.toml | 215 ++ .../flavors/catppuccin-mocha.yazi/preview.png | Bin 0 -> 675868 bytes .../flavors/catppuccin-mocha.yazi/tmtheme.xml | 2112 ++++++++++++ config/yazi/init.lua | 3 + config/yazi/plugins/auto-layout.yazi/LICENSE | 21 + .../yazi/plugins/auto-layout.yazi/README.md | 24 + config/yazi/plugins/auto-layout.yazi/main.lua | 180 + config/yazi/plugins/git.yazi/LICENSE | 21 + config/yazi/plugins/git.yazi/README.md | 78 + config/yazi/plugins/git.yazi/main.lua | 228 ++ .../yazi/plugins/sidebar-status.yazi/main.lua | 14 + config/yazi/yazi.toml | 7 + config/zed/keymap.json | 129 + config/zed/settings.json | 236 ++ config/zellij/config.kdl | 133 + config/zellij/layouts/dev.kdl | 80 + config/zellij/layouts/tabs.kdl | 77 + flake.lock | 130 + flake.nix | 27 + fonts/Myna-Bold.otf | Bin 0 -> 255816 bytes fonts/Myna-BoldItalic.otf | Bin 0 -> 275884 bytes fonts/Myna-Regular.otf | Bin 0 -> 211504 bytes fonts/Myna-RegularItalic.otf | Bin 0 -> 237576 bytes fonts/MynaNerdFont-Regular.otf | Bin 0 -> 2296300 bytes home.nix | 84 + local_bin/random_wallpaper | 15 + local_share/dark-mode.d/theme-switch | 3 + local_share/easyeffects/input/default.json | 278 ++ local_share/light-mode.d/theme-switch | 3 + pi/agent/settings.json | 20 + result | 1 + secrets/git_config.age | 29 + secrets/jj_config.age | 9 + secrets/secrets.nix | 6 + 454 files changed, 52429 insertions(+) create mode 100644 agents/skills/c4-model/SKILL.md create mode 100644 agents/skills/c4-model/references/c4-code.md create mode 100644 agents/skills/c4-model/references/c4-component.md create mode 100644 agents/skills/c4-model/references/c4-container.md create mode 100644 agents/skills/c4-model/references/c4-context.md create mode 100644 agents/skills/cavecrew/SKILL.md create mode 100644 agents/skills/caveman-commit/SKILL.md create mode 100644 agents/skills/caveman-compress/README.md create mode 100644 agents/skills/caveman-compress/SECURITY.md create mode 100644 agents/skills/caveman-compress/SKILL.md create mode 100644 agents/skills/caveman-compress/scripts/__init__.py create mode 100644 agents/skills/caveman-compress/scripts/__main__.py create mode 100644 agents/skills/caveman-compress/scripts/benchmark.py create mode 100644 agents/skills/caveman-compress/scripts/cli.py create mode 100644 agents/skills/caveman-compress/scripts/compress.py create mode 100644 agents/skills/caveman-compress/scripts/detect.py create mode 100644 agents/skills/caveman-compress/scripts/validate.py create mode 100644 agents/skills/caveman-help/SKILL.md create mode 100644 agents/skills/caveman-review/SKILL.md create mode 100644 agents/skills/caveman-stats/SKILL.md create mode 100644 agents/skills/caveman/SKILL.md create mode 100644 agents/skills/compress/SKILL.md create mode 100644 agents/skills/compress/scripts/__init__.py create mode 100644 agents/skills/compress/scripts/__main__.py create mode 100644 agents/skills/compress/scripts/benchmark.py create mode 100644 agents/skills/compress/scripts/cli.py create mode 100644 agents/skills/compress/scripts/compress.py create mode 100644 agents/skills/compress/scripts/detect.py create mode 100644 agents/skills/compress/scripts/validate.py create mode 100644 agents/skills/diagnose/SKILL.md create mode 100644 agents/skills/diagnose/scripts/hitl-loop.template.sh create mode 100644 agents/skills/find-skills/SKILL.md create mode 100644 agents/skills/graphify/.graphify_version create mode 100644 agents/skills/graphify/SKILL.md create mode 100644 agents/skills/grill-me/SKILL.md create mode 100644 agents/skills/grill-with-docs/ADR-FORMAT.md create mode 100644 agents/skills/grill-with-docs/CONTEXT-FORMAT.md create mode 100644 agents/skills/grill-with-docs/SKILL.md create mode 100644 agents/skills/improve-codebase-architecture/DEEPENING.md create mode 100644 agents/skills/improve-codebase-architecture/INTERFACE-DESIGN.md create mode 100644 agents/skills/improve-codebase-architecture/LANGUAGE.md create mode 100644 agents/skills/improve-codebase-architecture/SKILL.md create mode 120000 agents/skills/oh-my-mermaid create mode 100644 agents/skills/ponytail-audit/SKILL.md create mode 100644 agents/skills/ponytail-debt/SKILL.md create mode 100644 agents/skills/ponytail-gain/SKILL.md create mode 100644 agents/skills/ponytail-help/SKILL.md create mode 100644 agents/skills/ponytail-review/SKILL.md create mode 100644 agents/skills/ponytail/SKILL.md create mode 100644 agents/skills/tdd/SKILL.md create mode 100644 agents/skills/tdd/deep-modules.md create mode 100644 agents/skills/tdd/interface-design.md create mode 100644 agents/skills/tdd/mocking.md create mode 100644 agents/skills/tdd/refactoring.md create mode 100644 agents/skills/tdd/tests.md create mode 100644 agents/skills/to-issues/SKILL.md create mode 100644 agents/skills/to-prd/SKILL.md create mode 100644 agents/skills/touying-author/SKILL.md create mode 100644 agents/skills/touying-author/docs/build-your-own-theme.md create mode 100644 agents/skills/touying-author/docs/changelog.md create mode 100644 agents/skills/touying-author/docs/code-styles.md create mode 100644 agents/skills/touying-author/docs/dynamic/complex.md create mode 100644 agents/skills/touying-author/docs/dynamic/cover.md create mode 100644 agents/skills/touying-author/docs/dynamic/equation.md create mode 100644 agents/skills/touying-author/docs/dynamic/handout.md create mode 100644 agents/skills/touying-author/docs/dynamic/other.md create mode 100644 agents/skills/touying-author/docs/dynamic/simple.md create mode 100644 agents/skills/touying-author/docs/external/pdfpc.md create mode 100644 agents/skills/touying-author/docs/external/pympress.md create mode 100644 agents/skills/touying-author/docs/external/typst-preview.md create mode 100644 agents/skills/touying-author/docs/global-settings.md create mode 100644 agents/skills/touying-author/docs/integration/cetz.md create mode 100644 agents/skills/touying-author/docs/integration/codly.md create mode 100644 agents/skills/touying-author/docs/integration/fletcher.md create mode 100644 agents/skills/touying-author/docs/integration/mitex.md create mode 100644 agents/skills/touying-author/docs/integration/pinit.md create mode 100644 agents/skills/touying-author/docs/integration/theorion.md create mode 100644 agents/skills/touying-author/docs/intro.md create mode 100644 agents/skills/touying-author/docs/layout.md create mode 100644 agents/skills/touying-author/docs/multi-file.md create mode 100644 agents/skills/touying-author/docs/progress/counters.md create mode 100644 agents/skills/touying-author/docs/progress/sections.md create mode 100644 agents/skills/touying-author/docs/sections.md create mode 100644 agents/skills/touying-author/docs/start.md create mode 100644 agents/skills/touying-author/docs/themes/aqua.md create mode 100644 agents/skills/touying-author/docs/themes/custom.md create mode 100644 agents/skills/touying-author/docs/themes/dewdrop.md create mode 100644 agents/skills/touying-author/docs/themes/metropolis.md create mode 100644 agents/skills/touying-author/docs/themes/simple.md create mode 100644 agents/skills/touying-author/docs/themes/stargazer.md create mode 100644 agents/skills/touying-author/docs/themes/university.md create mode 100644 agents/skills/touying-author/docs/utilities/fit-to.md create mode 100644 agents/skills/touying-author/examples/aqua-zh.typ create mode 100644 agents/skills/touying-author/examples/aqua.typ create mode 100644 agents/skills/touying-author/examples/default.typ create mode 100644 agents/skills/touying-author/examples/dewdrop.typ create mode 100644 agents/skills/touying-author/examples/example.typ create mode 100644 agents/skills/touying-author/examples/metropolis.typ create mode 100644 agents/skills/touying-author/examples/simple.typ create mode 100644 agents/skills/touying-author/examples/stargazer.typ create mode 100644 agents/skills/touying-author/examples/university.typ create mode 100644 agents/skills/typst-author/SKILL.md create mode 100644 agents/skills/typst-author/docs/changelog/0.1.0.md create mode 100644 agents/skills/typst-author/docs/changelog/0.10.0.md create mode 100644 agents/skills/typst-author/docs/changelog/0.11.0.md create mode 100644 agents/skills/typst-author/docs/changelog/0.11.1.md create mode 100644 agents/skills/typst-author/docs/changelog/0.12.0.md create mode 100644 agents/skills/typst-author/docs/changelog/0.13.0.md create mode 100644 agents/skills/typst-author/docs/changelog/0.13.1.md create mode 100644 agents/skills/typst-author/docs/changelog/0.14.0.md create mode 100644 agents/skills/typst-author/docs/changelog/0.14.1.md create mode 100644 agents/skills/typst-author/docs/changelog/0.14.2.md create mode 100644 agents/skills/typst-author/docs/changelog/0.2.0.md create mode 100644 agents/skills/typst-author/docs/changelog/0.3.0.md create mode 100644 agents/skills/typst-author/docs/changelog/0.4.0.md create mode 100644 agents/skills/typst-author/docs/changelog/0.5.0.md create mode 100644 agents/skills/typst-author/docs/changelog/0.6.0.md create mode 100644 agents/skills/typst-author/docs/changelog/0.7.0.md create mode 100644 agents/skills/typst-author/docs/changelog/0.8.0.md create mode 100644 agents/skills/typst-author/docs/changelog/0.9.0.md create mode 100644 agents/skills/typst-author/docs/changelog/earlier.md create mode 100644 agents/skills/typst-author/docs/changelog/index.md create mode 100644 agents/skills/typst-author/docs/guides/accessibility.md create mode 100644 agents/skills/typst-author/docs/guides/for-latex-users.md create mode 100644 agents/skills/typst-author/docs/guides/index.md create mode 100644 agents/skills/typst-author/docs/guides/page-setup.md create mode 100644 agents/skills/typst-author/docs/guides/tables.md create mode 100644 agents/skills/typst-author/docs/index.md create mode 100644 agents/skills/typst-author/docs/reference/context.md create mode 100644 agents/skills/typst-author/docs/reference/data-loading/cbor.md create mode 100644 agents/skills/typst-author/docs/reference/data-loading/csv.md create mode 100644 agents/skills/typst-author/docs/reference/data-loading/index.md create mode 100644 agents/skills/typst-author/docs/reference/data-loading/json.md create mode 100644 agents/skills/typst-author/docs/reference/data-loading/read.md create mode 100644 agents/skills/typst-author/docs/reference/data-loading/toml.md create mode 100644 agents/skills/typst-author/docs/reference/data-loading/xml.md create mode 100644 agents/skills/typst-author/docs/reference/data-loading/yaml.md create mode 100644 agents/skills/typst-author/docs/reference/foundations/arguments.md create mode 100644 agents/skills/typst-author/docs/reference/foundations/array.md create mode 100644 agents/skills/typst-author/docs/reference/foundations/assert.md create mode 100644 agents/skills/typst-author/docs/reference/foundations/auto.md create mode 100644 agents/skills/typst-author/docs/reference/foundations/bool.md create mode 100644 agents/skills/typst-author/docs/reference/foundations/bytes.md create mode 100644 agents/skills/typst-author/docs/reference/foundations/calc.md create mode 100644 agents/skills/typst-author/docs/reference/foundations/content.md create mode 100644 agents/skills/typst-author/docs/reference/foundations/datetime.md create mode 100644 agents/skills/typst-author/docs/reference/foundations/decimal.md create mode 100644 agents/skills/typst-author/docs/reference/foundations/dictionary.md create mode 100644 agents/skills/typst-author/docs/reference/foundations/duration.md create mode 100644 agents/skills/typst-author/docs/reference/foundations/eval.md create mode 100644 agents/skills/typst-author/docs/reference/foundations/float.md create mode 100644 agents/skills/typst-author/docs/reference/foundations/function.md create mode 100644 agents/skills/typst-author/docs/reference/foundations/index.md create mode 100644 agents/skills/typst-author/docs/reference/foundations/int.md create mode 100644 agents/skills/typst-author/docs/reference/foundations/label.md create mode 100644 agents/skills/typst-author/docs/reference/foundations/module.md create mode 100644 agents/skills/typst-author/docs/reference/foundations/none.md create mode 100644 agents/skills/typst-author/docs/reference/foundations/panic.md create mode 100644 agents/skills/typst-author/docs/reference/foundations/plugin.md create mode 100644 agents/skills/typst-author/docs/reference/foundations/regex.md create mode 100644 agents/skills/typst-author/docs/reference/foundations/repr.md create mode 100644 agents/skills/typst-author/docs/reference/foundations/selector.md create mode 100644 agents/skills/typst-author/docs/reference/foundations/std.md create mode 100644 agents/skills/typst-author/docs/reference/foundations/str.md create mode 100644 agents/skills/typst-author/docs/reference/foundations/symbol.md create mode 100644 agents/skills/typst-author/docs/reference/foundations/sys.md create mode 100644 agents/skills/typst-author/docs/reference/foundations/target.md create mode 100644 agents/skills/typst-author/docs/reference/foundations/type.md create mode 100644 agents/skills/typst-author/docs/reference/foundations/version.md create mode 100644 agents/skills/typst-author/docs/reference/html/elem.md create mode 100644 agents/skills/typst-author/docs/reference/html/frame.md create mode 100644 agents/skills/typst-author/docs/reference/html/index.md create mode 100644 agents/skills/typst-author/docs/reference/html/typed.md create mode 100644 agents/skills/typst-author/docs/reference/index.md create mode 100644 agents/skills/typst-author/docs/reference/introspection/counter.md create mode 100644 agents/skills/typst-author/docs/reference/introspection/here.md create mode 100644 agents/skills/typst-author/docs/reference/introspection/index.md create mode 100644 agents/skills/typst-author/docs/reference/introspection/locate.md create mode 100644 agents/skills/typst-author/docs/reference/introspection/location.md create mode 100644 agents/skills/typst-author/docs/reference/introspection/metadata.md create mode 100644 agents/skills/typst-author/docs/reference/introspection/query.md create mode 100644 agents/skills/typst-author/docs/reference/introspection/state.md create mode 100644 agents/skills/typst-author/docs/reference/layout/align.md create mode 100644 agents/skills/typst-author/docs/reference/layout/alignment.md create mode 100644 agents/skills/typst-author/docs/reference/layout/angle.md create mode 100644 agents/skills/typst-author/docs/reference/layout/block.md create mode 100644 agents/skills/typst-author/docs/reference/layout/box.md create mode 100644 agents/skills/typst-author/docs/reference/layout/colbreak.md create mode 100644 agents/skills/typst-author/docs/reference/layout/columns.md create mode 100644 agents/skills/typst-author/docs/reference/layout/direction.md create mode 100644 agents/skills/typst-author/docs/reference/layout/fraction.md create mode 100644 agents/skills/typst-author/docs/reference/layout/grid.md create mode 100644 agents/skills/typst-author/docs/reference/layout/h.md create mode 100644 agents/skills/typst-author/docs/reference/layout/hide.md create mode 100644 agents/skills/typst-author/docs/reference/layout/index.md create mode 100644 agents/skills/typst-author/docs/reference/layout/layout.md create mode 100644 agents/skills/typst-author/docs/reference/layout/length.md create mode 100644 agents/skills/typst-author/docs/reference/layout/measure.md create mode 100644 agents/skills/typst-author/docs/reference/layout/move.md create mode 100644 agents/skills/typst-author/docs/reference/layout/pad.md create mode 100644 agents/skills/typst-author/docs/reference/layout/page.md create mode 100644 agents/skills/typst-author/docs/reference/layout/pagebreak.md create mode 100644 agents/skills/typst-author/docs/reference/layout/place.md create mode 100644 agents/skills/typst-author/docs/reference/layout/ratio.md create mode 100644 agents/skills/typst-author/docs/reference/layout/relative.md create mode 100644 agents/skills/typst-author/docs/reference/layout/repeat.md create mode 100644 agents/skills/typst-author/docs/reference/layout/rotate.md create mode 100644 agents/skills/typst-author/docs/reference/layout/scale.md create mode 100644 agents/skills/typst-author/docs/reference/layout/skew.md create mode 100644 agents/skills/typst-author/docs/reference/layout/stack.md create mode 100644 agents/skills/typst-author/docs/reference/layout/v.md create mode 100644 agents/skills/typst-author/docs/reference/math/accent.md create mode 100644 agents/skills/typst-author/docs/reference/math/attach.md create mode 100644 agents/skills/typst-author/docs/reference/math/binom.md create mode 100644 agents/skills/typst-author/docs/reference/math/cancel.md create mode 100644 agents/skills/typst-author/docs/reference/math/cases.md create mode 100644 agents/skills/typst-author/docs/reference/math/class.md create mode 100644 agents/skills/typst-author/docs/reference/math/equation.md create mode 100644 agents/skills/typst-author/docs/reference/math/frac.md create mode 100644 agents/skills/typst-author/docs/reference/math/index.md create mode 100644 agents/skills/typst-author/docs/reference/math/lr.md create mode 100644 agents/skills/typst-author/docs/reference/math/mat.md create mode 100644 agents/skills/typst-author/docs/reference/math/op.md create mode 100644 agents/skills/typst-author/docs/reference/math/primes.md create mode 100644 agents/skills/typst-author/docs/reference/math/roots.md create mode 100644 agents/skills/typst-author/docs/reference/math/sizes.md create mode 100644 agents/skills/typst-author/docs/reference/math/stretch.md create mode 100644 agents/skills/typst-author/docs/reference/math/styles.md create mode 100644 agents/skills/typst-author/docs/reference/math/underover.md create mode 100644 agents/skills/typst-author/docs/reference/math/variants.md create mode 100644 agents/skills/typst-author/docs/reference/math/vec.md create mode 100644 agents/skills/typst-author/docs/reference/model/bibliography.md create mode 100644 agents/skills/typst-author/docs/reference/model/cite.md create mode 100644 agents/skills/typst-author/docs/reference/model/document.md create mode 100644 agents/skills/typst-author/docs/reference/model/emph.md create mode 100644 agents/skills/typst-author/docs/reference/model/enum.md create mode 100644 agents/skills/typst-author/docs/reference/model/figure.md create mode 100644 agents/skills/typst-author/docs/reference/model/footnote.md create mode 100644 agents/skills/typst-author/docs/reference/model/heading.md create mode 100644 agents/skills/typst-author/docs/reference/model/index.md create mode 100644 agents/skills/typst-author/docs/reference/model/link.md create mode 100644 agents/skills/typst-author/docs/reference/model/list.md create mode 100644 agents/skills/typst-author/docs/reference/model/numbering.md create mode 100644 agents/skills/typst-author/docs/reference/model/outline.md create mode 100644 agents/skills/typst-author/docs/reference/model/par.md create mode 100644 agents/skills/typst-author/docs/reference/model/parbreak.md create mode 100644 agents/skills/typst-author/docs/reference/model/quote.md create mode 100644 agents/skills/typst-author/docs/reference/model/ref.md create mode 100644 agents/skills/typst-author/docs/reference/model/strong.md create mode 100644 agents/skills/typst-author/docs/reference/model/table.md create mode 100644 agents/skills/typst-author/docs/reference/model/terms.md create mode 100644 agents/skills/typst-author/docs/reference/model/title.md create mode 100644 agents/skills/typst-author/docs/reference/pdf/artifact.md create mode 100644 agents/skills/typst-author/docs/reference/pdf/attach.md create mode 100644 agents/skills/typst-author/docs/reference/pdf/data-cell.md create mode 100644 agents/skills/typst-author/docs/reference/pdf/header-cell.md create mode 100644 agents/skills/typst-author/docs/reference/pdf/index.md create mode 100644 agents/skills/typst-author/docs/reference/pdf/table-summary.md create mode 100644 agents/skills/typst-author/docs/reference/png.md create mode 100644 agents/skills/typst-author/docs/reference/scripting.md create mode 100644 agents/skills/typst-author/docs/reference/styling.md create mode 100644 agents/skills/typst-author/docs/reference/svg.md create mode 100644 agents/skills/typst-author/docs/reference/symbols/emoji.md create mode 100644 agents/skills/typst-author/docs/reference/symbols/index.md create mode 100644 agents/skills/typst-author/docs/reference/symbols/sym.md create mode 100644 agents/skills/typst-author/docs/reference/syntax.md create mode 100644 agents/skills/typst-author/docs/reference/text/highlight.md create mode 100644 agents/skills/typst-author/docs/reference/text/index.md create mode 100644 agents/skills/typst-author/docs/reference/text/linebreak.md create mode 100644 agents/skills/typst-author/docs/reference/text/lorem.md create mode 100644 agents/skills/typst-author/docs/reference/text/lower.md create mode 100644 agents/skills/typst-author/docs/reference/text/overline.md create mode 100644 agents/skills/typst-author/docs/reference/text/raw.md create mode 100644 agents/skills/typst-author/docs/reference/text/smallcaps.md create mode 100644 agents/skills/typst-author/docs/reference/text/smartquote.md create mode 100644 agents/skills/typst-author/docs/reference/text/strike.md create mode 100644 agents/skills/typst-author/docs/reference/text/sub.md create mode 100644 agents/skills/typst-author/docs/reference/text/super.md create mode 100644 agents/skills/typst-author/docs/reference/text/text.md create mode 100644 agents/skills/typst-author/docs/reference/text/underline.md create mode 100644 agents/skills/typst-author/docs/reference/text/upper.md create mode 100644 agents/skills/typst-author/docs/reference/visualize/circle.md create mode 100644 agents/skills/typst-author/docs/reference/visualize/color.md create mode 100644 agents/skills/typst-author/docs/reference/visualize/curve.md create mode 100644 agents/skills/typst-author/docs/reference/visualize/ellipse.md create mode 100644 agents/skills/typst-author/docs/reference/visualize/gradient.md create mode 100644 agents/skills/typst-author/docs/reference/visualize/image.md create mode 100644 agents/skills/typst-author/docs/reference/visualize/index.md create mode 100644 agents/skills/typst-author/docs/reference/visualize/line.md create mode 100644 agents/skills/typst-author/docs/reference/visualize/path.md create mode 100644 agents/skills/typst-author/docs/reference/visualize/polygon.md create mode 100644 agents/skills/typst-author/docs/reference/visualize/rect.md create mode 100644 agents/skills/typst-author/docs/reference/visualize/square.md create mode 100644 agents/skills/typst-author/docs/reference/visualize/stroke.md create mode 100644 agents/skills/typst-author/docs/reference/visualize/tiling.md create mode 100644 agents/skills/typst-author/docs/tutorial/advanced-styling.md create mode 100644 agents/skills/typst-author/docs/tutorial/formatting.md create mode 100644 agents/skills/typst-author/docs/tutorial/index.md create mode 100644 agents/skills/typst-author/docs/tutorial/making-a-template.md create mode 100644 agents/skills/typst-author/docs/tutorial/writing-in-typst.md create mode 100644 agents/skills/zoom-out/SKILL.md create mode 100644 config/aerospace/aerospace.toml create mode 100644 config/btop/btop.conf create mode 100644 config/btop/themes/catppuccin_latte.theme create mode 100644 config/btop/themes/catppuccin_mocha.theme create mode 100644 config/cursor/commands/journal.md create mode 100644 config/cursor/rules/auto-document.mdc create mode 100644 config/cursor/rules/commit-messages.mdc create mode 100644 config/cursor/rules/golang-errors.mdc create mode 100644 config/cursor/rules/golang-style.mdc create mode 100644 config/cursor/rules/golang-testing.mdc create mode 100644 config/cursor/rules/php-docs.mdc create mode 100644 config/cursor/rules/php-errors.mdc create mode 100644 config/cursor/rules/php-performance.mdc create mode 100644 config/cursor/rules/php-security.mdc create mode 100644 config/cursor/rules/php-style.mdc create mode 100644 config/cursor/rules/php-testing.mdc create mode 100644 config/fastfetch/config.jsonc create mode 100644 config/fastfetch/config.jsonc.bak create mode 100644 config/fastfetch/logo/hyprland.icon create mode 100644 config/fastfetch/logo/loli.icon create mode 100644 config/fastfetch/logo/pochita.icon create mode 100644 config/ghostty/config create mode 100644 config/helix/config.toml create mode 100644 config/helix/themes/catppuccin_latte_transparent.toml create mode 100644 config/helix/themes/catppuccin_mocha_transparent.toml create mode 100644 config/hypr/.luarc.json create mode 100644 config/hypr/empty_workspaces.conf create mode 100644 config/hypr/hypridle.conf create mode 100644 config/hypr/hyprland.conf create mode 100644 config/hypr/hyprland.lua create mode 100644 config/hypr/hyprlock.conf create mode 100644 config/hypr/mocha.conf create mode 120000 config/hypr/theme.conf create mode 100644 config/lazygit/config.yml create mode 120000 config/mako/config create mode 100644 config/mcphub/servers.json create mode 100644 config/niri/config.kdl create mode 100644 config/nushell/completions/pm.nu create mode 100644 config/nushell/config.nu create mode 100644 config/nushell/env.nu create mode 100644 config/nushell/scripts/alias-finder.nu create mode 100644 config/nushell/scripts/commands.nu create mode 100644 config/nushell/scripts/git/common.nu create mode 100644 config/nushell/scripts/git/complete.nu create mode 100644 config/nushell/scripts/git/core.nu create mode 100644 config/nushell/scripts/git/db.nu create mode 100644 config/nushell/scripts/git/git-flow.nu create mode 100644 config/nushell/scripts/git/histogram.nu create mode 100644 config/nushell/scripts/git/mod.nu create mode 100644 config/nushell/scripts/git/shortcut.nu create mode 100644 config/nushell/scripts/git/stat.nu create mode 100644 config/nushell/scripts/git/utils.nu create mode 100755 config/nushell/scripts/theme-switch.nu create mode 100755 config/nushell/scripts/wallpaper-switch.nu create mode 100644 config/nushell/ssh-agent.nu create mode 100644 config/opencode/agents/dev.md create mode 100644 config/opencode/agents/orchestrator.md create mode 100644 config/opencode/agents/pm.md create mode 100644 config/opencode/agents/qa.md create mode 100644 config/opencode/opencode.jsonc create mode 100644 config/quickshell/AGENTS.md create mode 100644 config/quickshell/Bar/Bar.qml create mode 100644 config/quickshell/Bar/BarPill.qml create mode 100644 config/quickshell/Bar/BarSection.qml create mode 100644 config/quickshell/Bar/qmldir create mode 100644 config/quickshell/Theme/Theme.qml create mode 100644 config/quickshell/Theme/qmldir create mode 100644 config/quickshell/Widgets/AppLauncherWindow.qml create mode 100644 config/quickshell/Widgets/AudioWidget.qml create mode 100644 config/quickshell/Widgets/ClipboardPickerWindow.qml create mode 100644 config/quickshell/Widgets/Clock.qml create mode 100644 config/quickshell/Widgets/CpuWidget.qml create mode 100644 config/quickshell/Widgets/HyprlandWorkspaceWidget.qml create mode 100644 config/quickshell/Widgets/MemoryWidget.qml create mode 100644 config/quickshell/Widgets/NetTrafficWidget.qml create mode 100644 config/quickshell/Widgets/NiriWorkspaceWidget.qml create mode 100644 config/quickshell/Widgets/PowerMenuWindow.qml create mode 100644 config/quickshell/Widgets/StorageWidget.qml create mode 100644 config/quickshell/Widgets/TemperatureWidget.qml create mode 100644 config/quickshell/Widgets/ThemeSwitcherWindow.qml create mode 100644 config/quickshell/Widgets/TrayWidget.qml create mode 100644 config/quickshell/Widgets/WallpaperSwitcherWindow.qml create mode 100644 config/quickshell/Widgets/qmldir create mode 100644 config/quickshell/scripts/cpu-temp.sh create mode 100644 config/quickshell/shell.qml create mode 100644 config/starship.toml create mode 100644 config/themes/catppuccin/latte/gtk-theme-name create mode 100644 config/themes/catppuccin/latte/hypr.conf create mode 100644 config/themes/catppuccin/latte/mako.conf create mode 100644 config/themes/catppuccin/latte/quickshell/Theme.qml create mode 100644 config/themes/catppuccin/latte/wofi.css create mode 100644 config/themes/catppuccin/mocha/gtk-theme-name create mode 100644 config/themes/catppuccin/mocha/hypr.conf create mode 100644 config/themes/catppuccin/mocha/mako.conf create mode 100644 config/themes/catppuccin/mocha/quickshell/Theme.qml create mode 100644 config/themes/catppuccin/mocha/wofi.css create mode 100644 config/waybar/config create mode 100644 config/waybar/config.jsonc create mode 100644 config/waybar/mocha.css create mode 100755 config/waybar/modules/mail.py create mode 100755 config/waybar/modules/spotify.sh create mode 100755 config/waybar/modules/storage.sh create mode 100755 config/waybar/modules/weather.sh create mode 100644 config/waybar/style.css create mode 100755 config/waybar/waybar.sh create mode 100644 config/wlogout/layout create mode 100644 config/wlogout/style.css create mode 100644 config/wofi/config create mode 100755 config/wofi/launch.sh create mode 120000 config/wofi/style.css create mode 100644 config/yazi/flavors/catppuccin-latte.yazi/LICENSE create mode 100644 config/yazi/flavors/catppuccin-latte.yazi/LICENSE-tmtheme create mode 100644 config/yazi/flavors/catppuccin-latte.yazi/README.md create mode 100644 config/yazi/flavors/catppuccin-latte.yazi/flavor.toml create mode 100644 config/yazi/flavors/catppuccin-latte.yazi/preview.png create mode 100644 config/yazi/flavors/catppuccin-latte.yazi/tmtheme.xml create mode 100644 config/yazi/flavors/catppuccin-mocha.yazi/LICENSE create mode 100644 config/yazi/flavors/catppuccin-mocha.yazi/LICENSE-tmtheme create mode 100644 config/yazi/flavors/catppuccin-mocha.yazi/README.md create mode 100644 config/yazi/flavors/catppuccin-mocha.yazi/flavor.toml create mode 100644 config/yazi/flavors/catppuccin-mocha.yazi/preview.png create mode 100644 config/yazi/flavors/catppuccin-mocha.yazi/tmtheme.xml create mode 100644 config/yazi/init.lua create mode 100644 config/yazi/plugins/auto-layout.yazi/LICENSE create mode 100644 config/yazi/plugins/auto-layout.yazi/README.md create mode 100644 config/yazi/plugins/auto-layout.yazi/main.lua create mode 100644 config/yazi/plugins/git.yazi/LICENSE create mode 100644 config/yazi/plugins/git.yazi/README.md create mode 100644 config/yazi/plugins/git.yazi/main.lua create mode 100644 config/yazi/plugins/sidebar-status.yazi/main.lua create mode 100644 config/yazi/yazi.toml create mode 100644 config/zed/keymap.json create mode 100644 config/zed/settings.json create mode 100644 config/zellij/config.kdl create mode 100644 config/zellij/layouts/dev.kdl create mode 100644 config/zellij/layouts/tabs.kdl create mode 100644 flake.lock create mode 100644 flake.nix create mode 100644 fonts/Myna-Bold.otf create mode 100644 fonts/Myna-BoldItalic.otf create mode 100644 fonts/Myna-Regular.otf create mode 100644 fonts/Myna-RegularItalic.otf create mode 100644 fonts/MynaNerdFont-Regular.otf create mode 100644 home.nix create mode 100755 local_bin/random_wallpaper create mode 100755 local_share/dark-mode.d/theme-switch create mode 100644 local_share/easyeffects/input/default.json create mode 100755 local_share/light-mode.d/theme-switch create mode 100644 pi/agent/settings.json create mode 120000 result create mode 100644 secrets/git_config.age create mode 100644 secrets/jj_config.age create mode 100644 secrets/secrets.nix diff --git a/agents/skills/c4-model/SKILL.md b/agents/skills/c4-model/SKILL.md new file mode 100644 index 0000000..92115fd --- /dev/null +++ b/agents/skills/c4-model/SKILL.md @@ -0,0 +1,84 @@ +--- +name: c4-model +description: Generate C4 architecture documentation at any level using specialized agents (Code, Component, Container, Context). Use this skill whenever the user wants to document system architecture with the C4 model, create architecture diagrams, document code structure, define component boundaries, map deployment containers, or create system context diagrams. Trigger for prompts like "document architecture", "create C4 diagram", "generate architecture docs", "map system components", "create context diagram", "document this codebase architecture", or "analyze code structure with C4". Always use this skill for C4 documentation requests, even partial ones like a single level. +--- + +# C4 Model Documentation Orchestrator + +Orchestrates four specialized agents to generate C4 model architecture documentation. Each agent targets one hierarchical level, producing documentation files that feed into the next level. + +## C4 Levels Overview + +| Level | Agent subagent_type | Input | Output files | +| ------------- | ------------------- | --------------------------------------- | --------------------------------- | +| **Code** | `c4-code` | Source directories | `c4-code-.md` per directory | +| **Component** | `c4-component` | `c4-code-*.md` files | `c4-component-.md` + index | +| **Container** | `c4-container` | Component docs + deployment configs | `c4-container.md` + OpenAPI specs | +| **Context** | `c4-context` | Container/component docs + README/tests | `c4-context.md` | + +## Workflow: Bottom-Up (Standard) + +When the user requests full C4 documentation: + +``` +1. Code level → Analyze all source directories (run in parallel per directory) +2. Component → Synthesize code docs into logical components +3. Container → Map components to deployment units + document APIs +4. Context → Create high-level stakeholder view +``` + +Run agents in sequence (each level depends on the previous). Within the Code level, multiple directories can be processed in parallel. + +## Selective Documentation + +Ask the user which level(s) they need if not clear from context: + +- Single level: invoke just that agent +- Partial chain: e.g., only Code + Component +- Full chain: all four in order + +## Agent Reference Files + +When working on a specific level, read the corresponding reference file for full agent instructions, templates, and diagram syntax: + +- **Code level** → `references/c4-code.md` +- **Component level** → `references/c4-component.md` +- **Container level** → `references/c4-container.md` +- **Context level** → `references/c4-context.md` + +## Output Organization + +Suggest placing all documentation in a consistent location: + +``` +docs/architecture/ +├── c4-code-handlers.md # Code level (one per directory) +├── c4-code-services.md +├── c4-component-api.md # Component level +├── c4-component-domain.md +├── c4-component.md # Component index +├── c4-container.md # Container level +├── api-spec.yaml # OpenAPI specs (if generated) +└── c4-context.md # Context level +``` + +## Invoking the Agents + +Use the `Agent` tool with the appropriate `subagent_type`. Example for Code level: + +``` +Agent( + subagent_type="c4-code", + prompt="Analyze the directory src/handlers and create C4 Code-level documentation. Save to docs/architecture/c4-code-handlers.md" +) +``` + +For the Context level agent, note it lives at `./references/c4-context.md` — use `subagent_type="c4-context"`. + +## Key Principles + +- **Bottom-up**: Code → Component → Container → Context (each level builds on the previous) +- **Parallel Code runs**: Multiple directories can be documented simultaneously +- **Sequential synthesis**: Component, Container, and Context must run after their inputs exist +- **Self-contained**: Each output file should be understandable independently +- **Mermaid diagrams**: Each level has specific diagram types (see reference files) diff --git a/agents/skills/c4-model/references/c4-code.md b/agents/skills/c4-model/references/c4-code.md new file mode 100644 index 0000000..6896d17 --- /dev/null +++ b/agents/skills/c4-model/references/c4-code.md @@ -0,0 +1,153 @@ +# C4 Code Level — Agent Reference + +Agent: `c4-code` | Model: haiku | Output: `c4-code-.md` + +## Purpose + +Documents individual source code directories at the most granular C4 level. Captures every function, class, module, and dependency. Creates documentation that feeds into the Component level. + +## Capabilities + +- Directory structure analysis and file relationships +- Function/method signature extraction (parameters, return types, type hints) +- Class hierarchy and module export documentation +- Internal and external dependency mapping +- Design pattern and architectural pattern recognition +- Language-agnostic (Python, TypeScript, Java, Go, Rust, C#, Ruby, etc.) +- Mermaid diagram generation (classDiagram for OOP, flowchart for FP/procedural) + +## Programming Paradigm → Diagram Type + +| Code Style | Diagram | When | +| -------------------------------- | -------------------------------- | -------------------------------------------------- | +| OOP (classes, interfaces) | `classDiagram` | Inheritance, composition, interface implementation | +| FP (pure functions, pipelines) | `flowchart` | Data transformations, function composition | +| FP (modules with exports) | `classDiagram` with `<>` | Module structure and dependencies | +| Procedural (structs + functions) | `classDiagram` | Data structures and associated functions | +| Mixed | Combination | Use multiple diagrams if needed | + +## Workflow + +1. Analyze directory structure (file relationships, module boundaries) +2. Extract all functions/classes/modules with complete signatures +3. Map all dependencies (internal and external) +4. Generate structured documentation following the template below +5. Add Mermaid diagrams for complex relationships + +## Documentation Template + +```markdown +# C4 Code Level: [Directory Name] + +## Overview + +- **Name**: [Descriptive name for this code directory] +- **Description**: [Short description of what this code does] +- **Location**: [Link to actual directory path] +- **Language**: [Primary programming language(s)] +- **Purpose**: [What this code accomplishes] + +## Code Elements + +### Functions/Methods + +- `functionName(param1: Type, param2: Type): ReturnType` + - Description: [What this function does] + - Location: [file path:line number] + - Dependencies: [what this function depends on] + +### Classes/Modules + +- `ClassName` + - Description: [What this class does] + - Location: [file path] + - Methods: [list of methods] + - Dependencies: [what this class depends on] + +## Dependencies + +### Internal Dependencies + +- [List of internal code dependencies] + +### External Dependencies + +- [List of external libraries, frameworks, services] + +## Relationships + +[Optional Mermaid diagram — see paradigm table above] +``` + +## OOP Diagram Example + +```mermaid +--- +title: Code Diagram for [Component Name] +--- +classDiagram + namespace ComponentName { + class Class1 { + +attribute1 Type + +method1() ReturnType + } + class Interface1 { + <> + +requiredMethod() ReturnType + } + } + Class1 ..|> Interface1 : implements +``` + +## FP Module Structure Example + +```mermaid +--- +title: Module Structure for [Component Name] +--- +classDiagram + namespace DataProcessing { + class validators { + <> + +validateInput(data) Result~Data, Error~ + +sanitize(input) string + } + class transformers { + <> + +parseJSON(raw) Record + +normalize(data) NormalizedData + } + } + transformers --> validators : uses +``` + +## FP Data Flow Example + +```mermaid +--- +title: Data Pipeline for [Component Name] +--- +flowchart LR + subgraph Input + A[readFile] + end + subgraph Transform + B[parseJSON] + C[validateInput] + D[normalize] + end + subgraph Output + E[writeFile] + end + A -->|raw string| B + B -->|parsed data| C + C -->|valid data| D + D -->|normalized| E +``` + +## Notes + +- Analyze starting from the deepest directories upward +- Document every significant code element, not just public APIs +- Create one `c4-code-.md` file per analyzed directory +- This output feeds directly into the Component level agent diff --git a/agents/skills/c4-model/references/c4-component.md b/agents/skills/c4-model/references/c4-component.md new file mode 100644 index 0000000..746c6cf --- /dev/null +++ b/agents/skills/c4-model/references/c4-component.md @@ -0,0 +1,121 @@ +# C4 Component Level — Agent Reference + +Agent: `c4-component` | Model: sonnet | Input: `c4-code-*.md` | Output: `c4-component-.md` + index + +## Purpose + +Synthesizes C4 Code-level documentation into logical, well-bounded components. Defines component interfaces, maps relationships, and creates Component-level diagrams. Bridges code detail with deployment concerns (handled at Container level). + +## Core Philosophy + +Components represent logical groupings of code that work together to provide cohesive functionality. Boundaries should align with domain, technical, or organizational boundaries. Each component must have clear responsibilities and well-defined interfaces. + +## Workflow + +1. Review all `c4-code-*.md` files to understand code structure +2. Identify logical component boundaries (domain, technical, or organizational) +3. Define component names, descriptions, and responsibilities +4. List software features provided by each component +5. Link `c4-code-*.md` files to their containing components +6. Document component interfaces (APIs, protocols, data contracts) +7. Map dependencies and relationships between components +8. Generate Mermaid C4Component diagrams +9. Create master `c4-component.md` index with all components + +## Documentation Template + +```markdown +# C4 Component Level: [Component Name] + +## Overview + +- **Name**: [Component name] +- **Description**: [Short description of component purpose] +- **Type**: [Application, Service, Library, etc.] +- **Technology**: [Primary technologies used] + +## Purpose + +[Detailed description of what this component does and what problems it solves] + +## Software Features + +- [Feature 1]: [Description] +- [Feature 2]: [Description] + +## Code Elements + +This component contains the following code-level elements: + +- [c4-code-file-1.md](./c4-code-file-1.md) - [Description] +- [c4-code-file-2.md](./c4-code-file-2.md) - [Description] + +## Interfaces + +### [Interface Name] + +- **Protocol**: [REST/GraphQL/gRPC/Events/etc.] +- **Description**: [What this interface provides] +- **Operations**: + - `operationName(params): ReturnType` - [Description] + +## Dependencies + +### Components Used + +- [Component Name]: [How it's used] + +### External Systems + +- [External System]: [How it's used] + +## Component Diagram + +[See diagram syntax below] +``` + +## Component Diagram Syntax + +Use `C4Component` Mermaid syntax. Shows components **within a single container**: + +```mermaid +C4Component + title Component Diagram for [Container Name] + + Container_Boundary(container, "Container Name") { + Component(component1, "Component 1", "Type", "Description") + Component(component2, "Component 2", "Type", "Description") + ComponentDb(component3, "Component 3", "Database", "Description") + } + Container_Ext(externalContainer, "External Container", "Description") + System_Ext(externalSystem, "External System", "Description") + + Rel(component1, component2, "Uses") + Rel(component2, component3, "Reads from and writes to") + Rel(component1, externalContainer, "Uses", "API") +``` + +## Master Index Template + +```markdown +# C4 Component Level: System Overview + +## System Components + +### [Component 1] + +- **Name**: [Component name] +- **Description**: [Short description] +- **Documentation**: [c4-component-name-1.md](./c4-component-name-1.md) + +## Component Relationships + +[Mermaid diagram showing all components and their relationships] +``` + +## Key Principles + +- Focus on **logical grouping**, not deployment concerns (deferred to Container level) +- Component boundaries should reflect domain or technical cohesion +- Every component needs clear responsibilities and at least one defined interface +- This output feeds directly into the Container level agent diff --git a/agents/skills/c4-model/references/c4-container.md b/agents/skills/c4-model/references/c4-container.md new file mode 100644 index 0000000..759fe1e --- /dev/null +++ b/agents/skills/c4-model/references/c4-container.md @@ -0,0 +1,275 @@ +# C4 Container Level — Agent Reference + +Agent: `c4-container` | Model: sonnet | Input: Component docs + deployment configs | Output: `c4-container.md` + OpenAPI specs + +## Purpose + +Maps logical components to deployment containers (processes, applications, services, databases). Documents container interfaces as OpenAPI/Swagger specs. Shows high-level technology choices and deployment architecture. + +## Core Philosophy + +Containers are deployable units that must be running for the system to work. Container diagrams show **high-level technology choices** and how responsibilities are distributed. Technology details belong here, not at Component or Context level. + +## Workflow + +1. Review all `c4-component-*.md` files to understand component structure +2. Review deployment definitions (Dockerfiles, K8s manifests, Terraform, cloud configs) +3. Map components to containers based on deployment reality +4. Identify container names, descriptions, and deployment characteristics +5. Create OpenAPI/Swagger specs for all container interfaces +6. Map inter-container communication (HTTP, gRPC, queues, events) +7. Generate Mermaid C4Container diagrams +8. Link container docs to API specs and deployment configs + +## Documentation Template + +```markdown +# C4 Container Level: System Deployment + +## Containers + +### [Container Name] + +- **Name**: [Container name] +- **Description**: [Short description of container purpose and deployment] +- **Type**: [Web Application, API, Database, Message Queue, etc.] +- **Technology**: [Node.js, Python, PostgreSQL, Redis, etc.] +- **Deployment**: [Docker, Kubernetes, Cloud Service, etc.] + +## Purpose + +[Detailed description of what this container does and how it's deployed] + +## Components + +This container deploys the following components: + +- [Component Name]: [Description] + - Documentation: [c4-component-name.md](./c4-component-name.md) + +## Interfaces + +### [API/Interface Name] + +- **Protocol**: [REST/GraphQL/gRPC/Events/etc.] +- **Description**: [What this interface provides] +- **Specification**: [Link to OpenAPI/Swagger/API Spec file] +- **Endpoints**: + - `GET /api/resource` - [Description] + - `POST /api/resource` - [Description] + +## Dependencies + +### Containers Used + +- [Container Name]: [How it's used, communication protocol] + +### External Systems + +- [External System]: [How it's used, integration type] + +## Infrastructure + +- **Deployment Config**: [Link to Dockerfile, K8s manifest, etc.] +- **Scaling**: [Horizontal/vertical scaling strategy] +- **Resources**: [CPU, memory, storage requirements] + +## Container Diagram + +[See diagram syntax below] +``` + +## Container Diagram Syntax + +```mermaid +C4Container + title Container Diagram for [System Name] + + Person(user, "User", "Uses the system") + System_Boundary(system, "System Name") { + Container(webApp, "Web Application", "Spring Boot, Java", "Provides web interface") + Container(api, "API Application", "Node.js, Express", "Provides REST API") + ContainerDb(database, "Database", "PostgreSQL", "Stores data") + Container_Queue(messageQueue, "Message Queue", "RabbitMQ", "Handles async messaging") + } + System_Ext(external, "External System", "Third-party service") + + Rel(user, webApp, "Uses", "HTTPS") + Rel(webApp, api, "Makes API calls to", "JSON/HTTPS") + Rel(api, database, "Reads from and writes to", "SQL") + Rel(api, messageQueue, "Publishes messages to") + Rel(api, external, "Uses", "API") +``` + +## OpenAPI Spec Template + +For each container API, create a specification file (e.g., `api-spec.yaml`): + +```yaml +openapi: 3.1.0 +info: + title: [Container Name] API + description: [API description] + version: 1.0.0 +servers: + - url: https://api.example.com + description: Production server +paths: + /api/resource: + get: + summary: [Operation summary] + description: [Operation description] + responses: + '200': + description: [Response description] + content: + application/json: + schema: + type: object +``` + +## Key Principles + +- This is where **technology details belong** in the C4 model +- Map based on deployment reality, not just logical grouping +- Every container interface should have an OpenAPI/Swagger spec +- Show communication protocols between containers +- Link to deployment configs (Dockerfiles, K8s manifests, etc.) +- This output feeds into the Context level agen# C4 Container Level — Agent Reference + +Agent: `c4-container` | Model: sonnet | Input: Component docs + deployment configs | Output: `c4-container.md` + OpenAPI specs + +## Purpose + +Maps logical components to deployment containers (processes, applications, services, databases). Documents container interfaces as OpenAPI/Swagger specs. Shows high-level technology choices and deployment architecture. + +## Core Philosophy + +Containers are deployable units that must be running for the system to work. Container diagrams show **high-level technology choices** and how responsibilities are distributed. Technology details belong here, not at Component or Context level. + +## Workflow + +1. Review all `c4-component-*.md` files to understand component structure +2. Review deployment definitions (Dockerfiles, K8s manifests, Terraform, cloud configs) +3. Map components to containers based on deployment reality +4. Identify container names, descriptions, and deployment characteristics +5. Create OpenAPI/Swagger specs for all container interfaces +6. Map inter-container communication (HTTP, gRPC, queues, events) +7. Generate Mermaid C4Container diagrams +8. Link container docs to API specs and deployment configs + +## Documentation Template + +```markdown +# C4 Container Level: System Deployment + +## Containers + +### [Container Name] + +- **Name**: [Container name] +- **Description**: [Short description of container purpose and deployment] +- **Type**: [Web Application, API, Database, Message Queue, etc.] +- **Technology**: [Node.js, Python, PostgreSQL, Redis, etc.] +- **Deployment**: [Docker, Kubernetes, Cloud Service, etc.] + +## Purpose + +[Detailed description of what this container does and how it's deployed] + +## Components + +This container deploys the following components: + +- [Component Name]: [Description] + - Documentation: [c4-component-name.md](./c4-component-name.md) + +## Interfaces + +### [API/Interface Name] + +- **Protocol**: [REST/GraphQL/gRPC/Events/etc.] +- **Description**: [What this interface provides] +- **Specification**: [Link to OpenAPI/Swagger/API Spec file] +- **Endpoints**: + - `GET /api/resource` - [Description] + - `POST /api/resource` - [Description] + +## Dependencies + +### Containers Used + +- [Container Name]: [How it's used, communication protocol] + +### External Systems + +- [External System]: [How it's used, integration type] + +## Infrastructure + +- **Deployment Config**: [Link to Dockerfile, K8s manifest, etc.] +- **Scaling**: [Horizontal/vertical scaling strategy] +- **Resources**: [CPU, memory, storage requirements] + +## Container Diagram + +[See diagram syntax below] +``` + +## Container Diagram Syntax + +```mermaid +C4Container + title Container Diagram for [System Name] + + Person(user, "User", "Uses the system") + System_Boundary(system, "System Name") { + Container(webApp, "Web Application", "Spring Boot, Java", "Provides web interface") + Container(api, "API Application", "Node.js, Express", "Provides REST API") + ContainerDb(database, "Database", "PostgreSQL", "Stores data") + Container_Queue(messageQueue, "Message Queue", "RabbitMQ", "Handles async messaging") + } + System_Ext(external, "External System", "Third-party service") + + Rel(user, webApp, "Uses", "HTTPS") + Rel(webApp, api, "Makes API calls to", "JSON/HTTPS") + Rel(api, database, "Reads from and writes to", "SQL") + Rel(api, messageQueue, "Publishes messages to") + Rel(api, external, "Uses", "API") +``` + +## OpenAPI Spec Template + +For each container API, create a specification file (e.g., `api-spec.yaml`): + +```yaml +openapi: 3.1.0 +info: + title: [Container Name] API + description: [API description] + version: 1.0.0 +servers: + - url: https://api.example.com + description: Production server +paths: + /api/resource: + get: + summary: [Operation summary] + description: [Operation description] + responses: + '200': + description: [Response description] + content: + application/json: + schema: + type: object +``` + +## Key Principles + +- This is where **technology details belong** in the C4 model +- Map based on deployment reality, not just logical grouping +- Every container interface should have an OpenAPI/Swagger spec +- Show communication protocols between containers +- Link to deployment configs (Dockerfiles, K8s manifests, etc.) +- This output feeds into the Context level agent diff --git a/agents/skills/c4-model/references/c4-context.md b/agents/skills/c4-model/references/c4-context.md new file mode 100644 index 0000000..f6fdf74 --- /dev/null +++ b/agents/skills/c4-model/references/c4-context.md @@ -0,0 +1,117 @@ +# C4 Context Level — Agent Reference + +Agent: `c4-context` | Model: sonnet | Input: Container/component docs + README + tests | Output: `c4-context.md` + +## Purpose + +Creates the highest-level C4 view: the system as a box surrounded by users and external systems. Focuses on **people and software systems**, not technologies. Produces stakeholder-friendly documentation understandable by non-technical audiences. + +## Core Philosophy + +Context diagrams show the system boundary, all users (human and programmatic), and all external systems the system interacts with. Technology, protocols, and low-level details are deliberately excluded at this level. + +## Workflow + +1. Review `c4-container.md` to understand system deployment +2. Review `c4-component.md` to understand system components +3. Review system documentation (README, architecture docs, requirements) +4. Review test files to understand system behavior and features +5. Identify system purpose and boundaries +6. Identify all personas (human users AND programmatic users / external systems) +7. Identify all high-level features provided by the system +8. Map user journeys for each key feature per persona +9. Identify all external systems and dependencies +10. Generate Mermaid C4Context diagram +11. Create comprehensive context documentation + +## Documentation Template + +```markdown +# C4 Context Level: System Context + +## System Overview + +### Short Description + +[One-sentence description of what the system does] + +### Long Description + +[Detailed description of the system's purpose, capabilities, and the problems it solves] + +## Personas + +### [Persona Name] + +- **Type**: [Human User / Programmatic User / External System] +- **Description**: [Who this persona is and what they need] +- **Goals**: [What this persona wants to achieve] +- **Key Features Used**: [List of features this persona uses] + +## System Features + +### [Feature Name] + +- **Description**: [What this feature does] +- **Users**: [Which personas use this feature] +- **User Journey**: [Link to user journey map] + +## User Journeys + +### [Feature Name] - [Persona Name] Journey + +1. [Step 1]: [Description] +2. [Step 2]: [Description] +3. [Step 3]: [Description] + +### [External System] Integration Journey + +1. [Step 1]: [Description] +2. [Step 2]: [Description] + +## External Systems and Dependencies + +### [External System Name] + +- **Type**: [Database, API, Service, Message Queue, etc.] +- **Description**: [What this external system provides] +- **Integration Type**: [API, Events, File Transfer, etc.] +- **Purpose**: [Why the system depends on this] + +## System Context Diagram + +[See diagram syntax below] + +## Related Documentation + +- [Container Documentation](./c4-container.md) +- [Component Documentation](./c4-component.md) +``` + +## Context Diagram Syntax + +```mermaid +C4Context + title System Context Diagram + + Person(user, "User", "Uses the system to accomplish their goals") + System(system, "System Name", "Provides features X, Y, and Z") + System_Ext(external1, "External System 1", "Provides service A") + System_Ext(external2, "External System 2", "Provides service B") + SystemDb(externalDb, "External Database", "Stores data") + + Rel(user, system, "Uses") + Rel(system, external1, "Uses", "API") + Rel(system, external2, "Sends events to") + Rel(system, externalDb, "Reads from and writes to") +``` + +## Key Principles + +- Focus on **people and software systems**, not technologies or protocols +- Show the **system boundary** clearly (what's inside vs. outside) +- Include **all users**: human and programmatic (external systems that call the system are also "users") +- Include all **external systems** the system interacts with +- Keep it **stakeholder-friendly** — avoid implementation details +- Document **user journeys** for each key feature and persona +- This is the final step of the C4 documentation chain diff --git a/agents/skills/cavecrew/SKILL.md b/agents/skills/cavecrew/SKILL.md new file mode 100644 index 0000000..efa413f --- /dev/null +++ b/agents/skills/cavecrew/SKILL.md @@ -0,0 +1,82 @@ +--- +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 new file mode 100644 index 0000000..729318c --- /dev/null +++ b/agents/skills/caveman-commit/SKILL.md @@ -0,0 +1,65 @@ +--- +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 new file mode 100644 index 0000000..7c0e8ba --- /dev/null +++ b/agents/skills/caveman-compress/README.md @@ -0,0 +1,163 @@ +

+ +

+ +

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 new file mode 100644 index 0000000..693108c --- /dev/null +++ b/agents/skills/caveman-compress/SECURITY.md @@ -0,0 +1,31 @@ +# 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 new file mode 100644 index 0000000..7b3e3aa --- /dev/null +++ b/agents/skills/caveman-compress/SKILL.md @@ -0,0 +1,111 @@ +--- +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 new file mode 100644 index 0000000..16b8c53 --- /dev/null +++ b/agents/skills/caveman-compress/scripts/__init__.py @@ -0,0 +1,9 @@ +"""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 new file mode 100644 index 0000000..4e28416 --- /dev/null +++ b/agents/skills/caveman-compress/scripts/__main__.py @@ -0,0 +1,3 @@ +from .cli import main + +main() diff --git a/agents/skills/caveman-compress/scripts/benchmark.py b/agents/skills/caveman-compress/scripts/benchmark.py new file mode 100644 index 0000000..eac927d --- /dev/null +++ b/agents/skills/caveman-compress/scripts/benchmark.py @@ -0,0 +1,78 @@ +#!/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 new file mode 100644 index 0000000..428fd86 --- /dev/null +++ b/agents/skills/caveman-compress/scripts/cli.py @@ -0,0 +1,73 @@ +#!/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 new file mode 100644 index 0000000..1622a7a --- /dev/null +++ b/agents/skills/caveman-compress/scripts/compress.py @@ -0,0 +1,176 @@ +#!/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 new file mode 100644 index 0000000..5f50fd3 --- /dev/null +++ b/agents/skills/caveman-compress/scripts/detect.py @@ -0,0 +1,121 @@ +#!/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 new file mode 100644 index 0000000..3c4d4c1 --- /dev/null +++ b/agents/skills/caveman-compress/scripts/validate.py @@ -0,0 +1,189 @@ +#!/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 new file mode 100644 index 0000000..078e487 --- /dev/null +++ b/agents/skills/caveman-help/SKILL.md @@ -0,0 +1,59 @@ +--- +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 new file mode 100644 index 0000000..48f4adb --- /dev/null +++ b/agents/skills/caveman-review/SKILL.md @@ -0,0 +1,55 @@ +--- +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 new file mode 100644 index 0000000..a7348ac --- /dev/null +++ b/agents/skills/caveman-stats/SKILL.md @@ -0,0 +1,10 @@ +--- +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 new file mode 100644 index 0000000..2ab498b --- /dev/null +++ b/agents/skills/caveman/SKILL.md @@ -0,0 +1,67 @@ +--- +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/compress/SKILL.md b/agents/skills/compress/SKILL.md new file mode 100644 index 0000000..8537948 --- /dev/null +++ b/agents/skills/compress/SKILL.md @@ -0,0 +1,111 @@ +--- +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 new file mode 100644 index 0000000..16b8c53 --- /dev/null +++ b/agents/skills/compress/scripts/__init__.py @@ -0,0 +1,9 @@ +"""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 new file mode 100644 index 0000000..4e28416 --- /dev/null +++ b/agents/skills/compress/scripts/__main__.py @@ -0,0 +1,3 @@ +from .cli import main + +main() diff --git a/agents/skills/compress/scripts/benchmark.py b/agents/skills/compress/scripts/benchmark.py new file mode 100644 index 0000000..eac927d --- /dev/null +++ b/agents/skills/compress/scripts/benchmark.py @@ -0,0 +1,78 @@ +#!/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 new file mode 100644 index 0000000..c314f87 --- /dev/null +++ b/agents/skills/compress/scripts/cli.py @@ -0,0 +1,85 @@ +#!/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 new file mode 100644 index 0000000..7adc4fb --- /dev/null +++ b/agents/skills/compress/scripts/compress.py @@ -0,0 +1,254 @@ +#!/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 new file mode 100644 index 0000000..8d5f6d7 --- /dev/null +++ b/agents/skills/compress/scripts/detect.py @@ -0,0 +1,121 @@ +#!/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 new file mode 100644 index 0000000..dc07307 --- /dev/null +++ b/agents/skills/compress/scripts/validate.py @@ -0,0 +1,213 @@ +#!/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/diagnose/SKILL.md b/agents/skills/diagnose/SKILL.md new file mode 100644 index 0000000..ed55bda --- /dev/null +++ b/agents/skills/diagnose/SKILL.md @@ -0,0 +1,117 @@ +--- +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. +--- + +# Diagnose + +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. + +## Phase 1 — Build a feedback loop + +**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. + +Spend disproportionate effort here. **Be aggressive. Be creative. Refuse to give up.** + +### Ways to construct one — try them in roughly this order + +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. +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. +8. **Bisection harness.** If the bug appeared between two known states (commit, dataset, version), automate "boot at state X, check, repeat" so you can `git bisect run` it. +9. **Differential loop.** Run the same input through old-version vs new-version (or two configs) and diff outputs. +10. **HITL bash script.** Last resort. If a human must click, drive _them_ with `scripts/hitl-loop.template.sh` so the loop is still structured. Captured output feeds back to you. + +Build the right feedback loop, and the bug is 90% fixed. + +### Iterate on the loop itself + +Treat the loop as a product. Once you have _a_ loop, ask: + +- 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. + +### 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. + +### 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. + +Do not proceed to Phase 2 until you have a loop you believe in. + +## Phase 2 — Reproduce + +Run the loop. Watch the bug appear. + +Confirm: + +- [ ] 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. + +## Phase 3 — Hypothesise + +Generate **3–5 ranked hypotheses** before testing any of them. Single-hypothesis generation anchors on the first plausible idea. + +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. + +**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 + +Each probe must map to a specific prediction from Phase 3. **Change one variable at a time.** + +Tool preference: + +1. **Debugger / REPL inspection** if the env supports it. One breakpoint beats ten logs. +2. **Targeted logs** at the boundaries that distinguish hypotheses. +3. Never "log everything and grep". + +**Tag every debug log** with a unique prefix, e.g. `[DEBUG-a4f2]`. Cleanup at the end becomes a single grep. Untagged logs survive; tagged logs die. + +**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 + +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. + +**If no correct seam exists, that itself is the finding.** Note it. The codebase architecture is preventing the bug from being locked down. Flag this for the next phase. + +If a correct seam exists: + +1. Turn the minimised repro into a failing test at that seam. +2. Watch it fail. +3. Apply the fix. +4. Watch it pass. +5. Re-run the Phase 1 feedback loop against the original (un-minimised) scenario. + +## Phase 6 — Cleanup + post-mortem + +Required before declaring done: + +- [ ] Original repro no longer reproduces (re-run the Phase 1 loop) +- [ ] 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. diff --git a/agents/skills/diagnose/scripts/hitl-loop.template.sh b/agents/skills/diagnose/scripts/hitl-loop.template.sh new file mode 100644 index 0000000..40afc46 --- /dev/null +++ b/agents/skills/diagnose/scripts/hitl-loop.template.sh @@ -0,0 +1,41 @@ +#!/usr/bin/env bash +# Human-in-the-loop reproduction loop. +# Copy this file, edit the steps below, and run it. +# The agent runs the script; the user follows prompts in their terminal. +# +# Usage: +# bash hitl-loop.template.sh +# +# Two helpers: +# step "" → show instruction, wait for Enter +# capture VAR "" → show question, read response into VAR +# +# At the end, captured values are printed as KEY=VALUE for the agent to parse. + +set -euo pipefail + +step() { + printf '\n>>> %s\n' "$1" + read -r -p " [Enter when done] " _ +} + +capture() { + local var="$1" question="$2" answer + printf '\n>>> %s\n' "$question" + read -r -p " > " answer + printf -v "$var" '%s' "$answer" +} + +# --- edit below --------------------------------------------------------- + +step "Open the app at http://localhost:3000 and sign in." + +capture ERRORED "Click the 'Export' button. Did it throw an error? (y/n)" + +capture ERROR_MSG "Paste the error message (or 'none'):" + +# --- edit above --------------------------------------------------------- + +printf '\n--- Captured ---\n' +printf 'ERRORED=%s\n' "$ERRORED" +printf 'ERROR_MSG=%s\n' "$ERROR_MSG" diff --git a/agents/skills/find-skills/SKILL.md b/agents/skills/find-skills/SKILL.md new file mode 100644 index 0000000..114c663 --- /dev/null +++ b/agents/skills/find-skills/SKILL.md @@ -0,0 +1,142 @@ +--- +name: find-skills +description: Helps users discover and install agent skills when they ask questions like "how do I do X", "find a skill for X", "is there a skill that can...", or express interest in extending capabilities. This skill should be used when the user is looking for functionality that might exist as an installable skill. +--- + +# Find Skills + +This skill helps you discover and install skills from the open agent skills ecosystem. + +## When to Use This Skill + +Use this skill when the user: + +- Asks "how do I do X" where X might be a common task with an existing skill +- Says "find a skill for X" or "is there a skill for X" +- Asks "can you do X" where X is a specialized capability +- Expresses interest in extending agent capabilities +- Wants to search for tools, templates, or workflows +- Mentions they wish they had help with a specific domain (design, testing, deployment, etc.) + +## What is the Skills CLI? + +The Skills CLI (`npx skills`) is the package manager for the open agent skills ecosystem. Skills are modular packages that extend agent capabilities with specialized knowledge, workflows, and tools. + +**Key commands:** + +- `npx skills find [query]` - Search for skills interactively or by keyword +- `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/ + +## How to Help Users Find Skills + +### Step 1: Understand What They Need + +When a user asks for help with something, identify: + +1. The domain (e.g., React, testing, design, deployment) +2. The specific task (e.g., writing tests, creating animations, reviewing PRs) +3. Whether this is a common enough task that a skill likely exists + +### Step 2: Check the Leaderboard First + +Before running a CLI search, check the [skills.sh leaderboard](https://skills.sh/) to see if a well-known skill already exists for the domain. The leaderboard ranks skills by total installs, surfacing the most popular and battle-tested options. + +For example, top skills for web development include: +- `vercel-labs/agent-skills` — React, Next.js, web design (100K+ installs each) +- `anthropics/skills` — Frontend design, document processing (100K+ installs) + +### Step 3: Search for Skills + +If the leaderboard doesn't cover the user's need, run the find command: + +```bash +npx skills find [query] +``` + +For example: + +- User asks "how do I make my React app faster?" → `npx skills find react performance` +- User asks "can you help me with PR reviews?" → `npx skills find pr review` +- User asks "I need to create a changelog" → `npx skills find changelog` + +### Step 4: Verify Quality Before Recommending + +**Do not recommend a skill based solely on search results.** Always verify: + +1. **Install count** — Prefer skills with 1K+ installs. Be cautious with anything under 100. +2. **Source reputation** — Official sources (`vercel-labs`, `anthropics`, `microsoft`) are more trustworthy than unknown authors. +3. **GitHub stars** — Check the source repository. A skill from a repo with <100 stars should be treated with skepticism. + +### Step 5: Present Options to the User + +When you find relevant skills, present them to the user with: + +1. The skill name and what it does +2. The install count and source +3. The install command they can run +4. A link to learn more at skills.sh + +Example response: + +``` +I found a skill that might help! The "react-best-practices" skill provides +React and Next.js performance optimization guidelines from Vercel Engineering. +(185K installs) + +To install it: +npx skills add vercel-labs/agent-skills@react-best-practices + +Learn more: https://skills.sh/vercel-labs/agent-skills/react-best-practices +``` + +### Step 6: Offer to Install + +If the user wants to proceed, you can install the skill for them: + +```bash +npx skills add -g -y +``` + +The `-g` flag installs globally (user-level) and `-y` skips confirmation prompts. + +## Common Skill Categories + +When searching, consider these common categories: + +| Category | Example Queries | +| --------------- | ---------------------------------------- | +| Web Development | react, nextjs, typescript, css, tailwind | +| Testing | testing, jest, playwright, e2e | +| DevOps | deploy, docker, kubernetes, ci-cd | +| Documentation | docs, readme, changelog, api-docs | +| Code Quality | review, lint, refactor, best-practices | +| Design | ui, ux, design-system, accessibility | +| Productivity | workflow, automation, git | + +## Tips for Effective Searches + +1. **Use specific keywords**: "react testing" is better than just "testing" +2. **Try alternative terms**: If "deploy" doesn't work, try "deployment" or "ci-cd" +3. **Check popular sources**: Many skills come from `vercel-labs/agent-skills` or `ComposioHQ/awesome-claude-skills` + +## When No Skills Are Found + +If no relevant skills exist: + +1. Acknowledge that no existing skill was found +2. Offer to help with the task directly using your general capabilities +3. Suggest the user could create their own skill with `npx skills init` + +Example: + +``` +I searched for skills related to "xyz" but didn't find any matches. +I can still help you with this task directly! Would you like me to proceed? + +If this is something you do often, you could create your own skill: +npx skills init my-xyz-skill +``` diff --git a/agents/skills/graphify/.graphify_version b/agents/skills/graphify/.graphify_version new file mode 100644 index 0000000..ff70965 --- /dev/null +++ b/agents/skills/graphify/.graphify_version @@ -0,0 +1 @@ +0.7.13 \ No newline at end of file diff --git a/agents/skills/graphify/SKILL.md b/agents/skills/graphify/SKILL.md new file mode 100644 index 0000000..8c296b0 --- /dev/null +++ b/agents/skills/graphify/SKILL.md @@ -0,0 +1,1031 @@ +--- +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 new file mode 100644 index 0000000..bd04394 --- /dev/null +++ b/agents/skills/grill-me/SKILL.md @@ -0,0 +1,10 @@ +--- +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". +--- + +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. diff --git a/agents/skills/grill-with-docs/ADR-FORMAT.md b/agents/skills/grill-with-docs/ADR-FORMAT.md new file mode 100644 index 0000000..da7e78e --- /dev/null +++ b/agents/skills/grill-with-docs/ADR-FORMAT.md @@ -0,0 +1,47 @@ +# ADR Format + +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. + +## Template + +```md +# {Short title of the decision} + +{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. + +## 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 + +## Numbering + +Scan `docs/adr/` for the highest existing number and increment by one. + +## When to offer an ADR + +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 + +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. +- **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. diff --git a/agents/skills/grill-with-docs/CONTEXT-FORMAT.md b/agents/skills/grill-with-docs/CONTEXT-FORMAT.md new file mode 100644 index 0000000..ddfa247 --- /dev/null +++ b/agents/skills/grill-with-docs/CONTEXT-FORMAT.md @@ -0,0 +1,77 @@ +# CONTEXT.md Format + +## Structure + +```md +# {Context Name} + +{One or two sentence description of what this context is and why it exists.} + +## Language + +**Order**: +{A concise description of the term} +_Avoid_: Purchase, transaction + +**Invoice**: +A request for payment sent to a customer after delivery. +_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. +- **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 + +**Single context (most repos):** One `CONTEXT.md` at the repo root. + +**Multiple contexts:** A `CONTEXT-MAP.md` at the repo root lists the contexts, where they live, and how they relate to each other: + +```md +# Context Map + +## 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 + +## Relationships + +- **Ordering → Fulfillment**: Ordering emits `OrderPlaced` events; Fulfillment consumes them to start picking +- **Fulfillment → Billing**: Fulfillment emits `ShipmentDispatched` events; Billing consumes them to generate invoices +- **Ordering ↔ Billing**: Shared types for `CustomerId` and `Money` +``` + +The skill infers which structure applies: + +- If `CONTEXT-MAP.md` exists, read it to find contexts +- If only a root `CONTEXT.md` exists, single context +- If neither exists, create a root `CONTEXT.md` lazily when the first term is resolved + +When multiple contexts exist, infer which one the current topic relates to. If unclear, ask. diff --git a/agents/skills/grill-with-docs/SKILL.md b/agents/skills/grill-with-docs/SKILL.md new file mode 100644 index 0000000..6dad6ad --- /dev/null +++ b/agents/skills/grill-with-docs/SKILL.md @@ -0,0 +1,88 @@ +--- +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. +--- + + + +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). + + diff --git a/agents/skills/improve-codebase-architecture/DEEPENING.md b/agents/skills/improve-codebase-architecture/DEEPENING.md new file mode 100644 index 0000000..ecaf5d7 --- /dev/null +++ b/agents/skills/improve-codebase-architecture/DEEPENING.md @@ -0,0 +1,37 @@ +# 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**. + +## Dependency categories + +When assessing a candidate for deepening, classify its dependencies. The category determines how the deepened module is tested across its seam. + +### 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. + +### 2. Local-substitutable + +Dependencies that have local test stand-ins (PGLite for Postgres, in-memory filesystem). Deepenable if the stand-in exists. The deepened module is tested with the stand-in running in the test suite. The seam is internal; no port at the module's external interface. + +### 3. Remote but owned (Ports & Adapters) + +Your own services across a network boundary (microservices, internal APIs). Define a **port** (interface) at the seam. The deep module owns the logic; the transport is injected as an **adapter**. Tests use an in-memory adapter. Production uses an HTTP/gRPC/queue adapter. + +Recommendation shape: *"Define a port at the seam, implement an HTTP adapter for production and an in-memory adapter for testing, so the logic sits in one deep module even though it's deployed across a network."* + +### 4. True external (Mock) + +Third-party services (Stripe, Twilio, etc.) you don't control. The deepened module takes the external dependency as an injected port; tests provide a mock adapter. + +## Seam discipline + +- **One adapter means a hypothetical seam. Two adapters means a real one.** Don't introduce a port unless at least two adapters are justified (typically production + test). A single-adapter seam is just indirection. +- **Internal seams vs external seams.** A deep module can have internal seams (private to its implementation, used by its own tests) as well as the external seam at its interface. Don't expose internal seams through the interface just because tests use them. + +## 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. +- 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. diff --git a/agents/skills/improve-codebase-architecture/INTERFACE-DESIGN.md b/agents/skills/improve-codebase-architecture/INTERFACE-DESIGN.md new file mode 100644 index 0000000..3197723 --- /dev/null +++ b/agents/skills/improve-codebase-architecture/INTERFACE-DESIGN.md @@ -0,0 +1,44 @@ +# Interface Design + +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**. + +## Process + +### 1. Frame the problem space + +Before spawning sub-agents, write a user-facing explanation of the problem space for the chosen candidate: + +- 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 + +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. + +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 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. + +Each sub-agent outputs: + +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 + +### 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. diff --git a/agents/skills/improve-codebase-architecture/LANGUAGE.md b/agents/skills/improve-codebase-architecture/LANGUAGE.md new file mode 100644 index 0000000..530c276 --- /dev/null +++ b/agents/skills/improve-codebase-architecture/LANGUAGE.md @@ -0,0 +1,53 @@ +# 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 new file mode 100644 index 0000000..05984a6 --- /dev/null +++ b/agents/skills/improve-codebase-architecture/SKILL.md @@ -0,0 +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. +--- + +# 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. + +## Glossary + +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. + +## Process + +### 1. Explore + +Read the project's domain glossary and any ADRs in the area you're touching first. + +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: + +- Where does understanding one concept require bouncing between many small modules? +- Where are modules **shallow** — 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 + +Present a numbered list of deepening opportunities. For each candidate: + +- **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 + +**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." + +**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. + +Do NOT propose interfaces yet. 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. + +Side effects happen inline as decisions crystallize: + +- **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. +- **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). diff --git a/agents/skills/oh-my-mermaid b/agents/skills/oh-my-mermaid new file mode 120000 index 0000000..aaba546 --- /dev/null +++ b/agents/skills/oh-my-mermaid @@ -0,0 +1 @@ +/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 new file mode 100644 index 0000000..5582d10 --- /dev/null +++ b/agents/skills/ponytail-audit/SKILL.md @@ -0,0 +1,41 @@ +--- +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 new file mode 100644 index 0000000..ecbc0ca --- /dev/null +++ b/agents/skills/ponytail-debt/SKILL.md @@ -0,0 +1,44 @@ +--- +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 new file mode 100644 index 0000000..012e37b --- /dev/null +++ b/agents/skills/ponytail-gain/SKILL.md @@ -0,0 +1,50 @@ +--- +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 new file mode 100644 index 0000000..7e096bf --- /dev/null +++ b/agents/skills/ponytail-help/SKILL.md @@ -0,0 +1,69 @@ +--- +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 new file mode 100644 index 0000000..e137a85 --- /dev/null +++ b/agents/skills/ponytail-review/SKILL.md @@ -0,0 +1,57 @@ +--- +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 new file mode 100644 index 0000000..ee895f6 --- /dev/null +++ b/agents/skills/ponytail/SKILL.md @@ -0,0 +1,117 @@ +--- +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/tdd/SKILL.md b/agents/skills/tdd/SKILL.md new file mode 100644 index 0000000..7a98941 --- /dev/null +++ b/agents/skills/tdd/SKILL.md @@ -0,0 +1,109 @@ +--- +name: tdd +description: Test-driven development with red-green-refactor loop. Use when user wants to build features or fix bugs using TDD, mentions "red-green-refactor", wants integration tests, or asks for test-first development. +--- + +# Test-Driven Development + +## Philosophy + +**Core principle**: Tests should verify behavior through public interfaces, not implementation details. Code can change entirely; tests shouldn't. + +**Good tests** are integration-style: they exercise real code paths through public APIs. They describe _what_ the system does, not _how_ it does it. A good test reads like a specification - "user can checkout with valid cart" tells you exactly what capability exists. These tests survive refactors because they don't care about internal structure. + +**Bad tests** are coupled to implementation. They mock internal collaborators, test private methods, or verify through external means (like querying a database directly instead of using the interface). The warning sign: your test breaks when you refactor, but behavior hasn't changed. If you rename an internal function and tests fail, those tests were testing implementation, not behavior. + +See [tests.md](tests.md) for examples and [mocking.md](mocking.md) for mocking guidelines. + +## Anti-Pattern: Horizontal Slices + +**DO NOT write all tests first, then all implementation.** This is "horizontal slicing" - treating RED as "write all tests" and GREEN as "write all code." + +This produces **crap tests**: + +- Tests written in bulk test _imagined_ behavior, not _actual_ behavior +- You end up testing the _shape_ of things (data structures, function signatures) rather than user-facing behavior +- Tests become insensitive to real changes - they pass when behavior breaks, fail when behavior is fine +- You outrun your headlights, committing to test structure before understanding the implementation + +**Correct approach**: Vertical slices via tracer bullets. One test → one implementation → repeat. Each test responds to what you learned from the previous cycle. Because you just wrote the code, you know exactly what behavior matters and how to verify it. + +``` +WRONG (horizontal): + RED: test1, test2, test3, test4, test5 + GREEN: impl1, impl2, impl3, impl4, impl5 + +RIGHT (vertical): + RED→GREEN: test1→impl1 + RED→GREEN: test2→impl2 + RED→GREEN: test3→impl3 + ... +``` + +## Workflow + +### 1. Planning + +When exploring the codebase, use the project's domain glossary so that test names and interface vocabulary match the project's language, and respect ADRs in the area you're touching. + +Before writing any code: + +- [ ] Confirm with user what interface changes are needed +- [ ] Confirm with user which behaviors to test (prioritize) +- [ ] Identify opportunities for [deep modules](deep-modules.md) (small interface, deep implementation) +- [ ] Design interfaces for [testability](interface-design.md) +- [ ] List the behaviors to test (not implementation steps) +- [ ] Get user approval on the plan + +Ask: "What should the public interface look like? Which behaviors are most important to test?" + +**You can't test everything.** Confirm with the user exactly which behaviors matter most. Focus testing effort on critical paths and complex logic, not every possible edge case. + +### 2. Tracer Bullet + +Write ONE test that confirms ONE thing about the system: + +``` +RED: Write test for first behavior → test fails +GREEN: Write minimal code to pass → test passes +``` + +This is your tracer bullet - proves the path works end-to-end. + +### 3. Incremental Loop + +For each remaining behavior: + +``` +RED: Write next test → fails +GREEN: Minimal code to pass → passes +``` + +Rules: + +- One test at a time +- Only enough code to pass current test +- Don't anticipate future tests +- Keep tests focused on observable behavior + +### 4. Refactor + +After all tests pass, look for [refactor candidates](refactoring.md): + +- [ ] Extract duplication +- [ ] Deepen modules (move complexity behind simple interfaces) +- [ ] Apply SOLID principles where natural +- [ ] Consider what new code reveals about existing code +- [ ] Run tests after each refactor step + +**Never refactor while RED.** Get to GREEN first. + +## Checklist Per Cycle + +``` +[ ] Test describes behavior, not implementation +[ ] Test uses public interface only +[ ] Test would survive internal refactor +[ ] Code is minimal for this test +[ ] No speculative features added +``` diff --git a/agents/skills/tdd/deep-modules.md b/agents/skills/tdd/deep-modules.md new file mode 100644 index 0000000..0d9720c --- /dev/null +++ b/agents/skills/tdd/deep-modules.md @@ -0,0 +1,33 @@ +# Deep Modules + +From "A Philosophy of Software Design": + +**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 interfaces, ask: + +- Can I reduce the number of methods? +- Can I simplify the parameters? +- Can I hide more complexity inside? diff --git a/agents/skills/tdd/interface-design.md b/agents/skills/tdd/interface-design.md new file mode 100644 index 0000000..a0a20ca --- /dev/null +++ b/agents/skills/tdd/interface-design.md @@ -0,0 +1,31 @@ +# Interface Design 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 diff --git a/agents/skills/tdd/mocking.md b/agents/skills/tdd/mocking.md new file mode 100644 index 0000000..71cbfee --- /dev/null +++ b/agents/skills/tdd/mocking.md @@ -0,0 +1,59 @@ +# When to Mock + +Mock at **system boundaries** only: + +- External APIs (payment, email, etc.) +- Databases (sometimes - prefer test DB) +- Time/randomness +- File system (sometimes) + +Don't mock: + +- Your own classes/modules +- Internal collaborators +- Anything you control + +## Designing for Mockability + +At system boundaries, design interfaces that are easy to mock: + +**1. Use dependency injection** + +Pass external dependencies in rather than creating them internally: + +```typescript +// Easy to mock +function processPayment(order, paymentClient) { + return paymentClient.charge(order.total); +} + +// Hard to mock +function processPayment(order) { + const client = new StripeClient(process.env.STRIPE_KEY); + return client.charge(order.total); +} +``` + +**2. Prefer SDK-style interfaces over generic fetchers** + +Create specific functions for each external operation instead of one generic function with conditional logic: + +```typescript +// GOOD: Each function is independently mockable +const api = { + getUser: (id) => fetch(`/users/${id}`), + getOrders: (userId) => fetch(`/users/${userId}/orders`), + createOrder: (data) => fetch('/orders', { method: 'POST', body: data }), +}; + +// BAD: Mocking requires conditional logic inside the mock +const api = { + fetch: (endpoint, options) => fetch(endpoint, options), +}; +``` + +The SDK approach means: +- Each mock returns one specific shape +- No conditional logic in test setup +- Easier to see which endpoints a test exercises +- Type safety per endpoint diff --git a/agents/skills/tdd/refactoring.md b/agents/skills/tdd/refactoring.md new file mode 100644 index 0000000..8a44439 --- /dev/null +++ b/agents/skills/tdd/refactoring.md @@ -0,0 +1,10 @@ +# Refactor Candidates + +After TDD cycle, look for: + +- **Duplication** → Extract function/class +- **Long methods** → Break into private helpers (keep tests on public interface) +- **Shallow modules** → Combine or deepen +- **Feature envy** → Move logic to where data lives +- **Primitive obsession** → Introduce value objects +- **Existing code** the new code reveals as problematic diff --git a/agents/skills/tdd/tests.md b/agents/skills/tdd/tests.md new file mode 100644 index 0000000..ff22f80 --- /dev/null +++ b/agents/skills/tdd/tests.md @@ -0,0 +1,61 @@ +# Good and Bad Tests + +## Good Tests + +**Integration-style**: Test through real interfaces, not mocks of internal parts. + +```typescript +// GOOD: Tests observable behavior +test("user can checkout with valid cart", async () => { + const cart = createCart(); + cart.add(product); + const result = await checkout(cart, paymentMethod); + expect(result.status).toBe("confirmed"); +}); +``` + +Characteristics: + +- Tests behavior users/callers care about +- Uses public API only +- Survives internal refactors +- Describes WHAT, not HOW +- One logical assertion per test + +## Bad Tests + +**Implementation-detail tests**: Coupled to internal structure. + +```typescript +// BAD: Tests implementation details +test("checkout calls paymentService.process", async () => { + const mockPayment = jest.mock(paymentService); + await checkout(cart, payment); + expect(mockPayment.process).toHaveBeenCalledWith(cart.total); +}); +``` + +Red flags: + +- Mocking internal collaborators +- Testing private methods +- Asserting on call counts/order +- Test breaks when refactoring without behavior change +- Test name describes HOW not WHAT +- Verifying through external means instead of interface + +```typescript +// BAD: Bypasses interface to verify +test("createUser saves to database", async () => { + await createUser({ name: "Alice" }); + const row = await db.query("SELECT * FROM users WHERE name = ?", ["Alice"]); + expect(row).toBeDefined(); +}); + +// GOOD: Verifies through interface +test("createUser makes user retrievable", async () => { + const user = await createUser({ name: "Alice" }); + const retrieved = await getUser(user.id); + expect(retrieved.name).toBe("Alice"); +}); +``` diff --git a/agents/skills/to-issues/SKILL.md b/agents/skills/to-issues/SKILL.md new file mode 100644 index 0000000..5a40716 --- /dev/null +++ b/agents/skills/to-issues/SKILL.md @@ -0,0 +1,81 @@ +--- +name: to-issues +description: Break a plan, spec, or PRD into independently-grabbable issues on the project issue tracker using tracer-bullet vertical slices. Use when user wants to convert a plan into issues, create implementation tickets, or break down work into issues. +--- + +# To Issues + +Break a plan into independently-grabbable issues using vertical slices (tracer bullets). + +The issue tracker and triage label vocabulary should have been provided to you — run `/setup-matt-pocock-skills` if not. + +## Process + +### 1. Gather context + +Work from whatever is already in the conversation context. If the user passes an issue reference (issue number, URL, or path) as an argument, fetch it from the issue tracker and read its full body and comments. + +### 2. Explore the codebase (optional) + +If you have not already explored the codebase, do so to understand the current state of the code. Issue titles and descriptions should use the project's domain glossary vocabulary, and respect ADRs in the area you're touching. + +### 3. Draft vertical slices + +Break the plan into **tracer bullet** issues. Each issue is a thin vertical slice that cuts through ALL integration layers end-to-end, NOT a horizontal slice of one layer. + +Slices may be 'HITL' or 'AFK'. HITL slices require human interaction, such as an architectural decision or a design review. AFK slices can be implemented and merged without human interaction. Prefer AFK over HITL where possible. + + +- Each slice delivers a narrow but COMPLETE path through every layer (schema, API, UI, tests) +- A completed slice is demoable or verifiable on its own +- Prefer many thin slices over few thick ones + + +### 4. Quiz the user + +Present the proposed breakdown as a numbered list. For each slice, show: + +- **Title**: short descriptive name +- **Type**: HITL / AFK +- **Blocked by**: which other slices (if any) must complete first +- **User stories covered**: which user stories this addresses (if the source material has them) + +Ask the user: + +- Does the granularity feel right? (too coarse / too fine) +- Are the dependency relationships correct? +- Should any slices be merged or split further? +- Are the correct slices marked as HITL and AFK? + +Iterate until the user approves the breakdown. + +### 5. Publish the issues to the issue tracker + +For each approved slice, publish a new issue to the issue tracker. Use the issue body template below. Apply the `needs-triage` triage label so each issue enters the normal triage flow. + +Publish issues in dependency order (blockers first) so you can reference real issue identifiers in the "Blocked by" field. + + +## Parent + +A reference to the parent issue on the issue tracker (if the source was an existing issue, otherwise omit this section). + +## What to build + +A concise description of this vertical slice. Describe the end-to-end behavior, not layer-by-layer implementation. + +## Acceptance criteria + +- [ ] Criterion 1 +- [ ] Criterion 2 +- [ ] Criterion 3 + +## Blocked by + +- A reference to the blocking ticket (if any) + +Or "None - can start immediately" if no blockers. + + + +Do NOT close or modify any parent issue. diff --git a/agents/skills/to-prd/SKILL.md b/agents/skills/to-prd/SKILL.md new file mode 100644 index 0000000..7bdc82a --- /dev/null +++ b/agents/skills/to-prd/SKILL.md @@ -0,0 +1,74 @@ +--- +name: to-prd +description: Turn the current conversation context into a PRD and publish it to the project issue tracker. Use when user wants to create a PRD from the current context. +--- + +This skill takes the current conversation context and codebase understanding and produces a PRD. Do NOT interview the user — just synthesize what you already know. + +The issue tracker and triage label vocabulary should have been provided to you — run `/setup-matt-pocock-skills` if not. + +## Process + +1. Explore the repo to understand the current state of the codebase, if you haven't already. Use the project's domain glossary vocabulary throughout the PRD, and respect any ADRs in the area you're touching. + +2. Sketch out the major modules you will need to build or modify to complete the implementation. Actively look for opportunities to extract deep modules that can be tested in isolation. + +A deep module (as opposed to a shallow module) is one which encapsulates a lot of functionality in a simple, testable interface which rarely changes. + +Check with the user that these modules match their expectations. Check with the user which modules they want tests written for. + +3. Write the PRD using the template below, then publish it to the project issue tracker. Apply the `needs-triage` triage label so it enters the normal triage flow. + + + +## Problem Statement + +The problem that the user is facing, from the user's perspective. + +## Solution + +The solution to the problem, from the user's perspective. + +## User Stories + +A LONG, numbered list of user stories. Each user story should be in the format of: + +1. As an , I want a , so that + + +1. As a mobile bank customer, I want to see balance on my accounts, so that I can make better informed decisions about my spending + + +This list of user stories should be extremely extensive and cover all aspects of the feature. + +## Implementation Decisions + +A list of implementation decisions that were made. This can include: + +- The modules that will be built/modified +- The interfaces of those modules that will be modified +- Technical clarifications from the developer +- Architectural decisions +- Schema changes +- API contracts +- Specific interactions + +Do NOT include specific file paths or code snippets. They may end up being outdated very quickly. + +## Testing Decisions + +A list of testing decisions that were made. Include: + +- A description of what makes a good test (only test external behavior, not implementation details) +- Which modules will be tested +- Prior art for the tests (i.e. similar types of tests in the codebase) + +## Out of Scope + +A description of the things that are out of scope for this PRD. + +## Further Notes + +Any further notes about the feature. + + diff --git a/agents/skills/touying-author/SKILL.md b/agents/skills/touying-author/SKILL.md new file mode 100644 index 0000000..0ee5f6f --- /dev/null +++ b/agents/skills/touying-author/SKILL.md @@ -0,0 +1,231 @@ +--- +name: touying-author +description: Author, refactor, and troubleshoot Typst slide decks built with Touying +--- + +# Touying Author + +Guide Typst presentation authoring with Touying, emphasizing clean structure, repeatable configuration, and slide-safe patterns. + +## Quick start +- Import Touying and a theme, then apply the theme with `#show: .with(...)`. +- Keep configuration centralized; include slide content from separate files. +- Use headings to create slides; use `#slide` for custom layouts or animations. +- Start from `examples/simple.typ` for a minimal deck, or `examples/default.typ` for the bare theme. + +Snippet from `examples/simple.typ`: + +```typst +#import "@preview/touying:0.6.1": * +#import themes.simple: * + +#show: simple-theme.with( + aspect-ratio: "16-9", + footer: [Simple slides], +) +``` + +## Best practices and code structure + +- Use a single entry file (e.g., `main.typ`) that applies `#show` and all `config-*` calls. +- For multi-file decks, follow the `globals.typ` + `main.typ` + `content.typ` pattern; use `#include` for content and `#import` for globals to avoid circular refs. +- Docs use both `config.typ` (see `docs/start.md`) and `globals.typ` (see `docs/multi-file.md`) for the shared config file; pick one name and use it consistently in your project. +- For large decks, move `content.typ` into `sections/` and include `sections/content.typ` (and optional `sections/another-section.typ`) from `main.typ`. +- Prefer `config-page`, `config-common`, `config-info`, `config-colors`, `config-methods`, and `config-store` over direct `set page` or ad-hoc global `show`. +- Use headings for most slides; use `config-common(slide-level: n)` to choose which heading levels create slides. +- Use `#slide` only for custom layout or animation; always wrap slide functions with `touying-slide-wrapper`. +- For callback-style animation (`#slide(repeat: n, self => [...])`), set `repeat` explicitly and use `utils.methods(self)` to access `uncover`, `only`, and `alternatives`. + +### Single-file structure + +``` +. +├── globals.typ +├── main.typ +└── content.typ +``` + +### Multi-file structure + +``` +. +├── globals.typ +├── main.typ +└── sections/ + ├── content.typ + └── another-section.typ +``` + +## Core API map (exports) + +- Slides: `touying-slides`, `slide`, `touying-slide`, `touying-slide-wrapper`, `empty-slide` +- Dynamics: `pause`, `meanwhile`, `uncover`, `only`, `effect`, `alternatives`, `alternatives-match`, `alternatives-fn`, `alternatives-cases` +- Config: `config-common`, `config-page`, `config-info`, `config-colors`, `config-methods`, `config-store`, `default-config`, `touying-set-config`, `appendix` +- Utilities: `utils.*` (fit-to-height, fit-to-width, cover helpers, progress, heading helpers) +- Components: `components.side-by-side`, `components.adaptive-columns`, `components.progressive-outline`, `components.custom-progressive-outline` +- Integrations: `touying-reducer`, `touying-equation`, `touying-mitex`, `speaker-note`, `pdfpc.*` +- Recall: `touying-recall`, `touying-fn-wrapper` + +## Slide structure and headings + +- Use heading labels to control numbering/outline/bookmarks: use `` (see `docs/code-styles.md`), and see `docs/changelog.md` for ``, ``, ``, and ``. +- Use `components.adaptive-columns(outline(...))` for a table of contents slide; use `components.progressive-outline` for progress-aware outlines. +- Use `== ` to insert a blank title slide and clear the previous heading context. +- Use `#pagebreak()` or `---` to split slides without changing headings. +- Use `#empty-slide[...]` for slides without header/footer. +- Use `config-common(handout: true)` to keep only the last subslide per slide in handout output. +- Use `#show: appendix` to freeze last-slide counts after the main deck. + +Snippet from `examples/default.typ`: + +```typst += Outline + +#components.adaptive-columns(outline(title: none, indent: 1em)) +``` + +## Animations and dynamic content + +- Use `#pause` and `#meanwhile` for simple reveals; avoid using them inside `context` where marks are not supported. +- Use `#uncover` to reserve layout space; use `#only` to remove layout space when hidden. +- When marks cause warnings, use callback-style slides with `repeat` and `utils.methods(self)`. +- For math animations, use `pause`/`meanwhile` inside `$ ... $`; use `touying-equation` when you need the helper for inline equation text (you can also use `#pause` or `#pause;`). +- See `examples/example.typ` for simple/complex/callback animations and equation animations. + +Snippet from `examples/simple.typ`: + +```typst +== Dynamic slide + +Did you know that... + +#pause + +...you can see the current section at the top of the slide? +``` + +Snippet from `examples/example.typ`: +```typst +#slide( + repeat: 3, + self => [ + #let (uncover, only, alternatives) = utils.methods(self) + + At subslide #self.subslide, we can + + use #uncover("2-")[`#uncover` function] for reserving space, + + use #only("2-")[`#only` function] for not reserving space, + + #alternatives[call `#only` multiple times \u{2717}][use `#alternatives` function #sym.checkmark] for choosing one of the alternatives. + ], +) +``` + +## Layout and theming +- Use `composer` in `#slide` for columns; pass `(1fr, 2fr)` or a custom `grid` function. +- Use `config-page` for margin, header, footer, and background; do not use `set page` directly. +- Use `config-methods(cover: utils.semi-transparent-cover.with(alpha: 85%))` only when layout changes are acceptable. +- Use `config-store` to stash theme-specific values for headers/footers or navigation elements. +- Use `config-common(new-section-slide-fn: none)` to disable automatic section slides, or provide a custom function to replace them. +- Apply global styles either around `#show: .with(...)` or via `config-methods(init: ...)` in a theme. +- Use `config-info(...)` for title/author/date and `config-common(datetime-format: ...)` to control date formatting. + +Snippet from `examples/default.typ`: + +```typst +#import "@preview/touying:0.6.1": * +#import themes.default: * + +#import "@preview/numbly:0.1.0": numbly + +#show: default-theme.with( + aspect-ratio: "16-9", + config-common( + slide-level: 3, + zero-margin-header: false, + ), + config-colors(primary: blue), + config-methods(alert: utils.alert-with-primary-color), + config-page( + header: text(gray, utils.display-current-short-heading(level: 2)), + ), +) +``` + +## Speaker notes and presenter tools + +- Add notes with `#speaker-note[...]`. +- Show notes on second screen with `config-common(show-notes-on-second-screen: right)` or `bottom`. +- Export pdfpc metadata with `enable-pdfpc: true` and `typst query --field value --one ""`. + +## Use bundled docs and examples + +- Read only the specific docs needed for the task; avoid loading the full docs tree. +- Read `docs/start.md` and `docs/intro.md` for basics and import patterns. +- Read `docs/multi-file.md` for multi-file layout and include patterns. +- Read `docs/layout.md` and `docs/sections.md` for slide-level and heading behavior. +- Read `docs/code-styles.md` for simple vs block style and pagination tricks. +- Read `docs/global-settings.md` for global styles and `config-info` usage. +- Read `docs/dynamic/*.md` for `pause`, `meanwhile`, cover behavior, and equation animation. +- Read `docs/themes/*.md` for theme-specific APIs and defaults. +- Read `docs/external/*.md` for pdfpc and Pympress usage. +- Read `docs/integration/*.md` for CeTZ/Fletcher/Theorion/MiTeX integrations. +- Use `examples/*.typ` as working templates for each theme. + +## File tree (docs and examples) + +``` +docs/ +├── build-your-own-theme.md +├── changelog.md +├── code-styles.md +├── dynamic +│ ├── complex.md +│ ├── cover.md +│ ├── equation.md +│ ├── handout.md +│ ├── other.md +│ └── simple.md +├── external +│ ├── pdfpc.md +│ ├── pympress.md +│ └── typst-preview.md +├── global-settings.md +├── integration +│ ├── cetz.md +│ ├── codly.md +│ ├── fletcher.md +│ ├── mitex.md +│ ├── pinit.md +│ └── theorion.md +├── intro.md +├── layout.md +├── multi-file.md +├── progress +│ ├── counters.md +│ └── sections.md +├── sections.md +├── start.md +├── themes +│ ├── aqua.md +│ ├── custom.md +│ ├── dewdrop.md +│ ├── metropolis.md +│ ├── simple.md +│ ├── stargazer.md +│ └── university.md +└── utilities + └── fit-to.md + +examples/ +├── aqua-zh.typ +├── aqua.typ +├── default.typ +├── dewdrop.typ +├── example.typ +├── metropolis.typ +├── simple.typ +├── stargazer.typ +└── university.typ +``` diff --git a/agents/skills/touying-author/docs/build-your-own-theme.md b/agents/skills/touying-author/docs/build-your-own-theme.md new file mode 100644 index 0000000..3a0f976 --- /dev/null +++ b/agents/skills/touying-author/docs/build-your-own-theme.md @@ -0,0 +1,448 @@ +--- +sidebar_position: 11 +--- + +# Build Your Own Theme + +Creating your own theme with Touying can be a bit complex due to the many concepts we've introduced. But rest assured, if you do create a theme with Touying, you might deeply appreciate the convenience and powerful customizability that Touying offers. You can refer to the [source code of the themes](https://github.com/touying-typ/touying/tree/main/themes). The main things you need to implement are: + +- Customizing the `xxx-theme` function; +- Customizing the color theme, i.e., `config-colors()`; +- Customizing the header; +- Customizing the footer; +- Customizing the `slide` method; +- Customizing special slide methods, such as `title-slide` and `focus-slide` methods; + +To demonstrate how to create a theme with Touying, let's step by step create a simple and aesthetically pleasing Bamboo theme. + +## Modifying Existing Themes + +If you want to modify a Touying internal theme locally instead of creating one from scratch, you can achieve this by: + +1. Copying the [theme code](https://github.com/touying-typ/touying/tree/main/themes) from the `themes` directory to your local, for example, copying `themes/university.typ` to your local `university.typ`. +2. Replacing the `#import "../src/exports.typ": *` command at the top of the `university.typ` file with `#import "@preview/touying:0.6.1": *`. + +Then you can import and use the theme by: + +```typst +#import "@preview/touying:0.6.1": * +#import "university.typ": * + +#show: university-theme.with( + aspect-ratio: "16-9", + config-info( + title: [Title], + subtitle: [Subtitle], + author: [Authors], + date: datetime.today(), + institution: [Institution], + logo: emoji.school, + ), +) +``` + +## Importing + +Depending on whether the theme is your own or part of Touying, you can import it in two ways: + +If it's just for your own use, you can directly import Touying: + +```typst +#import "@preview/touying:0.6.1": * +``` + +If you want the theme to be part of Touying, placed in the Touying `themes` directory, then you should change the import statement above to + +```typst +#import "../src/exports.typ": * +``` + +And add + +```typst +#import "bamboo.typ" +``` + +in Touying's `themes/themes.typ`. + +## register Function and init Method + +Next, we will differentiate between the `bamboo.typ` template file and the `main.typ` file, which is sometimes omitted. + +Generally, the first step in making slides is to determine the font size and page aspect ratio, so we need to register an initialization method: + +```typst +// bamboo.typ +#import "@preview/touying:0.6.1": * + +#let bamboo-theme( + aspect-ratio: "16-9", + ..args, + body, +) = { + set text(size: 20pt) + + show: touying-slides.with( + config-page(paper: "presentation-" + aspect-ratio), + config-common( + slide-fn: slide, + ), + ..args, + ) + + body +} + +// main.typ +#import "@preview/touying:0.6.1": * +#import "bamboo.typ": * + +#show: bamboo-theme.with(aspect-ratio: "16-9") + += First Section + +== First Slide + +A slide with a title and an *important* information. +``` + +As you can see, we've created a `bamboo-theme` function and passed in an `aspect-ratio` parameter to set the page aspect ratio. We've also added `set text(size: 20pt)` to set the font size. You can also place some additional global style settings here, such as `set par(justify: true)`, etc. If you need to use `self`, you might consider using `config-methods(init: (self: none, body) => { .. })` to register an `init` method. + +As you can see, later in `main.typ`, we apply our style settings through `#show: bamboo-theme.with(aspect-ratio: "16-9")`, and internally `bamboo` uses `show: touying-slides.with()` for corresponding configurations. + +## Color Theme + +Picking an aesthetically pleasing color theme for your slides is key to making good slides. Touying provides built-in color theme support to minimize API differences between different themes. Touying offers two dimensions of color selection. The first dimension is `neutral`, `primary`, `secondary`, and `tertiary`, which are used to distinguish color tones, with `primary` being the most commonly used theme color. The second dimension is `default`, `light`, `lighter`, `lightest`, `dark`, `darker`, `darkest`, which are used to distinguish brightness levels. + +Since we are creating the Bamboo theme, we have chosen a color close to bamboo for the `primary` theme color, `rgb("#5E8B65")`, and added neutral colors `neutral-lightest`, `neutral-darkest`, respectively, as the background and font colors. + +As shown in the following code, we can use the `config-colors()` method to modify the color theme. Its essence is a wrapper for `self.colors += (..)`. + +```typst +#let bamboo-theme( + aspect-ratio: "16-9", + ..args, + body, +) = { + set text(size: 20pt) + + show: touying-slides.with( + config-page(paper: "presentation-" + aspect-ratio), + config-common( + slide-fn: slide, + ), + config-colors( + primary: rgb("#5E8B65"), + neutral-lightest: rgb("#ffffff"), + neutral-darkest: rgb("#000000"), + ), + ..args, + ) + + body +} +``` + +After adding the color theme as shown above, we can access this color through `self.colors.primary`. + +It's also worth noting that users can change the color theme at any time in `main.typ` by using `config-colors()` or + +```typst +#show: touying-set-config.with(config-colors( + primary: blue, + neutral-lightest: rgb("#ffffff"), + neutral-darkest: rgb("#000000"), +)) +``` + +This feature of being able to change the color theme at any time is a testament to Touying's powerful customizability. + +## Practical: Custom Alert Method + +Generally, we need to provide a `#alert[..]` function for users, similar to `#strong[..]`, both of which are used to emphasize the current text. Typically, `#alert[..]` will change the text color to the theme color, which will look more aesthetically pleasing, and this is our next goal. + +We add a line in the `register` function: + +```typst +config-methods(alert: (self: none, it) => text(fill: self.colors.primary, it)) +``` + +This code means to change the text color to `self.colors.primary`, and the `self` here is passed in through the parameter `self: none`, so that we can get the `primary` theme color in real-time. + +We can also use a shorthand. + +```typst +config-methods(alert: utils.alert-with-primary-color) +``` + +## Custom Header and Footer + +Here, I assume you have read the page layout section, so we know that we should add a header and footer to the slides. + +First, we add `config-store(title: none)`, which means that we save the current slide's title as a member variable `self.store.title` inside `self`, making it convenient for us to use in the header and for subsequent modifications. Similarly, we also create a `config-store(footer: footer)` and save the `footer: none` parameter of the `bamboo-theme` function for display in the footer at the bottom left corner. + +Then it's worth noting that our header is actually a content function with `self` as a parameter, like `let header(self) = { .. }`, rather than a simple content, so that we can get the information we need from the latest `self`, such as `self.store.title`. The footer is the same. + +The `components.cell` used here is actually `#let cell = block.with(width: 100%, height: 100%, above: 0pt, below: 0pt, breakable: false)`, and `show: components.cell` is also a shorthand for `components.cell(body)`, and the `show: pad.with(.4em)` for the footer is the same. + +Another point to note is that the `utils` module contains many contents and methods related to counters and states, such as `utils.display-current-heading(level: 1)` for displaying the current `section`, and `context utils.slide-counter.display() + " / " + utils.last-slide-number` for displaying the current page number and total number of pages. + +We also find that we use syntax like `utils.call-or-display(self, self.store.footer)` to display `self.store.footer`, which is to deal with the situation of `self.store.footer = self => {..}`, so that we can unify the display of content functions and content. + +To ensure that the header and footer are displayed correctly and have enough spacing from the main text, we need to set the margin, such as `config-page(margin: (top: 4em, bottom: 1.5em, x: 2em))`. + +We also need to customize a `slide` method, which accepts `#let slide(title: auto, ..args) = touying-slide-wrapper(self => {..})`, where `self` in the callback function is a required parameter to get the latest `self`; the second `title` is used to update `self.store.title` for display in the header; the third `..args` is used to collect the remaining parameters and pass them to `touying-slide(self: self, ..args)`, which is also necessary for the normal functioning of Touying's `slide` feature. Moreover, we need to register this method in the `bamboo-theme` function using `config-methods(slide: slide)`. + +```typst +// bamboo.typ +#import "@preview/touying:0.6.1": * + +#let slide(title: auto, ..args) = touying-slide-wrapper(self => { + if title != auto { + self.store.title = title + } + // set page + let header(self) = { + set align(top) + show: components.cell.with(fill: self.colors.primary, inset: 1em) + set align(horizon) + set text(fill: self.colors.neutral-lightest, size: .7em) + utils.display-current-heading(level: 1) + linebreak() + set text(size: 1.5em) + if self.store.title != none { + utils.call-or-display(self, self.store.title) + } else { + utils.display-current-heading(level: 2) + } + } + let footer(self) = { + set align(bottom) + show: pad.with(.4em) + set text(fill: self.colors.neutral-darkest, size: .8em) + utils.call-or-display(self, self.store.footer) + h(1fr) + context utils.slide-counter.display() + " / " + utils.last-slide-number + } + self = utils.merge-dicts( + self, + config-page( + header: header, + footer: footer, + ), + ) + touying-slide(self: self, ..args) +}) + +#let bamboo-theme( + aspect-ratio: "16-9", + footer: none, + ..args, + body, +) = { + set text(size: 20pt) + + show: touying-slides.with( + config-page( + paper: "presentation-" + aspect-ratio, + margin: (top: 4em, bottom: 1.5em, x: 2em), + ), + config-common( + slide-fn: slide, + ), + config-methods( + alert: utils.alert-with-primary-color, + ), + config-colors( + primary: rgb("#5E8B65"), + neutral-lightest: rgb("#ffffff"), + neutral-darkest: rgb("#000000"), + ), + config-store( + title: none, + footer: footer, + ), + ..args, + ) + + body +} + + +// main.typ +#import "@preview/touying:0.6.1": * +#import "bamboo.typ": * + +#show: bamboo-theme.with(aspect-ratio: "16-9") + += First Section + +== First Slide + +A slide with a title and an *important* information. +``` + +![image](https://github.com/touying-typ/touying/assets/34951714/d33bcda7-c032-4b11-b392-5b939d9a0a47) + +## Custom Special Slides + +On the basis of the basic slides we've created, we further add some special slide functions, such as `title-slide`, `focus-slide`, and custom `slides` methods. + +For the `title-slide` method, first, we can obtain the information saved in `self.info` through `let info = self.info + args.named()`, and we can also update the information with `args.named()` passed in through the function parameters for subsequent use in the form of `info.title`. The specific page content `body` will vary for each theme, so I won't go into too much detail here. + +For the `new-section-slide` method, it's the same, but the only thing to note is that we registered `new-section-slide-fn: new-section-slide` in `config-methods()`, so `new-section-slide` will be automatically called when encountering a first-level heading. + +```typst +// bamboo.typ +#import "@preview/touying:0.6.1": * + +#let slide(title: auto, ..args) = touying-slide-wrapper(self => { + if title != auto { + self.store.title = title + } + // set page + let header(self) = { + set align(top) + show: components.cell.with(fill: self.colors.primary, inset: 1em) + set align(horizon) + set text(fill: self.colors.neutral-lightest, size: .7em) + utils.display-current-heading(level: 1) + linebreak() + set text(size: 1.5em) + if self.store.title != none { + utils.call-or-display(self, self.store.title) + } else { + utils.display-current-heading(level: 2) + } + } + let footer(self) = { + set align(bottom) + show: pad.with(.4em) + set text(fill: self.colors.neutral-darkest, size: .8em) + utils.call-or-display(self, self.store.footer) + h(1fr) + context utils.slide-counter.display() + " / " + utils.last-slide-number + } + self = utils.merge-dicts( + self, + config-page( + header: header, + footer: footer, + ), + ) + touying-slide(self: self, ..args) +}) + +#let title-slide(..args) = touying-slide-wrapper(self => { + let info = self.info + args.named() + let body = { + set align(center + horizon) + block( + fill: self.colors.primary, + width: 80%, + inset: (y: 1em), + radius: 1em, + text(size: 2em, fill: self.colors.neutral-lightest, weight: "bold", info.title), + ) + set text(fill: self.colors.neutral-darkest) + if info.author != none { + block(info.author) + } + if info.date != none { + block(utils.display-info-date(self)) + } + } + touying-slide(self: self, body) +}) + +#let new-section-slide(self: none, body) = touying-slide-wrapper(self => { + let main-body = { + set align(center + horizon) + set text(size: 2em, fill: self.colors.primary, weight: "bold", style: "italic") + utils.display-current-heading(level: 1) + } + touying-slide(self: self, main-body) +}) + +#let focus-slide(body) = touying-slide-wrapper(self => { + self = utils.merge-dicts( + self, + config-page( + fill: self.colors.primary, + margin: 2em, + ), + ) + set text(fill: self.colors.neutral-lightest, size: 2em) + touying-slide(self: self, align(horizon + center, body)) +}) + +#let bamboo-theme( + aspect-ratio: "16-9", + footer: none, + ..args, + body, +) = { + set text(size: 20pt) + + show: touying-slides.with( + config-page( + paper: "presentation-" + aspect-ratio, + margin: (top: 4em, bottom: 1.5em, x: 2em), + ), + config-common( + slide-fn: slide, + new-section-slide-fn: new-section-slide, + ), + config-methods(alert: utils.alert-with-primary-color), + config-colors( + primary: rgb("#5E8B65"), + neutral-lightest: rgb("#ffffff"), + neutral-darkest: rgb("#000000"), + ), + config-store( + title: none, + footer: footer, + ), + ..args, + ) + + body +} + + +// main.typ +#import "@preview/touying:0.6.1": * +#import "bamboo.typ": * + +#show: bamboo-theme.with( + aspect-ratio: "16-9", + footer: self => self.info.institution, + config-info( + title: [Title], + subtitle: [Subtitle], + author: [Authors], + date: datetime.today(), + institution: [Institution], + ), +) + +#title-slide() + += First Section + +== First Slide + +A slide with a title and an *important* information. + +#focus-slide[ + Focus on it! +] +``` + +![image](https://github.com/touying-typ/touying/assets/34951714/03c5ad02-8ff4-4068-9664-d9cfad79baaf) + + + +## Conclusion + +Congratulations! You've created a simple and elegant theme. Perhaps you may find that Touying introduces a wealth of concepts, making it initially challenging to grasp. This is normal, as Touying opts for functionality over simplicity. However, thanks to Touying's comprehensive and unified approach, you can easily extract commonalities between different themes and transfer your knowledge seamlessly. You can also save global variables, modify existing themes, or switch between themes effortlessly, showcasing the benefits of Touying's decoupling. \ No newline at end of file diff --git a/agents/skills/touying-author/docs/changelog.md b/agents/skills/touying-author/docs/changelog.md new file mode 100644 index 0000000..ca5bad5 --- /dev/null +++ b/agents/skills/touying-author/docs/changelog.md @@ -0,0 +1,321 @@ +--- +sidebar_position: 14 +--- + +# Changelog + +## v0.6.1 + +Added support for the [theorion](https://github.com/OrangeX4/typst-theorion) package, and used it as the default math theorem environment. + +## v0.6.0 + +It's not a big update, but it's the first touying release since typst 0.13 was released. + +### Features + +- feat: add auto style for display-current-heading. + - For users, you can use `show heading: set text(blue)` to change color for heading in some themes like `dewdrop`. + - For theme creator, you can use syntax like `utils.display-current-heading(level: 1, style: auto)` to achieve the same result. +- feat: apply config-info information to `set document`. +- feat: set `stretch: false` by default for `alternatives` functions. This is **a minor breaking change**, but I think it would be more intuitive: no auto empty space. + +### Fixes + +- fix: fix error with uncover using semi-transparent-cover +- fix: fix type string comparison https://github.com/touying-typ/touying/pull/153 +- fix: fix horizontal-line bug in typst 0.13.0 +- refactor: fix display-current-short-heading + + +## v0.5.4 & v0.5.5 + +### Features + +- docs: improve param documentation and we have better hints for tinymist https://github.com/touying-typ/touying/pull/98 +- feat: fake frozon states support for `heading` https://github.com/touying-typ/touying/pull/124 +- feat: add alpha-changing-cover and color-changing-cover https://github.com/touying-typ/touying/pull/129 +- feat: add effect function https://github.com/touying-typ/touying/issues/111 + - Example: `#effect(text.with(fill: red), "2-")[Something]` will display `[Something]` if the current slide is 2 or later. +- feat: add argument `config: (..)` for `xxx-slide` functions +- feat: add `align` argument for university theme + +### Fixes + +- fix: also hide enum numbers with show-hide-set-list-marker-none https://github.com/touying-typ/touying/pull/114 +- fix: fixed progress bar not to break apart when global figure gutter is set nonzero https://github.com/touying-typ/touying/pull/120 +- fix: fixed frozen-counters bug with multiple #pause commands https://github.com/touying-typ/touying/pull/124 +- fix: fixed incorrect page num when draft is true https://github.com/touying-typ/touying/pull/125 +- fix: fix behaviors of fit-to-height and fit-to-width partially https://github.com/touying-typ/touying/pull/131 +- fix: duplicated footnotes in headings https://github.com/touying-typ/touying/pull/132 +- fix: do not hardcode page sizes https://github.com/touying-typ/touying/pull/134 +- fix: add default numbering for page https://github.com/touying-typ/touying/issues/100 +- refactor: move show-strong-with-alert to per-slide level https://github.com/touying-typ/touying/issues/123 +- refactor: remove unnecessary `config-page(fill: ...)` +- theme(metropolis): fix color of title page and fix https://github.com/touying-typ/touying/issues/103 +- theme(metropolis): fixed metropolis slide's header to return content if title is specified https://github.com/touying-typ/touying/pull/126 +- theme(metropolis): respect colors dict in metropolis theme https://github.com/touying-typ/touying/pull/133 + +Thanks for the contributions from [@enklht](https://github.com/enklht). + + +## v0.5.3 + +### Features + +- feat: add `stretch` parameter for `#alternatives[]` function class. This allows us to handle cases where the internal element is a context expression. +- feat: add `config-common(align-enum-marker-with-baseline: true)` for aligning the enum marker with the baseline. +- feat: add `linebreaks` option to `components.mini-slides`. https://github.com/touying-typ/touying/pull/96 +- feat: add `` label to skip a new-section-slide. +- feat: add `config-common(show-hide-set-list-marker-none: true)` to make the markers of `list` and `enum` invisible after `#pause`. +- feat: add `config-common(bibliography-as-footnote: bibliography(title: none, "ref.bib"))` to display the bibliography in footnotes. +- refactor: add `config-common(show-strong-with-alert: true)` configuration to display strong text with an alert. (small breaking change for some themes) +- refactor: refactor `display-current-heading` for preserving heading style in title and subtitle. https://github.com/touying-typ/touying/issues/71 +- refactor: make `new-section-slide-fn` function class can receive `body` parameter. We can use `receive-body-for-new-section-slide-fn` to control it. **(Breaking change)** + - For example, you can add `#speaker-note[]` for a new section slide, like `= Section Title \ #speaker-note[]`. + - If you don't want to append content to the body of the new section slide, you can use `---` after the section title. + +### Fixes + +- fix outdated documentation. +- fix bug of `enable-frozen-states-and-counters` in handout mode. +- fix unusable `square()` function. https://github.com/touying-typ/touying/issues/73 +- fix hidden footer for `show-notes-on-second-screen: bottom`. https://github.com/touying-typ/touying/issues/89 +- fix metadata element in table cells. https://github.com/touying-typ/touying/issues/77 https://github.com/touying-typ/touying/issues/95 +- fix `auto-offset-for-heading` to `false` by default. +- fix uncover/only hides more content than it should. https://github.com/touying-typ/touying/issues/85 +- theme(simple): fix wrong title and subtitle. https://github.com/touying-typ/touying/issues/70 + + +## v0.5.1 & v0.5.2 + +- Fix somg bugs. + + +## v0.5.0 + +This is a significant disruptive version update. Touying has removed many mistakes that resulted from incorrect decisions. We have redesigned numerous features. The goal of this version is to make Touying more user-friendly, more flexible, and more powerful. + +**Major changes include:** + +- Avoiding closures and OOP syntax, which makes Touying's configuration simpler and allows for the use of document comments to provide more auto-completion information for the slide function. + - The existing `#let slide(self: none, ..args) = { .. }` is now `#let slide(..args) = touying-slide-wrapper(self => { .. })`, where `self` is automatically injected. + - We can use `config-xxx` syntax to configure Touying, for example, `#show: university-theme.with(aspect-ratio: "16-9", config-colors(primary: blue))`. +- The `touying-slide` function no longer includes parameters like `section`, `subsection`, and `title`. These will be automatically inserted into the slide as invisible level 1, 2, or 3 headings via `self.headings` (controlled by the `slide-level` configuration). + - We can leverage the powerful headings provided by Typst to support numbering, outlines, and bookmarks. + - Headings within the `#slide[= XXX]` function will be adjusted to level `slide-level + 1` using the `offset` parameter. + - We can use labels on headings to control many aspects, such as supporting the `` and other special labels, implementing short headings, or recalling a slide with `#touying-recall()`. +- Touying now supports the normal use of `set` and `show` rules at any position, without requiring them to be in specific locations. + +A simple usage example is shown below, and more examples can be found in the `examples` directory: + +```typst +#import "@preview/touying:0.6.1": * +#import themes.university: * + +#show: university-theme.with( + aspect-ratio: "16-9", + config-info( + title: [Title], + subtitle: [Subtitle], + author: [Authors], + date: datetime.today(), + institution: [Institution], + logo: emoji.school, + ), +) + +#set heading(numbering: "1.1") + +#title-slide() + += The Section + +== Slide Title + +#lorem(40) +``` + +**Theme Migration Guide:** + +For detailed changes to specific themes, you can refer to the `themes` directory. Generally, if you want to migrate an existing theme, you should: + +1. Rename the `register` function to `xxx-theme` and remove the `self` parameter. +2. Add a `show: touying-slides.with(..)` configuration. + - Change `self.methods.colors` to `config-colors(primary: rgb("#xxxxxx"))`. + - Change `self.page-args` to `config-page()`. + - Change `self.methods.slide = slide` to `config-methods(slide: slide)`. + - Change `self.methods.new-section-slide = new-section-slide` to `config-methods(new-section-slide: new-section-slide)`. + - Change private theme variables like `self.xxx-footer` to `config-store(footer: [..])`, which you can access through `self.store.footer`. + - Move the configuration of headers and footers into the `slide` function rather than in the `xxx-theme` function. + - You can directly use `set` or `show` rules in `xxx-theme` or configure them through `config-methods(init: (self: none, body) => { .. })` to fully utilize the `self` parameter. +3. For `states.current-section-with-numbering`, you can use `utils.display-current-heading(level: 1)` instead. + - If you only need the previous heading regardless of whether it is a section or a subsection, use `utils.display-current-heading()`. +4. The `alert` function can be replaced with `config-methods(alert: utils.alert-with-primary-color)`. +5. The `touying-outline()` function is no longer needed; you can use `components.adaptive-columns(outline())` instead. Consider using `components.progressive-outline()` or `components.custom-progressive-outline()`. +6. Replace `states.slide-counter.display() + " / " + states.last-slide-number` with `context utils.slide-counter.display() + " / " + utils.last-slide-number`. That is, we no longer use `states` but `utils`. +7. Remove the `slides` function; we no longer need this function. Instead of implicitly injecting `title-slide()`, explicitly use `#title-slide()`. If necessary, consider adding it in the `xxx-theme` function. +8. Change `#let slide(self: none, ..args) = { .. }` to `#let slide(..args) = touying-slide-wrapper(self => { .. })`, where `self` is automatically injected. + - Change specific parameter configurations to `self = utils.merge-dicts(self, config-page(fill: self.colors.neutral-lightest))`. + - Remove `self = utils.empty-page(self)` and use `config-common(freeze-slide-counter: true)` and `config-page(margin: 0em)` instead. + - Change `(self.methods.touying-slide)()` to `touying-slide()`. +9. You can insert visible headings into slides by configuring `config-common(subslide-preamble: self => text(1.2em, weight: "bold", utils.display-current-heading(depth: self.slide-level)))`. +10. Finally, don't forget to add document comments to your functions so your users can get better auto-completion hints, especially when using the Tinymist plugin. + +**Other Changes:** + +- theme(stargazer): new stargazer theme modified from [Coekjan/touying-buaa](https://github.com/Coekjan/touying-buaa). +- feat: implemented fake frozen states support, allowing you to use numbering and `#pause` normally. This behavior can be controlled with `enable-frozen-states-and-counters`, `frozen-states`, and `frozen-counters` in `config-common()`. +- feat: implemented `label-only-on-last-subslide` functionality to prevent non-unique label warnings when working with `@equation` and `@figure` in conjunction with `#pause` animations. +- feat: added the `touying-recall(