Skip to content

refactor: simplify the codebase and fix the defects a scan found - #10

Merged
TudorAndrei merged 122 commits into
mainfrom
t3/a6528b53
Nov 12, 2026
Merged

TudorAndrei merged 122 commits into
mainfrom
t3/a6528b53

Conversation

@TudorAndrei

@TudorAndrei TudorAndrei commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

Why

A read-only scan of the whole repository listed duplicated code, dead code and about 60 implicit state machines, and it turned up defects along the way. This PR applies the simplifications that keep behaviour the same and fixes the defects that the code confirmed. There is no issue for it.

It is larger than one change. Each area was done on its own branch and merged here, so the merge commits split it by area if you prefer to review or land it in parts.

What changes

No single diagram fits, so this is a table by area. "Fixed" rows change behaviour on purpose; the rest are refactors.

Area Before After
Task store, scheduler Seven copies of "enter terminal state, set expiry, delete lease". UPDATE tasks SET state had no state predicate. A lost renewal or a start-time rejection settled a task twice and logged Store(NotFound). One end() helper. The update only matches the state that was checked. One settlement() picks the outcome and it is written once. Fixed: rejecting a task cancelled while leased is a no-op; a shutdown that lands just before a start requeues the task.
Pact gateway begin_send had 18 early returns through a Begun type. A refresh token was consumed before the caller was checked. A dropped request left its message "still being answered" for 24 h. begin_send returns a Result. Fixed: the refresh consume only matches the grant's own caller; a reservation guard discards the message on drop; deny refuses expired codes.
Agent adapters A cancel that arrived before a Codex turn was registered was lost. early_cancels grew without bound. An approval request seen while waiting for a response was dropped. Setup time was not charged to the turn deadline. Fixed, all four. Sandbox is a typed enum, validated once. Agent::set_workspace and supports_workspace_change are removed; Executor::set_workspace stays.
Hub client Request plumbing repeated per method; three listing shapes; wire errors mirrored twice. A lost answer to approve left the hub row accepted with no local approval for 7 days. Shared request helpers, one listing type, one error type per layer. Fixed: an ambiguous failure keeps the approval; a listing the node cannot store is taken off the hub; unblock removes the local block first and reports a failure; a failed pin or encode undoes the grant and the group membership it added.
Node, CLI, transport Four abort-and-join copies, field-by-field CLI copying, five Frame literals, link state as Option + bool. The admin socket was bound, then set to 0600. One stop helper, Frame::reply_to, LinkState and Phase enums. Fixed: the socket is bound in a 0700 staging directory, set to 0600, then renamed into place.
Directory and managed clients Twin error enums, Result<_, ()> in ten functions, roster_sync.rs, two pinned HTTP modules. A renew could overwrite a newer capability. One error type, one pinned client module, roster_sync.rs gone. Fixed: renew and publish hold one mutex until the directory answers.
MCP server The data directory was an Option that production always set; 17 guards for the empty case. Required, one constructor, guards gone, shared ask helper. Tool names, schemas and texts are unchanged.
Admin UI A 10-field Notice struct, ~18 hand-written one-button forms, four day selects, two bools for the UI mode, a 2,950-line test module in admin_ui.rs. Notice and UiMode enums, post_button, days_select, tests moved next to their code (admin_ui.rs 3,822 → 1,451 lines, same 79 tests). Fixed: publish_listing requires a session; a failed confirm keeps its token; the waiting reload returns to the page it was on.
Hub server Three transition lambdas, six copies of commit-then-notify, four copies of the owner-link liveness rule. One @transitions table, Versions.commit/1, live()/stale(). Fixed: expired unswept owner links no longer count toward limits; lastSeen is null once the keep window passes.
Integrations Grokbot: a failed marker write blocked every later claim; a lock with no owner was never taken over; the installer never rebuilt an old binary. Hermes: a handler error killed the reader thread; a quick reconnect ran two threads. Fixed, all five. Grokbot now replays the shared socket transcript.
Tests, scripts Step helpers defined two or three times; three e2e scripts shared a skeleton. Four feature scenarios failed where sleep is not on the shell's default path (NixOS). Helpers in tests/common, start_relay and fail in lib.sh. The slow fake Codex finds sleep.
Deleted ProofHandle, HubStore, and dead items (MAX_DIRECT_ACCESS_DAYS, FAKE_CODEX_SCRIPT, HubClient::listing(), NodeHub::with_flag, NodeHub::set_stored_url, DiscoveryError::NotFound, others).
  • Smaller behaviour changes that came with the work:
    • A wrong caller on token refresh gets "Unknown, used or expired refresh_token" (still invalid_grant).
    • An admin form POST with an unknown action gets 400 from the form parser before the session check.
    • If the local write fails during a listing renewal, the listing is off the hub until the next good renewal.
    • Hermes is_connected honours extra.data_dir.
    • A node with only some directory-publication flags fails before it binds.
  • Left out on purpose:
    • the PendingApproval and OperatorReviewed task states
    • protocol-1 hub compatibility
    • the single-value brand_user
    • unread columns
    • the two hub DELETE routes the node never calls
    • the bare aether node / aether mcp entry points
      Each needs a protocol, migration, CLI or product decision.
  • Known and not changed:
    • Hub errors on admin forms still answer 200 while other refused forms answer 400.
    • DELETE /v1/owner-links/{id} answers 204 for an expired link that is not swept yet.
    • The live-model retry settings in scripts/openclaw-e2e.sh and demo/e2e.sh expand to 61 tries and 201 s.

