# AGENTS.md — ShadowClaw

> Guidance for AI coding agents (Antigravity, Claude, Codex, etc.) working in this repo.
> **Documentation:** For detailed architecture docs, subsystem deep-dives, step-by-step guides, and architecture decision records, see [`docs/`](docs/README.md).

## Project Snapshot

ShadowClaw is a dual-runtime AI assistant written in **TypeScript** (`.ts`). It features an interactive, browser-native client (deployable as a PWA or Electron desktop app) whose core orchestration runs off the main thread in a Web Worker, paired with a host-native headless server-side agent participant (`shadow-claw agent`) that executes the same reasoning loop, declarative skills, and tool chains natively in Node.js against real filesystem handles and host OS child processes. It is backed by a Node.js server (local proxying, control plane, task scheduler, Stateless MCP) and driven via the `shadow-claw` CLI.
The project uses a **Rolldown build pipeline** to bundle the application.

**Stack:** HTML + TypeScript / ESM · Web Components · TC39 Signals · IndexedDB · SQLite (`node:sqlite`) · OPFS + Node FS Handles · Web Workers · Service Worker (Workbox PWA · Web Push) · Express dev server · Electron desktop · AWS Bedrock / OpenRouter / Anthropic / Gemini / Transformers.js · Jest + Playwright tests · Storybook

## Subsystem Documentation

ShadowClaw has been significantly deduplicated. Instead of a massive `AGENTS.md` file, subsystem documentation now lives in `docs/`. **You must read the relevant files before modifying subsystems:**

| Subsystem / Topic             | Relevant Documentation                                                                               |
| ----------------------------- | ---------------------------------------------------------------------------------------------------- |
| Architecture & Data Flow      | [docs/architecture/overview.md](docs/architecture/overview.md)                                       |
| Orchestrator & State          | [docs/architecture/orchestrator.md](docs/architecture/orchestrator.md)                               |
| Worker Protocol (LLM / Tools) | [docs/architecture/worker-protocol.md](docs/architecture/worker-protocol.md)                         |
| Storage (IndexedDB / OPFS)    | [docs/architecture/storage.md](docs/architecture/storage.md)                                         |
| Token / Context Management    | [docs/architecture/context-management.md](docs/architecture/context-management.md)                   |
| Streaming (SSE / UI)          | [docs/architecture/streaming.md](docs/architecture/streaming.md)                                     |
| Accounts & Credentials        | [docs/subsystems/accounts.md](docs/subsystems/accounts.md)                                           |
| Agent Skills                  | [docs/subsystems/skills.md](docs/subsystems/skills.md)                                               |
| Attachment Capabilities       | [docs/subsystems/attachment-capabilities.md](docs/subsystems/attachment-capabilities.md)             |
| A2UI Interactive Surfaces     | [docs/subsystems/a2ui.md](docs/subsystems/a2ui.md)                                                   |
| AGUI Events & Adapter         | [docs/subsystems/agui.md](docs/subsystems/agui.md)                                                   |
| Channels & Multi-Conversation | [docs/subsystems/channels.md](docs/subsystems/channels.md)                                           |
| Chat Template Sanitizer       | [docs/subsystems/sanitizer.md](docs/subsystems/sanitizer.md)                                         |
| Cryptography & Secrets        | [docs/subsystems/crypto.md](docs/subsystems/crypto.md)                                               |
| Custom Element Security       | [docs/subsystems/custom-element-security.md](docs/subsystems/custom-element-security.md)             |
| Electron Desktop App          | [docs/subsystems/electron.md](docs/subsystems/electron.md)                                           |
| Email Integration             | [docs/subsystems/email.md](docs/subsystems/email.md)                                                 |
| Git Integration               | [docs/subsystems/git.md](docs/subsystems/git.md)                                                     |
| Headless Agent Participant    | [docs/decisions/headless-cli-agent-participant.md](docs/decisions/headless-cli-agent-participant.md) |
| Local Models & Hugging Face   | [docs/subsystems/local-models.md](docs/subsystems/local-models.md)                                   |
| Notifications & Tasks         | [docs/subsystems/notifications.md](docs/subsystems/notifications.md)                                 |
| Pages System                  | [docs/subsystems/pages.md](docs/subsystems/pages.md)                                                 |
| Providers (OpenAI, Anthropic) | [docs/subsystems/providers.md](docs/subsystems/providers.md)                                         |
| Remote MCP                    | [docs/subsystems/remote-mcp.md](docs/subsystems/remote-mcp.md)                                       |
| Shell Emulator / Bash Tool    | [docs/subsystems/shell.md](docs/subsystems/shell.md)                                                 |
| Tools & Execution             | [docs/subsystems/tools.md](docs/subsystems/tools.md)                                                 |
| Trusted Types Tinyfill        | [docs/subsystems/trusted-types-tinyfill.md](docs/subsystems/trusted-types-tinyfill.md)               |
| UI & Signals (Web Components) | [docs/subsystems/reactive-ui.md](docs/subsystems/reactive-ui.md)                                     |
| WebMCP Integration            | [docs/subsystems/webmcp.md](docs/subsystems/webmcp.md)                                               |
| Web Share Target              | [docs/subsystems/share-target.md](docs/subsystems/share-target.md)                                   |
| WebVM (v86 Alpine)            | [docs/subsystems/vm.md](docs/subsystems/vm.md)                                                       |
| CLI & Static Site Publishing  | [docs/subsystems/cli.md](docs/subsystems/cli.md)                                                     |
| Control Plane & Client Bridge | [docs/subsystems/control-plane.md](docs/subsystems/control-plane.md)                                 |
| Stateless MCP Server          | [docs/subsystems/mcp-server.md](docs/subsystems/mcp-server.md)                                       |
| File Backup Subsystem         | [docs/subsystems/backup.md](docs/subsystems/backup.md)                                               |
| Theming & Stylesheets         | [docs/subsystems/theming.md](docs/subsystems/theming.md)                                             |
| OpenAPI & Discoverability     | [docs/subsystems/openapi.md](docs/subsystems/openapi.md)                                             |
| Server A2A Protocol (HTTP)    | [docs/decisions/server-a2a-http-binding.md](docs/decisions/server-a2a-http-binding.md)               |

## Conventions & Guardrails

### Test Driven Development

Tests are the source of truth for expected behavior. Before implementing a new feature or fixing a bug, first write a failing test that captures the desired behavior. Then implement the feature or fix the bug until the test passes.

### File Naming

- Source files use `.ts` (TypeScript) and follow strict `kebab-case` naming across all modules and directories (e.g. `wrap-untrusted-content.ts`, `tool-chain.ts`, `read-group-file.ts`, `is-binary.ts`).
- Tests live **next to** their source file: `src/core/orchestrator/orchestrator.ts` → `src/core/orchestrator/orchestrator.test.ts`.
- Storybook stories live **next to** their component file: `src/components/shadow-claw-toast/shadow-claw-toast.ts` → `src/components/shadow-claw-toast/shadow-claw-toast.stories.ts`.
- End-to-end tests live in `e2e/` and use Playwright with fixtures + Page Objects. Extensions are `.ts`.
- Components are in `src/components/shadow-claw-*/shadow-claw-*.ts` (each in its own subdirectory with co-located `.html` and `.css` files). Many large components extract their logic into co-located `utils/` subdirectories. Common shared primitives reside in `src/components/common/` and settings panels in `src/components/settings/`.
- `src/core/theme-init.ts` is a TypeScript bootstrap script compiled by Rolldown as a self-contained IIFE (`dist/public/theme-init.js`). It must remain free of module-level side effects that depend on the full app being ready.

### Types & Imports

