Compare commits

...
30 Commits
Author SHA1 Message Date
dckc a83a5e62db obsidian-markdown: heading links use the heading text, not GitHub's slug
Generated-by: Claude Opus 5.5
2026-11-27 00:38:40 -06:00
dckc 391d9383d1 makefile-style: make for named checkpoints, from the madmode-blog page
From pages/2026/makefile-style.md in madmode-blog, plus the CONFIRM=
guard on destructive targets ("no yolo! makefiles plz", the iPad
restore, 2026-11-25) and the Nix result mtime trap (coffeebox,
2026-11-26).

Generated-by: Claude Opus 5.5
2026-11-26 10:48:53 -06:00
dckc a633aa44da journalism-101: lead with the news; don't write about the document
Dan, 2026-11-26, on a tv-remote intro that began "This page works
toward...": no newspaper story starts with "This newspaper story...".
Avoid "this document..." in general. Don't bury the lede, too.

Generated-by: Claude Opus 5.5
2026-11-26 09:13:07 -06:00
dckc e16e856eca fix(discord-agent-workspace): confine the bot with bwrap in a user unit, not ProtectHome=
Where the user manager can't mount (Ubuntu's
kernel.apparmor_restrict_unprivileged_userns=1), ProtectHome= and
friends are dropped without an error and the service runs unconfined.
Ship a generic unit, as cloros1 runs: tmux for /login, bwrap for the
confinement.

Generated-by: Claude Opus 5.5
2026-11-23 15:41:30 -06:00
dckc cf83169064 hypertext-links: link it into context
A page nothing links to is a bug. Link first, page second, as on a
wiki or the NeXT WorldWideWeb browser (citations TODO). Per TimBL's
"Linking to context" in the W3C hypertext style guide.

Generated-by: Claude Opus 5.5
2026-11-21 22:39:14 -06:00
dckc 53dd9b3b2d watchme: caveat on the recorded shell's cwd vanishing
A merge that empties a directory recreates it; a shell cd'd there is
left in the deleted one until cd "$PWD".

Generated-by: Claude Opus 5.5
2026-11-20 14:23:31 -06:00
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
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
dckcandClaude Opus 5.5 abde27c130 wiring-diagram: multiplicity, facets, proxies, step-throughs
From drawing E's sugarMint sturdyrefs and reviewing cookie-rotation-wiring:
one pane per maker call and stack only what a scope makes many of;
facets point at shared state; cross-vat references go through a proxy
in the holder's vat; read fields before calling something data; a
step-through format; no PNG deliverables until the diagram is
confirmed. The template's marker id is now "arrow": "head" collided
with an <h2 id="head"> and arrowheads vanished.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-31 13:21:06 -05:00
dckc e887996105 WIP: citation-needed/SKILL.md 2026-10-31 13:04:09 -05:00
dckc 4221f2d176 citation-needed: writing for publication
Public sources only, dated references, outline References, the
CSL-JSON sidecar, bib: front matter for published posts, and the
Zotero import (which publishes). Moved here from agent memory.

Generated-by: Claude Opus 5.5
2026-10-30 16:08:56 -05:00
dckc fd47da3a98 no-ambient-authority: calibrate POLA for small Python scripts
Python can't enforce a capability boundary, so attenuation that lives
mostly in names is par for the course in a script; robustness against
adversaries means leaving Python.

Generated-by: Claude Opus 5.5
2026-10-30 16:08:56 -05:00
dckcandClaude Opus 5.5 65761a1da5 hypertext-links: applies to Discord messages too
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-14 20:19:27 -05:00
dckcandClaude Opus 5.5 b1cdb74e75 no-ambient-authority: point Python work at the DisciplinedPython guide and checker
Trigger on any Python script work, and link the awesome-ocap style guide,
attenuation notes, and disciplined_python_check.py, so conventions such as
logging.info for status come from the guide rather than being invented.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-13 16:38:26 -05:00
dckc d25d46557e pola: the test takes the spontaneous step; actors decide the rest
Replaces the self/puppet split: `alice.tradeWith(bob)` rather than
`alice.pay(to, amount)`, per the actor-sim skill.

Generated-by: Claude Opus 5.5
2026-10-12 17:01:00 -05:00
dckc 8cf472636d pola: split a party's self facet from its puppet facet
From a review of vattr97 #33: a public `pay` method is as good as
handing out the purse.

Generated-by: Claude Opus 5.5
2026-10-12 16:54:34 -05:00
dckc b64b80efd5 pola: organize all code by the flow of authority
From Mark Miller's SOSP panel statement and Navigating the Attack
Surface talk, after a review found two parties' purses in one test
scope.

Generated-by: Claude Opus 5.5
2026-10-12 16:22:32 -05:00
23 changed files with 892 additions and 81 deletions

No files matched your search