Look at: the refresh-token change in crates/aether-store/src/pact.rs (use_refresh_token) and the kept-approval rule in crates/aether/src/admin_ui/hub.rs (approve, with HubError::may_have_applied). Both decide who gets access.

Evidence

Run on the merged branch, head 5d0ac48:

  • cargo fmt --all -- --check: pass.
  • cargo clippy --workspace --all-targets -- -D warnings: pass.
  • cargo test --workspace: aether lib 413 passed, 2 ignored (live Codex, not enabled); aether-store 69 passed; aether-core 5 passed.
  • cargo test -p aether --test features: 96 of 96 scenarios, 538 steps.
  • Hub: mix format --check-formatted clean, mix test 327 passed.
  • OpenClaw plugin: node --test integrations/openclaw-plugin/test/ 38 of 38.
  • Grokbot bridge: npm test 26 of 26.
  • Hermes plugin: 19 run, 3 skipped. The adapter tests skipped because Hermes was not on PYTHONPATH.
  • sh -n on every script in scripts/ and demo/: clean.

Unchecked:

  • Container proofs (mise run container-proof) and the edited e2e scripts: Docker is not installed on this machine.
  • The Hermes reconnect fix against real Hermes: only run against a stub of the gateway modules.
  • TLA+ models (mise run tla): not run. No spec changed.
  • Live Codex tests: not enabled.

Test changes: the defect fixes each add a regression test, most written first and seen to fail on the old code. Two fixes have no failing-first test: the setup-time deadline (the test only pins the new behaviour) and the shutdown-before-start requeue (the race is too narrow to reproduce). The admin UI test move keeps the same 79 test names and bodies. One Codex test that asserted the dead set_workspace hook is replaced by an executor test for the workspace a turn runs in. Runtime cost is unchanged (estimated; the lib suite still finishes in about 6 s).

Admin UI: the HTML of every response the admin tests render was compared before and after the refactors with attributes sorted and tokens blanked, and it is the same, so there are no screenshots.

Merge danger

Door: two-way. No migration, no change to A2A frames, the invite line, the Agent Card or the hub protocol.
Blast radius: all nodes

A node from this branch talks to released nodes and to the hub as before; signed request bytes are pinned by tests and unchanged. The change touches grants, access groups and PACT tokens: the risk is in the rollback and guard paths listed under "Look at", where a mistake would leave a grant applied or refuse a valid refresh. Nothing needs a restart beyond the usual update.

🤖 Generated with Claude Code


Autofix with [code]smith
Open in [code]smith · Need help on this PR? Tag @codesmith-bot with what you need.

TudorAndrei and others added 30 commits November 12, 2026 00:09
mark_rejected returned NotFound for a task cancelled while leased,
because cancel had already deleted the lease. Treat an already
cancelled task as a no-op, like mark_failed and mark_unknown_result.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
mark_succeeded, mark_failed, mark_unknown_result, mark_rejected, cancel,
cancel_if_owned and lease recovery each repeated "enter the terminal
state, start the input retention deadline, delete the lease". Move it
into one helper, run the three lease-holding mark_* calls through one
end_execution body, and have cancel_if_owned reuse cancel's body after
its ownership check.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
change() read the state, checked the transition, then updated by id
alone. Update only while the row still holds the state it checked and
report InvalidState when no row matched, so the guard does not depend on
there being a single connection.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Write and sync the active-claim marker under a private name and link it
into place, so a failed write leaves nothing behind while the link still
fails if another bridge holds a claim. Report an unreadable marker with
the same message as an invalid one.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A node with both pages shows the caller at /agents, and the page script
moved it to / after four seconds. The hub section now names its screen in
data-hub-waiting and the script reloads that path. Reloading the address
bar itself would GET the path of the last form, which only answers a POST.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A bridge that stopped between creating runtime.lock and writing
owner.json left a lock no other bridge would take over or proxy to.
Treat a lock still without owner.json after two seconds as stale.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Disconnecting stops the active claim and clears waiting work, so the
connected terms next to stopped and pending were redundant. The send()
failure paths stay.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
POST /listing/publish called ensure_admin_session, which starts a session
for a request without one, while every other POST requires the session it
already has. A cookieless POST is now refused with 403 like the others.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The remote proxy, the bridge-socket dispatcher and the MCP tool wrapper
now come from OPERATIONS (name -> argument names). The MCP schemas and
the local mailbox executor stay hand-written.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Every write that changes what an endpoint sees now runs through
Versions.commit/1, which bumps the touched versions in the transaction
and notifies after the commit, instead of six copies of
atomic |> notify |> case.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…uest limit

