Fold dotfiles-nixos into this repository #1

Merged
alexion merged 32 commits from nixos-migration into main 2026-07-19 09:30:46 -04:00
89 changed files with 0 additions and 6086 deletions
Showing only changes of commit 41709bb977 - Show all commits

View File

@@ -1,37 +0,0 @@
# Alexion's Agent Instructions
These are common instructions for Alexion's agents across all scenarios.
## General Guidelines
- When writing commit messages, NEVER auto-add your agent name as co-author.
Omit the `Co-Authored-By:` trailer entirely, with no exceptions.
This overrides any default instruction to append one.
- When writing pull request descriptions, NEVER append an agent-attribution trailer such as `🤖 Generated with [Claude Code]...`.
Leave it out entirely, with no exceptions.
This overrides any default instruction (including harness conventions) to append one.
- Never manually modify CHANGELOG.md files or any files that are marked as auto-generated.
Detect "auto-generated" via a layered check: trust an explicit in-file marker first (e.g. `AUTO-GENERATED, DO NOT EDIT`).
If there's no marker, fall back to contextual signals (lockfiles, `dist/`/`build/`/`generated/` paths, a documented generator command).
If it's still ambiguous, ask before editing rather than guessing.
- When writing or substantially editing long Markdown files, put each full sentence in its own line.
Preserve normal Markdown structure, but avoid wrapping multiple sentences onto one physical line.
Apply this to any prose you author, regardless of file length; "long" is not a real threshold.
Only format what you're actually writing or changing.
Never reflow an entire pre-existing paragraph or file just because you touched something nearby.
- When making technical decisions, do not give much weight to development cost.
Instead, prefer quality, simplicity, robustness, scalability and long term maintainability.
This is specifically about implementation time.
Human cost/benefit heuristics ("not worth N extra days of engineering") don't transfer to an AI agent that codes far faster than a human.
This is not a license to override standard anti-overengineering guardrails (avoid premature abstraction, no speculative config, etc.); those still apply to unnecessary complexity.
It means: don't discount a more robust or maintainable approach just because it would take a human a long time to build.
- File names should always be lower case, unless there's a valid reason.
Established ecosystem or tool conventions count as a valid reason automatically (e.g. `README.md`, `LICENSE`, `CHANGELOG.md`, `Makefile`, `Dockerfile`, `.github/` files), without needing to ask each time.
- When you discover that a belief you held about an objective fact or convention of the current project was wrong, write it down so it isn't relearned next time.
This applies whether the user corrected you or you caught the mistake yourself, and only to things that are true regardless of who is operating the project (a wrong build command, a wrong file path, a convention you guessed at instead of checking) — not personal working-style preferences or one-off task details.
Record it in that project's own CLAUDE.md, not this global file, under a dedicated `## Gotchas` section (create the section if the file doesn't have one yet).
If the project has nested CLAUDE.md files, use the one nearest to where the mistake occurred, falling back to the project's top-level CLAUDE.md.
Append to an existing CLAUDE.md immediately, without asking; if no CLAUDE.md exists yet for the project, ask before creating one.
Briefly mention the edit in your response rather than making it silently.
If an existing entry is later found to be wrong or stale, correct or remove it the same way.

View File

@@ -1,21 +0,0 @@
#!/bin/sh
# attention-bell.sh — ring the terminal bell in this Claude session's tmux pane
# so tmux's monitor-bell flags the (background) window red in the status bar.
#
# Claude Code runs hooks as detached subprocesses: they have no controlling
# terminal, so /dev/tty is unavailable here. But the parent-process chain up to
# the `claude` process stays intact, and `claude` itself holds the pane's pty.
# So we walk ancestry to find it and write the bell straight to that tty.
# (Writing a bare BEL to an explicit /dev/pts/N works even from a detached
# process — verified against tmux's window_bell_flag.)
pid=$PPID
while [ "$pid" -gt 1 ] 2>/dev/null; do
if [ "$(ps -o comm= -p "$pid" 2>/dev/null)" = claude ]; then
tty=$(ps -o tty= -p "$pid" 2>/dev/null | tr -d ' ')
[ -n "$tty" ] && [ "$tty" != '?' ] && printf '\a' > "/dev/$tty"
exit 0
fi
pid=$(ps -o ppid= -p "$pid" 2>/dev/null | tr -d ' ')
[ -z "$pid" ] && break
done

View File

@@ -1,36 +0,0 @@
{
"hooks": {
"Stop": [
{
"hooks": [
{
"type": "command",
"command": "~/.claude/hooks/attention-bell.sh"
}
]
}
],
"Notification": [
{
"hooks": [
{
"type": "command",
"command": "~/.claude/hooks/attention-bell.sh"
}
]
}
],
"PreToolUse": [
{
"matcher": "Write|Edit",
"hooks": [
{
"type": "command",
"command": "f=$(jq -r '.tool_input.file_path // empty'); printf '%s' \"$f\" | grep -Eq '(\\.(test|spec)\\.[cm]?[jt]sx?$)|/__tests__/' && jq -n '{hookSpecificOutput:{hookEventName:\"PreToolUse\",additionalContext:\"test-driven-development skill: the MAIN agent must not author test files. Each test is written by a test-writer sub-agent (via the Agent tool) from the public interface alone. If you are running /implement or any TDD flow and have not loaded /test-driven-development, load it now and delegate this test to the sub-agent. If you ARE the test-writer sub-agent, disregard this reminder.\"}}' || true"
}
]
}
]
},
"model": "opus"
}

View File

@@ -1,37 +0,0 @@
# 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.

View File

@@ -1,44 +0,0 @@
# 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 using the Agent tool. Each must produce a **radically different** interface for the deepened module.
Prompt each sub-agent with a separate technical brief (file paths, coupling details, dependency category from [DEEPENING.md](DEEPENING.md), what sits behind the seam). The brief is independent of the user-facing problem-space explanation in Step 1. Give each agent a different design constraint:
- Agent 1: "Minimize the interface — aim for 13 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 `.claude/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.

View File

@@ -1,113 +0,0 @@
---
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 repository) 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.
## 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.

View File

@@ -1,195 +0,0 @@
# Glossary — Building Great Skills
The domain model for what makes a skill great. A skill exists to wrangle determinism out of a stochastic system; the root virtue is **Predictability**, and every term below is a lever on it. This is the disclosed reference for [`craft-skill`](SKILL.md).
The terms are grouped by axis: **Invocation** (how a skill is reached), **Information Hierarchy** (how its content is arranged), **Steering** (how the agent's runtime behaviour is shaped), and **Pruning** (how it is kept lean). Each **failure mode** lives beside the lever that cures it, tagged _failure mode_.
**Bold terms** in any definition are themselves defined in this glossary; find them by their heading.
## Predictability
The degree to which a skill makes the agent behave the same _way_ on every run — the same process, not the same output (a brainstorming skill should _predictably_ diverge; its tokens vary, its behaviour doesn't). The root virtue every other term serves — cost and maintainability are symptoms of it, not rivals.
_Avoid_: consistency, reliability, robustness, output-determinism
## Invocation
How a skill is reached — and the two loads you pay for the choice.
### Model-Invoked
A skill that keeps its **description** field, so the agent can see it and fire it autonomously — and the human can still type its name, so model-invocation always _includes_ user reach. There is no model-only state: a description only ever _adds_ agent discovery, never removes the human's. Pays a permanent **context load** on every turn in exchange for that discoverability. Reachable by other skills, because the description that makes it agent-discoverable makes it invocable. A model-invoked skill whose content is all **reference** is also one home for shared reference: another skill can invoke it, so reference needed by several skills lives in one place. Pick model-invocation only when the agent must reach the skill on its own; if it never fires except by hand, drop the description and pay no context load.
_Avoid_: ability, tool, capability
### User-Invoked
A skill with its **description** stripped — invisible to the agent and reachable only by the human typing its name (user-_only_, where **model-invoked** is user-_and-agent_). Trades agent-discoverability for zero **context load**. Because it has no description, nothing but the human can reach it: no other skill can fire it.
_Avoid_: procedure, workflow, command
### Description
The skill's machine-readable trigger, and the one **context pointer** a **model-invoked** skill is forced to keep loaded at all times. Its mere presence _is_ the invocation axis: keep it and the skill is model-invoked (and reachable by other skills); delete it and the skill is **user-invoked**, reachable only by the human. The source of a model-invoked skill's **context load**.
_Avoid_: frontmatter, summary
### Context Pointer
A reference held in the agent's context that names some out-of-context material and encodes the condition for reaching it. The **description** is the top-level context pointer (context window → skill); pointers to disclosed files are the same object one level down. Its wording, not the target, decides _when_ the agent reaches — and _how reliably_. A must-have target behind a weakly worded pointer is a variance bug: fix the wording first, and inline the material only if sharpening fails.
_Avoid_: link, reference, import
### Context Load
The cost a **model-invoked** skill imposes on the agent's context window — its **description**, always loaded, spending both tokens and attention. What **user-invoked** skills escape by having no description, and the brake on splitting into more model-invoked skills.
_Avoid_: token cost, context bloat
### Cognitive Load
The cost a **user-invoked** skill imposes on the human — what they must hold in their head: which skills exist and when to reach for each (the human is the index). What **model-invocation** removes by being agent-discoverable, and the brake on splitting into more user-invoked skills. Not a cost to minimise: it is the price of human agency, the reason some skills stay user-invoked. Spend it where human judgement matters; remove it where it does not.
_Avoid_: human index, burden, overhead
### Router Skill
A **user-invoked** skill whose job is to point at your other user-invoked skills — naming each and when to reach for it — so the human has one skill to remember instead of many. It can only hint, never fire them: user-invoked skills have no **description**, so nothing but the human can reach them. The cure for **cognitive load** when user-invoked skills multiply.
_Avoid_: dispatcher, menu, registry, index, router procedure
### Granularity
How finely you divide skills. Finer division spends one of the two loads: more **model-invoked** skills spend **context load** (more descriptions crowding the window and competing for attention); more **user-invoked** skills spend **cognitive load** (more for the human to remember and reach for). Two cuts guide the division. By **invocation**, split off a model-invoked skill where you have a distinct **leading word** to trigger it — a trigger word you actually use in your prompts. By **sequence**, split a run of **steps** where a step's **post-completion steps** need hiding, since isolating it in its own context clears what follows. Beware the reverse: merging sequences exposes each step's post-completion steps to what follows, inviting premature completion.
_Avoid_: chunking, modularity
## Information Hierarchy
How a skill's content is arranged, and how far down the ladder each piece sits.
### Information Hierarchy
A skill's content ranked by how immediately the agent needs it — a single ladder, produced by two cuts: in-file or behind a pointer, and step or reference. The rungs:
- **Steps** — in-file, primary
- **Reference**, in-file — secondary
- **Reference**, disclosed — behind a **context pointer**
A skill with no **steps** uses just the bottom two rungs — often a legitimately flat peer-set (e.g. every rule of a review on one rung), which is a fine arrangement, not a smell. The hierarchy is independent of invocation: a skill can be model- or user-invoked whether it is all steps, all reference, or both. When a skill has steps, in-file reference that should be disclosed buries them and turns attending to them into a coin-flip — a variance lever, not just a legibility one. Keep the top of the ladder legible; push down it whatever you can.
_Avoid_: structure, organization, layout
### Steps
The ordered actions the agent performs — when a skill has them, the primary tier of its content, and the part that earns its place in SKILL.md. Not every skill has steps: a skill can be all steps (`test-driven-development`), all **reference** (a review), or both, independent of invocation. Every step ends on a **completion criterion**, clear or vague.
_Avoid_: workflow, instructions, choreography
### Reference
Material the agent refers to on demand — definitions, facts, parameters, examples, conditional instructions. When a skill has **steps** it is secondary to them; when a skill has none it is the entire content; or it lives outside any skill entirely — see **External Reference**. Reached via **context pointers**, and the prime candidate for **progressive disclosure**.
_Avoid_: supporting material, docs, background
### External Reference
**Reference** that lives outside the skill system — a plain file, no **description**, no **steps**, not invocable — that any skill can point at. The home for shared reference that needn't fire on its own, and the only shared home two **user-invoked** skills can use, since neither has a description and so neither can fire the other.
_Avoid_: doc, resource, knowledge base
### Progressive Disclosure
Moving **reference** down the ladder — out of SKILL.md and behind a **context pointer** — so the top stays legible. Not primarily a token optimisation; it is how the **information hierarchy** is protected. Licensed by **branching**: disclose what only some branches need, inline what every path needs, and if a pointer fires unreliably on must-have material, sharpen its wording, and pull it back inline only if that fails.
_Avoid_: lazy loading, chunking
### Co-location
Keeping the material an agent needs at once in one place — a concept's definition, rules, and caveats under a single heading, not scattered across the file — so reading one part brings its neighbours with it. The within-file companion to the **Information Hierarchy**: the hierarchy ranks _how far down_ a piece sits; co-location decides _what sits beside it_ once there. There is no formula for the right format of a body of **reference**; the test is that a skill should read like documentation written for the agent, and grouped material reads that way where scattered material does not. Distinct from **Duplication**: that repeats one meaning in two places, where scattering fragments a single meaning across many.
_Avoid_: grouping, clustering, cohesion
### Sprawl
_Failure mode._ A skill that is simply too long — too many lines in SKILL.md — independent of whether they are stale or repeated. Even an all-live, all-unique skill can sprawl. It costs readability (the agent wades through more before it can act, and attention thins across the excess), maintainability (every extra line is one more to keep **relevant**), and tokens. The cure is the **information hierarchy**: push **reference** down behind **context pointers**, and split by **branch** or sequence so each path carries only what it needs. Distinct from **sediment** (length from stale accumulation) and **duplication** (length from repeated meaning) — sprawl is length itself, whatever its cause.
_Avoid_: bloat, length, size, verbosity
## Steering
The levers that shape the agent's runtime behaviour toward **Predictability**.
### Branch
A distinct way a skill can be invoked — a case the skill handles — so different runs take different paths through it. A skill with many steps may carry many branches; a linear one has none.
_Avoid_: path, case, fork
### Leading Word
A compact concept — also called a _Leitwort_ — already living in the model's pretraining, that the agent thinks with while running the skill. It encodes a behavioural principle in the fewest possible tokens by invoking priors the model already holds (e.g. _lesson_, _proximal zone of development_, _fog of war_, _tracer bullets_). Repeated as a token, never as a sentence, it accumulates a distributed definition across the skill and anchors a whole region of behaviour. Coining your own works if you define it clearly, but a made-up word recruits no priors — you pay in definition tokens what a pretrained word gives free. Reach for an existing word first.
A leading word serves **predictability** twice. In the body it anchors **execution** — the agent reaches for the same behaviour every time the concept appears, and inside flat reference it focuses attention on a class of thing to look for, recruiting the right checks each run. In the **description** it anchors **invocation** — and not only within the skill: when the same word lives in your prompts, your docs, and your codebase, the agent links that shared language to the skill and fires it more reliably. Word a description with the leading words you actually use when you want the skill.
_Avoid_: keyword, term, motif
### Completion Criterion
The condition that tells the agent a unit of work is done — the target it judges against. Two properties make it a lever, not just a quality. Its **clarity** (can the agent tell done from not-done?) resists **premature completion** — a vague bound ("understanding reached") lets the agent declare done and slip to the next step; this axis needs _steps_ to bite, since premature completion is a between-steps failure. Its **demand** (how much it requires) sets **legwork** — "every modified model accounted for" forces thorough work where "produce a change list" does not — and this axis is _not_ step-bound: it can bind a body of flat reference too, which is how a skill with no steps still carries an exhaustiveness bar ("every rule applied"). The strongest criteria are both checkable and exhaustive.
_Avoid_: done condition, exit condition, stopping rule
### Legwork
The work an agent does behind the scenes within a single step — reading files, exploring the codebase, making changes, digging up what it needs rather than offloading to the user. It lives below the step structure: never written as its own step, latent in the wording, controlled by the agent rather than the skill. The within-step counterpart to **post-completion steps**' across-step pull. Raised by a **leading word** (_comprehensive_, _thorough_) or a **completion criterion** that demands the work be exhaustive — including the demand axis applied to flat reference, which is what drives a skill of flat reference to cover all its rungs. Goes thin either when that demand is missing or when **premature completion** cuts the step short.
_Avoid_: scope, effort, diligence, coverage
### Post-Completion Steps
The **steps** that follow the current step. Visible, they pull the agent forward into **premature completion** — the more it sees, the stronger the tug; the defence is to hide them by splitting the sequence of steps into two.
_Avoid_: horizon, fog of war, lookahead
### Premature Completion
_Failure mode._ Ending the current step before it is genuinely done, because the agent's attention slips to being done rather than to the work. A between-steps failure: it needs **steps** to occur — a skill with no steps that quits early isn't premature completion but thin **legwork** under an unmet demand. A tug-of-war between two forces: visible **post-completion steps** (the pull forward) and the **completion criterion**'s clarity (the resistance — a sharp, checkable bar holds; a vague one gives way). Fuzziness is the necessary condition: a sharp bound resists the pull no matter how many later steps are visible, so a step that never rushes needs no defending. Two levers hold a step that does, but reach for them in order: **sharpen the bound first** — it is local and cheap. Only when the criterion is irreducibly fuzzy _and_ you actually observe the rush do you **hide the later steps** — and hiding only works across a real context boundary (a user-invoked hand-off or a subagent dispatch; an inline model-invoked call leaves the later steps in context and clears nothing). One cause of thin legwork, but distinct from it: legwork can be thin even when a step runs to full completion.
_Avoid_: premature closure, the rush, rushing, shortcutting
## Pruning
Keeping a skill lean — each remedy paired with the failure it cures.
### Single Source of Truth
The desired state where each meaning lives in exactly one authoritative place, so a change to the skill's behaviour is a change in one place. **Duplication** is its violation.
_Avoid_: home, canonical location
### Duplication
_Failure mode._ The same meaning given more than one **single source of truth**. It costs maintenance (change one place, you must change the others), costs tokens, and inflates prominence — repeating a meaning weights it on the ladder past its real rank. The accidental inverse of a **leading word**, which raises attention on purpose by repeating a token, never the meaning.
_Avoid_: repetition, redundancy
### Relevance
Whether a line still bears on what the skill does — the lens for what to keep. A line loses relevance either by never bearing on the task (mere exposition, or a **branch** that should be disclosed) or by going stale: drifting out of date as the behaviour or world it describes changes. Shorter skills are easier to keep relevant, because each line is cheaper to check. Distinct from **no-op**: relevance asks whether a line bears on the task, not whether it changes behaviour.
_Avoid_: load-bearing, staleness, freshness
### Sediment
_Failure mode._ Layers of old content that settle in a skill and are never cleared, because adding feels safe and removing feels risky — so stale and irrelevant lines accumulate and you must core down through them to find what is still live. The default fate of any skill without a pruning discipline; the slow erosion of **relevance**, as opposed to **duplication**'s repeated meaning.
_Avoid_: accretion, bloat, cruft, rot
### No-Op
_Failure mode._ An instruction that changes nothing because the model already does it by default — you pay load to tell the agent what it would do anyway. The test: does a line change behaviour versus the default? A line can be perfectly **relevant** and still be a no-op. The same priors that make a **leading word** free make a no-op worthless.
A leading word is a _technique_; No-Op is a _verdict_ on a line — and they cross. A leading word too weak to beat the default is a no-op (_be thorough_ when the agent is already thorough-ish), and the fix is a stronger word that passes the verdict (_relentless_), not a different technique. So the No-Op test — does it change behaviour versus the default? — is also how you grade whether a leading word is earning its repetitions. This is model-relative, not reader-relative: two people disagreeing over whether a line is a no-op disagree about the default, and settle it by running the skill, not by debate.
_Avoid_: redundant instruction, restating the obvious, belaboring

View File

@@ -1,49 +0,0 @@
---
name: craft-skill
description: Draft a new skill, or audit and rewrite an existing one, judged against the vocabulary in GLOSSARY.md.
disable-model-invocation: true
---
Draft a new skill from scratch, or audit and rewrite an existing one — both judged against one bar: **predictability**, the agent taking the same process every run. **Bold terms** are defined in [`GLOSSARY.md`](GLOSSARY.md); look them up there for the full meaning.
This skill does not judge general prose quality (clarity, jargon, sentence structure) — only skill-specific structure. A dedicated technical-writing-guide skill will cover the former once it exists; until then, use your own judgment for sentence-level prose.
## Which branch
If the request describes a new workflow, capability, or repeated manual process with no existing skill named — **Draft a new skill**. If it names an existing skill (by name or path) to review, fix, or improve — **Audit an existing skill**. Both end at **Verify and ship**.
## Draft a new skill
1. **Capture intent.** If the conversation already contains the workflow (e.g. "turn this into a skill"), extract answers from it first; only ask about what's missing. Ask one question at a time — several at once is bewildering:
- What should this make the agent do — is it a **procedure** (ordered **steps**), **knowledge** it consults (**reference**), or both? This decides the shape from the start.
- When would you actually reach for it: do you type its name, or should the agent reach for it unprompted? Walk the **context load** vs **cognitive load** tradeoff explicitly rather than defaulting — see `Invocation` in GLOSSARY.md.
- Does it have distinct **branches** — cases that take different paths? Name each. A linear checklist's items aren't branches by themselves — look for actual alternate paths, not the steps that always all run.
- Is this workflow already documented somewhere in the project (a README, CLAUDE.md, CONTRIBUTING)? If so the draft should point there rather than restate it — see `External Reference` and `Single Source of Truth` in GLOSSARY.md.
- For each step, what does done look like — a **completion criterion** you could check without ambiguity?
- Is there already a word — in your prompts, docs, or codebase — that names this behavior? Reach for that **leading word** before coining one.
Done when every axis above has an answer, or the user says to just draft something and iterate.
2. **Write the draft.** First decide where it lives: project-local `.claude/skills/` if the workflow is tied to this one repo, `~/.claude/skills/` if it's general-purpose across projects. Then follow the **information hierarchy**: steps for what the agent does in order, in-file **reference** for facts every branch needs, and disclose the rest behind a pointer — to a sibling file, or to the existing project docs identified in step 1 rather than restating them. Done when every branch from step 1 has somewhere to live, and no sentence fails the no-op test in isolation (see `No-Op` in GLOSSARY.md).
## Audit an existing skill
1. **Locate it.** Check the current project's `.claude/skills/`, then `~/.claude/skills/`, then `~/.claude/skills/library/`, in that order; ask if the name is ambiguous across locations. If it's tracked in a project's `skills-lock.yaml`, mention that editing it here will make it read as locally-customized to `update-skills` — confirm that's actually intended rather than editing the library source.
2. **Apply the checklist.** Read the skill and its disclosed files, then check each against GLOSSARY.md, quoting the offending line for anything that fails:
- **Premature completion** — is each completion criterion checkable, and does it demand what the step actually needs?
- **Duplication** — does any meaning appear in more than one place?
- **Sediment** — any line that no longer bears on what the skill does?
- **Sprawl** — could in-file reference be disclosed instead, or a run of steps split by branch?
- **No-op** — any sentence the model would already do by default? Test sentence by sentence, not line by line — a line can carry one load-bearing sentence and one no-op sentence together.
- Is the **invocation** choice (model- vs user-invoked) still the right one for how this skill actually gets used? Is there a restated concept that should collapse into a **leading word**?
3. **Rewrite** based on the findings. Done when every finding from step 2 is either addressed or explicitly noted as intentionally kept.
## Verify and ship
1. Propose one realistic test prompt — reflecting the trigger phrasing gathered (draft) or the skill's existing purpose (audit) — and get it confirmed or adjusted before spending a run on it.
2. Spawn one subagent: give it the skill's path and the confirmed prompt, have it attempt the task using the skill, and report back what happened — including anywhere it hesitated, misread the skill, or did something unexpected.
3. Re-read the draft/rewrite against GLOSSARY.md's failure modes in light of that run, and fix whatever either pass turned up. If the fix is substantial, repeat from step 1; otherwise it's done.
4. Stage the specific changed or created paths — one path per file, never a wildcard — with the host project's own staging convention: plain `git add <path>` normally, or e.g. `dot add <path>` in this dotfiles setup (wrap as `fish -c "dot add <path>"` if the invoking shell isn't fish — `dot` is a fish function, not a binary on `$PATH`). Do not commit; that's left to the user.
Done when the subagent's run succeeded without confusion on the confirmed prompt, the checklist raised nothing outstanding, and every changed path is staged.

View File

@@ -1,47 +0,0 @@
# ADR Format
ADRs live in `.claude/adr/` and use sequential numbering: `0001-slug.md`, `0002-slug.md`, etc.
Create the `.claude/adr/` directory lazily — only when the first ADR is needed.
## Template
```md
# {Short title of the decision}
{1-3 sentences: what's the context, what did we decide, and why.}
```
That's it. An ADR can be a single paragraph. The value is in recording *that* a decision was made and *why* — not in filling out sections.
## Optional sections
Only include these when they add genuine value. Most ADRs won't need them.
- **Status** frontmatter (`proposed | accepted | deprecated | superseded by ADR-NNNN`) — useful when decisions are revisited
- **Considered Options** — only when the rejected alternatives are worth remembering
- **Consequences** — only when non-obvious downstream effects need to be called out
## Numbering
Scan `.claude/adr/` for the highest existing number and increment by one.
## When to offer an ADR
All three of these must be true:
1. **Hard to reverse** — the cost of changing your mind later is meaningful
2. **Surprising without context** — a future reader will look at the code and wonder "why on earth did they do it this way?"
3. **The result of a real trade-off** — there were genuine alternatives and you picked one for specific reasons
If a decision is easy to reverse, skip it — you'll just reverse it. If it's not surprising, nobody will wonder why. If there was no real alternative, there's nothing to record beyond "we did the obvious thing."
### What qualifies
- **Architectural shape.** "We're using a monorepo." "The write model is event-sourced, the read model is projected into Postgres."
- **Integration patterns between contexts.** "Ordering and Billing communicate via domain events, not synchronous HTTP."
- **Technology choices that carry lock-in.** Database, message bus, auth provider, deployment target. Not every library — just the ones that would take a quarter to swap out.
- **Boundary and scope decisions.** "Customer data is owned by the Customer context; other contexts reference it by ID only." The explicit no-s are as valuable as the yes-s.
- **Deliberate deviations from the obvious path.** "We're using manual SQL instead of an ORM because X." Anything where a reasonable reader would assume the opposite. These stop the next engineer from "fixing" something that was deliberate.
- **Constraints not visible in the code.** "We can't use AWS because of compliance requirements." "Response times must be under 200ms because of the partner API contract."
- **Rejected alternatives when the rejection is non-obvious.** If you considered GraphQL and picked REST for subtle reasons, record it — otherwise someone will suggest GraphQL again in six months.

View File

@@ -1,30 +0,0 @@
# CONTEXT.md Format
## Structure
```md
# {Context Name}
{One or two sentence description of what this context is and why it exists.}
## Language
**Order**:
{A one or two sentence description of the term}
_Avoid_: Purchase, transaction
**Invoice**:
A request for payment sent to a customer after delivery.
_Avoid_: Bill, payment request
**Customer**:
A person or organization that places orders.
_Avoid_: Client, buyer, account
```
## Rules
- **Be opinionated.** When multiple words exist for the same concept, pick the best one and list the others under `_Avoid_`.
- **Keep definitions tight.** One or two sentences max. Define what it IS, not what it does.
- **Only include terms specific to this project's context.** General programming concepts (timeouts, error types, utility patterns) don't belong even if the project uses them extensively. Before adding a term, ask: is this a concept unique to this context, or a general programming concept? Only the former belongs.
- **Group terms under subheadings** when natural clusters emerge. If all terms belong to a single cohesive area, a flat list is fine.

View File

@@ -1,56 +0,0 @@
---
name: domain-modeling
description: Build and sharpen a project's domain model. Use when the user wants to pin down domain terminology or a ubiquitous language, record an architectural decision, or when another skill needs to maintain the domain model.
---
# Domain Modeling
Actively build and sharpen the project's domain model as you design. This is the *active* discipline — challenging terms, inventing edge-case scenarios, and writing the glossary and decisions down the moment they crystallise. (Merely *reading* `.claude/CONTEXT.md` for vocabulary is not this skill — that's a one-line habit any skill can do. This skill is for when you're changing the model, not just consuming it.)
## File structure
```
/
├── .claude/
│ ├── CONTEXT.md
│ └── adr/
│ ├── 0001-event-sourced-orders.md
│ └── 0002-postgres-for-write-model.md
└── src/
```
Create files lazily — only when you have something to write. If no `.claude/CONTEXT.md` exists, create it when the first term is resolved. If no `.claude/adr/` exists, create it when the first ADR is needed.
## During the session
### Challenge against the glossary
When the user uses a term that conflicts with the existing language in `.claude/CONTEXT.md`, call it out immediately. "Your glossary defines 'cancellation' as X, but you seem to mean Y — which is it?"
### Sharpen fuzzy language
When the user uses vague or overloaded terms, propose a precise canonical term. "You're saying 'account' — do you mean the Customer or the User? Those are different things."
### Discuss concrete scenarios
When domain relationships are being discussed, stress-test them with specific scenarios. Invent scenarios that probe edge cases and force the user to be precise about the boundaries between concepts.
### Cross-reference with code
When the user states how something works, check whether the code agrees. If you find a contradiction, surface it: "Your code cancels entire Orders, but you just said partial cancellation is possible — which is right?"
### Update .claude/CONTEXT.md inline
When a term is resolved, update `.claude/CONTEXT.md` right there. Don't batch these up — capture them as they happen. Use the format in [CONTEXT-FORMAT.md](./CONTEXT-FORMAT.md).
`.claude/CONTEXT.md` should be totally devoid of implementation details. Do not treat `.claude/CONTEXT.md` as a spec, a scratch pad, or a repository for implementation decisions. It is a glossary and nothing else.
### Offer ADRs sparingly
Only offer to create an ADR when all three are true:
1. **Hard to reverse** — the cost of changing your mind later is meaningful
2. **Surprising without context** — a future reader will wonder "why did they do it this way?"
3. **The result of a real trade-off** — there were genuine alternatives and you picked one for specific reasons
If any of the three is missing, skip the ADR. Use the format in [ADR-FORMAT.md](./ADR-FORMAT.md).

View File

@@ -1,20 +0,0 @@
---
name: grill
description: Interview the user relentlessly about a plan or design, capturing the resolved terms and decisions into the project's domain model as you go if one exists. Use when the user wants to stress-test a plan before building, or uses any 'grill' trigger phrase.
---
Interview me relentlessly about every aspect of this plan or design. Walk down each branch of the design tree, resolving dependencies between decisions one by one, and give your recommended answer for each question. Keep going until every branch carries an explicit decision and no dependency between decisions is left open — not merely until it feels like "we understand each other."
Ask the questions one at a time, waiting for feedback on each before continuing. Asking several at once is bewildering.
If a question can be answered by exploring the codebase, explore the codebase instead of asking it.
**Never start implementation during or after the interview without an explicit instruction from the user.** This applies at every point — mid-interview and after the final question alike.
## Closing the interview
When every branch carries an explicit decision and no dependency is left open, produce a concise summary of all decisions reached, then stop and wait for the user's next instruction.
## Tracking the domain model as you go
If a `.claude/CONTEXT.md` file exists in the project, also run [`domain-modeling`](../domain-modeling/SKILL.md) alongside this interview: resolve each term into `.claude/CONTEXT.md` the moment it crystallizes, and offer an ADR using that skill's own criteria — hard to reverse, surprising without context, and the result of a real trade-off. If no `.claude/CONTEXT.md` exists, run the interview alone with no doc side effects.

View File

@@ -1,72 +0,0 @@
---
name: implement
description: Implement a task file produced by /to-tasks on its own branch, review it, close it out, and open a PR.
disable-model-invocation: true
---
Implement a task file end-to-end: branch, build it, review it, close it out, and open a PR.
## Process
### 1. Read the task file and check blockers
The user passes the path to a task file (`.claude/tasks/<NNNN>-slug.md`, as produced by `/to-tasks`) explicitly — don't infer one from context.
If the task's frontmatter has a `blocked-by` field, read each referenced task file and check for any unresolved `- [ ]` acceptance criterion. If any blocker isn't fully resolved, warn the user which one and why, and confirm before proceeding — don't refuse outright.
### 2. Sync `main` and branch off it
Switch to `main`, fast-forward it (`git pull --ff-only`), then create and switch to a branch named `task-<NNNN>-<slug>` — taken verbatim from the task file's basename, so `.claude/tasks/0003-issue-view-and-truncation.md` gives `task-0003-issue-view-and-truncation`.
Use whatever git invocation the project itself uses; a repo may wrap it.
Stop and ask the user before going further if:
- **The working tree has uncommitted changes.** Never stash them automatically.
- **`git pull --ff-only` fails.** Local `main` has diverged; report what diverged. Never `reset --hard`.
- **The task's `blocked-by` work isn't reachable from `main`.** The blocker's PR is likely unmerged; name it.
If the task branch already exists, switch to it and carry on — don't recreate it, and don't rebase it onto the freshly pulled `main`.
Always branch off `main`, never off a sibling task branch.
### 3. Implement
Build the work described in the task's "What to build" section, satisfying its acceptance criteria. ALWAYS use `/test-driven-development`, at the seams already agreed when the spec or task was written.
Run typechecking regularly, single test files regularly, and the full test suite once at the end.
### 4. Stage the changes
Stage (`git add`) each file you create or modify, specifically — not `git add -A` — so nothing untracked and unrelated gets swept in.
### 5. Review
Run `/review-uncommitted`, passing the task file itself as the spec source — it already links back to its parent spec via its `spec` frontmatter field, if any. Address anything it raises before moving on.
Keep its report — step 7 puts part of it in the PR.
### 6. Close out the task file
Mark every acceptance criterion `[x]` if satisfied or `[-]` if deliberately dropped, so none are left `[ ]`. Append a `## Implementation Notes` section explaining any deviations from the plan — dropped criteria (referencing which, and why), scope changes, decisions made mid-implementation, follow-ups worth flagging. Skip the section only if nothing deviated. Leave the `spec` and `blocked-by` frontmatter fields untouched — they're a permanent record, not a checklist to clear (see `to-tasks`'s `TASK-FORMAT.md`).
Stage the updated task file with the rest.
### 7. Commit, push, and open a PR
Make **one** commit for the whole task, code and task file together.
Match the repo's existing commit convention — read its recent history or its CLAUDE.md, don't assume one — and reference the task in the subject, e.g. `(task 0003)`.
Push the branch (`git push -u origin task-<NNNN>-<slug>`) and open a pull request against `main` with the repo's forge CLI: `tea` for Gitea, `gh` for GitHub.
Never base the PR on a sibling task branch.
Open it ready, not draft.
The PR body carries:
- The task file's path.
- A short summary of what was built, and any deviations — the same ones just written into `## Implementation Notes`.
- A `## Review` section: the `## Risk` block from step 5 verbatim (overall rating plus its six factor lines), then **only** the Standards and Spec findings left unaddressed, each with a one-line reason. Findings that were fixed are already in the diff; leave them out.
Don't ask for confirmation before pushing or opening the PR.
If the repo has no remote, stop after the commit and report that no PR was opened.
Stay on the task branch when done.
Report the branch name, the PR URL, and any unaddressed review findings.