- Types are declared in feature-local `*types.ts` modules (for example `src/subsystems/worker/types.ts`, `src/subsystems/tools/types.ts`, and `src/subsystems/channels/types.ts`).
- **A2UI types** live in `src/ui/a2ui/types.ts`. Utility functions are individual ESM files under `src/ui/a2ui/utils/`. Registries are under `src/ui/a2ui/registries/`. The old monolithic `src/ui/a2ui.ts` has been removed — do not recreate it.
- **A2UI catalog renderers** live in `src/components/shadow-claw-a2ui/catalog/basic/` (one file per component, co-located tests). Do not add files directly under `catalog/` — always place them inside a named subdirectory (e.g., `basic/`).
- External libraries are locally bundled using **Rolldown** and `npm install`. Node-only packages (Express, Jest, Workbox CLI, Electron) belong in `devDependencies`.
- **Package Library Exports:** ShadowClaw exposes modular ESM exports declared in `package.json` under `.`, `./cli`, `./cli/*`, `./components`, `./components/*`, `./utils`, and `./utils/*`. Library bundles and TypeScript declaration files (`.d.ts`) are compiled via `npm run build:lib` (`npm run tsc:lib` + `rolldown -c configs/rolldown/rolldown.lib.config.mjs`) into `dist/lib/`. CLI scripts are compiled via `npm run build:cli` (`rolldown -c configs/rolldown/rolldown.cli.config.mjs`) into `dist/cli/`.
- **Shared Utilities Convention:** Generic application-wide utilities must reside in `src/utils/` (e.g. `base64.ts`, `coerce.ts`, `dedent.ts`, `delay.ts`, `filename.ts`, `is-binary.ts`, `mime.ts`, `normalize-string-list.ts`, `normalize-workspace-path.ts`, `parse-boolean-config.ts`, `parse-stored-string-list.ts`, `seo.ts`, `ulid.ts`), which is the authoritative root for reusable cross-cutting helpers and exported via package library exports (`./utils`). Complementary operations (such as encode/decode, basename/sanitize, byte/MIME binary detection) should be consolidated into dual-purpose unified functions that cover both operations rather than creating single-function silos. Tool-family-specific utilities shared across multiple tools reside in `src/worker/tools/utils/`. Do not introduce ad-hoc utility directories or duplicate single-function utilities across private `utils/` folders.
- **JSON Imports:** Always use ES import attributes (`with { type: "json" }`), not the deprecated `assert` syntax.

### Code Formatting & Developer Tooling

- Code formatting uses Prettier.
- `npm run format` formats all files using Prettier with persistent disk caching enabled (`.cache/.prettiercache`).
- `npm run format:changed` (`bin/format-changed.mjs`) selectively formats only modified and staged files for fast incremental developer iterations.

### JS Shell Capabilities & Limitations (Bash tool)

When WebVM is unavailable, the `bash` tool falls back to a lightweight JavaScript shell emulator powered by `just-bash`.

- **Supported:** POSIX shell built-ins (`echo`, `cat`, `ls`, `cd`, `grep`, `sed`, `awk`, `find`, `jq`, etc.), piping (`|`), redirects (`>`, `>>`), variables, and loops.
- **NOT Supported:** `apt`, `npm`, `pip`, `curl`, `wget`, `git` (use `git_*` agent tools instead).
- **Network Access:** External internet connectivity within the shell is dynamic and controlled globally by the **Internet Access** setting (`vm_bash_full_internet_access`). When disabled, routing to public ranges is blocked.

### Git Merge Conflict Resolution

When `git_merge` encounters conflicts, it returns a **structured conflict report** with inline conflict regions.

1. Use `read_file` to see the full file content with conflict markers.
2. Decide the correct resolution.
3. Use `write_file` to overwrite the file with the **complete resolved content** (no conflict markers remaining).
   **Important:** Always use `read_file` + `write_file` for conflict resolution. Do **not** use `bash`, `sed`, or `awk` — these are fragile with conflict markers and waste iterations.

### Task Recursion Guard

To prevent infinite execution loops, the system enforces a strict recursion guard during task execution.

- Tools that manage tasks (`create_task`, `update_task`, `delete_task`, `enable_task`, `disable_task`) and notifications (`send_notification`) are blocked during scheduled task execution.
- The `run_task` tool is explicitly blocked within **any** task execution context (scheduled or manual) to prevent runaway self-triggering loops.
- The `spawn_subagent` tool is explicitly excluded from the subagent's allowed tools to prevent infinite subagent recursion. Furthermore, parallel subagent spawns respect a globally configured limit (`SUBAGENT_MAX_PARALLEL`).
- The `ask_user` tool **blocks the worker** until the UI sends back an `ask-user-response` message. Never call it from a scheduled task or subagent context (including tasks with the subagent flag enabled) where no human is present to respond — it will deadlock the worker.

### Provider Error Dialogs & Auto-Close

- Provider errors (such as `429` rate limiting, unreachable providers, missing or invalid API keys, and local runtime faults) surface help dialogs via `requestDialog` configured with `autoCloseSeconds: 30`.
- Dialogs display a 1-second visual countdown on the confirmation button and an `aria-live="polite"` status region (`role="status"`, `aria-atomic="true"`). Auto-close ensures unattended task executions and automated runs do not deadlock or block indefinitely waiting for manual modal dismissal.
- **Dialog Link Base-Path Resolution:** Action links passed to `requestDialog` (`links`) are automatically resolved under the active application base path via `applyBasePath(rawHref)` for internal and relative URLs, ensuring modal documentation and troubleshooting links route correctly on subpath deployments while external URLs (`http://`, `https://`, `mailto:`, `tel:`) and hash anchors (`#`) are preserved.

### Subagent Dispatch & Tool Allowlisting

- Route subagent invocation through `dispatchSubagentInvoke` (`src/core/orchestrator/utils/dispatch-subagent-invoke.ts`) so provider-specific browser/runtime handling stays centralized.
- Do not call `executeTool` from provider loops without passing the active enabled tool list (`allowedTools`). Runtime allowlist checks, recursion guards, and headless capability checks are enforced in `executeTool` via centralized guards in `src/worker/utils/guards.ts` (`runToolGuards`, `checkAllowedToolGuard`, `checkTaskExecutionGuard`, `checkScheduledTaskBlockedGuard`, `checkHeadlessCapabilityGuard`).
- Conversation-level `pinnedMaxTokens` overrides are optional and must remain model-aware (clamped to provider/model output limits).

### Private Network Access & Loopback Connections

- **Service Worker Loopback Bypass:** The Service Worker fetch proxy (`src/service-worker/fetch-proxy-rules.ts`) unconditionally bypasses all loopback (`localhost`, `127.0.0.1`, `::1`, `[::1]`) and private IP ranges (`10.x`, `172.16-31.x`, `192.168.x`) so browser tabs hosted on static platforms (such as GitHub Pages or Cloudflare Pages) can connect directly to local servers without Service Worker interception.
- **Service Worker Atomic Precache, Multi-Cache Matching & Offline Navigation:** The Service Worker fetch proxy (`src/service-worker/fetch-proxy.ts`) serves SPA app-route navigations (`fetchAppShellWithOriginAgentCluster`) **Cache-First** from `workbox-precache*` matched against the worker's stamped `self.__SHADOWCLAW_PRECACHE_INDEX_REVISION__` when a precached entry exists, keeping `index.html`, `index.js`, and the core boot/shell/sidebar/settings chunks on an atomic snapshot until the new Service Worker activates (falling back to Network-First + `"shadow-claw-cache"` when no precache entry exists). Pretty-path / non-app-route navigations (`fetchNavigationWithFallback`) remain **Network-First**, updating `"shadow-claw-cache"` on `2xx` responses and falling back to cached candidates or `findCachedAppShell` when offline or on non-OK errors. `matchCacheEntry` prioritizes `workbox-precache*` caches ahead of `"shadow-claw-cache"` across all CacheStorage caches with `ignoreSearch: true`. In `src/service-worker/workbox-config.cjs`, non-precached root hashed JS chunks use `CacheFirst` (`"shadow-claw-chunks-cache"`, bounded to 150 entries / 30 days), while other same-origin runtime assets use `NetworkFirst` (`"shadow-claw-cache"`) with a `fetchDidSucceed` plugin that falls back to cached `200` responses on HTTP `404` or `5xx`. During builds (`src/cli/build/build.ts` and watch-mode `configs/rolldown/rolldown.config.mjs`), `collectPrecacheShellChunks` (`src/cli/build/utils/collect-precache-shell-chunks.ts`) and `syncServiceWorkerPrecacheRevisions` (`src/cli/build/utils/sync-service-worker-precache.ts`) merge the boot/shell/sidebar/settings JS chunk closure into `precacheAndRoute` (with `revision: null` for hashed chunks), refresh MD5 hashes against `dist/public` and consumer `.agents/` + `static-main-manifest.json`, and stamp `self.__SHADOWCLAW_PRECACHE_INDEX_REVISION__`.
- **Service Worker Lifecycle, Chunk Recovery & Update Dialog Flow:** In `src/service-worker/init.ts`, the Workbox service worker registers with `{ updateViaCache: "none" }`. Registration runs immediately when a controller is already present (`hadControllerAtStart`) and is deferred by 10 seconds only on first install to prioritize startup. Periodic update checks run every hour (`SW_UPDATE_CHECK_INTERVAL_MS`), on window focus and visibility (`SW_UPDATE_CHECK_ON_FOCUS`, min 30-second gap `SW_UPDATE_CHECK_MIN_GAP_MS`), and whenever a worker enters the waiting state. `ensureComponentLoaded` (`src/components/shadow-claw/utils/load-component.ts`) evicts rejected loads from `loadingPromises` so retries succeed and dispatches `shadow-claw-chunk-load-error` (also dispatched by `src/core/index.ts` on boot failure); `init.ts` listens for `shadow-claw-chunk-load-error`, dynamic-import `unhandledrejection`, and `index.js` `<script>` errors to register immediately, bypass `"Later"` backoff, and trigger `wb.update()`. When `confirmServiceWorkerUpdate` returns `null` because the UI bridge never mounted, `init.ts` retries on subsequent checks unless `chunkLoadFailed` or an un-upgraded `<shadow-claw>` host is already controlled (`hadControllerAtStart`), in which case it auto-applies `SKIP_WAITING` + reload (bounded by `MAX_FALLBACK_RELOAD_ATTEMPTS` and `UPDATE_FAILURE_COOLDOWN_MS`). When deferred with "Later", reprompting backs off by 15 minutes (`SW_UPDATE_REPROMPT_INTERVAL_MS`). Workbox enables `cleanupOutdatedCaches: true`. New worker activations in other tabs prompt open tabs to reload via `controllerchange` ("Update Installed").
- **Client `targetAddressSpace` Signaling:** Outgoing client fetch requests targeting local or private network endpoints (`control-plane-client.ts`, `backup-controller.ts`, `push-client.ts`, `task.ts`, and `fetch-proxy.ts`) must supply `targetAddressSpace: 'loopback'` (or `'private'`) for Chromium Private Network Access (PNA) compliance.
- **Server PNA & Cross-Origin Headers:** Server endpoints set `Access-Control-Allow-Private-Network: true` on both preflight (`OPTIONS`) and cross-origin responses, and trust `.github.io` / `.pages.dev` / `allowedOrigins` origins for browser integration.

