mirror of
https://github.com/ksyasuda/dotfiles.git
synced 2026-08-24 18:15:25 -07:00
Compare commits
20
Commits
e518b6b6e9
..
master
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
67afa82778
|
||
|
|
20b38a79d3
|
||
|
|
a9d3d00be9
|
||
|
|
1a0f0cdabb
|
||
|
|
c62d9e9d0e
|
||
|
|
5346c3fa5e
|
||
|
|
ba1324d10a
|
||
|
|
7d560759ca
|
||
|
|
fc8062f1c1
|
||
|
|
e7d8cc9107
|
||
|
|
57bc3af61b
|
||
|
|
fe23f30550
|
||
|
|
ce72d3a0e3
|
||
|
|
a0011ef4f5
|
||
|
|
a3266acbe4
|
||
|
|
5bc3a20f3d
|
||
|
|
69d787aeb0
|
||
|
|
7871a51d51
|
||
|
|
0cee4cc0e2
|
||
|
|
5e60b7a744
|
@@ -0,0 +1,7 @@
|
||||
---
|
||||
name: bro
|
||||
description: Restate the last message in plain human language, with no jargon.
|
||||
disable-model-invocation: true
|
||||
---
|
||||
|
||||
Restate your last message. Stop using jargon and speak coherently. State it more simply and concisely, like one human talking to another.
|
||||
@@ -1,93 +1,184 @@
|
||||
---
|
||||
name: claude-code-computer-delegate
|
||||
description: "Route Claude Code computer-use, browser-use, GUI automation, and workstation interaction tasks to Codex subagents only. Use when Claude Code needs another agent to inspect or operate a desktop app, browser, local UI, terminal-driven workflow, or repo task involving computer control. Always use GPT-5.6 Codex models only: gpt-5.6-terra for narrow/simple work and gpt-5.6-sol for complex/high-risk work. Never use gpt-5.6-luna, Luna aliases, Claude models, or non-GPT-5.6 Codex models."
|
||||
description: "Delegate desktop GUI and workstation control to a Codex subagent that acts as remote hands while Claude Code reads the screenshots. Use when a task needs to see or operate the local desktop: take a screenshot, check what is currently on screen, inspect or drive a native or Electron app window, read window/workspace/monitor state, launch a desktop program, or run a live-session workflow that a sandboxed shell cannot reach. Not for web pages (use the Chrome DevTools or Playwright MCP tools) and not for ordinary repo edits (use the delegate skill). Codex only: gpt-5.6-terra for narrow work, gpt-5.6-sol for complex or risky work; never gpt-5.6-luna, Luna aliases, or Claude models."
|
||||
---
|
||||
|
||||
# Claude Code Computer Delegate
|
||||
|
||||
## Overview
|
||||
## The one thing to understand first
|
||||
|
||||
Delegate computer-use work from Claude Code to Codex subagents. Route every task to `gpt-5.6-terra` or `gpt-5.6-sol`; reject Luna and every other model.
|
||||
**Codex is the hands. Claude Code is the eyes.**
|
||||
|
||||
## Hard Rules
|
||||
Verified on this machine: a `codex exec` subagent *cannot view image files*. Asked to
|
||||
screenshot the desktop and describe it, it replies `CANNOT VIEW IMAGES`. So never ask
|
||||
Codex "what does the screen look like" or "check whether the dialog appeared". It is
|
||||
blind.
|
||||
|
||||
- Use provider `codex` only.
|
||||
- Use only `gpt-5.6-terra` or `gpt-5.6-sol`.
|
||||
- Never use `gpt-5.6-luna`, `luna`, aliases, "latest", fallback models, Claude models, or pre-5.6 Codex models.
|
||||
- If a requested model violates these rules, stop and report the conflict. Do not silently substitute.
|
||||
- Do not delegate recursively. The Codex subagent must complete the task itself and report back.
|
||||
- Prefer read-only delegation for inspection, diagnosis, screenshots, or review. Use write mode only for explicit implementation or file edits.
|
||||
The working division of labor:
|
||||
|
||||
## Route Selection
|
||||
| Step | Who | How |
|
||||
|---|---|---|
|
||||
| Capture screen, drive windows, launch apps, run live-session commands | Codex subagent | `grim`, `hyprctl`, `wtype` |
|
||||
| Interpret pixels: layout, colors, error text, "did it work" | Claude Code (you) | `Read` the PNG path Codex reports |
|
||||
| Decide the next action | Claude Code (you) | Send a follow-up brief |
|
||||
|
||||
Choose the smallest adequate route:
|
||||
Codex reasons only over **text**: `hyprctl -j clients` JSON, command output, exit codes,
|
||||
log files. Have it report those. Have it report *screenshot paths*, never screenshot
|
||||
*descriptions*.
|
||||
|
||||
| Complexity | Use | Model | Effort |
|
||||
|---|---|---|---|
|
||||
| Narrow | Single screen, one command, simple browser/GUI check, small file inspection, bounded terminal task | `gpt-5.6-terra` | medium |
|
||||
| Narrow but context-heavy | Same scope, but with long logs, many screenshots, or nuanced UI state | `gpt-5.6-terra` | high |
|
||||
| Standard | Multi-step computer workflow, multi-file repo task, ordinary debugging, meaningful trade-offs | `gpt-5.6-sol` | medium |
|
||||
| Deep | Architecture, security, concurrency, risky edits, broad ambiguity, high-impact user/system state | `gpt-5.6-sol` | high |
|
||||
## Use this skill when
|
||||
|
||||
Default to `gpt-5.6-sol` when failure could change user data, spend money, publish, delete, overwrite, or affect credentials. Default to `gpt-5.6-terra` when the task is reversible, local, and easy to verify.
|
||||
- "What's on my screen right now", "take a screenshot", "look at my desktop"
|
||||
- Inspecting or operating a native/Electron/GTK/Qt app window
|
||||
- Reading window, workspace, or monitor layout state
|
||||
- Launching or focusing a desktop program
|
||||
- A command that must touch the live graphical session
|
||||
|
||||
## Preferred Invocation
|
||||
## Do NOT use this skill when
|
||||
|
||||
When the local `delegate` broker is available, use it because it enforces the approved Codex model set and safe execution modes:
|
||||
- **Web page or web app work.** You have `chrome-devtools` and `playwright` MCP tools
|
||||
in-process. They give you the DOM, console, network, and snapshots you can actually
|
||||
see. Delegating browser work to a blind subagent is strictly worse. Use the MCP tools.
|
||||
- **Plain repo work** (reading code, edits, reviews) with no GUI involved. Use the
|
||||
`delegate` skill instead.
|
||||
- The task is a single command you can just run in Bash yourself. Do that.
|
||||
|
||||
## Hard model policy
|
||||
|
||||
- Provider `codex` only. Model must be `gpt-5.6-terra` or `gpt-5.6-sol`.
|
||||
- Never `gpt-5.6-luna`, `luna`, aliases, `latest`, fallbacks, Claude models, or pre-5.6
|
||||
Codex models.
|
||||
- If the user names a model outside this set, stop and report the conflict. Do not
|
||||
silently substitute.
|
||||
- The subagent must not delegate further.
|
||||
|
||||
| Complexity | Model | Effort |
|
||||
|---|---|---|
|
||||
| Single screenshot, one command, bounded lookup | `gpt-5.6-terra` | medium |
|
||||
| Same scope, long logs or fiddly state | `gpt-5.6-terra` | high |
|
||||
| Multi-step GUI workflow, ordinary debugging | `gpt-5.6-sol` | medium |
|
||||
| Risky, ambiguous, or touching credentials/money/user data | `gpt-5.6-sol` | high |
|
||||
|
||||
Default to `sol` when a mistake could change user data, spend money, publish, delete, or
|
||||
overwrite. Default to `terra` when the action is reversible and easy to verify.
|
||||
|
||||
## Sandbox: the part that used to silently fail
|
||||
|
||||
GUI access requires `--sandbox danger-full-access`. This is not optional and there is no
|
||||
narrower mode that works.
|
||||
|
||||
Measured on this box (Wayland, Hyprland 0.56.2):
|
||||
|
||||
| Sandbox | `grim` screenshot | `hyprctl` |
|
||||
|---|---|---|
|
||||
| `read-only` | fails, `failed to create display` | fails, `Couldn't set socket timeout` |
|
||||
| `workspace-write` | fails, `failed to create display` | fails |
|
||||
| `workspace-write --add-dir /run/user/1000` | still fails | still fails |
|
||||
| `danger-full-access` | works | works |
|
||||
|
||||
The sandbox passes `WAYLAND_DISPLAY` and `XDG_RUNTIME_DIR` through as environment
|
||||
variables but blocks the compositor sockets themselves, so the failure looks like a
|
||||
missing display rather than a permission error. `--add-dir` does not fix it.
|
||||
|
||||
Because `danger-full-access` removes the sandbox entirely, keep the blast radius in the
|
||||
brief instead: name the exact commands allowed, and forbid everything else.
|
||||
|
||||
## Run it
|
||||
|
||||
```bash
|
||||
python3 /Users/sudacode/.agents/skills/delegate/scripts/delegate.py \
|
||||
--provider codex \
|
||||
--tier quick \
|
||||
--mode read \
|
||||
--repo "$PWD" <<'TASK'
|
||||
<self-contained computer-use task>
|
||||
TASK
|
||||
```
|
||||
|
||||
Map tiers as follows:
|
||||
|
||||
- `quick` -> `gpt-5.6-terra`, medium
|
||||
- `quick-context` -> `gpt-5.6-terra`, high
|
||||
- `standard` -> `gpt-5.6-sol`, medium
|
||||
- `deep` -> `gpt-5.6-sol`, high
|
||||
|
||||
Use `--mode write` only when the user explicitly wants implementation or edits.
|
||||
|
||||
## Direct Codex Fallback
|
||||
|
||||
If the broker is unavailable, call Codex directly with an approved model:
|
||||
|
||||
```bash
|
||||
codex exec \
|
||||
cd "$PWD" && timeout 900 codex exec \
|
||||
--ignore-user-config \
|
||||
--model gpt-5.6-terra \
|
||||
--config 'model_reasoning_effort="medium"' \
|
||||
--config 'approval_policy="never"' \
|
||||
--sandbox read-only \
|
||||
--config model_reasoning_effort="medium" \
|
||||
--config approval_policy="never" \
|
||||
--sandbox danger-full-access \
|
||||
--ephemeral \
|
||||
--skip-git-repo-check \
|
||||
--cd "$PWD" \
|
||||
-
|
||||
--output-last-message /tmp/codex-gui-1.md \
|
||||
--cd "$PWD" - <<'TASK'
|
||||
<brief from the template below>
|
||||
TASK
|
||||
cat /tmp/codex-gui-1.md
|
||||
```
|
||||
|
||||
For write tasks, use `--sandbox workspace-write`; never grant broader access unless the user explicitly approves that exact operation.
|
||||
Notes that matter:
|
||||
|
||||
## Task Brief
|
||||
- Always feed the brief on stdin via a **quoted** heredoc (`<<'TASK'`) so the shell does
|
||||
not expand anything in it. The trailing `-` is what tells Codex to read stdin.
|
||||
- `--output-last-message` gives you the clean report; stdout also carries the reasoning
|
||||
stream, which is what you want when a run fails.
|
||||
- Give screenshots a path you can reach afterward. Prefer your scratchpad directory.
|
||||
- A nonzero exit or empty report file is a failure even if stdout printed something.
|
||||
Check both.
|
||||
|
||||
Write a complete brief; the Codex subagent starts with no conversation context. Include:
|
||||
## Brief template
|
||||
|
||||
- Goal and definition of done.
|
||||
- Exact app, browser tab, local URL, file path, command, or screen state involved.
|
||||
- Constraints: forbidden actions, allowed edits, credentials/payment/publishing restrictions.
|
||||
- Verification expected: screenshot, command output, tests, or concise report.
|
||||
- Reporting format: summary, actions taken, evidence, files changed, verification, open questions.
|
||||
Codex starts with zero context.
|
||||
|
||||
Pass raw evidence such as errors, logs, screenshots paths, or diffs. Do not tell Codex the answer to find.
|
||||
```
|
||||
You are a subagent with direct access to the live graphical session.
|
||||
|
||||
## Safety Checks
|
||||
Environment: Wayland + Hyprland. Available: grim (screenshot), slurp (region),
|
||||
wtype (typing), hyprctl (window control and JSON introspection), xdotool
|
||||
(XWayland windows only), playwright, google-chrome-stable, firefox.
|
||||
|
||||
- Before launching: state selected model, tier, mode, and why.
|
||||
- After completion: inspect the report and verify load-bearing claims before acting on them.
|
||||
- For write mode: review `git diff` and run targeted tests/checks before reporting success.
|
||||
- On failure: report selected model, exact command path used, and the error. Retry once only for transient failures, with the same allowed model family.
|
||||
You CANNOT view images. Never describe the contents of a screenshot. Capture it,
|
||||
report the absolute path, and let the caller look at it.
|
||||
|
||||
Hard constraints:
|
||||
- Run only these commands: <explicit list>
|
||||
- Do not close, move, or resize the user's existing windows unless told to.
|
||||
- Do not type into or click on windows the task does not name.
|
||||
- Do not delegate further or invoke Codex/Claude recursively.
|
||||
|
||||
Report, in these sections:
|
||||
- Summary: what you did.
|
||||
- Screenshots: absolute path of each, and what each was meant to capture.
|
||||
- Structural state: relevant `hyprctl -j clients` output or command stdout, verbatim.
|
||||
- Commands run: each with its exit code.
|
||||
- Open questions: anything you could not determine without vision.
|
||||
|
||||
Task:
|
||||
<self-contained task>
|
||||
```
|
||||
|
||||
Pass raw evidence. Do not tell Codex the answer you expect it to find.
|
||||
|
||||
## Desktop cookbook (verified available here)
|
||||
|
||||
Prefer structured text over pixels wherever possible, since that is the part Codex can
|
||||
reason about.
|
||||
|
||||
```bash
|
||||
grim /path/shot.png # whole screen
|
||||
grim -g "$(slurp)" /path/region.png # region (interactive, needs a human)
|
||||
hyprctl -j clients # every window: class, title, at[x,y], size[w,h], workspace
|
||||
hyprctl -j activewindow # focused window
|
||||
hyprctl -j monitors # geometry and scale
|
||||
hyprctl notify -1 3000 "rgb(44ccff)" "message"
|
||||
wtype 'text to type' # types into the focused window
|
||||
```
|
||||
|
||||
`hyprctl -j clients` is the highest-value call: it returns exact window rectangles, so
|
||||
Codex can position and identify windows without seeing anything.
|
||||
|
||||
## Known limits, state honestly
|
||||
|
||||
- **No synthetic mouse clicks.** `ydotool` is not installed and the user is not in the
|
||||
`input` group, so `/dev/uinput` is not writable. There is no working click injection.
|
||||
If a task needs a click, say so and ask the user, rather than having Codex flail.
|
||||
- **Hyprland 0.56 changed the dispatch API** to a Lua form (`hl.dsp.window.close()`).
|
||||
Old `hyprctl dispatch <name>` strings error out. Verify a dispatcher before relying on
|
||||
it.
|
||||
- `xdotool` only reaches XWayland clients, not native Wayland ones.
|
||||
- **Screenshots are downscaled when you Read them.** A 3440x1440 capture is shown to you
|
||||
at 2000x837. If you derive coordinates from the image, multiply by the stated factor
|
||||
before handing them to anything.
|
||||
|
||||
## After the run
|
||||
|
||||
- Read the screenshot yourself before believing any claim about UI state.
|
||||
- Treat the report as a claim. Spot-check load-bearing parts against the raw output.
|
||||
- On failure, report the model, the exact command, and the error. Retry once only for
|
||||
transient faults, on the same model family. If the error is `failed to create display`,
|
||||
the sandbox flag was wrong, not the task.
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
interface:
|
||||
display_name: "Claude Code Computer Delegate"
|
||||
short_description: "Route Claude Code computer-use tasks to Codex"
|
||||
default_prompt: "Use $claude-code-computer-delegate to route computer-use work from Claude Code to the right Codex model."
|
||||
short_description: "Codex acts on the desktop; Claude Code reads the screenshots"
|
||||
default_prompt: "Use $claude-code-computer-delegate to drive the local desktop through a Codex subagent (gpt-5.6-terra or gpt-5.6-sol) and interpret the captured screenshots here."
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
# Deepening
|
||||
|
||||
How to deepen a cluster of shallow modules safely, given its dependencies. Assumes the vocabulary in [SKILL.md](SKILL.md) — **module**, **interface**, **seam**, **adapter**.
|
||||
|
||||
## Dependency categories
|
||||
|
||||
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.
|
||||
@@ -0,0 +1,44 @@
|
||||
# Design It Twice
|
||||
|
||||
When the user wants to explore alternative interfaces for a chosen deepening candidate, use this parallel sub-agent pattern. Based on "Design It Twice" (Ousterhout) — your first idea is unlikely to be the best.
|
||||
|
||||
Uses the vocabulary in [SKILL.md](SKILL.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. 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 [SKILL.md](SKILL.md) vocabulary and CONTEXT.md vocabulary in the brief so each sub-agent names things consistently with the architecture language and the project's domain language.
|
||||
|
||||
Each sub-agent outputs:
|
||||
|
||||
1. Interface (types, methods, params — plus invariants, ordering, error modes)
|
||||
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.
|
||||
@@ -0,0 +1,114 @@
|
||||
---
|
||||
name: codebase-design
|
||||
description: Shared vocabulary for designing deep modules. Use when the user wants to design or improve a module's interface, find deepening opportunities, decide where a seam goes, make code more testable or AI-navigable, or when another skill needs the deep-module vocabulary.
|
||||
---
|
||||
|
||||
# Codebase Design
|
||||
|
||||
Design **deep modules**: a lot of behaviour behind a small interface, placed at a clean seam, testable through that interface. Use this language and these principles wherever code is being designed or restructured. The aim is leverage for callers, locality for maintainers, and testability for everyone.
|
||||
|
||||
## Glossary
|
||||
|
||||
Use these terms exactly — don't substitute "component," "service," "API," or "boundary." Consistent language is the whole point.
|
||||
|
||||
**Module** — anything with an interface and an implementation. Deliberately scale-agnostic: a function, class, package, or tier-spanning slice. _Avoid_: unit, component, service.
|
||||
|
||||
**Interface** — everything a caller must know to use the module correctly: the type signature, but also invariants, ordering constraints, error modes, required configuration, and performance characteristics. _Avoid_: API, signature (too narrow — they refer only to the type-level surface).
|
||||
|
||||
**Implementation** — what's inside a module, its body of code. Distinct from **Adapter**: a thing can be a small adapter with a large implementation (a Postgres repo) or a large adapter with a small implementation (an in-memory fake). Reach for "adapter" when the seam is the topic; "implementation" otherwise.
|
||||
|
||||
**Depth** — leverage at the interface: the amount of behaviour a caller (or test) can exercise per unit of interface they have to learn. A module is **deep** when a large amount of behaviour sits behind a small interface, **shallow** when the interface is nearly as complex as the implementation.
|
||||
|
||||
**Seam** _(Michael Feathers)_ — a place where you can alter behaviour without editing in that place; the *location* at which a module's interface lives. Where to put the seam is its own design decision, distinct from what goes behind it. _Avoid_: boundary (overloaded with DDD's bounded context).
|
||||
|
||||
**Adapter** — a concrete thing that satisfies an interface at a seam. Describes *role* (what slot it fills), not substance (what's inside).
|
||||
|
||||
**Leverage** — what callers get from depth: more capability per unit of interface they learn. One implementation pays back across N call sites and M tests.
|
||||
|
||||
**Locality** — what maintainers get from depth: change, bugs, knowledge, and verification concentrate in one place rather than spreading across callers. Fix once, fixed everywhere.
|
||||
|
||||
## Deep vs shallow
|
||||
|
||||
**Deep module** = small interface + lots of implementation:
|
||||
|
||||
```
|
||||
┌─────────────────────┐
|
||||
│ Small Interface │ ← Few methods, simple params
|
||||
├─────────────────────┤
|
||||
│ │
|
||||
│ Deep Implementation│ ← Complex logic hidden
|
||||
│ │
|
||||
└─────────────────────┘
|
||||
```
|
||||
|
||||
**Shallow module** = large interface + little implementation (avoid):
|
||||
|
||||
```
|
||||
┌─────────────────────────────────┐
|
||||
│ Large Interface │ ← Many methods, complex params
|
||||
├─────────────────────────────────┤
|
||||
│ Thin Implementation │ ← Just passes through
|
||||
└─────────────────────────────────┘
|
||||
```
|
||||
|
||||
When designing an interface, ask:
|
||||
|
||||
- Can I reduce the number of methods?
|
||||
- Can I simplify the parameters?
|
||||
- Can I hide more complexity inside?
|
||||
|
||||
## Principles
|
||||
|
||||
- **Depth is a property of the interface, not the implementation.** A deep module can be internally composed of small, mockable, swappable parts — they just aren't part of the interface. A module can have **internal seams** (private to its implementation, used by its own tests) as well as the **external seam** at its interface.
|
||||
- **The deletion test.** Imagine deleting the module. If complexity vanishes, it was a pass-through. If complexity reappears across N callers, it was earning its keep.
|
||||
- **The interface is the test surface.** Callers and tests cross the same seam. If you want to test *past* the interface, the module is probably the wrong shape.
|
||||
- **One adapter means a hypothetical seam. Two adapters means a real one.** Don't introduce a seam unless something actually varies across it.
|
||||
|
||||
## Designing for testability
|
||||
|
||||
Good interfaces make testing natural:
|
||||
|
||||
1. **Accept dependencies, don't create them.**
|
||||
|
||||
```typescript
|
||||
// Testable
|
||||
function processOrder(order, paymentGateway) {}
|
||||
|
||||
// Hard to test
|
||||
function processOrder(order) {
|
||||
const gateway = new StripeGateway();
|
||||
}
|
||||
```
|
||||
|
||||
2. **Return results, don't produce side effects.**
|
||||
|
||||
```typescript
|
||||
// Testable
|
||||
function calculateDiscount(cart): Discount {}
|
||||
|
||||
// Hard to test
|
||||
function applyDiscount(cart): void {
|
||||
cart.total -= discount;
|
||||
}
|
||||
```
|
||||
|
||||
3. **Small surface area.** Fewer methods = fewer tests needed. Fewer params = simpler test setup.
|
||||
|
||||
## Relationships
|
||||
|
||||
- A **Module** has exactly one **Interface** (the surface it presents to callers and tests).
|
||||
- **Depth** is a property of a **Module**, measured against its **Interface**.
|
||||
- A **Seam** is where a **Module**'s **Interface** lives.
|
||||
- An **Adapter** sits at a **Seam** and satisfies the **Interface**.
|
||||
- **Depth** produces **Leverage** for callers and **Locality** for maintainers.
|
||||
|
||||
## Rejected framings
|
||||
|
||||
- **Depth as ratio of implementation-lines to interface-lines** (Ousterhout): rewards padding the implementation. We use depth-as-leverage instead.
|
||||
- **"Interface" as the TypeScript `interface` keyword or a class's public methods**: too narrow — interface here includes every fact a caller must know.
|
||||
- **"Boundary"**: overloaded with DDD's bounded context. Say **seam** or **interface**.
|
||||
|
||||
## Going deeper
|
||||
|
||||
- **Deepening a cluster given its dependencies** — see [DEEPENING.md](DEEPENING.md): dependency categories, seam discipline, and replace-don't-layer testing.
|
||||
- **Exploring alternative interfaces** — see [DESIGN-IT-TWICE.md](DESIGN-IT-TWICE.md): spin up parallel sub-agents to design the interface several radically different ways, then compare on depth, locality, and seam placement.
|
||||
@@ -0,0 +1,3 @@
|
||||
interface:
|
||||
display_name: "Codebase Design"
|
||||
short_description: "Vocabulary for deep-module design"
|
||||
@@ -5,9 +5,13 @@ description: Delegate self-contained tasks to Claude or Codex subagents run as f
|
||||
|
||||
# Delegate
|
||||
|
||||
Hand a self-contained task to a fresh Claude or Codex subagent and get back a
|
||||
structured report. Each invocation is one subagent; run several in parallel for
|
||||
independent tasks.
|
||||
Hand a self-contained task to a fresh `claude` or `codex` CLI process and get
|
||||
back a structured report. Each invocation is one subagent; run several in
|
||||
parallel for independent tasks.
|
||||
|
||||
You call the CLIs directly. The command shapes below are the default recipe,
|
||||
not a fixed harness — adjust flags when the task needs it (extra directories,
|
||||
different tools, a longer timeout), and say what you changed in your report.
|
||||
|
||||
## When to delegate
|
||||
|
||||
@@ -61,45 +65,123 @@ The subagent starts with zero context. Write a self-contained task containing:
|
||||
|
||||
Pass raw evidence; do not tell the subagent the answer you expect.
|
||||
|
||||
Wrap the brief in this scaffold. Keep the constraint block matching the mode
|
||||
and keep the report sections verbatim — the result-handling steps below assume
|
||||
them.
|
||||
|
||||
```
|
||||
You are a subagent completing a delegated task inside the current repository.
|
||||
Work independently; the caller cannot answer questions mid-task. If the task is
|
||||
ambiguous, choose the safest reasonable interpretation and note the choice in
|
||||
your report.
|
||||
|
||||
<constraints for the chosen mode — see below>
|
||||
- Do not delegate further or invoke Claude or Codex recursively.
|
||||
|
||||
End your reply with a report containing these sections:
|
||||
- Summary: what you did or found, in a few sentences.
|
||||
- Details: key evidence, decisions, or findings, with file:line references.
|
||||
- Files changed: list each changed file, or "none".
|
||||
- Verification: what you ran and the outcome, or "not verified" and why.
|
||||
- Open questions: anything unresolved the caller must decide, or "none".
|
||||
|
||||
Task:
|
||||
<self-contained task brief>
|
||||
```
|
||||
|
||||
`read` constraints:
|
||||
|
||||
```
|
||||
Hard constraints:
|
||||
- You are in read-only mode. Do not modify, create, rename, or delete files.
|
||||
- Do not commit, branch, push, or contact external systems that change state.
|
||||
- Base claims on repository evidence. Cite file paths and line numbers.
|
||||
```
|
||||
|
||||
`write` constraints:
|
||||
|
||||
```
|
||||
Hard constraints:
|
||||
- Work only inside the given repository directory.
|
||||
- Do not commit, branch, push, or open pull requests unless the task says to.
|
||||
- Do not delete or rename files the task does not cover; if something looks
|
||||
wrong or unexpected, stop and report instead of guessing.
|
||||
- Verify your work (build, tests, or a targeted check) when feasible.
|
||||
```
|
||||
|
||||
## Run it
|
||||
|
||||
Resolve `<skill-dir>` to the directory containing this `SKILL.md`. Send the
|
||||
task on stdin; do not interpolate it into the shell command.
|
||||
Always send the prompt on stdin via a quoted heredoc (`<<'TASK'`) so nothing in
|
||||
the brief is expanded or re-parsed by the shell. Run the CLI from the target
|
||||
repo with `cd <repo> && ...`.
|
||||
|
||||
Codex, read-only:
|
||||
|
||||
```bash
|
||||
python3 <skill-dir>/scripts/delegate.py \
|
||||
--provider codex \
|
||||
--tier standard \
|
||||
--mode read \
|
||||
--repo "$PWD" <<'TASK'
|
||||
<self-contained task brief>
|
||||
cd /path/to/repo && codex exec \
|
||||
--ignore-user-config \
|
||||
--model gpt-5.6-sol \
|
||||
--config model_reasoning_effort="medium" \
|
||||
--config approval_policy="never" \
|
||||
--sandbox read-only \
|
||||
--ephemeral \
|
||||
--skip-git-repo-check \
|
||||
--output-last-message /tmp/delegate-codex-1.md \
|
||||
--cd /path/to/repo - <<'TASK'
|
||||
<scaffold + brief>
|
||||
TASK
|
||||
cat /tmp/delegate-codex-1.md
|
||||
```
|
||||
|
||||
Codex, write mode: swap `--sandbox read-only` for `--sandbox workspace-write`.
|
||||
|
||||
`--output-last-message` writes just the final report; Codex's stdout also
|
||||
carries its reasoning stream, which is useful when a run fails or you want to
|
||||
see what it actually did. Add `--add-dir <dir>` for extra writable roots.
|
||||
|
||||
Claude, read-only:
|
||||
|
||||
```bash
|
||||
cd /path/to/repo && claude --print \
|
||||
--model claude-opus-4-8 \
|
||||
--effort medium \
|
||||
--disable-slash-commands \
|
||||
--no-session-persistence \
|
||||
--permission-mode plan \
|
||||
--tools Read,Glob,Grep <<'TASK'
|
||||
<scaffold + brief>
|
||||
TASK
|
||||
```
|
||||
|
||||
Flags:
|
||||
Claude, write mode: replace the last two lines with
|
||||
|
||||
- `--provider claude|codex` (required)
|
||||
- `--tier quick|quick-context|standard|deep` (default `standard`)
|
||||
- `--mode read|write` (default `read`)
|
||||
- `--model <approved-model>` for an explicit allowed override
|
||||
- `--repo <dir>` (default cwd)
|
||||
- `--timeout <seconds>` (default 1800)
|
||||
- `--dry-run` to inspect routing and command construction without running
|
||||
```bash
|
||||
--permission-mode acceptEdits \
|
||||
--tools Read,Glob,Grep,Edit,Write,Bash \
|
||||
--allowedTools Edit,Write,Bash
|
||||
```
|
||||
|
||||
Claude prints the final message on stdout. Widen `--tools` when a task
|
||||
genuinely needs more (for example `WebSearch` for external research, or
|
||||
`Bash` in read mode for a `git diff` the subagent must see) — that is a
|
||||
deliberate choice, so note it when you report back.
|
||||
|
||||
Give long runs a timeout that fits the task (the Bash tool's `timeout` is in
|
||||
milliseconds; 1800000 is a reasonable ceiling for a `deep` tier run).
|
||||
|
||||
Parallel delegation: launch each invocation as a separate background shell
|
||||
command, then collect the outputs. Never point two `write`-mode subagents at
|
||||
overlapping files; split by file/directory or run them sequentially.
|
||||
command, write each Codex report to its own `--output-last-message` path, then
|
||||
collect the outputs. Never point two `write`-mode subagents at overlapping
|
||||
files; split by file/directory or run them sequentially.
|
||||
|
||||
## Handle the result
|
||||
|
||||
The report ends with Summary / Details / Files changed / Verification / Open
|
||||
questions sections. Then:
|
||||
|
||||
- Treat it as a subagent's claim, not ground truth: spot-check load-bearing
|
||||
findings, and for `write` mode review the diff (`git diff`) and re-run
|
||||
verification before building on it.
|
||||
- Treat the report as a subagent's claim, not ground truth: spot-check
|
||||
load-bearing findings, and for `write` mode review the diff (`git diff`) and
|
||||
re-run verification before building on it.
|
||||
- Relay the outcome to the user in your own words; credit which provider/model
|
||||
produced it when it matters.
|
||||
- On failure, report the provider, model, and exact error. Retry once with the
|
||||
same route if transient; escalate tier or switch provider only deliberately,
|
||||
and say you did.
|
||||
- On failure, report the provider, model, and exact error. A nonzero exit or
|
||||
empty output is a failure even if the CLI printed something — check both.
|
||||
Retry once with the same route if transient; escalate tier or switch provider
|
||||
only deliberately, and say you did.
|
||||
|
||||
Binary file not shown.
@@ -1,270 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Delegate a self-contained task to a Claude or Codex subagent."""
|
||||
|
||||
import argparse
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
ALLOWED_MODELS = {
|
||||
"codex": frozenset({"gpt-5.6-terra", "gpt-5.6-sol"}),
|
||||
"claude": frozenset(
|
||||
{"claude-sonnet-4-6", "claude-sonnet-5", "claude-opus-4-8"}
|
||||
),
|
||||
}
|
||||
|
||||
# tier -> provider -> (model, effort)
|
||||
ROUTES = {
|
||||
"quick": {
|
||||
"codex": ("gpt-5.6-terra", "medium"),
|
||||
"claude": ("claude-sonnet-4-6", "medium"),
|
||||
},
|
||||
"quick-context": {
|
||||
"codex": ("gpt-5.6-terra", "high"),
|
||||
"claude": ("claude-sonnet-5", "high"),
|
||||
},
|
||||
"standard": {
|
||||
"codex": ("gpt-5.6-sol", "medium"),
|
||||
"claude": ("claude-opus-4-8", "medium"),
|
||||
},
|
||||
"deep": {
|
||||
"codex": ("gpt-5.6-sol", "high"),
|
||||
"claude": ("claude-opus-4-8", "high"),
|
||||
},
|
||||
}
|
||||
|
||||
READ_ONLY_RULES = """\
|
||||
Hard constraints:
|
||||
- You are in read-only mode. Do not modify, create, rename, or delete files.
|
||||
- Do not commit, branch, push, or contact external systems that change state.
|
||||
- Base claims on repository evidence. Cite file paths and line numbers."""
|
||||
|
||||
WRITE_RULES = """\
|
||||
Hard constraints:
|
||||
- Work only inside the given repository directory.
|
||||
- Do not commit, branch, push, or open pull requests unless the task says to.
|
||||
- Do not delete or rename files the task does not cover; if something looks
|
||||
wrong or unexpected, stop and report instead of guessing.
|
||||
- Verify your work (build, tests, or a targeted check) when feasible."""
|
||||
|
||||
REPORT_FORMAT = """\
|
||||
End your reply with a report containing these sections:
|
||||
- Summary: what you did or found, in a few sentences.
|
||||
- Details: key evidence, decisions, or findings, with file:line references.
|
||||
- Files changed: list each changed file, or "none".
|
||||
- Verification: what you ran and the outcome, or "not verified" and why.
|
||||
- Open questions: anything unresolved the caller must decide, or "none"."""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Route:
|
||||
provider: str
|
||||
model: str
|
||||
effort: str
|
||||
|
||||
|
||||
def select_route(provider: str, tier: str) -> Route:
|
||||
if tier not in ROUTES:
|
||||
raise ValueError(f"Unknown tier: {tier}")
|
||||
if provider not in ("claude", "codex"):
|
||||
raise ValueError(f"Unknown provider: {provider}")
|
||||
model, effort = ROUTES[tier][provider]
|
||||
return Route(provider, model, effort)
|
||||
|
||||
|
||||
def apply_model_override(route: Route, model: str) -> Route:
|
||||
if model not in ALLOWED_MODELS[route.provider]:
|
||||
raise ValueError(f"Model {model!r} is not allowed for {route.provider}")
|
||||
return Route(route.provider, model, route.effort)
|
||||
|
||||
|
||||
def build_command(
|
||||
route: Route,
|
||||
repo: Path,
|
||||
mode: str,
|
||||
output_path: Path | None = None,
|
||||
) -> list[str]:
|
||||
if route.provider == "codex":
|
||||
if output_path is None:
|
||||
raise ValueError("Codex requires an output path")
|
||||
sandbox = "read-only" if mode == "read" else "workspace-write"
|
||||
return [
|
||||
"codex",
|
||||
"exec",
|
||||
"--ignore-user-config",
|
||||
"--model",
|
||||
route.model,
|
||||
"--config",
|
||||
f'model_reasoning_effort="{route.effort}"',
|
||||
"--config",
|
||||
'approval_policy="never"',
|
||||
"--sandbox",
|
||||
sandbox,
|
||||
"--ephemeral",
|
||||
"--skip-git-repo-check",
|
||||
"--output-last-message",
|
||||
str(output_path),
|
||||
"--cd",
|
||||
str(repo),
|
||||
"-",
|
||||
]
|
||||
|
||||
command = [
|
||||
"claude",
|
||||
"--print",
|
||||
"--model",
|
||||
route.model,
|
||||
"--effort",
|
||||
route.effort,
|
||||
"--disable-slash-commands",
|
||||
"--no-session-persistence",
|
||||
]
|
||||
if mode == "read":
|
||||
command += [
|
||||
"--permission-mode",
|
||||
"plan",
|
||||
"--tools",
|
||||
"Read,Glob,Grep",
|
||||
]
|
||||
else:
|
||||
command += [
|
||||
"--permission-mode",
|
||||
"acceptEdits",
|
||||
"--tools",
|
||||
"Read,Glob,Grep,Edit,Write,Bash",
|
||||
"--allowedTools",
|
||||
"Edit,Write,Bash",
|
||||
]
|
||||
return command
|
||||
|
||||
|
||||
def build_prompt(task: str, route: Route, mode: str) -> str:
|
||||
rules = READ_ONLY_RULES if mode == "read" else WRITE_RULES
|
||||
return f"""You are a {route.provider} subagent completing a delegated task \
|
||||
inside the current repository. Work independently; the caller cannot answer \
|
||||
questions mid-task. If the task is ambiguous, choose the safest reasonable \
|
||||
interpretation and note the choice in your report.
|
||||
|
||||
{rules}
|
||||
- Do not delegate further or invoke Claude or Codex recursively.
|
||||
|
||||
{REPORT_FORMAT}
|
||||
|
||||
Task:
|
||||
{task.strip()}
|
||||
"""
|
||||
|
||||
|
||||
def run_delegation(
|
||||
route: Route,
|
||||
repo: Path,
|
||||
prompt: str,
|
||||
mode: str,
|
||||
*,
|
||||
timeout: int = 1800,
|
||||
) -> str:
|
||||
if shutil.which(route.provider) is None:
|
||||
raise RuntimeError(f"Required CLI is not installed: {route.provider}")
|
||||
|
||||
with tempfile.TemporaryDirectory(prefix="delegate-") as temp_dir:
|
||||
output_path = (
|
||||
Path(temp_dir) / "report.md" if route.provider == "codex" else None
|
||||
)
|
||||
command = build_command(route, repo, mode, output_path)
|
||||
try:
|
||||
result = subprocess.run(
|
||||
command,
|
||||
cwd=repo,
|
||||
input=prompt,
|
||||
text=True,
|
||||
capture_output=True,
|
||||
timeout=timeout,
|
||||
check=False,
|
||||
)
|
||||
except subprocess.TimeoutExpired as error:
|
||||
raise RuntimeError(
|
||||
f"{route.provider} delegation timed out after {timeout}s"
|
||||
) from error
|
||||
if result.returncode != 0:
|
||||
detail = (result.stderr or result.stdout).strip() or "no error output"
|
||||
raise RuntimeError(
|
||||
f"{route.provider} delegation failed ({result.returncode}): {detail}"
|
||||
)
|
||||
if route.provider == "codex":
|
||||
if output_path is None or not output_path.is_file():
|
||||
raise RuntimeError("Codex did not produce a report")
|
||||
report = output_path.read_text().strip()
|
||||
else:
|
||||
report = result.stdout.strip()
|
||||
if not report:
|
||||
raise RuntimeError(f"{route.provider} returned an empty report")
|
||||
return report
|
||||
|
||||
|
||||
def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Delegate a self-contained task to a Claude or Codex subagent."
|
||||
)
|
||||
parser.add_argument("--provider", choices=("claude", "codex"), required=True)
|
||||
parser.add_argument(
|
||||
"--tier",
|
||||
choices=("quick", "quick-context", "standard", "deep"),
|
||||
default="standard",
|
||||
)
|
||||
parser.add_argument("--mode", choices=("read", "write"), default="read")
|
||||
parser.add_argument("--model", help="Approved model override")
|
||||
parser.add_argument("--repo", type=Path, default=Path.cwd())
|
||||
parser.add_argument("--timeout", type=int, default=1800)
|
||||
parser.add_argument("--dry-run", action="store_true")
|
||||
return parser.parse_args(argv)
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
args = parse_args(argv)
|
||||
try:
|
||||
task = sys.stdin.read().strip()
|
||||
if not task:
|
||||
raise ValueError("Task must be provided on stdin")
|
||||
repo = args.repo.expanduser().resolve()
|
||||
if not repo.is_dir():
|
||||
raise ValueError(f"Repository directory does not exist: {repo}")
|
||||
route = select_route(args.provider, args.tier)
|
||||
if args.model:
|
||||
route = apply_model_override(route, args.model)
|
||||
prompt = build_prompt(task, route, args.mode)
|
||||
if args.dry_run:
|
||||
output_path = (
|
||||
Path(tempfile.gettempdir()) / "delegate-dry-run-report.md"
|
||||
if route.provider == "codex"
|
||||
else None
|
||||
)
|
||||
command = build_command(route, repo, args.mode, output_path)
|
||||
print(f"provider: {route.provider}")
|
||||
print(f"model: {route.model}")
|
||||
print(f"effort: {route.effort}")
|
||||
print(f"mode: {args.mode}")
|
||||
print(f"command: {' '.join(command)}")
|
||||
print(f"prompt:\n{prompt}")
|
||||
return 0
|
||||
report = run_delegation(
|
||||
route,
|
||||
repo,
|
||||
prompt,
|
||||
args.mode,
|
||||
timeout=args.timeout,
|
||||
)
|
||||
print(f"[{route.provider} · {route.model} · {route.effort} · {args.mode}]")
|
||||
print(report)
|
||||
return 0
|
||||
except (OSError, RuntimeError, ValueError) as error:
|
||||
print(f"delegate: error: {error}", file=sys.stderr)
|
||||
return 2
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,138 @@
|
||||
---
|
||||
name: diagnosing-bugs
|
||||
description: Diagnosis loop for hard bugs and performance regressions. Use when the user says "diagnose"/"debug this", or reports something broken/throwing/failing/slow.
|
||||
---
|
||||
|
||||
# Diagnosing Bugs
|
||||
|
||||
A discipline for hard bugs. Skip phases only when explicitly justified.
|
||||
|
||||
When exploring the codebase, read `CONTEXT.md` (if it exists) to get a clear mental model of the relevant modules, and check ADRs in the area you're touching.
|
||||
|
||||
## Redact
|
||||
|
||||
This skill has you show commands, outputs and captured artifacts. **Redact every secret first** — write `<REDACTED>` in its place. Build loops against env vars, so the credential stays in the environment rather than in what you show. Captured artifacts carry auth headers: quote only the lines that carry the signal.
|
||||
|
||||
If the redacted output is not enough to diagnose the bug, say so and ask the user.
|
||||
|
||||
## Phase 1 — Build a feedback loop
|
||||
|
||||
**This is the skill.** Everything else is mechanical. If you have a **tight** pass/fail signal for the bug — one that goes red on _this_ bug — you will find the cause; bisection, hypothesis-testing, and instrumentation all just consume it. If you don't have one, no amount of staring at code will save you.
|
||||
|
||||
Spend disproportionate effort here. **Be aggressive. Be creative. Refuse to give up.**
|
||||
|
||||
### Ways to construct one — try them in roughly this order
|
||||
|
||||
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.
|
||||
|
||||
### Tighten the loop
|
||||
|
||||
Treat the loop as a product. Once you have _a_ loop, **tighten** it:
|
||||
|
||||
- Can I make it faster? (Cache setup, skip unrelated init, narrow the test scope.)
|
||||
- Can I make the signal sharper? (Assert on the specific symptom, not "didn't crash".)
|
||||
- Can I make it more deterministic? (Pin time, seed RNG, isolate filesystem, freeze network.)
|
||||
|
||||
A 30-second flaky loop is barely better than no loop; a 2-second deterministic one is tight — a debugging superpower.
|
||||
|
||||
### Non-deterministic bugs
|
||||
|
||||
The goal is not a clean repro but a **higher reproduction rate**. Loop the trigger 100×, parallelise, add stress, narrow timing windows, inject sleeps. A 50%-flake bug is debuggable; 1% is not — keep raising the rate until it's debuggable.
|
||||
|
||||
### 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 redacted captured artifact (HAR file, log dump, core dump, screen recording with timestamps), or (c) permission to add temporary production instrumentation. Do **not** proceed to hypothesise without a loop.
|
||||
|
||||
### Completion criterion — a tight loop that goes red
|
||||
|
||||
Phase 1 is done when the loop is **tight** and **red-capable**: you can name **one command** — a script path, a test invocation, a curl — that you have **already run at least once** (show the invocation and its output, redacted), and that is:
|
||||
|
||||
- [ ] **Red-capable** — it drives the actual bug code path and asserts the **user's exact symptom**, so it can go red on this bug and green once fixed. Not "runs without erroring" — it must be able to _catch this specific bug_.
|
||||
- [ ] **Deterministic** — same verdict every run (flaky bugs: a pinned, high reproduction rate, per above).
|
||||
- [ ] **Fast** — seconds, not minutes.
|
||||
- [ ] **Agent-runnable** — you can run it unattended; a human in the loop only via `scripts/hitl-loop.template.sh`.
|
||||
|
||||
If you catch yourself reading code to build a theory before this command exists, **stop — jumping straight to a hypothesis is the exact failure this skill prevents.** No red-capable command, no Phase 2.
|
||||
|
||||
## Phase 2 — Reproduce + minimise
|
||||
|
||||
Run the loop. Watch it go red — the bug appears.
|
||||
|
||||
Confirm:
|
||||
|
||||
- [ ] The loop produces the failure mode the **user** described — not a different failure that happens to be nearby. Wrong bug = wrong fix.
|
||||
- [ ] The 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.
|
||||
|
||||
### Minimise
|
||||
|
||||
Once it's red, shrink the repro to the **smallest scenario that still goes red**. Cut inputs, callers, config, data, and steps **one at a time**, re-running the loop after each cut — keep only what's load-bearing for the failure.
|
||||
|
||||
Why bother: a minimal repro shrinks the hypothesis space in Phase 3 (fewer moving parts left to suspect) and becomes the clean regression test in Phase 5.
|
||||
|
||||
Done when **every remaining element is load-bearing** — removing any one of them makes the loop go green.
|
||||
|
||||
Do not proceed until you have reproduced **and** minimised.
|
||||
|
||||
## Phase 3 — Hypothesise
|
||||
|
||||
Generate **3–5 ranked hypotheses** before testing any of them. Single-hypothesis generation anchors on the first plausible idea.
|
||||
|
||||
Each hypothesis must be **falsifiable**: state the prediction it makes.
|
||||
|
||||
> Format: "If <X> is the cause, then <changing Y> will make the bug disappear / <changing Z> 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
|
||||
|
||||
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
|
||||
@@ -0,0 +1,3 @@
|
||||
interface:
|
||||
display_name: "Diagnosing Bugs"
|
||||
short_description: "Diagnose hard bugs and regressions"
|
||||
@@ -0,0 +1,44 @@
|
||||
#!/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 "<instruction>" → show instruction, wait for Enter
|
||||
# capture VAR "<question>" → show question, read response into VAR
|
||||
#
|
||||
# At the end, captured values are printed as KEY=VALUE for the agent to parse.
|
||||
#
|
||||
# `capture` prints its value back to the terminal, where the agent reads it — so
|
||||
# capture observations, and leave signing in to the user as a `step`.
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
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"
|
||||
@@ -4,4 +4,4 @@ description: A relentless interview to sharpen a plan or design.
|
||||
disable-model-invocation: true
|
||||
---
|
||||
|
||||
Run a `/grilling` session.
|
||||
Call the Skill tool with "grilling".
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
interface:
|
||||
display_name: "Grill Me"
|
||||
short_description: "Sharpen a plan through interview"
|
||||
policy:
|
||||
allow_implicit_invocation: false
|
||||
@@ -0,0 +1,22 @@
|
||||
---
|
||||
name: grilling
|
||||
description: Grill the user relentlessly about a plan, decision, or idea. Use when the user wants to stress-test their thinking, or uses any 'grill' trigger phrases.
|
||||
---
|
||||
|
||||
Interview the user relentlessly until you reach a shared understanding. Map this as a **design tree**: every decision branches into the decisions that hang off it.
|
||||
|
||||
Work the tree in **rounds**. The **frontier** is every decision whose prerequisites are already settled: the questions you can ask _now_ without guessing at answers you haven't heard yet. Ask the whole frontier in one round: number each question and give your recommended answer. Then wait for the user's answers before the next round.
|
||||
|
||||
Each question should be formatted like so:
|
||||
|
||||
```
|
||||
❓ **Q1** - **<question title>**: <question body, might be multiple paragraphs, including multiple choices>
|
||||
|
||||
➡️ <your recommended answer>
|
||||
```
|
||||
|
||||
Each round the user answers reshapes the tree: settled decisions push the frontier outward and unblock questions that depended on them. Recompute the frontier and ask the next round. A question whose answer depends on another question still open in this round belongs to a _later_ round, not this one.
|
||||
|
||||
Finding _facts_ is your job, never the user's. When a frontier question needs a fact from the environment (filesystem, tools, etc.), dispatch a sub-agent to find it; don't ask the user for anything you could look up yourself. Don't block on it: a running exploration is an unsettled prerequisite, so only the questions downstream of it wait for the sub-agent to report; ask the rest of the frontier now. The _decisions_ are the user's: put each to them and wait.
|
||||
|
||||
The session is done when the frontier is empty: every branch of the design tree visited, nothing left silently assumed. Do not act on it until the user confirms you have reached a shared understanding.
|
||||
@@ -0,0 +1,3 @@
|
||||
interface:
|
||||
display_name: "Grilling"
|
||||
short_description: "Stress-test thinking a round of questions at a time"
|
||||
@@ -0,0 +1,123 @@
|
||||
# HTML Report Format
|
||||
|
||||
The architectural review is rendered as a single self-contained HTML file in the OS temp directory. Tailwind and Mermaid both come from CDNs. Mermaid handles graph-shaped diagrams reliably; hand-built divs and inline SVG handle the more editorial visuals (mass diagrams, cross-sections). Mix the two — don't lean on Mermaid for everything, it'll start to look generic.
|
||||
|
||||
## Scaffold
|
||||
|
||||
```html
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<title>Architecture review — {{repo name}}</title>
|
||||
<script src="https://cdn.tailwindcss.com"></script>
|
||||
<script type="module">
|
||||
import mermaid from "https://cdn.jsdelivr.net/npm/mermaid@11/dist/mermaid.esm.min.mjs";
|
||||
mermaid.initialize({ startOnLoad: true, theme: "neutral", securityLevel: "loose" });
|
||||
</script>
|
||||
<style>
|
||||
/* small custom layer for things Tailwind doesn't cover cleanly:
|
||||
dashed seam lines, hand-drawn-feeling arrow heads, etc. */
|
||||
.seam { stroke-dasharray: 4 4; }
|
||||
.leak { stroke: #dc2626; }
|
||||
.deep { background: linear-gradient(135deg, #0f172a, #1e293b); }
|
||||
</style>
|
||||
</head>
|
||||
<body class="bg-stone-50 text-slate-900 font-sans">
|
||||
<main class="max-w-5xl mx-auto px-6 py-12 space-y-12">
|
||||
<header>...</header>
|
||||
<section id="candidates" class="space-y-10">...</section>
|
||||
<section id="top-recommendation">...</section>
|
||||
</main>
|
||||
</body>
|
||||
</html>
|
||||
```
|
||||
|
||||
## Header
|
||||
|
||||
Repo name, date, and a compact legend: solid box = module, dashed line = seam, red arrow = leakage, thick dark box = deep module. No introduction paragraph — straight into the candidates.
|
||||
|
||||
## Candidate card
|
||||
|
||||
The diagrams carry the weight. Prose is sparse, plain, and uses the glossary terms (from the `/codebase-design` skill) without ceremony.
|
||||
|
||||
Each candidate is one `<article>`:
|
||||
|
||||
- **Title** — short, names the deepening (e.g. "Collapse the Order intake pipeline").
|
||||
- **Badge row** — recommendation strength (`Strong` = emerald, `Worth exploring` = amber, `Speculative` = slate), plus a tag for the dependency category (`in-process`, `local-substitutable`, `ports & adapters`, `mock`).
|
||||
- **Files** — monospaced list, `font-mono text-sm`.
|
||||
- **Before / After diagram** — the centrepiece. Two columns, side by side. See patterns below.
|
||||
- **Problem** — one sentence. What hurts.
|
||||
- **Solution** — one sentence. What changes.
|
||||
- **Wins** — bullets, ≤6 words each. e.g. "Tests hit one interface", "Pricing logic stops leaking", "Delete 4 shallow wrappers".
|
||||
- **ADR callout** (if applicable) — one line in an amber-tinted box.
|
||||
|
||||
No paragraphs of explanation. If the diagram needs a paragraph to be understood, redraw the diagram.
|
||||
|
||||
## Diagram patterns
|
||||
|
||||
Pick the pattern that fits the candidate. Mix them. Don't make every diagram look the same — variety is part of the point.
|
||||
|
||||
### Mermaid graph (the workhorse for dependencies / call flow)
|
||||
|
||||
Use a Mermaid `flowchart` or `graph` when the point is "X calls Y calls Z, and look at the mess." Wrap it in a Tailwind-styled card so it doesn't feel parachuted in. Style with classDef to colour leakage edges red and the deep module dark. Sequence diagrams work well for "before: 6 round-trips; after: 1."
|
||||
|
||||
```html
|
||||
<div class="rounded-lg border border-slate-200 bg-white p-4">
|
||||
<pre class="mermaid">
|
||||
flowchart LR
|
||||
A[OrderHandler] --> B[OrderValidator]
|
||||
B --> C[OrderRepo]
|
||||
C -.leak.-> D[PricingClient]
|
||||
classDef leak stroke:#dc2626,stroke-width:2px;
|
||||
class C,D leak
|
||||
</pre>
|
||||
</div>
|
||||
```
|
||||
|
||||
### Hand-built boxes-and-arrows (when Mermaid's layout fights you)
|
||||
|
||||
Modules as `<div>`s with borders and labels. Arrows as inline SVG `<line>` or `<path>` elements positioned absolutely over a relative container. Reach for this when you want the "after" diagram to feel like one thick-bordered deep module with greyed-out internals — Mermaid won't render that with the right weight.
|
||||
|
||||
### Cross-section (good for layered shallowness)
|
||||
|
||||
Stack horizontal bands (`h-12 border-l-4`) to show layers a call passes through. Before: 6 thin layers each doing nothing. After: 1 thick band labelled with the consolidated responsibility.
|
||||
|
||||
### Mass diagram (good for "interface as wide as implementation")
|
||||
|
||||
Two rectangles per module — one for interface surface area, one for implementation. Before: interface rectangle is nearly as tall as the implementation rectangle (shallow). After: interface rectangle is short, implementation rectangle is tall (deep).
|
||||
|
||||
### Call-graph collapse
|
||||
|
||||
Before: a tree of function calls rendered as nested boxes. After: the same tree collapsed into one box, with the now-internal calls shown faded inside it.
|
||||
|
||||
## Style guidance
|
||||
|
||||
- Lean editorial, not corporate-dashboard. Generous whitespace. Serif optional for headings (`font-serif` works well with stone/slate).
|
||||
- Colour sparingly: one accent (emerald or indigo) plus red for leakage and amber for warnings.
|
||||
- Keep diagrams ~320px tall so before/after sits comfortably side by side without scrolling.
|
||||
- Use `text-xs uppercase tracking-wider` for module labels inside diagrams — they should read as schematic, not as UI.
|
||||
- The only scripts are the Tailwind CDN and the Mermaid ESM import. The report is otherwise static — no app code, no interactivity beyond Mermaid's own rendering.
|
||||
|
||||
## Top recommendation section
|
||||
|
||||
One larger card. Candidate name, one sentence on why, anchor link to its card. That's it.
|
||||
|
||||
## Tone
|
||||
|
||||
Plain English, concise — but the architectural nouns and verbs come straight from the `/codebase-design` skill. Concision is not an excuse to drift.
|
||||
|
||||
**Use exactly:** module, interface, implementation, depth, deep, shallow, seam, adapter, leverage, locality.
|
||||
|
||||
**Never substitute:** component, service, unit (for module) · API, signature (for interface) · boundary (for seam) · layer, wrapper (for module, when you mean module).
|
||||
|
||||
**Phrasings that fit the style:**
|
||||
|
||||
- "Order intake module is shallow — interface nearly matches the implementation."
|
||||
- "Pricing leaks across the seam."
|
||||
- "Deepen: one interface, one place to test."
|
||||
- "Two adapters justify the seam: HTTP in prod, in-memory in tests."
|
||||
|
||||
**Wins bullets** name the gain in glossary terms: *"locality: bugs concentrate in one module"*, *"leverage: one interface, N call sites"*, *"interface shrinks; implementation absorbs the wrappers"*. Don't write *"easier to maintain"* or *"cleaner code"* — those terms aren't in the glossary and don't earn their place.
|
||||
|
||||
No hedging, no throat-clearing, no "it's worth noting that…". If a sentence could be a bullet, make it a bullet. If a bullet could be cut, cut it. If a term isn't in the `/codebase-design` glossary, reach for one that is before inventing a new one.
|
||||
@@ -0,0 +1,71 @@
|
||||
---
|
||||
name: improve-codebase-architecture
|
||||
description: Scan a codebase for deepening opportunities, present them as a visual HTML report, then grill through whichever one you pick.
|
||||
disable-model-invocation: true
|
||||
---
|
||||
|
||||
# Improve Codebase Architecture
|
||||
|
||||
Surface architectural friction and propose **deepening opportunities** — refactors that turn shallow modules into deep ones. The aim is testability and AI-navigability.
|
||||
|
||||
This command is _informed_ by the project's domain model and built on a shared design vocabulary:
|
||||
|
||||
- Call the Skill tool with "codebase-design" for the architecture vocabulary (**module**, **interface**, **depth**, **seam**, **adapter**, **leverage**, **locality**) and its principles (the deletion test, "the interface is the test surface", "one adapter = hypothetical seam, two = real"). Use these terms exactly in every suggestion — don't drift into "component," "service," "API," or "boundary."
|
||||
- The domain language in `CONTEXT.md` gives names to good seams; ADRs in `docs/adr/` record decisions this command should not re-litigate.
|
||||
|
||||
## Process
|
||||
|
||||
### 1. Explore
|
||||
|
||||
**Scope before you scan — YAGNI.** Deepening a module pays off by making future changes to it easier, so put extra weight on the parts of the codebase that have recently changed. Decide *where* to look before you look:
|
||||
|
||||
- If the user named a direction — a module, a subsystem, a pain point — take it, and skip the inference below.
|
||||
- Otherwise, walk back a good stretch of the commit history (`git log --oneline`) to find the codebase's hot spots — the files and areas that keep coming up — and let those paths pull your attention first. If the changes are scattered with no clear hot spot, widen the net.
|
||||
|
||||
Read the project's domain glossary (`CONTEXT.md`) and any ADRs in the area you're touching first.
|
||||
|
||||
Then spawn a sub-agent to walk the codebase. Don't follow rigid heuristics — explore organically and note where you experience friction:
|
||||
|
||||
- Where does understanding one concept require bouncing between many small modules?
|
||||
- Where are modules **shallow** — interface nearly as complex as the implementation?
|
||||
- Where 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 as an HTML report
|
||||
|
||||
Write a self-contained HTML file to the OS temp directory so nothing lands in the repo. Resolve the temp dir from `$TMPDIR`, falling back to `/tmp` (or `%TEMP%` on Windows), and write to `<tmpdir>/architecture-review-<timestamp>.html` so each run gets a fresh file. Open it for the user — `xdg-open <path>` on Linux, `open <path>` on macOS, `start <path>` on Windows — and tell them the absolute path.
|
||||
|
||||
The report uses **Tailwind via CDN** for layout and styling, and **Mermaid via CDN** for diagrams where a graph/flow/sequence reliably communicates the structure. Mix Mermaid with hand-crafted CSS/SVG visuals — use Mermaid when relationships are graph-shaped (call graphs, dependencies, sequences), and hand-built divs/SVG when you want something more editorial (mass diagrams, cross-sections, collapse animations). Each candidate gets a **before/after visualisation**. Be visual.
|
||||
|
||||
For each candidate, render a card with:
|
||||
|
||||
- **Files** — which files/modules are involved
|
||||
- **Problem** — why the current architecture is causing friction
|
||||
- **Solution** — plain English description of what would change
|
||||
- **Benefits** — explained in terms of locality and leverage, and how tests would improve
|
||||
- **Before / After diagram** — side-by-side, custom-drawn, illustrating the shallowness and the deepening
|
||||
- **Recommendation strength** — one of `Strong`, `Worth exploring`, `Speculative`, rendered as a badge
|
||||
|
||||
End the report with a **Top recommendation** section: which candidate you'd tackle first and why.
|
||||
|
||||
**Use CONTEXT.md vocabulary for the domain, and the `/codebase-design` vocabulary for the architecture.** If `CONTEXT.md` defines "Order," talk about "the Order intake module" — not "the FooBarHandler," and not "the Order service."
|
||||
|
||||
**ADR conflicts**: if a candidate contradicts an existing ADR, only surface it when the friction is real enough to warrant revisiting the ADR. Mark it clearly in the card (e.g. a warning callout: _"contradicts ADR-0007 — but worth reopening because…"_). Don't list every theoretical refactor an ADR forbids.
|
||||
|
||||
See [HTML-REPORT.md](HTML-REPORT.md) for the full HTML scaffold, diagram patterns, and styling guidance.
|
||||
|
||||
Do NOT propose interfaces yet. After the file is written, ask the user: "Which of these would you like to explore?"
|
||||
|
||||
### 3. Grilling loop
|
||||
|
||||
Once the user picks a candidate, call the Skill tool with "grilling" to walk the decision tree with them — constraints, dependencies, the shape of the deepened module, what sits behind the seam, what tests survive.
|
||||
|
||||
Side effects happen inline as decisions crystallize — call the Skill tool with "domain-modeling" to keep the domain model current as you go:
|
||||
|
||||
- **Naming a deepened module after a concept not in `CONTEXT.md`?** Add the term to `CONTEXT.md`. 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.
|
||||
- **Want to explore alternative interfaces for the deepened module?** Call the Skill tool with "codebase-design" and use its design-it-twice parallel sub-agent pattern.
|
||||
@@ -0,0 +1,5 @@
|
||||
interface:
|
||||
display_name: "Improve Codebase Architecture"
|
||||
short_description: "Find and grill architecture improvements"
|
||||
policy:
|
||||
allow_implicit_invocation: false
|
||||
@@ -1,21 +0,0 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2025 Hardik Pandya
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -1,62 +0,0 @@
|
||||
# Stop Slop
|
||||
|
||||
A skill for removing AI tells from prose.
|
||||
|
||||
<img width="3840" height="2160" alt="G-Yg4RVbIAAhVxW" src="https://github.com/user-attachments/assets/902afc15-1f40-4a9d-af24-8cd67afb8ebf" />
|
||||
|
||||
## What this is
|
||||
|
||||
AI writing has patterns. Predictable phrases, structures, rhythms. This skill teaches Claude (or any LLM) to catch and remove them.
|
||||
|
||||
## Skill Structure
|
||||
|
||||
```
|
||||
stop-slop/
|
||||
├── SKILL.md # Core instructions
|
||||
├── references/
|
||||
│ ├── phrases.md # Phrases to remove
|
||||
│ ├── structures.md # Structural patterns to avoid
|
||||
│ └── examples.md # Before/after transformations
|
||||
├── README.md
|
||||
└── LICENSE
|
||||
```
|
||||
|
||||
## Quick start
|
||||
|
||||
**Claude Code:** Add this folder as a skill.
|
||||
|
||||
**Claude Projects:** Upload `SKILL.md` and reference files to project knowledge.
|
||||
|
||||
**Custom instructions:** Copy core rules from `SKILL.md`.
|
||||
|
||||
**API calls:** Include `SKILL.md` in your system prompt. Reference files load on demand.
|
||||
|
||||
## What it catches
|
||||
|
||||
**Banned phrases** - Throat-clearing openers, emphasis crutches, business jargon, all adverbs, vague declaratives, meta-commentary. See `references/phrases.md`.
|
||||
|
||||
**Structural clichés** - Binary contrasts, negative listings, dramatic fragmentation, rhetorical setups, false agency, narrator-from-a-distance voice, passive voice. See `references/structures.md`.
|
||||
|
||||
**Sentence-level rules** - No Wh- sentence starters, no em dashes, no staccato fragmentation, no lazy extremes, active voice required.
|
||||
|
||||
## Scoring
|
||||
|
||||
Rate 1-10 on each dimension:
|
||||
|
||||
| Dimension | Question |
|
||||
|-----------|----------|
|
||||
| Directness | Statements or announcements? |
|
||||
| Rhythm | Varied or metronomic? |
|
||||
| Trust | Respects reader intelligence? |
|
||||
| Authenticity | Sounds human? |
|
||||
| Density | Anything cuttable? |
|
||||
|
||||
Below 35/50: revise.
|
||||
|
||||
## Author
|
||||
|
||||
[Hardik Pandya](https://hvpandya.com)
|
||||
|
||||
## License
|
||||
|
||||
MIT. Use freely, share widely.
|
||||
@@ -1,68 +0,0 @@
|
||||
---
|
||||
name: stop-slop
|
||||
description: Remove AI writing patterns from prose. Use when drafting, editing, or reviewing text to eliminate predictable AI tells.
|
||||
metadata:
|
||||
trigger: Writing prose, editing drafts, reviewing content for AI patterns
|
||||
author: Hardik Pandya (https://hvpandya.com)
|
||||
---
|
||||
|
||||
# Stop Slop
|
||||
|
||||
Eliminate predictable AI writing patterns from prose.
|
||||
|
||||
## Core Rules
|
||||
|
||||
1. **Cut filler phrases.** Remove throat-clearing openers, emphasis crutches, and all adverbs. See [references/phrases.md](references/phrases.md).
|
||||
|
||||
2. **Break formulaic structures.** Avoid binary contrasts, negative listings, dramatic fragmentation, rhetorical setups, false agency. See [references/structures.md](references/structures.md).
|
||||
|
||||
3. **Use active voice.** Every sentence needs a human subject doing something. No passive constructions. No inanimate objects performing human actions ("the complaint becomes a fix").
|
||||
|
||||
4. **Be specific.** No vague declaratives ("The reasons are structural"). Name the specific thing. No lazy extremes ("every," "always," "never") doing vague work.
|
||||
|
||||
5. **Put the reader in the room.** No narrator-from-a-distance voice. "You" beats "People." Specifics beat abstractions.
|
||||
|
||||
6. **Vary rhythm.** Mix sentence lengths. Two items beat three. End paragraphs differently. No em dashes.
|
||||
|
||||
7. **Trust readers.** State facts directly. Skip softening, justification, hand-holding.
|
||||
|
||||
8. **Cut quotables.** If it sounds like a pull-quote, rewrite it.
|
||||
|
||||
## Quick Checks
|
||||
|
||||
Before delivering prose:
|
||||
|
||||
- Any adverbs? Kill them.
|
||||
- Any passive voice? Find the actor, make them the subject.
|
||||
- Inanimate thing doing a human verb ("the decision emerges")? Name the person.
|
||||
- Sentence starts with a Wh- word? Restructure it.
|
||||
- Any "here's what/this/that" throat-clearing? Cut to the point.
|
||||
- Any "not X, it's Y" contrasts? State Y directly.
|
||||
- Three consecutive sentences match length? Break one.
|
||||
- Paragraph ends with punchy one-liner? Vary it.
|
||||
- Em-dash anywhere? Remove it.
|
||||
- Vague declarative ("The implications are significant")? Name the specific implication.
|
||||
- Narrator-from-a-distance ("Nobody designed this")? Put the reader in the scene.
|
||||
- Meta-joiners ("The rest of this essay...")? Delete. Let the essay move.
|
||||
|
||||
## Scoring
|
||||
|
||||
Rate 1-10 on each dimension:
|
||||
|
||||
| Dimension | Question |
|
||||
|-----------|----------|
|
||||
| Directness | Statements or announcements? |
|
||||
| Rhythm | Varied or metronomic? |
|
||||
| Trust | Respects reader intelligence? |
|
||||
| Authenticity | Sounds human? |
|
||||
| Density | Anything cuttable? |
|
||||
|
||||
Below 35/50: revise.
|
||||
|
||||
## Examples
|
||||
|
||||
See [references/examples.md](references/examples.md) for before/after transformations.
|
||||
|
||||
## License
|
||||
|
||||
MIT
|
||||
@@ -1,59 +0,0 @@
|
||||
# Before/After Examples
|
||||
|
||||
## Example 1: Throat-Clearing + Binary Contrast
|
||||
|
||||
**Before:**
|
||||
> "Here's the thing: building products is hard. Not because the technology is complex. Because people are complex. Let that sink in."
|
||||
|
||||
**After:**
|
||||
> "Building products is hard. Technology is manageable. People aren't."
|
||||
|
||||
**Changes:** Removed opener, binary contrast structure, and emphasis crutch. Direct statements.
|
||||
|
||||
---
|
||||
|
||||
## Example 2: Filler + Unnecessary Reassurance
|
||||
|
||||
**Before:**
|
||||
> "It turns out that most teams struggle with alignment. The uncomfortable truth is that nobody wants to admit they're confused. And that's okay."
|
||||
|
||||
**After:**
|
||||
> "Teams struggle with alignment. Nobody admits confusion."
|
||||
|
||||
**Changes:** Cut hedging ("most"), removed throat-clearing phrases, deleted permission-granting ending.
|
||||
|
||||
---
|
||||
|
||||
## Example 3: Business Jargon Stack
|
||||
|
||||
**Before:**
|
||||
> "In today's fast-paced landscape, we need to lean into discomfort and navigate uncertainty with clarity. This matters because your competition isn't waiting."
|
||||
|
||||
**After:**
|
||||
> "Move faster. Your competition is."
|
||||
|
||||
**Changes:** Eliminated jargon entirely. Core message in six words.
|
||||
|
||||
---
|
||||
|
||||
## Example 4: Dramatic Fragmentation
|
||||
|
||||
**Before:**
|
||||
> "Speed. Quality. Cost. You can only pick two. That's it. That's the tradeoff."
|
||||
|
||||
**After:**
|
||||
> "Speed, quality, cost—pick two."
|
||||
|
||||
**Changes:** Single sentence. No performative emphasis.
|
||||
|
||||
---
|
||||
|
||||
## Example 5: Rhetorical Setup
|
||||
|
||||
**Before:**
|
||||
> "What if I told you that the best teams don't optimize for productivity? Here's what I mean: they optimize for learning. Think about it."
|
||||
|
||||
**After:**
|
||||
> "The best teams optimize for learning, not productivity."
|
||||
|
||||
**Changes:** Direct claim. No rhetorical scaffolding.
|
||||
@@ -1,128 +0,0 @@
|
||||
# Phrases to Remove
|
||||
|
||||
## Throat-Clearing Openers
|
||||
|
||||
Remove these announcement phrases. State the content directly.
|
||||
|
||||
- "Here's the thing:"
|
||||
- "Here's what [X]"
|
||||
- "Here's this [X]"
|
||||
- "Here's that [X]"
|
||||
- "Here's why [X]"
|
||||
- "The uncomfortable truth is"
|
||||
- "It turns out"
|
||||
- "The real [X] is"
|
||||
- "Let me be clear"
|
||||
- "The truth is,"
|
||||
- "I'll say it again:"
|
||||
- "I'm going to be honest"
|
||||
- "Can we talk about"
|
||||
- "Here's what I find interesting"
|
||||
- "Here's the problem though"
|
||||
|
||||
Any "here's what/this/that" construction is throat-clearing before the point. Cut it and state the point.
|
||||
|
||||
## Emphasis Crutches
|
||||
|
||||
These add no meaning. Delete them.
|
||||
|
||||
- "Full stop." / "Period."
|
||||
- "Let that sink in."
|
||||
- "This matters because"
|
||||
- "Make no mistake"
|
||||
- "Here's why that matters"
|
||||
|
||||
## Business Jargon
|
||||
|
||||
Replace with plain language.
|
||||
|
||||
| Avoid | Use instead |
|
||||
|-------|-------------|
|
||||
| Navigate (challenges) | Handle, address |
|
||||
| Unpack (analysis) | Explain, examine |
|
||||
| Lean into | Accept, embrace |
|
||||
| Landscape (context) | Situation, field |
|
||||
| Game-changer | Significant, important |
|
||||
| Double down | Commit, increase |
|
||||
| Deep dive | Analysis, examination |
|
||||
| Take a step back | Reconsider |
|
||||
| Moving forward | Next, from now |
|
||||
| Circle back | Return to, revisit |
|
||||
| On the same page | Aligned, agreed |
|
||||
|
||||
## Adverbs
|
||||
|
||||
Kill all adverbs. No -ly words. No softeners, no intensifiers, no hedges.
|
||||
|
||||
Specific offenders:
|
||||
|
||||
- "really"
|
||||
- "just"
|
||||
- "literally"
|
||||
- "genuinely"
|
||||
- "honestly"
|
||||
- "simply"
|
||||
- "actually"
|
||||
- "deeply"
|
||||
- "truly"
|
||||
- "fundamentally"
|
||||
- "inherently"
|
||||
- "inevitably"
|
||||
- "interestingly"
|
||||
- "importantly"
|
||||
- "crucially"
|
||||
|
||||
Also cut these filler phrases:
|
||||
|
||||
- "At its core"
|
||||
- "In today's [X]"
|
||||
- "It's worth noting"
|
||||
- "At the end of the day"
|
||||
- "When it comes to"
|
||||
- "In a world where"
|
||||
- "The reality is"
|
||||
|
||||
## Meta-Commentary
|
||||
|
||||
Remove self-referential asides. The essay should move, not announce its own structure.
|
||||
|
||||
- "Hint:"
|
||||
- "Plot twist:" / "Spoiler:"
|
||||
- "You already know this, but"
|
||||
- "But that's another post"
|
||||
- "X is a feature, not a bug"
|
||||
- "Dressed up as"
|
||||
- "The rest of this essay explains..."
|
||||
- "Let me walk you through..."
|
||||
- "In this section, we'll..."
|
||||
- "As we'll see..."
|
||||
- "I want to explore..."
|
||||
|
||||
## Performative Emphasis
|
||||
|
||||
False intimacy or manufactured sincerity:
|
||||
|
||||
- "creeps in"
|
||||
- "I promise"
|
||||
- "They exist, I promise"
|
||||
|
||||
## Telling Instead of Showing
|
||||
|
||||
Announcing difficulty or significance rather than demonstrating it:
|
||||
|
||||
- "This is genuinely hard"
|
||||
- "This is what leadership actually looks like"
|
||||
- "This is what X actually looks like"
|
||||
- "actually matters"
|
||||
|
||||
## Vague Declaratives
|
||||
|
||||
Sentences that announce importance without naming the specific thing. Kill these.
|
||||
|
||||
- "The reasons are structural"
|
||||
- "The implications are significant"
|
||||
- "This is the deepest problem"
|
||||
- "The stakes are high"
|
||||
- "The consequences are real"
|
||||
|
||||
If a sentence says something is important/deep/structural without showing the specific thing, cut it or replace it with the specific thing.
|
||||
@@ -1,134 +0,0 @@
|
||||
# Structures to Avoid
|
||||
|
||||
## Binary Contrasts
|
||||
|
||||
These create false drama. State the point directly.
|
||||
|
||||
| Pattern | Problem |
|
||||
|---------|---------|
|
||||
| "Not because X. Because Y." / "Not because X, but because Y." | Telegraphed reversal |
|
||||
| "[X] isn't the problem. [Y] is." | Formulaic reframe |
|
||||
| "The answer isn't X. It's Y." | Predictable pivot |
|
||||
| "It feels like X. It's actually Y." | Setup/reveal cliche |
|
||||
| "The question isn't X. It's Y." | Rhetorical misdirection |
|
||||
| "Not X. But Y." / "not X, it's Y" / "isn't X, it's Y" | Mechanical contrast |
|
||||
| "It's not this. It's that." | Same formula, different words |
|
||||
| "stops being X and starts being Y" | False transformation arc |
|
||||
| "doesn't mean X, but actually Y" | Negation-then-assertion crutch |
|
||||
| "is about X but not Y" | False distinction |
|
||||
| "not just X but also Y" | Additive hedge |
|
||||
|
||||
**Instead:** State Y directly. "The problem is Y." "Y matters here." Drop the negation entirely.
|
||||
|
||||
## Negative Listing
|
||||
|
||||
Listing what something is *not* before revealing what it *is*. A rhetorical striptease.
|
||||
|
||||
| Pattern | Problem |
|
||||
|---------|---------|
|
||||
| "Not a X... Not a Y... A Z." | Dramatic buildup through negation |
|
||||
| "It wasn't X. It wasn't Y. It was Z." | Same structure, past tense |
|
||||
|
||||
**Instead:** State Z. The reader doesn't need the runway.
|
||||
|
||||
## Dramatic Fragmentation
|
||||
|
||||
Sentence fragments for emphasis read as manufactured profundity.
|
||||
|
||||
| Pattern | Problem |
|
||||
|---------|---------|
|
||||
| "[Noun]. That's it. That's the [thing]." | Performative simplicity |
|
||||
| "X. And Y. And Z." | Staccato drama |
|
||||
| "This unlocks something. [Word]." | Artificial revelation |
|
||||
|
||||
**Instead:** Complete sentences. Trust content over presentation.
|
||||
|
||||
## Rhetorical Setups
|
||||
|
||||
These announce insight rather than deliver it.
|
||||
|
||||
| Pattern | Problem |
|
||||
|---------|---------|
|
||||
| "What if [reframe]?" | Socratic posturing |
|
||||
| "Here's what I mean:" | Redundant preview |
|
||||
| "Think about it:" | Condescending prompt |
|
||||
| "And that's okay." | Unnecessary permission |
|
||||
|
||||
**Instead:** Make the point. Let readers draw conclusions.
|
||||
|
||||
## Formulaic Constructions
|
||||
|
||||
| Pattern | Problem |
|
||||
|---------|---------|
|
||||
| "By the time X, I was Y." | Narrative template |
|
||||
| "X that isn't Y" | Indirect. Say "X is broken" |
|
||||
|
||||
## False Agency
|
||||
|
||||
Giving inanimate things human verbs. Complaints don't "become" fixes. Bets don't "live or die." Decisions don't "emerge." A person does something to make those things happen. AI loves this because it avoids naming the actor.
|
||||
|
||||
| Pattern | Problem |
|
||||
|---------|---------|
|
||||
| "a complaint becomes a fix" | The complaint did nothing. Someone fixed it. |
|
||||
| "a bet lives or dies in days" | Bets don't have lifespans. Someone kills the project or ships it. |
|
||||
| "the decision emerges" | Decisions don't emerge. Someone decides. |
|
||||
| "the culture shifts" | Cultures don't shift on their own. People change behavior. |
|
||||
| "the conversation moves toward" | Conversations don't move. Someone steers. |
|
||||
| "the data tells us" | Data sits there. Someone reads it and draws a conclusion. |
|
||||
| "the market rewards" | Markets don't reward. Buyers pay for things. |
|
||||
|
||||
**Instead:** Name the human. "The team fixed it that week" beats "the complaint becomes a fix." If no specific person fits, use "you" to put the reader in the seat.
|
||||
|
||||
## Narrator-from-a-Distance
|
||||
|
||||
Floating above the scene instead of putting the reader in it.
|
||||
|
||||
| Pattern | Problem |
|
||||
|---------|---------|
|
||||
| "Nobody designed this." | Disembodied observation |
|
||||
| "This happens because..." | Lecturer voice |
|
||||
| "This is why..." | Same |
|
||||
| "People tend to..." | Armchair sociologist |
|
||||
|
||||
**Instead:** Put the reader in the room. "You don't sit down one day and decide to..." beats "Nobody designed this."
|
||||
|
||||
## Passive Voice
|
||||
|
||||
Every sentence needs a subject doing something. Passive voice hides the actor and drains energy.
|
||||
|
||||
| Pattern | Fix |
|
||||
|---------|-----|
|
||||
| "X was created" | Name who created it |
|
||||
| "It is believed that" | Name who believes it |
|
||||
| "Mistakes were made" | Name who made them |
|
||||
| "The decision was reached" | Name who decided |
|
||||
|
||||
**Instead:** Find the actor. Put them at the front of the sentence.
|
||||
|
||||
## Sentence Starters to Avoid
|
||||
|
||||
| Pattern | Fix |
|
||||
|---------|-----|
|
||||
| Sentences starting with What, When, Where, Which, Who, Why, How | Restructure. Lead with the subject or the verb. |
|
||||
| Paragraphs starting with "So" | Start with content |
|
||||
| Sentences starting with "Look," | Remove |
|
||||
|
||||
Wh- openers become a crutch. "What makes this hard is..." becomes "The constraint is..." or better, name the specific constraint.
|
||||
|
||||
## Rhythm Patterns
|
||||
|
||||
| Pattern | Fix |
|
||||
|---------|-----|
|
||||
| Three-item lists | Use two items or one |
|
||||
| Questions answered immediately | Let questions breathe or cut them |
|
||||
| Every paragraph ends punchily | Vary endings |
|
||||
| Em-dashes | Remove. Use commas or periods. No em dashes at all. |
|
||||
| Staccato fragmentation | Don't stack short punchy sentences |
|
||||
| "Not always. Not perfectly." | Hedging disguised as reassurance |
|
||||
|
||||
## Word Patterns
|
||||
|
||||
| Pattern | Problem |
|
||||
|---------|---------|
|
||||
| Lazy extremes (every, always, never, everyone, everybody, nobody) | False authority. Use specifics instead of sweeping claims. |
|
||||
| All adverbs (-ly words, "really," "just," "literally," "genuinely," "honestly," "simply," "actually") | Empty emphasis. See phrases.md for full list. |
|
||||
@@ -0,0 +1,38 @@
|
||||
---
|
||||
name: tdd
|
||||
description: Test-driven development. Use when the user wants to build features or fix bugs test-first, mentions "red-green-refactor", or wants integration tests.
|
||||
---
|
||||
|
||||
# Test-Driven Development
|
||||
|
||||
TDD is the red → green loop. This skill is the reference that makes that loop produce tests worth keeping: what a good test is, where tests go, the anti-patterns, and the rules of the loop. Every section applies on every cycle — consult them before and during the loop, not after.
|
||||
|
||||
When exploring the codebase, read `CONTEXT.md` (if it exists) so test names and interface vocabulary match the project's domain language, and respect ADRs in the area you're touching.
|
||||
|
||||
## What a good test is
|
||||
|
||||
Tests verify behavior through public interfaces, not implementation details. Code can change entirely; tests shouldn't. A good test reads like a specification — "user can checkout with valid cart" tells you exactly what capability exists — and survives refactors because it doesn't care about internal structure.
|
||||
|
||||
See [tests.md](tests.md) for examples and [mocking.md](mocking.md) for mocking guidelines.
|
||||
|
||||
## Seams — where tests go
|
||||
|
||||
A **seam** is the public boundary you test at: the interface where you observe behavior without reaching inside. Tests live at seams, never against internals.
|
||||
|
||||
**Test only at pre-agreed seams.** Before writing any test, write down the seams under test and confirm them with the user. No test is written at an unconfirmed seam. You can't test everything — agreeing the seams up front is how testing effort lands on the critical paths and complex logic instead of every edge case.
|
||||
|
||||
Ask: "What's the public interface, and which seams should we test?"
|
||||
|
||||
When the shape of that interface is itself in question — how deep the module is, where the seam belongs, what the interface should expose — call the Skill tool with "codebase-design" for the vocabulary. It is the shared source of the module, interface, depth, seam, adapter, leverage and locality terms, and it is a reference to consult, not a session to run.
|
||||
|
||||
## Anti-patterns
|
||||
|
||||
- **Implementation-coupled** — mocks internal collaborators, tests private methods, or verifies through a side channel (querying the database instead of using the interface). The tell: the test breaks when you refactor but behavior hasn't changed.
|
||||
- **Tautological** — the assertion recomputes the expected value the way the code does (`expect(add(a, b)).toBe(a + b)`, a snapshot derived by hand the same way, a constant asserted equal to itself), so it passes by construction and can never disagree with the code. Expected values must come from an independent source of truth — a known-good literal, a worked example, the spec.
|
||||
- **Horizontal slicing** — writing all tests first, then all implementation. Bulk tests verify _imagined_ behavior: you test the _shape_ of things rather than user-facing behavior, the tests go insensitive to real changes, and you commit to test structure before understanding the implementation. Work in **vertical slices** instead — one test → one implementation → repeat, each test a **tracer bullet** that responds to what the last cycle taught you.
|
||||
|
||||
## Rules of the loop
|
||||
|
||||
- **Red before green.** Write the failing test first, then only enough code to pass it. Don't anticipate future tests or add speculative features.
|
||||
- **One slice at a time.** One seam, one test, one minimal implementation per cycle.
|
||||
- **Refactoring is not part of the loop.** It belongs to the review stage (see the `code-review` skill), not the red → green implementation cycle.
|
||||
@@ -0,0 +1,3 @@
|
||||
interface:
|
||||
display_name: "TDD"
|
||||
short_description: "Test-driven red-green-refactor"
|
||||
@@ -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
|
||||
@@ -0,0 +1,77 @@
|
||||
# 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");
|
||||
});
|
||||
```
|
||||
|
||||
**Tautological tests**: Expected value restates the implementation, so the test passes by construction.
|
||||
|
||||
```typescript
|
||||
// BAD: Expected value is recomputed the way the code computes it
|
||||
test("calculateTotal sums line items", () => {
|
||||
const items = [{ price: 10 }, { price: 5 }];
|
||||
const expected = items.reduce((sum, i) => sum + i.price, 0);
|
||||
expect(calculateTotal(items)).toBe(expected);
|
||||
});
|
||||
|
||||
// GOOD: Expected value is an independent, known literal
|
||||
test("calculateTotal sums line items", () => {
|
||||
expect(calculateTotal([{ price: 10 }, { price: 5 }])).toBe(15);
|
||||
});
|
||||
```
|
||||
@@ -1,371 +0,0 @@
|
||||
---
|
||||
name: test-driven-development
|
||||
description: Use when implementing any feature or bugfix, before writing implementation code
|
||||
---
|
||||
|
||||
# Test-Driven Development (TDD)
|
||||
|
||||
## Overview
|
||||
|
||||
Write the test first. Watch it fail. Write minimal code to pass.
|
||||
|
||||
**Core principle:** If you didn't watch the test fail, you don't know if it tests the right thing.
|
||||
|
||||
**Violating the letter of the rules is violating the spirit of the rules.**
|
||||
|
||||
## When to Use
|
||||
|
||||
**Always:**
|
||||
- New features
|
||||
- Bug fixes
|
||||
- Refactoring
|
||||
- Behavior changes
|
||||
|
||||
**Exceptions (ask your human partner):**
|
||||
- Throwaway prototypes
|
||||
- Generated code
|
||||
- Configuration files
|
||||
|
||||
Thinking "skip TDD just this once"? Stop. That's rationalization.
|
||||
|
||||
## The Iron Law
|
||||
|
||||
```
|
||||
NO PRODUCTION CODE WITHOUT A FAILING TEST FIRST
|
||||
```
|
||||
|
||||
Write code before the test? Delete it. Start over.
|
||||
|
||||
**No exceptions:**
|
||||
- Don't keep it as "reference"
|
||||
- Don't "adapt" it while writing tests
|
||||
- Don't look at it
|
||||
- Delete means delete
|
||||
|
||||
Implement fresh from tests. Period.
|
||||
|
||||
## Red-Green-Refactor
|
||||
|
||||
```dot
|
||||
digraph tdd_cycle {
|
||||
rankdir=LR;
|
||||
red [label="RED\nWrite failing test", shape=box, style=filled, fillcolor="#ffcccc"];
|
||||
verify_red [label="Verify fails\ncorrectly", shape=diamond];
|
||||
green [label="GREEN\nMinimal code", shape=box, style=filled, fillcolor="#ccffcc"];
|
||||
verify_green [label="Verify passes\nAll green", shape=diamond];
|
||||
refactor [label="REFACTOR\nClean up", shape=box, style=filled, fillcolor="#ccccff"];
|
||||
next [label="Next", shape=ellipse];
|
||||
|
||||
red -> verify_red;
|
||||
verify_red -> green [label="yes"];
|
||||
verify_red -> red [label="wrong\nfailure"];
|
||||
green -> verify_green;
|
||||
verify_green -> refactor [label="yes"];
|
||||
verify_green -> green [label="no"];
|
||||
refactor -> verify_green [label="stay\ngreen"];
|
||||
verify_green -> next;
|
||||
next -> red;
|
||||
}
|
||||
```
|
||||
|
||||
### RED - Write Failing Test
|
||||
|
||||
Write one minimal test showing what should happen.
|
||||
|
||||
<Good>
|
||||
```typescript
|
||||
test('retries failed operations 3 times', async () => {
|
||||
let attempts = 0;
|
||||
const operation = () => {
|
||||
attempts++;
|
||||
if (attempts < 3) throw new Error('fail');
|
||||
return 'success';
|
||||
};
|
||||
|
||||
const result = await retryOperation(operation);
|
||||
|
||||
expect(result).toBe('success');
|
||||
expect(attempts).toBe(3);
|
||||
});
|
||||
```
|
||||
Clear name, tests real behavior, one thing
|
||||
</Good>
|
||||
|
||||
<Bad>
|
||||
```typescript
|
||||
test('retry works', async () => {
|
||||
const mock = jest.fn()
|
||||
.mockRejectedValueOnce(new Error())
|
||||
.mockRejectedValueOnce(new Error())
|
||||
.mockResolvedValueOnce('success');
|
||||
await retryOperation(mock);
|
||||
expect(mock).toHaveBeenCalledTimes(3);
|
||||
});
|
||||
```
|
||||
Vague name, tests mock not code
|
||||
</Bad>
|
||||
|
||||
**Requirements:**
|
||||
- One behavior
|
||||
- Clear name
|
||||
- Real code (no mocks unless unavoidable)
|
||||
|
||||
### Verify RED - Watch It Fail
|
||||
|
||||
**MANDATORY. Never skip.**
|
||||
|
||||
```bash
|
||||
npm test path/to/test.test.ts
|
||||
```
|
||||
|
||||
Confirm:
|
||||
- Test fails (not errors)
|
||||
- Failure message is expected
|
||||
- Fails because feature missing (not typos)
|
||||
|
||||
**Test passes?** You're testing existing behavior. Fix test.
|
||||
|
||||
**Test errors?** Fix error, re-run until it fails correctly.
|
||||
|
||||
### GREEN - Minimal Code
|
||||
|
||||
Write simplest code to pass the test.
|
||||
|
||||
<Good>
|
||||
```typescript
|
||||
async function retryOperation<T>(fn: () => Promise<T>): Promise<T> {
|
||||
for (let i = 0; i < 3; i++) {
|
||||
try {
|
||||
return await fn();
|
||||
} catch (e) {
|
||||
if (i === 2) throw e;
|
||||
}
|
||||
}
|
||||
throw new Error('unreachable');
|
||||
}
|
||||
```
|
||||
Just enough to pass
|
||||
</Good>
|
||||
|
||||
<Bad>
|
||||
```typescript
|
||||
async function retryOperation<T>(
|
||||
fn: () => Promise<T>,
|
||||
options?: {
|
||||
maxRetries?: number;
|
||||
backoff?: 'linear' | 'exponential';
|
||||
onRetry?: (attempt: number) => void;
|
||||
}
|
||||
): Promise<T> {
|
||||
// YAGNI
|
||||
}
|
||||
```
|
||||
Over-engineered
|
||||
</Bad>
|
||||
|
||||
Don't add features, refactor other code, or "improve" beyond the test.
|
||||
|
||||
### Verify GREEN - Watch It Pass
|
||||
|
||||
**MANDATORY.**
|
||||
|
||||
```bash
|
||||
npm test path/to/test.test.ts
|
||||
```
|
||||
|
||||
Confirm:
|
||||
- Test passes
|
||||
- Other tests still pass
|
||||
- Output pristine (no errors, warnings)
|
||||
|
||||
**Test fails?** Fix code, not test.
|
||||
|
||||
**Other tests fail?** Fix now.
|
||||
|
||||
### REFACTOR - Clean Up
|
||||
|
||||
After green only:
|
||||
- Remove duplication
|
||||
- Improve names
|
||||
- Extract helpers
|
||||
|
||||
Keep tests green. Don't add behavior.
|
||||
|
||||
### Repeat
|
||||
|
||||
Next failing test for next feature.
|
||||
|
||||
## Good Tests
|
||||
|
||||
| Quality | Good | Bad |
|
||||
|---------|------|-----|
|
||||
| **Minimal** | One thing. "and" in name? Split it. | `test('validates email and domain and whitespace')` |
|
||||
| **Clear** | Name describes behavior | `test('test1')` |
|
||||
| **Shows intent** | Demonstrates desired API | Obscures what code should do |
|
||||
|
||||
## Why Order Matters
|
||||
|
||||
**"I'll write tests after to verify it works"**
|
||||
|
||||
Tests written after code pass immediately. Passing immediately proves nothing:
|
||||
- Might test wrong thing
|
||||
- Might test implementation, not behavior
|
||||
- Might miss edge cases you forgot
|
||||
- You never saw it catch the bug
|
||||
|
||||
Test-first forces you to see the test fail, proving it actually tests something.
|
||||
|
||||
**"I already manually tested all the edge cases"**
|
||||
|
||||
Manual testing is ad-hoc. You think you tested everything but:
|
||||
- No record of what you tested
|
||||
- Can't re-run when code changes
|
||||
- Easy to forget cases under pressure
|
||||
- "It worked when I tried it" ≠ comprehensive
|
||||
|
||||
Automated tests are systematic. They run the same way every time.
|
||||
|
||||
**"Deleting X hours of work is wasteful"**
|
||||
|
||||
Sunk cost fallacy. The time is already gone. Your choice now:
|
||||
- Delete and rewrite with TDD (X more hours, high confidence)
|
||||
- Keep it and add tests after (30 min, low confidence, likely bugs)
|
||||
|
||||
The "waste" is keeping code you can't trust. Working code without real tests is technical debt.
|
||||
|
||||
**"TDD is dogmatic, being pragmatic means adapting"**
|
||||
|
||||
TDD IS pragmatic:
|
||||
- Finds bugs before commit (faster than debugging after)
|
||||
- Prevents regressions (tests catch breaks immediately)
|
||||
- Documents behavior (tests show how to use code)
|
||||
- Enables refactoring (change freely, tests catch breaks)
|
||||
|
||||
"Pragmatic" shortcuts = debugging in production = slower.
|
||||
|
||||
**"Tests after achieve the same goals - it's spirit not ritual"**
|
||||
|
||||
No. Tests-after answer "What does this do?" Tests-first answer "What should this do?"
|
||||
|
||||
Tests-after are biased by your implementation. You test what you built, not what's required. You verify remembered edge cases, not discovered ones.
|
||||
|
||||
Tests-first force edge case discovery before implementing. Tests-after verify you remembered everything (you didn't).
|
||||
|
||||
30 minutes of tests after ≠ TDD. You get coverage, lose proof tests work.
|
||||
|
||||
## Common Rationalizations
|
||||
|
||||
| Excuse | Reality |
|
||||
|--------|---------|
|
||||
| "Too simple to test" | Simple code breaks. Test takes 30 seconds. |
|
||||
| "I'll test after" | Tests passing immediately prove nothing. |
|
||||
| "Tests after achieve same goals" | Tests-after = "what does this do?" Tests-first = "what should this do?" |
|
||||
| "Already manually tested" | Ad-hoc ≠ systematic. No record, can't re-run. |
|
||||
| "Deleting X hours is wasteful" | Sunk cost fallacy. Keeping unverified code is technical debt. |
|
||||
| "Keep as reference, write tests first" | You'll adapt it. That's testing after. Delete means delete. |
|
||||
| "Need to explore first" | Fine. Throw away exploration, start with TDD. |
|
||||
| "Test hard = design unclear" | Listen to test. Hard to test = hard to use. |
|
||||
| "TDD will slow me down" | TDD faster than debugging. Pragmatic = test-first. |
|
||||
| "Manual test faster" | Manual doesn't prove edge cases. You'll re-test every change. |
|
||||
| "Existing code has no tests" | You're improving it. Add tests for existing code. |
|
||||
|
||||
## Red Flags - STOP and Start Over
|
||||
|
||||
- Code before test
|
||||
- Test after implementation
|
||||
- Test passes immediately
|
||||
- Can't explain why test failed
|
||||
- Tests added "later"
|
||||
- Rationalizing "just this once"
|
||||
- "I already manually tested it"
|
||||
- "Tests after achieve the same purpose"
|
||||
- "It's about spirit not ritual"
|
||||
- "Keep as reference" or "adapt existing code"
|
||||
- "Already spent X hours, deleting is wasteful"
|
||||
- "TDD is dogmatic, I'm being pragmatic"
|
||||
- "This is different because..."
|
||||
|
||||
**All of these mean: Delete code. Start over with TDD.**
|
||||
|
||||
## Example: Bug Fix
|
||||
|
||||
**Bug:** Empty email accepted
|
||||
|
||||
**RED**
|
||||
```typescript
|
||||
test('rejects empty email', async () => {
|
||||
const result = await submitForm({ email: '' });
|
||||
expect(result.error).toBe('Email required');
|
||||
});
|
||||
```
|
||||
|
||||
**Verify RED**
|
||||
```bash
|
||||
$ npm test
|
||||
FAIL: expected 'Email required', got undefined
|
||||
```
|
||||
|
||||
**GREEN**
|
||||
```typescript
|
||||
function submitForm(data: FormData) {
|
||||
if (!data.email?.trim()) {
|
||||
return { error: 'Email required' };
|
||||
}
|
||||
// ...
|
||||
}
|
||||
```
|
||||
|
||||
**Verify GREEN**
|
||||
```bash
|
||||
$ npm test
|
||||
PASS
|
||||
```
|
||||
|
||||
**REFACTOR**
|
||||
Extract validation for multiple fields if needed.
|
||||
|
||||
## Verification Checklist
|
||||
|
||||
Before marking work complete:
|
||||
|
||||
- [ ] Every new function/method has a test
|
||||
- [ ] Watched each test fail before implementing
|
||||
- [ ] Each test failed for expected reason (feature missing, not typo)
|
||||
- [ ] Wrote minimal code to pass each test
|
||||
- [ ] All tests pass
|
||||
- [ ] Output pristine (no errors, warnings)
|
||||
- [ ] Tests use real code (mocks only if unavoidable)
|
||||
- [ ] Edge cases and errors covered
|
||||
|
||||
Can't check all boxes? You skipped TDD. Start over.
|
||||
|
||||
## When Stuck
|
||||
|
||||
| Problem | Solution |
|
||||
|---------|----------|
|
||||
| Don't know how to test | Write wished-for API. Write assertion first. Ask your human partner. |
|
||||
| Test too complicated | Design too complicated. Simplify interface. |
|
||||
| Must mock everything | Code too coupled. Use dependency injection. |
|
||||
| Test setup huge | Extract helpers. Still complex? Simplify design. |
|
||||
|
||||
## Debugging Integration
|
||||
|
||||
Bug found? Write failing test reproducing it. Follow TDD cycle. Test proves fix and prevents regression.
|
||||
|
||||
Never fix bugs without a test.
|
||||
|
||||
## Testing Anti-Patterns
|
||||
|
||||
When adding mocks or test utilities, read @testing-anti-patterns.md to avoid common pitfalls:
|
||||
- Testing mock behavior instead of real behavior
|
||||
- Adding test-only methods to production classes
|
||||
- Mocking without understanding dependencies
|
||||
|
||||
## Final Rule
|
||||
|
||||
```
|
||||
Production code → test exists and failed first
|
||||
Otherwise → not TDD
|
||||
```
|
||||
|
||||
No exceptions without your human partner's permission.
|
||||
@@ -1,299 +0,0 @@
|
||||
# Testing Anti-Patterns
|
||||
|
||||
**Load this reference when:** writing or changing tests, adding mocks, or tempted to add test-only methods to production code.
|
||||
|
||||
## Overview
|
||||
|
||||
Tests must verify real behavior, not mock behavior. Mocks are a means to isolate, not the thing being tested.
|
||||
|
||||
**Core principle:** Test what the code does, not what the mocks do.
|
||||
|
||||
**Following strict TDD prevents these anti-patterns.**
|
||||
|
||||
## The Iron Laws
|
||||
|
||||
```
|
||||
1. NEVER test mock behavior
|
||||
2. NEVER add test-only methods to production classes
|
||||
3. NEVER mock without understanding dependencies
|
||||
```
|
||||
|
||||
## Anti-Pattern 1: Testing Mock Behavior
|
||||
|
||||
**The violation:**
|
||||
```typescript
|
||||
// ❌ BAD: Testing that the mock exists
|
||||
test('renders sidebar', () => {
|
||||
render(<Page />);
|
||||
expect(screen.getByTestId('sidebar-mock')).toBeInTheDocument();
|
||||
});
|
||||
```
|
||||
|
||||
**Why this is wrong:**
|
||||
- You're verifying the mock works, not that the component works
|
||||
- Test passes when mock is present, fails when it's not
|
||||
- Tells you nothing about real behavior
|
||||
|
||||
**your human partner's correction:** "Are we testing the behavior of a mock?"
|
||||
|
||||
**The fix:**
|
||||
```typescript
|
||||
// ✅ GOOD: Test real component or don't mock it
|
||||
test('renders sidebar', () => {
|
||||
render(<Page />); // Don't mock sidebar
|
||||
expect(screen.getByRole('navigation')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
// OR if sidebar must be mocked for isolation:
|
||||
// Don't assert on the mock - test Page's behavior with sidebar present
|
||||
```
|
||||
|
||||
### Gate Function
|
||||
|
||||
```
|
||||
BEFORE asserting on any mock element:
|
||||
Ask: "Am I testing real component behavior or just mock existence?"
|
||||
|
||||
IF testing mock existence:
|
||||
STOP - Delete the assertion or unmock the component
|
||||
|
||||
Test real behavior instead
|
||||
```
|
||||
|
||||
## Anti-Pattern 2: Test-Only Methods in Production
|
||||
|
||||
**The violation:**
|
||||
```typescript
|
||||
// ❌ BAD: destroy() only used in tests
|
||||
class Session {
|
||||
async destroy() { // Looks like production API!
|
||||
await this._workspaceManager?.destroyWorkspace(this.id);
|
||||
// ... cleanup
|
||||
}
|
||||
}
|
||||
|
||||
// In tests
|
||||
afterEach(() => session.destroy());
|
||||
```
|
||||
|
||||
**Why this is wrong:**
|
||||
- Production class polluted with test-only code
|
||||
- Dangerous if accidentally called in production
|
||||
- Violates YAGNI and separation of concerns
|
||||
- Confuses object lifecycle with entity lifecycle
|
||||
|
||||
**The fix:**
|
||||
```typescript
|
||||
// ✅ GOOD: Test utilities handle test cleanup
|
||||
// Session has no destroy() - it's stateless in production
|
||||
|
||||
// In test-utils/
|
||||
export async function cleanupSession(session: Session) {
|
||||
const workspace = session.getWorkspaceInfo();
|
||||
if (workspace) {
|
||||
await workspaceManager.destroyWorkspace(workspace.id);
|
||||
}
|
||||
}
|
||||
|
||||
// In tests
|
||||
afterEach(() => cleanupSession(session));
|
||||
```
|
||||
|
||||
### Gate Function
|
||||
|
||||
```
|
||||
BEFORE adding any method to production class:
|
||||
Ask: "Is this only used by tests?"
|
||||
|
||||
IF yes:
|
||||
STOP - Don't add it
|
||||
Put it in test utilities instead
|
||||
|
||||
Ask: "Does this class own this resource's lifecycle?"
|
||||
|
||||
IF no:
|
||||
STOP - Wrong class for this method
|
||||
```
|
||||
|
||||
## Anti-Pattern 3: Mocking Without Understanding
|
||||
|
||||
**The violation:**
|
||||
```typescript
|
||||
// ❌ BAD: Mock breaks test logic
|
||||
test('detects duplicate server', () => {
|
||||
// Mock prevents config write that test depends on!
|
||||
vi.mock('ToolCatalog', () => ({
|
||||
discoverAndCacheTools: vi.fn().mockResolvedValue(undefined)
|
||||
}));
|
||||
|
||||
await addServer(config);
|
||||
await addServer(config); // Should throw - but won't!
|
||||
});
|
||||
```
|
||||
|
||||
**Why this is wrong:**
|
||||
- Mocked method had side effect test depended on (writing config)
|
||||
- Over-mocking to "be safe" breaks actual behavior
|
||||
- Test passes for wrong reason or fails mysteriously
|
||||
|
||||
**The fix:**
|
||||
```typescript
|
||||
// ✅ GOOD: Mock at correct level
|
||||
test('detects duplicate server', () => {
|
||||
// Mock the slow part, preserve behavior test needs
|
||||
vi.mock('MCPServerManager'); // Just mock slow server startup
|
||||
|
||||
await addServer(config); // Config written
|
||||
await addServer(config); // Duplicate detected ✓
|
||||
});
|
||||
```
|
||||
|
||||
### Gate Function
|
||||
|
||||
```
|
||||
BEFORE mocking any method:
|
||||
STOP - Don't mock yet
|
||||
|
||||
1. Ask: "What side effects does the real method have?"
|
||||
2. Ask: "Does this test depend on any of those side effects?"
|
||||
3. Ask: "Do I fully understand what this test needs?"
|
||||
|
||||
IF depends on side effects:
|
||||
Mock at lower level (the actual slow/external operation)
|
||||
OR use test doubles that preserve necessary behavior
|
||||
NOT the high-level method the test depends on
|
||||
|
||||
IF unsure what test depends on:
|
||||
Run test with real implementation FIRST
|
||||
Observe what actually needs to happen
|
||||
THEN add minimal mocking at the right level
|
||||
|
||||
Red flags:
|
||||
- "I'll mock this to be safe"
|
||||
- "This might be slow, better mock it"
|
||||
- Mocking without understanding the dependency chain
|
||||
```
|
||||
|
||||
## Anti-Pattern 4: Incomplete Mocks
|
||||
|
||||
**The violation:**
|
||||
```typescript
|
||||
// ❌ BAD: Partial mock - only fields you think you need
|
||||
const mockResponse = {
|
||||
status: 'success',
|
||||
data: { userId: '123', name: 'Alice' }
|
||||
// Missing: metadata that downstream code uses
|
||||
};
|
||||
|
||||
// Later: breaks when code accesses response.metadata.requestId
|
||||
```
|
||||
|
||||
**Why this is wrong:**
|
||||
- **Partial mocks hide structural assumptions** - You only mocked fields you know about
|
||||
- **Downstream code may depend on fields you didn't include** - Silent failures
|
||||
- **Tests pass but integration fails** - Mock incomplete, real API complete
|
||||
- **False confidence** - Test proves nothing about real behavior
|
||||
|
||||
**The Iron Rule:** Mock the COMPLETE data structure as it exists in reality, not just fields your immediate test uses.
|
||||
|
||||
**The fix:**
|
||||
```typescript
|
||||
// ✅ GOOD: Mirror real API completeness
|
||||
const mockResponse = {
|
||||
status: 'success',
|
||||
data: { userId: '123', name: 'Alice' },
|
||||
metadata: { requestId: 'req-789', timestamp: 1234567890 }
|
||||
// All fields real API returns
|
||||
};
|
||||
```
|
||||
|
||||
### Gate Function
|
||||
|
||||
```
|
||||
BEFORE creating mock responses:
|
||||
Check: "What fields does the real API response contain?"
|
||||
|
||||
Actions:
|
||||
1. Examine actual API response from docs/examples
|
||||
2. Include ALL fields system might consume downstream
|
||||
3. Verify mock matches real response schema completely
|
||||
|
||||
Critical:
|
||||
If you're creating a mock, you must understand the ENTIRE structure
|
||||
Partial mocks fail silently when code depends on omitted fields
|
||||
|
||||
If uncertain: Include all documented fields
|
||||
```
|
||||
|
||||
## Anti-Pattern 5: Integration Tests as Afterthought
|
||||
|
||||
**The violation:**
|
||||
```
|
||||
✅ Implementation complete
|
||||
❌ No tests written
|
||||
"Ready for testing"
|
||||
```
|
||||
|
||||
**Why this is wrong:**
|
||||
- Testing is part of implementation, not optional follow-up
|
||||
- TDD would have caught this
|
||||
- Can't claim complete without tests
|
||||
|
||||
**The fix:**
|
||||
```
|
||||
TDD cycle:
|
||||
1. Write failing test
|
||||
2. Implement to pass
|
||||
3. Refactor
|
||||
4. THEN claim complete
|
||||
```
|
||||
|
||||
## When Mocks Become Too Complex
|
||||
|
||||
**Warning signs:**
|
||||
- Mock setup longer than test logic
|
||||
- Mocking everything to make test pass
|
||||
- Mocks missing methods real components have
|
||||
- Test breaks when mock changes
|
||||
|
||||
**your human partner's question:** "Do we need to be using a mock here?"
|
||||
|
||||
**Consider:** Integration tests with real components often simpler than complex mocks
|
||||
|
||||
## TDD Prevents These Anti-Patterns
|
||||
|
||||
**Why TDD helps:**
|
||||
1. **Write test first** → Forces you to think about what you're actually testing
|
||||
2. **Watch it fail** → Confirms test tests real behavior, not mocks
|
||||
3. **Minimal implementation** → No test-only methods creep in
|
||||
4. **Real dependencies** → You see what the test actually needs before mocking
|
||||
|
||||
**If you're testing mock behavior, you violated TDD** - you added mocks without watching test fail against real code first.
|
||||
|
||||
## Quick Reference
|
||||
|
||||
| Anti-Pattern | Fix |
|
||||
|--------------|-----|
|
||||
| Assert on mock elements | Test real component or unmock it |
|
||||
| Test-only methods in production | Move to test utilities |
|
||||
| Mock without understanding | Understand dependencies first, mock minimally |
|
||||
| Incomplete mocks | Mirror real API completely |
|
||||
| Tests as afterthought | TDD - tests first |
|
||||
| Over-complex mocks | Consider integration tests |
|
||||
|
||||
## Red Flags
|
||||
|
||||
- Assertion checks for `*-mock` test IDs
|
||||
- Methods only called in test files
|
||||
- Mock setup is >50% of test
|
||||
- Test fails when you remove mock
|
||||
- Can't explain why mock is needed
|
||||
- Mocking "just to be safe"
|
||||
|
||||
## The Bottom Line
|
||||
|
||||
**Mocks are tools to isolate, not things to test.**
|
||||
|
||||
If TDD reveals you're testing mock behavior, you've gone wrong.
|
||||
|
||||
Fix: Test real behavior or question why you're mocking at all.
|
||||
@@ -0,0 +1,31 @@
|
||||
---
|
||||
name: type-system-discipline
|
||||
description: "Apply when designing types, reviewing a function signature, or writing code in any statically-typed language. Make illegal states unrepresentable, brand semantic primitives, parse external data at boundaries, refuse to lie to the compiler, exhaust variants, derive from authoritative schemas."
|
||||
disable-model-invocation: true
|
||||
---
|
||||
|
||||
# Type System Discipline
|
||||
|
||||
The type checker is a proof assistant. Use it to eliminate impossible states, mismatched primitives, and unhandled variants at compile time. A case the types let you ignore becomes a runtime failure the compiler could have stopped. Prefer defining errors and special cases out of existence over proliferating handlers; unrepresentable states, total functions, and interface redesign (the patterns below) are the tools.
|
||||
|
||||
Applies to any typed language. Skills like `typescript-best-practices` ground it in specific syntax.
|
||||
|
||||
**The patterns:**
|
||||
|
||||
- **Make illegal states unrepresentable.** Model variants as sum types: discriminated unions in TypeScript, enums with payloads in Rust/Swift/Kotlin, sealed classes in Scala, ADTs in Haskell/OCaml. Don't model state as a bag of optional fields where contradictory combinations compile. A subtle anti-pattern worth naming: `{ completed: boolean; completedAt?: Date }` admits `completed: true; completedAt: undefined`, which is meaningless. Derive the boolean from a single source like `completedAt !== null`, or model the variants explicitly as `{ kind: 'open' } | { kind: 'done'; at: Date }`. If a bug forces the question "wait, can this combination actually happen?", the type is too loose.
|
||||
- **Types are constructions, not restrictions.** Build the type up from the values you want instead of carving them out of a looser type with checks. The invariant that seems to need a refinement type is usually a construction away. A non-empty list is a head plus a rest, not a list with a length check. A valid time range is a start plus a duration, not two timestamps you must keep ordered. No representation is privileged. A list of pairs is an even-length list if you interpret it that way, so choose the shape that cannot build the illegal value and expose the interface callers need on top.
|
||||
- **Brand semantic primitives.** `UserId` and `OrderId` are strings underneath but should not be interchangeable. Newtypes in Rust, opaque types in Swift, value classes in Kotlin, phantom types in Haskell, branded intersections in TypeScript. Validate once at creation, trust the type downstream.
|
||||
- **External data is untyped until parsed.** RPC payloads, JSON, IPC messages, CLI args, config files, environment variables, database rows. Have a parse function at every boundary that turns unstructured input into the typed model. See the **boundary-discipline** principle skill for where to put validation.
|
||||
- **Don't lie to the type system.** Casts, unsafe coercions, and assertion functions that bypass the compiler are runtime crashes waiting to happen. If the compiler can't prove a fact, prove it (validate, narrow, refine the model) or accept that the cast is a hazard. The cast you bury today is the postmortem you write next week.
|
||||
- **Exhaustive matching is the compiler's job.** When you match on a sum type, the compiler must fail compilation if a new variant is added without handling. Use the idiom your language provides: `never`-typed binding in TypeScript, unannotated `match` in Rust, `-Wincomplete-patterns` in Haskell, sealed-class match exhaustiveness in Kotlin.
|
||||
- **Derive types from authoritative schemas.** When a protocol buffer, OpenAPI spec, GraphQL schema, database migration, or design-system token file defines a shape, derive from it instead of hand-rolling a parallel type. Manual duplication drifts. See the **encode-lessons-in-structure** principle skill.
|
||||
- **Strengthen a type only where partiality appears.** A runtime assertion, null check, or "this should never happen" throw marks the place a type is too weak. Push that check up into the type. Then stop. The type system's job is to track the cases each use site must handle, not to describe the data as precisely as possible. Prefer total functions. `sum` of an empty list is 0, so it takes the plain list. `head` of an empty list has no answer, so it demands the non-empty one. Extra precision costs reuse and ceremony and buys no safety.
|
||||
|
||||
**The tests:**
|
||||
|
||||
- "Can I write a comment explaining when this combination of fields is valid?" If yes, the type is too loose. Split it into a sum type.
|
||||
- "Do two of my function arguments share a primitive type but mean different things?" Brand them.
|
||||
- "Where did this `any`, this `as`, this `assertNotNull` come from?" Trace it to the boundary and validate there instead.
|
||||
- "If a new variant is added next month, will the compiler tell the next agent where to add a case?" If no, the match isn't exhaustive.
|
||||
- "Is this type duplicating a shape another file owns?" Derive instead.
|
||||
- "Am I strengthening this type to keep an operation total, or just to be more precise?" If nothing would otherwise panic, keep the plain type.
|
||||
@@ -0,0 +1,28 @@
|
||||
---
|
||||
name: typescript-best-practices
|
||||
description: TypeScript best practices. Use when reading or editing any .ts or .tsx file.
|
||||
---
|
||||
|
||||
# TypeScript best practices
|
||||
|
||||
Apply the **type-system-discipline** principle skill first; this skill grounds it in TypeScript syntax.
|
||||
|
||||
| Rule | Summary |
|
||||
|------|---------|
|
||||
| Discriminated unions | Model variants with a `kind` literal discriminant so impossible states can't be represented. No optional-field bags. |
|
||||
| Branded types | Brand primitives with `& { readonly __brand: "X" }` so they can't be mixed up. Validate once at creation. |
|
||||
| Constructive modeling | Build the shape so the illegal value can't be constructed. `[T, ...T[]]` for non-empty, `[T, T][]` for even length, `start` plus `duration` for a range. Not a runtime guard, not a wish for refinement types. |
|
||||
| Simplest total type | Keep `T[]` while every operation on it stays total. Strengthen to `NonEmpty<T>` only where the loose type forces `!`, a cast, or a "should never happen" throw. |
|
||||
| `unknown` over `any` | External data is `unknown`. `any` disables type checking everywhere it touches. |
|
||||
| No `as` casts | Every `as` is a runtime crash waiting. Cast only after validation. |
|
||||
| Narrowing hierarchy | Discriminant switch > `in` operator > `typeof`/`instanceof` > user-defined type guard > `as`. |
|
||||
| Type guards | Must verify the claim. A lying guard is worse than `as` because the bug hides behind a name that says it's safe. Name them `isX` or `hasX`. |
|
||||
| Exhaustiveness | Inline `const _exhaustive: never = x;` in default arms so the compiler errors when a new variant is added. |
|
||||
| `satisfies` over `as` | Validates the value without widening literal types. |
|
||||
| Boundary validation | Validate where data crosses in; trust types inside. See the **boundary-discipline** principle skill. |
|
||||
| Schema-derived types | Reach for `Pick`/`Omit`/`Parameters`/`ReturnType`/`Awaited`/`typeof` before declaring a new interface. |
|
||||
| Object args | Pass objects, not positional, so argument order is self-documenting. Skip on hot paths (per-frame render, tokenizers, parsers). |
|
||||
| Real tests | Don't mock what you can run. Prefer the framework's real test primitives with leak/disposable checks, and verify UI in a running build. Mock only what you can't run locally. |
|
||||
| Structured telemetry | Prefer structured logger diagnostics with enough context to debug from an id. No `console.log` in shipped code. |
|
||||
|
||||
Examples: `references/patterns.md`.
|
||||
@@ -0,0 +1,292 @@
|
||||
# TypeScript patterns
|
||||
|
||||
Code examples for each rule in `SKILL.md`. The underlying principles are language-agnostic; see the **type-system-discipline** and **boundary-discipline** principle skills.
|
||||
|
||||
## Branded types
|
||||
|
||||
Brand primitives so they can't be mixed up. Validate once at creation; downstream code trusts the type.
|
||||
|
||||
```ts
|
||||
type AgentId = string & { readonly __brand: "AgentId" };
|
||||
|
||||
function parseAgentId(input: string): AgentId {
|
||||
if (!isUUID(input)) throw new Error(`Invalid agent id: ${input}`);
|
||||
return input as AgentId;
|
||||
}
|
||||
|
||||
function focusAgent(id: AgentId): void {
|
||||
/* input is trusted */
|
||||
}
|
||||
```
|
||||
|
||||
Match the `readonly __brand: 'X'` shape; don't invent a new convention.
|
||||
|
||||
## Discriminated unions
|
||||
|
||||
If a bug forces the question "wait, can this combination actually happen?", the type is too loose. Model variants with a literal discriminant: every variant shares the field name and each variant's value is unique, so impossible combos can't be represented.
|
||||
|
||||
```ts
|
||||
// Don't. Boolean + optionals lets contradictory states exist.
|
||||
type DiffState = { loading: boolean; diff?: GitDiff; error?: string };
|
||||
|
||||
// Do. Only valid states exist.
|
||||
type DiffState =
|
||||
| { kind: "loading" }
|
||||
| { kind: "ready"; diff: GitDiff }
|
||||
| { kind: "error"; error: string };
|
||||
```
|
||||
|
||||
Pick one discriminant name (`kind`, `type`, `tag`) and stick to it.
|
||||
|
||||
## Constructive modeling
|
||||
|
||||
Build the type from parts that are all legal instead of restricting a loose type with runtime checks. Adding is easier than subtracting.
|
||||
|
||||
Non-empty, via a variadic tuple:
|
||||
|
||||
```ts
|
||||
type NonEmpty<T> = [T, ...T[]];
|
||||
|
||||
// Don't: T[] plus a length check every caller must repeat
|
||||
function pickWinner(entries: string[]): string {
|
||||
if (entries.length === 0) throw new Error("no entries");
|
||||
return entries[Math.floor(Math.random() * entries.length)];
|
||||
}
|
||||
|
||||
// Do: an empty value of the type can't exist
|
||||
function pickWinner(entries: NonEmpty<string>): string {
|
||||
return entries[Math.floor(Math.random() * entries.length)];
|
||||
}
|
||||
```
|
||||
|
||||
Where a plain `T[]` arrives, narrow once with a guard. The fact then travels in the type:
|
||||
|
||||
```ts
|
||||
const isNonEmpty = <T>(arr: T[]): arr is NonEmpty<T> => arr.length > 0;
|
||||
```
|
||||
|
||||
Even length, as pairs. TypeScript has no refinement types (no `arr.length % 2 === 0` at the type level); you don't need one:
|
||||
|
||||
```ts
|
||||
type Pairs<T> = [T, T][];
|
||||
```
|
||||
|
||||
A time range, as start plus duration:
|
||||
|
||||
```ts
|
||||
// Don't: a comment holds the invariant
|
||||
type TimeRange = { start: Date; end: Date }; // start <= end
|
||||
|
||||
// Do: a negative range can't be written; derive end when needed
|
||||
type TimeRange = { start: Date; durationMs: number };
|
||||
```
|
||||
|
||||
Keep `durationMs` a plain number. Brand it (per Branded types) only if a raw number could be passed where a duration is expected, not by reflex. A `Pairs<T>` is an even-length list under the interpretation you give it, the same way `{ start, durationMs }` is a range. Pick the representation that makes the bad state unconstructable, then expose the reading you need on top (`pairs.flat()`, a `rangeEnd()` helper).
|
||||
|
||||
## Simplest total type
|
||||
|
||||
Don't strengthen everything. Keep `T[]` when every operation on it is total:
|
||||
|
||||
```ts
|
||||
const sum = (xs: number[]) => xs.reduce((a, b) => a + b, 0); // [] is 0, fine
|
||||
```
|
||||
|
||||
Strengthen when the loose type forces a lie at a use site. The tells are `!`, `arr[0] as T`, and a "should never happen" throw:
|
||||
|
||||
```ts
|
||||
// Don't: partiality smuggled past the compiler
|
||||
function newestSession(sessions: Session[]): Session {
|
||||
return sessions.at(0)!;
|
||||
}
|
||||
|
||||
// Do: strengthen the input; the assertion disappears
|
||||
function newestSession(sessions: NonEmpty<Session>): Session {
|
||||
return sessions[0];
|
||||
}
|
||||
```
|
||||
|
||||
Weakening the result to `Session | undefined` is the other total signature. Either way the empty case lands at the call site, the one place that knows what empty means.
|
||||
|
||||
## `unknown` over `any`
|
||||
|
||||
`any` disables type checking for everything it touches. External data is always `unknown`. Narrow before use.
|
||||
|
||||
```ts
|
||||
// Don't
|
||||
function handle(input: any) {
|
||||
return input.foo.bar;
|
||||
}
|
||||
|
||||
// Do
|
||||
function handle(input: unknown) {
|
||||
if (typeof input === "object" && input !== null && "foo" in input) {
|
||||
// narrowed; compiler verifies access
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
External sources include RPC payloads, `JSON.parse`, `postMessage`, IPC, file contents, environment variables, database results.
|
||||
|
||||
## No `as` casts
|
||||
|
||||
Every `as` is a potential runtime crash. Cast only after the type system has verified the claim.
|
||||
|
||||
```ts
|
||||
// Don't
|
||||
const user = data as User;
|
||||
|
||||
// Do. Earn the cast at the boundary.
|
||||
function parseUser(data: unknown): User {
|
||||
if (typeof data !== "object" || data === null) {
|
||||
throw new Error("expected object");
|
||||
}
|
||||
if (!("id" in data) || typeof (data as Record<string, unknown>).id !== "string") {
|
||||
throw new Error("expected id");
|
||||
}
|
||||
// ... validate all fields
|
||||
return data as User; // OK, earned cast after full validation
|
||||
}
|
||||
```
|
||||
|
||||
When refactoring an `as` out of existing code, identify why TypeScript can't infer:
|
||||
|
||||
- Missing discriminant: add one, switch to a discriminated union.
|
||||
- Overly wide source type (e.g. `Record<string, unknown>`): narrow it.
|
||||
- Untyped boundary: add a parse function or schema.
|
||||
- Genuinely inexpressible: use a branded type or `satisfies`.
|
||||
|
||||
## Narrowing hierarchy
|
||||
|
||||
From best to last-resort:
|
||||
|
||||
1. **Discriminated union switch / if.** Compiler narrows automatically.
|
||||
2. **`in` operator.** `"key" in obj` narrows to variants containing that key.
|
||||
3. **`typeof` / `instanceof`.** For primitives and class instances.
|
||||
4. **User-defined type guard.** When the above aren't enough.
|
||||
5. **`as` cast.** Only after validation.
|
||||
|
||||
```ts
|
||||
function area(s: Shape): number {
|
||||
if ("radius" in s) return Math.PI * s.radius ** 2; // narrowed to circle
|
||||
return s.width * s.height; // narrowed to rect
|
||||
}
|
||||
```
|
||||
|
||||
## Type guards
|
||||
|
||||
A guard must actually verify the claim. A lying guard is worse than `as` because the bug hides behind a name that says it's safe.
|
||||
|
||||
```ts
|
||||
function isCircle(s: Shape): s is Shape & { kind: "circle" } {
|
||||
return s.kind === "circle";
|
||||
}
|
||||
```
|
||||
|
||||
Prefer discriminant narrowing when possible. The guard adds a layer the reader has to follow.
|
||||
|
||||
## Exhaustiveness
|
||||
|
||||
In default arms, assign the discriminant to a `never`-typed local. The compiler errors if a new variant is added without handling.
|
||||
|
||||
```ts
|
||||
// Value-returning switch
|
||||
function area(s: Shape): number {
|
||||
switch (s.kind) {
|
||||
case "circle":
|
||||
return Math.PI * s.radius ** 2;
|
||||
case "rect":
|
||||
return s.width * s.height;
|
||||
default: {
|
||||
const _exhaustive: never = s;
|
||||
return _exhaustive;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Void switch
|
||||
function handle(s: Shape): void {
|
||||
switch (s.kind) {
|
||||
case "circle":
|
||||
drawCircle(s);
|
||||
break;
|
||||
case "rect":
|
||||
drawRect(s);
|
||||
break;
|
||||
default: {
|
||||
const _exhaustive: never = s;
|
||||
void _exhaustive;
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Return-style in value-returning switches; void-style in statement switches.
|
||||
|
||||
## `satisfies` over `as`
|
||||
|
||||
`satisfies` validates without widening literal types.
|
||||
|
||||
```ts
|
||||
// Don't. Widens, loses literal types.
|
||||
const config = { theme: "dark", cols: 3 } as Config;
|
||||
|
||||
// Do. Validates AND preserves literal types.
|
||||
const config = { theme: "dark", cols: 3 } satisfies Config;
|
||||
// config.theme is "dark" (literal), not string
|
||||
```
|
||||
|
||||
## Boundary validation
|
||||
|
||||
Validate once where data crosses in; trust types inside. See the **boundary-discipline** principle skill.
|
||||
|
||||
- **Wire formats** (proto, JSON-RPC): parse with `ignoreUnknownFields` so forward-compatible changes don't break old clients.
|
||||
- **Persisted JSON:** versioned blob with a try/catch around the parse.
|
||||
- **Don't re-validate** deep in call chains.
|
||||
|
||||
## Schema-derived types
|
||||
|
||||
When a `.proto`, OpenAPI spec, GraphQL schema, or database migration already defines a shape, derive from the generated types instead of duplicating them.
|
||||
|
||||
```ts
|
||||
// Don't. Duplicate shape, drifts when the schema changes.
|
||||
type CheckSummary = {
|
||||
totalCount: number;
|
||||
checks: { name: string; status: string }[];
|
||||
};
|
||||
function renderChecks(s: CheckSummary) {
|
||||
/* ... */
|
||||
}
|
||||
|
||||
// Do. Derive from the generated schema type.
|
||||
import type { ChecksMessage } from "<generated module>";
|
||||
function renderChecks(s: Pick<ChecksMessage, "totalCount" | "checks">) {
|
||||
/* ... */
|
||||
}
|
||||
```
|
||||
|
||||
Reach for `Pick`, `Omit`, `Parameters`, `ReturnType`, `Awaited`, `typeof` before writing a new interface.
|
||||
|
||||
## Object args
|
||||
|
||||
```ts
|
||||
// Don't. Swap two args, still compiles.
|
||||
openFile(uri, {
|
||||
startLineNumber: 10,
|
||||
startColumn: 1,
|
||||
endLineNumber: 10,
|
||||
endColumn: 1,
|
||||
});
|
||||
|
||||
// Do. Order-independent, self-documenting.
|
||||
openFile({
|
||||
uri,
|
||||
selection: {
|
||||
startLineNumber: 10,
|
||||
startColumn: 1,
|
||||
endLineNumber: 10,
|
||||
endColumn: 1,
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
Skip on hot paths: per-frame render, tokenizers, parsers, anything in a tight loop where the allocation cost matters.
|
||||
@@ -0,0 +1,80 @@
|
||||
---
|
||||
name: unslop
|
||||
description: Cut AI tells from any writing. Must always apply.
|
||||
---
|
||||
|
||||
# Unslop
|
||||
|
||||
Edit text to remove AI patterns and add human voice.
|
||||
|
||||
## Process
|
||||
|
||||
1. Scan for the patterns below.
|
||||
2. Rewrite. Preserve meaning, match intended tone.
|
||||
3. Add soul (see next section).
|
||||
4. Self-audit: "What makes this obviously AI generated?" Fix remaining tells.
|
||||
|
||||
## Adding soul
|
||||
|
||||
Removing patterns is half the job. Sterile, voiceless writing is just as obvious.
|
||||
|
||||
- **Have opinions.** React to facts instead of neutrally listing pros and cons.
|
||||
- **Vary rhythm.** Short sentences. Then longer ones that take their time. Mix it up.
|
||||
- **Acknowledge complexity.** "Impressive but also kind of unsettling" beats "impressive."
|
||||
- **Use "I" when it fits.** First person isn't unprofessional.
|
||||
- **Let some mess in.** Perfect structure looks machine-made.
|
||||
- **Be specific.** Not "this is concerning" but "there's something unsettling about agents churning away at 3am."
|
||||
|
||||
## Patterns to detect and fix
|
||||
|
||||
### Content
|
||||
|
||||
1. **Puffery.** "pivotal moment", "testament to", "evolving landscape", "setting the stage for", "indelible mark", "deeply rooted". Cut puffery, state what happened.
|
||||
2. **Name-dropping.** Listing media outlets without context. Pick one, say what was said.
|
||||
3. **Superficial -ing phrases.** "highlighting...", "ensuring...", "reflecting...", "showcasing...", "fostering...". Delete or expand with real sources.
|
||||
4. **Promotional language.** "nestled", "vibrant", "breathtaking", "groundbreaking", "renowned", "stunning", "must-visit". Use neutral descriptions.
|
||||
5. **Vague attributions.** "Experts believe", "Industry reports suggest", "Some critics argue". Name the source or delete.
|
||||
6. **Formulaic challenges.** "Despite challenges... continues to thrive." Replace with specific facts.
|
||||
|
||||
### Language
|
||||
|
||||
7. **AI vocabulary.** Additionally, crucial, delve, enduring, enhance, fostering, garner, interplay, intricate, landscape (abstract), pivotal, showcase, tapestry (abstract), testament, underscore, vibrant. Replace with plain words.
|
||||
8. **Fancy ways to say "is".** "serves as", "stands as", "boasts", "features". Just say "is" or "has".
|
||||
9. **"Not just X, but Y."** State the point directly instead.
|
||||
10. **Rule of three.** Forcing ideas into groups of three. Use the natural number.
|
||||
11. **Synonym cycling.** Protagonist, main character, central figure, hero all in one paragraph. Pick one, repeat it.
|
||||
12. **False ranges.** "from X to Y" where X and Y aren't on a meaningful scale. List topics directly.
|
||||
|
||||
### Style
|
||||
|
||||
13. **Em dash overuse.** Avoid em dashes entirely. Use periods or commas only (no parentheses, no en dashes, no hyphen-as-dash substitutes). Em dashes are an AI tell, and reaching for parentheses instead just trades one tell for another. If a thought needs separation, end the sentence or use a comma.
|
||||
14. **Colon overuse.** Colons are fine before a list or example. Not as mid-sentence connectors. "If you're coming from traditional automation: instead of registering event handlers, you describe conditions" adds nothing with the colon. Rewrite to let the point stand on its own without comparison framing. "Describing when the scheduler should fire works best as plain English." Same meaning, no crutch punctuation.
|
||||
15. **Boldface overuse.** Don't bold every proper noun or acronym.
|
||||
16. **Inline-header lists.** The tell is a bold label and colon that restates the line: "**Performance:** Performance improved...". Convert those to prose. A bold lead-in that ends in a period, names the item, and is followed by genuinely new detail ("**Schema in TypeScript.** Tables live in one file.") is fine, not a tell.
|
||||
17. **Title case headings.** Use sentence case.
|
||||
18. **Decorative emojis.** Remove from headings and bullets.
|
||||
19. **Curly quotes.** Replace with straight quotes.
|
||||
|
||||
### Communication artifacts
|
||||
|
||||
20. **Chatbot phrases.** "I hope this helps!", "Let me know if...", "Of course!", "Certainly!", "Found the smoking gun!" Remove.
|
||||
21. **Cutoff disclaimers.** "While specific details are limited..." Find sources or remove.
|
||||
22. **Sycophantic tone.** "Great question! You're absolutely right!" Respond directly.
|
||||
|
||||
### Filler
|
||||
|
||||
23. **Filler phrases.** "In order to" becomes "To". "Due to the fact that" becomes "Because". "It is important to note that" gets deleted.
|
||||
24. **Excessive hedging.** "could potentially possibly be argued that it might" becomes "may".
|
||||
25. **Generic conclusions.** "The future looks bright." State specific plans or facts.
|
||||
|
||||
### Jargon
|
||||
|
||||
26. **Abstract metaphor nouns.** Substrate, wedge, vector, locus, vantage, nexus, primitive (as noun), harness (as metaphor), surface (as in "API surface"), bedrock, scaffolding (as metaphor), modality, paradigm, gold-plating, ratchet (as metaphor), evacuate (for moving code), endgame, north star, flywheel. These read as technical but usually have a plainer concrete word. "Substrate" becomes "base". "Wedge in" becomes "add". "Vector" becomes "way" or "method". "Gold-plating" becomes "more than the job needs". "Ratchet" becomes the mechanism's real name or "a limit that only tightens". "Evacuate" becomes "move out". "Endgame" becomes "the last phase". Pick the concrete word.
|
||||
|
||||
### Plain speech
|
||||
|
||||
27. **Say what it does, not how it feels.** "the database stays close at hand", "SQL you can read", "types that follow your schema" name a feeling. The fix names the mechanism or a number: "`.toSQL()` returns the exact string sent to the database", "a column rename fails the build". Ask what the sentence tells the reader to do or know, then write that. If you can't restate it as a concrete instruction, fact, or number, cut it. One more check: if the sentence could appear unchanged in another project's docs, it says nothing about this one. Cut it.
|
||||
28. **Shorten or split dense sentences.** If the reader has to backtrack to parse a sentence, break it in two or drop clauses. One idea per sentence.
|
||||
29. **Active voice.** Prefer it. Catch "is/are/was/were + past participle" and name the actor: "queries are validated" becomes "the compiler validates queries", "the file is parsed by the loader" becomes "the loader parses the file". Passive is fine only when the actor is unknown or genuinely doesn't matter.
|
||||
30. **Cut adverbs, or use a stronger verb.** "runs quickly" becomes "is fast" or the number. "significantly improves" becomes the measured delta. An adverb propping up a weak verb means the verb is wrong.
|
||||
31. **Prefer the plain word.** "utilize" becomes "use", "leverage" becomes "use", "facilitate" becomes "help", "numerous" becomes "many", "in the event that" becomes "if". The fancier synonym is rarely clearer.
|
||||
@@ -1,7 +1,8 @@
|
||||
{
|
||||
"attribution": {
|
||||
"commit": "",
|
||||
"pr": ""
|
||||
"pr": "",
|
||||
"sessionUrl": false
|
||||
},
|
||||
"permissions": {
|
||||
"deny": [
|
||||
@@ -46,5 +47,6 @@
|
||||
},
|
||||
"effortLevel": "high",
|
||||
"tui": "fullscreen",
|
||||
"skipDangerousModePermissionPrompt": true
|
||||
"skipDangerousModePermissionPrompt": true,
|
||||
"agentPushNotifEnabled": true
|
||||
}
|
||||
|
||||
@@ -1,7 +1,11 @@
|
||||
{
|
||||
"env": {
|
||||
"PLAYWRIGHT_MCP_EXECUTABLE_PATH": "/opt/helium-browser-bin/helium"
|
||||
},
|
||||
"attribution": {
|
||||
"commit": "",
|
||||
"pr": ""
|
||||
"pr": "",
|
||||
"sessionUrl": false
|
||||
},
|
||||
"permissions": {
|
||||
"allow": [
|
||||
@@ -40,6 +44,7 @@
|
||||
"Bash(yadm push --force*)"
|
||||
]
|
||||
},
|
||||
"model": "opus[1m]",
|
||||
"hooks": {
|
||||
"Notification": [
|
||||
{
|
||||
@@ -47,7 +52,19 @@
|
||||
"hooks": [
|
||||
{
|
||||
"type": "command",
|
||||
"command": "notify-send 'Claude Code' 'Claude Code needs your attention'"
|
||||
"command": "notify-send -a 'Claude Code' -i claude-desktop 'Claude Code' 'Claude Code needs your attention'"
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"Stop": [
|
||||
{
|
||||
"matcher": "",
|
||||
"hooks": [
|
||||
{
|
||||
"type": "command",
|
||||
"command": "jq -r '.cwd // \".\"' | { read -r d; notify-send -a 'Claude Code' -i claude-desktop -u normal 'Claude Code' \"Finished: $(basename \"$d\")\"; } 2>/dev/null || true",
|
||||
"async": true
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -63,19 +80,25 @@
|
||||
"playwright@claude-plugins-official": true,
|
||||
"coderabbit@claude-plugins-official": true,
|
||||
"discord@claude-plugins-official": true,
|
||||
"chrome-devtools-mcp@claude-plugins-official": true
|
||||
"chrome-devtools-mcp@claude-plugins-official": false,
|
||||
"lua-lsp@claude-plugins-official": true
|
||||
},
|
||||
"sandbox": {
|
||||
"enabled": false,
|
||||
"autoAllowBashIfSandboxed": true,
|
||||
"network": {
|
||||
"allowUnixSockets": ["/var/run/docker.sock"],
|
||||
"allowUnixSockets": [
|
||||
"/var/run/docker.sock"
|
||||
],
|
||||
"allowLocalBinding": true
|
||||
},
|
||||
"excludedCommands": ["docker"]
|
||||
"excludedCommands": [
|
||||
"docker"
|
||||
]
|
||||
},
|
||||
"effortLevel": "high",
|
||||
"tui": "fullscreen",
|
||||
"skipDangerousModePermissionPrompt": true,
|
||||
"agentPushNotifEnabled": true,
|
||||
"voiceEnabled": true
|
||||
}
|
||||
|
||||
+36
-13
@@ -1,25 +1,49 @@
|
||||
# AGENTS.MD
|
||||
|
||||
Work style: telegraph; noun-phrases ok; drop grammar; min tokens.
|
||||
|
||||
## Agent Protocol
|
||||
|
||||
- PRs: use `gh pr view/diff` (no URLs).
|
||||
- Need upstream file: stage in `/tmp/`, then cherry-pick; never overwrite tracked.
|
||||
- Keep files <~500 LOC; split/refactor as needed.
|
||||
- Commits: Conventional Commits (`feat|fix|refactor|build|ci|chore|docs|style|perf|test`).
|
||||
- Prefer end-to-end verify; if blocked, say what’s missing.
|
||||
- Do not use em-dashes
|
||||
|
||||
## Coding Preferences - general
|
||||
|
||||
- Keep things simple. Channel "yagni" energy unless told otherwise
|
||||
- Typesafety is useful, take full advantage of it
|
||||
- Don't be scared to propose bold ideas if they can meaningfully benefit our
|
||||
work
|
||||
- Be careful with destructive actions that are not explicitly requested by the
|
||||
user
|
||||
- Tests are good! Endless smoke tests, "regression tests" for feature deletions
|
||||
and things like that are not good. Tests should be focused and not slop
|
||||
- Comments are a great way to clarify functionality and how code is used, but
|
||||
don't comment on every line. Feel free to describe (concisely) how functions
|
||||
are used above function definitions, classes, etc
|
||||
- Keep comments up to date. When making changes, it's important to keep things in
|
||||
sync
|
||||
|
||||
## Coding Preferences (Typescript focused)
|
||||
|
||||
- `any` is the enemy. Inferred types are our friend. Our system should adapt to
|
||||
changes, instead of requiring changes everywhere
|
||||
- If TS code looks like it was written by a Python dev, then it's bad TS code
|
||||
- Avoid one-line functions that are just casting wrappers
|
||||
|
||||
## Questions are read-only
|
||||
|
||||
- A question is a request for an answer, not for changes. If the message opens
|
||||
with something along the lines of "how hard would it be", "what would it look
|
||||
like if we did X", "what are your thoughts", "why does", "should we", "is it
|
||||
possible", or otherwise asks rather than instructs - answer it and do not edit
|
||||
files
|
||||
- If the answer is obvious and the change is trivial, still answer it first and
|
||||
offer to make the change after. Ask before making it
|
||||
|
||||
## Docs
|
||||
|
||||
- Keep notes short; update docs when behavior/API changes (no ship w/o docs).
|
||||
|
||||
## PR Feedback
|
||||
|
||||
- Active PR: `gh pr view --json number,title,url --jq '"PR #\\(.number): \\(.title)\\n\\(.url)"'`.
|
||||
- PR comments: `gh pr view …` + `gh api …/comments --paginate`.
|
||||
- Replies: cite fix + file/line; resolve threads only after fix lands.
|
||||
- When merging a PR: thank the contributor in `CHANGELOG.md`.
|
||||
- Keep notes short; update docs when behavior/API changes
|
||||
|
||||
## Build / Test
|
||||
|
||||
@@ -29,7 +53,6 @@ Work style: telegraph; noun-phrases ok; drop grammar; min tokens.
|
||||
## Git
|
||||
|
||||
- Safe by default: `git status/diff/log`. Push only when user asks.
|
||||
- `git checkout` ok for PR review / explicit request.
|
||||
- Branch changes require user consent.
|
||||
- Destructive ops forbidden unless explicit (`reset --hard`, `clean`, `restore`, `rm`, …).
|
||||
- Don’t delete/rename unexpected stuff; stop + ask.
|
||||
@@ -38,7 +61,7 @@ Work style: telegraph; noun-phrases ok; drop grammar; min tokens.
|
||||
- If user types a command (“pull and push”), that’s consent for that command.
|
||||
- No amend unless asked.
|
||||
- Big review: `git --no-pager diff --color=never`.
|
||||
- Multi-agent: check `git status/diff` before edits; ship small commits.
|
||||
- Multi-agent: check `git status/diff` before edits.
|
||||
|
||||
## Language/Stack Notes
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
model = "gpt-5.5"
|
||||
model_reasoning_effort = "medium"
|
||||
model = "gpt-5.6-sol"
|
||||
model_reasoning_effort = "high"
|
||||
personality = "pragmatic"
|
||||
tool_output_token_limit = 25000
|
||||
# Leave room for native compaction near the 272–273k context window.
|
||||
@@ -94,6 +94,15 @@ trust_level = "trusted"
|
||||
[projects."/Users/sudacode/projects/japanese/anilist-jiten"]
|
||||
trust_level = "trusted"
|
||||
|
||||
[projects."/Users/sudacode/Documents/Codex/2026-08-16/on"]
|
||||
trust_level = "trusted"
|
||||
|
||||
[projects."/Users/sudacode/Documents/Codex/2026-08-16/help"]
|
||||
trust_level = "trusted"
|
||||
|
||||
[projects."/Users/sudacode/Documents/Codex/2026-08-19/this"]
|
||||
trust_level = "trusted"
|
||||
|
||||
[mcp_servers.backlog]
|
||||
command = "backlog"
|
||||
args = ["mcp", "start"]
|
||||
@@ -115,22 +124,23 @@ startup_timeout_sec = 120
|
||||
NODE_REPL_NATIVE_PIPE_CONNECT_TIMEOUT_MS = "1000"
|
||||
NODE_REPL_NODE_MODULE_DIRS = "/Applications/ChatGPT.app/Contents/Resources/cua_node/lib/node_modules"
|
||||
NODE_REPL_NODE_PATH = "/Applications/ChatGPT.app/Contents/Resources/cua_node/bin/node"
|
||||
NODE_REPL_TRUSTED_CODE_PATHS = "/Users/sudacode/.codex"
|
||||
NODE_REPL_TRUSTED_CODE_PATHS = "/Users/sudacode/.codex:/Applications/ChatGPT.app/Contents/Resources/cua_node/lib/node_modules"
|
||||
CODEX_HOME = "/Users/sudacode/.codex"
|
||||
NODE_REPL_TRUSTED_BROWSER_CLIENT_SHA256S = "6d25aa7656feac858f3a3bdaea5bcbab0dbfd426c9de8e6931ce90c399ee8e4f,c8b7e809d7cf9e20a57123b2530d476ccec9a01a6230a7b2b924fea7d94d7f4a"
|
||||
NODE_REPL_TRUSTED_BROWSER_CLIENT_SHA256S = "9230e2bd8b24b7ac7a0ba6774c64bf0d78ecdabbdd91d0ed627b02a587bae2df"
|
||||
BROWSER_USE_AVAILABLE_BACKENDS = "chrome,iab"
|
||||
NODE_REPL_INSTRUCTIONS_USE_CASE_BROWSER = "Control the in-app browser in conjunction with the Browser Plugin."
|
||||
NODE_REPL_INSTRUCTIONS_USE_CASE_CHROME = "Control the Chrome browser in conjunction with the Chrome Plugin. Prefer this method of controlling Chrome over alternatives (such as Computer Use) unless the user explicitly mentions an alternative."
|
||||
NODE_REPL_INSTRUCTIONS_USE_CASE_COMPUTER_USE = "Control desktop apps on macOS through Computer Use."
|
||||
BROWSER_USE_CODEX_APP_BUILD_FLAVOR = "prod"
|
||||
BROWSER_USE_CODEX_APP_VERSION = "26.707.31428"
|
||||
BROWSER_USE_CODEX_APP_VERSION = "26.810.52044"
|
||||
SKY_CUA_SERVICE_PATH = "/Users/sudacode/.codex/computer-use/Codex Computer Use.app"
|
||||
CODEX_CLI_PATH = "/Applications/ChatGPT.app/Contents/Resources/codex"
|
||||
|
||||
[mcp_servers.computer-use]
|
||||
command = "./Codex Computer Use.app/Contents/SharedSupport/SkyComputerUseClient.app/Contents/MacOS/SkyComputerUseClient"
|
||||
args = ["mcp"]
|
||||
cwd = "."
|
||||
enabled = true
|
||||
enabled = false
|
||||
|
||||
[plugins."github@openai-curated"]
|
||||
enabled = true
|
||||
@@ -156,9 +166,18 @@ enabled = true
|
||||
[plugins."visualize@openai-bundled"]
|
||||
enabled = true
|
||||
|
||||
[plugins."computer-use@openai-bundled"]
|
||||
enabled = true
|
||||
|
||||
[plugins."browser@openai-bundled"]
|
||||
enabled = true
|
||||
|
||||
[plugins."pdf@openai-primary-runtime"]
|
||||
enabled = true
|
||||
|
||||
[plugins."template-creator@openai-primary-runtime"]
|
||||
enabled = true
|
||||
|
||||
[notice.model_migrations]
|
||||
"gpt-5.2-codex" = "gpt-5.4"
|
||||
|
||||
@@ -167,12 +186,12 @@ enabled = true
|
||||
"gpt-5.6-sol" = 4
|
||||
|
||||
[marketplaces.openai-bundled]
|
||||
last_updated = "2026-07-10T05:36:55Z"
|
||||
last_updated = "2026-08-16T07:38:41Z"
|
||||
source_type = "local"
|
||||
source = "/Users/sudacode/.codex/.tmp/bundled-marketplaces/openai-bundled"
|
||||
|
||||
[marketplaces.openai-primary-runtime]
|
||||
last_updated = "2026-05-09T00:22:09Z"
|
||||
last_updated = "2026-08-16T07:39:44Z"
|
||||
source_type = "local"
|
||||
source = "/Users/sudacode/.cache/codex-runtimes/codex-primary-runtime/plugins/openai-primary-runtime"
|
||||
|
||||
@@ -228,3 +247,8 @@ global = "vscode"
|
||||
"/Users/sudacode/github/SubMiner" = "vscode"
|
||||
"/Users/sudacode/projects/japanese/SubMiner" = "vscode"
|
||||
"/Users/sudacode/.codex/worktrees/204a/SubMiner" = "ghostty"
|
||||
|
||||
[shell_environment_policy.set]
|
||||
BROWSER_USE_AVAILABLE_BACKENDS = "chrome,iab"
|
||||
NODE_REPL_TRUSTED_BROWSER_CLIENT_SHA256S = "9230e2bd8b24b7ac7a0ba6774c64bf0d78ecdabbdd91d0ed627b02a587bae2df"
|
||||
NODE_REPL_TRUSTED_CODE_PATHS = "/Users/sudacode/.codex:/Applications/ChatGPT.app/Contents/Resources/cua_node/lib/node_modules"
|
||||
|
||||
@@ -7,11 +7,11 @@ tool_output_token_limit = 25000
|
||||
# With tool_output_token_limit=25000 ⇒ 273000 - (25000 + 15000) = 233000
|
||||
model_auto_compact_token_limit = 233000
|
||||
suppress_unstable_features_warning = true
|
||||
notify = ["/home/sudacode/.codex/scripts/codex-notify"]
|
||||
sandbox_mode = "workspace-write"
|
||||
service_tier = "default"
|
||||
|
||||
[tui]
|
||||
notifications = ["agent-turn-complete"]
|
||||
notifications = ["agent-turn-complete", "approval-requested"]
|
||||
notification_condition = "always"
|
||||
|
||||
[tui.model_availability_nux]
|
||||
@@ -30,6 +30,7 @@ skills = true
|
||||
shell_snapshot = true
|
||||
multi_agent = true
|
||||
js_repl = false
|
||||
default_mode_request_user_input = true
|
||||
|
||||
[mcp_servers.deepwiki]
|
||||
url = "https://mcp.deepwiki.com/mcp"
|
||||
@@ -41,6 +42,10 @@ args = ["@playwright/mcp@latest", "--executable-path", "/usr/bin/helium-browser"
|
||||
[mcp_servers.openaiDeveloperDocs]
|
||||
url = "https://developers.openai.com/mcp"
|
||||
|
||||
[mcp_servers.anki]
|
||||
command = "npx"
|
||||
args = ["-y", "@ankimcp/anki-mcp-server", "--stdio"]
|
||||
|
||||
[projects."/home/sudacode/projects"]
|
||||
trust_level = "trusted"
|
||||
|
||||
@@ -218,6 +223,33 @@ trust_level = "trusted"
|
||||
[projects."/home/sudacode/.agents/skills"]
|
||||
trust_level = "trusted"
|
||||
|
||||
[projects."/home/sudacode/github/manatan"]
|
||||
trust_level = "trusted"
|
||||
|
||||
[projects."/home/sudacode/Downloads/jdownloader/tmp"]
|
||||
trust_level = "trusted"
|
||||
|
||||
[projects."/home/sudacode/games/ModEngine2"]
|
||||
trust_level = "trusted"
|
||||
|
||||
[projects."/truenas/jellyfin/anime/BanG Dream! It's MyGO!!!!!/Season-1"]
|
||||
trust_level = "trusted"
|
||||
|
||||
[projects."/tmp/claude-1000/-home-sudacode--agents-skills-claude-code-computer-delegate/df15b0bc-3ae1-4e90-a006-21c31ddc8634/scratchpad"]
|
||||
trust_level = "trusted"
|
||||
|
||||
[projects."/home/sudacode/.local/share/Steam/steamapps/common/DARK SOULS III/Game"]
|
||||
trust_level = "trusted"
|
||||
|
||||
[projects."/home/sudacode/projects/japanese/kiku"]
|
||||
trust_level = "trusted"
|
||||
|
||||
[projects."/home/sudacode/Documents/anki"]
|
||||
trust_level = "trusted"
|
||||
|
||||
[projects."/home/sudacode/Documents/anki/stats"]
|
||||
trust_level = "trusted"
|
||||
|
||||
[notice.model_migrations]
|
||||
"gpt-5.3-codex" = "gpt-5.4"
|
||||
|
||||
@@ -236,9 +268,6 @@ enabled = true
|
||||
[plugins."chrome@openai-bundled"]
|
||||
enabled = true
|
||||
|
||||
[plugins."subminer-workflow@subminer-local"]
|
||||
enabled = true
|
||||
|
||||
[plugins."coderabbit@openai-curated"]
|
||||
enabled = true
|
||||
|
||||
|
||||
@@ -5,6 +5,9 @@ import subprocess
|
||||
import sys
|
||||
|
||||
|
||||
CHATGPT_ICON = "/usr/share/icons/hicolor/512x512/apps/chatgpt-desktop.png"
|
||||
|
||||
|
||||
def main() -> int:
|
||||
if len(sys.argv) != 2:
|
||||
return 0
|
||||
@@ -27,7 +30,13 @@ def main() -> int:
|
||||
message = message[:177] + "..."
|
||||
|
||||
subprocess.run(
|
||||
[notify_send, "--app-name=Codex", "Codex", message],
|
||||
[
|
||||
notify_send,
|
||||
"--app-name=Codex",
|
||||
f"--icon={CHATGPT_ICON}",
|
||||
"Codex",
|
||||
message,
|
||||
],
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL,
|
||||
check=False,
|
||||
|
||||
@@ -68,7 +68,7 @@ update_ms = 2000
|
||||
|
||||
#* Processes sorting, "pid" "program" "arguments" "threads" "user" "memory" "cpu lazy" "cpu direct",
|
||||
#* "cpu lazy" sorts top process over time (easier to follow), "cpu direct" updates top process directly.
|
||||
proc_sorting = "memory"
|
||||
proc_sorting = "cpu lazy"
|
||||
|
||||
#* Reverse sorting order, True or False.
|
||||
proc_reversed = false
|
||||
@@ -228,7 +228,7 @@ net_download = 100
|
||||
net_upload = 100
|
||||
|
||||
#* Use network graphs auto rescaling mode, ignores any values set above and rescales down to 10 Kibibytes at the lowest.
|
||||
net_auto = true
|
||||
net_auto = false
|
||||
|
||||
#* Sync the auto scaling for download and upload to whichever currently has the highest scale.
|
||||
net_sync = true
|
||||
|
||||
@@ -147,7 +147,11 @@ hl.bind("ALT + Tab", hl.dsp.focus({ last = true }))
|
||||
|
||||
hl.bind("CTRL + F9", hl.dsp.pass({ window = "class:^(com\\.obsproject\\.Studio)$" }))
|
||||
hl.bind("CTRL + F10", hl.dsp.pass({ window = "class:^(com\\.obsproject\\.Studio)$" }))
|
||||
hl.bind("CTRL + SHIFT + M", hl.dsp.pass({ window = "class:^(discord)$" }))
|
||||
-- Discord mute: also re-bound inside the "clean" submap below so it keeps working there
|
||||
local function bindDiscordMute()
|
||||
hl.bind("CTRL + SHIFT + M", hl.dsp.pass({ window = "class:^(discord)$" }))
|
||||
end
|
||||
bindDiscordMute()
|
||||
|
||||
hl.bind("CTRL + SHIFT + D", hl.dsp.exec_cmd("~/.local/bin/dragon"))
|
||||
hl.bind("CTRL + ALT + F", hl.dsp.exec_cmd("~/.local/bin/favorite-wallpaper"))
|
||||
@@ -189,6 +193,8 @@ hl.define_submap("clean", function()
|
||||
restoreMouseWindowBinds()
|
||||
hl.dispatch(hl.dsp.submap("reset"))
|
||||
end)
|
||||
-- only other keybind allowed in clean
|
||||
bindDiscordMute()
|
||||
end)
|
||||
|
||||
hl.bind("SUPER + l", hl.dsp.exec_cmd("hyprlock"))
|
||||
|
||||
@@ -71,6 +71,7 @@ x-scheme-handler/tonsite=org.telegram.desktop.desktop;
|
||||
x-scheme-handler/tradingview=tradingview.desktop;TradingView.desktop;
|
||||
application/x-wine-extension-ini=nvim.desktop;
|
||||
x-scheme-handler/subminer=subminer.desktop;SubMiner.desktop;
|
||||
x-scheme-handler/t3code=t3code-url-handler.desktop;
|
||||
|
||||
[Default Applications]
|
||||
application/x-extension-htm=helium.desktop;zen.desktop
|
||||
@@ -159,4 +160,5 @@ x-scheme-handler/subminer=subminer.desktop
|
||||
x-scheme-handler/claude-cli=claude-code-url-handler.desktop
|
||||
x-scheme-handler/mux=mux.desktop
|
||||
x-scheme-handler/claude=com.anthropic.claude-desktop.desktop
|
||||
x-scheme-handler/t3code=t3code.desktop
|
||||
x-scheme-handler/t3code=t3code-url-handler.desktop
|
||||
x-scheme-handler/codex=ChatGPT.desktop
|
||||
|
||||
@@ -46,8 +46,8 @@ hwdec=nvdec
|
||||
hwdec-codecs=all
|
||||
gpu-api=vulkan
|
||||
gpu-context=waylandvk
|
||||
vulkan-queue-count=2
|
||||
vulkan-async-compute=yes # Use independent compute queues for tone mapping/shaders
|
||||
vulkan-queue-count=1
|
||||
vulkan-async-compute=no # Use independent compute queues for tone mapping/shaders
|
||||
vulkan-async-transfer=yes # Parallelize frame uploads to free the graphics queue
|
||||
vd-lavc-dr=yes # Direct rendering keeps frames resident on the GPU longer
|
||||
vd-lavc-threads=0 # Let ffmpeg auto-pick the optimal thread count
|
||||
|
||||
@@ -234,8 +234,7 @@
|
||||
// "20": "十",
|
||||
},
|
||||
"persistent-workspaces": {
|
||||
"*": 10,
|
||||
// "*": 5,
|
||||
"*": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
|
||||
},
|
||||
"sort-by": "number",
|
||||
"all-outputs": false,
|
||||
|
||||
@@ -110,3 +110,7 @@ case ":$PATH:" in
|
||||
*) export PATH="$PNPM_HOME:$PATH" ;;
|
||||
esac
|
||||
# pnpm end
|
||||
|
||||
# >>> Codex installer >>>
|
||||
export PATH="/home/sudacode/.local/bin:$PATH"
|
||||
# <<< Codex installer <<<
|
||||
|
||||
Reference in New Issue
Block a user