View File

@@ -1,119 +0,0 @@
# 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 — {{repository 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` glossary, terms and exclusions alike. Concision is not an excuse to drift.
**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.

View File

@@ -1,68 +0,0 @@
---
name: improve-codebase
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
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:
- Run the `/codebase-design` skill 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 its terms exactly in every suggestion, per its glossary.
- The domain language in `.claude/CONTEXT.md` gives names to good seams; ADRs in `.claude/adr/` record decisions this command should not re-litigate.
## Process
### 1. Explore
Read the project's domain glossary (`.claude/CONTEXT.md`) and any ADRs in the area you're touching first.
Then use the Agent tool with `subagent_type=Explore` to walk every top-level module or directory in scope (the whole repository, or the area the user pointed you to) — even if only briefly for the ones that turn out clean. Within each, judge friction organically rather than against a rigid checklist:
- 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.
Zero candidates is a legitimate outcome for a genuinely clean area — but it has to follow from having looked, not from stopping early.
### 2. Present candidates as an HTML report
Write a self-contained HTML file to the OS temp directory so nothing lands in the repository. 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. Treat the open as best-effort: it's a no-op in a headless/sandboxed environment with no display server, so report the absolute path regardless of whether the open succeeded.
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 `.claude/CONTEXT.md` vocabulary for the domain, and the `/codebase-design` vocabulary for the architecture.** If `.claude/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, run `/grill` to walk the design tree with them — constraints, dependencies, the shape of the deepened module, what sits behind the seam, what tests survive.
Side effects happen inline as decisions crystallize — run `/domain-modeling` to keep the domain model current as you go, even if `.claude/CONTEXT.md` doesn't exist yet:
- **Naming a deepened module after a concept not in `.claude/CONTEXT.md`?** Add the term to `.claude/CONTEXT.md`. Create the file lazily if it doesn't exist.
- **Sharpening a fuzzy term during the conversation?** Update `.claude/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?** Run the `/codebase-design` skill and use its design-it-twice parallel sub-agent pattern.

View File