### HTML Sanitization & Trusted Types

- **Explicit Pre-Sanitization:** All dynamically rendered HTML, inline SVGs, or iframe `srcdoc` values must be sanitized using DOMPurify (e.g., `sanitizeToTrustedHtml` or `sanitizeSrcdocHtml`) **before** being passed to the Trusted Types policy.
- **Identity Transform Policy:** The primary Trusted Types policy's `createHTML` callback in `src/security/trusted-types.ts` is intentionally implemented as an identity transform `(input) => input`. This prevents double-sanitization and preserves caller-specified custom sanitization options (such as allowing `blob:` URLs for relative workspace media previews) that would otherwise be lost.
- **Default Trusted Types Policy:** Use `ensureDefaultTrustedTypesPolicy()` from `src/security/default-trusted-types-policy.ts` to register the `"default"` Trusted Types policy idempotently. It uses `trustedTypes.getPolicy("default")` before attempting `createPolicy`, so it is safe to call from multiple modules (including after HMR). Use `toDefaultTrustedScriptUrl()` for script URL sinks such as Workbox service worker registration. Both are called as early as possible from `src/core/theme-init.ts`.
- **Custom Purify Options:** When rendering media resolved relative to the workspace, pass custom DOMPurify configurations extending the standard `ALLOWED_URI_REGEXP` to allow `blob:` URIs safely.
- **Iframe Embed Allowlists**

Markdown and HTML preview work should preserve the Settings-backed iframe host allowlist in `src/security/iframe-sanitizer.ts`; update the sanitizer tests and docs when adding or changing embed hosts.

### Local Inference & Transformers.js

- **Hardware Acceleration**: Ensure CPU/WASM fallback explicitly uses `q4` to avoid software emulation. Reject WebGPU adapters lacking `shader-f16`.
- **Chat Templates**: Local providers use dynamic Jinja templating (`chat_template.jinja`) fetched with the tokenizer via the Hugging Face API. Do not hardcode chat templates.
- **Unified Local Model Tool Calling**: Tool call formatting and extraction across local models (both the server proxy route in `src/server/routes/transformers-js.ts` and in-process Node execution in `src/worker/tools/node-transformers-executor.ts`) are unified via `parseLocalModelToolCalls` (`src/subsystems/providers/utils/parse-local-model-tool-call.ts`), supporting multi-tool calls, Gemma 4 `call:` syntax, and defensive schema sanitization. Token streaming suppresses raw tool call syntax via `createToolCallStreamFilter`. In headless mode, `handleInvoke` preserves and forwards formatted messages with the system prompt to in-process local executors (`node-transformers-executor.ts` and `node-llamafile-executor.ts`), and `normalizeMessagesForChatTemplate` preserves tool call IDs and names on tool turns.
- **Local Binary Driver Architecture & Tool Calling**: `LocalBinaryDriver` in `src/server/services/llamafile-manager.ts` manages local `.llamafile` and `.agentfile` binaries. Instruction-tuned Llamafile models (`supportsTools: true`) support tool calling in server mode (`/v1/chat/completions`), CLI prompt injection mode, and upstream proxy routes (`/llamafile-proxy/tools`). Autonomous Agentfile binaries (`agentfile`) execute internal tool loops with diagnostics on `stderr` and answers on `stdout`. On non-Windows platforms, processes are spawned via `/bin/sh` to avoid Linux `binfmt_misc`/`run-detectors` execution issues with APE binaries.
- **In-Browser Default & Prompt API Degradation Ladder**: ShadowClaw defaults out-of-the-box in the browser client to Transformers.js (`transformers_js_browser` with default model `onnx-community/Qwen3-0.6B-ONNX`) and guided onboarding (the chat onboarding dialog routes users to Transformers.js by default). When the Prompt API (`prompt_api`) is manually selected and native browser Prompt API (`window.LanguageModel`) is unavailable or reports `"no"` / `"unavailable"`, ShadowClaw degrades transparently to local ONNX execution via `prompt-api-polyfill` and `built-in-ai-task-apis-polyfills`, updating chat cards and runtime status accordingly. Users can explicitly prepare and download local models from Settings > AI ("Download Local AI Model") with real-time download progress to satisfy browser user-activation requirements before executing writing tasks.

### Static Main Site, Routing & Page Suppression

