refactor/types: restructure API/store, split agent modes, consolidate web stores, harden security #5

Merged
jd merged 24 commits from refactor/types into main 2026-10-19 01:57:15 -04:00
Owner

Large pre-1.0 structural pass across the Go server, branch tooling, and the web
client. Mostly moving code and deleting duplication, with a set of security
fixes folded in. 25 commits, 214 files, +12.5k/−8.4k.

Go server

  • Extract internal/store.Querier and replace the per-domain dep structs
    (AccountDeps, KeyDeps, OverviewDeps, AdminDeps, ModeDeps) with one
    shared interface, decoupling internal/api from internal/server/db.
  • Split internal/server/agents/{modes,auto,notice} into their own subpackages;
    delete the internal/server/api_admin.go adapter in favor of internal/api/admin.go.
  • Move the session message verbs onto a message domain (api/message.go, 470
    lines of new tests) and drop the leftover handlers from session.go.
  • Unify model options: ModelOptions → model.Options, AdditionalOptions
    widened to map[string]any; ServiceTier now lives inside it and
    AutoReasoningLevel is gone.
  • Add sessions.initiator (system/user/agent) so initiator is gated in code
    rather than inferred, and DeleteSubagentSession now relies on FK cascade.

Security / robustness

  • web_fetch refuses loopback, link-local, private-range and multicast
    destinations at both URL and dial time (DNS rebinding), and vets every redirect.
  • shell clamps timeout_seconds before the multiplication and sweeps the
    process group after cancellation, so a SIGTERM-ignoring grandchild can't outlive the call.
  • sandbox bounds host-binary probes with a 5s timeout, fixes nested read-only
    bind ordering, and keeps rw precedence when a path is in both ro_paths and rw_paths.
  • Server: serialize user-config reads/upserts under one lock, reject unknown
    params members, tighten key scope grammar, make key/create cookie-only,
    compare hosts port-stripped in CSRF, refuse unverified OIDC emails, and purge
    user sessions past the 72h max lifetime in the janitor.

Web

  • useBranchStore centralizes the connected-branch list plus its
    load/error/loaded state and invalidator; BranchMenu and MentionPalette
    stop calling branch/list independently.
  • Shared chrome primitives (BusyBadge, PrimaryButton, QuietButton),
    callAllPages and parseJSON helpers, and a withStore test helper.
  • Family graph gutter, turn counts, and initiator-aware folding in the overview.
  • Network rejections in the API client surface as ApiError(0) instead of a
    bare TypeError; notification handler rejections are logged; the SharedWorker
    port is closed on non-persisted pagehide.

Tests

  • New: pkg/toolschema extraction tests, branch/fs, sandbox, web_fetch,
    sameorigin, querier, auth/user, sessions/messages DB, graph.ts, branch.ts.
  • Per-run Turso cache dir via internal/testutil to fix cross-test interference
    and the branch hub test race.

