Compare commits

..
Author SHA1 Message Date
dckc 9c75e44fef obsidian-markdown: name notes for their subject, not README
Generated-by: Claude Opus 5.5
2026-11-20 08:20:38 -06:00
dckc 8eaff2bf7a Add typed-remotes skill
A bare Remote is Remote<any>: name what a reference is, declare
buildRootObject with @satisfies so its root type can be exported, and
put the one cast where the kernel loses the type. Fixed twice in vattr97
code and back again, because toybox's CONTRIBUTING called bare Remote
the one place any was fine; so the skill also says to fix the guidance
and add a lint rule.

Generated-by: Claude Opus 5.5
2026-11-18 01:45:20 -06:00
dckc 5118c5c9b0 feat(gh-progress-report): a milestone comment on an issue, as a record
How to write the GitHub issue comment that reports a milestone: an h2
naming it, no date (GitHub dates comments), real commands and their
output, `git log10` back to the last checkpoint as a list, so the hashes
link (`owner/repo@hash` for another repo), and how it's put together,
from where authority enters.

Said in three sessions before it was written down: 2026-11-11 ("I like
to use high-entropy stuff such as git hash... actual commands and their
output"), 2026-11-16 ("start with a ## heading and leave out the date"),
and 2026-11-18 ("did I not make that clear?"; "this style of major
progress report", not every comment; "that's not log10 style"; of a
wiring diagram that began mid-story, "by magic?"; and "git log10 output
in a code block loses the benefit of linked hashes").

Generated-by: Claude Opus 5.5
2026-11-18 01:44:57 -06:00
dckc 2851fe872a feat(no-ambient-authority): designation is not authority; tests' helpers
From reworking toybox's tests: a port or a path, joined to a fetch or fs
the code holds anyway, reaches more than the one resource, so hand out
the object bound to it (a toybox's sockets; a tree rooted at a
directory, as openat reaches it). Swiss numbers belong at the boundary
that can't carry references. A test's I/O is set up once, as a promise
each test awaits, and each helper gets only the powers it uses.

Generated-by: Claude Opus 5.5
2026-11-16 16:24:19 -06:00
dckc 2b8704bdd0 docs(README): mark pattern parts in the text, not as headings
Generic headings (Context, Problem, Forces, ...) waste heading space;
docs-files-api already says headings name the point. Mark the parts as
Alexander did: bold problem, a list of forces, a bold "Therefore:".
TODO: rework the patterns that still use the parts as headings.

Generated-by: Claude Opus 5.5
2026-11-15 21:11:57 -06:00
dckc e13420cd6d disclose-gen-ai: no trailer for a line or two the human approved
An awesome-ocap commit (one talk entry, worded in chat and approved
as-is) got the harness default Co-Authored-By trailer; the operator
had it removed: "you saved me a little typing, but only a very little."
2026-11-15 00:31:08 -06:00
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
9 changed files with 307 additions and 6 deletions

No files matched your search

+11 -1
View File
@@ -26,8 +26,15 @@ Code](https://code.claude.com/docs/en/skills) and
instrument. instrument.
- [silent-failures-are-evil](silent-failures-are-evil/SKILL.md) — every - [silent-failures-are-evil](silent-failures-are-evil/SKILL.md) — every
failure path leaves a trace in the logs. failure path leaves a trace in the logs.
- [typed-remotes](typed-remotes/SKILL.md) — `Remote<X>`, never a bare
`Remote`; `@satisfies`, not `@type`; and a lint rule so it stays fixed.
- [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.
@@ -51,6 +58,9 @@ Code](https://code.claude.com/docs/en/skills) and
with live links, quoted and dated. with live links, quoted and dated.
- [hackmd-deck](hackmd-deck/SKILL.md) — a light talk as a flashback: - [hackmd-deck](hackmd-deck/SKILL.md) — a light talk as a flashback:
TADA, then how, then the challenges, tagged for an emoji retro. TADA, then how, then the challenges, tagged for an emoji retro.
- [gh-progress-report](gh-progress-report/SKILL.md) — a milestone comment
on an issue: `## heading`, no date, real commands and their output,
`git log10` back to the last checkpoint.
- [ibis-design](ibis-design/SKILL.md) — search a design space: - [ibis-design](ibis-design/SKILL.md) — search a design space:
issues, positions, and arguments. issues, positions, and arguments.
- [wiring-diagram](wiring-diagram/SKILL.md) — who holds what, drawn - [wiring-diagram](wiring-diagram/SKILL.md) — who holds what, drawn
@@ -89,7 +99,7 @@ Write the body for an agent in the middle of a task. It reads the skill's text,
For each line, ask: would deleting it change what an agent does? If not, it belongs in the footer or the commit message. For each line, ask: would deleting it change what an agent does? If not, it belongs in the footer or the commit message.
When a skill resolves a tension, with forces pulling different ways, write it as a pattern after the Portland Pattern Repository (and Alexander before it): **Context**, **Problem**, **Forces**, **Therefore**, **Resulting context**. The forces give an agent reasons to handle cases the rules don't cover, and the resulting context says what the resolution costs. An anti-pattern takes the same form, with the tempting answer among the forces. See [notify-me](notify-me/SKILL.md) and [acls-dont](acls-dont/SKILL.md). A recipe with no tension, like [yarn-lock-separate-commit](yarn-lock-separate-commit/SKILL.md), stays plain. When a skill resolves a tension, with forces pulling different ways, write it as a pattern after the Portland Pattern Repository (and Alexander before it): context, problem, forces, therefore, resulting context. Mark the parts in the text, as Alexander did, not with generic headings: the context in the opening paragraph, the problem as a bold sentence, the forces as a list, the resolution after a bold **Therefore:**, and its cost to close. Headings, where the body needs them, name the point ([docs-files-api](docs-files-api/SKILL.md)): "Confidential details stay private", not "Therefore". The forces give an agent reasons to handle cases the rules don't cover, and the resulting context says what the resolution costs. An anti-pattern takes the same form, with the tempting answer among the forces. TODO: rework the patterns ([notify-me](notify-me/SKILL.md), [acls-dont](acls-dont/SKILL.md), [refactor-mercilessly](refactor-mercilessly/SKILL.md), [hackmd-deck](hackmd-deck/SKILL.md)), which still use the parts as headings. A recipe with no tension, like [yarn-lock-separate-commit](yarn-lock-separate-commit/SKILL.md), stays plain.
TODO: revise every skill with this in mind. TODO: revise every skill with this in mind.
+5 -2
View File
@@ -21,8 +21,11 @@ Generated-by: Claude Opus 5.5
## the rules ## the rules
- **When:** the content is substantially machine-generated: code, - **When:** the content is substantially machine-generated: code,
docs, tests, or a rewrite. Not needed for a typo fix or an edit the docs, tests, or a rewrite. Not needed for a typo fix, an edit the
human typed. human typed, or a line or two the human approved word for word,
such as one entry added to a list: the tool saved a little typing,
nothing more. This holds even when the harness says to add its own
trailer to every commit.
- **Form:** `Generated-by: <Tool> <Version>`, as the last paragraph of - **Form:** `Generated-by: <Tool> <Version>`, as the last paragraph of
the message, in git trailer format (`git interpret-trailers` can the message, in git trailer format (`git interpret-trailers` can
parse it). parse it).
+24
View File
@@ -0,0 +1,24 @@
---
name: gh-progress-report
description: >-
Progress report on a milestone, as a GitHub issue comment — use after a milestone on work that has an issue, when proposing or posting a comment that says something works and how; when someone says "report success on #N", "progress comment", or "include git log10". Not for short replies or quick notes on an issue.
---
# Progress report
An issue comment that reports a milestone is a record its reader keeps: it reaches email, it's searchable for decades, and a public one shows up as a quick note on the author's blog. Write it as a document of its own.
- **Start with an h2**, `## <the milestone>`, such as `## Coinbase sync works, as a toybox toy`. Subsections are `###`. A short reply or a quick note gets no heading.
- **No date.** GitHub dates every comment; a date in the body only repeats it.
- **Show real commands and their output**, pasted as-is: `git log10`, `git annex list`, a test summary. They carry high-entropy facts, such as hashes, that let a later reader find exactly what was done.
- **`git log10`** is an alias: `log -n 10 --pretty=format:'%ad %h %s' --date='format:%Y-%m-%d %H:%M'`. Run the alias itself, not a format of your own. Filter by path to the code that matters, add `-n 30` or whatever reaches back to the last checkpoint reported, and trim uninteresting commits. Keep the hashes even when they're about to go bad: an unpushed branch, a retcon to come.
- **Hashes stay linked**: put `git log10` lines in a list, not a code block, where GitHub would show them as plain text. In prose GitHub links a hash of the issue's own repo; for another repo, write `owner/repo@hash`. So a line reads `- 2026-11-18 00:58 dckc/vattr97@ea49f0f fix(toybox): ...`, and the subject's own markup, such as backticks, still renders.
- **Say how it's put together**, not only that it works: who holds what, and how they came to hold it. A Mermaid `flowchart` with a subgraph per process works as a quick wiring diagram, and a `sequenceDiagram` shows the messages; GitHub renders both. Start the sequence where authority enters, not where the interesting part begins; nothing should arrive by magic ([wiring-diagram](../wiring-diagram/SKILL.md)).
- **Link, don't paste, long code**: a gist or a file at a pushed commit. A link into a commit that isn't pushed is a 404; name the path instead.
- **End with what's still to do**, briefly.
Keep confidential details out: hosts, ports, accounts, credentials, balances.
## Sources
- [The closet librarian approach to cloud services](https://www.madmode.com/2021/closet-librarian-approach-cloud-services.html), MadMode 2021: why issue comments are an archive.
+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.
+47 -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 a helper takes a port, a socket path, or a file path beside the fetch or fs that reaches it ("designation vs authority"); when setting up a test's I/O; when asked what OCap discipline is. Source: the Agoric wiki's OCap Discipline page.
--- ---
# OCap Discipline # OCap Discipline
@@ -42,6 +42,43 @@ capability-based languages, systems, papers, and talks.
authority they need, then *delegate* it downward. authority they need, then *delegate* it downward.
3. **Test scripts** are named `test-*.js`; tests export nothing. 3. **Test scripts** are named `test-*.js`; tests export nothing.
## designation is not authority
A string that names a resource is a designator: a port, a socket path, a file path, a package directory computed from `import.meta.url`. Joined to a broad power the code holds anyway (`fetch`, `WebSocket`, `fs`), it becomes access to that resource, and to everything else the same power reaches. That's the integer-to-pointer cast again, done by the caller. Hand out the object bound to the resource, not its address:
- A test harness's `startToybox()` answered `{ server, port, appPort, sock }`, and each test joined those to its own `fetch` and `WebSocket`. Now it answers `{ http(path, init), app(path, init), admin(kernel), stop() }`, each bound to its own socket, so a helper can be handed just the app socket.
- A module-level `here` (the package's path) let any line read or write anywhere by joining onto it. Instead, hand a directory and the tree under it, as `openat(dirfd, path)` reaches it: `pkg.readText('test/boot/boot.js')`, relative paths only, no `..`. endo's `EndoMount` and `ReadableTree`, and workerd's disk service, have the same shape.
- Where something truly needs an address (workerd's `-d dir=<path>`), the bound object can answer one (`tree.path(rel)`), at the edge.
Bearer secrets (swiss numbers, webkeys) are designation and authority in one string, for crossing a boundary that can't carry a reference: a link, a page's JSON. Mint and deref them at that boundary, and let inner modules deal in references. A module that mints them holds a registry and entropy its task doesn't need.
## tests are the edge; their helpers aren't
A test may import Node's I/O, but set it up once, as a promise each test awaits, not at module level (ava's `test.before(t => { t.context = ... })` is the same idea):
```js
const worldP = (async () => {
const { startToybox } = makeToyboxes({ startWorkerd, freePort, mkdir, fetch, WebSocket });
const fs = { cp, mkdir, readFile, rm, writeFile };
return {
startToybox,
net: { createHttpServer, listenLocal },
pkg: makeTree(fs, fileURLToPath(new URL('..', import.meta.url))),
makeDir: async prefix => makeTree(fs, await mkdtemp(join(tmpdir(), prefix))),
};
})();
test('...', async () => {
const { startToybox, pkg, makeDir } = await worldP;
// ...
});
```
- Each helper takes its powers as its first parameter, and only those it uses: `copyExamples({ pkg }, dir)`, not `copyExamples(world, dir)`.
- Group powers that are equivalent in authority anyway, and pass the group whole: with a server and a local listener, `net` reaches the network as `fetch` would.
- Destructure the world on one line. When a whole group fits better than its members, take the group and pick at the call: `makeClient({ fetch: net.fetch }, url)`.
- Spawning a shell script to copy a few files (`execFile('wallet-boot.sh')`) is the biggest hammer for the smallest job. If the copy is configuration, make it data, or point a read-only root at the files where they are.
## Python: DisciplinedPython ## Python: DisciplinedPython
For Python, the rules above are spelled out in the DisciplinedPython style For Python, the rules above are spelled out in the DisciplinedPython style
@@ -53,12 +90,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
@@ -79,6 +121,9 @@ before writing or refactoring a Python script; don't invent conventions.
helpers become untestable without monkey-patching; inject a helpers become untestable without monkey-patching; inject a
narrower interface (the caller passes the one URL's worth of fetch, narrower interface (the caller passes the one URL's worth of fetch,
not the whole world). not the whole world).
- A helper taking `(port, fetch)` or `(path, fs)` → designation split
from authority: the helper can reach any port, any path. Hand it the
bound object (see above).
- A module's default export closing over bindings/config → a - A module's default export closing over bindings/config → a
powerful object export. Split: pure logic (argument-only) + a thin powerful object export. Split: pure logic (argument-only) + a thin
program-script-ish edge that wires authority in. program-script-ish edge that wires authority in.
+2
View File
@@ -25,6 +25,8 @@ When you rewrite a wrapped paragraph, unwrap it. Don't unwrap a whole file you a
Obsidian shows file names in tabs, the file explorer, and search, so name files for what's in them. Obsidian shows file names in tabs, the file explorer, and search, so name files for what's in them.
Avoid `README.md` for notes in a vault: a folder of them shows as a row of tabs all named "README". Name the file for its folder's subject (`gadget-tub/gadget-tub.md`). A repo's top-level README is the exception; GitHub needs it.
Headings show in Obsidian's outline pane: make them say something. Headings show in Obsidian's outline pane: make them say something.
## Frontmatter ## Frontmatter
+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".
+66
View File
@@ -0,0 +1,66 @@
---
name: typed-remotes
description: >-
Typed references in Endo / toybox / Agoric JSDoc — use when writing or reviewing a vat's `Params` typedef, a `buildRootObject`, a store that holds references, or any `@param`/`@property`/`@type` that names another vat's object or a device; when about to write a bare `Remote`, `Remote[]`, `{any}`, or `@type {BuildRootObject<...>}`; when someone says "Params has a bunch of any", "it won't stay fixed", or "type the remotes". Not for whether a reference should be handed over at all (that's pola).
---
# Typed remotes
A bare `Remote` is `Remote<any>`. Every call through it, and everything
it answers, goes unchecked, so a wrong method name or a misread answer
gets through `tsc --checkJs` and fails at runtime, in another vat.
## The rule
- **Name what the reference is:** `Remote<X>`, never `Remote` or
`Remote[]`. `X` is:
- for another vat's root, that vat's own type, exported beside its
code: `/** @typedef {ReturnType<typeof buildRootObject>} Cache */`
- for a facet it hands out, the method's answer:
`ReturnType<Cache['viewer']>`
- for a device or a platform vat with no exported type, a small
interface naming the calls this code makes, in one `types.ts`
- **Declare `buildRootObject` with `@satisfies`, not `@type`:**
`/** @satisfies {BuildRootObject<Params>} */`. `@type` checks the
params but answers only `object`, so `ReturnType<typeof
buildRootObject>` is useless; `@satisfies` checks the same and keeps
what it infers.
- **One cast, where the type is truly lost, and it says why.** The
kernel answers only "some vat's root" for `createVat`. Look roots up
through one accessor typed by a role table:
```js
/** @typedef {{ cache: Cache, gateway: Gateway }} Roles */
/**
* it's the vat Roles names because ensure made it from that role's code
* @template {keyof Roles} R @param {R} role @returns {Remote<Roles[R]>}
*/
const rootOf = role => /** @type {Remote<Roles[R]>} */ (vats.get(role).root);
```
- **`unknown`, not `any`,** for what isn't checked yet, such as parsed
JSON: `{{ key?: unknown, at?: unknown }}`. Then narrow with a check.
- **Type the store's values too:** `MapStore<keyof State, State[keyof
State]>` with `put`/`got` generic over the key, not
`MapStore<string, any>`.
## Make it stay fixed
A fix to the code alone drifts back: the next agent copies the nearest
example, or a doc that blesses `Remote` as the place `any` is fine.
- Fix the **guidance** that licensed it (CONTRIBUTING, AGENTS.md), not
just the instances.
- Add a **lint rule** that rejects a bare `Remote` or `any` in JSDoc
types, on the files that are clean now, and widen its `files` as more
get typed. vattr97's `eslint-typed-refs.mjs` is one, with no
dependencies: it finds each type tag's balanced `{...}` in JSDoc
comments and flags `\bany\b` and `\bRemote\b(?!\s*<)`.
- After typing, **remove the test's `any`s**: they hid the same gaps
in the code under test (one, here, hid a store typed so that
`got('user')` was always `undefined`).
## Sources
- [@agoric/internal types.ts](https://github.com/Agoric/agoric-sdk/blob/master/packages/internal/src/types.ts) — the `Remote` that toybox's follows, `any` by default.
- [TypeScript 4.9: the satisfies operator](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-4-9.html#the-satisfies-operator) — checks a type without widening what's inferred; JSDoc `@satisfies` since 5.0.