Architecture review · bella-enterprise

2026-10-24 · main @ 4359dbbf7

Scope: the hot spots since 2026-09-20, namely Gateway reply delivery, the reasoning-engine adapters, browser runs, Knowledge files and inbound intake. 4 explorers proposed 15 candidates. Each candidate then went to 2 read-only skeptics, one rechecking the evidence and one arguing against the design. 9 cards survived, 5 were dropped, and 2 merged into one. worker/ means packages/worker/src/.

module seam leakage / defect deep module StrongWorth exploringSpeculative

Defects found on the way

These are behaviour bugs, not refactors. checked means I re-read the code myself; reported means a skeptic agent found it and I have not re-checked it.

1 · A send on the Turn's envelope records itself

Strongin-process
worker/agent/gateway/reply-counts.ts (165) · worker/agent/gateway/surface-dispatcher.ts · worker/agent/gateway/executor.ts:2369, 2557, 2773, 2844, 2908, 2990 · worker/turn/direct-turn.ts:777 · worker/turn/routed-finish.ts:215 · worker/agent/narration-salvage-meta.ts (44) · worker/turn/settle-errand-narration.ts (48) · worker/surface/terminal-reply.ts:327 · worker/surface/web-inbound-surface.ts (5 salvage reads)
Before: 8 sends, 3 signals for "did it go out?"
flowchart LR
  R["message.reply
executor:2369"] --> D["dispatchSurfaceReply"] N["5 Gateway notices
executor:2557…2990"] --> D S["2 salvage closures
direct-turn · routed-finish"] --> D N -- "counts even on ok:false" --> C["reply-counts
counter on TurnContext"] R --> C S -- "never counted" --> F["salvage flag
result.meta"] E["settle-errand
output non-empty?"] C --> Doors["6 doors"] F --> Doors E -. "third test" .-> Doors classDef leak stroke:#dc2626,stroke-width:2px,color:#7f1d1d; class N,F,E leak linkStyle 3 stroke:#dc2626,stroke-width:2px linkStyle 5 stroke:#dc2626,stroke-width:2px
After: one module sends and records
reply notice ×5 salvage ×2 held narration
send on this Turn → delivered?
dispatch
in-process · HTTP
ok:false never counts
record the kind of send
answers: seatAnswered · anyWordsReachedThePerson
6 doors · watchdog · pre-turn ack ask the predicates; no door reads the salvage flag

Problem. Each caller has to dispatch, then remember to record, then read the record correctly. Five callers forget the ok:false check, two never record, and the doors fill the gap with a second flag and a third test. In its one-month life reply-counts.ts has taken four behavioural fixes, each narrowing the same question.

Solution. Deepen reply-counts.ts together with dispatchSurfaceReply into one module. It sends on the Turn's own envelope, records only what went out, and answers the few predicates the doors need.

  • Locality: the defect class is fixed once
  • Leverage: one interface, 8 send sites
  • Delete the salvage-flag read paths
  • Tests: send then ask, no Lark surface

The skeptics narrowed this. The record already exists, and the doors need two predicates, not one. The 585-line test's mocks belong to Lark intake and would remain.

ADR 0014 §1/§4 names the repliesEmitted counter as the mechanism. That can stay as the implementation. ADR 0127's ratchet budgets executor.ts, and this change shrinks it.

2 · One engine turn verdict behind the adapter seam

Worth exploringin-process
worker/agent/nullclaw-acp-adapter.ts (3443, at its 3444 ceiling) :2305-2537 · worker/agent/nullclaw-lean-adapter.ts (1712) :1131-1253 · worker/agent/hermes-acp-adapter.ts (1218) :365-370, :722-737 · worker/agent/pi-cli-adapter.ts (764) :671 · worker/agent/nullclaw-refusal-diagnosis.ts · worker/observability/circuit-breaker-diag.ts · worker/agent/nullclaw-empty-relay-retry.ts
Before: each adapter composes its own verdict, and they drift
outcomeacpleanhermespi
refusal✓✓ships text—
silent empty success✓✓✓—
breaker stop✓✓——
truncation✓———
errorDiag stamp✓———
e78b84202 edited both nullclaw ladders, 7 lines in one and 4 in the other. 52 test files each define their own FakeChild, and the breaker test is 308 lines of byte-exact JSON-RPC.
After: adapters translate their wire; one module decides
acp wire
lean wire
hermes wire
pi exit
↓ facts the turn ended with: stop reason, streamed text, rounds, tools, exit ↓
engine turn verdict
diagnoseRefusal
deliverableStreamedText
stoppedByCircuitBreaker
truncation
→ success · reason · errorText · deliverable · retry flags
Tests become a table from facts to verdict, with no spawn and no frames.

Problem. The engine seam is real, with 4 adapters, but each one composes the outcome from shared predicates in its own 25 to 80 lines. The copies have drifted into the defects listed above.

Solution. One verdict module takes the facts a turn ended with and returns the outcome. Each adapter only maps its wire to those facts.

  • Locality: drift becomes impossible
  • acp gets headroom under its ceiling
  • Interface is the test surface
  • Delete the copy-policing arch tests

The skeptics narrowed this. The hard predicates are already shared, and only the composition is copied. pi and hermes have different facts, so the input needs care to avoid becoming a lowest-common-denominator bag.

ADR 0127 owner #3 "Engine edge" already plans this ("relay normalisation, exit-0 laundering"). ADR 0024 §Alternatives keeps lean self-contained, and §7 plans to converge lean and rich, which would delete one copy without any new module. Reopening it for the verdict alone is worth asking. ADR 0021 and 0025 are not affected, though 0025's pointer to isEmptySuccess would move.

3 · A Knowledge File's stamps sit beside what it owes

Worth exploringlocal-substitutable
packages/database/src/repositories/knowledge-files.ts (1073) :163-164, :189-355 · worker/knowledge/files/index-job.ts (521) :172-178, :280, :302, :390-402 · worker/knowledge/parse/parser-client.ts :213-224 · worker/knowledge/files/unpack.ts :38 · worker/knowledge/files/stt.ts (334) :306 · worker/knowledge/files/index-plan.ts (66)
Before: the reader and the writer use different predicates
flowchart TB
  subgraph DB["@bella/database"]
    T["INDEX_OWED_CLAUSES
12 SQL + TS twins"] P["isPdfRow · isDocxRow"] T --- P end subgraph W["worker index job"] J["3 stamp sites
:280 · :302 · :390"] Q["isPdfFile · isDocxFile
unpackKindOf"] J --- Q end J -- "writes stage_versions" --> T Q -. "mirrors, by hand" .-> P X["quality.stt
untyped JSON, 5+ casts"] J --> X T --> X classDef leak stroke:#dc2626,stroke-width:2px,color:#7f1d1d; class Q,X leak linkStyle 3 stroke:#dc2626,stroke-width:2px
After: each clause names the stamp that settles it
file ledger (beside KIND_ROUTE)
clauseowed when (SQL / TS)stamp that settles it
pdf_textisPdfRow ∧ ¬stamppdf_text: v
docx_textisDocxRow ∧ ¬stampdocx_text: v
sttmedia ∧ ¬settledtyped TranscriptState
… 9 more
The job reports stage outcomes and never names a stage_versions key. A round-trip test checks that, for every kind and every outcome, the row then owes nothing.

Problem. The owed side is already one table. The stamp side is assembled in the worker at 3 sites through predicates that mirror the table by hand, and that split caused the mislabelled-file requeue loop.

Solution. Move stamp production into the clause table so each clause carries its settling stamp, and type transcript state the way preview state is already typed.

  • Locality: writer and reader in one place
  • One round-trip test covers every kind
  • Delete the hand-mirrored predicates
  • Transcript casts become a type

The skeptics narrowed this: do not generate SQL from TS, because a predicate DSL would move complexity rather than remove it. The requeue bug was caught before merge, so the churn signal is a feature still being built.

Aligned with ADR 0425 §2 (the SQL/TS twin design) and §5.

4 · One composer for a Knowledge answer's files

Worth exploringin-process
worker/agent/gateway/knowledge-dispatcher.ts (694) :376-533 · worker/knowledge/files/list-with-files.ts (98) · worker/knowledge/files/delivery-next.ts (186, 14 exports) · worker/knowledge/files/found-this-run.ts (188) · worker/knowledge/files/page-originals.ts (163)
Before: two callers repeat the same files slice
knowledge.search
fold page originals
documents before pictures
filesAnsweringTheAsk
next: held files only ✓
customer strip
knowledge.list
fold page originals
documents before pictures
filesAnsweringTheAsk (note only)
next: every file, closest too
customer strip
b938dc121 patched search only. delivery-next.ts calls itself "the one home" but only holds strings.
After: delivery-next composes the slice
searchlist
files, closest, reader → files · next · doNotBrowse · noted
fold + order
held vs closest
customer strip
knowledge.read stays outside because it does no search and has no closest case. Search keeps its tracker, folder and link branches.

Problem. Search and list each compose the files part of the answer themselves, and they have already drifted. List offers closest offerings with a "send" instruction.

Solution. Finish delivery-next.ts into a composer for the files, closest, reader slice, called by both tools.

  • Locality: held-file rule lives once
  • One table test, no search mock
Fits ADR 0346 §5, 0347 §4 (doNotBrowse), 0348 §2 and 0349 §4 (fold and order). No ADR decides against it.

5 · Pull the done-challenge chain out of the browser run

Worth exploringports & adapters
worker/orchestrator/browser-agent-loop.ts (2306, ceiling 2307) :1564-1720 · worker/orchestrator/browser/patterns.ts :119-239 · worker/orchestrator/browser/budgets.ts :259 · worker/orchestrator/browser-step-parse.ts :33 · worker/orchestrator/browser-hand-prompt.ts (171) · skills/chrome-operator/SKILL.md
Before: one function, one step body, the chain inline
151–2306 step body 619–2258 6 LLM re-asks (1564–1720) share `challenged` + DONE_CHALLENGE_BUDGET read decided · pageView · currentScreen · committedAny · sawVision · askOnce · act 36 lets before the loop 38 `decided =` assignments 32 of the last 40 commits are line-neutral 93 test files · 302 vi.mock
After: the loop asks once; the chain owns the budget
loop: forcing guards stay here (bulk, send, save), together with SCOPE SERVED
done challenge: proposed done + run record → accepted done | still working
empty · named · infra
dead domain · intention · blind
spent budget across steps
port: askOnceport: node status

Problem. The hottest file in the repo sits at its line ceiling, so every fix trades lines inside one step body. The six done challenges, which share one budget, can only be reached by driving the whole loop with mocks.

Solution. Move the six-challenge chain, with its budget and claim patterns, into one module. The LLM ask and the node-status call come in as ports. The forcing guards stay in the loop.

  • Tests: scripted asks, no Gateway fake
  • Loop regains headroom under its ceiling
  • Locality: exit honesty in one module

The skeptics narrowed this. An "accept or challenge" interface cannot also hold the forcing guards, which act rather than ask, so those stay in the loop.

6 · One WhatsApp wire seam over the per-wire files

Worth exploringmock (true external)
worker/message-listener.ts (1041) :231-474 · worker/services/answering-mode-admin-send.ts (755) :461-707 · worker/services/mark-chat-read.ts (158) :63, :148 · worker/user-session-manager.ts (1476) :1088-1160 · worker/watchdog-delivery.ts · worker/surface/kirimdev-bridge.ts (835) · worker/surface/sambungapi-bridge.ts (508)
Before: every consumer switches on the wire
flowchart LR
  A["admin send
media"] --> K{"kind?"} M["mark read"] --> K2{"kind?"} U["media fetch
user-session-manager"] --> K3{"handle?"} WD["watchdog delivery"] --> K4{"kind?"} K --> B1["bridge"] & B2["Kirimdev"] & B3["Sambungapi"] K2 --> B1 & B2 K2 -- "no timeout" --> B3 K3 --> B2 & B3 K4 --> B1 & B2 & B3 L["message-listener
3 × (surface 23 deps + intake 19 deps)"] classDef leak stroke:#dc2626,stroke-width:2px,color:#7f1d1d; class B3,L leak
After: consumers call the wire; each wire is one adapter
admin sendmark readmedia fetchwatchdog
WhatsApp wire
send media · mark read (bounded) · fetch media · decode inbound
bridge
Kirimdev
Sambungapi
The Org Bella intake is built once from a wire, replacing 3 copies in which only 4 facts differ. One contract suite runs against 3 fakes.

Problem. Per-wire behaviour lives in the consumers rather than the wires, so a rule like ca7714dad's 15 s bound reached two wires and missed the third. ADR 0424's edit and delete handling exists only on the bridge, so on Kirimdev and Sambungapi edits and deletes are silently lost.

Solution. Put the per-wire switches (media send, mark-read, media fetch, decode) behind one wire interface whose adapters are the existing per-wire files, and build the Org Bella intake once per wire.

  • Locality: a wire rule lands once
  • Two adapters justify it; there are 3
  • Delete 2 of 3 listener blocks

The skeptics narrowed this. Most "wire branches" are slug-to-medium folds that stay. The Inbox text leg runs through the API process's /api/bella/send and is out of reach. Decode and send should stay separate halves.

Contradicts ADR 0286 D2 ("every consumer gains its branch") and ADR 0191's closed outbound union. It is worth reopening because that ADR's predicted cost has now produced a missed-wire defect.

7 · Finish recordInbound inside SurfaceIntake

Worth exploringlocal-substitutable
worker/surface/intake.ts (1653) :921-1000, :1276-1296, :1321, :1354, :1399, :1562 · worker/surface/web-inbound-surface.ts (1936) :30-33 · worker/handlers/lark-event-route.ts :125 · worker/surface/lark-inbound-surface.ts :544
Before: the rule's home exists, but writers go around it
recordInbound: "the rule lives here and nowhere else"
step (a) write · monitor branch · suppression branch bypass it
ownsUserPersistence: 7 reads, its stated reason is stale
:1399: a branch for a combination nothing wires
Teams named inside generic intake (:1314-1349)
Lark dedups twice (route Set + adapter Set)
After: every intake write goes through one module
recordInbound
who writes the row
inboundMetadata
keepArrivingFile
Web's late writes and the Teams Graph marker stay outside, because they need facts only those surfaces hold. "One row per thing said" tests then run without mocking the welcome.

Problem. Intake already has a home for the inbound-row rule, but three of its own branches write around it, and two adapter flags steer the whole pipeline.

Solution. Route every write intake makes through recordInbound, delete the dead branch, and retire ownsUserPersistence.

  • Interface shrinks: one flag gone
  • Locality: the row rule lives once

The skeptics narrowed this. A module that also owned Web's and Teams' rows would fail the deletion test, because complexity would move into a parameter bag.

ADR 0018 §6 says Web stays out of SurfaceIntake, and the code already contradicts it. Fix the ADR in the same change. ADR 0014 §3 owns the repository-side helper.

8 · One source for the hands' in-page functions

Speculativein-process
packages/desktop/src/browser.ts (2005) · packages/chrome-extension/background.js (3035) · dom-snapshot.js (636) · dom-act.js (1229) · tools/testing/*-cases.js
node hand
settleProbe · formDigest · fieldReadout · focusTarget
KEEP IN STEP
⇄
8 + 11 parity suites
extension
inline in background.js
page-script files (dom-snapshot.js, dom-act.js, and the rest)
node hand loadsextension loads

Problem. The in-page functions are written twice. The shared case tables already catch drift, so the cost is co-editing: 10 of 11 recent commits to browser.ts also touched the extension.

Solution. Finish moving the functions still inline in background.js into the standalone page-script files, and have the node hand load them.

The rule that the node runner must not depend on the extension package blocks the cheap path. ADR 0193 names the extension as the eventual primary hand, and if the node hand retires this candidate goes away.

9 · Inbound adapters hand over turn facts, not prompt text

Speculativein-process
worker/surface/lark-inbound-surface.ts :997-1901 · worker/surface/org-bella-whatsapp-surface.ts :1206-2276 · worker/surface/web-inbound-surface.ts :881-1936 · worker/surface/teams-inbound-surface.ts :482-740 · worker/prompt/direct-turn-context.ts · worker/agent/gateway/acp.ts:218
Before
Lark: 54 += into skillContext · WhatsApp: 29
4 hand-written "## Sender Context" blocks
5 calls to execute with 13 positional args
string parsed back downstream (stripIntakeSections, looksLikeBodSender)
After
adapters fill TurnContext facts (it already carries messageText and the sender)
prompt assembly renders the facts once (ADR 0127 owner 4)

Problem. Each adapter assembles prompt context by string concatenation, and downstream code parses it back.

Solution. Finish TurnContext as the facts record and render it once.

The skeptics narrowed this. The measured defect (Web's prepended block breaking the split) is already fixed, because readers prefer messageText. A shared run-a-turn module would change behaviour, and ADR 0018 §7 requires a behaviour-preserving lift.

Dropped after verification

Top recommendation

1 · A send on the Turn's envelope records itself

This is the only candidate where the duplicated interface is producing a live defect today: a connect link is lost and the engine is told it went out. The defect sits in the hottest Gateway file, and fixing it deepens a module that already exists rather than adding one.