Settings parsing and the wake hint move out of main(). The waking flag is
gone: the 30 s cool-down starts before the 5 s request, so it never
blocked a call. The 256 KiB limit is defined once in server.mjs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Denying a device authorization now also requires it to be unexpired,
and the poll that consumes an approval names the approved state and
the expiry in its update, like approve_device does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
approve, accept and deliver now name a move in @transitions (side,
status before, status after) and transition/4 checks it in one place.
The update also matches the status before, and zero rows is the same
forbidden answer as the guard.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Move the fake aether script, the stdio MCP connector and until() into
test/support.mjs instead of repeating them across the test files.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The MCP server is built in one place, serve_stdio_for, and always with a
data directory. McpServer::new now takes the socket, data directory, hub
flag and caller-only switch, replacing McpServer::socket and the
with_caller, with_hub_flag and with_caller_only builders. The seventeen
"no node/caller data directory" guards and the fallible data_dir()
accessor are gone; tests pass the temp directory they already use.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The four people and agent search routes share search/3 (parse, count the
search limits, run as the account). Invites.request answers {:ok, row}
for a new row, so counted/2 has one arm for every counted success.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
PinnedJsonClient::open now returns HttpError, which already converts from
PinnedError, so the directory and managed clients lose their duplicate
From<PinnedError> impls. The two client error enums stay separate: their
variants and messages name different services, and the directory one has
UntrustedRecord.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Names.find/2 answers not_found for an account of another type, which
invites, requests and owner links each spelled out. Names.named/2 is the
one name-and-number query condition for Names, People and Listings, and
Repo.ok!/1 rolls back on an error inside a transaction.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
When the installer owns tools/bin/aether (no --aether-bin) and the probe
for --adapter fails, rebuild it once with cargo install --force and probe
again instead of asking the user to delete it by hand.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Remove items whose only use was their own definition:

- aether-core: MAX_DIRECT_ACCESS_DAYS (limits.rs)
- aether: FAKE_CODEX_SCRIPT (fixture.rs; fake_codex_script kept)
- aether: HubClient::listing (hub_client.rs)
- aether: NodeHub::with_flag, NodeHub::set_stored_url (hub_client/node_hub.rs)
- aether: free fn hub_access and its re-export (hub_client/node_hub.rs, hub_client.rs)
- aether: NodeServeContext::hub_access (node_serve_context.rs)
- aether: DiscoveryError::NotFound and its From match arm (discovery.rs, control_service.rs)
- aether: INVITE_SECONDS and PROTOCOL_VERSION re-exports from hub_client (hub_client.rs)
- aether: FullName::name_part and FullName::path_under (hub_client/full_name.rs)
- aether: orphaned doc comment above HubState (admin_ui/hub.rs)
- aether: Default derive and #[default] on Tab and Outcome (admin_ui/layout.rs, admin_ui/pact.rs)

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
within_limits! counted expired rows that the sweeper had not removed
yet, and its open-claim count checked the claim window but not the
expiry, so for up to one sweep interval a link that no node sees still
counted toward max_open_claims and max_owner_links.

OwnerLinks now has live/0 and stale/0, and the reads, the limits,
active_owner and the sweep all use them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
put merges the body over the current values (or the defaults for a
claim) and checks the service-not-searchable rule once; claim and change
read the merged values. The two else arms of block/2 are one.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Like the OpenClaw and Hermes conformance tests, drive NodeLink and the
mailbox through protocol/agent-socket/transcript.json. The host claims a
task just before it answers, as a Bot does. NodeLink's line filter is
exported as parseNodeMessage, and its reconnect delay can be shortened
for tests.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
….waiting?

