Compare commits

...
7 Commits
Author SHA1 Message Date
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
dckcandClaude Opus 5.5 384a88899c feat(pola): what you hand out includes what its functions return
Add the rule to pola's description and body, and split three skills
out by situation: facet (what crosses a callback boundary),
capability-based-design (Tribble: one object per authority
distinction; narrowing only intersects), and caretaker.

A/B tested with Claude Haiku 5.5 in isolated runs, graded by an
explorer that plays Mallory. On a discord.js-style bot task, every
failure was `post: text => channel.send(text)`, whose implicit return
hands out the Message and so the client's token. Pooled pass rates:
no skills 35/70; pola's old description 36/48; the rule anywhere
139/144; this set 12/12 vs 5/12 for no skills in the same batch, and
21/21 on seven other tasks. Examples use an email SDK; they fixed the
chat-domain mistake anyway. The rule belongs in the description
because agents opened skill bodies in only some runs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 00:42:25 -06:00
dckcandClaude Opus 5.5 e62f6ac285 README: tension/resolution patterns; list acls-dont
A skill that resolves a tension is written as a pattern: context,
problem, forces, therefore, resulting context. An anti-pattern takes
the same form, with the tempting answer among the forces. A recipe
with no tension stays plain.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 21:20:17 -06:00
dckcandClaude Opus 5.5 b5411466e3 pola: mechanism vs policy as extreme modularity
Frame the API-shaping section with MarkM's "Security as Extreme
Modularity" slide: keeping policy out of a mechanism is modularity,
and in ocap code it's least authority too, since policy is which
references get handed out. The allowlist bullet now points to
acls-dont. The flower bullet gains its distinguishing force: each
step returns a new immutable handle, since a mutable builder passed
along can be widened. The section moves after the test example it had
split from its list, and a sources footer cites the slide.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 21:20:17 -06:00
dckcandClaude Opus 5.5 f720e3d341 acls-dont: allowlists as an anti-pattern, in pattern form
Don't check who's asking; hand each party a capability narrowed to
what it may do. Forces include why the allowlist tempts (simple,
every framework's default) and why it fails (the component holds
everyone's authority and chooses whose to use: a confused deputy).
After Tyler Close's "ACLs don't" and Norm Hardy's "The Confused
Deputy".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 21:20:17 -06:00
dckcandClaude Opus 5.5 427a8f4642 README: write a skill's body for the agent; sources in a footer
An agent reads a skill's text, not the pages it links to, and acts on
rules, examples, and reasons. A well-known term is a key into what it
already knows; a bare URL gives it nothing mid-task, and history
changes nothing it does. Links still serve people and back claims
when challenged, so they move to a footer; history moves to commits.

TODOs: revise every skill on these lines, and for flow, since edits
tend to be local.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 21:13:32 -06:00
dckcandClaude Opus 5.5 5e468ef525 pola: shaping an API: attenuate rather than allowlist, flower-shaped handles, mechanism vs policy
From designing a toybox Discord bot (dckc/vattr97#57): access by narrowed
capability, not a checked allowlist; the service hands out and narrows
access while its creator composes policy (a $1-per-user seller); narrow
then fire; narrowings follow the protocol (host patterns for resume URLs);
patterns as data rather than predicates; refs to secrets, redeemable only
where they belong; one timer primitive with schedules as a library.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 20:56:06 -06:00
7 changed files with 274 additions and 5 deletions

No files matched your search

+22 -4
View File
@@ -16,6 +16,10 @@ Code](https://code.claude.com/docs/en/skills) and
- [pola](pola/SKILL.md) — organize all code, tests included, by - [pola](pola/SKILL.md) — organize all code, tests included, by
the flow of authority: each part gets only what its task needs. the flow of authority: each part gets only what its task needs.
- [facet](facet/SKILL.md) — hand other code a fresh, frozen object; what its functions return crosses the boundary too.
- [capability-based-design](capability-based-design/SKILL.md) — one object per authority distinction; narrowing only intersects.
- [caretaker](caretaker/SKILL.md) — revocable access as a forwarder plus a separate revoker.
- [acls-dont](acls-dont/SKILL.md) — don't check who's asking; hand out narrowed capabilities. An anti-pattern, in pattern form.
- [no-ambient-authority](no-ambient-authority/SKILL.md) — clocks, - [no-ambient-authority](no-ambient-authority/SKILL.md) — clocks,
RNGs, `fetch`, and the filesystem come in as parameters. RNGs, `fetch`, and the filesystem come in as parameters.
- [io-between-turns](io-between-turns/SKILL.md) — sync I/O is a pointy - [io-between-turns](io-between-turns/SKILL.md) — sync I/O is a pointy
@@ -24,6 +28,9 @@ 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.
- [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.
@@ -75,7 +82,18 @@ Code](https://code.claude.com/docs/en/skills) and
## adding one ## adding one
Name the directory for the trigger, not the topic. Write the Name the directory for the trigger, not the topic. Write the `description` for the matcher: what I'd say, what I'd be doing, and what it's *not* for.
`description` for the matcher: what I'd say, what I'd be doing, and
what it's *not* for. Cite the source; quote the key line; explain the Write the body for an agent in the middle of a task. It reads the skill's text, not the pages the skill links to, and it acts on rules, examples, and reasons:
rest.
- **Body:** the rule, an example, and a line of why; the why carries the rule to cases it doesn't spell out. Use terms of art by name ("confused deputy", "POLA"): a known name is a key into what the agent already knows. Quote a source only where its words *are* the rule.
- **Sources:** a footer with one line per source: title, link, and a clause saying what's there. It's for people, and for backing a claim when it's challenged ([citation-needed](citation-needed/SKILL.md)).
- **History**, such as who said what, when, or how the rule came about, goes in 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.
TODO: revise every skill with this in mind.
TODO: revise every skill for flow. Edits tend to be local: a new point gets added where it was needed, without asking how it changes the whole. Read each skill end to end, and rework it so it reads as one document.
+54
View File
@@ -0,0 +1,54 @@
---
name: acls-dont
description: >-
ACLs don't: allowlists and access lists are an anti-pattern; hand out a narrowed capability instead of checking who's asking. Use when about to write or review an allowlist, whitelist, ACL, permission table, role check, `isAllowed(user)`, `allowed.includes(sender)`, or an `access.json`; when deciding who may use a bot, service, endpoint, device, or store; when someone says "allowlist", "ACL", "ACLs don't", or "confused deputy". Not for choosing which narrowing to hand out, or how to shape the API that narrows (that's pola).
---
# ACLs don't
```js
// anti-pattern: the bot hears everyone, then checks a list
E(gateway).subscribe(msg => {
if (allowed.includes(msg.author.id)) respond(msg);
});
// therefore: whoever holds "hear everyone" narrows it, and the bot gets only that
const fromDan = M.splitRecord({ author: M.splitRecord({ id: danId }) });
const bot = makeBot({ messages: E(all).narrow(fromDan) });
```
## Context
A component can do things for several parties, and not every party should get all of it: a bot in a shared channel, an HTTP endpoint, a device, a store.
## Problem
**How does the component keep each party to what it may do?**
## Forces
- An allowlist looks simple and auditable: one list, one check.
- Frameworks offer one by default, so it's the first thing to hand. The Discord plugin keeps one in `access.json`.
- To check the list, the component must hold the authority for every party and choose, on each request, whose to use. That is the setup for a **confused deputy**: it uses one party's authority on behalf of another. The check asks "who is asking?" when the question that matters is "with what authority?", and once a request has passed through a third party, the answer is gone.
- The list puts policy inside the mechanism. Changing who may do what means editing the component's state or config, and a party can't pass a slice of its access on to someone else without asking whoever keeps the list.
- Some identity has to come in from outside: a Discord user id, a login.
## Therefore
**Don't check who's asking. Hand each party a capability narrowed to what it may do, and let the component serve whoever holds one.**
- The component offers its wide capability, and ways to narrow it: `narrow(pattern)`, `pathjoin`, `withinHost` (see [pola](../pola/SKILL.md)).
- The party that creates it narrows and hands out. "Who may do X" is now "who was handed X".
- An outside identity becomes a capability once, at the edge, by a narrowing done by the party that holds the wide capability: `all.narrow(from(userId))`. Components inside never see the list.
- To take access back, hand out a revocable forwarder (a caretaker) and revoke it, rather than deleting a list entry.
## Resulting context
There's no check to forget or get wrong, and a party can't use authority it wasn't handed. "Who can do X?" is answered by who holds a reference to X, which a [wiring-diagram](../wiring-diagram/SKILL.md) shows. A holder can share its access, or a narrower slice of it, without asking anyone.
Revocation has to be designed in, as caretakers, rather than coming free with a list. Auditing means tracing references, not reading one table.
## Sources
- [ACLs don't](https://papers.agoric.com/papers/acls-dont/full-text/): Tyler Close, HP Labs, 2009 (HPL-2009-20). The ACL model can't make correct access decisions for interactions among more than two principals, because the information they need isn't kept across message sends; CSRF and clickjacking are instances of this.
- [The Confused Deputy](http://cap-lore.com/CapTheory/ConfusedDeputy.html): Norm Hardy, 1988. A compiler with authority to write its billing file is tricked into overwriting it by a user who names that file as the output.
+41
View File
@@ -0,0 +1,41 @@
---
name: capability-based-design
description: >-
Capability-based design (Tribble): every distinction in authority is a different object, and narrowing never widens. Use when designing an API, SDK, service, device, or object model that others will hold pieces of; when writing attenuation or builder methods (readOnly, subdir, narrow, restrict, scoped, forUser); when splitting read from write, or use from administration; when a scoped handle checks paths, URLs, or names. Not for what one callback receives (that's facet).
---
# Capability-based design
Give each distinct authority its own object; holding the object is the permission.
1. **One object per authority distinction.** Reading and writing are different objects; so are using a resource and administering it.
```js
// bad: one object, a mode flag, and a check
file.write(data, { as: user });
// good
const { reader, writer } = openFile(path);
```
2. **Narrowing returns a new object and only intersects.** A narrowed handle's narrowing methods can't escape its own limits: "widening is a security hole".
```js
// bad: the second call replaces the first
onlyTypes: types => make({ ...opts, types }),
// good: keep every constraint; all must hold
onlyTypes: types => make({ ...opts, filters: [...opts.filters, t => types.includes(t)] }),
```
3. **Keep limits and secrets in closures,** never on properties the holder can read or overwrite (`this.root`, `this.token`). Freeze every object you return.
4. **Check the parsed form,** the one the far side will act on, not string prefixes of the raw input.
```js
// bad: 'docs/../../etc/passwd' starts with 'docs/'
if (!rel.startsWith(dir)) throw Error('outside');
// good
const abs = path.resolve(root, rel);
if (!abs.startsWith(root + path.sep)) throw Error('outside');
```
5. **Separate access control from use.** The code that decides who gets which handle is not the code that uses it; the handle's methods take no identity.
6. **Identify the authoritative source.** A file's name belongs to the directory, not the file; give each fact to the object that owns it.
Before finishing, write a test that plays the holder of the narrowest handle: call every method with hostile arguments and narrow it again, and check that nothing reaches outside its limits.
## Sources
- Dean Tribble, *Capability-based Design: Applying Security Techniques to Object-Oriented Design* (slides, Agoric): "All distinctions in authority are represented by different objects"; "'Widening' is a security hole"; "Capability-based design also drives clear abstraction boundaries".
+27
View File
@@ -0,0 +1,27 @@
---
name: caretaker
description: >-
Caretaker: revocable access as a forwarder plus a separate revoker. Use when access must end later: when a contract, session, share, conversation, or trial ends; when someone asks for "revoke", "expire", "cancel access", or "undo sharing".
---
# Caretaker: revoke by cutting the forwarder
**Bad:** a flag on the object you hand out; the holder can read and flip it.
```js
const share = { file, revoked: false, read() { if (!this.revoked) return this.file.read(); } };
```
**Good:** the holder gets the forwarder; only the owner gets the revoker.
```js
const makeCaretaker = target => {
let t = target;
const forwarder = Object.freeze({ read: () => { if (!t) throw Error('revoked'); return t.read(); } });
const revoker = Object.freeze({ revoke: () => { t = null; } });
return { forwarder, revoker };
};
```
Rules: the forwarder exposes no way to reach the target, the revoker, or the revoked state; every method checks; revocation can't be undone by the holder.
## Sources
- [E in a Walnut: Capability Patterns](https://www.skyhunter.com/marcs/ewalnut.html#SEC45): the caretaker as revocable forwarder.
+37
View File
@@ -0,0 +1,37 @@
---
name: facet
description: >-
Facet: hand other code a fresh, frozen object with just the functions it needs, never your SDK objects. Use when passing an argument to, or returning a value from, code you don't control: a vendor SDK's callback, an AI model's tools, a plugin, a webhook handler, a contractor's or user's script. Not for choosing which methods a service offers (that's capability-based-design).
---
# Facet: a new, narrow object for each party
Whatever you hand to another party, plus everything reachable from it (properties, prototype, and the return value of every function), is what they get. Build that object on purpose.
**Bad:** hand over the SDK object. An email SDK's Email reaches `.mailbox.account.password`.
```js
summarize({ email });
```
**Good:** a frozen object of closures and plain data.
```js
const { freeze } = Object;
summarize(freeze({
subject: email.subject,
thread: async () => (await email.thread()).map(e => freeze({ from: e.from.address, body: e.body })),
reply: async text => { await email.reply(String(text)); },
}));
```
Rules:
1. **Return data, not what the underlying call returned.** `text => email.reply(text)` hands out the Email that `reply` returns. Chaining APIs (`db.set()` returning the db, any method returning `this`) leak the same way.
2. **Copy records** into frozen plain objects; SDK records carry back-references.
3. **Keep authority in closures,** not properties: a `this.client` or `this.headers` field is readable and writable by the holder. Freeze what you hand out.
4. **Bind scope when you make the facet.** Don't take a folder name, path, or user from the holder and act on it with your own authority.
Before finishing, walk everything reachable from each facet and add a test that does it: no client, token, raw store, or other party's data.
## Sources
- [E in a Walnut: Capability Patterns](https://www.skyhunter.com/marcs/ewalnut.html#SEC45): facets.
- [awesome-ocap wiki](https://github.com/dckc/awesome-ocap/wiki): a pattern language for ocaps.
+28 -1
View File
@@ -1,7 +1,7 @@
--- ---
name: pola name: pola
description: >- description: >-
Principle of Least Authority as the way to organize all code: trace the flow of authority, give each component only what its task needs, design APIs around attenuation. Use when writing or reviewing any code, tests included: makers and their parameters, module imports and exports, which objects share a scope, what a facet exposes; when someone says "POLA", "least authority", "who can reach that?", "Bob shouldn't see Alice's purse", or "makeFoo-style actors". The table stakes (no clocks, fetch, or env reached for inside logic) are no-ambient-authority; this is the organizing principle on top. Principle of Least Authority as the way to organize all code: trace the flow of authority, give each component only what its task needs, design APIs around attenuation. Everything reachable from what you hand out is handed out too, including what its functions return: wrappers return plain data, never the SDK's objects. Use when writing or reviewing any code, tests included: makers and their parameters, module imports and exports, which objects share a scope, what a facet exposes; when designing a service's API (attenuation methods, flower-shaped narrow-then-fire handles, mechanism vs policy, secrets in payloads); when tempted to write an allowlist; when someone says "POLA", "least authority", "who can reach that?", "Bob shouldn't see Alice's purse", or "makeFoo-style actors". The table stakes (no clocks, fetch, or env reached for inside logic) are no-ambient-authority; this is the organizing principle on top.
--- ---
# POLA: organize code by the flow of authority # POLA: organize code by the flow of authority
@@ -25,6 +25,7 @@ So at each level, code has two roles:
- **Makers take only what their task needs.** `makeAlice({ usdcPurse, stockDepositFacet })`, not `makeAlice({ ledger })`. - **Makers take only what their task needs.** `makeAlice({ usdcPurse, stockDepositFacet })`, not `makeAlice({ ledger })`.
- **Attenuate at API boundaries.** Hand out the narrowest facet that works: a deposit facet rather than the purse; a seat rather than the escrow's admin; a read-only view rather than the DB. When designing an API, decide which facets it has and who should get each. - **Attenuate at API boundaries.** Hand out the narrowest facet that works: a deposit facet rather than the purse; a seat rather than the escrow's admin; a read-only view rather than the DB. When designing an API, decide which facets it has and who should get each.
- **What you hand out includes everything reachable from it: properties, prototypes, and what its functions return.** A wrapper like `text => email.reply(text)` hands out whatever `reply` returns, often an SDK object that leads back to the client and its token. Return plain data or nothing, and copy SDK records into frozen plain objects.
- **Separate parties get separate scopes.** If two parties' authority shares a scope, a bug or a careless line lets one act as the other. A scope holding both Alice's and Bob's purses is a design error. - **Separate parties get separate scopes.** If two parties' authority shares a scope, a bug or a careless line lets one act as the other. A scope holding both Alice's and Bob's purses is a design error.
- **Tests too.** Tests are where the code's intended authority flow is first written down. Write each party as a `makeFoo`-style actor holding its own authority privately; the test's top level is the wiring layer that creates the parties and introduces them ([sequence-diagram-actor-sim](https://github.com/Agoric/agoric-sdk/blob/master/.agents/skills/sequence-diagram-actor-sim/SKILL.md)). - **Tests too.** Tests are where the code's intended authority flow is first written down. Write each party as a `makeFoo`-style actor holding its own authority privately; the test's top level is the wiring layer that creates the parties and introduces them ([sequence-diagram-actor-sim](https://github.com/Agoric/agoric-sdk/blob/master/.agents/skills/sequence-diagram-actor-sim/SKILL.md)).
- **The test takes the spontaneous step; actors carry out the consequences.** Give an actor what it knows at construction and let it decide how to act: `alice.run()`, or `alice.tradeWith(bob)` to introduce a counterparty. Don't drive it with arguments that decide for it, like `alice.pay(to, amount)`: that is the test acting with Alice's authority, as if it held her purse. What an actor hands others (a deposit facet, a shop) carries no authority to spend for it. - **The test takes the spontaneous step; actors carry out the consequences.** Give an actor what it knows at construction and let it decide how to act: `alice.run()`, or `alice.tradeWith(bob)` to introduce a counterparty. Don't drive it with arguments that decide for it, like `alice.pay(to, amount)`: that is the test acting with Alice's authority, as if it held her purse. What an actor hands others (a deposit facet, a shop) carries no authority to spend for it.
@@ -49,6 +50,26 @@ const makeAlice = async ({ usdcIssuer, stockIssuer, dollars }) => {
await alice.tradeWith(bob); // the one spontaneous step await alice.tradeWith(bob); // the one spontaneous step
``` ```
## Shaping an API: hand out authority, then narrow it
Security is extreme modularity. MarkM's slide puts it as two parallel principles:
> Modularity: Avoid needless dependencies
> Security: Avoid needless vulnerabilities
> Vulnerability is a form of dependency
> Mod: Principle of info hiding - need to know.
> Sec: Principle of least authority - need to do.
So the moves that make a module well-factored also make it hold less authority:
- **A service is mechanism; its creator sets policy.** Keeping policy out of a mechanism is modularity. In ocap code it is least authority too, because policy is which references get handed out. A service that only hands out and narrows access needs no authority to decide who gets what, so it holds none. Its creator decides by what it hands out, and new kinds of authority come out of that composition: a governor that fences a mower by pushes, or a seller that sells "talk to user X" at $1 and refuses after N sales. Neither the mower nor the Discord vat knows about fences or prices.
- **Don't check who's asking; hand out narrowed capabilities.** An allowlist inside the service is policy inside the mechanism ([acls-dont](../acls-dont/SKILL.md)).
- **Make it flower-shaped: narrow, then fire.** A handle to something wide offers narrowings that each return a narrower handle, and the act comes last: `socket.pathjoin(p).withHeaders(h).connect(listener)`, not `connect(url, headers, listener)`. One wide call needs its caller to hold every argument's authority at once; a chain lets each holder narrow it and pass it on. Each step returns a new, immutable handle that can only be narrower: patterns intersect, and a header that contradicts an earlier grant throws. A mutable builder that gets passed along lets whoever holds it widen what you handed out. The raw device can keep the wide call, and a vat over it hands out the flower, as WebApp does over the fetch device.
- **Narrow along the lines the protocol needs.** Check where the authority actually has to go. Discord sends a resuming client to another host, which a handle narrowed by path can't reach. A narrowing by host pattern (`withinHost('*.discord.gg')`) covers exactly that, so there's no need to widen the handle back to "anywhere".
- **A narrowing is data, not a callback.** Pass a pattern (an Endo `M` pattern; it's passable, so it can cross vats) for the service to apply. A predicate object called on every item sees everything it filters, so it already holds the authority it was meant to narrow.
- **Hand out a reference to a secret, not the secret.** When the secret has to go inside a payload, such as a token in a WebSocket frame, a splicer holds the secret and gives out a ref exo it alone can redeem. Accept the ref only in the fields that carry it to its proper recipient. If a field Discord broadcasts would also accept it, anyone with the ref can publish the secret.
- **One primitive, with libraries on top.** A timer device offers `wakeAt(t, handler)`; repeaters and cron schedules are a library over it, and each schedule is its own object whose holder can cancel only that one. Reading something is authority too: `wake(now)` reveals the clock, so a vat that may wait but not read the time gets a delay-only facet.
## Review checklist ## Review checklist
Before committing, for each new maker, scope, and export: Before committing, for each new maker, scope, and export:
@@ -57,3 +78,9 @@ Before committing, for each new maker, scope, and export:
2. Does any non-wiring scope hold two parties' authority, or more than its task needs? 2. Does any non-wiring scope hold two parties' authority, or more than its task needs?
3. Could a narrower facet replace what's passed? Does any facet let a caller spend for its owner, or does the test decide what an actor does? 3. Could a narrower facet replace what's passed? Does any facet let a caller spend for its owner, or does the test decide what an actor does?
4. Name the wiring layer at this level. Is it small? 4. Name the wiring layer at this level. Is it small?
5. Does any component check an allowlist, or take a policy decision that its creator could make by narrowing what it hands out?
6. Walk everything reachable from each object you hand out, including the return value of each of its functions. Does it reach an SDK client, a token, or another party's data?
## Sources
- [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".
+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".