Skip to content

Release 0.8.14: code in the browser, the notebook, and NEMAR's worked examples - #487

Merged
neuromechanist merged 53 commits into
mainfrom
develop
Sep 24, 2026
Merged

neuromechanist merged 53 commits into
mainfrom
develop

Conversation

@neuromechanist

Copy link
Copy Markdown
Member

Promotes develop to main: 52 commits, 172 files. The browser-execution epic (#429) and everything built on it since 0.8.13, plus CI-owned version bumps.

What reaches production

CHANGELOG.md has the full list under ## [0.8.14] - 2026-09-24 (#484, #485).

Other communities

No other community changes behavior. Every new surface is opt-in and defaults to what was there before: launcher defaults to bubble, color_scheme to light, and client tools bind only when both the community config and the caller declare them. No config.yaml other than NEMAR's is in the diff. The one change every community gets is a fix: the widget keeps its own field colors on a dark host page.

Embedders pinned by Subresource Integrity keep the old widget until they re-pin, since jsDelivr's GitHub mirror is immutable per commit.

Coupled release

nemarOrg/nemar-cli v0.10.6 (#1504, merged) ships get_events' where, columns and columns_summary, which NEMAR's prompt now teaches. It reached production first.

What changes at the edge on merge

  • deploy-notebook.yml runs on main for the first time. It creates the notebook.osc.earth DNS record and Pages custom domain if missing, each step checking before it creates. It has run cleanly on every develop push, where it maintains develop-notebook.osc.earth.
  • sync-worker-cors.yml deploys the edge Worker with the new /{community}/runtime/{file} and /{community}/chat/resume routes and one new origin, https://test.nemar.org.
  • The backend container follows on the hourly auto-update.sh cron. For up to an hour the edge serves the new routes in front of the old backend, which answers them 404. That is expected and passes through cleanly; a "notebook tab does not load" report in that window is not a regression.

Review

A release review of the full main...develop diff, with five parallel checks (workflows, deployment config, other communities, embedder defaults, backend API and limits), found no production blockers. Its findings were all changelog completeness, fixed in #484 before this PR. #486 marks the live HED validation tests as network, since a slow hedtools.org failed two PRs' unit jobs today. CORS, rate limits (/chat/resume has its own hourly budget, and a reply is capped at 20 browser runs), the runtime wheel route's sha256 check and the per-deployment resolution were each checked against the code.

A staging run on test.nemar.org (develop, 0.8.14.dev16) asked for a power spectrum and an ERP image of xx099906. Both ran end to end; the ERP image was unfiltered because the model wrote the prompt's low-pass as a single spike, which #485 fixes and tests.

Version

src/version.py is 0.8.14.dev18 or later. ensure-stable-version.yml strips the suffix on main; not hand-bumped.

After merge

  • ensure-stable-version.yml sets 0.8.14 and tag-release.yml tags it
  • deploy-notebook.yml on main green; curl -I https://notebook.osc.earth/osa/ returns 200
  • sync-cors production deploy green
  • https://api.osc.earth/osa/health reports 0.8.14 once the hourly cron has pulled
  • https://widget.osc.earth/osa/nemar/ resolves NEMAR's MCP server to mcp.nemar.org and fetch_allow to zarr.nemar.org
  • demo.osc.earth and the other communities' widgets unaffected

neuromechanist and others added 30 commits September 21, 2026 18:45
…435)

* feat: add rate-limit-only chat/resume route to osa-worker

POST /{community}/chat/resume had no matcher (three path segments vs
the two-segment ask|chat pattern) and fell through to 404. Route it
like /feedback: rate-limit-only, no Turnstile, since the resume POST
follows a client-executed tool call rather than a widget-composed
message and cannot carry a fresh single-use Turnstile token.

Also exempt it from the per-hour KV counter (checkRateLimit gains a
countHourly option) so that a turn with N browser executions costs
only its per-minute budget, not N extra hourly requests shared across
a NAT'd lab. The per-minute limiter is unaffected.

Route matchers are now exported as ROUTE_PATTERNS, and
isValidCommunityId/validateCommunityId are exported, so routing
behavior can be tested directly against the real patterns used by
fetch().

* test: add osa-worker routing tests

Hand-rolled bun script (matching frontend/test-streaming.js's style,
no test framework) covering: /chat/resume matches the new route and
the existing (ask|chat) route still matches unaffected; an extra
trailing segment matches neither; validateCommunityId rejects a
malformed or reserved community id on the resume path exactly as it
does on ask/chat; reserved top-level paths never match either
community route pattern. Imports and exercises the same ROUTE_PATTERNS
and validateCommunityId used by fetch(), not a parallel copy.

* ci: run osa-worker routing tests in both test workflows

Wire bun workers/osa-worker/test-routing.js into the frontend-tests
job in tests.yml and test.yml, beside the existing frontend checks.

* feat: define the browser tool result contract

What a browser execution may send back, and what the session keeps of it.
Images ride into run 2 and never enter stored history; the text is fenced and
labeled as data because the return path is an injection channel; every field is
sized before use.

Part of #430.

* fix: floor langchain-core at 1.6 for image token counting

count_tokens_approximately only learned to charge image blocks a per-image
penalty in 1.6. Before that any non-string content was repr()-ed whole, so one
figure measured near 100,000 tokens against an 80,000 budget and trim_messages
silently discarded the conversation. The floor admitted 1.2.0, and CI resolves
without the lockfile (#374), so this was reachable.

Corrects the claim in the design note and in #422 that this repository needs its
own image-aware counter. It does not; it needs a floor.

Part of #430.

* feat: hold a browser tool turn in the session and resume it

ChatSession widens to BaseMessage, learns to adopt a graph run's final message
list whole, and holds at most one pending browser call. Claiming is synchronous
on purpose: the session store has no locking, so the only thing keeping
check-then-clear atomic is that no await appears between them.

Adds POST /{community}/chat/resume, which is run 2 of the two-run continuation.
Authorization binds to the server-generated call_id rather than the session id,
because a client may choose its own session id.

An unanswered call is closed out with a synthetic tool message before the next
turn, since an assistant message carrying tool_calls with no matching result is
rejected outright and would make every later turn fail, not just that one.

Closes #422. Part of #430.

* test: drive the two-run continuation through the real graph

The graph, the routing, the client_tools node, the astream_events shape, the
SSE assembly and the session store are all real; only the chat model stands in.
An earlier draft replayed canned LangGraph events and was dropped: the fact this
phase most depends on is that the root graph's on_chain_end carries
pending_client_call, and a canned event proves nothing about that.

Adds a scripted chat model helper, because every langchain-core fake raises from
bind_tools, which BaseAgent catches and then runs with no tools bound at all,
silently removing the thing under test.

Allowlists /chat/resume in the verify_api_key guard test. It genuinely spends
the credential against an LLM, which is what that allowlist is for.

Part of #430.

* test: cover the client tool kill switch end to end

Asserted against a community that configures the tool AND a caller that
declared it, since that is the only case where the switch is reached. A switch
tested against a config that binds nothing would pass while doing nothing.

Part of #430.

* test: history trimming never orphans a tool call

Walks every cut point rather than one. A browser turn is four messages, so
three caps in four land where a naive cut is already safe; the first version of
this test picked such a cap and passed while measuring nothing. A companion
assertion confirms the hazard is real at some of the same points, so the two
together say the function both acts and is needed.

Verified by mutation: replacing the boundary search with a naive cut fails two
of these tests.

Part of #430.

* feat: add client tool config models

ClientToolConfig, RuntimeLimits, PythonRuntimeConfig, RuntimeConfig;
ExtensionsConfig.client_tools and CommunityConfig.runtime, plus a
cross-field validator requiring a matching runtime section. limits
defaults to RuntimeLimits() so a community need not spell out {}.

* feat: add client-executed tool class and binder

ClientTool (BaseTool subclass whose _run/_arun always raise),
client_tools_disabled kill switch, and build_client_tools, which binds
only the intersection of configured and caller-declared tool names.

* feat: route client tool calls to a parking node

BaseAgentState gains pending_client_call. BaseAgent takes
client_tool_names (derived from tools if omitted); _should_use_tools
adds a client_tools destination for any batch touching a client tool.
build_graph adds the client_tools node/edge-to-END only when needed,
so a community with none keeps the pre-existing graph unchanged.
The node runs server calls through a lazily-built ToolNode, parks the
first client call as pending_client_call with the provider's own
tool_call id, and rejects further client calls and unknown names with
an error ToolMessage.

* fix: charge images at Anthropic's rate, not OpenAI's

count_tokens_approximately defaults tokens_per_image to 85, which is OpenAI's
low-resolution cost. Anthropic bills roughly width*height/750 and caps near
1600, so the default under-counts a real plot by more than an order of
magnitude. Under-counting is the direction that fails: it means believing a
conversation fits when it does not.

Introduces count_conversation_tokens so the agent's budget check, its trimmer,
its post-trim log and the API's warning threshold cannot drift apart by one of
them forgetting the rate.

Part of #430.

* fix: address review findings on the browser tool path

Silent failures:
- A dropped root on_chain_end ended the turn as an ordinary empty done,
  dropping the model's request to run code platform-wide with nothing to alert
  on. The node's own event is now independent evidence a call was parked, and a
  disagreement between the two is a loud error carrying an id.
- from_state now requires every key. A renamed one parked a call with EMPTY
  args: no exception, no log, no failing test.
- _finish_with_tool_request validated after mutating, so a malformed payload
  left a session permanently unanswerable. It validates first now.
- claim_pending_call and the kill switch logged nothing. An operator flipping
  OSA_CLIENT_TOOLS_DISABLED had no server-side proof it took effect, and browser
  call timeouts were unmeasurable.

Correctness:
- set_pending_call refuses to silently replace an unanswered call.
- The tools node is built from server tools only, so a ClientTool is
  structurally unreachable rather than relying on langgraph's default handler.
- Resume metrics were recorded as /chat, folding the half that actually spends
  the credential into run 1's numbers.
- artifacts are bounded per item, not only in count.

Adds HTTP-level tests for /chat/resume, which had none. That gap let a real bug
through during this very change: the handler passed an argument the streaming
function did not accept, and the whole suite stayed green.

Part of #430.

* test: bind execute_code before invoking in the round-trip suite

Every invoke sent an unbound model a message list containing tool_use/
tool_result blocks. Follows the proven pattern in
test_anthropic_platform.py: declare a matching tool, bind it, invoke
the bound model everywhere. Cannot run locally (no ANTHROPIC_API_KEY);
confirmed it still imports and collects.

* test: pin BaseAgentState.pending_client_call's declared shape

The three tests built a dict literal annotated : BaseAgentState and
asserted on exactly what they wrote; TypedDict enforces nothing at
runtime, so deleting the field would not have failed any of them.
Replaced with introspection of __annotations__/__optional_keys__/
__required_keys__ against BaseAgentState and PendingClientCallPayload,
mirroring test_tool_results.py's technique for the reader's side.
Verified by deleting the field and confirming 3 of 5 tests fail, then
restoring.

* test: narrow ExecuteCodeArgs required-field checks to ValidationError

pytest.raises(Exception, match=...) would also pass if a missing field
became a mere warning. ExecuteCodeArgs is a pydantic BaseModel, so
narrow to pydantic.ValidationError, matching every other test in the
file.

* test: cover a pure-server batch when client tools are also bound

Every existing case in TestShouldUseTools either binds no client tool
at all (client_tool_names empty, so the & check in
BaseAgent._should_use_tools is never reached) or already includes a
client call (where & and | agree). Add the one case that
distinguishes them: an agent with both a server and a client tool
bound, given a server-only batch, must route to "tools". Verified by
mutating & to | in src/agents/base.py: only this new test fails (19
others still pass), then reverted.

* test: pin that /ask never binds a client-executed tool

AskRequest has no client_tools field and neither ask() branch passes
declared_client_tools to create_community_assistant, so it defaults to
None; nothing pinned this, and a copy-paste from ChatRequest would
silently violate it. Asserts on real behavior: the field is absent
from AskRequest.model_fields (and a passed value is dropped, not
rejected -- AskRequest is extra="ignore" by default, not
extra="forbid" as initially assumed), and a CommunityAssistant built
the way ask() builds one, against a config with a client tool
configured, binds none of it (checked via the model's own recorded
bound_tool_names).

* test: drive real fetch() dispatch for chat/resume routing

test-routing.js only exercised ROUTE_PATTERNS regexes directly, so wiring
bugs in the fetch() dispatcher and options bugs in the rate-limit calls
were invisible. Add dispatch-level tests that call the real, exported
fetch() handler with a stub env (KV, per-minute limiter, and outbound
fetch stand-ins), and assert on response status/body:

- /chat/resume never requires or verifies a Turnstile token; /chat does.
- /chat/resume is exempt from the /chat hourly KV counter; /chat is not.
- the per-minute limiter is still consulted for resume, and its rejection
  still yields a 429.

Confirmed each new assertion can fail: deleting the countHourly:false
option from handleChatResume's rateLimitOrReject call, and wiring the
resume route to handleProtectedEndpoint instead of handleChatResume, each
independently turn tests red.

* fix: bound /chat/resume chains with a separate hourly budget

/chat/resume is exempt from the /chat hourly counter because one turn
with N tool executions costs 1 + N requests. But a resume can itself end
in another tool_request, so nothing bounded how many times that repeats:
an hourly-counted /chat call could chain resume calls up to the
per-minute limiter's ceiling alone (10/min * 60 = 600/hour in production,
~30x the 20/hour /chat budget), and the tool's stdout is an explicit
injection channel that could drive such a chain without the user's
cooperation.

Add a separate per-IP KV counter for resume calls (RESUME_LIMIT_PER_HOUR:
100/hour prod, 500/hour dev -- 5x the /chat hourly cap, generous for a
legitimate multi-step analysis while capping the worst-case amplification
at 5x instead of ~30x). Exceeding it 429s with a reason distinct from the
/chat hourly rejection. Document the new budget in handleRoot and README.

* fix: complete the review findings and keep the CLI dependency-light

Review findings addressed:
- LRU eviction spared a session waiting on a browser call unless every session
  is waiting. A person reading code before approving it does not touch
  last_active, so that session was exactly the one a naive rule evicted first,
  and their resume then 404s with the running work gone.
- Overlapping turns on one session silently discarded each other: both copy the
  message list and write the whole thing back, so the later one wins. Refused
  now, with a self-healing claim so a dropped connection cannot wedge a session.
- A client tool sharing a name with a server tool would drop the server tool
  from the node that executes it and park its calls for a browser with no
  executor, hanging the turn. Refused at construction.
- Client tool calls never reached tools_called, so per-tool usage metrics would
  have read zero for browser execution forever.
- RuntimeLimits is now bounded by the server's own caps, so a community cannot
  declare a limit the server is guaranteed to reject with a 422.
- The runtime check is a mapping rather than a chain with no else, so adding a
  runtime and forgetting a branch is a KeyError at config load, not a tool that
  binds and can never be answered.

Corrections to earlier claims in this branch:
- The image-counting fix landed in langchain-core 1.2.8, not 1.6. Bisected
  release by release. The 1.6.0 floor stays as a margin, and now says so.
- tool_results' docstring said the browser enforces its own copy of the caps.
  No such client exists yet; that is phase 2.
- ANTHROPIC_TOKENS_PER_IMAGE is right for the offered models, which are all
  standard tier. Noted that a higher-resolution tier would undercount by ~3x.

Moves the shared caps into src/core/limits.py, which imports nothing. Reaching
into src.api.tool_results from the config module pulled langchain-core into
every CLI import and broke the "works without the server extra" contract that
tests/test_cli/test_validate.py pins. Measured after the move: importing the
config module now pulls in zero langchain modules.

Part of #430.
…p-after-v0.8.13

chore: sync develop with main after v0.8.13
Brings the widget-hostname work (#437, #438, #440, #441) and the release
hardening (#443) onto the epic branch. Two conflicts, both real rather
than textual.

workers/osa-worker/index.js: phase 1 matched its routes against the raw
url.pathname, which predates develop's host-gated stripMountPrefix. Left
as merged, every phase 1 route would have 404'd on widget.osc.earth
while ordinary chat worked, so the two-run continuation would have been
broken on the mounted host only. Both communityAction and
communityChatResume now match the stripped pathname; the named
ROUTE_PATTERNS constants from phase 1 are kept.

workers/osa-worker/test-routing.js: both branches created this file
independently. Develop's version drives the real exported fetch handler,
phase 1's asserted against the regex constants in isolation. Kept
develop's, because a test that matches a pattern by hand cannot catch a
route wired to the wrong variable, which is exactly the bug above. Phase
1's resume coverage is re-added in that style, driving the real handler
prefixed and unprefixed.

The workflow conflicts were duplicate steps; develop already runs the
routing test in the same job.

Tested: 102 routing, 10 mounted-hosts, 13 endpoint, ruff clean, 2483
pytest passed. Note that a fresh worktree resolves Python 3.14, where
langfuse's pydantic.v1 usage fails at collection; pin 3.12 to match CI.
Model-written Python runs in the reader's browser, in a sealed Pyodide worker, after the reader approves it; results, figures included, return through the two-run continuation. NEMAR is the first community to offer it, on Pyodide 0.29.5 with zarr and eegprep-lean from a lock overlay the API verifies and serves, and its prelude registering eegprep-lean's transport over osa.fetch.

Local review by seven Sonnet agents, every finding addressed (see the PR). The browser harness now runs in headless Chrome in CI, including a valid tampered wheel that only the integrity check can refuse.

Tested: pytest, every bun suite, bundle --check, chrome.js; CI run 35801562919 green, integration included.

Closes #431.
* Teach NEMAR's model the read in physical units

The browser lane told the model to start from the recipe's open_array
read, whose window is stored digital counts, and then to plot it with
plot_window, which takes read_window's Window. The prompt now carries
one snippet (read_index, index.store, read_window, plot_window) and
says where each value comes from. It also says on datasets are
imported from OpenNeuro and nm are NEMAR's own, lets search filters
answer directly, and drops three sections that restated the ladder or
contradicted the citation rule.

Tested: pytest tests/test_assistants.

* Test that NEMAR's prompt snippet actually runs

test-data-lane.js now extracts the one canonical python snippet from
config.yaml's system_prompt (the first fence after "## Running code in
the reader's browser"), fills its placeholders whole-word, and runs it
unchanged through eegprep-lean's real read_index/read_window against a
loopback format-3 index.json served by the existing store. Asserts
shape, unit, rate, labels, physical values against digital*scale+offset,
and exactly one PNG in the result, then reads window.data again from a
follow-up run() in the same namespace.

Tested: bun frontend/test-data-lane.js (49/49). Mutation-checked by hand
(not committed): swapping read_window for a raw open_array/getitem read
fails 9 of the new assertions with AttributeError on window.unit; removing
the heading or the fence makes the extraction guard fail with its message
in both cases.

* Let MCP images reach the model, on the Anthropic path only

_wrap_tool's _call now returns a content-block list (text plus one
Anthropic-native image block per accepted PNG) when an MCP result carries
ImageContent, so nemar_render_overview's picture can reach the model
instead of being silently dropped. Images are capped by MAX_IMAGES,
MAX_IMAGE_BYTES and MAX_IMAGE_EDGE_PX (width/height read from the PNG's
own IHDR chunk), gated to image/png only, and refused images become a
text line naming why.

The provider decision is threaded in, not sniffed: CommunityAssistant
gets a new allow_mcp_images flag (mirroring citations), passed to
_load_mcp_tools -> discover_mcp_tools -> _wrap_tool at wrap time. The
router sets it from provider_choice.provider == 'anthropic'. The MCP
tool-discovery cache key now includes allow_images, so the same server
discovered for an Anthropic request and an OpenRouter request does not
share one wrapped tool list. A live kill switch, OSA_MCP_IMAGES_DISABLED,
is checked fresh on every call rather than baked in at wrap time.

The same gate now applies to phase 2's client-tool images:
build_live_tool_message takes allow_images, and the /chat/resume handler
resolves the provider (best-effort; a resolution failure defaults to no
images rather than changing which status code the endpoint returns) to
decide it before building the live message it hands to _stream_chat_response.

Two more leaks closed:
- ChatSession.replace_history now runs scrub_stored_images over whatever
  a graph run's final state hands back, replacing every image content
  block (any of the four spellings the payload-transport tests cover)
  with a text placeholder. This is what actually fixes the leak where a
  run that parks a second browser call adopts the graph's state whole,
  which still carries the first call's LIVE tool message from
  initial_messages, and the leak where a real MCP ToolMessage with an
  image (built by LangGraph's ToolNode, never through
  build_history_tool_message) is stored as-is.
- Both tool_end SSE handlers in community.py now render tool_output
  through _sse_safe_tool_output instead of a bare str(), so a tool
  output that is a content-block list never streams its image's base64
  in the SSE event.

Tested: uv run pytest tests/test_api tests/test_assistants tests/test_tools
tests/test_core -m 'not network' (1544 passed, 17 skipped, 21 deselected).
uv run ruff check and ruff format clean on the four changed files.

* Test png_dimensions, scrub_stored_images, and the live-message image gate

Adds tests/helpers/images.tiny_png (an exact-size real PNG, for tests
that need to know dimensions in advance rather than derive them from a
chart). Covers png_dimensions against real IHDR bytes and malformed
input, image_block_placeholder and ToolResultImage.placeholder sharing
one format, scrub_stored_images across all four known image-block
spellings plus non-image and string content, and
build_live_tool_message's new allow_images gate.

Tested: uv run pytest tests/test_api/test_tool_results.py (51 passed).
Mutation-checked by hand: removing png_dimensions's signature/IHDR
guards fails 3 of 5 TestPngDimensions tests; dropping image_url from
_is_image_block's recognized types lets base64 leak past
test_the_data_url_block_is_replaced_too. Both restored after confirming
the failure.

* Test MCP images end to end, against the fixture server and production

_build_server() gains render_overview (real ImageContent), many_images
(exercises MAX_IMAGES), undecodable_image, and wrong_mime_image; the
exact tool-set assertion and the two tool-count assertions are updated.

New TestImages class invokes through a ToolCall dict (name/args/id/type)
rather than a bare args dict, so LangChain actually builds a ToolMessage
via _format_output -- the path that matters, since a malformed block in
the returned list would get stringified there instead of proving the
list survives. Covers: an accepted image lands as a real content block;
allow_images=False and the OSA_MCP_IMAGES_DISABLED kill switch both
withdraw it; a non-PNG mime and undecodable PNG data are refused by
name; MAX_IMAGES caps how many of one result's images are attached.

Added a network test to TestAgainstProductionNemar:
render_overview on nm000103 (recording path from a real
list_recordings call) reaches a real ToolMessage as an image block.

Tested: uv run pytest tests/test_tools/test_mcp_client.py (25 passed,
including the 4 network tests, run against the live NEMAR MCP server).

* Test the provider gate on both real transports for MCP images

_content_of's output feeds a real ToolMessage through both real payload
builders: an accepted image survives CachingChatAnthropic._get_request_payload
(the same proof the existing tests use, on MCP-shaped input this time), and
a gated result reaches ChatLiteLLM._create_message_dicts as text only. A
third test is the control: the same accepted content, sent to LiteLLM
anyway, shows that transport forwards an image block unexamined -- which is
the concrete reason allow_images gates construction rather than trusting
LiteLLM to reject it.

Tested: uv run pytest tests/test_core/test_tool_result_image_transport.py
(12 passed).

* Test tool_end sanitization and the two-source history-image scrub

_sse_safe_tool_output had to change from what was committed: on_tool_end's
output is the ToolMessage LangGraph's ToolNode built, not a tool's raw
return value, so str() on it prints .content in full regardless. The
real test caught this immediately (str(ToolMessage) embedded the base64
that a bare list check let through undetected). Fixed to read
.content off the output when present, and to only take the special path
when that content is a list containing an actual image block, so a
plain-string tool's event renders through the exact same str(tool_output)
it always has.

Added render_with_image, a real server-executed tool returning the same
content-block shape src.tools.mcp_client._wrap_tool returns for an
accepted image, to exercise both the tool_end sanitizer and the history
scrub against a real LangGraph ToolNode round trip. New tests: tool_end
never carries render_with_image's base64 (with a plain-string control);
a batch combining that tool with a parked execute_code stores no base64
in session history; a second parked call still scrubs the first call's
live image out of stored history.

Tested: uv run pytest tests/test_api/test_client_tool_streaming.py
(32 passed) and tests/test_api -m 'not network' (608 passed).
Mutation-checked by hand: disabling the image-block guard in
_sse_safe_tool_output makes test_the_image_becomes_a_placeholder_not_its_base64
fail with the base64 string present in the event; restored after
confirming.

* Design note: MCP images follow the client-tool image policy

One paragraph after the existing image-in-history rule: MCP images are
gated to the Anthropic path via allow_mcp_images, re-sent with every
later model call within a run, never kept in stored history
(scrub_stored_images), and can be withdrawn live via
OSA_MCP_IMAGES_DISABLED.

Not tested (documentation only).

* Add a live contract guard for NEMAR's read_window recipe

New tests/test_assistants/test_nemar_contract_live.py. Two pure ast-based
helpers, non-network and run in every CI sweep: eegprep_lean_exported_names
parses the vendored wheel's eegprep_lean/__init__.py (names imported from
submodules, plus the keys of _EXTRA_NAMES) without importing or executing
it; eegprep_lean_names_used parses a python snippet for the eegprep_lean
names it actually reads (from-imports and eegprep_lean.X attribute access),
ignoring comments and strings by construction.

Network tests (against https://mcp.nemar.org/mcp, deselected by default):
list_recordings gives every recording a path and named groups; read_window
returns a recipe with how_to.python_browser and the sample_slice
start/end fields the prompt's snippet needs; every eegprep_lean name the
live recipe uses is exported by the committed wheel -- the guard that
would go red if the server or the wheel drifted.

Tested: uv run pytest tests/test_assistants/test_nemar_contract_live.py
(12 passed: 9 non-network, 3 against production). Mutation-checked by
hand: dropping the _EXTRA_NAMES branch from eegprep_lean_exported_names
fails 2 of the wheel tests (open_array is only reachable through it);
restored after confirming.

* Add a scheduled workflow watching NEMAR's live MCP contract

Daily cron plus workflow_dispatch, modeled on widget-route-health.yml:
runs the three NEMAR network test targets (test_mcp_client.py's
TestAgainstProductionNemar, test_nemar_mcp_wiring.py -m network, and the
new test_nemar_contract_live.py), opens or comments on one issue labeled
nemar-mcp-contract on failure and fails the run, closes it with a
Recovered comment on the next green run.

Validated with actionlint (clean; the tool's other findings across the
repo are pre-existing and unrelated to this file). act is not installed
in this environment, so it could not be used.

* Gate run 2's figures by provider before the claim

build_live_tool_message now requires the provider decision, and a
withheld figure says it was never sent rather than not retained.
/chat/resume resolves the provider before claiming the parked call,
so nothing it raises can strand the session. Entry-point tests drive
the route with each provider's key; both mutations fail them.

* Tell the model a withheld image was never seen

MCP and browser placeholders share one phrase, and the prompt says
what it means. The kill-switch test now sets the switch after wrap
time, and the refusal and LiteLLM assertions pin exact text.

* Find the vendored wheel through NEMAR's overlay

The contract test no longer names the dev1 wheel, so a re-vendor
needs no edit, and comments no longer cite a pre-squash commit.

* Run the prompt's own snippet in the Chrome harness

widget_e2e.py --nemar gains a "prompt" script, read from NEMAR's
config, and stands in the Anthropic provider so run 2 still gets the
figure. Ran in Chrome on live nm000103: (4, 500) uV at 250 Hz,
labeled E1 to E4, one image reached run 2.

* Pass the provider decision in the budget tests

The aliased call in test_image_token_budget.py was the one site the
keyword-required allow_images still missed; the full suite found it.

* Fail closed on tool_end; one native-block check

ProviderChoice.takes_native_blocks now answers citations, MCP images and
browser figures alike. tool_end streams only text blocks and names any
other block. /chat/resume logs a swallowed provider error. A test pins
that replace_history scrubs images while it trims. Each change was
mutation-checked against its test.

* Guard MCP image reading and name every cap

Reading a result's images can no longer end the turn: a failure is
logged and the answer goes out without them. An image over both caps
names both. The discovery cache and the factory's provider gate each
have a test through real discovery, and the kill switches share one
env-flag helper.

* Check the live recipe's keywords against the wheel

A name check could not see read_index(index_url=...) on a wheel without
that parameter. The guard now reads each exported function's signature
from the vendored wheel. Against nemar-cli dev's recipe it reports
read_index takes no keyword 'index_url' on dev1 and nothing on dev2.

* Fall back to the prompt's snippet in step 3

Production's recipe names read_window only in a comment, so step 3 now
says to use the prompt's own snippet when the recipe has no read_window
call.

* Open the contract issue on setup failures too

A job that fails before the checks run is a failing check. The report
delimiter is random. actionlint is clean.
* feat: record where each vendored wheel comes from

Add sources.toml, one table per wheel in runtime/wheels/, and a test that
fails if a wheel has no entry or an entry names no wheel.

* chore: re-vendor eegprep-lean 0.1.0.dev2

sccn/eegprep@b4aa18bd adds read_index's index_url keyword, which
nemar-cli dev's browser recipe now requires. Regenerate the lock overlay
and update the README's provenance table and the generator test's
wheel filename to match.

* feat: add the eegprep-lean upstream drift watcher

scripts/eegprep_lean_drift.py compares the commit sources.toml records
against the newest commit on sccn/eegprep's develop branch that touches
packages/eegprep-lean, never by version string alone (it can sit still
across more than one upstream commit). current/behind/unknown, exit
0/1/2; unknown is never reported as current.

Real run against GitHub before this PR's re-vendor: behind, recorded
67670f5b/0.1.0.dev1 vs upstream b4aa18bd/0.1.0.dev2. Against the
now-committed sources.toml: current.

* test: run nemar-cli dev's level-0 recipe in the data lane

Add nemar_cli dev's level-0 python_browser recipe (buildHowTo's isLevel0
branch, read_index with index_url) to the data lane, filled for the
loopback dataset. Asserts the primary physical read (read_window: shape,
unit, rate, labels, values) and the raw digital-counts read the recipe
keeps as a fallback. Production's recipe (0.10.5, open_array-first) keeps
running unchanged; both pass on the re-vendored dev2 wheel.

* test: run the live recipe on CPython against the vendored wheel

Fetch nm000103's live python_browser recipe from mcp.nemar.org and run
it verbatim in a fresh uv --isolated subprocess with only eegprep-lean[zarr]
installed from the vendored wheel file. The runner (scripts/run_python_
browser_recipe.py) compiles with ast.PyCF_ALLOW_TOP_LEVEL_AWAIT, evaluates
to get the coroutine, awaits it, and reports what window/digital bound.

Checked what eegprep-lean's CPython transport sends: UrllibTransport
already sets User-Agent to 'eegprep-lean', never the bare Python-urllib
default the NEMAR hosts refuse, so no workaround was needed. Verified
live: passes in ~10s against production.

Added as its own target in nemar-mcp-contract.yml, split out from the
existing whole-file target so it gets its own pass/fail line.

* refactor: extract a composite action for tracking-issue workflows

widget-route-health.yml and nemar-mcp-contract.yml each opened, commented
on and closed a labeled issue near-identically; the weekly eegprep-lean
watcher would be a third copy. Pull the plumbing into
.github/actions/track-issue, taking label/title/failed/report/
recovery_message, still passing text through env rather than
interpolating it into the script.

Behavior preserved: same labels and titles, nemar-mcp-contract.yml still
opens on a setup failure (failure() is disallowed inside a with: value,
so that check now reads job.status == 'failure'), widget-route-health.yml
still opens/closes only when its own probe step ran, recovery still
closes with the same message text. Verified the extracted script logic
with a standalone simulation (create vs comment, close vs no-op).

actionlint is workflow-only and refuses action.yml outright (no jobs:/
on:), so it was run against the two workflow files, not the composite
action. act is not installed on this machine.

* feat: add the weekly eegprep-lean drift watcher workflow

Weekly + workflow_dispatch, contents: read / issues: write. Runs
scripts/eegprep_lean_drift.py; behind or unknown opens or updates the
eegprep-lean-drift issue (via .github/actions/track-issue) with the
watcher's report and the refresh procedure's location, current closes
it. unknown is distinguished from behind in the issue body, both by the
bold status line and by an explanatory paragraph.

Verified the shell step locally against the real committed state:
unauthenticated it hit GitHub's anonymous rate limit and correctly
reported unknown (exit 2), never current; with a token (as the workflow
always has via github.token) it reports current (exit 0).

* docs: write down the eegprep-lean refresh procedure

Owner (the OSA maintainer for NEMAR), signal (the drift watcher's
issue), build (from sources.toml's commit, with the reproducible
SOURCE_DATE_EPOCH command), and proof in order: overlay --check,
bun test-data-lane.js, bun browser-harness/chrome.js, then
widget_e2e.py --nemar's recipe and prompt scripts against the live
archive. Only then update sources.toml and the table.

* Fail the drift watcher closed; add reviewed_through

check_drift returned current by default and relied on each failure
path to change it; every return now names its status. reviewed_through
acknowledges an upstream commit that leaves the wheel as it is, since
a re-vendor needs a new version. A test pins the build command to the
recorded commit. Mutation-checked.

* Leave tracking issues alone on a cancelled run

if: always() let a cancelled run pass failed=false, which the action
reads as green and closes the issue. The watcher's issue title now
fits unknown as well as behind. actionlint is clean.

* Check the live recipe's physical read and dtype

The runner described a bare array by its .data, a memoryview with no
dtype. The live test now checks every read's width and dtype, and a
physical read's unit. A tool that answers in text fails with its text.
Ran against production and nemar-cli dev's recipe on dev2.

* Name NEMAR's absent dataset id in the data lane

Loopback indexes used ids in the reserved exemplar band; they now use
nm099900, which nemar-cli declares never resolves. The dev recipe is
labeled as transcribed from buildHowTo, not verbatim.

* Track scheduled-check issues from a job of their own

The composite action loads from the workspace, so a failed checkout in
the check job would also lose the issue. Each workflow now runs the
action in a second job with a sparse checkout, which also gives the
health probe issues on setup failures. The check jobs drop issues:write.
The watcher's status comes from its status line, never its exit code,
and the action refuses a failed value other than true or false.
actionlint is clean; act is not available.

* Report any watcher failure as unknown

An overlay that is not a JSON object, or any crash inside the check,
is now an unknown report with its reason, never an uncaught exit 1.
Tests cover the human report for each status, GitHub error shapes,
wrapped base64 and the JSON fields. Mutation-checked.

* Run recipes offline in tests; fail on no read

The runner called asyncio.run on None for a recipe with no await, which
the new offline tests found. A recipe that binds neither window nor
digital now exits 3. Mutation-checked.

* Require each live answer's key; share the index doc

A structured error answer now fails with its content rather than a
KeyError. The data lane builds its two loopback indexes with one helper.
The live tests pass against production.
#451)

* feat: a boot progress bar that does not jump

Compute the whole boot's step count once, before it starts: one for
the interpreter, one per preload name, one for micropip plus one per
allow_install entry when there is one, and one for the prelude when
there is one. Every progress message now carries step/steps instead
of the per-phase index/total that reset mid-boot. The widget renders
a determinate progressbar from them, and runtime_loaded gets its own
reassuring label instead of rendering nothing.

* feat: serve wheel routes as immutable in the harness

serve.js sent no-store everywhere, so the browser cache was never
measured. Wheel routes now send the same "public, max-age=31536000,
immutable" the API and worker send. Named as a module constant on
the Python side (RUNTIME_WHEEL_CACHE_CONTROL) with a drift test that
keeps it equal to the worker's IMMUTABLE and the harness server's own
copy. Also adds an in-memory lock-change overlay variant (one wheel
renamed with a build tag, same bytes) for the upcoming warm-cache
measurement.

* feat: measure wheel caching, warm and cold, in chrome.js

Auto-attach to the blob worker Pyodide runs in (Target.setAutoAttach
on the page session, Network.enable and runIfWaitingForDebugger per
worker session) and record its network traffic. After the nemarlike
run, a new cache-boot.html page reboots NEMAR's overlay on the same
server, port and browser: every overlay wheel request must now be
served from cache, cross-checked against encodedDataLength. A third
boot serves eegprep-lean under a renamed (same-bytes) file name, and
only that wheel should reach the network. jsDelivr's own assets are
reported, not gated. Numbers recorded in README.md.

* docs: a guide for a community adopting the browser runtime

docs/community-browser-runtime.md covers the client_tools and
runtime.python config keys, fetch_allow as the egress control, the
lock overlay and its refresh procedure (linked, not copied, since
nemar's runtime/README.md is being rewritten elsewhere), the prelude,
the Pyodide version pin CI enforces, the embedding page's CSP and why
a refused runtime hangs, the measured first-load cost and what the
cache gate found for a warm load, and the pybids blocker. Linked from
the README's Adding a New Community section. Also updates the design
note's stale scipy-era size figures to match.

* test: whitelist the progress bar's numeric interpolations

progress.step and progress.steps are only ever null or a positive
integer (guarded in onRuntimeProgress), so they cannot carry a quote
character; the drift test already whitelists other numeric
interpolations for the same reason.

* fix: correct the lock-change wheel's measured byte count

28,502 B, not 28,475 B: verified against a clean (non-mutated) run
rather than the earlier mutation-check run, which measured the same
wheel while every route was reverted to no-store.

* Re-measure the wheel cache with eegprep-lean dev2

Rebased onto the dev2 re-vendor; chrome.js passes its warm and
lock-change checks there, and the table now shows dev2's 28,852 bytes.

* Clear the boot's progress once Python is ready

The panel kept the boot's last label and a full bar while the reader's
code ran. The widget now takes the runtime's state changes and goes
back to 'Running Python' on ready. runtime_loaded no longer says Python
is ready while its packages are still to load. Mutation-checked.

* Require every overlay wheel in the cache checks

The warm and lock-change checks passed when a wheel went unobserved,
for example from a worker the recorder missed. Both now compare against
the overlay's own file names, and a failed worker attach is logged.
Mutation-checked: hiding zarr fails both.

* Clear boot progress whenever the boot ends

Failed, terminated and idle now clear the bar as ready does. A step
count that is not a positive integer, or a step past it, draws no bar.
Widget tests: 127 of 127; both guards mutation-checked.

* Test step counts for every boot shape

The plain boot, allow_install without preload, and a failing boot, plus
the runtime forwarding step and steps unchanged. Worker core 135 of 135,
lifecycle 166 of 166; each new case mutation-checked.

* Drop nextStep's unused return

Rebuilds the runtime bundle and its integrity pin.

* Check each file sends the wheel header constant

The drift test now fails when a route sends another literal or a file
spells the value twice. Mutation-checked on all three files.

* Fail cache checks on an unwatched worker

A worker whose network could not be watched fails its run, an empty
overlay list stops the harness, and page listeners are removed after
each run. chrome.js: all checks pass; both guards mutation-checked.

* Correct the adopter guide's limits and headers

Four limits are server-capped (stdout, stderr, images, image_px);
memory_mb and exec_seconds are the browser's own. jsDelivr's header has
no immutable. MCP dropped from the example; CORS, CI and API spelled
out. Reflowed to semantic line breaks.

* Reflow the harness cache notes, add new guards

Semantic line breaks, and the two guarantees this round added: an
unwatched worker fails its run, and the checks need the exact set.

* Align the design note with ADR 0049's amendment

* Say which limits default to the server cap

image_px is capped by the server but defaults below the cap.
* Run the live recipe in the widget e2e page

widget_e2e.py --nemar ran a hand-written recipe that neither production
nor nemar-cli dev serves. It now fetches the python_browser recipe from
mcp.nemar.org at start-up. Verified in Chrome against nm000103.

* Keep recipe ahead of prompt in the e2e page

The scripted model answers the first keyword it finds; the live recipe
was appended after prompt. Also finishes a README sentence.
* Add notebook-bench.js for surface timing measurement

* ADR 0010: skip marimo, pin JupyterLite to 0.29.5

* Record ADR 0010's verdict in the design note

* Export chrome.js helpers, guard entry point

* notebook-bench.js: share chrome.js, harden it

* Fix dashes and abbreviations in design note

* Split ADR 0010, record phase 4c decision

* Link the JupyterLite follow-up, #453, in ADR 0010
… export (#455)

* Extract the STORED-zip writer into osa-zip.js

* Add workspace file validation to output capture

* Add osa.save_script and osa.save_artifact

* Wire save_script/save_artifact into the worker

* Keep a run's saved files off the server result

* Add the workspace store, manifest and notebook

* Persist a run's workspace files in the controller

* Export the workspace API from the runtime entry

* Test save_script and save_artifact in Pyodide

* Test saved files never reach the server result

* Test workspace persistence and its failure path

* Test workspace paths, manifest, notebook, zip

* Validate the workspace export with real nbformat

* Run workspace tests and set up Bun in CI

* Add the workspace panel to widget Settings

* Add a Chrome harness page for the workspace

* Document the workspace in the runtime guide

* Tell NEMAR's model about the workspace

* Cap explicit saves at 32 files, split path checks

E5: a run may save at most 32 distinct explicit files, matching
ClientToolResult.artifacts' own cap, so saved always equals
announced. D7: path validation runs on the caller's raw name/path
before scripts/ or artifacts/ is prefixed, so an absolute-looking
argument is refused for what it actually is.

* Validate save paths before prefixing (D7)

save_script/save_artifact now check the caller's raw name/path for
being relative and well-formed before scripts/ or artifacts/ is
added, so an absolute path is refused as "must be relative" rather
than as a confusing empty path segment. Docstrings state the numeric
limits (D3) and point to the Settings panel's whole-workspace
download/delete, never a per-file delete (D5).

* Bound WorkspaceStore calls by a deadline

E1: every public method races a deadline (default 10s, overridable
per instance like PyodideRuntime's bootTimeoutMs), and _open reacts
to onblocked and resets its cached promise on rejection, so a stuck
IndexedDB request reports failure instead of hanging a chat turn.

C1: ordinal assignment is now atomic. _reserveOrdinal reads a
session's highest ordinal and writes a RESERVED placeholder in ONE
readwrite transaction, relying on IndexedDB serializing overlapping
transactions across tabs and connections, so two tabs recording at
once never collide on run-NNN and silently overwrite each other.
deriveManifest and exportZip leave a still-reserved run out.

E2: the run-record and deleteAll transactions gain onabort, matching
putFile's existing three-handler pattern.

D4/C2/E5(host): the 25MB per-run budget and the 32-file cap apply
only to explicit saves, both re-checked on the host; automatic files
are bounded by their own caps (_FULL_CHARS, image limits) and never
compete with a path Python already accepted for the same budget.

* Refuse zip overflow; flag non-ASCII names as UTF-8

C3: buildStoredZip throws rather than writing a wrapped entry count
past the 16-bit end-of-central-directory field's 65,535-entry limit.
C4: local and central headers set the general-purpose flag's UTF-8
bit (0x0800), so a future caller passing a non-ASCII name gets a
correctly labeled archive.

* Log unexpected workspace failures; never clip the note

E3: a genuine (non-timeout) rejection from recordRun -- WorkspaceStore's
own failures always resolve to a value -- is logged with
console.error and every explicit save for that run is dropped from
artifacts, with a deterministic stderr line naming the failure, so a
bug here never lets the model believe an unverifiable save succeeded.

E4: the workspace failure note is appended AFTER the run's own stderr
is clipped to the community's limit, keeping only whole lines (with
an "and N more" trailer) rather than letting toClientToolResult's
own clipping cut the note away or truncate it mid-line.

* Test workspace failure logging and note truncation

Covers E3 (a genuine recordRun rejection is logged and drops every
explicit save) and E4 (a note is never clipped mid-line even when
stderr_chars is set to its 256-character floor). Also drops a stale
reference to a plan document in a comment (D2).

* Test the store deadline, zip limits, and multi sessions

E1: a real dbFactory whose open() never settles proves the deadline
reports failure rather than hanging, and a fast rejecting one proves
_open resets its cached promise rather than replaying it.
T2: a second session in the zip-writer test proves exportZip scopes
each session's manifest and notebook to only its own runs.
T5: the exact per-file byte cap passes, mirroring the existing
community-cap pair.
C3/C4: buildStoredZip's entry-count refusal and its UTF-8 flag bit,
the latter checked against Python's zipfile since the system unzip
on this machine mis-decodes UTF-8 names regardless of the flag.

* Expose the workspace panel for testing

Adds setWorkspaceStore, formatWorkspaceBytes, refreshWorkspacePanel,
downloadWorkspace, handleWorkspaceDeleteClick and closeSettings to
the __OSA_TEST__ surface, so a test can exercise the Settings
workspace panel against a real WorkspaceStore without booting a
runtime (T3).

* Test the Settings workspace panel (T3)

Size formatting across B/KB/MB/GB boundaries, hidden when there is
no store, the first Delete click only arms it while the second
attempts the delete, reopening Settings disarms a pending confirm,
and a failed size read or delete shows an error rather than nothing
-- all against a real WorkspaceStore, genuinely unavailable under
happy-dom exactly as it is under Bun.

* Add a malformed-base64 worker directive (E3 fixture)

BADFILE reports one artifact whose base64 is genuinely invalid,
something real encoding can never produce, so a real recordRun call
against it makes atob() throw for real -- the trigger the browser
harness needs to exercise ClientToolController#persist's catch path.

* Add harness checks for concurrency and budgets

Against real IndexedDB, since none of these are reachable under Bun:
E3 (a genuine recordRun failure logs and reports, via a protocol-
speaking worker rather than real Pyodide), E5 host-side (the 32-file
cap), T1 (the per-run byte budget), T4 (ordinals survive a reload),
T6 (two sessions in one community), and C1 (two connections
recording concurrently for one session never collide on an ordinal).
E6 bounds each phase by its own deadline so a hang fails loudly.

* Test multi-session scoping in the export zip (T2)

A second session in the fixture, with its own run and its own
scripts/run-001.py, proves each session's manifest and notebook in
the exported zip hold only that session's own content, never
leaking a call_id across the shared archive.

* Pin workspace limits against the generated Python (D6)

WORKSPACE_LIMITS in osa-workspace.js mirrors five constants declared
in the Python buildOutputCaptureSource generates; this test reads
them out of that generated text and compares, the same drift-guard
pattern already used for SERVER_LIMITS.

* Correct doc claims about full output (D1)

results/run-NNN's stdout/stderr/summary are bounded at 262,144
characters (_FULL_CHARS), the same copy get_full_output keeps, not
literally the full, untruncated text as the doc previously claimed.

* Rebuild the runtime bundle

Regenerated from the review-fix changes to osa-workspace.js,
osa-controller.js, osa-egress.js, osa-output.js and osa-worker-core.js.

* Drop review labels from comments and checks

Labels like E3 and T6 named review items, not anything in the repository;
each comment now states its rule. Suites and chrome.js rerun green.
* Add runLocal to the browser tool controller

* Test the reader's own edit-and-run

* Rebuild the runtime bundle

* Add the editable re-run panel to the chat widget

* Test the editable re-run panel

* Whitelist rerun control indices in the drift test

* Add runLocal checks to the workspace harness

* Tell NEMAR's model about Edit and run

* Document the editable re-run panel

* Refuse get_full_output for the reader's own runs

* Carry workspace save failures off the wire

* Target Stop cancellation and mark local runs private

* Render workspace save-failure notes for every run

* Fix rerun error handling: no throw swallowed or overwritten

* Target rerun Stop buttons and drop phase labels

* Test real Run/Stop clicks against a real controller

* Drop stale phase label from a manifest comment

* Narrow the re-run panel's privacy claims in docs

* Test targeted Stop and get_full_output privacy

* Rebuild the runtime bundle
* Correct ADR 0010's CORS and export facts

zarr.nemar.org already admits osc.earth and every *.osc.earth origin (checked live 2026-09-23), so a notebook site hosted there needs no nemar-cli change. The export list now names results/ and the reader's own runs.

* State the per-run save caps and local runs

The guide's manifest fields gain local, and its limits say the 25 MB budget and the 32-file cap count explicit saves only, as recordRun does. execute_code tells the model the same caps osa.save_* enforces.

* Fail a bench run whose worker went unwatched

A worker the recorder could not attach to makes every byte and request count an undercount, so the run now fails naming it, as chrome.js does.

* Name the wheel route's narrower CORS

OSA's wheel route admits embed origins and the demo hosts, not every osc.earth subdomain, so a hosted notebook there still needs an OSA allowlist change. The bench comment now claims only the attach failures reported before polling ends.
…docs (#460)

* Mark what the design note built differently

Architecture, Sequence, Server changes and Phasing now carry as-built notes for the two-run transport: no interrupt(), no checkpointer, and a parked call closed out on next use. The NEMAR adoption row names eegprep-lean and python_browser, and the caps table gains the per-reply run cap.

* Tidy ADR 0010 and the adopter guide

ADR 0010 names #456 instead of a phase label and says prerequisite 3 needs nemar-cli only off osc.earth. The guide gains the per-reply run cap, spells out URL, OPFS and the File System Access API, and drops double-hyphen dashes.

* Add the browser-execution changelog entry

* fix: remove XMLHttpRequest from worker global

* test: check ResultStatus matches tool_results.py

* test: check workspace cap prose vs constants

* test: assert frontend-tests job parity in CI

* ci: smoke-test the runtime wheel route

* Drop a double-hyphen dash from the guard

Comment only; the guard source is bundled, so the bundle and its integrity pin are rebuilt.

* Say XMLHttpRequest is removed, not shimmed

* Read ResultStatus across wrapped lines

The drift test matched a single line, so a formatter-wrapped Literal would have failed it loudly. It now reads up to the closing bracket. Checked with a wrapped Literal (passes) and a Python-only status (fails).
Pull requests are reviewed locally, and the action failed on every run of this epic without posting a review. It was never a required check. claude.yml, which answers @claude mentions, stays.
…-epic-browser-execution

Browser execution: run model-written Python in the reader's browser
* Admit nemar.org's staging site for NEMAR

test.nemar.org embeds the widget against the dev worker before a release pins it on nemar.org. Without it in NEMAR's cors_origins, every chat from staging is refused with 403 (no platform key for an unlisted origin). The worker's origin list is regenerated by scripts/sync_worker_cors.py. Tested: the new authorization test, failing with the origin removed; the API, assistant and config suites; the worker's routing tests.

* Name test.nemar.org in the wheel-route note
* Add a user_bubble_color widget setting

The reader's bubbles were fixed at the platform blue. A community can now name their color on its own, never derived from theme_color, so a community that sets only a theme renders exactly as before. Validated as #RRGGBB like theme_color, on the server and again in the widget.

* Theme NEMAR's widget in NEMAR teal

theme_color and user_bubble_color #257a92: nemar.org's brand teal (#5bbad5) darkened in lightness only, from 2.2:1 to 4.9:1 against the widget's white text. The logo's electrodes move from orange to nemar.org's pale gold (#f4d06b), the site's treatment of the mark on a dark ground. Tests keep both colors at 4.5:1 and every other community without a bubble color.
…ssage (#463)

Three opt-in widget colors (theme_text_color, accent_color, user_bubble_text_color) so NEMAR's widget matches nemar.org's search button (#5bbad5 with #04121f text, #257a92 accent on white) while every other community renders as before; preload_on: first_message, which boots the runtime when the reader sends their first message; a warning for malformed colors; a runtime field on getBrowserRuntimeStatus(); and docs/community-widget.md.
The pinned, integrity-checked snippet dropped defer, which made the inline setConfig throw and silently start the default HED assistant; release notes, widget-sri.py, the demo page and the widget test page now publish the script tag first and setConfig after it, from demo.osc.earth or a jsDelivr pin. docs/community-widget.md no longer loads the script from the API edge. A test parses every published snippet, checks order and hosts, and flags a widget script tag in any file it does not parse. The remaining console.anthropic.com links point at platform.claude.com.
Opt-in widget.launcher: capsule (default bubble, unchanged for every other community) and widget.launcher_label. The capsule adds a notebook button, active when the page reports a dataset with a Zarr copy through OSAChatWidget.setDataset and opening notebook.osc.earth/osa/open.html for it, and a high-performance computing (HPC) placeholder marked coming soon. Unavailable buttons use aria-disabled and explain why in a tooltip and label. setConfig({notebookUrl}) sets the notebook site per environment. NEMAR uses the capsule with the label Explore NEMAR.
* feat: add notebook config schema for communities

* test: add tests for notebook config schema

* feat: add NEMAR notebook starter

* feat: add notebook site build script

* test: add tests for notebook site build script

* feat: add notebook site bootstrap page

* test: add notebook bootstrap and e2e tests

* ci: run notebook bootstrap tests in frontend suite

* ci: add notebook site deploy workflow

* docs: add ADR 0011 for the notebook site

* docs: add notebook site adopter guide

* fix: reconcile /osa in docstrings, comments, and the changelog

PR review findings: config.yaml's comment omitted /osa; notebook_lock.py's
module docstring omitted it too; test_shipped_runtimes.py's docstring cited
the build script by its old hyphenated name (build-notebook-site.py, the
real file uses underscores); the changelog's code span for
deploy-notebook.yml was split across a line wrap; browser-execution-tool-
design.md still said the hosted JupyterLite surface was deferred to #453
with no mention that ADR 0011 has since built and hosted it.

* feat: harden open.js against a loose pattern and a hung storage call

Two PR review findings, both defense in depth for the same bootstrap page:

- A dataset id now must match a generic safe shape
  (^[A-Za-z0-9._-]{1,64}$) BEFORE it is even checked against the
  community's own dataset_pattern. The value is substituted unescaped into
  the starter's Python source, so a community pattern that is accidentally
  too loose must not become a code-injection hole on its own.
- The storage write (the community's directory entry, then the notebook
  itself, never overwriting an existing one) is now raced against a five-
  second timeout (raceStorage/STORAGE_TIMEOUT). Some private-browsing and
  storage-blocked modes never settle a storage call at all, which used to
  leave the reader stuck on "Opening your notebook..." forever; this page
  now shows a plain sentence instead. writeToStorage is pulled out of
  main() specifically so the race wraps only the storage section, not the
  network fetches above it.

* test: cover open.js's dataset guard, timeout, and no-overwrite rule

Adds, all against real stand-ins for localforage at the boundary (a real
in-memory store, and a real never-settling Promise), never a mock of this
module's own logic:

- datasetProblem refuses a hostile probe (a quote, a backslash, a newline,
  a space) even under a deliberately wide-open community pattern.
- writeToStorage never overwrites a path that already holds content, proven
  by seeding one and confirming a second write leaves it untouched.
- raceStorage resolves to STORAGE_TIMEOUT against a storage call that never
  settles, and passes through a call that settles normally.
- A composed assertion at the production shape: storageDatabaseName(
  resolveBaseUrl(config, '/osa/')) is exactly 'JupyterLite Storage - /osa/'.

Each new guard was mutation-tested by hand (removed, confirmed the relevant
assertions turn red -- the timeout guard's removal was confirmed by an
actual hang under a 15s wall clock, not just a failed assertion --
restored, confirmed green again).

* feat: refuse a community dataset_pattern that admits a hostile probe

PR review finding: NotebookConfig.dataset_pattern was checked for anchoring
and compilation, but nothing stopped a pattern loose enough to accept a
quote, a backslash, a newline, or a space -- exactly what open.js's own
generic shape guard exists to keep out, and a dataset id is substituted
unescaped into the starter's Python source. A new field validator
(_dataset_pattern_refuses_hostile_probes) refuses any dataset_pattern that
matches one of HOSTILE_DATASET_PROBES, independent of open.js's client-side
guard, so a community's pattern can never rely on that guard alone. Also
fixes this file's own /osa omission in two docstrings, found by the same
review pass that flagged the config.yaml comment.

* test: cover the hostile dataset_pattern probe guard

Four patterns that would each let through one hostile probe (a match-all,
and three narrower ones each reaching a quote, a backslash, or whitespace
directly), plus a check that NEMAR's own shipped pattern still passes.
Mutation-tested: emptied the validator's hostile-probe list by hand,
confirmed all four rejection cases fail, restored, confirmed green.

* refactor: extract finalize_publish_root for offline testing

PR review finding: the reviewer demonstrated that writing _headers/
_redirects into the site subdirectory instead of the true Cloudflare Pages
publish root passes every existing offline test, because build()'s own
wiring of write_headers/write_root_redirect is only exercised by the
network-marked full build. Pulling that wiring into its own function
(finalize_publish_root) makes it callable against a synthetic output tree,
with no jupyterlite build and no network. Also fixes this file's own /osa
omission in its module docstring.

* test: cover _headers/_redirects placement against a synthetic tree

Builds a fake output tree (a site subdirectory with a placeholder file,
standing in for a real jupyterlite build) and asserts finalize_publish_root
writes _headers/_redirects at the publish root, never inside the site
subdirectory, plus the bare-host case where no _redirects file is written
at all. Mutation-tested: pointed both writes at the site subdirectory
instead of the publish root, confirmed the new test fails, restored,
confirmed green.

* fix: trigger the notebook deploy on its own config-layer changes

paths: named the build script and the assistant-side notebook/runtime/
config files, but not src/core/config/notebook_lock.py, community.py, or
runtime_lock.py -- so a Pyodide pin bump or a lock-merge fix there would
never trigger a redeploy.

* ci: add a workflow that actually fails on a notebook site regression

PR review finding: TestFullBuildEndToEnd only runs in test.yml's post-merge
Integration Tests job, with continue-on-error, and notebook/e2e-check.js
runs in no workflow at all -- the reviewer demonstrated concretely that a
regression in either the _headers/_redirects placement or the no-overwrite
rule passes every check that gates a PR today.

notebook-site-check.yml runs both for real, with no continue-on-error, on a
pull request touching the notebook site's own paths (the same list
deploy-notebook.yml deploys on), a weekly schedule, and workflow_dispatch.
A scheduled failure opens or updates a tracking issue through the existing
.github/actions/track-issue, the same convention widget-route-health.yml
uses; a pull_request failure does not, since it already surfaces as a
failing PR check.

* ci: lint the notebook workflows with actionlint

PR review finding. Fixes a pre-existing shellcheck SC2129 in deploy-
notebook.yml's site-URL step (individual >> "$GITHUB_OUTPUT" redirects
collapsed into one { ...; } block) so actionlint on this file is clean, then
adds an actionlint step to both lint jobs (test.yml, tests.yml), pinned to
1.7.12 and scoped to deploy-notebook.yml and notebook-site-check.yml only --
not every workflow in .github/workflows/, which would surface pre-existing,
unrelated findings (confirmed locally: test.yml itself has one at line 225)
that are out of scope for this change.

* docs: spell out abbreviations on first use, apply line breaks

PR review findings: CORS, CDN, CSP, and API each appeared before being
spelled out in ADR 0011, community-notebook.md, or notebook/README.md.
Also applies semantic line breaks (one sentence per line, split further at
a colon or em-dash for a long sentence) to the two paragraphs the review
named: ADR 0011's /osa naming-rule paragraph and notebook/README.md's
--site-url subdirectory paragraph.

* docs: record every measured Chrome timing run, including the omitted one

PR review finding: the timing table recorded four cold runs (7.6-8.6 s),
but the handback report separately cited a 9.1 s run that never made it
into the table. Adds that run (row 5) plus two more real runs from this
review pass (rows 6-7, 10.1 s and 8.6 s, after this PR's own review-driven
code changes), and updates the prose range (7.6-10.1 s across seven runs on
two separate days) so it matches the table exactly. The warm figures have
not moved in any run measured so far.

* feat: diagnose e2e-check.js on any timeout instead of just failing

PR #465's CI run showed only 'timed out after 120000ms ... last value:
false' with no way to tell whether the notebook was stuck, a request
failed, or the page threw. Wraps the whole flow (open, run, edit/save,
warm reopen, refusals) in a try/catch that, on any failure, prints bounded
diagnostics for whichever page was active before rethrowing: the page's
URL, every cell's prompt and output text (a traceback renders as plain
visible text, so it is captured the same way as any other output), every
console error/warning and uncaught exception seen so far, and every
network request that failed or returned 4xx/5xx -- across the page's own
session AND every worker it spawned, via chrome.js's existing
NetworkRecorder/attachWithNetwork (Pyodide's own fetches happen inside a
worker the page's Network domain never sees). Everything is capped (20
list items, 1000 chars per item) so a real failure cannot flood the log.

Verified against a real forced timeout (a bogus sentinel string, a
shortened poll deadline): the diagnostics printed the page URL, all four
cells with their live prompt state, the one benign favicon 404, and 27
bounded console warnings, then the process still exited 1 with the
original timeout error, exactly as before. Verified the unmodified happy
path is unaffected (two full local runs, both ALL CHECKS PASSED).

* feat: log the Chrome build e2e-check.js actually ran under

Cheap, always printed: the GitHub-hosted runner and a laptop are rarely on
the exact same Chrome release, and this was worth knowing directly rather
than cross-referencing the runner image manifest by hand while
investigating PR #465's CI-only timeout.

* fix: wait for the kernel to be idle before firing Run All Cells

The diagnostics from PR #465's CI run (35962090521) showed the exact race:
at timeout, every code cell's prompt was still '[ ]:' (never executed, not
'[*]:' queued), with no failed requests and no exceptions -- notebook:run-
all-cells fired before the notebook's kernel session was ready, so it
queued nothing. This Mac's kernel comes up sooner, so the race never showed
locally.

waitForKernelIdle polls the same thing a person reads off the notebook's
own kernel indicator: window.jupyterapp's current panel's sessionContext,
a session whose kernel.status is 'idle'. Given its own 90s deadline, called
before every Run All (cold run and the warm re-run both fire it). Cold time
is still measured from opening the link, unchanged.

runAllCellsAndConfirmQueued replaces the bare fire-and-forget call: after
firing, it confirms within 20s that at least one prompt left '[ ]:' before
falling through to the existing full-run wait. Deliberately not a retry --
a blind re-fire would hide a real 'Run All does nothing' bug behind an
apparent pass on a second try -- so a genuine no-op fails immediately with
that stated, rather than only after the full 120s timeout.

diagnose() now also reports the kernel's session/name/status and whether a
Pyodide worker target has even been seen, via the same KERNEL_INFO_EXPR
waitForKernelIdle itself polls, and openPage() tracks worker target URLs
(Target.attachedToTarget, type 'worker') for that.

Verified: two normal local runs, both ALL CHECKS PASSED (cold 7.3s/10.3s).
Verified against the actual race, not just a fast machine: with a temporary
CPU-throttle test hook (Emulation.setCPUThrottlingRate, removed before this
commit) at 4x, the full flow passed end to end; at 6x, the cold run's Run
All still passed correctly with the fix in place. With the fix temporarily
disabled and 6x throttling applied, the original bug reproduced exactly --
'did not queue any cell within 20s', with the kernel's own status caught
mid-transition to idle in the diagnostics -- confirming the throttle is a
meaningful stand-in for the race and that this fix is what prevents it.

Two unrelated, pre-existing timing assumptions surfaced only under heavy
throttling and are NOT touched here (out of scope for this fix): the
refusal-check's first page read can run before open.html's own script has
set up #app, and the edit-and-save-then-reopen step can race under 6x.
Both passed at normal speed and under 4x; flagging for a separate look.

* fix: harden the refusal check and the save-then-reopen step

Two more timing assumptions the throttled runs exposed, on top of 17ba233.

(1) The refusal check read document.getElementById('app').textContent
once. Right after Page.navigate, the target can still be showing
about:blank (no #app at all) before open.html's own document has loaded,
so #app is null and .textContent throws -- a page exception that crashed
the whole poll on its first iteration under load, rather than letting
pollUntil retry. Fixed with optional chaining
(getElementById('app')?.textContent ?? null): a page not yet loaded is now
just "condition not yet true," the same as everywhere else in this file.

(2) The save-then-reopen step polled only the document model's own dirty
flag before opening a second page. That flag is a UI-level convenience and,
under CPU throttling, testing showed it is not sufficient proof the
underlying write is visible to a DIFFERENT page's read. Added a second,
authoritative confirmation: window.jupyterapp.serviceManager.contents.get()
-- the SAME Contents drive a fresh page's notebook load reads through --
polled until its last_modified actually moves from its pre-edit value.

Testing also found a third, related gap needed to fully close this under
throttle: the edit-survived check itself read document.body.innerText once,
right after waitForNotebookReady, which only confirms the notebook widget
object exists, not that its cell views have finished mounting their editor
DOM. Wrapped in the same pollUntil pattern (up to 15s); a genuine failure
still reports FAIL, it is not swallowed or loosened.

No blind sleeps or retries anywhere in this change; every wait is a
condition on real state (an element's content, a last_modified timestamp,
rendered DOM text).

Verified with a temporary CPU-throttle test hook (Emulation.
setCPUThrottlingRate, removed before this commit, not shipped): two runs at
6x, both ALL CHECKS PASSED (previously this reproduced 'FAIL: the edit
survived...' consistently at 6x even with 17ba233 applied). Two further
runs at normal speed, both ALL CHECKS PASSED (cold 8.8s, 13.3s).

* Keep overlay lockfiles from the first pass

The wheel-copy loop re-read runtime.python.lockfile through two
Optionals the first loop had already narrowed; ty flagged all three
reads. Tested: build script unit tests pass, ty clean on the file.

* Read each environment's own Zarr host in the notebook

The develop notebook site is embedded by test.nemar.org, whose dataset
pages read zarr-test.nemar.org, but the starter always read
zarr.nemar.org and the pattern refused xx ids, so a staging fixture
such as xx099903 could never open.

A community's notebook block now declares zarr_base and
dataset_page_base per environment (production, develop), and
build_notebook_site.py takes a required --environment that fills them
into the starter at build time. The deploy workflow passes develop or
production by branch, e2e-check.js takes the same flag with one fixture
per environment, and the scheduled check runs both. NEMAR's pattern
admits xx ids.

Tested: offline suite passes (2,836; the one failure is the version
test under FORCE_COLOR=1, unrelated). e2e-check.js in Chrome, both
environments: develop opens xx099903 from zarr-test.nemar.org, cold
8.3 s; production opens nm000103, cold 11.3 s; ALL CHECKS PASSED.

* Test the environment flag and deploy mapping

Review of #465 found the per-environment build guarded only by build()
calls with valid values. New tests: the CLI refuses a missing or
unknown --environment, build() fails before the JupyterLite build,
a missing dataset_page_base is refused, the shipped NEMAR starter
carries exactly its own hosts per environment, and the deploy
workflow's branch script is run for main and develop.

Tested: each guard mutated in the dangerous direction (nine
mutations, including a swapped workflow mapping and a typo'd NEMAR
develop host); every one fails a test.

* Refuse unknown options in the notebook check

--environment=develop, or a typo'd flag, used to be taken as the
screenshot path while the check ran against production. It now
accepts both --environment forms and throws on any other option or
extra argument.

Tested: a typo, an unknown environment, a missing value and an extra
argument each exit with the usage; --environment=develop builds.

* Correct the notebook host docs and comments

From review: the NotebookConfig docstring named a staging key the
code refuses, the CommunityConfig.notebook example lacked the two
now-required maps, three new comments used a double-hyphen dash, and
the per-environment rationale was repeated in four places; it now
lives in ADR 0011 and the others point there.

Tested: ruff, ty and the config and build tests pass.
github-actions Bot and others added 23 commits September 24, 2026 08:03
* Let the widget embed the notebook as a tab

frame-ancestors was 'none'. The build now writes it per environment
from the platform's widget hosts and each notebook community's
cors_origins (develop adds previews and loopback), refusing an origin
frame-ancestors cannot express.

notebook/osa-bridge.js, added to the notebook page, runs a starter's
osa-autorun cells on open and after a kernel restart, and when
embedded reports ready and setup status to the widget and applies its
light or dark theme. Every build now exposes the app it drives, so the
--expose-app flag is gone. Settings overrides: follow the device theme
when opened alone, autosave every 5 s. NEMAR's starter gains the
agreed instructions and its setup cell runs on open. _headers covers
/osa/open, the path Pages serves open.html at.

Tested: build unit tests (47 offline); e2e-check.js in Chrome, next
commit.

* Check the embedded notebook in Chrome

e2e-check.js serves the build's own _headers and now checks that the
setup cell runs with no clicks, an unsaved edit autosaves, a kernel
restart reruns setup, the notebook works framed on an allowed
cross-site origin (a first dark message on a light device, then
light, then the device switching back must not override it), and an
origin not on the list is refused; production checks loopback is.

Tested: develop and production pass in Chrome 153. Seven mutations
(no headers sent, no bridge, follow-the-device left on, no wait for
it to turn off, restarts ignored, autosave override dropped) each
fail their check. The first theme check found a real race in the
bridge, fixed in the previous commit.

* Record the notebook tab decision (ADR 0012)

ADR 0012 amends 0011: the widget's sites may embed the notebook, the
bridge and its messages, why not a JupyterLab extension, and the two
settings overrides, with what was measured. The adopter guide
documents the osa-autorun tag, who may embed the notebook and the
frame-src embedders need; the notebook README the bridge and the
removed flag.

Tested: docs only.

* Report bridge failures and prove setup ran

From review of #471: a bridge that failed to start only logged to the
console, so the widget would wait for ready forever; it now posts
{type: 'error', phase: 'startup'}. The whole setup run is inside its
try, so every path posts a setup status. A setup cell counts as run
only if it gets an execution count, cleared first because a reopened
notebook shows its saved one. The theme reply is always sent, with
applied true or false, after up to 10 s. A new kernel reruns setup,
as a restart does.

Tested: develop e2e-check.js passes in Chrome, including the restart
rerun (prompt [2] to [1]) and every theme check.

* Harden the embed policy and its tests

From review of #471: X-Frame-Options SAMEORIGIN for a browser too old
to read frame-ancestors (a current one ignores it when both are sent,
measured: the allowed embed still loads in Chrome). The origin check is
tested with quote, semicolon, newline and path payloads, and the config
loader is shown to refuse them first. embed_origins raises clearly for
an environment without platform hosts, and a test keeps the two lists
in step. The refused-origin Chrome check now first proves its host page
loaded and pointed at the notebook, so silence means refusal.

Tested: 56 build tests; loosening the origin pattern fails 3; pointing
the refused host at a dead port fails the Chrome check; develop passes.

* Say what ships now in the notebook docs

From review of #471: the adopter guide described the widget's notebook
tab as shipped, but the widget still opens a new tab until #470; it now
says which is which. The build docstring cited ADR 0011 for the bridge,
which is 0012's subject. ADR 0012 records the X-Frame-Options fallback,
the bridge's failure messages, and that the config loader refuses an
inexpressible origin before the build re-checks it.

Tested: docs and a docstring.
Keeps the widget's chat input, Settings fields, panel text and scrollbars in its own colors on a dark host page, for every community. Adds widget.color_scheme (light default, or auto; only NEMAR sets auto) and OSAChatWidget.setColorScheme for a host page's own choice, which outranks the community's and reaches the pop-out. The dark panel replaces accent_color with the theme color, lifted toward white only when it reads under 4.5:1 on the panel or the assistant's bubble.

Tested: test-widget-color-scheme.js (128 checks, 46 mutations caught) and color-scheme-check.mjs --serve in headless Chrome, both in CI; the whole pytest and Bun suites.
* Require a notebook section for the capsule launcher

The capsule's notebook icon opens the community's starter on the
notebook site as a tab of the widget (#470). Without a notebook section
the site has no starter for the community, so the loader now refuses
the config instead of shipping an icon that can only open an error.

Tested: pytest tests/test_core/test_config/test_community.py (new
TestCommunityConfigCapsule); disabling the check fails the rejection test.

* Open the notebook as a tab of the widget's panel

The capsule's notebook circle opened the notebook site in a new browser
tab. It now opens the panel on a Notebook tab, framing the same
open.html address, and the chat circle goes back to chat (#470).

- One frame, made when the tab first opens and kept while the reader is
  on chat, so its Python keeps running; a new dataset replaces it, one
  with no Zarr copy drops it and returns to chat.
- The header follows the tab: "Notebook" with a status line driven by
  notebook/osa-bridge.js's messages, heard only from the widget's own
  frame at the notebook's origin. Chat-only header buttons are hidden.
- The widget's scheme is posted to the notebook's origin on load, on
  ready and on every change.
- No ready 12 s after load or 45 s after creation, or a startup error
  before ready, shows a fallback: Try again, or Open in a new tab.
- The capsule's circles are 46px (15% over the 40px Send button); a
  filled indicator slides to the open tab, the pill grows out of the
  chat button, the icons stagger in, the views fade through, and a
  ring turns on the notebook circle while Python starts off-tab.
  Reduced motion keeps only a short fade.
- The capsule's panel resizes to 1400px wide and the window's height;
  the frame takes no pointer events during a drag.

Tested: bun frontend/test-widget-notebook-tab.js (108, new, in both CI
workflows), test-widget-capsule.js (127), test-widget-tools.js (312),
test-widget-color-scheme.js (128); 30 single mutations, 26 killed, the
other 4 each backed by a second guard and killed as pairs.

* Check the notebook tab in Chrome against develop

notebook-tab-check.mjs drives the capsule's notebook tab against the
live develop notebook: circle sizes, the indicator, ready and setup
from the bridge's own messages, dark applied inside the frame, the
frame kept across a tab switch, and a resize across the frame.
widget_e2e.py's policy allows both notebook hosts in frame-src, as a
host page must. Needs the network, so it is not in CI.

Tested: 12/12 in Chrome 153 against widget_e2e.py --nemar; setting the
capsule's width limit back to 600px fails the resize step.

* Document the notebook tab

community-widget.md gains "The notebook tab" (behavior, fallback, the
host page's frame-src, the pop-out not carrying it yet) and the
capsule's new look; community-notebook.md drops "opens a new tab
today"; ADR 0012 records the widget's half of the decision.

Tested: docs only; the frame-src load behavior the ADR cites was
measured in Chrome 153 with a one-off page.

* Harden the notebook tab after review

- Only a capsule listens for the notebook's messages.
- The pre-set config's notebookUrl is validated like setConfig's, so
  every reader can rely on a normalized URL; the raw fallbacks go.
- A failed frame is kept when the reader returns to the tab, so the
  fallback stays until Try again, and a slow notebook still recovers.
- A failure, or a setup that did not finish, while the reader is on
  chat puts a dot on the notebook circle, with a tooltip saying which.
- A theme the notebook could not apply, and any message from it the
  widget does not recognize, reach the console.
- The staleness check in setDataset no longer depends on operand order
  to avoid reading a null dataset.

Tested: bun frontend/test-widget-notebook-tab.js (148; new checks for
each item above, the exact chat icon, focus by identity, reopening via
the notebook circle, setDataset(null) with a frame, a bubble's 56px);
44 single mutations, 39 killed, the other 5 killed as pairs with the
guard that backs each; capsule, tools and color-scheme suites unchanged.

* Open the notebook tab from the keyboard in Chrome

notebook-tab-check.mjs now opens the notebook with Enter on the
focused circle and returns to it with Space, as real key presses, and
times from the key press.

Tested: 14/14 in Chrome 153 against widget_e2e.py --nemar.

* Document the review changes to the notebook tab

The widget guide covers the kept failed frame, the circle's cue, the
console warnings, and the resize floor at a bubble's 600 by 800; ADR
0012 records why a failed frame is kept. NEMAR's config comment and
the launcher and notebook field docstrings say the notebook opens as a
tab and that the capsule requires a notebook section.

Tested: docs and comments only; pytest (2930 passed) and ruff.
* Draw the widget in the community's look at once

On every load the launcher appeared in the built-in defaults (the 56px
bubble, #2563eb) and changed to the community's look when its config
request returned, about 450 ms later on test.nemar.org, a reload
included (#475).

- The config's widget block is remembered in localStorage, per
  community and API endpoint, and applied before anything is drawn,
  through the same checks as a fresh one. The fresh config still wins
  and replaces it; setConfig still outranks both.
- The colors are set before the widget joins the page, so the first
  style is already the community's, with nothing to fade from.
- A first visit keeps the launcher hidden, with transitions off, until
  the config arrives (at most 1.5 s, or a failed request), then shows it.
- Re-applying the same logo no longer rebuilds the avatar.

Tested: bun frontend/test-widget-first-paint.js (56, new, in both CI
workflows); test-widget-capsule.js's bubble test now checks the settled
markup and what a first visit adds while it waits; 15 mutations, 13
killed, 2 equivalent; every other Bun suite unchanged and passing.

* Share the Chrome checks' harness server helper

startServer and waitForServer move out of color-scheme-check.mjs into
harness-server.js, for the first paint check to use too; the caller now
reports a server that did not start.

Tested: color-scheme-check.mjs --serve, 26 checks, 0 failures; a server
that cannot start is reported with its output.

* Check the widget's first paint in Chrome

first-paint-check.mjs records the launcher on every animation frame
from document start, with the config request held 600 ms, and requires
every visible frame to show the community's look, on a first visit and
on a reload. Runs in CI beside the light and dark check.

Tested: 12/12 in Chrome 153; develop's widget fails it, as does each of
four mutations (transitions on while waiting, colors set after the
widget joins the page, nothing remembered, no first-visit wait).

* Document the widget's first paint

community-widget.md gains a section on the remembered look: what is
kept and where, how a fresh config and setConfig rank against it, the
first-visit wait and its cap, and blocked storage.

Tested: docs only.

* Let the fresh config win for every field

Review of #476: the server leaves defaults out (a bubble launcher, the
light scheme, an unset color), so a remembered value for a field the
fresh config omits survived the whole load, and a remembered capsule
could not turn back into a bubble at all.

- After a remembered look, the display fields go back to their
  pre-init values before the fresh config is applied; setConfig keys,
  including ones set while the request was in flight, are kept.
- revertLauncherMode undoes the capsule to the bubble's markup; unset
  colors remove their properties; a dropped logo restores the avatar.
- The config is remembered under the community it was requested for.
- The first-visit cap is scheduled before the widget is built, so an
  exception cannot leave the launcher hidden; the tooltip's timer
  starts when the launcher is shown.
- One warning per invalid color and value, not one per application.
- The feedback dialog's "shared with" line follows the config; a first
  visit named the default community's maintainers.

Tested: bun frontend/test-widget-first-paint.js (81; a stale capsule
reverts to the markup of a load remembering the new config, dropped
fields, mid-flight setConfig and community change, an injected fault,
the tooltip, one warning); 16 mutations, all killed; other suites pass.

* Check the first paint on dark devices and a bubble

first-paint-check.mjs records whether the widget is dark on every
frame, and runs three times: NEMAR on a light and a dark device, and the
harness's bubble community (color_scheme auto) on a dark device.

Tested: 42/42 in Chrome 153; develop's widget fails 12 of them.

* Document how the fresh config wins over memory

The first paint section now says what happens to a field the fresh
config leaves out, including the launcher's shape, when a changed look
reaches a reader, the tooltip's timing, and one warning per bad color.

Tested: docs only.
* Use nm000132 (ERP CORE) as NEMAR's example

The general suggested question, the prompt's example identifier and its
describe-dataset step, and the setDataset example in the widget docs now
name nm000132, a public EEG dataset with a Zarr copy, instead of
nm000219, nm000329 and nm000103.

Tested: test_communities_endpoint.py and test_community.py pass.

* Add dataset_suggested_questions to the config

A widget block can now carry question templates for a dataset page
(#477): {dataset_id} required, {subject} and {task} optional, nothing
else, and needs_zarr on the ones that run code against a recording.
resolve() and the API omit the field when a community sets none.

Tested: test_community.py (the new TestDatasetSuggestedQuestions: blank,
brace, markup, length, unknown-field and count refusals); full offline
pytest, 2947 passed.

* Show questions about the dataset on screen

setDataset takes subject and task, BIDS labels, beside id and zarr. On
a dataset page the opening screen shows up to three filled templates,
needs_zarr ones only with a Zarr copy, and the general list when none
fits; mid-conversation a dataset new to the conversation gets a compact
row of two. Each sent message records the dataset on screen, so the row
goes once the reader sends from that page, and stays gone on reload.

Tested: test-widget-dataset-questions.js (51, in both CI workflows), and
22 single-line mutations of the new code each fail it; every other Bun
suite CI runs passes; checked in Chrome, light, dark and at phone width.

* Give NEMAR questions about its dataset pages

Five templates: what the dataset is and how it was recorded, a 10 second
plot and a power spectrum of the page's first Zarr recording (needs_zarr),
how to download it, and which events it annotates. The two that run code
stay within the chat runtime, which has no scipy.

Tested: test_communities_endpoint.py (NEMAR alone sends the field, every
template names its dataset, three need no Zarr copy).

* Document the dataset-page questions

The dataset_suggested_questions field and its rules, setDataset's new
subject and task, and the setConfig key.

Tested: docs only.

* Drop a bad label alone; tell the pop-out too

Review of #478. An invalid subject or task no longer refuses the whole
setDataset call, which kept the previous dataset, and its notebook icon,
on screen; only that fact is dropped. A pop-out is told the dataset on
screen when it opens and on every later setDataset, so its suggestions
follow the page. The harness page takes subject and task too.

Tested: test-widget-dataset-questions.js (64), with tests for both, for
a malformed setConfig value and for the hidden empty area; 29 single-line
mutations each fail it; the color-scheme, first-paint, capsule, notebook
and tools suites pass; bundle check.

* Test a non-string dataset question text

Review of #478: an unquoted YAML number or a null where the text belongs
must fail as a config error, not as an AttributeError.

Tested: TestDatasetSuggestedQuestions, 22 pass; removing the isinstance
guard fails the five new cases.

* Correct the dataset-question docs

Review of #478: NEMAR's config comment no longer says nemar.org passes
subject and task (website#356 is open); BIDS is spelled out where the
widget docs first use it; long sentences break at clause punctuation;
the pop-out and the dropped-label rule are documented; and a CHANGELOG
entry.

Tested: docs and comments only; test_communities_endpoint.py passes.
* Resolve config values for the running deployment

mcp_servers[].url, runtime.python.fetch_allow and runtime.python.prelude
each take one value or a {production, develop} map (#480). The backend
is develop when OSA_DEPLOYMENT says so, or, unset, when mounted at
/osa-dev; the MCP client connects to the resolved URL and the public
config response carries the resolved runtime.

Tested: test_deployment.py (new), the router and MCP client tests; 10
single-line mutations each fail them; full offline pytest, 2956 passed.

* Point NEMAR's develop chat at staging's hosts

test.nemar.org embeds the develop widget and shows only the exemplar
fleet, which production's MCP and Zarr host do not know. Develop now
reads mcp-test.nemar.org and zarr-test.nemar.org, and its prelude points
eegprep-lean's read_index at the staging host (#480).

Tested: test_nemar_runtime.py, test_nemar_mcp_wiring.py, and an offline
check of the vendored wheel that read_index reads the template global
at call time.

* Name the dev container's deployment explicitly

auto-update-dev.sh passes OSA_DEPLOYMENT=develop, which takes effect
when the host's copy is next updated; until then the /osa-dev mount
decides (#480).

Tested: shell change only; the fallback is covered by test_deployment.py.

* Record ADR 0013: the chat follows its deployment

Why per-deployment maps, how the backend knows its deployment, and the
eegprep-lean global the develop prelude relies on (#480).

Tested: docs only.

* Name the deployment in every launch path

auto-update.sh and deploy.sh pass OSA_DEPLOYMENT for whichever deployment
ENVIRONMENT selects, and docker-compose.yml sets production. Production no
longer relies on the ROOT_PATH fallback, since both containers read one
shared .env and a stray ROOT_PATH=/osa-dev there would have sent production
readers to staging hosts. Review finding on #481.

Tested: pytest tests/test_deploy (runs each script's own selection block
under bash for dev and prod) and the offline suite.

* Refuse an unresolved runtime in the config response

CommunityConfigResponse rejects a runtime whose fetch_allow or prelude is
still a per-deployment map, so a caller that skips for_deployment fails on
the server instead of handing the widget a value it reads as no egress and
no prelude. Review finding on #481.

Tested: pytest tests/test_api/test_community_router.py; the validator
mutated off fails both new cases.

* Tighten per-deployment map checks and typing

A map that both misses a deployment and names an unknown one now says both,
since {production, staging} is a typo for develop. A blank OSA_DEPLOYMENT
counts as unset, now pinned by a test. Both deployments' preludes are
tested for compilation, not only develop's. for_deployment's signature and
NOTEBOOK_ENVIRONMENTS are typed with the Deployment literal, clearing two
mypy errors in the new code. Review findings on #481.

Tested: pytest tests/test_core/test_config (a prelude check limited to
develop now fails a test).

* Scope NEMAR's MCP host to production in its docs

The config comment and the module docstring named mcp.nemar.org as the
server for every deployment; develop now reads the staging one. Adds the
#480 changelog entry. Review findings on #481.

Tested: docs only; pytest tests/test_assistants passes.

* Resolve NEMAR's runtime per deployment in JS tests

test-data-lane.js and the browser harness read config.yaml directly and
handed the widget code a per-deployment map, which it reads as no prelude.
Both now resolve production's values, as the server does for a local run.
The data lane also boots the develop prelude in real Pyodide, which nothing
had run before: it checks that FetchTransport is the default and that
read_index points at zarr-test.nemar.org.

Tested: every Bun suite in test.yml's Frontend Tests job, the runtime
bundle check, and bun frontend/browser-harness/chrome.js (exit 0); removing
the develop prelude's INDEX_URL_TEMPLATE line fails the new check.
* Load the pop-out's widget by its address

The pop-out wrote the widget's source inline into an about:blank window,
which inherits the host page's Content Security Policy, so on a page
without script-src 'unsafe-inline' it opened blank. It now writes a
script-free document, sets its presets on the pop-out's window as the
pop-out's own data, and adds a script element with the widget's address
and the host tag's integrity and crossorigin. The widget source is no
longer fetched. A script that does not load says so in the pop-out, and
setColorScheme and setDataset keep the presets current for a pop-out
that has not started yet.

The light and dark Chrome check no longer adds 'unsafe-inline' to the
page's policy for its pop-out step, and checks the page refuses inline
script first.

Tested: bun frontend/test-widget-popout.js (new, 49 passed); the tools
(312), capsule (128), color scheme (126), notebook tab (148), first
paint (81) and dataset question (60) suites; color-scheme-check.mjs
--serve in Chrome 153, all passing, and the widget before this change
times out waiting for the pop-out's widget there.

* Give the pop-out the panel's Chat and Notebook tabs

A capsule community's pop-out now has the panel's tabs as a strip under
its header, since a pop-out has no launcher to hold the circles. It
opens on the tab the reader was on (a new __OSA_TAB__ preset), drawn
there at once rather than fading in from chat, and its notebook tab is a
frame of its own, a fresh notebook session. The strip reuses setTab,
ensureNotebookFrame and the notebook's status line and cues, and follows
the page's dataset. The pop-out button now stays on the notebook tab. A
bubble community's pop-out is unchanged.

Tested: bun frontend/test-widget-popout.js (115 passed), the capsule
(131), notebook tab (148), tools (312), color scheme (126), first paint
(81) and dataset question (60) suites; in Chrome 153, a pop-out opened
from the notebook tab with the fading setTab shows the chat and records
its fade, and with this change does neither.

* Check the pop-out in Chrome under a policy without 'unsafe-inline'

popout-check.mjs --serve starts widget_e2e.py --nemar and opens the
pop-out from the capsule's chat and notebook tabs, attaching to it as
the new target whose opener is the page. It checks that the pop-out
renders on the tab it came from, that its document has no inline
script, that the notebook's frame is at the contract address, and that
the page's policy is in force in both windows (an inline script is
refused). On widget-e2e-sri.html, a new harness route that pins the
widget's tag with integrity and crossorigin as nemar.org does, the
pop-out carries both and renders, and with a wrong digest on the tag
the browser refuses the next pop-out, which says so. Runs in CI beside
the first paint check, in both workflows.

Tested: popout-check.mjs --serve in Chrome 153, 46 of 46; with the
initial tab set by the fading setTab it fails two checks; ruff check
and format on widget_e2e.py.

* Say the pop-out shares the page's storage, and check it

docs/community-browser-runtime.md said the pop-out can run on another
origin and see neither the chat history nor the workspace. It is an
about:blank window of the page's own origin, so it has the page's
storage. popout-check.mjs now checks that every pop-out has the page's
origin and reads a localStorage value only the page wrote.

Tested: popout-check.mjs --serve in Chrome 153, 49 of 49.

* Document the pop-out and what its page's policy needs

docs/community-widget.md gains "The pop-out window": what it carries
and shares with the page, the tab strip, its notebook as a frame and a
fresh notebook session of its own, and what a host page's policy needs
for it (nothing beyond the widget's own; integrity and crossorigin kept
together). The notebook tab's text says the pop-out button stays there,
and the "does not carry the notebook yet" note is gone. ADR 0012 gets an
update section for the two sentences the pop-out now contradicts, and
docs/community-notebook.md stops saying "once it carries the notebook".
CHANGELOG entries under Added and Fixed.

Tested: docs only; the paths and names they cite were checked against
the branch.

* Tighten three pop-out tests a mutation sweep passed

The sweep over the pop-out's widget code left three changes uncaught:
a strip on the page's own panel, the busy cue on the open notebook tab,
and the strip's Chat tab not focusing the input, which passed because
focus never left the input in happy-dom. Each now has a check that
fails under it.

Tested: bun frontend/test-widget-popout.js (118 passed); each of the
three mutations now fails it, and the file is restored after each.

* Account for the harness's pinned page in the embed tripwire

widget_e2e.py's widget-e2e-sri.html route carries a widget script tag,
which TestEveryWidgetScriptTagIsAccountedFor requires to be parsed or
exempted by name. It is a dev harness page with a relative src, like
widget-e2e.html, so it joins that allowlist with its reason.

Tested: uv run pytest tests/test_frontend/test_embed_snippet_hygiene.py
(17 passed; the tripwire failed before this).

* Let the pop-out check load the real notebook on request

popout-check.mjs --live-notebook points the notebook at the develop
notebook site and requires the pop-out's own notebook to report "Python
ready" through the bridge, which shows the site's frame-ancestors admits
a pop-out and the bridge's messages reach the pop-out's widget. It needs
the network, so CI runs the check without it.

Tested: popout-check.mjs --serve --live-notebook in Chrome 153, all
passing, "Python ready" 8.9 s after the tab showed; --serve alone still
49 of 49.

* Hand an open pop-out's API its own copy of the dataset

forwardDatasetToPopout copied the dataset into the pop-out's realm for
its preset but passed the page's own object to its setDataset. Both now
get the same copy, as openPopout's presets do. Harmless before, since
setDataset rebuilds the object from its fields; a review raised it.

Tested: bun frontend/test-widget-popout.js (119 passed); passing the
page's object again fails the new check; dataset question (60),
notebook tab (148) and capsule (131) suites.

* Test a pop-out whose notebook tab goes stale

Opened from the notebook tab, the pop-out is told that tab once, while its
dataset preset follows the page until it starts. A new case clears the
dataset, or names one with no Zarr copy, before the pop-out starts, and
checks it opens on chat with no frame. Another pins that a later
setConfig does not reach an open pop-out, as documented. Review findings
on #482.

Tested: bun frontend/test-widget-popout.js (132 passed); disabling
setTab's notebook fallback now fails four checks.

* Say a nonce-only policy is not supported

The widget adds script elements of its own, the pop-out's and the browser
runtime's, without a nonce, so a policy that allows scripts only by nonce
refuses them. Review finding on #482.

Tested: docs only.
#483)

* Read notebook outputs, not the page, in the e2e check

JupyterLab renders only the cells in view, so once a starter is longer
than the viewport the read cell's output leaves the DOM and the check
timed out. The read line, the figure count and any error now come from
the notebook model; the figure check allows one figure per cell rather
than one in all, and an error names its cell, type and message.

Tested: bun notebook/e2e-check.js --environment production and develop
(all checks pass); before the fix, a longer starter timed out on the
read line, and a SciPy error in an off-screen cell was invisible to the
old Traceback search.

* Teach NEMAR spectra, events and ERP images

A prompt section on Welch's method, filtering and epoching in numpy (the
chat runtime has no SciPy), and on finding a dataset's conditions from
nemar_get_events' columns_summary before asking for them with where and
columns, with ERP CORE's N170 as the worked example. The dataset-page
questions offer the power spectrum and an ERP image first. The widget
test's templates are relabeled as a fixture, not NEMAR's list.

Tested: pytest tests/test_assistants and tests/test_core/test_config;
bun frontend/test-widget-dataset-questions.js (64 passed); the worked
example's numbers come from running it on nm000132.

* End NEMAR's starter with a power spectrum

The last cell reads the first two minutes of the recording and plots each
channel's spectrum and their median, with SciPy, leaving out EOG, ECG and
EMG channels by name. It takes Welch's periodograms one segment at a time:
scipy.signal.welch's strided view of every segment at once overflows the
browser's 32-bit Python on a long multichannel read. It links to NEMAR's
worked examples for more.

Tested: the notebook e2e check in both environments; the cells in
CPython on nm000132, nm000103, xx099903 (EMG, 259 channels at 1000 Hz),
xx099904 and xx099906; the segment-wise average matches
scipy.signal.welch to 1e-15.

* Fix the prompt's filter recipe and channel choice

np.convolve is one-dimensional and an even tap count shifts the signal by
half a sample, so the prompt now says to filter the plotted channel (or
loop), with an odd tap count it gives as code. It says to read every
channel of the group for these analyses, and to offer the power spectrum
when a recording has no events that name conditions. EOG and ECG are
spelled out. Review findings on #483.

Tested: pytest tests/test_assistants and tests/test_core/test_config
(690 passed); the recipe as now written is the one the OSC docs' chat
example runs, which reproduces the page's -4.2 uV.

* Guard an empty read and spell out abbreviations

The spectrum cell stops with a message on a recording with no samples,
which the index contract allows. The notebook and the changelog spell
out ERP, EOG, ECG and EMG. Review findings on #483.

Tested: the cells in CPython on nm000103 and xx099906; the notebook e2e
check in both environments.

* Require one figure from each plotting cell

The figure check allowed a plotting cell that silently drew nothing, as
long as another cell drew one. It now requires exactly one figure from
each of the starter's two plotting cells. Review finding on #483.

Tested: bun notebook/e2e-check.js --environment production and develop
(all checks pass, figures per code cell [0,0,1,1]).
* Title the changelog's release as 0.8.14

Tested: docs only.

* Complete the 0.8.14 changelog

Release review: add the widget's Notebook tab (#471, #474), color_scheme auto (#472), the first-paint fix (#476) and the dark-page field colors; the capsule and notebook-site bullets described the notebook opening in a new tab, which #474 replaced.

Tested: docs-only; each claim checked against origin/develop (config.yaml color_scheme, osa-widget-config- key, ADR 0012 path).
tests/test_tools/test_hed_validation.py calls hedtools.org in every test but only one class carried a marker (integration), so the unit jobs ran the rest and a slow response failed unrelated PRs: #484 (read operation timed out) and #485 (two validations returned False) on 2026-09-24. A module-level pytestmark = pytest.mark.network leaves them to test.yml's network job, which is continue-on-error.

Tested: -m 'not integration and not llm and not network' deselects all 11; -m network runs all 11, passing against hedtools.org; ruff check and format clean.
* Give NEMAR's prompt the ERP low-pass as code

In a staging run on test.nemar.org/dataset/xx099906 the model wrote np.sinc(n) * np.hamming(taps) from the prose, which is a single spike: its gain at 50 Hz is 1.0, so every ERP image it drew was unfiltered. The prompt now carries the kernel as a python block with the cutoff (np.sinc(2 * 30 / rate * n)), puts the ERP image's time axis in milliseconds, and asks for deflections with latency and size before naming a component.

test-data-lane.js runs that block as the prompt writes it in real Pyodide: 101 taps at 250 Hz, gain 1.000 at 5 Hz and 0.0007 at 50 Hz, and a 5 Hz plus 50 Hz sine comes out as the 5 Hz sine.

Tested: bun frontend/test-data-lane.js 66/66; mutated the prompt to np.sinc(n), 2 checks fail; pytest test_nemar_runtime, test_nemar_mcp_wiring, test_core 616 passed; ruff clean.

* Changelog: the ERP low-pass fix

Tested: docs-only.

* Clamp the ERP cutoff and filter by FFT

Review of #485: at 60 Hz the 30 Hz cutoff reaches the Nyquist frequency and the kernel is a spike again, and at 5000 Hz np.convolve with 2001 taps is too slow for a browser. The prompt's filter clamps the cutoff to rate / 4 and convolves by FFT, which equals np.convolve(x, kernel, "same") and takes a channels-by-samples array. The test runs the block at 60, 125, 250, 1000 and 5000 Hz, compares it with np.convolve and row by row, and requires the block to follow the ERP bullet's opening lines.

Tested: bun frontend/test-data-lane.js 93/93; mutations (no clamp, np.sinc(k), slice off by one) fail 2, 6+ and 6+ checks; pytest nemar runtime and wiring pass.
@github-actions

Copy link
Copy Markdown
Contributor

Preview Deployment

Name Link
Preview URL https://develop-demo.osc.earth
Branch develop
Commit 5df5838

This preview will be updated automatically when you push new commits.

@neuromechanist
neuromechanist merged commit 0bb6c20 into main Sep 24, 2026
29 checks passed

This branch was previously deployed

1 inactive deployment
testpypi — 67216556 Deployed Sep 24, 2026 by neuromechanist via Publish to TestPyPI #97
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant