125 Commits

Author SHA1 Message Date
Illia Polosukhin
7194808f11 fix(web): keep Routines tab after engine v1 → v2 upgrade (#2982) (#2992)
* fix(web): keep Routines tab after engine v1 → v2 upgrade (#2982)

Users upgrading from a v1 install (e.g. 0.24.0 → 0.26.0) lost the UI
affordance to view or manage existing routines: `applyEngineModeToTabs()`
and `applyEngineModeUi()` unconditionally hid the v1-only Routines tab
whenever ENGINE_V2 was enabled, even though the routines were still in
the database and the API still served them.

The fix adds a `userHasLegacyRoutines` flag, populated from
`/api/routines/summary` on first gateway-status poll. The Routines tab
stays visible (and `#/routines/<id>` still resolves to the legacy
detail view) when the user has any v1 routines.

Also fixes a wire-contract drift in `gateway-tee.js`: it read
`data.engine_v2` for the activity store and `data.engine_v2_enabled`
for the global, with `applyEngineModeUi()` running before the global
was set. Per `.claude/rules/types.md` ("Wire-contract field naming"),
the duplicate `engine_v2` field is removed from
`GatewayStatusResponse`; the JS now reads the single canonical name
once and sets the global before any UI helper consults it.

* fix(web): address PR #2992 review notes — race guard, dedup, post-delete refresh

Three review-driven hardening tweaks plus expanded Playwright coverage,
all on the same #2982 fix:

- gateway-tee.js: flip `engineModeApplied = true` synchronously so a
  second status poll firing while the first refresh is still in flight
  cannot kick off a duplicate `/api/routines/summary` request. The
  trailing `.then()` still runs on fetch failure (the `.catch()` chain
  resolves to undefined), so the UI still settles.
- projects.js: route the routines-tab visibility branch through
  `shouldHideRoutinesTab()` instead of duplicating the predicate
  inline. Single source of truth for the rule.
- routines.js: refresh `userHasLegacyRoutines` after a successful
  `deleteRoutine` so the v2 user who just removed their last legacy
  routine sees the tab fall back to hidden without a page reload.

Playwright coverage grew from 5 to 11 cases: route-mocked summary,
zero-total clears the flag, fetch failure preserves the prior value,
post-delete refresh hides the tab, dual back-to-back first polls fan
out only one summary fetch, and `restoreFromHash` routes correctly when
legacy data exists.
2026-04-28 14:57:03 +03:00
jinxin
93d0305547 fix(web): drop SSE plan_update/approval_needed events without thread_id (#2986) 2026-04-28 08:48:39 +03:00
Henry Park
983a95cc98 Merge pull request #3002 from nearai/main
Main
2026-04-27 16:50:23 -07:00
Henry Park
91c4c7ca7b fix: resolve v2 tool_info action inventory lookup (#2994) 2026-04-27 23:32:40 +03:00
Illia Polosukhin
e7d9922ce0 fix(engine): make mission threads_today reset timezone-aware (#2989)
* fix(engine): make mission threads_today reset timezone-aware

The daily-budget reset added in #2570 compared `last_fire_at.date_naive()`
against `now.date_naive()`, both in UTC. Cron missions configured with a
non-UTC timezone (e.g. `America/Los_Angeles`) expect their budget to
refresh at the user's local midnight, not at 00:00 UTC — under the old
logic such a mission could stay stuck at "exhausted" for up to ~17 hours
into the new local day.

Extract the staleness check into `threads_today_is_stale(&mission)` and
use the mission's cron timezone (when set) for the day boundary; UTC
remains the fallback for manual / event-driven cadences and for cron
missions without a configured timezone.

Tests:
- cron_mission_threads_today_resets_via_tick locks in the tick + cron
  path; the existing reset test only covered fire_on_system_event.
- threads_today_resets_at_cron_local_midnight uses Pacific/Auckland to
  produce a `last_fire_at` that is yesterday-local but same UTC day,
  which the old logic would not have reset.
- threads_today_is_stale_predicate covers the boundary helper directly.

Fixes #1945

* review: address reviewer feedback on threads_today_is_stale

- Inject `now: DateTime<Utc>` into `threads_today_is_stale` so the
  predicate is unit-testable against fixed instants and so the call
  site can pin a single timestamp across the staleness check and the
  cooldown check (Gemini, Copilot).
- Capture `now` once at the top of the staleness/cooldown block in
  `fire_mission` and reuse it for the cooldown comparison so the two
  cannot disagree across a midnight tick.
- Reword the helper doc to drop the hard-coded "5 PM local" claim,
  which varies under DST (Copilot).
- Consolidate the prior wall-clock-based Auckland integration test
  into deterministic synthetic-instant cases inside
  `threads_today_is_stale_predicate`. The previous test could pass
  even when the timezone branch was disabled, depending on when of
  day it ran (Copilot). The new case asserts: same UTC date, but
  Auckland local dates straddle the boundary — exactly the regression
  the timezone branch fixes.
- Document why `last_fire_at = None` with a non-zero counter must
  return `true` (recovery direction), not `false` — `false` would
  re-introduce the permanent-exhaustion bug this helper exists to fix.
2026-04-27 23:03:37 +03:00
Henry Park
2ef7d2c982 engine-v2: make available_actions callable-only for blocked providers (#2868)
* engine-v2: make available_actions callable-only for blocked providers

* fix(engine): address review fixture tempdir leak (#2868)

* engine-v2: refresh canonical prompt metadata on resume (#2869)

* fix(engine): align prompt metadata refresh with resume state

* fix(engine): finish prompt refresh compaction coverage (#2869)

* fix(engine): preserve prompt refresh on resume (#2869)

* Add engine v2 action discovery metadata (#2876)

* Add engine v2 action discovery metadata

* fix(engine): address action discovery review (#2876)

* fix(engine): address follow-up review comments (#2876)

* fix(engine): satisfy clippy in orchestrator lookup

* fix(engine): propagate action snapshots in executor paths (#2876)

* fix(bridge): restrict tool_info to callable actions (#2876)

* [codex] Finish engine v2 deferred action inventory cleanup (#2889)

* Add deferred action inventory groundwork

* fix(engine): address deferred action inventory follow-up

* fix(engine): address deferred inventory review feedback

* test: fix fmt and clippy failures

* engine-v2: trim unused callable discovery payload

* tests: restore env vars in review-fix cases

* engine-v2: populate callable snapshots consistently

* Unify v2 integration enablement on tool_activate

* engine-v2: tighten tool_info inventory and approvals

* llm: normalize tool_info hint syntax

* engine-v2: tighten tool_activate install approval lookup

* tests: align gmail settings-first flow with approval contract

* engine-v2: fix remaining tool surface review issues

* engine-v2: restore auto-approve defaults

* fix(engine): align v2 tool permissions with defaults

* fix(engine): close v2 callable snapshot gaps

* fix(bridge): label latent-only providers accurately
2026-04-24 19:38:59 -07:00
jinxin
444bf6f4d1 fix(web): resolve empty “Fetch available models” result for NEAR AI in settings (#2890)
* fix(web): match subdomains of private-chat-stg.near.ai as NEAR AI private endpoint

* fix(web): remove LLM provider restart notices now that hot-reload is supported

LLM provider changes (switch/add/configure/update) now apply without a
restart, so the inline "Changes take effect after restart" banner in the
LLM Providers section, the mirrored banner in the Inference settings
panel, and the "(restart to apply)" suffix on the provider toasts are
all stale. Drops the HTML banner, the dynamic mirror in settings.js,
the three show-calls in config.js, the now-unused .config-notice CSS,
the config.restartNotice i18n key, and the suffix from providerConfigured
/ providerActivated / providerAdded / providerUpdated across en / zh-CN
/ ko. RESTART_REQUIRED_KEYS (embeddings, tunnel, gateway) is untouched —
those still require a restart.

* fix(web): avoid /v1/v1/models for NEAR AI private hosts with /v1 suffix

fetch_provider_models unconditionally appended /v1 for any NEAR AI
private host, so operators configuring a base URL that already ends in
/v1 (e.g. https://us.private-chat-stg.near.ai/v1) got /v1/v1/models and
404s from "Fetch available models". The Anthropic branch already had
the guard; the NEAR AI branch did not.

Extract models_endpoint_base(adapter, base) as a pure helper covering
both adapters, and swap the inline logic in fetch_provider_models for a
single call. Adds caller-level regression tests around the URL
construction path per .claude/rules/testing.md — the previous helper-
only tests on is_nearai_private_endpoint would have stayed green
through this bug.

* chore: minor

* fix(web): atomically switch llm_backend + selected_model on provider activation

setActiveProvider() was issuing two sequential PUTs — /api/settings/llm_backend
then /api/settings/selected_model. The settings handler hot-reloads the LLM
provider chain after each write, and config/llm.rs gives selected_model
precedence over provider defaults/overrides, so the first reload rebuilds the
chain with the new backend but the previous provider's model. If the second
request then fails, the instance stays stuck in that mixed state while the
success toast has already fired.

Route both writes through /api/settings/import instead: set_all_settings
commits the pair in one transaction and triggers a single reload, with
snapshot-based rollback of every key if the resulting chain fails to build.

Raised on the restart-notice removal PR (27c70552) — before that commit the
inline banner at least hinted the switch wasn't fully live; now that the
banner is gone, the atomicity gap is the only thing standing between the
toast and reality.

* fix(web): fall back to env var for builtin provider API keys

`resolve_api_key_from_secrets` previously only consulted the encrypted
secrets store, so the "Fetch available models" and "Test" buttons in
the Configure dialog sent no Authorization header when the UI showed
"Key configured (leave blank to keep)" — the provider then responded
401 even though chat worked.

Default IronClaw onboarding (`api_key_login()` in `llm/session.rs`)
writes the key to `NEARAI_API_KEY` + `~/.ironclaw/.env`, not to the
vault. The secrets-store-only lookup missed that path entirely. Add
an env-var fallback that resolves the right env name per provider —
`NEARAI_API_KEY` for NEAR AI, `ProviderDefinition::api_key_env` for
registry providers — so the configure dialog matches what the chat
pipeline already sees. Only applies to builtin providers; custom
providers have no declared env var and are unchanged.

Adds a caller-level regression test driving `llm_list_models_handler`
against a local mock server and asserting the forwarded
`Authorization: Bearer <key>` matches the env var. Also takes
`config::helpers::lock_env()` in both NEARAI env-mutating tests so
the module no longer flakes under parallel test execution.
2026-04-24 18:00:31 +03:00
Illia Polosukhin
eb75a62a97 feat(debug-panel): expand Activity tab coverage with CodeAct + warnings (#2850)
* feat(debug-panel): expand Activity tab coverage with CodeAct + warnings

The Activity tab was missing most event types: CodeAct runs showed only
lossy chat summaries, WARN/ERROR logs only landed in server stdout, and
tool entries hid their parameters on success.

- Emit AppEvent::CodeExecuted (verbose-only) with raw code, stdout, and
  return value from the engine orchestrator so observers see what the
  model actually wrote.
- Bridge WARN/ERROR tracing into AppEvent::Warning via
  spawn_warning_bridge, scoped by owner_id in multi-tenant mode to
  prevent cross-tenant log bleed.
- Backfill params_summary on ActionExecuted/ActionFailed events from
  structured + scripting executors so the Activity tab shows tool args
  immediately (not just on failure) without waiting for tool_completed.
- Wire debug-panel.js to render code_executed, warning, gate_required,
  gate_resolved, approval_needed, skill_activated, plan_update,
  thread_state_changed, child/mission_thread_spawned, onboarding_state,
  image_generated, suggestions, and the full sandbox-job event family.
- Extract shared on(name, handler) wrapper to dedupe ~25 copies of the
  JSON-parse + reconnect-counter housekeeping and keep lastEventTime
  bookkeeping consistent across listeners.
- Add i18n strings (en/ko/zh-CN) and CSS icon colors for the new
  activity types.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(debug-panel): address review feedback on activity-trace PR

- summarize_params generic fallback: skip sensitive-looking parameter
  keys (token/secret/password/api_key/auth/credential/bearer) so MCP
  and unknown-tool calls can't surface secret values into
  ActionExecuted events or debug-panel SSE. Adds two regression tests.
- Cap CodeExecuted code/stdout at 8_000 chars (tail-last) before
  emission so a step that prints a large blob can't bloat persisted
  thread events. Matches the existing scripting OUTPUT_TRUNCATE_LEN.
- await_thread_outcome: skip broadcasting verbose-only AppEvents when
  no debug subscriber is connected — mirrors the send_status gate
  and keeps CodeExecuted off the shared SSE broadcast buffer for
  normal browser tabs.
- spawn_warning_bridge: same short-circuit on has_verbose_receivers.
- debug-panel.js: introduce GATE_RESOLUTION_STATUS so `expired`
  (a failure path from router.rs) no longer renders as a green
  success badge; shared STATUS_TO_ACTIVITY map is kept for jobs/
  plans/onboarding where `success` is the right default.
- debug-panel.js: migrate the remaining legacy listeners to the
  shared on() wrapper so lastEventTime / totalEventsReceived
  bookkeeping stays consistent across every activity listener.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(debug-panel): address PR #2850 follow-up review on leak / tenant scoping

- Warning bridge (`src/channels/web/mod.rs`): disable entirely in
  multi-tenant mode. The `tracing` layer captures log context at the
  global subscriber scope, not at request scope, so scoping the bridge
  to the gateway `owner_id` misroutes tenant A's WARN/ERROR log lines
  to the admin account (and prevents tenant A from ever seeing them).
  Per-request provenance would need threading through every `warn!` /
  `error!` call site — out of scope for this PR — so the safe move is
  to keep the bridge off until that lands.
- `summarize_params` (`crates/ironclaw_engine/src/types/event.rs`):
  strip URL query strings / fragments / userinfo for `http` and
  `web_fetch`, and redact auth-bearing flag values (`-H`, `--header`,
  `-u`, `--user`, `--token`, `--api-key`, `--password`, `--auth`,
  `--bearer`) plus embedded URL query strings inside `shell` commands.
  Signed URLs, inline `Authorization: Bearer …` headers, and query-
  string API keys no longer reach `ToolCompleted.parameters` on the
  debug SSE stream. Six regression tests added.
- `CodeExecuted` redaction (`src/bridge/router.rs`): apply the leak
  detector to `code` / `stdout` / `return_value` at the bridge
  boundary before SSE broadcast. The engine crate has no dependency on
  `ironclaw_safety`, so scrubbing lives here. Adds
  `SafetyLayer::leak_detector()` and `EffectBridgeAdapter::safety()`
  accessors. Handles both `Redact` and `Block`-action matches
  (scan_and_clean's `redacted_content` is `None` for Block-only
  matches, which would have passed bearer tokens / API keys through
  unchanged). Regression test covers string and nested-JSON cases.

* fix(debug-panel): address PR #2850 Copilot follow-up review

- `src/channels/web/log_layer.rs`: annotate `spawn_warning_bridge`'s
  `sse.broadcast_for_user` / `sse.broadcast` sites with
  `// projection-exempt: log source, WARN/ERROR tracing bridge →
  AppEvent::Warning` so the PROJECTION safety check (#9 in
  `scripts/pre-commit-safety.sh`) recognises the tracing
  `LogBroadcaster` as a typed source log. Added a comment block
  explaining why the source-log category isn't yet in
  `.claude/rules/gateway-events.md`'s table.
- `crates/ironclaw_engine/src/executor/orchestrator.rs`: replace
  `tail_chars` (O(n) via `chars().count()`) with a local
  `tail_utf8_bytes` helper for the `CodeExecuted` emission path. Byte
  based so it stays O(1) + ≤3-byte UTF-8 boundary walk for arbitrarily
  large `code`/`stdout`. Also add `bounded_return_value` so a CodeAct
  snippet returning a 50 MB JSON value doesn't bloat persisted thread
  events — strings are tail-truncated; structured values that
  serialize past 8 KiB are dropped to `None` (rather than truncated
  into unparseable JSON). Seven regression tests cover ASCII / emoji
  boundary / null / small struct / oversized struct / large-string
  paths.

`tail_chars` is kept unchanged for its existing callers, whose inputs
are already bounded (`OUTPUT_TRUNCATE_LEN`, 500-char error slices).

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-24 13:48:02 +09:00
firat.sertgoz
1a44a9442e chore(engine): bump Monty to v0.0.16 (#2784) 2026-04-24 04:31:18 +03:00
firat.sertgoz
2d4b35daa9 feat(missions): redesign missions overview surface (#2894) 2026-04-24 04:24:42 +03:00
Pranav Raja
49f3e8d566 feat(credentials): path-based credential matching for per-endpoint auth (#2168)
* feat(credentials): path-based credential matching for per-endpoint auth

Add `path_patterns` field to `CredentialMapping` to scope credentials to
specific URL path prefixes on a host. When set, the request path must
match a prefix at a segment boundary (`/` or `?`). When empty (default),
credentials match all paths on the host — fully backwards compatible.

Key changes:
- `CredentialMapping.matches(host, path)` with segment-boundary enforcement
- `path_matches_prefix()` rejects `..` traversal, normalizes trailing slashes
- `host_matches_pattern()` deduplicated to single source in secrets/types.rs,
  case-insensitive per RFC 4343
- HTTP tool uses `find_for_url(host, path)` for path-aware credential lookup
- Auth manager pre-flight check uses path-aware `find_for_url`
- WASM tool/channel wrappers carry `path_patterns` through to injection time
- `CredentialMappingSchema`, `SkillCredentialSpec` support `path_patterns`

Tests cover segment-boundary attacks, path traversal rejection, case-insensitive
host matching, path-scoped injection, and different credentials for different
paths on the same host.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix(credentials): address PR #2168 review feedback

- Narrow `..` rejection in path_matches_prefix to per-segment so
  legitimate paths like /api/..config are no longer falsely blocked
  (path_matches_prefix was using path.contains("..")).
- Path-scope credential injection in the channels WASM wrapper:
  ResolvedHostCredential now carries path_patterns and
  inject_host_credentials honors it, matching the tools-side wrapper.
- Add path-aware CredentialInjector API (find_credentials_for_url /
  inject_for_url); deprecate the host-only variants and
  SharedCredentialRegistry::find_for_host with #[deprecated] attrs.
- Tighten CredentialMappingSchema.path_patterns from
  Option<Vec<String>> to #[serde(default)] Vec<String>, matching
  sibling types.
- Validate path_patterns in validate_credential_spec: require
  leading '/', reject empty, reject '..' as a segment.
- Expand comment in http.rs documenting why LLM-header blocking is
  host-scoped (exfil defense) while injection is path-scoped
  (minimum privilege).

Tests: +5 validation cases, +2 injector cases, +2 channel wrapper
cases, +2 path_matches_prefix cases covering dot-dot-inside-segment.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(credentials): address PR #2168 round-3 review

- secrets/types: reject %2e / %2E in paths (percent-encoded traversal
  bypass for servers that decode before routing, e.g. IIS/Tomcat)
- sandbox/proxy/policy: find_credential now honors path_patterns via
  CredentialMapping::matches, using request.path (regression test added)
- wasm wrappers: extract shared extract_url_path_for_matching helper in
  secrets/types, with tracing::debug! on URL parse failure; removes
  duplicated 12-line block between tools/wasm and channels/wasm
- ironclaw_skills/validation: factor validate_path_pattern out of
  validate_credential_spec and reject '?' and '#' in path_patterns
  (Url::path() strips them, so these silently never match)
- tools/wasm/capabilities_schema: plumb the same validate_path_pattern
  through the WASM manifest loader — bad patterns log as warnings
  instead of silently failing to match
- tools/builtin/http: unit tests for extract_path_from_params (valid,
  missing url, query+fragment stripping, bare host, malformed)
- tests/skill_credential_injection: caller-level tests driving
  HttpTool::execute with path-scoped credentials — segment boundary
  and auth-gap-on-non-matching-path (per .claude/rules/testing.md
  "Test Through the Caller, Not Just the Helper")

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(credentials): address PR #2168 round-4 review

- secrets/types: path_matches_prefix now decodes each segment and rejects
  only dot-segments (literal . or .., plus percent-encoded equivalents
  like %2e, %2e%2e, mixed case, .%2e, %2e.). Legitimate literal paths
  with embedded encoded dots — /files/foo%2ebar → foo.bar,
  /releases/v1%2e2 → v1.2 — are now allowed. Replaces the previous
  "reject any %2e substring" rule which over-rejected normal filenames.
  (Firat #3125964627)

- secrets/types: add match_specificity(path_patterns, req_path) returning
  the length of the longest matching prefix (0 if unscoped). Exported
  pub(crate) for callers that need deterministic credential precedence.

- credential_injector + both wasm wrappers: sort matching credentials by
  ascending path specificity, tie-broken alphabetically on secret_name,
  before the last-write-wins header merge. The most-specific mapping now
  wins any header conflict regardless of HashMap iteration order, which
  fixes nondeterministic winner selection on overlapping mappings.
  ResolvedHostCredential gains a secret_name field purely for stable
  tie-breaks (no secret material exposed). (Firat #3125963270)

- bridge/auth_manager::check_http_auth: replace "return Ready on first
  resolved mapping" short-circuit with conjunctive evaluation — every
  non-optional matched mapping must resolve for Ready. Optional mappings
  are skipped. Missing required credentials are accumulated and returned
  as MissingCredentials so endpoints needing bearer + org-header surface
  the auth gate instead of failing at the wire with a raw 401.
  (Firat #3125963977)

- tools/builtin/http::execute: stop clearing missing_credential on peer
  success and drop the !injected_any_credential guard. Track the first
  missing required credential for the 401/403 remediation UX; skip
  optional mappings. Matches the new auth_manager behavior.

Regression tests:
- secrets/types: path_matches_prefix_rejects_percent_encoded_dot_segments
  (adds .%2e and %2e. mixed-form cases), path_matches_prefix_allows_legit_
  embedded_encoded_dot (foo%2ebar, v1%2e2), match_specificity_ranks_
  longer_prefixes_higher.
- tools/wasm/wrapper: test_inject_host_credentials_most_specific_path_wins
  verifies the sort is order-independent by constructing the same creds
  in both orders and asserting the specific one wins.
- bridge/auth_manager: check_http_conjunctive_auth_any_missing_required_
  raises_gate, check_http_conjunctive_auth_all_required_resolved_is_ready.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* style: cargo fmt after round-3/round-4 review fixes

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* chore: untrack accidentally-committed local scratch files

Follow-up to 50f6771f, which inadvertently staged local-only scratch
files via `git add -A`:
- .DS_Store
- tests_all/ — operator scratch dir with env files (rotate any tokens
  that were in tests_all/source_env_vars.sh in that commit)
- integrations/abound/tests/source_env_vars.sh — same concern
- src/cli/snapshots/*.snap.new — stale insta snapshot proposals that
  should be resolved via `cargo insta review`, not committed

This commit removes them from the index and adds matching patterns to
.gitignore so they cannot recur. The content is left on disk for local
use.

NOTE: the tokens that were in the env files are still visible in the
50f6771f commit object and must be rotated regardless of this cleanup.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(credentials): address PR #2168 round-5 review

- secrets/types: tighten the percent-decoded dot-segment check to also
  reject segments whose decoded form contains `/` (percent-encoded
  slash, e.g. `%2f`). Blocks `%2e%2e%2fadmin`-style smuggling on
  servers that decode encoded slashes before routing (Tomcat with
  `allowEncodedSlash=true`, older IIS, certain reverse proxies).
  Literal dots inside a single segment (`foo%2ebar`, `v1%2e2`) stay
  allowed. (Firat #3126256056)
- sandbox/proxy/policy: `find_credential` now returns the most-specific
  matching mapping via `max_by(...)` on `(match_specificity, secret_name)`
  rather than `.find(...)`. Behavior matches `SharedCredentialRegistry::
  find_for_url` and both WASM `inject_host_credentials` — a host with a
  global + a `/api/v1/write` credential picks WRITE_TOKEN on writes
  regardless of Vec order. (Firat #3126256060)
- tools/wasm/capabilities_schema: `to_credential_mapping` now returns
  `Option` and `to_http_capability` filter_maps invalid mappings out
  entirely. Previously `path_patterns: [""]` survived the warning-only
  validator and silently widened the credential back to global scope
  (`path_matches_prefix(path, "")` → true for every absolute path).
  The drop-on-invalid semantics match the skills pipeline. Removed the
  duplicate warn-loop in `validate()` since the load path now handles
  it. (Firat #3126256040)

Regression tests:
- secrets/types: path_matches_prefix_rejects_percent_encoded_slash_
  smuggling covers lowercase/uppercase `%2f` in traversal and embedded
  positions.
- sandbox/proxy/policy: test_sandbox_proxy_most_specific_credential_
  wins registers the same credentials in both orders and asserts
  WRITE_TOKEN always wins on the write path.
- tools/wasm/capabilities_schema: three tests covering empty-string
  pattern (drops mapping), missing-leading-slash (drops mapping), and
  valid pattern (preserved).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-23 11:58:26 -07:00
firat.sertgoz
b5ba7496f0 fix(engine): enforce tool use for stop/pause/cancel commands (#2814)
* fix(engine): enforce tool use for stop/pause/cancel commands (#2808)

The LLM was narrating about calling mission_pause/mission_list instead of
actually executing them because neither the tool-intent nudge nor the
execution obligation recognized stop/pause/cancel as action commands.

- Add stop/pause/cancel/halt/disable to signals_tool_intent ACTION_VERBS
  so the nudge fires when the LLM says "I'll pause the mission"
- Add stop/pause/cancel phrases to signals_execution_intent EXEC_PHRASES
  so the obligation system forces tool calls for "stop it", "pause the X"
- Add bare imperative detection (startswith) for "stop", "stop pinging",
  "pause", "cancel" — avoids false positives like "I can't stop"
- Add 5 regression tests covering true positives and false negatives

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix: address review findings (iteration 1)

- Add missing "please halt " to EXEC_PHRASES for consistency with
  please stop/pause/cancel
- Strip trailing punctuation from bare commands so "Stop." and "cancel!"
  are detected
- Add 2 regression tests covering both fixes

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix(engine): address gemini-code-assist review — halt/disable consistency (#2814)

- Add "halt it/that/this/the" and "disable it/that/this/the" to
  EXEC_PHRASES for consistency with signals_tool_intent
- Add "please disable " to polite execution phrases
- Add "disable" to BARE_COMMANDS and IMPERATIVE_STARTS
- Add regression test for halt/disable execution intent phrases

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-23 08:50:35 +03:00
firat.sertgoz
009d3cd82f fix(web): use conversation-only chat sidebar (#2867)
* fix(web): use conversation-only chat sidebar

* fix(ci): use unwrap_or_default() for clippy compliance

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-23 08:31:12 +03:00
Henry Park
d33fecb17c engine-v2: centralize action vs capability surface policy (#2827)
* Add canonical engine capability status enum

* Add bridge tool surface assignment policy

* fix(engine): tighten scoped surface assignment

* fix(bridge): remove premature approval_gated field, surface ReadyScoped in capabilities

- Remove approval_gated from SurfacePolicyInput (YAGNI until policy uses it)
- Change ReadyScoped fallback from neither() to capabilities_only() so
  scoped subjects remain visible in background context
- Update tests to match new behavior

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix(ci): unblock section 2 policy PR

* engine-v2: add capability projection and two-surface prompt baseline (#2826)

* Add capability projection and two-surface prompt baseline

* Reduce step-context args for clippy-clean two-surface stack

* fix(engine): address two-surface review follow-ups

* fix(engine): normalize alias-aware capability projection

* fix(bridge): share extension fetch between projectors, preserve NeedsAuth in actions

- Fetch list_capability_extensions once in EffectBridgeAdapter and pass
  to both ActionProjector and CapabilityProjector via prefetched_extensions
- Keep NeedsAuth provider tools in available_actions so the LLM can
  trigger auth gates by attempting to call them
- Add unit tests for NeedsAuth preservation and latent tool omission
  at the ActionProjector level where extension maps can be controlled

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: serrrfirat <f@nuff.tech>
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: serrrfirat <f@nuff.tech>
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-22 11:36:25 -07:00
Illia Polosukhin
c559a58810 feat(bridge): project 7 more engine events to AppEvents (#2844)
* feat(bridge): project 7 more engine events to AppEvents

Second slice of #2654 bridge-coverage under #2792 Phase 1. Builds on
#2797 (StepFailed, ChildCompleted, CodeExecutionFailed) by closing the
remaining cheap `EventKind` drops:

| `EventKind` | `AppEvent` |
|---|---|
| `LeaseGranted { lease_id, capability_name }` | new `LeaseGranted` |
| `LeaseRevoked { lease_id, reason }` | new `LeaseRevoked` |
| `LeaseExpired { lease_id }` | new `LeaseExpired` |
| `SelfImprovementStarted` | new `SelfImprovement { phase: Started, .. }` |
| `SelfImprovementComplete { prompt_updated, patterns_added }` | `SelfImprovement { phase: Complete, prompt_updated, patterns_added, .. }` |
| `SelfImprovementFailed { error }` | `SelfImprovement { phase: Failed, error, .. }` |
| `OrchestratorRollback { from, to, reason }` | new `OrchestratorRollback` |

The three engine `SelfImprovement*` variants collapse into one wire
event with a `SelfImprovementPhase` discriminator — consumers need one
handler, variant-specific data is conveyed via optional phase-scoped
fields. Following the types.md "Wire-stable enums" pattern — the phase
enum is snake_case serde, not a stringly-typed `status` field.

The lease events are security-visible: capability grants, revocations,
and expiries should be auditable on the UI stream. `LeaseExpired` in
particular closes a "tools start failing after TTL with no visible
reason" gap.

Also:

- Adds `impl fmt::Display for LeaseId` in the engine alongside the
  existing `ThreadId` / `ProjectId` impls. The bridge code stringifies
  `LeaseId` for the wire; missing `Display` blocked the first compile.
- Cleans up a stray doc-comment misplacement from #2797 where the
  `thread_event_to_app_events` docstring was attached to
  `code_execution_category_to_wire`.

Regression tests mirror the #2797 pattern — one per representative arm
(lease grant for the lease family, self-improvement complete for the
richest phase, orchestrator rollback). The two remaining lease
variants and two remaining self-improvement phases are covered by the
existing `event_type_matches_serde_type_field` drift-catch test.

Approval pair (`EventKind::ApprovalRequested` / `ApprovalReceived`) is
still deferred — they need to land together with the gate-manager
migration in Phase 1 PR 3 to avoid duplicate-emit with the direct
`GateRequired` / `GateResolved` broadcasts.

Refs: #2792, #2654

* refactor(bridge): typed SelfImprovementPhase + exhaustive match

Addresses two Gemini review comments on #2844.

**1. `SelfImprovementPhase` as a typed internally-tagged enum.**

Previously the `AppEvent::SelfImprovement` variant carried three
`Option<T>` fields (`prompt_updated`, `patterns_added`, `error`), only
some of which were populated per phase. Per `.claude/rules/types.md` —
and the reviewer's note — this is an `Option`-that-can-lie pattern the
type system should rule out. Phase-specific data now lives on the
variant:

```rust
enum SelfImprovementPhase {
    Started,
    Complete { prompt_updated: bool, patterns_added: usize },
    Failed { error: String },
}
```

Wire shape is preserved via `#[serde(tag = "phase")]` on the enum and
`#[serde(flatten)]` on the `AppEvent::SelfImprovement.phase` field —
JSON still looks like a flat object:
`{"type": "self_improvement", "phase": "complete", "prompt_updated": true, ...}`.

**2. Exhaustive `thread_event_to_app_events` match.**

Dropped the `_ => vec![]` wildcard in favour of explicit arms for
every `EventKind` variant. Deferred-bridge variants get `vec![]` with
a comment naming the migration plan:

- `ApprovalRequested` / `ApprovalReceived` → waiting on the gate
  manager migration in #2792 Phase 1 PR 3 to avoid duplicate-emit with
  the existing direct `GateRequired` / `GateResolved` broadcasts.
- `Unknown` → forward-compat catch-all in the engine enum; nothing
  useful to project from a variant written by a newer binary during a
  rolling deploy.

New engine variants now fail the bridge to compile, which is exactly
what the state-convergence epic (#2792) needs — no more silent drops.

Refs: #2792, #2844 review

* fix(bridge): sanitize OrchestratorRollback.reason before SSE projection

`EventKind::OrchestratorRollback.reason` originates from
`format!("execution failed: {e}")` in
`crates/ironclaw_engine/src/executor/loop_engine.rs:327`, where
`e: EngineError`. Variants like `Store { reason }` and
`Llm { reason }` render DB connection strings, file paths, and raw
upstream HTTP bodies — all of which reached every authenticated SSE
consumer verbatim through the new `AppEvent::OrchestratorRollback`
projection.

Route the reason through a new `user_facing_rollback_reason`
classifier that maps the existing `FailureCategory` taxonomy to
short operator-facing messages (`"LLM provider unavailable"`,
`"execution failed"`, etc.). The raw text still lives in the
`debug!` log for operator triage, matching the pattern already
used for `AppEvent::Error`.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* chore(deny): ignore RUSTSEC-2026-0104 (rustls-webpki CRL panic)

Same transitive pin as 0049/0098/0099 — rustls-webpki 0.102.8 is
held by libsql 0.6.0 → rustls 0.22 → hyper-rustls 0.25. The
advisory explicitly notes that applications not parsing CRLs are
unaffected; we do not parse CRLs.

[skip-regression-check] — deny.toml-only config change.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* test(bridge): cover 4 new engine→AppEvent arms; sharpen rollback test

Review follow-ups on PR #2844:

- Add unit tests for `LeaseRevoked`, `LeaseExpired`,
  `SelfImprovementStarted`, and `SelfImprovementFailed` bridge arms
  — only `LeaseGranted` / `SelfImprovementComplete` /
  `OrchestratorRollback` had coverage before, leaving four new
  projections untested.
- Rewrite `rollback_reason_drops_engine_error_detail` to drive the
  sanitiser with two unrelated leaky inputs and assert identical
  outputs (`execution failed`). The load-bearing check is
  input-independence; `!contains` probes remain as sentinel sniffs
  for the specific leak shapes. Avoids classifier-triggering tokens
  (no `upstream`, no `http 5xx`) so both inputs fall through to
  `Unknown`.
- Reword the `ApprovalRequested` / `ApprovalReceived` comment: they
  are temporarily suppressed pending the gate-manager migration, not
  permanently dropped. The bridge will eventually map them here.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-23 00:38:01 +09:00
Henry Park
9d651ea366 engine-v2: add canonical capability status vocabulary (#2825)
* Add canonical engine capability status enum

* refactor(engine): add hash support for capability status
2026-04-22 15:05:45 +03:00
Illia Polosukhin
e9bf77dcfc feat(bridge): project 3 dropped engine events to AppEvents (#2797)
* feat(bridge): project 3 dropped engine events to AppEvents

Closes the first 3 of ~9 coverage gaps in `thread_event_to_app_events`
(#2654) — the UI state convergence work tracked under #2792 (Phase 1).

Bridges:
- `EventKind::StepFailed` → `AppEvent::Error` (LLM / step failures were
  silently dropped; "Processing..." stuck with no explanation)
- `EventKind::ChildCompleted` → new `AppEvent::ChildThreadCompleted`
  (symmetric to existing `ChildThreadSpawned`; tree views couldn't mark
  child branches finished)
- `EventKind::CodeExecutionFailed` → new `AppEvent::CodeExecutionFailed`
  (CodeAct / Monty runtime failures never surfaced to the UI)

Scope kept deliberately narrow: the 3 variants with no duplicate-emit
risk. `ApprovalRequested` / `ApprovalReceived` are deferred to the PR
that adds the `projection-exempt` lint (Phase 1 PR 2), where the
existing direct emits from the gate manager can be audited in the
same change.

Regression tests mirror the existing
`thread_event_to_app_events_preserves_call_id_for_action_events`
pattern — one per new arm, asserting field mapping and `thread_id`
propagation.

Refs: #2792, #2654

* refactor(bridge): type CodeExecutionFailed.category as enum

Addresses a types.md regression in the previous commit. `category` was
stringified on the wire via the engine's `Display` impl, which violates
the "Fixed small sets → enum" rule and risks silent drift if the engine
enum adds a variant.

- Define `CodeExecutionFailureCategory` in `ironclaw_common::event` as a
  parallel Copy enum with matching `#[serde(rename_all = "snake_case")]`
  — same wire format, compile-time variant safety.
- Bridge the engine enum via an exhaustive match in
  `code_execution_category_to_wire`. Exhaustiveness is the point:
  adding a variant to the engine enum is now a compile error here,
  forcing the wire mirror to be kept in lockstep.
- Re-export `CodeExecutionFailureCategory` from the crate root and
  update the bridge test to assert against the typed variant rather
  than a string literal.

The `ironclaw_engine::CodeExecutionFailure` can't be imported directly
into `ironclaw_common` (dependency direction), so the parallel enum is
the cleanest option without a bigger crate restructure.

Refs: #2792
2026-04-22 16:49:55 +09:00
jinxin
d4d5263ea6 fix: model provider config hardening (#2572)
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-22 11:15:24 +08:00
Illia Polosukhin
4dea5dd5da fix: bug bash 4/16 triage — error boundary, TEE secrets, pairing, rehydration (#2753)
* fix: bug bash 4/16 triage — error boundary, TEE secrets, pairing, rehydration

Addresses six bug-bash tickets that cluster into five focused fixes.
Grouped into one commit because the changes are all small, independent,
and share the same release window — split per-file reviewability is
preserved by the touched-surface list below and each change carries a
regression test.

- #2540 — Orchestrator VM timeout is now configurable via
  `IRONCLAW_ORCHESTRATOR_MAX_DURATION_SECS` (30..=3600s, default 300s).
  Timeout, memory-limit, and Python-traceback errors map to user-safe
  messages instead of leaking the Monty interpreter's internal trace.

- #1994, #2546 — New `LlmError::BadGateway { provider, status,
  retry_after }` variant. Upstream 502/503/504 from `nearai_chat` now
  map here (body logged at debug, never carried on the error) and are
  retried by `RetryProvider` + counted transient by the circuit
  breaker. Root cause of #2546's raw-traceback leak was the response
  body being wrapped into `RequestFailed.reason` and nested three
  layers deep on the way out; that path is gone.

- #1537 — `AppBuilder::init_secrets` always installs a secrets store:
  persistent when the master key + DB handles resolve, ephemeral
  in-memory otherwise. This mirrors the ExtensionManager fallback so
  `WasmToolLoader` and `setup_wasm_channels` get a store on hosted TEE
  deployments where `SECRETS_MASTER_KEY` is absent, restoring the
  fail-closed credential-injection path instead of silently dropping
  into unauthenticated HTTP.

- #1839 — Slack `chat.postMessage` returns HTTP 200 on scope/token
  failures with `{"ok": false, "error": ...}` in the body. Response
  parsing was extracted into a testable `slack_post_message_result`
  helper that now surfaces the failure, and `send_pairing_reply` errors
  are logged with scope guidance (`chat:write`, `im:write`) instead of
  being swallowed by `let _ = ...`.

- #1993 — Chat rehydration's `reconcile_in_progress_with_turns` now
  requires BOTH a final response AND all recorded tool calls having
  `has_result && !has_error` before dropping the in-progress flag.
  Previously a 502 mid-turn would persist the agent's "Done!" claim
  while the tool call errored, and reopen showed fabricated success.
  The deeper fix (engine-v2 side-effect gate for the forward path at
  #2544 / #2541) is a follow-up.

Touched surfaces:
- channels-src/slack/src/lib.rs
- crates/ironclaw_engine/src/executor/orchestrator.rs
- src/app.rs
- src/channels/web/features/chat/mod.rs
- src/llm/{error,nearai_chat,retry,circuit_breaker}.rs

Regression tests:
- `orchestrator::tests::failure_reason_*` (4 cases covering timeout,
  memory limit, traceback strip, pass-through)
- `llm::retry::tests::test_is_retryable_classification` (BadGateway arm)
- `app::tests::ephemeral_secrets_store_is_constructible_and_usable`
- `slack::tests::slack_post_message_result_{accepts,rejects,empty}`
- `chat::tests::test_reconcile_retains_in_progress_when_tool_call_failed`

Out of scope / deferred:
- #2544, #2541 — engine-v2 hard side-effect gate (documented as
  aspirational in `.claude/rules/tool-evidence.md`; design belongs in
  its own PR).
- #2437 — closed upstream, no code change; see
  https://github.com/nearai/ironclaw/issues/2437#issuecomment-4282541384
- #2543 — likely fixed by #2515, needs retest on staging.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(tee): surface persistent-store failures and probe in doctor

Follow-up to the #1537 ephemeral-store fallback. The fallback alone
doesn't tell an operator *why* the persistent store is missing on a
hosted TEE — that was #1537's real ergonomic pain. Three diagnostic
improvements:

1. `install_ephemeral_secrets_store` now takes a `reason` tag and
   logs at `warn!` with the specific path (no master key / crypto
   failure / no DB handles / feature-flag mismatch / unexpected
   create_secrets_store None). Previously the install was silent at
   `debug!`, so operators had no signal the fallback had fired.

2. `ironclaw doctor`'s `check_secrets` now runs the same
   `SecretsConfig::resolve` path `AppBuilder::init_secrets` uses, then
   calls `create_secrets_store` to probe that the backing store is
   actually reachable. The old check only read
   `settings.secrets_master_key_source`, which misses the exact
   hosted-TEE failure mode: master key resolves to `Env`/`Keychain`
   but the DB handle isn't wired, so the store factory returns None
   and runtime silently falls back to ephemeral.

3. `src/db/CLAUDE.md` note claiming `LibSqlSecretsStore` is "not
   plumbed through the main startup path" was stale — the factory
   dispatches on `DatabaseHandles` (init_secrets path) and
   `DatabaseBackend` (CLI helper) and both wire libSQL. Note updated
   to reflect the actual wiring plus the #1537 ephemeral-fallback
   contract.

The two existing `check_secrets` unit tests asserted the old settings-
only behavior; rewritten as "does-not-panic" checks because the new
function reads real env and the outcome is test-host dependent (matches
the shape of `check_docker_daemon_does_not_panic`).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(llm,app): address PR #2753 review comments

Three fixes from Copilot + Gemini review on PR #2753:

1. **BadGateway retry_after no longer forces 60s sleeps.** Copilot
   flagged that `retry_after_header` was always `Some(parse_retry_after(...))`,
   and `parse_retry_after` returns a 60s default when the header is absent.
   That meant 502/503/504 responses without a Retry-After header would
   sleep ~60s between attempts instead of using exponential backoff
   (1s → 2s → 4s). Now the header is parsed only when present; absent
   header → `None` → `RetryProvider` falls through to
   `retry_backoff_delay`. Existing 429 rate-limit behavior is preserved
   (60s fallback kept explicit at the 429 call site).

2. **HTTP 500 is now mapped to BadGateway.** Gemini (security-medium)
   pointed out that upstream application errors frequently return 500
   with a Python traceback in the body, and my prior change only mapped
   502–504. 500 was falling through to `RequestFailed { reason: "HTTP
   500: <body>" }` — exactly the leak #2546 describes. Match broadened
   to `500..=599`; the `status` field still records the specific code
   for operators. Matches the intent documented in
   `.claude/rules/error-handling.md` ("raw HTTP 5xx → temporarily
   unavailable").

3. **Ephemeral secrets store now fails loud.** Copilot observed that
   `build_ephemeral_secrets_store` returning `None` + the fallback
   install silently dropping it left `self.secrets_store = None`
   possible, which would blow up much later in `init_extensions` with
   a less-actionable "secrets store not initialized" error. Changed
   to return `Result`; `install_ephemeral_secrets_store` propagates
   via `?` so startup aborts at the real root cause.

Regression tests:
- `llm::retry::tests::bad_gateway_without_retry_after_does_not_match_some_arm`
  (fix 1 — guards against the `Some(_)` match arm catching a None value)
- `llm::retry::tests::test_is_retryable_classification` gains a
  `BadGateway { status: 500, .. }` case (fix 2)
- `app::tests::ephemeral_secrets_store_is_constructible_and_usable`
  already exercised `.expect(...)` on the builder — now validates the
  `Result` contract (fix 3)

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(engine,gateway): typed orchestrator failure + preserve debug detail

Addresses the remaining PR #2753 review feedback (Copilot + serrrfirat):

- Introduce OrchestratorFailure / OrchestratorFailureKind typed enum in
  the engine's error module. Replaces the format!()-built `reason` that
  fed EngineError::Effect. Parse, start, resume, and NameLookup panic
  paths all route through the typed classifier — user-safe message via
  Display, raw detail preserved in `debug_detail`.

- EngineError gains an Orchestrator(OrchestratorFailure) variant and a
  debug_detail() accessor. ThreadOutcome::Failed carries the detail
  through to the channel edge.

- bridge/router.rs: new `gateway_debug_errors_enabled()` helper reads
  IRONCLAW_DEBUG_ERRORS and appends the preserved detail to the reply
  when on. Off by default — low-level detail still goes to tracing::debug.

- Tighten the orchestrator timeout substring match from the bare
  "duration" to "timed out" / "timeout" / "duration limit" /
  "max_duration" / "maximum duration" so unrelated runtime errors no
  longer get misclassified as time-budget exhaustion.

- doctor's check_secrets is now read-only: uses crate::secrets::
  resolve_master_key (env + keychain only) instead of the auto-
  persisting SecretsConfig::resolve. Missing key reports as Skip
  without mutating ~/.ironclaw/.env.

- Chat reload: turn_tool_calls_succeeded keys off the *trailing* tool
  call rather than every tool call in turn history, so a turn that
  errored once and recovered via a later successful retry no longer
  stays pinned to Processing forever.

Regression tests:
- failure_reason_does_not_treat_bare_duration_as_timeout
- failure_reason_strips_python_traceback asserts debug_detail retains raw trace
- test_reconcile_allows_recovery_from_earlier_tool_error

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(gateway): surface engine debug detail to Debug Inspector + logs

Replaces the IRONCLAW_DEBUG_ERRORS env-var gate with unconditional
visibility in the two places it actually belongs: the gateway's Debug
Inspector panel and debug text logs. The chat reply stays sanitized.

- Drop gateway_debug_errors_enabled() and the env-var-gated append in
  bridge_outcome_for_failed_thread. The flag was only there because the
  only delivery path was the chat reply, which can't carry raw detail.
- Extend AppEvent::Error with an optional debug_detail field. Serialized
  onto the SSE `error` event so any listener (Debug Inspector, future
  tooling) sees it.
- On ThreadOutcome::Failed, broadcast AppEvent::Error with
  {sanitized message, raw debug_detail, thread_id} so the inspector
  picks it up even though the chat reply is sanitized.
- debug-panel.js renders debug_detail underneath the sanitized message
  on the Activity tab so operators can triage without tailing logs.
- tracing::warn! on the failure path now includes debug_detail, which
  flows through log_layer into the gateway's log event stream.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(engine,gateway,doctor): PR #2753 follow-up review fixes

Addresses four Copilot comments on commits 3c08e0c3 / 042c2ee7:

- orchestrator.rs: OrchestratorFailureKind::Other no longer renders
  the raw err_msg in Display. Channel-edge surfaces that bypass
  `user_facing_thread_failure` (runtime/mission.rs builds
  `format!("Mission failed: {error}")` directly) would have leaked
  tracebacks / internal file paths via unclassified Monty errors.
  User-facing text is now a generic "internal orchestrator failure";
  the raw message is preserved on OrchestratorFailure::debug_detail
  as before. Dropped the now-unused `message` field on Other.
- bridge/router.rs: the failure-path `warn!` now logs only
  `debug_detail_bytes`, not the full detail. Full raw text is emitted
  at `debug!` level so higher-severity logs don't carry multi-KB
  tracebacks. Operators still see the complete detail in the Debug
  Inspector (via AppEvent::Error.debug_detail) or with
  `RUST_LOG=ironclaw::bridge::router=debug`.
- cli/doctor.rs: source_label had an unreachable KeySource::None
  arm. Since the key-present guard above already returned Skip,
  `source` is only ever Env or Keychain here — folded the match
  into the existing env-wins branch.

Regression test renamed: `failure_reason_hides_unknown_raw_message_from_user_text`
now asserts `Other`'s Display does not leak `NameError` while
debug_detail still preserves it.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(engine,gateway,doctor): PR #2753 follow-up round 2

Addresses serrrfirat's review on commit 82d06410 — four issues that
remained after the previous fix landed:

- router.rs: a failed engine v2 thread on the web flow used to
  broadcast both AppEvent::Error on SSE and BridgeOutcome::Respond.
  GatewayChannel::respond then re-broadcast the same sanitized text
  as a response frame, so the browser rendered the same failure twice.
  The helper now takes sse_will_deliver_to_user and returns NoResponse
  when the originating channel is the gateway, so the SSE error card
  is the single user-visible surface. Non-gateway channels (telegram,
  relay, cli) still get Respond(sanitized) for primary delivery.

- AppEvent::Error: debug_detail travelled on the default scoped SSE
  error event, where every authenticated consumer (chat UI, devtools,
  custom clients) sees it. Raw Monty tracebacks / upstream HTTP bodies
  must not cross that boundary. The field is removed from the wire
  payload; detail stays server-side via the existing tracing::debug!
  edge. The Debug Inspector now renders only the sanitized message.

- doctor.rs: check_secrets probed the runtime via
  db::create_secrets_store, which opens a fresh backend and runs
  migrations — side-effectful, and not the same path that failed on
  hosted-TEE in #1537. The probe now uses connect_without_migrations
  + secrets::create_secrets_store(crypto, &handles), exercising the
  exact DatabaseHandles→Option<Arc<SecretsStore>> dispatch that
  AppBuilder::init_secrets runs. No migrations fire.

- orchestrator.rs: the OrchestratorFailureKind::TimeLimit classifier
  caught any err_msg containing "timeout"/"timed out", so upstream
  LLM/network timeouts (Request timed out, Connection timed out) got
  mapped to TimeLimit and the user-facing message advised raising
  IRONCLAW_ORCHESTRATOR_MAX_DURATION_SECS — wrong remediation. The
  predicate set is narrowed to unmistakable Monty wall-clock markers
  (duration limit / max_duration / maximum duration / execution
  duration exceeded / orchestrator timed out). Upstream timeouts now
  fall through to Other.

Regression tests:
- failed_thread_outcome_is_no_response_when_sse_will_deliver locks
  in the single-surface contract for the gateway web flow.
- failure_reason_does_not_treat_upstream_timeout_as_time_limit asserts
  four upstream-timeout shapes classify as Other (not TimeLimit) and
  their user message does NOT advise the budget knob.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(engine,gateway,doctor): PR #2753 follow-up round 3

Addresses Copilot review comments on 8489a978 plus four review-derived
nits surfaced during triage:

- Update stale rehydration comment in `reconcile_in_progress_with_turns`
  to describe trailing-tool-call semantics (earlier failed attempts are
  allowed if a later retry succeeded) rather than the old "every recorded
  tool call completed successfully" wording.
- Update stale rustdoc on `check_secrets` to describe the read-only
  `resolve_master_key()` probe instead of the dropped `SecretsConfig::
  resolve` path that used to auto-generate keys.
- Export `GATEWAY_CHANNEL_NAME` from `channels::web` and reference it
  from both the `Channel::name()` impl and `bridge::router`, eliminating
  the duplicated string literal.
- Split `parse_retry_after` into two helpers. The existing
  `Option<&HeaderValue> -> Duration` stays for rate-limit callers
  (60s default on missing). New `parse_retry_after_value(&HeaderValue)
  -> Duration` is for 5xx paths that want to distinguish "absent" from
  "unparseable" so missing headers fall through to exponential backoff.
- Strengthen doctor secrets tests: add
  `check_secrets_reports_env_source_when_env_key_is_set` which, under
  ENV_MUTEX, sets SECRETS_MASTER_KEY and asserts the rendered message
  surfaces the env source label plus the settings-vs-runtime drift
  warning — pinning the exact #1537 hosted-TEE axis the prior
  "doesn't panic" test couldn't detect.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(doctor): allow await_holding_lock on env-guarded test

`check_secrets_reports_env_source_when_env_key_is_set` holds the
global `ENV_MUTEX` from `config::helpers::lock_env()` (a
`std::sync::Mutex`) across `check_secrets(..).await`, which the
`clippy::await_holding_lock` lint flags. The env vars the guard
protects (`SECRETS_MASTER_KEY`) must stay pinned through the await
because `check_secrets` reads them internally — dropping the guard
early would let a concurrent test race on the env var. Mirrors the
existing pattern in `bridge::auth_manager` (six existing sites).

Local `cargo clippy --lib` missed this; CI runs with `--tests`.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-22 02:27:56 +09:00
Illia Polosukhin
22fa85b670 feat(engine): add short title field to v2 threads for sidebar labels (#2776)
* feat(engine): add short title field to v2 threads for sidebar labels

`Thread.goal` is the execution prompt — a multi-paragraph meta-prompt
for missions, or the full first user message for gateway chats. Reusing
it as the sidebar label makes the conversation list expand to fit the
longest prompt in view.

Split the two concerns:

- `Thread.title: Option<String>` (with `#[serde(default)]`) for the
  compact human label; legacy rows without the field rehydrate cleanly
  as None.
- Threaded a `title` parameter through `ThreadManager::spawn_thread_with_history`
  and added a `spawn_thread_with_title` wrapper; title is applied before
  `save_thread` so the executor's in-memory copy observes it atomically.
- Mission-spawned threads pass `Some(mission.name)`; gateway conversation
  threads pass `Thread::derive_title_from_message(content)` (first
  non-empty line, trimmed, char-safe truncated to 60 with an ellipsis).
- `EngineThreadInfo` carries the new field; `chat_threads_handler` prefers
  it and falls back to a derived short label for pre-existing threads.
- Belt-and-braces CSS truncation on `.thread-label` so the sidebar can
  never bleed across the page even if a title somehow slips through long.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* refactor(engine): streaming title truncation + docstring/test-name fix

Addresses review feedback on PR #2776:

- Drop the unreachable `trimmed.is_empty()` guard — the `find`
  predicate already guarantees the line is non-empty after trim.
- Replace `trimmed.chars().count()` + re-iterate with a single
  streaming pass: take up to MAX_CHARS-1 chars, peek the rest,
  and append either the final char (no ellipsis, result is
  MAX_CHARS) or '…'. Avoids an O(n) scan on pathological
  single-line input.
- Correct the docstring to say "leading and trailing whitespace"
  so it matches `trim()`, which is the right behavior for a
  sidebar label.
- Rename `derive_title_trims_trailing_whitespace` to
  `derive_title_trims_whitespace` since the test input has
  whitespace on both ends.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* test(bridge): assert thread_to_info carries title and goal separately

Addresses self-review finding on PR #2776: the `EngineThreadInfo` wire
contract gained a `title` field but nothing in the Rust tree directly
exercised the DTO populator after upstream dropped the sidebar
engine-thread merging. Adds two small tests that build a `Thread` with
and without a title and assert `thread_to_info` passes both `title` and
`goal` through independently — so mission DTOs can render the short
label without reading the multi-paragraph meta-prompt.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(bridge): propagate title through EngineThreadInfo and archive roundtrip

Addresses two medium-severity review findings on PR #2776 (same class of
bug — a new `Thread.title` field was added without propagation to
satellite types, per `.claude/rules/review-discipline.md`):

1. `thread_to_info` now falls back to deriving a short label from
   `goal` when `title` is `None`. Without this, legacy engine threads
   persisted before the `title` field existed flow through to frontends
   (TUI, mission detail views) as `title = None`, and the frontend
   `threadTitle()` fallback chain in `history.js` renders a UUID
   prefix because `EngineThreadInfo` has no `turn_count`.

2. `ThreadArchiveSummary` now carries `title` (with `#[serde(default)]`
   for backwards compatibility, mirroring the `total_cost_usd`
   precedent at #2562). `compact_thread_summary` persists it,
   `thread_from_archive` reads it. `backfill_archived_threads` is a
   live consumer — without this, workspaces that only have archived
   summaries still rehydrate threads with no title.

Tests:
- `thread_to_info_derives_title_from_goal_when_absent`
- `thread_to_info_derives_from_first_line_of_long_goal`
- `archive_summary_preserves_title_through_round_trip`
- `archive_summary_handles_legacy_json_without_title_field`

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-22 02:06:29 +09:00
Illia Polosukhin
8fffa8797c fix(tests): close staging test backlog — full suite green (#2744)
* fix(tests): close the staging test backlog — rust suite green, e2e 14→4

A pass over staging turned up 12 rust test failures and 14 playwright
e2e failures + 1 fixture error. Most were wiring/invariant drift or
stale test expectations around engine v2. This patch cleans up the
ones with clear root causes.

Rust (12 → 0):
- `tools::builtin::skill_tools` (8 tests): ripped out hand-rolled ZIP
  byte blobs that were missing the EOCD record since the extractor
  switched to `zip::ZipArchive::new` in #2385. Tests now build through
  `zip::ZipWriter`, matching the production path. Drops the obsolete
  nested-path assertion whose assumption conflicts with intentional
  GitHub-archive root stripping.
- `extensions::manager::test_telegram_token_colon_preserved_in_validation_url`:
  `src/pairing/approval.rs::propagate_approval_restores_runtime_state_when_on_start_fails`
  was mutating the `IRONCLAW_TEST_TELEGRAM_API_BASE_URL` runtime-env
  overlay without holding `ENV_MUTEX`. Now acquires `lock_env()` so
  concurrent readers see a stable value.
- `bridge::router::handle_with_engine_persists_attachment_files_and_indexes_them`:
  two distinct `ENGINE_STATE_TEST_LOCK` statics (one in `test_support`,
  one in the sibling `tests` module) meant cross-module tests raced on
  the shared `ENGINE_STATE` `OnceLock`. Replaced the private duplicate
  with `use super::test_support::ENGINE_STATE_TEST_LOCK`.
- `e2e_attachments::engine_v2_channel_attachments_persist_for_telegram_and_whatsapp`:
  attachment persistence resolves paths through the cached
  `bootstrap::ironclaw_base_dir()`, not the test's tempdir CWD. Added
  `bridge::override_engine_project_root_for_test` and wired the test to
  use it.
- `telegram_auth_integration::test_group_message_emits_chat_type_metadata`:
  local fix — rebuild `channels-src/telegram` so the WASM picks up the
  April-17 `chat_type` emit from #2513. CI rebuilds the module per run,
  so no binary committed here.

Playwright (14 failed + 1 error → 4 failed + 1 error):
- `test_chat.py::test_gateway_attachment_flow_renders_thread_and_reaches_llm`
  and the unextractable variant: a legacy change listener on
  `#image-file-input` fired before the unified `handleAttachmentFiles`
  path, cleared `e.target.value`, and left the FileList empty by the
  time the unified handler ran. Removed the duplicate wiring in
  `crates/ironclaw_gateway/static/js/surfaces/chat.js`.
- `test_chat.py::test_slash_autocomplete_shows_commands_and_skills`:
  `SLASH_COMMANDS` never merged installed skills. Added
  `refreshSlashSkillEntries()` that fetches `/api/skills` on menu open
  and re-runs the filter once the skills land.
- `test_pending_user_messages.py::test_pending_message_survives_sse_reconnect`:
  the SSE open handler only reloads history when `disconnectMs >
  SSE_RELOAD_THRESHOLD_MS`; the test's instant reconnect skipped that.
  Ages `_sseDisconnectedAt` past threshold.
- `test_pending_user_messages.py::test_welcome_card_hidden_when_pending`:
  `_create_new_thread` returned `currentThreadId` before the new-thread
  API round-trip set it, so callers got the pre-click id and keyed
  `_pendingUserMessages` on the wrong thread. Now waits for the id to
  change.
- `TestV2EngineSkillInstallFlow` (7 → 2 failures):
  - Skill card template didn't render `usage_hint`, `has_requirements`,
    `has_scripts`, or `install_source_url`. Extended `renderSkillCard`
    in `surfaces/skills.js`.
  - The deny message `"Do not execute it; choose an alternative
    approach"` accidentally matched `user_signals_execution_intent`'s
    EXEC_PHRASES ("execute it"), re-arming `require_action_attempt` on
    resume and nudging the LLM into another tool call. Rephrased to
    `"Do not retry; choose a different approach"` in
    `src/bridge/router.rs`.

Partial progress (still failing, needs deeper engine-v2 work):
- `test_v2_engine_oauth_google::test_oauth_token_refresh_on_expiry`:
  added an `oauth:` block to the test's `google_drive` skill (which
  registers a refresh config via `credential_spec_to_oauth_refresh`)
  and aligned `GOOGLE_OAUTH_CLIENT_ID` with the mock proxy's expected
  `hosted-google-client-id`. Thread still hits the auth gate instead
  of refreshing — the pre-flight path isn't reaching
  `oauth_refresh_for_secret("google_drive_token")`; needs
  instrumentation on the engine-v2 gate pipeline.

Net: rust suite green, playwright 4 failures left (2 skill-install
approval-flow edge cases, 1 OAuth refresh, 1 REPL auth that flakes
only under full-suite load) + 1 restart-fixture health-check timeout
that flakes under 20-min suite pressure.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(tests): close the final 4 e2e failures + add copy-button coverage

Follow-up to the earlier staging test pass. Drives the remaining
playwright failures to green and adds the missing test for the
per-message Copy button.

New coverage:
- `test_chat.py::test_message_copy_button_writes_raw_text`: clicking
  the per-message Copy button writes the raw text (user turn) or the
  raw markdown (assistant, via `data-raw`) to navigator.clipboard and
  flashes the button label to "Copied!" then back to "Copy". The
  existing `test_copy_from_chat_forces_plain_text` only covered the
  Cmd+C selection handler, so a regression to the button path was
  invisible.

Fixes:

- `TestV2EngineSkillInstallFlow::test_implicit_skill_activation_works_immediately_after_install`:
  the pika skill manifest uses the legacy `metadata.openclaw.requires`
  shape without a top-level `activation:` block, so `score_skill`
  scored 0 for every prompt and the skill never activated unless the
  user typed `/pikastream-video-meeting`. "Please use
  pikastream-video-meeting to prepare this call" should activate just
  like the slash form. `score_skill` now treats the skill name (and
  the hyphen/underscore-normalized form) as an implicit keyword,
  gated at ≥4 chars so short generic names don't false-match.
  `test_installed_skill_does_not_overfire_on_unrelated_prompt` still
  passes — a grocery-list prompt doesn't accidentally trigger pika.

- `TestV2EngineSkillInstallFlow::test_duplicate_install_is_idempotent_and_keeps_single_card`:
  the test was waiting for an approval card on the second install,
  but `SkillInstallTool::requires_approval` short-circuits to
  `ApprovalRequirement::Never` when the skill is already loaded —
  asking the user to approve a guaranteed no-op is pure friction, and
  the test was asserting against that intentional behavior. Rewrote
  the test to skip the approval step and assert on the terminal
  message's idempotent "already installed / no install needed"
  wording, which matches the actual production output.

- Mock LLM: the pattern branch in `match_tool_call` was re-emitting a
  matching tool call on every LLM round because "last user content"
  doesn't change across turns, so the engine looped until it hit the
  multi-result summary path. Added a guard that falls through to the
  text-response path when the matching tool_name is already present
  in `recent_tool_results` — mirroring real LLM behavior.

- `test_v2_engine_oauth_google::test_oauth_token_refresh_on_expiry`:
  two compounding issues blocked the refresh path. (1) The mock
  `/oauth/refresh` handler validates `client_id == "hosted-google-
  client-id"`, but the fixture env set `test-google-client-id`.
  (2) Proxy URL points at `http://127.0.0.1:<port>` (the mock LLM)
  and the production SSRF guard blocks loopback by default; mock E2E
  tests opt in via `IRONCLAW_OAUTH_PROXY_ALLOW_LOOPBACK=1`. Also added
  an `oauth:` block to the test's `google_drive` skill so
  `credential_spec_to_oauth_refresh` registers a refresh config under
  `google_drive_token`. Finally, the refresh path needs a stored
  refresh token — paste-based auth (the earlier tests' fallback when
  no google-drive WASM binary is available) only persists the access
  token, so the test now skips in that configuration rather than
  asserting on a refresh that can't happen, matching the pattern
  already used by `test_oauth_redirect_flow`.

Remaining after this PR: `test_repl_http_auth_prompt_accepts_token_and_retries`
passes in isolation but flakes under full-suite load (the PTY REPL
sibling test is already `@pytest.mark.skip` for the same reason); and
`test_always_approve_survives_restart` which times out the `/api/health`
probe under full-suite pressure. Both are PTY / fixture-startup
concurrency issues, not product regressions.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(tests): close the last 2 e2e failures — full suite green (401 passed, 0 failed)

Root-causes the two tests left open after the previous commit. Both
were real bugs/config drift masquerading as flakiness.

- `test_repl_http_auth_prompt_accepts_token_and_retries`:
  `CLI_MODE` defaults to `tui` (the ratatui full-screen UI), which
  reads stdin keystroke-by-keystroke and renders into a framebuffer.
  The PTY-driven tests in this file send whole lines via
  `os.write(master_fd, b"prompt\n")` and match for specific text in
  the raw stream — under the default TUI that line-based send never
  reaches the agent, so the auth card never fires and `_read_repl_until`
  times out with only cursor-position escape sequences captured.
  Pinning `CLI_MODE=repl` on the fixture routes the test back onto
  the plain line-based REPL surface it's written against. Confirmed
  passing 5/5 in isolation and under full-suite load.

- `test_always_approve_survives_restart`: the fixture's ironclaw
  subprocess was dying at startup with
  `Channel webhook_server failed to start: Failed to bind to
  127.0.0.1:8080: Address already in use (os error 98)` — the
  fixture picked a free `GATEWAY_PORT` but left `HTTP_HOST`/
  `HTTP_PORT` unset, so the HTTP channel tried to claim the
  default port 8080 and collided with every other e2e server
  (and anything else on 8080). Every `/api/health` probe was
  hitting a dead process, which showed up as a 60 s timeout
  instead of a bind error because the subprocess's stderr was
  never drained — a full 64 KiB pipe buffer made the child
  block on its next write before it could even log the bind
  failure. Fix:
    - allocate a second free TCP port for `HTTP_PORT` (mirrors
      the sibling `v2_approval_server` fixture);
    - wire `stdout`/`stderr` through background drain tasks so
      `RUST_LOG=ironclaw=debug` output can't back-pressure the
      child into a startup hang;
    - surface the last 32 KiB of stderr in the timeout error so
      future regressions (panic, bind conflict) show up in the
      failure message instead of being silently swallowed.

Full-suite e2e: 401 passed, 8 skipped, 0 failed, 0 errored
(17:31). Rust unit + integration tests still green, clippy clean,
fmt clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(tests): address PR #2744 review + reconcile with staging

## Review feedback

- **Slash-skill cache spam (3× — Gemini + 2× Copilot):** the previous
  `refreshSlashSkillEntries()` re-fetched `/api/skills` on every
  keystroke in `filterSlashCommands`; the in-flight guard only
  suppressed concurrent duplicates. Added a 30 s TTL and an
  `invalidateSlashSkillCache()` hook that the install/remove flows in
  `surfaces/skills.js` call so the menu picks up install/remove
  changes immediately instead of waiting for the TTL.
- **Wrong module path in comment (Copilot):** `src/bridge/router.rs`
  comment referenced `llm::reasoning::user_signals_execution_intent`
  but `reasoning` isn't `pub` — the helper is re-exported as
  `crate::llm::user_signals_execution_intent`. Updated the comment to
  use the canonical path and cross-reference the defining file.
- **Misleading `#[tokio::test]` justification (Copilot):** prior
  comment said "single-threaded tokio and cannot deadlock" without
  pinning the runtime flavor. `#[tokio::test]` *does* default to the
  current-thread runtime in this crate, but spelling it out is safer
  against future defaults drifting. Pinned
  `#[tokio::test(flavor = "current_thread")]` explicitly and reworded
  the comment to name the runtime kind.
- **Drain tasks cancelled but not awaited (Copilot):** the restart
  fixture in `test_v2_engine_approval_flow.py` cancelled the
  stdout/stderr drainers on `stop()` without awaiting them, causing
  "Task was destroyed but it is pending!" warnings and, on
  stop→start cycles, zombie readers. Now cancels *and* `asyncio.gather
  (..., return_exceptions=True)` awaits them.

## Merge reconciliation with `origin/staging`

Staging merge introduced:

- A strict MIME allowlist on `/api/chat/send` attachments (#2332).
  `test_gateway_attachment_unextractable_file_uses_placeholder`
  previously relied on `application/octet-stream` reaching
  `document_extraction` and triggering the "[Failed to extract …]"
  placeholder; the new gateway-side allowlist rejects that MIME
  outright at the HTTP layer, so the test never exercised the fallback
  path. Updated the test to upload a corrupt PDF (`%PDF-1.4` magic +
  garbage body) which passes MIME + header checks but fails
  extraction — the exact scenario the placeholder was designed for.
- A conflict in `src/pairing/approval.rs` where staging added
  `#[ignore]` to the propagate-approval test (needs a pre-built
  telegram WASM binary) and this branch added
  `#[allow(clippy::await_holding_lock)]`. Merged both, plus pinned the
  explicit `current_thread` runtime flavor per review.

## Pre-existing failures left alone

`test_portfolio.py::test_portfolio_chat_keyword_triggers_skill` and
`test_portfolio_wallet_address_triggers_skill` both fail identically
against plain `origin/staging` (verified via `git stash` + checkout of
the staging versions of the test file and
`crates/ironclaw_engine/orchestrator/default.py`). Root cause is
unrelated to this PR — appears to be the mock LLM's portfolio
response text tripping the engine's tool-intent nudge path before
reaching the canned response the test asserts on. Out of scope here.

## Verification

- `cargo fmt`
- `cargo clippy --all --benches --tests --examples --all-features` — zero warnings
- `cargo test --lib` — 5329 passed, 7 ignored, 0 failed
- `pytest scenarios/test_chat.py scenarios/test_v2_engine_approval_flow.py scenarios/test_v2_engine_auth_flow.py::TestV2EngineSkillInstallFlow scenarios/test_v2_auth_oauth_matrix.py scenarios/test_pending_user_messages.py` — **58 passed, 1 skipped, 0 failed**

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(fmt): collapse override_engine_project_root call onto single line

rustfmt on staging collapses this call; my earlier `cargo fmt` ran before
the `project_root.clone()` edit landed so the local check missed it.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* Address PR #2744 review: startup-timeout leak + attachment test isolation

1. `test_v2_engine_approval_flow.py` — `start()` re-raised `TimeoutError`
   from `wait_for_ready` without tearing the subprocess down. Because
   `await start()` runs before the fixture's `try/finally`, a startup
   timeout would leak the child process and its bound ports into the
   rest of the test run. Snapshot the stderr tail before teardown,
   `await stop()` (which kills the proc and cancels/awaits the drain
   tasks), then re-raise with the captured tail.

2. `tests/e2e_attachments.rs` — the `engine_v2_project_root()` helper
   derived from `bootstrap::ironclaw_base_dir()` is a process-global
   `LazyLock` that resolves to `$HOME/.ironclaw` on dev machines and CI
   runners. Passing its parent as the engine's project_root meant this
   test was writing real attachment files into `~/.ironclaw/attachments`
   every time it ran. Allocate a per-test `tempfile::TempDir` instead
   and point `override_engine_project_root_for_test` at it — now writes
   are fully contained. The `engine_v2_attachment_root_lock` mutex stays
   (still required to serialize mutations of the process-global engine
   state across concurrent tests).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-21 22:46:43 +09:00
firat.sertgoz
edbf0eaaa1 fix(engine): stop failed missions from respawning (#2736) (#2760)
* fix(engine): stop failed missions from respawning (#2736)

* fix(engine): address henrypark133 review — allow failed mission resume (#2760)
2026-04-21 13:56:09 +03:00
ironclaw-ci[bot]
d546cf6121 chore: release (#2606)
* chore: release

* fix(release): bump ironclaw to v0.26.0

* docs(release): expand v0.26.0 changelog

---------

Co-authored-by: ironclaw-ci[bot] <266877842+ironclaw-ci[bot]@users.noreply.github.com>
Co-authored-by: Henry Park <henrypark133@gmail.com>
2026-04-20 22:02:12 -07:00
Henry Park
b6397603ac [codex] Fix windows clippy test gating and bump channel versions (#2773) 2026-04-20 20:08:50 -07:00
Henry Park
a4966c6694 [codex] Fix gateway slash autocomplete and attachment rendering (#2763)
* fix gateway slash autocomplete and attachment rendering

* fix(web): restore attachment uploads and binary fallback

* fix(web): preserve in-progress attachment turns on reload
2026-04-20 19:05:28 -07:00
firat.sertgoz
904e378677 fix(gateway): keep engine threads out of chat sidebar (#2751)
* fix(gateway): keep engine threads out of chat sidebar

* fix: address review findings (iteration 1)

* fix: address review findings (iteration 2)
2026-04-20 20:38:41 +02:00
firat.sertgoz
e35099de23 [codex] Support web document uploads (#2332)
* fix: support web document uploads

* fix(web): address zmanian review — MIME allowlist, rename ImageData, update spec (#2332)

- Add server-side MIME type allowlist in uploads_to_attachments() to reject
  unsafe file types (executables, scripts, HTML). Accepts: image/*, audio/*,
  PDF, plain text, CSV, Markdown, JSON, XML, RTF, and Office documents.
- Rename ImageData → AttachmentData since it now carries any file type.
- Update web channel CLAUDE.md spec: body limit is 16 MB (not 10 MB),
  document supported upload types and MIME rejection behavior.
- Clarify JS file size constants with comment explaining why two exist.
- Add regression tests for MIME allowlist (reject + accept paths).

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix(web): server-side magic-byte sniffing + fix JS file staging race (#2332)

Address henrypark133 review: MIME allowlist was validating the client-
supplied media_type field, not actual bytes. Add validate_content_matches_
claimed_type() that checks magic bytes for binary formats (PDF, PNG,
JPEG, GIF, WebP, ZIP/Office, OLE2/Office, RTF, MP3, OGG, WAV) and
UTF-8 validity for text/* claims. Called after base64 decode in
uploads_to_attachments().

Address gemini-code-assist review: handleAttachmentFiles() had a race
condition where stagedBytes/stagedCount were computed from stagedFiles,
but stagedFiles was only updated in the async FileReader.onload callback.
Rapid concurrent calls could bypass MAX_STAGED_FILES and
MAX_TOTAL_FILE_SIZE_BYTES limits. Fix by pushing a placeholder entry
to stagedFiles synchronously (with loading:true), then filling in
data/dataUrl in the callback. Send path blocks while files are loading.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix(web): address zmanian review — harden upload MIME validation (#2332)

* fix(web): correct upload test payloads, tighten ADTS, clear clippy warnings

- Integration tests: use `mime_type`/`data_base64` to match `AttachmentData`
  wire shape so both caller-level tests exercise the validation path they
  claim to (previously failed with 422 before reaching the handler).
- Tighten `audio/aac` magic-byte check with mask 0xF6 so MP3 frames
  mis-declared as AAC are rejected; accept ADIF as fallback.
- Refactor `validate_content_matches_claimed_type` into match-with-guards,
  clearing 13 new `clippy::collapsible_match` warnings.
- Add `debug_assert!` guard where allow-list and extension map must stay
  in sync; fallback stays for defence-in-depth.
- Regression tests: PDF-body mismatch, MP3-spoofed-as-AAC, valid ADTS AAC.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Co-authored-by: Illia Polosukhin <ilblackdragon@gmail.com>
2026-04-21 02:58:29 +09:00
Coffee
ae9b179560 fix(channel): feishu pairing (#2454)
* Fix Feishu webhook auth refresh and extension card overflow

* Keep pending pairing approvals visible in active channel cards

* chore: fmt

* Fix WASM channel secret lookup owner context

* Make channel secret config injection manifest-driven

* Harden WASM secret config mappings and enforce owner scope

* Use owner scope for WASM channel webhook secret resolution

* Use owner scope for WASM channel credential injection

* Remove scope changes from Feishu secret mapping PR

* chore: fmt

* Centralize reserved WASM runtime config keys

* chore: fmt

* Address open review items on feishu-pairing PR

- Extract shared inject_wasm_channel_secret_config_mappings helper so
  startup, hot-activation, and refresh paths share identical behavior
  (env-var fallback + logging). Fixes drift flagged in review.
- Include 'ready' channel state alongside 'active' for the compact
  pending-pairing UI in the gateway.
- Add reserved-key coupling test so a new RUNTIME_CONFIG_KEY_*
  constant cannot be introduced without extending the reserved set.
- Restore OAuth nonce delete rationale after earlier reorder.
- Replace fully-qualified SecretConfigMappingSchema paths with module
  imports.
- Expand comment on validated_secret_config_mappings_with_warnings
  side-effect call.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Illia Polosukhin <ilblackdragon@gmail.com>
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-21 02:38:32 +09:00
Nige
392a33a478 feat(tui): support multiline message drafting (#2462)
Co-authored-by: Guille <gagdiez.c@gmail.com>
2026-04-21 00:45:44 +09:00
jinxin
4577d0e82f fix(gateway): wire standalone missions tab (load, back, refresh) (#2745)
Three parallel wiring gaps in the engine v2 Missions tab — each one was
code that only handled the Projects drill-in (cr-*) path and silently
no-op'd on the standalone tab, so the surface looked empty or frozen
even when the backend returned data:

- switchTab had no branch for 'missions', so opening the tab rendered
  the panel shell but never fetched data. /api/engine/missions returned
  rows; the table stayed empty.
- close-mission-detail only hid the cr-detail drawer, so the Back
  button on the standalone detail view did nothing.
- refreshMissionView refreshed the detail view or the project drill-in
  but not the Missions list, so fire/pause/resume actions succeeded but
  the list stayed stale.

[skip-regression-check]
2026-04-21 00:13:01 +09:00
Illia Polosukhin
c725366e70 docs(rules): add review-driven guidance for Claude Code (#2714)
* docs(rules): add review-driven guidance for Claude Code

Synthesizes recurring patterns from ~30 merged PRs, 147 bot review
comments (Copilot/Gemini), human reviews, and ~50 issues filed in the
past 2 weeks. Each rule cites the motivating PR/issue numbers.

New files:
- error-handling.md — silent-failure taxonomy (unwrap_or_default, .ok()?,
  poisoned caches), persist-then-reload atomicity, channel-edge error
  mapping. (#2526, #2633, #2653, #2673, #2546, #2407, #2408)
- agent-evidence.md — side-effect claims must cite tool evidence,
  empty-fast outputs are errors, external-effect tools must read back,
  setup UI round-trip. (#2544, #2580, #2582, #2541, #2545, #2411, #2543,
  #2586)
- lifecycle.md — discovery vs. activation, terminal auth rejection,
  list_installed vs. list_active, deactivation unwinds, snapshot
  rehydrate must re-validate. (#2556, #2557, #2558, #2564, #2419,
  PR #2617, PR #2631)

Extended:
- types.md — from_trusted boundary rule, validated-newtype template with
  shared validate(&str), serde(try_from) required for validated types,
  wire-stable enums (no Debug; serde alias for migrations), canonical
  wire-contract field naming. (PR #2685, #2681, #2687, #2678, #2669,
  #2665, #2683, #2702)
- safety-and-sandbox.md — every new ingress scans pre-transform/pre-
  injection, bounded resources (interners/streams/fan-out caps), cache
  keys must be complete. (#2491, #2676, #2470, #2633, #2673, #2710,
  PR #2702)
- review-discipline.md — PR scope discipline, guardrail scripts are
  code (regression tests, grouped-import parsing, CI has_code inclusion),
  absolute-path ban in committed docs, stale comments after refactors.
  (PR #2668, #2628, #2680, #2687, #2647, #2689, #2701)

All new files carry paths: frontmatter so they auto-load only on
matching files.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* refactor(rules): split agent-evidence into prompt + code rule

agent-evidence.md mixed two concerns: runtime agent instruction (what
the LLM should do when concluding a turn) and code-enforcement rules
(what the dispatcher, engine, and tools must implement). Rules under
.claude/rules/ only guide Claude Code when editing the repo — the
runtime agent never reads them.

Splits the two:

- crates/ironclaw_engine/prompts/codeact_postamble.md — new section
  "Evidence before claiming side effects". Sits next to the existing
  "FINAL() answer quality" guidance; loaded via include_str! in
  executor/prompt.rs (no Rust change needed).
- .claude/rules/tool-evidence.md — renamed from agent-evidence.md,
  keeps only the code invariants (engine v2 side-effect gate,
  empty-fast ToolError::EmptyResult, external-effect tools must read
  back, setup UI round-trip).

Prompt tests pass unchanged; the postamble addition is pure text.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* prompt: tighten evidence rule to FINAL() claims only, not tool use

Live-test validation of the "Evidence before claiming side effects"
section (added in the prior commit) showed it inhibited legitimate
tool use. With the original wording, `zizmor_scan_v2` live-recording
timed out at 302s with zero responses; reverting the postamble
restored healthy behavior (88s run, 8 shell calls including
`cargo install zizmor` and full workflow analysis).

The original phrasing conflated two things: what the agent should
claim and what tools it should call. The rule is only about the
claim. Re-tunes the section to:

- Open with an explicit "this does not restrict tool calls" scope.
- Drop the "<1ms = failure" heuristic (too broad — normal tools like
  `tool_info(schema)` are legitimately fast).
- Drop the full enumeration of forbidden side-effect verbs; keep the
  rule narrower and clearer.
- Shorten the code example (remove redundant early-return).

Re-tuned run: agent is active (shell calls, real reasoning), live
recording completes in ~9s. The remaining test failure is a
pre-existing assertion bug (exact `t == "shell"` match against tool
strings that now carry arguments like `"shell(cmd)"`) — reproduces
with the old postamble too.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* test(live): fix tool-name assertions + re-record zizmor traces

The two `zizmor_scan*` live tests had four broken tool-name assertions
that silently failed to match: `tools.iter().any(|t| t == "shell")`
against a tool list that now contains `"shell(cmd)"` strings (tool
events carry args via `format_action_display_name` in
`src/bridge/router.rs`). Two of the four were negative assertions
checking for the absence of `tool_install` recovery loops — those
silently passed even when a recovery loop actually ran. `sandbox_live_e2e.rs:203`
already used the correct `t == "shell" || t.starts_with("shell(")`
pattern; applied it consistently to all four sites.

Verified live:

- `IRONCLAW_LIVE_TEST=1 cargo test --test e2e_live -- zizmor_scan --ignored --test-threads=1`
  → 2 passed, 0 failed, 51.78s. Agent installs and runs zizmor
  end-to-end, producing real findings (exit code 14, dangerous
  triggers, excessive permissions, etc.).

Traces re-recorded with the tuned postamble (commit 50d85175) and
scrubbed: replaced `/home/illia/.cargo/bin/zizmor` with
`/home/user/.cargo/bin/zizmor` per the developer-local-path ban in
`.claude/rules/review-discipline.md`. No credentials, PII, or
high-entropy secrets in either trace (only git SHAs from zizmor's
workflow analysis output).

Replay still passes: `cargo test --test e2e_live -- zizmor_scan --ignored`
→ 2/2 ok.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* test(replay): update zizmor_scan_v2 insta snapshot

The engine v2 replay-snapshot gate (`engine_v2_tests::snapshot_zizmor_scan_v2`)
failed against the re-recorded trace from 1691efec because the old
snapshot encoded a broken run:

- final_state: Failed
- Missing Assistant message role
- 3 issues: thread_failure (error), no_response (warning), llm_error (error)
- 6 tool calls that never produced a final answer

The new trace completes cleanly:

- final_state: Done
- System / User / Assistant roles present
- 1 issue: mixed_mode (info)
- 3 shell tool calls + successful `FINAL()` with real findings

The snapshot was pinning a regression. Regenerated with
`INSTA_UPDATE=always cargo test --test e2e_engine_v2 -- snapshot_zizmor_scan_v2`;
passes on replay.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* docs(rules): address PR #2714 review feedback

- review-discipline: reword "Doc Absolute Paths" as a review convention
  (pre-commit only scans .rs; the rule misleadingly claimed enforcement).
- safety-and-sandbox: broaden `paths:` frontmatter to include the actual
  ingress owners (`bridge`, `channels`, `workspace`, `agent`, engine
  crate) so the rule auto-loads where it applies.
- tool-evidence: mark the side-effect gate, empty-fast rule, and
  `unverified` flag as target/aspirational invariants — neither
  `ToolError::EmptyResult`, an `unverified` field on `ToolOutput`, nor a
  byte-count field on `ActionRecord` exist today. Point at concrete
  interim conventions (`ToolError::ExecutionFailed`, `unverified: true`
  in the JSON result body).
- types: scope "Validated newtypes must gate Deserialize" to *new*
  types, document the `CredentialName`/`ExtensionName` exception (they
  intentionally use `#[serde(transparent)]` + derived `Deserialize`
  under the `serde_does_not_revalidate` test). Clarify the
  `from_trusted` trust boundary (trusted = typed upstream, untrusted =
  raw JSON field even if the field *name* is "registry entry").
  Switch `new` template to `impl Into<String>` to avoid an unnecessary
  clone when an owned `String` is passed.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* docs(rules): simplify types.md + split doc-hygiene; address review round 2

- types: collapse two templates into one canonical validated-newtype
  shape. New types use `#[serde(try_from = "String")]` with a shared
  `validate(&str)` helper — no more dual "transparent for some /
  try_from for others" guidance. `CredentialName`/`ExtensionName` are
  documented as the sole legacy exception (locked in by the
  `serde_does_not_revalidate` test); new code must not copy their
  `transparent` + `from_trusted` pattern. Removes the long "Using
  `from_trusted` safely" section and the separate "Validated newtypes
  must gate Deserialize" subsection that contradicted the Don'ts list.
- doc-hygiene: new tiny rule file scoped to `**/*.md`, `**/*.py`,
  `docs/**` that carries the "no developer-local absolute paths in
  committed docs" convention. Removed from review-discipline.md where
  its `src/**/*.rs` scope meant the rule never loaded on the files it
  governed.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* test(live): match hyphenated tool-install in attempted_relevant_tool

The engine records `action_name` as the raw string the LLM emitted
(`crates/ironclaw_engine/src/executor/structured.rs:381`), and the
registry's lookup canonicalization only affects dispatch — not the
name that reaches `StatusUpdate::ToolStarted`. The two other predicates
in this file (`bad_recovery` at :420, `phase_b_recovery` at :531)
already defend against both forms; this one should too, for
consistency. Addresses PR #2714 review.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-21 00:03:29 +09:00
Zaki Manian
5d99d55015 fix(gate): handle orphaned approval gates when thread deleted (#2347)
* fix(gate): handle orphaned approval gates when thread is deleted (#2323)

When a thread is deleted while an approval gate is pending, the gate
becomes orphaned -- unresolvable on backend and undismissable on
frontend. This fixes three root causes:

1. execute_pending_gate_action now detects missing threads and emits a
   gate_resolved event with resolution "expired" instead of erroring,
   so the frontend can dismiss the stale card.

2. PendingGateStore gains discard_for_thread() for bulk cleanup of all
   gates tied to a specific thread, regardless of user.

3. Frontend handleGateResolved now handles "expired" resolution to
   remove stale approval cards and re-enable chat input.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix(gate): split Ok(None)/Err(_) arms and wire discard_for_thread into production

Address review feedback on #2347:

1. Split the conflated `Ok(None) | Err(_)` match arm in
   `execute_pending_gate_action`: `Ok(None)` means the thread was
   genuinely deleted (emit "expired" gate resolution), while `Err(_)`
   indicates a transient DB failure (propagate the error so the caller
   can retry instead of permanently discarding the gate).

2. Wire `discard_for_thread()` into the conversation clear path
   (`clear_engine_conversation`), replacing the per-user `discard()`
   call. This ensures all pending gates for a thread are cleaned up
   regardless of which user created them, preventing orphaned gates.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix(gate): pre-flight thread check before persisting AlwaysAllow

Address review feedback on #2347:

1. **codex P2 — AlwaysAllow silent commit on thread-delete race.**
   When `resolve_gate` hit `Approved { always: true }`, it persisted
   `AlwaysAllow` to DB *before* calling `execute_pending_gate_action`.
   The rollback branch only fires on `result.is_err()`, but the
   thread-missing path now returns `Ok(BridgeOutcome::Respond(...))` for
   graceful `expired` UX — so the preference would stick even though the
   tool never ran. Added a pre-flight `load_thread` check in the
   `Approved` arm that short-circuits with `emit_gate_expired_dismissal`
   before any auto-approve / DB write occurs.

2. **Rebase onto staging (`scope_thread_id: Option<ExternalThreadId>`).**
   The PR predated #2561/#2473's identity-type tightening. The inline
   `pending.scope_thread_id.clone().or_else(|| Some(pending.thread_id.to_string()))`
   no longer type-checks against `Option<String>` on the wire field.
   Replaced with `Some(pending.effective_wire_thread_id())` — matches
   the five other `GateResolved` emit sites and satisfies the
   "don't re-derive identity values" invariant in
   `src/bridge/CLAUDE.md`.

3. **Extracted `emit_gate_expired_dismissal`** so the expired-SSE path
   is shared between the pre-flight check and
   `execute_pending_gate_action`'s `Ok(None)` arm. Documented the
   pre-flight contract on the helper itself.

4. **Regression test**
   `resolve_gate_approved_with_missing_thread_emits_expired_and_skips_persist`
   drives `resolve_gate` at the caller level with `Approved { always: true }`
   and no thread in the store. Asserts the first SSE event is `expired`
   (not `approved_always`), satisfying `.claude/rules/testing.md` →
   "Test Through the Caller, Not Just the Helper".

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Co-authored-by: Illia Polosukhin <ilblackdragon@gmail.com>
2026-04-20 23:55:31 +09:00
firat.sertgoz
ab38a0b234 feat(bridge): workspace-backed project registration + adapter improvements (#2533)
* feat(projects): workspace-backed project registration; migrate commitments into projects/commitments/

[cherry-pick-target: feat/projects-workspace-backed]

Replace the parallel `.system/engine/projects/*.json` schema with
workspace-backed project registration. Writing any file under
`projects/<slug>/` is now the declaration that the project exists —
the engine auto-registers it on `memory_write`, and `mission_create`
can reference it by slug. The model reasons about projects through
normal workspace APIs instead of a hidden sidecar schema.

Engine + bridge

- `ProjectId::from_slug(user_id, slug)` derives a stable v5 UUID;
  `Project::new` routes through it so constructing the same project
  twice returns the same ID (no duplicates).
- `slugify_simple` in `ironclaw_engine::types` — pure slug, no UUID
  suffix, reverses cleanly from a `projects/<slug>/` directory name.
- Project metadata moves from `.system/engine/projects/{slug}--{id8}/
  project.json` to user-facing `projects/<slug>/.project.json`.
  One-shot startup migration copies legacy files over, idempotent.
- `HybridStore::load_projects_from_workspace` scans `projects/*/` and
  synthesizes a stub `Project` for bare directories, so a write under
  `projects/foo/` surfaces immediately on restart.
- `EffectBridgeAdapter::ensure_project_for_memory_write` hook runs
  after a successful `memory_write`: if the target is under
  `projects/<slug>/...`, finds-or-creates the project and splices
  `project_id` into the tool output (enables
  `{{call-N.project_id}}` template refs).
- Extract `resolve_project_ref` helper from the inline block in
  `handle_mission_call` — now used by both `mission_create`'s
  `project_id` param and future project-aware tools.

Skills (13 files)

- Mechanical `commitments/` → `projects/commitments/` across the nine
  commitment-domain skills (commitment-setup, -triage, -digest,
  decision-capture, delegation-tracker, idea-parking,
  tech-debt-tracker, product-prioritization, security-review).
- Four persona setup skills (ceo-setup, developer-setup,
  trader-setup, content-creator-setup) gain an explicit "declare the
  project" step (write `projects/commitments/AGENTS.md` with
  persona-specific operating principles) and pass
  `project_id: "commitments"` on every `mission_create`. Setup
  markers move to `projects/commitments/.<persona>-setup-complete`.
- `ceo-setup` gets a v0.4.0 rewrite that also installs two dashboard
  widgets under `projects/commitments/.system/widgets/`:
  `commitments-this-week` (overdue / due / completed counts) and
  `delegations-waiting` (delegation list with stale-at-2-days flag).
  Both poll `projects/commitments/widgets/state.json`, refreshed by
  the triage mission each run.

Tests

- Three new unit tests in `bridge::effect_adapter::tests`:
  `extract_project_slug_recognizes_project_paths`,
  `extract_project_slug_rejects_degenerate_targets`,
  `project_new_is_deterministic_from_user_and_slug`.
- Update `tests/e2e_live_personas.rs` path assertions
  (`workspace_paths`, `read_under`, `verify_setup_landed`,
  `DEV_SETUP_CHECKS` needles, two workflow turn messages) to the new
  `projects/commitments/` prefix.
- Add a diagnostic dump in `run_turn` when a persona workflow turn
  times out with no response, so live-test hangs surface the
  captured status events instead of an opaque panic.

No backcompat for the old flat `commitments/` layout — pre-production
deployment, nothing in the wild depends on it.

* fix: adapt cherry-picked project registration to staging API surface

Add missing struct fields (engine_store, skill_registry) and setter
methods to EffectBridgeAdapter, expose MissionManager::store() accessor,
add sync_v1_skill_to_store to skill_migration, and remove references
to fields/methods not yet on staging (Project::goals/metrics,
LiveTestHarnessBuilder::with_skills_dir, V2SkillMetadata::bundle_path).

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix(bridge): address review — drop slug-prefix fallback, harden tests (#2533)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix(bridge): address PR #2533 review — slug-consistency, migration hardening, caller-level tests

- synth_bare_project now normalizes the raw dir name via slugify_simple
  before ProjectId::from_slug, matching Project::new. Returns Option so
  unsluggable dirs (`---`, `!!!`) don't produce phantom projects.
- migrate_legacy_project_jsons upgraded to warn! and moves unparseable
  legacy project.json aside as project.broken.json so the user can
  recover instead of the engine masking the loss on every boot.
- Document project_slug's engine-internal (mission-path, UUID-suffixed)
  scope vs project_dir's user-facing (no-UUID) scope so the two slug
  schemes aren't conflated in future edits.
- Drop unused ProjectId param from project_dir / project_path.
- Trim Project::new docstring per CLAUDE.md style.

Tests added (19):
- types::project: slug variant collapse, unicode, empty-slug stability,
  run/edge normalization
- store_adapter unit: project_slug_for_name contract, project_dir/path,
  synth_bare_project↔Project::new ID equivalence across 12 weird names,
  unsluggable-dir rejection, cross-user isolation
- store_adapter migration_tests (libsql): bare-dir load, metadata over
  synth, non-canonical skip, weird-slug collapse, user-edit preservation,
  broken-JSON move-aside
- effect_adapter caller-level: drives execute_action("memory_write")
  for canonical / idempotent / non-projects / nested / weird-slug /
  cross-user / pathological targets per .claude/rules/testing.md

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Illia Polosukhin <ilblackdragon@gmail.com>
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-20 23:23:15 +09:00
Illia Polosukhin
038853f8ee refactor(types): adopt MissionId in router + introduce McpServerName (#2681)
* refactor(types): adopt MissionId in router + introduce McpServerName

- src/bridge/router.rs response DTO now uses engine's MissionId(Uuid)
  instead of String
- McpServerName newtype in ironclaw_common encapsulates the allowlist
  validation added in #2400

Closes the type gap for two identifiers flagged in the recent
audit of string-typed values in the system.

* refactor(mcp): address review feedback — validate server names at construction

- McpClient::new and new_with_name: validate through McpServerName::new
  with a canonical "unknown" fallback + debug log, instead of
  from_trusted. Closes two HIGH-severity allowlist bypasses (e.g. IPv6
  bracketed hosts and caller-supplied bad names).
- McpClient:🆕 apply the same hyphen→underscore fold as the other
  constructors (only when a hyphen is present) for consistency.
- identity.rs: extract validate_mcp_server_name() helper so
  TryFrom<String> consumes the owned buffer without re-allocating;
  MAX_MCP_SERVER_NAME_LEN aliased to MAX_NAME_LEN to prevent drift.
- factory.rs: capture validated McpServerName and thread .as_str()
  through hottest downstream uses; TODO left for full threading.
- Adds regression tests covering the IPv6-host and invalid-caller-name
  paths against the caller (McpClient::new / new_with_name).

* fix(mcp): annotate panic-safe McpServerName::new("unknown") .expect() calls

The no-panics CI check flagged two `.expect()` calls on `McpServerName::new("unknown")`
fallbacks inside `McpClient::new` and `McpClient::new_with_name`. The literal
`"unknown"` always satisfies the alnum-only validation rule, so the call is
infallible. Document that with an inline `// safety: ...` comment per the
project's panic-check suppression convention.

* refactor(mcp): validate HttpMcpTransport::new server_name with safe fallback

* refactor(mcp): validate McpClient constructor server names with safe fallback

Address PR nearai/ironclaw#2681 Copilot review comments 3108427003,
3108427048, and 3108427073. The three remaining constructors
(`new_with_transport`, `new_with_config`, `new_authenticated`) were
wrapping caller-provided names with `McpServerName::from_trusted`,
allowing invalid values to enter the typed field.

Beyond bypassing the allowlist, the `_with_config` and `_authenticated`
paths also diverged from `HttpMcpTransport::new`, which independently
validates and falls back to `"unknown"` — so an invalid name could
leave the client keyed one way and the transport another, silently
breaking `Mcp-Session-Id` tracking.

Each constructor now runs the same canonicalize-with-fallback pattern
used by `McpClient::new`, `new_with_name`, and `HttpMcpTransport::new`,
and threads the single validated name into both the transport and the
client's typed field so the two cannot diverge.

Regression tests added (per .claude/rules/testing.md, "Test Through
the Caller"): invalid config/transport inputs fall back to "unknown";
valid inputs survive; client and transport names agree for both cases.

* fix(mcp): migrate legacy overlong server names at load instead of dropping

Address PR nearai/ironclaw#2681 review comment 3110617080. Before the
`McpServerName` newtype landed, `McpServerConfig::validate()` only
enforced non-empty + `[A-Za-z0-9_-]`. Delegating validation to
`McpServerName::new` added a 64-byte length cap — and `load_mcp_servers_from*`
silently dropped invalid configs via `retain(...)`, so a legacy persisted
server name >64 bytes would vanish from the loaded config on upgrade.

The load paths now in-place truncate overlong names at a char boundary
(safe even if the pre-validation string contains multi-byte UTF-8),
emit a `warn!` documenting the migration, and let the (now
cap-satisfying) entry pass validation. Invalid-char cases still drop
via `retain`, matching the pre-PR behavior for that class.

Regression tests cover both the happy path (ASCII overlong name kept,
truncated to exactly the cap) and char-boundary safety (multi-byte
sequence straddling byte 64 must not panic).
2026-04-20 23:05:38 +09:00
firat.sertgoz
c8f87537fc fix(gateway): remove v2 active-work pills from web ui (#2671) 2026-04-20 11:14:41 +02:00
firat.sertgoz
532e07fd07 fix: prevent immediate requests creating missions (#2328)
* fix: prevent immediate requests creating missions

* fix: address review findings (iteration 1)

* fix: use prefix stem matching for scheduling intent words

Addresses review feedback: "monitoring" now matches the "monitor" stem,
"routinely" matches "routin", etc. Replaces exact word matching with
starts_with prefix matching so morphological variants are caught without
maintaining an exhaustive word list. Adds regression test for
"set up monitoring now" being correctly allowed.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* style: fix cargo fmt alignment in SCHEDULE_STEMS

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix(bridge): add caller-level tests for immediate mission rejection (#2328)

Address henrypark133 review: the `should_reject_immediate_mission_create`
predicate was only covered by helper-level unit tests. Per the "Test
Through the Caller" rule, add three caller-level tests that drive
`EffectBridgeAdapter::execute_action` end-to-end:

- Reject path: foreground + immediate goal → EngineError::Effect
- Allow path: foreground + scheduling intent → mission created
- Alias path: routine_create → mission_create alias also rejected

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix(skills): remove useless .into_iter() flagged by clippy 1.95

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix(ci): resolve clippy 1.95 collapsible-match and useless-conversion lints

Collapse nested `if` into match arm guards per clippy::collapsible_match
(new in Rust 1.95). Replace `.sort_by(|a, b| b.1.cmp(&a.1))` with
`.sort_by_key(|x| Reverse(x.1))` per clippy::unnecessary_sort_by.

Affected crates: ironclaw (main), ironclaw_engine, ironclaw_tui,
ironclaw_skills.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix(test): add thread_goal to ThreadExecutionContext in gate integration test

The merge from staging introduced a new test that constructs
ThreadExecutionContext without the thread_goal field added by this PR.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix(ci): resolve clippy lint and 3 test failures

- Add #[allow(clippy::too_many_arguments)] on register_startup_channels
- Extract extension name from tool_install params in pending_gate_extension_name fallback
- Isolate re_resolve_llm tests from user config.toml via temp file
- Mark propagate_approval test #[ignore] (requires prebuilt telegram WASM)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Co-authored-by: Illia Polosukhin <ilblackdragon@gmail.com>
2026-04-20 15:58:12 +09:00
firat.sertgoz
862ac13a87 feat(memory): configurable insights interval, session summary hook, reasoning-augmented recall (#2336)
* feat(memory): configurable insights interval, session summary hook, reasoning-augmented recall

Three memory enrichment features:

1. Configurable conversation insights interval via MISSION_INSIGHTS_INTERVAL
   env var (default: 5, min: 1) with MissionsConfig + MissionSettings wiring
2. SessionSummaryHook that writes LLM-generated conversation summaries to
   workspace daily logs on session end (fail-open, 30s timeout)
3. Optional reasoning parameter on memory_search that synthesizes raw chunks
   via cheap LLM before returning, controlled by SEARCH_REASONING_ENABLED

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix(memory): address PR #2336 review feedback and CI failures

Critical fixes:
- Use DB-first config system for MissionsConfig instead of raw
  std::env::var in router.rs (issue #1)
- SessionSummaryHook now uses thread_ids from HookEvent::SessionEnd
  to summarize the correct conversation instead of guessing via
  recency; falls back to most-recent for backward compatibility (#2)
- Add per-user rate limiter (10/min, 60/hr) and 15s timeout on
  reasoning LLM calls in MemorySearchTool to prevent unbounded
  usage (#3)

Test coverage:
- Caller-level tests for reasoning-augmented recall (LLM wiring,
  disabled config, and failure fallback paths) (#4)
- SessionSummaryHook LLM failure path test confirming fail-open
  behavior (#5)
- reasoning_enabled config field tests (default, env, DB override) (#6)
- MissionSettings and SearchSettings round-trip assertions in
  comprehensive_db_map_round_trip (#11)

Convention fixes:
- Remove double env-var parsing in MissionsConfig::resolve (#7)
- Use ChatMessage::system()/user() constructors in
  SessionSummaryHook (#8)
- Add TODO comments for inline prompt strings (#9)
- Add timeout on reasoning LLM call (#10)

CI fixes:
- Remove 4 stale wasmtime advisory entries from deny.toml
- Add RUSTSEC-2026-0097 (rand 0.8.5) to advisory ignore list

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix(memory): address henrypark133 + ilblackdragon review — safety, concurrency, prompts (#2336)

- Move inline prompt templates to prompts/*.md per project convention
  (session_summary.md, memory_reasoning_synthesis.md) — resolves TODOs
- Add Arc<Semaphore> to SessionSummaryHook to cap concurrent LLM calls
  on mass session expiry (follows OutboundWebhookHook pattern)
- Sanitize LLM-generated summaries via ironclaw_safety::Sanitizer before
  writing to workspace (mitigates stored prompt injection vector)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix(memory): CI compile fix + reasoning sanitizer parity + harden test

- Add live_state / live_state_started_at fields to ConversationSummary
  literals in three session-summary test sites; staging added these
  fields after the branch was created and clippy/test builds were
  failing on missing-field errors.
- Replace silent unwrap_or_default on MissionsConfig::resolve in
  bridge::router::init_engine with an explicit warn-and-default match,
  so a misconfigured MISSION_INSIGHTS_INTERVAL surfaces in logs instead
  of being absorbed into the default.
- Run the reasoning-synthesis output through ironclaw_safety::Sanitizer
  before persisting it to the tool result, matching the parity already
  applied in SessionSummaryHook. Memory chunks fed into synthesis can
  carry attacker-controlled text and the synthesis flows back into
  future LLM contexts via memory_search results.
- Strengthen reasoning_enabled_fires_llm_and_returns_synthesis: add a
  preflight assertion that FTS returns the seeded doc, then
  unconditionally assert the LLM was called once and that synthesis
  matches the mocked response. Removes the prior `if llm.calls() > 0`
  guard that made the synthesis assertions vacuous when search returned
  empty.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
Co-authored-by: Illia Polosukhin <ilblackdragon@gmail.com>
2026-04-20 15:52:15 +09:00
Illia Polosukhin
833cb4844f refactor(channels): introduce ExternalThreadId newtype at channel boundary (#2685)
* refactor(channels): introduce ExternalThreadId newtype at channel boundary

External channel thread ids (Telegram chat id, web UUID, Slack thread_ts)
flow as raw Option<String> through IncomingMessage, StatusUpdate, and
pending-gate store. Wraps them in a validated ExternalThreadId so the
compiler distinguishes boundary-layer ids from the internal ThreadId(Uuid).

Maps to bug pattern from #2349, #2444, #2517 where thread-id confusion
crossed a layer silently.

* fix(bridge): adapt test thread_id to ExternalThreadId newtype

Post-merge fix: a test added in staging (insert_and_notify_pending_gate_uses_extension_manager_for_auth_display_name) assigned a raw String to message.thread_id, but the field type became ExternalThreadId on this branch. Wrap with ExternalThreadId::from_trusted to match the other tests in the same module.

* refactor(types): address review feedback — byte units, shared validate, try_-variants, dedup pending-gate

* refactor(types): validate scope_thread_id + relay respond prefers typed msg.thread_id

- router.rs: scope_thread_id written to PendingGate was wrapped via
  ExternalThreadId::from_trusted from message.conversation_scope(), which
  can carry untrusted WASM/metadata-sourced strings. Now validates via
  ExternalThreadId::new; invalid values log at debug and store None.
  Applied at both call sites (authentication-fallback path and generic
  gate-insertion path).
- relay/channel.rs: respond() derived thread_id only from response or
  metadata — now also consults the validated msg.thread_id as the second
  fallback (before raw metadata) and filters empty strings so we never
  emit thread_ts: "" to Slack.
2026-04-20 15:29:04 +09:00
Illia Polosukhin
0476a3d8e9 fix(gateway): Settings extension button label reflects auth state (#2235) (#2709)
* fix(gateway): label Settings extension button Setup vs Reconfigure by auth state

Closes nearai/ironclaw#2235. Extracted from #2375.

The Settings → Extensions card fallback branch unconditionally labeled
the action button "Reconfigure", so users opening the settings for a
chat-installed channel saw "Reconfigure" even though credentials had
never been entered — and clicking it opened the credential popup,
matching the QA repro on the 2026-04-09 bug bash.

Pick the label from `ext.authenticated`: "Setup" when no credentials
are on file, "Reconfigure" once they are. `setup_required` /
`installed` keep the legacy label because the inline setup form below
already provides the same action — preserves the no-duplicate-setup
invariant guarded by `test_wasm_channel_setup_states`.

Tests:
- `test_extensions_list_reports_authenticated_after_setup_submit`
  drives POST setup-submit → GET list and asserts `authenticated`
  flips on the wire (the field the JS branch reads).
- `test_settings_extensions_labels.py` (Playwright) covers both
  label states, the no-duplicate-setup invariant, and that clicking
  Reconfigure on an authenticated channel does not fire /activate.

Does not touch `classify_wasm_channel_activation` (keeps the
`has_paired` axis the #1921 truth-table tests guard) or introduce an
`owner_bound` wire field.

Co-Authored-By: Nige <G7CNF@users.noreply.github.com>
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(gateway): use ext.reconfigure i18n key consistently (PR #2709 review)

Address gemini-code-assist review on #2709: the `inlineSetupCoversIt`
branch was the sole remaining caller of `extensions.reconfigure`. All
other Reconfigure buttons in this file already use `ext.reconfigure`
(lines 177, 218, 354). Both keys resolve to the same string in en/ko/
zh-CN locales, so this is a no-op for users — it removes the odd key
out and aligns with the project's `extensions.*` → `ext.*` migration.

Declined the paired suggestion to swap `var` → `const`: the surrounding
wasm-channel branch consistently uses `var` (lines 309/311/317/325),
and partial modernization inside the same conditional is worse than
matching the existing style.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(gateway): drop 'installed' from inlineSetupCoversIt + fix Playwright mock (PR #2709 review)

Copilot review on #2709 flagged two real bugs:

1. `inlineSetupCoversIt` treated `fallbackStatus === 'installed'` as if
   an inline setup form was present, but the inline form only renders
   when effective status is `setup_required` (see `loadInlineChannelSetup`
   branch at line 380). A production `installed` wire shape
   (`activation_status='installed'`, `onboarding_state=null` —
   `derive_onboarding` only emits non-null for `Pairing`) therefore kept
   the `Reconfigure` label with no inline form, which is exactly the
   #2235 QA repro. Drop `installed` from the conditional.

2. `test_reconfigure_click_does_not_send_auth_event` mocked the
   setup-fetch with empty `secrets`/`fields`, which makes
   `showConfigureModal` short-circuit with a `noConfigNeeded` toast
   and never render `.configure-modal`. The wait-for would have timed
   out on first CI run. Return a non-empty `secrets` array so
   `renderConfigureModal` actually fires.

Also adds `test_fallback_button_says_setup_on_production_installed_wire_shape`
— pins the exact #2235 wire shape (activation_status='installed',
onboarding_state=null) so this class of bug has a named regression
test going forward.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* refactor: reuse `status` and drop redundant presence assert (PR #2709 review)

Copilot second-round review on #2709:

- extensions.js: `fallbackStatus` recomputed the expression already
  stored in `status` at line 309. Reuse `status` directly; drop the
  one-use `inlineSetupCoversIt` alias while we are here — the
  `status === 'setup_required'` branch is short enough to read inline.

- features/extensions/mod.rs: the `telegram.get("authenticated").is_some()`
  assertion is redundant with the preceding `assert_eq!(..., true)` —
  a missing field indexes to `Value::Null` and trips the equality check.
  Folded the "must stay on the wire" rationale into the equality
  assertion's message so the diagnostic still documents why the field
  matters.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Nige <G7CNF@users.noreply.github.com>
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-20 15:27:30 +09:00
Illia Polosukhin
77e746f683 feat(portfolio): complete tool, tests, widget, and share-gains flow (#2368)
* feat(portfolio): complete tool, tests, widget, and share-gains flow

Portfolio WASM tool with full pipeline:
- Indexer (fixture, dune, dune-replay backends)
- Analyzer (6 protocol classifiers, health extraction, stablecoin detection)
- Strategy filter (yield-floor, health-guard, LP impermanent-loss-watch)
- Intent builder (fixture + solver backends, bounded checks, leg bundling)
- Format (suggestion markdown, progress metric, widget state)

172 unit tests covering all modules including edge cases:
- filter.rs: 33 tests (yield floor, health guard, LP watch, helpers)
- bounded.rs: 16 tests (slippage, cost, chain allowlist, multi-leg)
- parser.rs: 18 tests (delimiters, YAML, kind inference, real strategies)
- fixture.rs: 14 tests (slippage calc, ID formats, payload structure)
- analyzer: 18 tests (stablecoin detection, health extraction, debt/yield)
- format.rs: 16 tests (totals, empty states, progress windowing)
- widget.rs: 10 tests (rendering, intents, non-ready filtering)
- types: 16 tests (parse_decimal, ChainSelector serde)
- 14 YAML replay scenarios + 4 live Dune API tests (ignored by default)

Share-gains feature:
- Gateway-level IronClaw.api.share() modal with X, LinkedIn, Facebook,
  copy-to-clipboard, and download buttons
- Portfolio widget generates SVG card showing gains (APY, annual savings,
  moves found) — no addresses or balances exposed
- "Share gains" button appears only when portfolio has positive delta

E2E Playwright tests (11 scenarios):
- Skill discovery via API and settings UI
- Chat integration (keyword + wallet address triggering)
- Widget rendering with pre-seeded state (positions, totals, suggestions)
- Share button visibility (present with gains, absent without)
- Share modal lifecycle (opens with card image, social buttons, closes)

Supporting changes:
- E2E conftest: SKILLS_DIR points to workspace skills/
- Mock LLM: canned responses for portfolio/defi and wallet address patterns
- Skill YAML, registry entry, capabilities JSON, 3 strategy docs, 4 scripts

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix(portfolio): address PR review — XSS, OnceLock, bounded checks, docs

Addresses review comments from #2368:

- XSS: widget renders all interpolated fields through escapeHtml();
  share modal creates <img> via DOM API with data:image/ prefix check
- OnceLock: protocol registry parsed once via std::sync::OnceLock
- to_ascii_lowercase() for wallet address lookups (fixture + dune_replay)
- bounded.rs: reject empty value_usd in single-leg slippage check
- fixture.rs: compute min_out amount and value_usd separately
- fixture.rs: clarify expires_at=0 comment (fixture = no expiry)
- schema.json: add "dune-replay" to source enum
- parser.rs: fix doc comment re kind inference (defaults, not inferred)
- live_tests.rs: fix log placeholder (raw_count vs classified.len())
- intent.rs: expand kind comment to match SCHEMA.md

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix(portfolio): escape remaining innerHTML fields, add tests, WASM build

- Escape delta_vs_last_run_usd and next_mission_run in widget innerHTML
- Add fixture test with amount != value_usd (stETH: 3.5 tokens / $12250)
  to verify the review fix separating amount from value_usd
- Add empty-legs test for bundling.rs order_legs
- Add comment explaining multi-leg empty value_usd tolerance in bounded.rs
- WASM component builds successfully (754K release binary)
  via: cargo component build --release --target wasm32-wasip2

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix(portfolio): address second-round PR review comments

- Tighten share image validation to data:image/png only (was data:image/*)
- Add ClipboardItem existence check to prevent runtime errors in some browsers
- Fix SCHEMA.md to correctly attribute invariant enforcement (bounded.rs vs bundling.rs)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* feat(portfolio): NEAR support end-to-end with engine v2 quality fixes

Add full NEAR Protocol support to the portfolio tool: scan via FastNEAR +
Intear, classify positions through new protocols (Linear, Meta Pool, Rhea
lending, Rhea LP), match against new NEAR-specific yield strategies, and
build intent bundles. Plus assorted infrastructure fixes uncovered while
exercising the v2 / CodeAct path.

Indexer
- New `near` source: FastNEAR `/v1/account/{id}/full` + Intear
  `/list-token-price` (235 KB, vs `/tokens` at 3.2 MB which exceeded fuel).
- New `near-replay` source for offline fixture replay.
- `auto` source dispatches per address: `0x...` → Dune, `*.near`/`*.tg` →
  NEAR backend. Mixed lists are split and merged.
- `classify_near_token()` tags known NEAR DeFi contracts (Linear, Meta
  Pool, Rhea/Burrow, Rhea/Ref) with proper `protocol_id`. Default for
  unknown FT contracts is `wallet`.
- Dust filter raised from \$0.01 → \$1 to keep wallets like `root.near`
  from passing 100+ micro-cap positions through the analyzer.
- Dune `value_usd` now accepts both string and number (Dune started
  returning floats).

Analyzer
- New protocols: `wallet`, `near-staking`, `linear`, `meta-pool`,
  `rhea-lending`, `rhea-lp`. Wallet positions are no longer silently
  dropped (the prior bug that made root.near show "meteor-private" only).

Strategies
- New `near-staking-yield`, `near-lending-yield`, `near-lp-yield` —
  match wallet/staking/LP positions on `chain == "near"`.
- `StrategyAppliesTo` gains `chains` and `tokens` filters.

Tool API
- `propose.strategies` is now optional → falls back to bundled defaults
  (3 EVM + 3 NEAR strategies).
- `propose.config` is now optional → falls back to `ProjectConfig::default()`.
- `build_intent.config` optional with default.
- `propose` recovers from stringified positions (common LLM mistake of
  calling `json.dumps()` first) and returns a clearer error message.
- Capability `dune_api_key` marked `optional: true` — NEAR-only and
  fixture flows no longer block on a missing Dune key.
- Default source is now `auto`.

WASM runtime
- Default fuel limit raised 10M → 500M across config, settings, channel
  runtime, and ResourceLimits. Production was using 10M (config path)
  while tests used `ResourceLimits::DEFAULT_FUEL_LIMIT` (was 100M) — the
  divergence masked the real fuel exhaustion. The 235 KB Intear parse
  uses ~27M fuel, so 500M provides ample headroom.
- Wrapper now logs fuel consumption at debug level for diagnostics.

Engine v2 / CodeAct UX
- Preamble: 3 new rules
  - Never reconstruct tool results manually — reference variables.
  - Never paste Python code outside `\`\`\`repl` or `FINAL(answer)`.
  - Chain tool calls in a single block.
  - Pass native Python objects to tools, never `json.dumps()` first.
- Postamble: explicit good/bad chaining example + `FINAL()` answer
  quality guidance (no terse counts).
- Orchestrator: when an action result exceeds 500 chars, the truncated
  preview now tells the LLM the full result is in `state['<tool>']`
  to discourage manual reconstruction.

Skill (`skills/portfolio/SKILL.md`)
- Step 4 (Propose): explicit anti-patterns for fabricated positions,
  strategy-name-only strings, and `floor_apy` percentage integers.
- Step 5 (Rank): allows informational LLM-only suggestions when
  `propose` returns no `ready` proposals.
- Step 6 (Build intents): explicit skip when no `ready` proposals;
  documents required `plan` shape (`legs`, `expected_out`,
  `expected_cost_usd`, `proposal_id`).
- Step 8 (Summarize): require detailed Markdown output, not counts.

Tests
- `tests/e2e_wasm_portfolio.rs` (5 tests): scan, propose, full pipeline
  via `TestRigBuilder` with canned HTTP — exercises real wasmtime sandbox
  with fuel metering.
- `tests/e2e_live_portfolio.rs` (2 tests, live-only via `IRONCLAW_LIVE_TEST=1`):
  end-to-end via `LiveTestHarness` against real LLM + real FastNEAR/Intear,
  with `engine_v2(true)`. Requires `--test-threads=1` due to a v2
  thread-registry race.
- Portfolio unit tests: 183 pass (added NEAR indexer parsers, dispatch
  auto-detection, new strategy filter cases).
- Live portfolio tests: 10 pass against real APIs.
- Updated `hostile/fake-token-dust` scenario for the new "wallet"
  protocol behaviour.

Bug fixes uncovered along the way
- `intents/bounded.rs`: epsilon raised to 0.005 to tolerate the 2-decimal
  truncation in `intents/fixture.rs` (intent bundles previously failed
  the slippage check on synthetic targets).

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix(portfolio): address review findings from #2368

Correctness:
- bounded.rs: multi-leg slippage now checks the terminal leg (matching
  plan.expected_out.chain), not just single-leg bundles. Regression
  tests added for the bypass and for a multi-leg bundle with min_out=0
  on the terminal leg.
- bounded.rs: reject zero/negative/NaN/infinite expected_out (would
  make min_required = 0 and every leg pass vacuously).
- indexer/mod.rs: is_near_address now validates NEAR account rules
  (2..64 chars, lowercase, separators). Previously any non-0x string
  (empty, whitespace, emoji, SQL injection) passed.
- indexer/mod.rs: scan_auto rejects addresses that are neither valid
  EVM nor valid NEAR, instead of silently routing them to Dune.

Code quality:
- bundling.rs: replace .expect("indegree") and .expect("leg by id")
  with explicit error returns.
- fixture.rs: replace .unwrap() on plan.legs.last() with an Err path.
- types/mod.rs: pub use → pub(crate) use (crate-internal only).
- dune.rs / near.rs: warn (via host::log at Warn level) when a
  non-zero amount has a missing/zero value_usd, so silent undercounts
  surface in diagnostics rather than being invisible.

Security:
- gateway config.js: hoist the data:image/png prefix check to the top
  of IronClaw.api.share() so both img.src and a.href are gated.
- gateway config.js: add noopener,noreferrer to window.open features
  on share popups to close reverse-tabnabbing surface.
- widget/index.js: extend escapeXml to also escape apostrophes.

Infrastructure:
- limits.rs: TODO comment noting that 500M fuel default is driven by
  one tool (portfolio/near) and follow-up should add a per-tool
  override so the global default can stay tighter.
- test_portfolio.py: silent-return on missing widget tab converted to
  pytest.skip via shared _open_portfolio_tab_or_skip helper, so a
  regression that removes widget registration fails loudly instead of
  passing silently.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(portfolio): address follow-up review comments

- lib.rs: BuildIntent.solver now defaults to "fixture" (a valid
  value), not "auto" (unrecognized by intents::build — was shipping
  the default straight into an "Unknown intent solver: 'auto'" error
  whenever the caller omitted the field).
- capabilities.json: update discovery_summary to reflect that
  strategies/config on propose and config/solver on build_intent are
  optional. Stale text had propose requiring both positions and
  strategies.
- limits.rs + config/wasm.rs: fix the fuel-limit doc comments. The
  prior value in limits.rs was 100M (not 10M — that was the config
  path). Clarify both paths converged at 500M in #2368.
- config.js (share modal): add aria-label, aria-modal, role=dialog,
  aria-labelledby for the modal and explicit aria-label on every
  icon-only share button. Mark decorative SVGs aria-hidden. Toast
  becomes role=status with aria-live=polite.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-20 14:47:51 +09:00
jinxin
d30c76de69 feat: add debug inspector panel for web gateway (#1873)
* feat(web): add debug inspector panel for web gateway chat UI (#1493)

Add a debug inspector sidebar with three tabs (Prompt, Activity, Stats)
activated via ?debug=true URL parameter. Consolidate theme-init.js into
a new init.js for early initialization. The panel shows real-time SSE
event timeline, system prompt component breakdown with token estimates,
and session-wide statistics including per-model usage.

- New files: init.js, debug-panel.js, debug-panel.css
- New endpoint: /api/debug/debug/prompt for system prompt inspection
- i18n support (en + zh-CN) for all debug panel strings
- Responsive layout: sidebar on desktop, overlay on tablet, hidden on mobile

* chore: minor

* feat(web): add debug inspection endpoints and verbose SSE mode (#1492)

Add per-subscriber verbose filtering to SSE, new AppEvent variants
(ToolResultFull, TurnMetrics), and enhanced debug prompt endpoint.
Debug subscribers (?debug=true) receive full tool output, per-LLM-call
metrics with model/duration/cache tokens, and tool parameters on
success. Non-debug subscribers see no change (backward compatible).

- New AppEvent variants: tool_result_full, turn_metrics with is_verbose_only()
- SseManager.subscribe()/subscribe_raw() accept verbose flag
- Emit TurnMetrics from dispatcher after each LLM call
- Emit ToolResultFull with 50KB cap after tool execution
- tool_completed() always includes redacted parameters
- /api/debug/prompt returns system_prompt, model, context_limit
- Frontend: turn-based activity tracking, turn navigation, message click
- Frontend: prompt tab with model name, progress bar, full prompt view
- Unit test for verbose SSE filtering

* fix(debug-panel): start turn counter at 0 so first message shows turn 1

* chore: minor

* chore: minor

* chore: fix lint

* fix(i18n): add Korean debug panel translations and fix hardcoded string

* fix(i18n): add Korean debug panel translations and fix hardcoded string

* fix: fix lint

* fix(web): propagate call_id to SSE events, gate debug mode on admin role, and skip verbose broadcasts without subscribers

- Add call_id field to AppEvent::ToolStarted/ToolCompleted/ToolResult and
  propagate from StatusUpdate conversion instead of silently dropping it,
  fixing mismatched tool start/complete pairs during concurrent same-name
  tool calls in the debug panel
- Update debug-panel.js to key pending tools by call_id (flat map) instead
  of FIFO name-based queues
- Skip ToolResultFull/TurnMetrics allocation and broadcast when no
  SSE/WebSocket subscribers are connected (SseManager::has_receivers)
- Require admin role for verbose/debug SSE and WebSocket event streams,
  matching the existing AdminUser gate on /api/debug/prompt
- Add audit log (tracing::debug) on debug prompt endpoint access

* fix(gateway): add admin gate to WS debug mode, add call_id to ToolResultFull, fix debug panel i18n

- Require admin role for WebSocket debug mode (server.rs), matching the
  existing SSE handler check — prevents non-admin users from receiving
  verbose tool output via ?debug=true
- Add call_id: Option<String> to StatusUpdate::ToolResultFull and
  AppEvent::ToolResultFull for correct concurrent same-name tool
  matching; update dispatcher, web gateway conversion, and debug-panel.js
- Remove dead chat_ws_handler from handlers/chat.rs (superseded by
  server.rs local version)
- Fix debug panel overlay blocking page on viewport resize by switching
  from inline style to CSS class toggle with transparent background
- Internationalize hardcoded English strings in debug panel (In/Out/
  Cost/Model/Cache labels) with en/ko/zh-CN translations
- Fix activity entries not updating on language switch: store labelKey,
  resolve during render without mutating entry, rebuild activity DOM
  in refreshDynamicI18n
- Fix pre-existing subscribe_raw() test compilation errors (missing
  verbose parameter)

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
Co-authored-by: Illia Polosukhin <ilblackdragon@gmail.com>
2026-04-20 13:02:37 +09:00
firat.sertgoz
141435eb0b feat(gateway): expose engine v2 threads in chat history and sidebar (#2532)
* feat(gateway): expose engine v2 threads in chat history and sidebar

Engine v2 threads weren't appearing in the gateway sidebar and
deep-linking to one by id (`#/chat/<engine-thread-id>`) returned an
empty history because the v1 `assistant` flow dual-writes into the
single assistant conversation id, not the engine thread id.

Three coordinated fixes:

- `chat_history_handler`: extend the ownership check with an engine v2
  lookup so an engine thread id is recognized, then fall back to
  loading messages via `bridge::get_engine_thread` when the v1
  conversation table has nothing.
- `chat_threads_handler`: merge engine threads from
  `bridge::list_engine_threads` into the sidebar, label them with
  their goal, and re-sort by `updated_at`. Bump the v1 conversation
  cap from 50 to 500 so older threads stop silently aging off the
  sidebar.
- Gateway frontend (`app.js`): when restoring from `#/chat/<id>` on
  load, switch even if the id is not in the loaded sidebar list — the
  history endpoint resolves it via the DB. Log a warning instead of
  silently dropping the URL.

Cherry-picked from 8df22ab2 (feat/skills-engine-fixes), adapted to
staging where chat_history_handler and chat_threads_handler still live
in both server.rs and handlers/chat.rs.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix(gateway): address v2 history review comments

* test(gateway): caller-level coverage for v2 thread ownership + history

Adds tests exercising chat_history_handler through the three ownership
branches the PR introduces, and two HTTP-driven e2e scenarios against
an ENGINE_V2=true server. Fills the caller-level coverage gap flagged
in review.

- Rust caller-level tests on chat_history_handler:
  - v2-owned: engine thread owned by user returns synthesized history
  - cross-user: alice can't read bob's engine thread (404)
  - session-only: in-memory session-owned thread returns 200 without DB
- Playwright e2e under ENGINE_V2=true:
  - engine-only thread appears in sidebar with channel=engine
  - deep-link by engine thread id returns synthesized turns

Exposes a minimal bridge::test_support module (ThreadTestStore,
install_engine_state_with_threads, clear_engine_state, shared test
lock) so cross-module tests can seed ENGINE_STATE without the weight
of the bridge's own full-featured TestStore.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(ci): align with staging EngineState fields and clippy rules

- `EngineState` on staging now has `extension_manager` and `project_root`
  fields (added in #2549 and the attachments flow). Update the test-only
  `install_engine_state_with_threads` helper to populate them.
- Rewrite the `let Some(...) else { return None }` in
  `engine_history_entry_to_message` as a `?` — clippy::question_mark is
  denied on staging's all-features CI.
- Add missing `AuthenticatedUser` + `Query` imports to the server.rs
  test module for the `history_request` helper.
- `cargo fmt` on the 500-error test.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Co-authored-by: Illia Polosukhin <ilblackdragon@gmail.com>
2026-04-20 12:57:27 +09:00
Illia Polosukhin
e88236ab08 refactor(events): replace JobResult.status String with JobResultStatus enum (#2678)
* refactor(events): replace JobResult.status String with JobResultStatus enum

Producers at 7 sites and consumers at 3 sites previously agreed by
convention only. Promotes the status field to a typed enum with
snake_case serde — wire format preserved.

Maps to bug pattern from #2570, #2531, #2517 where status transitions
drifted between producer and consumer.

Tests cover snake_case serialization, wire-format round-trip, and the
is_success() predicate used at consumer sites.

* refactor(events): add Stuck variant, accept "error" alias, case-insensitive parse

JobResultStatus now covers the full set of wire values producers emit:
- New `Stuck` variant for worker/job.rs `mark_stuck` path (was coerced
  to Failed + warn log, losing the distinction that job monitor and
  recovery logic care about).
- `FromStr` accepts `"error"` as a legacy alias for `Failed` so
  claude_bridge and acp_bridge wire payloads deserialize cleanly
  instead of hitting the default-on-unknown branch.
- `FromStr` trims whitespace and uses `eq_ignore_ascii_case`, so
  `"  COMPLETED  "` and `"Failed"` parse rather than falling back.
- Empty / whitespace-only input now returns `Err` (distinct from
  "unknown value") so callers can log it separately.

Producer migration: worker/job.rs emits `JobResultStatus::Stuck`
directly via `serde_json::json!` so the wire string stays pinned to
`as_str()`. claude_bridge and acp_bridge keep emitting `"error"` on
the wire; the FromStr alias covers them without churn on those call
sites.

Added unit tests for each variant, the `"error"` alias, case
insensitivity, whitespace trimming, empty-string error, and
preservation of the original input in `JobResultStatusParseError`.

---------

Co-authored-by: Henry Park <henrypark133@gmail.com>
2026-04-20 12:39:42 +09:00
Illia Polosukhin
fdaba100a6 feat(gateway): add attachment flows, v2 skill install coverage, and e2e stabilization (#2385)
* feat(gateway): add attachment flows and slash-skill coverage

* feat(v2): persist project attachments across channels

* feat(skills): install GitHub skill bundles

* feat(v2): cover live skill install and setup flow

* test(e2e): stabilize gateway and auth coverage

* test(e2e): stabilize post-merge warnings and browser flows

* fix(review): address follow-up PR feedback

* fix(review): address remaining attachment and skill install comments

* Address remaining attachment review comments

* fix(ci): allowlist ws.rs → server::inline_attachments_to_incoming

ws.rs was already allowlisted for the attachment shim symbols
(`images_to_attachments`, the rate limiter types, etc.) so the new
unified entrypoint added by this branch (combining images and
generic attachments before validation) follows the same pattern.
The entry will be removed together with the rest of the ws.rs
server:: block once the attachment helpers migrate into platform/.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(e2e): attachment persistence path and Slack activate signature

Two e2e-surfacing regressions after merging staging:

1. `persist_project_attachments` was writing to
   `<base_dir>/projects/.ironclaw/attachments/...` because PR #2385's
   reviewer-requested switch from `std::env::current_dir()` to an
   explicit `project_root` kept the `.ironclaw/` prefix baked into
   `PROJECT_ATTACHMENT_DIR` while rooting at `ironclaw_base_dir()/projects`.
   Point `resolve_project_root()` at the parent of the base dir so
   `<parent>/.ironclaw/attachments/<owner>/<project>/...` matches the
   prompt's `project_path` and the user's expectation when base dir is
   `~/.ironclaw`. Updates the corresponding assertion in
   test_v2_engine_auth_flow.py to resolve paths against the fixture's
   home tempdir instead of the repo root.

2. `activate_slack()` grew a required `http_url` arg during the
   skill-install branch work but the `active_slack` fixture in
   test_slack_e2e.py still passed the old three-arg shape. That tripped
   every Slack scenario at setup (TypeError). Thread `http_url` from
   `slack_e2e_server` through the fixture.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(engine-v2): auth-prompt surfacing, bundle_path injection, attachment-only inputs

- Orchestrator formatter now writes `Installed bundle path on disk:` into
  each skill block so the skill body sees the bundle location it needs to
  reference (e.g. running `pip install -r <bundle>/requirements.txt`).
  Previously the bundle_path metadata field was populated but never
  surfaced into the prompt, so skills that rely on filesystem paths
  silently no-op'd.
- The router no longer rejects messages whose text body is empty when
  the payload carries attachments. Safety validation's empty-input
  guard is a v1 input-sanity check; a pure-attachment follow-up (image
  upload with no caption) is a legitimate submission in the v2 gateway
  contract and previously tripped "Input cannot be empty".
- The engine auth-flow e2e tests now detect gate-paused state via
  `HistoryResponse.pending_gate` (and `resume_kind.Authentication`)
  rather than scanning the turn response text for "paste your token".
  Auth instructions live in the `onboarding_state` SSE event, not in
  the chat response (see `test_auth_no_duplicate_response.py`); the old
  string-matching assertion was checking the wrong surface.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(e2e): switch approval/auth-prompt probes to pending_gate

Approval and auth prompts are surfaced through HistoryResponse.pending_gate
and the onboarding_state/gate_required SSE events, not as text in
turns[-1].response — the duplicate-response regression guard in
test_auth_no_duplicate_response.py explicitly forbids them from appearing
in the chat transcript.

Update the helpers in test_v2_engine_approval_flow.py,
test_v2_engine_auth_cancel.py, and test_v2_kernel_auth_preflight.py to
poll pending_gate instead of scanning turn text for "requires approval"
or "paste your token". Unblocks 5 approval, 1 auth-cancel, and 3
preflight tests.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(e2e): google-oauth _wait_for_auth_prompt / _wait_for_response use pending_gate

Bring the Google Drive / skill-OAuth regression file in line with the rest
of the v2 e2e helpers: poll `HistoryResponse.pending_gate` for auth/approval
prompts, and accept a pending_gate as a valid terminal state for
`_wait_for_response` (an auth-retry chain that hits another gate is still
progress, not a hang).

Unblocks the oauth-cancel, invalid-token-paste, and api-key-then-api-call
scenarios; the lingering token-refresh scenario still exposes a real v2
auto-refresh regression (the engine prompts the user instead of issuing a
refresh against the stored refresh_token).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(e2e): relax a few stale v2-surface assertions

- `test_skill_oauth_flow::test_auth_required_sse_event` was pinned to the
  old `onboarding_state/auth_required` SSE payload. The v2 gate pipeline
  delivers credential gates as `gate_required` (resume_kind
  `Authentication`) or, when preflight falls through to approval first,
  `approval_needed`. Accept any of those three, and treat a `thinking`
  "Running <tool>" status as evidence the tool call fired when no
  standalone `tool_started` event is emitted.
- `test_message_persistence` helpers asserted HTTP 200 on `/api/chat/send`,
  but the gateway now returns 202 ACCEPTED (fire-and-forget). Accept both.
- `test_project_detail` flipped the wrong global (`engineV2`) instead of
  `engineV2Enabled`, leaving the `data-v2-only` Projects tab hidden so the
  click timed out. Set the real flag.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(review): address attachment index note correctness

Two Copilot review findings on the attachment persistence path:

- `attachment_index_note` in `src/bridge/router.rs` used the raw
  user-supplied filename in the markdown `# Uploaded attachment:` header
  and in the memory-doc `title` field. A filename with newlines /
  backticks / control characters would corrupt the agent-visible
  transcript and break searchable titles. Route the filename through a
  new `sanitize_filename_for_display` that strips control chars,
  collapses newlines/tabs to spaces, swaps backticks for apostrophes,
  truncates at 256 chars, and falls back to `"attachment"` when the
  sanitized result is empty.
- `persist_project_attachments` cleared `attachment.data` before
  calling `attachment_index_note`, so the `size_bytes.unwrap_or(
  data.len() as u64)` fallback reported `0` bytes whenever the channel
  hadn't pre-populated `size_bytes`. Swap the order — build the index
  note while the buffer is still populated, then drop the bytes.

Also adjust `src/agent/attachments.rs::format_attachment` for the
Image arm: when `data` has been cleared but `local_path` is set (the
engine-v2 persist-then-clear flow), the "visual content not available
in this conversation" message is misleading — the image is available,
just on disk. Surface a dedicated prompt that tells the agent to
reference the project file path instead of trying to load bytes from
memory.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(e2e): cancel_during_auth asserts pending_gate clears, not chat text

The test polled \`turns[-1].response\` for "cancel" but the cancel flow
never writes an assistant row to the chat-history DB: resolve_gate
returns \`BridgeOutcome::Respond("Cancelled.")\` which broadcasts via
SSE and calls \`stop_thread\` on the engine thread, neither of which
goes through the DB persistence path that populates turn responses.

Switch the test to verify the user-visible signal the gateway actually
emits — \`history.pending_gate\` disappears after "cancel" resolves the
gate. Matches the approach used in \`test_v2_engine_approval_flow.py\`'s
deny-flow tests.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(e2e): pairing approve test tolerates ExtensionName boundary reject

Staging's new `features/pairing/` slice (ironclaw#2599 stage 4b) validates
the `{channel}` URL segment through `ExtensionName::new` at the handler
boundary: a path-traversal / control-character / whitespace-containing
segment (like `evil.Ignore all`) now returns 400 instead of silently
routing to a pairing-store miss.

The regression test used to assert the older 200+JSON shape. Relax it
to accept either 200 (generic `Invalid or expired pairing code.`) or 400
(boundary validation); the real invariant the test exists to protect —
the raw injection-shaped channel string must not echo back into the
response — is still asserted.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(review): preserve image bytes through LLM call + document drive mock pin

Two review findings:

- `src/bridge/router.rs::persist_project_attachments` was clearing
  `attachment.data` after writing the file to disk. The very next step
  in `handle_with_engine_inner` is `augment_with_attachments`, which
  only emits a multimodal `image_parts` entry when `att.data` is
  non-empty — so every engine-v2 image upload was silently dropped
  from the LLM request even though the file landed on disk. The
  `persisted_attachments` Vec is local to the dispatch and is dropped
  as soon as the engine call returns, so the "storage hygiene" comment
  the clear used to justify was a no-op. Stop clearing; let RAII free
  the bytes. Updates `src/agent/attachments.rs`'s Image-arm prompt to
  reflect the refined invariant (`data.is_empty()` now implies a
  downstream caller or channel stripped the buffer, not the normal
  persist path).

- `tests/e2e/scenarios/test_v2_engine_oauth_google.py::_pin_mock_drive_api_url`
  posts to `/__mock/set_github_api_url`. The wire name is historical
  — the Drive suite reused the knob — but the fixture name made the
  intent hard to follow. Adds a docstring that calls out the shared
  `_github_api_url` in `mock_llm.py` and explains why the endpoint
  rename would cascade into every other test that uses it.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(review): address remaining Copilot feedback on PR 2385

- audio attachments: include `mime` (and size) attribute in `<attachment>`
  XML for parity with image/document so the frontend can render MIME and
  size in attachment cards
- /api/skills list/search: parallelize per-skill filesystem I/O
  (`read_install_metadata`, `try_exists`, `metadata`) via
  `futures::future::join_all` instead of awaiting serially — keeps the
  handler O(n) in wall time for large skill sets
- history parseUserMessageContent: only strip the trailing
  `<attachments>…</attachments>` block when at least one `<attachment>`
  tag is parsed from inside it, otherwise leave the raw text intact so
  user messages that legitimately end with that markup are preserved
- sync_v1_skill_to_store: look up existing shared skill doc via
  `list_skills_global()` instead of `list_shared_memory_docs(project_id)`
  so shared skills installed under one project are updated in place when
  re-synced from another project (prevents duplicate shared docs across
  per-user projects) and preserve the original `project_id` on in-place
  update

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-20 12:38:30 +09:00
Henry Park
64193474dd Preserve paused leases across engine auth resume (#2631)
* Preserve paused leases across engine auth resume

* fix(review): validate paused_lease snapshot at gate resume

Addresses PR #2631 review comments from Copilot:

1. **Snapshot used without validation** (src/bridge/router.rs:684 orig):
   `pending.paused_lease.clone()` was used directly to resume a gated
   action. A gate can sit in the pending-gate store for hours or across
   process restarts; during that window the original lease may have
   been revoked, expired, or the pending record could have drifted off
   its original thread.

   Extract `snapshot_lease_still_valid` + `resume_lease_for_pending_gate`
   helpers. The snapshot must pass four checks before use:
     - `lease.thread_id == pending.thread_id`
     - `granted_actions.covers(&pending.action_name)`
     - `!revoked`
     - `expires_at` is unset or in the future

   If any check fails, fall through to `LeaseManager::find_lease_for_action`
   (the normal path). Matches the reviewer's suggestion to avoid silently
   resuming a stale snapshot; still prefers the snapshot when valid so
   the original bug (no active lease at resume after restart) stays
   fixed.

2. **No router-level regression test** for the snapshot-vs-fallback
   decision. Six new libsql-free tests in `bridge::router::tests`:
     - `resume_lease_prefers_snapshot_even_when_lease_manager_empty` —
       reproduces the original bug; snapshot must carry the resume.
     - `resume_lease_rejects_revoked_snapshot_and_falls_back`
     - `resume_lease_rejects_expired_snapshot_and_falls_back`
     - `resume_lease_rejects_snapshot_with_wrong_thread_id`
     - `resume_lease_rejects_snapshot_missing_action_coverage`
     - `resume_lease_returns_none_when_no_snapshot_and_no_active_lease`

Verified: `cargo fmt`, `cargo clippy --all --benches --tests --examples
--all-features` (0 warnings), `cargo test -p ironclaw_engine` (435
passed), `cargo test -p ironclaw --lib` (5182 passed, +6 new).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* style: collapse assert!(matches!()) per rustc 1.95 rustfmt

CI rustfmt (nightly/stable 1.95.0) wants the `assert!(matches!())` in
`orchestrator.rs::parse_outcome_gate_paused` collapsed to fewer lines.
Local rustfmt 1.94 was happy with the expanded form; matching CI to
unblock the fmt check.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Illia Polosukhin <ilblackdragon@gmail.com>
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-20 01:45:49 +09:00
Illia Polosukhin
a35f9d9ab5 refactor(gateway): split monolithic style.css and app.js into per-surface modules (#2683)
The gateway's static frontend had grown into two merge-conflict hotspots: a
6 887-line `style.css` and an 11 189-line `app.js`, each a catch-all for every
surface of the SPA. Any two PRs touching different tabs were likely to collide.

This change splits both files by surface/concern while preserving bytes and
behavior. `STYLE_CSS` and `APP_JS` in `crates/ironclaw_gateway/src/assets.rs`
now `concat!(include_str!(...))` the split pieces at compile time, so the
served `/style.css` and `/app.js` URLs are unchanged and the existing
workspace-overlay (`custom.css`) path still works. Cuts land on function /
block boundaries; `node --check` validates the concat. Admin assets move
under `static/admin/` for symmetry. Per-commit safety + CI workflow validate
the split files per-file instead of the old monolith.

- Styles split into 20 files under `static/styles/{base,layout}.css +
  styles/{components,primitives,surfaces}/*.css`
- JS split into 24 files under `static/js/{core,surfaces}/*.js`
- No URL, CSP, or behavioural change — pure file-layout refactor

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-20 00:12:29 +09:00
firat.sertgoz
08693aa3cc feat(skills): activation feedback pipeline + install idempotence (#2530)
* feat(events): SkillActivated carries activation feedback notes

Add an optional `feedback: Vec<String>` field to the SkillActivated
event so the engine and selector can surface human-readable activation
notes (chain-load reasons, marker exclusions, scoring summaries) to the
UI. Wire the field through the StatusUpdate, the SSE bridge, and the
gateway's activity timeline; serialize-skip empty vectors so the wire
format stays backwards compatible.

* fix(skills): skill_install never prompts when skill is already loaded

When the LLM force-activates a persona via `/ceo-setup` it sometimes
follows up with a redundant `skill_install("ceo-setup")` call. The
`execute` path was already idempotent (returns `already_installed`
without touching the catalog), but `requires_approval` still gated
the call behind a confirmation prompt — pure friction on a guaranteed
no-op.

Mirror the idempotent shortcut in `requires_approval`: when a skill
with the requested name is already loaded (bundled, user, workspace,
or previously installed), return `ApprovalRequirement::Never`. The
shortcut wins even when `install_dependencies=true` because the
top-level execute is still a no-op (companions get reconciled by their
own activation paths). Regression test covers all three cases.

* fix(skills): preserve approval for dependency installs

* fix(events): include feedback in AppEvent::SkillActivated all-variants list

The variant-enumeration constructor in event.rs:501 was missed when
the new `feedback` field was added to AppEvent::SkillActivated, breaking
the build with E0063. All three Clippy CI jobs failed on this.

Regression: covered by `cargo build --all-features`, which fails to
compile if any variant in this list is constructed with missing fields.

* feat(skills): wire up v1 feedback producer for SkillActivated

The `SkillActivated` event carried an empty `feedback` field because
nothing populated it. This adds the producer end of the pipeline.

**Selector:**
- `prefilter_skills` now returns `SelectionOutcome { selected, notes }`.
- `try_select` returns a reason enum (`Selected`, `BudgetFull`,
  `CandidateLimit`, `MarkerSatisfied`, `AlreadySelected`) so callers
  can render distinct notes instead of opaque "skipped".
- Notes generated for:
  - `<companion>: chain-loaded from <parent>`
  - `<companion>: chain-load skipped (budget full)`
  - `<companion>: chain-load skipped (max active skills reached)`
  - `<companion>: chain-load skipped (setup already complete)`
  - `<skill>: skipped (skill context budget exhausted)` for parents
    that scored but didn't fit.

**Agent loop:**
- `select_active_skills` returns the notes alongside selected skills
  and prepends a `<skill>: force-activated via /mention` note for each
  explicit mention.

**Dispatcher:**
- Emits `StatusUpdate::SkillActivated { skill_names, feedback }` via
  `channels.send_status` whenever something activated or notes exist
  (so "nothing loaded because budget exhausted" surfaces too).
- Silent when nothing activated and no notes — no UI noise.

**Stale comment:**
- Router's v2-bridge comment no longer claims v1 callers populate
  feedback "directly on `StatusUpdate`"; the v1 dispatcher now emits
  its own event, and v2 remains empty until the Python orchestrator
  is updated.

Regression: existing selector test `test_chain_load_respects_budget`,
`test_chain_load_skips_companion_with_satisfied_marker`, and
`test_chain_load_is_non_transitive` now also assert that the
corresponding note is in `outcome.notes`. The 42 selector tests and
503 agent-module tests all pass.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Illia Polosukhin <ilblackdragon@gmail.com>
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-19 22:19:32 +09:00
Illia Polosukhin
43d6fc16b0 feat(engine-v2): Phase 4 cost tracking + Phase 6 mission lifecycle acceptance (#2660)
* feat(engine-v2): Phase 4 cost tracking + Phase 6 mission lifecycle acceptance

Closes two gaps blocking v2 engine becoming the default:

**Phase 4 — token + cost accounting**

- Delete orphaned `crates/ironclaw_engine/src/executor/compaction.rs`
  (176 lines). The Python orchestrator (`default.py::compact_if_needed`)
  has owned compaction policy since #1557; the Rust module had no
  callers anywhere in the workspace.
- Wire `cost_usd` in `LlmBridgeAdapter` by calling
  `LlmProvider::calculate_cost()` at both the no-tools and with-tools
  response paths. The engine's `Thread::total_cost_usd` accumulator and
  `max_budget_usd` gates were already plumbed — only the adapter was
  hardcoding 0.0.
- Persist `total_cost_usd` through `ThreadArchiveSummary` round-trip in
  `store_adapter.rs`. Previously, rehydrating an archived thread
  silently dropped the cost to 0.0. `#[serde(default)]` keeps existing
  archive files deserializing cleanly.

**Phase 6 — mission lifecycle acceptance**

Three new integration tests in `bridge/effect_adapter.rs` driving
`execute_action()` end-to-end (per `.claude/rules/testing.md` "Test
Through the Caller"):

- `mission_full_lifecycle_via_execute_action` — create → list → complete
  → list, asserting the `Completed` status surfaces through
  `mission_list` after `mission_complete`.
- `mission_fire_returns_thread_id_for_manual_cadence_via_execute_action`
  — fresh manual mission fires successfully and returns a UUID thread_id
  rather than `not_fired`.
- `mission_list_returns_all_user_missions_via_execute_action` — all
  three created missions appear in `mission_list` output.

**Regression tests for cost wiring**

Three new tests in `bridge/llm_adapter.rs`:

- `complete_no_tools_populates_cost_usd_through_adapter`
- `complete_with_tools_populates_cost_usd_through_adapter`
- `complete_routes_subcalls_through_cheap_provider_for_cost` — pins that
  `depth > 0` is priced with the cheap provider, not the primary.

Coordinated with in-flight work: skipped paths owned by #2504 (auth
E2E), #2631 (paused-lease resume), #2570 (mission re-fire), #2549
(mission_get), #2452 (tool_calls persistence), #2621 (replay snapshot).

Verified: `cargo fmt`, `cargo clippy --all --benches --tests --examples
--all-features` (0 warnings), `cargo test -p ironclaw_engine` (409
passed), `cargo test -p ironclaw --lib` (5079 passed).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat(engine-v2): surface engine capability actions to LLM via available_actions

Fixes the gap called out in the PR body: `EffectBridgeAdapter::available_actions`
was only enumerating v1 `ToolRegistry` tools + latent OAuth actions, so
engine-native capabilities like `missions` never appeared in the LLM's
tools list even when a thread held an active lease for them. The LLM
was therefore unable to call `mission_create` / `mission_list` / etc.
via structured tool calls; the only ways to drive missions were CodeAct
Python calls (which relied on the same `known_actions` set and hit the
same gap) or `/routine` slash commands falling through to v1.

Wire `CapabilityRegistry` into the adapter and iterate active leases to
surface every leased, engine-registered capability action. Respects
lease grant scope — a lease granting only `mission_list` does not leak
`mission_create`. Skips the `"tools"` capability since that lease is
already reconciled from the v1 path.

Router wires the shared `Arc<CapabilityRegistry>` to both the adapter
and `ThreadManager` at setup.

Three new regression tests:
- `available_actions_surfaces_leased_mission_capability`
- `available_actions_respects_partial_lease_grant`
- `available_actions_omits_capability_without_lease`

Verified: `cargo fmt`, `cargo clippy --all --benches --tests --examples
--all-features` (0 warnings), `cargo test -p ironclaw_engine` (409
passed), `cargo test -p ironclaw --lib` (5082 passed).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* test(engine-v2): close review gaps — archive round-trip, v1/engine merge, defensive filters

Addresses gaps raised in PR #2660 review:

- **Consolidate `use ironclaw_engine::{...}`** into a single grouped
  import in `effect_adapter.rs` (was split across two statements).

- **Apply `is_v1_only_tool` / `is_v1_auth_tool` filters** to the engine
  capability path in `available_actions`. Defensive guardrail: a future
  engine capability that registers an action under a v1-denylisted name
  (`create_job`, `tool_auth`, ...) must not bypass the v2-isolation
  filters by virtue of coming through a different capability registry.

- **`ThreadArchiveSummary` serialization round-trip tests** in
  `store_adapter.rs`:
    - `archive_summary_preserves_total_cost_usd_through_round_trip` —
      pins the regression the PR fixed (cost silently zeroed on
      rehydration).
    - `archive_summary_handles_legacy_json_without_total_cost_usd_field`
      — pins `#[serde(default)]` back-compat for archive files written
      before this PR.

- **`available_actions` combined advertising tests** in
  `effect_adapter.rs`:
    - `available_actions_merges_v1_tools_with_engine_capabilities` —
      v1 tool + mission capability both surface on one call.
    - `available_actions_filters_v1_denylisted_names_from_engine_capabilities`
      — pins the new defensive filter.

- **`cost_usd_from` subscription-billed-provider test** in
  `llm_adapter.rs`:
    - `complete_with_subscription_billed_provider_yields_zero_cost` —
      zero `cost_per_token` round-trips to exactly `0.0`, no NaN/Inf.

Verified: `cargo fmt`, `cargo clippy --all --benches --tests --examples
--all-features` (0 warnings), `cargo test -p ironclaw_engine` (409
passed), `cargo test -p ironclaw --lib` (5087 passed, +5 new).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(engine-v2): price cache tokens correctly in LlmBridgeAdapter

Addresses PR #2660 review (gemini-code-assist + Copilot, L23/L115/L189):
`cost_usd_from` only priced `input_tokens + output_tokens`, ignoring
`cache_read_input_tokens` and `cache_creation_input_tokens`. For
providers with prompt caching (Anthropic, OpenAI), this undercounted
input cost and silently neutered the `max_budget_usd` gate.

Extend the helper to mirror the canonical formula in
`src/agent/cost_guard.rs::CostGuard::record_llm_call`:

  uncached_input = input_tokens - (cache_read + cache_write)
  cache_read_cost  = input_rate * cache_read  / cache_read_discount()
  cache_write_cost = input_rate * cache_write * cache_write_multiplier()
  cost = input_rate * uncached_input
       + cache_read_cost
       + cache_write_cost
       + output_rate * output_tokens

All `LlmProvider` implementations already supply `cache_read_discount()`
(default 1, Anthropic 10, OpenAI 2) and `cache_write_multiplier()`
(default 1, Anthropic 1.25 for 5m / 2.0 for 1h) through the decorator
chain, so no trait surgery is required.

Regression test: `complete_prices_cache_tokens_with_discount_and_multiplier`
uses Anthropic Sonnet 5m-TTL rates, exercises a 10k-input / 2k-read /
1k-write / 500-output response, and pins the correct total ($0.03285)
against the old naive $0.0375 that would have undercounted ~14%.

Verified: `cargo fmt`, `cargo clippy --all --benches --tests --examples
--all-features` (0 warnings), `cargo test -p ironclaw_engine` (435
passed), `cargo test -p ironclaw --lib` (5136 passed).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-19 21:25:12 +09:00
Illia Polosukhin
0af0267125 feat(engine-v2): per-project sandbox (Phases 1–7) (#2211)
* feat(engine-v2): mount-backend abstraction for per-project sandbox (Phase 1)

Adds the engine-side `MountBackend` trait + minimal `WorkspaceMounts` registry
and a host-side bridge interceptor that routes sandbox-eligible tool calls
(`file_read`, `file_write`, `list_dir`, `apply_patch`, `shell`) through a
backend when their path argument starts with `/project/`. Default behavior is
unchanged: until `EffectBridgeAdapter::set_workspace_mounts(Some(...))` is
called (Phase 6), the interception path is dormant.

This is the first phase of the per-project sandbox plan
(`docs/plans/2026-04-10-engine-v2-sandbox.md`) and a deliberately small subset
of the unified Workspace VFS proposed in nearai/ironclaw#1894 — just enough
abstraction so the sandbox can be a `MountBackend` rather than a special case
in the bridge. When #1894's full mount table lands, the sandbox backend slots
in unchanged.

Engine crate (`crates/ironclaw_engine/src/workspace/`):
- `mount.rs` — `MountBackend` trait, `MountError` (NotFound / InvalidPath /
  PermissionDenied / Io / Tool / Backend / Unsupported), `DirEntry`,
  `EntryKind`, `ShellOutput`
- `filesystem.rs` — `FilesystemBackend`: passthrough host-fs implementation
  with two-layer path validation (lexical reject of absolute / `..`, then
  symlink-escape canonicalization). `read`/`write`/`list` fully implemented;
  `patch`/`shell` return `Unsupported` so the bridge falls through to the
  host tool until Phase 5
- `registry.rs` — `WorkspaceMounts` per-project registry with lazy
  `ProjectMountFactory`, longest-prefix-match resolution, cached and
  invalidatable

Bridge (`src/bridge/sandbox/`):
- `intercept.rs` — `maybe_intercept` and `SANDBOX_TOOL_NAMES`. Returns
  `Handled(json)` on a successful backend dispatch, `FellThrough` for
  non-sandbox tools, host paths, missing path params, or `Unsupported`
  backend ops
- `effect_adapter.rs` — `workspace_mounts` field + `set_workspace_mounts`
  setter; interception block in `execute_action_internal` right before
  `execute_tool_with_safety`, gated on the optional mount table

Tests (31 new):
- 17 engine workspace unit tests covering trait error mapping, path safety
  (lexical + symlink), longest-prefix routing, and lazy factory caching
- 9 bridge sandbox unit tests including `intercept_actually_dispatches_into_backend`
  (counting backend) which proves the interceptor reaches the backend
- 5 integration tests in `tests/engine_v2_sandbox_integration.rs` driving
  `EffectBridgeAdapter::execute_action()` end-to-end per the
  "Test Through the Caller" rule (`.claude/rules/testing.md`), including
  a host-path-falls-through test that asserts the sandbox tempdir was
  not touched, and a `..`-escape test that verifies no `/etc/passwd`
  content leaks even after safety-layer redaction

Drive-by: feature-gate two pre-existing dead-code helpers in
`crates/ironclaw_skills/src/parser.rs` on `#[cfg(feature = "registry")]` to
match their only call site, fixing a pre-existing clippy warning that blocked
the workspace's `-D warnings` policy when `ironclaw_skills` is built with
`default-features = false` (as the engine crate does).

Verification:
- `cargo fmt --check` clean
- `cargo clippy --all --benches --tests --examples --all-features` zero warnings
- 31 / 31 new tests passing; no existing tests broken

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* feat(engine-v2): per-project sandbox — Phases 2–7 + live Docker e2e test

Completes the per-project sandbox plan (docs/plans/2026-04-10-engine-v2-sandbox.md
Phases 2–7), building on Phase 1's mount-backend abstraction (#2211).

Phase 2 — Project workspace folder:
- `Project.workspace_path: Option<PathBuf>` field + `with_workspace_path()`
- Host-side `project_workspace_path()`, `ensure_project_workspace_dir()` (creates
  `~/.ironclaw/projects/<id>/` mode 0700, idempotent)
- `FilesystemMountFactory` taking a `ProjectPathResolver` closure (decoupled from
  `Store`); wired into `EffectBridgeAdapter` via `set_workspace_mounts()`

Phase 3 — Standalone daemon binary:
- `src/bin/sandbox_daemon.rs` — NDJSON over stdin/stdout, health/shutdown/execute_tool
- Constructs ReadFileTool/WriteFileTool/ListDirTool/ApplyPatchTool/ShellTool with
  `base_dir=/project` (override via `IRONCLAW_SANDBOX_BASE_DIR`)

Phase 4 — Dockerfile.sandbox:
- Multi-stage build: rust-slim builder (+ python3 for pyo3) compiles sandbox_daemon;
  debian-slim runtime with tini PID 1, common build tools, `/project` mount target

Phase 5 — ProjectSandboxManager + ContainerizedFilesystemBackend:
- protocol.rs: Request/Response/RpcError matching daemon wire format
- transport.rs: `SandboxTransport` trait (seam for testing without Docker)
- containerized_backend.rs: `ContainerizedFilesystemBackend` impls `MountBackend`,
  translates relative→`/project/<rel>`, maps tool-error→MountError
- docker_transport.rs: real bollard exec session, serialized Mutex, lazy reconnect
- lifecycle.rs: deterministic `ironclaw-sandbox-<pid>` naming, ensure_running/stop/remove
- manager.rs: `ProjectSandboxManager` per-project transport cache

Phase 6 — Router gating on ENGINE_V2_SANDBOX:
- `engine_v2_sandbox_enabled()` helper (truthy: 1/true/yes/on)
- Router selects `ContainerizedMountFactory` when enabled + Docker reachable;
  falls back to `FilesystemMountFactory` with warning otherwise

Live e2e bugs caught and fixed:
- Shell without explicit `workdir` defaulted to host (not sandbox); fixed by
  defaulting to `/project/` in `extract_path_param`
- `ContainerizedFilesystemBackend::shell` parsed `stdout`/`stderr` but host
  ShellTool returns merged `output` field; fixed with fallback key lookup
- SANDBOX_TOOL_NAMES only had v2 names (`file_read`/`file_write`) but host
  registry uses v1 names (`read_file`/`write_file`); added both aliases

Tests (62 sandbox-related, all green):
- 27 bridge sandbox unit tests (intercept, workspace_path, factory, protocol,
  lifecycle, containerized_backend with ScriptedTransport mock)
- 7 containerized-backend tests (including 2 regression tests for the shell bugs)
- 5 engine v2 sandbox integration tests (EffectBridgeAdapter end-to-end)
- 5 daemon binary smoke tests (real subprocess + NDJSON I/O)
- 17 engine workspace unit tests
- 1 live Docker e2e test: agent clones nearai/ironclaw into sandbox, renames
  to megaclaw via sed, verifies with grep — 70s, $0.09, recorded trace committed

Verification:
- `cargo fmt --check` clean
- `cargo clippy --all --benches --tests --examples --all-features` zero warnings
- All 62 sandbox tests passing; no existing tests broken

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix: replace .expect() with Result in DockerTransport::ensure_session

CI's no-panics checker flagged the .expect("just inserted") in production
code. Replace with .ok_or_else() returning MountError::Backend.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix: multi-tenant project paths + unify sandbox env var with v1

Two issues addressed:

1. Project workspace paths now namespace by user_id:
   `~/.ironclaw/projects/<user_id>/<project_id>/` instead of
   `~/.ironclaw/projects/<project_id>/`. Prevents filesystem collisions
   in multi-tenant deployments where two users could theoretically have
   the same project UUID.

2. Sandbox enablement now reads `SANDBOX_ENABLED` (same env var as v1
   sandbox) in addition to `ENGINE_V2_SANDBOX`. Either being truthy
   enables the per-project sandbox. This means a single flag governs
   sandbox behavior regardless of engine version, while the v2-specific
   override remains available for transitional setups.

Tests: 30 bridge sandbox unit tests passing (added multi-tenant path
tests + env var combination tests).

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix: address PR review — TOCTOU race, shell env passthrough, canonicalize guard

Three issues flagged by the code review bot on #2211:

1. TOCTOU race in WorkspaceMounts::resolve (HIGH): Added double-checked
   locking — re-check the cache after acquiring the write lock so two
   threads racing on the same project's first access don't both call
   factory.build(). The second thread finds the insert from the first.

2. Shell intercept ignores env parameter (MEDIUM): The shell arm in
   maybe_intercept was passing HashMap::new() instead of forwarding
   the tool call's env map. Fixed to parse parameters["env"] and pass
   it through to backend.shell().

3. Canonicalization fails when root doesn't exist (MEDIUM): When
   self.root hasn't been created yet (first write to a new project),
   canonicalize_under_root would walk up to a real ancestor and the
   starts_with check against the non-existent root would always fail.
   Now skips canonicalization entirely when root doesn't exist — lexical
   safety is already guaranteed by safe_join.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix: address PR review round 2 — apply_patch schema, content validation, dir perms, docs

- Fix apply_patch schema mismatch: MountBackend::patch now takes
  (old_string, new_string, replace_all) matching ApplyPatchTool's
  actual contract. Previously sent {patch: diff} which would fail
  with invalid_params in the containerized daemon.
- Validate file_write content param: return error instead of silently
  writing empty string when content is missing.
- Log stderr frames from sandbox daemon at debug! instead of silently
  discarding them in docker_transport StreamReader.
- Tighten permissions on intermediate directories created by
  ensure_project_workspace_dir (projects/, <user_id>/) to 0o700,
  not just the leaf.
- Fix stale module doc in sandbox/mod.rs (referenced "Phase 5 will
  add" but all phases shipped).
- Fix doc path mismatch: workspace path is <user_id>/<project_id>/,
  not <project_id>/ (workspace_path.rs, CLAUDE.md, design plan).

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix: address PR review round 3 — symlink safety, visibility, debug logging

- Close TOCTOU window in canonicalize_under_root: re-canonicalize and
  verify containment when the reassembled path exists on disk
- Fix list_dir_recursive: use symlink_metadata (lstat) so symlinks are
  detected instead of followed; validate directories against root before
  recursive traversal
- Tighten is_mountable_path to /project/, /memory/, /home/ prefixes
  instead of any absolute path (defense-in-depth)
- Narrow sandbox module visibility to pub(crate) and remove unused
  pub use re-exports
- Remove concrete types (FilesystemBackend, DirEntry, EntryKind,
  ShellOutput) from engine crate top-level re-exports; access via
  ironclaw_engine::workspace:: module path
- Add debug! tracing to sandbox intercept routing decisions
- Add read_file/write_file v1 aliases to daemon SUPPORTED_TOOLS health
  response
- Remove developer-local path from sandbox mod.rs doc comment
- Merge staging to fix CI (user_timezone field on ThreadExecutionContext)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix: address PR review round 4 — safety validation, network isolation, binary writes

- Add pre-intercept safety param validation so sandbox-dispatched calls
  go through the same checks as host-dispatched calls (#1)
- Set network_mode: "none" on sandbox containers to prevent outbound
  network access (#3)
- Reject binary content in containerized write instead of silently
  corrupting via from_utf8_lossy (#5)
- Cap list_dir depth to 10 to prevent unbounded traversal (#8)
- Change container creation log from info! to debug! to avoid breaking
  REPL/TUI output (#10)
- Make is_truthy case-insensitive so SANDBOX_ENABLED=True works (#11)
- Return error instead of unwrap_or_default for missing container ID (#12)
- Propagate set_permissions errors instead of silently ignoring (#13)
- Return error for missing daemon output key instead of defaulting to
  empty object (#14)
- Add env mutex guard in sandbox_live_e2e test (#15)
- Fix rustfmt formatting for let-chain in canonicalize_under_root

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix: address review round 5 — path traversal, error types, tests

Security fixes:
- Sanitize user_id in workspace path to prevent directory traversal via
  malicious user IDs containing `..` or `/`
- Add Component::ParentDir check in ContainerizedFilesystemBackend::container_path
  matching the defense-in-depth approach of FilesystemBackend::safe_join

Correctness:
- Use MountError::Tool instead of MountError::InvalidPath for missing
  tool parameters (content, old_string, new_string) — fixes confusing
  LLM-visible error messages
- Fix clippy sort_by_key suggestion in registry.rs

Cleanup:
- Remove spurious Notify import and dead _notify_link function

New tests:
- ContainerizedFilesystemBackend path traversal rejection (read + write)
- container_path unit tests for safe and unsafe paths
- Adversarial user_id test in workspace_path
- Daemon-side path traversal test in sandbox_daemon_smoke

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix: address review round 6 — param normalization, error types, edge cases

- Normalize sandbox params via prepare_tool_params() before validation,
  matching the host execution path (fixes inconsistent validation)
- Return ToolError::InvalidParameters instead of EngineError::Effect for
  sandbox param validation failures (consistent error surface)
- ensure_dir checks path.is_dir() not path.exists() (rejects files)
- Empty user_id returns "_anonymous" sentinel instead of empty hex string
  that would drop the tenant namespace via PathBuf::join("")
- Restore ENGINE_V2_SANDBOX env var after sandbox live E2E test
- Tighten is_mountable_path to /project/ only (no mounts for /memory/
  or /home/ yet)
- Add v1 tool name aliases (read_file, write_file) to SUPPORTED_TOOLS

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* refactor: unify sandbox env var — remove ENGINE_V2_SANDBOX, use SANDBOX_ENABLED only

Single env var controls sandboxing for both engine versions. The
transitional ENGINE_V2_SANDBOX override is removed from code, tests,
docs, and Dockerfile.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix: double-checked locking in transport_for, explicit stdin close in smoke test

- ProjectSandboxManager::transport_for no longer holds the mutex across
  the Docker ensure_running await. Uses double-checked locking so
  concurrent projects initialize in parallel.
- sandbox_daemon_smoke: explicitly take() stdin before wait_with_output
  so EOF is sent even without a shutdown request.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix: address review — network mode, error types, race, protocol dedup

- Change sandbox container network_mode from "none" to default bridge
  so git clone / cargo build / pip install work inside the container
- Fix binary content rejection to use MountError::Tool instead of
  MountError::InvalidPath (semantic mismatch)
- Fix list depth: use actual depth value instead of depth.max(1)
- Fix orphan container race in transport_for by holding lock across
  container creation instead of double-checked locking
- Deduplicate protocol types: daemon now imports from shared
  bridge::sandbox::protocol instead of defining its own copies
- Make bridge::sandbox pub (narrow exposure: only protocol and
  workspace_path sub-modules are pub)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* docs: update plan doc — sandbox uses bridge networking, not network_mode=none

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-19 20:20:17 +09:00
Illia Polosukhin
77c3821f33 feat(common): apply ExtensionName newtype to fan-out sites (PR 2/2) (#2617)
* feat(common): add CredentialName and ExtensionName newtypes

Introduce typed identifiers for the backend-secret vs user-facing extension
identity split that the Extension/Auth Invariants section of CLAUDE.md
describes. Four recent PRs (#2561, #2473, #2512, #2574) have been identity-
confusion bugs with the same shape: a stringly-typed value passed through
multiple layers with each layer meaning a different thing. Newtypes make
each of those a compile error.

This is PR 1 of 2. PR 1 lands the newtypes and migrates the core auth seam
(ResumeKind::Authentication, MissingCredential, ToolReadiness::NeedsAuth,
LatentActionExecution::NeedsAuth, extensions/naming.rs). PR 2 will migrate
AppEvent.extension_name, OAuth/pending-flow stores, TUI events, and the
remaining extension_name: String fields.

Wire format is unchanged — both newtypes use #[serde(transparent)] so on-
wire and on-disk representations stay plain strings and legacy persisted
rows keep deserializing. Validation runs at explicit construction
(::new / ::try_from / ::from_str), not at deserialize time.

Also adds .claude/rules/types.md codifying the "no stringly-typed
internals" rule.

Regression coverage: 17 new unit tests in identity.rs; existing
auth_manager, router, and gate tests (130+ cases) all pass unchanged.

* fix(common): address PR #2611 review feedback

Four fixes from Copilot, Gemini, and Claude reviews:

- **identity.rs docs**: drop reference to a non-existent `validate()`
  re-validation API. Document that instances represent "passed
  validation at some point in history" rather than "guaranteed valid
  right now" — by design.

- **effect_adapter.rs**: the `awaiting_authorization` / `awaiting_token`
  gate path was using `CredentialName::from_trusted` to wrap a value
  read straight out of a tool's JSON output. Tool output is
  external/untrusted; use `CredentialName::new` (validating) with a
  cascade: external → tool name → `from_trusted(tool_name)` as final
  fallback. Closes a credential-name shape-injection vector.

- **canonicalize()**: reorder checks cheapest-first against the trimmed
  slice so invalid inputs reject without allocating a canonicalized
  `String`. `replace('-', "_")` is deferred until after the structural
  checks pass; since `-`/`_` are both one byte, the earlier length
  check stays valid.

- **Remove `Deref<Target = str>`** from identity newtypes, keep
  `AsRef<str>`. Auto-deref let `&cred_name` silently coerce to `&str`,
  which is exactly the implicit-conversion pattern these newtypes
  exist to prevent. Callers that had a `&CredentialName` where `&str`
  was expected now write `.as_str()` explicitly. Added a regression
  test for the accessor contract and updated the rule template in
  `.claude/rules/types.md` to document the decision.

Declined one review item (Claude): the remaining `to_string()` calls
inside `IdentityError` variants are on the exception path; the common
invalid-input case no longer allocates twice after the canonicalize
reorder, and errors must carry owned strings so they can escape the
function.

Regression coverage: 5035 lib tests + 18 identity tests (one new —
`explicit_accessors_work`) pass. Zero clippy warnings.

* feat(common): apply ExtensionName newtype to fan-out sites (PR 2/2)

Follow-up to #2611. Migrates the remaining stringly-typed extension_name
and credential_name fields to use the ExtensionName and CredentialName
newtypes introduced in ironclaw_common::identity.

Fields now typed:

- AppEvent::{OnboardingState, GateRequired, ExtensionStatus}.extension_name
  (serde transparent — wire format unchanged)
- StatusUpdate::{AuthRequired, AuthCompleted}.extension_name
- TuiEvent::{AuthRequired, AuthCompleted}.extension_name (adds
  ironclaw_common dep to ironclaw_tui)
- PendingOAuthLaunchParams.extension_name
- PendingOAuthFlow.extension_name
- PendingAuth.extension_name, PendingAuthPrompt.extension_name
- ParsedAuthData.extension_name, selected_auth_prompt tuple
- emit_auth_required_status() and Session::enter_auth_mode() parameters
- event_from_configure_result() parameter
- resolve_extension_for_action() and resolve_auth_gate_display_name()
  return types
- normalize_extension_name() return type

PendingAuthPrompt::new is now infallible (accepts ExtensionName directly)
since the identity validator carries the non-empty invariant the
constructor used to re-check. The "blank extension name" rejection test
moved out — that logic lives in ironclaw_common::identity tests.

Test updates use `ExtensionName::new("...").unwrap()` at construction
sites and `from_trusted(...)` where a trusted upstream string is being
adapted. Every site is a compile-time audit of where the type was
crossing a boundary untyped.

Regression coverage: existing 5034 lib tests + 26 engine_v2_gate
integration tests + 40 ironclaw_common tests all pass. Zero clippy
warnings across all features.

* fix(web): return ExtensionName from pending_gate_extension_name

Addresses Claude's review comment on #2611: the function was doing
`Some(credential_name.as_str().to_string())` in the fallback branch,
defeating the newtype's purpose by re-stringifying the identity.

Return `Option<ExtensionName>` instead. Plumbs through `PendingGateInfo.
extension_name` (wire format unchanged — `#[serde(transparent)]`).
The fallback path's cross-identity conversion (credential name →
extension name) is now an explicit `ExtensionName::from_trusted` call,
making the boundary crossing visible at the call site.

Also fixes the `Deref<Target = str>` removal fallout that followed the
rebase onto the updated PR 1: call sites that relied on auto-deref
(`ext.contains(...)`, `auth_manager.submit_auth_token(&cred_name, ...)`)
now explicitly call `.as_str()`.

* fix(router,web): address PR #2617 review feedback

Four Gemini review comments, all on the boundary between credential/
extension identifiers and user input.

1. [HIGH, security] extensions_setup_submit_handler was wrapping the
   URL path segment in ExtensionName::from_trusted, which skips the
   newtype's path-traversal / invalid-character validation. That path
   is user-controlled (`/api/extensions/{name}/setup`). Validate with
   ExtensionName::new at the handler entry and return 400 on failure;
   downstream uses switch to .as_str() or .clone() of the validated
   value, and the three in-handler from_trusted sites disappear.

2. Rename resolve_auth_gate_display_name ->
   resolve_auth_gate_extension_name. The function returns an
   identifier/slug, not a human-readable display name — the old name
   was a leftover from when the value was a String.

3. Return Option<ExtensionName> from the renamed function. Previously
   the non-Authentication gate branch fabricated an
   ExtensionName::from_trusted(pending.action_name), which was
   semantically wrong (an action name is not an extension identifier)
   and silently defeated the type's invariants. Now it returns None
   for Approval/External gates, and callers thread an Option through.
   send_pending_gate_status accepts Option<&ExtensionName> and only
   uses it on the Authentication arm, with a warn! log if upstream
   plumbing ever reaches the arm with None. The GateRequired SSE
   event's extension_name is now a clean .clone() of the Option.

4. Rename auth_display_name -> extension_name on
   send_pending_gate_status so the parameter name matches both its
   type and the StatusUpdate::AuthRequired.extension_name field it
   feeds.

Regression: new test_extensions_setup_submit_rejects_path_traversal_name
at the handler tier (per .claude/rules/testing.md "Test Through the
Caller, Not Just the Helper") drives the handler with malformed path
segments and asserts 400 before the value reaches extension lookup or
any from_trusted wrap. 5035 lib tests pass, zero clippy warnings.

* docs(identity): codify web-boundary rules + add static check

Three rule additions + one enforcement hook covering the identity
boundary that PR #2617 review uncovered:

- src/channels/web/CLAUDE.md — extend "Unified Extension Onboarding"
  with explicit rules:
  * Setup/configure/activate routes MUST validate `{name}` via
    `ExtensionName::new` at handler entry (return 400 on failure).
  * Web DTOs and handlers MUST NOT reference `CredentialName` —
    credential identity is backend-only; the dispatcher/auth_manager
    resolves it from the ExtensionName server-side.
  * Auth-flow extension resolution happens in *one* place
    (`AuthManager::resolve_extension_name_for_auth_flow`). Wrappers
    are thin and delegate; they must not duplicate the precedence
    logic or re-derive from credential prefixes. The four recent
    identity bugs (#2561, #2473, #2512, #2574) were duplicate-
    resolution drift.

- src/bridge/CLAUDE.md — new module spec documenting auth_manager.rs
  as the single authority for auth-flow extension resolution, with
  the resolver's four-step precedence order and the approved wrapper
  call sites.

- scripts/pre-commit-safety.sh — new check #8 (CREDNAME): flags
  `CredentialName` references in newly-added production lines under
  `src/channels/web/**`. Test-mod code is excluded via the existing
  `strip_test_mod_lines` filter. Suppression via
  `// web-identity-exempt: <reason>` for the rare legitimate case of
  reading an already-typed value off a backend struct. Smoke-tested:
  * baseline (current branch) — no warnings
  * injected violation — fires with CREDNAME warning
  * injected violation + `// web-identity-exempt:` — suppressed

The rules and the check live at the same level — humans read the
rule, CI enforces it.

* fix(auth): validate user-influenced names at the resolver boundary

Addresses four Copilot review comments on PR #2617 that all pointed at
the same seam: the canonical `AuthManager::resolve_extension_name_for_auth_flow`
returned a raw `String` whose first branch (the LLM-supplied `name`
parameter on `tool_install` / `tool_activate` / `tool_auth` actions)
passed through without `ExtensionName` validation. Both call sites
then wrapped the result in `ExtensionName::from_trusted`, promoting an
unvalidated user-influenced value to a typed identity.

- **Resolver now returns `ExtensionName`.** Branch 1 validates the
  user-controlled name via `ExtensionName::new` and falls through on
  failure; branches 2–4 use `from_trusted` because their sources
  (tool registry hint, canonicalizer, typed credential fallback) are
  already trusted upstream. This consolidates validation in the single
  "resolve once" site documented in `src/bridge/CLAUDE.md`.

- **router.rs and server.rs drop their wraps.** `resolve_extension_for_action`
  (router) and `pending_gate_extension_name` (server) return the
  resolver's typed output directly. The tool-registry fallback in
  router.rs (no-auth-manager path) keeps its `from_trusted` wrap
  since it operates on the same trusted sources as branch 2.

- **`restore_selected_auth_prompt` re-validates rehydrated prompts.**
  `PendingAuthPrompt` is `#[serde(transparent)]`, so deserialize does
  not re-check the inner `ExtensionName` string. A legacy-persisted
  invalid name would previously have been dropped by the old
  `PendingAuthPrompt::new(String, ...)` empty-string rejection; now
  `restore_selected_auth_prompt` re-runs `ExtensionName::new` and
  drops + warns on failure, upgrading the old non-empty-only check to
  the full identity invariant. New test
  `test_restore_selected_auth_prompt_rejects_invalid_legacy_row` forges
  three invalid rows (empty / uppercase / path-traversal) straight
  through serde and asserts each is dropped.

- **Docstring on `PendingAuthPrompt` refreshed.** The old comment
  claimed `::new` "trims and validates extension_name is non-empty",
  which is no longer true — `::new` is infallible and the invariant
  lives in `ExtensionName` itself. The new comment documents the
  split: validation runs at `ExtensionName::new` construction and at
  restore-from-persistence, not inside `PendingAuthPrompt`.

Regression: 5063 lib tests pass (+1 new). Clippy zero warnings.

* fix(ci): adapt post-merge-from-staging sites to ExtensionName

Staging shipped #2640 (repl unlock) and gateway refactor commits after
my last merge. The CI build picked them up via auto-merge and hit three
type mismatches my branch hadn't seen:

- src/channels/repl.rs:908 — new test constructs
  `StatusUpdate::AuthRequired { extension_name: "google_oauth_token"
  .to_string(), ... }`. Typed field; now `ExtensionName::new(...).unwrap()`.

- src/channels/web/server.rs:1405-1424 — staging added a no-auth-manager
  fallback chain to `pending_gate_extension_name` that returned raw
  `Some(String)` on three branches. Aligned with
  `AuthManager::resolve_extension_name_for_auth_flow`: branch 1
  (user-influenced `tool_install`/`tool_activate`/`tool_auth` `name`
  param) validates via `ExtensionName::new` and falls through on
  failure; branches 2-3 (provider-extension hint, credential-name
  fallback) use `from_trusted` because they're sourced from typed
  upstream state. Mirrors the fix applied to the canonical resolver
  in c813caa9.

- src/channels/web/server.rs:3831 — test used `.as_deref()` on the
  function's Option<ExtensionName> return; switched to
  `.as_ref().map(|n| n.as_str())` matching the pattern from the
  adjacent test.

No new logic — just adapting two staging landings to the typed surface
PR #2617 introduces. The validation behaviour for the fallback path is
already locked in by the identity-layer tests in
`ironclaw_common::identity` (rejects_path_traversal, rejects_uppercase,
etc.) and by the regression test added in c813caa9
(test_restore_selected_auth_prompt_rejects_invalid_legacy_row).

[skip-regression-check] — type adaptation to unblock CI, no behaviour
change needing its own regression test.

Clippy with `-D warnings` clean, 5074 lib tests pass.

* fix(auth): extract shared resolver; wrapper delegates instead of duplicating

Addresses two Copilot comments on PR #2617 that surfaced the same
architectural issue: the no-auth-manager fallback in
`pending_gate_extension_name` had grown a three-branch copy of the
resolver's precedence that quietly skipped branch 3 (canonicalize
action_name + check `ExtensionManager::extension_info`). Exactly the
duplicate-resolution drift the "one resolver" rule in
`src/bridge/CLAUDE.md` warns against — four prior identity bugs
(#2561, #2473, #2512, #2574) were the same pattern.

- Extracted `pub(crate) async fn resolve_auth_flow_extension_name` to
  `src/bridge/auth_manager.rs` as the single site of the four-branch
  precedence. Takes `Option<&ToolRegistry>` + `Option<&ExtensionManager>`
  so both the `AuthManager` method (which passes its own fields) and
  the web wrapper (which passes `state.tool_registry` /
  `state.extension_manager`) share identical logic.

- `AuthManager::resolve_extension_name_for_auth_flow` is now a 1-block
  delegator.

- `pending_gate_extension_name` in `web/server.rs` drops its inline
  fallback entirely and calls the shared free function from both
  branches. The bare-test-harness path now runs branch 3 (canonicalize
  + installed-extension check) that it previously missed.

- Updated `src/bridge/CLAUDE.md` to document the free function as the
  single authority, the three approved wrappers as thin delegators,
  and the return type as `ExtensionName` (was stale `String` from the
  pre-c813caa9 era).

Regression coverage: the existing
`resolve_extension_name_for_auth_flow_prefers_installed_channel_name`
test passes unchanged — it exercises branch 3 through the method, which
now reaches it via the extracted free function.

* Merge remote-tracking branch 'origin/staging' into feat/identity-newtypes-pr2

Picks up #2644 (platform/ extraction) and #2645 (features/oauth/ move).

Manual resolutions:
- src/channels/web/server.rs: staging removed 720 lines of OAuth
  callback code (moved to features/oauth/mod.rs in #2645). My PR 2
  ExtensionName changes to two of those functions (oauth_callback_handler,
  slack_relay_oauth_callback_handler) ported to the new location.
- src/bridge/auth_manager.rs: extended the shared resolver's
  branch-1 action pattern to include 'tool-activate' and 'tool-auth'
  variants, matching staging's new
  pending_gate_extension_name_uses_install_parameters_for_hyphenated_activate_tool
  test expectation. Underscore + hyphen variants for all three actions.

No new PR 2 logic — just aligning the type surface with two staging
refactors. 5074 lib tests pass (+1 vs previous — the new staging
hyphenated-tool test). Clippy -D warnings clean.

* fix(web): address PR #2617 round-3 review feedback

Two Copilot findings from the 2026-04-18 review:

1. `/api/extensions/{name}/{activate,remove,setup}` handlers accepted
   `Path<String>` and forwarded it to the extension manager without
   validating path-traversal, invalid characters, or case — only
   `extensions_setup_submit_handler` had the `ExtensionName::new` guard.
   Applied the same boundary validation to all three siblings.

2. `restore_pending_auth_mode` took `extension_name: &str` and
   re-wrapped it with `ExtensionName::from_trusted`, re-introducing an
   unvalidated string boundary even though every caller already held
   an `ExtensionName` (`pending_auth.extension_name`). Changed the
   helper to accept `&ExtensionName` so the identity stays typed
   end-to-end; `from_trusted` is no longer needed here.

Regression: added `test_extensions_sibling_handlers_reject_path_traversal_name`
covering activate / remove / setup-GET with the same malformed slugs
the setup-submit test already locks in (path traversal, slash in
segment, uppercase, space, trailing underscore). Drives the handlers
through axum routing so the boundary is exercised end-to-end.

* fix(ci): adapt replay_outcome to ExtensionName after staging merge

Staging #2621 added `tests/support/replay_outcome.rs`, which destructures
`StatusUpdate::{AuthRequired,AuthCompleted}.extension_name` into a
`String` field of `EventSummary`. This PR made those `StatusUpdate`
fields `ExtensionName`, so the post-merge build breaks in the replay
snapshot gate and all-features clippy jobs.

Convert to `String` at the destructure via `ExtensionName::into()` so
the `EventSummary` shape (and the persisted `.snap` files) stay
unchanged. The test-support / snapshot wire format is a legitimate
String boundary per `.claude/rules/types.md`.
2026-04-19 19:58:43 +09:00