31 Commits

Author SHA1 Message Date
zhanghui
010ca4b44d
fix(*): probe raven web before launch and install plugins from the release list (#588)
## Summary

The one-line installers are served from `main` and install the latest
published release, so an ending on `raven web` (PR #476) shipped against
v0.1.13, which has no `web`: since 2026-09-17 every `curl
raven.evermind.ai/install.sh | sh` has ended in `No such command 'web'`
with exit code 2. This PR fixes that class of failure and the upgrade
defect behind the next release.

- **Probe rule.** Every `raven <sub>` call in `install.sh` and
`install.ps1` is preceded by `raven <sub> --help`. When the probe fails
the install ends on the one command every release has (`raven`), and
neither the stop nor the page's own exit code becomes the script's.
`RAVEN_NO_LAUNCH=1` skips the launch (CI, Dockerfiles); the PATH hint
the launch displaced is back.
- **The release says what it ships.** `release.yml` writes
`raven-plugins.txt`, one `name @ url` line per plugin wheel it just
built, beside the wheel and the constraints. Both installers derive
every URL from the release page redirect and hand the list to `uv tool
install --with-requirements`. No GitHub API call, no grepping asset
names out of its JSON. A release without a list (0.1.13 and older)
installs raven alone, as it effectively did before.
- **Upgrade keeps the plugins.** uv replaces a tool's requirement set
with what one command names, so the old helper (`raven[channels]` only)
uninstalled every plugin the installer had put in. The helper now
installs from the same list, descends one loss at a time (engines, then
the memory plugin, then the channel extras), and refuses to run without
the list rather than install raven alone. `raven upgrade` on an
up-to-date install whose list names a plugin it lacks reinstalls the
version with its plugins. The helper also moves a beta wheel URL's
deploy token into the request header (urllib reads `user:token@host` as
a host name) and copies it onto the list's URLs for uv.
- **Gates.** CI installs the latest release with the PR's scripts,
piped, on ubuntu and windows whenever an installer changes. The release
job installs itself from `dist/` with `install.sh` before the draft is
created and asserts the three plugin packages and `web` on the result.
The beta publisher builds and lists the same three plugin wheels. A
contract test holds the release workflow, the beta publisher, both
installers (remote list and local clone mode) and the helper to one
plugin list.

Decisions, for the reviewer: the plugins are not published to PyPI and
no names are reserved there; the list carries direct URLs, so no plugin
is ever resolved by name against an index. The LibreOffice and chromium
steps in the scripts are unchanged. The three hosted-memory plugins
(mem0, zep, memos) are built and uploaded as before but stay off the
default list.

## Type

- [x] Fix
- [ ] Feature
- [ ] Docs
- [ ] CI / tooling
- [ ] Refactor
- [ ] Other

## Verification

All installs below ran piped (`cat install.sh | sh`) in isolated
directories (own HOME, UV_TOOL_DIR, UV_TOOL_BIN_DIR, UV_CACHE_DIR,
RAVEN_HOME) with `RAVEN_MINIMAL=1`.

- `main`'s `install.sh` against the live latest release (v0.1.13): exit
2, `No such command 'web'`. This branch's `install.sh`, same
environment: exit 0, `Raven installed. Open a new terminal ... then run:
raven`; `raven --version` prints 0.1.13. With `RAVEN_NO_LAUNCH=1`: exit
0.
- A local release directory built by `scripts/publish_beta.py` (`_build`
at 0.1.14b1: raven wheel, three plugin wheels, constraints, list): this
branch's `install.sh` with `RAVEN_WHEEL_URL=file://...` installs raven
0.1.14b1, `python -c "import raven_everos, raven_design, raven_ppt"`
succeeds in the tool venv, and the uv receipt lists raven plus the three
plugins.
- The release workflow's two new step bodies (`Write the plugin list`,
`Install the release from dist with install.sh`) extracted and run
locally against that build: exit 0; removing one plugin wheel makes the
list step exit 1.
- The script's ending against the 0.1.14b1 install: `raven web --help`
exit 0, `raven web --stop` exit 0 with nothing to stop, `raven web
--foreground --port 18999` answers `GET /` with HTTP 200 after about 20
seconds.
- `uv run raven upgrade` and `uv run raven upgrade --check` from the
checkout against live GitHub: `Raven 0.1.13 is up to date.`, exit 0.
- `uv run pytest tests/integration/test_cli_upgrade_real_uv.py`: 2
passed. The test now installs the old fixture `--with` a companion wheel
and asserts the companion survives the upgrade; against `main`'s helper
the same test fails on that assertion.
- `uv run pytest tests/test_install_script.py
tests/test_release_plugin_list.py tests/test_updates_upgrade.py
tests/test_publish_beta.py tests/test_cli_smoke.py`: all pass (37 + 6 +
188 on the last run of each).
- `uv run pytest` (full suite, before the last installer rewrite): 23543
passed, 121 skipped, 4 failed. The 4 (`test_agents_oncall_launcher`,
`test_agents_code_launcher`, `test_agent_loop_token_budget`,
`test_ppt_engine_image_search`) fail identically on plain `github/main`
in a separate worktree.
- `uv run ruff check` and `uv run ruff format --check` on every touched
Python file: clean. `sh -n install.sh`, `bash -n install.sh`: clean.
Both workflow files parse.
- Not run here: the new CI job's Windows leg and the release gate inside
GitHub Actions (this PR is their first run). `install.ps1` has no local
PowerShell to execute it; its changes mirror `install.sh` and are pinned
by the text tests.

- [x] Relevant tests pass locally
- [x] Relevant lint / type checks pass locally
- [ ] User-facing docs or screenshots are updated when needed

## Risk

User-visible changes: the installers no longer fail on a release without
`web`; they print the plugins they install and a warning when a release
carries none; `raven upgrade` refuses to proceed when the target
release's plugin list cannot be fetched (previously it would install
raven alone and drop the plugins), and repairs an up-to-date install
that lacks listed plugins. The beta channel's next publish carries the
three plugin wheels and the list; a beta upgrade to a build published
before this change will refuse for lack of a list, and rerunning the
beta installer is the remedy.

Rollback: revert the commit. Releases published with `raven-plugins.txt`
keep working with the old scripts, which ignore the file.

- [x] Security impact considered
- [x] Backward compatibility considered
- [x] Rollback path is clear for risky changes

## Related Issues

N/A

---------

Co-authored-by: Claude (claude-fable-5-1) <noreply@anthropic.com>
2026-09-21 16:25:33 +08:00
Handsome-wzw
7b45527b5b fix(tools): an array sent as its own JSON is still an array
## Summary

Reported as "deliver_files is broken". It is not: **the tool never ran.**

Every `deliver_files` call on one install was refused before dispatch -- five in a row in a single session -- and nothing was ever delivered:

```
Error: Invalid parameters for tool 'deliver_files': files should be array
```

What the model sent was the array, spelled as a string:

```json
{"files": "[{\"path\": \"...poster.png\", \"title\": \"...\"}]", "message": "..."}
```

`cast_params` already forgives that spelling for every scalar type -- `"3"` for an integer, `"true"` for a boolean -- and did not for arrays or objects, which are exactly the types a model is most likely to stringify.

## Type

- [x] Fix
- [ ] Feature

## The edge of the forgiving is the design

When the value is a string, try `json.loads`, and take the result **only if it is the type the schema asked for**. A string that is not JSON, or is JSON of the wrong shape, is returned unchanged so the validator still names the real problem -- the point is to widen what is accepted, not to swallow a type error.

**Nothing here can raise.** Turning "your argument has the wrong type" into a traceback would be worse than the refusal it replaces, so the parse is wrapped and failure falls through.

**A `type: "string"` field is never parsed.** JSON is ordinary text in a message body or a file's content, and replacing it would hand the tool something it never asked for. Two independent things prevent it today (the string branch returns before the parse is reached, and the parse only wins on a type match), which is why the case pinning it is a tripwire rather than a load-bearing assertion -- said so in its own docstring rather than left to look like coverage.

## Not just deliver_files

Six built-in tools declare an array or object parameter and were all exposed:

| tool | parameter |
|---|---|
| `deliver_files` | `files` |
| `ask_user` | `questions` |
| `image_generate` | `images` |
| `message` | `media` |
| `create_playbook` | `skills` |
| `video_generate` | `params` |

The same failure was already seen from the other side: `acp_client/acp_agent.py` records `update_task_state` and `operations should be array` from a real dispatch.

## Verification

```
make lint-python    ruff check + ruff format --check, 1850 files
make lint-imports   9 contracts kept, 0 broken
pytest tests/       19,699 passed, 7 failed (all pre-existing, see below)
```

- [x] Relevant tests pass locally
- [x] Relevant lint / type checks pass locally
- [ ] User-facing docs or screenshots -- no user-facing string

**End to end, through the real tool**, with the exact payload that failed five times in production:

```
files sent as:            str -> [{"path": ".../poster.png", "title": "..."}]
returned:                 Delivered 1 file(s): poster.png (72 B).
still "should be array":  False
registered in the store:  True
```

Twelve cases, five mutations, each killing at least one:

| mutation | red |
|---|---|
| drop the whole branch (the old behaviour) | 3 |
| raise instead of falling through on a parse failure | 5 |
| accept the parse whatever type it yielded | 1 |
| do not re-cast the parsed value, so items are not cast | 1 |
| widen the tuple to include `string` | **survived -- unreachable** |

The last is worth stating rather than hiding: that mutation cannot change behaviour, because the `type == "string"` branch returns earlier and the type check would refuse the result anyway. I also tried moving the new block above that branch, alone and combined with widening the tuple, and neither reddens anything either. The invariant holds by construction; the case that documents it says so.

**Pre-existing failures, checked against the base.** 7 failed in the full run, all in `tests/test_security_network.py` (`test_a_redirect_to_a_dangerous_address_is_refused` and siblings). Running that file alone on this same tree gives 4 -- the count is order-dependent -- and the change touches only `raven/agent/tools/params.py` plus a new test file, neither of which `raven/security/network.py` imports. The failures are the box's resolver: it returns poisoned answers roughly half the time, which I measured separately (`en.wikipedia.org` came back as `2001::1` on 3 of 6 lookups). Not introduced here, and worth someone's attention on its own.

## Risk

- [x] Security impact considered -- widens what reaches a tool's own validation, not what bypasses it. A parsed value is still validated against the same schema, and a parse that yields the wrong type is refused exactly as before
- [x] Backward compatibility considered -- a call that worked before takes the identical path; the new branch is reached only by a `str` where an array or object is declared, which previously always failed
- [x] Rollback path is clear -- single-commit revert

## Related Issues

N/A

## Swept

`mr-review-patterns` pre-submit sweep, over `git diff origin/main...HEAD`.

- **1 (a write location moved)** -- nothing moved; a branch was added to an existing dispatch on `target_type`. Grepped every caller of `cast_params`: the registry is the only one, and it runs `validate_params` right after, which is the reader this affects.
- **2 (a value with several entry points)** -- the cast is the single funnel every tool argument passes through, which is why the fix belongs here and not in `deliver_files`.
- **3 (a guard)** -- checked both directions: what it wrongly lets through (JSON of the wrong type, non-JSON text -- both refused, with cases) and what it wrongly refuses (a real list, unaffected, with a case).
- **4 (tests)** -- five mutations above, one honestly reported as unreachable. Failing-ID sets diffed against the base rather than counts.
- **6 (stale text)** -- the module docstring enumerated what is coerced ("a string that should be an integer"); it now names arrays and objects too. Grepped the tracked tree for other statements of the rule: none.
- **9 (error handling)** -- the new path adds one way to end and it is caught: `json.loads` raises `ValueError` on bad text and `TypeError` on a non-string, and both fall through to the untouched value.
- **11** -- `git ls-files | grep -c node_modules` is 0; the commit-message gate was run, not eyeballed.

Not applicable, with reasons: **3b, 3c, 3d, 3e** (no tool schema produced, no state moved, one lane, no assertion lost its symbol); **4b, 4c, 4d** (no platform branch, no shell, no rendered number); **5, 5b** (no dependency; `json` is stdlib and already imported across this package); **6b, 6c** (no backup, no generated artifact); **7, 7b** (nothing on disk); **8** (no asset, no secret); **10** (no prompt text).

## Deliberately not fixed

The error text still ends with `[Analyze the error above and try a different approach.]`, and the model plainly did not -- it sent the same shape five times. A message naming the expected spelling (`files must be a JSON array, not a string containing one`) would give it something to act on. That is a change to the registry's error surface, affects every tool, and deserves its own argument.

## Moved from !594

Opened on a compliant source branch. AGENTS.md 2.1 asks for a 3-5 word snake_case description and the previous branch had seven; GitLab cannot change an existing merge request's source branch, so the change moves rather than the name.

Same commits, rebased onto `c2a9768f`. Both code findings from the review on !594 are already in them -- `RecursionError` caught with its regression case, and the implementation comment reduced to the two non-obvious reasons. Nothing else changed, so that review carries.
2026-09-09 15:42:36 +00:00
forrestjgq
f01231fef6 fix(cli): overhaul trajectory browser interaction ux (#379)
## Summary

Overhaul the interactive `raven trajectory` browser end to end, fixing
every
issue from real-terminal testing:

- Navigation: every screen opens with a help area under its title (page
  purpose plus "[Key] function" hotkey hints, rendered in a new readable
help color). Esc walks one level up (action -> attempt -> session); on
the
top-level session screen Esc stays put and quitting is Ctrl+C only,
which
prints a single exit notice. Esc inside a running action cancels just
that
action through a dedicated exception at the action boundary, so the back
  sentinel can never reach a conversion or the data layer; a cancelled
  report keeps its pre-confirm bundle-and-pin side effects (the existing
  declined-report contract). Back/Exit menu entries are gone; answered
  prompts erase themselves and navigation is echoed as breadcrumb lines
  with markup-escaped untrusted text.
- Tables: the session list is TITLE | ATTEMPTS | LAST ACTIVITY and the
  attempt list is # | STARTED | TURNS | SPANS | VERDICT | PIN | MERGED |
PREVIEW with green check cells. Time cells keep the year. The layout is
  budgeted per screen build from the live terminal width (row indent, a
safety margin, and inter-column gaps are all part of the math); PREVIEW
  drops as a whole column when it no longer fits, and below the dynamic
  minimum width the tightest layout is kept while the renderer clips
  overlong lines at the terminal edge. Every dynamic cell passes a
  single-line sanitization gate before width math (verdict sidecars only
  guarantee a non-empty string), cells are measured and truncated by
terminal display width (CJK is 2 cells), and fixed column widths always
  fit their headers.
- Space preview: Space on an attempt row prints that attempt's per-turn
input/output previews, collected in the same snapshot scan and sorted by
a fully-stringified key so ordering never follows log source order (the
  table PREVIEW cell derives from the same sorted collection). Any key,
arrow keys included, returns with the cursor kept on the row; the waiter
  passes the terminal's CPR reply through to the renderer instead of
  treating it as a keypress, and Ctrl+C keeps the browser-wide cancel.
- Merge hotkey: with two or more attempts, m/M opens the multi-select
merge
  (advertised in the help line; the old "Merge attempts" menu entry is
gone). The checkbox screen carries its own help line for toggle,
confirm,
  and cancel. A single attempt neither binds nor advertises the key.
- Theme and feel: new success (green check) and help (readable hint
text)
colors in both palettes, all WCAG AA on their backgrounds; a lone ESC is
flushed after 50ms instead of prompt_toolkit's 0.5s default, removing
the
  laggy Esc feel.

The data layer is untouched: changes are confined to
raven/cli/trajectory_browse.py, raven/cli/_theme.py, and their tests.
The
id-taking subcommands (raven trajectory save/list/...) behave as before.

## Type

- [x] Fix
- [ ] Feature
- [ ] Docs
- [ ] CI / tooling
- [ ] Refactor
- [ ] Other

## Verification

- `COLORTERM=truecolor uv run pytest tests/test_cli_theme.py
tests/test_cli_trajectory_browse.py
tests/test_cli_trajectory_commands.py -q` -> 220 passed
- `COLORTERM=truecolor uv run pytest tests/ --ignore=tests/integration
-q` -> 6917 passed; the 10 failed + 20 errors are the pre-existing
environment-dependent set, identical file-by-file on a clean main
checkout (cron, everos server, config loader, tracing viewer)
- `uv run ruff check` and `uv run ruff format --check` on the four
touched files -> clean
- PTY smoke on a CPR-answering pseudo terminal at 100 and 58 columns:
full flow (preview, merge cancel, action screen, staged Esc backout,
Ctrl+C quit) and the narrow-width degradation contract
- New coverage includes real pipe-input key-binding tests (Esc on all
four prompt kinds, Space/m/M hits, waiter key paths with CPR
pass-through), table budget/clipping boundaries at the computed minimum
width, and corrupt verdict/timestamp corpora

- [x] Relevant tests pass locally
- [x] Relevant lint / type checks pass locally
- [x] User-facing docs or screenshots are updated when needed

## Risk

- The interactive browser's look and key protocol change wholesale (that
is
  the point of this PR): Esc no longer quits from the top level (Ctrl+C
  does), Back/Exit entries are gone, and lists render as tables. The
machine-facing subcommands and the trajectory data layer are untouched.
- Rollback: revert the squash commit; the browser returns to the
previous
  interaction wholesale, no data migration involved.

- [x] Security impact considered
- [x] Backward compatibility considered
- [x] Rollback path is clear for risky changes

## Related Issues

N/A

---------

Co-authored-by: 江国庆 <guoqingjiang@deepglint.com>
Co-authored-by: Claude (claude-fable-5) <noreply@anthropic.com>
2026-09-05 23:58:20 +08:00
0xKT
28299e5f0e fix(*): relays on the page lane, live direct chats reported, continuation heads cut
## Summary

Four sub-agent orchestration defects found on 2026-09-08 while running the research
sub-agent from the TUI and the page; all share one root, the host loop not seeing what
its sub-agents are doing right now.

1. A sub-agent's result relay into a page session ran on the gateway spine while the
   page's own turns to that session ran on the RPC spine, so a relay and a user turn ran
   at once: the same tool calls were drawn twice and the result delivered twice, and
   `turn.send`'s one-turn-per-session guard saw neither. The RPC stack now exposes its
   turn scheduler (`RpcStack.turn_scheduler`, surfaced on `PageMount.submit`), and
   `raven.gateway.submit_router.route_submit` hands turns whose conversation carries
   the page prefix (`tui:`) to the page lane and everything else to the gateway lane.
   The sub-agent manager and the deep-research submit both take the routed callable;
   a gateway without a page keeps the gateway submit unchanged.