- **Page Seeding & Suppression:** Static main site pages are seeded from the `pages/main/` directory via `seedStaticMainSite` (`src/storage/static-main-site.ts`). When removing pages from the Pages sidebar, ensure suppression is recorded via `suppressPage` (`src/storage/suppressed-pages.ts`) so they are not automatically re-seeded on app launch. Re-adding a page calls `unsuppressPage` to clear suppression.
- **Static Pretty Paths, Routing & SEO Metadata:** When `pages/routes.json` is present, `src/cli/prerender/pretty-paths/prerender-pretty-paths.ts` generates physical `index.html` files with DSD shells for pretty paths and injects the routing manifest into `#shadow-claw-static-routing` and `static-routing.json` (`src/storage/static-routing.ts`). Routes support optional `title` and `description` overrides. Pre-rendering automatically patches Yoast-style SEO metadata into head tags (`patchHtmlHeadMetadata` in `src/utils/seo.ts`): page titles (`formatSeoTitle` with priority order: route `title` -> frontmatter `seo_title` / `title` -> first Markdown `# Heading` -> slug -> site title fallback), meta descriptions (`extractMarkdownDescription` from route `description`, frontmatter `description` / `excerpt`, or first paragraph truncated to 160 chars), absolute canonical URLs (`resolveCanonicalUrl`), and Open Graph/Twitter social cards. Client-side SPA navigation in `shadow-claw-pages` dynamically synchronizes `document.title` and restores the site title on home view. Keep routing resolution environment-agnostic (Node.js, Electron, GitHub Pages). Pages containing the `--purge-pages` slug are excluded from pre-rendered static site manifests and DSD output to prevent accidental publication. Client-side route matching uses `isPossibleAppRoute` to validate path compatibility (stripping base path, matching valid top-level pages and pretty paths), ensuring same-origin links to non-app routes (like external demo subpaths) fall back gracefully to native browser navigation. Static routing supports root pretty path resolution (mapping `/` and `/index.html` to `{ page: "pages", groupId: "br:main", path: "index.html" }` and resolving `{ page: "pages" }` back to `/`). In-feed scroll and scroll-spy `replaceState` navigations (`inFeedScroll`, `scrollSpy`, `suppressRouter` in navigation or history state) are guarded against re-triggering SPA route transitions in `getRoute` and `popstateListener`. Slotted sidebar active links synchronize synchronously on scroll via `setupSlottedSidebarActiveLinks` by inspecting `ev.destination.url` (or target URL) across `shadow-claw-feed-scroll` and Navigation API `navigate`, eliminating off-by-one highlighting lags. Feed routes (`/feed/`, `/feed/atom/`, `/feed/rdf/`, `/feed/rss.xml`, `/atom.xml`, etc.) are recognized by `isFeedRoute` and bypassed by SPA routing across `isPossibleAppRoute`, `getRoute`, `fallbackClickListener`, and `resolvePrettyPathToRoute`, navigating directly via `window.location.assign` to native full-page XML views. During bootstrap, caching `initialLocationUrl` and verifying feed presence (`#postsFeed`) alongside history state flags (`inFeedScroll`, `scrollSpy`, `suppressRouter`) in `applyRouteFromCurrentLocation` prevents in-feed scroll state from resetting or triggering unwanted page transitions during feed scroll hydration. `#postsFeed` detection traverses multiple nesting depths — direct DOM, `shadow-claw-pages` shadow root, and `shadow-claw`'s shadow root (including nested `shadow-claw-pages` shadow root) — so feeds hosted inside deeply nested DSD containers are correctly recognized. When any of `inFeedScroll`, `scrollSpy`, or `suppressRouter` flags are present in history state, `OrchestratorStore.init()` treats the pathname as root and pins `activePinnedPage` to `defaultPinnedPage` (rather than restoring the last-visited page), preventing the wrong page from appearing after a feed-scroll reload on a non-root URL.
- **Syndication Feeds (RSS 2.0, Atom 1.0, RDF 1.0):** Configured via `feed.enabled` in `shadow-claw.config.json` (or `feed: true`) or custom `feedPath`. `generateAllFeeds` (`src/cli/site-config/feed/generate-feed.ts`) generates RSS 2.0 (`/feed/rss.xml`, `/feed/index.xml`), Atom 1.0 (`/feed/atom/atom.xml`, `/feed/atom/index.xml`), and RDF 1.0 (`/feed/rdf/index.xml`) syndication feeds, HTML redirect helpers (`/feed/index.html`, `/feed/atom/index.html`, `/feed/rdf/index.html`), and injects `<link rel="alternate">` autodiscovery tags into `index.html` `<head>`. Server static file middleware sets proper `application/rss+xml`, `application/atom+xml`, and `application/rdf+xml` Content-Types.
- **Pre-rendered DSD Shell Override, SSR Block Tokenizer & Cooperative Idle Scheduling:** `OVERRIDE_PRERENDER_SKELETON` (`override_prerender_skeleton`) allows suppressing Declarative Shadow DOM (DSD) shell content on initial load to prevent visual flash before full hydration. Handled during bootstrap in `src/core/theme-init.ts` and `src/components/shadow-claw/shadow-claw.ts`, defaulting to `false` in `src/utils/prerender-skeleton-default.ts` and `shadow-claw.config.json` so pre-rendered DSD content is displayed immediately without skeleton flash. In `src/components/shadow-claw/shadow-claw.html`, the `data-page-id="pages"` container is active by default (`<div class="page active" data-page-id="pages"></div>`) and stamped with `active` during DSD pre-rendering, ensuring pre-rendered SSR page content renders immediately in browsers with JavaScript disabled or prior to client hydration. `buildShadowClawDsdTemplate` and `buildShadowClawDsdTemplateWithoutPages` (`src/cli/prerender/dsd-shell/prerender-dsd-shell.ts`) employ attribute-order-agnostic helper functions (`addClassToTagAttrs`, `removeClassFromTagAttrs`) so host element injection into `<div data-page-id="pages">` and active class manipulation succeed reliably regardless of attribute ordering or minification (e.g. `class="active page"` vs `class="page active"`). During SSR pre-rendering (`prerender-dsd-shell.ts`), `marked` is configured with a custom element block tokenizer so custom elements (tags with hyphens) are treated as block-level HTML and never wrapped in `<p>` tags or split across blank lines. To maintain 98/100+ Lighthouse scores and eliminate main-thread blocking, `seedStaticMainSite` runs synchronously during `init()` using the embedded static manifest, and secondary store loads, Web Worker initialization, and WebMCP registration are deferred cooperatively via `requestIdleCallback` and `yieldToMain()`.
- **In-Place DSD HTML Hydration, CLS Elimination & Image Optimization:** `shadow-claw-pages` preserves pre-rendered Declarative Shadow DOM (DSD) shell content directly during hydration for both Markdown and HTML pages (including root `index.html`), suppressing hidden iframes (`[hidden] { display: none !important; }`) and maintaining container heights (`iframe.style.height = ${rendered.offsetHeight}px`) to prevent layout shifts (CLS < 0.02). `hasExistingRendered` ensures that any visible rendered content (including initial DSD seeds whose `renderedKey` is null on first hydration) triggers the graceful wait-for-iframe-load path, eliminating jarring wide-SSR to narrow-CSR FOUC transitions. In `renderPageHtml`, `optimizeImgTags` parses local image headers without native dependencies (`image-dimensions.ts` for PNG, JPEG, GIF, WebP, SVG) and injects explicit `width` and `height`, assigning `loading="eager" fetchpriority="high" decoding="async"` to the hero image and `loading="lazy" decoding="async"` to subsequent images. `getImageFileDimensions` resolves `node:fs/promises` and `node:path` dynamically via `process.getBuiltinModule` rather than static imports, preventing bundler import-resolution errors in browser client builds. Production builds (`--prod`) pre-compress static assets into sibling `.br` and `.gz` files via `precompressAssets`.
- **Theme Stylesheet Shadow Root Injection:** `prerender-dsd-shell.ts` and `prerender-pretty-paths.ts` inject `<link rel="stylesheet" data-theme-stylesheet="true" href="...">` directly into `<shadow-claw-pages>` DSD templates, and `ensureThemeStylesheet()` in `shadow-claw-pages.ts` injects it during CSR, preventing FOUC inside shadow roots.
- **Configurable Page Rendering Modes & Custom Element Initialization:** By default, HTML pages render in a sandboxed `<iframe>` using `setTrustedSrcdoc` to ensure CSS isolation and script sandboxing. Preview iframes carry `allow="fullscreen; clipboard-write"` so embedded content can use `navigator.clipboard.writeText()` without a SecurityError. Direct shadow DOM rendering is configurable via page frontmatter (`iframe: false`, `render: "shadow"` | `"direct"`, or `shadowDom: true`) or site configuration (`pages.iframe: false`, `pages.render: "shadow"` | `"direct"`, `pages.shadowDom: true`, `pages.directPages`, `pages.shadowDomPages`, with `pages.iframePages` for selective opt-in). When adopting pre-rendered DSD shells or direct shadow DOM rendering, scripts with `hasInit: true` (such as `block-garden-adapter.js`) are dynamically imported with resolved origin URLs and initialized via `init(rendered)` to install BroadcastChannel bridges. Local custom element script paths are normalized to root-relative URLs (`/.agents/...`, `/x.mjs`) across subroutes, and pre-rendering (`buildCustomElementScriptTags`) emits companion inline modules that invoke `init()`. Scripts marked `global: true` are excluded from iframe srcdoc (`scopedScripts = approvedScripts.filter((s) => !s.global)`), preventing duplicate global script execution in sandboxed preview iframes.
- **Anchor Navigation & Smooth Scrolling:** `handleAnchorNavigation` smoothly scrolls `#id` or `a[name="id"]` targets in rendered containers and preview iframes (via `shadow-claw-scroll-to-anchor` postMessage events handled by `file-viewer-preview-bridge.js`), re-scrolling once pending images settle. The router listens for `hashchange` events alongside `popstate`, configures `scroll: "manual"` during navigation interception, and suppresses scroll reset (`resetScroll = false`) when navigating with an anchor in `showPage`.
- **Markdown Frontmatter Visibility:** Markdown preview surfaces can optionally render YAML frontmatter as visible metadata/details blocks. Keep the four frontmatter toggles (`pages`, `file_viewer`, `chat`, `tasks`) and their config keys in sync with the rendering behavior when touching markdown UX.
- **Page Navigation & Sanitization:** Ensure `title` strings passed to headers (like `shadow-claw-page-header`) are sanitized (HTML stripped/escaped). Keyboard navigation (`ArrowLeft`/`ArrowRight`) is throttled (`KEY_NAVIGATION_THROTTLE_MS = 300ms`) to prevent rapid flipping when holding down keys, and both keyboard navigation and swipe gestures must include strict focus guards to prevent interfering with active inputs or selections.

### Agent Skills & Declarative Tools

