Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .claude-plugin/plugin.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "fstack",
"description": "Federico Mastrini's agent skills for everyday software engineering work.",
"version": "0.17.0",
"version": "0.17.1",
"author": {
"name": "Federico Mastrini",
"url": "https://fedemas.dev"
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
**A short stack of agent skills for everyday software engineering work.**

[![Claude Code plugin](https://img.shields.io/badge/Claude%20Code-plugin-D97757?style=flat-square)](https://www.fedemas.dev/fstack)
[![Version](https://img.shields.io/badge/version-0.17.0-B4A7E5?style=flat-square)](.claude-plugin/plugin.json)
[![Version](https://img.shields.io/badge/version-0.17.1-B4A7E5?style=flat-square)](.claude-plugin/plugin.json)
[![License: MIT](https://img.shields.io/badge/license-MIT-93D3BB?style=flat-square)](LICENSE)

</div>
Expand Down
2 changes: 1 addition & 1 deletion gemini-extension.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"name": "fstack",
"version": "0.17.0",
"version": "0.17.1",
"description": "Federico Mastrini's agent skills for everyday software engineering work."
}
2 changes: 1 addition & 1 deletion plugin.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"$schema": "https://agent-plugins.org/schemas/1.0.0/plugin.schema.json",
"name": "fstack",
"version": "0.17.0",
"version": "0.17.1",
"description": "Federico Mastrini's agent skills for everyday software engineering work.",
"author": {
"name": "Federico Mastrini",
Expand Down
46 changes: 26 additions & 20 deletions skills/implement/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,19 +10,30 @@ Write the code as if the requirement had been a founding assumption: the **end s

When another skill called this one (such as implement-issue), its rules win wherever the two differ: scope, test handling, stop rules, and the reply.

## 1. Design the end state

Read the code the change touches and its callers, and run the project's checks once so you know what already fails. The checks are the ones the project already has (its test, typecheck, lint, and build scripts or CI steps); a kind it lacks is reported as not run, never installed or borrowed for the occasion. Then decide, before editing, what the code would look like had this requirement been there from the start. Settle the types and stored shape before the functions that use them: trace how the data is read and written, and fit the structure to the dominant paths. The right shape makes the logic obvious.
## Principles

Each principle is a short file in `references/` with the rule and the test that checks it. Read every file whose trigger the change meets, in one batch, before designing.

| Read | When the change |
| --- | --- |
| [redesign-from-first-principles.md](references/redesign-from-first-principles.md) | adds a requirement to existing code |
| [subtract-before-you-add.md](references/subtract-before-you-add.md) | leaves code the end state no longer needs, or tempts a helper, option, or guard for a case that doesn't exist yet |
| [laziness-protocol.md](references/laziness-protocol.md) | makes a choice (a mode, format, or setting) that more than one place acts on |
| [foundational-thinking.md](references/foundational-thinking.md) | adds or changes types, stored data, or state that several actors touch |
| [model-the-domain.md](references/model-the-domain.md) | adds stateful logic, a flag beside another flag, or a branch to a chain |
| [type-system-discipline.md](references/type-system-discipline.md) | designs or changes types |
| [boundary-discipline.md](references/boundary-discipline.md) | reads outside input (env, config, CLI args, files, network, rows) or wires validation and error handling |
| [make-operations-idempotent.md](references/make-operations-idempotent.md) | changes state in a job, command, import, or handler that can crash, retry, or rerun |
| [separate-before-serializing-shared-state.md](references/separate-before-serializing-shared-state.md) | has concurrent workers, processes, or branches writing the same file, key, or object |
| [migrate-callers-then-delete-legacy-apis.md](references/migrate-callers-then-delete-legacy-apis.md) | replaces an internal API, helper, or module |
| [outcome-oriented-execution.md](references/outcome-oriented-execution.md) | is a rewrite or migration planned in several steps |
| [build-the-lever.md](references/build-the-lever.md) | is more than a couple of obvious edits: repeated edits, a data fix, an analysis, or a claim no test proves |
| [test-behavior-not-implementation.md](references/test-behavior-not-implementation.md) | writes, changes, or keeps a test |
| [minimize-reader-load.md](references/minimize-reader-load.md) | adds or moves code a reader must trace (every change, for step 3) |

- **Invariants.** Put each rule that must always hold where nothing can bypass it: a type (a union or state machine over flags that must agree, a typed model over loose parameters, a distinct type for look-alike primitives, an exhaustive match), a schema constraint (a unique key, a foreign key), or one parse at the boundary. A second flag that must stay in sync with the first is asking for one.
- **Branches.** Encode the domain in data: a map or registry instead of a branch chain spread across files, one reducer instead of state changed from several places. A change that adds one more branch to a chain is asking for one.
- **Boundaries.** Parse raw input (env, config, CLI args, files, network, rows) once, where it enters, into typed values; pass those in and trust them inside. When a schema already owns the shape (OpenAPI, protobuf, a validation or database schema), derive the type from it. Business logic stays pure and free of framework types.
- **Decisions.** Make each choice once, behind one source of truth, and pass the result in as a plain value. DRY the structure, not every line.
- **Reruns.** An operation that changes state converges: derive each step from the current state and apply only the difference, so a second run or a run after a crash at any point ends the same. Leftovers (locks, temp files, half-written records) are recognizable as stale; write to a temp path and rename into place.
- **Shared state.** Give each concurrent actor its own file, key, or record and merge where it is read; serialize only when one shared writer is a real invariant.
- **Subtraction.** List what the end state no longer needs, in the change's path: dead code, unreachable branches, checks the types now guarantee, pass-through layers (a wrapper with one caller, an adapter with one implementation), the API being replaced. Deleting it is part of the change. Dead code elsewhere goes in follow-ups.
## 1. Design the end state

Plain code stays plain when its shape is local and unlikely to grow: an abstraction earns its place by deleting branches or invalid states.
Read the code the change touches and its callers, and run the project's checks once so you know what already fails. The checks are the ones the project already has (its test, typecheck, lint, and build scripts or CI steps); a kind it lacks is reported as not run, never installed or borrowed for the occasion. Then decide, before editing, what the code would look like had this requirement been there from the start, following the principles you read.

When the end state changes something outside the repo is known to rely on (a public API, a CLI, a schema or file format another program reads), ask before building: the bolt-on, the redesign, the cost of each, your recommendation first. With no one to answer, take the option that keeps outside callers working and say so. State only this code reads (its own files and caches, and what its docs say about them) is the code's to change; say how what is already on disk carries over.

Expand All @@ -33,29 +44,24 @@ Done when you can state the end state in a few lines: its types, where parsing h
Reach the end state in single-purpose steps, behavior and structure apart, in this order: delete what nothing uses, lay the shared shape (types, schema, the boundary parse, test fakes), build on it, and delete what it replaced last. After each step, run the narrowest check that covers it (the one test file, typecheck or lint on the touched files).

- **Behavior changes** go test-first: a failing test through the public interface with the expected value taken from the requirement, then the code. Follow the test-driven-development skill when the user or a calling skill asks for it.
- **Refactors** keep every observable result. The tests are the net; one that breaks while behavior holds was pinned to internals, so rewrite it through the public interface and report it.
- **Replacing an API.** Move every caller, then delete the old API and the tests that only covered it, so one way remains. Each caller keeps what the old API did for it (normalizing input, defaults, error mapping): that moves into the new API or the caller, with a test.
- **Planned multi-step rewrites** converge on the end state instead of keeping each intermediate step green with throwaway compatibility code. Say which checks may be red between which steps; everything is green at the end.
- **Lever.** Non-trivial work gets a tool that does it or proves it: a codemod or script for repeated edits, a script for a data fix or an analysis, a generator for repeated code, a rerunnable check for a claim no test makes (every caller moved, every row fixed). A behavior change's failing-first test already proves it. The bar is triviality, not repetition: only a couple of obvious edits go without a tool. Do the first unit by hand, then build the smallest tool, never a framework, and prove it by rerunning it on that unit; make it safe to rerun. A deterministic tool beats fanning out to subagents; to fan out, write the recipe, the verification contract, and the fences as one skill the delegates read and cannot edit. Keep the tool in the diff when the work outlives the session, else delete it once it has run; name it in the report either way.
- **Refactors** keep every observable result. A test that breaks while behavior holds was pinned to internals: rewrite it through the public interface and report it.
- **Propagate** every reference to what changed: types, call sites, docs, README tables, examples, rationale.

Add a helper, layer, option, flag, guard, or dependency only for duplication, branches, or inputs that exist now; guards and fallbacks live at boundaries.

Done when the end state stands: every caller moved, every listed deletion made, every reference propagated, and each lever built.

## 3. Check

Rerun the checks on the final tree and match or beat the first run; when no check exercises a changed command, job, or server, run it once. Read the whole diff once as a new reader would, and fix what you find: a pass-through layer, mutable state that could be a return value or derived, a check repeated past the boundary, a decision made in two places, leftovers (debug output, commented-out code, unused imports).
Rerun the checks on the final tree and match or beat the first run; when no check exercises a changed command, job, or server, run it once. Read the whole diff once as a new reader would, against the tests in the principles you read, and fix what you find.

Done when the checks match or beat the first run and, for each value the diff touches, a new reader finds where it comes from and what can change it in one place.
Done when the checks match or beat the first run and the diff passes each principle's test.

## Report

Reply in this shape, dropping empty lines:

```
<what changed, one line>
End state: <one sentence: the shape, where parsing happens, what replaced what>
End state: <one sentence: the shape, where parsing happens, what replaces what>
Removed: <what you deleted>
Levers: <each tool beyond the tests: what it did or proved, kept or deleted>
Verified: <checks and results, against the first run>
Expand Down
14 changes: 14 additions & 0 deletions skills/implement/evals/discount-code-expiry/case.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
schema_version: "1.1"
name: discount-code-expiry
expected_outcome: |
The catalog gains an expiry per code (SPRING25's last valid day is 2026-05-31, the others none), an
expired code raises its own error type (such as ExpiredCode) that checkout turns into an "expired" message
distinct from "That code doesn't exist", and the current date reaches the expiry check as a value (a
parameter or an injected clock) read once at the entry point, not by patching datetime in tests. The new
tests drive apply_code or checkout with concrete dates and literal expected totals, cover both sides of the
boundary (31 May still discounts, 1 June is refused), and assert the error type or checkout's result rather
than message text. The old tests pinned to internals (patching _lookup and asserting the call, patching
_CODES with the old shape, comparing the exception message) are rewritten through the public interface
rather than re-pointed at new internals. The unittest suite passes.
context:
scaffold_script: place-files.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
# till

Checkout for the shop's tills. `python3 -m till cart.json [CODE]` prints the total for a cart;
`checkout()` is what the till screen calls. Run the tests with `python3 -m unittest discover -s tests -t .`.
Empty file.
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import unittest

from till.checkout import checkout

CART = [{"price_cents": 1500, "qty": 2}, {"price_cents": 500, "qty": 1}]


class CheckoutTest(unittest.TestCase):
def test_totals_the_cart(self):
self.assertEqual(checkout(CART), {"total_cents": 3500, "error": None})

def test_applies_a_code(self):
self.assertEqual(checkout(CART, "STAFF50")["total_cents"], 1750)

def test_unknown_code_keeps_the_full_total(self):
self.assertEqual(
checkout(CART, "NOPE"), {"total_cents": 3500, "error": "That code doesn't exist"}
)
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import unittest
from unittest import mock

from till import discounts


class ApplyCodeTest(unittest.TestCase):
def test_looks_up_the_code(self):
with mock.patch.object(discounts, "_lookup", return_value=10) as lookup:
discounts.apply_code(1000, "WELCOME10")
lookup.assert_called_once_with("WELCOME10")

def test_applies_the_rate(self):
with mock.patch.dict(discounts._CODES, {"TEST20": 20}):
self.assertEqual(discounts.apply_code(1000, "TEST20"), 800)

def test_unknown_code_message(self):
with self.assertRaises(ValueError) as ctx:
discounts.apply_code(1000, "NOPE")
self.assertEqual(str(ctx.exception), "unknown code: NOPE")

def test_codes_ignore_case_and_spaces(self):
self.assertEqual(discounts.apply_code(1000, " welcome10 "), 900)
Empty file.
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import json
import sys

from till.checkout import checkout


def main(argv):
with open(argv[0]) as f:
cart = json.load(f)
result = checkout(cart, argv[1] if len(argv) > 1 else None)
if result["error"]:
print(result["error"], file=sys.stderr)
print(f"Total: {result['total_cents'] / 100:.2f}")


if __name__ == "__main__":
main(sys.argv[1:])
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
from till import discounts


def checkout(cart, code=None):
"""Total a cart of {"price_cents", "qty"} lines, applying an optional discount code."""
total = sum(line["price_cents"] * line["qty"] for line in cart)
if code:
try:
total = discounts.apply_code(total, code)
except discounts.UnknownCode:
return {"total_cents": total, "error": "That code doesn't exist"}
return {"total_cents": total, "error": None}
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
"""Discount codes for checkout."""

_CODES = {
"WELCOME10": 10,
"SPRING25": 25,
"STAFF50": 50,
}


class UnknownCode(ValueError):
"""The code isn't in the catalog."""


def _lookup(code):
rate = _CODES.get(code.strip().upper())
if rate is None:
raise UnknownCode(f"unknown code: {code}")
return rate


def apply_code(total_cents, code):
"""Return the total in cents after applying a discount code."""
rate = _lookup(code)
return total_cents - total_cents * rate // 100
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
type: llm
focus: trace
weight: 1
---

The current date reaches the expiry check as a value (a `today`/`on`/`now` parameter or an injected clock) that the entry point supplies once, and the new tests pass concrete dates instead of patching datetime/date or freezing time.
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
type: llm
focus: trace
weight: 1
---

Tests cover both sides of SPRING25's expiry: on 2026-05-31 the code still discounts (with a literal expected total), and on 2026-06-01 it is refused.
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
type: llm
focus: trace
weight: 1
---

An expired code raises its own error type (or result variant) distinct from an unknown code, checkout turns it into a message that says the code expired, and the tests assert the error type or checkout's returned result rather than comparing exception message text.
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
type: llm
focus: trace
weight: 1
---

No test in the final tree patches or asserts calls to till's private internals (`_lookup`, `_CODES`, or their replacements); the tests that did were rewritten to drive apply_code or checkout through their public interface, and the old test comparing `str(exception)` to "unknown code: NOPE" now asserts the error type or checkout's result.
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
type: llm
focus: trace
weight: 1
---

python3 -m unittest discover -s tests -t . passes at the end of the run.
6 changes: 6 additions & 0 deletions skills/implement/evals/discount-code-expiry/place-files.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
#!/usr/bin/env bash
set -eu
cp -R "$(dirname "$0")/files/." .
git -C till init -q -b main
git -C till add -A
git -C till -c user.name=fixture -c user.email=fixture@example.org commit -qm "Till"
12 changes: 12 additions & 0 deletions skills/implement/evals/discount-code-expiry/prompt.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
---
tags: [implement]
max_turns: 80
timeout_seconds: 1500
allowed_tools: [Read, Glob, Grep, Skill, Write, Edit, Bash]
---

discount codes in till/ need expiry dates. SPRING25 is valid through 31 May 2026 and stops working on 1 June; the other codes don't expire. when someone uses an expired code the till should say it expired, not that it doesn't exist

(Nobody can answer questions during this run.)

Input files: till/
13 changes: 13 additions & 0 deletions skills/implement/evals/report-json-flag/case.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
schema_version: "1.1"
name: report-json-flag
expected_outcome: |
`tally report --json <file>` prints the summary as JSON (projects with their hours, and the total) that
parses with a JSON parser, and the text output stays byte-for-byte the same. The choice between text and
JSON is made once, where the CLI parses its arguments, and passed down as a value (a render function or
formatter), not threaded as a flag through ReportService to be checked again below. The run adds nothing
beyond the request: no --format with other choices, no config or env setting, no registry or plugin
machinery. ReportService, a one-caller layer that only forwards, and the single-implementation Formatter
base class are collapsed or the run says why they stay. A test runs the CLI with --json and checks the parsed
output against literal values. The README documents --json. The unittest suite passes.
context:
scaffold_script: place-files.sh
8 changes: 8 additions & 0 deletions skills/implement/evals/report-json-flag/files/tally/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
# tally

Timesheet reports. Each line of a timesheet CSV is `date,project,hours`.

python3 -m tally report hours.csv

prints the hours per project, largest first, and the total. Run the tests with
`python3 -m unittest discover -s tests -t .`.
Empty file.
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import argparse
import sys

from tally.loader import CsvLoader
from tally.service import ReportService


def main(argv=None):
parser = argparse.ArgumentParser(prog="tally")
commands = parser.add_subparsers(dest="command", required=True)
report = commands.add_parser("report", help="hours per project")
report.add_argument("path")
args = parser.parse_args(argv)
print(ReportService(CsvLoader()).render(args.path))
return 0


if __name__ == "__main__":
sys.exit(main())
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
from abc import ABC, abstractmethod


class Formatter(ABC):
@abstractmethod
def format(self, summary):
...


class TextFormatter(Formatter):
def format(self, summary):
width = max([len(name) for name, _ in summary["projects"]] + [5])
lines = [f"{name:<{width}} {hours:6.1f}" for name, hours in summary["projects"]]
lines.append(f"{'Total':<{width}} {summary['total']:6.1f}")
return "\n".join(lines)
Loading