Skip to content

feat(ui): Brain Orb Phase 3 — client-held Gemini Live voice tile + read-only KB search (abilityai/trinity-enterprise#60) - #1395

Merged
dolho merged 17 commits into
feature/58-brain-orbfrom
feature/60-brain-orb-voice
Jul 2, 2026
Merged

dolho merged 17 commits into
feature/58-brain-orbfrom
feature/60-brain-orb-voice

Conversation

@vybe

@vybe vybe commented Jul 1, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Brain Orb Phase 3 (enterprise#60) — the client-held voice surface on top of the shipped static render + scope control. The browser holds its own Gemini Live session (connects directly to Gemini via a short-lived, config-locked ephemeral token minted by Trinity — no audio proxying), drives the orb by voice, and searches the agent's KB read-only.

Stacked on #1389 (feature/58-brain-orb). Retarget to dev once Phase 1/2 merges.

What's in this PR (5 commits)

  1. Client-held voice tile + read-only KB search — POST /brain-orb/voice-token (ephemeral-token mint, v1alpha client, model+config+tools locked, uses=1, short expiry); POST /brain-orb/tool → agent ~/.trinity/brain-orb/search hook; scope-by-voice reuses the Phase-2 broker; brain_orb_voice_available flag. Writes stay OFF by construction (locked manifest + no /session route; field is ephemeral_token, never token).
  2. SDK bump google-genai 1.12.1 → 1.63.0 — the pinned version had no auth_tokens, so the mint 502'd; verified the existing VOICE-001 stack still imports. Wired BRAIN_ORB_* flags through compose.
  3. Strict capability gating — the route guard (not just the tab) fetches /info and redirects unless the agent declares the brain-orb capability, so the orb is never launchable on a non-Cornelius agent, even via a raw URL. Restored the p5 audio-reactive voice orb (vendored locally, CSP-clean) that was stripped with the CDN removal.
  4. Auto-start + smoothing — the voice tile starts automatically when opened (V key), no manual "Start"; capped the p5 voice orb to pixelDensity(1) and the main WebGL orb to 1.5x on hi-DPR for frame headroom inside the SPA.
  5. Tab / logo / close-buttons — the Brain tab is now an in-page settings panel with an "Open Brain Orb" launch button (no auto-jump); a small brain logo in the AgentDetail header opens the orb; every orb widget has a small always-visible close (lens/scope/search gained one; a find dock chip re-opens search).

Key design (from the plan-time reviews)

  • JWT never leaves orb.js: the orb page mints and relays only the ephemeral Google token to the nested voice iframe over origin-checked postMessage — never in a URL.
  • CSP-clean, no nginx change: connect-src already allows wss:; the Gemini client is hand-rolled, all voice JS + the mic worklet + p5 are externalized/vendored (script-src 'self'). The source page's hardcoded key is stripped.

Test Plan

  • tests/unit/test_brain_orb.py — 39 pass: mint gating/field-name/v1alpha/rate-limit, /tool proxy + error map, agent-server search hook.
  • Verified live on a locally-deployed Cornelius agent (real FAISS brain): the orb renders the graph; the Brain tab appears only on Cornelius; a raw URL to a non-Cornelius agent redirects; the voice tile shows the restored animated orb; real semantic KB search drives navigate_to_note; the ephemeral-token mint + browser relay work end-to-end.
  • /verify-only (needs a live browser + mic): the actual audio conversation over the Constrained-token WS handshake; a live VOICE-001 smoke test confirming the SDK bump didn't regress aio.live.connect.

Deferred (Phase 4)

Transcript capture, KB-write actions, headless-skill injection.

Part of abilityai/trinity-enterprise#60

Generated with Claude Code

Eugene Vyborov and others added 5 commits July 1, 2026 09:37
…ad-only KB search (abilityai/trinity-enterprise#60)

Adds the voice control surface on top of the Phase 1/2 orb (static render +
live scope control). The browser holds its own Gemini Live session — it connects
DIRECTLY to Gemini using a short-lived, config-locked ephemeral token minted by
Trinity — so the voice→tool→orb loop stays in-browser and Trinity never proxies
the audio.

Backend:
- POST /api/agents/{name}/brain-orb/voice-token (AuthorizedAgentByName, per-user
  rate-limited): mints an ephemeral Gemini Live token via a dedicated v1alpha
  genai client (NOT the cached voice singleton). live_connect_constraints lock
  the model + the whole config incl. a READ/VISUAL/SCOPE-only tool manifest;
  uses=1; ~60s new-session window; expiry = VOICE_MAX_DURATION. Response field is
  `ephemeral_token` (never `token`, which would flip orb.js's Phase-4 write
  surface on). services/brain_orb_voice_service.py.
- POST /api/agents/{name}/brain-orb/tool (read-only): proxies to the agent's
  ~/.trinity/brain-orb/search hook (scope-aware, no writes; 404 when absent).
- BRAIN_ORB_VOICE_ENABLED flag → brain_orb_voice_available (= flag && GEMINI_API_KEY),
  distinct from brain_orb_available.

Frontend:
- New CSP-clean voice tile: public/brain-orb/voice/{orb.html,voice.js,mic-worklet.js}.
  Adapted from the Cornelius page with the hardcoded API key and p5-from-CDN
  stripped, logic externalized (script-src 'self'), the mic worklet shipped as a
  same-origin file. Hand-rolled Gemini Live client uses the Constrained method +
  access_token param + setup{model} (config locked in the token).
- orb.js: mints the token via the JWT-gated broker and relays only the ephemeral
  token to the nested voice iframe over postMessage (JWT never enters the iframe
  or a URL); repoints navigate_to_note's vault fallback at the read-only /tool;
  un-hides the voice tile on the voice flag. Same-origin postMessage guards.
- AgentBrainOrb.vue: allow="microphone" on the host iframe; relays voiceAvailable.

Writes stay off by construction (locked manifest + no /session route). Tests
extend tests/unit/test_brain_orb.py (39 pass): mint gating/field-name/v1alpha/
rate-limit, /tool proxy, search hook, and the locked-manifest guard. The live
ephemeral handshake + end-to-end loop are /verify-only (need a live agent+Gemini).

Docs: requirements §46 FR-7, feature-flows/brain-orb.md Phase 3, architecture.md.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…or the voice tile (abilityai/trinity-enterprise#60)

Local deploy surfaced that the pinned google-genai==1.12.1 has NO `auth_tokens`
attribute, so the Brain Orb voice-token mint 502'd (`'Client' object has no
attribute 'auth_tokens'`) — the ephemeral-token API was added in a later release.

- docker/backend/Dockerfile: google-genai 1.12.1 → 1.63.0. Verified in the local
  stack: POST /voice-token returns a real auth_tokens/… token (model+voice locked,
  11 read/visual/scope tools, zero write tools, no bare `token` field), and
  services/gemini_voice.py (existing VOICE-001 backend-proxied path) still imports
  cleanly under 1.63. A live VOICE-001 voice-session smoke test is a pre-merge item.
- docker-compose.yml: pass BRAIN_ORB_ENABLED + BRAIN_ORB_VOICE_ENABLED through to
  the backend container (they were never wired into compose, so the flags couldn't
  reach config.py even when set in .env).
- Docs: brain-orb.md / voice-chat.md updated for the new pin.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…orb animation (abilityai/trinity-enterprise#60)

Two fixes surfaced by local testing on a real Cornelius agent:

1. STRICT GATING — the orb is no longer launchable on a non-Cornelius agent, even
   via a raw URL. The route guard (router/index.js beforeEnter) now fetches
   GET /api/agents/{name}/info and redirects to AgentDetail unless the agent
   declares the `brain-orb` capability (in addition to the platform flag) — not
   just the tab. Previously the raw /agents/{name}/brain URL loaded an empty orb
   for any agent; now a non-capable (or stopped) agent redirects. The voice tile
   inside the page then only needs the platform voice flag (capability already
   guaranteed by the guard).

2. VOICE ORB ANIMATION RESTORED — the audio-reactive orb in the voice tile (the
   p5 smoke/core sketch) was cut when p5 was removed for loading from a CDN
   (CSP script-src 'self'). Re-added by vendoring p5 locally
   (voice/vendor/p5.min.js — no eval/Function, CSP-clean) and restoring the
   sketch + an output AnalyserNode, so the orb breathes when idle and pulses with
   Cornelius's speech (enqueueAudio routes each output buffer through outAnalyser).

Verified end-to-end on a locally-deployed Cornelius agent (brain-orb capability):
the orb renders the real graph, the Brain tab appears only on Cornelius, a raw
URL to a non-Cornelius agent redirects, and the voice tile shows the animated orb;
the /tool search + /scopes hooks and the ephemeral-token mint all function.

Docs: requirements §46 FR-2/FR-7, feature-flows/brain-orb.md, architecture.md.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…b (abilityai/trinity-enterprise#60)

- Auto-start: opening the voice tile (V key / dock chip) now starts the
  conversation automatically instead of requiring a manual "Start" click. The
  tile auto-starts on load, and re-opening an already-loaded tile re-starts via
  an `orb-voice-start` message. The Start button remains as a retry if the mic is
  denied (auto-start → ERROR).
- Voice-orb jank: cap the p5 audio-reactive orb to pixelDensity(1). The sketch is
  fill-bound (many radial gradients/frame); at retina 2x it costs ~4x and starves
  the main WebGL knowledge orb of frames, so the big orb visibly jerks during its
  slow rotation/fly. 1x is imperceptible on the small voice orb and frees the main
  render loop. (The main orb's animation loop is unchanged — byte-identical to the
  upstream Cornelius source, dt-clamped; the jank was pure frame contention added
  by the restored voice orb inside the Trinity SPA + nested iframes.)

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…abilityai/trinity-enterprise#60)

- Brain TAB is now an in-page panel (BrainPanel.vue) — brain settings placeholder
  + an "Open Brain Orb" launch button — instead of auto-jumping to the full-page
  orb on tab select (removed the route-push watcher). Clearer, and leaves room for
  real brain settings.
- Header brain LOGO: a small orb glyph in the AgentDetail header (AgentHeader),
  capability-gated (platform flag AND the agent's brain-orb capability), that opens
  the orb page directly.
- Every orb WIDGET now has a small, always-visible close ✕: the `.tile-x` is no
  longer hover-only (opacity .32, brightens on hover), and lens/scope/search — which
  had none — get one too. Search gains a `find` dock chip to re-open; the briefing
  cards re-inject their ✕ after their innerHTML re-render. Every panel is closeable
  and re-openable from the dock.
- Also cap the main WebGL orb to pixelRatio 1.5 on hi-DPR displays (was 2.0) for
  GPU headroom inside the Trinity SPA — a retina jank mitigation (verify on device).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@vybe
vybe marked this pull request as draft July 1, 2026 12:45
…ink) (abilityai/trinity-enterprise#61)

Completes the Brain Orb write surface with the low-risk half of Phase 4:
owner/admin-only capture-a-note and link-two-notes. Split from the full
Phase 4 during /autoplan (two independent reviews) — run_skill (headless
claude -p exec), automatic transcript capture, and transcript injection
are deferred to trinity-enterprise#66 (they carry the exec/injection risk
and depend on an unproven Gemini-Live-transcription path).

Backend:
- routers/agent_brain_orb.py: GET /brain-orb/actions + POST /brain-orb/action
  (OwnedAgentByName). Action verb enum-validated at the boundary (run_skill/
  capture_transcript -> 400, never forwarded), body-capped (413), rate-limited
  per (user, agent, action), audit-logged, Idempotency-Key deduped (Invariant
  #18, key folded per verb; effect_guard doesn't fit — no execution_id).
- services/brain_orb_voice_service.py: can_write folds capture_note/link_notes
  into the LOCKED voice manifest only for owners; shared users keep the
  read-only Phase-3 manifest. can_write computed in the mint route.
- config.py + routers/settings.py: BRAIN_ORB_WRITE_ENABLED kill-switch
  (default OFF, distinct from BRAIN_ORB_ENABLED) -> brain_orb_write_available.

Agent-server (Invariant #5 mirror):
- routers/brain_orb.py: GET/POST /api/brain-orb/action[s] via the hardened
  _run_hook over the agent's ~/.trinity/brain-orb/action convention hook
  (agent owns the write, Invariant #8; stdin-only, no shell string).

Frontend:
- orb.js: rewire initActions/postAction/doCapture/doLink from the dead
  localhost voice proxy (X-Orb-Token) to the broker + Bearer JWT +
  Idempotency-Key; un-hide #actions via body.brain-orb-write only after the
  broker confirms owner + flag + hook; add capture_note/link_notes to
  ORB_TOOLS; double-submit re-entrancy guard.
- orb-trinity.css / AgentBrainOrb.vue / stores/sessions.js: gate the panel on
  the write flag, relay writeAvailable in the init handshake.

Tests: 14 new cases (owner-gate 403, flag-off 404, no-hook 404, enum 400,
413, 429 + claim-release, idempotency replay/409, owner-only voice manifest,
agent-server action hook). 62/62 green. Security: /review 0 critical,
/cso --diff 0 findings.

Docs: requirements §46 FR-8, feature-flows/brain-orb.md Phase 4a, learnings
(effect_guard vs Idempotency-Key), cso-diff-2026-07-01 report.

Refs abilityai/trinity-enterprise#61

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Eugene Vyborov and others added 10 commits July 1, 2026 15:53
…he flag reaches the container (abilityai/trinity-enterprise#61)

The Phase 4a write flag existed in config.py + settings feature-flags but was
never added to the backend `environment:` block in docker-compose.yml (mirrors
BRAIN_ORB_ENABLED/BRAIN_ORB_VOICE_ENABLED at lines 40-41). Without it the flag
never reaches the container, so brain_orb_write_available stays false and the
write routes 404 regardless of .env. Surfaced during the localhost demo.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…ost-session processing (abilityai/trinity-enterprise#66)

Mirrors the original cornelius-internal voice proxy (resources/agent-visualization/
voice/{proxy_server,transcript_io}.py): the client captures per-turn transcription,
the agent renders + saves it, Trinity brokers. De-scoped per direction — transcript
saving (for debug/analyze) + an optional post-session prompt; run_skill (arbitrary
exec) stays out.

- Mint (brain_orb_voice_service): add input_audio_transcription +
  output_audio_transcription to the LOCKED LiveConnectConfig so the constrained
  ephemeral token returns per-turn transcription. Verified: auth_tokens.create
  accepts it and the mint returns a real token (de-risks the F6.1 unknown).
- voice.js: buffer content.inputTranscription/outputTranscription into conversation
  events (session_start/user_turn/model_turn/tool_call/session_end); flush in
  endConversation() (the correct seam — onclose early-returns on wsClosedByUs) AND
  the error-close branch; relay {session_id, events} to the parent orb.
- orb.js: on 'orb-capture-transcript' (owner + ACTIONS.enabled) →
  postAction('capture_transcript', {..., process:true}) with session_id as the
  Idempotency-Key (double session-end = one save). postAction gains an optional key.
- Backend (agent_brain_orb): accept capture_transcript + process_transcript verbs
  (still OwnedAgentByName, audited); raise the action body cap to 1 MiB for whole
  conversations. run_skill remains rejected (400).
- Agent-server (brain_orb): raise the /action body cap to 1 MiB to match.
- Agent action hook (cornelius template): render markdown transcript (ported
  transcript_io) → resources/inbox/Voice Conversations/; process_transcript runs the
  agent's configured prompt (~/.trinity/brain-orb/voice-postprocess.md — configuring
  it is the opt-in) over the transcript via a DETACHED claude -p with the transcript
  on STDIN (no shell string → no command injection), writing a processed note.

Security posture (owner-gated exec): OwnedAgentByName + owner-authored prompt +
owner's-own-transcript; transcript via stdin closes command injection. Residual
(follow-up): the post-process claude -p uses --dangerously-skip-permissions (full
tools) — a tool-constrained sub-invocation + transcript credential-sanitization are
the hardening path if this graduates beyond a debug tool.

Verified on localhost: mint accepts transcription config; synthetic voice events
render + save to the KB; process_transcript spawns the detached claude -p (ran end
to end — only blocked by the agent's Claude credit balance, not code). Full
live-audio transcription streaming is a manual voice-session check. 64 unit tests
green.

Refs abilityai/trinity-enterprise#66

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…te control (abilityai/trinity-enterprise#67, #68)

Fixes the feedback from the live voice test: notes/links created via the orb
landed in the inbox but never appeared on the graph, and there was no way to
confirm integration happened.

#67 (mechanism):
- Backend `POST /brain-orb/refresh` (OwnedAgentByName, 200s timeout mirroring
  /scope, audited `brain_orb_refresh`) → agent-server `POST /api/brain-orb/refresh`
  → the `action` hook's `refresh` verb reindexes + re-exports data.json (folds
  inbox notes + _links.md edges into the graph; agent owns generation, Invariant #8).
- orb.js `refreshGraph()` refetches /data and rebuilds in place (same machinery as
  setScope). Auto-triggered after capture/link; voice writes debounced ~4s so a
  burst coalesces into one rebuild.

#68 (observability):
- Visible "↻ integrate & refresh" control in the actions panel, an "integrating…"
  state, and a "graph updated · +N notes, +M links" / "graph up to date"
  confirmation toast so the user can see the write land.

Verified on localhost: capture → refresh folds the note in as a real graph node
(1072 → 1079 nodes, +3 edges), and the UI control rebuilds with the confirmation
toast. 70 unit tests green (6 new refresh cases).

Refs abilityai/trinity-enterprise#67 abilityai/trinity-enterprise#68

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…yai/trinity-enterprise#70)

Voice-test feedback: navigating to a note or highlighting a topic/group lit the
target but didn't zoom/center to fit it — it settled at a fixed distance
(focusNode→195, highlightGroup→250) regardless of where the selection sat or how
spread out it was, so the highlight read as "not focused."

Add frameNodes(indices): centers on the selection's centroid direction AND derives
a fit distance from the selection's max shell radius + angular spread vs the camera
FOV (single note zooms in; a spread-out cluster zooms out), clamped to the existing
zoom bounds and never inside the node shell. Route focusNode and highlightGroup(frame)
through it, replacing the fixed 195/250.

Verified on localhost: navigate to a single note 330→144 (zooms in; was fixed 195);
highlight a cluster computes a per-group fit; the highlighted group is centered and
framed. (Client-side WebGL camera math — no pytest surface; verified in-browser.)

Fixes abilityai/trinity-enterprise#70

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…ding refresh on miss (abilityai/trinity-enterprise#70)

Second round of voice-test feedback: after "create a node, link it to Dopamine,
now show me the connection," the user saw the Dopamine node but not the edge to the
new note. Two causes, both under the navigate/focus (#70) umbrella:

1. Framing showed a LONE node. focusNode already lit up the node + neighbours + drew
   the connecting edges (setHover), but frameNodes([i]) fit only the single node — so
   the other endpoint of a just-made link sat off-screen. Now frame the node TOGETHER
   with its highlighted neighbours (hoverSet), so both ends of the edge are in view.
2. Timing race. Voice writes integrate on a ~4s debounce, so navigate_to_note could
   fire before the new note was a graph node and fall back to the vault reader. Now,
   on a miss, if an integration is pending, flush it (refreshGraph) and retry before
   the vault fallback — so "create X → show me X" lands on the real graph node.

Verified on localhost: navigate to the just-created "Random Node 24" frames it with
Dopamine and draws the connecting edge (both endpoints visible, link line rendered).

Fixes abilityai/trinity-enterprise#70

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…points (abilityai/trinity-enterprise#71, #72)

Two more voice-test issues in the write→refresh loop:

#72 — selection lost on refresh. applyData()→teardownGraph() wipes
lastInspectedIdx/hover and node indices change, so a capture/link auto-refresh
deselected whatever the user was looking at mid-task. refreshGraph() now snapshots
the selection BY ID (inspected node, or highlighted group) before the rebuild and
re-selects/re-frames it after; and it SKIPS the rebuild entirely when nothing
changed (added_nodes==0 && added_edges==0) so a no-op refresh never disturbs the
selection. Camera view was already preserved by teardown.

#71 — link to a non-existent note silently "succeeded" (dangling reference,
false success, no renderable edge). The agent action hook's `link` verb now
validates BOTH endpoints resolve to real notes (graph node or inbox file) and
returns a clear "note not found — create it first" error otherwise (agent-owned
per Invariant #8; the orb already surfaces r.error). This repo change is the
contract note + the orb selection fix; the demo cornelius hook was updated to
match and the real agent adopts the same.

Verified on localhost: selecting Dopamine then refreshing (with a pending capture
forcing a real rebuild) keeps Dopamine selected + inspector shown; linking to a
non-existent "Random Node 25" now returns a clear not-found error.

Fixes abilityai/trinity-enterprise#71 abilityai/trinity-enterprise#72

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…ntegrates it (abilityai/trinity-enterprise#72)

Feedback: "add the node" captures + refreshes a few seconds later, but the new
node isn't selected — you had to ask to select it separately. Now a capture sets a
_pendingFocusTitle that refreshGraph() consumes after the rebuild: it focuses the
just-created note (inspector + highlight + framing) once it's folded into the graph,
taking priority over restoring the prior selection. Falls back to restoring the
prior selection when there's no pending capture. Purely client-side — the agent
doesn't need a second navigate_to_note call.

Verified on localhost: a voice capture_note with no follow-up navigate ends with the
new note auto-selected in the inspector after the debounced refresh.

Refs abilityai/trinity-enterprise#72

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…toggle + prompt editor) (abilityai/trinity-enterprise#73)

The Brain tab was a launch button + a "no settings yet" placeholder. Give it its
first real control: configure the post-voice-session processing (#66) from the UI.

- BrainPanel.vue: "Post-voice processing" section — an on/off toggle ("run a
  processing step after each voice session") + a prompt textarea + Save, loaded on
  mount. Shown only when brain_orb_write_available + agent running.
- Backend GET/PUT /api/agents/{name}/brain-orb/postprocess (OwnedAgentByName,
  write-flag-gated, PUT audited) → agent-server GET/PUT /api/brain-orb/postprocess
  (direct file I/O). Config is agent-owned (Invariant #8):
  ~/.trinity/brain-orb/voice-postprocess.json = {enabled, prompt}, with the legacy
  .md as a prompt-only read fallback.
- The action hook's _spawn_postprocess now gates on the `enabled` flag (default OFF)
  — disabling keeps the saved prompt but skips the claude -p.

Verified on localhost: the Brain tab shows the toggle + prompt (loaded from config);
saving writes voice-postprocess.json and GET reflects it; with enabled:false a
capture_transcript still saves the transcript but the post-process is skipped
("post-processing disabled"). 76 unit tests green (6 new).

Refs abilityai/trinity-enterprise#73

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…gn system (abilityai/trinity-enterprise#73)

The Brain-tab Save + Open Brain Orb buttons used bg-state-autonomous-500/600
(amber, and a non-standard lighter shade — the only -500/-600 primary buttons in
the app). The app-wide primary-action convention is bg-blue-600 hover:bg-blue-700
(22 usages); focus rings are focus:ring-blue-500 (35 usages). Aligned the buttons,
the enable checkbox accent, and the prompt textarea focus ring to blue. Amber
(state-autonomous) is kept ONLY for the Brain Orb identity (the orb icon + BETA
badge). No shared Button component exists, so this matches the established Tailwind
convention rather than a component.

Verified on localhost: both buttons compute rgb(37,99,235) = blue-600.

Refs abilityai/trinity-enterprise#73

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…meout stagger, safe audit (abilityai/trinity-enterprise#61)

Applies the fixes from the final pre-merge review of the Phase-4 branch:

- F1 (med): /refresh drove the agent action hook but was gated only on
  BRAIN_ORB_ENABLED — the write kill-switch wasn't airtight. Added
  _require_write_enabled() + test_refresh_write_flag_off_404.
- F3 (low/med): /action backend timeout == agent-server timeout (60/60); a
  premature backend 504 could release the idempotency claim → double-write on
  retry. Staggered backend to 90s > agent 60s (mirrors the scope route).
- F4 (low): /postprocess PUT capped at 1MiB vs the agent-server's 64KiB; capped
  the backend at 64KiB to match.
- F5 (low): audit awaited after complete() unguarded → an audit failure 500s a
  completed write (fresh-key retry double-writes). Added _safe_audit best-effort
  wrapper on all post-write audit calls.
- orb-tool postMessage handler lacked an origin check; 4a added owner-write tools
  to ORB_TOOLS. Added the origin guard (matches the two sibling handlers;
  CSP frame-ancestors already mitigated it).
- F2 (med): the committed 4a-only CSO report declared "0 findings / no claude -p"
  — stale vs the shipped exec/transcript surface. Rewrote it as the full-branch
  final review (findings + resolution).

Auth boundaries, can_write split, enum gate, stdin-only exec, and idempotency
ordering all verified clean by an independent reviewer. 77 unit tests green.
Learning captured (kill-switch completeness across incremental routes).

Refs abilityai/trinity-enterprise#61

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@vybe
vybe marked this pull request as ready for review July 2, 2026 09:24
feat(brain-orb): Phase 4a/4b KB-write + voice-transcript + write→graph refresh (ent#61, #66, #67, #68)

@dolho dolho left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Reviewed the actual head diff (c2133d4 vs base feature/58-brain-orb), security surface first. Verdict: the security envelope is excellent — but the branch content no longer matches the PR description, and it now overlaps #1407. Reconcile the stack before merge.

Strong (Phase-3 security envelope)

  • Ephemeral-token mint is correctly locked. client.auth_tokens.create(CreateAuthTokenConfig(uses=1, expire_time, new_session_expire_time, live_connect_constraints=LiveConnectConstraints(model=VOICE_MODEL, config=config))) — the whole LiveConnectConfig is bound (no lock_additional_fields), so the browser cannot widen model or tool surface at connect time. Dedicated v1alpha client (not the VOICE-001 singleton), uses=1, dual expiry (session + 60s new-session window). This is the right pattern.
  • Capability route guard is raw-URL-safe. The router beforeEnter fetches /info and redirects unless the agent declares the brain-orb capability (and bails on a stopped agent whose /info can't be read) — the orb is genuinely un-launchable on a non-capable agent, not just tab-hidden.
  • JWT never leaves orb.js. Response field is ephemeral_token (never token), and only the short-lived Google token is relayed to the nested voice iframe over an origin-checked postMessage; the platform JWT stays in the orb page. Reconnect re-mints (token is uses=1). Clean three-frame separation.
  • Read-only search hook. Agent-server /tool → ~/.trinity/brain-orb/search runs a scope-aware, fail-closed, read-only vault search via _run_hook(stdin=…) (stdin-only, no shell string). No writes on this path.

Headline finding — description ⇄ branch mismatch + overlap with #1407

The Summary says "Brain Orb Phase 3 … Writes stay OFF by construction … Deferred (Phase 4): … KB-write actions, headless-skill injection." But this PR's actual head (c2133d4) contains the full Phase-4a (and 4b-documented) write surface:

  • Backend /api/agents/{name}/brain-orb/action + /actions routes, BRAIN_ORB_WRITE_ENABLED, and the can_write owner-only write-tool folding in the mint service (_ORB_VOICE_WRITE_TOOLS).
  • input/output_audio_transcription locked into the token, and feature-flows/brain-orb.md documents Phase 4a (capture/link) and Phase 4b (process_transcript → detached claude -p) as shipping here.

So the branch has effectively collapsed the stack forward — #1395's diff now substantially overlaps #1407 (the write-surface PR). This isn't a code defect, but it makes "review #1395 as read-only Phase 3" impossible and will double-review the same code. Please either (a) update this PR's title/Summary to reflect that it now carries Phase 3 + 4a (+4b transcript pipeline), and clarify what #1407 still adds on top, or (b) re-slice the branches so each PR owns a disjoint layer. Right now the descriptions are stale on both.

Notes on the write surface it now contains

I reviewed that code in depth on #1407 — it's sound (owner-gated OwnedAgentByName, enum-validated verb, body caps, rate-limit-with-claim-release, idempotency ordering, stdin-only agent hook, no XSS). The two small suggestions I left there apply equally here: (1) the write summary is stale, and (2) the /action idempotency key isn't namespaced by current_user.id (the rate-limit key already is) — a same-key collision between two owner/admins could replay the other's snapshot.

SDK bump risk

google-genai 1.12.1 → 1.63.0 is a large jump on the shared VOICE-001 dependency. The Summary verifies imports still resolve, but the live aio.live.connect smoke test is an unchecked box — worth confirming the real workspace-voice path didn't regress before this lands, since it's the widest blast radius in the diff.

Reviewed as head-vs-base for the stacked branch (merge order 58 → 60 → 61), not vs dev.

🤖 Generated with Claude Code

@dolho
dolho merged commit e83bdc2 into feature/58-brain-orb Jul 2, 2026
8 checks passed
@vybe
vybe deleted the feature/60-brain-orb-voice branch July 2, 2026 19:55
vybe added a commit that referenced this pull request Sep 7, 2026
…or below the state card (#2538, #2539) (#2546)

* fix(brain-orb): latch wheel routing per gesture so momentum never zooms (#2538)

The single window-level `wheel` listener in public/brain-orb/orb.js decided
zoom-vs-scroll PER EVENT via panelCanScroll(), with no gesture memory. On a
macOS trackpad one flick keeps emitting `wheel` at frame cadence long after
the fingers lift, so the inertia tail that arrived after a panel reached its
edge was routed to camTargetDist and the camera zoomed out.

- Gesture latch: a run of wheel events with inter-event gaps <= 150 ms
  (WHEEL_GAP_MS — the top of the issue's 120-150 ms range) is one gesture.
  Its first vertical event decides the route from the scroll container under
  the pointer; every later event keeps it. Panel-latched events that can
  scroll nothing are swallowed (preventDefault), never zoomed. A fresh
  gesture (gap > 150 ms) over an already-edged panel still zooms, so the
  deliberate "scroll to the end, then keep going to zoom out" chaining is
  preserved.
- Clock is e.timeStamp (input time) with a performance.now() fallback.
  Chromium coalesces events queued behind a stalled frame into one, so a
  stall > 150 ms still ends the gesture — bounded to one re-decided step.
- deltaY === 0 (pure-horizontal) events never start a latch; they refresh
  the clock and otherwise behave exactly as before. deltaX handling stays
  deferred, as the issue itself defers it.
- Allowlist gone: panelCanScroll() walks the target's ancestors up to <body>
  and asks computed style, so the CSS is the single source of truth.
  #scopePanel (overflow-y:auto all along) scrolls under the wheel at last.
- The ctrlKey pinch branch and the Safari gesture* listeners are untouched.
- index.html: orb.js is un-hashed under prod nginx's 1y-immutable cache, so
  the <script> tag now carries ?v=2026-09-06 (comment says: bump BOTH).

Proof: e2e/brain-orb-wheel-latch.spec.js (@smoke; standalone
/brain-orb/index.html FALLBACK graph — no agent, no auth; skips without
WebGL, fails loudly on a boot error). Red before the fix at A2+A3
(camTargetDist 330 -> 473.9 across a 25-event tail), A4 ([true,false]) and
A5 (#scopePanel wheel zoomed, defaultPrevented true); 9 passed after. A1
scrolls #inspContent into the inspector's visible box and asserts the aim
point before firing its one trusted wheel, so a mis-aim can never read as
a routing failure.

Co-Authored-By: Claude Fable 5.1 <[email protected]>

* fix(brain-orb): floor the inspector below the state card (#2539)

#stateBox (top:26px, 174px tall) and #inspector (top:50%; translateY(-50%);
max-height:82vh) are both right-anchored .panels at z-index 10 with nothing
reserving vertical space, so a tall inspector rose into the state card and,
being later in DOM order, painted over "STATE / Idle" — measured overlap
128 / 119 / 103 px at 1280×800 / 1440×900 / 1920×1080 (132 px on the real
1280×756 iframe viewport).

CSS only — exactly two values on #inspector change:
- transform: translateY(max(-50%, calc(224px - 50vh))) keeps the centring
  while the box is short and floors its TOP edge at 224px (26 + 174 card +
  24 gap) once it is tall — continuous, no jump. The 174px premise holds
  for every STATES desc and the boot-time "reflecting last run" string
  (<=3 lines at 26ch); spec B1 asserts it rather than trusting it.
- max-height: min(82vh, calc(100vh - 224px - 26px)) keeps the BOTTOM edge
  26px inside the viewport.
No fallback pairs: the sheet already relies on min() unguarded. No JS:
makeDraggable/restorePanels set inline right:auto + transform:none, so a
dragged or restored inspector keeps its user-chosen spot (spec B3).

Cost, stated so nobody raises the cap later: on the real iframe a
full-height inspector shrinks from 82vh to 100vh-250px (~549 -> 420 px at a
1280×800 window). Out of scope, follow-ups: the #controls legend under a
full-height inspector, #scopePanel's own gutter collision, and — surfaced
by spec B1 — the top-centred #dock covering the state value at <=760px.

index.html: styles.css now carries the shared ?v=2026-09-06 token (the
orb.js tag got it in the previous commit; bump BOTH on every edit).

Proof: e2e/brain-orb-inspector-layout.spec.js (@smoke; standalone FALLBACK
page, no agent/auth). Red against the previous styles.css at all five
viewports — "inspector.top 72|81|97|68|81 vs stateBox.bottom 199.86,
Expected >= 215.86" — 8 passed after. The shared helper gains a
`paragraphText` option so B2's short note sits inside the centring band
(h <= 100vh - 448) instead of on its edge.

Co-Authored-By: Claude Fable 5.1 <[email protected]>

* docs(brain-orb): state the ?v= cache-bust convention in the feature flow (#2538, #2539)

The "Known limitations" bullet said the orb was frozen (verbatim) and that a
future orb update "needs a cache-bust" — both false once #2538/#2539 edit
orb.js and styles.css and index.html carries the shared ?v=2026-09-06
token. Rewrite that one bullet to state the convention (bump BOTH tokens on
every edit) and its residual (/brain-orb/index.html itself is heuristically
cached by prod nginx — the \.html$ no-store rule is a paired follow-up),
and list the two Playwright HUD specs + helper in the file map. Nothing
else in the flow changes.

Co-Authored-By: Claude Fable 5.1 <[email protected]>

* docs(brain-orb): name the symmetric latch at the zoom branch so nobody re-decides per event (#2538)

The block comment above panelCanScroll() states the gesture rule ("every
later event of the gesture keeps that route"), but the line a future reader
would actually edit — the zoom branch that runs while `can` is true for a
zoom-latched gesture — only said "zoom-latched". That is exactly where an
`if(wheelMode==='zoom' && can) return;` "improvement" would land and quietly
turn a zoom flick into an inspector scroll (the reported bug's mirror
image). Say it at that line: the latch is symmetric by design, the first
event decides, and spec A4 pins it. Comment only — no behaviour change;
spec A re-run green (9 passed).

Co-Authored-By: Claude Fable 5.1 <[email protected]>

* docs(brain-orb): the ?v= bullet — first orb edits since v0.8.0, not since vendoring (#2538, #2539)

"the first edits to the orb since it was vendored" is false: `git log --all
-- src/frontend/public/brain-orb/orb.js` shows the Phase 2–4 PRs (#1395,
#1407, #1494 and their hardening follow-ups) editing orb.js in-repo after
#1389 vendored it. What IS true, and what the cache-bust convention hinges
on, is that #2538/#2539 are the first orb edits to reach `dev` since the
v0.8.0 release merge (the only commit touching these files on origin/dev).
Say that instead.

Co-Authored-By: Claude Fable 5.1 <[email protected]>

---------

Co-authored-by: Eugene Vyborov <[email protected]>
Co-authored-by: Claude Fable 5.1 <[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