Compare commits

...
Author SHA1 Message Date
dckc ff600b84f6 no-ambient-authority: tests don't check logs; note DPY010 :memory: bug
Logging is an operational side effect, not output, so tests check
stdout and return values, never log records. This follows from the
style guide's choice to call logging directly rather than inject it.
Moved here from py-doctest, where it was orthogonal.

The checker flags sqlite3.connect(':memory:'), which isn't I/O. Note
it beside "treat each finding as a bug" until the checker learns the
exemption.

Generated-by: Claude Opus 5.5
2026-11-14 15:50:50 -06:00
dckc 5c477151cc feat(py-doctest): Python tests are doctests on the API they test
Docs go stale, and a test is often the clearest statement of what code
does; a doctest is both. Setup goes in private helpers in the module
(a `_MockIO` named after `main`'s parameters, `_shown()` to sort), so
each example is a call and its output. A script's module docstring is
its manual and runs `main(...)` with fakes; otherwise the module
docstring stays brief, per docs-files-api.

The rule had lived only in one workspace's project memory. It came
from qtrx, where agents kept copying test_bld_balance.py: "test_bld_balance
is a bad precedent. I keep running into that." Hence the trigger on
being about to write a test_*.py, and lazy-tdd's step 1 now points
here, since "the project's existing framework and style" is what sent
agents to the neighboring file.

The example script's doctests pass under several PYTHONHASHSEEDs.

Generated-by: Claude Opus 5.5
2026-11-14 15:50:50 -06:00
dckcandClaude Opus 5.5 6adb4bce33 feat(refactor-mercilessly): at each green, shrink what holds authority
From toybox's lend-the-mower example (dckc/vattr97#50): its boot vat
held vatAdmin, bundles, and an ingress, and also rendered the yard page
and routed its requests, all reached only by the Cloudflare test, and
the kernel test re-implemented its wiring. Dan pointed at agoric-sdk's
habit of small vat modules and `*.exo.js` makers, and at security as
extreme modularity; splitting it out gave each piece a fast test.

Peeling the kernel apart one example at a time, for the same PR,
showed the coupling cost: removing one feature took edits across
eight files. Dan's caveat shapes the commits rule: reviewers who knew
the prior state want small diffs as they go, so fold refactors into
history only when the audience changes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-06 15:29:02 -06:00
5 changed files with 164 additions and 3 deletions

No files matched your search

+5
View File
@@ -28,6 +28,11 @@ Code](https://code.claude.com/docs/en/skills) and
failure path leaves a trace in the logs. failure path leaves a trace in the logs.
- [lazy-tdd](lazy-tdd/SKILL.md) — works the first time? fine. Goofed? - [lazy-tdd](lazy-tdd/SKILL.md) — works the first time? fine. Goofed?
You owe a test. You owe a test.
- [py-doctest](py-doctest/SKILL.md) — Python tests are doctests on the
API they test, setup in private helpers, no `test_*.py`.
- [refactor-mercilessly](refactor-mercilessly/SKILL.md) — at each
green, move logic out of the modules that hold authority into small,
fast-tested ones; keep refactors in commits of their own.
- [docs-files-api](docs-files-api/SKILL.md) — README sells and gets - [docs-files-api](docs-files-api/SKILL.md) — README sells and gets
you to TADA; CONTRIBUTING has the rest; AGENTS.md links to it. you to TADA; CONTRIBUTING has the rest; AGENTS.md links to it.
Exported API docs over file docs. Avoid chit-chat. Exported API docs over file docs. Avoid chit-chat.
+3 -1
View File
@@ -31,7 +31,9 @@ From Dan Connolly's
## paying the debt (test-driven debugging) ## paying the debt (test-driven debugging)
1. Write a test that reproduces the goof, in the project's existing test 1. Write a test that reproduces the goof, in the project's existing test
framework and style, next to related tests. framework and style, next to related tests. For a Python script or
tool, that's a doctest in the module, whatever files sit next to it
([py-doctest](../py-doctest/SKILL.md)).
2. Run it; **watch it fail** for the reason you expect. A test that 2. Run it; **watch it fail** for the reason you expect. A test that
passes before the fix proves nothing about the fix. passes before the fix proves nothing about the fix.
3. Fix the code. 3. Fix the code.
+7 -2
View File
@@ -1,7 +1,7 @@
--- ---
name: no-ambient-authority name: no-ambient-authority
description: >- description: >-
Use when writing or reviewing code whose functions touch I/O, clocks, random number generators, process.env, fetch, or filesystem; before writing or refactoring any Python script (DisciplinedPython style guide and checker); when someone says "ambient authority", "wash your mouth out", or "that function shouldn't reach for that"; when debating dependency injection or default-arg seams; when asked what OCap discipline is. Source: the Agoric wiki's OCap Discipline page. Use when writing or reviewing code whose functions touch I/O, clocks, random number generators, process.env, fetch, or filesystem; before writing or refactoring any Python script (DisciplinedPython style guide and checker); when someone says "ambient authority", "wash your mouth out", or "that function shouldn't reach for that"; when debating dependency injection or default-arg seams; when tempted to inject a logger or assert on log output; when asked what OCap discipline is. Source: the Agoric wiki's OCap Discipline page.
--- ---
# OCap Discipline # OCap Discipline
@@ -53,12 +53,17 @@ before writing or refactoring a Python script; don't invent conventions.
guard, authorities passed by name), standard authority names (`argv`, guard, authorities passed by name), standard authority names (`argv`,
`cwd`, `stdout`, `connect`, `run`, `urlopen`, `now`), prompt attenuation `cwd`, `stdout`, `connect`, `run`, `urlopen`, `now`), prompt attenuation
in `main`, and **status goes through `logging.info(...)` directly**: not in `main`, and **status goes through `logging.info(...)` directly**: not
`print`, not `stderr` writes, not an injected logger. `print`, not `stderr` writes, not an injected logger. Logging is an
operational side effect, not output: tests check `stdout` and return
values, never log records, since correctness doesn't depend on logging.
- [disciplined-python-attenuation.md](https://codeberg.org/dckc/awesome-ocap/src/branch/master/style-guide/disciplined-python-attenuation.md): - [disciplined-python-attenuation.md](https://codeberg.org/dckc/awesome-ocap/src/branch/master/style-guide/disciplined-python-attenuation.md):
narrowing authority function by function. narrowing authority function by function.
- Checker: run `~/projects/awesome-ocap/tools/disciplined_python_check.py path/to/script.py` - Checker: run `~/projects/awesome-ocap/tools/disciplined_python_check.py path/to/script.py`
and treat each finding as a bug. It points at matching before/after and treat each finding as a bug. It points at matching before/after
examples in `tests/fixtures/disciplined_python/{errors,fixed}/`. examples in `tests/fixtures/disciplined_python/{errors,fixed}/`.
Known checker bug: it flags `sqlite3.connect(':memory:')` as DPY010,
but an in-memory database is private to the process, not I/O; leave
that call in place.
- Calibration: Python can't enforce a capability boundary (name mangling - Calibration: Python can't enforce a capability boundary (name mangling
and introspection get around any wrapper), so for a small script, and introspection get around any wrapper), so for a small script,
attenuation that lives mostly in names is fine. An example: a read-only attenuation that lives mostly in names is fine. An example: a read-only
+84
View File
@@ -0,0 +1,84 @@
---
name: py-doctest
description: >-
Python doctests document the API and test it at once. Use when writing, refactoring, or fixing a Python module, script, or tool and deciding where its tests go; when about to write or add to a test_*.py, unittest, or pytest file. Not for whether a test is owed at all (that's lazy-tdd).
---
# Doctests in the module
Docs and tests both make code better, but docs go stale, and a test is often the clearest statement of what code does. A doctest is both: an example a reader sees next to the code, checked on every run. So **put Python tests in the module as doctests, on the API they test, with setup in small private helpers.**
As in [docs-files-api](../docs-files-api/SKILL.md), the API's docstrings carry the weight, and the module docstring stays brief and points to them. A script is the exception: people open it to learn how to run it, so its module docstring is the manual, and a doctest there runs `main(...)` with fakes. That's cheap when `main(...)` takes its authority as arguments ([no-ambient-authority](../no-ambient-authority/SKILL.md)). The example is a script, so it has both.
```python
"""Match bank rows to orders.
Usage, documented and tested together:
>>> usage = 'match_orders book.db'
>>> io = _MockIO()
>>> main(usage.split(), io.stdout, io.connect)
>>> print(io.stdout.getvalue(), end='')
1 matched; unmatched: ['A-17']
"""
def unmatched(conn):
"""Order ids with no bank row of the same amount.
>>> _shown(unmatched(_MockIO().connect('book.db')))
['A-17']
"""
return {oid for (oid,) in conn.execute(
"select id from orders where amount not in (select amount from bank)")}
def main(argv, stdout, connect):
[_, db] = argv
conn = connect(db)
left = unmatched(conn)
[(n,)] = conn.execute("select count(*) from orders")
print(f"{n - len(left)} matched; unmatched: {_shown(left)}", file=stdout)
class _MockIO:
def __init__(self):
from io import StringIO
self.stdout = StringIO()
def connect(self, _db):
import sqlite3
conn = sqlite3.connect(':memory:') # in-process: not I/O
conn.executescript("""
create table orders (id text, amount int);
create table bank (id int, amount int);
insert into orders values ('A-16', 1200), ('A-17', 350);
insert into bank values (1, 1200);
""")
return conn
def _shown(x):
"""Sorted, so output doesn't depend on string hashing."""
return sorted(x.items()) if isinstance(x, dict) else sorted(x)
if __name__ == '__main__':
def _script_io():
import sqlite3
import sys
main(sys.argv, sys.stdout, sqlite3.connect)
_script_io()
```
Run with `python3 -m doctest tool.py` (add `-v` to see each example). Silence means pass.
- Ignore neighboring `test_*.py` files as a style cue: one may be an accident that stuck, and each copy makes the next look more like a precedent. Don't add to them or start a new one. When refactoring a module that has one, moving its tests into doctests is fair game, in a commit of its own.
- When a test needs more than a helper can hide (a fixture tree on disk, a subprocess, minutes of runtime), say so and ask before reaching for a test file.
## Sources
- [No more undocumented, untested code](https://www.madmode.com/2006/advogato_entry0044.html): Dan Connolly, MadMode, 2006-03-18. "If the code is worth writing, it's worth testing and documenting."
- [Practical production python scripts](https://www.madmode.com/2019/python-eng.html): Dan Connolly, MadMode, 2019-07-22. Factoring logic out of `main()` with a doctest on `fizzbuzz()`, then a module doctest of usage with `StringIO` for `stdout`.
- [doctest](https://docs.python.org/3/library/doctest.html): in the stdlib since Python 2.1 (2001); option flags such as `ELLIPSIS` and `NORMALIZE_WHITESPACE`.
+65
View File
@@ -0,0 +1,65 @@
---
name: refactor-mercilessly
description: >-
Refactor mercilessly, in the XP sense: once the tests are all green, look for code that only a slow, outer test reaches, logic sitting in the module that holds the most authority, duplicated wiring, and setup a test re-implements, and pull it into small modules with tests of their own. Use when a change has just gone green; when a vat, entry module, boot vat, or handler has grown past its wiring; when code is "only tested at the cf level" or by an end-to-end test; when a test builds what production builds, by hand; when someone says "refactor mercilessly", "all green", "extract", "small vat modules", "*.exo.js", or "provideX". Not for regrouping commits (that's retcon), or for fixing a goof (that's lazy-tdd).
---
# Refactor mercilessly
```js
// before: the boot vat renders HTML, routes requests, and lends the mower,
// and only the Cloudflare test runs any of it
export const buildRootObject = ({ E, Far, zone }, { vatAdmin, bundles, ingress }) => {
const esc = s => ...; const page = (cut, log) => ...; // 40 lines
const makeYard = zone.exoClass('Yard', ..., { async handle() { ... } });
return Far('boot', { async start() { /* make 3 vats, lend, serve */ } });
};
// after: the boot vat wires; the rest is modules a fast test can reach
import { lendMower, makeNeighbors } from './lend.js'; // the kernel test calls it too
import { provideYard } from './yard.exo.js'; // tested in a heap zone, fake mower
export const buildRootObject = ({ E, Far, zone }, { vatAdmin, bundles, ingress }) => {
const yard = provideYard(zone, { E, lease, fence: FENCE });
return Far('boot', { async start() { /* ensure vats, lend once, serve yard */ } });
};
```
## Context
The tests just went green. The code works, and it was written to get there: logic landed wherever the first caller was, often the entry module, the boot vat, or a handler, the place that holds the most authority. The test that proves it is the slowest one: a whole service under workerd or wrangler.
## Problem
**When the tests pass, how much of the code they cover is in a shape you'd want to keep?**
## Forces
- Green is when it's safe to restructure, and the cheapest time, while the code is fresh. Later, every caller and reviewer has learned its shape.
- Security is extreme modularity (see [pola](../pola/SKILL.md)). A module that holds vatAdmin, bundles, and an ingress, and also renders HTML, gives every line of that HTML the module's authority. The module holding the most authority should have the least code: wiring that a reader can check by eye.
- Code reached only by an end-to-end test is tested slowly and coarsely. A goof in it shows up as "the yard page is wrong", not as which function is wrong.
- A test that builds by hand what production builds (makes the three vats, then lends the mower) tests its own copy of the wiring. Production's copy can drift untested.
- How hard a feature is to pull out measures its coupling. If peeling one example off a kernel takes edits in eight files (kernel, supervisor, config, types, client, test harness), its seams are in the wrong place.
- Bundles, vats, and other isolation boundaries can force a copy: a boot directory's bundle can't import a helper from outside itself.
- Reviewers who followed along know the prior state, and read a small diff against it easily. A big restructure, folded into history, makes them reread everything.
## Therefore
**At each green, before moving on, move logic out of the modules that hold authority into small modules that hold none, each with a test as fast as it can be. Then reach for green again.**
- **Pure functions** (rendering, parsing, arithmetic) go in their own module, tested in plain node.
- **A kind of durable object** goes in `<name>.exo.js` as `provide<Name>(zone, powers)` (or `prepare<Name>`, which answers the maker), taking only the powers it uses. Test its behavior in a heap zone, with fakes made in the same zone: fast, and no vatstore. A heap zone can't show durability (state that persists, an object that outlasts an incarnation), so add one test under a durable zone (liveslots over an in-memory vatstore) that makes a second incarnation over the same vatstore. The heap zone must share the durable zone's defaults, such as what a kind given no guard checks, or the two disagree on the same code; and both keep the library's. When a fast test seems to need a looser default, look for what differs in the test's environment: Node's async_hooks ids on promises, not the kind, made async results fail the passable check.
- **Wiring that a test also does** goes in a function both call, such as `lendMower(E, makeVat, fence)`, so the test exercises production's wiring.
- **What's left** in the vat, entry module, or handler is wiring: get the powers, call the modules, hand out the results. One slow test covers that it's wired.
- **A copy that a boundary forces** gets a comment saying where its twin is, until there's a way to share it (a capability, or a library in the bundle).
- **Commits:** a refactor is a commit of its own, and so is a behavior change, each green, and each pushed when made. While someone is following along, keep them separate, so each one diffs against a state they knew. Fold them into the history ([retcon](../retcon/SKILL.md)) only when the audience changes to readers who never saw the prior state, or when asked.
## Resulting context
The modules that hold authority shrink to wiring, and the logic sits where a fast test reaches it, so a goof names its own function. The next feature adds modules and a line of wiring rather than edits across the kernel. There are more files, and an import graph to learn; a reader starts at the wiring and follows its imports.
A refactor still risks behavior. Keep it to code the tests reach, and when a refactor needs a new test to be safe, write that test first ([lazy-tdd](../lazy-tdd/SKILL.md)).
## Sources
- [Refactor Mercilessly](https://wiki.c2.com/?RefactorMercilessly): the c2 wiki's XP page. Refactor whenever you see the chance, so the design stays simple as it grows.
- [From E to EcmaScript and Back Again](https://qconsf.com/sf2010/dl/qcon-sanfran-2010/slides/MarkS.Miller_FromEToECMAScriptAndBackAgain.pdf): Mark S. Miller, QCon SF 2010; slide 3 is "Security as Extreme Modularity".