Skip to content

Hand five hand-written mechanisms to the libraries that own them - #753

Merged
max-sixty merged 12 commits into
mainfrom
settled-swaps
Sep 17, 2026
Merged

max-sixty merged 12 commits into
mainfrom
settled-swaps

Conversation

@max-sixty

@max-sixty max-sixty commented Sep 17, 2026 •

Copy link
Copy Markdown
Owner

The five high-confidence rows of TODO.md's platform and dependency cutover, each replacing hand-written code with the library the ecosystem has settled on. Every replaced mechanism is deleted rather than wrapped.

A nonce CSP for the per-body hash pipeline. script_hash computed a source expression over the exact composed bytes of each inline script, which made route scoping a step that had to run before hashing. One nonce per delivery says the same thing: the scripts a delivery composed carry it, and markup a page's own inputs wrote into it does not. SourceDocument now records where each inline script's start tag ends, so the mark goes in at an exact offset rather than through a second pass over the source. Export does the same with a nonce per file. default-src 'self' is unchanged, so what stops injected markup reaching the network is what it was. On the published site the nonce is weaker than the hashes it replaces: write_live_shell mints it once per release, so every reader gets the same one in the page source. No channel reaches that today — source validation forbids scripts and event attributes, and runtime content goes in through DOM APIs — so the comments state where the guarantee holds rather than the code keeping two mechanisms.

psutil for the process readings in host.py. Two platform doors of hand-laid proc_pidinfo and sysctl struct layouts through ctypes, plus /proc parsing, become Process.ppid(), .name(), and .cmdline(). pid_alive stays on os.kill, because psutil.pid_exists counts EPERM as alive and every pid this module records runs as this user.

unidiff for the git-diff parser in data.py. Leaf keeps the manifest, the verbatim per-file section the widget renders, and the refusals unidiff does not make: copy metadata, a hunkless entry that is not the exact four-line path-only rename, C-escape validation, and a bare empty line, which unidiff reads as an empty context line and lf-diff refuses. Checked by running the old and new parsers side by side over 150 commits as both git show and git format-patch output: 152 identical manifests, 0 cases where one accepted and the other refused. Two edges the hand-written parser handled and unidiff does not, both accepted as rare: a path with a segment ending in b (real git output, refused at capture), and a bare \r or \ <text> hunk line (git never emits them; only a patch damaged in transit carries one).

watchfiles for the watcher in scripts/preview.py. The stat snapshots and the re-expansion cache are gone; watch_paths now returns the roots to subscribe to and what each reported path means. Dev group only, so an install never fetches it. Every path is resolved before it enters a set or the subscription, since a watcher can report changes under the root string it was given and a package reached through a symlink or .. would otherwise never match; and each package file's directory joins the subscription, since the layer reading follows a link inside a package to wherever it resolves. This one found a bug: watching every holding directory meant the page's first media/ file added a root, tearing the subscription down mid-refresh and losing the edit made right after it.

dependency-cruiser for the import graph in eslint.config.mjs. The acorn graph walk, Tarjan SCC, and BFS paths go; cycles, the transitive closures, and the direct-edge bans are declarations in .dependency-cruiser.mjs. eslint keeps the rules a module's own source answers. The new graph was diffed edge for edge against the old one — 153 modules, 723 dependencies, zero difference — and each of the five fault classes was planted and confirmed red. no-boot-entry was dropped because no-restricted-imports already refuses that import and more broadly. Resolution runs with no default extensions, as browser ESM does, so an extensionless import the browser would 404 fails the gate instead of resolving.

Lines

The generated lockfile grows by 160 for three packages. Source and config are net −107, and −95 of that is the eslint swap alone: psutil −56, unidiff −6, watchfiles −3, and the nonce CSP +27. The survey's Saving column measured the size of each region rather than what the library takes over, so three of the four Python rows were scored well above their actual deletion. The value in psutil is the kind of code removed, not the count; the value in the CSP row is the ordering constraint and the per-delivery SHA-256, and it was never a line-count win.