@@ -1,152 +0,0 @@
---
name: nbdev
description: nbdev conventions for notebooks — directives, cell structure, docments, tests, execution. Use for any .ipynb operation — including reads — in an nbdev project.
---
# nbdev
## Tool Preference
- Use the **Jupyter MCP** for all `.ipynb` operations — read, edit, insert, delete, execute
- Do **not** use the built-in `NotebookEdit` tool; it writes cell source as a single JSON string which breaks standard Jupyter formatting and produces noisy diffs
- Re-read the notebook before editing if it may have changed since your last read — cell indices/IDs can shift under concurrent edits (e.g. via JupyterLab's real-time collaboration), and editing by a stale index can hit the wrong cell
## nbdev Directives
Directives are comments at the top of a cell that control how nbdev processes it:
- `#| export` — include this cell in the exported Python module and in the docs
- `#| hide` — exclude this cell from both the module and the docs
- `#| hide_input` — show cell output in docs but hide the source code
- `#| default_exp module_name` — set which module this notebook exports to (second cell)
- `#| exporti` — export to module but do not show in docs (for internal helpers)
- `#| eval: false` — include in docs but do not execute during `nbdev-test`
Imports needed only for tests or examples should **not** be exported.
Never hand-edit the exported `.py` module files — they're build artifacts regenerated from the notebook by `nbdev_export`. All edits go through the source notebook in `nbs/`.
## Notebook Structure
Every notebook must follow this structure:
**Cell 1 — Markdown frontmatter:**
```markdown
# Module Title
> A one-line description of what this module does
```
The H1 becomes the page title in docs. The blockquote becomes the subtitle.
**Cell 2 — Default export:**
```python
#| default_exp module_name
```
**Body cells** — alternating between exported code, demonstrations, and markdown explanations (see Cell Structure below).
**Last cell:**
```python
#| hide
import nbdev; nbdev.nbdev_export()
```
Before declaring any notebook task complete, restart the kernel and run all cells top-to-bottom to verify it is fully reproducible.
## Cell Structure
Keep cells short. Each exported function gets its own cell, immediately followed by a demonstration. Do not write long functions with comments interspersed — split them into small separate cells with explanations and working examples after each.
The pattern per concept:
1. *(Optional)* A markdown cell explaining what comes next
2. A `#| export` code cell with the function
3. One or more plain code cells demonstrating usage
4. Assertions that double as tests
Example:
```python
#| export
def slugify(text: str) -> str:
"Convert text to a URL-safe slug"
return re.sub(r"[^a-z0-9]+", "-", text.lower()).strip("-")
```
```python
slug = slugify("Hello, World!")
assert slug == "hello-world"
slug
```
## Docstrings and Parameter Documentation
Keep docstrings short — a single-line summary is sufficient for most functions. Elaborate in separate markdown or code cells below, where you can use real examples.
Use **docments** (inline parameter comments) instead of verbose docstring parameter sections:
```python
#| export
def greet(
name: str, # Person to greet
greeting: str="Hi", # Greeting word to use
) -> str: # The composed greeting
"Compose a greeting for name"
return f"{greeting}, {name}!"
```
This renders as a clean parameter table in the docs automatically — no need to repeat type information in the docstring body.
Use backticks around symbol names in docstrings and markdown — nbdev automatically converts these to hyperlinks to the relevant reference page.
## Code Style
- **Prefer composition**: write small functions that do one thing well
- Each exported function should be focused enough to fit naturally in a single notebook cell — one cell, one idea
- Use type hints on all exported functions
- Avoid classes unless state is genuinely needed — prefer functions that take and return data
- If you do write a class, use `fastcore`'s `@patch` decorator to define each method in its own cell, immediately followed by a demonstration. This avoids long class definitions and keeps examples close to the code
When a class is needed, document its methods with `show_doc`:
```python
from nbdev.showdoc import show_doc
show_doc(MyClass.my_method)
```
## Tests
Every code cell is run as a test by nbdev unless explicitly marked otherwise — any exception fails the test.
- Turn demonstrations into tests by adding `assert` statements
- Use `fastcore.test` helpers for better error messages:
```python
from fastcore.test import test_eq, test_fail
test_eq(slugify("Hello World"), "hello-world")
```
- Document expected error cases with `test_fail`:
```python
test_fail(lambda: slugify(""), contains="empty")
```
- Each test/demo cell should import what it needs directly — don't rely on a name imported in a later cell just because it happened to be in scope during a prior run
## Execution
- Always execute cells after writing them to verify they work
- If a cell errors, read the full traceback before attempting a fix — do not guess
- When installing packages, use `%pip install` inside the notebook (not `!pip install`) so they install into the running kernel
- Use autoreload at the top of notebooks that import from other modules in the project:
```python
%load_ext autoreload
%autoreload 2
```
## Documentation
- Use H2 (`##`) markdown cells to group related symbols within a notebook
- Use H4 (`####`) markdown cells to split long explanations within a symbol's section (notes, examples, edge cases, etc.)
- Add rich representations to classes via `_repr_markdown_` where it aids understanding
- Include real code examples, plots, and diagrams — notebooks support rich output, use it
## Outputs
- Never print secrets, tokens, passwords, or API keys into cell output — notebook outputs get committed to git and published in docs, unlike transient script output
- Prefer summaries over dumping large data structures (`.head()`, `len()`, `[:5]`, etc.)
- Large outputs consume context window — keep them concise

View File

@@ -1,37 +0,0 @@
---
name: remove-skills
description: Remove one or more previously added library skills from the current project.
disable-model-invocation: true
---
Removes a skill that [`setup-skills`](../setup-skills/SKILL.md) previously
copied into the current project, deleting both its files and its entry in
`.claude/skills-lock.yaml` (see [LOCKFILE.md](../setup-skills/LOCKFILE.md)
for its schema).
## Steps
1. Read `.claude/skills-lock.yaml`. If it doesn't exist or is empty, tell
the user there's nothing installed to remove and stop.
2. Determine which skill(s) to remove:
- If the user's invocation already named a specific skill, use that —
if it isn't in the lockfile, say so and stop.
- Otherwise, list every skill currently in the lockfile and ask the
user to pick one (or more).
3. For each skill to remove, compute its current hash
(`~/.claude/skills/setup-skills/hash-dir.sh .claude/skills/<name>`)
and compare it to the hash stored in the lockfile:
- If it matches (never modified since it was installed), delete
`.claude/skills/<name>/` and remove its lockfile entry immediately —
no confirmation needed, since nothing of the user's is being lost.
- If it differs (locally customized), tell the user it has local
changes that will be permanently lost and ask for confirmation
before deleting. If they decline, leave that skill installed and
move on to the next.
4. Finish with a summary of what was removed and what was left in place.
Done when every skill to remove has been either deleted (with its lockfile
entry removed) or explicitly left in place with a stated reason.

View File

@@ -1,147 +0,0 @@
---
name: review-uncommitted
description: Review the working tree's uncommitted changes along three axes — change risk, repo standards, and spec fidelity — using parallel sub-agents.
---
Three-axis review of the diff between `HEAD` and the working tree:
- **Risk** — how much attention does this change warrant, from low to high?
- **Standards** — does the code conform to this repo's documented coding standards?
- **Spec** — does the code faithfully implement the originating PRD or task file?
All three axes run as **parallel sub-agents** so they don't pollute each other's context, then this skill aggregates their findings.
## Process
### 1. Capture the diff
The diff command is `git diff HEAD` — everything uncommitted, staged or not.
New files must already be tracked (`git add`ed) to show up; this skill doesn't scan for untracked files, so that's the caller's responsibility.
Confirm the diff is non-empty before going further.
An empty diff should fail here — not inside three parallel sub-agents.
### 2. Identify the spec source
Look for the originating spec, in this order:
1. A path the user passed as an argument.
2. A spec file matching the branch name or feature — `.claude/spec/<feature-slug>.md`.
3. If nothing is found, ask the user where the spec is.
If they say there isn't one, the **Spec** sub-agent will skip and report "no spec available".
### 3. Identify the standards sources
Anything in the repo that documents how code should be written, such as `CODING_STANDARDS.md` or `CONTRIBUTING.md`.
On top of whatever the repo documents, the Standards axis always carries the **smell baseline** below — a fixed set of Fowler code smells (_Refactoring_, ch.3) that applies even when a repo documents nothing.
Two rules bind it:
- **The repo overrides.**
A documented repo standard always wins; where it endorses something the baseline would flag, suppress the smell.
- **Always a judgement call.**
Each smell is a labelled heuristic ("possible Feature Envy"), never a hard violation — and, like any standard here, skip anything tooling already enforces.
Each smell reads *what it is**how to fix*; match it against the diff:
- **Mysterious Name** — a function, variable, or type whose name doesn't reveal what it does or holds.
→ rename it; if no honest name comes, the design's murky.
- **Duplicated Code** — the same logic shape appears in more than one hunk or file in the change.
→ extract the shared shape, call it from both.
- **Feature Envy** — a method that reaches into another object's data more than its own.
→ move the method onto the data it envies.
- **Data Clumps** — the same few fields or params keep travelling together (a type wanting to be born).
→ bundle them into one type, pass that.
- **Primitive Obsession** — a primitive or string standing in for a domain concept that deserves its own type.
→ give the concept its own small type.
- **Repeated Switches** — the same `switch`/`if`-cascade on the same type recurs across the change.
→ replace with polymorphism, or one map both sites share.
- **Shotgun Surgery** — one logical change forces scattered edits across many files in the diff.
→ gather what changes together into one module.
- **Divergent Change** — one file or module is edited for several unrelated reasons.
→ split so each module changes for one reason.
- **Speculative Generality** — abstraction, parameters, or hooks added for needs the spec doesn't have.
→ delete it; inline back until a real need shows.
- **Message Chains** — long `a.b().c().d()` navigation the caller shouldn't depend on.
→ hide the walk behind one method on the first object.
- **Middle Man** — a class or function that mostly just delegates onward.
→ cut it, call the real target direct.
- **Refused Bequest** — a subclass or implementer that ignores or overrides most of what it inherits.
→ drop the inheritance, use composition.
### 4. Risk rubric
The Risk axis judges the diff alone — no repo-doc lookup, no input from the Standards or Spec sub-agents.
It always runs; it only needs the diff from step 1.
Rate each of these six factors **Low / Medium / High**, then take the single highest-rated factor as the overall rating (worst-factor-wins):
- **Blast radius** — isolated change vs. ripples across many files, modules, or callers.
- **Reversibility** — trivial rollback vs. hard to undo (migrations, deletions, published API/schema changes).
- **Test coverage** — covered by tests in/around the diff vs. untested.
- **Sensitive domain** — touches auth, security, payments, permissions, concurrency, or data migrations.
- **Size & complexity** — large diff or tangled control flow vs. small/simple.
- **Runtime criticality** — hot path/production-critical vs. internal or dev-only tooling.
### 5. Spawn all three sub-agents in parallel
Send a single message with three `Agent` tool calls.
Use the `general-purpose` subagent for all three.
**Risk sub-agent prompt** — include:
- The full diff (output of `git diff HEAD`).
- The six risk factors from step 4, pasted in full.
- The brief: "Rate each of the six factors Low/Medium/High with a one-clause reason, then give the overall rating as the highest of the six.
Report the overall rating first, then the six factor lines.
Under 200 words."
**Standards sub-agent prompt** — include:
- The full diff (output of `git diff HEAD`).
- The list of standards-source files you found in step 3, **plus the smell baseline from step 3** pasted in full — the sub-agent has no other access to it.
- The brief: "Report — per file/hunk where relevant — (a) every place the diff violates a documented standard: cite the standard (file + the rule); and (b) any baseline smell you spot: name it and quote the hunk.
Distinguish hard violations from judgement calls — documented-standard breaches can be hard, but baseline smells are always judgement calls, and a documented repo standard overrides the baseline.
Skip anything tooling enforces.
Under 400 words."
**Spec sub-agent prompt** — include:
- The full diff (output of `git diff HEAD`).
- The path or fetched contents of the spec.
- The brief: "Report: (a) requirements the spec asked for that are missing or partial; (b) behaviour in the diff that wasn't asked for (scope creep); (c) requirements that look implemented but where the implementation looks wrong.
Quote the spec line for each finding.
Under 400 words."
If the spec is missing, skip the Spec sub-agent and note this in the final report.
### 6. Aggregate
Present the Risk report first, under a `## Risk` heading, with the overall rating bolded on its own line followed by the six factor lines:
```
## Risk
**Overall: HIGH**
- Blast radius: ...
- Reversibility: ...
- Test coverage: ...
- Sensitive domain: ...
- Size & complexity: ...
- Runtime criticality: ...
```
Then present the Standards and Spec reports under `## Standards` and `## Spec` headings, verbatim or lightly cleaned.
Do **not** merge or rerank findings — the axes are deliberately separate (see _Why Standards and Spec stay separate_).
End with a one-line summary: total findings per axis (Standards/Spec only), and the worst issue _within each axis_ (if any).
Don't pick a single winner across axes — that's the reranking the separation exists to prevent.
The risk rating isn't repeated here; it already leads the report.
## Why Standards and Spec stay separate
A change can pass one axis and fail the other:
- Code that follows every standard but implements the wrong thing → **Standards pass, Spec fail.**
- Code that does exactly what the PRD or task asked but breaks the project's conventions → **Spec pass, Standards fail.**
Reporting them separately stops one axis from masking the other.

View File

@@ -1,53 +0,0 @@
# Skills Lockfile
`.claude/skills-lock.yaml`, at the root of a project, tracks which library
skills (from `~/.claude/skills/library/`) have been copied into that
project's `.claude/skills/`, so [`setup-skills`](SKILL.md),
[`update-skills`](../update-skills/SKILL.md), and
[`remove-skills`](../remove-skills/SKILL.md) all agree on what's installed
without re-deriving it from the filesystem.
## Schema
A YAML list of entries, one per installed skill:
```yaml
- name: nbdev
hash: 3f2a9b8c1d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0c1d2e3f4a5b6c7d8e9f0a
- name: terraform-conventions
hash: 9c1d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0c1d2e3f4a5b6c7d8e9f0a3f2a9b
```
- `name` — matches both the skill's directory name in the library
(`skills/library/<name>`) and its copied directory name in the project
(`.claude/skills/<name>`).
- `hash` — the output of `hash-dir.sh` run against that one skill's
directory contents, recorded at the moment it was last copied or
confirmed up to date. Never a hash of anything else — not the whole
project, not the whole library, just that one skill's own directory
tree.
## What a mismatch means
To classify a skill's state, compare three values: the lockfile's stored
`hash`, `hash-dir.sh` on the project's current copy
(`.claude/skills/<name>`), and `hash-dir.sh` on the library's current
source (`~/.claude/skills/library/<name>`).
| stored vs. project copy | stored vs. library source | meaning |
|--------------------------|----------------------------|--------------------------------------|
| match | match | nothing to do |
| match | differs | library moved on — safe to update |
| differs | match | project customized on purpose — leave it |
| differs | differs | conflict — report, don't touch |
## Writing to the lockfile
- Adding a skill: append a new `{name, hash}` entry.
- Applying a safe update: overwrite that entry's `hash` in place with the
library's current hash.
- Removing a skill: delete its entry entirely.
Never reorder or restructure existing entries beyond what an add, update,
or remove requires — this file is meant to diff cleanly in a project's
git history.

View File

@@ -1,46 +0,0 @@
---
name: setup-skills
description: Add relevant skills from the shared skills library to the current project.
disable-model-invocation: true
---
Adds opt-in, project-specific skills from `~/.claude/skills/library/` into
the current project's `.claude/skills/`, tracked in
`.claude/skills-lock.yaml` (see [LOCKFILE.md](LOCKFILE.md) for its schema).
Only ever adds — checking already-installed skills for updates is
[`update-skills`](../update-skills/SKILL.md)'s job, not this one's.
## Steps
1. Read `.claude/skills-lock.yaml` in the current project, if it exists.
Note every skill name already listed — these are already installed and
must not be re-proposed.
2. List every skill under `~/.claude/skills/library/*/SKILL.md` and read
each one's `name` and `description`.
3. Inspect the current project (file tree, manifests like
`pyproject.toml`/`package.json`, file extensions present, etc.) and
judge which library skills — excluding ones already installed — seem
relevant, the same way you'd reason about any unfamiliar codebase.
Propose that shortlist to the user with your reasoning, one line per
skill. If the user asks to see the full catalog instead, list every
library skill (minus already-installed ones) with its description.
4. Let the user confirm, adjust, or pick freely from the full list.
5. For each confirmed skill:
- If `.claude/skills/<name>/` already exists in the project and is
*not* in the lockfile, skip it and tell the user why (a same-named
skill already lives there and isn't tracked — remove or rename it
first if they want the library version).
- Otherwise, copy `~/.claude/skills/library/<name>/` to
`.claude/skills/<name>/` in the project, run
`~/.claude/skills/setup-skills/hash-dir.sh .claude/skills/<name>`,
and append `{name, hash: <output>}` to `.claude/skills-lock.yaml`
(create the file, an empty YAML list, if it doesn't exist yet).
6. Report what was added and what was skipped, and why.
Done when every confirmed skill is either copied and recorded in the
lockfile, or explicitly skipped with a stated reason.

View File

@@ -1,23 +0,0 @@
#!/usr/bin/env bash
# Deterministic recursive hash of a directory's file contents.
#
# Hashes relative paths, not absolute ones, so two directories with
# identical contents hash identically regardless of where they live on
# disk (needed to compare a project's copied skill against the library
# source it was copied from).
#
# Usage: hash-dir.sh <directory>
set -euo pipefail
if [ $# -ne 1 ]; then
echo "Usage: hash-dir.sh <directory>" >&2
exit 1
fi
dir="$1"
if [ ! -d "$dir" ]; then
echo "Not a directory: $dir" >&2
exit 1
fi
(cd "$dir" && find . -type f -print0 | sort -z | xargs -0 -r sha256sum) | sha256sum | awk '{print $1}'

View File

@@ -1,153 +0,0 @@
---
name: test-driven-development
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
## Philosophy
**Core principle**: Tests should verify behavior through public interfaces, not implementation details. Code can change entirely; tests shouldn't.
**Good tests** are integration-style: they exercise real code paths through public APIs. They describe _what_ the system does, not _how_ it does it. A good test reads like a specification - "user can checkout with valid cart" tells you exactly what capability exists. These tests survive refactors because they don't care about internal structure.
**Bad tests** are coupled to implementation. They mock internal collaborators, test private methods, or verify through external means (like querying a database directly instead of using the interface). The warning sign: your test breaks when you refactor, but behavior hasn't changed. If you rename an internal function and tests fail, those tests were testing implementation, not behavior.
**Tautological tests** restate the implementation inside the assertion, so they pass by construction and give zero confidence. When the expected value is computed the way the code computes it — `expect(add(a, b)).toBe(a + b)`, snapshotting a figure you derived by hand the same way the code does, asserting a constant equals itself — the test can never disagree with the code: break the code wrong and the assertion breaks wrong with it. The expected value must come from an independent source of truth — a known-good literal, a worked example, the spec.
See [tests.md](tests.md) for examples and [mocking.md](mocking.md) for mocking guidelines.
## Anti-Pattern: Horizontal Slices
**DO NOT write all tests first, then all implementation.** This is "horizontal slicing" - treating RED as "write all tests" and GREEN as "write all code."
This produces **crap tests**:
- Tests written in bulk test _imagined_ behavior, not _actual_ behavior
- You end up testing the _shape_ of things (data structures, function signatures) rather than user-facing behavior
- Tests become insensitive to real changes - they pass when behavior breaks, fail when behavior is fine
- You outrun your headlights, committing to test structure before understanding the implementation
**Correct approach**: Vertical slices via tracer bullets. One test → one implementation → repeat. Each test responds to what you learned from the previous cycle.
The test-writer sub-agent (below) is handed **one behavior at a time** and never sees the behavior backlog, so it can't bulk-write the suite.
```
WRONG (horizontal):
RED: test1, test2, test3, test4, test5
GREEN: impl1, impl2, impl3, impl4, impl5
RIGHT (vertical):
RED→GREEN: test1→impl1
RED→GREEN: test2→impl2
RED→GREEN: test3→impl3
...
```
## Roles
Every test is written by a **test-writer sub-agent**. The main agent writes every line of implementation, and never writes or edits a test.
The sub-agent must not read the implementation source of the module under test — that is what keeps its tests from asserting _how_ instead of _what_. It works from the public interface alone.
Use one `general-purpose` sub-agent for the whole task: spawn it at the first RED, then continue it with `SendMessage` for each subsequent RED, so it keeps the test file and conventions it established. Cold-spawn a replacement only if its ID is lost.
### Test-writer sub-agent prompt — include:
- **One behavior**, quoted verbatim from the acceptance criterion or the agreed behavior list. Never the task file, never the rest of the list.
- The **public interface** under test — signatures only.
- The existing test file(s) for the module, and the project's test conventions (fixtures, helpers, runner invocation).
- [tests.md](tests.md) and [mocking.md](mocking.md).
- The **independent source of truth for the expected value** — the spec excerpt, worked example, or known-good literal. Without it the sub-agent recomputes the expected value the way the code would, and the test is tautological.
- `.claude/CONTEXT.md` (if it exists) and any ADRs in the area, so test names and interface vocabulary match the project's domain language.
- The test-side checklist from [Checklist Per Cycle](#checklist-per-cycle), pasted in full — the sub-agent has no other access to it.
- The brief: "Write ONE test for this behavior. Do not read the implementation source of the module under test. Write it to the test file, run it, and confirm it fails with a genuine assertion failure — not an import, syntax, or collection error, which prove nothing. Report the test's name and the exact failure message you saw."
## Workflow
### 1. Planning
When exploring the codebase, read `.claude/CONTEXT.md` (if it exists) so that test names and interface vocabulary match the project's domain language, and respect ADRs in the area you're touching.
Identify opportunities for deep modules (small interface, deep implementation) — run the `/codebase-design` skill for the vocabulary and the testability checks. Do this regardless of what triggered this workflow.
**If a task file is already in context** (e.g. passed to `/implement`, which called this skill), its acceptance criteria are the behavior list to test — the interface and priorities were already agreed during `/to-spec` and `/to-tasks`. Don't re-confirm them with the user; go straight to the tracer bullet.
**Otherwise**, before writing any code:
- [ ] Confirm with user what interface changes are needed
- [ ] Confirm with user which behaviors to test (prioritize)
- [ ] List the behaviors to test (not implementation steps)
- [ ] Get user approval on the plan
Ask: "What should the public interface look like? Which behaviors are most important to test?"
**You can't test everything.** Confirm with the user exactly which behaviors matter most. Focus testing effort on critical paths and complex logic, not every possible edge case.
Planning stays with the main agent on both paths — exploration, interface, and the order behaviors are tested in. The sub-agent receives behaviors one at a time; it never chooses what to test next.
### 2. Tracer Bullet
ONE test that confirms ONE thing about the system:
```
RED: Spawn the test-writer sub-agent with the first behavior → it writes the test, runs it, reports a genuine failure
GREEN: Main agent writes minimal code to pass → test passes
```
This is your tracer bullet - proves the path works end-to-end.
### 3. Incremental Loop
For each remaining behavior:
```
RED: SendMessage the same sub-agent the next behavior → it writes the test, runs it, reports a genuine failure
GREEN: Main agent writes minimal code to pass → passes
```
Rules:
- One test at a time
- Only enough code to pass current test
- Don't anticipate future tests
- Keep tests focused on observable behavior
### When a test looks wrong
The main agent never edits a sub-agent-authored test — not to fix an import, not to "simplify" an assertion, not to reach GREEN.
- **Mechanical defect** — bad import path, a fixture or helper that doesn't exist, doesn't parse. Send the error output back to the sub-agent and let it fix its own test.
- **Semantic disagreement** — you believe the expected value or the asserted behavior is wrong. Stop and ask the user. Do not resolve it yourself; this disagreement is the signal the sub-agent exists to surface, and half the time it's the code that's wrong.
### 4. Refactor
After all tests pass, look for [refactor candidates](refactoring.md):
- [ ] Extract duplication
- [ ] Deepen modules (move complexity behind simple interfaces)
- [ ] Apply SOLID principles where natural
- [ ] Consider what new code reveals about existing code
- [ ] Run tests after each refactor step
**Never refactor while RED.** Get to GREEN first.
A test that breaks during refactor means the refactor broke behavior — fix the code. The one exception is a public interface change you made deliberately (a module deepened, a signature moved, as agreed in the plan): send the interface change to the sub-agent and let it update its own tests. There is no case where the main agent edits the test itself.
## Checklist Per Cycle
Test-writer sub-agent, per test — paste into its prompt:
```
[ ] Test describes behavior, not implementation
[ ] Test uses public interface only
[ ] Test would survive internal refactor
[ ] Expected values are independent literals, not recomputed from the code
```
Main agent, per GREEN:
```
[ ] Code is minimal for this test
[ ] No speculative features added
```

View File

@@ -1,59 +0,0 @@
# 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

View File

@@ -1,10 +0,0 @@
# Refactor Candidates
After TDD cycle, look for:
- **Duplication** → Extract function/class
- **Long methods** → Break into private helpers (keep tests on public interface)
- **Shallow modules** → Combine or deepen — see DEEPENING.md in `/codebase-design` for dependency categories and seam discipline
- **Feature envy** → Move logic to where data lives
- **Primitive obsession** → Introduce value objects
- **Existing code** the new code reveals as problematic

View File

@@ -1,77 +0,0 @@
# 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);
});
```

View File

@@ -1,21 +0,0 @@
---
name: to-spec
description: Turn the current conversation into a spec and write it to .claude/spec/ — no interview, just synthesis of what you've already discussed.
disable-model-invocation: true
---
This skill takes the current conversation context and codebase understanding and produces a spec. Do NOT interview the user — just synthesize what you already know.
If the conversation doesn't actually contain a feature or problem to synthesize a spec from, say so and ask what it's for instead of fabricating one.
## Process
1. Explore the repo until you can name the existing modules, flows, and seams the feature will touch, if you haven't already. Use the project's domain glossary vocabulary throughout the spec, and respect any ADRs in the area you're touching.
2. Sketch out the seams at which you're going to test the feature. Existing seams should be preferred to new ones. Use the highest seam possible. If new seams are needed, propose them at the highest point you can. The fewer seams across the codebase, the better - the ideal number is one.
Check with the user that these seams match their expectations.
3. Derive a short kebab-case feature-slug from the feature's name (e.g. `checkout-flow`). Tell the user the path you're about to write to (`.claude/spec/<feature-slug>.md`). If a file already exists there, summarize what would change and confirm with the user before overwriting it — never overwrite silently.
4. Write the spec using the format in [SPEC-FORMAT.md](./SPEC-FORMAT.md) to `.claude/spec/<feature-slug>.md`, creating the `.claude/spec/` directory if it doesn't exist yet.

View File

@@ -1,55 +0,0 @@
# Spec Format
## Template
```md
## Problem Statement
The problem that the user is facing, from the user's perspective.
## Solution
The solution to the problem, from the user's perspective.
## User Stories
An extensive, numbered list of user stories, covering all aspects of the feature. Each user story should be in the format of:
1. As an <actor>, I want a <feature>, so that <benefit>
<user-story-example>
1. As a mobile bank customer, I want to see balance on my accounts, so that I can make better informed decisions about my spending
</user-story-example>
## Implementation Decisions
A list of implementation decisions that were made. This can include:
- The modules that will be built/modified
- The interfaces of those modules that will be modified
- Technical clarifications from the developer
- Architectural decisions
- Schema changes
- API contracts
- Specific interactions
## Testing Decisions
A list of testing decisions that were made. Include:
- A description of what makes a good test (only test external behavior, not implementation details)
- Which modules will be tested
- Prior art for the tests (i.e. similar types of tests in the codebase)
## Out of Scope
A description of the things that are out of scope for this spec.
## Further Notes
Any further notes about the feature.
```
## Rules
- **Don't include specific file paths or code snippets.** They may end up being outdated very quickly. Exception: if a prototype produced a snippet that encodes a decision more precisely than prose can (state machine, reducer, schema, type shape), inline it within the relevant decision in Implementation Decisions and note briefly that it came from a prototype. Trim to the decision-rich parts — not a working demo, just the important bits.

View File

@@ -1,57 +0,0 @@
---
name: to-tasks
description: Break a plan or spec into independently-grabbable task files under .claude/tasks/ using tracer-bullet vertical slices.
disable-model-invocation: true
---
# To Tasks
## Process
### 1. Gather context
Work from whatever is already in the conversation context. If the user passes a spec path or other reference as an argument, read it directly.
Determine the feature-slug this breakdown belongs to, if any: if a spec file is in context or was passed as an argument, derive it from the filename (`.claude/spec/<feature-slug>.md``<feature-slug>`) for each task's `spec` field — see [TASK-FORMAT.md](./TASK-FORMAT.md) for the field's rules. If no spec file exists, proceed without one.
### 2. Explore the codebase (optional)
If you have not already explored the codebase, do so to understand the current state of the code. Task titles and descriptions should use the project's domain glossary vocabulary, and respect ADRs in the area you're touching.
Look for opportunities to prefactor the code to make the implementation easier. "Make the change easy, then make the easy change."
### 3. Draft vertical slices
Break the plan into **tracer bullet** tasks — vertical slices, not horizontal layers.
<vertical-slice-rules>
- Each slice delivers a narrow but COMPLETE path through every layer the change requires (schema, API, UI, tests), never a horizontal slice of just one
- A completed slice is demoable or verifiable on its own
- Any prefactoring should be done first
</vertical-slice-rules>
### 4. Quiz the user
Number slices with a single sequence shared across every file already in `.claude/tasks/`: scan for the highest existing `NNNN` (four-digit, zero-padded decimal, `0000`-`9999`) and increment from there. Never restart the sequence per feature and never reuse a number.
Present the proposed breakdown as a numbered list. For each slice, show:
- **File**: the `NNNN-slice-slug` it will be written as, per the numbering above
- **Blocked by**: which other slices (if any) must complete first — "None" if it can start immediately
- **User stories covered**: which user stories this addresses (if the source material has them)
Ask the user:
- Does the granularity feel right? (too coarse / too fine)
- Are the dependency relationships correct?
- Should any slices be merged or split further?
Iterate until the user approves the breakdown, including the proposed numbers and slugs.
### 5. Write the task files
For each approved slice, write a file to `.claude/tasks/<NNNN>-<slice-slug>.md` (create the directory if it doesn't exist) using the numbers and slugs approved in step 4. Use the template in [TASK-FORMAT.md](./TASK-FORMAT.md).
Do NOT modify the parent spec file (`.claude/spec/<feature-slug>.md`) when writing tasks.

View File

@@ -1,28 +0,0 @@
# Task Format
## Template
```md
---
spec: <feature-slug>
blocked-by: <slice-slug-or-list>
---
## What to build
A concise description of this vertical slice. Describe the end-to-end behavior, not layer-by-layer implementation.
## Acceptance criteria
- [ ] Criterion 1
- [ ] Criterion 2
- [ ] Criterion 3
```
## Rules
- **`spec`**: the feature-slug this task was written from. Omit the field entirely if there's no spec.
- **`blocked-by`**: which other task(s) must complete before this one can start. Omit the field entirely if there are none. Each value is the blocking task's full `<NNNN>-<slice-slug>` filename stem, not just its slug. A single blocker is a bare string (`blocked-by: 0010-add-schema`); more than one is a YAML list (`blocked-by: [0010-add-schema, 0011-wire-api]`). Once written, keep the field even after the referenced task is completed — it's a permanent record of the dependency, not a "still blocked" flag.
- **Don't include specific file paths or code snippets** in "What to build" — they go stale fast. Exception: if a prototype produced a snippet that encodes a decision more precisely than prose can (state machine, reducer, schema, type shape), inline it here and note briefly that it came from a prototype. Trim to the decision-rich parts — not a working demo, just the important bits.
- A task is done when every criterion in "Acceptance criteria" is resolved: mark `[x]` as satisfied, or `[-]` if deliberately dropped (`/implement` records the reason in the task's Implementation Notes) — track completion here, not anywhere else.
- A slice becomes pickable once every task named in `blocked-by` is done (all of its acceptance criteria resolved) — check the referenced tasks' state, not just whether the field is present. The file's number is an identifier and a rough ordering hint, not a strict gate — sibling slices with no blockers can be worked in parallel.

View File

@@ -1,52 +0,0 @@
---
name: update-skills
description: Check the current project's installed library skills for upstream changes and apply the safe ones.
disable-model-invocation: true
---
Compares every skill listed in the current project's
`.claude/skills-lock.yaml` (see [LOCKFILE.md](../setup-skills/LOCKFILE.md)
for its schema) against both the project's own copy and the current
library source, and decides what to do about each one. Never installs a
skill that isn't already there — that's
[`setup-skills`](../setup-skills/SKILL.md)'s job.
## Steps
1. Read `.claude/skills-lock.yaml`. If it doesn't exist or is empty, tell
the user there's nothing to check and stop.
2. For each `{name, hash}` entry, compute:
- `project_hash`: `~/.claude/skills/setup-skills/hash-dir.sh .claude/skills/<name>`
- `library_hash`: `~/.claude/skills/setup-skills/hash-dir.sh ~/.claude/skills/library/<name>`
If either path is missing entirely, report that anomaly for this skill
(don't try to classify it) and move on to the next entry.
3. Classify each entry against the table in
[LOCKFILE.md](../setup-skills/LOCKFILE.md#what-a-mismatch-means),
using `project_hash` in place of "project copy" and `library_hash` in
place of "library source". The two outcomes that need action below are
**safe update** (stored matches project, differs from library) and
**conflict** (stored differs from both). "Locally customized" needs no
message beyond the summary.
4. If there are any safe updates, list them by name and ask for one
confirmation to apply all of them — unless the user's invocation
already included an explicit go-ahead argument (e.g. `-y`, `yes`), in
which case apply them without asking. Applying means: delete
`.claude/skills/<name>/` entirely and copy
`~/.claude/skills/library/<name>/` in its place, so no file the project
copy had but the library no longer has can survive — then recompute its
hash and overwrite that entry's `hash` in `.claude/skills-lock.yaml` in
place.
5. For every conflict, report it and show a recursive diff between the
project's copy and the library's current version
(`diff -ru .claude/skills/<name> ~/.claude/skills/library/<name>`).
Do not modify the project's copy or the lockfile entry for a
conflicted skill under any circumstances — surfacing it is the whole
job here.
6. Finish with a summary: updated, left alone (customized), conflicted,
already current, and any anomalies from step 2.

View File

@@ -1,88 +0,0 @@
[general]
working_directory = "None"
live_config_reload = true
[env]
TERM = "xterm-256color"
WINIT_X11_SCALE_FACTOR = "1.0"
[window]
dimensions = { columns = 100, lines = 30 }
dynamic_padding = true
decorations = "Full"
opacity = 0.8
title = "Alacritty@CachyOS"
class = { instance = "Alacritty", general = "Alacritty" }
decorations_theme_variant = "Dark"
[scrolling]
history = 10000
multiplier = 3
[font]
normal = { family = "MesloLGS Nerd Font Mono", style = "Regular" }
bold = { family = "MesloLGS Nerd Font Mono", style = "Bold" }
italic = { family = "MesloLGS Nerd Font Mono", style = "Italic" }
bold_italic = { family = "MesloLGS Nerd Font Mono", style = "Bold Italic" }
size = 12.0
[colors]
draw_bold_text_with_bright_colors = true
[colors.primary]
background = "0x2E3440"
foreground = "0xD8DEE9"
[colors.normal]
black = "0x3B4252"
red = "0xBF616A"
green = "0xA3BE8C"
yellow = "0xEBCB8B"
blue = "0x81A1C1"
magenta = "0xB48EAD"
cyan = "0x88C0D0"
white = "0xE5E9F0"
[colors.bright]
black = "0x4C566A"
red = "0xBF616A"
green = "0xA3BE8C"
yellow = "0xEBCB8B"
blue = "0x81A1C1"
magenta = "0xB48EAD"
cyan = "0x8FBCBB"
white = "0xECEFF4"
[selection]
semantic_escape_chars = ",│`|:\"' ()[]{}<>\t"
save_to_clipboard = true
[cursor]
style = { shape = "Underline", blinking = "Off" }
unfocused_hollow = true
thickness = 0.15
[mouse]
hide_when_typing = true
bindings = [
{ mouse = "Middle", mods = "None", action = "PasteSelection" },
]
[keyboard]
bindings = [
{ key = "Paste", mods = "None", action = "Paste" },
{ key = "Copy", mods = "None", action = "Copy" },
{ key = "L", mods = "Control", action = "ClearLogNotice" },
{ key = "L", mods = "Control", mode = "~Vi", chars = "\f" },
{ key = "PageUp", mods = "Shift", mode = "~Alt", action = "ScrollPageUp" },
{ key = "PageDown", mods = "Shift", mode = "~Alt", action = "ScrollPageDown" },
{ key = "Home", mods = "Shift", mode = "~Alt", action = "ScrollToTop" },
{ key = "End", mods = "Shift", mode = "~Alt", action = "ScrollToBottom" },
{ key = "V", mods = "Control|Shift", action = "Paste" },
{ key = "C", mods = "Control|Shift", action = "Copy" },
{ key = "F", mods = "Control|Shift", action = "SearchForward" },
{ key = "B", mods = "Control|Shift", action = "SearchBackward" },
{ key = "C", mods = "Control|Shift", mode = "Vi", action = "ClearSelection" },
{ key = "Key0", mods = "Control", action = "ResetFontSize" },
]

View File

@@ -1 +0,0 @@
{"sessionId":"d1732179-27b7-49fb-82af-6669b783a444","pid":45537,"procStart":"7266197","acquiredAt":1783288905666}

View File

@@ -1,76 +0,0 @@
## Problem Statement
Several KDE settings on this machine have already been changed by hand away from their KDE/CachyOS defaults — the caps-lock/Escape swap is live right now, and screenshot-related keybind changes (Spectacle bindings, moving Lock Session off `Meta+L`) are planned next — but none of this is tracked anywhere in the dotfiles repo. If the machine were rebuilt today, these settings would silently revert to defaults with no record of what needs to be reapplied. There's also no way to notice *unexpected* drift (a setting that changed without the owner deliberately choosing to change it), and no tooling to bring a manually-tweaked setting under tracking without hand-writing one-off `kwriteconfig6`/D-Bus calls — exactly the accumulation of ad hoc scripts the dotfiles project has otherwise avoided.
## Solution
Add a `dot kde` subcommand family with three verbs:
- **`dot kde apply`** — pushes every setting declared in a tracked manifest onto the live KDE session (repo → system).
- **`dot kde diff`** — a broad, read-only scan reporting every live KDE setting that differs from its default, tagging each mismatch as either already-declared (in the manifest) or undeclared (system → discovery, no write).
- **`dot kde save`** — the write path into the manifest (system → repo). Run with no arguments, it refreshes every already-declared entry's stored value from the live system. Run with explicit coordinates, it begins tracking one new setting, seeded from its current live value.
The manifest is a single flat, mechanism-agnostic file: opaque `identifier=value` lines. `dot kde` internally figures out *how* to read/write a given identifier (three different underlying mechanisms exist across KDE's config surface), so the manifest itself never needs to know or care how KDE happens to store that particular setting.
## User Stories
1. As the machine owner, I want to declare that a KDE setting should have a specific value, so that a freshly-built machine ends up with the same intentional deviations from KDE's defaults without me re-discovering and re-typing the underlying `kwriteconfig6`/D-Bus incantations.
2. As the machine owner, I want `dot kde apply` to push all declared settings onto a live session in one idempotent command, so that re-running it after a KDE update or on a new machine is safe and has no unintended side effects.
3. As the machine owner, I want `dot kde diff` to show me every KDE setting currently different from default, so that I can catch drift I didn't intend, not just check the handful of settings I already know about.
4. As the machine owner, I want `dot kde diff`'s output to distinguish "this is already declared and intentional" from "this is undeclared and I've never seen it before," so that the noise of broad scanning doesn't bury genuinely unexpected changes.
5. As the machine owner, I want to run `dot kde save` with no arguments and have every already-tracked setting's manifest value refreshed from whatever is currently live, so that if I tweak a tracked setting by hand (e.g. change a keybind in System Settings) the manifest catches up without me re-typing its identifier.
6. As the machine owner, I want to run `dot kde save` with an explicit identifier to begin tracking one specific setting I just noticed via `diff`, so that I control exactly what enters the manifest instead of everything non-default being swept in at once.
7. As the machine owner, I want global keyboard shortcuts to be read and written through KDE's own shortcut-management service rather than by hand-editing `kglobalshortcutsrc`, so that changes take effect immediately in the running session and I never have to reconstruct KDE's internal triplet bookkeeping (current/default/friendly-name) myself.
8. As the machine owner, I want KConfigXT-schema-backed settings to have their "default" value discovered automatically wherever KDE's schema declares it, so that broad drift-scanning covers as much of the KDE config surface as possible without me manually cataloguing every setting I might ever care about.
9. As a future contributor to this dotfiles repo, I want `dot kde`'s subcommand files to live alongside its Python helper in one place, discoverable the same way every other `dot` subcommand is, so that adding this feature doesn't require bespoke wiring outside the established convention.
## Implementation Decisions
- **Subcommand family**: `dot kde apply` / `dot kde diff` / `dot kde save`, following the project's existing nested-subcommand dispatch convention (each level checks for `help` as its first positional argument before `argparse`, calling its own usage function).
- **`dot kde save` has two modes**:
- No arguments: iterate every identifier already in the manifest, read its current live value via the appropriate mechanism, and rewrite the manifest with the refreshed value.
- Explicit coordinates given: read the current live value for that one setting and add it to the manifest as a new declared entry. This is the only way new entries enter the manifest — there is no bulk/"track everything currently non-default" mode, by design, so that curation stays deliberate.
- **`dot kde diff`**: enumerates every setting it knows how to check (see mechanisms below), compares live vs. default, and reports every mismatch. Each reported mismatch is tagged as declared (present in the manifest, i.e. an intentional, already-tracked deviation) or undeclared (never explicitly declared). Diff never writes anything.
- **Manifest**:
- Location: a flat file directly under `~/.config/dot/` (not nested in a subdirectory — no near-term plan for multiple KDE-like targets that would justify one), named to convey "the set of KDE settings intentionally different from default."
- Format: plain text, one entry per line, `identifier=value`, split on the *first* `=` only (so values may themselves contain `=`).
- Identifier scheme: `file.group.key`, split on the first two `.`s only (so the key portion may contain further dots, spaces, or other characters freely — relevant for `kglobalshortcutsrc` action names, which can contain spaces).
- The manifest carries no mechanism/type discriminator field. It is a pure `identifier → value` map; `dot kde` decides internally how to resolve a given identifier.
- **Three underlying mechanisms**, dispatched purely by inspecting the identifier (no stored metadata):
1. **Shortcuts** (`kglobalshortcutsrc.<componentUnique>.<actionUnique>`) — resolved not by editing the rc file directly, but through KDE's `kglobalaccel` D-Bus service:
- Read current value: `shortcut(actionId)`.
- Read default value: `defaultShortcut(actionId)`.
- Write: `setShortcut(actionId, keys, flags)` with `flags = NoAutoloading` (so the declared value always wins over any previously-saved shortcut; using the `Autoloading` flag would make `apply` a no-op after the first run).
- `actionId` is a 4-element list: `[componentUniqueName, actionUniqueName, componentFriendlyName, actionFriendlyName]` (confirmed against KDE's own `actionIdFields` enum and verified live via `gdbus`). Only `componentUnique`/`actionUnique` are stored in the manifest; the two friendly-name fields (needed to actually place the D-Bus call) are resolved dynamically at call time by looking up the component's shortcut list, not stored.
- No read-modify-write is needed for this mechanism — `setShortcut` only ever touches the live/current value, never the default, so there's no risk of clobbering KDE's own bookkeeping.
2. **KConfigXT schema-backed settings** (most `kwinrc`, `kdeglobals`, etc. entries) — read/write via `kreadconfig6`/`kwriteconfig6`; the "default" value comes from the setting's `.kcfg` schema.
- The `(rcfile → [kcfg files])` mapping table is auto-derived at runtime by scanning the system's `.kcfg` schema directory for files that statically declare their target rc file (`<kcfgfile name="...">`), plus a small hand-maintained list for the exceptions that declare `<kcfgfile arg="true">` (i.e. the target file is only known at runtime by the owning app, not in the schema — `kwin.kcfg` is a known example).
- This mechanism is what enables `diff`'s broad-scan coverage: every entry reachable through the mapping table can be checked automatically, not just entries someone has already thought to add to the manifest.
3. **Freeform/schema-less settings** (e.g. `kxkbrc`'s `Options=` line) — read/write via `kreadconfig6`/`kwriteconfig6`; there is no schema, so "default" is defined as "the key is absent." Because there's no schema to enumerate from, this mechanism cannot participate in broad undeclared-drift discovery the way schema-backed settings can — it can only be checked for settings that are already declared in the manifest.
- Mechanism selection for a given identifier: if the rc file is `kglobalshortcutsrc`, use the shortcuts mechanism; otherwise, if the mapping table resolves the `(rcfile, group, key)` to a schema, use the schema-backed mechanism; otherwise, treat it as freeform.
- **File/module layout**: the fish dispatcher and its Python helper live together in one subdirectory under the project's existing commands location, rather than the Python helper sitting as a same-directory sibling of a same-named fish file at the top level.
- **Cross-cutting change to `dot` itself**: the subcommand-discovery mechanism (used both for help-listing and for dispatch) is extended to glob one additional directory level deep, not just the flat top level — required to support the subcommand-plus-helper layout above. This must be updated in both places the discovery logic currently exists (they are intentionally duplicated today rather than shared, for fish-autoload reasons), and applies to any future subcommand that wants a companion file, not just this one.
## Testing Decisions
- **Guiding principle**: tests should exercise this feature's own logic (manifest parsing, identifier dispatch, mapping-table auto-derivation, mechanism selection), not re-verify that external dependencies (`kreadconfig6`, `kwriteconfig6`, the KDE session itself) work correctly.
- **Primary seam**: full CLI invocation of `dot kde apply` / `dot kde diff` / `dot kde save`, run against a scratch `$HOME`, mirroring the existing project convention for testing `dot` subcommands (override `$HOME` per test case, no mocking of the real `kreadconfig6`/`kwriteconfig6` binaries — they run for real against fixture rc files under the scratch home). This covers the schema-backed and freeform mechanisms end-to-end: manifest read/write, identifier parsing, mechanism dispatch, and mapping-table-driven default lookup.
- **New seam introduced for this feature**: the KConfigXT schema directory is normally a fixed system path outside `$HOME`. To make the auto-derivation logic testable without depending on (or mutating) the real system's schema files, the schema directory location must be overridable (e.g. via an environment variable), defaulting to the real system path in normal use and pointing at a small fixture directory of synthetic `.kcfg` files in tests.
- **Deliberately not covered by automated tests**: the shortcuts mechanism (`kglobalaccel` D-Bus calls). It depends on a live, already-running session service that isn't practically substitutable without building dedicated mock infrastructure, which is disproportionate to what it would protect (three D-Bus calls). This path is verified manually against the real session instead.
- **Prior art**: the existing test suite for `dot`'s other subcommands already establishes the scratch-`$HOME`-plus-`fishtape` pattern this feature reuses.
## Out of Scope
- A `dot setup`-style subcommand for machine bootstrap tasks (extra groups, etc.) — considered during planning and set aside as not currently relevant.
- Folder naming / XDG user-dirs conventions — a real, separate piece of planned work, but standalone from `dot kde` and not part of this spec.
- Tracking Plasma's panel layout (`plasma-org.kde.plasma.desktop-appletsrc`) — previously decided this doesn't need tracking, since the current panel is CachyOS's own shipped default and reproduces automatically on a fresh install.
- An "empirical fallback" mechanism (spinning up a scratch config environment to let an app generate its own default config for diffing) — not needed given the three mechanisms above cover everything currently in scope; noted only as a possible future extension if some setting fits none of them.
- A bulk/`--all` mode for `dot kde save` — deliberately excluded so that every new manifest entry is a deliberate choice.
- Interactive picker UX for `diff`/`save` (e.g. selecting an undeclared entry from a list rather than typing its identifier) — not part of this spec.
- `dot voice` (hands-free dictation) — an unrelated, separately shelved piece of work, not touched by this feature.
## Further Notes
- The caps-lock/Escape swap (`kxkbrc`'s `Options=caps:escape_shifted_capslock`) is already live on this machine by hand, unrecorded anywhere — it's a ready-made first real candidate for the explicit-coordinates form of `dot kde save` once built, and a natural first end-to-end smoke test beyond the automated suite.
- The screenshot-related keybind work (Spectacle bindings, moving Lock Session off `Meta+L` to `Meta+X`, renaming Spectacle's save folder) was the original motivating case for this feature but is applied *through* `dot kde apply`/`save` rather than being separate work — once `dot kde` exists, those keybind changes are just manifest entries.
- Per the project's own cross-cutting convention, once any keybind changes are actually applied via this feature, the corresponding rows in the project's keybindings reference document need to be added/updated in the same change.

View File

@@ -1,59 +0,0 @@
## Problem Statement
The old `~/wrk/dotfiles` repo's `setup_folders` (part of its bash `bin/dot init`) renamed the standard XDG user folders to short names (`Documents→doc`, `Downloads→dwn`, etc.) for better fish shell-completion ergonomics — shorter shared prefixes are easier to disambiguate by typing fewer characters. That behavior has no equivalent in the new bare-repo `dot` CLI. Right now this machine's `user-dirs.dirs` is untracked and has drifted from even the old convention: it uses the full XDG default names, plus an ad hoc `XDG_PROJECTS_DIR=$HOME/Projects` line that never existed in the old repo at all. If this machine were rebuilt today, none of the short-name convention would be restored, and the current drifted state isn't recorded anywhere.
## Solution
Add a `folders` task to a new `dot setup` subcommand family (the general home for idempotent, re-runnable machine-setup tasks, as opposed to `dot init`'s one-shot bootstrap). `dot setup folders` brings the 8 standard XDG user directories under the project's short-name convention, tracks the resulting `user-dirs.dirs` directly as a plain dotfile, and safely migrates any content sitting in the old, full-named folders into their short-named replacements.
`~/wrk` (already in active use, e.g. `~/wrk/dotfiles`) replaces the old `Projects`-style folder as the general working-files location, but is treated as a plain convention-only directory, not a tracked XDG category.
## User Stories
1. As the machine owner, I want the standard XDG user folders renamed to short names (`doc`, `dwn`, `mus`, `pic`, `vid`, `.desktop`), so that fish-completion on my home directory has shorter, easier-to-disambiguate shared prefixes than the full XDG default names.
2. As the machine owner, I want `Templates` and `Public` (both unused) collapsed into a single hidden `.ignoreme` folder, so that apps respecting `XDG_TEMPLATES_DIR`/`XDG_PUBLICSHARE_DIR` don't scatter files directly into `$HOME`, without needing two separate unused folders.
3. As the machine owner, I want the nested `Pictures/Screenshots` folder lowercased to `pic/screenshots` in the same pass as the `Pictures→pic` rename, so that the screenshot folder matches the rest of the short-folder naming convention without a separate migration step.
4. As the machine owner, I want `~/wrk` to have no XDG variable pointing at it, so that a non-standard, barely-recognized XDG extension (`XDG_PROJECTS_DIR`) doesn't get tracked for a directory that already works fine as a plain convention.
5. As the machine owner, I want `user-dirs.dirs` tracked directly in the bare dotfiles repo like any other plain dotfile, so that the desired short names are recorded and restorable on a fresh machine without needing a code-generation step.
6. As the machine owner, I want `dot setup folders` to migrate content out of any legacy full-named folder into its short-named replacement automatically when the legacy folder is empty, so that re-running setup on a fresh install requires no manual folder shuffling.
7. As the machine owner, I want `dot setup folders` to stop and ask for explicit confirmation before moving anything out of a legacy folder that actually has content in it, so that I never silently lose files to an automated migration I forgot was going to run.
8. As the machine owner, I want confirmation to be satisfiable via a `--yes` flag rather than an interactive prompt, so that the same command works identically whether I'm running it by hand or from an automated/tested context.
9. As the machine owner, I want a filename collision between a legacy folder and an already-populated short-named target to never be silently overwritten, so that re-running the migration after a partial/interrupted prior run can't destroy a file just because both sides happen to have a same-named entry.
10. As the machine owner, I want to be told which files were skipped due to a collision and have the legacy folder left in place when that happens, so that I have a clear, actionable signal that something needs manual attention instead of silent partial data loss.
11. As the machine owner, I want `dot setup folders` to notify running apps of the directory changes via `xdg-user-dirs-update` after migrating, so that session-long apps pick up the new paths without requiring a full logout/login.
12. As the machine owner, I want to run `dot setup` with no arguments to perform every machine-setup task (folders plus future ones like extra groups) in one command, so that setting up a fresh machine doesn't require remembering and running each task individually.
13. As the machine owner, I want to also be able to run `dot setup folders` on its own, so that I can re-run just this one task in isolation (e.g. after a confirmation was declined) without re-running unrelated setup tasks.
## Implementation Decisions
- **Subcommand family**: `dot setup`, following the project's existing nested-subcommand dispatch convention (`help`-then-`argparse`, `_dot_<name>_usage`). Bare `dot setup` (no arguments) runs every machine-setup task unconditionally (folders, plus future tasks such as extra groups, mirroring the old bash `bin/dot init`'s dual-mode: no-args ran everything, an explicit keyword ran just one task). `dot setup folders` runs just the folders task.
- **Folder mapping** (identical to the old repo's `setup_folders`, no changes): `Desktop→.desktop`, `Documents→doc`, `Downloads→dwn`, `Music→mus`, `Pictures→pic`, `Videos→vid`, `Templates→.ignoreme`, `Public→.ignoreme`. `Templates` and `Public` both point at the *same* `.ignoreme` folder, as before.
- **Nested screenshots rename**: as part of the same `Pictures→pic` migration pass, the nested `Screenshots` folder (currently created empty by KDE/Spectacle defaults) is renamed to lowercase `screenshots`, so the result is `pic/screenshots`. This is folded into the folders task rather than deferred to the separate Spectacle-keybind work, since it's the same naming-convention concern and falls out for free once `Pictures/*` is moved into `pic/`.
- **`wrk` is out of the XDG mapping**: no `XDG_PROJECTS_DIR` (or any other XDG variable) is written for it. It's a plain, convention-only directory. The currently-existing ad hoc `~/Projects` folder (created by this machine's diverged, untracked `user-dirs.dirs`) is left alone — out of scope for the folders task, since it was never one of the 8 standard XDG categories the task manages, and it's empty and harmless.
- **`user-dirs.dirs` is tracked directly** as a plain dotfile in the bare repo (not generated/overwritten by `dot setup folders` from a hardcoded table each run) — unlike KDE's rc files (tracked via a separate declarative-manifest mechanism, see the `dot-kde` spec), `user-dirs.dirs` has no volatile/machine-specific fields, so it fits the same direct-tracking treatment as any other plain dotfile (`.bashrc`, etc.). The tracked file is the single source of truth for the desired short names.
- **`dot setup folders` still needs a small hardcoded table** mapping each of the 8 standard XDG categories to its legacy default folder name (`Documents`, `Downloads`, etc.) — this is used purely to locate content left behind by a fresh XDG-defaults install and merge it into the already-tracked short-named target; it is not the source of truth for the target names themselves (that's the tracked `user-dirs.dirs`).
- **Migration safety, per legacy folder**:
- Empty (strict check: any file at all, including dotfiles/metadata like a stray KDE `.directory` file, counts as non-empty) → merge silently, no prompt.
- Non-empty → print what would be moved and require an explicit `--yes` flag before proceeding. No interactive prompt.
- Collisions (a same-named entry exists in both the legacy folder and its short-named target) → use no-clobber semantics (e.g. `mv -n`) so a colliding file is never silently overwritten; report which files were skipped; leave the legacy folder in place (don't remove it) if any collision occurred, rather than deleting a folder that still holds something that couldn't be merged.
- **Post-migration step**: run `xdg-user-dirs-update` (no arguments) once folder moves are complete, to notify running apps/portals via its D-Bus signal. This is safe against the hand-tracked file — `user-dirs.dirs`'s own header documents that local edits are preserved across runs of the tool.
## Testing Decisions
- **Guiding principle**: test the folders task's own logic (mapping, empty-vs-non-empty gating, `--yes` behavior, collision handling, idempotency) through the real CLI entry point, not the internals of `mv`/`mkdir` themselves.
- **Primary seam**: full CLI invocation of `dot setup folders` (and bare `dot setup`), run against a scratch `$HOME` per test case — the existing project convention (see `dot install`'s tests). No new seam is introduced.
- **External command handling**: `xdg-user-dirs-update` is faked out via a `PATH`-prepended fake binary that logs its invocation (and exit code), exactly mirroring how `sudo`/`pacman` are faked for `dot install`'s tests. Real `mkdir`/`mv`/`rmdir` run for real against the scratch `$HOME` — no need to fake filesystem operations themselves.
- **Cases to cover**: fresh migration of empty legacy folders (no `--yes` needed); a legacy folder with real content refuses without `--yes` and proceeds with it; the nested `Pictures/Screenshots→pic/screenshots` rename; a stray dotfile (e.g. a fake `.directory`) in an otherwise-"empty" legacy folder still triggers the confirmation gate; a filename collision between legacy and target is skipped (not overwritten), reported, and leaves the legacy folder in place; re-running `dot setup folders` after a clean migration is a no-op (idempotency); bare `dot setup` runs the folders task as part of running everything; `dot setup folders help` prints usage and touches nothing.
- **Prior art**: `tests/dot.fish`'s existing scratch-`$HOME`-plus-`fishtape` pattern, and specifically the fake-`sudo`/fake-`pacman`-via-`PATH` technique used for `dot install`.
## Out of Scope
- The **extra groups** task (`dot setup groups` or similar, porting the old `.extra_groups`/`setup_users` behavior) — it will share the same `dot setup` dispatcher and dual-mode (bare-runs-everything vs. named-task) shape decided here, but its own design (group list format, idempotency, etc.) was not addressed in this spec.
- Any KDE-side settings (caps-lock/Escape swap, screenshot keybinds, Lock Session rebind) — covered separately by the `dot-kde` spec/design.
- Removing the currently-existing, now-orphaned `~/Projects` folder — explicitly left alone, not cleaned up by this feature.
- Any `~/.github/README.md` command-table row or `~/.github/keybindings.md` update — not applicable here (no keybind changes), but the README row is still required by the project's standard "adding a subcommand" checklist at implementation time.
## Further Notes
- The old bash `setup_folders`'s naive `mv $from/* $to` has a latent bug this design deliberately avoids: an unquoted glob against an empty directory can misbehave, and it has no collision protection at all. The no-clobber-plus-report behavior specified here is a deliberate improvement over the old script's behavior, not a straight port.
- This spec covers only the `folders` task; `dot setup` itself (the dispatcher, `_dot_setup_usage`, wiring into `commands/`, the completions/help-glob duplication point noted in the project's `CLAUDE.md`) needs to exist as scaffolding for this task to attach to, even though its only other planned task (extra groups) is out of scope here.

View File

@@ -1,46 +0,0 @@
## Problem Statement
On a freshly cloned dotfiles checkout (or any machine where `~/.local/share/nvim/lazy/` is empty or stale), `lazy.nvim` only discovers that plugins are missing when `nvim` is actually launched. The first interactive launch then silently spends a long time cloning `nord.nvim`, `nvim-treesitter`, and `render-markdown.nvim` and compiling every `nvim-treesitter` parser listed in `ensure_installed`, with no obvious progress indication in a normal terminal session — it reads as "nvim isn't starting" rather than "nvim is installing plugins." Nothing in `dot` proactively drives this sync, even though the exact plugin versions are already pinned and tracked in `~/.config/nvim/lazy-lock.json`.
Separately, `nvim-treesitter`'s parser build step has a known race: concurrent parser installs can collide on a relative `tree-sitter-<lang>-tmp` directory, causing one parser (e.g. `bash`) to fail to compile. Because the compiled `.so` never lands in `~/.local/share/nvim/lazy/nvim-treesitter/parser/`, that parser gets retried (and can fail again) on every subsequent `nvim` launch until it eventually succeeds — a silent, recurring cost with no clear signal to the user that anything is wrong.
## Solution
Add an `nvim` task to the `dot setup` family (introduced by the `dot-setup-folders` spec as the general home for idempotent, re-runnable machine-setup tasks). `dot setup nvim` drives a headless `nvim` session that syncs installed plugins to exactly what `lazy-lock.json` already pins, and verifies afterward that every pinned plugin actually landed on disk — turning a silent, ambiguous first-launch stall into an explicit, scriptable, pass/fail setup step. Bare `dot setup` (no task name) runs this alongside `folders` (and any future tasks).
## User Stories
1. As the machine owner, I want `dot setup nvim` to install/sync every plugin pinned in `lazy-lock.json` before I ever open `nvim` interactively, so that my first real editing session isn't interrupted by an unexplained multi-second-to-multi-minute stall that looks like a hang.
2. As the machine owner, I want `dot setup nvim` to use the already-tracked `lazy-lock.json` as the source of truth (not re-resolve latest versions), so that a fresh machine ends up with the exact plugin commits I've already vetted, not whatever is newest upstream that day.
3. As the machine owner, I want `dot setup nvim` to exit non-zero and say clearly which plugin(s) failed to install, so that a partial/broken sync is an obvious, actionable failure rather than something I only notice later inside nvim.
4. As the machine owner, I want re-running `dot setup nvim` when everything is already in sync to be a fast no-op that still exits 0, so that it's safe to include unconditionally in `dot setup`'s bare "run everything" mode without slowing down every re-run.
5. As the machine owner, I want to be able to run `dot setup nvim` in isolation (not just as part of bare `dot setup`), so that I can re-sync plugins on their own after e.g. manually editing `lazy-lock.json` or clearing the plugin directory.
6. As the machine owner, I want `dot setup nvim help` to print usage without touching any plugin state, so that it's consistent with every other `dot` subcommand's `help` behavior.
## Implementation Decisions
- **Subcommand family**: lives under the `dot setup` dispatcher established by the `dot-setup-folders` spec — same nested-subcommand convention (`help`-then-`argparse`, `_dot_setup_nvim_usage`), same dual-mode shape (bare `dot setup` runs every task; `dot setup nvim` runs just this one). This spec does not re-describe the shared dispatcher scaffolding itself; see `dot-setup-folders.md` for that.
- **Core action**: run `nvim --headless "+Lazy! restore" +qa`. `Lazy! restore` checks out every plugin in the spec to the exact commit recorded in `lazy-lock.json` (installing it first via clone if missing), so it both fixes "missing plugin" and "plugin present but on the wrong commit" in one call. No separate `TSUpdate`/`TSInstall` step is needed: because none of the current plugins (`nord.nvim`, `nvim-treesitter`, `render-markdown.nvim`) declare a lazy-loading trigger (`event`/`cmd`/`ft`), they load eagerly as part of this same headless session, which drives `nvim-treesitter`'s own `ensure_installed` parser-compilation step as a natural side effect — matching what was observed when reproducing the issue.
- **Failure detection**: `nvim`'s process exit code from `--headless ... +qa` does not reliably reflect whether `Lazy! restore` itself succeeded (Lazy reports failures via its own UI/messages, not necessarily the process exit status). `dot setup nvim` must independently verify success after the headless run completes, by checking that every plugin name declared in `lazy-lock.json` has a corresponding directory under `~/.local/share/nvim/lazy/`. Any pinned plugin missing a directory is treated as a failure: print which plugin(s) didn't install and exit non-zero.
- **Parser-compile failures are out of scope for pass/fail**: the `tree-sitter-<lang>-tmp` collision race affects `nvim-treesitter`'s internal parser build, not the plugin-directory check above (nvim-treesitter's own directory will exist regardless of whether an individual parser compiled). `dot setup nvim`'s success criterion is "all pinned plugins are present," not "all treesitter parsers compiled" — a parser-level compile flake is expected to self-heal on a later `nvim` launch or `:TSUpdate`, per the `Further Notes` in this spec's investigation. Detecting and retrying individual parser build failures is not attempted here.
- **No package-list file**: unlike `dot install`, there's nothing to record — `lazy-lock.json` is already the tracked source of truth, so `dot setup nvim` never writes to it.
## Testing Decisions
- **Guiding principle**: test `dot setup nvim`'s own logic (that it invokes `nvim` correctly, that it correctly detects success vs. a missing plugin) through the real CLI entry point, faking only the external `nvim` binary — not real plugin installs, real git clones, or real compilation, which would be slow and network-dependent in tests.
- **Primary seam**: full CLI invocation of `dot setup nvim` (and bare `dot setup`), run against a scratch `$HOME` per test case — the existing project convention (see `dot install`'s and the planned `dot setup folders`' tests). No new seam is introduced.
- **Faking `nvim`**: a `PATH`-prepended fake `nvim` binary, mirroring the fake-`pacman`/fake-`sudo`/fake-`xdg-user-dirs-update` technique already used/planned in `tests/dot.fish`. The fake logs its invocation args (so a test can assert `dot setup nvim` called it with `--headless "+Lazy! restore" +qa`) and, driven by an env var or scratch-`$HOME` fixture, can simulate "all plugins present" vs. "one plugin missing" by controlling whether it creates the expected directories under the scratch `~/.local/share/nvim/lazy/`.
- **Cases to cover**: a successful sync (fake `nvim` creates all pinned plugin directories) exits 0; a plugin missing after the fake run exits non-zero and names the missing plugin; re-running against an already-fully-synced scratch `$HOME` is still a pass (idempotency) without requiring the fake to do anything different; bare `dot setup` runs the `nvim` task alongside `folders`; `dot setup nvim help` prints usage and never invokes the fake `nvim` at all.
- **Prior art**: `tests/dot.fish`'s scratch-`$HOME`-plus-`fishtape` pattern, and specifically the fake-binary-via-`PATH` technique used for `dot install` (and planned for `dot setup folders`'s `xdg-user-dirs-update` fake).
## Out of Scope
- The `dot setup` dispatcher scaffolding itself (bare-runs-everything, per-task dispatch, `_dot_setup_usage`) — already specified in `dot-setup-folders.md`; this spec only adds the `nvim` task onto it.
- The `folders` and any future (e.g. `groups`) `dot setup` tasks — unaffected by this spec beyond now running alongside `nvim` in bare `dot setup`.
- Fixing the underlying `nvim-treesitter` `tree-sitter-<lang>-tmp` race itself (an upstream plugin behavior) — `dot setup nvim` tolerates it rather than working around it.
- Any change to `~/.config/nvim`'s plugin specs, `lazy-lock.json` contents, or which plugins/parsers are installed — this spec only adds a way to proactively sync to what's already pinned.
- A `~/.github/README.md` command-table row — not written here, but required by the project's standard "adding a subcommand" checklist at implementation time.
## Further Notes
- This spec grew out of debugging a real "nvim isn't starting" report: the actual cause was an empty `lazy.nvim` plugin directory triggering a full, slow reinstall on first launch, compounded by a `tree-sitter-bash-tmp` mkdir collision that made the `bash` parser fail and re-attempt on every subsequent launch until it happened to succeed. `dot setup nvim` addresses the first (silent first-launch stall) directly; the second (parser race) is a pre-existing upstream flake this spec does not attempt to fix.

View File

@@ -1,56 +0,0 @@
## Problem Statement
Today, `to-spec`, `to-tasks`, and `implement` track specs and tasks as local files (`.claude/spec/<slug>.md`, `.claude/tasks/<NNNN>-<slug>.md`) scoped to a single git working tree.
That means task state and context don't survive across the machine boundary — a spec or task can't be picked up from a different clone, referenced from a PR, or handed to a differently-scoped agent session without manually carrying the files over.
There's also no natural place for `review-uncommitted`'s findings to live once produced, other than the terminal output, which the operator has to capture manually if they want it preserved as a record.
## Solution
Once `gitea-axi` (see the companion `gitea-axi` spec) exists, replace the local-file storage in this project's skill-based task-management pipeline with Gitea issues and pull requests: specs and tasks become labeled issues, "readiness" becomes a label state, and implemented work becomes a pull request that `review-uncommitted` comments on directly.
The workflow-specific semantics (label names, state transitions, PR-to-issue linking) live entirely in the skills' own prose, calling `gitea-axi`'s generic primitives — `gitea-axi` itself stays unaware of this project's conventions.
## User Stories
1. As the operator, I want `to-spec` to open a Gitea issue containing the spec instead of writing a local file, so that the spec is visible and referenceable outside my local working tree.
2. As the operator, I want the spec issue labeled to mark it ready for task breakdown, so that a later session can find it without me telling it the issue number.
3. As the operator, I want a new session to be able to locate and read a spec issue by its readiness label, so that I can hand off spec-to-task work across sessions without manually passing context.
4. As the operator, I want `to-tasks` to open one Gitea issue per task instead of writing local task files, so that each task is independently discoverable and referenceable the same way the spec is.
5. As the operator, I want each task issue to retain a reference back to its parent spec issue, so that the `spec` traceability that today's local task-file frontmatter provides isn't lost in the move to issues.
6. As the operator, I want `to-tasks` to remove the spec issue's readiness label once tasks are created from it, so that the state machine reflects "spec has already been broken down" and isn't reprocessed.
7. As the operator, I want to ask a new session to implement "the next task" and have it find the right task issue by its readiness label, so that I don't have to look up and paste an issue number myself.
8. As the operator, I want `implement` to read a task issue's full details before starting work, so that it has the same context a local task file would have given it.
9. As the operator, I want `implement` to open a pull request (carrying the implementation commit) once work is done, instead of leaving only an uncommitted or committed local diff, so that the work is reviewable and mergeable through Gitea like any other PR.
10. As the operator, I want `review-uncommitted` to fetch its diff and spec context from the pull request and its linked issue when run in this workflow, so that I don't need a local spec file for it to work against.
11. As the operator, I want `review-uncommitted`'s three-axis findings posted as a comment on the pull request, so that they're visible as a permanent record on the PR itself, not just in my terminal.
12. As the operator, I want the label taxonomy and state machine (spec/task readiness, PR-to-issue linking conventions) to be easy to change later, so that I can iterate on the workflow without touching `gitea-axi`'s code.
13. As the operator, I want PR granularity (one commit vs. several, one task vs. several per PR) decided case-by-case between me and the agent at `implement` time, rather than fixed by a rule baked into the skill.
## Implementation Decisions
- Depends on `gitea-axi` existing first (see the companion spec) — this spec only covers how this project's skills consume it, not the tool itself.
- Affected skills: `to-spec`, `to-tasks`, `implement`, `review-uncommitted`. Each swaps its local-file I/O (`Read`/`Write`/`Edit` against `.claude/spec/` and `.claude/tasks/`) for calls to `gitea-axi`'s generic issue/PR primitives.
- `to-spec` opens an issue (instead of writing `.claude/spec/<feature-slug>.md`) carrying the same spec content and format, labeled to mark it as newly created and ready for breakdown.
- `to-tasks` reads the spec issue, opens one issue per task slice (instead of `.claude/tasks/<NNNN>-<slice-slug>.md`), each carrying a reference back to the parent spec issue (replacing the current `spec` frontmatter field), labels each task issue as ready for implementation, and removes the readiness label from the spec issue once done.
- `implement` locates its target task issue (by number if given, or by readiness label/query if asked for "the next task"), reads it in place of a local task file, does the work, and opens a pull request carrying the implementation commit — in place of just staging locally and leaving the commit to the operator.
- `review-uncommitted` gains a Gitea-aware path: when working against a PR, it fetches PR diff/metadata and the linked spec/task issue instead of `git diff HEAD` and a local spec file, and posts its aggregated Risk/Standards/Spec report as a single PR comment once done (per the companion spec's decision to keep this a single comment, not per-finding inline comments).
- Label taxonomy and exact naming (today referred to provisionally as "spec"/"ready-for-agent") are explicitly left open — to be finalized when these skill updates are actually implemented, not fixed by this spec.
- PR granularity (commits per PR, tasks per PR) is explicitly left as a case-by-case decision made between the operator and the agent at `implement` time — not a fixed rule this spec encodes.
## Testing Decisions
- Skills are prose (`SKILL.md` files), not unit-testable code — there is no automated test seam for the skill updates themselves. Verification is behavioral: running each updated skill against a real (or disposable) Gitea instance end-to-end and confirming the resulting issues, PRs, labels, and comments match what the prose describes.
- The one seam that is testable in the traditional sense is `gitea-axi` itself, already covered by the companion spec — these skill updates are downstream consumers of that seam, not a new one.
- No prior art in this repo for testing prompt-based skills; `~/.config/dot/tests/dot.fish` (fishtape, end-to-end against fixtures) is the closest pattern, but it tests code, not prose, so it doesn't transfer directly.
## Out of Scope
- Building `gitea-axi` itself (fully covered by the companion `gitea-axi` spec).
- Deciding the actual label taxonomy and state machine names — deferred to implementation time.
- Deciding PR granularity rules — deferred to case-by-case decisions at `implement` time.
- Inline per-finding PR review comments for `review-uncommitted` (deferred enhancement, noted in the companion spec).
- Any change to `codebase-design`, `domain-modeling`, `test-driven-development`, or other skills not in the four listed above.
## Further Notes
- This spec assumes `gitea-axi`'s generic primitives (issue create/read/find-by-label/update-labels, PR create/get/comment) are sufficient for the four listed skills. If implementation reveals a missing primitive, it should be added to `gitea-axi` itself (kept generic) rather than special-cased here.
- This is an opinionated, single-adopter view of `gitea-axi` — it intentionally isn't part of the `gitea-axi` spec itself, since that tool is meant to stay usable by others regardless of this project's specific workflow conventions.

View File

@@ -1,70 +0,0 @@
## Problem Statement
Coding agents that need to drive a Gitea-hosted workflow (issues, pull requests, labels) today have two poor options.
The official `tea` CLI is human-oriented: it has no token-efficiency, no contextual guidance, and no agent-facing error conventions.
Gitea's MCP servers expose the full API surface (dozens of tools) rather than being tuned for token or turn efficiency.
There is no Gitea-focused tool built to the same "agent ergonomics" standard that `gh-axi` established for GitHub.
## Solution
Build `gitea-axi`: a thin, generic CLI wrapper around the official `tea` binary that reshapes its output according to the 10 AXI (Agent eXperience Interface) principles — token-efficient output, minimal default schemas, structured errors, contextual next-steps, and so on.
It gives coding agents an ergonomic, low-token way to drive issues and pull requests on any Gitea instance.
It ships both as an installable npm CLI and as an installable Agent Skill, so any agent session can adopt it with one install step.
## User Stories
1. As a coding agent, I want to create a Gitea issue with a title, body, and labels, so that I can record work items for later retrieval.
2. As a coding agent, I want to find issues by label (and other basic filters), so that I can locate relevant work without already knowing its issue number.
3. As a coding agent, I want to read an issue's full body, labels, and comments, so that I can load its context into a session.
4. As a coding agent, I want to add and remove labels on an existing issue, so that I can reflect state transitions as work progresses.
5. As a coding agent, I want to create a pull request from the current branch, so that completed work becomes reviewable.
6. As a coding agent, I want to fetch a pull request's metadata and diff, so that review tooling can operate on it without re-deriving it from git.
7. As a coding agent, I want to post a comment on a pull request, so that findings or notes are visible as a permanent reference on the PR itself.
8. As a coding agent, I want command output in a token-minimized format (TOON, minimal default fields, truncated large fields with an escape hatch), so that repeated calls across a long-running session don't consume excessive context.
9. As a coding agent, I want pre-computed aggregates in list/read output, so that I don't need follow-up calls just to derive obvious derived fields.
10. As a coding agent, I want explicit empty-state output when a query returns nothing, so that "no results" is never ambiguous with an error or a hang.
11. As a coding agent, I want structured errors with actionable suggestions and meaningful exit codes instead of prose failures, so that I can self-correct without the operator's help.
12. As a coding agent, I want mutations to be idempotent and to never prompt interactively, so that unattended, scripted use never stalls or double-applies.
13. As a coding agent, I want contextual next-step suggestions appended after output, so that I know what to call next without being taught the tool from scratch every session.
14. As a coding agent, I want a consistent per-subcommand `--help`, so that I can discover the interface on demand rather than needing it pre-loaded in context.
15. As an operator, I want gitea-axi run with no arguments to show live, actionable repository state instead of a help screen, so that I get immediate value without memorizing flags.
16. As an operator, I want gitea-axi to reuse my existing `tea` login configuration (including multi-instance profiles), so that I don't manage a second set of credentials.
17. As an operator, I want gitea-axi's command surface to stay generic, with no workflow-specific behavior baked in, so that it's useful across different projects and label/workflow conventions without code changes.
18. As an operator, I want gitea-axi published to npm and as an installable Agent Skill, so that I (and others) can adopt it with a single install step.
## Implementation Decisions
- New standalone repository — not bundled into any other tool or CLI framework.
- Developed against the operator's personal Gitea instance; push-mirrored to GitHub for npm publishing and public discoverability/contribution.
- Language/runtime: TypeScript on Node, matching the `gh-axi` reference implementation this design is modeled on.
- Implementation strategy: wrap the `tea` binary as a subprocess, invoking it with `--output json` (or the most structured format it supports) and reshaping that output — not a from-scratch Gitea API client. This reuses `tea`'s auth, multi-instance login, and full command coverage for free.
- **Flagged risk**: subprocess-wrapping-a-CLI can become fragile or slow at higher call volumes or in edge cases (partial output, non-JSON error text, version drift in `tea`'s own output shape). If this proves to be a real problem in practice, the fallback is a direct Gitea HTTP API client (as Gitea's own MCP server already does) — noted here so it isn't re-litigated from scratch if revisited.
- Auth: no independent credential handling. Every command shells out through `tea`, so it relies entirely on `tea login add` already being configured, including `tea`'s own `--login`/multi-instance profile resolution.
- Command surface: generic Gitea primitives only — issue create/read/find-by-label/update-labels, PR create/get/comment (see User Stories above for the full list). No project-specific or workflow-specific commands (e.g. nothing that hardcodes a particular label taxonomy or state machine).
- Output ergonomics follow the 10 AXI principles (https://axi.md/, https://github.com/kunchenguid/axi), grouped as:
- Efficiency: TOON-formatted stdout (~40% fewer tokens than JSON), minimal default schemas (3-4 fields per list item), truncated large fields with size hints and an escape hatch to fetch full content.
- Robustness: pre-computed aggregates to avoid round trips, explicit empty-state messages, structured errors and exit codes, idempotent mutations, no interactive prompts, fail loudly on unknown flags.
- Discoverability: opt-in session integration plus an on-demand skill, no-args shows live data rather than help text, contextual next-step suggestions appended after output.
- Help: consistent per-subcommand `--help`.
- Distribution: published to npm as a global-installable CLI, and packaged as an installable Agent Skill (installable the same way as `gh-axi`'s, e.g. via `npx skills`) — both built together from the start, not phased.
## Testing Decisions
- Good tests exercise the actual command-line interface (argv in, stdout/exit-code out) — the one seam every caller depends on — not internal functions, and not a mock of the `tea` subprocess call itself (that would only prove gitea-axi calls `tea` with certain arguments, not that the output is correctly reshaped).
- Tests should run the real, built CLI against either a disposable/fixture Gitea instance or a recorded fixture of `tea`'s own JSON output.
- Prior art: `~/.config/dot/tests/dot.fish` tests `dot`'s subcommands end-to-end with fishtape, building a throwaway bare-git remote fixture per scenario rather than mocking `git`. The equivalent here is a disposable Gitea fixture (or recorded `tea` output) rather than mocking `tea`.
## Out of Scope
- Any workflow-specific commands or hardcoded label/state semantics (tracked separately — see the companion `gitea-axi-integration` spec for one concrete adopter's usage).
- Inline per-line PR review comments (a possible future addition; the primitive here is a plain PR comment).
- A from-scratch Gitea HTTP API client bypassing `tea` (deferred fallback if the subprocess-wrapping approach proves fragile — see flagged risk above).
- Multi-instance orchestration beyond what `tea`'s own login profiles already provide.
- A `dot` (or any other host CLI's) subcommand wrapping this tool — it is intentionally a standalone, independently distributed tool.
## Further Notes
- AXI ("Agent eXperience Interface") is an existing framework: https://axi.md/ and https://github.com/kunchenguid/axi. Its reference implementation, `gh-axi` (https://github.com/kunchenguid/gh-axi), wraps GitHub's `gh` CLI the same way this spec proposes wrapping `tea`, and reports (its own benchmarks) 100% task success vs. 86% for raw `gh`, and 66% cheaper / 74% fewer input tokens / half the interaction turns vs. GitHub's official MCP server on the same 17-task benchmark.
- The official Gitea MCP server (https://gitea.com/gitea/gitea-mcp) was evaluated and rejected as the primary approach: roughly 45 consolidated tools, actively maintained, but — by analogy to the gh-axi-vs-GitHub-MCP benchmark — generic MCP servers expose the full API surface rather than being tuned for token/turn efficiency, and using one directly would forfeit control over output shape.
- Raw `tea` was also evaluated and rejected as the long-term approach (though it remains the dependency this tool wraps): it already supports `--output json/yaml/csv/tsv`, so it's scriptable, but its schemas are human-oriented, not agent-ergonomic (no truncation, no contextual next-steps, no token minimization).
- Name collision check (as of this writing): `gitea-axi` is unclaimed on both npm and GitHub.

View File

@@ -1,31 +0,0 @@
---
spec: dot-kde
---
## What to build
Extend the subcommand-discovery mechanism to glob one directory level
deeper, so a `dot` subcommand can live as `commands/<name>/<name>.fish`
alongside a companion file (e.g. a Python helper), not just as a flat
`commands/<name>.fish`. This mechanism exists in two places today
(`dot.fish`'s `__dot_help` and `completions/dot.fish`'s
`__dot_custom_subcommands`), intentionally duplicated rather than shared
(fish autoload constraints) — both must be updated together and stay in
sync. Existing flat-file subcommands must keep working unchanged.
This is pure prefactoring: no KDE-specific behavior is introduced here.
## Acceptance criteria
- [x] `dot help` lists a subcommand that lives at `commands/<name>/<name>.fish`
- [x] `dot <name>` sources and dispatches to `commands/<name>/<name>.fish`'s `_dot_<name>` function
- [x] Tab-completion (`__dot_custom_subcommands`) lists a nested-directory subcommand
- [x] Existing flat-file subcommands (`dot install`) are still discovered and dispatched correctly
- [x] `tests/dot.fish` covers a nested-directory dummy command dispatching correctly, alongside the existing flat-file dispatch case
## Implementation Notes
- The dispatch check in `dot.fish` tries the flat file first, then falls back to `commands/<name>/<name>.fish` — a flat file always wins if both somehow exist for the same name.
- The nested-directory scan requires the file basename to match its containing directory's name (`commands/foo/foo.fish`), not just any `.fish` file one level deep — this matches the acceptance criteria's exact convention and avoids misclassifying a stray companion file (e.g. a `.py` helper) as its own subcommand.
- Tab-completion's nested-directory listing was verified manually (sourcing `completions/dot.fish` and calling `__dot_custom_subcommands` directly) rather than via an automated test — `tests/dot.fish` has no existing infrastructure for testing completions at all, even for pre-existing flat commands, so adding one here would be out of scope for this prefactoring task.
- Updated `CLAUDE.md`'s "Architecture" and "Adding a subcommand" sections to document the new nested-directory convention, since it previously only described the flat-file dispatch contract.

View File

@@ -1,63 +0,0 @@
---
spec: dot-kde
blocked-by: 0000-nested-subcommand-discovery
---
## What to build
Stand up `dot kde` itself: the fish dispatcher plus its Python helper,
living together under `commands/kde/` per the nested-subcommand layout
from the prior task. Establish the manifest file (flat text file directly
under `~/.config/dot/`, one `identifier=value` line each, split on the
first `=` only; identifier split on the first two `.`s into
`file.group.key`, leaving the key free to contain further dots or spaces).
Implement the KConfigXT schema-backed mechanism: reads and writes go
through `kreadconfig6`/`kwriteconfig6`, and the "default" value for a
setting comes from its `.kcfg` schema. Build the `(rcfile → [kcfg files])`
mapping table by scanning the system's KConfigXT schema directory for
files that statically declare their target rc file
(`<kcfgfile name="...">`), plus a small hand-maintained list for the
exceptions that only declare their target file at runtime
(`<kcfgfile arg="true">``kwin.kcfg` is a known example). The schema
directory location must be overridable (e.g. via an environment variable),
defaulting to the real system path, so tests can point it at a fixture
directory of synthetic `.kcfg` files instead.
Structure identifier resolution as a dispatchable decision (rc file is
`kglobalshortcutsrc` → shortcuts; else resolves via the mapping table →
schema-backed; else → freeform) even though only the schema-backed branch
is implemented yet — later tasks add the other two branches without
restructuring this.
Implement `dot kde save` for schema-backed settings, in both modes:
run with no arguments, refresh every already-declared manifest entry's
value from the live system; run with an explicit identifier, read its
current live value and add it to the manifest as a new declared entry.
Add `dot kde help` and `dot kde save help`, following the project's
check-for-`help`-before-`argparse` convention at each dispatch level.
Add README rows for `dot kde help`, `dot kde save <identifier>`, and
`dot kde save` (no arguments).
## Acceptance criteria
- [x] `dot kde` and `dot kde save` are discoverable via `dot help` and dispatch correctly
- [x] Manifest parsing splits correctly on the first `=` (values may contain `=`) and the first two `.`s of the identifier (keys may contain dots/spaces)
- [x] The `(rcfile → [kcfg files])` mapping table is derived by scanning a schema directory for `<kcfgfile name="...">`, plus the hand-maintained exceptions list for `arg="true">` schemas
- [x] The schema directory is overridable via an environment variable, defaulting to the real system path
- [x] `dot kde save <identifier>` reads the current live value via `kreadconfig6` and adds a new declared entry to the manifest
- [x] `dot kde save` with no arguments refreshes every already-declared manifest entry's stored value from the live system, leaving undeclared settings untouched
- [x] `dot kde help` and `dot kde save help` print usage without touching the manifest or invoking `kreadconfig6`/`kwriteconfig6`
- [x] Tests run against a scratch `$HOME` and a fixture `.kcfg` schema directory, exercising manifest read/write, identifier parsing, and mapping-table-driven default lookup, per the project's scratch-`$HOME`-plus-`fishtape` convention
- [x] README has rows for `dot kde help`, `dot kde save <identifier>`, and `dot kde save`
## Implementation Notes
- File layout: `commands/kde/kde.fish` (thin dispatcher: help-before-dispatch at the `dot kde` level, then hands off to the Python helper) plus `commands/kde/kde.py` (manifest parsing, mapping-table derivation, mechanism resolution, `kreadconfig6` invocation, and `save`'s own help-before-work check).
- Manifest location: `~/.config/dot/kde-manifest`, a flat file directly under `~/.config/dot/` as specified.
- Mechanism dispatch (`resolve_mechanism`) implements all three branches described in the parent spec (shortcuts / schema / freeform) even though only `schema` is wired to real behavior; `shortcuts` and `freeform` both currently raise a clear "not yet supported" error from `save_one`, so later tasks can fill them in without restructuring the dispatch.
- Test fixtures added under `tests/fixtures/kcfg/`: `testrc.kcfg` (a plain `<kcfgfile name="...">` schema, including an entry whose ini `key=` differs from its schema `name=`, and one entry whose key contains dots and spaces), `kwin.kcfg` (an `arg="true"` schema resolved only via the hand-maintained exceptions list), and `unmapped.kcfg` (an `arg="true"` schema absent from that list, proving it's never guessed at from its own filename).
- Per the project's testing convention, `kreadconfig6` is never mocked for the tests exercising actual `save` behavior — it runs for real against fixture rc files under a scratch `$HOME`. It's faked (via a `$PATH`-prepended logging stub) only for the two tests asserting that `dot kde help` / `dot kde save help` never invoke it.
- Applied two small cleanups surfaced by `/review-uncommitted`'s Standards pass before closing out: extracted a shared `_parse_kcfg` helper (was duplicated between `build_kcfg_map` and `find_schema_default`), and introduced a `Setting = namedtuple("Setting", ["file", "group", "key"])` to stop threading those three strings as separate parameters across `resolve_mechanism`/`find_schema_default`/`read_live_value`/`save_one`.
- The Spec pass caught that the `unmapped.kcfg` fixture was created but never actually exercised by a test; added a case asserting `dot kde save unmapped.Whatever.Setting` resolves to freeform rather than schema-backed.

View File

@@ -1,32 +0,0 @@
---
spec: dot-kde
blocked-by: 0001-kde-schema-backed-save
---
## What to build
Implement `dot kde apply` for schema-backed settings: read every entry in
the manifest and write its declared value onto the live system via
`kwriteconfig6`. Re-running it against an already-applied system must be a
no-op with no unintended side effects — this is the idempotence the
feature depends on for safe re-runs after a KDE update or on a freshly
built machine. Add `dot kde apply help`, following the project's
check-for-`help`-before-`argparse` convention.
Add a README row for `dot kde apply`.
## Acceptance criteria
- [x] `dot kde apply` pushes every manifest entry's declared value onto the live system via `kwriteconfig6`
- [x] Re-running `dot kde apply` against a system already matching the manifest changes nothing (idempotent)
- [x] `dot kde apply help` prints usage without writing anything
- [x] Tests run against a scratch `$HOME`, exercising apply over a manifest with schema-backed entries, verifying resulting rc-file contents and idempotence on a second run
- [x] README has a row for `dot kde apply`
## Implementation Notes
- File layout mirrors `save`'s: `write_live_value` (the `kwriteconfig6` counterpart to `read_live_value`) and `apply_one` (mirroring `save_one`'s `parse_identifier``resolve_mechanism` → schema-only gate) added to `commands/kde/kde.py`; `cmd_apply` mirrors `cmd_save`'s help/argument/error-handling scaffold. `kde.fish` gained an `apply` dispatch case above `save`.
- `apply` takes no arguments (unlike `save`, which supports an optional identifier) — the task only specifies pushing the whole manifest, and the parent spec's `apply` user story has no per-identifier mode, so `dot kde apply <extra-arg>` is rejected as misuse rather than silently ignored.
- `write_live_value` passes the value positionally after a `--` separator (`kwriteconfig6 --file ... --group ... --key ... -- <value>`) rather than via a `--value` flag, since `kwriteconfig6` takes the value as a mandatory positional argument, not a flag; `--` guards against a value that itself looks like an option.
- Non-schema (shortcuts/freeform) manifest entries are rejected with the same "not yet supported" error `save_one` already raises for those mechanisms, kept out of scope per this task's title ("...apply for schema-backed settings"); those mechanisms are added in later tasks (0004, 0005) without needing to restructure `cmd_apply`.
- `/review-uncommitted` flagged two baseline duplication smells (`apply_one`/`cmd_apply` mirroring `save_one`/`cmd_save`'s shape) and one observation (a failing entry mid-manifest halts `apply` immediately, leaving earlier writes already applied — a partial-apply state, untested either way). Left as-is: the duplication mirrors an already-established local convention from task 0001 rather than introducing a new one, and the partial-apply behavior is consistent with `cmd_save`'s pre-existing control flow, not a new risk introduced by this task.

View File

@@ -1,35 +0,0 @@
---
spec: dot-kde
blocked-by: 0001-kde-schema-backed-save
---
## What to build
Implement `dot kde diff`'s broad, read-only scan for schema-backed
settings: walk every `(rcfile, group, key)` reachable through the
mapping table built in the prior task, compare each live value
(`kreadconfig6`) against its schema-declared default, and report every
mismatch. Each reported mismatch is tagged as declared (its identifier is
present in the manifest — an intentional, already-tracked deviation) or
undeclared (never explicitly declared). `diff` never writes anything.
Add `dot kde diff help`, following the project's
check-for-`help`-before-`argparse` convention.
Add a README row for `dot kde diff`.
## Acceptance criteria
- [x] `dot kde diff` reports every schema-backed setting whose live value differs from its schema-declared default
- [x] Each reported mismatch is tagged declared or undeclared based on manifest presence
- [x] `dot kde diff` makes no writes under any circumstances
- [x] `dot kde diff help` prints usage without scanning
- [x] Tests run against a scratch `$HOME` and fixture `.kcfg` schema directory, covering: a declared mismatch, an undeclared mismatch, and a setting matching its default (not reported)
- [x] README has a row for `dot kde diff`
## Implementation Notes
- `cmd_diff` (in `commands/kde/kde.py`) reuses `build_kcfg_map`/`iter_schema_identifiers` (already built for `kde.py complete`) to walk every schema-backed `(rcfile, group, key)`, then `find_schema_default`/`read_live_value` (already built for `save`) to compare live vs. default. No new scanning machinery was needed — this task's whole job was wiring existing pieces together into a read-only report.
- Output format: one line per mismatch, `<declared|undeclared> <identifier> = <live> (default: <default>)`. Not specified by the task, so chosen to read clearly and stay unambiguous under substring matching in tests (avoided bracketed tags like `[declared]`, since fish's `string match` glob treats `[...]` as a character class).
- `/review-uncommitted`'s Spec pass caught that `cmd_diff` had no error handling around `read_live_value`, unlike `cmd_apply`/`cmd_save`'s `try/except (ValueError, RuntimeError)` — a single `kreadconfig6` failure would have aborted the entire broad scan with an uncaught traceback, contradicting `diff`'s "report every mismatch" framing. Fixed: `cmd_diff` now catches `RuntimeError` per-identifier, prints a warning to stderr, and continues scanning the rest.
- The Standards pass flagged the "build map → iterate `sorted(set(iter_schema_identifiers(...)))`" shape as now duplicated between `cmd_diff` and `cmd_complete`, and the new test scenarios' fixture boilerplate as repeating the `apply` tests' shape almost verbatim. Left both as-is: the loop duplication is two call sites doing genuinely different things with the result, and the test boilerplate matches this file's already-established per-scenario convention (each scenario resets `$HOME` independently) rather than introducing a new pattern.
- Post-closeout fix (user-reported): `~/.config/fish/completions/dot.fish`'s `dot kde` completion block only ever listed `save`/`help` as verbs — `apply` was never added when task 0002 built it, and this task initially repeated the same omission for `diff`. Fixed both by adding `apply` and `diff` to the top-level verb-offering line and to the post-subcommand `help` gating; verified manually via `complete -C"dot kde "` and `complete -C"dot kde apply "`/`complete -C"dot kde diff "`.

View File

@@ -1,41 +0,0 @@
---
spec: dot-kde
blocked-by: [0002-kde-schema-backed-apply, 0003-kde-schema-backed-diff]
---
## What to build
Add the freeform mechanism as a dispatch branch across `save`, `apply`,
and `diff`: for settings with no KConfigXT schema (e.g. `kxkbrc`'s
`Options=` line), read and write via `kreadconfig6`/`kwriteconfig6`, with
"default" defined as "the key is absent" rather than any schema-declared
value. In the identifier-resolution decision from the first schema-backed
task, this is the fallback branch: an identifier whose `(rcfile, group,
key)` doesn't resolve through the mapping table is freeform. Because
there's no schema to enumerate, freeform settings can only be checked by
`diff` when already declared in the manifest — they never participate in
undeclared broad-scan discovery.
As the real-world validation for this task, bring the machine's live,
already-hand-set `kxkbrc` caps-lock/Escape swap
(`Options=caps:escape_shifted_capslock`) under tracking via
`dot kde save`, and confirm `dot kde apply`/`dot kde diff` behave
correctly against it.
## Acceptance criteria
- [x] An identifier whose `(rcfile, group, key)` has no schema match is treated as freeform rather than erroring
- [x] `dot kde save <identifier>` and `dot kde save` (refresh) work for freeform entries
- [x] `dot kde apply` writes freeform entries via `kwriteconfig6`, idempotently
- [x] `dot kde diff` reports a freeform mismatch when its identifier is already declared in the manifest, and never surfaces an undeclared freeform setting via broad scan
- [x] Tests run against a scratch `$HOME`, covering freeform save/apply/diff using a fixture rc file with no corresponding schema
- [x] The live `kxkbrc` caps-lock/Escape swap is tracked via `dot kde save` and the manifest committed to the dotfiles repo
## Implementation Notes
- `save_one`/`apply_one`'s gate changed from `mechanism != "schema"` (reject everything but schema) to `mechanism == "shortcuts"` (reject only shortcuts) — freeform now flows through the same `read_live_value`/`write_live_value` calls schema-backed settings already use, since both mechanisms only differ in what "default" means, not in how the read/write itself happens.
- `cmd_diff` gained a second pass after the existing schema broad-scan: it walks the manifest (not the kcfg mapping table, which freeform settings are absent from by definition), resolves each identifier's mechanism, and reports only those that resolve to `freeform` and whose live value is non-empty — structurally guaranteeing freeform can never surface via undeclared broad scan, since the loop never sees anything outside the manifest.
- **Real-world validation surfaced a stale premise**: the task assumed the caps-lock/Escape swap was "already hand-set" and live, but the machine had no `kxkbrc` file and no active XKB option at all. Confirmed with the user before proceeding; with their approval, wrote the option live via `kwriteconfig6 --file kxkbrc --group Layout --key Options -- caps:escape_shifted_capslock` and applied it immediately via a live KWin reconfigure (`busctl --user call org.kde.KWin /KWin org.kde.KWin reconfigure`), then ran `dot kde save kxkbrc.Layout.Options` to bring it under tracking. `dot kde apply`/`dot kde diff` were both verified against the real entry (idempotent apply; diff reports `declared kxkbrc.Layout.Options = caps:escape_shifted_capslock (default: )`).
- Added a `.github/keybindings.md` row for the swap (`CapsLock``Esc`, `Shift`+`CapsLock` → real Caps Lock toggle), per the project's cross-cutting keybindings convention.
- Existing tests that previously asserted freeform saves/applies were *rejected* (written when freeform was still unimplemented, per task 0001/0002's "not yet supported" stopgap) were updated to assert success instead, using a new `somefreeform` fixture rc file with no corresponding `.kcfg` schema. Coverage for the still-unimplemented shortcuts mechanism (task 0005) was added in the same spots to keep the "not yet supported" rejection path tested now that freeform no longer exercises it.
- `/review-uncommitted`'s Spec pass caught that `cmd_diff`'s new freeform loop called `parse_identifier` on raw manifest keys with no exception guard, unlike the rest of the function — a hand-edited manifest with a malformed identifier would have crashed the whole scan instead of reporting a clean per-identifier error. Fixed: the loop body is now wrapped in `try/except (ValueError, RuntimeError)`, matching the file's established per-identifier-failure-tolerant convention. The Standards pass also flagged threading a hardcoded `None`/blank literal through the freeform loop instead of the real `default` value returned by `resolve_mechanism`; fixed by reusing that variable directly (`default or ''` for display, since freeform's default is always `None`).

View File

@@ -1,57 +0,0 @@
---
spec: dot-kde
blocked-by: [0002-kde-schema-backed-apply, 0003-kde-schema-backed-diff]
---
## What to build
Add the shortcuts mechanism as a dispatch branch across `save`, `apply`,
and `diff`: identifiers rooted at `kglobalshortcutsrc` are resolved not by
editing the rc file directly but through KDE's `kglobalaccel` D-Bus
service — `shortcut(actionId)` for the current value, `defaultShortcut
(actionId)` for the default, and `setShortcut(actionId, keys, flags)`
with `flags = NoAutoloading` for writes (so a declared value always wins
over any previously saved shortcut). `actionId` is the 4-element
`[componentUnique, actionUnique, componentFriendly, actionFriendly]`
tuple; only the two `Unique` fields are stored in the manifest, and the
two friendly-name fields are resolved dynamically at call time by looking
up the component's shortcut list.
Per the spec's testing decisions, this mechanism is deliberately excluded
from the automated test suite (it depends on a live, already-running
session service that isn't practically substitutable without disproportionate
mock infrastructure) — verify it manually against the real session instead.
As the real-world validation, apply the planned screenshot/session-lock
keybind changes (Spectacle bindings, moving Lock Session off `Meta+L` to
`Meta+X`) through `dot kde save`/`dot kde apply`, and update the
corresponding rows in `keybindings.md` in the same change, per the
project's cross-cutting keybindings convention.
## Acceptance criteria
- [x] An identifier whose rc file is `kglobalshortcutsrc` dispatches to the `kglobalaccel` D-Bus mechanism rather than the schema-backed or freeform paths
- [x] `dot kde save <identifier>` and `dot kde save` (refresh) read a shortcut's current value via `shortcut(actionId)`, resolving the friendly-name fields dynamically
- [x] `dot kde apply` writes a declared shortcut via `setShortcut(actionId, keys, NoAutoloading)`, verified manually to take effect immediately in the running session
- [x] `dot kde diff` reports a declared shortcut mismatch by comparing against `defaultShortcut(actionId)`, verified manually
- [-] The Spectacle and Lock-Session (`Meta+X`) keybind changes are applied through `dot kde save`/`apply` and tracked in the manifest
- [x] `keybindings.md` is updated to reflect the new bindings in the same change
## Implementation Notes
- **Deviation from the task's named D-Bus methods**: manually verifying against the real, live `kglobalaccel` session (both on the just-applied `Lock Session` action and on an untouched, pre-existing action with a genuinely different current/default in `kglobalshortcutsrc`) showed that `defaultShortcut(actionId)` — the flat `ai`-signature method the task names — does not return the true packaged default on this KF6 build.
It just mirrors `shortcut(actionId)`.
Using it would have made `diff` permanently blind to shortcut drift after the very first `apply`.
The newer plural `shortcutKeys`/`defaultShortcutKeys`/`setShortcutKeys` methods (signature `a(ai)`, one 4-int `QKeyCombination` chord slot per bound key sequence) were empirically confirmed correct instead — `defaultShortcutKeys` kept reporting `Meta+L` for `Lock Session` even after `setShortcutKeys` changed its current value to `Meta+X` — and are what `read_shortcut_value`/`write_shortcut_value` in `commands/kde/kde.py` actually call.
`NoAutoloading`'s value (`0x4`, from `KF6/KGlobalAccel/kglobalaccel.h`) is unchanged by this swap.
- Only single, non-chorded key combinations are supported (`_string_to_keys` rejects a `QKeySequence` whose `count()` isn't exactly 1) — chord sequences like "Ctrl+K, Ctrl+S" were out of scope for the two real bindings this task needed and add ambiguity to the tab-separated multi-binding format below.
- **Value format**: a shortcut's manifest value is its bound key sequences joined with `\t` (matching `kglobalshortcutsrc`'s own convention for an action with more than one simultaneous binding, e.g. `Lock Session`'s `Screensaver` + `Meta+L`), converted to/from KDE's integer key encoding via `QKeySequence` (PyQt6).
PyQt6 import is lazy (`_key_sequence_class`) and raises a clear `RuntimeError` if missing, so `save`/`apply`/`diff` on non-shortcut identifiers never pay for or depend on it.
- **Spectacle bindings dropped** from this change's real-world validation.
Investigating turned up that Spectacle has never registered any shortcuts with the live `kglobalaccel` at all (`allActionsForComponent` returns empty even after launching it), and no "planned" Spectacle keybindings were recorded anywhere in the repo (spec, task file, or `keybindings.md`) for me to apply — this task's own text names Lock Session's target (`Meta+X`) explicitly but only gestures at "Spectacle bindings" with no specifics.
Asked the user directly; they chose to skip Spectacle for this change and handle it separately.
Only the Lock Session move is applied here.
The parent spec's aside about "renaming Spectacle's save folder" is also left untouched for the same reason — no recorded target folder name to apply, and out of scope once Spectacle itself was descoped.
- **Lock Session validation**: `dot kde save "kglobalshortcutsrc.ksmserver.Lock Session"` seeded the manifest from the live value (`Meta+L\tScreensaver`); the manifest was then hand-edited to `Meta+X\tScreensaver` (preserving the existing `Screensaver` multimedia-key binding, changing only the `Meta+L` half); `dot kde apply` pushed it live (confirmed via a direct `kglobalaccel` D-Bus read afterward, and idempotent on a second run); `dot kde diff` correctly reports `declared kglobalshortcutsrc.ksmserver.Lock Session = Meta+X\tScreensaver (default: Meta+L\tScreensaver)`.
`Meta+X` is now live and tracked; `keybindings.md` has a row for it.
- Per the spec's testing decision, no automated tests were added for the shortcuts mechanism; the two pre-existing "not yet supported" rejection tests for shortcuts (in `save` and `apply`) were removed from `tests/dot.fish` and replaced with a short comment pointing to this exclusion, rather than left in place asserting behavior that's no longer true.

View File

@@ -1,90 +0,0 @@
---
spec: dot-setup-folders
---
## What to build
A new `dot setup` subcommand family, following the project's existing
nested-subcommand dispatch convention. Bare `dot setup` (no arguments) runs
every machine-setup task unconditionally; `dot setup <task>` runs just that
one task. The only task that exists yet is `folders`.
`dot setup folders` brings the 8 standard XDG user directories under the
project's short-name convention (`Desktop→.desktop`, `Documents→doc`,
`Downloads→dwn`, `Music→mus`, `Pictures→pic`, `Videos→vid`, `Templates` and
`Public` both →`.ignoreme`). The desired short names live in a tracked
`user-dirs.dirs` file (a plain dotfile, not generated from a table each run).
A separate small hardcoded table maps each of the 8 standard XDG categories
to its legacy full-named folder, used only to locate content an XDG-defaults
install would have left behind, and merge it into the already-tracked
short-named target.
This slice covers the core happy path: a legacy folder found empty (strictly:
no entries at all, including dotfiles/metadata) is merged into its
short-named target silently, with no confirmation needed. As part of the same
`Pictures→pic` pass, a nested `Screenshots` folder is renamed to lowercase
`screenshots`, landing at `pic/screenshots`. After all folder moves complete,
run `xdg-user-dirs-update` (no arguments) once to notify running apps/portals.
`~/wrk` gets no XDG variable of its own and is out of scope for any mapping;
the existing ad hoc `~/Projects` folder is left alone.
Non-empty legacy folders and filename collisions are out of scope for this
slice (covered by later tasks) — for now it's acceptable for a non-empty
legacy folder to be handled in whatever minimal way unblocks the empty-folder
path (e.g. left untouched with a message), since the confirmation gate and
collision safety are built out next.
Wire the new command into the project's standard subcommand checklist: a
`_dot_setup_usage` help function reachable via `dot setup help` (and
`dot setup folders help` for the nested task), the completions/help-glob
duplication point, and a README command-table row.
## Acceptance criteria
- [x] `dot setup folders` on a fresh scratch `$HOME` (all 8 legacy folders
present and empty) renames them to their short-name targets per the
mapping table, including `Pictures/Screenshots→pic/screenshots`, and
leaves the tracked `user-dirs.dirs` short names in place
- [x] The fake `xdg-user-dirs-update` (PATH-prepended, logging its invocation
per the project's existing fake-`sudo`/fake-`pacman` testing pattern)
is invoked exactly once after a successful migration
- [x] Bare `dot setup` on a fresh scratch `$HOME` runs the `folders` task as
part of running everything
- [x] `dot setup folders help` and `dot setup help` print usage and make no
filesystem changes
- [x] Re-running `dot setup folders` after a clean migration is a no-op
(idempotent)
- [x] `~/.github/README.md` has a command-table row for `dot setup`
(and its `folders` task) with paths relative to `$HOME`
- [x] `~/.config/dot/tests/dot.fish` covers the above cases and
`fishtape ~/.config/dot/tests/dot.fish` passes
## Implementation Notes
- The desired short names for `dot setup folders` are read directly from the
tracked `~/.config/user-dirs.dirs` (parsed via `grep`/`string match`, not
sourced as shell), per the parent spec's decision that this file is the
single source of truth. This machine's real `user-dirs.dirs` was
deliberately left untouched/untracked and no live migration was run against
this machine's actual home directory — the user chose "code + tests only"
scope for this task (a real rename of `~/Desktop`, `~/Documents`, etc. is a
separate, explicit action to take later), so only the scratch-`$HOME`
fishtape fixtures exercise the short-name `user-dirs.dirs` content.
Tracking the real file and running the real migration remains open.
- During `/review-uncommitted`, the spec-fidelity pass caught a real bug: the
nested `Pictures/Screenshots→pic/screenshots` move ran unconditionally,
before checking whether `Pictures` held other, unrelated content — so a
`Pictures` folder with both `Screenshots/` and some other file got
partially mutated (Screenshots pulled out) while still being reported as
"left in place." Fixed by gating the Screenshots move on the rest of the
folder being empty too; added a regression test for this case
("Screenshots is not peeled off... when Pictures still has other
content").
- Completions (`~/.config/fish/completions/dot.fish`) got a `dot setup`
block mirroring `dot kde`'s per-subcommand completion entries, even though
the task's required "completions/help-glob duplication point" is already
satisfied automatically by the existing generic directory glob (no changes
were needed there for `dot setup`/`dot help` to discover the new nested
command). The added completions are a small polish addition beyond the
strict letter of the acceptance criteria, consistent with the existing
`kde` subcommand's treatment.

View File

@@ -1,52 +0,0 @@
---
spec: dot-setup-folders
blocked-by: 0006-setup-dispatcher-and-folders-core
---
## What to build
Extend `dot setup folders`'s migration so a legacy folder found non-empty
(any entry at all, including a stray dotfile or KDE metadata like a
`.directory` file, counts as non-empty) stops and prints what would be moved,
then refuses to proceed unless an explicit `--yes` flag was passed on the
command line — no interactive prompt. With `--yes`, the migration proceeds
for that folder the same way the empty-folder path already does.
This applies uniformly across all 8 mapped categories, including the nested
`Pictures/Screenshots→pic/screenshots` rename from the prior slice: a
non-empty `Screenshots` folder is also gated behind the same confirmation
rule.
## Acceptance criteria
- [x] A legacy folder with real content (a real file, not just an empty
directory) refuses to migrate without `--yes`, prints what would have
been moved, and leaves the folder and its contents untouched
- [x] The same legacy folder migrates successfully when `--yes` is passed
- [x] A legacy folder containing only a stray dotfile/metadata file (e.g. a
fake `.directory`) is still treated as non-empty and triggers the same
confirmation gate
- [x] `~/.config/dot/tests/dot.fish` covers the above cases and
`fishtape ~/.config/dot/tests/dot.fish` passes
## Implementation Notes
- `--yes`'s actual move reuses the exact same branch shape as the existing
silent-empty path (rename `Screenshots``screenshots` when present, then
`rmdir` the legacy folder), extended to also `mv` any remaining top-level
entries into the target first. Screenshots is always moved as one atomic
unit — its individual files are never mv'd/reported separately — so a
non-empty `Screenshots` (own acceptance criterion in the parent spec) is
gated and migrated the same way a non-empty top-level file would be.
- Collision handling (no-clobber `mv -n`, reporting skipped files, leaving the
legacy folder in place on a collision) is explicitly out of scope here —
it's owned by 0008-folders-collision-handling.md, per that task's own
frontmatter/spec section. The `--yes` path added here uses a plain `mv`.
- `/review-uncommitted` flagged two minor issues, both fixed: a stale comment
claiming a helper variable was used by both the silent-empty and `--yes`
paths when it was only read by the latter, and a duplicated `find`
invocation computing the same top-level listing twice under one condition
(now computed once and reused). It also flagged the non-empty "would move"
preview listing recursively-nested files individually instead of treating
`Screenshots` as one unit like the real move does — fixed so the preview
and the actual move share the same top-level-entries list.

View File

@@ -1,55 +0,0 @@
---
spec: dot-setup-folders
blocked-by: 0007-folders-non-empty-confirmation
---
## What to build
Make the `--yes`-confirmed merge from the prior slice collision-safe: when a
legacy folder and its short-named target both contain an entry with the same
name, use no-clobber move semantics so the target's existing file is never
silently overwritten. Report which files were skipped due to a collision, and
leave the legacy folder in place (don't remove it) whenever any collision
occurred during that folder's migration, rather than deleting a folder that
still holds something that couldn't be merged.
This closes the gap left by the old bash `setup_folders`'s naive `mv $from/*
$to`, which had no collision protection at all.
## Acceptance criteria
- [x] A filename collision between a legacy folder and its already-populated
short-named target is skipped, not overwritten (the target's existing
file is preserved byte-for-byte)
- [x] The skipped collision is reported to the user
- [x] The legacy folder is left in place (not removed) when a collision
occurred, even though `--yes` was given and other non-colliding files
in it were moved
- [x] Re-running `dot setup folders` after a collision was reported and left
in place behaves consistently (doesn't lose the previously-skipped
file, doesn't re-move already-migrated files)
- [x] `~/.config/dot/tests/dot.fish` covers the above cases and
`fishtape ~/.config/dot/tests/dot.fish` passes
## Implementation Notes
- The two prior branches (silent-empty merge vs. `--yes`-confirmed merge)
were unified into one `if test (count $other_entries) -eq 0; or set -q
_flag_yes` branch, since the collision-detection/no-clobber logic is
identical either way. This has one side effect beyond the letter of the
acceptance criteria (which frame collision handling around the `--yes`
path): a legacy folder that's otherwise "empty" except for an emptyish
nested `Screenshots` dir now also gets collision-checked against an
already-populated `pic/screenshots` on the silent, no-`--yes` path. This
closes the same unguarded-`mv` gap the spec calls out as the motivating
problem (the old code's silent-path `mv $screenshots_path
$target_path/screenshots` had no collision protection at all either), so
it was kept rather than special-cased away. Covered by its own test
("a silent-path Screenshots collision ...").
- Collision detection is a pre-check (`test -e $target_path/...`) before an
actual `mv -n`, rather than relying on `mv -n`'s exit code alone, so each
colliding entry can be individually identified and reported by path.
- `/review-uncommitted` (risk: Medium, standards: 0 hard violations, spec:
0 missing/wrong requirements) raised no changes needed; the one scope note
it flagged (the silent-path Screenshots case above) was a deliberate,
judged-correct decision rather than an oversight.

View File

@@ -1,51 +0,0 @@
---
blocked-by: 0005-kde-shortcuts-mechanism
---
## What to build
`dot kde save`'s tab-completion (`cmd_complete` in `commands/kde/kde.py`)
currently only enumerates schema-backed identifiers via
`iter_schema_identifiers` — it was built as a side effect of the `diff`
task (0003) and never revisited when the shortcuts mechanism (0005)
landed. Extend `cmd_complete` to also enumerate shortcut identifiers.
Source the shortcut identifiers live via `kglobalaccel`, mirroring how
schema identifiers are freshly parsed from `.kcfg` files on every call:
call `allMainComponents()` to get every registered component's
`componentUnique`, then `allActionsForComponent()` per component
(already used by `_resolve_shortcut_action_id`) to get every
`actionUnique`, yielding `kglobalshortcutsrc.<componentUnique>.<actionUnique>`
candidates. No caching — walk fresh on every invocation.
Print shortcut identifiers as their own block, after the existing
schema-backed block — not merged into one interleaved sorted list.
Keep them plain, with no friendly-name description text, matching the
existing schema-identifier output style.
If the D-Bus walk fails for any reason — a non-zero `busctl` exit
(`RuntimeError`, already raised by `_kglobalaccel_call`) or `busctl`
itself being missing (`OSError` from `subprocess.run`) — swallow it
silently: omit the shortcuts block, still print the schema block, and
emit no stderr diagnostic.
Freeform identifiers (e.g. `kxkbrc.Layout.Options`) are explicitly out
of scope for this task: there is no schema to enumerate them from, so
this stays a permanent, accepted completion gap, not something to fix
here.
## Acceptance criteria
- [x] `python3 kde.py complete` includes every currently-registered `kglobalshortcutsrc.<componentUnique>.<actionUnique>` identifier, sourced live via `allMainComponents`/`allActionsForComponent`
- [x] Schema-backed identifiers print first, followed by shortcut identifiers, as two distinct blocks — not interleaved into one merged sorted list
- [x] Shortcut identifiers print plain, with no friendly-name description text
- [x] If the D-Bus walk raises `RuntimeError` or `OSError`, the shortcuts block is omitted, the schema block still prints normally, and nothing is written to stderr
- [x] Freeform identifiers remain unlisted by `cmd_complete` (unchanged, confirmed not a regression)
- [x] Verified manually against a live session — no new automated tests, consistent with the existing shortcuts-mechanism test carve-out (spec's testing decisions, 0005's Implementation Notes)
## Implementation Notes
- `iter_shortcut_identifiers` (new, `commands/kde/kde.py`) walks `allMainComponents()` then `allActionsForComponent()` per component, yielding `kglobalshortcutsrc.<componentUnique>.<actionUnique>`. `cmd_complete` wraps that walk in `sorted(set(...))` and appends it as a second print loop after the existing schema-backed one, inside a `try/except (RuntimeError, OSError)` that falls back to an empty list on any failure — so a missing `busctl` or an unreachable D-Bus session degrades completion instead of breaking it.
- Manually verified both paths: live run on this machine prints 278 shortcut identifiers after 322 schema-backed ones; with `busctl` removed from `PATH` (simulating a non-KDE/minimal shell), `cmd_complete` still exits 0, prints only the 322 schema identifiers, and writes nothing to stderr.
- `/review-uncommitted`'s Standards pass flagged two judgement-call smells: (1) the D-Bus call/unpack idiom for `allActionsForComponent` was duplicated between the new function and `_resolve_shortcut_action_id`; (2) the silent `except` swallow had no comment explaining why. Fixed both: extracted a shared `_actions_for_component(component_unique)` helper used by both call sites, and added a comment on the `try` explaining that fish invokes this on every TAB press in shells that may lack a live KDE session, so a broken shortcuts source must never cost the already-printed schema candidates. Re-ran the full test suite (101/101 pass) and both manual checks after the fix.
- No automated tests added, per the task's own acceptance criterion and the shortcuts mechanism's existing test carve-out (0005's Implementation Notes: a live D-Bus session isn't practically substitutable without disproportionate mock infrastructure).

View File

@@ -1,102 +0,0 @@
---
blocked-by: [0005-kde-shortcuts-mechanism, 0009-kde-shortcut-completion]
---
## What to build
`dot kde diff`'s broad-scan (the pass that reports *undeclared* drift, not
just already-declared entries) currently only walks schema-backed
identifiers via `iter_schema_identifiers`. Shortcuts are treated the same
as freeform in `cmd_diff` -- checked only when already present in the
manifest -- per the code comment at the top of that loop. That comment is
overstated for shortcuts: unlike freeform, which genuinely has no
enumeration source, shortcuts *are* enumerable via `kglobalaccel`'s
`allMainComponents`/`allActionsForComponent`, and `iter_shortcut_identifiers`
(added in 0009 for tab-completion) already walks exactly that.
Add a second broad-scan pass in `cmd_diff`, after the existing schema-backed
one, over `sorted(set(iter_shortcut_identifiers()))`: for each identifier,
compare `shortcutKeys` against `defaultShortcutKeys` (the same live/default
read already used for declared shortcuts), and tag `declared`/`undeclared`
exactly like the schema loop. Remove the shortcuts branch from the
manifest-only loop below it (now redundant), leaving that loop for freeform
only, since freeform is the only mechanism that still can't be enumerated.
Tolerate two failure modes without aborting the whole command:
- The enumeration call itself (`allMainComponents`) failing (no live
session, no `busctl`) -- print one diagnostic to stderr and skip the
shortcuts block entirely, same as any other reported problem in `diff`.
- An individual action failing to resolve (`_resolve_shortcut_action_id`
raising because its owning app hasn't registered with kglobalaccel this
session) -- print that one identifier's error to stderr and continue,
matching the schema loop's existing per-identifier tolerance.
Update `DIFF_USAGE` to reflect that shortcuts now participate in broad-scan
alongside schema-backed settings, leaving only freeform as declared-only.
## Acceptance criteria
- [x] `dot kde diff` reports undeclared shortcut drift (a shortcut changed
from its packaged default but never `dot kde save`d) without requiring
it to be in the manifest first
- [x] Already-declared shortcut drift is still reported, tagged `declared`,
with no duplicate line from the old manifest-only loop
- [x] A shortcut belonging to an app that hasn't registered with kglobalaccel
this session produces one stderr diagnostic for that identifier and
does not stop the rest of the scan (schema block, other shortcuts,
freeform block) from completing
- [x] If the `allMainComponents` enumeration itself fails (no `busctl`, no
live session), `diff` prints one diagnostic, skips the shortcuts block,
and still completes the schema and freeform passes, exiting 0
- [x] Freeform remains declared-only (unchanged) -- only its loop comment and
the removed shortcuts branch change
- [x] `DIFF_USAGE` text updated to describe shortcuts as broad-scanned
- [x] Verified manually against the real session (consistent with the
shortcuts mechanism's existing test carve-out, 0005/0009) -- no new
automated tests
- [x] Full existing test suite still passes unchanged
## Implementation Notes
- `cmd_diff` (`commands/kde/kde.py`) gained a second broad-scan pass between
the existing schema-backed loop and the manifest-only loop: it walks
`sorted(set(iter_shortcut_identifiers()))` (the same enumeration
`cmd_complete` already uses), compares `shortcutKeys` against
`defaultShortcutKeys` per identifier, and tags `declared`/`undeclared`
exactly like the schema loop.
- The manifest-only loop below it lost its `shortcuts` branch entirely
(`resolve_mechanism` returning `"shortcuts"` now just falls through
`if mechanism != "freeform": continue`), since the new broad-scan pass
already reports every declared shortcut mismatch -- keeping the old branch
would have double-printed them.
- Two failure modes, handled at different granularity: `iter_shortcut_identifiers()`
itself is wrapped in `try/except (RuntimeError, OSError)` -- a failure there
(no live session, missing `busctl`) prints one diagnostic and skips the
whole shortcuts block, letting the schema and freeform passes still run.
Inside the per-identifier loop, `read_shortcut_value` raising `RuntimeError`
(an app that hasn't registered with kglobalaccel this session yet) prints
one diagnostic for that identifier and continues, matching the schema
loop's existing per-identifier tolerance.
- Real-world validation on this machine: manually ran the same enumeration in
a throwaway script before implementing, confirming 29 of 278 registered
shortcuts differed from default (the Meta+1-9 desktop-switch remap,
Meta+Shift+1-9 window-to-desktop binds, and Meta+A/Meta+Shift+A activity
switching) -- all 29 were `dot kde save`d into the manifest in the same
session as a prerequisite for testing this cleanly. After implementing,
`dot kde diff` reported all 30 shortcuts (29 plus the pre-existing
`ksmserver.Lock Session`) as `declared` with correct default values, and
~34 unrelated `RuntimeError`s for apps not launched this session (Konsole,
Spectacle, Dolphin, etc.) printed to stderr without aborting the scan.
Removing one entry (`kwin.Switch to Desktop 1`) from the manifest and
re-running confirmed it flips to `undeclared` with the same live/default
values, then restoring the manifest flipped it back to `declared` --
confirms both tags work and the manifest was left untouched by `diff`
itself (read-only, as documented).
- Full test suite re-run after the change: 101/101 pass, unchanged from
before this task. No automated tests added for the new pass itself, per
the shortcuts mechanism's existing carve-out (0005's Implementation Notes:
a live `kglobalaccel` D-Bus session isn't practically substitutable without
disproportionate mock infrastructure) -- the existing tests already
exercise `dot kde diff` against the real live session and continued to
pass with the new pass active, incidentally covering that it doesn't break
anything even though it isn't asserting on the new pass's own output.

View File

@@ -1,79 +0,0 @@
---
spec: dot-setup-folders
blocked-by: 0008-folders-collision-handling
---
## What to build
Remove the `--yes` confirmation gate that 0007/0008 built: a legacy folder
with real content in it is migrated unconditionally now, the same as an
empty one, since the collision handling from 0008 already makes the merge
non-destructive on its own (a same-named entry is never overwritten, and the
legacy folder is kept whenever any collision occurred). The `--yes` gate
turned out to protect against a scenario collision handling already
prevents, while making the everyday case — a machine that already has real
files in `~/Documents`, `~/Pictures`, etc. — a silent no-op unless the flag
was remembered, which defeats the point of the task.
In its place:
- `dot setup folders` always attempts the merge for every legacy folder,
content or none.
- A new `--dry-run` flag replaces `--yes` in the flag slot: it reports what
would move and what would be skipped as a collision, without touching the
filesystem at all (no `mkdir`, no `mv`/`rmdir`, no `xdg-user-dirs-update`).
- A real (non-dry-run) run now reports what it moved per legacy folder
(e.g. `moved 12 entries from ~/Documents to ~/doc`), instead of staying
silent on success. A folder where nothing top-level moved (already empty,
or everything in it collided) prints no such line — only non-trivial moves
and collisions produce output.
- `--yes` is removed outright (not kept as a silent no-op): passing it now
fails with argparse's standard unknown-option error.
## Acceptance criteria
- [x] A legacy folder with real content merges on a plain `dot setup
folders`, with no flag required
- [x] A real run prints `moved N entries from ~/<legacy> to ~/<target>` for a
folder where top-level entries actually moved, and nothing for a
folder where none did
- [x] A real run prints a dedicated line when the nested Screenshots folder
itself is moved (e.g. `moved ~/Pictures/Screenshots to ~/pic/screenshots`)
- [x] Collision detection/reporting and the "leave the legacy folder in
place when a collision occurred" behavior from 0008 are unchanged
under the new unconditional default
- [x] `--dry-run` reports the same would-move/would-skip information without
creating any target directory, moving/removing anything, or invoking
`xdg-user-dirs-update`
- [x] `dot setup folders --yes` fails with an unknown-option error (argparse
default), rather than being silently accepted or gated on
- [x] `dot setup folders help` output no longer mentions `--yes` and
documents `--dry-run` instead
- [x] Idempotency holds: re-running after a clean merge, and re-running
after a collision was reported, both behave the same as before
- [x] `~/.config/dot/tests/dot.fish` is updated to exercise the above
(replacing the old `--yes`-gated cases) and
`fishtape ~/.config/dot/tests/dot.fish` passes
## Implementation Notes
- The `--yes` gate and the `screenshots_emptyish`/`other_entries` machinery
that computed it were deleted outright rather than special-cased away:
once merging is unconditional, that machinery had no remaining purpose
(it existed solely to decide "empty enough to skip the gate").
- `mkdir -p $target_path` and the final `xdg-user-dirs-update` are both now
guarded by `not set -q _flag_dry_run`, making `--dry-run` a true no-op
rather than "no-op except for directory scaffolding."
- Collision detection (`test -e $target_path/...`) runs identically in both
modes; `--dry-run` only gates the actual `mv`/`rmdir`/`mkdir` calls, so the
reported would-move/would-skip split is exactly what a real run would do.
- Success reporting is per-legacy-folder and suppressed at zero: a folder
that was already empty (or whose only entries all collided) prints
nothing, so a routine re-run stays quiet like before.
- All prior collision/idempotency/Screenshots test scenarios were kept,
just re-pointed at the plain `dot setup folders` invocation instead of
`--yes`; two scenarios that only differed by which code branch (`--yes`
vs. silent-empty) they exercised now hit the same branch, but were both
kept since they still cover distinct fixture shapes (Pictures with vs.
without unrelated top-level content alongside a colliding Screenshots).
- `fishtape ~/.config/dot/tests/dot.fish` passes (178 tests).

View File

@@ -1,64 +0,0 @@
---
spec: dot-setup-folders
blocked-by: 0011-folders-unconditional-merge
---
## What to build
Stop reading the short-name target from `~/.config/user-dirs.dirs` and
hardcode the legacy-name -> short-name mapping directly in
`_dot_setup_folders`, dropping the dependency on that file entirely.
The original design treated the tracked `user-dirs.dirs` as the single
source of truth for target names, assuming someone would hand-edit it to
the short names before ever running the command. On this machine that
never happened: the tracked file still had the stock XDG defaults
(`XDG_DOCUMENTS_DIR="$HOME/Documents"`, etc.), so `target_path` resolved to
the exact same directory as `legacy_path` for every folder. The migration
logic then reported every entry as a "collision" against itself instead of
moving anything -- a confusing, silent-feeling failure rather than an
actual migration.
The short names are fixed (`.desktop`, `doc`, `dwn`, `mus`, `pic`, `vid`,
`.ignoreme`) and not meant to be configurable, so there's nothing to read
from a file in the first place. `user-dirs.dirs` remains a separate,
manually tracked dotfile (edited and tracked by hand, like any other
dotfile) for apps/`xdg-user-dirs-update` to consult -- `dot setup folders`
itself no longer reads it, requires its presence, or writes to it.
## Acceptance criteria
- [x] `_dot_setup_folders` no longer reads, parses, or requires
`~/.config/user-dirs.dirs`; the legacy->short-name mapping is a fixed
table in the function itself
- [x] Migration works identically whether `user-dirs.dirs` is absent,
empty, or declares stale/full-name values (the exact real-world case)
- [x] `user-dirs.dirs` is left byte-for-byte untouched by `dot setup
folders` when present, and no file is created when absent
- [x] `dot setup folders help` no longer describes reading target names
from `user-dirs.dirs`
- [x] `~/.config/dot/tests/dot.fish` no longer seeds a `user-dirs.dirs`
fixture as a migration precondition, and covers the stale/missing
cases above; `fishtape ~/.config/dot/tests/dot.fish` passes
## Implementation Notes
- Replaced the `xdg_vars`/`grep`/`string match` parsing of `user-dirs.dirs`
with two parallel hardcoded arrays, `legacy_names` and `target_names`,
indexed together -- same shape the code already used for `legacy_names`
alone, just extended to cover the target side too.
- The early `if not test -f $user_dirs; return 1` guard was deleted outright
rather than kept as a soft check: there's nothing left for the function to
read from that file, so requiring its existence would just be a
vestigial, unjustifiable precondition.
- Removed the `short_name_user_dirs` fixture and its seeding step from every
test scenario (it was previously duplicated into ~15 scenarios as a
migration precondition); added two new scenarios instead: one reproducing
the exact real-machine bug (stale full-name `user-dirs.dirs` values) and
one confirming migration works with no `user-dirs.dirs` file at all.
- Verified against this machine's real, still-stale `~/.config/user-dirs.dirs`
via `_dot_setup_folders --dry-run`: previously reported every entry in
Desktop/Documents/Downloads/Pictures/Videos as a collision against
itself; now correctly reports `would move N entries from ~/Documents to
~/doc` etc.
- `fishtape ~/.config/dot/tests/dot.fish` passes (183 tests).

View File

@@ -1,167 +0,0 @@
# Dotfiles
This machine's dotfiles are a bare git repo at `~/.dotfiles`, checked out with
`$HOME` as its work-tree. The `dot` fish function wraps that invocation
(`git --git-dir=~/.dotfiles --work-tree=$HOME $argv`, declared with
`--wraps=git`), so every git subcommand works through it: `dot status`,
`dot add`, `dot commit`, `dot push`, etc.
This directory (`~/.config/dot`) holds the `dot` CLI's custom subcommands,
tests, and package lists, but the repo tracks files across `$HOME` — fish
config, git identity, the `dot` function itself, and more. To see everything
tracked, run `dot ls-tree -r --name-only HEAD` from `$HOME` (paths are shown
relative to cwd, so running it from elsewhere silently truncates the list).
For an agent driving this through separate tool calls: `cd ~` in one call does
not reliably carry over to the next, since each call may reset to the
project's working directory. Always `cd "$HOME"` and run the `ls-tree` (or any
other cwd-sensitive `dot`/`git` command) in that *same* call — e.g.
`cd "$HOME" && dot ls-tree -r --name-only HEAD` — rather than trusting a prior
`cd` to have stuck. Getting this wrong silently narrows the listing to
whatever the leftover cwd happens to be, which reads as "this file isn't
tracked" when it actually is.
## Always add by explicit path
`status.showUntrackedFiles=no` is set locally (see `dot init` below), and
`.gitignore` only excludes `.dotfiles` itself plus OS/editor cruft — it is
**not** a whitelist. That
means virtually everything under `$HOME` reads as untracked, and `git status`
deliberately hides all of it.
**Always run `dot add <specific-path>`.** Never `dot add -A`, `dot add .`, or
any wildcard add — that would try to stage the entire home directory (caches,
secrets, everything).
**Stage automatically after changes.** Once a tracked file is edited, run
`dot add <specific-path>` for it right away rather than waiting to be asked —
one explicit path per changed file, still never a wildcard. This does not
extend to `dot commit` or `dot push`, which still require an explicit
request.
## The dot CLI
### Architecture
`dot` is defined in one file: `~/.config/fish/functions/dot.fish`. It holds
three functions:
- `dot` (`--wraps=git`) — dispatches `init`, `help`, and any file found under
`~/.config/dot/commands/`, otherwise forwards everything to
`git --git-dir=~/.dotfiles --work-tree=$HOME $argv` (full passthrough).
- `__dot_init` — the bootstrap logic, inlined in the same file rather than
autoloaded separately, because it's the one subcommand that must work
before the dotfiles repo has ever been cloned onto a machine.
- `__dot_help` — prints usage: the built-in commands plus whatever is
currently found under `~/.config/dot/commands/`, generated by globbing that
directory rather than a hardcoded list, so it can't drift from reality.
`__dot_help`'s glob over `~/.config/dot/commands/*.fish` is duplicated in
`~/.config/fish/completions/dot.fish`'s `__dot_custom_subcommands` rather than
shared: fish only autoloads a function from a file named after that function,
so a helper defined inside `dot.fish` would be undefined if tab-completion
ran before `dot` had ever been sourced in the session. Keep both copies in
sync when the listing logic changes.
Both copies also glob one directory level deeper, matching `~/.config/dot/commands/<name>/<name>.fish`, so a subcommand's companion file (e.g. a Python helper) can live alongside it in its own directory.
`dot init`:
- refuses to run if `~/.dotfiles` already exists (no re-init support)
- clones the bare repo from `--url` (default: the hardcoded Gitea remote) —
if the clone fails, it errors out; it never falls back to `git init`
- backs up any pre-existing file that checkout would clobber into
`~/.dotfiles-backup/<timestamp>/`, then retries the checkout
- explicitly sets `status.showUntrackedFiles=no` after cloning — this is a
local-only git setting, so a fresh `git clone` never carries it over
### Adding a subcommand
Beyond `init`, `dot` looks for `~/.config/dot/commands/<name>.fish`, sources
it, and calls `_dot_<name>`.
A subcommand needing a companion file can instead live nested one level deeper, as `~/.config/dot/commands/<name>/<name>.fish` — both layouts dispatch identically.
These files are deliberately kept out of
`~/.config/fish/functions/` (fish's autoload path) so they never become
independently invokable top-level commands or clutter tab-completion outside
of `dot` itself.
1. Create `~/.config/dot/commands/<name>.fish` defining a `_dot_<name>`
function.
2. Confirm `dot <name>` dispatches to it. No other wiring is needed —
`~/.config/fish/completions/dot.fish` and `__dot_help` both discover new
command files by globbing that directory, and `--wraps=git` still covers
raw git subcommands.
3. Implement a `help` subcommand: check for `help` as `_dot_<name>`'s first
positional argument before `argparse`, and call a `_dot_<name>_usage`
function that prints usage and every flag. If `_dot_<name>` itself
dispatches to nested subcommands, apply this same check-then-dispatch
pattern at that level too — there's no central `--help` handling in
`dot.fish` to lean on; each level is responsible for its own.
`_dot_<name>_usage` should print its text as a single multi-line
`echo "..."` string (fish preserves literal newlines inside double
quotes) rather than one `echo` per line.
4. Add a row to `~/.github/README.md`'s command table for it — one row per
distinct use case, with paths written relative to `$HOME`
(`~/.config/dot/...`), not relative to the README's own location.
5. Add a case to `~/.config/dot/tests/dot.fish` covering it, including its
`help` output, and run `fishtape ~/.config/dot/tests/dot.fish` until it
passes.
### Testing
Tests live at `~/.config/dot/tests/dot.fish`, run with
`fishtape ~/.config/dot/tests/dot.fish`. Fishtape is installed via Fisher
(`fisher install jorgebucaran/fishtape`) and tracked in
`~/.config/fish/fish_plugins` — a real, restorable dependency for developing
`dot`, but never required just to use it.
- Each scenario overrides `$HOME` (`set -gx HOME (mktemp -d)`) before calling
`dot`, so tests never touch the real `~/.dotfiles`.
- Build a throwaway bare "remote" fixture with `git init --bare` plus a
seeded commit, and explicitly set its `HEAD`
(`git --git-dir=$remote symbolic-ref HEAD refs/heads/main`). Pushing with
`git push origin HEAD:main` does **not** update the bare repo's `HEAD`
symref — skip this and a clone of the fixture can end up "on a branch yet
to be born."
- Don't use `.gitconfig` as a fake pre-existing "conflict" file in a
fixture — git parses `$HOME/.gitconfig` as its own global config on every
invocation, and garbage content there spams "key does not contain a
section" errors that drown out the real assertion. Use a harmless file
like `.bashrc` instead.
- `@test "description" <expr> <op> <expected>` mirrors fish's `test` builtin
(`-eq`, `-ne`, `=`, `-e`, `-f`, `-d`, `-n`, `-z`); `-a`/`-o` combinators
aren't supported.
## Gotchas
- `~/.claude/` (Claude Code's own config: skills, agents, commands, etc.) is
a plain directory, not a separate git repo of its own — plain `git` commands
run from inside it report "not a git repository". It's tracked the same way
as everything else under `$HOME`: through the `dot` bare repo. Use
`dot add`/`dot status` on paths under `~/.claude/`, not a `git` invocation
scoped to that directory, and don't assume an unrelated repo (e.g. a
separate skills-source checkout elsewhere) is the tracked copy just because
it also holds a copy of the same files.
- `~/.claude/` and this project's own `.claude/` (e.g. `~/.config/dot/.claude/`)
are two different directories that both happen to exist. Project-relative
paths referenced in specs, task breakdowns, or other project docs — like
`.claude/spec/<slug>.md` or `.claude/tasks/<NNNN>-<slug>.md` — are relative
to this project directory (`~/.config/dot/.claude/...`), not to
`$HOME/.claude/`. Writing to `$HOME/.claude/tasks/` instead of
`~/.config/dot/.claude/tasks/` silently lands files in Claude Code's own
global config dir instead of the project.
- An agent's `Bash` tool runs commands through **zsh**, not fish, so the
`dot` fish function (defined in `~/.config/fish/functions/dot.fish`) is
not on that shell's autoload path. Typing `dot <subcommand>` there
silently resolves to `/usr/bin/dot` (Graphviz) instead, producing
confusing "can't open <arg>: No such file or directory" / "syntax error
near '--'" errors rather than a clear "command not found". Either invoke
it as `fish -c "dot <subcommand> ..."`, or bypass the wrapper and call
`git --git-dir=$HOME/.dotfiles --work-tree=$HOME <args>` directly.
## Keybindings
Whenever a keybind is added, changed, or removed in *any* config on this
machine (tmux, KDE, neovim, fish, whatever), add or update its row in
[`~/.github/keybindings.md`](../../.github/keybindings.md) in the same
change. That file is the single reference for every keybind across tools —
it drifts the moment a bind changes somewhere without a matching edit there.

View File

@@ -1,59 +0,0 @@
function _dot_install_usage
echo "usage: dot install [--restore] [--no-sync] [package ...]
--restore reinstall every package from the tracked list
--no-sync skip 'pacman -Sy' before installing"
end
function _dot_install
if test "$argv[1]" = help
_dot_install_usage
return 0
end
argparse 'restore' 'no-sync' -- $argv
or return 1
set -l list_dir $HOME/.config/dot/packages
set -l list_file $list_dir/pacman
set -l packages
if set -q _flag_restore
if test (count $argv) -gt 0
echo "dot install: --restore cannot be combined with package names" >&2
return 1
end
if not test -s $list_file
echo "dot install: no package list found at $list_file" >&2
return 1
end
set packages (cat $list_file)
else
if test (count $argv) -eq 0
echo "dot install: no packages given (use --restore to reinstall from the list)" >&2
return 1
end
set packages $argv
end
if not set -q _flag_no_sync
sudo pacman -Sy
or return 1
end
sudo pacman -S --needed $packages
or return 1
if set -q _flag_restore
return 0
end
mkdir -p $list_dir
test -f $list_file
or touch $list_file
printf '%s\n' $packages >>$list_file
sort -u -o $list_file $list_file
end

View File

@@ -1,35 +0,0 @@
function _dot_kde_usage
echo "usage: dot kde <command>
Commands:
apply push manifest entries onto the live system
diff scan for settings whose live value differs from its default
save write live KDE settings into the manifest
help show this message
Run 'dot kde <command> help' for flags on a specific command."
end
function _dot_kde
if test "$argv[1]" = help
_dot_kde_usage
return 0
end
set -l helper_dir (status dirname)
switch "$argv[1]"
case apply
python3 $helper_dir/kde.py apply $argv[2..-1]
return $status
case diff
python3 $helper_dir/kde.py diff $argv[2..-1]
return $status
case save
python3 $helper_dir/kde.py save $argv[2..-1]
return $status
case '*'
_dot_kde_usage
return 1
end
end

View File

@@ -1,535 +0,0 @@
#!/usr/bin/env python3
import json
import os
import subprocess
import sys
import xml.etree.ElementTree as ET
from collections import defaultdict, namedtuple
from pathlib import Path
KCFG_NS = "{http://www.kde.org/standards/kcfg/1.0}"
DEFAULT_SCHEMA_DIR = "/usr/share/config.kcfg"
KGLOBALACCEL_SERVICE = "org.kde.kglobalaccel"
KGLOBALACCEL_PATH = "/kglobalaccel"
KGLOBALACCEL_IFACE = "org.kde.KGlobalAccel"
# KGlobalAccel::GlobalShortcutLoading::NoAutoloading, per KF6/KGlobalAccel/kglobalaccel.h --
# makes a write always win over whatever shortcut was previously saved, rather than being
# ignored in favor of it (the Autoloading=0x0 default).
SHORTCUT_NO_AUTOLOADING = 0x4
# .kcfg files that only declare their target rc file at runtime
# (<kcfgfile arg="true">), so it can't be discovered by scanning.
ARG_TRUE_RCFILES = {
"kwin.kcfg": "kwinrc",
}
SAVE_USAGE = """usage: dot kde save [identifier]
identifier declare a new manifest entry, seeded from its current live value
(no args) refresh every already-declared manifest entry from the live system
help show this message"""
APPLY_USAGE = """usage: dot kde apply
Pushes every manifest entry's declared value onto the live system.
help show this message"""
DIFF_USAGE = """usage: dot kde diff
Scans every schema-backed setting reachable through the kcfg mapping
table, and every shortcut registered with kglobalaccel, reporting each
one whose live value differs from its default, tagged declared
(present in the manifest) or undeclared. Also reports already-declared
freeform settings whose live value differs from their default (no
schema to broad-scan, so it's only checked when already declared).
Read-only -- never writes the manifest or the live system.
help show this message"""
Setting = namedtuple("Setting", ["file", "group", "key"])
def _split_on_known_prefix(rest, candidates):
matches = [c for c in candidates if rest == c or rest.startswith(c + ".")]
if not matches:
return None
prefix = max(matches, key=len)
remainder = rest[len(prefix):].lstrip(".")
if not remainder:
return None
return prefix, remainder
def _known_schema_groups(file, kcfg_map):
groups = set()
for path in kcfg_map.get(file, []):
root = _parse_kcfg(path)
if root is None:
continue
for group_elem in root.iter(f"{KCFG_NS}group"):
name = group_elem.get("name")
if name:
groups.add(name)
return groups
def _split_schema_group_key(file, rest, kcfg_map):
match = _split_on_known_prefix(rest, _known_schema_groups(file, kcfg_map))
if match is not None:
return match
# No schema group matches -- freeform. Its group is never known to contain
# a dot (there's no schema to have told us otherwise), so the boundary is
# just the first remaining dot.
group, _, key = rest.partition(".")
if not key:
raise ValueError(f"invalid identifier {file}.{rest!r} (expected file.group.key)")
return group, key
def _split_shortcut_group_key(rest):
(components,) = _kglobalaccel_call("allMainComponents", None)
match = _split_on_known_prefix(rest, [component[0] for component in components])
if match is None:
raise RuntimeError(
f"no live kglobalaccel component matches {rest!r} "
"(the owning application may need to run once to register its shortcuts with kglobalaccel)"
)
return match
# Only the file segment is unambiguous (rc file names never contain a dot).
# The group/key boundary can't be found by counting dots -- both KConfig group
# names (e.g. "org.kde.kdecoration2") and kglobalaccel componentUnique names
# (e.g. "org.kde.dolphin.desktop") routinely contain their own dots -- so it's
# resolved against known-good data instead: the live kglobalaccel component
# list for shortcuts, the kcfg schema's declared group names for everything
# else (falling back to freeform's first-dot split when no schema matches).
def parse_identifier(identifier, kcfg_map):
file, sep, rest = identifier.partition(".")
if not sep or not rest:
raise ValueError(f"invalid identifier {identifier!r} (expected file.group.key)")
if file == "kglobalshortcutsrc":
group, key = _split_shortcut_group_key(rest)
else:
group, key = _split_schema_group_key(file, rest, kcfg_map)
return Setting(file, group, key)
def load_manifest(path):
entries = {}
if not path.exists():
return entries
for line in path.read_text().splitlines():
if not line.strip():
continue
identifier, _, value = line.partition("=")
entries[identifier] = value
return entries
def write_manifest(path, entries):
lines = [f"{identifier}={value}" for identifier, value in entries.items()]
path.write_text("".join(f"{line}\n" for line in lines))
def _parse_kcfg(path):
try:
return ET.parse(path).getroot()
except ET.ParseError:
return None
def _kcfgfile_name(root):
elem = root.find(f"{KCFG_NS}kcfgfile")
if elem is None:
return None
return elem.get("name")
def build_kcfg_map(schema_dir):
mapping = defaultdict(list)
if not schema_dir.is_dir():
return mapping
for path in sorted(schema_dir.glob("*.kcfg")):
root = _parse_kcfg(path)
if root is None:
continue
rcfile = _kcfgfile_name(root) or ARG_TRUE_RCFILES.get(path.name)
if rcfile:
mapping[rcfile].append(path)
return mapping
def find_schema_default(kcfg_paths, setting):
for path in kcfg_paths:
root = _parse_kcfg(path)
if root is None:
continue
for group_elem in root.iter(f"{KCFG_NS}group"):
if group_elem.get("name") != setting.group:
continue
for entry in group_elem.findall(f"{KCFG_NS}entry"):
if (entry.get("key") or entry.get("name")) != setting.key:
continue
default_elem = entry.find(f"{KCFG_NS}default")
return default_elem.text if default_elem is not None and default_elem.text else ""
return None
def iter_schema_identifiers(kcfg_map):
for rcfile, paths in kcfg_map.items():
for path in paths:
root = _parse_kcfg(path)
if root is None:
continue
for group_elem in root.iter(f"{KCFG_NS}group"):
group = group_elem.get("name")
if not group:
continue
for entry in group_elem.findall(f"{KCFG_NS}entry"):
key = entry.get("key") or entry.get("name")
if key:
yield Setting(rcfile, group, key)
def resolve_mechanism(setting, kcfg_map):
if setting.file == "kglobalshortcutsrc":
return "shortcuts", None
default = find_schema_default(kcfg_map.get(setting.file, []), setting)
if default is not None:
return "schema", default
return "freeform", None
def read_live_value(setting, default):
cmd = ["kreadconfig6", "--file", setting.file, "--group", setting.group, "--key", setting.key]
if default is not None:
cmd += ["--default", default]
result = subprocess.run(cmd, capture_output=True, text=True)
if result.returncode != 0:
raise RuntimeError(
f"kreadconfig6 failed for {setting.file}/{setting.group}/{setting.key}: {result.stderr.strip()}"
)
return result.stdout.rstrip("\n")
def write_live_value(setting, value):
cmd = [
"kwriteconfig6",
"--file", setting.file,
"--group", setting.group,
"--key", setting.key,
"--",
value,
]
result = subprocess.run(cmd, capture_output=True, text=True)
if result.returncode != 0:
raise RuntimeError(
f"kwriteconfig6 failed for {setting.file}/{setting.group}/{setting.key}: {result.stderr.strip()}"
)
def _key_sequence_class():
try:
from PyQt6.QtGui import QKeySequence
except ImportError as e:
raise RuntimeError(
"the shortcuts mechanism requires PyQt6 (install python-pyqt6) to translate key names"
) from e
return QKeySequence
def _keys_to_string(key_ints):
QKeySequence = _key_sequence_class()
return "\t".join(QKeySequence(key).toString() for key in key_ints)
def _string_to_keys(value):
if not value:
return []
QKeySequence = _key_sequence_class()
keys = []
for part in value.split("\t"):
part = part.strip()
if not part or part.lower() == "none":
continue
sequence = QKeySequence(part)
if sequence.count() != 1:
raise RuntimeError(f"invalid key sequence {part!r} (expected exactly one key combination)")
keys.append(int(sequence[0].toCombined()))
return keys
def _kglobalaccel_call(method, signature, *tokens):
cmd = ["busctl", "--user", "--json=short", "call",
KGLOBALACCEL_SERVICE, KGLOBALACCEL_PATH, KGLOBALACCEL_IFACE, method]
if signature:
cmd += [signature, *(str(token) for token in tokens)]
result = subprocess.run(cmd, capture_output=True, text=True)
if result.returncode != 0:
raise RuntimeError(f"kglobalaccel {method} failed: {result.stderr.strip()}")
return json.loads(result.stdout)["data"]
def _actions_for_component(component_unique):
(actions,) = _kglobalaccel_call("allActionsForComponent", "as", 1, component_unique)
return actions
def iter_shortcut_identifiers():
(components,) = _kglobalaccel_call("allMainComponents", None)
for component in components:
for action in _actions_for_component(component[0]):
yield Setting("kglobalshortcutsrc", action[0], action[1])
def _resolve_shortcut_action_id(component_unique, action_unique):
for action in _actions_for_component(component_unique):
if action[0] == component_unique and action[1] == action_unique:
return action
raise RuntimeError(
f"no shortcut action {action_unique!r} in component {component_unique!r} "
"(the owning application may need to run once to register its shortcuts with kglobalaccel)"
)
# The plural *Keys methods (a(ai), one 4-int QKeyCombination chord slot per bound
# key sequence) are used instead of the singular shortcut()/defaultShortcut()/
# setShortcut() methods the flat ai signature suggests: on this KF6 build,
# defaultShortcut() was empirically found to just mirror shortcut() -- returning
# whatever the *current* value is rather than the true packaged default -- while
# defaultShortcutKeys() correctly returns the untouched default even after
# setShortcutKeys() has changed the current value. Only single, non-chorded key
# combinations are supported (see _string_to_keys), so only the first of each
# chord's 4 int slots is ever meaningful here; the rest are always 0.
def _keys_from_chords(chords):
return [chord[0][0] for chord in chords]
def read_shortcut_value(component_unique, action_unique, method="shortcutKeys"):
action_id = _resolve_shortcut_action_id(component_unique, action_unique)
(chords,) = _kglobalaccel_call(method, "as", len(action_id), *action_id)
return _keys_to_string(_keys_from_chords(chords))
def write_shortcut_value(component_unique, action_unique, value):
action_id = _resolve_shortcut_action_id(component_unique, action_unique)
keys = _string_to_keys(value)
tokens = [len(action_id), *action_id, len(keys)]
for key in keys:
tokens += [4, key, 0, 0, 0]
tokens.append(SHORTCUT_NO_AUTOLOADING)
_kglobalaccel_call("setShortcutKeys", "asa(ai)u", *tokens)
def save_one(identifier, kcfg_map):
setting = parse_identifier(identifier, kcfg_map)
mechanism, default = resolve_mechanism(setting, kcfg_map)
if mechanism == "shortcuts":
return read_shortcut_value(setting.group, setting.key)
return read_live_value(setting, default)
def apply_one(identifier, value, kcfg_map):
setting = parse_identifier(identifier, kcfg_map)
mechanism, _default = resolve_mechanism(setting, kcfg_map)
if mechanism == "shortcuts":
write_shortcut_value(setting.group, setting.key, value)
return
write_live_value(setting, value)
def cmd_save(args, manifest_path, schema_dir):
if args and args[0] == "help":
print(SAVE_USAGE)
return 0
if len(args) > 1:
print("dot kde save: too many arguments", file=sys.stderr)
return 1
kcfg_map = build_kcfg_map(schema_dir)
manifest = load_manifest(manifest_path)
try:
if args:
manifest[args[0]] = save_one(args[0], kcfg_map)
else:
for identifier in manifest:
manifest[identifier] = save_one(identifier, kcfg_map)
except (ValueError, RuntimeError) as e:
print(f"dot kde save: {e}", file=sys.stderr)
return 1
write_manifest(manifest_path, manifest)
return 0
def cmd_apply(args, manifest_path, schema_dir):
if args and args[0] == "help":
print(APPLY_USAGE)
return 0
if args:
print("dot kde apply: too many arguments", file=sys.stderr)
return 1
kcfg_map = build_kcfg_map(schema_dir)
manifest = load_manifest(manifest_path)
try:
for identifier, value in manifest.items():
apply_one(identifier, value, kcfg_map)
except (ValueError, RuntimeError) as e:
print(f"dot kde apply: {e}", file=sys.stderr)
return 1
return 0
def cmd_diff(args, manifest_path, schema_dir):
if args and args[0] == "help":
print(DIFF_USAGE)
return 0
if args:
print("dot kde diff: too many arguments", file=sys.stderr)
return 1
kcfg_map = build_kcfg_map(schema_dir)
manifest = load_manifest(manifest_path)
for setting in sorted(set(iter_schema_identifiers(kcfg_map))):
identifier = f"{setting.file}.{setting.group}.{setting.key}"
default = find_schema_default(kcfg_map.get(setting.file, []), setting)
try:
live = read_live_value(setting, default)
except RuntimeError as e:
print(f"dot kde diff: {e}", file=sys.stderr)
continue
if live == default:
continue
tag = "declared" if identifier in manifest else "undeclared"
print(f"{tag} {identifier} = {live} (default: {default})")
# Shortcuts are enumerable via kglobalaccel's allMainComponents/
# allActionsForComponent (the same source iter_shortcut_identifiers already
# walks for tab-completion), so unlike freeform they can participate in
# broad undeclared-drift discovery too.
try:
shortcut_settings = sorted(set(iter_shortcut_identifiers()))
except (RuntimeError, OSError) as e:
print(f"dot kde diff: shortcuts scan unavailable: {e}", file=sys.stderr)
shortcut_settings = []
for setting in shortcut_settings:
identifier = f"{setting.file}.{setting.group}.{setting.key}"
try:
live = read_shortcut_value(setting.group, setting.key)
default = read_shortcut_value(setting.group, setting.key, method="defaultShortcutKeys")
except RuntimeError as e:
print(f"dot kde diff: {e}", file=sys.stderr)
continue
if live == default:
continue
tag = "declared" if identifier in manifest else "undeclared"
print(f"{tag} {identifier} = {live} (default: {default})")
# Freeform settings have no schema to enumerate from, so unlike the
# schema-backed and shortcuts scans above, they can only be checked by
# walking identifiers already in the manifest -- they never surface an
# undeclared setting via broad scan. Shortcuts entries are skipped here
# (rather than re-parsed) since the broad-scan pass above already reports
# every declared shortcut mismatch; parsing one here would also mean an
# extra live kglobalaccel round-trip per entry for no benefit.
for identifier in manifest:
if identifier.split(".", 1)[0] == "kglobalshortcutsrc":
continue
try:
setting = parse_identifier(identifier, kcfg_map)
mechanism, default = resolve_mechanism(setting, kcfg_map)
if mechanism != "freeform":
continue
live = read_live_value(setting, default)
if live == "":
continue
except (ValueError, RuntimeError) as e:
print(f"dot kde diff: {e}", file=sys.stderr)
continue
print(f"declared {identifier} = {live} (default: {default or ''})")
return 0
def cmd_complete(schema_dir):
kcfg_map = build_kcfg_map(schema_dir)
for setting in sorted(set(iter_schema_identifiers(kcfg_map))):
print(f"{setting.file}.{setting.group}.{setting.key}")
try:
# Fish's completion runs this on every TAB press, in shells that may have no
# live KDE session (or no busctl at all) -- a broken shortcuts source must
# never cost the schema-backed candidates already printed above.
shortcut_settings = sorted(set(iter_shortcut_identifiers()))
except (RuntimeError, OSError):
shortcut_settings = []
for setting in shortcut_settings:
print(f"{setting.file}.{setting.group}.{setting.key}")
return 0
def main(argv):
if not argv:
print("dot kde: no command given", file=sys.stderr)
return 1
command, rest = argv[0], argv[1:]
schema_dir = Path(os.environ.get("DOT_KDE_KCFG_DIR", DEFAULT_SCHEMA_DIR))
manifest_path = Path(os.environ["HOME"]) / ".config" / "dot" / "kde-manifest"
if command == "save":
return cmd_save(rest, manifest_path, schema_dir)
if command == "apply":
return cmd_apply(rest, manifest_path, schema_dir)
if command == "diff":
return cmd_diff(rest, manifest_path, schema_dir)
# Internal, not a user-facing `dot kde` subcommand -- called directly by
# completions/dot.fish to source candidates from the live schema, never
# dispatched to via kde.fish.
if command == "complete":
return cmd_complete(schema_dir)
print(f"dot kde: unknown command {command!r}", file=sys.stderr)
return 1
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))

View File

@@ -1,134 +0,0 @@
function _dot_setup_folders_usage
echo "usage: dot setup folders [--dry-run]
Brings the 8 standard XDG user directories under the project's fixed
short-name convention (Desktop -> .desktop, Documents -> doc, Downloads ->
dwn, Music -> mus, Pictures -> pic, Videos -> vid, Templates/Public ->
.ignoreme). This mapping is fixed and does not depend on
~/.config/user-dirs.dirs, which is a separate, manually tracked dotfile
this command never reads or writes.
Content left behind in a legacy full-named folder (e.g. ~/Documents) by a
fresh XDG-defaults install -- empty or not -- is merged into its short-named
replacement. A nested Pictures/Screenshots folder is renamed to
pic/screenshots as part of the same pass.
An entry that collides by name with something already in the short-named
target is never overwritten: it's skipped, reported, and its legacy folder is
left in place (not removed) even when everything else in it migrated.
--dry-run report what would move and what would be skipped as a
collision, without changing anything on disk
Runs xdg-user-dirs-update once afterwards to notify running apps/portals
(skipped under --dry-run)."
end
function _dot_setup_folders
if test "$argv[1]" = help
_dot_setup_folders_usage
return 0
end
argparse 'dry-run' -- $argv
or return 1
# Fixed legacy-name -> short-name mapping. Deliberately hardcoded rather
# than read from ~/.config/user-dirs.dirs: that file is a separate,
# manually tracked dotfile whose XDG_*_DIR values can drift or go stale
# (or never get edited to the short names at all), and this command's
# own migration logic must not depend on it being correct.
set -l legacy_names Desktop Documents Downloads Music Pictures Videos Templates Public
set -l target_names .desktop doc dwn mus pic vid .ignoreme .ignoreme
for i in (seq (count $legacy_names))
set -l legacy_name $legacy_names[$i]
set -l target_rel $target_names[$i]
set -l target_path $HOME/$target_rel
set -l legacy_path $HOME/$legacy_name
if not set -q _flag_dry_run
mkdir -p $target_path
end
if not test -d $legacy_path
continue
end
# Screenshots is always moved as one atomic unit (renamed to
# lowercase screenshots), so its individual files must never appear
# as separate move/report entries.
set -l screenshots_path $legacy_path/Screenshots
set -l top_level_entries (find $legacy_path -mindepth 1 -maxdepth 1 -not -name Screenshots)
# No-clobber: an entry whose name already exists in the target is
# never moved over. It's collected here and reported below; its
# legacy folder is left in place (not removed) if any collision
# occurred, even though everything else in it migrated successfully.
set -l collisions
set -l movable_entries
set -l screenshots_movable 0
if test -d $screenshots_path
if test -e $target_path/screenshots
set -a collisions $screenshots_path
else
set screenshots_movable 1
end
end
for entry in $top_level_entries
if test -e $target_path/(path basename $entry)
set -a collisions $entry
else
set -a movable_entries $entry
end
end
set -l movable_count (count $movable_entries)
set -l entry_word entries
test $movable_count -eq 1
and set entry_word entry
if set -q _flag_dry_run
if test $screenshots_movable -eq 1
echo "dot setup folders: would move $screenshots_path to $target_path/screenshots"
end
if test $movable_count -gt 0
echo "dot setup folders: would move $movable_count $entry_word from ~/$legacy_name to ~/$target_rel"
end
if test (count $collisions) -gt 0
echo "dot setup folders: ~/$legacy_name has entries already present in ~/$target_rel, would skip (not overwritten):"
for c in $collisions
echo " $c"
end
echo "dot setup folders: ~/$legacy_name would remain in place due to the collision(s) above"
end
continue
end
if test $screenshots_movable -eq 1
mv -n $screenshots_path $target_path/screenshots
echo "dot setup folders: moved $screenshots_path to $target_path/screenshots"
end
if test $movable_count -gt 0
mv -n $movable_entries $target_path/
echo "dot setup folders: moved $movable_count $entry_word from ~/$legacy_name to ~/$target_rel"
end
if test (count $collisions) -gt 0
echo "dot setup folders: ~/$legacy_name has entries already present in ~/$target_rel, skipping (not overwritten):"
for c in $collisions
echo " $c"
end
echo "dot setup folders: leaving ~/$legacy_name in place due to the collision(s) above"
else
rmdir $legacy_path
end
end
if not set -q _flag_dry_run
xdg-user-dirs-update
end
end

View File

@@ -1,35 +0,0 @@
function _dot_setup_usage
echo "usage: dot setup [<task>]
Tasks:
folders bring the 8 standard XDG user directories under the short-name convention
help show this message
Run 'dot setup <task> help' for details on a specific task.
With no task given, runs every setup task."
end
function _dot_setup
if test "$argv[1]" = help
_dot_setup_usage
return 0
end
set -l helper_dir (status dirname)
source $helper_dir/folders.fish
if test -z "$argv[1]"
_dot_setup_folders
return $status
end
switch $argv[1]
case folders
_dot_setup_folders $argv[2..-1]
return $status
case '*'
_dot_setup_usage
return 1
end
end

View File

@@ -1,29 +0,0 @@
function _dot_vpn_usage
echo "usage: dot vpn <command>
Commands:
up bring the UDM-PRO-Laptop WireGuard connection up
down bring the UDM-PRO-Laptop WireGuard connection down
help show this message"
end
function _dot_vpn
if test "$argv[1]" = help
_dot_vpn_usage
return 0
end
set -l connection UDM-PRO-Laptop
switch "$argv[1]"
case up
nmcli connection up $connection
return $status
case down
nmcli connection down $connection
return $status
case '*'
_dot_vpn_usage
return 1
end
end

View File

@@ -1,32 +0,0 @@
kxkbrc.Layout.Options=caps:escape_shifted_capslock
kglobalshortcutsrc.ksmserver.Lock Session=Meta+L Screensaver
kglobalshortcutsrc.kwin.Window to Desktop 1=Meta+!
kglobalshortcutsrc.kwin.Window to Desktop 2=Meta+@
kglobalshortcutsrc.kwin.Window to Desktop 3=Meta+#
kglobalshortcutsrc.kwin.Window to Desktop 4=Meta+$
kglobalshortcutsrc.kwin.Window to Desktop 5=Meta+%
kglobalshortcutsrc.kwin.Window to Desktop 6=Meta+^
kglobalshortcutsrc.kwin.Window to Desktop 7=Meta+&
kglobalshortcutsrc.kwin.Window to Desktop 8=Meta+*
kglobalshortcutsrc.kwin.Window to Desktop 9=Meta+(
kglobalshortcutsrc.kwin.Switch to Desktop 1=Meta+1
kglobalshortcutsrc.kwin.Switch to Desktop 2=Meta+2
kglobalshortcutsrc.kwin.Switch to Desktop 3=Meta+3
kglobalshortcutsrc.kwin.Switch to Desktop 4=Meta+4
kglobalshortcutsrc.kwin.Switch to Desktop 5=Meta+5
kglobalshortcutsrc.kwin.Switch to Desktop 6=Meta+6
kglobalshortcutsrc.kwin.Switch to Desktop 7=Meta+7
kglobalshortcutsrc.kwin.Switch to Desktop 8=Meta+8
kglobalshortcutsrc.kwin.Switch to Desktop 9=Meta+9
kglobalshortcutsrc.plasmashell.activate task manager entry 1=
kglobalshortcutsrc.plasmashell.activate task manager entry 2=
kglobalshortcutsrc.plasmashell.activate task manager entry 3=
kglobalshortcutsrc.plasmashell.activate task manager entry 4=
kglobalshortcutsrc.plasmashell.activate task manager entry 5=
kglobalshortcutsrc.plasmashell.activate task manager entry 6=
kglobalshortcutsrc.plasmashell.activate task manager entry 7=
kglobalshortcutsrc.plasmashell.activate task manager entry 8=
kglobalshortcutsrc.plasmashell.activate task manager entry 9=
kglobalshortcutsrc.Alacritty.desktop._launch=Meta+Return
kglobalshortcutsrc.org.kde.konsole.desktop._launch=
kglobalshortcutsrc.kwin.Window Close=Meta+Shift+Q

View File

@@ -1,2 +0,0 @@
neovim
tmux

File diff suppressed because it is too large Load Diff

View File

@@ -1,9 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<kcfg xmlns="http://www.kde.org/standards/kcfg/1.0">
<kcfgfile arg="true"/>
<group name="Windows">
<entry name="BorderSize" type="String">
<default>Normal</default>
</entry>
</group>
</kcfg>

View File

@@ -1,15 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<kcfg xmlns="http://www.kde.org/standards/kcfg/1.0">
<kcfgfile name="testrc"/>
<group name="General">
<entry name="Greeting" type="String">
<default>Hello</default>
</entry>
<entry name="AliasedKey" key="RealKey" type="String">
<default>AliasDefault</default>
</entry>
<entry name="Some.Key With Spaces" type="String">
<default>SpacedDefault</default>
</entry>
</group>
</kcfg>

View File

@@ -1,9 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<kcfg xmlns="http://www.kde.org/standards/kcfg/1.0">
<kcfgfile arg="true"/>
<group name="Whatever">
<entry name="Setting" type="String">
<default>Unreachable</default>
</entry>
</group>
</kcfg>

View File

@@ -1,196 +0,0 @@
# This is terribly complicated
# It's because:
# 1. bun run has to have dynamic completions
# 2. there are global options
# 3. bun {install add remove} gets special options
# 4. I don't know how to write fish completions well
# Contributions very welcome!!
function __fish__get_bun_bins
string split ' ' (bun getcompletes b)
end
function __fish__get_bun_scripts
set -lx SHELL bash
set -lx MAX_DESCRIPTION_LEN 40
string trim (string split '\n' (string split '\t' (bun getcompletes z)))
end
function __fish__get_bun_packages
if test (commandline -ct) != ""
set -lx SHELL fish
string split ' ' (bun getcompletes a (commandline -ct))
end
end
function __history_completions
set -l tokens (commandline --current-process --tokenize)
history --prefix (commandline) | string replace -r \^$tokens[1]\\s\* "" | string replace -r \^$tokens[2]\\s\* "" | string split ' '
end
function __fish__get_bun_bun_js_files
string split ' ' (bun getcompletes j)
end
set -l bun_install_boolean_flags yarn production optional development no-save dry-run force no-cache silent verbose global
set -l bun_install_boolean_flags_descriptions "Write a yarn.lock file (yarn v1)" "Don't install devDependencies" "Add dependency to optionalDependencies" "Add dependency to devDependencies" "Don't update package.json or save a lockfile" "Don't install anything" "Always request the latest versions from the registry & reinstall all dependencies" "Ignore manifest cache entirely" "Don't output anything" "Excessively verbose logging" "Use global folder"
set -l bun_builtin_cmds_without_run dev create help bun upgrade discord install remove add update init pm x repl
set -l bun_builtin_cmds_accepting_flags create help bun upgrade discord run init link unlink pm x update
function __bun_complete_bins_scripts --inherit-variable bun_builtin_cmds_without_run -d "Emit bun completions for bins and scripts"
# Do nothing if we already have a builtin subcommand,
# or any subcommand other than "run".
if __fish_seen_subcommand_from $bun_builtin_cmds_without_run
or not __fish_use_subcommand && not __fish_seen_subcommand_from run
return
end
# Do we already have a bin or script subcommand?
set -l bins (__fish__get_bun_bins)
if __fish_seen_subcommand_from $bins
return
end
# Scripts have descriptions appended with a tab separator.
# Strip off descriptions for the purposes of subcommand testing.
set -l scripts (__fish__get_bun_scripts)
if __fish_seen_subcommand_from (string split \t -f 1 -- $scripts)
return
end
# Emit scripts.
for script in $scripts
echo $script
end
# Emit binaries and JS files (but only if we're doing `bun run`).
if __fish_seen_subcommand_from run
for bin in $bins
echo "$bin"\t"package bin"
end
for file in (__fish__get_bun_bun_js_files)
echo "$file"\t"Bun.js"
end
end
end
# Clear existing completions
complete -e -c bun
# Dynamically emit scripts and binaries
complete -c bun -f -a "(__bun_complete_bins_scripts)"
# Complete flags if we have no subcommand or a flag-friendly one.
set -l flag_applies "__fish_use_subcommand; or __fish_seen_subcommand_from $bun_builtin_cmds_accepting_flags"
complete -c bun \
-n $flag_applies --no-files -s 'u' -l 'origin' -r -d 'Server URL. Rewrites import paths'
complete -c bun \
-n $flag_applies --no-files -s 'p' -l 'port' -r -d 'Port number to start server from'
complete -c bun \
-n $flag_applies --no-files -s 'd' -l 'define' -r -d 'Substitute K:V while parsing, e.g. --define process.env.NODE_ENV:\"development\"'
complete -c bun \
-n $flag_applies --no-files -s 'e' -l 'external' -r -d 'Exclude module from transpilation (can use * wildcards). ex: -e react'
complete -c bun \
-n $flag_applies --no-files -l 'use' -r -d 'Use a framework (ex: next)'
complete -c bun \
-n $flag_applies --no-files -l 'hot' -r -d 'Enable hot reloading in Bun\'s JavaScript runtime'
# Complete dev and create as first subcommand.
complete -c bun \
-n "__fish_use_subcommand" -a 'dev' -d 'Start dev server'
complete -c bun \
-n "__fish_use_subcommand" -a 'create' -f -d 'Create a new project from a template'
# Complete "next" and "react" if we've seen "create".
complete -c bun \
-n "__fish_seen_subcommand_from create" -a 'next' -d 'new Next.js project'
complete -c bun \
-n "__fish_seen_subcommand_from create" -a 'react' -d 'new React project'
# Complete "upgrade" as first subcommand.
complete -c bun \
-n "__fish_use_subcommand" -a 'upgrade' -d 'Upgrade bun to the latest version' -x
# Complete "-h/--help" unconditionally.
complete -c bun \
-s "h" -l "help" -d 'See all commands and flags' -x
# Complete "-v/--version" if we have no subcommand.
complete -c bun \
-n "not __fish_use_subcommand" -l "version" -s "v" -d 'Bun\'s version' -x
# Complete additional subcommands.
complete -c bun \
-n "__fish_use_subcommand" -a 'discord' -d 'Open bun\'s Discord server' -x
complete -c bun \
-n "__fish_use_subcommand" -a 'bun' -d 'Generate a new bundle'
complete -c bun \
-n "__fish_seen_subcommand_from bun" -F -d 'Bundle this'
complete -c bun \
-n "__fish_seen_subcommand_from create; and __fish_seen_subcommand_from react next" -F -d "Create in directory"
complete -c bun \
-n "__fish_use_subcommand" -a 'init' -F -d 'Start an empty Bun project'
complete -c bun \
-n "__fish_use_subcommand" -a 'install' -f -d 'Install packages from package.json'
complete -c bun \
-n "__fish_use_subcommand" -a 'add' -F -d 'Add a package to package.json'
complete -c bun \
-n "__fish_use_subcommand" -a 'remove' -F -d 'Remove a package from package.json'
for i in (seq (count $bun_install_boolean_flags))
complete -c bun \
-n "__fish_seen_subcommand_from install add remove update" -l "$bun_install_boolean_flags[$i]" -d "$bun_install_boolean_flags_descriptions[$i]"
end
complete -c bun \
-n "__fish_seen_subcommand_from install add remove update" -l 'cwd' -d 'Change working directory'
complete -c bun \
-n "__fish_seen_subcommand_from install add remove update" -l 'cache-dir' -d 'Choose a cache directory (default: $HOME/.bun/install/cache)'
complete -c bun \
-n "__fish_seen_subcommand_from add" -d 'Popular' -a '(__fish__get_bun_packages)'
complete -c bun \
-n "__fish_seen_subcommand_from add" -d 'History' -a '(__history_completions)'
complete -c bun \
-n "__fish_seen_subcommand_from pm; and not __fish_seen_subcommand_from (__fish__get_bun_bins) (__fish__get_bun_scripts) cache;" -a 'bin ls cache hash hash-print hash-string' -f
complete -c bun \
-n "__fish_seen_subcommand_from pm; and __fish_seen_subcommand_from cache; and not __fish_seen_subcommand_from (__fish__get_bun_bins) (__fish__get_bun_scripts);" -a 'rm' -f
# Add built-in subcommands with descriptions.
complete -c bun -n "__fish_use_subcommand" -a "create" -f -d "Create a new project from a template"
complete -c bun -n "__fish_use_subcommand" -a "build bun" --require-parameter -F -d "Transpile and bundle one or more files"
complete -c bun -n "__fish_use_subcommand" -a "upgrade" -d "Upgrade Bun"
complete -c bun -n "__fish_use_subcommand" -a "run" -d "Run a script or package binary"
complete -c bun -n "__fish_use_subcommand" -a "install" -d "Install dependencies from package.json" -f
complete -c bun -n "__fish_use_subcommand" -a "remove" -d "Remove a dependency from package.json" -f
complete -c bun -n "__fish_use_subcommand" -a "add" -d "Add a dependency to package.json" -f
complete -c bun -n "__fish_use_subcommand" -a "init" -d "Initialize a Bun project in this directory" -f
complete -c bun -n "__fish_use_subcommand" -a "link" -d "Register or link a local npm package" -f
complete -c bun -n "__fish_use_subcommand" -a "unlink" -d "Unregister a local npm package" -f
complete -c bun -n "__fish_use_subcommand" -a "pm" -d "Additional package management utilities" -f
complete -c bun -n "__fish_use_subcommand" -a "x" -d "Execute a package binary, installing if needed" -f
complete -c bun -n "__fish_use_subcommand" -a "outdated" -d "Display the latest versions of outdated dependencies" -f
complete -c bun -n "__fish_use_subcommand" -a "update" -d "Update dependencies to their latest versions" -f
complete -c bun -n "__fish_use_subcommand" -a "publish" -d "Publish your package from local to npm" -f
complete -c bun -n "__fish_use_subcommand" -a "repl" -d "Start a REPL session with Bun" -f
complete -c bun -n "__fish_seen_subcommand_from repl" -s "e" -l "eval" -r -d "Evaluate argument as a script, then exit" -f
complete -c bun -n "__fish_seen_subcommand_from repl" -s "p" -l "print" -r -d "Evaluate argument as a script, print the result, then exit" -f
complete -c bun -n "__fish_seen_subcommand_from repl" -s "r" -l "preload" -r -d "Import a module before other modules are loaded"
complete -c bun -n "__fish_seen_subcommand_from repl" -l "smol" -d "Use less memory, but run garbage collection more often" -f
complete -c bun -n "__fish_seen_subcommand_from repl" -s "c" -l "config" -r -d "Specify path to Bun config file"
complete -c bun -n "__fish_seen_subcommand_from repl" -l "cwd" -r -d "Absolute path to resolve files & entry points from"
complete -c bun -n "__fish_seen_subcommand_from repl" -l "env-file" -r -d "Load environment variables from the specified file(s)"
complete -c bun -n "__fish_seen_subcommand_from repl" -l "no-env-file" -d "Disable automatic loading of .env files" -f

View File

@@ -1,34 +0,0 @@
function __dot_custom_subcommands
echo init
echo help
path basename $HOME/.config/dot/commands/*.fish 2>/dev/null | path change-extension ''
for d in $HOME/.config/dot/commands/*/
test -d $d; or continue
set -l name (path basename $d)
test -f $d$name.fish; or continue
echo $name
end
end
complete -c dot -n __fish_use_subcommand -a "(__dot_custom_subcommands)"
# --- dot install ---
complete -c dot -n "__fish_seen_subcommand_from install; and not __fish_seen_argument -l restore" -l restore -d "reinstall every package from the saved list"
complete -c dot -n "__fish_seen_subcommand_from install; and not __fish_seen_argument -l no-sync" -l no-sync -d "skip the pacman -Sy database refresh"
complete -c dot -n "__fish_seen_subcommand_from install; and not __fish_seen_argument -l restore" -f -a "(__fish_print_pacman_packages)"
# --- dot setup ---
complete -c dot -n "__fish_seen_subcommand_from setup; and not __fish_seen_subcommand_from folders help" -f -a folders -d "bring the 8 standard XDG user directories under the short-name convention"
complete -c dot -n "__fish_seen_subcommand_from setup; and not __fish_seen_subcommand_from folders help" -f -a help -d "show usage"
complete -c dot -n "__fish_seen_subcommand_from setup; and __fish_seen_subcommand_from folders" -f -a help -d "show usage"
# --- dot kde ---
complete -c dot -n "__fish_seen_subcommand_from kde; and not __fish_seen_subcommand_from apply diff save help" -f -a apply -d "push manifest entries onto the live system"
complete -c dot -n "__fish_seen_subcommand_from kde; and not __fish_seen_subcommand_from apply diff save help" -f -a diff -d "scan for settings whose live value differs from its default"
complete -c dot -n "__fish_seen_subcommand_from kde; and not __fish_seen_subcommand_from apply diff save help" -f -a save -d "write live KDE settings into the manifest"
complete -c dot -n "__fish_seen_subcommand_from kde; and not __fish_seen_subcommand_from apply diff save help" -f -a help -d "show usage"
complete -c dot -n "__fish_seen_subcommand_from kde; and __fish_seen_subcommand_from apply diff save" -f -a help -d "show usage"
# Sourced live from the schema mapping table (real .kcfg files), not a
# hardcoded list -- same helper kde.py's own save/refresh logic builds from.
complete -c dot -n "__fish_seen_subcommand_from kde; and __fish_seen_subcommand_from save" -f -a "(python3 $HOME/.config/dot/commands/kde/kde.py complete 2>/dev/null)"

View File

@@ -1,2 +0,0 @@
complete --command fishtape --short v --long version --description "Print version"
complete --command fishtape --short h --long help --description "Print help"

View File

@@ -1,4 +0,0 @@
alias cp='cp -v'
alias vi=nvim
alias vim=nvim
alias tmx='tmux new-session -A -s'

View File

@@ -1,4 +0,0 @@
set -gx EDITOR nvim
set -x ANDROID_HOME $HOME/Android/Sdk
fish_add_path $ANDROID_HOME/platform-tools
fish_add_path $ANDROID_HOME/tools/bin

View File

@@ -1 +0,0 @@
test -f "$HOME/.cargo/env.fish"; and source "$HOME/.cargo/env.fish"

View File

@@ -1,15 +0,0 @@
source /usr/share/cachyos-fish-config/cachyos-config.fish
set -gx EDITOR nvim
set -gx VISUAL nvim
# overwrite greeting
# potentially disabling fastfetch
#function fish_greeting
# # smth smth
#end
# bun
set --export BUN_INSTALL "$HOME/.bun"
set --export PATH $BUN_INSTALL/bin $PATH

View File

@@ -1 +0,0 @@
jorgebucaran/fishtape

View File

@@ -1,82 +0,0 @@
# This file contains fish universal variable definitions.
# VERSION: 3.0
SETUVAR __done_min_cmd_duration:10000
SETUVAR __done_notification_urgency_level:low
SETUVAR __fish_initialized:4300
SETUVAR _fisher_jorgebucaran_2F_fishtape_files:\x7e/\x2econfig/fish/functions/fishtape\x2efish\x1e\x7e/\x2econfig/fish/completions/fishtape\x2efish
SETUVAR _fisher_plugins:jorgebucaran/fishtape
SETUVAR _fisher_upgraded_to_4_4:\x1d
SETUVAR fish_user_paths:/home/alexion/\x2elocal/bin\x1e/home/alexion/Android/Sdk/platform\x2dtools
SETUVAR pure_begin_prompt_with_current_directory:true
SETUVAR pure_check_for_new_release:false
SETUVAR pure_color_at_sign:pure_color_mute
SETUVAR pure_color_aws_profile:pure_color_warning
SETUVAR pure_color_command_duration:pure_color_warning
SETUVAR pure_color_current_directory:pure_color_primary
SETUVAR pure_color_danger:red
SETUVAR pure_color_dark:black
SETUVAR pure_color_exit_status:pure_color_danger
SETUVAR pure_color_git_branch:pure_color_mute
SETUVAR pure_color_git_dirty:pure_color_mute
SETUVAR pure_color_git_stash:pure_color_info
SETUVAR pure_color_git_unpulled_commits:pure_color_info
SETUVAR pure_color_git_unpushed_commits:pure_color_info
SETUVAR pure_color_hostname:pure_color_mute
SETUVAR pure_color_info:cyan
SETUVAR pure_color_jobs:pure_color_normal
SETUVAR pure_color_k8s_context:pure_color_success
SETUVAR pure_color_k8s_namespace:pure_color_primary
SETUVAR pure_color_k8s_prefix:pure_color_info
SETUVAR pure_color_light:white
SETUVAR pure_color_mute:brblack
SETUVAR pure_color_nixdevshell_prefix:pure_color_info
SETUVAR pure_color_nixdevshell_symbol:pure_color_mute
SETUVAR pure_color_normal:normal
SETUVAR pure_color_prefix_root_prompt:pure_color_danger
SETUVAR pure_color_primary:blue
SETUVAR pure_color_prompt_on_error:pure_color_danger
SETUVAR pure_color_prompt_on_success:pure_color_success
SETUVAR pure_color_success:magenta
SETUVAR pure_color_system_time:pure_color_mute
SETUVAR pure_color_username_normal:pure_color_mute
SETUVAR pure_color_username_root:pure_color_light
SETUVAR pure_color_virtualenv:pure_color_mute
SETUVAR pure_color_warning:yellow
SETUVAR pure_convert_exit_status_to_signal:false
SETUVAR pure_enable_aws_profile:true
SETUVAR pure_enable_container_detection:true
SETUVAR pure_enable_git:true
SETUVAR pure_enable_k8s:false
SETUVAR pure_enable_nixdevshell:false
SETUVAR pure_enable_single_line_prompt:false
SETUVAR pure_enable_virtualenv:true
SETUVAR pure_reverse_prompt_symbol_in_vimode:true
SETUVAR pure_separate_prompt_on_error:false
SETUVAR pure_shorten_prompt_current_directory_length:0
SETUVAR pure_shorten_window_title_current_directory_length:0
SETUVAR pure_show_exit_status:false
SETUVAR pure_show_jobs:false
SETUVAR pure_show_numbered_git_indicator:false
SETUVAR pure_show_prefix_root_prompt:false
SETUVAR pure_show_subsecond_command_duration:false
SETUVAR pure_show_system_time:false
SETUVAR pure_symbol_aws_profile_prefix:
SETUVAR pure_symbol_container_prefix:
SETUVAR pure_symbol_exit_status_prefix:\x7c
SETUVAR pure_symbol_exit_status_separator:\x7c
SETUVAR pure_symbol_git_dirty:\x2a
SETUVAR pure_symbol_git_stash:\u2261
SETUVAR pure_symbol_git_unpulled_commits:\u21e3
SETUVAR pure_symbol_git_unpushed_commits:\u21e1
SETUVAR pure_symbol_k8s_prefix:\u2638
SETUVAR pure_symbol_nixdevshell_prefix:\u2744\ufe0f
SETUVAR pure_symbol_prefix_root_prompt:\x23
SETUVAR pure_symbol_prompt:\u276f
SETUVAR pure_symbol_reverse_prompt:\u276e
SETUVAR pure_symbol_ssh_prefix:
SETUVAR pure_symbol_title_bar_separator:\x2d
SETUVAR pure_symbol_virtualenv_prefix:
SETUVAR pure_system_time_format:\x2b\x25T
SETUVAR pure_threshold_command_duration:5
SETUVAR pure_truncate_prompt_current_directory_keeps:\x2d1
SETUVAR pure_truncate_window_title_current_directory_keeps:\x2d1

View File

@@ -1,130 +0,0 @@
function dot --wraps=git --description 'Manage dotfiles via a bare repo checked out over $HOME'
set -l dotfiles_dir $HOME/.dotfiles
if test "$argv[1]" = init
set -e argv[1]
__dot_init $dotfiles_dir $argv
return $status
end
if test "$argv[1]" = help
__dot_help
return $status
end
set -l commands_dir $HOME/.config/dot/commands
set -l command_file $commands_dir/$argv[1].fish
set -l nested_command_file $commands_dir/$argv[1]/$argv[1].fish
if test -n "$argv[1]"
if test -f "$command_file"
source $command_file
_dot_$argv[1] $argv[2..-1]
return $status
else if test -f "$nested_command_file"
source $nested_command_file
_dot_$argv[1] $argv[2..-1]
return $status
end
end
git --git-dir=$dotfiles_dir --work-tree=$HOME $argv
end
# Kept inline (not a separate autoloaded function file) because this is the
# only subcommand that must work before the dotfiles repo has been cloned.
function __dot_init
set -l dotfiles_dir $argv[1]
set -e argv[1]
argparse 'url=' -- $argv
or return 1
set -l url $_flag_url
test -n "$url"; or set url ssh://gitea@git.alexion.dev:2022/alexion/dotfiles.git
if test -e $dotfiles_dir
echo "dot init: $dotfiles_dir already exists, refusing to re-initialize" >&2
return 1
end
git clone --bare $url $dotfiles_dir
or begin
echo "dot init: failed to clone $url" >&2
return 1
end
git --git-dir=$dotfiles_dir config status.showUntrackedFiles no
set -l checkout_output (git --git-dir=$dotfiles_dir --work-tree=$HOME checkout 2>&1)
set -l checkout_status $status
if test $checkout_status -ne 0
set -l conflicts
set -l in_block 0
for line in $checkout_output
if test $in_block -eq 1
if string match -rq '^\s' -- $line
set -a conflicts (string trim -- $line)
continue
else
set in_block 0
end
end
string match -q '*would be overwritten by checkout:*' -- $line
and set in_block 1
end
if test (count $conflicts) -eq 0
echo "dot init: checkout failed and no recoverable conflicts were found:" >&2
printf '%s\n' $checkout_output >&2
return 1
end
set -l backup_dir $HOME/.dotfiles-backup/(date +%Y%m%dT%H%M%S)
for f in $conflicts
mkdir -p (path dirname $backup_dir/$f)
mv $HOME/$f $backup_dir/$f
echo "dot init: backed up ~/$f to $backup_dir/$f"
end
git --git-dir=$dotfiles_dir --work-tree=$HOME checkout
or begin
echo "dot init: checkout still failing after backing up conflicts, aborting" >&2
return 1
end
end
echo "dot init: bootstrapped $dotfiles_dir from $url"
end
# The custom-subcommand glob is duplicated (not shared with
# completions/dot.fish) because fish only autoloads a function from a file
# named after that function; a shared helper would go undefined if `dot help`
# ran in a completion context before `dot` itself had ever been sourced.
function __dot_help
echo "dot: manage dotfiles via a bare repo checked out over \$HOME
Commands:
init bootstrap the dotfiles repo on a new machine
help show this message"
for f in $HOME/.config/dot/commands/*.fish
test -e $f; or continue
echo " "(path basename $f | path change-extension '')
end
for d in $HOME/.config/dot/commands/*/
test -d $d; or continue
set -l name (path basename $d)
test -f $d$name.fish; or continue
echo " $name"
end
echo "
Run 'dot <command> help' for flags on a specific command.
Any other command is passed through to git (dot status, dot add, dot commit, dot push, ...)."
end

View File

@@ -1,116 +0,0 @@
function fishtape --description "Test scripts, functions, and plugins in Fish"
switch "$argv"
case -v --version
echo "fishtape, version 3.0.1"
case "" -h --help
echo "Usage: fishtape <files ...> Run test files"
echo "Options:"
echo " -v or --version Print version"
echo " -h or --help Print this help message"
case \*
set --local files (realpath $argv)
for file in $files
if test ! -f $file
echo "fishtape: Invalid file or file not found: \"$file\"" >&2
return 1
end
end
set --local operators -{n,z,b,c,d,e,f,g,G,k,L,O,p,r,s,S,t,u,w,x}
set --local expectations \
"a non-zero length string" \
"a zero length string" \
"a block device" \
"a character device" \
"a directory" \
"an existing file" \
"a regular file" \
"a file with the set-group-ID bit set" \
"a file with same group ID as the current user" \
"a file with the sticky bit set" \
"a symbolic link" \
"a file owned by the current user" \
"a named pipe" \
"a file marked as readable" \
"a file of size greater than zero" \
"a socket" \
"a terminal tty file descriptor" \
"a file with the set-user-ID bit set" \
"a file marked as writable" \
"a file marked as executable"
set --universal _fishtape_test_number 0
set --universal _fishtape_test_passed 0
set --universal _fishtape_test_failed 0
function @echo
echo "# $argv"
end
function @test --argument-names name --inherit-variable operators --inherit-variable expectations
set --erase argv[1]
set --query argv[2] || set --append argv ""
set _fishtape_test_number (math $_fishtape_test_number + 1)
if test $argv
set _fishtape_test_passed (math $_fishtape_test_passed + 1)
echo "ok $_fishtape_test_number $name"
else
if test $argv[1] = "!"
set operator "! "
set expected "not "
set --erase argv[1]
end
if set --query argv[3]
set operator "$operator"$argv[2]
set expected (string escape -- $argv[3])
set actual (string escape -- $argv[1])
else
set operator "$operator"$argv[1]
set expected "$expected"$expectations[(contains --index -- $argv[1] $operators)]
set actual (string escape -- $argv[2])
end
set _fishtape_test_failed (math $_fishtape_test_failed + 1)
status print-stack-trace |
string replace --filter --regex -- "\s+called on line (\d+) of file (.+)" '$2:$1' |
read --local at
echo "not ok $_fishtape_test_number $name"
echo " ---"
echo " operator: $operator"
echo " expected: $expected"
echo " actual: $actual"
echo " at: $at"
echo " ..."
end
end
echo TAP version 13
for file in $files
fish --init-command=(functions @echo | string collect) --init-command=(functions @test | string collect) $file
end
echo
echo "1..$_fishtape_test_number"
echo "# pass $_fishtape_test_passed"
test $_fishtape_test_failed -eq 0 &&
echo "# ok" ||
echo "# fail $_fishtape_test_failed"
functions --erase @echo @test
set --local failed $_fishtape_test_failed
set --erase _fishtape_test_number
set --erase _fishtape_test_passed
set --erase _fishtape_test_failed
test $failed -eq 0
end
end

View File

@@ -1 +0,0 @@
vim.opt_local.conceallevel = 2

View File

@@ -1,3 +0,0 @@
require("vim_options")
require("keys")
require("plugin")

View File

@@ -1,13 +0,0 @@
{
"diffview.nvim": { "branch": "main", "commit": "4516612fe98ff56ae0415a259ff6361a89419b0a" },
"gitsigns.nvim": { "branch": "main", "commit": "eb60cc7b94c46005237fd34170d76f3a089a90aa" },
"lazy.nvim": { "branch": "main", "commit": "306a05526ada86a7b30af95c5cc81ffba93fef97" },
"neogit": { "branch": "master", "commit": "6fc2fa890bd2031ed999c074daab0fb4feff20a5" },
"nord.nvim": { "branch": "main", "commit": "87394d4fc35c901bbe38326a78d31ab1ead826b6" },
"nvim-treesitter": { "branch": "master", "commit": "cf12346a3414fa1b06af75c79faebe7f76df080a" },
"oil.nvim": { "branch": "master", "commit": "b73018b75affd13fa38e2fc94ef753b465f770d7" },
"plenary.nvim": { "branch": "master", "commit": "74b06c6c75e4eeb3108ec01852001636d85a932b" },
"render-markdown.nvim": { "branch": "main", "commit": "f422cb5c6855f150e2ddcfaf44e7157b98b34f6a" },
"snacks.nvim": { "branch": "main", "commit": "882c996cf28183f4d63640de0b4c02ec886d01f2" },
"which-key.nvim": { "branch": "main", "commit": "3aab2147e74890957785941f0c1ad87d0a44c15a" }
}

View File

@@ -1,8 +0,0 @@
local map = vim.keymap.set
map("n", "<C-h>", "<C-w>h", { desc = "Move focus left" })
map("n", "<C-j>", "<C-w>j", { desc = "Move focus down" })
map("n", "<C-k>", "<C-w>k", { desc = "Move focus up" })
map("n", "<C-l>", "<C-w>l", { desc = "Move focus right" })
map("n", "<Esc>", "<cmd>nohlsearch<CR>", { desc = "Clear search highlight" })

View File

@@ -1,23 +0,0 @@
local lazypath = vim.fn.stdpath("data") .. "/lazy/lazy.nvim"
if not vim.uv.fs_stat(lazypath) then
local lazyrepo = "https://github.com/folke/lazy.nvim.git"
local out = vim.fn.system({ "git", "clone", "--filter=blob:none", "--branch=stable", lazyrepo, lazypath })
if vim.v.shell_error ~= 0 then
vim.api.nvim_echo({
{ "Failed to clone lazy.nvim:\n", "ErrorMsg" },
{ out, "WarningMsg" },
{ "\nPress any key to exit..." },
}, true, {})
vim.fn.getchar()
os.exit(1)
end
end
vim.opt.rtp:prepend(lazypath)
require("lazy").setup({
spec = {
{ import = "plugins" },
},
install = { colorscheme = { "nord" } },
checker = { enabled = false },
})

View File

@@ -1,36 +0,0 @@
return {
{
"NeogitOrg/neogit",
dependencies = {
"nvim-lua/plenary.nvim",
"sindrets/diffview.nvim",
},
keys = {
{
"<leader>g",
function()
require("gitsigns").toggle_current_line_blame(true)
require("neogit").open()
end,
desc = "Open git (Neogit)",
},
},
config = function()
require("neogit").setup()
vim.api.nvim_create_autocmd("BufUnload", {
callback = function(args)
if vim.bo[args.buf].filetype == "NeogitStatus" then
require("gitsigns").toggle_current_line_blame(false)
end
end,
})
end,
},
{
"lewis6991/gitsigns.nvim",
event = "BufWinEnter",
opts = {
current_line_blame = false,
},
},
}

View File

@@ -1,27 +0,0 @@
return {
{
"stevearc/oil.nvim",
lazy = false,
opts = {
view_options = { show_hidden = true },
},
keys = {
{ "<leader>e", "<cmd>Oil<CR>", desc = "Open file browser" },
},
},
{
"folke/snacks.nvim",
priority = 1000,
lazy = false,
opts = {
picker = { enabled = true },
notifier = { enabled = true },
input = { enabled = true },
},
keys = {
{ "<leader>f", function() require("snacks").picker.files() end, desc = "Find files" },
{ "<leader>s", function() require("snacks").picker.grep() end, desc = "Search text" },
{ "<leader>b", function() require("snacks").picker.buffers() end, desc = "Switch buffer" },
},
},
}

View File

@@ -1,55 +0,0 @@
return {
{
"gbprod/nord.nvim",
lazy = false,
priority = 1000,
opts = {
transparent = true,
},
config = function(_, opts)
require("nord").setup(opts)
vim.cmd.colorscheme("nord")
end,
},
{
"MeanderingProgrammer/render-markdown.nvim",
ft = { "markdown" },
dependencies = { "nvim-treesitter/nvim-treesitter" },
opts = {},
},
{
"folke/which-key.nvim",
lazy = false,
config = true,
},
{
"nvim-treesitter/nvim-treesitter",
branch = "master",
build = ":TSUpdate",
opts = {
ensure_installed = {
"markdown",
"markdown_inline",
"lua",
"bash",
"fish",
"rust",
"javascript",
"typescript",
"java",
"kotlin",
"c",
"cpp",
"html",
"css",
"python",
},
auto_install = false,
highlight = { enable = true },
indent = { enable = true },
},
config = function(_, opts)
require("nvim-treesitter.configs").setup(opts)
end,
},
}

View File

@@ -1,29 +0,0 @@
vim.g.mapleader = " "
local opt = vim.opt
-- Clipboard: use neovim's built-in OSC 52 provider, no external binary needed.
vim.g.clipboard = "osc52"
opt.clipboard = "unnamedplus"
opt.number = true
opt.relativenumber = true
opt.shiftwidth = 2
opt.tabstop = 2
opt.expandtab = true
opt.mouse = "a"
opt.undofile = true
opt.ignorecase = true
opt.smartcase = true
opt.splitright = true
opt.splitbelow = true
opt.wrap = false
opt.scrolloff = 8
opt.cursorline = true

View File

@@ -1,74 +0,0 @@
# Prefix: Ctrl-Space. Chosen over Ctrl-b (awkward reach) and Ctrl-a (collides
# with readline's beginning-of-line, which fights editing text in shells and
# in Claude Code's prompt). Verified clear of IME/KDE/Claude Code bindings.
unbind C-b
set -g prefix C-Space
bind C-Space send-prefix
set -g mouse on
# OSC52 lets copy-mode selections land in the system clipboard via the
# terminal itself (Alacritty supports it) -- no wl-copy/xclip needed, and it
# still works over SSH later since the escape sequence travels with the data.
set -g set-clipboard on
set -g mode-keys vi
set -g status-keys vi
bind -T copy-mode-vi v send -X begin-selection
bind -T copy-mode-vi y send -X copy-selection-and-cancel
bind -T copy-mode-vi MouseDragEnd1Pane send -X copy-selection-and-cancel
# tmux's -h/-v split flags name the *arrangement*, not the divider line, which
# is backwards from how the divider looks -- so pick keys by what they draw:
# \ draws a side-by-side split (vertical line), - draws a stacked split
# (horizontal line). Unshifted versions of |/- since splitting is frequent.
unbind %
unbind '"'
bind \\ split-window -h -c "#{pane_current_path}"
bind - split-window -v -c "#{pane_current_path}"
bind c new-window -c "#{pane_current_path}"
bind h select-pane -L
bind j select-pane -D
bind k select-pane -U
bind l select-pane -R
set -g base-index 1
setw -g pane-base-index 1
set -g renumber-windows on
bind r source-file ~/.config/tmux/tmux.conf \; display-message "tmux.conf reloaded"
# True color passthrough. ",*" (rather than naming Alacritty's xterm-256color
# specifically) so this keeps working if the terminal emulator changes later.
set -g default-terminal "tmux-256color"
set -ag terminal-overrides ",*:RGB"
# Default 500ms delay on Esc exists to disambiguate meta-key sequences; it
# reads as noticeable lag exiting insert mode in neovim, so drop it.
set -sg escape-time 10
set -g history-limit 10000
# Flag a background window in the status bar when its Claude Code session
# rings the terminal bell (permission prompt / task done while unfocused).
# bell-action=none stops tmux from ever passing the actual BEL through to
# Alacritty (no beep, no flash) -- monitor-bell's per-window tracking for the
# status-line highlight is independent of that and keeps working.
setw -g monitor-bell on
set -g bell-action none
# Minimal status bar (session + window list only), styled to match the Nord
# theme already used in alacritty.toml.
set -g status-position bottom
set -g status-style "bg=#2E3440,fg=#D8DEE9"
set -g status-left " #S "
set -g status-left-length 20
set -g status-right ""
setw -g window-status-current-style "bg=#88C0D0,fg=#2E3440,bold"
setw -g window-status-current-format " #I:#W "
setw -g window-status-format " #I:#W "
setw -g window-status-style "fg=#4C566A"
setw -g window-status-bell-style "bg=#BF616A,fg=#2E3440,bold"
set -g pane-border-style "fg=#3B4252"
set -g pane-active-border-style "fg=#88C0D0"

View File

@@ -1,16 +0,0 @@
# This file is written by xdg-user-dirs-update
# If you want to change or add directories, just edit the line you're
# interested in. All local changes will be retained on the next run.
# Format is XDG_xxx_DIR="$HOME/yyy", where yyy is a shell-escaped
# homedir-relative path, or XDG_xxx_DIR="/yyy", where /yyy is an
# absolute path. No other format is supported.
#
XDG_DESKTOP_DIR="$HOME/.desktop"
XDG_DOWNLOAD_DIR="$HOME/dwn"
XDG_TEMPLATES_DIR="$HOME/.ignoreme"
XDG_PUBLICSHARE_DIR="$HOME/.ignoreme"
XDG_DOCUMENTS_DIR="$HOME/doc"
XDG_MUSIC_DIR="$HOME/mus"
XDG_PICTURES_DIR="$HOME/pic"
XDG_VIDEOS_DIR="$HOME/vid"
XDG_PROJECTS_DIR="$HOME/wrk"

View File

@@ -1,3 +0,0 @@
[user]
name = alexion
email = contact@alexion.dev

40
.github/README.md vendored
View File

@@ -1,40 +0,0 @@
# dotfiles
Dotfiles managed as a bare git repo checked out over `$HOME`, for machines
running CachyOS with KDE Plasma.
## Bootstrapping a new machine
```sh
mkdir -p ~/.config/fish/functions
curl -fsSL https://git.alexion.dev/alexion/dotfiles/raw/branch/main/.config/fish/functions/dot.fish \
-o ~/.config/fish/functions/dot.fish
fish -c 'dot init'
```
## Commands
| Command | Description |
| ----------------------- | ----------------------------------------------------------------------------------------- |
| `dot help` | Lists available commands. |
| `dot init` | Bootstraps the dotfiles repo on a new machine. |
| `dot install <pkgs>` | Installs the given pacman packages and appends them to the tracked list (`~/.config/dot/packages/pacman`). |
| `dot install --restore` | Reinstalls every package from the tracked list. |
| `dot kde apply` | Pushes every manifest entry's declared value onto the live system. |
| `dot kde diff` | Reports every schema-backed setting whose live value differs from its default, tagged declared or undeclared. |
| `dot kde help` | Lists `dot kde`'s subcommands. |
| `dot kde save <identifier>` | Reads a KDE setting's current live value and declares it in the manifest (`~/.config/dot/kde-manifest`). |
| `dot kde save` | Refreshes every already-declared manifest entry's value from the live system. |
| `dot setup` | Runs every machine-setup task (currently just `folders`). |
| `dot setup folders` | Brings the 8 standard XDG user directories (`~/Desktop`, `~/Documents`, ...) under a fixed short-name convention (`~/.desktop`, `~/doc`, ...). |
| `dot vpn up` | Brings the `UDM-PRO-Laptop` WireGuard connection up via NetworkManager. |
| `dot vpn down` | Brings the `UDM-PRO-Laptop` WireGuard connection down. |
| `dot <git>` | Everything else is passed to `git`. |
See [CLAUDE.md](../.config/dot/CLAUDE.md) for the `dot` tool's internal
architecture, bootstrap logic, subcommand dispatch, and test suite.
## Keybindings
See [keybindings.md](keybindings.md) for custom and useful default
keybindings across configured tools (currently: tmux).

View File

@@ -1,42 +0,0 @@
# Keybindings
Quick reference for custom and useful default keybindings, so they don't have
to be re-discovered or looked up per tool.
Comma-separated keys are pressed in sequence, not together.
| Key | Context | Action |
| ----------------------------------------------------- | ------- | -------------------------------------------------- |
| `Ctrl` + `Space`, `\` | tmux | Split side-by-side, opens in current directory |
| `Ctrl` + `Space`, `-` | tmux | Split stacked, opens in current directory |
| `Ctrl` + `Space`, `h` / `j` / `k` / `l` | tmux | Move focus left / down / up / right |
| `Ctrl` + `Space`, `z` | tmux | Zoom/unzoom pane to fullscreen |
| `Ctrl` + `Space`, `o` | tmux | Cycle focus to next pane |
| `Ctrl` + `Space`, `x` | tmux | Kill current pane (asks to confirm) |
| `Ctrl` + `Space`, `Ctrl` + `Up`/`Down`/`Left`/`Right` | tmux | Resize pane |
| `Ctrl` + `Space`, `c` | tmux | New window, opens in current directory |
| `Ctrl` + `Space`, `0`-`9` | tmux | Jump to window by number |
| `Ctrl` + `Space`, `n` / `p` | tmux | Next / previous window |
| `Ctrl` + `Space`, `w` | tmux | Interactive window list |
| `Ctrl` + `Space`, `,` | tmux | Rename current window |
| `Ctrl` + `Space`, `&` | tmux | Kill current window (asks to confirm) |
| `Ctrl` + `Space`, `[` | tmux | Enter copy mode |
| `Ctrl` + `Space`, `]` | tmux | Paste most recent copy |
| `h` / `j` / `k` / `l` | tmux | Move cursor |
| `v` | tmux | Begin selection |
| `y` | tmux | Copy selection to system clipboard, exit copy mode |
| `/` / `?` | tmux | Search forward / backward |
| `q` | tmux | Exit copy mode |
| `Ctrl` + `Space`, `d` | tmux | Detach from session |
| `Ctrl` + `Space`, `$` | tmux | Rename session |
| `Ctrl` + `Space`, `s` | tmux | Interactive session list |
| `Ctrl` + `Space`, `(` / `)` | tmux | Switch to previous / next session |
| `Ctrl` + `Space`, `r` | tmux | Reload `tmux.conf` |
| `Ctrl` + `h` / `j` / `k` / `l` | neovim | Move focus between splits left / down / up / right |
| `Esc` | neovim | Clear search highlight |
| `Space`, `e` | neovim | Toggle file explorer (netrw) |
| `CapsLock` | KDE | Acts as `Esc` (`kxkbrc` `Options=caps:escape_shifted_capslock`) |
| `Shift` + `CapsLock` | KDE | Toggles Caps Lock |
| `Meta` + `X` | KDE | Lock Session (moved off `Meta+L`, tracked via `dot kde`) |
| `Meta` + `Shift` + `q` | KDE | Kill window |

8
.gitignore vendored
View File

@@ -1,9 +1 @@
.dotfiles
.DS_Store
*.swp
*.swo
*~
Thumbs.db
**/__pycache__
.config/fish/conf.d/secrets.fish
/reference/