2. The watch-work judgement (one model call on a turn's first look) was paid on relay
   and sentinel turns, whose "last user message" is the runtime's re-injected report,
   and ran unbounded: one relay turn spent 1229 seconds in it on a reasoning runaway.
   The turn's origin now reaches the loop; a re-injected origin (SUBAGENT, SENTINEL)
   reads as no request, and the judgement is cut at 60 seconds and treated as no
   verdict. CRON and heartbeat turns are deliberately still judged: their text is the
   owner's own instruction.

3. The direct-chat handoff recorded a turn only when it landed, so an instance the user
   was mid-conversation with rendered to the main agent as "no turns yet"; the model
   read that as free and spawned onto it. The handoff now reads the manager's live
   direct turns (`live_direct_turns`) and renders an answering instance with the time
   it began answering (handle lock held) and a line saying it is the user's conversation. The spawn that lands
   behind such a turn no longer writes `running` before it holds the handle lock (it
   stays the `pending` it was announced as), and no longer takes over the instance's
   live view: `activity.watching_instance` registers only when the slot is free and
   pops only what it registered, so the direct chat's steps stay on screen and the
   spawn's appear once it runs.

4. When reasoning ran to the model's output ceiling with no content and the
   empty-response recovery fed it back as a prefill, the continuation opened on the
   rest of the cut thought and that fragment streamed and was stored as the head of the
   answer. `cut_reasoning_head` drops an opening fragment that starts in lowercase or
   whitespace and ends at the first sentence or line boundary within 200 characters;
   `ContinuationGate` holds streamed deltas until the same rule can decide, so what the
   reader sees matches what the session stores. Only a continuation after
   ceiling-cut reasoning (`finish_reason == "length"`) is treated this way.

Decisions worth knowing:

- The `tui:` prefix is spelled in `raven.gateway.submit_router` and as
  `RoutingQuestionBroker`'s default; the layer contract keeps `raven.gateway` from
  importing `raven.rpc`, so a test holds the two equal instead of one importing the
  other.
- The gateway wiring has no import seam, so its test pins the source of the mounted
  block, the same way the neighbouring cron-partition test does.
- The `subagent.status` payload shape is unchanged; only the `running` frame's timing
  moved (after the handle lock). The page's spawn card reads identity from `pending`
  and the record id from `running`, both still present.
- A CJK boundary class in the head-cut regex is spelled as escapes because the
  source-language gate reads the literal marks as non-English source.

Review round 1 (all findings non-blocking, all taken):

- The lane key is now one definition, `raven.spine.conversation_id`; the scheduler's
  method, the rpc spine and the submit router call it, and the router test pins the
  identity and compares against the scheduler's method instead of literals.
- The loop's wiring of the handoff to the manager's live turns has its own test (a bare
  `DirectChatHandoff()` went green before).
- `activity.live_instances_of` is gone: nothing called it.
- The watch-work judgement now reads any exception as no verdict, not only a timeout.
  The enclosing handler already kept the turn alive, but left the verdict unset, so a
  failing judgement was paid again on every path-touching tool call; the comment that
  claimed a raise was handled is corrected.
- A direct chat's start time is stamped once the handle lock is held, not when the slot
  is claimed, so a chat queued behind another holder is not reported as answering.
- The continuation cut deliberately leaves a continuation that opens directly on CJK
  whole (no case, so no mid-sentence signal); the comment and a test now say that the
  CJK stops end an admitted fragment rather than open one.

## Type

- [x] Fix
- [ ] Feature
- [ ] Docs
- [ ] CI / tooling
- [ ] Refactor
- [ ] Other

## Verification

```
uv run pytest tests -q -p no:cacheprovider -n 8 --ignore=tests/integration
  -> 7 failed, 19705 passed, 153 skipped. The same 7 fail on a detached origin/main
     worktree through the same interpreter (doctor memories path 1, NAT64 resolution 4,
     design-engine rendering 2): 0 introduced.
uv run pytest tests/test_agent_loop_empty_recovery.py tests/test_watch_work.py \
  tests/test_gateway_submit_router.py tests/test_subagent_activity.py \
  tests/test_subagent_handoff.py tests/test_subagent_direct_chat.py \
  tests/test_rpc_bootstrap.py tests/test_cli_gateway_page.py tests/test_cli_gateway_commands.py
  -> 279 passed (before round 1); round 1 adds 5 tests and removes 1, see the pipeline
uv run ruff check raven tests; uv run ruff format --check raven tests   -> clean
uv run lint-imports                                                       -> 9 kept, 0 broken
make check-source-language                                                -> exit 0
scripts/check_commit_messages.py origin/main..HEAD                        -> exit 0
```

Red-checked (fix reverted, test goes red, fix restored): activity.py alone reverted
-> `a second lane never unseats the first`; the spawn-path hunk of manager.py alone reverted
-> `['pending', 'running'] == ['pending']`; turn_path.py alone reverted -> the continuation
test sees the `Lagg in an token` head. Round 1: the handoff wiring test goes red on a bare
`DirectChatHandoff()`; the queued-direct-chat test goes red with the stamp back on the slot;
the raising-judgement test goes red with the narrow catch (two calls instead of one). The other new tests fail without their change by
construction (missing symbol or signature), which proves less and is noted as such.

Live check of the shipped page: the served `ui-web/dist` bundle booted under happy-dom in
stub and live mode against a gateway running this branch, desk mounted, no console
errors; `subagents.list` and `subagents.instances` answer as before.

- [x] Relevant tests pass locally
- [x] Relevant lint / type checks pass locally
- [x] User-facing docs or screenshots are updated when needed (CHANGELOG, CONTEXT.md
      Handoff Block)

## Risk

- A relay into a page session now waits behind the page's running turn on that session
  instead of running beside it. That is the intended serialisation; the cost is latency
  on a relay while a long page turn runs.
- A judgement that takes over 60 seconds is dropped and the turn runs unwatched for
  that turn only; before, the same turn hung. No configuration knob: the bound is a
  class attribute.
- The head cut only runs on the continuation after a ceiling-cut prefill. A
  continuation whose intended answer begins with a lowercase word and a full stop within
  200 characters would lose that first clause; the test file names the shapes kept.
- Rollback: revert the squash commit. No persisted format changes.

- [x] Security impact considered (no new surface; routing stays in-process)
- [x] Backward compatibility considered (payload shapes unchanged; a gateway without a
      page mount is unaffected)
- [x] Rollback path is clear for risky changes

## Related Issues

N/A
2026-09-09 06:25:28 +00:00
userName20260323
50ad9377bd fix(*): relays on the page lane, live direct chats reported, continuation heads cut
## Summary

Four sub-agent orchestration defects found on 2026-09-08 while running the research
sub-agent from the TUI and the page; all share one root, the host loop not seeing what
its sub-agents are doing right now.

1. A sub-agent's result relay into a page session ran on the gateway spine while the
   page's own turns to that session ran on the RPC spine, so a relay and a user turn ran
   at once: the same tool calls were drawn twice and the result delivered twice, and
   `turn.send`'s one-turn-per-session guard saw neither. The RPC stack now exposes its
   turn scheduler (`RpcStack.turn_scheduler`, surfaced on `PageMount.submit`), and
   `raven.gateway.submit_router.route_submit` hands turns whose conversation carries
   the page prefix (`tui:`) to the page lane and everything else to the gateway lane.
   The sub-agent manager and the deep-research submit both take the routed callable;
   a gateway without a page keeps the gateway submit unchanged.

2. The watch-work judgement (one model call on a turn's first look) was paid on relay
   and sentinel turns, whose "last user message" is the runtime's re-injected report,
   and ran unbounded: one relay turn spent 1229 seconds in it on a reasoning runaway.
   The turn's origin now reaches the loop; a re-injected origin (SUBAGENT, SENTINEL)
   reads as no request, and the judgement is cut at 60 seconds and treated as no
   verdict. CRON and heartbeat turns are deliberately still judged: their text is the
   owner's own instruction.

3. The direct-chat handoff recorded a turn only when it landed, so an instance the user
   was mid-conversation with rendered to the main agent as "no turns yet"; the model
   read that as free and spawned onto it. The handoff now reads the manager's live
   direct turns (`live_direct_turns`) and renders an answering instance with the time
   it began answering (handle lock held) and a line saying it is the user's conversation. The spawn that lands
   behind such a turn no longer writes `running` before it holds the handle lock (it
   stays the `pending` it was announced as), and no longer takes over the instance's
   live view: `activity.watching_instance` registers only when the slot is free and
   pops only what it registered, so the direct chat's steps stay on screen and the
   spawn's appear once it runs.

4. When reasoning ran to the model's output ceiling with no content and the
   empty-response recovery fed it back as a prefill, the continuation opened on the
   rest of the cut thought and that fragment streamed and was stored as the head of the
   answer. `cut_reasoning_head` drops an opening fragment that starts in lowercase or
   whitespace and ends at the first sentence or line boundary within 200 characters;
   `ContinuationGate` holds streamed deltas until the same rule can decide, so what the
   reader sees matches what the session stores. Only a continuation after
   ceiling-cut reasoning (`finish_reason == "length"`) is treated this way.

Decisions worth knowing:

- The `tui:` prefix is spelled in `raven.gateway.submit_router` and as
  `RoutingQuestionBroker`'s default; the layer contract keeps `raven.gateway` from
  importing `raven.rpc`, so a test holds the two equal instead of one importing the
  other.
- The gateway wiring has no import seam, so its test pins the source of the mounted
  block, the same way the neighbouring cron-partition test does.
- The `subagent.status` payload shape is unchanged; only the `running` frame's timing
  moved (after the handle lock). The page's spawn card reads identity from `pending`
  and the record id from `running`, both still present.
- A CJK boundary class in the head-cut regex is spelled as escapes because the
  source-language gate reads the literal marks as non-English source.

Review round 1 (all findings non-blocking, all taken):

- The lane key is now one definition, `raven.spine.conversation_id`; the scheduler's
  method, the rpc spine and the submit router call it, and the router test pins the
  identity and compares against the scheduler's method instead of literals.
- The loop's wiring of the handoff to the manager's live turns has its own test (a bare
  `DirectChatHandoff()` went green before).
- `activity.live_instances_of` is gone: nothing called it.
- The watch-work judgement now reads any exception as no verdict, not only a timeout.
  The enclosing handler already kept the turn alive, but left the verdict unset, so a
  failing judgement was paid again on every path-touching tool call; the comment that
  claimed a raise was handled is corrected.
- A direct chat's start time is stamped once the handle lock is held, not when the slot
  is claimed, so a chat queued behind another holder is not reported as answering.
- The continuation cut deliberately leaves a continuation that opens directly on CJK
  whole (no case, so no mid-sentence signal); the comment and a test now say that the
  CJK stops end an admitted fragment rather than open one.

## Type

- [x] Fix
- [ ] Feature
- [ ] Docs
- [ ] CI / tooling
- [ ] Refactor
- [ ] Other

## Verification

```
uv run pytest tests -q -p no:cacheprovider -n 8 --ignore=tests/integration
  -> 7 failed, 19705 passed, 153 skipped. The same 7 fail on a detached origin/main
     worktree through the same interpreter (doctor memories path 1, NAT64 resolution 4,
     design-engine rendering 2): 0 introduced.
uv run pytest tests/test_agent_loop_empty_recovery.py tests/test_watch_work.py \
  tests/test_gateway_submit_router.py tests/test_subagent_activity.py \
  tests/test_subagent_handoff.py tests/test_subagent_direct_chat.py \
  tests/test_rpc_bootstrap.py tests/test_cli_gateway_page.py tests/test_cli_gateway_commands.py
  -> 279 passed (before round 1); round 1 adds 5 tests and removes 1, see the pipeline
uv run ruff check raven tests; uv run ruff format --check raven tests   -> clean
uv run lint-imports                                                       -> 9 kept, 0 broken
make check-source-language                                                -> exit 0
scripts/check_commit_messages.py origin/main..HEAD                        -> exit 0
```

Red-checked (fix reverted, test goes red, fix restored): activity.py alone reverted
-> `a second lane never unseats the first`; the spawn-path hunk of manager.py alone reverted
-> `['pending', 'running'] == ['pending']`; turn_path.py alone reverted -> the continuation
test sees the `Lagg in an token` head. Round 1: the handoff wiring test goes red on a bare
`DirectChatHandoff()`; the queued-direct-chat test goes red with the stamp back on the slot;
the raising-judgement test goes red with the narrow catch (two calls instead of one). The other new tests fail without their change by
construction (missing symbol or signature), which proves less and is noted as such.

Live check of the shipped page: the served `ui-web/dist` bundle booted under happy-dom in
stub and live mode against a gateway running this branch, desk mounted, no console
errors; `subagents.list` and `subagents.instances` answer as before.

- [x] Relevant tests pass locally
- [x] Relevant lint / type checks pass locally
- [x] User-facing docs or screenshots are updated when needed (CHANGELOG, CONTEXT.md
      Handoff Block)

## Risk

- A relay into a page session now waits behind the page's running turn on that session
  instead of running beside it. That is the intended serialisation; the cost is latency
  on a relay while a long page turn runs.
- A judgement that takes over 60 seconds is dropped and the turn runs unwatched for
  that turn only; before, the same turn hung. No configuration knob: the bound is a
  class attribute.
- The head cut only runs on the continuation after a ceiling-cut prefill. A
  continuation whose intended answer begins with a lowercase word and a full stop within
  200 characters would lose that first clause; the test file names the shapes kept.
- Rollback: revert the squash commit. No persisted format changes.

- [x] Security impact considered (no new surface; routing stays in-process)
- [x] Backward compatibility considered (payload shapes unchanged; a gateway without a
      page mount is unaffected)
- [x] Rollback path is clear for risky changes

## Related Issues

N/A
2026-09-09 06:25:28 +00:00
daoxize1
5ee8a14f43 feat(rpc): attribute and filter usage by task
## Change description

Attach session and root-task identifiers to usage records. Propagate ownership through ACP child agents and asynchronous tool execution so recorded child usage can be attributed to its parent task.

Add a task selector to the usage settings page, including task titles and an all-tasks view. Prevent stale requests from replacing the selected task's results. Historical records without task identifiers remain visible only in the aggregate view.

Include usage recorded by child agents and the built-in image tool in the owning task. Extend the usage RPC schema and generated clients, and bump the contract version for the root-task field.

Validation:

- `uv run pytest tests/test_token_wise_usage_tracker.py tests/test_rpc_contract_shapes.py tests/test_subagent_acp_mcp_lifecycle.py tests/test_rpc_schema_match.py tests/test_kernel_budget.py tests/test_contracts_two_tier_ledger.py tests/test_media_gen_tool.py -x`: 498 passed.
- `npm --prefix ui-web test -- --run src/features/settings/SettingsPage.test.tsx`: 46 passed.
- `npm --prefix ui-web run type-check`: passed.
- `make lint-python`, `make check-source-language check-large-files`, and `git diff --check`: passed.
- Both repository commit-message checks passed.

## Type of change

- [ ] Bug fix
- [x] New feature
- [ ] Document
- [ ] Others

## Related issues (if there is)

N/A

## Checklists

### Development

- [x] Lint rules pass locally
- [x] Application changes have been tested thoroughly
- [x] Automated tests covering modified code pass

### Security

- [x] Security impact of change has been considered
- [x] Code follows company security practices and guidelines

### Code review

- [x] Merge request has a descriptive title and context useful to a reviewer. Screenshots or screencasts are attached as necessary
- [ ] Merge request linked to JIRA ticket when applicable

No related JIRA ticket was supplied.
2026-09-09 04:15:30 +00:00
daoxize1
135312987b feat(rpc): attribute and filter usage by task
## Change description

Attach session and root-task identifiers to usage records. Propagate ownership through ACP child agents and asynchronous tool execution so recorded child usage can be attributed to its parent task.

Add a task selector to the usage settings page, including task titles and an all-tasks view. Prevent stale requests from replacing the selected task's results. Historical records without task identifiers remain visible only in the aggregate view.

Include usage recorded by child agents and the built-in image tool in the owning task. Extend the usage RPC schema and generated clients, and bump the contract version for the root-task field.

Validation:

- `uv run pytest tests/test_token_wise_usage_tracker.py tests/test_rpc_contract_shapes.py tests/test_subagent_acp_mcp_lifecycle.py tests/test_rpc_schema_match.py tests/test_kernel_budget.py tests/test_contracts_two_tier_ledger.py tests/test_media_gen_tool.py -x`: 498 passed.
- `npm --prefix ui-web test -- --run src/features/settings/SettingsPage.test.tsx`: 46 passed.
- `npm --prefix ui-web run type-check`: passed.
- `make lint-python`, `make check-source-language check-large-files`, and `git diff --check`: passed.
- Both repository commit-message checks passed.

## Type of change

- [ ] Bug fix
- [x] New feature
- [ ] Document
- [ ] Others

## Related issues (if there is)

N/A

## Checklists

### Development

- [x] Lint rules pass locally
- [x] Application changes have been tested thoroughly
- [x] Automated tests covering modified code pass

### Security

- [x] Security impact of change has been considered
- [x] Code follows company security practices and guidelines

### Code review

- [x] Merge request has a descriptive title and context useful to a reviewer. Screenshots or screencasts are attached as necessary
- [ ] Merge request linked to JIRA ticket when applicable

No related JIRA ticket was supplied.
2026-09-09 04:15:30 +00:00
0xKT
231b270dd7 refactor(*): the vendored subagents tree retires and agents/ is the one home
## Summary

Retires the vendored fork tree (`subagents/`, ~7,500 files) and makes `agents/` the one home for the five agent products. The products were already thin launchers that render a config and exec the installed raven's own `raven acp`; this PR removes the frozen fork checkouts they replaced, migrates every consumer, and keeps the A/B verification power as byte snapshots.

Key decisions:

- **A side becomes a record.** The fork trees are deleted; the files the parity guards compare against live on as byte snapshots under `tests/fixtures/vendored_fork/` (added to ruff's exclude so a record can never be reformatted). The research flow's oracle is the fork's frozen measurement (`research_parity_probe.json`), a constant by construction.
- **Config floors v6 and v7.** Stored roster rows that pointed into the retired tree are migrated in place (floor six): rows whose folder maps to a shipped product are re-aimed at `agents/`, fork-era rows that cannot be re-aimed are left untouched and reported, unparseable rows get a fix-by-hand notice. Verdict-driven, path-root anchored, with a stamped sidecar so each pass runs once.
- **The research product reclaims its name (floor seven).** The `-NG` suffix existed only to coexist with the fork's own row, so it retires with the fork: registered `Raven-Research-NG` rows rename to `Raven-Research` on load; if a fork-era row still holds the name, the advisory repeats and the stamp holds at floor six, so the rename completes on a later load once the name frees (never two rows under one name). Display name only -- the machine id `raven-research-ng` (state root, ACP home, everos identity, the `RESEARCH_NG_*` variables) is a stable key and stays. The v6 name gate maps the research folder to None (never re-aim): the fork's research rows were cli-kind on a different flow, and after the rename a name match would select exactly the rows the gate exists to refuse.
- **Guards retire with their subject.** The vendored-invariant and vendored-subagents guard suites, their Makefile/pre-commit/CI hooks, and the fork-era install stage in `install.sh` are removed. The external-consumer tripwire now derives the promised surface from the five product installers and the charter's uninstall recipe (`add_third_party_subagent` and `remove_third_party_subagent` today) instead of restating a list that goes stale; the fork-era pin count (eight names) retired with its consumers, and `get_third_party_subagents` stays only as a courtesy to fork-era installer copies already carried into raven homes.
- **Wheel and sdist slim down.** The wheel force-includes `agents/` file-by-file from the git index (filled-in `.env` files are refused). The sdist shrinks 93.2 MB -> 2.76 MB (-97%).
- **Docs speak one era.** AGENTS.md, CONTEXT.md, README, CHANGELOG, the demo READMEs, and the RPC field descriptions (models.py -> openrpc.json -> both generated clients) describe the product tree in the present and the fork in the past.

## Type

- [ ] Fix
- [ ] Feature
- [ ] Docs
- [ ] CI / tooling
- [x] Refactor
- [ ] Other

## Verification

- Controlled A/B on a clean bench, same machine and env fingerprint, at the current pair: base 19,938 passed / 137 skipped / 0 failed vs branch 19,796 / 137 / 0, skip roster identical line by line. The -142 delta equals the collection delta and reconciles file by file: -159 across the twelve retired or trimmed test files, +9 floor-six migration tests, +8 floor-seven tests. The branch diff is fingerprint-stable across rebases (`git patch-id --stable` verified pairwise), so the reconciliation transfers to later bases. A second fingerprint (dev worktree env) shows 19,555 / 148 / 2 at the final tip; the 2 are `test_design_engine_rendering_outcome` renders hitting a local playwright-home quirk -- on the clean bench both sides skip them identically ("no system chromium"), and the branch does not touch that file.
- `uv run pytest tests/integration/test_research_subagent_smoke.py -m integration`: 2 passed (the smoke now drives the migrated product launcher end to end).
- `make lint-python` (ruff check + format), `make lint-imports` (tail line: `Contracts: 9 kept, 0 broken.` -- the ninth contract landed on main mid-branch), `make check-large-files`: all green.
- `npm run lint:rpc --prefix ui-tui` and `npm run gen:check --prefix ui-web`: generated clients in sync with `rpc-schema/openrpc.json`.
- `bash -n install.sh`: clean.
- Wheel built from the branch, installed into a clean venv: onboarding discovers the five products, and a filled-in `.env` placed in the tree fails the build (secrets refusal probed).
- Real-config upgrade rehearsal on a genuine floor-5 home config (owner present): the migration stamped the sidecar to 6, rewrote nothing (the five product rows were already registered against `agents/`; the one fork-era orphan row got its advisory notice and was left untouched), a second load was silent, and the upgraded config served a live probe plus one full one-shot agent turn. The floor-seven rehearsal on the same config renamed its one transition row (a one-line diff against the byte backup), stamped seven, was silent on the second load, and left the machine ids and the row's command untouched.

- [x] Relevant tests pass locally
- [x] Relevant lint / type checks pass locally
- [x] User-facing docs or screenshots are updated when needed

## Risk

- User-visible: on first load of a pre-v6 config, roster rows pointing into the retired tree are re-aimed at the product tree, with a one-line `Migrated` notice per changed row and a cleanup hint for the stale on-disk copy. Rows the migration cannot decide are reported, never rewritten. The floor-seven rename tells once per changed row too; only a blocked rename repeats its advisory, deliberately, until the blocking row is gone. While the block holds, the roster shows the discovered `Raven-Research` row beside the stored `Raven-Research-NG` row -- same launcher, same state root, no state split -- and converges to one row once the name frees.
- Rollback: revert the squash commit. The fork trees return from git history, and a config the migration already re-aimed keeps working on both sides of the revert: the wheel carries `agents/` before and after (that packaging landed separately), so no config rollback is needed. Rows the migration could not decide were never rewritten, and the version sidecar is additive.
- Packaging: a wheel built from an sdist (what a combined `uv build` does) carries no agent products by design -- the sdist has no `.git` for the hook's tracked-files read; the hook warns loudly, and release.yml builds the wheel directly from the checkout and asserts the products are present. Release artifacts are unaffected; do not publish a combined-build wheel.

- [x] Security impact considered
- [x] Backward compatibility considered
- [x] Rollback path is clear for risky changes

## Related Issues

N/A

BREAKING CHANGE: the `subagents/` source tree is gone. Installs never consumed it directly (the wheel carries `raven/agents`), but any local tooling that read `subagents/` paths must move to `agents/` or the snapshots under `tests/fixtures/vendored_fork/`.
2026-09-09 03:59:19 +00:00
0xKT
677d090476 feat(ui-web): an instance can be set apart from the conversation
## Summary

!478 gives the conversation a sub-agent tier. This gives one instance an effort of its own, from that instance's own pane.

The two are a **precedence, not a pair**: `SubagentManager.resolve_mode` reads the instance's override and falls through to the session's tier when there is none. So the default is not a mode -- it is the ABSENCE of one, and the wire already says so with `mode: null`. The row for it reads **Auto**, and `clear: true` is what puts an instance back on it. There is no sentinel id for it on purpose, since an agent is free to call one of its own modes "default".

**Auto names where it currently lands**, not just "Auto". That is what `inherited` is for, and why !474 reports it apart from `mode`: it is the session's tier already clamped to this agent's rungs, which is not the same as the tier. A session on `high` and an agent that cannot rank it means the agent's own default runs, and the row says so.

**The menu is this AGENT's, never the ladder.** Each advertises its own rungs from its own ACP handshake -- measured, not declared. raven-research offers `fast`/`deep`/`ultra` and raven-code `low`/`max`; drawing `medium`/`high`/`max` here would offer rungs the agent does not have. An agent that advertises none draws no chip: nothing to choose between is not the same as a choice that could not be read.

A reply decides, never the click. The manager refuses a rung the agent does not advertise, naming what it does offer, and that refusal is shown rather than the chip moved to a mode the next turn will not run at.

On the pane header, through the shared menu writer with the trailing tick the model chip already uses, rather than a third popover. Live instances only -- a record is a run that already happened.

## Type

- [ ] Fix
- [x] Feature
- [ ] Docs
- [ ] CI / tooling
- [ ] Refactor
- [ ] Other

## Stacked on !478

Target is !478's branch. Kept separate per the ask to split MRs by focus: !478 is the conversation's control and stands alone, this is the per-instance one and only makes sense after it.

Worth noting that !474's later scope change made this smaller. Withdrawing the per-dispatch `mode` left `resolve_mode` at two levels -- the instance's override, else the session's tier -- which is exactly the two a reader can be shown. The third would have had to be explained without being settable.

## Verification, and what it does not cover

Said plainly, because the interesting half could not be driven end to end here.

**What the server really answered.** On the running page, against !474's server, with a real instance started from the agents panel:

```
subagents.instance.set_mode -> { mode: null, inherited: null, availableModes: [] }
```

Every agent registered in this environment is `kind` `cli` or `openai`, and `agent_meta` reads modes only for `acp` -- so none can advertise any, and **the chip correctly draws nothing**. That much is end to end: real server, real instance, real pane, no chip.

**What the component does with a menu** could only be driven by answering the seam on the page. The component, the menu writer, the styles and the pane are the real built ones; the reply is not the server's:

```
Auto                chip "Deep"  (.auto)      menu: Auto · Deep ✓ / Fast / Deep / Ultra
pick Ultra          chip "Ultra" (pill)       sent: ('Raven', 'raven-4cc87d', 'ultra')
reopen              menu: Auto · Deep / Fast / Deep / Ultra ✓
pick Auto           chip "Deep"  (.auto)      sent: ('Raven', 'raven-4cc87d', null)
```

So: the wire shape, the clear-versus-set distinction and the rendering are verified; **what is not** is a real agent's real advertised menu arriving over the socket. Reaching that needs an ACP sub-agent product installed and probed, which this environment has none of. The unit cases cover the states.

I also tried the other way first -- hand-writing a capability snapshot with `availableModes` -- and it changed nothing, because `agent_meta` gates the read on `kind == "acp"` and no configured agent is one. Recording it so nobody repeats it.

```
ui-web  vitest 93 files / 1330 tests, type-check, gen:check (161 methods)
ui-tui  lint:i18n up to date, lint:rpc in sync, type-check clean
```

Mutation-checked nine ways, each redding a different case: Auto showing "Auto" instead of the inherited rung, an empty menu still drawing, painting the click instead of the reply, the Auto row sending an id instead of clearing, the chip not stopping `pointerdown`, and a failed read keeping the previous instance's value. The last one survived the first pass -- the case I had only failed the FIRST read, where there is nothing to keep -- so a case was added for a pane moving to an instance it cannot read.

## After review

**An Auto chip went stale when the conversation tier moved -- `536c62a9`.** Under
Auto the chip shows `inherited`, the session's tier clamped to this agent, so a
switch changes what the pane says with nothing on the pane touched. The effect
keyed on `(agent, handle)` and `shell/tier.ts` told nobody. Reproduced by counting
the reads, with a control, since the chip does not draw against this
environment's agents:

```
                                  before          after
Auto pane open                    High, reads 1   High, reads 1
session tier switched to Max      HIGH, reads 1   Max,  reads 2
control: open another instance     reads 2         reads 3
```

The tier publishes the move and lets whoever is in the way decide -- the shape
`composer/sheets` uses for `watchAsking`, and for its reason. Two tightenings
mutation-checking forced: it tells listeners **only on a real move** (every read
passes through the same place, including the one per conversation change, so
announcing an unchanged value would have every open pane re-fetch for nothing --
my first version notified unconditionally and the suite stayed green), and the
listener re-reads **only under Auto**, through a ref so switching this instance's
own mode does not tear the subscription down and rebuild it.

**The new test file had no purpose comment -- same commit.** AGENTS.md 1.1 wants
one on every new code file. Worth recording what I checked: 38 of the 40 `ui-web`
test files I sampled carry nothing beyond the vitest directive, so the practice is
not the rule; `features/workspace/deliveries.test.ts` is the compliant form. The
rule wins for a file I am adding. `shell/tier.test.ts` on !478 has the same gap
and I have raised it there rather than pushing to an MR already cleared.

```
ui-web  vitest 93 files / 1333 tests, type-check, gen:check (161 methods)
ui-tui  lint:i18n up to date, lint:rpc in sync, type-check clean
```

## Swept

`mr-review-patterns` pre-submit sweep, over the branch diff.

- **1 (a write location moved)** — nothing moved; a new reader of an existing method.
- **2 (a value with several entry points)** — the held state has one writer, fed only by a reply.
- **3c (state out of its owner)** — kept in the component rather than a store: it is one pane's, read when the pane points at a different instance, and no other surface reads it.
- **3d (several lanes through one sink)** — one lane, the seam. The pane header's `pointerdown` is the drag handle and the pane raise, so the chip stops it; there is a case for that.
- **6c (generated artifacts)** — `ui-tui/src/i18n/messages.generated.ts` regenerated, since the catalogue is shared and `make lint-tui` fails without it.
- **9 (error handling)** — a failed read draws nothing rather than a stale rung; a refused switch is shown with the manager's own text, which names the rungs the agent does offer.
- **11** — `tsc --listFiles` resolves 194 files, 0 outside this worktree; `npm ci` in both workspaces.
- **4** — failing test IDs diffed against the base, not counts: 0 introduced.

Not applicable: 3, 3b, 3e, 4b-4d, 5, 5b, 6, 6b, 7, 7b, 8, 10.
2026-09-07 05:36:07 +00:00
Handsome-wzw
b33a35a171 feat(ui-web): an instance can be set apart from the conversation
## Summary

!478 gives the conversation a sub-agent tier. This gives one instance an effort of its own, from that instance's own pane.

The two are a **precedence, not a pair**: `SubagentManager.resolve_mode` reads the instance's override and falls through to the session's tier when there is none. So the default is not a mode -- it is the ABSENCE of one, and the wire already says so with `mode: null`. The row for it reads **Auto**, and `clear: true` is what puts an instance back on it. There is no sentinel id for it on purpose, since an agent is free to call one of its own modes "default".

**Auto names where it currently lands**, not just "Auto". That is what `inherited` is for, and why !474 reports it apart from `mode`: it is the session's tier already clamped to this agent's rungs, which is not the same as the tier. A session on `high` and an agent that cannot rank it means the agent's own default runs, and the row says so.

**The menu is this AGENT's, never the ladder.** Each advertises its own rungs from its own ACP handshake -- measured, not declared. raven-research offers `fast`/`deep`/`ultra` and raven-code `low`/`max`; drawing `medium`/`high`/`max` here would offer rungs the agent does not have. An agent that advertises none draws no chip: nothing to choose between is not the same as a choice that could not be read.

A reply decides, never the click. The manager refuses a rung the agent does not advertise, naming what it does offer, and that refusal is shown rather than the chip moved to a mode the next turn will not run at.

On the pane header, through the shared menu writer with the trailing tick the model chip already uses, rather than a third popover. Live instances only -- a record is a run that already happened.

## Type

- [ ] Fix
- [x] Feature
- [ ] Docs
- [ ] CI / tooling
- [ ] Refactor
- [ ] Other

## Stacked on !478

Target is !478's branch. Kept separate per the ask to split MRs by focus: !478 is the conversation's control and stands alone, this is the per-instance one and only makes sense after it.

Worth noting that !474's later scope change made this smaller. Withdrawing the per-dispatch `mode` left `resolve_mode` at two levels -- the instance's override, else the session's tier -- which is exactly the two a reader can be shown. The third would have had to be explained without being settable.

## Verification, and what it does not cover

Said plainly, because the interesting half could not be driven end to end here.

**What the server really answered.** On the running page, against !474's server, with a real instance started from the agents panel:

```
subagents.instance.set_mode -> { mode: null, inherited: null, availableModes: [] }
```

Every agent registered in this environment is `kind` `cli` or `openai`, and `agent_meta` reads modes only for `acp` -- so none can advertise any, and **the chip correctly draws nothing**. That much is end to end: real server, real instance, real pane, no chip.

**What the component does with a menu** could only be driven by answering the seam on the page. The component, the menu writer, the styles and the pane are the real built ones; the reply is not the server's:

```
Auto                chip "Deep"  (.auto)      menu: Auto · Deep ✓ / Fast / Deep / Ultra
pick Ultra          chip "Ultra" (pill)       sent: ('Raven', 'raven-4cc87d', 'ultra')
reopen              menu: Auto · Deep / Fast / Deep / Ultra ✓
pick Auto           chip "Deep"  (.auto)      sent: ('Raven', 'raven-4cc87d', null)
```

So: the wire shape, the clear-versus-set distinction and the rendering are verified; **what is not** is a real agent's real advertised menu arriving over the socket. Reaching that needs an ACP sub-agent product installed and probed, which this environment has none of. The unit cases cover the states.

I also tried the other way first -- hand-writing a capability snapshot with `availableModes` -- and it changed nothing, because `agent_meta` gates the read on `kind == "acp"` and no configured agent is one. Recording it so nobody repeats it.

```
ui-web  vitest 93 files / 1330 tests, type-check, gen:check (161 methods)
ui-tui  lint:i18n up to date, lint:rpc in sync, type-check clean
```

Mutation-checked nine ways, each redding a different case: Auto showing "Auto" instead of the inherited rung, an empty menu still drawing, painting the click instead of the reply, the Auto row sending an id instead of clearing, the chip not stopping `pointerdown`, and a failed read keeping the previous instance's value. The last one survived the first pass -- the case I had only failed the FIRST read, where there is nothing to keep -- so a case was added for a pane moving to an instance it cannot read.

## After review

**An Auto chip went stale when the conversation tier moved -- `536c62a9`.** Under
Auto the chip shows `inherited`, the session's tier clamped to this agent, so a
switch changes what the pane says with nothing on the pane touched. The effect
keyed on `(agent, handle)` and `shell/tier.ts` told nobody. Reproduced by counting
the reads, with a control, since the chip does not draw against this
environment's agents:

```
                                  before          after
Auto pane open                    High, reads 1   High, reads 1
session tier switched to Max      HIGH, reads 1   Max,  reads 2
control: open another instance     reads 2         reads 3
```

The tier publishes the move and lets whoever is in the way decide -- the shape
`composer/sheets` uses for `watchAsking`, and for its reason. Two tightenings
mutation-checking forced: it tells listeners **only on a real move** (every read
passes through the same place, including the one per conversation change, so
announcing an unchanged value would have every open pane re-fetch for nothing --
my first version notified unconditionally and the suite stayed green), and the
listener re-reads **only under Auto**, through a ref so switching this instance's
own mode does not tear the subscription down and rebuild it.

**The new test file had no purpose comment -- same commit.** AGENTS.md 1.1 wants
one on every new code file. Worth recording what I checked: 38 of the 40 `ui-web`
test files I sampled carry nothing beyond the vitest directive, so the practice is
not the rule; `features/workspace/deliveries.test.ts` is the compliant form. The
rule wins for a file I am adding. `shell/tier.test.ts` on !478 has the same gap
and I have raised it there rather than pushing to an MR already cleared.

```
ui-web  vitest 93 files / 1333 tests, type-check, gen:check (161 methods)
ui-tui  lint:i18n up to date, lint:rpc in sync, type-check clean
```

## Swept

`mr-review-patterns` pre-submit sweep, over the branch diff.

- **1 (a write location moved)** — nothing moved; a new reader of an existing method.
- **2 (a value with several entry points)** — the held state has one writer, fed only by a reply.
- **3c (state out of its owner)** — kept in the component rather than a store: it is one pane's, read when the pane points at a different instance, and no other surface reads it.
- **3d (several lanes through one sink)** — one lane, the seam. The pane header's `pointerdown` is the drag handle and the pane raise, so the chip stops it; there is a case for that.
- **6c (generated artifacts)** — `ui-tui/src/i18n/messages.generated.ts` regenerated, since the catalogue is shared and `make lint-tui` fails without it.
- **9 (error handling)** — a failed read draws nothing rather than a stale rung; a refused switch is shown with the manager's own text, which names the rungs the agent does offer.
- **11** — `tsc --listFiles` resolves 194 files, 0 outside this worktree; `npm ci` in both workspaces.
- **4** — failing test IDs diffed against the base, not counts: 0 introduced.

Not applicable: 3, 3b, 3e, 4b-4d, 5, 5b, 6, 6b, 7, 7b, 8, 10.
2026-09-07 05:36:07 +00:00
0xKT
9f4a091857 feat(agents): the request's checkable parts ride back down to where it is answered
## Summary

Three of the dimensions lost on 2026-09-04 were not research failures. A named
section was absent from the report entirely, five candidates outside the stated
length envelope took slots in the main table, and the do-not-bother list carried
items the request had already ruled out. Each of those was stated in the request
and satisfied by intention rather than by checking, because by the time the report
is written the request is fifteen thousand tokens up the context - the same reason
the template reminder exists, and it rides the same seam.

`brief_checklist` reads a request for the parts a parser can settle and the
reminder carries them back:

```
Read literally, this message asks for: 15 to 25 items; nothing from LongBench,
LooGLE, ZeroSCROLLS, LoCoMo; a do-not-bother list; a community-convention table.
Deliver each one, or name it in `## Limitations` and say why it is absent.
```

Three properties are the whole design.

**It only reads; it never judges the answer.** No bounce, no model call, no
latency. The gate that owns bouncing says in its own docstring that it bounces for
a missing section and nothing else, and a checklist wrong about what was asked
would spend generations arguing with the reader. A checklist that is merely
incomplete costs nothing.

**It quotes rather than interprets.** The count is the range as written, the
exclusions are the names as written, the artefacts are the noun phrases as
written. A misread is then visibly a misread of the request rather than a rule the
harness invented, which is also why the sentence opens "read literally" and closes
with somewhere for a wrong item to go.

**It stays silent when unsure.** A range followed by a unit is a size, not a count
("16k-256k words", "2024-2026", "4x-8x", "8-80GB"). An exclusion stated in prose
("the four we already ran") yields nothing. A bare "a table" is not an artefact and
"a report" is the answer itself. On a request with no machine-readable constraints
the reminder renders exactly the bytes it always rendered - pinned by a test.

The one thing worth naming as a near-miss: an earlier form of the name rule
anchored on a leading capital and quoted `xRAG` back as `RAG`, which is a checklist
telling the model about a benchmark that does not exist. Items are now split first
and kept or dropped whole, and that case is a test.

No new config key, and no new injection seam: the checklist rides inside the
reminder's own delimiters, so one pair still bounds everything injected and
`strip_reminder` needs no second case.

## Type

- [ ] Fix
- [x] Feature
- [ ] Docs
- [ ] CI / tooling

## Verification

```
uv run --frozen --python 3.12 --all-extras pytest -q tests/ -k research
  774 passed in 61.74s

PYTHONPATH=. uv run --frozen --python 3.12 --extra dev python scripts/check_source_language.py origin/main...HEAD
  clean

uv run --frozen --python 3.12 --extra dev ruff check agents tests
  All checks passed!

uv run --frozen --python 3.12 --extra dev ruff format --check agents tests
  907 files already formatted
```

Sixteen tests, weighted towards what the extractors refuse: four shapes of range
that are sizes rather than counts, a prose exclusion, a bare noun, the answer
itself, an empty task, the camel-cased name, and the unchanged bytes on a request
that carries nothing.
2026-09-07 05:35:48 +00:00
ZuyiZhou
3ab6df8504 feat(agents): the request's checkable parts ride back down to where it is answered
## Summary

Three of the dimensions lost on 2026-09-04 were not research failures. A named
section was absent from the report entirely, five candidates outside the stated
length envelope took slots in the main table, and the do-not-bother list carried
items the request had already ruled out. Each of those was stated in the request
and satisfied by intention rather than by checking, because by the time the report
is written the request is fifteen thousand tokens up the context - the same reason
the template reminder exists, and it rides the same seam.

`brief_checklist` reads a request for the parts a parser can settle and the
reminder carries them back:

```
Read literally, this message asks for: 15 to 25 items; nothing from LongBench,
LooGLE, ZeroSCROLLS, LoCoMo; a do-not-bother list; a community-convention table.
Deliver each one, or name it in `## Limitations` and say why it is absent.
```

Three properties are the whole design.

**It only reads; it never judges the answer.** No bounce, no model call, no
latency. The gate that owns bouncing says in its own docstring that it bounces for
a missing section and nothing else, and a checklist wrong about what was asked
would spend generations arguing with the reader. A checklist that is merely
incomplete costs nothing.

**It quotes rather than interprets.** The count is the range as written, the
exclusions are the names as written, the artefacts are the noun phrases as
written. A misread is then visibly a misread of the request rather than a rule the
harness invented, which is also why the sentence opens "read literally" and closes
with somewhere for a wrong item to go.

**It stays silent when unsure.** A range followed by a unit is a size, not a count
("16k-256k words", "2024-2026", "4x-8x", "8-80GB"). An exclusion stated in prose
("the four we already ran") yields nothing. A bare "a table" is not an artefact and
"a report" is the answer itself. On a request with no machine-readable constraints
the reminder renders exactly the bytes it always rendered - pinned by a test.

The one thing worth naming as a near-miss: an earlier form of the name rule
anchored on a leading capital and quoted `xRAG` back as `RAG`, which is a checklist
telling the model about a benchmark that does not exist. Items are now split first
and kept or dropped whole, and that case is a test.

No new config key, and no new injection seam: the checklist rides inside the
reminder's own delimiters, so one pair still bounds everything injected and
`strip_reminder` needs no second case.

## Type

- [ ] Fix
- [x] Feature
- [ ] Docs
- [ ] CI / tooling

## Verification

```
uv run --frozen --python 3.12 --all-extras pytest -q tests/ -k research
  774 passed in 61.74s

PYTHONPATH=. uv run --frozen --python 3.12 --extra dev python scripts/check_source_language.py origin/main...HEAD
  clean

uv run --frozen --python 3.12 --extra dev ruff check agents tests
  All checks passed!

uv run --frozen --python 3.12 --extra dev ruff format --check agents tests
  907 files already formatted
```

Sixteen tests, weighted towards what the extractors refuse: four shapes of range
that are sizes rather than counts, a prose exclusion, a bare noun, the answer
itself, an empty task, the camel-cased name, and the unchanged bytes on a request
that carries nothing.
2026-09-07 05:35:47 +00:00
0xKT
d365264b41 fix(ppt-engine): let an outline's optional page fields arrive as null
## Summary

Two engine-side fixes for `ppt_outline` and `ppt_template`, both measured on live deck runs.

**1. Optional outline fields accept `null`.** `ppt_outline` declared every optional page field (`carries`, `layout`, `layers`, `anti_pattern`, `figures`, `says`, `section`, `role`, `needs`) as a bare `string` or `array`. A page whose `anti_pattern` was `null` was therefore refused by the registry's schema check before the tool ran, once per page, and the whole outline with it. A model with nothing to put in an optional field writes `null` as readily as it leaves the key out, and both readers (`_plan` at the tool, `load_outline` in the contracts) already read the two alike. Measured cost: three live runs lost an outline round to this (the amber run on 2026-09-06 twice, a Shanghai deck on 2026-09-07 once), each a minutes-long re-plan, each surfaced to the user as a wall of `pages[N].anti_pattern should be string` errors. The nine optional page fields now take `["<type>", "null"]`, the shape `prototype` and `borrowed` already had, and the two with an enum (`layout`, `role`) list `null` in the enum as well: a provider reads the parameters as JSON Schema, where `type` and `enum` apply together, so the type alone promised nothing there. `page` and `claim` stay required and still refuse `null`.

**2. The template roster rides on a bind, not on every page read.** A `ppt_template` call with `pages=[...]` returned the full roster (`canvas_in`, `layouts`, `example_pages`, `build_from`, `theme_colours`, `fonts`) ahead of the source, on every reply. The Shanghai run read pages in seven calls and received the same roster seven times, inside a reply the host already cuts at 16,000 characters. The roster is now assembled by one helper and attached to a bind and to a render call, where it first shows or changes; a bare page read returns the pages, the `pages_read` / `pages_cut` / `pages_not_read` bookkeeping, and the note when a `path` was ignored. A call that binds and reads in one go keeps the roster. The tool description says a `pages` call returns "those example pages, and only those".

Not in this MR: the amber run also once omitted the required `page` on every entry (`missing required pages[N].page`); numbering absent pages by position is a separate decision.

## Type

- [x] Fix
- [ ] Feature
- [ ] Docs
- [ ] CI / tooling
- [ ] Refactor
- [ ] Other

## Verification

```
PYTHONPATH=plugins-dist/ppt-engine uv run --frozen --no-sync pytest tests/test_ppt_engine_outline_roles.py tests/test_ppt_engine_outline_checks.py tests/test_ppt_engine_prompt_claims.py tests/test_ppt_engine_plugin.py -q
  -> 109 passed, 23 skipped (the skips are the fetched template payload, absent in this checkout)
PYTHONPATH=plugins-dist/ppt-engine uv run --frozen --no-sync pytest tests/test_ppt_engine_template_tool.py tests/test_ppt_engine_template.py -q
  -> 117 passed
uv run --frozen --no-sync ruff check / ruff format --check <4 files> -> clean
uv run --frozen --no-sync python scripts/check_source_language.py HEAD -> ok
```

Mutation checks: `test_a_page_saying_null_for_what_it_has_no_answer_to_is_accepted` drives the call through `ToolRegistry.execute`, so the schema check is the one under test; with `anti_pattern` put back to a bare `string` it fails (1 failed), and it pins that `claim: null` is still refused. `test_the_declared_schema_takes_null_in_every_optional_page_field_as_json_schema` validates the declared parameters with `jsonschema.Draft202012Validator` against a page with all nine optional fields null, and fails with `None is not one of ['', 'P1', ...]` when the layout enum loses its null. `test_a_page_read_carries_the_pages_and_not_the_roster_again` fails (1 failed) when the roster is attached unconditionally; `test_a_call_that_binds_and_reads_in_one_go_keeps_the_roster` pins the bind-and-read case.

- [x] Relevant tests pass locally
- [x] Relevant lint / type checks pass locally
- [ ] User-facing docs or screenshots are updated when needed (none needed: the tool descriptions are the documentation the author model reads, and the `ppt_template` one is updated in this MR)

## Risk

Engine behaviour visible to the author model only. An outline carrying `null` in an optional page field is now accepted and read as empty, where before it was refused. A `ppt_template` page read no longer carries the roster; an author that wants the layouts again calls the tool with just the project (renders) or with `path` (bind), as before. Nothing in the recorded outline, the bound template, or the build changes. Rollback: revert the two commits.

- [x] Security impact considered (no new input reaches anything; the values were already accepted when the key was absent, and the roster change only removes fields from a reply)
- [x] Backward compatibility considered (outlines on disk are unaffected; the readers did not change)
- [x] Rollback path is clear for risky changes

## Related Issues

N/A
2026-09-07 05:35:22 +00:00
Tchen
effe985f11 fix(ppt-engine): let an outline's optional page fields arrive as null
## Summary

Two engine-side fixes for `ppt_outline` and `ppt_template`, both measured on live deck runs.

**1. Optional outline fields accept `null`.** `ppt_outline` declared every optional page field (`carries`, `layout`, `layers`, `anti_pattern`, `figures`, `says`, `section`, `role`, `needs`) as a bare `string` or `array`. A page whose `anti_pattern` was `null` was therefore refused by the registry's schema check before the tool ran, once per page, and the whole outline with it. A model with nothing to put in an optional field writes `null` as readily as it leaves the key out, and both readers (`_plan` at the tool, `load_outline` in the contracts) already read the two alike. Measured cost: three live runs lost an outline round to this (the amber run on 2026-09-06 twice, a Shanghai deck on 2026-09-07 once), each a minutes-long re-plan, each surfaced to the user as a wall of `pages[N].anti_pattern should be string` errors. The nine optional page fields now take `["<type>", "null"]`, the shape `prototype` and `borrowed` already had, and the two with an enum (`layout`, `role`) list `null` in the enum as well: a provider reads the parameters as JSON Schema, where `type` and `enum` apply together, so the type alone promised nothing there. `page` and `claim` stay required and still refuse `null`.

**2. The template roster rides on a bind, not on every page read.** A `ppt_template` call with `pages=[...]` returned the full roster (`canvas_in`, `layouts`, `example_pages`, `build_from`, `theme_colours`, `fonts`) ahead of the source, on every reply. The Shanghai run read pages in seven calls and received the same roster seven times, inside a reply the host already cuts at 16,000 characters. The roster is now assembled by one helper and attached to a bind and to a render call, where it first shows or changes; a bare page read returns the pages, the `pages_read` / `pages_cut` / `pages_not_read` bookkeeping, and the note when a `path` was ignored. A call that binds and reads in one go keeps the roster. The tool description says a `pages` call returns "those example pages, and only those".

Not in this MR: the amber run also once omitted the required `page` on every entry (`missing required pages[N].page`); numbering absent pages by position is a separate decision.

## Type

- [x] Fix
- [ ] Feature
- [ ] Docs
- [ ] CI / tooling
- [ ] Refactor
- [ ] Other

## Verification

```
PYTHONPATH=plugins-dist/ppt-engine uv run --frozen --no-sync pytest tests/test_ppt_engine_outline_roles.py tests/test_ppt_engine_outline_checks.py tests/test_ppt_engine_prompt_claims.py tests/test_ppt_engine_plugin.py -q
  -> 109 passed, 23 skipped (the skips are the fetched template payload, absent in this checkout)
PYTHONPATH=plugins-dist/ppt-engine uv run --frozen --no-sync pytest tests/test_ppt_engine_template_tool.py tests/test_ppt_engine_template.py -q
  -> 117 passed
uv run --frozen --no-sync ruff check / ruff format --check <4 files> -> clean
uv run --frozen --no-sync python scripts/check_source_language.py HEAD -> ok
```

Mutation checks: `test_a_page_saying_null_for_what_it_has_no_answer_to_is_accepted` drives the call through `ToolRegistry.execute`, so the schema check is the one under test; with `anti_pattern` put back to a bare `string` it fails (1 failed), and it pins that `claim: null` is still refused. `test_the_declared_schema_takes_null_in_every_optional_page_field_as_json_schema` validates the declared parameters with `jsonschema.Draft202012Validator` against a page with all nine optional fields null, and fails with `None is not one of ['', 'P1', ...]` when the layout enum loses its null. `test_a_page_read_carries_the_pages_and_not_the_roster_again` fails (1 failed) when the roster is attached unconditionally; `test_a_call_that_binds_and_reads_in_one_go_keeps_the_roster` pins the bind-and-read case.

- [x] Relevant tests pass locally
- [x] Relevant lint / type checks pass locally
- [ ] User-facing docs or screenshots are updated when needed (none needed: the tool descriptions are the documentation the author model reads, and the `ppt_template` one is updated in this MR)

## Risk

Engine behaviour visible to the author model only. An outline carrying `null` in an optional page field is now accepted and read as empty, where before it was refused. A `ppt_template` page read no longer carries the roster; an author that wants the layouts again calls the tool with just the project (renders) or with `path` (bind), as before. Nothing in the recorded outline, the bound template, or the build changes. Rollback: revert the two commits.

- [x] Security impact considered (no new input reaches anything; the values were already accepted when the key was absent, and the roster change only removes fields from a reply)
- [x] Backward compatibility considered (outlines on disk are unaffected; the readers did not change)
- [x] Rollback path is clear for risky changes

## Related Issues

N/A
2026-09-07 05:35:22 +00:00
0xKT
f8885923aa fix: drop workspace members from exported install constraints
## Summary

`uv export --no-emit-project` leaves workspace members in the exported constraints as unnamed editables (`-e ./plugins-dist/...`), and `uv tool install -c` rejects unnamed requirements. Since `plugins-dist/*` joined the uv workspace (2026-08-31), every constraints-pinned install path failed at constraint parsing: `./install.sh` from a checkout (all three fallbacks), `install.ps1` on Windows, and any beta published by `scripts/publish_beta.py`, whose `raven-constraints.txt` is what `raven upgrade` downloads for `-c`. The `release.yml` copy was latent until the next GitHub tag; no published release carries a bad file (v0.1.13 predates the defect).

Key decisions:

- Switch all four trunk export sites to `--no-emit-workspace`: it drops the members along with the root project and keeps every transitive pin. The export loses exactly the three editable lines and their via comments (697 -> 691 lines).
- Add `tests/test_constraints_export_contract.py` as the tripwire: any export site using `--no-emit-project` inside a project that declares `[tool.uv.workspace]` fails; the four trunk sites are pinned by name so a rename cannot blind the scan; the vendored forks' 12 export sites stay watched. The forks themselves are untouched: their `--no-emit-project` is correct while they declare no workspace, and the contract fires the day one appears.

Not covered here: `install.ps1` was not executed end to end (no PowerShell on the dev machine; the flag semantics are proven by the same uv binary through the sh path), and a beta published between the defect (2026-08-31) and this fix would still carry a bad constraints file in the registry until the next `make beta` overwrites it.

## Type

- [x] Fix
- [ ] Feature
- [ ] Docs
- [ ] CI / tooling
- [ ] Refactor
- [ ] Other

## Verification

- Reproduced the reported three-error cascade at the unfixed base with a sandboxed replica of install.sh's install core (`UV_TOOL_DIR` / `UV_TOOL_BIN_DIR` isolated, real tool env untouched).
- Same replica after the fix: install passes on the first attempt (154 packages, everos plugin editable installed), `raven --version` runs from the sandbox bin, no fallback fires.
- `uv export` variants (install `--frozen`, release `--locked`, beta unlocked) each emit 0 unnamed requirements; `uv pip install --dry-run -c <file> packaging` accepts the fixed file.
- Mutation audit of the contract test: reverting install.sh's flag fails 2 of its tests; adding a `[tool.uv.workspace]` table to a fork fails the tripwire naming all 3 of that fork's sites; both mutations restored.
- `make test-python`: 19154 passed, 133 skipped, 0 failed (7m36s).
- After rebase onto latest main: `uv run pytest tests/test_constraints_export_contract.py tests/test_updates_beta_channel.py tests/test_updates_upgrade.py tests/test_vendored_invariants.py -q` -> 194 passed.
- `make lint-python`, `make check-commits`, `make check-vendored-subagents`, `make check-vendored-invariants`, `scripts/check_source_language.py`, `scripts/check_large_files.py`: all pass.
- No user-facing docs affected: RELEASING.md describes the CI step without naming the flag and stays accurate.

- [x] Relevant tests pass locally
- [x] Relevant lint / type checks pass locally
- [ ] User-facing docs or screenshots are updated when needed

## Risk

- User-visible change: `./install.sh` / `install.ps1` from a source checkout work again, and `make beta` publishes a usable constraints file. Constraint strength is unchanged (same pins, minus the three unnamed editable lines uv rejected).
- Rollback: revert the single commit; the installers return to failing at constraint parsing, nothing else depends on the new flag.
- No security surface: the change alters which lines an already-local export writes, not what gets downloaded or executed.

- [x] Security impact considered
- [x] Backward compatibility considered
- [x] Rollback path is clear for risky changes

## Related Issues

N/A
2026-09-07 05:34:33 +00:00
Handsome-wzw
c065cb0f3c refactor: rename ui to ui-web
## Summary

Rename `ui/` to `ui-web/`. Second half of the `ui-webui` retirement (!425): with three directories called some variant of "ui", the served page had the name that says least about it.

Mechanical, but it reaches CI, the release workflow and the wheel build, so it is its own MR rather than 155k lines of deletion with a rename hidden in it.

## The one decision worth reviewing

**The path inside the wheel stays `raven/ui/dist`. The source tree becomes `ui-web/`.**

Two names on purpose:

- `ui-web/` is what this repository calls the page's sources.
- `raven/ui/dist` is the **installed layout**. `_install_guard` reads it back out of the installed RECORD (`PAGE_RECORD_ENTRY`), the release workflow and `publish_beta.py` assert it inside the built wheel, and anything outside this repository that packages or copies an installed raven may name it.

Renaming a source directory is not a reason to move a path that leaves the repository, and "不破坏" was the constraint I was given. So `hatch_build.py` copies `ui-web/dist` → `raven/ui/dist`, with the reason written where the two sit next to each other, and the same note beside `_UI_DIR` / `_PACKAGED_UI_DIST` in `serve_commands.py`.

`test_hatch_build.py` now asserts the source and the destination as two *different* strings, with a comment saying it is deliberate — otherwise the next reader files the mismatch as drift and "fixes" it.

**If you would rather the wheel path move too, say so and I will do it in this MR** — it is `PAGE_RECORD_ENTRY`, two assertions in `release.yml`, two in `publish_beta.py`, `hatch_build.py`, `_PACKAGED_UI_DIST`, and the doctor/install-guard message text.

## What was deliberately not renamed

- **`docs/plans/` and `docs/specs/`.** They record what was true when written, and one (`2026-08-25-build-wrapup-precondition.md`) is a verification log of a run that actually happened — rewriting it would be editing a record. Same rule I applied in !425.
- **The vendored sub-agent trees under `subagents/`.** My first pass hit four of them; every match was `ui/composer` used as a *concept*, not a path, and those trees answer to `check_vendored_invariants`. Reverted.

## Verification

- `uv run pytest -q` — **12610 passed**, 50 skipped, **5 failed**
  - The 5 are pre-existing on `origin/main`: same node ids fail on an untouched `origin/main` worktree at the merge base (`e1011cb1`). Four `test_security_network.py` NAT64 cases, one `test_cli_doctor_commands.py::test_doctor_answers_where_the_memories_are`.
  - A 6th failed on my first run and was **mine**: `test_hatch_build.py::test_an_editable_install_gets_no_copy_of_the_web_assets`, which is exactly the test that should catch a rename touching the wheel path. Fixed as described above.
- `uv run ruff check raven tests scripts` — All checks passed
- `uv run ruff format --check raven tests scripts` — 1241 files already formatted
  - (Both halves. On !425 I ran only the first and CI caught the second.)
- `npm run build --prefix ui-web` + `python3 ui-web/build.py` + `check-page.mjs`, `check-css.mjs`, `count-shared-globals.mjs` — pass
- `npx vitest run` in `ui-web` — 89 files, 1222 passed
- `npm run gen:check --prefix ui-web` — in sync, 147 methods; `type-check` clean
- `scripts/check_vendored_invariants.py`, `scripts/check_vendored_subagents.py` — pass
- `git diff --check origin/main...HEAD` — clean
- `scripts/commit_lint` — no errors
- `git ls-files | grep -c node_modules` — 0

## Type

- [ ] Fix
- [ ] Feature
- [ ] Docs
- [ ] CI / tooling
- [x] Refactor

## Risk

- [x] Security impact considered
- [x] Backward compatibility considered
- [x] Rollback path is clear

No wire change, no behaviour change. The installed layout is unchanged, which is the compatibility surface that matters. The blast radius is build and CI paths, all of which are exercised above. Rollback is a revert.

**Merge order:** independent of !425 except for one line in `AGENTS.md` that lists the application source trees; whichever lands second takes a one-line conflict there.
2026-08-28 12:51:24 +00:00
Handsome-wzw
9a87470fdf fix(rpc): turn.started is a turn event, and says so on all three sides
## Summary

Found while investigating the first row of Dizhan's `子智能体功能与显示问题` doc (*回注内容过程中未正常显示,刷新后才会正常显示*). This is not that bug's fix, but it is a real defect on the same wire, and it is the one that explains why "前后端接线没有约定好" was a fair thing to say.

**`turn.started` is not in the `TurnEvent` union — on either side.** It has a schema component, it has a Pydantic model, and neither is reachable from the union that `tests/test_rpc_schema_match.py` walks. The 290-test contract guard has never looked at this event.

So it drifted the first time anyone touched it. `05957452` (judge a dag node) taught `announce_dag_exception` to emit:

```python
mark = {"kind": "dag", "label": run_id, "status": "exception", "run_id": run_id, "node_id": node_id}
```

while `TurnStartedEvent.payload.delegated` still declared `status: enum ["ok","error"]` with `additionalProperties: false`, and `TurnStartedPayload` had **no `delegated` field at all** under `extra="forbid"`. Verified with `jsonschema` against the published contract before changing anything:

```
Additional properties are not allowed ('node_id' was unexpected)
```

That commit did carry `exception` into `TranscriptDelegated` and `SubagentDeliveredEvent` — two of the three places this status lives. The third is the one no test covers.

**It does not crash today**, and I want to be exact about that: `SubscriptionEmitter.emit` pushes a raw dict with no validation, and the page reads only the fields it knows. But the contract test's own docstring says what the cost is — *"both sides declare `additionalProperties: false` / `extra="forbid"`, so a consumer validating against the schema rejects the whole event, not just the unknown field"*. Losing this event loses the boundary that advances the workspace turn counter and draws the delegated row.

## What this does

- `TurnStartedEvent` joins the `TurnEvent` union, in `openrpc.json` and in `raven/rpc/models.py`, so the existing sweep covers it from now on.
- The schema's `delegated.status` gains `exception`; `node_id` is declared.
- `TurnStartedPayload` gains `delegated` as a typed model (`TurnStartedDelegated`), three-valued status included.
- Both generated TypeScript clients regenerated.
- A new test drives **the exact marker `manager.py` builds** through both validators, so the next status or field fails here instead of in a client nobody is watching.

## One thing the union surfaced

`ui-tui` never handled `turn.started`. Its exhaustiveness check said so the moment the variant existed. It draws the delegated row from `subagent.delivered`, which the page deliberately ignores in favour of this event — the two mark different moments: **submitted** versus **started**.

Left as it is, with an explicit `case 'turn.started'` saying why. Moving that surface onto the truer moment changes when the TUI draws the row, which is a product change, not a contract fix.

## Verification

- New test red before the fix, by construction: adding the variant to the union alone reds `test_schema_match_turn_event_discriminated_union` and `..._payload_fields` (schema/pydantic drift), which is how the gap was proved.
- Mutation checks, each reverting one thing:

| reverted | reds |
|---|---|
| `exception` out of the schema enum | 1 |
| `node_id` out of the schema | 1 |
| `delegated` off the Pydantic payload | 2 |

- `uv run pytest -q` — **12900 passed**, 50 skipped, 5 failed; the same five pre-existing on `origin/main` (four `test_security_network.py` NAT64 cases, one `test_doctor_answers_where_the_memories_are`), reproduced on an untouched merge-base worktree.
- `uv run ruff check` / `ruff format --check` on `raven tests scripts` — both clean (both halves of `make lint-python`).
- `ui`: `gen:check` 147 methods, `type-check` clean, `npx vitest run` 89 files / **1225 passed**.
- `ui-tui`: `type-check` clean, `lint:rpc` in sync, `lint:i18n` up to date, `npm test` 138 files / **1990 passed**.
  - Worth recording: with `ui-tui/node_modules` symlinked from another checkout the suite reports 82 failed / 59 failed — and reports **the same numbers on an untouched `origin/main`**. It is the symlink, not the branch. Ran `npm ci` in the worktree to get a trustworthy number.
- `scripts/commit_lint` — no errors.
- `git ls-files | grep -c node_modules` — 0.

## Type

- [x] Fix

## Risk

- [x] Security impact considered
- [x] Backward compatibility considered
- [x] Rollback path is clear

Widening a contract to match what the runtime already emits: every payload valid before is valid now. No emit site changes, no behaviour changes. The one code change outside the schema and the models is an explicit no-op branch in `ui-tui`. Rollback is a revert.
2026-08-28 12:51:10 +00:00
forrestjgq
8ecfae3e0c test(tracing): isolate span emission into per-test tmp dirs (#371)
## Summary

Unit tests were leaking tracing spans into the real `~/.raven/traces`
store. Tracing is on by default and `trace.span()` calls are embedded in
library code (agent loop, subagents, TUI RPC), so any test exercising
those paths emitted spans with fabricated session keys (`session-a`,
`weixin:c`, `tui:default`, ...). Those spans then surfaced as phantom
sessions in `raven trajectory`, while the TUI `/sessions` list (which
reads the real session store) stayed clean.

This PR adds an autouse fixture in `tests/conftest.py` that:

- redirects `RAVEN_TRACING_DIR` to a per-test tmp directory, and
- resets the lazy module-level `TraceStore` cache
(`raven.tracing.spans._store`) around each test, since it pins the
directory resolved at first emit.

Key decisions:

- Only the directory is redirected, not the enabled switch, so the suite
keeps exercising the real emission path with zero behavior change; leaks
land in tmp instead.
- This centralizes the setenv-plus-cache-reset pattern that 8
tracing/trajectory test files already perform manually. Those tests keep
working: their own `monkeypatch.setenv` runs after the fixture and wins,
and they already reset the cache themselves.
- Existing phantom sessions come from archived span logs written before
this fix; the fixture only prevents new leaks. One archive file mixes a
real session with test keys, so cleanup needs line-level filtering and
is left out of scope.

## Type

- [ ] Fix
- [ ] Feature
- [ ] Docs
- [ ] CI / tooling
- [ ] Refactor
- [x] Other

Test-suite hygiene (`test` commit type).

## Verification

- `uv run pytest tests/test_tracing_api.py
tests/test_trajectory_store.py tests/test_trajectory_bundle.py
tests/test_trajectory_replay.py tests/test_trajectory_redact.py
tests/test_cli_tracing_commands.py tests/test_cli_trajectory_commands.py
tests/test_cli_trajectory_browse.py -q`: 308 passed, 1 failed
(`test_viewer_health_true_for_our_viewer`, fails identically on
unmodified `main`, environment-specific)
- `uv run pytest tests/test_agent_loop_run_emit.py
tests/test_subagent_manager.py tests/test_tui_rpc_turn_send.py
tests/test_deep_research_tool.py tests/test_agent_loop_approval.py -q`:
109 passed; the real `~/.raven/traces` log did not grow during the run
- Positive check: running `tests/test_agent_loop_run_emit.py` with
`--basetemp` shows the previously leaked session keys (`cli:c`, `tg:c`,
`weixin:c`) now land in per-test tmp dirs
- `uv run pytest tests/ --ignore=tests/integration -q`: 6837 passed, 11
failed, 20 errors; the same failure set reproduces on unmodified `main`
(environment-specific: cron/tz, everos server, theme, config loader,
viewer health), zero regressions from this change
- `uv run ruff check tests/conftest.py` and `uv run ruff format --check
tests/conftest.py`: both pass

- [x] Relevant tests pass locally
- [x] Relevant lint / type checks pass locally
- [ ] User-facing docs or screenshots are updated when needed

Docs box left blank: test-only change, no user-facing docs affected.

## Risk

- [x] Security impact considered
- [x] Backward compatibility considered
- [x] Rollback path is clear for risky changes

Test-only change; no production code touched. One known interaction:
`RAVEN_TRACING_DIR` takes precedence over `RAVEN_HOME`, so a future test
that fakes `RAVEN_HOME` and expects traces under it must also set
`RAVEN_TRACING_DIR` itself. Rollback: revert the single commit.

## Related Issues

N/A

Co-authored-by: 江国庆 <guoqingjiang@deepglint.com>
Co-authored-by: Claude (claude-fable-5) <noreply@anthropic.com>
2026-08-28 19:21:16 +08:00
arelchan
7c33c4133a fix(rpc): let the viewer open the files a turn actually wrote
## Summary

A delivered artifact could not be opened from the page: the file viewer answered
403 and the transcript drew "Raven is confined to the workspace, so this file
cannot be opened here" over a delivery card it had just rendered.

The viewer's state-directory fence exempts the workspace subtree, on the stated
grounds that the default workspace lives inside raven's home and denying it
would refuse every file the agent itself wrote. Since agent home and the working
directory were split apart, a turn no longer writes there: it writes in
`~/.raven/tmp/<channel>`, a sibling of the workspace, inside the same state root
and outside the carve-out. So the fence denied exactly what the carve-out exists
to allow, one directory over, for every artifact produced since that split.

This exempts the working-directory root alongside the workspace, using the same
containment test in the same direction, so a working-directory root that happens
to sit above raven's home earns no exemption. `config.json`, `oauth/` and
`serve.json` are siblings of both and stay refused, which is what the fence is
for.

Worth noting for a reviewer: the bytes were already reachable. `/files/download`
serves a delivered file by token with no path fence, so this was never a
security boundary for deliveries -- only a viewer that refused to render what
the same page could already download.

## Type

- [x] Fix
- [ ] Feature
- [ ] Docs
- [ ] CI / tooling
- [ ] Refactor
- [ ] Other

## Verification

- `uv run pytest tests/test_rpc_transport.py tests/test_rpc_files.py tests/test_rpc_knowledge.py tests/test_rpc_console.py -q` -> 123 passed
- `uv run ruff check` and `uv run ruff format --check` on both changed files -> clean
- Both new assertions were mutation-checked, each against its own mutation:
  - narrowing the carve-out back to the workspace alone reds
    `test_the_turn_working_directory_is_exempt_from_the_state_dir_fence` only (1 failed, 3 passed)
  - dropping the containment-direction guard reds
    `test_a_working_directory_root_that_contains_the_state_root_earns_no_exemption`
    and the pre-existing state-dir test (2 failed, 2 passed)
- Against the real reporting case: the two files that were answering 403
  (`~/.raven/tmp/tui/*.md`, `*.pptx`) now resolve, while `~/.raven/config.json`
  and `~/.raven/serve.json` still raise PermissionError.

- [x] Relevant tests pass locally
- [x] Relevant lint / type checks pass locally
- [ ] User-facing docs or screenshots are updated when needed

## Risk

- Widens what the file viewer will render by exactly one subtree: the directory
  turns work in. Everything the fence was written to protect (provider keys in
  `config.json`, the OAuth token store, `serve.json`) sits beside that subtree,
  not inside it, and stays refused -- pinned by the tests above.
- `fs.list` / `fs.reveal` share the function but pass the session's working
  directory as the root, which their own containment check already bounds, so
  their behaviour is unchanged.
- Rollback is a one-line revert of the exemption tuple.

- [x] Security impact considered
- [x] Backward compatibility considered
- [x] Rollback path is clear for risky changes

## Related Issues

N/A
2026-08-28 04:57:29 +00:00
LivXue
4e35a5d627 fix(tui): show the copy-on-select confirmation as a transient notice (#366)
## Summary

PR #360 reports every copy-on-select write as a permanent transcript
line, so a
reading session that drags through the transcript piles up "copied N
characters" rows under the conversation. The confirmation splits by what
the
line is for: the unbounded terse repeats become a transient notice
rendered
above the input box -- one line that replaces itself on every new copy
and
clears after 3 seconds -- while the first copy of a session keeps its
path
caveat in the transcript. The caveat is the answer a user comes looking
for
after a paste comes up empty minutes later, and it cannot pile up
because it
is once per session by construction.

The reporter still owns the per-session caveat tally and now returns
`{ text, firstOfSession }` so the caller can route the caveat to the
transcript and the repeats to the notice. A new `copyNoticeStore` holds
the
single notice; `showCopyNotice` keeps one dismiss timer, clearing any
pending
one before arming the next, so an earlier deadline can never clear a
newer
notice. `/copy` is deliberately untouched: an explicit command's answer
still
belongs in the transcript, and it cannot stack on its own.

## Type

- [x] Fix

## Verification

Run from `ui-tui/` at branch head, in a fresh worktree of `github/main`.
Dependencies came from `npm ci` in `ui-tui/` and in the hermes package;
the
hermes package's own `node_modules` holds only esbuild, so the ink
render
tests run against one react copy (two copies break every hook call).

```
npx vitest run --no-file-parallelism
  Test Files  93 passed (93)
  Tests  1084 passed | 13 skipped (1097)

npm run type-check
  clean, exit 0

npm run lint
  22 problems (0 errors, 22 warnings)

npx prettier --check src/app/copyNoticeStore.ts src/__tests__/copyNotice.test.tsx
  src/__tests__/clipboard.test.ts src/app/useMainApp.ts
  src/components/appLayout.tsx src/lib/clipboard.ts
  All matched files use Prettier code style!

python3 -m scripts.check_commit_messages github/main..HEAD
  exit 0
```

The 22 lint warnings are the baseline, not new: 22 before the branch and
22
after, none in a file this branch touches. The suite is run with
`--no-file-parallelism` deliberately: the ink render tests fail under
default
worker parallelism at this suite size, and no CI job runs them.

Suites that exercise the changed code directly:
`src/__tests__/copyNotice.test.tsx`
(7 cases), `src/__tests__/clipboard.test.ts` (30 cases, the 3 reporter
cases
updated to the new return shape).

New tests were proved load-bearing rather than assumed:

- Removing the notice render line in `appLayout.tsx` makes the render
test
  fail (content and placement above the input box).
- Removing the pending-timer clear in `showCopyNotice` makes the
re-shown-notice test fail: the earlier 3s deadline then clears the newer
  notice.
- The dismissed-notice case now shows a notice first, and removing
  `dismissCopyNotice`'s atom clear turns it red (review fix).

- [x] Relevant tests pass locally
- [x] Relevant lint / type checks pass locally
- [ ] User-facing docs or screenshots are updated when needed

No doc change. `ui-tui/CONTEXT.md` has no clipboard or selection entry,
and
"copy notice" continues the existing "notice" vocabulary of
`copyResultNotice`
/ `copyOnSelectNotice`, so nothing new is coined.

## Risk

Behaviour change: the per-drag copy confirmation is now transient and
above
the input box instead of a permanent transcript line, and the first copy
of a
session lands one transcript line, exactly as on `main`. Reverting the
branch
restores the #360 behaviour; no data or on-disk format is involved.

- [x] Security impact considered
- [x] Backward compatibility considered
- [x] Rollback path is clear for risky changes

## Related Issues

N/A

---------

Co-authored-by: Claude (deepseek-v4-pro) <noreply@anthropic.com>
2026-08-25 14:27:24 +08:00
LivXue
bedd83a777 build: ship the vendored sub-agents in every wheel
## Summary

A `pip` / `uv tool install` of raven had no sub-agents. Onboarding step 5 reported
"No sub-agent tree in this installation (source checkouts only)" on every
non-editable install, so the four vendored agents existed only for people working
from a clone.

The reading side was already complete: `subagents_root()` looks for a packaged tree
at `raven/subagents`, and `_install_packaged_tree()` copies one out to the raven home
so an upgrade cannot take the built venvs with it. Nothing ever put the tree in a
wheel. This adds that, and settles where the rule lives.

**The tree is enumerated from git's index, file by file, not force-included as a
directory.** Hatchling applies no `include` / `exclude` config to a force-included
path: `recurse_forced_files` drops a hardcoded set of directories and nothing else.
Measured on a developer box, a directory entry would have shipped 165.9 MiB,
including all four forks' filled-in `.env` (scaffolded by `subagents/install.sh` and
holding live provider keys), 35 MiB of rollback tarballs and 26 MiB of untracked
benchmark data. Reading the list from git is safe by construction, and is the rule
`scripts/check_vendored_subagents.py` already applies for the same reason. A path
that looks like a filled-in secrets file fails the build.

**Editable builds are skipped.** Hatchling honours the same map there, through
`get_forced_inclusion_map` folding `build_data` in via `build_force_include`, so
without the guard every `uv sync` copied 106 MiB into a site-packages directory that
nothing reads -- `raven.__file__` resolves to the source tree, where the neighbouring
checkout is found instead. Measured: 116 MiB before the guard, 4 KiB after.

**The beta-only path is retired.** `publish_beta.py` staged the committed tree and
injected a force-include line into a temporary `pyproject.toml`, so the agents
reached beta testers and nobody else, deliberately keeping stable releases small.
Both mechanisms at once map the same distribution paths and hatchling refuses the
build outright ("A second file is being added to the wheel archive at the same
path"), so one had to go. Keeping the hook also drops a rewrite that matched the
force-include table header by string. What the staging also guaranteed -- that the
agents are really in the artifact -- is now asserted at both publish boundaries
instead, along with a refusal to publish anything that looks like a secrets file.

Cost, measured on the built wheel rather than estimated:

| | compressed | uncompressed |
|---|---|---|
| `raven/subagents/**` | 67.3 MiB | 106.2 MiB |
| everything else | 2.9 MiB | 9.1 MiB |
| wheel on disk | 71.4 MiB (was about 3 MiB) | |

So the download grows by 67 MiB, not 106; 50.5 MiB of the payload is raven-ppt's
PPT templates. On first run the tree is **copied** -- not moved -- to
`<raven home>/subagents`, once per raven version. Both copies then persist: the one
under site-packages is what the installer's RECORD owns and is the fallback
`subagents_root()` uses when the copy-out fails, so an install holds about 212 MiB
across the two. Neither has an expiry or a size cap; deleting the raven home copy
reclaims half, the rest going when raven itself is uninstalled. That directory grows
to roughly 3 GB once all four venvs are built.

A tree that is absent, or present but untracked, now warns instead of passing
quietly. A wheel built from an sdist has neither the tree nor a `.git` to read it
from, which is the same trap the release workflow already documents for the TUI
bundle.

## Type

- [ ] Fix
- [ ] Feature
- [ ] Docs
- [x] CI / tooling
- [ ] Refactor
- [ ] Other

## Verification

Full suite, run at the rebased head:

    uv run --frozen --all-extras pytest -q
    -> 11650 passed, 40 skipped, 13 deselected in 371s

The 40 skips are the pre-existing ones that need a non-root user (`chmod` does not
block root); none are new.

    make lint-python              -> All checks passed / 1170 files already formatted
    make check-vendored-subagents -> exit 0
    uv run python scripts/check_commit_messages.py origin/main..HEAD -> exit 0

Wheel contents, built from this branch and compared against the index:

    uv build --wheel
    -> raven/subagents entries: 5400
       git ls-files subagents:  5400
       exact match with git:    True
       secrets: NONE   .venv/: 0   /.git/: 0   *.tar.gz: 0   node_modules/: 0
       4 subagent.json, 4 install.py, install.sh + README + TREE_HASHES present

Clean-machine install, on a freshly launched box with `~/.raven` deleted and no
source checkout in play (the resolved package path was read first and confirmed to
be the tool's own site-packages, not a shared mount):

    uv tool install "raven[channels] @ <wheel>"
    -> raven/subagents present in site-packages
       tree copied to the raven home, version stamp 0.1.13, 5401 files
       discover_vendored_rows() -> 4 agents
       configure_subagents(non_interactive=True) reaches the per-folder stage
       13/13 checks pass

Then the copied-out tree was actually built, to prove the packaging did not break
the installer:

    bash install.sh raven-research   -> exit 0, venv 156 packages, .env from template

Its readiness moved from "venv not built in Raven-X" to "no LLM credential", which is
the correct next gate on a box where no key was injected.

The new assertions were each proved load-bearing by reverting the change and watching
them fail (3 in `test_publish_beta.py`, 5 in `test_hatch_build.py`).

- [x] Relevant tests pass locally
- [x] Relevant lint / type checks pass locally
- [x] User-facing docs or screenshots are updated when needed

## Risk

User-visible changes:

- The download is about 67 MiB larger. Every install and every upgrade pays it.
- First run copies another 106 MiB into `<raven home>/subagents`, and the copy under
  site-packages stays, so an install holds about 212 MiB of tree in total.
- Beta builds no longer stage the tree themselves; they get it from the wheel like
  everyone else. `make beta` would have failed outright if both had been kept.
- Step 5's message changed, and three docstring and changelog claims that described
  the tree as checkout-only, or the copy-out as a move, were corrected.

Rollback: revert the five commits. Nothing persists that a revert cannot undo except
`<raven home>/subagents`, which a user deletes by hand; a raven without the packaged
tree ignores it, and an older raven finds it exactly where it looks today.

Known gap, deliberately not fixed here: the secrets check matches `.env` and `.env.*`
only, so a credential in a file named something else would not be caught by it. The
real defence is that only git-tracked files ship at all; the name check is a second
net at the publish boundary, not the primary control.

- [x] Security impact considered
- [x] Backward compatibility considered
- [x] Rollback path is clear for risky changes

## Related Issues

N/A
2026-08-26 08:49:52 +00:00
gloryfromca
df9a7d7f37 chore(*): merge upstream v0.1.13 into the gitlab trunk
Absorbs the GitHub release into the downstream trunk. A merge rather than a
rebase so v0.1.13 becomes a real ancestor: the next sync starts from v0.1.13
instead of v0.1.12, and the eventual contribution back to GitHub can still tell
our commits from the upstream ones it already has.

Cost this round: 51 conflict hunks over 27 files, against 54 over 31 for
v0.1.12. The hunks were the cheap half. Upstream's #284 moves the model and
provider from process-wide state to a per-session binding, and the trunk had 230
commits standing on the old shape.

What git reported as a clean merge and was not
---------------------------------------------

Fourteen upstream-changed paths do not exist here, because we renamed or moved
them since v0.1.12. Rename detection found none of them, so their changes were
merged into paths nothing reads, silently:

* raven/tui_rpc/* -> raven/rpc/* (renamed in ce526ad5). Nine files, including
  question_broker.py, whose whole #354 rewrite was lost, and methods/config.py,
  methods/model.py, methods/session.py, models.py and errors.py. Each was
  replayed by three-way merge against dd82f52c. The three test modules were
  rebased function by function onto upstream's version instead, after a
  three-way merge spliced assertions into the wrong tests.
* raven/agent/tools/mcp.py -> raven/mcp/client.py. Carried the release-blocking
  fix, and is handled in the commit that follows this one.
* ui-tui/rpc-schema/openrpc.json -> rpc-schema/openrpc.json.

Decisions
---------

Follow upstream wherever the two disagree about provider and model:

* providers/pin.py is gone, so a bare model id is refused instead of derived.
  A model id does not name whose credential serves it, and the derivation
  walked a list -- with two vendors configured, which one pays came down to
  their order in it. rpc/methods/config.py now requires the provider.
* ModelSwitchInTurnError (-32009) is gone with it. A session switch lands on
  that session's next turn, so there is nothing to refuse mid-turn.
* AgentLoop.refresh_context_window and the LazyProvider on_built wiring are
  gone: the window rides on the binding now.
* The skill gate no longer forwards an unpaired pin.

Keep ours where the trunk is ahead, and graft upstream's behaviour into it:

* raven/agent/subagent/backends/raven_loop.py is the live sub-agent path, so
  manager.py's inline loop stays retired and the web_search gate from #312
  applies there.
* skill_hub/client.py keeps the public zip limits the skillhub RPC path imports,
  and takes upstream's query-string cap.
* ask_user keeps our JSON-string normalizers and feeds them into upstream's
  batch contract, so a batch validated by _prepare is one _normalize_questions
  has already coerced.
* The chat view composes both filters: hideIntroAfterFirstTurn drops the cover,
  visibleRows still hands the view to a direct chat.

Tests removed, not repaired
---------------------------

Eight tests covered mechanisms this merge deletes, and one of them hung rather
than failed:

* seven in test_agent_loop_model_switch.py over AgentLoop._pending_provider,
  the switch-parking mechanism #284 replaced with per-session bindings. Its
  replacement arrives with upstream as test_agent_loop_session_model.py.
* test_a_refusal_during_a_turn_keeps_its_own_code in test_acp_methods.py, whose
  error class no longer exists.

Baseline: the pipeline for 01d39e58, this merge's base, is green, so nothing
here can be charged to a pre-existing failure.

Co-authored-by: Claude (claude-opus-5) <noreply@anthropic.com>
2026-08-25 16:12:43 +08:00
Handsome-wzw
a1d5b24de3 feat(agent): withhold web_search without a key, and make tool capabilities visible (#312)
## Summary

A WeChat user asked for a recommendation and the bot answered "the web
search
tool is not configured here". That sentence was not the model's own
phrasing --
it was the tool's error text, relayed outward. `web_search` needs a
Serper key
and that deployment has never had one, but the tool was registered
unconditionally, so on every search-shaped question the model saw it,
reached
for it, and passed the setup error on to whoever was in the chat.

Withholding the tool fixes that and creates a second problem: an
unregistered
tool is invisible. Nothing in a running Raven then says the capability
exists at
all -- the model is never offered it, no document lists it, and `raven
doctor`
reports on providers and memory but has never mentioned tools. The only
way to
learn that web search is one account and one edit away was to read the
source.

This does both halves, because either alone leaves a real gap: the
deployer is
told what this install can and cannot do, and the model is still not
offered a
tool it cannot run.

### Withholding the unusable tool

`web_search` is gated on a resolved key, in the main loop and in the
sub-agent
surface (`subagent/manager.py`) -- a sub-agent that reaches for a search
it
cannot run reports the failure to its caller, and that text lands in the
parent
turn, the same leak one level down.

The gate asks the tool, not the config. `WebSearchTool.api_key` resolves
at call
time from the constructor value *or* `SERPER_API_KEY`, so reading
`tools.web.search.apiKey` alone would withdraw a working tool from any
deploy
that exports the variable and configures nothing.

The tool's error message also hard-coded `~/.raven/config.json` while
the
gateway runs with `--config` elsewhere, so following it meant editing a
file the
process never reads. It names the path actually in force now. That text
is
reachable only if the key disappears after registration, which is
exactly why it
should be right: it is the message for the case the gate cannot cover.

### Three rules, and nowhere to read them

Registration is decided per family, each a different shape:

| family | rule |
|---|---|
| `web_search` | a resolved key, asked of the built tool |
| `web_fetch` | nothing -- always registered, a key only improves
extraction |
| media x3 | an `api_key` *or* a `model`, either counting as configured
|

For media those are two questions, not one. A section naming only a
model is
registered, because a model alone counts as asking for the tool, and
then every
call returns a missing-key error. Whether a capability is *offered* and
whether
it *works* come apart there, and a report treating them as one fact
ticks a
capability that cannot run.

Each rule is defensible where it sits. What is missing is anywhere to
read them.
Providers had the same sprawl once and answered it with
`providers.auth`: a
declarative table plus `credential_status` as the single authority, with
an AST
invariant enforcing that authority, because six surfaces had answered
the same
question six ways and each looked reasonable alone. Tools never got the
equivalent.

### What this adds

**Each tool answers for itself,** twice where the questions differ.
`WebSearchTool.is_configured` reads the config value *or*
`SERPER_API_KEY`,
because those are two sources and only the tool consults both. The media
base
answers `is_configured` on a model *or* a key -- which is what stops an
OpenRouter credential set for chat from silently switching on three
tools that
bill per call -- and answers `has_key` separately on the chain it
actually
resolves at call time: its own section, the borrowed provider key, then
`OPENROUTER_API_KEY`. Both rules live with the credential they read.

**`capabilities.py` describes the five** for a human deciding what to
set up:
what each does in one line, how much work it is (nothing / reuse a
credential
you already have / obtain an account), where the key goes, where to get
one, and
what it costs. It rules on nothing -- `is_configured` and
`has_credential` both
ask the tools -- so it cannot become a second opinion.

**`raven doctor` grows a section**, listing every capability configured
or not,
ordered by how much the deployer has to do:

```
(markers render as a green check and a yellow bang; spelled [ok] and [!] here to
keep this description ASCII, since it becomes the squash commit body)

Tool capabilities
  web_fetch:       [ok] Read a web page the agent already has the URL for
  image_generate:  [ok] Generate an image  (borrowed: providers.openrouter.apiKey)
  text_to_speech:  [!] Generate speech from text
                   no key resolves; calls will fail
                   set: tools.media.speech.apiKey
                   or env: OPENROUTER_API_KEY
  video_generate:  -  Generate a video
                   switch on: tools.media.video.model
                   key: reusing providers.openrouter.apiKey
                   Billed per call; needs prepaid OpenRouter credit.
  web_search:      -  Search the web
                   set: tools.web.search.apiKey
                   or env: SERPER_API_KEY
                   key from: https://serper.dev
  2 capability(s) available but not set up; the agent is not offered them.
```

Three deliberate details.

Naming the credential is load-bearing in both directions. A row that
cannot
distinguish a reused credential from a missing one sends someone to
create an
account they already have -- and a row that claims a reuse with nothing
to reuse
is worse, because acting on it means setting a model, getting a
registered tool,
and watching every call fail on a credential they were told they had. So
the
reuse line prints only when a key is genuinely there to pick up, and a
capability already in that broken state says so outright instead of
showing a
satisfied tick.

The credential is named at the path that holds it. For the media family
`config_path` names the *model*, so reusing it as the key source pointed
the
deployer at a line with no credential in it.

And each fact is on its own line rather than in a sentence, because the
terminal
wraps a long line mid-path and a config key broken across two rows
cannot be
copied, which is the only thing that row is for.

Nothing here moves the exit code, including the warned row. An install
without
image generation is a choice, not a fault, and a doctor that fails on it
teaches
people to ignore doctor. The half-finished one is arguable -- the memory
section
does exit non-zero for a role the user configured that the server could
not
build -- but that failure is silent where it happens, recall just
returning
nothing, whereas this one returns an error string to the model on every
call.
Say the word and it becomes an exit code instead.

### Not in this change

Registration still lives in `AgentLoop`. Having it read the table is the
point
of this shape and removes the last duplicate reader, but it edits
`agent/loop/main.py`, which is under active change, and it is worth
doing on its
own once that settles. Until then the table is a description, and the
tests
below are what keep it honest.

`deep_research` is deliberately absent: it is moving to the sub-agent
surface
and its tool is going away.

## Type

- [ ] Fix
- [x] Feature
- [ ] Docs
- [ ] CI / tooling
- [ ] Refactor
- [ ] Other

Mixed on purpose: the first commit is a fix and the rest are the feature
it
made necessary. Splitting them would land a change that hides a
capability
without landing the one that makes it discoverable.

## Verification

```
make lint                                            exit 0
make build                                           exit 0
npm run test --prefix ui-tui                         969 passed, 13 skipped
uv run --all-extras pytest -q                        6186 passed, 35 skipped, 1 failed
uv run pytest tests/test_tool_capabilities.py \
              tests/test_cli_doctor_commands.py \
              tests/test_agent_loop_web_tools.py     64 passed
uv run --extra dev ruff check raven tests scripts    All checks passed
uv run --extra dev ruff format --check               828 files already formatted
npx commitlint --from origin/main --to HEAD          exit 0
scripts/check_commit_messages.py origin/main..HEAD   exit 0
```

The one failure is
`test_read_file_image.py::test_an_attachment_that_cannot_be_
read_costs_a_note_not_the_turn`, and it is not from this branch: it
fails the
same way on `main` at `1cb604a` with these commits absent. The case
makes a file
unreadable with `chmod 000`, which does not block a root user, so it
fails for
anyone running the suite as root and passes in CI. This branch does not
touch
that file or the code under it.

The capability tests drive a real `AgentLoop` and compare what it
registered
against what the table predicts, rather than asserting the table against
itself.
The gated set is derived -- tools present once credentials are supplied,
absent
without -- so a sixth gated tool whose author forgets the table fails
here rather
than going unnoticed.

That last claim was false when first written, and the last commit is
what makes
it true. The fixture listing the media tools by hand never switched a
fourth one
on, so a new one never joined the gated set and the assertion held over
an
already-incomplete table. #305, which adds a MiniMax voice-clone tool,
is that
case: merged against this branch the assertion passed. Read from
`MediaGenConfig` instead, it fails and names the tool -- `gated but
undeclared:
['voice_clone']`.

Which means whichever of the two lands second turns this red,
deliberately. The
fix is one table entry, and it needs the rule that PR settles:
`voice_clone`
counts as configured on `api_key or api_base or model` in
`effective_media_config` while registration still gates on `api_key or
model`,
so an `apiBase`-only install with no MiniMax key is configured by one
rule and
withheld by the other. That is the divergence this table exists to make
visible,
and it is worth resolving there rather than papering over here.

Fifteen mutations, each caught:

```
the web_search gate removed from the main loop    3 failed
the same gate removed from the sub-agent surface  1 failed
media rule reads only the key                     7 failed
web_search rule reads only the config             1 failed
a tool removed from the table                     6 failed
the doctor section not rendered                   6 failed
doctor lists only configured tools                4 failed
unconfigured treated as a failure                17 failed
the reuse line is printed unconditionally         1 failed
the key source falls back to the model path       3 failed
a keyless registered capability is not flagged    1 failed
has_key always answers yes                        1 failed
has_credential collapses into is_configured       1 failed
the credential chain drops OPENROUTER_API_KEY     3 failed
the reuse check ignores the environment           3 failed
```

Four of those tests exist only because a mutation pass found the earlier
versions insufficient, and the last rounds are why the shape changed. A
media
case that sets both a model and an OpenRouter key proves nothing about
the "or
model" half: the borrow fills the key in, so a rule reading only the key
still
answers correctly. The case that pins it has nothing to borrow.

The sub-agent case is the same argument applied to the second call site:
with
the gate present only in the main loop, every test above still passes,
because
nothing was watching what the sub-agent surface registers.

More usefully, mutating `has_key` to always answer yes changed no test
at all in
the first version, which said the ruling was not load-bearing: the
doctor was
inferring "no credential" from an *empty source string* rather than from
the
tool's answer, so a fourth credential source would have been reported as
a
missing one. `has_credential` is now its own fact, asked of the tools,
and that
mutation fails.

Separately, autouse fixtures clear `SERPER_API_KEY` and
`OPENROUTER_API_KEY`,
without which several of these pass for the wrong reason on any machine
where a
developer exported one.

Rendering was checked against a real config in six states -- nothing
set, a
provider key present, a model with nothing to borrow, a tool with its
own key, a
model plus a borrowable key, and an exported variable as the only source
--
rather than only asserted on.

- [x] Relevant tests pass locally
- [x] Relevant lint / type checks pass locally
- [ ] User-facing docs or screenshots are updated when needed

## Risk

One behaviour change: `web_search` is no longer offered to the model
when no key
resolves. That is the fix. A deployment that has a key, in config or in
the
environment, is unaffected; one that has none was getting an error
string in
place of an answer.

The rest is additive. No other registration logic changed, so which
tools an
agent is offered is otherwise exactly what it was; `is_configured` moved
the
existing predicates onto the tools without altering them, and the
mutation
results above are what pins that. `has_key` and `_resolve_key` are new
names for
the chain `api_key` already resolved -- the property calls the extracted
one, so
callers see the same answers.

`raven doctor` gains a section and no new exit code. Its zero-network
guarantee
holds: the table reads config and environment only.

Two allowlist entries were added to
`test_only_the_auth_module_decides_configuredness_from_a_key`, argued in
place:
`subagent/manager.py`, which asks the built tool whether a key resolved
so an
unusable search is withheld, and `capabilities.py`, which reads keys to
*report*
-- which source supplied one, and whether one is there to reuse. Both
ruling
halves are delegated to the tools, whose files were already listed.

Rollback is a revert. Nothing is written and no configuration is read
differently.

- [x] Security impact considered
- [x] Backward compatibility considered
- [x] Rollback path is clear for risky changes

## Related Issues

N/A

---------

Co-authored-by: Claude (claude-opus-5) <noreply@anthropic.com>
2026-08-25 10:05:58 +08:00
arelchan
82eea1dd20 fix(ui): show Raven logo as page favicon
## Summary

- Declare the existing Raven application logo as the served page favicon.
- Copy the logo into the packaged page assets so installed builds render the same branding.

## Type

- [x] Fix
- [ ] Feature
- [ ] Docs
- [ ] CI / tooling
- [ ] Refactor
- [ ] Other

## Verification

- [x] Relevant tests pass locally
- [x] Relevant lint / type checks pass locally
- [ ] User-facing docs or screenshots are updated when needed

- `npm test --prefix ui` - 32 test files and 528 tests passed.
- `npm run type-check --prefix ui` - passed.
- `npm run build --prefix ui` - passed.
- `python3 ui/build.py` - built the page and copied the Raven logo asset.
- `node ui/scripts/check-page.mjs` - passed.
- `make check-large-files` - passed.

## Risk

- [x] Security impact considered
- [x] Backward compatibility considered
- [x] Rollback path is clear for risky changes

Low risk. The change only adds favicon metadata and packages an existing application asset. Reverting the two source changes restores the prior browser-default icon.

## Related Issues

N/A
2026-08-23 11:11:06 +00:00
gloryfromca
56858acbce fix(*): report an invalid memory identity as the config error it is (#350)
## Summary

An identity EverOS cannot accept becomes a directory segment on its
write path, so `EverosBackend.start()` rejects it. The rejection carried
the one message a user can act on -- it names the key and the accepted
pattern -- and no surface delivered it as one. Three of the four call
sites fold the raise into `logger.exception`; under the TUI loguru is
file-only, so there an invalid identity turned memory off with nothing
on screen. The fourth, in `import_commands._build_and_run`, is not
wrapped at all, so the `ValueError` escaped as a bare traceback. Where
it was visible it was a traceback, which is not a thing a user reads as
"edit this key".

The state machine then told the user the opposite of the truth.
`start()` died before assigning a state, so `_state` stayed `UNKNOWN`,
which is not in `_NEVER_HAD_MEMORY`; every `store()` after it counted a
dropped write, and the session ended with:

```
1 turn(s) were not written to long-term memory because the memory service was
unavailable.
```

The service was fine. That sends the user to debug a server that never
broke.

**The change.** Catch the `ValueError` in `start()`, give it a
`BAD_IDENTITY` state, and file that state with the other two the user
must fix themselves:

- terminal, so a stray probe cannot promote it to `READY`;
- never-had-memory, so no dropped-write count and no outage wording;
- the message goes to stderr, matching what the unconfigured-LLM and
missing-binary paths beside it already do.

Two things came out of running it rather than reading it:

1. **The message needs escaping.** It quotes the accepted-character
class, and rich reads `[a-zA-Z0-9_.@+-]` as a markup tag and eats it,
leaving the user the pattern `^+$` to match their id against. The test
now pins the full class.
2. **`raven import` had the same defect on its own gate.** It kept the
outage wording and pointed at the server log, which holds nothing about
a config error. It now names the config keys instead.

Before / after, same config (`memory.userId: "bad/id"`), same command:

```
- 1 turn(s) were not written to long-term memory because the memory service was
- unavailable.

+ Long-term memory is off: memory.userId='bad/id' is not accepted by EverOS: it
+ becomes a directory segment on the write path, so it must match
+ ^[a-zA-Z0-9_.@+-]+$ and must not be '.' or '..'.
+ Fix memory.userId / memory.agentId in your config.json, then start a new session.
```

## Type

- [x] Fix
- [ ] Feature
- [ ] Docs
- [ ] CI / tooling
- [ ] Refactor
- [ ] Other

## Verification

Re-run after rebasing onto `d35e398c`, the current `main`.

```
uv run pytest tests/test_everos_backend.py tests/test_cli_import_commands.py \
              tests/test_everos_plugin_discovery.py -q
162 passed

uv run pytest -q
1 failed, 6478 passed, 43 skipped, 13 deselected

uv run ruff check <the four touched files>            All checks passed
uv run ruff format --check <the four touched files>   4 files already formatted
```

The one failure is
`tests/test_cli_theme.py::test_bold_accent_renders_styled_not_bare`. It
is pre-existing on this base: checked out `d35e398c` in a clean worktree
and ran `uv run pytest tests/test_cli_theme.py` there, same failure, 1
failed / 44 passed. It passes in isolation and fails when the file runs
as a whole, so it is order-dependent, and it is unrelated to anything
here. That file is untouched by this change.

Manual check, sandbox `RAVEN_HOME`, `memory.userId: "bad/id"`, `raven
agent -m "hi"`: prints the block quoted above, and the session no longer
ends with the dropped-write line.

- [x] Relevant tests pass locally
- [x] Relevant lint / type checks pass locally
- [ ] User-facing docs or screenshots are updated when needed

## Risk

Terminal-only wording plus one new enum member. No config, schema, or
protocol change; an identity that was accepted before is accepted now,
on the same code path. The only behaviour change for a valid setup is
none.

For an invalid identity the turn behaves as it did -- memory off, turn
completes -- and only what the user is told changes. Rollback is
reverting the single commit.

`ServiceState.BAD_IDENTITY` is new. Every consumer was checked:
`raven/cli/import_commands.py` (handled here) and
`tests/test_everos_plugin_discovery.py` (reads `READY` only).
`_may_spawn` allowlists `UNKNOWN` via `_SPAWNABLE_STATES`, so a new
member is non-spawnable without a change.

- [x] Security impact considered
- [x] Backward compatibility considered
- [x] Rollback path is clear for risky changes

## Related Issues

Fixes #271

Co-authored-by: zhanghui <23442919+gloryfromca@users.noreply.github.com>
Co-authored-by: Claude (claude-opus-5[1m]) <noreply@anthropic.com>
2026-08-20 14:41:45 +08:00
arelchan
bbd5b6f1b5 feat(subagent): discover the vendored raven builds and install them from the page
## Summary

The four raven builds under `subagents/` were reachable only by running each folder's `install.py` by hand, while four rows the package hardcoded -- `research-raven`, `code-raven`, `data-raven`, `content-raven` -- sat on the agent table looking like agents. They were not. The backend factory reads four fields off a built-in row (`model`, `restrict_to_workspace`, `tools`, `skills`) and all four were unset on all four rows, so every one of them dispatched the same provider, the same model, the same tool set and the same system prompt; the sub-agent was never even told which name it ran under. What they had was four descriptions on the roster, which is why the dispatching model wrote `research-raven` on a node -- it was picking off a menu, not from the work. Per-step differentiation was always in `promptTemplate`, and it still is.

So the labels are gone and the real builds take their place, discovered rather than written: a folder shipping a manifest and an installer becomes a `cli` row on every table build, and deleting the folder removes the row. Composition happens inside `AgentRegistry.apply` for the reason `enabled_agents` documents about its own filter -- six paths hand it a config list, and composing at the boundary would be six places to keep in step.

Three failure modes this had to be built around, each of which would have been silent:

- a folder's venv lives inside its own checkout, and a wheel install is replaced wholesale on upgrade, so a tree under site-packages loses every venv each time. The tree is installed out to the raven home under a version stamp; the stamp is also what makes deleting a folder stick, since a same-version start is a no-op.
- the launchers inherit the host raven's whole provider block when a folder has no key of its own, so gating readiness on the folder's own key would have disabled every row on a correctly configured machine.
- `install.py` bakes an absolute path into the row it writes, and a config row otherwise beats a discovered one, so a stored row would keep naming a launcher an upgrade had deleted.

An unready folder is listed and disabled rather than dropped: `venv_ready` already records why a name the model can pick and then fail on is worse than no name, and dropping it would hide the folder from the operations view that exists to show "present, not set up". Onboarding now offers to build one instead of only mentioning that it is unbuilt, and no longer registers anything -- the row `install.py` used to write is the stale-path hazard above.

The beta wheel carries the tree through a force-include added to the same temporary pyproject rewrite that stamps the version, exported from git rather than copied from the working tree: force-include bypasses hatch's exclusion patterns, and a directory reference would ship four venvs and a `.env` holding a live credential. The GitHub release builds from the committed pyproject, so a stable release is unaffected -- no size change and no extra rows for anyone who did not opt into beta.

Eight further defects were found by opening the page rather than by reading the diff, and are the second and third commits:

- `subagents.list` assembled its own view and never asked the discovery layer, so the four folders were absent from the one screen a human reads to answer "what can it dispatch to". On the screen built to say they installed, that reads as "they did not".
- all four then reported "installed, ready" while three could not start: the probe launches nothing and checks the command's first token, which for one of these is the interpreter and always exists. The readiness verdict now overrides the probe and carries the reason.
- the rows landed in the "connect one" section behind a Connect button they cannot honour, having no preset to install from and no row to write.
- adding the flag that fixes that took four edits, because one row shape is declared in four places: the OpenRPC contract, the pydantic model that validates the response with `extra=forbid`, the island's TypeScript type, and the live data source -- which is a whitelist, so a field it does not name is a field the page never sees.
- the switch on a discovered row answered `subagent_not_found`, because `subagents.toggle` creates an override row for a built-in name and refuses anything else.
- `"enabled": false` in a folder's `subagent.json` did nothing: the readiness verdict overwrote it, so the manifest carried a field the code accepted and ignored.

The fourth commit adds the action the section existed to make reachable. A folder that is not built has its code and lacks its dependencies, and the only way to supply them was a terminal -- the card said "run subagents/install.sh raven-ppt" and left, which most readers do not do, so four agents that shipped read as four that are broken. `subagents.build` runs the tree's own installer for one folder, returns as soon as it is under way (one measures 627 MB and several minutes, so holding the request open would time it out and leave the build unobservable), and the row carries `building` until it finishes. Two things are read back rather than trusted: success is `venv_ready` on the filesystem rather than the installer's exit status, and a build in flight outranks the reason it is fixing so the card stops saying "go run this" for the minutes it takes. Delegated to `install.sh` rather than calling `uv sync` here because that script knows each folder's optional-dependency extra -- `raven-ppt` really does resolve as `uv sync --extra ppt`.

Stored playbooks naming one of the retired four are repointed at `raven`, by name and not by the `-raven` suffix. Left alone they would fail validation, and the failure is invisible: the runtime warns and the playbook drops out of the library.

## Type

- [x] Feature
- [ ] Fix
- [ ] Docs
- [ ] CI / tooling
- [ ] Refactor
- [ ] Other

## Verification

Ran on the branch rebased onto `origin/main`:

- `uv run --frozen pytest tests/` -- 9557 passed, 9 failed. The nine are environment-specific and fail identically on a clean tree (verified by stashing): `test_cli_update_notice` reaches the release registry, `test_start_webapp` needs bash 4 and this host has 3.2.
- `make coverage && make coverage-diff` -- diff coverage passed the 90% threshold. `make coverage-ratchet` -- line 79.38% -> 80.11% (+0.73pp), branch 69.17% -> 69.95% (+0.79pp).
- `uv run --frozen ruff check` and `ruff format --check` -- clean.
- `make lint-ui`, `make lint-tui` -- clean, including the `openrpc.json` -> `generated.ts` and `messages.json` -> catalogue sync checks (both regenerated in this branch).
- `npm run test --prefix ui` 373 passed, `npm test --prefix ui-tui` 1301 passed.
- `node ui/scripts/check-page.mjs`, `count-shared-globals.mjs` (24 of a ceiling of 24), `check-css.mjs` -- clean.
- `make lint-bridge` was not run: this host has no `tsc` in `bridge/node_modules`. `bridge/` is untouched.
- 20 mutation checks on the new logic (readiness gate, placeholder resolution, version stamp, host-key inheritance, installer-presence test, refresh-preserves-venv, stale-row guard both ways, playbook migration both ways, the page's section split both ways, the manifest's declared `enabled`, the switch variant both ways, build-verdict-from-exit-status, the one-build-at-a-time guard, the stale reason during a build, the failure reason reaching the row, the `building` flag reaching the row). All 20 were caught by the tests.
- End to end on the served page, twice. With one folder's venv built by hand: the row flips to enabled, reaches the dag tool's `subagent` enum and the roster the model reads, tagged `no-progress`; the other three list with the exact command that would build them. Deleting a folder drops its row on the next table build. And through the page's own Install button on a second folder: `uv sync --extra ppt` ran for real, the button held "Installing..." and disabled, the row flipped to ready on its own when the build finished, and the name then appeared in the graph tool's `subagent` enum. An actual dispatch to a vendored agent was not run -- it spends the host's LLM budget -- so verification stops at backend construction plus the launcher, interpreter and venv paths all existing.

- [x] Relevant tests pass locally
- [x] Relevant lint / type checks pass locally
- [x] User-facing docs or screenshots are updated when needed

## Risk

User-visible changes:

- the four label agents are gone from the roster. A dag node or playbook naming one is migrated to `raven` on load; a hand-typed name is refused by the tool's enum, as any unknown name is. Nothing that ran before runs differently, because all five rows dispatched identically.
- the roster the model reads shrinks from ~299 tokens to ~61 on every request that carries the spawn or graph tool.
- an install that has the `subagents/` tree gains up to four rows, disabled until each folder's venv is built. A wheel without the tree gets a byte-identical table to before.
- `subagents.list` grows `vendored` and `building` booleans, and `subagents.build` is a new method. Both fields are optional in the contract, so a client that predates them is unaffected.

Rollback: revert the four commits. The discovery layer writes no config, so there is no stored state to undo. The one thing it does write is a copy of the packaged tree under `~/.raven/subagents/` with a `.raven-version` stamp; deleting that directory is a complete rollback of it.

Not covered here, and deliberately: the beta wheel does not build the venvs (`.venv` is platform-specific and absolute-path bound) and does not ship credentials, so a fresh beta install shows the four rows disabled until something builds them -- either `raven onboard`, which now offers to, or the page's own Install button. Neither happens by itself: one venv measures 543 MB and 320 packages, which is not something to do silently at install time.

## Related Issues

N/A
2026-08-21 02:23:10 +00:00
arelchan
feacba682c refactor(ui): the session rail becomes a react island
## Summary

The session rail (left sidebar) becomes a React island: `ui/src/features/rail/` with types, a plain external store (draw/skeleton/markNew/remove/rename, fold state on the `raven.gui.grpfold` localStorage key), the Row/Group/RailApp components with classes and DOM shape copied byte-for-byte from the legacy renderer, and 13 tests.

Key decisions:
- `SESS`/`cur` stay shared page globals: ten demo/live files write them (including whole-array rebinds), so the island owns no rows. It reads through `DS.sessions.snapshot()`, a closure over the rebindable bindings, re-read on every `drawList()`.
- Island actions go out through 9 new optional bridge verbs (`drawList, setCur, openSession, removeSession, renameTitle, dropDraft, pinPersist, openCron, navState`), each one a guarded one-liner in 155-bridge.js and late-bound so live rebinds keep winning.
- `plainTitle` moved into the bundle and is republished as `window.plainTitle` for its 6 legacy callers (same pattern as `cronExprHuman`).
- Shrink: demo/050-rail.js 222 -> 16 lines; live/010-boot-guard.js raw-DOM skeleton painter became one `RavenIslands.rail.skeleton()` call; live/030-sessions.js untouched (already renderer-free, its helpers are read by other domains).
- Pre-existing bug left as-is: live/080-overrides' rename persist wrapper queries `#title input` after the h1 swap and throws today; the island reproduces the demo DOM dance exactly rather than patching another domain in this MR.

Ratchet: 57 -> 57 (the strands touching this domain remain demo-declared/live-assigned by design; nothing new added).

Note: pipelines are currently red project-wide with `ci_quota_exceeded` (shared-runner minutes exhausted). Local gates below are the same commands CI runs; the pipeline should be retried once quota recovers.

Review round: the fake shell handed `markNew` an empty nav and a folded More group, so both of its branches were dead in every test -- exactly the part of the port that changed shape (`Object.keys(NAV_OF)` to `nav.pages`, `$('#' + p)` to `getElementById`, `MORE_ROWS[i][0]` to `nav.morePages[i]`). Two cases added with the real nav: a module page up marks its own rail button over the new-task row, and an open More group puts the mark on the row whose page is up while the parent gives it up and takes it back when folded. Both fail against a wrong port.

## Type

- [x] Refactor

## Verification

- `npm run --prefix ui type-check` clean
- `npm test --prefix ui` 49/49 (13 new rail tests)
- `npm run --prefix ui build` (223.95 kB IIFE) and `python3 ui/build.py` (1,094,616 bytes)
- `node ui/scripts/check-page.mjs` OK; `node ui/scripts/count-shared-globals.mjs` 57/57
- `uv run pytest tests/test_ui_language_repaint.py` 9/9
- Stub browser pass (`?stub=1`): DOM byte-compared to legacy (.grp/.sess shapes, aria-current moves, fold persistence, search, pin+persist, delete+undo toast, rename via top bar, running mark lifecycle, More flyout marks, zh/en repaint)
- Live pass against a throwaway gateway (temp RAVEN_HOME, dummy keys, nonce auth): boot shows exactly 6 skeleton rows with the legacy width formula while `data-counts="pending"` holds, then the real list swaps in; draft's first send creates a real session; two-session switching moves a single mark; second boot renders with no mock flash
- Not exercised live: a successful provider turn and parked done/err badges (needs a real key); covered by unit tests and the stub replay

## Risk

User-visible behavior is intended to be identical; the rail DOM shape and class names are unchanged. Rollback is reverting the single commit.

## Related Issues

N/A
2026-08-20 06:17:21 +00:00
arelchan
e32f4b6034 fix(*): keep migration notices off stdout, and stop planting defaults (#346)
## Summary

Three follow-ups from #341, which fixed a retired `contextWindowTokens:
65536` capping every upgraded install at 64k. Two are its loose ends;
the third is the reason it happened at all.

**The notice no longer prints on stdout.** #341 drains config-migration
notices in the `run()` wrapper so every command tells the user, which
caught the two whose stdout is a machine-readable document: `raven
doctor --json` and `raven import --json`, both advertised for
automation. Reproduced -- a config still carrying the retired pin makes
`doctor --json` emit JSON with a sentence after it, and `jq` refuses the
result. Moved to stderr, where the rest of this class of message already
goes (the `ConfigReadError` branch a few lines up in the same wrapper,
and the loader's malformed-config warning). That fixes any future
`--json` command without it having to know this exists, which
allow-listing the two would not. The window is narrow -- the migration
fires once per install -- but the run it can spoil is a first run after
upgrading, and a CI job is exactly the caller not watching.

**`raven doctor` gains a Config section and a `--fix`.** The premise
changed while building it: the migrations run at load, so by the time
this command looks, nothing is pending -- they already happened,
silently, one launch ago. What is left for a person to ask about is what
Raven deliberately will not decide for them. So it reports a
`contextWindowTokens` pinned below what the configured model holds, and
names what rides on it: the per-turn history budget, when the Curator
starts paying for a slow path, and when memory consolidation archives.
`--fix` removes the pin.

Reported without `--fix`, never written: that pin is a real
configuration for a local model or an endpoint served smaller than the
catalogue thinks, and the flag is the user saying which case theirs is.
The write carries the file mode across (config.json holds
`providers.*.apiKey`) and uses a per-PID temp name -- the same rules the
loader's migration writer follows.

One check rather than two. A config naming no provider is the other
thing worth asking about, but it reads differently on either side of the
explicit-provider rule in #284, so it belongs to that change; a model
that routes to nothing is already reported above it.

**The bootstrap stops writing every default into the user's config.**
This is the cause of the bug #341 cured. `save_config` dumped the whole
`Config()`, so a new install started life with eight kilobytes of
settings its owner had never heard of and, worse, with that day's
defaults frozen into their file -- after which a default we improve
never reaches anyone who already has one. `contextWindowTokens: 65536`
got onto disk exactly this way.

It now writes only what differs from the defaults. Lossless on reload,
since a value equal to its default reloads as that default. A fresh
config drops from 7,985 bytes to 2, and to 634 once the extension blocks
are seeded -- what is left is the handful of lines someone actually
chose, which is also a config they can read.

That third one is the only change here with a broad blast radius, and it
has one visible consequence, which is an improvement: the onboarding
picker used to lead with the schema's default model, because the
bootstrap had written it into the config and the wizard read it back as
"the current model" -- a value nobody had chosen, offered as though
somebody had. With nothing written, the wizard leads with the provider's
own recommendation instead. The test that pinned the old list now pins
the new one and says why.

## Type

- [x] Fix
- [ ] Feature
- [ ] Docs
- [ ] CI / tooling
- [ ] Refactor
- [ ] Other

## Verification

```
pytest tests/                       6650 passed, 1 failed, 33 skipped
                                    (tests/test_cli_theme.py::test_bold_accent_renders_styled_not_bare,
                                    which fails identically on github/main when its file runs
                                    together and passes alone on both)
ruff check raven/ tests/            All checks passed
ruff format                         clean
```

Driven by hand as well as by tests, each against a throwaway home:

```
doctor --json on a fossil config   stdout parses as JSON again; the notice is on stderr
doctor    (pin 65536, model 1M)    reports the pin and what is sized against it
doctor --fix                       pin removed, file still 0600, a second run reports nothing
save_config on a fresh Config()    2 bytes; 634 after the extension blocks are seeded
```

New cases cover the stderr split, both doctor paths including the mode
preservation, and the save round-trip keeping every value the user
chose.

- [x] Relevant tests pass locally
- [x] Relevant lint / type checks pass locally
- [ ] User-facing docs or screenshots are updated when needed

## Risk

The bootstrap change alters what every new install's config file looks
like: nearly empty instead of a full dump. Existing configs are
untouched -- nothing rewrites them -- and both shapes load identically,
so the risk is confined to anyone reading `config.json` as documentation
of what can be set. `raven doctor` and the schema remain the answer to
that question.

The onboarding picker's default moves from the schema default to the
provider's recommendation, as described above.

`doctor --fix` writes only when asked, and only removes a key.
Everything else here is output routing.

Rollback: revert the commits. Nothing persists a new format, so a
reverted build reads every config written under this one.

## Related Issues

N/A

---------

Co-authored-by: arelchan <204152633+arelchan@users.noreply.github.com>
Co-authored-by: Claude (claude-opus-5) <noreply@anthropic.com>
2026-08-18 18:55:29 +08:00
arelchan
e91431c93b refactor(ui): the schedules page becomes the first react island
## Summary

Stacked on !110 (target is its branch; retarget to main when it merges). The schedules page becomes the first React island -- the pattern MR for the framework migration the team agreed on.

What moves and what stays:

- `ui/src/features/cron/` gains the renderer as a React component reading the same `DS.cron` source. Class names and DOM structure are copied from the legacy renderer; `ui/src/styles/page.css` is untouched, so the page is pixel-identical (screenshot-verified in both modes).
- `ui/src/demo/140-schedule.js` shrinks from 442 lines to 73: five one-line shims (the names the rail, palette, Esc handler and the live layer still call: openCron/closeCron/refreshCron/drawCron/cronWarm) plus the fixture source, unchanged. The live rpc source (`live/100-schedules.js`) is untouched.
- Two page-wide seams carry the interop, each growing one line per need: `window.RavenShell` (demo/155-bridge.js, late-bound closures so the live layer's toast rebind wins) and `window.DS` (published by the seam part -- a separate script cannot see the page script's lexical scope).
- Vite builds the island as one classic IIFE; `build.py` inlines it at `/*__MODERN__*/` ahead of the page script. The one-file dist contract holds. `check-page.mjs` now pins the two-inline-script shape, and also rejects raw `</script` closers and `<!--` inside script payloads (both break inline-script parsing at the HTML layer, which `node --check` cannot see).
- Page assembly now has a node step: `npm run --prefix ui build` before `python3 ui/build.py`. The GitHub `unit`/`page`/release steps pick it up; a follow-up commit on !108 does the same for the GitLab job (guarded, so branches without `ui/package.json` are unaffected).
- Form inputs stay uncontrolled and mutate the draft in place -- the discipline the legacy form kept -- so focus and IME composition survive typing; only a frequency change or a refusal redraws.

One deliberate behaviour nit: reopening the sheet after a blank-save refusal used to flip the title from "new schedule" to "edit schedule" (the legacy call passed the draft back in). The island keys the title off `draft.fresh`, so it stays "new schedule".

## Type

- [x] Refactor

## Verification

- `npm run type-check` clean (strict, noUncheckedIndexedAccess); `npm test` 15/15 -- the island driven through the same two seams production wires (fake RavenShell, fixture DS.cron), covering rows/empty/failing-banner render, detail open/back, refused save landing under the control, blank-draft per-field notes, handled-delete keeping the reader in place, toggle+refetch.
- `python3 ui/build.py` + `check-page.mjs` (1,100,055 bytes, 2 scripts parse) + `count-shared-globals.mjs` 63 (ceiling 63) all green.
- `uv run pytest tests/test_ui_language_repaint.py tests/test_cli_gateway_page.py`: 14 passed -- the language-flip guard still finds the cron renderer through the shim.
- Stub mode (`?stub=1` over a throwaway http.server): open page, rows/hero/failing banner, detail open/back, draft text survives a language redraw, sheet focus lands on the name field, blank refusal notes, cancel, toggle with toast, aria flip, row menu (4 items), confirmed delete removes the row, Esc closes the page.
- Live mode (throwaway gateway, temp RAVEN_HOME, dummy keys): empty state from a real server; create through the sheet -- refuse-without-instant shows the need-instant note, then a real `cron.save` lands "once tomorrow 09:00" as a row; toggle pauses via `cron.set_enabled`; delete via detail returns to the empty list. Environment torn down after.

## Risk

- The page build now requires node+npm (release and CI already run node for ui-tui). A checkout without the bundle fails `build.py` with instructions rather than shipping a page whose schedules tab is blank.
- Island bundle adds ~200 KB to the one-file page (React 19 production). Known, accepted in the migration plan.
- Rollback: revert the commit; the legacy renderer returns whole.

## Related Issues

N/A
2026-08-19 10:04:28 +00:00
arelchan
8325c81d2b feat(cli): tell every tester about a new build within a minute
## Summary

A newly published beta reached its testers on a 30-minute poll. `make beta` moves
the pointer, and every tester is on another machine with no inbound path from the
publishing host, so `_announce_updates` in `raven/cli/serve_commands.py` was the
only thing that carried a build to them: first look 90s after boot, then once
every half hour.

This makes that poll fast instead of adding a second delivery route.

**The pointer is cheap to watch, so watch it often.** Measured against the live
channel: `latest/latest.json` in the GitLab generic package registry is 23 bytes,
returns an `ETag`, and honours `If-None-Match` with a 304 and no body. So the
update cache now keeps that validator next to the version it read, and
`beta_channel.read_pointer` sends it back. An unchanged channel costs one
conditional request and zero bytes of body, which is what makes a 60-second
interval affordable: the cost of looking stopped scaling with how often we look.
A tester is now offered a build within about a minute of the publish.

**The fast path is the beta channel's, and stable keeps its half hour.** The
interval is chosen per tick from `beta_channel.is_active()`, not a single
constant:

- `_UPDATE_POLL_BETA_S = 60` -- a beta lands whenever a maintainer runs
  `make beta`, this poll is the only route to a tester, and the check is a
  conditional request against a 23-byte pointer in a registry that is ours.
- `_UPDATE_POLL_STABLE_S = 30 * 60` -- unchanged, deliberately. A stable release
  lands on a cadence of days, and its check reads GitHub's release-page redirect
  rather than our own registry. A minute there would spend someone else's budget,
  from every install behind one shared egress, to learn nothing about 43,000
  times a month. Nothing on the stable channel checks more often than before.

Read per tick and not once at startup because joining or leaving the channel is a
file appearing or being deleted, and a resident gateway should follow that without
a restart.

**A registry that stops answering is not polled every minute forever.**
`_refresh` now reports whether its source answered, `update_notice.check_now`
passes that up as `Checked(latest, reached)`, and the announcer doubles its wait
on consecutive failures: 1, 2, 4, 8, 16, 30 minutes, ceiling
`_UPDATE_BACKOFF_CEILING_S = 30 * 60`. An offline gateway therefore settles at
exactly the cadence it would have used had it never joined the channel, and one
answer -- a 304 counts -- puts it straight back to a minute. The stable channel's
base already equals the ceiling, so its cadence never grows. The exponent stops
at `_UPDATE_BACKOFF_STEPS = 5`, past which the ceiling has already won.

`check_for_update` keeps its old signature and its callers; it is now the thin
half of `check_now`, for callers with nothing to pace.

**What a 304 is allowed to change.** It updates `checked_at` and nothing else.
That stamp is what `maybe_refresh_async` reads to decide whether a launch needs a
refresh thread at all, and a pointer confirmed unchanged is as fresh an answer as
exists -- treating it as "no answer" would spawn a thread on every launch for a
channel that has not moved. The version and the validator are kept as they were.
One guard is worth naming: a validator is only offered when a version is cached
beside it, because a 304 means "unchanged from what you have" and an orphaned
etag would otherwise pin the notice off until the pointer happened to move.

**The announce seam stays.** `register_system_methods(dispatcher, *, channel,
send_frame=None)` takes the transport's broadcast sink, threaded from
`raven/rpc/bootstrap.py` -- the same shape `register_browser_methods` already
uses. A `system.version` call with `check: true` that finds a newer build now
announces `system.update_available` to every connected client instead of
answering only the caller, so one window's settings button updates the banner in
all of them. `bootstrap.py` also stops registering the four `system.*` handlers
by hand; the registered behaviour is identical, including the `LOCAL_CHANNEL`
default. The frame is byte for byte the one `_announce_updates` sends, which
`ui/src/live.js` already handles at `rpc.notify['system.update_available']`. Only
an explicit `check: true` announces; a plain `system.version`, which every page
calls at boot, does not, or one tab opening would banner all the others.

**The publish-time nudge is gone.** The first round of this MR also had
`scripts/publish_beta.py` open a WebSocket to the `raven serve` on the publishing
machine after a publish and ask it to check now. It only ever helped the one
machine that runs `make beta`; every actual tester still waited out the poll. It
solved a small fraction of the problem and put a credential-reading network path
and two stub-server tests into a release tool, so `nudge_local_serve`,
`_ask_serve_to_check`, that file's own `_pid_alive`, `_NUDGE_TIMEOUT_S`, the call
site, and the test class covering them are deleted. What `make beta` prints at the
end now names the real mechanism.

**On the two review findings about the nudge.** Both were real and both are moot,
because the code they applied to no longer exists: the unbounded receive after
the WebSocket upgrade (aiohttp clears the protocol read timeout, so
`ClientTimeout(total=)` bounded only the handshake) and `receive_str` raising on
a binary broadcast frame such as a browser view's screencast. Neither can recur
here -- nothing in this MR opens a client WebSocket. They are recorded rather than
quietly dropped in case the idea is ever revived.

## Type

- [ ] Fix
- [x] Feature
- [ ] Docs
- [ ] CI / tooling
- [ ] Refactor
- [ ] Other

## Verification

**Manual proof against the live channel, read-only, nothing published.** The
conditional request working end to end, first through curl and then through the
code path itself:

```
$ curl -s -H "DEPLOY-TOKEN: $TOKEN" -D h1 -o b1 \
    -w "http_code=%{http_code} size_download=%{size_download}\n" \
    "https://gitlab.com/api/v4/projects/85454048/packages/generic/raven/latest/latest.json"
http_code=200 size_download=23
    content-length: 23
    etag: "c9b42d2d49073b997392efac6d687308"
    body: {"version": "0.1.12b6"}       (23 bytes)

$ curl -s -H "DEPLOY-TOKEN: $TOKEN" -H 'If-None-Match: "c9b42d2d49073b997392efac6d687308"' ...
http_code=304 size_download=0
    etag: "c9b42d2d49073b997392efac6d687308"   (no body at all)
```

Then the same two requests through `beta_channel.read_pointer` and
`update_notice._refresh`, with the cache redirected to a scratch path so nothing
in the real agent home was written:

```
[1] unconditional read_pointer
    unchanged = False | version = 0.1.12b6 | etag = "c9b42d2d49073b997392efac6d687308"
[2] conditional read_pointer (If-None-Match)
    unchanged = True  | release = None     | etag = "c9b42d2d49073b997392efac6d687308"

wire log  (status, if-none-match sent, content-length, body bytes read)
    (200, None, '23', 23)
    (304, '"c9b42d2d49073b997392efac6d687308"', None, 0)

[3] _refresh end to end
    first  _refresh() -> True   latest_version=0.1.12b6  etag="c9b42d2d..."
    second _refresh() -> True   latest_version=0.1.12b6  etag="c9b42d2d..."
    version survived the 304: True     etag survived the 304: True
    checked_at moved on the 304: True
```

**Test suite.** `uv run pytest tests/ -q --ignore=tests/integration`

- Baseline, a throwaway worktree at `origin/main`: 12 failed, 8978 passed, 43
  skipped, 13 deselected.
- This branch: 12 failed, 9004 passed, 43 skipped, 13 deselected.
- The same 12 in both, all inside `tests/test_cli_update_notice.py` and
  `tests/test_cli_upgrade_commands.py`. They are pre-existing and local to this
  machine: their fixtures do not isolate `RAVEN_HOME`, so they read the developer's
  real `~/.raven/beta.json` and take the beta path. Re-run with an isolated home,
  both files are green before and after the change:
  `RAVEN_HOME=<tmp> uv run pytest tests/test_cli_update_notice.py
  tests/test_cli_upgrade_commands.py -q` gives 147 passed on `origin/main` and 156
  passed here. No test outside those two files fails.
- The four files this MR touches, run together: 175 passed.

**New tests.** A 304 keeps the cached version, keeps the validator, stamps
`checked_at`, and is never parsed as a body; a 200 with a new ETag updates both;
an orphaned validator is not offered; the stable path stores no validator; a
failed read reports `reached=False` and keeps what it had; the poll is 60s on the
beta channel and 30 minutes on stable and is re-read per tick; the delay doubles
to a 30-minute ceiling and one answer resets it, asserted through the loop's own
bookkeeping as well as the arithmetic; and `fetch_latest` still reads
unconditionally and refuses a 304 it did not ask for.

**Lint.** `uv run ruff check` and `uv run ruff format --check` on all nine touched
files: clean.

- [x] Relevant tests pass locally
- [x] Relevant lint / type checks pass locally
- [ ] User-facing docs or screenshots are updated when needed

## Risk

**Request volume.** On the beta channel a resident gateway goes from 48 checks a
day to about 1,440, each one a conditional GET against our own package registry
that answers 304 with no body while nothing has changed. The tester population is
small and the registry is ours, so this is the cost being accepted deliberately.
The stable channel is untouched at 48 a day against GitHub, which is the number
that was chosen to protect a shared egress.

**A refusing registry.** The backoff is what stops a minute-cadence loop from
hammering a source that has started answering 401 or 5xx: consecutive failures
double the wait to a 30-minute ceiling. Before this change there was no backoff
at all, but there was also nothing tighter than 30 minutes to back off from.

**Credentials.** Unchanged. The deploy token still travels in the `DEPLOY-TOKEN`
header on the pointer read, `~/.raven/beta.json` is still read and never
rewritten, and the ETag added to `update_check.json` is a registry-issued opaque
string, not a secret. This MR removes the only path that read `serve.json`'s
shared secret for a network call.

**Backward compatibility.** `check_for_update` keeps its signature and its
answer. `register_system_methods` grows a keyword-only argument that defaults to
the old silent behaviour, so the TUI transport, the demo runner and every test
that registers without a sink are unaffected. `system.version`'s response shape
is unchanged, and no schema change is needed:
`rpc-schema/openrpc.json` declares only request/response methods, and
`system.update_available` is a notification, as `turn.event` and `mcp.status`
already are. An `update_check.json` written by an older raven has no `etag` key,
which reads as "no validator" and costs exactly one unconditional request.

**Rollback.** Revert the commit. The pieces are independent: restoring
`_UPDATE_POLL_S = 30 * 60` alone returns every channel to the old cadence without
touching the ETag work, and dropping the `send_frame` argument in
`raven/rpc/bootstrap.py` alone restores the old caller-only version check.

Deliberately left out: nothing in `ui/` (the client already handles this
notification), and no push mechanism -- a tester's machine has no inbound path, so
polling a cheap pointer is the delivery route, not a fallback for one.

## Related Issues

N/A
2026-08-18 13:58:16 +00:00
arelchan
5fb280c015 feat(*): land the served page's acceptance rounds and the panels
## Summary

The remaining local work, on one branch, because it could not land as the four MRs it was spread across. Replaces !54, !45 and !42; !43 is superseded and explained below.

`chore/stack_on_main` was the integration branch for the stack that has now landed on `main` one MR at a time. Of its 28 commits, 24 are pre-squash copies of !24 through !34 -- rebasing it would replay each against its own squashed self. So nothing was rebased: the four commits that only exist there were cherry-picked onto `main`, then !45's own 46, then the one commit of !42's that !45 does not already contain.

**From the integration branch (4).** A `subagent.*` method group that reads a spawn's stored record so a client can draw what a call did; the browser driver's own test suite, which !33 landed without; a write tool that reports what it changed on disk rather than answering "ok"; and a per-surface name in traces, because every front end shares the RPC stack and so reported `channel="tui"`.

**From !45 (46).** Four acceptance rounds on the served page, the DAG graph view and its live clocks, the sub-agent panel with tool calls and token cost, `session.pin`, the file surface rooted at the session workdir, and the last three commits you reviewed this morning -- a graph node now keeps a transcript of its own (`<node>.transcript.jsonl`) and registers a live key, which is what a node's panel had been missing.

**From !42 (1 of 2).** `fix(ui): let a sub-agent answer rename only the header it was opened from`. Its other commit is `2b6fbeb` on !45, same change.

### !43 is superseded, not merged

Two of its five commits are already on !45 under different hashes (`4df2cc7`/`e90d4ac`, `8db1a32`/`08f65e4`). The other three are written against a DAG renderer !45 replaced -- !43 draws with `el()` and a clip path, !45 with `svgEl()`, a `dagMark` status glyph and a `d.els` clock map. Cherry-picking them onto !45's renderer conflicts in four hunks that are two implementations of the same picture, and hand-merging those is how one side's fix disappears without the diff showing it.

So they are not in this branch, and they are real behaviour worth keeping. Filed rather than smuggled:

1. **The sheet rebuilds on every node update.** A five-node run rebuilt it twelve times, so it slid up from below twelve times while the reader watched, losing canvas scroll and focus each time. !45 has no repaint path (`grep dagRepaint` on its tip: 0 hits).
2. **A long node name runs over its own duration** and prints into the next column. !43 clips it and puts the full name in a `<title>`.
3. **The agent list's redraw tears down an open node**, and a finished run cannot be folded again.

I would rather do those three as a follow-up MR against this renderer than fake a merge here.

### Conflicts resolved, and the two that were judgement calls

Nine conflicts. Six were mechanical (a hook declaration where both sides added one, a comment both sides reworded, generated i18n regenerated from the merged catalogue rather than hand-merged). Three were not:

**`raven/rpc/files.py` -- the state-directory fence.** Both sides fixed a real hole and neither had the other's. `main` iterates `_raven_state_roots()`, two roots, because `RAVEN_HOME` moves `serve.json` while the credential store hangs off `get_config_path().parent`, and a fence on either one leaves the other's OAuth tokens as ordinary paths. !45 collapses the fence into one `in_state_dir()` so the viewer, `fs.reveal` and the `fs.*` panel cannot answer differently -- and carves out the workspace subtree, because the default workspace lives *at* `<raven home>/workspace` and without it the fence denied every file the agent itself wrote. Taking either side loses the other's hole. The merged function is one fence over both roots, with the carve-out.

**`raven/agent/subagent/manager.py`.** `main` passes `provider`/`model` into `backend.run` and writes spawn status around it; !45 wraps the whole block in `activity.collecting()` and hands `activity=did` to every `record.finish`. Kept main's body, indented into the collector, with `activity=did` on all four exits -- so a cancelled or failed run still reports the tool calls and token cost it got as far as producing, which is the point of the collector.

**`raven/agent/subagent_dag/runner.py`.** `main` takes a shared dispatch gate (`semaphore if semaphore is not None else ...`); !45 adds a `node_activity` map and made its own semaphore. Kept main's gate and !45's map.

One commit's message was reworded while re-committing it: `866e1c5` had three Chinese lines in its body, which AGENTS.md 3.1.1 forbids. It is ASCII now.

## Type

- [ ] Fix
- [x] Feature
- [ ] Docs
- [ ] CI / tooling
- [ ] Refactor
- [ ] Other

## Verification

```
uv run ruff check .                              All checks passed
uv run pytest tests/ -q                          6 failed, rest passed
make build-ui                                    built dist/index.html (856,308 bytes)
                                                 copied dist/assets (283,892 bytes)
ui-tui: node scripts/gen-rpc-types.mjs --check   OK: in sync (sha256 d81cf0b3e94e)
ui-tui: node scripts/gen-i18n.mjs                regenerated, no diff
git grep -E "^<<<<<<< |^>>>>>>> "                no matches
```

All six failures reproduce on `main` with nothing from this branch applied, checked in a throwaway worktree rather than assumed: three `channels_qr` tests wanting channel adapters this environment has no deps for, `test_cli_theme.py::test_bold_accent_renders_styled_not_bare` reading a truecolor escape this terminal does not emit, and two `test_provider_rates.py` tests that resolve a context window through litellm's model map and get `None` here.

`HOME` is pointed at an empty directory for the run, because a developer's own `~/.raven/config.json` otherwise fails schema validation and reddens dozens of unrelated tests.

- [x] Relevant tests pass locally
- [x] Relevant lint / type checks pass locally
- [ ] User-facing docs or screenshots are updated when needed

## Risk

- [x] Security impact considered
- [x] Backward compatibility considered
- [x] Rollback path is clear for risky changes

The security-relevant change is the fence merge above; it is strictly narrower than either input on secrets and strictly wider on the workspace, which is the intent of both. The rest is additive: a new method group, new panels on a page that already shipped, and a richer stored tool entry.

Rollback is one revert of the squash. The four integration-branch commits and !45's line are independent of each other at the file level except in `ui/`, so a narrower revert is possible per area if it comes to that.

## Related Issues

N/A
2026-08-17 06:08:33 +00:00