Checks

Everyday suite 1,134 passed. Complete suite 2,690 passed, 5 failed. One was mine and is fixed: test_site.py compares the edge shell byte for byte with what the Leaf server serves, and the nonce is minted per delivery like the server id that test already normalised. Each document is now rewritten with the nonce its own scripts carry, so a policy naming some other one still parts the two; a planted served-only divergence confirms the comparison still catches one. test_site.py 45 passed after it.

The other four fail identically on a clean checkout of the merge base, established by running each alone in a detached worktree at that SHA: test_render_controls.py::test_a_stale_package_widget_uses_recursive_parent_eligibility, test_render_margin.py::test_the_margin_groups_meanings_at_one_destination_without_moving_the_page, test_render_pages.py::test_the_room_is_measured_after_a_late_rail, and test_render_startup.py::test_a_current_auxiliary_choice_replaces_a_persisted_tray_during_replay.

This was written by Claude Code on behalf of max-sixty

🤖 Generated with Claude Code

max-sixty and others added 10 commits September 16, 2026 21:25
`eslint.config.mjs` built its own module graph — an fs walk that parsed
every runtime file with acorn, a BFS for shortest paths, and Tarjan
strongly-connected components — and the `runtime-graph` rule read all
three. dependency-cruiser expresses every rule that graph carried, so
the builder, both analyses, and the rule are gone, 272 lines out of the
eslint config, which keeps the rules a module's own source answers.

`.dependency-cruiser.mjs` holds what moved: the two closure tables, the
application owners, and a rule each for the boot entry, the application
composition root, `keyboard/page.js`, cycles, and unresolvable modules.
An exact closure becomes `to: {reachable: true, pathNot: <allowed>}`
and a forbidden one `to: {reachable: true, path: <forbidden>}`. The
graph is the runtime directory plus `leaf.js`; vendored bundles are
excluded, including the two named by a site-absolute `/vendor/`
specifier, which resolves in the browser and not on disk.

Both graphs were built over the same tree and diffed: 153 modules and
723 edges each, with no edge in one and not the other. Each violation
class was then planted one at a time — a cycle, an exact-closure
breach, a forbidden-closure breach, an import of `../leaf.js`, an
import of `keyboard/page.js` — and each goes red naming the route.

dependency-cruiser is not an eslint plugin, so it takes a pre-commit
hook of its own, pinned there as the other lint tools are. The one
guarantee the tool does not cover is a declaration naming a module that
no longer exists, which matches nothing and passes silently; the config
checks its own names against the directory before building the rules.

Co-Authored-By: Claude Opus 5 <[email protected]>
Delivery hashed the runtime bootstrap and every authored module block into
script-src, which made route scoping a step that had to run before hashing and
grew a source expression per block. One nonce per delivery says the same thing:
the scripts a delivery composed carry it, and markup a page's own inputs wrote
into it does not. The parser now records where each inline script's start tag
ends, so the mark goes in at an exact offset rather than through a second pass
over the source.

Export does the same with a nonce per file.

Co-Authored-By: Claude Opus 5 <[email protected]>
`no-boot-entry` restated what `no-restricted-imports` already refuses, and more
narrowly: the eslint pattern covers the public facade and the dynamic form too.
With it gone the graph no longer needs `leaf.js` as a node, so the exclusion is
the runtime directory against everything else.

The `ignores` list sat beside `linterOptions`, which makes it a config's own
ignore rather than a global one, so a bare `npx eslint .` linted the vendored
bundles it names. It stands alone now, with `.venv` added for the same reason.

Co-Authored-By: Claude Opus 5 <[email protected]>
Two rows of the dependency survey's Python table: `host.py` carried two
hand-laid platform doors for each of `process_info` and `process_argv`
(macOS `proc_pidinfo` and `sysctl` KERN_PROCARGS2 through
`ctypes.Structure`, `/proc/<pid>/stat` and `/proc/<pid>/cmdline` on
Linux), and `data.py` hand-parsed a Git unified patch's hunk headers,
line counts, and header paths. psutil and unidiff own both readings now.
`ctypes` leaves `host.py`, and the process readings drop from 74 code
lines to 22.