Protocol.validate_endpoint/1 holds the endpoint check itself, its only
caller. Blocks.blocked?/2 is private, as nothing outside Blocks calls
it. Presence asks Notify.waiting?/1 instead of reading the Notify
registry by name.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
jsonwebtoken 11.1 requires both claims and matches them against
set_issuer and set_audience. The claims stay typed as one string,
which is what refuses a list.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Presence.last_seen/1 returned a time older than presenceKeepSeconds until
the next sweep removed it, so lastSeen stayed non-null after the time
PROTOCOL.md says it is null. The read now applies the same cutoff as
the sweep.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
An exception other than OSError from on_message skipped the status
callback, so open tasks were never closed, and it killed the link
thread, so the plugin never reconnected. Log it, close the session as a
socket error would, and keep the reconnect loop running.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
disconnect() set the shared stop event and connect() cleared it again,
so a quick disconnect-then-connect could leave the old link thread
running beside the new one. Each connect now makes its own event, and a
closing session only clears the link's socket if it is still its own.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
TudorAndrei and others added 29 commits November 12, 2026 01:06
…riter

wait_for_turn read turn/items twice and built the final answer in two
places; it now reads the items once, with one helper for an agent
message and one for a final answer. Codex's write_json and the connected
agent's write_line were the same newline-JSON writer; both use
write_json_line in agent.rs, which writes the line in one call.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
unblock removed the hub block first and then dropped any error from the
local removal. The node then kept refusing the endpoint with no message,
and the page, which lists blocks from the hub, no longer offered the
unblock. Remove the local block first and show its failure; the hub
block stays listed until it goes, so the owner can always try again.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The node builder repeated the body of policy::queue_limits to apply the
admin.limit.* overrides. Both now call policy::stored_queue_limits, and
stored_limit and PolicyFile::queue_limit are no longer needed outside it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
When pin_approval failed after sign_direct_invite, the host worker
revoked the grant but left the person in the access group that
join_and_apply had just put them in. Take them out again when the
signing added them; a person who was already a member stays.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… row

error_line moves to admin_components and replaces the five inline alert
lines. Those used two other markups than error_line, so an ErrorIcon
parameter keeps each: the icon nudged in a span, at the top, or centered.
section_heading replaces the sixteen text-xl headings and count_badge the
three counts beside a tab or heading. The relay row and the hub row of the
Connection card were the same disclosure and now share url_setting.

The empty-state note is left as it is: it is a one-class paragraph that
also carries ordinary descriptions, so a component would not be shorter.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The text, the accept and block buttons, the remove button and its label,
and the spinner of an invite row were decided in six places, with the
accept/block predicate written twice. invite_offer returns them as one
InviteOffer, and a table test covers each side and status.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Sixteen forms were a POST form, hidden fields and one button, eight to
twelve lines each. post_button takes the action, the hidden fields, the
variant and size, the label, and the form title, button aria-label or
disabled state where a form had one. The rendered HTML is unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
# Conflicts:
#	crates/aether/src/admin_ui/hub.rs
# Conflicts:
#	crates/aether/src/hub_client.rs
A node starts Codex with an empty environment. Where sleep is not on the
shell's default path (NixOS), the slow fake answered at once and four
feature scenarios that wait for a running task failed.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
…pers

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
HubStore only forwarded to aether_store::NodeStore under shorter names.
Call sites now open NodeStore::in_dir and call the NodeStore methods
directly. sender_approved_invite_ids moves into admin_ui/hub.rs as a
private function next to its only caller.

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
The four setters were only called once, from build, right after new
pre-filled the same fields with defaults. NodeOptions carries them in.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…t be encoded

sign_direct_invite applied the grant and added the person to the access
group before encoding the line. When encoding failed, both stayed
although no invite was produced. Revoke the grant, and leave the group
when this call joined it, as sign_and_pin does for a pin failure.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The admin_ui.rs test module held about 2,950 lines of tests for the
submodules. Each test now sits in the test module of the submodule whose
page or handler it exercises, and the shared fixtures live in
admin_ui/test_support.rs. The hub tests go to admin_ui/hub/tests.rs to
keep hub.rs readable. admin_ui.rs keeps only the tests of its own code:
PageContext, the session, response headers, the router and /events.

No test was added, removed, renamed or changed, and no production code
changed. The lock expectation moves to the hub tests, the only module
where it still fires.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@TudorAndrei
TudorAndrei merged commit 9eb071e into main Nov 12, 2026
11 checks passed
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.

1 participant