+37 -4
View File
@@ -14,14 +14,27 @@ Code](https://code.claude.com/docs/en/skills) and
## writing code
- [pola](pola/SKILL.md) — organize all code, tests included, by
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,
RNGs, `fetch`, and the filesystem come in as parameters.
- [io-between-turns](io-between-turns/SKILL.md) — sync I/O is a pointy
instrument.
- [silent-failures-are-evil](silent-failures-are-evil/SKILL.md) — every
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?
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
you to TADA; CONTRIBUTING has the rest; AGENTS.md links to it.
Exported API docs over file docs. Avoid chit-chat.
@@ -39,12 +52,18 @@ Code](https://code.claude.com/docs/en/skills) and
- [grice-maxims](grice-maxims/SKILL.md) — say what's needed and no
more, only what you can back up, in an order easy to follow.
- [journalism-101](journalism-101/SKILL.md) — lead with the news;
don't bury the lede, and don't write about the document ("This
page...").
- [hypertext-links](hypertext-links/SKILL.md) — link text says where
the link goes; no bare URLs, no "click here".
- [citation-needed](citation-needed/SKILL.md) — back a challenged claim
with live links, quoted and dated.
- [hackmd-deck](hackmd-deck/SKILL.md) — a light talk as a flashback:
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:
issues, positions, and arguments.
- [wiring-diagram](wiring-diagram/SKILL.md) — who holds what, drawn
@@ -59,6 +78,9 @@ Code](https://code.claude.com/docs/en/skills) and
## at the terminal
- [makefile-style](makefile-style/SKILL.md) — make for named
checkpoints: short targets, logic in scripts, `make help` from `##`
comments, file targets, `CONFIRM=` on destructive ones.
- [discord-agent-workspace](discord-agent-workspace/SKILL.md) — set
someone up like this: Claude Code in a workspace folder, messaged
from Discord.
@@ -73,7 +95,18 @@ Code](https://code.claude.com/docs/en/skills) and
## adding one
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. Cite the source; quote the key line; explain the
rest.
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.
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:
- **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. 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 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.
+49 -1
View File
@@ -1,6 +1,6 @@
---
name: citation-needed
description: Provide live, verifiable links when a factual claim is challenged with "citation needed", or when asserting a fact likely to be challenged. Formats citations as blockquote markup with the page title as the link and a date. Not for code references or repo-local docs.
description: Provide live, verifiable links when a factual claim is challenged with "citation needed", or when asserting a fact likely to be challenged; when writing an outline or article that may be published, with a References or sources section, a CSL-JSON sidecar, or a Zotero collection. Formats citations as blockquote markup with the page title as the link and a date. Not for code references or repo-local docs.
---
# Citation Needed
@@ -34,6 +34,54 @@ raw in-your-face URLs.
> — [Source Page Title](https://example.com/path), Site Name, Sep 23, 2026
```
In madmode.com posts, the dash is `--`:
`> -- [Page Title](https://example.com/path), Author or Site, Mon YYYY`.
## Writing for publication
Anything that may be shared publicly cites public sources only: never
unpublished notes, private LLM chats, or local-only links such as
`zotero://select`. A claim that rests on one of those either becomes the
author's own words or gets flagged ⚠️ until a real source turns up.
- **Primary sources first.** Cite the W3C workshop paper, not a post about
it. The author's own blog post on the topic goes in parentheses after
it, as an inline link.
- **Every reference gets a date**, so none pile up undated at the end of
a newest-first list: software by a release from around when it became
well known, web pages "as of" the month you read them, statutes by
enactment.
- **Outlines:** use Markdown footnotes (`[^key]`) collected in one
`## References` section at the end, newest first, with no subheadings
(Obsidian moves footnote definitions to the bottom, leaving
subheadings empty).
- **CSL-JSON sidecar:** keep `<name> - references.json` next to the
outline, in the same order, with `id` equal to the footnote key. It's
the data behind everything else.
- **Published posts:** don't hand-write the sources list. Put
`bib: <name> - references.json` in the post's front matter, and the
madmode site renders it with the xhlt91 bibliography conventions
(`templates/_bib.html`, `tools/csl_bib.py`). Notes starting "TODO" or
"placeholder" stay out of the published list.
- **Zotero:** `tools/zotero_import_csl.py` in madmode-blog imports the
sidecar into a collection named for the post (precedent: fs86,
ai-scrape26). The public library syncs, so importing is publishing.
Follow the library's existing conventions for each item type; RFCs, for
example, are reports with type "Request for Comments" and institution
"Internet Engineering Task Force", so the IETF RFCs saved search
finds them.
- **Links the fetcher can't read** (403, bot wall, JS-only): mark them 🙋
in the draft with the link; the author fetches the page by hand and
saves a Zotero snapshot, which can then be read from `~/Zotero/storage`.
- **Keep a copy of anything you quote, starting with the first fetch.**
Checking exact wording later means fetching again, and fetches fail:
PDFs come back as undecodable bytes, sites return 202 or 403. Save the
fetched file (e.g. under `.tmp/snapshots/`) and queue it for the author
in a 🙋 checklist (`<name> - snapshots.md`) with each source's link and
the words quoted from it. The author, acting as a human HTTP proxy,
attaches it in Zotero or saves a snapshot. Agents can't attach files to
existing Zotero items without a local API key.
## Search hygiene
If you are the one asserting a fact, do a quick search before stating it as
+5 -2
View File
@@ -21,8 +21,11 @@ Generated-by: Claude Opus 5.5
## the rules
- **When:** the content is substantially machine-generated: code,
docs, tests, or a rewrite. Not needed for a typo fix or an edit the
human typed.
docs, tests, or a rewrite. Not needed for a typo fix, an edit the
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
the message, in git trailer format (`git interpret-trailers` can
parse it).
+5 -1
View File
@@ -62,7 +62,11 @@ Whoever can message the bot can make it act with the session's powers: files, sh
## 4. Keeping it running
The session must stay open. Simplest: run it inside `tmux` (`tmux new -s bot`, start Claude, detach with Ctrl-b d; `tmux attach -t bot` to look in). On Linux, a systemd user unit can start it at boot and keep it out of secrets it doesn't need (`ProtectHome=read-only`, `ReadWritePaths=` the workspace and `~/.claude`, `InaccessiblePaths=` `~/.ssh` and other credential dirs).
The session must stay open. Simplest: run it inside `tmux` (`tmux new -s bot`, start Claude, detach with Ctrl-b d; `tmux attach -t bot` to look in). An expired login shows only in that terminal, never on Discord, so that's where `/login` happens.
On Linux, a systemd user unit can start it at boot and confine it: [claude-bot.service](claude-bot.service) runs Claude in tmux under `bwrap`, with everything read-only but the workspace, `~/.claude`, `~/.claude.json` and `~/.cache`, and credential dirs hidden. Hiding `$XDG_RUNTIME_DIR` also hides the systemd and D-Bus sockets, so `systemd-run` can't escape. Add `loginctl enable-linger` so it runs while they're logged out.
Use bwrap, not `ProtectHome=`, `ReadWritePaths=` and friends: where the user manager can't mount (Ubuntu's `kernel.apparmor_restrict_unprivileged_userns=1`), it silently runs the service unconfined. Check the live process: if `readlink /proc/<pid>/ns/mnt` matches the user's shell, it isn't confined.
## 5. First task
@@ -0,0 +1,43 @@
# claude-bot: Claude Code Discord bot, confined to one workspace folder.
# Install: ~/.config/systemd/user/claude-bot.service; systemctl --user enable --now claude-bot
# loginctl enable-linger $USER (so it runs without you logged in)
# Attach: tmux -S /run/user/$UID/claude-bot/tmux.sock attach (detach: C-b d; /login happens here)
[Unit]
Description=Claude Code Discord bot
[Service]
Type=forking
WorkingDirectory=%h/workspace
Environment=PATH=%h/.local/bin:/usr/local/bin:/usr/bin:/bin
Environment=TERM=xterm-256color
RuntimeDirectory=claude-bot
# Optional: GH_TOKEN=<a fine-grained token of the bot's own, for just the repos it needs>
EnvironmentFile=-%h/.config/claude-bot/env
# The user manager has no network-online.target.
ExecStartPre=/bin/sh -c 'until getent hosts gateway.discord.gg >/dev/null; do sleep 2; done'
# bwrap, not ProtectHome= and friends: on Ubuntu (kernel.apparmor_restrict_unprivileged_userns=1)
# the user manager can't mount, and silently runs the service unconfined.
# Everything is read-only except the --bind paths; --tmpfs hides credential dirs.
# Hiding %t removes the systemd and D-Bus sockets (systemd-run would escape) and the ssh/gpg agents.
ExecStart=/usr/bin/tmux -S %t/claude-bot/tmux.sock new-session -d -s claude-bot \
/usr/bin/bwrap --die-with-parent \
--ro-bind / / --dev /dev --proc /proc --tmpfs /tmp --tmpfs %t \
--bind %h/workspace %h/workspace \
--bind %h/.claude %h/.claude \
--bind %h/.claude.json %h/.claude.json \
--bind %h/.cache %h/.cache \
--tmpfs %h/.ssh --tmpfs %h/.gnupg --tmpfs %h/.config/gh \
--ro-bind /dev/null %h/.git-credentials \
claude -n claude-bot --permission-mode auto --channels plugin:discord@claude-plugins-official
ExecStop=-/usr/bin/tmux -S %t/claude-bot/tmux.sock kill-server
# tmux exits 0 when claude exits, so on-failure would never fire.
Restart=always
RestartSec=30
[Install]
WantedBy=default.target
+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.
+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.
+29 -1
View File
@@ -1,6 +1,6 @@
---
name: hypertext-links
description: Writing style for links in markdown docs — use when writing or reviewing any doc with URLs to external pages, repo files, or intra-repo documents; enforces descriptive link text over bare/generic links.
description: Writing style for links in markdown docs and chat (Discord supports `[text](<url>)`) — use when writing or reviewing any doc or Discord message with URLs to external pages, repo files, or intra-repo documents; when adding, moving, or deleting a doc (link it into context: from its parent, and back up); enforces descriptive link text over bare/generic links.
---
# Hypertext Links
@@ -42,3 +42,31 @@ Not `**Label**: [link](...)` — just bullets:
```markdown
- [Akka Core documentation](https://doc.akka.io/libraries/akka-core/current/)
```
## Link it into context
A page nothing links to is a bug: readers and agents won't find it, and it
rots unnoticed. When you add a document, in the same change:
- **Link to it** from its parent, the page whose subject it belongs to
(a goal tree, an index, a README).
- **Link from it** to that context, near the top: one line saying what it's
part of. Readers arrive by search or a pasted link, not from the start.
- **Make it stand alone**: no "as discussed above" or "next we consider";
link the first use of a project name or acronym to its home page.
The natural order is link first, page second. On a wiki, you add a page by
typing its WikiName where it belongs; that makes a link to a page that
doesn't exist yet, which you then follow and fill out (TODO: citation).
Tim Berners-Lee's original WorldWideWeb browser on NeXT worked the same
way: select some text, then make it a link to a new document (TODO:
citation).
Before deleting or moving a page, find what links to it (`git grep` the
file name), and fix those links in the same change. No links in? That was
the bug.
Source: Tim Berners-Lee, [Linking to context](https://www.w3.org/Provider/Style/IntoContext.html),
in W3C's _Style Guide for online hypertext_: "Watch that your text and
vocabulary stands by itself"; imagine "you yourself may wish to reuse the
document."
+30
View File
@@ -0,0 +1,30 @@
---
name: journalism-101
description: >-
Journalism 101: lead with the news, don't bury the lede, and don't write about the document ("This page...", "This doc covers...", "In this section we..."). Use when writing or revising the opening of any doc, page, README, issue, PR description, email, report, or reply; when someone says "bury the lede", "lede", "inverted pyramid", "navel-gazing", or "no newspaper story starts with 'This newspaper story'". Not for link text (that's hypertext-links) or trimming words in general (that's grice-maxims).
---
# Journalism 101
## Lead with the news
The first sentence says the most important thing: what happened, what's needed, what the reader should do. Background, history, and how we got here come after, in order of importance (the inverted pyramid), so a reader who stops early still has the point.
- Buried: "After the office move, two candidates turned up, and each one just has to press a few keys, so ... the iPad works."
- Lede first: "The iPad remote works: it pressed Home on bldbox from the couch. Next: enroll it on Mom's Wi-Fi."
A status, a result, or a decision goes at the top, not at the end of a paragraph of context.
## Don't write about the document
No newspaper story starts with "This newspaper story...". The reader knows what they're reading; say the thing itself.
- Navel-gazing: "This page works toward one remote that Mom and Dad can actually use."
- The thing itself: "Mom and Dad need one remote they can actually use."
The same goes for "This document describes...", "This section covers...", "In this README, we...", and "The purpose of this issue is...". In a heading or a link, too: name the subject, not the container.
## Sources
- [Inverted pyramid (journalism)](https://en.wikipedia.org/wiki/Inverted_pyramid_(journalism)), Wikipedia: most important first, details in descending order.
- [Lead paragraph](https://en.wikipedia.org/wiki/Lead_paragraph), Wikipedia: the lede, and "burying the lede".
+3 -1
View File
@@ -31,7 +31,9 @@ From Dan Connolly's
## paying the debt (test-driven debugging)
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
passes before the fix proves nothing about the fix.
3. Fix the code.
+62
View File
@@ -0,0 +1,62 @@
---
name: makefile-style
description: >-
Makefile style: make for named checkpoints, short targets, scripts for logic, an accurate `make help` from `##` comments, file targets instead of phony ones, and a CONFIRM= guard on destructive targets. Use when writing or reviewing a Makefile or `.mk` file; when about to run a sequence of device or admin commands by hand ("no yolo! makefiles plz"); when a recipe grows loops, conditionals, or traps; when adding a `help` target. Not for build systems other than make.
---
# Makefile style
## make names the checkpoints
Device and admin work (flash a card, restore an iPad, install a service) goes through make targets, not commands typed ad hoc. A target is a named step the operator can read before running, rerun, and cite later: `make flash DEV=/dev/sdd CONFIRM=erase` says what it does and what it touches.
## Short targets; logic goes in a script
A recipe is a few commands. Loops, conditionals, traps, and multi-line `test ... || { ...; }` chains go in a script beside the Makefile, which the target runs. AWK is fine for light text transforms; a non-trivial one gets its own `.awk` file.
Why: make's quoting (`$$`, one shell per line, `\` continuations) makes logic hard to read and easy to break; a script can be run, tested, and read on its own.
## `make help` from `##` comments
Put `## description` on the line before each target the operator runs; a small awk program pairs each `##` comment with the next `target:` line. Keep `help` accurate and current, and make it the first target, so plain `make` shows it.
```makefile
## Show available targets
help:
@awk 'BEGIN {d=""} /^## / {d=substr($$0,4)} \
/^[a-zA-Z0-9_.-]+:/ {if(d) {split($$0,t,":"); \
printf " %-12s %s\n", t[1], d; d=""}}' \
$(MAKEFILE_LIST)
```
Where a repo already has a shared `make-help.awk`, use it.
## Target the real file
Name the file a step produces as its target, so make skips the step when the file is there: no idempotence check, no phony alias. Factor a long path into a variable so its two uses are plainly the same. Prefer architecture-independent paths.
```makefile
AYATANA_PKG = gir1.2-ayatanaappindicator3-0.1
AYATANA_DOC = /usr/share/doc/$(AYATANA_PKG)/copyright
all: $(AYATANA_DOC) $(TARGETS)
systemctl --user daemon-reload
$(AYATANA_DOC):
sudo apt-get install -y $(AYATANA_PKG)
```
Except Nix's `result`: it links into the store, where every mtime is 1970, so as a target it always looks stale, and as a prerequisite it always forces a rebuild. Let a target check `test -e result` instead.
## Paths and installs
- `$(CURDIR)` for the working directory (`make -C dir` sets it); no `$(makeFileDir)` dance. `$(HOME)` for the target's home.
- `ln -sf` for durable installs from the source tree, so updates flow without a copy step.
## Destructive targets need CONFIRM=
A target that erases or overwrites (a disk, a device, a restore) refuses unless the operator says so on the command line, with a word that names the harm: `make restore CONFIRM=erase`. Before writing, it shows what it's about to touch (`lsblk` of the device) and checks it's the kind of thing expected (removable, on USB, a plausible size); that check is a script, per above.
## Sources
- [Makefile conventions](https://github.com/dckc/madmode-blog/blob/master/pages/2026/makefile-style.md), madmode-blog, 2026: checkpoints, short targets, the `help` awk, `$(CURDIR)`, `ln -sf`, file targets.
+70 -1
View File
@@ -1,7 +1,7 @@
---
name: no-ambient-authority
description: >-
Use when writing or reviewing code whose functions touch I/O, clocks, random number generators, process.env, fetch, or filesystem; 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
@@ -42,6 +42,72 @@ capability-based languages, systems, papers, and talks.
authority they need, then *delegate* it downward.
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
For Python, the rules above are spelled out in the DisciplinedPython style
guide in awesome-ocap (local checkout `~/projects/awesome-ocap`). Read it
before writing or refactoring a Python script; don't invent conventions.
- [ocap-py-style-guide.md](https://codeberg.org/dckc/awesome-ocap/src/branch/master/style-guide/ocap-py-style-guide.md):
the script recipe (`main(...)` plus `_script_io()` under the `__main__`
guard, authorities passed by name), standard authority names (`argv`,
`cwd`, `stdout`, `connect`, `run`, `urlopen`, `now`), prompt attenuation
in `main`, and **status goes through `logging.info(...)` directly**: not
`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):
narrowing authority function by function.
- 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
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
and introspection get around any wrapper), so for a small script,
attenuation that lives mostly in names is fine. An example: a read-only
library view whose path object could still POST. GET-only is ideal;
note the gap honestly and move on. Robustness against adversaries
means leaving Python (e.g. for Hardened JavaScript).
## how this shows up in review
- `crypto.getRandomValues()` called inside an exported function →
@@ -55,6 +121,9 @@ capability-based languages, systems, papers, and talks.
helpers become untestable without monkey-patching; inject a
narrower interface (the caller passes the one URL's worth of fetch,
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
powerful object export. Split: pure logic (argument-only) + a thin
program-script-ish edge that wires authority in.
+3
View File
@@ -19,12 +19,15 @@ When you rewrite a wrapped paragraph, unwrap it. Don't unwrap a whole file you a
- Standard markdown links with relative paths: `[the webkeys pattern](docs/webkeys.md)`. Obsidian follows them, and GitHub renders them. `[[wikilinks]]` render only in Obsidian.
- No spaces in file names, so links need no `%20`.
- Links to a heading, as in a TOC: Obsidian matches the fragment against the heading text, not GitHub's slug, so `#the-coffee-table-box` finds nothing. Write the heading text with spaces as `%20`: `[The coffee-table box](#The%20coffee-table%20box)`. Keep colons, `#`, `|`, `^`, and brackets out of headings you link to. GitHub won't follow these links; Obsidian is the reader that counts.
- Link text says where the link goes (see hypertext-links).
## File names and headings
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.
## Frontmatter
+86
View File
@@ -0,0 +1,86 @@
---
name: pola
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. 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
Mark Miller, [SOSP 50th anniversary panel](https://www.youtube.com/watch?v=br9DwtjqmVI) (3 min):
> we design abstraction boundaries so that a component's interface only requires arguments that are somehow relevant to its task. If such argument passing were the only source of authority, we would have taken a huge step towards least authority.
Every reference to anything but immutable data is authority: a purse is the right to spend some assets; a mint, the right to create them; a seat, the right to take part in one deal; a DB handle, every row. Ask of every reference: who holds it, who gave it to them, and does their task need all of it?
## Recursively, at every level
[Navigating the Attack Surface](https://www.youtube.com/watch?v=wW9-KuezPp8) (15 min): the same move repeats at each level of composition (OS accounts, apps, modules, objects), and the benefit multiplies, like a Menger sponge. CapMail's main module "receives all of that authority … wiring them together, subdividing the authority … and handing it out piecemeal … written knowing that the address book does not need access to the PGP keyring, so the main module simply doesn't give it that access."
So at each level, code has two roles:
- **A wiring layer** (entry point, `main`, test setup, a maker) holds a lot of authority, and its job is to split it and hand out pieces. Keep it small and obvious: it is the TCB at its level.
- **Everything else** gets only the pieces its task needs, as arguments, and can't reach more.
## In practice
- **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.
- **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.
- **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.
- **Modules decide what authority enters through imports and leaves through exports.** Export makers, not instances that close over power ([no-ambient-authority](../no-ambient-authority/SKILL.md)).
```ts
// wrong: one scope holds everyone's purses; Bob's code could spend Alice's
const alice = { usdc: await E(usdc.issuer).makeEmptyPurse(), ... };
const bob = { usdc: await E(usdc.issuer).makeEmptyPurse(), ... };
await E(seatB).offer(await E(bob.stock).withdraw(shares(3n)), ...);
// right: each party holds its own; the test wires, drives, and observes
const makeAlice = async ({ usdcIssuer, stockIssuer, dollars }) => {
const usdc = await E(usdcIssuer).makeEmptyPurse(); // Alice's alone
...
return harden({
// Alice decides what to pay; Bob shows only his shop
tradeWith: async bob => E(bob.shop).sell(await E(usdc).withdraw(price), ...),
getBalances,
});
};
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
Before committing, for each new maker, scope, and export:
1. Draw (in your head or as a [wiring-diagram](../wiring-diagram/SKILL.md)) who holds what after this change.
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?
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".
+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.
+5
View File
@@ -80,6 +80,11 @@ it survives independently of the transcript.
through them, or filter before quoting.
- Captures grow fast — tens of thousands of lines for a long session. Read
the tail by default, not the whole file.
- The recorded shell's cwd can vanish under it. A git merge or checkout
that moves every file out of a directory deletes the directory and
recreates it. A shell `cd`'d there is left in the deleted one: the prompt
shows the path, but `ls` is empty. The fix is `cd "$PWD"`. Before
running such a merge in the operator's working tree, warn them.
- These are local working artifacts, not deliverables. Keep them out of
version control unless a session is itself the thing worth preserving.
+65 -68
View File
@@ -1,41 +1,48 @@
---
name: wiring-diagram
description: >-
Capability wiring diagram, "who holds what" — use when asked for a wiring diagram, a picture of who holds what, a capability diagram, or "a diagram like the cookie-rotation one"; when reviewing a design for POLA and wanting to see the reference graph. MarkM ERTP-slide style: actors are balls, makers pale regions, objects rounded squares, state ledger tables, references dot-to-arrowhead; HTML/SVG plus a headless-Chromium PNG. Not for message order over time: that's a sequence diagram (sequence-diagram-actor-sim in agoric-sdk).
Capability wiring diagram: who holds a reference to what, and so who can do what — use when asked for a wiring diagram, a capability diagram, or a picture of who holds what; when reviewing a design for POLA and wanting to see the reference graph; when stepping through how that graph changes across create, checkpoint, crash and revive (an "algorithm animation"). In the style of MarkM's ERTP slides. Sequence diagrams of messages between parties are a separate skill (sequence-diagram-actor-sim).
---
# Capability wiring diagram
One picture that answers, for a design: **who holds a reference to what,
and therefore who can do what.** It complements a sequence diagram,
which shows *when* messages flow. This one shows the standing graph of
authority that makes those messages possible. For sequences, see
`~/projects/ymax-workspace/agoric-sdk/.agents/skills/sequence-diagram-actor-sim/SKILL.md`
(on agoric-sdk branches `connolly/ago-1264-agentic-planning` and
`connolly/ago-1299-agentic-planning-tdd`, not yet on master).
POLA says each party should hold only the authority its job needs. A wiring diagram lets you check that at a glance: one picture of **who holds a reference to what, and therefore who can do what**. The arrows that are absent are the security argument. To show what happens over time, step the diagram through frames, one message each (an algorithm animation, below), draw a sequence diagram (see sequence-diagram-actor-sim), or both.
Exemplars:
- `~/oros-bots/capsite-cookie-rotation/docs/cookie-rotation-wiring.html`
(+ `.png`): the original.
- `~/qtrx/packages/umb-download/docs/wiring.html` (+ `.png`): three
makers, two outside parties, and an adversary holding a webkey.
- `capsite-cookie-rotation/docs/cookie-rotation-wiring.html` (+ `.png`) in this workspace: the original.
- `~/qtrx/packages/umb-download/docs/wiring.html` (+ `.png`): three makers, two outside parties, and an adversary holding a webkey.
- `capsite-toybox-kernel/docs/sugarmint-sturdyrefs.html` in this workspace: a step-through of E's sugarMint making sturdyrefs, crashing, and reviving, with nested panes, facets on shared state, weak tables, and cross-vat proxies.
Start from [`template.html`](template.html), next to this file. It has
the drawing helpers and a small example scene to replace.
Start from [`template.html`](template.html), next to this file: it has the drawing helpers and a small scene to replace. For a step-through, start from the sugarMint page. The deliverable is a local HTML file in the repo's `docs/`, not a claude.ai artifact, unless asked.
## Read the graph from the code, not the story
Every arrow must correspond to something real: a constructor argument, a
stored id, a binding, a held token, or a file someone keeps. Before
drawing, list the references as `holder → target: where in the code`.
Read the factories (`make…`, `newX`, `configure`) and anything that
stores an id: a DO id held as a string *is* a reference. If you can't
cite where a reference comes from, it doesn't get an arrow.
Every arrow must correspond to something real: a constructor argument, a stored id, a binding, a held token, or a file someone keeps. Before drawing, list the references as `holder → target: where in the code`. Read the factories (`make…`, `newX`, `configure`) and anything that stores an id. An id is a reference when its holder can redeem it: a DO id string reaches the object through code that holds the namespace binding, or through a route that redeems ids for anyone (cookie-rotation's `/at/<id>`, which makes the id a bearer capability). Draw the arrow from the id's holder, and say what redeems it. If you can't cite where a reference comes from, it doesn't get an arrow.
Watch for references that are dropped on purpose (e.g. a setup route
that mints an instance, hands its id to one holder and forgets it).
That's often the point of the design. Say so in a caption, or just
leave the arrow out.
Read each object's fields before you say what it is. E's SturdyRef looks like plain data (vatID, swiss number) but also holds a LocatorUnum presence, which is its authority to look the number up. A table keyed by data can't be weak-keyed: say which side is weak (E's swissTable is a WeakValueMap), and draw the weak arrow dashed.
Watch for references dropped on purpose, such as a setup route that mints an instance, hands its id to one holder and forgets it. That's often the point of the design: say so in a caption, or leave the arrow out.
When a caption claims something a reader may doubt, cite the line that shows it, and keep what the code shows apart from what you infer. If the code is lost, say so and draw no arrows into it.
## One pane per maker call
In MarkM's [makeMint slide](https://docs.agoric.com/guides/js-programming/hardened-js.html#from-ocaps-to-electronic-rights-mint-and-purse), each stacked pane is one call to `makeMint`. Inside a pane is what that one call made: one issuer, mint, brand and ledger, and a stack of purses, because `makePurse` runs many times per mint. For each box, ask: *a new one per what call?*
- Stack a box only when its scope makes many. `store.readOnly()` returns the same object every time, so readOnly is 1:1 with its store and not stacked.
- Put state where the code keeps it. If one Durable Object holds many stores in one kv, the kv is one table in the DO's pane, like makeMint's ledger, not one per store.
- Name a pane after the real maker (the class or function in the code), not an invented `makeFoo`.
- Nested scopes nest panes: issuer ⊃ account ⊃ hold.
- Facets that close over shared state go in one pane, each facet a box, with arrows to the shared state table: an ERTP mint, issuer and brand; an account and its revoker. Drawing facets apart is how the picture shows attenuation.
- A stack can be over time: one vat pane per incarnation.
## Between vats
A reference to an object in another vat is a proxy in the holder's vat that forwards over CapTP or Cap'n Web. Draw the holder's vat as a small pane with the proxy in it, and the arrow from the proxy onward. That proxy is where a crash shows up as a broken reference.
## Include an adversary
Add a Mallory who holds whatever is most likely to leak (an instance id, a webkey, a URL), with an arrow to exactly what it reaches. Her caption says what she *can't* reach. Mallory makes the absent arrows visible.
## Vocabulary
@@ -43,71 +50,61 @@ leave the arrow out.
|---|---|---|
| blue ball | `actor(cx, cy, label)` | a person or a program with its own agency |
| grey ball | `actor(cx, cy, label, "url(#ext)")` | outside the system: a browser extension, a third-party service |
| pale region | `maker(x, y, w, h, "makeFoo")` | a maker (factory, DO class) and the instances it made; the stacked inner panes say "there are many" |
| rounded square | `obj(x, y, w, h, label, stacked)` | an object or facet; `stacked` when one is made per instance |
| pale region | `maker(x, y, w, h, "makeFoo")` | a maker (factory, DO class) and the instances it made; stacked panes say "there are many" |
| rounded square | `obj(x, y, w, h, label, stacked)` | an object or facet; `stacked` when its scope makes many |
| ledger table | `table(x, y, title, rows, [colW0, colW1])` | an object's state; rows are key/value; `rowY(i)` and `colX` give arrow anchors |
| dot → arrowhead | `ref(x1, y1, x2, y2, bend)` | holder references target; `bend` (±0.05–0.3) curves around things |
| speech bubble | the `path` + `code` block | the one call the picture is about, in `E(target).method(args)` form |
| caption | `cap(x, y, text, attrs)` | what an actor holds, and what it can't reach |
Facets are separate objects (`store` vs `readOnly`): drawing them apart
is how the picture shows attenuation.
## Include an adversary
Add a Mallory who holds whatever is most likely to leak (an instance
id, a webkey, a URL), with an arrow to exactly what it reaches. The
caption says what she *can't* reach. Absent arrows are the security
argument, and Mallory makes them visible.
## Layout
- Actors in a row along the top (y≈200), makers below (y≈320 onward),
captions along the bottom (y≈ height − 14).
- Put each maker under the actors that mostly use it, so arrows run
short and downward.
- Speech bubble at the top, its tail pointing at the speaker. Move the
bubble's path (`M x,y`) and the tail segment (`h… l-38,48 l6,-48`)
together.
- Captions: two or three short lines, never on top of an arrow or a
ball. Use `"text-anchor": "start"` to set one beside a ball.
- Long arrows that cross a maker: increase `|bend|` until the curve
clears tables and objects. The control point is the midpoint offset
by `bend × (−dy, dx)`.
- Actors in a row along the top (y≈200), makers below (y≈320 onward), captions along the bottom (y≈ height − 14).
- Put each maker under the actors that mostly use it, so arrows run short and downward.
- Speech bubble at the top, its tail pointing at the speaker. Move the bubble's path (`M x,y`) and the tail segment (`h… l-38,48 l6,-48`) together.
- Captions: two or three short lines, never on an arrow or a ball. Use `"text-anchor": "start"` to set one beside a ball.
- Long arrows that cross a maker: increase `|bend|` until the curve clears tables and objects. The control point is the midpoint offset by `bend × (−dy, dx)`. Where one bend can't clear everything, give explicit control points (the sugarMint page's `via` and `via2`).
## Step-through (algorithm animation)
When the story is a sequence of state changes (create, checkpoint, crash, revive), keep one layout and step through frames, like slides:
- Each frame is one message. The bubble shows it, with its tail at the sender; a step inside some object gets a dashed bubble with no tail.
- Orange marks what that message changed: a halo on new objects and tables, a fill on new rows, orange for new references.
- Below the picture: a short heading, a sentence saying what the message did and why, and a cite line (`file:line`).
- Dead things fade (opacity 0.25); broken references are red, dashed, with a ✕.
- Controls: Prev/Next, arrow keys, a slider, and `#sN` deep links.
- In code, name frames (`F.save`, `F.revive`) and derive visibility from them (`on(F.sturdy, F.rebuild)`, `fresh(F.save)`), so inserting a frame doesn't shift every index.
## Accessibility
Keep `<title>` short. Write `<desc>` as prose that names every actor and
maker, every reference, the bubble's call, and what the adversary
can't reach. Someone who can't see the picture should get the same
argument from it.
Keep `<title>` short. Write `<desc>` as prose that names every actor and maker, every reference, the bubble's call, and what the adversary can't reach. Someone who can't see the picture should get the same argument from it. A step-through sets `<desc>` per frame.
## Render and check
The page is self-contained (no network). Render a PNG with headless
Chromium. The viewport comes out shorter than `--window-size`, so render
taller and crop to the SVG size:
Render with headless Chromium. The viewport comes out shorter than `--window-size`, so render taller and crop to the SVG size; `--force-prefers-reduced-motion` keeps highlights from being caught mid-fade:
```sh
chromium --headless=new --disable-gpu --no-sandbox --hide-scrollbars \
chromium --headless=new --disable-gpu --no-sandbox --hide-scrollbars --force-prefers-reduced-motion \
--window-size=W,$((H+100)) --screenshot=full.png "file://$PWD/NAME.html"
python3 -c "from PIL import Image; Image.open('full.png').crop((0,0,W,H)).save('NAME.png')" && rm full.png
```
Then **look at the PNG** (Read it) and fix overlaps: captions on arrows,
arrows through tables, text clipped at the bottom. Expect two or three
rounds. Commit the HTML (source) and the PNG separately, so the source
diff stays readable.
**Look at each screenshot** (Read it) and fix overlaps: captions on arrows, arrows through tables, text clipped at the bottom. Expect two or three rounds. If arrowheads vanish, look for an id collision: SVG marker ids share the page's id namespace, and an `<h2 id="head">` once hijacked `url(#head)`. The template's marker is `arrow`.
QA screenshots in a scratch directory are fine at any point. Don't commit a PNG until the user confirms the diagram is right; a step-through gets none unless asked. Commit the HTML and the PNG separately, so the source diff stays readable.
## Review checklist
- Does every arrow cite something in the code? Is any real reference
missing?
- Does each actor hold only what its job needs (POLA)? If the picture
shows an actor holding more, that's a finding about the design, not a
drawing problem.
- Are facets drawn apart where they differ in authority?
- Does every arrow cite something in the code? Is any real reference missing?
- Does each actor hold only what its job needs? If the picture shows an actor holding more, that's a finding about the design, not a drawing problem.
- For each stacked box: is a new one really made per instance? For each unstacked box: is there really only one?
- Are facets drawn apart where they differ in authority, and pointed at shared state where they share it?
- Do references into another vat go through a proxy in the holder's vat?
- Does the adversary's caption match what the arrows show?
- Does `<desc>` tell the same story in prose?
- Is any secret value drawn? Elide values (`session=…`, `{…}`): the
picture shows *that* a row exists, not its contents.
- Is any secret value drawn? Elide values (`session=…`, `{…}`): the picture shows *that* a row exists, not its contents.
## TODO
Migrate or copy sequence-diagram-actor-sim here. It lives at `~/projects/ymax-workspace/agoric-sdk/.agents/skills/sequence-diagram-actor-sim/SKILL.md`, on agoric-sdk branches `connolly/ago-1264-agentic-planning` and `connolly/ago-1299-agentic-planning-tdd`, not yet on master.
+2 -2
View File
@@ -28,7 +28,7 @@ adversary can and cannot reach.</desc>
<stop offset="0%" stop-color="#6cbcf4"/>
<stop offset="100%" stop-color="#4aa8ec"/>
</linearGradient>
<marker id="head" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="9" markerHeight="9" orient="auto-start-reverse">
<marker id="arrow" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="9" markerHeight="9" orient="auto-start-reverse">
<path d="M0,0 L10,5 L0,10 z" fill="#1d4f7a"/>
</marker>
</defs>
@@ -54,7 +54,7 @@ const dot = (x, y) => el("circle", { cx: x, cy: y, r: 4.5, fill: INK });
const ref = (x1, y1, x2, y2, bend = 0, extra = {}) => {
dot(x1, y1);
const mx = (x1 + x2) / 2 - (y2 - y1) * bend, my = (y1 + y2) / 2 + (x2 - x1) * bend;
el("path", { d: `M${x1},${y1} Q${mx},${my} ${x2},${y2}`, fill: "none", stroke: INK, "stroke-width": 2, "marker-end": "url(#head)", ...extra });
el("path", { d: `M${x1},${y1} Q${mx},${my} ${x2},${y2}`, fill: "none", stroke: INK, "stroke-width": 2, "marker-end": "url(#arrow)", ...extra });
};
// maker box: a pale rounded region, with stacked instances inside