`pid_alive` stays on `os.kill(pid, 0)`. It counts EPERM as dead, because
every pid it reads runs as this user and after a reboot the low pids are
root's; `psutil.pid_exists` takes EPERM as proof a process is there, so
it is the opposite reading rather than the same one.

psutil's POSIX `Process.name()` completes a name the kernel truncated to
15 or 16 characters from the command line's program path, which the
struct read did not. Nothing compares against a truncated name:
`session_lifetime` matches `codex`, and `ancestry`'s other reader joins
the walked names into a refusal message.

## What unidiff took, and what capture kept

unidiff reads the hunks. Leaf keeps the manifest around them — the entry
shape, the paths a page author sees, the verbatim per-file section that
`lf-diff` renders, and the refusals that keep a capture to evidence the
widget can draw. Those refusals do not all move, because unidiff accepts
what `lf-diff` will not:

- a copy diff reads as a rename, so the copy refusal stays Leaf's;
- binary, mode-only and empty entries read as a file with no hunks, so
  the hunkless refusal stays;
- a quoted path comes back as Git wrote it, so `_decode_git_path` still
  decodes it and still refuses an escape Git would not write;
- a hunk ends as soon as its `@@` header's counts are met and the next
  line goes back to the file parser as metadata, so a declared count
  that undercounts its body is silently dropped rather than refused.
  `_parsed_hunks` requires the hunks to account for every line from the
  first `@@` on;
- a bare empty line reads as an empty context line, for patches that
  crossed a whitespace-stripping transport. `lf-diff` refuses one, so
  capture does too.

unidiff does refuse a hunk shorter than its header declares, a body line
with no marker, and a `+++` path that disagrees with the `diff --git`
header; those raise `DataError` with the library's reason rather than a
second Leaf check. The `---` side is Leaf's, since unidiff only checks
the target: the header is now compared against the pair rebuilt from the
`---`/`+++` paths, which also drops the regex that guessed where an
unquoted path with spaces ended.

Every refusal the old parser raised still refuses; six messages changed
wording. Checked by running both parsers over 150 commits as
`git show` and `git format-patch` output, both shipped `.patch`
fixtures, and the suite's own cases: 152 identical manifests, 148
message-only differences, no case where one accepted and the other
refused.

## Dependencies

`psutil>=6` and `unidiff>=1`, each the lowest version measured to work
here. unidiff 0.7.5 loses a C-quoted `diff --git` header and splits the
file in two. psutil 5.9.4 is the oldest with an abi3 wheel for macOS
arm64 but none for Linux aarch64, which the local Linux suite runs on;
6.0.0 covers every platform leaf's suite uses, so no install compiles.
psutil is the one compiled extension `uv sync --no-dev` now adds, and
`pyproject.toml` says why it is a runtime dependency.

Co-Authored-By: Claude Opus 5 <[email protected]>
`scripts/preview.py` stat-polled its whole input set every 0.25s and
inferred what had changed by comparing two readings: one dict for the
files, a second for the directories whose membership could have changed,
and a cached expansion to keep the two in step. watchfiles names the
paths that changed, so the script now only says which paths it follows
and what each one means, and an idle preview no longer stats several
hundred inputs four times a second.

`watch_paths` keeps both of its jobs and loses the third. It still names
the inputs one preview follows, and still tells the layer `page init`
vendors from the page's own source — re-copying the layer mints a fresh
generation, and a revision carrying one is a different program the
browser can only follow into a fresh document, while a prose edit is a
revision the reader keeps their page for. The file-versus-directory
split is what goes: watchfiles watches each root recursively, so a first
`versions/` directory or a `media/` nearer the source than the layer's
arrives as a change under the directory that will hold it. Fifty-five
stat'd directories become sixteen subscribed roots. Compared path by
path against the old expansion over three examples, nothing the old
watcher followed is unwatched now and the layer set is identical.