- **Agent Skills & Canonical Flat Discovery:** Skills are discovered from both the canonical flat `.agents/skills/<name>/SKILL.md` layout (used by the Open Agent Skills ecosystem / `npx skills`) and legacy group-partitioned `.agents/skills/main/<name>/SKILL.md` layout (`src/subsystems/skills/discover-skills.ts`). When the same skill exists in both locations, `discoverSkills` deduplicates them cleanly without duplicate-name warnings while prioritizing the canonical flat layout. Preserve required frontmatter validation, duplicate-name diagnostics, the model-invocation opt-out, and the 2,000-directory discovery limit. Update `docs/subsystems/skills.md` when this contract changes.
- **Open Agent Skills (`npx skills`) & `skills.sh` Ecosystem Integration (`src/cli/commands/agent.ts` & `src/cli/utils/migrate-skills.ts`):** ShadowClaw supports the Open Agent Skills ecosystem ([skills.sh](https://skills.sh) / `npx skills`) with 100% backwards compatibility and graceful degradation:
  - **CLI Management (`shadow-claw skills` / `shadow-claw agent skills`):** Supports `list`, `add <source>`, `remove <name>`, `find [query]`, `init [name]`, `sync`, `update`, `check`, and `restore`. `shadow-claw skills find` queries the [skills.sh](https://skills.sh) registry directly with native fallback. The top-level `shadow-claw skills` command is strictly workspace-scoped without conversation/group flags (`--group`), matching `npx skills` conventions.
  - **Provenance & Lockfile (`skills-lock.json`):** Reads and updates `skills-lock.json` (`readSkillsLock`, `writeSkillsLock`, `removeFromSkillsLock`) so `agent skills` displays provenance tags (`[source: <source>]` vs `[local]`) and `skills restore` can re-hydrate lockfile entries.
  - **Legacy Workspace Migration & Symlink Traversal:** `migrateLegacySkills` (`src/cli/utils/migrate-skills.ts`) automatically migrates older `main/` subdirectories (`.agents/skills/main/*`, `.agents/tools/main/*`, `.agents/scripts/main/*`) into canonical flat directories upon initialization or build. Both `generateSkillsIndex` (`src/cli/commands/skills-index.ts`) and `collectSkillSources` (`src/cli/prerender/dsd-shell/prerender-dsd-shell.ts`) follow symlinked skill directories (`isSymbolicLink()` + `stat()`/`realpath()`) created by `npx skills`.
- **Agent Skills Discovery Index:** `generateSkillsIndex` (`src/cli/commands/skills-index.ts`) generates `.well-known/agent-skills/index.json` complying with Agent Skills Discovery RFC v0.2.0, calculating SHA-256 digests and RFC 3986 relative URLs for skills, tools, and scripts, and emitting a relative `files: ["SKILL.md", ...]` array when a skill directory contains companion resources (`scripts/`, `references/`, `assets/`). The build pipeline (`src/cli/build/build.ts`) automatically generates this index in `dist/public` indexing both content and bundled skills (such as `skill-creator`) using content site metadata, while keeping `.agents/scripts` and repository indexes synchronized. CLI command: `shadow-claw skills:index [dir]`.
- **Declarative Skill Tool Chains:** Skills with `user-invocable: true` support `/skill-name` slash-command routing. Skills with `execution.type: "tools"` dispatch directly to `executeToolChain` on the worker thread via `execute-skill-tools` messages, executing deterministic tool pipelines (with `$pipe` output resolution) without scheduling a Task or calling model LLM prompts. Setting `suppressToast: true` or `suppressOutput: true` on the execution block cascades down to all steps in the tool chain. Default bundled skills include `skill-creator` (with example skills like `toast-random-number` provided in starter templates).
- **Declarative Tools:** Definitions are loaded from `.agents/tools/**/*.json` (and backward-compatible `.agents/tools/main/**/*.json`) and support `bash`, `javascript`, or delegated `tool` executors. Execution is encapsulated in `executeDeclarativeTool` (`src/worker/utils/declarative-tool-executor.ts`). Preserve built-in-name protection, active runtime allowlists, diagnostics for invalid definitions, and the eight-level delegation limit. Declarative tools (such as `generate_random_number.json` in starter templates) can be provided by content repositories. Update `docs/subsystems/tools.md` when this contract changes.
- **JS Tool Expression Evaluation:** `executeJavascript` in `src/worker/tools/ui/javascript.ts` automatically evaluates single expressions without an explicit `return` statement by wrapping them in `return (<expression>);` (with fallback to the raw code if syntax errors occur).
- **Remote Tool & Skill Importing (`import-artifacts.ts`, `discovery.ts` & `agent import`):** Supports discovering and importing tools, skills (including multi-file companion `files` manifests), and companion scripts from RFC v0.2.0 discovery manifests, direct `SKILL.md` URLs, GitHub `blob/` or `tree/` URLs, GitHub `owner/repo` and `owner/repo@skill` shorthands, and local filesystem directories into `.agents/tools/`, `.agents/skills/`, and `.agents/scripts/` in both the user's browser OPFS workspace and host filesystem CLI workspace (`shadow-claw agent import <source> [options]`) with SHA-256 verification, selective filtering (`--tools`, `--skills`, `--scripts`, `--all`), and auto-enablement. For GitHub shorthand or repo sources without an RFC v0.2.0 `index.json`, `agent import` delegates to `npx skills add` and installs into `.agents/skills/<name>/`, degrading gracefully to native HTTP discovery if `npx` is unavailable. Declarative JavaScript tools execute headlessly in Node.js environments using the `node:vm` sandbox fallback in `sandboxed-eval.ts`.
- **Runtime vs. Build-Time Security Boundaries (Never Suggest Inline Scripts):** Imported tools and scripts execute headless logic in Web Workers immediately. However, client-side OPFS files and scripts **cannot** dynamically register custom elements in the browser, punch through CSP, or inject scripts into preview iframes.
  - **Never** instruct users to insert `<script>` or `<script type="module">` tags into HTML/markdown documents—DOMPurify strips them unconditionally and the preview iframe blocks un-nonced scripts.
  - Custom elements (`<block-garden>`, `<x-pwgen>`), bundle URLs, companion adapters (`{ src: "...", hasInit: true }`), and external domains must be configured in `shadow-claw.config.json` under `customElements` and `security.connectSrc`.
  - For live IPC tools using `BroadcastChannel` (e.g., `/fireworks`), the page hosting the custom element must remain **pinned in view** (in Pages or Split View) to keep the iframe mounted while chatting.

### Custom Element Security & Iframe Sandboxing

- **Custom Element Guards:** `installCustomElementsRegistryGuard` and `installCustomElementDomGuard` (`src/security/custom-element-security.ts` and modular `src/security/custom-element-guard.ts` with `parse-host-pattern-match.ts`) intercept unauthorized custom element registrations and dynamically strip unapproved custom elements from the DOM tree. The modular guard allows early boot scripts (`src/core/theme-init.ts`) to initialize custom element security without bundling heavy HTML sanitization or CSP dependencies. Only core elements (`shadow-claw` and `shadow-claw-*`) or elements explicitly allowlisted via `shadow-claw.config.json` (or legacy `site-config.json`) or `CONFIG_KEYS.ALLOWED_CUSTOM_ELEMENTS` are permitted. `loadCustomElementSecurityFromDb` and `OrchestratorStore.applySiteConfigDefaults()` merge embedded `#shadow-claw-site-config` `allowedElements` and `allowedDomains` with persisted IndexedDB entries via `mergeAllowlistValues` so deployments adding new custom elements never fail against stale persisted allowlists.
- **Iframe Sandboxing & CSP:** Sandboxed preview iframes omit `allow-same-origin` by default to enforce opaque-origin (`null`) isolation and eliminate Chrome sandbox escape warnings, using a nonce-gated Content Security Policy with domain restrictions generated via `getIframeCsp(nonce)`. Persistent storage for sandboxed custom elements (`IndexedDB` and `localStorage`) is provided via a transparent `postMessage` storage proxy bridge (`iframe-storage-bridge.js`) handled by `dispatch-storage-proxy-command.ts` and `iframe-storage-proxy.ts`.
- **Iframe Attribute Cleanups:** When rendering preview iframes (such as in `shadow-claw-pages` and `shadow-claw-file-viewer`), rely on `allow="fullscreen"` and omit redundant `allowfullscreen` boolean attributes to avoid browser DevTools precedence warnings.
- **Approved Script Loading, Descriptors & Page Dependencies:** Dynamic loading of custom element scripts is restricted to safe protocols and validated host patterns using `loadApprovedCustomElementScript`. Custom element scripts (`customElements.scripts`) support string URLs and object descriptors (`{ id?: string, name?: string, src: string, global?: boolean, autoload?: boolean, hasInit?: boolean, type?: string, async?: boolean, defer?: boolean }`, standardized on `src`). Scripts marked with `global: true` or `autoload: true` are automatically injected on every page. Specific script dependencies can be requested in page frontmatter via `dependencies:` or `scripts:` (by `id`, `name`, filename, or stem). Furthermore, `resolvePageScriptDependencies` automatically scans markdown content for custom element tags (e.g. `<x-postpress-code`) and inline `<script src="...">` tags, auto-resolving them against approved descriptors. Pre-render pipelines (`prerender-pretty-paths.ts`, `prerender-dsd-shell.ts`) inject resolved scripts into `<head>` with deduplication, and `shadow-claw-pages.ts` loads them during client-side navigation. Unapproved or missing script IDs degrade gracefully without failing builds or rendering. Legacy configs omitting `id` remain 100% backward compatible via path, filename, and stem matching. The sandboxed preview iframe invokes `init()` exclusively when `hasInit: true` is explicitly configured (`if (typeof m?.init === "function") m.init();`). Helpers: `getApprovedCustomElementScriptDescriptors()` and `getApprovedCustomElementScripts()`.

### Component Lifecycle & Storybook Workbench

- **Observed Attributes on Custom Elements:** Custom elements extending `ShadowClawElement` that dynamically react to attribute modifications must declare `static observedAttributes` (for example, `ShadowClawEmptyState` observing `["message", "hint", "compact", "warning"]`) so `attributeChangedCallback` triggers component re-rendering.
- **Storybook Workbench:** Storybook (`npm run storybook` on port 6006, `npm run build:storybook` for static output in `dist/storybook`) uses `@storybook/web-components-vite` (v10) with custom HTML/CSS import attribute handling. Add co-located `*.stories.ts` files for UI components. Storybook defaults to dark mode (`.storybook/preview.ts`), covers all 18 A2UI catalog components (`shadow-claw-a2ui.stories.ts`), and isolates component visual verification from end-to-end integration tests.
- **Toast Inline Mode & Instance API:** `<shadow-claw-toast>` supports an `inline` attribute (`:host([inline])`) for non-fixed rendering inside documentation or story environments, and exposes a `.show(message, options)` instance method alongside `showToast` and `toastStore`.

### Declarative Configuration, Storage Namespacing & Dynamic Navigation

- **Declarative Configuration (`shadow-claw.config.json`):** Template repositories configure metadata, branding, tool defaults (`defaultToolsProfile`, `enabledTools`), custom element allowlists, navigation visibility, custom stylesheets (`theme.stylesheet`), and server/cache storage (`cacheDir`, `server.cacheDir`) via `shadow-claw.config.json` (a superset format with backward compatibility for legacy `site-config.json`), which is patched into production artifacts at build time via `src/cli/site-config/apply.ts` and seeded into IndexedDB at runtime via `applySiteConfigDefaults()`. Base path resolution (`resolveSiteBasePath` and `patchBaseHref` in `src/cli/site-config/apply.ts`) resolves the canonical `<base href="...">` from `--base-path` / `PAGES_BASE_PATH`, `--origin` / `PAGES_ORIGIN` pathname, or `branding.siteUrl` pathname, and applies it consistently across `dist/public/index.html` and all pre-rendered pretty-path `index.html` files (`src/cli/build/build.ts`, `src/cli/prerender/pretty-paths/prerender-pretty-paths.ts`). `patchIndexHtml` in `src/cli/site-config/apply.ts` synchronizes root `index.html` head tags via `patchHtmlHeadMetadata` (`src/utils/seo.js`), updating canonical links (`<link rel="canonical">`), Open Graph tags (`og:title`, `og:description`, `og:url`, `og:image`), and Twitter Card metadata (`twitter:title`, `twitter:description`) whenever `site` metadata or `branding.siteUrl` is provided. Injects Apple Home Screen Web App meta tags (`apple-mobile-web-app-capable`, `mobile-web-app-capable`, `apple-mobile-web-app-status-bar-style`, `apple-mobile-web-app-title`, `application-name`) into `index.html` and `share/share-target.html`, supports `pwa.id` (with automatic template slug derivation) and `pwa.scope` for isolated PWA installation, and normalizes SVG `appleTouchIconPath` to raster PNG (`180.png`). Build isolation ensures default ShadowClaw red lobster screenshots and icons never leak into consumer template distributions. Setting `branding.logoSlotHtml` to `'none'`, `''`, or `null` strips the header logo and resets left margin on `.header-title`.
- **Custom Stylesheet Injection & Theming:** Custom stylesheets declared under `theme.stylesheet` (e.g. `pages/main/theme.css`) are copied into `dist/public` and injected before `</head>` into `dist/public/index.html` and pre-rendered pretty path files. Tag injection uses `findClosingHeadIndex` (`src/cli/prerender/utils/insert-before-closing-head.ts`) to avoid falsely matching `</head>` literals inside inlined `<script>`, `<style>`, `<template>`, or comment blocks.
- **Layout Tokens & Shell Visibility Overrides:** Built-in web components reflect CSS Custom Properties. Sites can selectively hide default shell chrome or adjust branding dimensions by defining layout override variables in their custom stylesheet: `--shadow-claw-sidebar-footer-display: none;` (hides Settings footer), `--shadow-claw-header-main-toggle-display: none;` (hides header menu toggle), `--shadow-claw-page-header-display: none;` (hides page header), `--shadow-claw-logo-size: 1.5rem;` (controls header logo dimensions), and `--shadow-claw-logo-margin: 0 0 0.375rem;` (controls logo spacing).
- **Light DOM vs. Shadow DOM Styling Boundaries:** Slotted elements (`[slot="sidebar"]`, `.sidebar-custom-sections`, `[slot="header-actions-logo"]`) live in the Light DOM and must be styled with standard CSS rules in `theme.stylesheet`. Set `.sidebar-custom-sections { max-height: calc(100dvh - 4rem); overflow-y: auto; }` and `html:has(shadow-claw), body:has(shadow-claw) { height: 100dvh; overflow: hidden; }` to ensure scrolling sidebars never produce dual window scrollbars.
- **Theme Synchronization & Preview Iframes:** `.light-mode` and `.dark-mode` classes are synchronized directly onto `document.body` in addition to `document.documentElement` across the main application (in both early bootstrap `src/core/theme-init.ts` and `src/stores/theme.ts`) and sandboxed preview iframes (`file-viewer-preview-bridge.js`, `build-html-page-srcdoc.ts`), including `style.colorScheme` updates. Sandboxed preview iframes automatically load `theme.stylesheet` via `getIframeThemeStylesheetLink()` and mirror computed CSS custom properties via `getIframeThemeStyleHtml()` (`src/ui/iframe-theme.ts`), preserving consistent colors, typography, and dark/light modes.
- **Per-Deployment Storage Namespacing:** Use `namespacedStorage` for `localStorage` keys and `getDbName()` / `getOpfsRootName()` for IndexedDB/OPFS namespacing per deployment namespace (`getDeploymentNamespace()`) to prevent state leakage across subpath deployments. Legacy database stores are automatically migrated via `migrate-legacy-database.ts` and `migrate-legacy-opfs.ts`.
- **Dynamic Sidebar Navigation:** Sidebar navigation items (Pages, Chat, Tasks, Files) support runtime toggling and build-time DSD hiding. Ensure navigation fallback logic (`getDefaultSidebarPage`) resolves to the next visible item when active pages are hidden.
- **Slotted Sidebar & Custom Navigation:** `<shadow-claw>` exposes named slots for sidebar customization: `sidebar-nav`, `sidebar`, `sidebar-content`, and `sidebar-footer`. `shadow-claw.config.json` supports declarative sidebar configuration via `sidebar.slotHtml`, `sidebar.slotPath`, `sidebar.sections` (with nested items/links), or automatic discovery of `pages/main/sidebar.html` (or `sidebar.html`). Slotted navigation links automatically sync active state and `aria-current="page"` via `syncSlottedSidebarActiveLinks` on route and navigation changes, and automatically collapse the mobile sidebar drawer upon click.

### CLI, Headless Agent Participant & Dual-Root Build Pipeline

- **Dual-Root Path Resolution:** The build toolchain (`src/cli/build/build.ts`, invoked via `bin/build.mjs`) cleanly decouples `toolchainRoot` (the ShadowClaw package/repo root resolved dynamically via `getProjectRoot` in `src/cli/utils/resolve-project-root.ts`) from `contentRoot` (the consumer template project). In-repo builds (`resolve(contentRoot) === resolve(toolchainRoot)`) preserve the standalone in-tree compilation path. CLI/template consumer builds read pre-bundled web assets from `toolchainRoot/dist/public` (excluding local model cache directories) and inject `pages/`, `shadow-claw.config.json` (or `site-config.json`), `assets/`, `.agents/`, and pretty routes from `contentRoot`, outputting to `<contentRoot>/dist/public`. Library entry points across components and utilities are dynamically discovered in `configs/rolldown/rolldown.config.mjs` via `getLibraryEntries()`.
- **Standalone Single-File Builds & Companion Service Worker (`--single-file`, `--service-worker`):** `shadow-claw build --single-file` compiles markdown pages, theme stylesheets, and configuration into a standalone `dist/public/index.html`. Passing `--service-worker` emits a companion `service-worker.js` with content-hashed revision stamping (`// build: <sha256>`), network-first caching for navigation (`index.html`), and stale-while-revalidate caching for CDN runtime assets (`generateSingleFileServiceWorker`), alongside an inline registration script (`generateSingleFileSwRegistration`, `data-shadow-claw-sw="true"`) that mirrors the full update check, Trusted Types script URL wrapping, and UI dialog prompt flow. Single-file builds strip stale local modulepreload and script tags and warn on unpinned CDN URLs (`@latest`, `@next`).
- **CLI Commands (`src/cli/cli.ts`):** The `shadow-claw` / `shadowclaw` CLI is authored in TypeScript under `src/cli/` and bundled via Rolldown into `dist/cli/` (`npm run build:cli`), with thin entrypoint scripts in `bin/` (`bin/cli.mjs`). It provides `agent` (subcommands: `init`, `model`, `skills`, `tools`, `tool`, `skill`, `import`, `run`, `listen`), `skills` (top-level alias for `agent skills`: `list`, `add`, `remove`, `find`, `init`, `sync`, `update`, `check`, `restore`), `icons`, `build`, `dev`, `run`, `serve`, `server` (aliases: `services`, `api`), `init`, `clients`, `send`, `send-file`, `backup`, `tasks`, `mcp`, `skills:index`, `webrtc`, and `peer-id` commands. It supports running dev and headless service servers programmatically via `startServer` (`src/server/server.ts`) with custom `--root-path`, `--cache-dir <dir>`, and `--database-dir` arguments.
- **Headless CLI Agent Participant (`shadow-claw agent`):**
  - **Runtime Mode Flag:** Module-level `isHeadlessMode()` and `setHeadlessMode()` (`src/config/headless.ts`) signal headless server-side execution to tools and storage.
  - **Dual-Dispatch Storage Backend:** `ShadowClawDatabase` is widened to `IDBDatabase | ShadowClawSqliteDatabase | null` (`src/db/types.ts`). In headless mode, `openSqliteDatabase()` creates/opens an SQLite database mirroring the 5 IndexedDB stores (`messages`, `sessions`, `tasks`, `config`, `pendingShares`). `tx-promise.ts` routes IDB operations to SQL statements automatically.
  - **Filesystem Storage Backend & Workspace Isolation:** `NodeFsDirectoryHandle` (`src/storage/node-fs-handle.ts`) implements `FileSystemDirectoryHandle` and `FileSystemFileHandle` backed by `node:fs`. Writable streams support strings, `Uint8Array`, `ArrayBuffer`, `Blob`, and `WriteParams`. Both handles implement `isSameEntry()` and throw spec-compliant errors (`TypeMismatchError`, `NotFoundError`, `InvalidModificationError`). Both `_resolveChild` and `parsePath` strictly guard against backwards path traversal (`..` or root escaping) with `SecurityError`. When no `--workspace` is explicitly passed, headless agent bootstrap, init, and WebRTC listener isolate file operations inside an OS sandbox (`<tmpdir>/shadow-claw/workspace`) rather than exposing `.cache` or `process.cwd()`.
  - **Group Separation:** Server and CLI execution defaults to `server:main` (`DEFAULT_SERVER_GROUP_ID` in `src/config/config.ts`), preserving `br:main` for browser sessions.
  - **Peer Collaboration & WebRTC Orchestration (`agent listen` / `webrtc listen`):** CLI instances can register as PeerJS WebRTC peers to accept remote prompts, execute the orchestration loop (`runAgentRun`), exchange files via `send-file` or `send --file`, and coordinate autonomously via `prompt_peer`, `list_peers`, and direct `send_file(path, peer_id)` tools.
  - **Tool Capability Matrix & Schema Filtering:** Environment-agnostic tools execute natively headlessly. Browser-only tools (`BROWSER_ONLY_TOOLS`: `ask_user`, `attach_file_to_chat`, `clear_chat`, `create_room`, `invite_to_room`, `leave_room`, `list_components`, `list_room_members`, `open_file`, `render_component`, `show_toast`, `send_notification`, `spawn_subagent`) are filtered out of prompt schemas and function calling declarations in headless mode, and gated in `executeTool` to return actionable diagnostic errors rather than hanging or crashing.
  - **Native AI Task Execution:** Headless execution of built-in AI tasks (`summarize_text`, `rewrite_text`, etc.) is delegated via `handleNativeAiTaskMessage` (`src/cli/commands/native-ai-task-handler.ts`), resolving pending promises via global resolvers.
  - **Host OS Bash Execution & Process Confinement:** In headless mode, `bash` uses `node:child_process` directly via `native-bash-executor.ts`, providing real OS shell access. The child process working directory is strictly bound to the active workspace storage root (`getStorageRootPath()`).
  - **Direct Git Connections in Headless Mode:** In headless Node.js environments, `resolveCorsProxy` returns `undefined` by default to bypass browser CORS proxies for direct HTTPS operations (`gitClone`, `gitPull`, `gitPush`, `gitFetch`), while respecting explicit proxy configurations. `initGitFs` guards checks against `navigator.storage` to avoid runtime TypeErrors in Node.js.
  - **Direct Tool Inspection & Execution:** `shadow-claw agent tools` lists tools with capability tags; `shadow-claw agent tool <name> [jsonArgs]` inspects schemas or directly executes a tool against the workspace with stdin piping and plain-text parameter auto-mapping.
  - **Local Model Management (`shadow-claw agent model`):** Dedicated subcommands (`list`, `remote` / `-r` / `--hf`, `download`, `set`) inspect local cached models with recursive directory verification (excluding `.part` and `.tmp` files), query Hugging Face `onnx-community`, download weights with terminal progress bars (`src/cli/utils/progress-bar.ts`), and set workspace defaults.
  - **Interactive Model Selection & Prewarming:** `shadow-claw agent init` provides an interactive terminal model picker for headless workspaces with optional instant downloading (`--download`), supporting paginated (25 items/page) and searchable Hugging Face ONNX model browsing with in-memory session caching.
  - **Execution Flags, File Attachments & Streaming (`shadow-claw agent run`):** Supports `--stream` / `--no-stream`, `--progress` / `--no-progress`, download confirmation guards (`--download`, `-y` / `--yes`), custom system prompts (`--system-prompt`, `--system-prompt-file`, `--no-system-prompt` / `--system-prompt none`), `--no-history`, and tool filtering (`--tools`, `--tools-profile`). Repeatable `-f, --file <path>` flags attach local files to prompts with modality size limits (`MAX_NATIVE_IMAGE_BYTES` = 3 MB default, configurable via `--max-image-size <MB>` or `maxImageBytes`; audio = 5 MB; document = 20 MB; text inlining = 100 KB) that fall back to text references with `stderr` warnings when exceeded. Provider `streaming-error` events surface as process failures (`success: false`, exit code 1).
  - **Node-Native Offline Model Executors:** In headless mode, `handleInvoke` passes formatted messages with system prompts directly to `node-transformers-executor.ts` (running ONNX models in-process via `@huggingface/transformers` without requiring a browser or proxy server) and `node-llamafile-executor.ts` (managing host Llamafile and Agentfile binaries directly via `LocalBinaryDriver`).
  - **Termination Cleanup & Signal Handling:** Process signals (`SIGINT` code 130, `SIGTERM` code 143, and `exit`) are intercepted via `registerTerminationCleanup` in `src/cli/cli.ts` and `agent run` signal handlers with force-exit timeouts to ensure background child processes (such as spawned llamafiles or server listeners) terminate cleanly.
  - **Warning Suppression:** Node's experimental SQLite warnings are automatically intercepted via `src/cli/utils/suppress-warnings.ts`.
- **Provider & Model Precedence Hierarchy:**
  Default LLM provider and model resolution follows a strict cascade:
  1. CLI option: `--provider <name>` / `--model <model>`
  2. Environment variable: `SHADOW_CLAW_PROVIDER` / `SHADOW_CLAW_MODEL` (alongside provider-specific keys like `OPENROUTER_API_KEY`, `HUGGINGFACE_API_KEY`, `GEMINI_API_KEY`, `ANTHROPIC_API_KEY`)
  3. Database configuration: `CONFIG_KEYS.PROVIDER` (`"provider"`) / `CONFIG_KEYS.MODEL` (`"model"`)
  4. Declarative workspace config: `agent.defaultProvider` / `agent.defaultModel` or `settings.defaultProvider` / `settings.defaultModel` in `shadow-claw.config.json`
  5. Default fallback: `"transformers_js_local"` with `"onnx-community/gemma-4-E2B-it-ONNX"` (offline local default) or `"openrouter"` with `"openrouter/free"`.
     When executing `agent run`, missing credentials or provider API failures print clear actionable guidance to `stderr` and exit with code `1`.
- **Cache Directory Selection & Storage Paths:** When launching `dev`, `run`, `serve`, or `server` and no existing cache is detected, ShadowClaw displays an upfront skip tip and interactively prompts to select between the current working directory (`.cache`), system temporary storage (`node:os` `tmpdir()`), or a custom directory. Prompting can be skipped via `--tmp`, `-y`, `--cache-dir <dir>`, `SHADOWCLAW_TMP`, or `SHADOWCLAW_CACHE_DIR`. Cancellation via SIGINT / Ctrl+C is caught cleanly without error traces. All server storage paths (SQLite databases under `<cacheDir>/database`, TLS certs under `<cacheDir>/tls`, logs under `<cacheDir>/logs`, backups under `<cacheDir>/backups`, control tokens at `<cacheDir>/control-token.json`, and WebRTC IPC sockets at `<cacheDir>/webrtc-ipc.sock`) resolve under the configured `<cacheDir>`. On server start, control token files are also mirrored to `<tmpdir>/shadow-claw/control-token[-<port>].json` for cross-directory auto-discovery.
- **HTTPS & Control Plane:** Dev/run/serve/server commands accept `--https`, `--cert <path>`, `--key <path>`, and `--ssl-dir <path>` for opt-in HTTPS with auto-generated self-signed certs; control plane commands (`clients`, `send`, `backup`, `tasks`, `mcp`) accept `--https` and `-k, --insecure` to reach an HTTPS control plane server. Control clients automatically discover tokens from flags, `SHADOWCLAW_CONTROL_TOKEN`, system temp files, parent directory trees, and SQLite, and automatically retry across remaining candidate tokens on HTTP 401 Unauthorized responses.
- **Stateless MCP Server & Tri-Tier Tool Architecture:** The MCP server engine (`src/cli/commands/mcp.ts`, `src/server/mcp/`) implements the official Stateless Model Context Protocol (2026-07-28) with a tri-tier hierarchy:
  1. `shadowclaw_server_*`: Built-in server management tools (`shadowclaw_server_list_clients`, `shadowclaw_server_send_message`, `shadowclaw_server_status`).
  2. `shadowclaw_local_*`: Host-native CLI agent tools (`read_file`, `write_file`, `bash`, `list_files`, `git_*`) executing directly against host filesystem handles with workspace sandboxing and backwards traversal protection. Enabled by default in `mcp` mode (`--local-tools`), with configurable prefixes (`--tool-prefix local|none`), tool filtering (`--tools`), and profiles (`--tools-profile`). Unprefixed tool calls fallback to host-native local tools when no client is connected.
  3. `shadowclaw_client_*`: Relayed tools from connected browser clients dynamically discovered over the Control Plane (`shadowclaw_client_read_file`, `shadowclaw_client_javascript`), with legacy aliases and client-specific routing (`clientId`).
     Interactive tools like `ask_user` are relayed directly or handled via MRTR (`resultType: "input_required"`). STDIO mode preserves JSON-RPC framing by directing all logs and warnings strictly to `stderr`.
- **Naming Conventions:** Refer to the product/brand in prose and documentation as **ShadowClaw**. Use kebab-case **`shadow-claw`** for package name, CLI commands (`npx shadow-claw`), repositories, directory paths, and custom elements.

### Files Browser Safeguards & Workspace Transfers

- Directory operations enforce recursive ancestor checks to prevent self-paste and nesting loops (cannot paste a directory into itself or its descendants).
- File and folder operations support moving and copying across different conversation groups (`sourceGroupId` $\rightarrow$ `targetGroupId`).
- Destination name collisions present non-destructive rename or overwrite dialog choices.
- Peer and Room File Sharing: Files displayed in `<shadow-claw-files>` conditionally expose a "Send to peer" / "Send to room peers" action button (`.files__send-peer`) and `<shadow-claw-file-viewer>` provides a Share dropdown menu (`.modal-share-dropdown`) with peer transfer options when the active conversation is a peer (`peer:...`) or room (`room:...`). These sharing options are strictly hidden in standard non-peer conversations. File transfers dispatch through `orchestratorStore.sendFileToPeer()`, streaming in 64 KB chunks over WebRTC DataChannels with typing indicators and local message persistence.

### Web Share Target API Integration

- Declaratively registered in `manifest.json` targeting `share/share-target.html` (POST multipart/form-data) to receive text, URLs, and files from OS share sheets.
- Intercepted by the Service Worker (`src/service-worker/share-target.ts`), storing binary/metadata records into IndexedDB `pendingShares` and redirecting with HTTP 303 to `/?shared=1`.
- Consumed on application launch by `process-pending-shared-payloads.ts` and `src/share-target/pending-shares.ts`, creating or locating a dated conversation group (`br:shared-YYYY-MM-DD`) and persisting imported files directly into OPFS workspace storage.

### Provider Runtime Overrides & Token Metrics

- Conversations support fine-grained runtime overrides for local engines and cloud proxies via `providerRuntimeOverrides` in group metadata, including AWS Bedrock (`authMode`, `profile`, `region`) and Llamafile (`host`, `mode`, `offline`, `port`).
- Token metrics and prompt caching statistics (cache read hits, cache creation) are captured from provider responses and tracked in `StreamAccumulator` (`src/worker/stream-accumulator/stream-accumulator.ts`).

## What to Avoid

- **Do not** add a frontend framework (React, Vue, Svelte, etc.).
- **Do not** call `indexedDB` or `navigator.storage.getDirectory()` directly — use `src/db/db.ts` and `src/storage/storage.ts`.
- **Do not** `postMessage` to the worker with ad-hoc shapes — use the typed protocol in `docs/architecture/worker-protocol.md`.
- **Do not** store API keys in plaintext — always go through `src/security/crypto.ts`.
- **Do not** import Electron modules from browser-side `.ts` files — Electron is desktop-only.
- **Do not** register or inject unapproved custom elements without configuring them through `shadow-claw.config.json` (or `site-config.json`) or `setAllowedCustomElements`.
- **Do not** rely on `navigator.modelContext` alone for WebMCP detection; prefer `document.modelContext` with `navigator.modelContext` fallback for compatibility. Use `parseWebMcpInputSchema` to normalize schemas across Chrome 154+ (native object) and Chrome < 154 (DOMString JSON) versions, validate tool execution output against optional `outputSchema` / `output_schema` via `validateWebMcpOutput`, and use `getWebMcpTools` for querying registered tools with graceful degradation.
- **Do not** commit `dist-electron/`, `push-subscriptions.db`, `scheduled-tasks.db`, or `clients.db` — they are git-ignored.
- **Do not** add new docs pages without updating `docs/README.md` and verifying references in `AGENTS.md`.
- **Do not** allow file-browser copy/move flows to target the same folder or any descendant folder; enforce the guard in both UI and storage paths and cover it with tests. Always specify both `sourceGroupId` and `targetGroupId` when invoking storage moves/copies.
- **Do not** use raw `window.location.href` or traditional link anchors for internal navigation. Always dispatch a `shadow-claw-navigate` custom event (or use the `handleSpecialLinkNavigation` utility) to switch pages, open files, or scroll to anchors seamlessly.
- **Do not** bypass the proxy SSRF guard by passing `allowPrivate: true` in code — this is only for the `--allow-private-proxy` CLI flag path. Service-worker JSON requests use the `fromServiceWorker` heuristic automatically.
- **Do not** return raw external content from a new tool without first wrapping it with `wrapUntrustedContent` (`src/worker/utils/wrap-untrusted-content.ts`). Any tool that fetches web pages, emails, API responses, or remote MCP results must apply this wrapping so the LLM receives a structural signal that the content is untrusted data, not instructions.