Breaking changes

  • WebSocket/RPC verb rename: session/* message verbs → message/*.
  • Session schema: modelOptions column → model_options, service_tier and
    auto_reasoning_level removed, initiator added. Existing dev DBs need a reset.
  • subagent spawn tool no longer takes wait.
Large pre-1.0 structural pass across the Go server, branch tooling, and the web client. Mostly moving code and deleting duplication, with a set of security fixes folded in. 25 commits, 214 files, +12.5k/−8.4k. ## Go server - Extract `internal/store.Querier` and replace the per-domain dep structs (`AccountDeps`, `KeyDeps`, `OverviewDeps`, `AdminDeps`, `ModeDeps`) with one shared interface, decoupling `internal/api` from `internal/server/db`. - Split `internal/server/agents/{modes,auto,notice}` into their own subpackages; delete the `internal/server/api_admin.go` adapter in favor of `internal/api/admin.go`. - Move the session message verbs onto a `message` domain (`api/message.go`, 470 lines of new tests) and drop the leftover handlers from `session.go`. - Unify model options: `ModelOptions` → `model.Options`, `AdditionalOptions` widened to `map[string]any`; `ServiceTier` now lives inside it and `AutoReasoningLevel` is gone. - Add `sessions.initiator` (system/user/agent) so initiator is gated in code rather than inferred, and `DeleteSubagentSession` now relies on FK cascade. ## Security / robustness - `web_fetch` refuses loopback, link-local, private-range and multicast destinations at both URL and dial time (DNS rebinding), and vets every redirect. - `shell` clamps `timeout_seconds` before the multiplication and sweeps the process group after cancellation, so a SIGTERM-ignoring grandchild can't outlive the call. - `sandbox` bounds host-binary probes with a 5s timeout, fixes nested read-only bind ordering, and keeps rw precedence when a path is in both ro_paths and rw_paths. - Server: serialize user-config reads/upserts under one lock, reject unknown params members, tighten key scope grammar, make `key/create` cookie-only, compare hosts port-stripped in CSRF, refuse unverified OIDC emails, and purge user sessions past the 72h max lifetime in the janitor. ## Web - `useBranchStore` centralizes the connected-branch list plus its load/error/loaded state and invalidator; `BranchMenu` and `MentionPalette` stop calling `branch/list` independently. - Shared chrome primitives (`BusyBadge`, `PrimaryButton`, `QuietButton`), `callAllPages` and `parseJSON` helpers, and a `withStore` test helper. - Family graph gutter, turn counts, and initiator-aware folding in the overview. - Network rejections in the API client surface as `ApiError(0)` instead of a bare `TypeError`; notification handler rejections are logged; the SharedWorker port is closed on non-persisted `pagehide`. ## Tests - New: `pkg/toolschema` extraction tests, `branch/fs`, `sandbox`, `web_fetch`, `sameorigin`, `querier`, `auth/user`, sessions/messages DB, `graph.ts`, `branch.ts`. - Per-run Turso cache dir via `internal/testutil` to fix cross-test interference and the branch hub test race. ## Breaking changes - WebSocket/RPC verb rename: `session/*` message verbs → `message/*`. - Session schema: `modelOptions` column → `model_options`, `service_tier` and `auto_reasoning_level` removed, `initiator` added. Existing dev DBs need a reset. - `subagent` spawn tool no longer takes `wait`.
jd added 24 commits 2026-10-19 01:56:34 -04:00
- Rename `model.ModelOptions` to `model.Options` and `Message.ModelConfig`
  to `Message.ModelOptions`
- Remove `ServiceTier` from messages; it now lives in
  `ModelOptions.AdditionalOptions`
- Remove `AutoReasoningLevel` from sessions
- Add `Initiator` field to sessions with system/user/agent constants
- Rename `modelOptions` column to `model_options` in init migration
- Simplify `DeleteSubagentSession` to rely on FK cascade instead of
  manually deleting messages
- Add index on `UserSessions.user_id`
Replace per-domain function-based dependency structs (AccountDeps, KeyDeps,
OverviewDeps, AdminDeps, ModeDeps) with a single shared store.Querier
interface in the new internal/store package. This decouples internal/api
from internal/server/db, simplifies server wiring, and gives test fakes a
common stubQuerier base.

Also:
- Rename model.ModelOptions to model.Options and widen AdditionalOptions
  from map[string]string to map[string]any
- Remove AutoReasoningLevel tracking from sessions and the composer
- Move admin handler logic from internal/server/api_admin.go into
  internal/api/admin.go, deleting the server-side adapter
- Add WithAuthToken and WithUserAgent to the provider interface
- Enable finished-session suggestions for child sessions, not just
  top-level ones
- Remove the agents.ConfigStore func adapter in favor of the Querier
  interface directly
Move mode definitions, resolution, and tool filtering into
internal/server/agents/modes, auto-decision logic into
internal/server/agents/auto, and subagent notification constants into
internal/server/agents/notice. This reduces coupling between the agents
package and its concerns, allowing each to be imported independently.

- Add modes.Mode, modes.DefaultModeID, modes.AutoModeID, and
  modes.ModesConfig; update all call sites to use the new import path
- Move AutoDecisionCfg, AutoDecisionConfig, and ErrAutoDecision into
  the auto package; Manager now delegates to auto.New(...).Decision
- Create notice package with ResultPrefix, QuestionPrefix, and
  IsSubagentNotification to break the circular dependency between
  agents and auto
- Add Providers.SplitProviderModel to resolve "provider/model" pairs
  without requiring the Manager
- Add effectiveModeID to Manager so answer/approval paths resolve the
  synthetic Auto id to the cached agent's concrete mode
- Add unit tests for FilterTools, SpawnAllowed, supportedLevels, and
  ReasoningLevelIndex in their respective subpackages
Introduce Manager.DeicideReasoning to resolve a reasoning effort for a
given provider/model and task, and wire it into the subagent spawn tool so
child sessions start with a dynamically chosen effort.

- Add DeicideReasoning to the subagent Spawner interface and implement it
  on Manager by delegating to auto.Decision with IncReasoning=true
- In spawnTool.Execute, override ModelOpt.Reasoning with the result of
  DeicideReasoning before creating the subagent session
- Remove SessionID from auto.DecisionReq and the associated
  GetSessionMessages fallback; empty messages now return an error directly
- Strip the debug log block from auto.Decision
- Add initiator column to Sessions INSERT statements (InitiatorUser for
  top-level, InitiatorAgent for subagent)
- Reorder UserSessions SELECT columns to match Scan order
The auto reasoning level was a presentation-only feature that showed the
routed level in the "Auto → level" label. Remove it entirely since the
server-side DeicideReasoning now handles effort selection dynamically at
spawn time, making the client-side display redundant.

- Remove autoReasoningLevel prop from PromptComposer and PromptForm
- Remove autoLabel prop from ModelReasoningSelects, hardcode "Auto"
- Remove auto_reasoning_level from SessionGetResult and autoReasoningLevel
  from SessionViewState
- Remove the fetchSession test for auto reasoning level refresh
- Update suggestionsFor to no longer exclude subagent sessions
- Update comment references from agents.* to notice.* and modes.*
- Rename DeicideReasoning to DecideReasoning across Manager, Spawner
  interface, and subagent spawn tool
- Remove lastUserPrompt helper from auto package; empty messages now
  return ErrAutoDecision directly instead of falling back to prior user
  messages
- Remove SessionID from DecisionReq and auto test helpers
- In subagent spawn, only override the child's reasoning effort when the
  decision returns a non-empty value; otherwise keep the parent's effort
- Fix column order in insertSession SQL (user_id before initiator)
- Downgrade auto decision failure log from Error to Debug
- Update notice.IsSubagentNotification doc comment to remove reference
  to the deleted lastUserPrompt
When a session resumes via respond/approve with reasoning set to "auto",
the auto sentinel marker was being recorded on the session row, overwriting
the previously decided effort. Now the marker is replaced with the
session's existing reasoning value before recording, so session/get
continues to report the actual effort.

In the manager, the auto-decision flow now pins the routed reasoning
effort on the session row at handoff (pinAutoReasoning) instead of leaving
the sentinel marker in place. This ensures the row reflects the concrete
effort the agent was built with, and subsequent prompts do not re-route
unnecessarily.

- Add recordedOpt parameter to decisionPreamble to carry the session's
  current model options
- Split autoRouted into modeRouted and reasoningRouted for independent
  pinning
- Add pinAutoReasoning method mirroring pinAutoMode
- Update AutoReasoningSentinel doc comment to reflect new pinning behavior
- Add TestSessionRespondAutoReasoningNeverRecorded and
  TestSendPromptAutoDecisionCachedAgentLeavesReasoningUnpinned
- Update existing auto-decision tests to expect pinned effort instead of
  sentinel
An empty queued message (a resume, a retry, an image-only send) now walks
back to the session's newest human prompt instead of degrading, skipping
machine-injected subagent notifications. The notice literals fold into
agents so both consumers share them without an import cycle.
Sessions.initiator keeps no CHECK so the domain can grow without a
migration; Initiator.Valid is enforced at both INSERT paths. Also fixes
NULL password_hash reads, documents the closure/parent_id invariant the
overview depends on, and records the disposable-DB migration policy.
auth/whoami only needs the login chooser's names, so it now queries them
directly instead of materialising client secrets in the api layer. Also
validates empty halves in SplitProviderModel, makes ErrLastAdmin a const,
and splits the modes consts.
The wire carries the recorded options verbatim, so the string converters
leave and validation stays the one gate: a write must name a declared
option with a string value, while reads pass recorded values through.
session/create now passes one parent id instead of a variadic slice.
CreateSession now takes parentID directly (uuid.Nil for a root); an
AgentStore adapter keeps the agent library's still-variadic store.Store
satisfied. GetMessagesByIDs reads an id list across a user's sessions in
transcript order, the read behind the upcoming message/list verb.
message/create, message/list, message/get and message/parts replace the
four session/message* verbs; list is addressed by message ids (capped at
200) so a client fetches exactly the transcript session/get told it
about. session/get now reports the initiator the web gates suggestions
on, and the registry parity test runs unskipped.
The integration tests speak the new wire names; message/list takes ids
read off the persisted transcript. DESIGN.md describes the finish
reconcile as it is: poll message/get by id, then swap the transcript.
The store addresses message/list by the ids session/get carries, gates
the suggestions row to user-started sessions, and parents a spawn under
the source's own parent. A spawned selection now latches on a flag, so a
server-reported empty provider_model no longer re-seeds forever.
Condense verbose doc comments across api, db, agents, and web packages
to be more concise while preserving meaning. Apply small code
simplifications where the change is purely stylistic:

- Replace maps.Clone + maps.DeleteFunc with a single allocation loop in
  cleanAdditional
- Use cmp.Or for the two-field sort in GetMessagesByIDs
- Use slices.Backward in lastUserPrompt instead of a manual index loop
- Inline the redundant initiator validity check in CreateSubagentSession
- Simplify Initiator.Valid from a switch to a chain of comparisons
- Remove the redundant empty-task guard in spawnTool.Execute (the handler
  already rejects blank tasks before the decision call)
- Collapse the duplicated message column list into the shared
  messageColumns constant in db/message.go
- Inline the MessageListParams interface in web session store
The overview page now renders a per-family SVG gutter (rising elbow
branches, comb rails, lane rules, turn-count numerals, and dots) beside
each family's rows. Subagent rows collapse into one-line spur strips in
the gutter; fork rows remain full rows and are always visible.

API / store:
- OverviewSession gains `initiator` and `turn_count` (both omitempty).
- New `ListSessionTurnCounts` querier method counts role-"user" messages
  per session in one chunked query; the overview handler fetches counts
  for the page and threads them into the wire rows.
- `messageListMax` raised from 200 to 1000 to match the 20x OR-chain
  cap.
- `ListOverviewPage` no longer overwrites a root's `Updated` with its
  family's newest activity; rows keep their own stamp and the family
  activity is only the server's sort/cursor key.

Web:
- New `graph.ts` (pure geometry: post-order lane assignment, comb
  grouping, elbow path strings, timestamp interpolation) and
  `FamilyGraph.vue` (imperative SVG drawing beside measured rows).
- `days.ts` rewritten: `flattenRows` → `flatten` with newest-activity
  ordering inside each family, `familyBlocks` for gutter grouping,
  `foldLabel` for the collapsed-row count, and `Date.parse`-based time
  comparisons so RFC3339Nano stamps sort correctly.
- `OverviewView.vue` renders one family block per root with the graph
  gutter, subagent spur strips, and fold toggles.
- `spawnSession` now parents the new session under the source session
  directly (suggestions only fire for user-initiated rows), so a
  follow-up from a child nests under that child rather than its sibling.

Modes:
- New `Approach` field on `Mode` for per-mode thinking-order prose.
- Reworded shared fragment sentences (delegate, verify, gitRules, etc.)
  and replaced `TestModePrompt` with `TestBuiltinPromptGoldens` pinning
  both rendered prompts of every built-in mode.
Spawn now always returns immediately with the child's session ID,
eliminating the blocking wait path that serialized parallel spawns.
Results are collected via subagent_wait instead.

- Drop the `wait` field from spawnParams and the associated
  WaitSubagent call in spawnTool.Execute.
- Update spawn tool description to direct callers to use
  subagent_wait for result collection.
- Replace the four wait-related test cases (completed, failed,
  paused, still running, canceled) with a single "never waits"
  case asserting the immediate spawned shape.
- Update comments in wait.go and SubagentTool.vue to reflect that
  only subagent_message uses the waited shape.
Add per-binary TURSO_GO_CACHE_DIR overrides in agents, auth, db, and
server packages to prevent parallel test binaries from racing the
tursogo embedded .so extraction, which panics on a half-written file.

Also introduce awaitConn in branch/hub_test.go to eliminate a dispatch
race in the hello-less fs-verb tests: Serve installs the connection
after the websocket handshake, so a dispatch that fires before addConn
receives ErrUnavailable. The helper polls connFor until the branch is
registered.
The shared fragment constants in modes.go are rewritten to be more prescriptive:

- delegate: clarify that a subagent only sees the brief, and list what to
  include (goal, file paths, quoted code, constraints, report format).
- smallestChange: explicitly forbid refactoring or reformatting outside
  the change.
- verify: add "start with checks closest to your change", require
  confirming a failure is unrelated before moving on, and add a hard
  rule against weakening or deleting tests.
- verifyChild: give concrete examples (build affected package, run
  relevant tests) and require reporting exactly what was run.
- gitRules: expand the list of forbidden git commands (restore, merge,
  clean), and specify using a temporary directory for worktrees.
- commentStyle: add a rule against restating the code or narrating the
  change.
- readOnly: clarify that reading, searching, and read-only git are fine.

Test expectations in modes_test.go and modes/modes_test.go are updated
to match the new fragment text. The buildAgent call in
TestModeHashStaleness is updated to pass the new skillsHash and
CatalogHash arguments.
Introduce pkg/toolschema as a single home for the three helpers every tool
package was carrying privately (SchemaOf, Decode, JSON), and delete the
now-redundant internal/decode.go and the per-package copies in branch/tools,
subagent, skill, ask_question and web_search.

Branch tool hardening:
- web_fetch: refuse loopback, link-local, private-range and multicast
  destinations both at the URL level and at dial time (catching DNS
  rebinding), and vet every redirect hop.
- shell: clamp timeout_seconds to maxTimeout (10 min) before the
  multiplication to avoid overflow, and sweep the process group after a
  cancelled run so a SIGTERM-ignoring grandchild cannot outlive the call.
- sandbox: bound every host-binary probe (git, go, bwrap) with a 5 s
  timeout so a hung binary cannot wedge branch startup; re-stack nested
  read-only binds after their enclosing writable bind so the later bind
  wins; keep read-write precedence when a path is listed in both
  ro_paths and rw_paths.
- file_write: export CanonicalPath (formerly resolveTarget) and
  ExpandHome (formerly expandHome) so the branch fs verbs share the same
  symlink-resolution namespace as the sandbox gate.

Other:
- jsonrpc: add Calls.Route to deliver a peer response to the pending call
  keyed by envelope id, carrying a remote rpc error through.
- subagent: pass parentModeID through SpawnSubagent so the spawner can
  re-check the spawn permission rule against the parent's mode.
- skills: remove unused MergeEnabled helper.
- Add BusyBadge, PrimaryButton, and QuietButton components to eliminate
  repeated inline button and badge markup across admin, settings, session,
  and auth views.
- Introduce useBranchStore to centralize the connected-branch list, its
  load/error/loaded state, and the branch/updated invalidator; BranchMenu
  and MentionPalette now read from the store instead of each calling
  branch/list independently.
- Extract callAllPages into the API client so overview and archive stores
  share the cursor-walk logic instead of duplicating it.
- Add parseJSON helper to the session store and replace ad-hoc JSON.parse
  try/catch blocks in ShellTool, SubagentTool, WebSearchTool,
  ApprovalCard, and MessageList.
- Wrap the API client's fetch in a try/catch that converts network-level
  rejections into ApiError(0) so callers never see a bare TypeError.
- Make handleNotification async and log handler rejections instead of
  letting them escape as unhandled promise rejections.
- Remove unregisterInvalidator from the registry; the branch store
  registers its invalidator at module scope and never unregisters.
- Add withStore test helper that scopes a fresh Pinia instance alongside
  the fetch stub, reducing boilerplate in store-level tests.
- Refactor ModeEditor and CommandEditor to use a single reactive draft
  object with a seed function instead of parallel refs.
- Close the SharedWorker port on non-persisted pagehide to prevent
  leaked ports across HMR reloads.
- Simplify date formatting to use Intl.DateTimeFormat.format with
  comma stripping instead of manual formatToParts assembly.
- Remove the FOLD_LABEL constant and settle foldLabel to always count
  agent-initiated subagents only.
- api: shared read/upsert of UserConfigs rows under one lock, so
  concurrent command/mode edits no longer drop a write
- api: reject unknown params members, tighten key scope grammar,
  make key/create cookie-only, compare hosts port-stripped in CSRF
- auth: refuse unverified OIDC emails and link existing accounts by
  email instead of failing on the unique column
- janitor: purge user sessions past the 72h max lifetime
- tests: shared configStore fixture, per-run Turso cache dir
jd merged commit 54fe132db8 into main 2026-10-19 01:57:15 -04:00
jd deleted branch refactor/types 2026-10-19 01:57:16 -04:00
Sign in to join this conversation.
No reviewers
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
ersyne/ersa-agent!5
No description provided.