`test_a_preview_subscribes_to_a_root_over_every_input_it_follows` pins
what makes matching a reported path against a set sound: every watched
path sits under a subscribed root, so none can go unreported, and no
root reaches `.tmp`, where the page directory's own writes are a
reader's feedback rather than an edit. A reported batch is matched
against the reading taken when the subscription opened and a fresh one,
because an added input is only in the second and a deleted one only in
the first.

A subscription is fixed for its lifetime, so the one thing the watcher
must not do is rebuild it for nothing: the rust watcher collects while
Python is busy, and those collected changes die with the watcher it
belongs to. Keeping only the outermost root is what makes the set stand
still. Watching every holding directory instead cost
`test_preview_adds_immutable_media_before_stamping_source` the edit it
makes as soon as the page's first `media/` file lands, because that file
added a root and the refresh it triggered replaced the watcher mid-flight.
Two sub-second assertions now catch that, where the browser test caught
it as a thirty-second timeout.

`step` and `rust_timeout` are both 250ms: the first is the quiet gap
that closes an editor's save batch, which is what the old loop's one
quiet interval did, and the second is the idle wake-up at which the loop
re-reads its stop flag and the server's liveness. `debounce` keeps
watchfiles' 1.6s default, so writes that never go quiet now reach the
page instead of starving.

No host runs `scripts/preview.py`, so watchfiles is in the dev group,
floored at 1.1.0 — the first release with a wheel for the interpreter
this project runs on. That group is exactly what `bin/leaf` leaves out,
and a checkout named by `--runtime` has only what `bin/leaf` synced, so
the worker command becomes `uv run --no-dev --project <runtime> --with
watchfiles python`. Measured on both of its paths: the ready pipe and
Ctrl-C pass through unchanged, and it costs about 20ms over running the
environment's interpreter directly. The dev group's comment also loses a
TOML backport the group does not carry.

Checked by hand on a live preview of `heat-loss`: a source edit printed
`Reloaded heat-loss` with the layer generation unchanged, touching
`skills/leaf/assets/leaf.js` printed it again with a new generation, and
touching a sibling example and a Markdown file under
`skills/leaf/scripts` printed nothing. The preview, bootstrap, and
recompose tests in `tests/test_render_export.py` are green, as is
pre-commit.

Co-Authored-By: Claude Opus 5 <[email protected]>
The shell and the server compose the same transforms, which is what the check is
for, but each now mints its own script nonce, as each already minted its own
server id. Each document is rewritten with the nonce its own scripts carry, so a
policy naming some other one still parts the two.

Co-Authored-By: Claude Opus 5 <[email protected]>

@leaf-agent leaf-agent left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Four of the five swaps land cleanly. The diff parser and the preview watcher each changed behaviour in a way the parity evidence could not reach, and the lint gate lost one check; the nonce is a design point I'd rather hand back than patch. Inline comments carry each one.

The unidiff row is the one I'd hold on. I reproduced the sweep — 600/600 identical manifests over 300 commits, as both git show and git format-patch output — so the row's evidence stands; the divergences are only reachable by construction, and they fall on both sides of the capture contract. A path whose directory name ends in b (x b/y.py) makes unidiff split the diff --git header at the wrong space, so real git diff output that pierre-diffs renders is now refused. In the other direction a \r-only or \ <text> hunk line is now admitted, and the vendored parser throws parsePatchContent: invalid hunk line on it, so capture stores evidence the page answers with a failed file.

The watcher and the graph gate each lost a case the hand-written code covered: a package root reached through a symlink or a ../ path never matches a reported name, and an extensionless specifier now resolves instead of failing. Both have one-line fixes that I've run.

The nonce needs your call rather than a fix. Per delivery it is strictly better than the hashes it replaces, but write_live_shell mints one at build time and the worker serves those bytes verbatim, so every reader of leaf.page gets the same nonce for a release's whole life — which is the one shape where a nonce buys nothing over 'unsafe-inline'. Nothing reachable exploits it today; the docstring's guarantee just isn't true on the path that serves the most readers.

lint and test are green at this head, and so is my own selection — test_interact_document.py, test_interact_contract.py, test_revision_delivery.py, test_live_shell_artifact.py (455 passed; the one failure there is this environment's missing npm ci --prefix worker), plus the test_render_export.py watcher cases. The .dependency-cruiser.mjs closures are byte-identical to the eslint ones they replace, all five fault classes fire, and no-restricted-imports does cover the dropped no-boot-entry and more.

Say the word and I'll push the preview.py and .dependency-cruiser.mjs fixes.

# blank lines a patch may carry between files are neither hunk nor metadata.
body_text = section.rstrip("\n") + "\n"
try:
parsed = PatchSet.from_string(body_text)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

unidiff parses the diff --git header itself, and its RE_DIFF_GIT_HEADER is greedy, so it splits at the last b/ in the line. A directory whose name ends in b therefore breaks a patch the old parser read correctly:

$ mkdir "x b"; echo a > "x b/y.py"; git add -A; git commit -qm one; echo b > "x b/y.py"
$ git --no-pager diff
diff --git a/x b/y.py b/x b/y.py
...
old: ACCEPT [('x b/y.py', 1, 1)]
new: REFUSE  unsupported hunks for x b/y.py: Target without source: +++ b/x b/y.py

The widget has no trouble with it — parsePatchFiles on the same bytes gives [["x b/y.py","change",1]] — so the refusal costs a capture that used to work, and its message relays unidiff's internal wording rather than naming anything the author can fix.

This is exactly the ambiguity the deleted _diff_header_paths existed for, and _manifest_file still carries its comment ("the header is compared with the pair rebuilt from those paths rather than split at a guessed space") — but that rebuild now happens after unidiff has already parsed the header and failed. Handing unidiff a section whose header line has been normalised from the already-parsed ---/+++ pair would keep both readings.

Comment on lines +169 to +173
# unidiff reads a bare empty line as an empty context line, for a patch that
# crossed a transport which strips trailing whitespace. `lf-diff` refuses one,
# so capture refuses it too rather than storing evidence the page cannot draw.
if not all(body):
raise DataError(f"unsupported hunks for {path}: an empty line has no marker")

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

not all(body) catches "" but not the two other lines unidiff absorbs and lf-diff refuses. A bare \r matches unidiff's RE_HUNK_EMPTY_BODY_LINE and counts as an empty context line on both sides, so the @@ counts still balance; a \ <anything> line is typed \ and counted in len(hunk) but not in added/removed, so the accounting check passes too.

'...@@ -1,2 +1,2 @@\n-del\n\r\n+add\n'      old: REFUSE invalid hunk line   new: ACCEPT (1, 1)
'...@@ -1 +1 @@\n-del\n\\ hello there\n+add\n'  old: REFUSE invalid hunk line   new: ACCEPT (1, 1)

The first one the widget throws on — parsePatchContent: invalid hunk line — so the reader gets "that file's diff failed to load" from a capture that reported success. The second it silently reads as a no-newline marker and strips the preceding line's newline.

The guard below restores the old parser's reading. I ran it over 800 real patches (400 commits, both git show and git format-patch): zero divergence from this branch's current behaviour, and both cases above refused.

Suggested change
# unidiff reads a bare empty line as an empty context line, for a patch that
# crossed a transport which strips trailing whitespace. `lf-diff` refuses one,
# so capture refuses it too rather than storing evidence the page cannot draw.
if not all(body):
raise DataError(f"unsupported hunks for {path}: an empty line has no marker")
# unidiff reads a bare empty line as an empty context line and any `\`-led line
# as a no-newline marker, for a patch that crossed a transport which mangled it.
# `lf-diff` refuses both, so capture refuses them too rather than storing evidence
# the page cannot draw.
unreadable = next(
(
line
for line in body
if not line.startswith(("@@", " ", "+", "-"))
and line != r"\ No newline at end of file"
),
None,
)
if unreadable is not None:
raise DataError(f"unsupported hunk line for {path}: {unreadable!r}")

Comment thread scripts/preview.py Resolved
Comment thread .dependency-cruiser.mjs Resolved
Comment thread skills/leaf/scripts/leaf/http.py Resolved
… the nonce's reach

A watcher can report a change under the root string it was given, while the layer
reading answers in resolved paths, so a package reached through a symlink or `..`
named every change in a form the watched sets never held and stopped reloading.
Every path is now resolved before it enters a set or the subscription.

dependency-cruiser resolved `./repaint` to `repaint.js` through enhanced-resolve's
default extensions, so an import the browser 404s passed the gate. Extensions are
off, as in browser ESM; the graph is the same 723 dependencies.

A nonce keeps out markup written after delivery only while that markup cannot learn
it. That holds per response and not for `write_live_shell`, which mints one per
release, so the comments now say where the guarantee holds.

Co-Authored-By: Claude Opus 5 <[email protected]>

@leaf-agent leaf-agent left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

One case of the watched-path bug is still open, one level below the root the new commit fixes. input_paths resolves nested symlink targets on purpose — its docstring says so, and layer.py tests is_symlink() for every VENDORED_FILES entry and every PACKAGE_DIRS subdirectory — so a package whose widgets/ is a link, or whose vendored file is, puts the target path into layer and paths. holders still contributes only the package roots, so nothing subscribes to the directory that target lives in and watchfiles never reports a change to it. That falsifies Watched's own invariant — "Every path in paths sits under one of those roots; a path that did not would be an input the preview had silently stopped following" — and it is a regression against main, where the stat snapshot read each resolved path directly and containment never entered it.

Measured on a package whose widgets/ is a symlink to a tree outside the root:

layer holds the symlink target?       True
paths not under any subscribed root:  1
    /tmp/.../elsewhere/widgets/lf-x.js
roots: ['/tmp/.../pages', '/tmp/.../pkg', ...]

The two suggestions name the input_paths reading and add its parents to holders, the way page's parents already are. Taking the parents of layer as a whole does not work: runtime / "pyproject.toml" is in there and its parent is the checkout, which collapses the subscription onto the whole tree, .venv and .git included. With these two, the case above reports 0 uncovered paths, the ordinary subscription is unchanged, and the eight watch_paths cases in test_render_export.py stay green.

test_a_preview_names_a_linked_package_in_the_form_its_changes_arrive asserts that each path is resolved rather than that each sits under a subscribed root, which is why it passes today — the containment assertion is the one that closes this class rather than this instance of it.

Comment thread scripts/preview.py Resolved
Comment thread scripts/preview.py Resolved
The layer reading follows a link inside a package as well as one at its root, so a
package whose widgets directory links outside it put the target in the watched sets
while only the package root was subscribed, and changes there were never reported.
Each package file's directory now joins the subscription the way the page's own do;
for the shipped examples the subscription is unchanged. The test now asserts that
every watched path sits under a subscribed root, which is the invariant rather than
one instance of it.

Co-Authored-By: Claude Opus 5 <[email protected]>
@max-sixty
max-sixty merged commit 39c4c02 into main Sep 17, 2026
5 checks passed
@max-sixty
max-sixty deleted the settled-swaps branch September 17, 2026 06:51
max-sixty added a commit that referenced this pull request Sep 17, 2026
The Saving column called its figures lines deleted, but for the four swaps that
landed in #753 each figure was the size of the region a library would take over,
and each deleted far less because the refusals, contracts, and definitions around
the mechanism stayed. The definition now says so, with those four as the
calibration for reading the rows still open.

Co-Authored-By: Claude Opus 5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants