## License
diff --git a/THREAT_MODEL.md b/THREAT_MODEL.md
index d63d1335b..ba4999157 100644
--- a/THREAT_MODEL.md
+++ b/THREAT_MODEL.md
@@ -60,13 +60,11 @@ External content that reaches the LLM is treated as untrusted via `src/prompt_se
**Untrusted surfaces that must go through this wrapper:** web search results, fetched URLs, emails (read), saved memories, skill text, notes, and any tool output sourced from outside the server. Injecting untrusted content directly into the system role is a security bug.
-### Post-external-context tool approval gate — off by default
+### Post-external-context tool approval gate — on by default
`src/tool_capabilities.py` carries a second layer: once untrusted content has entered a run, `ToolRunSecurityContext.decision_for()` blocks tools that execute code, mutate state, or cause external side effects until the user authorises the action separately.
-**It is disabled unless `ODYSSEUS_TOOL_APPROVAL_GATE` is set** (`1`/`true`/`yes`/`on`). The default is off because the gate is conservative enough to interrupt ordinary agent work. That is a deliberate usability trade, and it means a default deployment relies on the wrapper above — not on the gate — to contain injected instructions.
-
-Operators who run the agent against untrusted web or email content with side-effecting tools enabled should turn it on. With the gate off, a successful injection can reach `bash`, `host_shell`, `send_email` and `delete_email` without a separate confirmation; with it on, each of those is refused until approved.
+It is on unless `ODYSSEUS_TOOL_APPROVAL_GATE` is set to a falsy value (`0`/`false`/`no`/`off`). Request authority narrows which tool families a turn may use, but within an admitted family it does not bind the exact action: a request to read email admits `send_email` and `delete_email`, and agent processes inherit the host network. Until those are covered by their own boundaries, this gate is what stops an injected instruction from reaching them. Turning it off lets a successful injection reach `bash`, `host_shell`, `send_email` and `delete_email` without a separate confirmation.
Two exemptions apply even when the gate is on, both deliberate:
@@ -85,7 +83,7 @@ Two exemptions apply even when the gate is on, both deliberate:
These are open, acknowledged, and contributor help is welcome:
-1. **No shell/filesystem sandbox.** The agent `bash` and `read_file`/`write_file` tools run as the app process user with no network egress filtering or filesystem confinement. A successful prompt-injection reaching a shell-enabled admin session can make outbound requests to internal services. See #1058 for the sandbox proposal. The tool approval gate above is the compensating control, and it is off by default — so on a default deployment this gap is unmitigated beyond the untrusted-context wrapper.
+1. **No shell/filesystem sandbox.** The agent `bash` and `read_file`/`write_file` tools run as the app process user with no network egress filtering or filesystem confinement. A successful prompt-injection reaching a shell-enabled admin session can make outbound requests to internal services. See #1058 for the sandbox proposal. The tool approval gate above is the compensating control and is on by default; turning it off leaves this gap unmitigated beyond the untrusted-context wrapper.
2. **SSRF via `/api/v1/chat` `base_url` parameter.** A chat-scoped API token can supply an arbitrary `base_url`; the server forwards the LLM request to that host without validating the scheme or address. PR #1039 fixes this.
diff --git a/app.py b/app.py
index 5215966fb..ae859a579 100644
--- a/app.py
+++ b/app.py
@@ -178,6 +178,14 @@ app.add_middleware(SecurityHeadersMiddleware)
import asyncio as _asyncio
from starlette.middleware.base import BaseHTTPMiddleware as _BaseHTTPMiddleware
from starlette.responses import JSONResponse as _JSONResponse
+import anyio as _anyio
+from starlette.requests import ClientDisconnect as _ClientDisconnect
+
+# SSE endpoints (e.g. /api/editor/bridge/events) end/abort mid-stream when the
+# browser disconnects; Starlette's BaseHTTPMiddleware surfaces that as
+# anyio.EndOfStream (and sometimes ClientDisconnect). Those are client-side
+# events, not server errors, so we map them to a 499 instead of a 500 traceback.
+_STREAM_CLIENT_EXC = (_anyio.EndOfStream, _ClientDisconnect)
REQUEST_HARD_TIMEOUT = float(os.getenv("REQUEST_HARD_TIMEOUT", "45"))
_TIMEOUT_EXEMPT_PREFIXES = (
@@ -190,6 +198,7 @@ _TIMEOUT_EXEMPT_PREFIXES = (
"/api/cookbook/setup", # remote pacman/apt installs
"/api/upload", # large files
"/api/image", # diffusion proxies (inpaint/harmonize/upscale/etc.) — own 120s httpx timeout
+ "/api/editor", # editor agent/bridge: generative steps can take 30-110s (SAM + local diffusion)
"/api/memory/audit", # retains own 120s LLM inactivity timeout
)
@@ -225,15 +234,43 @@ class _InteractiveActivityMiddleware(_BaseHTTPMiddleware):
return await call_next(request)
+# Heavy image ops that can run 30-150 s; a deploy restart must not cut these off.
+_HEAVY_IMAGE_OP_PREFIXES = (
+ "/api/image/inpaint",
+ "/api/image/replace-background",
+ "/api/image/outpaint",
+ "/api/image/extend",
+ "/api/image/remove-bg",
+ "/api/image/mask",
+ "/api/image/upscale-local",
+ "/api/image/denoise",
+ "/api/image/enhance-face",
+ "/api/gallery/ai-upscale",
+ "/api/gallery/style-transfer",
+ "/api/editor/agent",
+)
+
+
class _SlowRequestLogMiddleware(_BaseHTTPMiddleware):
async def dispatch(self, request, call_next):
+ from src import activity
+ path = request.url.path or ""
+ heavy = any(path.startswith(p) for p in _HEAVY_IMAGE_OP_PREFIXES)
+ if heavy:
+ activity.begin_image_op(path)
start = time.perf_counter()
status = 500
try:
response = await call_next(request)
status = getattr(response, "status_code", 0) or 0
return response
+ except _STREAM_CLIENT_EXC:
+ # Client disconnected / SSE stream ended — not a server error.
+ status = 499
+ return _JSONResponse({"detail": "client disconnected"}, status_code=499)
finally:
+ if heavy:
+ activity.end_image_op(path)
elapsed = time.perf_counter() - start
try:
threshold = float(os.getenv("ODYSSEUS_SLOW_REQUEST_LOG_SECONDS", "0.75") or "0.75")
@@ -516,28 +553,69 @@ app.mount("/static", _RevalidatingStatic(directory=STATIC_DIR), name="static")
@app.get("/api/generated-image/{filename}")
async def serve_generated_image(filename: str, request: Request):
"""Serve generated images from the data directory."""
- img_path = resolve_generated_image_path(filename)
- # SECURITY: filename is the only key, so anyone who knows / guesses a
- # 12-hex content hash could pull another user's image bytes. Require
- # auth and verify ownership via the gallery row (when one exists).
- try:
- from src.auth_helpers import get_current_user
- from core.database import SessionLocal as _SL, GalleryImage as _GI
- _user = get_current_user(request)
- if _user:
- _db = _SL()
+ # 1. Validate filename syntax upfront, rejecting malformed requests (400)
+ # without probing the filesystem or database.
+ from src.generated_images import GENERATED_IMAGE_RE
+ if not isinstance(filename, str) or not GENERATED_IMAGE_RE.fullmatch(filename):
+ raise HTTPException(status_code=400, detail="Invalid filename")
+
+ # 2. Ownership verification:
+ # If auth is enabled, verify caller identity and ownership BEFORE probing disk,
+ # preventing existence oracles during outages or unauthorized requests.
+ from src.auth_helpers import auth_disabled, effective_user
+ if not auth_disabled():
+ _user = effective_user(request)
+ if not _user:
+ raise HTTPException(status_code=401, detail="Not authenticated")
+
+ from src.generated_images import get_registered_image_owner
+ _reg_owner = get_registered_image_owner(filename)
+ if _reg_owner is not None:
+ if _reg_owner != _user:
+ raise HTTPException(status_code=404, detail="Image not found")
+ else:
try:
- _row = _db.query(_GI).filter(_GI.filename == filename).first()
- # Generated-but-not-yet-imported images have no row → allow.
- # Row exists with a different owner → 404 (don't confirm existence).
- if _row is not None and _row.owner and _row.owner != _user:
- raise HTTPException(status_code=404, detail="Image not found")
- finally:
- _db.close()
- except HTTPException:
- raise
- except Exception as _e:
- logger.warning("Image ownership verification failed for %r", filename, exc_info=_e)
+ from core.database import (
+ SessionLocal as _SL,
+ GalleryImage as _GI,
+ Session as _DbSession,
+ ChatMessage as _CM,
+ )
+ _db = _SL()
+ try:
+ _row = _db.query(_GI).filter(_GI.filename == filename).first()
+ if _row is not None:
+ if _row.owner:
+ if _row.owner != _user:
+ raise HTTPException(status_code=404, detail="Image not found")
+ elif _row.session_id:
+ _sess = _db.query(_DbSession).filter(_DbSession.id == _row.session_id).first()
+ if not _sess or not _sess.owner or _sess.owner != _user:
+ raise HTTPException(status_code=404, detail="Image not found")
+ else:
+ # Gallery record has no owner or session link -> fail closed
+ raise HTTPException(status_code=404, detail="Image not found")
+ else:
+ # Rowless image: check if referenced in a chat session owned by this user
+ _chat_ref = (
+ _db.query(_CM.id)
+ .join(_DbSession, _CM.session_id == _DbSession.id)
+ .filter(_DbSession.owner == _user, _CM.meta_data.like(f"%{filename}%"))
+ .first()
+ )
+ if not _chat_ref:
+ raise HTTPException(status_code=404, detail="Image not found")
+ finally:
+ _db.close()
+ except HTTPException:
+ raise
+ except Exception as _e:
+ logger.warning("Image ownership verification failed for %r", filename, exc_info=_e)
+ raise HTTPException(status_code=503, detail="Ownership verification unavailable")
+
+ # 3. Resolve confined path and verify existence on disk
+ img_path = resolve_generated_image_path(filename)
+
ext = filename.rsplit('.', 1)[-1].lower()
mime = {
"png": "image/png", "jpg": "image/jpeg", "jpeg": "image/jpeg",
@@ -545,10 +623,6 @@ async def serve_generated_image(filename: str, request: Request):
"mp4": "video/mp4", "mov": "video/quicktime", "webm": "video/webm",
"mkv": "video/x-matroska", "m4v": "video/mp4",
}.get(ext, "application/octet-stream")
- # Generated-image filenames are content hashes → the bytes for a given
- # filename never change. Cache them hard so the gallery doesn't
- # re-download every full-size image each time it's opened. `immutable`
- # tells the browser it never needs to revalidate within the max-age.
return FileResponse(
str(img_path),
media_type=mime,
@@ -718,7 +792,8 @@ app.include_router(setup_research_routes(research_handler, session_manager=sessi
# History
from routes.history.history_routes import setup_history_routes
-app.include_router(setup_history_routes(session_manager, upload_handler=upload_handler))
+history_router = setup_history_routes(session_manager, upload_handler=upload_handler)
+app.include_router(history_router)
# Search
from routes.search.search_routes import setup_search_routes
@@ -784,6 +859,10 @@ app.include_router(setup_gallery_routes())
from routes.editor_draft_routes import setup_editor_draft_routes
app.include_router(setup_editor_draft_routes())
+# Natural-language editor planning (planner wired to the configured chat model)
+from routes.editor_agent_routes import setup_editor_agent_routes
+app.include_router(setup_editor_agent_routes())
+
# Scheduled tasks + event bus
from src.task_scheduler import TaskScheduler
task_scheduler = TaskScheduler(session_manager)
@@ -878,6 +957,7 @@ app.include_router(setup_codex_routes(
memory_router=memory_router,
calendar_router=calendar_router,
document_router=document_router,
+ history_router=history_router,
))
app.include_router(setup_claude_routes())
@@ -961,6 +1041,16 @@ async def get_version():
"source_commit": APP_SOURCE_COMMIT,
}
+
+@app.get("/api/busy")
+async def get_busy():
+ """Report in-flight heavy work so a deploy can wait instead of dropping it."""
+ from src import activity
+ return {
+ "busy_image_ops": activity.heavy_image_ops_active(),
+ **activity.activity(),
+ }
+
@app.get("/api/health")
async def health_check() -> Dict[str, str]:
return {"status": "healthy", "timestamp": datetime.now(timezone.utc).isoformat()}
@@ -1399,4 +1489,35 @@ if __name__ == "__main__":
bind_host = os.getenv("APP_BIND", "127.0.0.1")
bind_port = int(os.getenv("APP_PORT", "7011"))
- uvicorn.run(app, host=bind_host, port=bind_port, log_level="info")
+ # Give in-flight requests time to finish on SIGTERM instead of being cut
+ # off mid-flight. Diffusion edits run 60-120 s; outpaint/extend can run up
+ # to ~330 s (provider cap 900 s), so default the graceful window to 900 s.
+ # systemd's TimeoutStopSec must exceed this (see the graceful-stop drop-in).
+ #
+ # We hook uvicorn's signal handler so a SIGTERM also flips src.shutdown:
+ # SSE / streaming generators check it and end promptly, so an open browser
+ # stream cannot stall a restart for the whole window. The long window stays
+ # a safety net for genuine in-flight image ops.
+ from src import shutdown as _shutdown
+
+ config = uvicorn.Config(
+ app,
+ host=bind_host,
+ port=bind_port,
+ log_level="info",
+ timeout_graceful_shutdown=int(os.getenv("ODYSSEUS_GRACEFUL_SHUTDOWN_TIMEOUT", "900") or 900),
+ )
+ server = uvicorn.Server(config)
+
+ # uvicorn's capture_signals() wires SIGINT/SIGTERM to self.handle_exit, so
+ # wrapping that method lets us set the shutdown flag before the normal exit
+ # path runs (this uvicorn version has no install_signal_handlers kwarg).
+ _uvicorn_handle_exit = server.handle_exit
+
+ def _handle_shutdown_signal(signum, frame):
+ _shutdown.request_shutdown()
+ _uvicorn_handle_exit(signum, frame)
+
+ server.handle_exit = _handle_shutdown_signal
+
+ server.run()
diff --git a/build-windows-portable.ps1 b/build-windows-portable.ps1
index 7da912f73..634ae8068 100644
--- a/build-windows-portable.ps1
+++ b/build-windows-portable.ps1
@@ -47,7 +47,8 @@ if (-not $pyExe) {
Write-Host ("Using Python: " + $pyExe)
Write-Step "Installing build dependencies"
-& $pyExe -m pip install --upgrade pip --quiet
+& $pyExe -m pip install --quiet --require-hashes --only-binary=:all: --no-deps -r requirements-bootstrap.txt
+if ($LASTEXITCODE -ne 0) { Fail "TLS build dependency bootstrap failed." }
& $pyExe -m pip install -r requirements.txt pyinstaller pystray Pillow
if ($LASTEXITCODE -ne 0) { Fail "Dependency install failed." }
diff --git a/core/models.py b/core/models.py
index a03e391fc..f1e1d89d5 100644
--- a/core/models.py
+++ b/core/models.py
@@ -11,6 +11,8 @@ from typing import Dict, List, Any, Optional, TYPE_CHECKING
from src.tool_approval_scopes import (
CHAT_SESSION_APPROVAL_CONTEXT_MARKER,
CHAT_SESSION_APPROVAL_DECISION,
+ CHAT_SESSION_APPROVAL_SIGNATURE_FIELD,
+ verify_chat_session_grant,
)
if TYPE_CHECKING:
@@ -60,6 +62,14 @@ def _history_grants_chat_session_approval(
ask_user.get("kind") == "tool_approval"
and ask_user.get("resolved") == CHAT_SESSION_APPROVAL_DECISION
and str(ask_user.get("session_id") or "") == expected_session
+ # Shape proves nothing here: routes that accept a
+ # caller-supplied metadata blob write into this same history.
+ and verify_chat_session_grant(
+ ask_user.get(CHAT_SESSION_APPROVAL_SIGNATURE_FIELD),
+ expected_session,
+ ask_user.get("approval_id"),
+ CHAT_SESSION_APPROVAL_DECISION,
+ )
):
return True
return False
diff --git a/docker-compose.gpu-amd.yml b/docker-compose.gpu-amd.yml
index 8e6702b43..5c85014d6 100644
--- a/docker-compose.gpu-amd.yml
+++ b/docker-compose.gpu-amd.yml
@@ -127,11 +127,15 @@ services:
- ${RENDER_GID:-render}
chromadb:
- image: docker.io/chromadb/chroma:latest
+ image: docker.io/chromadb/chroma:1.5.9@sha256:1e0b73a187a28757c572acba508c46f48c9e8b0acaf5c20e6d95cdedce1acdf6
ports:
- "${CHROMADB_BIND:-127.0.0.1}:8100:8000"
volumes:
- - chromadb-data:/chroma/chroma
+ # The image runs `chroma run /config.yaml`, whose persist_path is "/data".
+ # It declares no VOLUME, so anything written outside a mount lives in the
+ # container's writable layer and dies with it. /chroma/chroma is where
+ # pre-1.0 images kept the store; mounting there now catches nothing.
+ - chromadb-data:/data
environment:
- ANONYMIZED_TELEMETRY=FALSE
restart: unless-stopped
@@ -141,8 +145,8 @@ services:
# (depends_on: condition: service_healthy), so a broken upstream `latest`
# tag blocks the whole app from starting. 2026.6.2 crashes on boot with
# `KeyError: 'default_doi_resolver'`, failing the healthcheck (issue #1414).
- # Bump this deliberately after verifying a newer tag boots clean.
- image: docker.io/searxng/searxng:2026.9.25-12f8b6515@sha256:5286edb35782454ab8a102c5eff6b54bff745853191b46aeead95f225aa6dfb6
+ # Update all default/GPU pins together after native startup and trust checks.
+ image: docker.io/searxng/searxng:2026.10.24-ef0ec03da@sha256:7c7cbe509429e82755104b2a95f52085a98633c95d53f44e4e905fa3a59f08c8
entrypoint:
- /bin/sh
- -c
@@ -192,7 +196,7 @@ services:
restart: unless-stopped
ntfy:
- image: docker.io/binwiederhier/ntfy
+ image: docker.io/binwiederhier/ntfy:v2.32.0@sha256:59250e1d8be2ee2186c4560322f625faef22ace380331f05b63f8842dbd62602
command: serve
ports:
- "${NTFY_BIND:-127.0.0.1}:8091:80"
diff --git a/docker-compose.gpu-nvidia.yml b/docker-compose.gpu-nvidia.yml
index eb3c9d7e3..5c628fcfb 100644
--- a/docker-compose.gpu-nvidia.yml
+++ b/docker-compose.gpu-nvidia.yml
@@ -130,11 +130,15 @@ services:
capabilities: [gpu]
chromadb:
- image: docker.io/chromadb/chroma:latest
+ image: docker.io/chromadb/chroma:1.5.9@sha256:1e0b73a187a28757c572acba508c46f48c9e8b0acaf5c20e6d95cdedce1acdf6
ports:
- "${CHROMADB_BIND:-127.0.0.1}:8100:8000"
volumes:
- - chromadb-data:/chroma/chroma
+ # The image runs `chroma run /config.yaml`, whose persist_path is "/data".
+ # It declares no VOLUME, so anything written outside a mount lives in the
+ # container's writable layer and dies with it. /chroma/chroma is where
+ # pre-1.0 images kept the store; mounting there now catches nothing.
+ - chromadb-data:/data
environment:
- ANONYMIZED_TELEMETRY=FALSE
restart: unless-stopped
@@ -144,8 +148,8 @@ services:
# (depends_on: condition: service_healthy), so a broken upstream `latest`
# tag blocks the whole app from starting. 2026.6.2 crashes on boot with
# `KeyError: 'default_doi_resolver'`, failing the healthcheck (issue #1414).
- # Bump this deliberately after verifying a newer tag boots clean.
- image: docker.io/searxng/searxng:2026.9.25-12f8b6515@sha256:5286edb35782454ab8a102c5eff6b54bff745853191b46aeead95f225aa6dfb6
+ # Update all default/GPU pins together after native startup and trust checks.
+ image: docker.io/searxng/searxng:2026.10.24-ef0ec03da@sha256:7c7cbe509429e82755104b2a95f52085a98633c95d53f44e4e905fa3a59f08c8
entrypoint:
- /bin/sh
- -c
@@ -195,7 +199,7 @@ services:
restart: unless-stopped
ntfy:
- image: docker.io/binwiederhier/ntfy
+ image: docker.io/binwiederhier/ntfy:v2.32.0@sha256:59250e1d8be2ee2186c4560322f625faef22ace380331f05b63f8842dbd62602
command: serve
ports:
- "${NTFY_BIND:-127.0.0.1}:8091:80"
diff --git a/docker-compose.yml b/docker-compose.yml
index 4fb49a45b..2b90227a3 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -108,11 +108,15 @@ services:
restart: unless-stopped
chromadb:
- image: docker.io/chromadb/chroma:latest
+ image: docker.io/chromadb/chroma:1.5.9@sha256:1e0b73a187a28757c572acba508c46f48c9e8b0acaf5c20e6d95cdedce1acdf6
ports:
- "${CHROMADB_BIND:-127.0.0.1}:8100:8000"
volumes:
- - chromadb-data:/chroma/chroma
+ # The image runs `chroma run /config.yaml`, whose persist_path is "/data".
+ # It declares no VOLUME, so anything written outside a mount lives in the
+ # container's writable layer and dies with it. /chroma/chroma is where
+ # pre-1.0 images kept the store; mounting there now catches nothing.
+ - chromadb-data:/data
environment:
- ANONYMIZED_TELEMETRY=FALSE
restart: unless-stopped
@@ -122,8 +126,8 @@ services:
# (depends_on: condition: service_healthy), so a broken upstream `latest`
# tag blocks the whole app from starting. 2026.6.2 crashes on boot with
# `KeyError: 'default_doi_resolver'`, failing the healthcheck (issue #1414).
- # Bump this deliberately after verifying a newer tag boots clean.
- image: docker.io/searxng/searxng:2026.9.25-12f8b6515@sha256:5286edb35782454ab8a102c5eff6b54bff745853191b46aeead95f225aa6dfb6
+ # Update all default/GPU pins together after native startup and trust checks.
+ image: docker.io/searxng/searxng:2026.10.24-ef0ec03da@sha256:7c7cbe509429e82755104b2a95f52085a98633c95d53f44e4e905fa3a59f08c8
entrypoint:
- /bin/sh
- -c
@@ -173,7 +177,7 @@ services:
restart: unless-stopped
ntfy:
- image: docker.io/binwiederhier/ntfy
+ image: docker.io/binwiederhier/ntfy:v2.32.0@sha256:59250e1d8be2ee2186c4560322f625faef22ace380331f05b63f8842dbd62602
command: serve
ports:
- "${NTFY_BIND:-127.0.0.1}:8091:80"
diff --git a/docker/chromium-ca-policy.md b/docker/chromium-ca-policy.md
new file mode 100644
index 000000000..b4852ac3a
--- /dev/null
+++ b/docker/chromium-ca-policy.md
@@ -0,0 +1,20 @@
+# Chromium incident distrust policy
+
+`chromium-emudhra.json` is installed in the Docker image at `/etc/chromium/policies/managed/odysseus-emudhra.json`. Chromium 132 and later support `CADistrustedCertificates`: a list of base64-encoded DER X.509 certificates whose public keys must not be accepted for TLS server authentication. Matching is by SubjectPublicKeyInfo (SPKI), so one certificate per compromised key also blocks its cross-signs. This policy adds no trust, disables no certificate checks, and does not require a revocation-list download. Native browsers and other browser distributions require separately managed installation of the appropriate policy.
+
+Policy semantics: [Chromium's version-155 definition](https://github.com/chromium/chromium/blob/155.0.8059.79/components/policy/resources/templates/policy_definitions/CertificateManagement/CADistrustedCertificates.yaml). Linux installation paths: [Chromium policy documentation](https://www.chromium.org/administrators/configuring-policy-for-extensions/#linux).
+
+Public certificate source, retrieved 2026-10-21: [incident intermediate inventory](https://emudhra.we-have-a-problem.com/impacted-intermediates.json). Its downloaded JSON has SHA-256 `f67b3abe9b4879f4e91874ed041beccd71257f1db41c588c724ccf12aa90c59e`. Each selected certificate's DER fingerprint and public-key fingerprint were checked against that inventory before inclusion. The eight unique keys below are covered, including the code-signing intermediate keys listed in the incident. The policy contains only public certificates; no private key is included.
+
+| Intermediate | SHA-256 of DER SPKI |
+| --- | --- |
+| EM OV TLS CA - G3B | `43bffa19d6ef651451f6841e019931e96f6f2eaeff28ab4b6f1ce4576de2717b` |
+| EM DV TLS CA - G3C | `49dd353dc2b919a3770645117d0e60c16115e7d1bc259eefe734b00ea434fe5f` |
+| EM EV TLS CA - G3C | `5c0660a2b164910d8ff589c18e14552e9e0ec237dcefe2cb736d41a4811f81a0` |
+| EM OV TLS CA - G3C | `63ecefee431d49523bc1136c4e72d0206a477086caf606cd5cf025686c109cf8` |
+| EM OV CS CA - G3C | `92c063d67e8f14db71d288e11266ffdaf69cbf115f7bab14f3bc2f68d25e0e30` |
+| EM EV TLS CA - G3B | `e0254c7fcdc265e2f0f8a428dabb75ab4ae039b4872d62f5ee57f0877d5a8a41` |
+| EM DV TLS CA - G3B | `ebed6475c2c2d80fcb199f3fe8dd6e6b3ce60b77eb15d4e42c3dec0c6f5b5105` |
+| EM OV CS CA - G3B | `ec4ffa1ad0ac88081314b7aaffef6a91f97cd57291bb5ba686c5415f5eb4f6b6` |
+
+`tests/test_chromium_ca_policy.py` verifies that the policy distrusts exactly these eight keys using valid intermediate CA certificates and adds no trust settings. Changes to the encoded material need a fresh source/fingerprint check and behavioral validation: all twelve published incident HTTPS chains must be rejected by the actual Chromium binary while ordinary HTTPS still succeeds. Confirm loading and any policy errors at `chrome://policy`. Do not treat a passing PEM-store check as a browser-policy check.
diff --git a/docker/chromium-emudhra.json b/docker/chromium-emudhra.json
new file mode 100644
index 000000000..104f82f60
--- /dev/null
+++ b/docker/chromium-emudhra.json
@@ -0,0 +1,12 @@
+{
+ "CADistrustedCertificates": [
+ "MIIDZjCCAu2gAwIBAgIPbK2jZ/scEACIEg6iAtVoMAoGCCqGSM49BAMDMFYxCzAJBgNVBAYTAklOMSUwIwYDVQQKDBxlTXVkaHJhIFRlY2hub2xvZ2llcyBMaW1pdGVkMSAwHgYDVQQDDBdlbVNpZ24gUm9vdCBUTFMgQ0EgLSBHMzAeFw0yNTA0MzAxNjAwMTJaFw00MDA0MjgxODMwMDBaMD8xCzAJBgNVBAYTAk5MMRMwEQYDVQQKDAplTXVkaHJhIEJWMRswGQYDVQQDDBJFTSBPViBUTFMgQ0EgLSBHM0IwdjAQBgcqhkjOPQIBBgUrgQQAIgNiAARziXqg6zz9yosSQC/68KvE4SErr43ud4rJ7i1tuD+sKAxeBWOK56Ks1xwyKo42HN659pxDArndjXPRzGyqsswK7k4hbOl53VGKSvS2JuVoTN1lgDftDIVOTMEvTPhkbQ2jggGWMIIBkjAfBgNVHSMEGDAWgBThOqshfPHjTVSu1HK3/YtZQiCQVDAdBgNVHQ4EFgQUm9hlUa/n5yw3rQjuaRnZvzeErgowHQYDVR0lBBYwFAYIKwYBBQUHAwEGCCsGAQUFBwMCMF0GA1UdIARWMFQwOQYLKwYBBAGDjiEBAAEwKjAoBggrBgEFBQcCARYcaHR0cDovL3JlcG9zaXRvcnkuZW1zaWduLmNvbTANBgsrBgEEAYOOIQECbjAIBgZngQwBAgIwdQYIKwYBBQUHAQEEaTBnMCQGCCsGAQUFBzABhhhodHRwOi8vb2NzcC1iLmVtc2lnbi5jb20wPwYIKwYBBQUHMAKGM2h0dHA6Ly9yZXBvc2l0b3J5LmVtc2lnbi5jb20vY2VydHMvRU1PVlRMU0NBRzNCLnA3YzA3BgNVHR8EMDAuMCygKqAohiZodHRwOi8vY3JsLmVtc2lnbi5jb20vP3Jvb3R0bHNjYWczLmNybDAOBgNVHQ8BAf8EBAMCAQYwEgYDVR0TAQH/BAgwBgEB/wIBADAKBggqhkjOPQQDAwNnADBkAjBAk+5BizdJhrED3wb7F2Gm7bWI60dlNd075nghT2TrR4NWKZtJZcbc28xxIY/NONICMF6mPdsjosaqmvEMWqKcBh4vsIvXSKnQj5o8zrFB4oKS+accjYTe8Dz3bQjauvy9uw==",
+ "MIIDaDCCAu6gAwIBAgIPWIsuPCu4zaE+GhIJJUMhMAoGCCqGSM49BAMDMFYxCzAJBgNVBAYTAklOMSUwIwYDVQQKDBxlTXVkaHJhIFRlY2hub2xvZ2llcyBMaW1pdGVkMSAwHgYDVQQDDBdlbVNpZ24gUm9vdCBUTFMgQ0EgLSBHMzAeFw0yNTA0MzAxNTM1MDlaFw00MDA0MjgxODMwMDBaMEAxCzAJBgNVBAYTAlVTMRQwEgYDVQQKDAtlTXVkaHJhIEluYzEbMBkGA1UEAwwSRU0gRFYgVExTIENBIC0gRzNDMHYwEAYHKoZIzj0CAQYFK4EEACIDYgAEOnp4YsjETTJN3WkDOmeCwO/u/kBV5ooSP6A3G6O9kZRRTuFypDPjYw8CvRiAN9nlFJ+bd9uUooHfmHsv6oiLdL3+j9pMEJnubKGVZv4+8OX2sJpVbMyLpQVh3xsqRB0Bo4IBljCCAZIwHwYDVR0jBBgwFoAU4TqrIXzx401UrtRyt/2LWUIgkFQwHQYDVR0OBBYEFK5+EFw8KZbBqEcnBVnx4D3U5QrzMB0GA1UdJQQWMBQGCCsGAQUFBwMBBggrBgEFBQcDAjBdBgNVHSAEVjBUMDkGCysGAQQBg44hAQABMCowKAYIKwYBBQUHAgEWHGh0dHA6Ly9yZXBvc2l0b3J5LmVtc2lnbi5jb20wDQYLKwYBBAGDjiEBAmQwCAYGZ4EMAQIBMHUGCCsGAQUFBwEBBGkwZzAkBggrBgEFBQcwAYYYaHR0cDovL29jc3AtYy5lbXNpZ24uY29tMD8GCCsGAQUFBzAChjNodHRwOi8vcmVwb3NpdG9yeS5lbXNpZ24uY29tL2NlcnRzL0VNRFZUTFNDQUczQy5wN2MwNwYDVR0fBDAwLjAsoCqgKIYmaHR0cDovL2NybC5lbXNpZ24uY29tLz9yb290dGxzY2FnMy5jcmwwDgYDVR0PAQH/BAQDAgEGMBIGA1UdEwEB/wQIMAYBAf8CAQAwCgYIKoZIzj0EAwMDaAAwZQIxAMEN2HWMocbuWdy1d33pH6JpMvP/V/DIS5PtZbv1Q7TXEbxrcyxgyuddOJscYDJJlAIwB4sH1BpbScDzkdD4tJBSwrG/1Mx82vb8YaySehNuu1+1oXNdAEKwaJ0mVzScy2+6",
+ "MIIDaDCCAu6gAwIBAgIQAIAJkopkEHYBrwX6LxnxCTAKBggqhkjOPQQDAzBWMQswCQYDVQQGEwJJTjElMCMGA1UECgwcZU11ZGhyYSBUZWNobm9sb2dpZXMgTGltaXRlZDEgMB4GA1UEAwwXZW1TaWduIFJvb3QgVExTIENBIC0gRzMwHhcNMjUwNDMwMTUzOTMxWhcNNDAwNDI4MTgzMDAwWjBAMQswCQYDVQQGEwJVUzEUMBIGA1UECgwLZU11ZGhyYSBJbmMxGzAZBgNVBAMMEkVNIEVWIFRMUyBDQSAtIEczQzB2MBAGByqGSM49AgEGBSuBBAAiA2IABC1W6Cmm+4LGSkaX2WCvlR6QZ66R+SbTQwbaSKiq63hptqZ+bSdCbgRCqgOzbhmI3/Y2UU7hzwf1uks/8qBmRa59MdWGatMao9JG6wsxd+6Zy3VmxRbOdICKZo+R8MR/yqOCAZUwggGRMB8GA1UdIwQYMBaAFOE6qyF88eNNVK7Ucrf9i1lCIJBUMB0GA1UdDgQWBBSmJV6AqU2385Z8G8eR35K87kvrXzAdBgNVHSUEFjAUBggrBgEFBQcDAQYIKwYBBQUHAwIwXAYDVR0gBFUwUzA5BgsrBgEEAYOOIQEAATAqMCgGCCsGAQUFBwIBFhxodHRwOi8vcmVwb3NpdG9yeS5lbXNpZ24uY29tMA0GCysGAQQBg44hAQJ4MAcGBWeBDAEBMHUGCCsGAQUFBwEBBGkwZzAkBggrBgEFBQcwAYYYaHR0cDovL29jc3AtYy5lbXNpZ24uY29tMD8GCCsGAQUFBzAChjNodHRwOi8vcmVwb3NpdG9yeS5lbXNpZ24uY29tL2NlcnRzL0VNRVZUTFNDQUczQy5wN2MwNwYDVR0fBDAwLjAsoCqgKIYmaHR0cDovL2NybC5lbXNpZ24uY29tLz9yb290dGxzY2FnMy5jcmwwDgYDVR0PAQH/BAQDAgEGMBIGA1UdEwEB/wQIMAYBAf8CAQAwCgYIKoZIzj0EAwMDaAAwZQIwBy1wTnzH4lXDTy2PD91ysLjvnlVN3JbJmc1BIMEU8TOLkYVHibMc9HeyonikFSfmAjEA6uE3QRxlrZTz/1/lXPTEMUhoauAtycagtlNFp79kjhvNa2/fAal1GNxsOutLnr0Y",
+ "MIIDaDCCAu6gAwIBAgIPKWkmwiejoVJjkrGUgqUEMAoGCCqGSM49BAMDMFYxCzAJBgNVBAYTAklOMSUwIwYDVQQKDBxlTXVkaHJhIFRlY2hub2xvZ2llcyBMaW1pdGVkMSAwHgYDVQQDDBdlbVNpZ24gUm9vdCBUTFMgQ0EgLSBHMzAeFw0yNTA0MzAxNTM3NDFaFw00MDA0MjgxODMwMDBaMEAxCzAJBgNVBAYTAlVTMRQwEgYDVQQKDAtlTXVkaHJhIEluYzEbMBkGA1UEAwwSRU0gT1YgVExTIENBIC0gRzNDMHYwEAYHKoZIzj0CAQYFK4EEACIDYgAEE4JRzVKskpjByKrZdzId65fnCb0LTKCspV3IrVHc/J0ViaFZfjpRIOHv1jHGPhg1ysrimGmmLhYx6KKBgatWYW3EXZGKvAnzqw5jz3kqpNztc4e+N7ulaVSfHAKycO1no4IBljCCAZIwHwYDVR0jBBgwFoAU4TqrIXzx401UrtRyt/2LWUIgkFQwHQYDVR0OBBYEFDTq6gzryQra+dDF4u2beMmHnhtsMB0GA1UdJQQWMBQGCCsGAQUFBwMBBggrBgEFBQcDAjBdBgNVHSAEVjBUMDkGCysGAQQBg44hAQABMCowKAYIKwYBBQUHAgEWHGh0dHA6Ly9yZXBvc2l0b3J5LmVtc2lnbi5jb20wDQYLKwYBBAGDjiEBAm4wCAYGZ4EMAQICMHUGCCsGAQUFBwEBBGkwZzAkBggrBgEFBQcwAYYYaHR0cDovL29jc3AtYy5lbXNpZ24uY29tMD8GCCsGAQUFBzAChjNodHRwOi8vcmVwb3NpdG9yeS5lbXNpZ24uY29tL2NlcnRzL0VNT1ZUTFNDQUczQy5wN2MwNwYDVR0fBDAwLjAsoCqgKIYmaHR0cDovL2NybC5lbXNpZ24uY29tLz9yb290dGxzY2FnMy5jcmwwDgYDVR0PAQH/BAQDAgEGMBIGA1UdEwEB/wQIMAYBAf8CAQAwCgYIKoZIzj0EAwMDaAAwZQIxAMSZt2xsPeumRdeSMSQ3CbzIZeQ/q7GDCWfeE1Pq+mhgA6gRM44cNVF3xJ+wsxJk+wIwFJbaDMokD8Ei6eNOiA8yUMYvfzQyngmrhZQMdPCK1SewrR794rSb9vGqxZzelQth",
+ "MIIDWzCCAuGgAwIBAgIPVEt/kiwxriIKSpIpFvbmMAoGCCqGSM49BAMDMFUxCzAJBgNVBAYTAklOMSUwIwYDVQQKDBxlTXVkaHJhIFRlY2hub2xvZ2llcyBMaW1pdGVkMR8wHQYDVQQDDBZlbVNpZ24gUm9vdCBDUyBDQSAtIEczMB4XDTI1MDQzMDE2Mzg0MFoXDTQwMDQyODE4MzAwMFowPzELMAkGA1UEBhMCVVMxFDASBgNVBAoMC2VNdWRocmEgSW5jMRowGAYDVQQDDBFFTSBPViBDUyBDQSAtIEczQzB2MBAGByqGSM49AgEGBSuBBAAiA2IABLnw4GNHAqacpqrdRDz9YsQbm6SyCSRpfXl052kaEm+5avs+NML9O8X0gwYfJl3CpYQ2NHMjUQQ2so8E84YjYwZ5gOJQPgJTLWVGI1pxZaJZoe9Jb3QbX97neHII5Lj676OCAYswggGHMB8GA1UdIwQYMBaAFGh0A/iFyo1UUFcdFuDI3kUNq80tMB0GA1UdDgQWBBTub3MpjW+/p7Mbw5U09hVWRHhmtzATBgNVHSUEDDAKBggrBgEFBQcDAzBeBgNVHSAEVzBVMDkGCysGAQQBg44hAQABMCowKAYIKwYBBQUHAgEWHGh0dHA6Ly9yZXBvc2l0b3J5LmVtc2lnbi5jb20wDgYMKwYBBAGDjiEBAoFIMAgGBmeBDAEEATB0BggrBgEFBQcBAQRoMGYwJAYIKwYBBQUHMAGGGGh0dHA6Ly9vY3NwLWMuZW1zaWduLmNvbTA+BggrBgEFBQcwAoYyaHR0cDovL3JlcG9zaXRvcnkuZW1zaWduLmNvbS9jZXJ0cy9FTU9WQ1NDQUczQy5wN2MwNgYDVR0fBC8wLTAroCmgJ4YlaHR0cDovL2NybC5lbXNpZ24uY29tLz9yb290Y3NjYWczLmNybDAOBgNVHQ8BAf8EBAMCAQYwEgYDVR0TAQH/BAgwBgEB/wIBADAKBggqhkjOPQQDAwNoADBlAjEA8yPg8sntOhLwV2QXJ5LEaKSpo/fnE3uOgTadK73fDhyjiqr0Io9GVuQTYqBPbQ2TAjBgeuApmBS486+iei03lRrp139dPw6k28jjGNvWsAU7A1N86J1zPJVDEyVH+nMAWC0=",
+ "MIIDaDCCAu2gAwIBAgIQAMfEHv6S2CXwXq6EGkqCwTAKBggqhkjOPQQDAzBWMQswCQYDVQQGEwJJTjElMCMGA1UECgwcZU11ZGhyYSBUZWNobm9sb2dpZXMgTGltaXRlZDEgMB4GA1UEAwwXZW1TaWduIFJvb3QgVExTIENBIC0gRzMwHhcNMjUwNDMwMTYwMzMxWhcNNDAwNDI4MTgzMDAwWjA/MQswCQYDVQQGEwJOTDETMBEGA1UECgwKZU11ZGhyYSBCVjEbMBkGA1UEAwwSRU0gRVYgVExTIENBIC0gRzNCMHYwEAYHKoZIzj0CAQYFK4EEACIDYgAEJduoWmTTl9oLEFLp6lRuSHvv6pydnWigxerc/u91ppu11vwB9Cv7ym60C81kwHZ+Nv/QXZeoE8WqDGyVMOec9fCGZGjxOAZCCqXIUYQLHiUlQOeQ5LZUw4Uu1krx6GV9o4IBlTCCAZEwHwYDVR0jBBgwFoAU4TqrIXzx401UrtRyt/2LWUIgkFQwHQYDVR0OBBYEFD7cINmJRpiHe4c/2IFHslwV2EcGMB0GA1UdJQQWMBQGCCsGAQUFBwMBBggrBgEFBQcDAjBcBgNVHSAEVTBTMDkGCysGAQQBg44hAQABMCowKAYIKwYBBQUHAgEWHGh0dHA6Ly9yZXBvc2l0b3J5LmVtc2lnbi5jb20wDQYLKwYBBAGDjiEBAngwBwYFZ4EMAQEwdQYIKwYBBQUHAQEEaTBnMCQGCCsGAQUFBzABhhhodHRwOi8vb2NzcC1iLmVtc2lnbi5jb20wPwYIKwYBBQUHMAKGM2h0dHA6Ly9yZXBvc2l0b3J5LmVtc2lnbi5jb20vY2VydHMvRU1FVlRMU0NBRzNCLnA3YzA3BgNVHR8EMDAuMCygKqAohiZodHRwOi8vY3JsLmVtc2lnbi5jb20vP3Jvb3R0bHNjYWczLmNybDAOBgNVHQ8BAf8EBAMCAQYwEgYDVR0TAQH/BAgwBgEB/wIBADAKBggqhkjOPQQDAwNpADBmAjEA9Jq999oaOUKhFwopw33iCmt0OHIn3gjT43GfuOHR/YckXdwoNdDAlIEhz0NgRO3/AjEAvY/a3OMvktIZLYjn+WLKmp0QhrIMV+e6EpS7j4GVeOKouNp6MN/P+ByGeiRMghzB",
+ "MIIDaDCCAu6gAwIBAgIQAKSu5njyM2K0wORgt3LyFDAKBggqhkjOPQQDAzBWMQswCQYDVQQGEwJJTjElMCMGA1UECgwcZU11ZGhyYSBUZWNobm9sb2dpZXMgTGltaXRlZDEgMB4GA1UEAwwXZW1TaWduIFJvb3QgVExTIENBIC0gRzMwHhcNMjUwNDMwMTU1NDA4WhcNNDAwNDI4MTgzMDAwWjA/MQswCQYDVQQGEwJOTDETMBEGA1UECgwKZU11ZGhyYSBCVjEbMBkGA1UEAwwSRU0gRFYgVExTIENBIC0gRzNCMHYwEAYHKoZIzj0CAQYFK4EEACIDYgAE557ZwEqXc8RzXlERHahawr1eZKs3S4DhLLwgOOweTw47gS/JhZ4eZ6+wTi+LyX90hbplqpEe6KTkW2LVzAPVa+Z4s8OMtNyTfKJGDiOEU8iSk10p1E+R4VYGtjzO2rRoo4IBljCCAZIwHwYDVR0jBBgwFoAU4TqrIXzx401UrtRyt/2LWUIgkFQwHQYDVR0OBBYEFOIeL+ccGTkOVUtiwSAkVzUkiiUUMB0GA1UdJQQWMBQGCCsGAQUFBwMBBggrBgEFBQcDAjBdBgNVHSAEVjBUMDkGCysGAQQBg44hAQABMCowKAYIKwYBBQUHAgEWHGh0dHA6Ly9yZXBvc2l0b3J5LmVtc2lnbi5jb20wDQYLKwYBBAGDjiEBAmQwCAYGZ4EMAQIBMHUGCCsGAQUFBwEBBGkwZzAkBggrBgEFBQcwAYYYaHR0cDovL29jc3AtYi5lbXNpZ24uY29tMD8GCCsGAQUFBzAChjNodHRwOi8vcmVwb3NpdG9yeS5lbXNpZ24uY29tL2NlcnRzL0VNRFZUTFNDQUczQi5wN2MwNwYDVR0fBDAwLjAsoCqgKIYmaHR0cDovL2NybC5lbXNpZ24uY29tLz9yb290dGxzY2FnMy5jcmwwDgYDVR0PAQH/BAQDAgEGMBIGA1UdEwEB/wQIMAYBAf8CAQAwCgYIKoZIzj0EAwMDaAAwZQIwLmsGXi6oFMJ2klkcEMXMug6gvxQWZWkewiDWVzQyl2L6z6DuQfPOIbh1grvdULDCAjEAxZvLlxUavG69J6wnSjC8XBbqNIQsJ6CE2QdNOe84Ptxb6VG8gt2TlfJbHii+KNvK",
+ "MIIDWzCCAuCgAwIBAgIPeBiTP4+FtGGaKzX7qD0KMAoGCCqGSM49BAMDMFUxCzAJBgNVBAYTAklOMSUwIwYDVQQKDBxlTXVkaHJhIFRlY2hub2xvZ2llcyBMaW1pdGVkMR8wHQYDVQQDDBZlbVNpZ24gUm9vdCBDUyBDQSAtIEczMB4XDTI1MDQzMDE2MDgyN1oXDTQwMDQyODE4MzAwMFowPjELMAkGA1UEBhMCTkwxEzARBgNVBAoMCmVNdWRocmEgQlYxGjAYBgNVBAMMEUVNIE9WIENTIENBIC0gRzNCMHYwEAYHKoZIzj0CAQYFK4EEACIDYgAEqrsPsGZqz88B+tUr/P1MK/LLPDSX3nOVDlgZth/mlQmHQcjEkUObNKBDHK/+W/m0wcjorgAB+fTcitgsWfNjnpbNbD1NsM7+wmw9YlF7N3YTcnQ/jordd7EAZPKr5eBQo4IBizCCAYcwHwYDVR0jBBgwFoAUaHQD+IXKjVRQVx0W4MjeRQ2rzS0wHQYDVR0OBBYEFHn66OzP2w11jaRY1p+27dx8Sd7mMBMGA1UdJQQMMAoGCCsGAQUFBwMDMF4GA1UdIARXMFUwOQYLKwYBBAGDjiEBAAEwKjAoBggrBgEFBQcCARYcaHR0cDovL3JlcG9zaXRvcnkuZW1zaWduLmNvbTAOBgwrBgEEAYOOIQECgUgwCAYGZ4EMAQQBMHQGCCsGAQUFBwEBBGgwZjAkBggrBgEFBQcwAYYYaHR0cDovL29jc3AtYi5lbXNpZ24uY29tMD4GCCsGAQUFBzAChjJodHRwOi8vcmVwb3NpdG9yeS5lbXNpZ24uY29tL2NlcnRzL0VNT1ZDU0NBRzNCLnA3YzA2BgNVHR8ELzAtMCugKaAnhiVodHRwOi8vY3JsLmVtc2lnbi5jb20vP3Jvb3Rjc2NhZzMuY3JsMA4GA1UdDwEB/wQEAwIBBjASBgNVHRMBAf8ECDAGAQH/AgEAMAoGCCqGSM49BAMDA2kAMGYCMQC/zr03YEELsNKqzUtH2dVFi4BaKFdyrr/6G1dIWp8KAVgsw2/u4lyyboUDaC9jDvICMQC9HTxku84tNX9dmHOtH7aC2Nu/JM0jTf6KjZAvovCJzzv1IFWSZpVLZibynMLXOrM="
+ ]
+}
diff --git a/docker/searxng/Dockerfile b/docker/searxng/Dockerfile
new file mode 100644
index 000000000..0b487e66c
--- /dev/null
+++ b/docker/searxng/Dockerfile
@@ -0,0 +1,9 @@
+# Validation only. Deploy the unmodified upstream image selected by Compose.
+ARG SEARXNG_IMAGE
+FROM ${SEARXNG_IMAGE} AS validation
+COPY scripts/check_ca_trust.py docker/searxng/validate_image.py /opt/odysseus-trust/
+COPY tests/fixtures/ca-trust/incident.json /opt/odysseus-trust/incident.json
+RUN /usr/local/searxng/.venv/bin/python /opt/odysseus-trust/validate_image.py
+
+FROM validation AS live-validation
+RUN /usr/local/searxng/.venv/bin/python /opt/odysseus-trust/validate_image.py --live
diff --git a/docker/searxng/Dockerfile.dockerignore b/docker/searxng/Dockerfile.dockerignore
new file mode 100644
index 000000000..3e7e75e3f
--- /dev/null
+++ b/docker/searxng/Dockerfile.dockerignore
@@ -0,0 +1,10 @@
+**
+!scripts/
+!scripts/check_ca_trust.py
+!docker/
+!docker/searxng/
+!docker/searxng/**
+!tests/
+!tests/fixtures/
+!tests/fixtures/ca-trust/
+!tests/fixtures/ca-trust/incident.json
diff --git a/docker/searxng/validate_image.py b/docker/searxng/validate_image.py
new file mode 100644
index 000000000..c768cf010
--- /dev/null
+++ b/docker/searxng/validate_image.py
@@ -0,0 +1,162 @@
+"""Verify incident distrust and startup in the unmodified upstream image."""
+
+import hashlib
+import asyncio
+import json
+import os
+from pathlib import Path
+import re
+import signal
+import ssl
+import subprocess
+import sys
+import tempfile
+import time
+import urllib.request
+
+import certifi
+
+from check_ca_trust import check_bundle
+
+
+def check_chains():
+ incident = json.loads(Path(__file__).with_name("incident.json").read_text())
+ system = Path(os.environ["SSL_CERT_FILE"])
+ capath = os.environ["SSL_CERT_DIR"]
+ stores = [["-CAfile", str(system), "-no-CApath"],
+ ["-CAfile", certifi.where(), "-no-CApath"],
+ ["-no-CAfile", "-CApath", capath]]
+ check_bundle(system)
+ check_bundle(Path(certifi.where()))
+ with tempfile.TemporaryDirectory() as directory:
+ directory = Path(directory)
+ for fingerprint, pem in incident["certificates"].items():
+ if hashlib.sha256(ssl.PEM_cert_to_DER_cert(pem)).hexdigest() != fingerprint:
+ raise ValueError(f"incident fixture fingerprint mismatch: {fingerprint}")
+ (directory / fingerprint).write_text(pem)
+ positive = directory / "affected.pem"
+ positive.write_text("\n".join(incident["certificates"][fp] for fp in incident["roots"]))
+ for hostname, chain in incident["chains"].items():
+ untrusted = directory / "untrusted.pem"
+ untrusted.write_text("\n".join(incident["certificates"][fp] for fp in chain[1:]))
+ base = ["openssl", "verify", "-no-CAstore", "-attime", str(incident["verification_time"]),
+ "-purpose", "sslserver", "-verify_hostname", hostname,
+ "-x509_strict", "-partial_chain", "-trusted_first", "-untrusted", str(untrusted)]
+ expectations = [(selection, False) for selection in stores]
+ for selection, expected in expectations + [
+ (["-CAfile", str(positive), "-no-CApath"], True)]:
+ result = subprocess.run(base + selection + [str(directory / chain[0])],
+ capture_output=True, text=True)
+ if (result.returncode == 0) != expected:
+ raise RuntimeError(f"unexpected chain result: {hostname}: {selection}: {result.stderr}")
+ # Accept issuer lookup, self-signed and explicitly untrusted
+ # certificate errors, rather than tool or fixture failures.
+ if not expected and not re.search(r"error (?:2|18|19|20|21|27) at \d+ depth lookup", result.stderr):
+ raise RuntimeError(f"not a certificate trust rejection: {hostname}: {result.stderr}")
+ print(f"{len(incident['chains'])}/{len(incident['chains'])} incident chains rejected by system PEM, hashed directory and certifi; affected controls accepted")
+
+
+def check_boot(live=False):
+ with tempfile.TemporaryDirectory() as directory:
+ settings = Path(directory) / "settings.yml"
+ settings.write_text("use_default_settings: true\nserver:\n secret_key: offline-build-validation-only\n limiter: false\nsearch:\n formats: [html, json]\n")
+ cache = Path(directory) / "cache"
+ cache.mkdir()
+ env = dict(os.environ, SEARXNG_SETTINGS_PATH=str(settings),
+ __SEARXNG_CONFIG_PATH=directory, __SEARXNG_DATA_PATH=str(cache),
+ GRANIAN_HOST="127.0.0.1", GRANIAN_PORT="18888")
+ # Do not expose a port or issue an outbound search during offline builds.
+ with tempfile.TemporaryFile() as log:
+ process = subprocess.Popen(["/usr/local/searxng/entrypoint.sh"],
+ cwd="/usr/local/searxng", env=env, stdout=log,
+ stderr=subprocess.STDOUT, start_new_session=True)
+ try:
+ opener = urllib.request.build_opener(urllib.request.ProxyHandler({}))
+ healthy = False
+ for _ in range(60):
+ if process.poll() is not None:
+ break
+ try:
+ with opener.open("http://127.0.0.1:18888/healthz", timeout=1) as response:
+ healthy = response.status == 200
+ except OSError:
+ pass
+ if healthy:
+ break
+ time.sleep(0.5)
+ if not healthy:
+ log.seek(0)
+ raise RuntimeError("SearXNG failed boot smoke: " + log.read().decode(errors="replace")[-6000:])
+ print("SearXNG loopback healthcheck passed")
+ # Its root entrypoint regenerates system trust. Repeat the
+ # behavioral checks after that real startup path completes.
+ check_running(live=live, port=18888)
+ finally:
+ if process.poll() is None:
+ os.killpg(process.pid, signal.SIGTERM)
+ try:
+ process.wait(timeout=10)
+ except subprocess.TimeoutExpired:
+ os.killpg(process.pid, signal.SIGKILL)
+ process.wait()
+
+
+def check_running(live=False, port=None):
+ """Verify an existing service without repairing it or starting another one."""
+ port = int(os.environ.get("GRANIAN_PORT", "8080")) if port is None else port
+ opener = urllib.request.build_opener(urllib.request.ProxyHandler({}))
+ with opener.open(f"http://127.0.0.1:{port}/healthz", timeout=5) as response:
+ if response.status != 200:
+ raise RuntimeError("SearXNG running-service healthcheck failed")
+ check_chains()
+ for path in Path(os.environ["SSL_CERT_DIR"]).iterdir():
+ if re.fullmatch(r"[0-9a-fA-F]{8}\.[0-9]+", path.name):
+ check_bundle(path)
+ if live:
+ asyncio.run(check_https())
+ with opener.open(f"http://127.0.0.1:{port}/search?q=python+documentation&format=json", timeout=90) as search:
+ payload = json.load(search)
+ results = payload.get("results", [])
+ if not results:
+ raise RuntimeError("live search returned no results")
+ print(f"SearXNG live JSON search passed: {len(results)} results")
+
+
+async def check_https():
+ # Exercise the actual pinned SearXNG client factory with its default CA
+ # selection, rather than a different HTTP library's trust configuration.
+ sys.path.insert(0, "/usr/local/searxng")
+ from curl_cffi.requests.exceptions import RequestException
+ from searx.network.client import new_client
+
+ client = new_client(enable_http=False, verify=True, enable_http2=True,
+ enable_http3=False, max_connections=2, proxies={},
+ local_address=None, max_redirects=3)
+ try:
+ response = await client.get("https://pypi.org/simple/certifi/", timeout=30)
+ if response.status_code != 200:
+ raise RuntimeError(f"ordinary HTTPS failed: {response.status_code}")
+ print("SearXNG actual curl client ordinary HTTPS passed with verification enabled")
+ incident = json.loads(Path(__file__).with_name("incident.json").read_text())
+ for hostname in incident["chains"]:
+ try:
+ await client.get(f"https://{hostname}/", timeout=30, allow_redirects=False)
+ except RequestException as exc:
+ # libcurl code 60 is peer certificate verification failure.
+ # DNS failures, timeouts and handshake EOF do not prove distrust.
+ if exc.code != 60:
+ raise RuntimeError(f"inconclusive incident TLS failure: {hostname}: {exc}") from exc
+ else:
+ raise RuntimeError(f"incident HTTPS unexpectedly accepted: {hostname}")
+ print(f"SearXNG actual curl client rejects {len(incident['chains'])}/{len(incident['chains'])} incident hosts with certificate errors after startup")
+ finally:
+ await client.aclose()
+
+
+if __name__ == "__main__":
+ live = "--live" in sys.argv
+ if "--running" in sys.argv:
+ check_running(live=live)
+ else:
+ check_chains()
+ check_boot(live=live)
diff --git a/docs/EDITOR_AGENT_API.md b/docs/EDITOR_AGENT_API.md
new file mode 100644
index 000000000..c873d28d9
--- /dev/null
+++ b/docs/EDITOR_AGENT_API.md
@@ -0,0 +1,201 @@
+# Editor Agent API
+
+How an agent (LLM or script) drives the PhotoCraft editor. There are three layers:
+
+1. **Control API** — `window.geEditorControl`, a stable in-page command surface.
+2. **NL planner** — `window.geEditorAI`, turns a prompt into control-API steps (LLM or basic mode).
+3. **Bridge** — server-mediated SSE channel so a *server-side* agent can drive an **open** editor.
+
+All three are owner-scoped by the app session; nothing is exposed to unauthenticated users.
+
+---
+
+## 1. Control API (`window.geEditorControl`)
+
+Installed when the editor opens. Version `EDITOR_CONTROL_VERSION`.
+
+```js
+await window.geEditorControl.invoke(op, params) // { ok, op, result } | { ok:false, op, error }
+await window.geEditorControl.run([{op, params}]) // sequential, stops on first failure
+window.geEditorControl.list() // [{op, description}]
+```
+
+`invoke` is async. Every op that mutates the document pushes **one** undo entry via
+`_saveState`, so a single op is one undo step.
+
+### Op catalog
+
+| Op | Params | Notes |
+| --- | --- | --- |
+| `document.info` | – | size, layers, mode |
+| `document.importImage` | `{dataUrl,name,raster}` | load a raster image as a new layer |
+| `layers.list` | – | top-most first |
+| `layers.select` | `{id\|index\|name}` | index is top-most-first |
+| `layers.addRaster` | – | new empty pixel layer |
+| `layers.addAdjustment` | `{type,params}` | adjustment layer |
+| `layers.duplicate` / `layers.delete` | – | on the active/selected layer(s) |
+| `layers.setOpacity` | `{id?,opacity 0-1}` | |
+| `layers.setBlend` | `{id?,blendMode\|mode}` | |
+| `layers.group` / `layers.ungroup` | – | |
+| `selection.selectAll` / `deselect` / `invert` | – | |
+| `selection.rectangle` / `selection.ellipse` | `{x,y,w,h}` | document space |
+| `selection.subject` | `{label}` | SAM text grounding (falls back to a centred rect) |
+| `selection.face` | – | SAM "face" (falls back to an upper-centre ellipse) |
+| `selection.sky` | – | SAM "sky" (falls back to a top-band colour range) |
+| `selection.background` | `{fuzziness}` | border colour union |
+| `selection.samText` | `{text}` | SAM text grounding only (throws without SAM) |
+| `selection.colorRange` | `{color,fuzziness}` | |
+| `selection.hasMask` | – | `{active, space}` |
+| `adjustments.apply` | `{type,params}` | adjustment layer; camelCase types accepted |
+| `adjustments.applyMasked` | `{brightness,contrast,saturation,warmth,invert}` | pixel pass, masked if a selection exists else whole layer |
+| `filters.apply` | `{id}` | opens the slider dialog and applies |
+| `filters.applyMasked` | `{id,radius,amount,invert}` | `id`: blur-gaussian, sharpen, unsharp-mask |
+| `transform.start` / `transform.apply` / `transform.cancel` | – | |
+| `text.add` | `{text,x,y,color,size,font,align}` | |
+| `history.undo` / `history.redo` | – | |
+| `history.mark` | – | returns current undo depth (for grouping) |
+| `history.collapse` | `{mark,label}` | collapses entries above `mark` into one |
+| `export.png` | – | `{dataUrl}` of the flattened document |
+| `export.gallery` | – | saves a copy back to the gallery |
+| `screenshot` | – | `{dataUrl,width,height}` of the composited canvas |
+
+Param conventions the planner must respect:
+
+- `adjustments.applyMasked`: `brightness`/`contrast`/`warmth` are **-100..100** (0 neutral);
+ `saturation` is a **multiplier** (1 neutral; values >3 are treated as percentages).
+- `adjustments.apply` `type` aliases are normalised (`blackAndWhite` -> `black-white`).
+- `color-balance` params are `{shadows:{r,g,b}, midtones:{r,g,b}, highlights:{r,g,b}}`;
+ a bare number is coerced to `{r:n,g:n,b:n}`.
+- A masked op with **no** active selection degrades to a whole-layer edit (does not throw).
+
+---
+
+## 2. NL planner (`window.geEditorAI`)
+
+```js
+const res = await window.geEditorAI.execute('blur the background behind the person', { onStep });
+// exec: window.geEditorAI.execute('blur the background behind the person', { onStep });
+// res = { ok, prompt, reply, planner, basicMode, steps, trace, failed }
+```
+
+Flow (`static/js/editor/nl-edit.js`):
+
+1. Read document state + a **before** screenshot.
+2. Ask the **server planner** (`POST /api/editor/plan`) with the prompt, state and
+ screenshot. The client passes its strong guidance via `state.planner_guidance`.
+ If the route is unavailable it falls back to `localPlan` (regex — labelled
+ **"basic mode"** in the UI).
+3. `sanitizeSteps()`: drop no-op/export steps and, if a masked op has no preceding
+ `selection.*`, insert the region implied by the prompt (face/sky/background/subject).
+4. `history.mark`, then run each step, screenshotting after each one.
+5. **Self-check** (server plans only, max 3 rounds): send the after screenshot back in
+ `mode:"check"` with the original intent. If not satisfied, **revert** the previous
+ attempt (undo its history entries) and apply the model's **full corrected** plan.
+6. `history.collapse` — the whole request becomes a single undoable step.
+
+UI: the Quick Edit box routes multi-clause / "and ..." prompts to this executor and
+streams `Step i/n: ` into its status line; a `(basic mode)` suffix marks the offline planner.
+
+### Server route
+
+`POST /api/editor/plan` (HARNESS, `routes/editor_agent_routes.py`)
+
+```
+{ prompt, state, mode?: "plan"|"check", screenshot?: "data:image/..." }
+-> { reply, planner, steps: [{op, params}], done? }
+```
+
+Owner-scoped, authenticated. Uses the configured default/utility model with vision.
+If the model call is unavailable it returns a deterministic `planner:"fallback"` plan.
+
+---
+
+## 3. Bridge (server agent drives an open editor)
+
+`static/js/editor/editor-bridge.js` subscribes the open editor to the server queue.
+Enabled automatically when the editor opens (`window.__geEditorBridge`).
+
+- Subscribe: `GET /api/editor/bridge/events?session=` — SSE, `data: {id,op,params}` (keepalive every 15s).
+- The page runs the op via the control API and replies:
+ `POST /api/editor/bridge/result {id,ok,result,error,screenshot,ms}`.
+- Enqueue a command (server side): `POST /api/editor/bridge/command {session, op|steps, wait, timeout}`.
+ With `wait:true` the call blocks and returns the editor's result.
+
+Round-trip example (authenticated; `` = `window.__geEditorBridge.session`):
+
+```bash
+curl -s -X POST http://127.0.0.1:7011/api/editor/bridge/command \
+ -H 'Content-Type: application/json' -b "odysseus_session=$TOKEN" \
+ -d '{"session":"default","op":"layers.addRaster","wait":true,"timeout":8000}'
+# -> {"id":"...","ok":true,"result":{...},"screenshot":"data:image/png;base64,..."}
+```
+
+Session scoping is `owner:session`, so an agent can only drive editors owned by the
+same user. The bridge is a **browser-only** flow: it requires an editor page to be open.
+
+---
+
+## 4. SAM dependency
+
+`selection.subject` / `selection.face` / `selection.sky` / `selection.samText` use the
+server SAM mask tool (`POST /api/image/mask`). When the SAM tools are **not installed**
+the editor raises *"Object mask tools are not installed"* and the control op falls back
+to a **coarse approximation** (centred rect / upper-centre ellipse / top-band colour range).
+On a plain background the approximation is acceptable; on real photos it leaks, producing
+visible rectangular/elliptical artifacts. Install the Cookbook SAM mask dependencies for
+true subject/face/sky segmentation.
+
+`selection.colorRange` and `selection.background` never need SAM (pure colour matching),
+but they are also coarse on busy scenes.
+
+---
+
+## 5. Two ways for an agent to use this — pick one
+
+### Option A — built-in tool (in-process)
+
+Register an editor-control tool inside the app (same process as the model) that calls the
+bridge/control API directly. Uses the app's normal login; nothing new is exposed. This is
+the rejected stdio-MCP design's replacement: a server-side tool that talks to the bridge
+needs either an internal token (auth-bypass) or to run in-process. **Decision pending (user).**
+
+### Option B — browser-only flow (works today)
+
+No new server tool. An external agent drives an open editor purely through the bridge
+endpoints using the logged-in owner's session. Restricted to the editor the user has open.
+This is the flow demonstrated above and requires **no** auth-bypass.
+
+A stdio `photo_editor` MCP server was prototyped and **rejected** because the built-in MCP
+subprocess has no internal token; wiring it would require expanding an auth bypass.
+The two viable options above are left for the user to choose.
+
+---
+
+## 6. Known limitations / honest grading
+
+Live run against real 7011 with the server LLM planner (7 prompts): all 7 executed
+(`planner:"llm"`). Graded by eye:
+
+- PASS: black & white portrait; warm cinematic; sharper + more vivid; text title.
+- FAIL (region-masked, SAM-bound): "dramatic sky" (global over-saturation instead of a
+ dramatic, masked sky), "blur the background" (coarse mask leaks; visible rectangle),
+ "brighten the face" (coarse ellipse/rect artifact).
+
+Whole-image edits are reliable; subject/face/sky region edits need SAM. The self-check
+loop works (revert-and-replan) but the region cases spend all 3 iterations.
+
+## 7. Theming (control kit)
+
+The editor's interactive controls (ranges, number fields, selects, checkboxes) share a
+single themed kit: `static/js/editor/control-kit.js` adds `.ge-ctl-*` classes scoped to
+the editor roots (`#gallery-editor-container`, `.ge-adj-popup`, `.ge-filter-overlay`,
+`.ge-canvas-size-overlay`, `.ge-float-window`, `.ge-transform-popup`), and
+`static/css/13-image-editor.css` (section "Editor control kit") styles them from the app
+design tokens (`static/css/00-tokens.css`) to match the app sliders/selects. It keeps
+range fills in sync and attaches a **scrub-on-label** affordance to numeric fields
+(drag the field's label to change the value; arrow keys work, Shift = x10).
+
+**The PhotoCraft editor is dark-only.** `:root.light` flips the global tokens, but
+`13-image-editor.css` has no `.light` handling and the editor relies on dark surfaces,
+so light mode renders a garbled mix. Unlike the rest of Odysseus, the editor follows
+Photoshop and is not offered in a light theme.
diff --git a/docs/chromadb-volume-migration.md b/docs/chromadb-volume-migration.md
new file mode 100644
index 000000000..4ec7853ac
--- /dev/null
+++ b/docs/chromadb-volume-migration.md
@@ -0,0 +1,408 @@
+# ChromaDB Volume Migration — Upgrading from pre-#6166 installs
+
+> [!IMPORTANT]
+> This guide is only for Docker-based installs that were deployed before PR #6166
+> was merged. Native host installs are unaffected (they persist to `data/chroma/`
+> on the host filesystem, which was always stored correctly).
+
+---
+
+## 1. What changed and why
+
+Before PR #6166, the `chromadb-data` named volume was mounted at `/chroma/chroma` inside
+the ChromaDB container. However, current `chromadb/chroma` images (version 1.0+) write their
+database to `/data` — configured by the container image's internal `/config.yaml` (`persist_path: "/data"`).
+Because the upstream ChromaDB image declares no `VOLUME` directive:
+
+* **Any vector data written to `/data` accumulated exclusively in the container's writable layer.**
+* The mounted `chromadb-data` named volume at `/chroma/chroma` remained completely empty.
+* Any recreation or removal of the container (`docker compose down`, `docker compose up --force-recreate`, `docker rm`)
+ permanently destroys that writable layer and all vector embeddings within it.
+
+PR #6166 corrects the mount target across all Compose configurations to `chromadb-data:/data`.
+
+Fresh installations will persist data directly to the named volume automatically. However, for
+**existing running installations**, the vector store currently resides in the old container's
+writable layer.
+
+This guide provides a zero-data-loss, fail-closed operational procedure to quiesce, preserve,
+back up, verify, seed, and validate that data before performing cutover.
+
+---
+
+## 2. Architecture and Safety Principles
+
+1. **No Live `docker cp`:** ChromaDB uses SQLite (`chroma.sqlite3`) and binary HNSW segment index
+ files (`data_level0.bin`, `header.bin`, `length.bin`, `link_lists.bin`). Taking a file copy while
+ the database engine is running risks capturing torn SQLite pages or out-of-sync HNSW graph segments.
+ Writers must be quiesced and ChromaDB gracefully stopped before copying files.
+2. **Do Not Trust `docker rename` Alone:** Docker Compose tracks containers by internal metadata labels
+ (`com.docker.compose.project`, `com.docker.compose.service`, `com.docker.compose.container-number`),
+ **not** merely by container name. Renaming a container does not strip its labels; Compose commands
+ can still discover, restart, or recreate it. To guarantee preservation of the writable layer, the
+ stopped container must be committed to an immutable Docker image (`docker commit`).
+3. **Never Overwrite Existing Volumes:** Named volumes must be positively verified as empty prior to seeding.
+4. **Staging Validation Before Production Cutover:** The seeded named volume must be independently validated
+ using a disposable ChromaDB instance on an isolated port before touching the production Compose deployment.
+5. **No Rollback to `/chroma/chroma`:** Rolling back to pre-#6166 Compose files reintroduces the broken
+ mount path where ChromaDB never looks. Rollback procedures must restore data into the corrected `/data` path
+ or redeploy from the immutable backup image.
+
+---
+
+## 3. Step-by-Step Migration Procedure
+
+### Step 0: Identify your project and volume names
+
+Docker Compose prefixes container and volume names with the project name (usually the root directory name).
+Identify yours before proceeding:
+
+```bash
+# Identify running ChromaDB container
+docker ps --filter "ancestor=chromadb/chroma" --format "table {{.ID}}\t{{.Status}}\t{{.Names}}"
+
+# Identify the named volume
+docker volume ls --filter "name=chromadb"
+```
+
+Throughout this guide:
+* `` represents your Compose project (e.g. `odysseus` or `odysseus-maintainer-preview`).
+* `` represents the running ChromaDB container (e.g. `-chromadb-1`).
+* `` represents the named volume (e.g. `_chromadb-data`).
+
+Set shell variables for convenience:
+```bash
+PROJECT=""
+CONTAINER="${PROJECT}-chromadb-1"
+VOLUME="${PROJECT}_chromadb-data"
+```
+
+---
+
+### Step 1: Pre-Migration Collection Inventory (Baseline)
+
+Establish a baseline of all existing collections and their embedding counts through the live ChromaDB API:
+
+```bash
+# List all collections and record counts
+curl -s http://127.0.0.1:8100/api/v2/tenants/default_tenant/databases/default_database/collections \
+ | python3 -c '
+import json, sys, urllib.request
+data = json.load(sys.stdin)
+print(f"Total collections found: {len(data)}")
+for col in data:
+ c_id = col["id"]
+ name = col["name"]
+ try:
+ with urllib.request.urlopen(f"http://127.0.0.1:8100/api/v2/tenants/default_tenant/databases/default_database/collections/{c_id}/count") as resp:
+ count = resp.read().decode().strip()
+ except Exception as e:
+ count = f"error: {e}"
+ print(f"Collection: {name} (ID: {c_id}) -> Count: {count}")
+' | tee pre_migration_inventory.txt
+```
+
+Save `pre_migration_inventory.txt` securely. This baseline is used in Step 7 and Step 9 to verify
+zero data loss.
+
+---
+
+### Step 2: Quiesce Writers and Gracefully Stop ChromaDB
+
+To ensure transactional and referential consistency across SQLite and HNSW segment files:
+
+1. Stop application writers (Odysseus) to prevent any in-flight requests:
+ ```bash
+ docker compose stop odysseus
+ ```
+2. Gracefully stop the ChromaDB service. This permits SQLite to checkpoint the Write-Ahead Log (WAL)
+ and flushes all in-memory vector index segments to disk:
+ ```bash
+ docker compose stop chromadb
+ ```
+3. Confirm that the container status is `Exited`:
+ ```bash
+ docker ps -a --filter "name=${CONTAINER}" --format "table {{.ID}}\t{{.Status}}\t{{.Names}}"
+ ```
+ *Do not proceed if the container is still running.*
+
+---
+
+### Step 3: Preserve the Original Container as an Immutable Image
+
+Because Docker Compose discovers containers via service labels, running `docker compose up` later
+could recreate and destroy the original container's writable layer.
+
+Preserve the complete writable layer into an immutable Docker image:
+```bash
+BACKUP_IMAGE="${PROJECT}-chromadb-backup:pre-migration-$(date +%Y%m%d-%H%M%S)"
+docker commit "${CONTAINER}" "${BACKUP_IMAGE}"
+echo "Committed container writable layer to: ${BACKUP_IMAGE}"
+```
+
+Verify the image was created:
+```bash
+docker images "${BACKUP_IMAGE}"
+```
+
+This image is your ultimate insurance: even if all containers and volumes are deleted, your
+data remains safely archived in Docker's image store.
+
+---
+
+### Step 4: Take a Cold File Backup
+
+With the container stopped, copy the `/data` directory out to a dedicated host backup directory:
+
+```bash
+BACKUP_DIR="./chromadb-backup-$(date +%Y%m%d-%H%M%S)"
+mkdir -p "${BACKUP_DIR}"
+
+docker cp "${CONTAINER}:/data/." "${BACKUP_DIR}/"
+echo "Cold backup created at: ${BACKUP_DIR}"
+```
+
+---
+
+### Step 5: Verify Backup Integrity
+
+Never proceed to destructive cutover without verifying both SQLite and vector index structures.
+
+1. **Verify SQLite Database File:**
+ ```bash
+ test -s "${BACKUP_DIR}/chroma.sqlite3" || { echo "ERROR: chroma.sqlite3 is missing or 0 bytes"; exit 1; }
+ ```
+2. **Execute SQLite PRAGMA Integrity Check:**
+ ```bash
+ INTEGRITY=$(sqlite3 "${BACKUP_DIR}/chroma.sqlite3" "PRAGMA integrity_check;")
+ if [ "${INTEGRITY}" != "ok" ]; then
+ echo "ERROR: SQLite integrity check failed: ${INTEGRITY}"
+ exit 1
+ fi
+ echo "SQLite integrity check: OK"
+ ```
+3. **Verify Collections Table Structure:**
+ ```bash
+ sqlite3 "${BACKUP_DIR}/chroma.sqlite3" "SELECT id, name FROM collections;"
+ ```
+4. **Verify HNSW Index Binary Files:**
+ Vector representations are not stored inside SQLite; they are kept in segment directories under `/data`:
+ ```bash
+ find "${BACKUP_DIR}" -type f -name "*.bin"
+ ```
+ Ensure `.bin` files (`data_level0.bin`, `header.bin`, etc.) exist for indexed collections.
+
+---
+
+### Step 6: Verify Destination Volume is Empty and Seed Safely
+
+The named volume `${VOLUME}` must be empty before seeding. Under no circumstances should
+migration files be merged into a populated volume.
+
+1. **Positive Empty Check:**
+ ```bash
+ VOL_FILES=$(docker run --rm -v "${VOLUME}:/vol:ro" alpine ls -A /vol)
+ if [ -n "${VOL_FILES}" ]; then
+ echo "ERROR: Named volume ${VOLUME} already contains files: ${VOL_FILES}"
+ echo "Aborting migration to prevent overwriting existing volume data."
+ exit 1
+ fi
+ echo "Volume ${VOLUME} is empty and ready for seeding."
+ ```
+2. **Seed the Volume:**
+ Use a disposable Alpine container to populate the volume with exact ownership and permissions:
+ ```bash
+ docker run --rm \
+ -v "${VOLUME}:/target" \
+ -v "$(realpath "${BACKUP_DIR}"):/source:ro" \
+ alpine sh -c "cp -a /source/. /target/ && ls -la /target/"
+ ```
+3. **Verify Seeded Contents:**
+ ```bash
+ docker run --rm -v "${VOLUME}:/vol:ro" alpine ls -la /vol
+ ```
+
+---
+
+### Step 7: Staging Validation in an Isolated Disposable Container
+
+Before modifying your production Compose stack, validate that ChromaDB boots successfully from the
+seeded volume and serves all collections.
+
+1. **Start Disposable Staging Container:**
+ Run a temporary ChromaDB instance bound to an isolated loopback port (e.g. `127.0.0.1:18199`):
+ ```bash
+ docker run -d --name "${PROJECT}-chromadb-staging" \
+ -p 127.0.0.1:18199:8000 \
+ -v "${VOLUME}:/data" \
+ chromadb/chroma:latest
+
+ # Wait for staging ChromaDB to boot
+ sleep 4
+ curl -s http://127.0.0.1:18199/api/v2/heartbeat || { echo "Staging container failed to respond"; exit 1; }
+ ```
+2. **Compare Collection Counts with Baseline:**
+ ```bash
+ curl -s http://127.0.0.1:18199/api/v2/tenants/default_tenant/databases/default_database/collections \
+ | python3 -c '
+ import json, sys, urllib.request
+ data = json.load(sys.stdin)
+ print(f"Staging collections verified: {len(data)}")
+ for col in data:
+ c_id = col["id"]
+ name = col["name"]
+ with urllib.request.urlopen(f"http://127.0.0.1:18199/api/v2/tenants/default_tenant/databases/default_database/collections/{c_id}/count") as resp:
+ count = resp.read().decode().strip()
+ print(f" {name}: {count} records")
+ '
+ ```
+ *Confirm that the output matches `pre_migration_inventory.txt` from Step 1.*
+
+3. **Tear Down Staging Container:**
+ ```bash
+ docker rm -f "${PROJECT}-chromadb-staging"
+ ```
+
+---
+
+### Step 8: Apply Updated Compose Files and Perform Production Cutover
+
+Once the seeded volume is proven healthy:
+
+1. Update your repository to the revision containing PR #6166:
+ ```bash
+ git pull
+ ```
+2. Verify the mount line in your Compose file:
+ ```bash
+ grep -E 'chromadb-data:/data' docker-compose.yml
+ ```
+3. Bring up the updated ChromaDB container:
+ ```bash
+ docker compose up -d chromadb
+ ```
+ Docker Compose will detect the updated mount configuration, replace the stopped container,
+ and attach `${VOLUME}` directly to `/data`.
+4. Bring up the application stack:
+ ```bash
+ docker compose up -d odysseus
+ ```
+
+---
+
+### Step 9: Post-Migration Production Verification
+
+1. **Confirm Mount Point:**
+ ```bash
+ docker inspect "${CONTAINER}" --format '{{range .Mounts}}{{.Name}} -> {{.Destination}}{{"\n"}}{{end}}'
+ ```
+ Expected output:
+ ```
+ _chromadb-data -> /data
+ ```
+2. **Confirm Production Collection Counts:**
+ ```bash
+ curl -s http://127.0.0.1:8100/api/v2/tenants/default_tenant/databases/default_database/collections \
+ | python3 -c '
+ import json, sys, urllib.request
+ data = json.load(sys.stdin)
+ print(f"Production collections: {len(data)}")
+ for col in data:
+ c_id = col["id"]
+ name = col["name"]
+ with urllib.request.urlopen(f"http://127.0.0.1:8100/api/v2/tenants/default_tenant/databases/default_database/collections/{c_id}/count") as resp:
+ count = resp.read().decode().strip()
+ print(f" {name}: {count} records")
+ '
+ ```
+3. **Application Verification:**
+ Log in to Odysseus, navigate to **Settings -> Memory**, and confirm that memory items,
+ tool embeddings, and RAG document queries operate normally.
+
+---
+
+## 4. Rollback Procedures
+
+### Scenario A: Failure During Staging (Before Compose Cutover)
+
+If staging verification in Step 7 fails or reveals discrepancies:
+1. Remove the staging container:
+ ```bash
+ docker rm -f "${PROJECT}-chromadb-staging"
+ ```
+2. Clear the failed destination volume:
+ ```bash
+ docker run --rm -v "${VOLUME}:/target" alpine sh -c "rm -rf /target/*"
+ ```
+3. Restart the original production container. Because the original container was only stopped (never recreated),
+ its writable layer remains completely intact:
+ ```bash
+ docker compose start chromadb
+ docker compose start odysseus
+ ```
+4. Verify production status on port 8100.
+
+---
+
+### Scenario B: Failure After Compose Cutover
+
+If an issue occurs after `docker compose up -d`:
+
+> [!CAUTION]
+> **Do not `git checkout` the pre-#6166 Compose file!**
+> In the pre-#6166 Compose file, `chromadb-data` was mounted to `/chroma/chroma`.
+> ChromaDB 1.0+ persists to `/data`, so checking out the old Compose file will cause
+> ChromaDB to ignore the restored volume and boot with an empty database.
+
+To restore service:
+1. **Option 1 — Restore from Verified Host Backup into the `/data` Volume:**
+ If the container failed due to data corruption during startup:
+ ```bash
+ docker compose stop chromadb
+ docker run --rm -v "${VOLUME}:/target" alpine sh -c "rm -rf /target/*"
+ docker run --rm \
+ -v "${VOLUME}:/target" \
+ -v "$(realpath "${BACKUP_DIR}"):/source:ro" \
+ alpine cp -a /source/. /target/
+ docker compose up -d chromadb
+ ```
+2. **Option 2 — Fallback to Committed Backup Image:**
+ If Compose cannot start ChromaDB with the volume:
+ ```bash
+ docker compose stop chromadb
+ docker run -d --name "${PROJECT}-chromadb-fallback" \
+ -p 127.0.0.1:8100:8000 \
+ "${BACKUP_IMAGE}"
+ ```
+ This immediately restores the exact pre-migration container state.
+
+---
+
+## 5. Post-Migration Cleanup (Explicit Authorization)
+
+Retain the host backup directory (`${BACKUP_DIR}`) and the backup Docker image (`${BACKUP_IMAGE}`)
+for at least 7 days until routine backups have succeeded.
+
+Once you are completely confident in system stability, manually clean up:
+```bash
+# Remove host backup
+rm -rf ./chromadb-backup-*
+
+# Remove backup Docker image
+docker rmi "${BACKUP_IMAGE}"
+```
+
+---
+
+## 6. Re-indexing (Disaster Recovery Only)
+
+If an installation has already destroyed its pre-#6166 container writable layer (e.g. prior to following
+this guide), the vector embeddings cannot be restored from disk. In this scenario:
+
+* **RAG Documents:** Re-upload files under **Settings -> Memory -> RAG**. Odysseus automatically re-chunks
+ and re-indexes documents upon upload.
+* **Semantic Memories:** Text memory records reside authoritatively in `data/app.db` (SQLite). Vector representations
+ are re-indexed automatically when Odysseus connects to a healthy ChromaDB instance.
+* **Tool Index:** Rebuilt automatically by Odysseus upon first query.
+
+Re-indexing is a disaster recovery fallback, not a substitute for preserving existing database state.
diff --git a/docs/frontend-architecture/ADR-001-source-and-deployment.md b/docs/frontend-architecture/ADR-001-source-and-deployment.md
new file mode 100644
index 000000000..cc1eca04e
--- /dev/null
+++ b/docs/frontend-architecture/ADR-001-source-and-deployment.md
@@ -0,0 +1,135 @@
+# ADR 001: Feature-first native ESM with controlled deployment output
+
+Date: 2026-10-13. Status: implemented F1 proof, proposed for maintainer adoption.
+Baseline: official `upstream/dev` at `8feb50e89468235cd3e0986da80edbd3acaf2c40`.
+Scope: source ownership and distribution foundation. Notes implementation is deferred.
+
+## Decision
+
+Maintain migrated JavaScript in `frontend/src/`. Publish native ES modules to
+explicitly registered paths in `static/js/`, and commit source and output together.
+Use `python scripts/build_frontend.py` to copy bytes without rewriting imports,
+bundling, minification, source maps, timestamps or generated headers. A checked-in
+`frontend/modules.json` maps source paths to deployment paths. All other static
+files remain authored legacy modules or deployment assets until a reviewed slice
+transfers their ownership. Do not claim that the whole static tree is generated.
+
+The proof transfers maintenance of the stateless action-menu ordering helper to
+`frontend/src/shared/actionMenuOrder.js`. Its output remains
+`/static/js/actionMenuOrder.js`, with the same three exports and identical bytes.
+All seven current consumers, HTML, service worker and runtime entry points retain
+their existing URLs. There is no wrapper, extra request or second browser module
+instance. The source copy is a development input, not a second runtime entry point.
+
+Use `frontend/src/app/` for composition, `features//index.js` for feature
+public APIs, and responsibility directories only when implementation requires
+them. The [handbook](handbook.md) defines dependency, ownership and lifecycle rules.
+F1 creates only the shared proof, without empty application or feature scaffolding.
+
+## Evidence and alternatives
+
+Both options were executed against this helper, rather than assumed to work.
+Measurements are local compatibility observations, not general performance claims.
+
+| Property | Controlled native ESM copy, selected | esbuild 0.25.12 controlled ESM build |
+| --- | --- | --- |
+| Proof output | 1,688 bytes, identical SHA-256 to existing runtime | 1,554 bytes with `--bundle --format=esm --target=es2022 --platform=browser` |
+| Repeatability | Clean temporary publication and idempotent rerun tested | Two independent compiler invocations emitted identical bytes |
+| Runtime contract | Existing exports, imports, cache entry and module identity unchanged | Export names, icon and ordering matched in an executed Node import |
+| Tooling | Python standard library; no production dependency | Compiler and platform binary needed for artifact production |
+| Local cost | Copy check: 0.03 s, 15,596 KB maximum RSS | Cached `npx` ESM transform: 0.58 s, 114,196 KB maximum RSS |
+| Incremental migration | Explicit file ownership, preserved module boundaries | Feasible for the stateless leaf; stateful facade/chunk identity still needs a separate graph spike |
+| Release implications | Commit output; install/startup paths consume existing static assets | Would also need committed or release-produced output plus compiler locking and facade/chunk manifest policy |
+
+The timing rows measure different tool paths, including `npx` overhead. The
+compiler's single-leaf success does not establish stateful graph or lazy chunk
+compatibility. The 134-byte bundle reduction does not justify that additional
+contract in F1. A future compiler adoption requires a new ADR and graph-level
+evidence. React, Vue, TypeScript, a global state library, hashed chunks and a
+development server have no demonstrated necessity here.
+
+Acorn 8.19.0 is added only as an exact, lockfile-pinned development dependency for
+architecture checks. A real JavaScript parser is needed to enforce boundaries
+across multiline imports, re-exports and lazy thunks without treating comments
+and string literals as executable imports. It is MIT licensed, about 568 KB
+unpacked, and contributes no deployed JavaScript or runtime dependency.
+
+## Distribution contract
+
+1. Source and generated output are reviewed and committed together. CI checks
+ byte parity; it does not silently rebuild and accept drift.
+2. Native Python startup continues to use `STATIC_DIR` and `/static`, without
+ invoking the publisher. Native installers already obtain tracked static files.
+3. Docker's current `COPY . .` includes the output. `.dockerignore` excludes
+ `node_modules/`. The Docker runtime and entrypoint require no frontend build.
+4. `Odysseus.spec` and `build-windows-portable.ps1` already include `static/`.
+ The macOS wrapper uses the Python checkout and its static assets. Neither
+ needs the source tree or frontend tooling to serve the proof.
+5. A release producer runs the checks before packaging and distributes the
+ entire matching static graph. The publisher is not a transactional deployment
+ mechanism. Partial copying of a new graph into a live deployment is unsupported.
+6. New output paths must declare LF checkout behavior in `.gitattributes`, as
+ this proof does, so Windows checkout conversion cannot create false byte drift.
+ Before checking parity or writing output, the publisher uses the manifest to
+ require effective `text: set` and `eol: lf` on every source/output path. It asks
+ Git in a temporary repository containing only the applicable repository-owned
+ `.gitattributes` files, including nested rules. Global/local Git overrides
+ cannot supply missing declarations. No blanket legacy-JS rule is introduced.
+ Git is a development/publication prerequisite, not a startup dependency.
+
+An isolated distribution probe executes the real FastAPI lifespan, shell and
+static requests after omitting `frontend/` and `node_modules/` and removing Node
+from the child process search path. It verifies bytes, MIME, CSP, revalidation,
+source-tree 404 behavior and static path confinement. The same probe runs in an existing Docker image
+with networking disabled. This is not a claim that a fresh full Docker image or
+Windows/macOS executable was built; see [validation](validation.md).
+
+## Imports, identity and offline operation
+
+New maintained modules use one unversioned deployment URL. Existing legacy URLs,
+including their version queries, stay unchanged. A copy mapping must preserve
+the resolution of every literal relative import; the architecture checker rejects
+a mapping that changes that resolution. Canonical absolute `/static/js/...`
+imports are also supported. No bare packages or browser imports of `frontend/src`
+are supported. Existing graph and identity guards continue to cover the runtime.
+
+Each registered output joins the exact `PRECACHE` or `PANEL_PRECACHE` array. The
+new checker parses those arrays, rather than accepting a URL mentioned in a
+comment. Installation fetches do not evaluate lazy modules. Import-time DOM work,
+timers, state creation and network I/O must be characterized before changing an
+entry point's load timing. New source dependency cycles are rejected; existing
+legacy cycles are inventoried and remain outside the new rules.
+
+The proof already has its exact precache entry, so no SW cache-name or HTML edit
+is needed. Its first evaluation in a fresh offline browser page passes, and
+importing the panel registry does not evaluate the editor. The current worker's
+`/static/` scope cannot control the SPA root. Open PR #6227 addresses that existing
+limitation; F1 does not fix or mask it. Full root offline reload is not certified.
+
+## Security and compatibility
+
+Keep backend authorization and owner scope authoritative. No agent, database,
+auth, CSP, static mount or API implementation changes belong to this decision.
+The helper remains same-origin ESM without eval, compiler runtime or external
+resources. No new source maps or vendored assets are emitted; existing SRI/CSP
+policy and distribution notices remain unchanged. The publisher validates path
+containment, symlinks, duplicate ownership and unmapped source before writing.
+It never deletes unowned static assets. Deleting or retiring outputs is an
+explicit reviewed migration operation, not automatic cleanup.
+
+## Rollout, rollback and limits
+
+Adopt F1 for controlled, reviewed slices after maintainer review. Leave Notes,
+bootstrap, HTML and service worker unchanged here. Register new files explicitly;
+update offline manifests only when new runtime dependencies are introduced.
+F1 rollback can remove the source manifest, proof tooling, gates and documentation
+without changing runtime bytes. Later rollback restores the complete prior
+source/output/facade/precache set through an authorized follow-up change.
+
+Boundary gates cannot prove semantic purity, owner isolation or correct teardown.
+Domain platform/clock checks are intentionally conservative syntax guards;
+behavior tests still establish those contracts. Worker URLs, styles and vendored
+libraries are outside the maintained-JS import gate and need explicit review if
+a future lane changes them. Legacy exceptions require an exact specifier and a
+module-scoped reason; there are none in F1. New source is not permission to
+grandfather new dependency cycles or to replicate broadly shared mutable state.
diff --git a/docs/frontend-architecture/assessment.md b/docs/frontend-architecture/assessment.md
new file mode 100644
index 000000000..d5c746c7c
--- /dev/null
+++ b/docs/frontend-architecture/assessment.md
@@ -0,0 +1,127 @@
+# F1 runtime and architecture assessment
+
+Assessment date: 2026-10-13. Repository: `odysseus-dev/odysseus`.
+Worktree: `worktrees/architecture/frontend-foundation`.
+Branch: `refactor/frontend-architecture-foundation`.
+HEAD, local `upstream/dev`, and the live GitHub official `dev` commit were all
+`8feb50e89468235cd3e0986da80edbd3acaf2c40`. The initial worktree was clean.
+That commit is the merged PR #6495, selected Notes/Todos agent context.
+`origin` points to the maintainer fork; integration targets official `upstream/dev`.
+
+Inputs read completely: the 2026-10-13 frontend architecture RFC and coding brief
+from Downloads, `specs/frontend.md`, repository instructions and existing tests.
+The current user brief supersedes the coding brief's `origin/dev` wording and
+defines the Notes state/workflow slice before reminders. The design is self-contained
+in this directory and does not require access to Downloads.
+
+Input provenance:
+
+- RFC SHA-256: `11dedcbb9971f4d787f2721b9c27aa43299baba39ca91066d01507d2d69ac4f8`.
+- Coding brief SHA-256: `e4882867617b9c732ce4f445e3bc2da0b4ec1315119f8226c1fd8c1acbacf29d`.
+
+## Module graph and bootstrap
+
+`node scripts/check_frontend.mjs --inventory` reproduces the parser-based inventory.
+It excludes vendored `static/lib/` and committed editor build output. At this base
+it scans 230 JS files, finds 707 static import/re-export edges and 108 literal
+dynamic import edges, and finds no missing targets. No computed dynamic imports
+were found in the original parser audit. The earlier existing-regex scan counted
+814 edges; executable syntax parsing counts 815. Use parser evidence for design
+and retain the existing regression guard unchanged.
+
+| Area | Current boundary and implication |
+| --- | --- |
+| HTML shell | `static/index.html`: nonce-bearing boot scripts, CSS/preloads, direct ESM script tags, then app/init/a11y. Multiple entry roots mean module identity matters. |
+| App composition | `static/app.js`: feature imports, globals, route/sidebar composition, session hydration and auth-fetch wiring. It eagerly imports Notes, Calendar, Chat, Documents and Settings. |
+| Startup | `static/js/startupShell.js`, `sessions.js`, `init.js`: first-paint scheduling, deferred hydration, user-switch storage cleanup and cosmetic permission gates. Preserve boot ordering. |
+| Lazy loading | `static/js/panels.js`: only `editor` is registered. A memoized import thunk shares successful/in-flight promises and retries failed imports. Do not label all panels lazy. |
+| Optional libraries | `markdown.js` lazily loads vendored KaTeX/Mermaid. KaTeX and fonts are precached; Mermaid becomes cached after first use. Pyodide has a CDN dependency. |
+| Feature packages | Settings registry/navigation/finder/lifecycle, Calendar utilities/reminders, Email wrapper/package and editor tools already demonstrate partial decomposition. |
+
+Highest import fan-in: `ui.js` 77, `spinner.js` 55, `editor/state.js` 39,
+`escMenuStack.js` 23, and storage/modal/z-order helpers 17 each. The measured
+static strongly connected components are:
+
+- Theme and UI.
+- Email Inbox, compatibility wrapper, package index, AI reply, attachments,
+ body rendering, menus, reader, settings page and unsubscribe.
+- Cookbook, diagnosis, HW Fit, download, running and serve modules.
+
+These are existing compatibility constraints, not approved patterns for new
+source. Dynamic edges connect more features but do not themselves establish
+initialization cycles. No global legacy dependency rewrite is attempted in F1.
+
+## State, side effects and ownership
+
+| Owner | Evidence and architectural treatment |
+| --- | --- |
+| Shared configuration | `appConfig.js` owns invalidatable settings/tool request promises and consumes a sessionStorage prefetch once. Retain single identity and writer invalidation. |
+| Browser persistence | `storage.js` centralizes keys and safe access; feature files also use direct localStorage. `init.js` cleans storage on user changes. Preferences are not an authorization store. |
+| Feature state | Notes has module variables, selection sets, undo/drafts and reminder state. Email exports a broadly mutable package state object; editor state is imported by 39 modules. Keep ownership explicit; do not expand these into a global store. |
+| Import-time effects | Notes reads storage/window and schedules reminders. Email state reads localStorage. Theme/UI initialize from DOM readiness; modal manager installs global listeners. Chip/mobile helpers bind at startup. Moving an import can change behavior before any exported function is called. |
+| Compatibility globals | App exposes controllers on `window`; Notes exposes `window.notesModule`. They are compatibility bridges, not the new inter-feature API convention. |
+| Async ownership | Session hydration, config invalidation, draft serialized saves and request-generation guards already prevent stale completion. New slices must preserve these rather than only move declarations. |
+
+Good patterns to retain: narrow zero-state leaves, explicit wrapper export lists,
+public API tests, retryable memoized lazy imports, shared config invalidation,
+request-generation checks and source/package-aware regression helpers.
+
+Patterns to avoid: blanket barrels exposing internals, feature imports from
+generic helpers, cycles through coordinators, direct writes to another feature's
+state or DOM, anonymous global listener ownership, import-triggered network/timer
+initialization in new APIs, and helpers grouped by convenience instead of purpose.
+
+## Runtime, assets and distribution
+
+| Contract | Verified source |
+| --- | --- |
+| Static URL and revalidation | `app.py`: `register_static_mime_types`, `_RevalidatingStatic`, `/static` mount. JS MIME is `text/javascript`; JS/CSS/HTML have `Cache-Control: no-cache`. |
+| App paths | `src/constants.py` and `src/runtime_paths.py`: checkout root in native mode, PyInstaller `_MEIPASS` in frozen mode; static assets follow app root, persisted data follows data-directory policy. |
+| CSP | `core/middleware.py`: same-origin scripts, nonce and jsDelivr allowance; `src/app_helpers.py` injects HTML nonces. No CSP relaxation is needed for the proof. |
+| Integrity | No `integrity=` attributes were found in the shell. Proof output is byte-identical and emits no source maps; no existing SRI or vendored artifacts change. |
+| Runtime-generated assets | `/api/generated-image/...` uses a confined data path and owner handling; report/render endpoints, Blob manifests/icons and uploads are runtime concerns outside static source publication. |
+| Docker | `Dockerfile` copies app code and existing static output; `.dockerignore` excludes node_modules. Node/npm in the image support Browser MCP, not frontend startup. |
+| Native installers | `setup.py`, `start-macos.sh`, `launch-windows.ps1`, systemd service: Python dependencies/startup consume the checkout. No frontend build is invoked. |
+| Windows desktop | `Odysseus.spec` and `build-windows-portable.ps1` include the whole static directory. Maintain output here rather than require a new bundle path or compiler. |
+| macOS | `build-macos-app.sh` creates a launcher around the Python checkout. Static serving follows the existing checkout path. Installer execution was not performed on Linux. |
+
+## PWA limitations and test coverage
+
+`static/sw.js` matches exact URLs, including queries. Install fetches each
+precache entry separately and tolerates failed fetches. It does not discover
+transitive dependencies. HTML root and JS/CSS handlers are network-first;
+other static assets are cache-first with background refresh. API and non-GET
+requests bypass caching. Cache updates need explicit version/manifest review.
+The older frontend spec's root stale-while-revalidate description is stale.
+
+Registration in `static/index.html` currently requests no wider scope, so the
+worker controls `/static/`, not `/`. Root offline reload is therefore a known
+pre-existing gap. PR #6227 proposes the scope/header correction. F1 tests actual
+offline ESM loading under the current scope and leaves that separate fix alone.
+Offline APIs, first-use Mermaid and optional CDN runtimes are not certified.
+
+Existing coverage includes runtime graph resolution and version parity; editor
+offline graph coverage and lazy-loader retries; Email API/export/evaluation
+coverage; Notes autosave, XSS, selection/listener and agent-context regressions;
+MIME, nonce and runtime paths. Tests use pytest, Node's built-in runner and existing
+Playwright Chromium. `tests/TESTING_STANDARD.md` requires behavior-first, isolated
+tests. F1 adds real publication failures, architecture violations and an offline
+browser proof. It does not replace existing source-sensitive tests.
+
+## Open PR overlap, checked live on 2026-10-13
+
+The open-PR listing was fetched through all pages; selected PR file lists were
+inspected. Refresh this inventory before any later slice.
+
+| PR | Overlap and disposition |
+| --- | --- |
+| [#6470](https://github.com/odysseus-dev/odysseus/pull/6470) | Theme/sidebar redesign touches HTML, SW, shared UI and CSS. F1 changes none of those assets. Future manifest/UI slices need collision review. |
+| [#6695](https://github.com/odysseus-dev/odysseus/pull/6695) | OXS touches bootstrap, HTML, platform, middleware and other backend boundaries. F1 does not establish an extension API or modify that platform. |
+| [#6227](https://github.com/odysseus-dev/odysseus/pull/6227) | Root SW scope/header fix. Independent follow-up dependency for broader offline certification. |
+| [#6394](https://github.com/odysseus-dev/odysseus/pull/6394) | Older CSS extraction touches legacy style/SW assets; requires separate supersession review. |
+| [#6627](https://github.com/odysseus-dev/odysseus/pull/6627) | npm development-dependency update overlaps package/lock files; reconcile the exact Acorn development entry on integration. |
+| [#6585](https://github.com/odysseus-dev/odysseus/pull/6585), [#6647](https://github.com/odysseus-dev/odysseus/pull/6647), [#6652](https://github.com/odysseus-dev/odysseus/pull/6652) | Notes optional-field persistence and agent routing/dispatch. Future characterization must reflect their merged state; F1 changes no Notes or backend behavior. |
+| [#6594](https://github.com/odysseus-dev/odysseus/pull/6594), [#6152](https://github.com/odysseus-dev/odysseus/pull/6152) | Desktop launcher/build and frozen-runtime packaging work. Existing paths stay stable; packaging still needs platform-owner validation. |
+
+PR titles alone do not establish compatibility. This report records the checked
+file overlap and relevant dependencies, not approval of those implementations.
diff --git a/docs/frontend-architecture/evidence/notes/implementation.sha256 b/docs/frontend-architecture/evidence/notes/implementation.sha256
new file mode 100644
index 000000000..023b5ca30
--- /dev/null
+++ b/docs/frontend-architecture/evidence/notes/implementation.sha256
@@ -0,0 +1,112 @@
+53dfddd71f02a9a60df42e3fb045bd1a80919d50870c0b77afe18a853f485bea .gitattributes
+867c6a4b025fefecb6ac4a91a38563a36107d9653599f64685e16a5be4fe7727 frontend/modules.json
+76de35ac93d72edb5dcd295e85c704af9b3f08c2fe9fdc56e0bcbebd4b322fd8 frontend/src/features/notes/application/agentActions.js
+37021f9643f6a3299d36b6021783a559e60ad84848ac2b12f0980b5034b6b9c4 frontend/src/features/notes/application/cardOperations.js
+fe3033db6ef316c6b15c6b01c0f202ee76a61ea2c5b6952b20144660ff17eb54 frontend/src/features/notes/application/checklistOperations.js
+85fc592724524bb5ff37d7e5e58a68fda9d7e645810b6c87a2d4dd3cb41f9dd5 frontend/src/features/notes/application/deletion.js
+ce38e7976ee315b198baebffe45f9a1f4e63d87affd9898ed5cf4bde37b903e7 frontend/src/features/notes/application/drafts.js
+6210915184c30f73911f144fe0d12a9935d6f2ce42cb2aaf6aeaa75614ca51a2 frontend/src/features/notes/application/queries.js
+0da923790f4036d5fe354df4e529feb4b96e178495cb951f269093c0a8347e4e frontend/src/features/notes/application/reminders.js
+8f95d086fc2e60beae32b9e9debba41b35448e1c5b4ac78e4989652ef2d44e35 frontend/src/features/notes/application/selection.js
+4ceb424b3b6e30a5f507804f42051be02390d4ce1f03ef284094e48825cde5c3 frontend/src/features/notes/application/state.js
+1c5d5af833aab91f71a34c11535885eb7bf9f751de5aa89f79defe0f696f20fb frontend/src/features/notes/application/submission.js
+1d58ea2d495c8d301c550eb9ba7f627c515a8784bcd105558d941522965e77b0 frontend/src/features/notes/application/workflows.js
+9ddbfb20e0a5564dd83365ad498286d68ef03fd60d632619ad4d9656e2f73c95 frontend/src/features/notes/domain/noteRules.js
+946ef7a98b0a2dbe329e8259250af11a11702c74fd997e17fb3aff007fbe40c9 frontend/src/features/notes/domain/recurrence.js
+25cf3a1cef5dbac0840aef513ffa010a9b08d206de96ce2527e6159a5454b555 frontend/src/features/notes/index.js
+8b186bbfbb003b8d738c80713e1cbb5c6924ee14119929c5ea65707b46076b0c frontend/src/features/notes/infrastructure/http.js
+c7552d1f4600ae721437892fc0a1e5a0332abe30082bd943cd13a379c9514fec frontend/src/features/notes/infrastructure/notifications.js
+ff91a55c55fbdd876c69d9ec10e4e992104c95b6d12d752d9745193fccbc646a frontend/src/features/notes/infrastructure/storage.js
+4ff6d69d04547a0325041f774c3bf0707d8b67982d59a221127e07dc9b01383c frontend/src/features/notes/ui/cardChecklist.js
+dd87f1929ef8a5d57fdf1ddb12a0a6be53d95be07946be54f946c6fe31ef80bc frontend/src/features/notes/ui/cardInteractions.js
+4ff661a65d88e810f346260a354070dba325d6beaa57d1c4e82e8bf09b894538 frontend/src/features/notes/ui/cardRendering.js
+113d4457f25291d15afb7fb6775ea063f24c9dac51bb0d262787c9e40705235b frontend/src/features/notes/ui/cardReorder.js
+eecafbd92076209fa41826820125fbe9ffa757d6d1bff018e9acc2ede2a18e72 frontend/src/features/notes/ui/checklist.js
+155ea3d70e653f38a62ff50fc5be6aee019d42e86d28753da9edb258ac7c93e1 frontend/src/features/notes/ui/checklistReorder.js
+5462fea63a2aa9d1fc07dca91b462f6ff24f352b05d99ea6feb437469c0e1f3e frontend/src/features/notes/ui/clipboard.js
+2619e5f8b15eb3057330ef220abe6bc354a496effc0df3d89385cdfef9242c86 frontend/src/features/notes/ui/colors.js
+11cf24e7e8e8954d764cb58d786fa6f6d71f84f1c6c5ba644d761e28cfdbaedf frontend/src/features/notes/ui/draftEditor.js
+f55d4eff7f550e183ecf240a45002936063dbb4eae153e11834da4cb6bd13d35 frontend/src/features/notes/ui/drawing.js
+f85c86e70b3a380449fe3c7ecc7a4e68946de320523f5edc8e33f8eab3f0a02a frontend/src/features/notes/ui/editor.js
+3946b8324ad8f0212621e526479668308e48b799bf0dbb608e5cd4626f6c1f03 frontend/src/features/notes/ui/filters.js
+a893d09e96fb98d13db8ae5c3fb8c5e7a040c62031dd961396a18b7ae2a82a38 frontend/src/features/notes/ui/layout.js
+8d8c62a87d4df134d3b9dd97eaf59d02c52f1a38f6bc2e109e8426081d453a8d frontend/src/features/notes/ui/lifecycle.js
+62ad9408cb139143168f2c5834ec56b83264c4daed3e84fa9b4b0a281712144c frontend/src/features/notes/ui/mobileEditor.js
+2a3ccbad103dcc880e4baf2b3aa3ece4df7b73752bd30078185f03227585148f frontend/src/features/notes/ui/mobileReorder.js
+856fe945cf697278f795b8753704119839fa12bc5e0e69e9dab57c4b4dd6d24e frontend/src/features/notes/ui/panel.js
+8aa081cb7341d9a67ef46c74da49aebd729e9b53a73d618b81c89566c874b507 frontend/src/features/notes/ui/quickAdd.js
+8a4f23a013f06876894e6544b49540b288007d0d7e4cddca955978588f47a64a frontend/src/features/notes/ui/reminderDisplay.js
+cb043be801ab40cf8141af6ff1ad788e69fef57a87960ca992071ad9ad29ad90 frontend/src/features/notes/ui/reminderPicker.js
+38f12ba7771589aa427f054f48919569dcee9abe0246e02b9767202adb854cdc frontend/src/features/notes/ui/selection.js
+2634f252b2899e2e70fc9fec37144b0cc9b0ed00724da81bfef74b1acf7c05b6 frontend/src/features/notes/ui/text.js
+d2655ef163825ce6c40d8ef46bc9dfc63a2aa19fb1a7e10b28002f79cb0db409 frontend/src/features/notes/ui/toolbar.js
+a0aa203e87814d0eebebb6b049776c3efd576f4a5c6e17e486c8a2893c9c21df frontend/src/features/notes/ui/windowLayout.js
+68f0cbe07c7b61fcaf92920cd47042c576ab27fd9553c971cff45c595c25d80a frontend/src/shared/ui/confetti.js
+c16fcde607dce2f10a1afd1f8845403a7d0b97a9d5a67ec7aa329c367ba585e8 scripts/verify_frontend_runtime.py
+c2e5de2b8ce168220bad4fcefed710e60eeb0dd3e992e76cd980f2c0ca52815a scripts/verify_notes_browser_runtime.py
+fa31d673c40f973490e9fac52130b4a915b944a7abdd217a9bd8d57e66d57ca6 static/js/compare/vote.js
+76de35ac93d72edb5dcd295e85c704af9b3f08c2fe9fdc56e0bcbebd4b322fd8 static/js/features/notes/application/agentActions.js
+37021f9643f6a3299d36b6021783a559e60ad84848ac2b12f0980b5034b6b9c4 static/js/features/notes/application/cardOperations.js
+fe3033db6ef316c6b15c6b01c0f202ee76a61ea2c5b6952b20144660ff17eb54 static/js/features/notes/application/checklistOperations.js
+85fc592724524bb5ff37d7e5e58a68fda9d7e645810b6c87a2d4dd3cb41f9dd5 static/js/features/notes/application/deletion.js
+ce38e7976ee315b198baebffe45f9a1f4e63d87affd9898ed5cf4bde37b903e7 static/js/features/notes/application/drafts.js
+6210915184c30f73911f144fe0d12a9935d6f2ce42cb2aaf6aeaa75614ca51a2 static/js/features/notes/application/queries.js
+0da923790f4036d5fe354df4e529feb4b96e178495cb951f269093c0a8347e4e static/js/features/notes/application/reminders.js
+8f95d086fc2e60beae32b9e9debba41b35448e1c5b4ac78e4989652ef2d44e35 static/js/features/notes/application/selection.js
+4ceb424b3b6e30a5f507804f42051be02390d4ce1f03ef284094e48825cde5c3 static/js/features/notes/application/state.js
+1c5d5af833aab91f71a34c11535885eb7bf9f751de5aa89f79defe0f696f20fb static/js/features/notes/application/submission.js
+1d58ea2d495c8d301c550eb9ba7f627c515a8784bcd105558d941522965e77b0 static/js/features/notes/application/workflows.js
+9ddbfb20e0a5564dd83365ad498286d68ef03fd60d632619ad4d9656e2f73c95 static/js/features/notes/domain/noteRules.js
+946ef7a98b0a2dbe329e8259250af11a11702c74fd997e17fb3aff007fbe40c9 static/js/features/notes/domain/recurrence.js
+25cf3a1cef5dbac0840aef513ffa010a9b08d206de96ce2527e6159a5454b555 static/js/features/notes/index.js
+8b186bbfbb003b8d738c80713e1cbb5c6924ee14119929c5ea65707b46076b0c static/js/features/notes/infrastructure/http.js
+c7552d1f4600ae721437892fc0a1e5a0332abe30082bd943cd13a379c9514fec static/js/features/notes/infrastructure/notifications.js
+ff91a55c55fbdd876c69d9ec10e4e992104c95b6d12d752d9745193fccbc646a static/js/features/notes/infrastructure/storage.js
+4ff6d69d04547a0325041f774c3bf0707d8b67982d59a221127e07dc9b01383c static/js/features/notes/ui/cardChecklist.js
+dd87f1929ef8a5d57fdf1ddb12a0a6be53d95be07946be54f946c6fe31ef80bc static/js/features/notes/ui/cardInteractions.js
+4ff661a65d88e810f346260a354070dba325d6beaa57d1c4e82e8bf09b894538 static/js/features/notes/ui/cardRendering.js
+113d4457f25291d15afb7fb6775ea063f24c9dac51bb0d262787c9e40705235b static/js/features/notes/ui/cardReorder.js
+eecafbd92076209fa41826820125fbe9ffa757d6d1bff018e9acc2ede2a18e72 static/js/features/notes/ui/checklist.js
+155ea3d70e653f38a62ff50fc5be6aee019d42e86d28753da9edb258ac7c93e1 static/js/features/notes/ui/checklistReorder.js
+5462fea63a2aa9d1fc07dca91b462f6ff24f352b05d99ea6feb437469c0e1f3e static/js/features/notes/ui/clipboard.js
+2619e5f8b15eb3057330ef220abe6bc354a496effc0df3d89385cdfef9242c86 static/js/features/notes/ui/colors.js
+11cf24e7e8e8954d764cb58d786fa6f6d71f84f1c6c5ba644d761e28cfdbaedf static/js/features/notes/ui/draftEditor.js
+f55d4eff7f550e183ecf240a45002936063dbb4eae153e11834da4cb6bd13d35 static/js/features/notes/ui/drawing.js
+f85c86e70b3a380449fe3c7ecc7a4e68946de320523f5edc8e33f8eab3f0a02a static/js/features/notes/ui/editor.js
+3946b8324ad8f0212621e526479668308e48b799bf0dbb608e5cd4626f6c1f03 static/js/features/notes/ui/filters.js
+a893d09e96fb98d13db8ae5c3fb8c5e7a040c62031dd961396a18b7ae2a82a38 static/js/features/notes/ui/layout.js
+8d8c62a87d4df134d3b9dd97eaf59d02c52f1a38f6bc2e109e8426081d453a8d static/js/features/notes/ui/lifecycle.js
+62ad9408cb139143168f2c5834ec56b83264c4daed3e84fa9b4b0a281712144c static/js/features/notes/ui/mobileEditor.js
+2a3ccbad103dcc880e4baf2b3aa3ece4df7b73752bd30078185f03227585148f static/js/features/notes/ui/mobileReorder.js
+856fe945cf697278f795b8753704119839fa12bc5e0e69e9dab57c4b4dd6d24e static/js/features/notes/ui/panel.js
+8aa081cb7341d9a67ef46c74da49aebd729e9b53a73d618b81c89566c874b507 static/js/features/notes/ui/quickAdd.js
+8a4f23a013f06876894e6544b49540b288007d0d7e4cddca955978588f47a64a static/js/features/notes/ui/reminderDisplay.js
+cb043be801ab40cf8141af6ff1ad788e69fef57a87960ca992071ad9ad29ad90 static/js/features/notes/ui/reminderPicker.js
+38f12ba7771589aa427f054f48919569dcee9abe0246e02b9767202adb854cdc static/js/features/notes/ui/selection.js
+2634f252b2899e2e70fc9fec37144b0cc9b0ed00724da81bfef74b1acf7c05b6 static/js/features/notes/ui/text.js
+d2655ef163825ce6c40d8ef46bc9dfc63a2aa19fb1a7e10b28002f79cb0db409 static/js/features/notes/ui/toolbar.js
+a0aa203e87814d0eebebb6b049776c3efd576f4a5c6e17e486c8a2893c9c21df static/js/features/notes/ui/windowLayout.js
+7f1a7961d586767298672fad71a0d627389e185f0fb28792a04d0b987e1d5c5c static/js/notes.js
+68f0cbe07c7b61fcaf92920cd47042c576ab27fd9553c971cff45c595c25d80a static/js/shared/ui/confetti.js
+97fd43c17f3cb1928947e24159a3b59dc81ef7dca95862e8a47154e9cb732f88 static/sw.js
+910cd5777564e9f6338b8a864a772beffea197dc476464171c180e7be96e572d tests/browser/notesNative.mjs
+ef4bc40a710919c81c582d3b9fe80376d0d5ae66fb9be3c293871a83ee360f97 tests/browser/notesOffline.mjs
+437ec2e9865b3e066bbec8d7595a0d947f1e503b96e7b4d819ec1bed86c9bb1e tests/browser/notesReference.mjs
+9af973a5d2fb08a5eed550be0198bef501af56802c3844b5d0bb8e718cc685cf tests/fixtures/notesRecurrenceBaseline.mjs
+859a5f442dc717f59993891c338cd6ae9d6e5e009392a2ee69ab0e3b063bb572 tests/helpers/notes_source.py
+739ffc3f20de8e2bdf1d513b17bf485f85821e9906109cdf8ffea04b81b0f1dd tests/notesApplication.test.mjs
+1946369be43177b19a44cd9ae4f90d64da6558d1a470f8e347b490a2188782be tests/notesCharacterization.test.mjs
+99f0cd92a30cf01c0ee6814f6684edeb80ebdb9a5ab96583244092865bfb6212 tests/notesDraftAutosave.test.mjs
+0417205809de16c7c7338ea80ba19ca844603b3e06655987226f5f83d962d18b tests/notesInfrastructure.test.mjs
+dcf7c2d33de9bb457f96af070354ecc3ab69669002bdc9c7c943bef1b3d2e9bc tests/notesRecurrence.test.mjs
+dd9a703465dde8f92625a3226ab52d20a02aa5d3415fbcc70609f69a372ccc12 tests/notesReminders.test.mjs
+5a9112569f226525faaf6603a9867620b47902534f9cd882c08f71f2f96614b2 tests/notesWorkflows.test.mjs
+35fb2bd1f02757b73188342ec00f1e97253b8ba8dfb577861675872a517bd949 tests/selectedNotesContext.test.mjs
+c6c64c2b695b84d00f8a80a980be00766175c482548c86484f991ef671ecfbe9 tests/test_notes_document_mutual_minimize.py
+02c2aeb856798d982e5debcb9c605172933b0216a039cf0d96cdd415b1e2ef83 tests/test_notes_dom_xss_helpers.py
+5a511c7a2ef5d28463df34f3462db9ce59575d624cf8181577bab2cc371b4f9f tests/test_notes_mobile_checklist_toggle_static.py
+1db10a0d344818459d64279da807ddefe9b866dfe560ac4b154b486dd1a5efc0 tests/test_notes_reference_browser.py
+49f466b1a717098aa25439b6ff9ef3ae3d027d9dd976212b165b0b99a582b952 tests/test_notes_reference_contracts_js.py
+c2d877a11eafcb99b24a1c89111e5df4453a62bc8cf7d26ae1118b25c4a5ace4 tests/test_notes_search_reset_on_reopen_js.py
+6d95f073421427b5e149ef1e85c8b5749095d00337f05960134552985f73e372 tests/test_notes_select_esc_listener_js.py
+b3118a4b40fcfcbb26ad9ccbcb332fc6ced873d8cad1160be38a286ad1e664a4 tests/test_notes_sidebar_new_note.py
diff --git a/docs/frontend-architecture/evidence/notes/native-desktop.png b/docs/frontend-architecture/evidence/notes/native-desktop.png
new file mode 100644
index 000000000..fd30ced2a
Binary files /dev/null and b/docs/frontend-architecture/evidence/notes/native-desktop.png differ
diff --git a/docs/frontend-architecture/evidence/notes/native-mobile.png b/docs/frontend-architecture/evidence/notes/native-mobile.png
new file mode 100644
index 000000000..fdede2e84
Binary files /dev/null and b/docs/frontend-architecture/evidence/notes/native-mobile.png differ
diff --git a/docs/frontend-architecture/handbook.md b/docs/frontend-architecture/handbook.md
new file mode 100644
index 000000000..ade3bec14
--- /dev/null
+++ b/docs/frontend-architecture/handbook.md
@@ -0,0 +1,231 @@
+# Odysseus frontend architecture handbook
+
+Status: F1 merged in PR #6701. The complete Notes reference is implemented as an
+unpublished review diff on `refactor/notes-reference-decomposition`. Read its
+[case study](notes-case-study.md), [module inventory](notes-module-inventory.md)
+and [validation receipts](notes-validation.md). Publication and the recipient's
+post-integration reproduction remain pending.
+
+Read the [ADR](ADR-001-source-and-deployment.md), [assessment](assessment.md),
+[validation report](validation.md) and [Notes roadmap](notes-roadmap.md).
+The frontend program ends with the Notes reference decomposition and handoff.
+Calendar, Documents, Email, Chat, Skills, Settings and other later decompositions
+belong to the designated frontend maintainer; do not start them automatically.
+
+## Source, ownership and public APIs
+
+`frontend/src/app/` composes public feature APIs and platform ports. Each
+`features//index.js` is an intentional API, with explicit named exports
+and a compatibility default only when existing consumers require one. Internals
+live under `domain/`, `application/`, `infrastructure/` or `ui/` as needed. Do not
+create empty directories, boilerplate controllers or a framework by convention.
+Feature names `app` and `shared` are reserved.
+
+Keep pure business rules in domain; transitions and workflows in application;
+HTTP/storage/browser services in infrastructure; DOM rendering and lifecycle in
+UI. The index composes adapters, state and views. Application receives adapters
+as explicit arguments or constructor ports, rather than importing concrete
+infrastructure. Views call application operations; infrastructure does not own
+business decisions. A public API returns data/operations, not mutable stores or
+private DOM nodes. Importing an API should define capabilities; explicit lifecycle
+methods activate them. Legacy side effects remain characterized until a reviewed
+slice safely changes their placement.
+
+Shared code has a named, proven cross-feature responsibility. `shared/domain/`
+holds pure primitives, `shared/platform/` holds narrowly scoped platform adapters,
+and `shared/ui/` holds common DOM capabilities. A named stateless root leaf such
+as `shared/actionMenuOrder.js` is also allowed and receives domain restrictions.
+Do not create a central `utils.js` collection or move feature business rules into
+shared simply to satisfy an import rule.
+
+## Mechanically checked dependency contract
+
+| Importer | Permitted maintained-source targets |
+| --- | --- |
+| App composition | Other app code, shared code, feature `index.js` APIs |
+| Feature index | Its own responsibility modules and shared code; other feature public indexes |
+| Feature domain | Its own domain and shared domain/stateless leaves |
+| Feature application | Its own application/domain, shared domain, other feature public indexes |
+| Feature infrastructure | Its own infrastructure/domain, shared domain/platform |
+| Feature UI | Its own UI/application/domain, shared domain/platform/UI |
+| Shared domain leaf | Shared domain leaves only |
+| Shared platform | Shared platform/domain only |
+| Shared UI | Shared UI/platform/domain only |
+
+No feature imports app composition. No shared code imports a feature. No external
+feature imports private responsibility modules. UI and infrastructure communicate
+with another feature through a supplied application operation/port. Maintained
+source dependency cycles, including literal lazy imports, fail the architecture
+gate. If features need bidirectional coordination, app composition injects a
+callback or adapter instead of creating mutual imports. Prefer this even when a
+one-way public index import would pass the gate.
+
+Cross-feature events must document event name, payload, acknowledgement, owner,
+subscription disposal and delivery timing. Keep them local and specific; F1 adds
+no global event bus. Preserve `odysseus:notes-context-selected` and its synchronous
+`accepted` acknowledgement in future Notes work. The server remains authoritative
+for owner filtering and untrusted selected IDs. Frontend APIs cannot grant access.
+
+The checker parses executable ESM, forbids computed imports in new source,
+requires exact precache entries, rejects unresolved/remapped relative imports,
+and permits only canonical static JS URLs with one unversioned identity for
+maintained modules. Domain code cannot mention known browser/HTTP/timer globals
+or an ambient clock; use `now`/clock inputs. This is a conservative vocabulary
+check, including shadowed names, not a semantic purity proof. Randomness, hidden
+side effects, authorization and lifecycle behavior require behavioral tests.
+
+Legacy imports from new source default to forbidden. If an incremental bridge is
+necessary, declare `legacyImports` on that source's manifest entry as a list of
+`{ "specifier": "/static/js/example.js?v=existing", "reason": "contract, owner and removal slice" }`.
+Only feature composition, infrastructure or UI boundaries may use it. Exact
+specifier/reason and target existence are required; unused exceptions fail.
+Keep the existing query identity. New domain/application modules receive no
+legacy exception. F1 has zero exceptions. Do not use exceptions to invent new
+shared platform dependencies on feature internals.
+
+## State and lifecycle
+
+Each feature has one authoritative mutable application-state owner. A transition
+operation owns writes; UI receives a view/snapshot or subscription. Preserve
+existing objects and initialization timing when extracting a stateful module.
+Do not instantiate a new store in both the legacy facade and the feature API.
+Compatibility facades only forward the same live implementation.
+
+The Notes reference uses internal read-only live views to preserve captured note
+identity across existing asynchronous completions. Its state owner supplies all
+mutations; the public index exposes operations without the store. Notes deliberately
+retains last-completion fetch ordering. Do not infer request-generation guards from
+its decomposition. Its page-owned reminders survive panel closure, and panel/editor
+listeners and observers have separate disposal scopes.
+
+Document lifecycle scopes: page, authenticated user, session, mounted panel and
+editor/draft. Name owners of subscriptions, DOM listeners, timers, observers,
+pending requests and caches. Mounting must be idempotent; disposal releases the
+resources it owns. Background reminders may outlive an open panel. Closing the
+panel must not silently stop those reminders during extraction.
+
+Keep request-generation and selected-session checks around asynchronous
+completions. Serialize writes where the current contract requires it. Dispose
+subscriptions explicitly and prevent late updates to a replaced view. Feature
+state changes on user/session switch must follow current cleanup policy. Browser
+storage is for preferences/drafts/cache state, never a substitute for backend
+authorization, credential storage or owner filtering. Define every storage key's
+owner, retention/reset behavior and compatibility format before moving it.
+
+## Creating a module or introducing a feature
+
+1. Identify responsibility, owner, public consumers, side effects and behavioral
+ evidence before editing. Start with a pure leaf when introducing a feature.
+2. Place only the required source file(s), for example
+ `features/example/domain/calculate.js`. Add an index only when there is a
+ real supported feature API to compose.
+3. Register each source in `frontend/modules.json`. A typical new mapping is
+ `features/example/domain/calculate.js` to
+ `js/features/example/domain/calculate.js`. Preserve the source/deployment
+ relative graph. The proof's legacy URL mapping is an explicit special case.
+4. For an extracted leaf, the legacy feature coordinator may import its output
+ as a temporary composition bridge. New maintained features use public indexes;
+ the legacy tree is not globally forced into the new boundary rules in F1.
+5. Add the exact output URL to the appropriate explicit SW array, retain lazy
+ evaluation timing and bump the cache name when the graph changes. Declare
+ `text eol=lf` for both mapped paths in repository-owned `.gitattributes`
+ files; source-tree or scoped output patterns are allowed. The publisher checks
+ effective Git rules, including nested overrides, and rejects a missing LF rule
+ even if output bytes already match. Do not broaden unrelated legacy checkout
+ rules or automatically rewrite all existing query identities.
+6. Run the publisher, inspect the source/output diff, then run architecture,
+ identity, graph, offline and focused behavior checks. Include both sides of
+ the mapping in review. Retiring output requires a separate reviewed deletion;
+ the publisher does not clean the static tree.
+
+```sh
+python scripts/build_frontend.py
+python scripts/build_frontend.py --check
+npm ci --ignore-scripts --no-audit --no-fund
+node scripts/check_frontend.mjs
+node scripts/check_frontend.mjs --inventory
+node --test tests/frontendArchitecture.test.mjs
+./venv/bin/python -m pytest -q -rs tests/test_frontend_build.py tests/test_frontend_foundation_offline_js.py tests/test_frontend_module_graph.py tests/test_frontend_module_version_parity.py tests/test_panel_loader_js.py
+./venv/bin/python scripts/verify_frontend_runtime.py
+```
+
+Use your actual repository virtualenv path; the F1 environment is recorded in
+validation. Node 20+ follows current CI. Existing Playwright/browser prerequisites
+are documented in `tests/README.md` and `tests/KNOWN_FAILURES.md`. Missing Node can
+skip Python browser wrappers, which is a coverage gap, not a pass. The standalone
+Node gates require locked development dependencies and fail when missing.
+
+The publisher validates all inputs before writing and only overwrites owned
+outputs whose bytes differ. It is idempotent and working-directory independent.
+Git must be available for publication and `--check`; neither runs at application
+startup. Attribute evaluation uses a private temporary Git repository and ignores
+global/local overrides, so checkout consistency is reproducible in CI. It adds
+no runtime configuration or backend imports. CI checks LF attributes, parity and source
+syntax in existing jobs; the Node job also runs architecture self-tests. Existing
+runtime identity tests remain authoritative across legacy imports, HTML and SW.
+The isolated runtime probe is included in the new pytest publication tests.
+
+## Review, release and rollback
+
+Review the source/output mapping and exact exported API, then the owner/dependency
+contract and behavior tests. Check manifests, URL identities, MIME/CSP, load timing,
+storage compatibility and disposal. Reject unexplained feature behavior changes.
+Do not repair unrelated defects under an extraction title.
+
+Release from a validated revision with committed output. Native startup and
+packagers consume static files without a compiler. Run parity before producing a
+Docker or desktop artifact. Test the actual packaged application on its platform;
+Linux contract probes cannot certify macOS/Windows executables. Deploy matching
+shell, facades, graph and manifests as a unit. Keep an authorized path to the last
+complete artifact. Rollback restores the whole matching set, not just an entry
+file or cache version. Do not delete a facade until its public consumers have
+migrated and compatibility tests make that decision reviewable.
+
+## Proposal and PR templates
+
+For a decomposition proposal, record: baseline; responsibility map; current public
+API and consumers; state owner; I/O and lifecycle boundaries; planned slice;
+allowed dependencies/temporary exceptions; preserved behavior; deterministic
+characterization tests; deployment/offline changes; overlapping PRs; rollback;
+explicit non-goals and remaining uncertainties.
+
+For each migration PR, lead with the responsibility moved and resulting boundary.
+Record source/output paths, API compatibility, state/lifecycle ownership,
+characterization results, exact validation commands, platform gaps, exception
+removal plan, upstream dependencies and rollback. Attach a concrete before/after
+example when needed to establish behavioral equivalence. Preserve the repository
+PR template and never claim unexecuted checks.
+
+F1 is an entirely separate foundation-only PR. Deliver the complete Notes
+decomposition, regression tests, compatibility validation and final reference
+case study through one draft PR targeting official `dev`, using one Notes branch
+and worktree after F1 integration. N0 through N6 and the N5 substages are internal
+engineering checkpoints, not independent PRs or merges. Each checkpoint records
+focused tests, review evidence, its validated revision or reproducible snapshot,
+and rollback to the prior matching source/output/facade/precache set. Keep the
+draft open while those checkpoints progress; mark it ready only after the entire
+decomposition passes the [roadmap's acceptance gates](notes-roadmap.md).
+
+Structure the Notes PR description around the final integrated design and link
+each checkpoint's evidence. The receiving maintainer may use smaller independent
+PRs for future frontend features at their discretion; the one-PR Notes decision
+does not impose that delivery size on later work.
+
+## Program backlog and final handoff
+
+Priority order: review/integrate F1; resolve root offline certification with the
+owner of PR #6227; complete the Notes checkpoints and final reference case study
+within one draft PR following the [roadmap](notes-roadmap.md); integrate the
+complete Notes PR after its acceptance gates; finalize the recipient handoff.
+Only then does the receiving maintainer prioritize Calendar, Documents, Email,
+Chat, Skills and Settings against current behavior and risk. Existing partial
+packages and high fan-in helpers need assessment, not automatic replacement.
+
+Final H acceptance requires a designated maintainer, the integrated Notes PR
+revision and its internal checkpoint receipts, the actual public API/state/lifecycle
+map and final reference case study included in that PR, validated deployment/offline
+commands, known exceptions/debt,
+outstanding PR dependencies, rollback evidence and a reproducible independent
+setup by the recipient. F1 provides the handbook structure and contracts; it does
+not claim Notes or the completed handoff have occurred. The initiating architect
+then returns to separately authorized non-frontend architecture work.
diff --git a/docs/frontend-architecture/notes-case-study.md b/docs/frontend-architecture/notes-case-study.md
new file mode 100644
index 000000000..cc1a28d7e
--- /dev/null
+++ b/docs/frontend-architecture/notes-case-study.md
@@ -0,0 +1,260 @@
+# Notes reference decomposition
+
+Implementation started: 2026-10-13. Final validation: 2026-10-14.
+Foundation: [PR #6701](https://github.com/odysseus-dev/odysseus/pull/6701),
+`1cc56cb9d78f3e2399d1d61155b71d771a17b85b`. Branch was safely updated via
+non-destructive fast-forward to latest official `upstream/dev` at
+`86b886c611338282af6d4a717246ea4e256f58df`, incorporating PRs #6704 and #6693.
+Neither changed a file in the Notes diff. The independent AGY audit returned
+CONDITIONAL PASS; all pre-publication corrective actions (issue template conformance,
+PR template conformance, visual evidence paths, and em-dash removal) have been completed.
+
+The entire implementation belongs to one Notes PR. N0 through N6 are internal
+checkpoints, not separate branches, commits or PRs. The [validation receipts](notes-validation.md),
+[module inventory](notes-module-inventory.md) and [changed-file inventory](notes-changed-files.md)
+accompany this case study.
+
+## Responsibility map and size
+
+The original `static/js/notes.js` contained 5,471 lines. It mixed mutable Notes
+data, view preferences, selection, undo, CRUD, date calculations, reminders,
+browser persistence, editor autosave, rendering, canvas tools and window management.
+Its import evaluated storage preferences and scheduled reminder initialization.
+
+| Original responsibility | Maintained owner |
+| --- | --- |
+| Completion, tags, recurrence, date labels and serialization | `domain/recurrence.js`, `domain/noteRules.js` |
+| Notes data and selection/filter/editing state | `application/state.js`, instantiated once in `index.js` |
+| CRUD, undo and fetch completion ordering | `application/workflows.js`, `cardOperations.js`, `deletion.js` |
+| Checklist mutations and rollback | `application/checklistOperations.js` |
+| Editor optimistic submission and recovery | `application/submission.js` |
+| Serialized autosave and synchronous backup | `application/drafts.js`; form collection in `ui/draftEditor.js` |
+| Filtering, searching and ordering | `application/queries.js`; controls in `ui/filters.js` and `toolbar.js` |
+| Selected-note attachment and bulk requests | `application/selection.js`; controls in `ui/selection.js` |
+| Existing agent-solve workflow | `application/agentActions.js`, through supplied HTTP/session ports |
+| HTTP, persistence and browser notifications | `infrastructure/http.js`, `storage.js`, `notifications.js` |
+| Background scheduler and delivery decisions | `application/reminders.js` |
+| Panel mounting, closing, keyboard handling and navigation | `ui/panel.js` |
+| Docking, fullscreen bounds and stacking | `ui/windowLayout.js`, using existing shared capabilities |
+| Cards, card gestures, quick add and masonry | `ui/cardRendering.js`, `cardInteractions.js`, `cardChecklist.js`, `cardReorder.js`, `quickAdd.js`, `layout.js` |
+| Editor types, colors, reminders and checklists | `ui/editor.js`, `colors.js`, `reminderPicker.js`, `checklist.js` |
+| Drawing, local drawing undo and PNG upload | `ui/drawing.js` |
+| Mobile reader/editor and reorder gestures | `ui/mobileEditor.js`, `mobileReorder.js`, `checklistReorder.js` |
+| Clipboard, safe rendering and reminder display | `ui/clipboard.js`, `text.js`, `reminderDisplay.js` |
+| Owned document/window listener disposal | `ui/lifecycle.js`, with panel and observer disposal callbacks |
+| Composition and supported exports | `index.js`; five-line legacy facade at `static/js/notes.js` |
+
+The feature has 41 maintained modules: two domain, eleven application, three
+infrastructure, twenty-four UI and one index. Source is counted once, excluding
+byte-identical deployment copies. Domain has 356 lines, application 826,
+infrastructure 112, UI 4,628, and composition 518: 6,440 maintained feature lines.
+The module inventory records final per-file counts. The legacy entry shrank
+from 5,471 to five lines. Interfaces and explicit composition increase the total
+source size; reducing total lines was not the architectural objective.
+
+One 28-line stateless confetti renderer also moved to `shared/ui/confetti.js`.
+Notes and Compare both use it. Compare retains its existing `spawnConfetti` export,
+which is the same function as the shared export. This removes Notes' import of
+Compare's private voting implementation without migrating Compare itself.
+
+## Dependency graph and composition
+
+```mermaid
+flowchart TD
+ Legacy[Legacy Notes URL and window bridge] --> Index[Notes index: one composition]
+ Index --> UI[Notes UI factories]
+ Index --> App[Application workflows and state owner]
+ Index --> Ports[HTTP, persistence and notification adapters]
+ UI --> Rules[Pure domain rules]
+ App --> Rules
+ Index --> Shared[Existing shared UI capabilities and maintained confetti]
+```
+
+Application modules receive adapters and feedback operations as arguments. They
+do not import browser infrastructure or DOM views. Pure domain modules receive
+the clock at the original read sites. UI consumes a read-only state view and
+application operations. Composition supplies callbacks between views and workflows;
+modules do not import the coordinator back. F1 rejects maintained-source cycles.
+
+There are nine exact legacy-import exceptions, all on the Notes index. They bridge
+the existing UI, modal, color-picker, drag, tile, dock, stacking, Escape and tour-hint
+capabilities at their existing URLs. Their removal condition is migration of the
+corresponding shared responsibility to maintained source with its identity and
+lifecycle contract verified. No new feature imports another feature's private internals.
+
+## State and asynchronous ownership
+
+`createNotesState` is called once. It owns the Notes collection, selection IDs,
+editing ID, search, filters, archive/view flags, loading and dismissed-reminder time.
+Neither the facade nor reminders create a second collection. The public feature API
+does not expose this store.
+
+Internal views are read-only live views rather than detached snapshots. This choice
+preserves captured note identity: an existing asynchronous rollback still acts on
+the same captured note. Array/object writes and selection mutations must use the
+state owner's operations. Workflow-local undo queues and serialized draft promises,
+and UI-local canvas undo/gesture state, are not competing Notes stores.
+
+Fetches retain the original last-completion behavior. An earlier request that
+finishes later can overwrite a later request's result. Tests pin this behavior;
+generation guards would be a separate behavioral change. Submission also retains
+the original first-temporary-note replacement rule. Multiple simultaneous creations
+need a separately reviewed correlation fix, not a silent change during extraction.
+
+Archive, unarchive, pin, item edit/remove/add, delete and undo preserve their original
+optimistic ordering and rollback. Animation callbacks remain view-owned. Drawing
+save keeps the existing button guard around its asynchronous PNG upload. Draft writes
+are serialized per editor; a completed older save cannot clear a newer local draft.
+
+Reminder scans still use the originally loaded Notes collection, not a second
+all-active cache. An archived-only collection or a failure-cleared list can defer
+active reminders until an active refresh/reopen. The timer remains alive when the
+panel closes, but extraction does not redesign this inherited data-availability
+limitation. Review such a change separately from scheduler/state ownership.
+
+## Public compatibility
+
+The import URL remains `/static/js/notes.js?v=20260911notesselectioncancel1`.
+App, Chat stream updates, Chat note links and Documents continue using their existing
+imports. Calendar and Documents retain their window bridge calls. HTML and app
+bootstrap code are unchanged. The service worker retains the exact legacy entry.
+
+The legacy namespace still exports `openPanel`, `closePanel`, `togglePanel`,
+`isPanelOpen`, `openNote`, `newNote`, `refreshDueBadge`, `dismissFiredReminderDot`,
+`openNotes`, `closeNotes`, `isNotesOpen`, and `default`.
+The default object's ten methods are unchanged; `dismissFiredReminderDot` remains
+named-only. Aliases refer to the same functions, including those on the default
+object. `openNote` and `refreshDueBadge` remain async; function arities are pinned.
+
+`window.notesModule` is exactly the default controller. The canonical unversioned
+feature index and both tested legacy entry URLs share the same controller and
+operations. The default object retains its existing mutability. A different legacy
+URL has its own ESM namespace, as native ESM requires, but creates no second store
+or scheduler because it forwards to the same canonical index.
+
+The canonical index additionally exports `startNotesBackground` for explicit
+activation. The compatibility facade invokes it once through an idempotent start
+operation. Existing consumers need no change. Remove the facade only after every
+consumer, global bridge, bootstrap and offline reference has migrated together.
+
+## Protected selected Notes/Todos integration
+
+The sender dispatches `odysseus:notes-context-selected` on `window` with
+`{ noteIds, accepted: false }`. Dispatch and acknowledgement remain synchronous.
+Chat owns acceptance, its session/pending selection, the context indicator and
+the `selected_note_ids` send payload. Notes exits selection only after acceptance.
+Rejected selections stay selected and display the existing feedback.
+
+No Chat internals were imported or changed. Existing session lifecycle events still
+transfer a pending selection on materialization, restore selections on chat switches,
+and reset them for a new chat. Backend ID validation and owner filtering remain
+authoritative. Unit/backend tests cover these contracts; the real authenticated
+browser probe verifies rejection, pending-chat acceptance, the actual indicator and
+new-chat reset. Live model execution is not part of that probe.
+
+## Persistence and HTTP contracts
+
+| Key | Preserved format |
+| --- | --- |
+| `odysseus-notes-view` | `list` or `grid` |
+| `odysseus-notes-labels-collapsed` | `1` or `0` |
+| `odysseus-notes-first-open-hint-v1` | Existing first-open marker |
+| `odysseus-notes-reminder-fired` | JSON array of IDs |
+| `odysseus-notes-reminder-glowed` | JSON array of IDs |
+| `odysseus-notes-reminder-pending-highlight` | JSON array of IDs |
+| `odysseus-notes-reminder-active-highlight` | JSON array of IDs |
+| `odysseus-notes-reminder-dismissed-at` | Decimal millisecond timestamp |
+| `odysseus-note-draft-` and `odysseus-note-draft-__new__` | Existing JSON draft fields and `_ts` |
+
+CRUD, reorder, upload, reminder firing, default-chat lookup, session creation and
+chat-stream requests keep their URLs, methods, credentials, payloads and error
+interpretation. Uploads retain `files` and optional `gallery_id` multipart fields.
+The agent-solve stream still disables `manage_notes` and drains without switching
+the user's chat. No backend implementation changed.
+
+Storage backup failures still warn once; failed network saves keep recoverable
+drafts, including intentionally empty text. Draft JSON does not serialize a canvas
+bitmap. A drawing remains ephemeral until its explicit PNG upload, as before.
+
+## Lifecycle scopes and explicit corrections
+
+| Scope | Owner and disposal |
+| --- | --- |
+| Browser page | One reminder startup timeout and interval; page termination ends them. The reminder factory also has explicit disposal. |
+| Open panel | Capture/bubble keyboard handlers, reorder listeners and masonry observer; both close paths dispose them. |
+| Editor/canvas | Local DOM handlers and draft workflow; drawing's window listener is released when its canvas detaches or the panel closes. |
+| Mobile editor/gesture | Overlay and document touch handlers; owner replacement and panel disposal remove handlers and reset registration flags. |
+| Menus/hints | Notes portals close with the panel; shared dismiss functions unregister their Escape/tour lifetimes. |
+| File picker | Existing completion or 30-second cleanup owns the temporary input. |
+
+Two implementation corrections follow the user's explicit lifecycle requirements.
+The original close paths canceled the supposedly background reminder interval.
+The new page-owned interval survives closing/minimizing Notes, while retaining the
+3-second startup delay, 30-second period and immediate first check. Closing a panel
+also releases owned observers/listeners, pending hold timers, active Notes gestures
+and portals; late panel fetch callbacks do
+not recreate UI on a detached panel. Network completion/state ordering is preserved.
+
+Shared drag/window utilities continue owning their own active-gesture handlers.
+They were not moved into Notes. Idle open/close and editor replacement are verified;
+every possible interleaving with an active shared window drag was not tested.
+
+## Source and deployment
+
+Every maintained source is registered in `frontend/modules.json` and copied without
+rewriting imports. Notes sources map to `static/js/features/notes/` at the same
+relative paths. Shared confetti maps to `static/js/shared/ui/confetti.js`.
+Repository-owned LF attributes and byte parity cover all 43 maintained modules,
+including the unchanged F1 proof. The legacy facade is an authored compatibility
+entry, not a second implementation.
+
+All new outputs join exact service-worker precache arrays. A real offline test also
+found eight previously missing exact legacy URLs in the Notes graph; those entries
+are now included. The eager Notes graph has 57 exact runtime URLs. Cache naming
+follows the repository's `odysseus-v659-notes-reference` convention. Root offline
+reload remains outside certification because the existing worker scope is `/static/`.
+
+Python startup and Docker serve the committed static graph without maintained
+source or frontend tooling. The publisher is a development check/copy operation,
+not a runtime compiler or an atomic deployment system.
+
+## Checkpoints, rollback and lessons
+
+[Checkpoint receipts](notes-validation.md#internal-checkpoints) record the actual
+checks and local snapshot hashes. These intermediate snapshots are engineering
+evidence, not standalone release artifacts. N5 includes bounded editor, cards,
+checklist, drawing, mobile, toolbar and window reviews on the same branch.
+
+The N3 mechanical state rewrite initially confused canvas-local and feature undo
+bindings. The N5 drawing test found it; the canvas binding was restored and the
+same drawing/undo interaction was replayed against the original implementation.
+Use scope-aware transformations and test each stateful UI responsibility before
+accepting a broad rewrite. Source parsing alone does not prove semantic equivalence.
+
+For rollback, reconstruct the prior complete artifact from its revision/snapshot
+in a fresh temporary directory, run parity/graph/behavior checks there, then publish
+the matching static graph and service worker as a unit through the authorized
+release process. Restore the whole facade/source/output/manifest set, not just
+`notes.js`. No schema or storage-key migration needs reversal. Do not reset a dirty
+worktree or delete unrelated outputs. The validation report gives a non-destructive
+snapshot reproduction recipe.
+
+For the next maintainer:
+
+1. Start with the module inventory and the state/workflow contracts, then reproduce
+ the focused tests, offline test and isolated native browser probe.
+2. Review the explicit timer/lifecycle corrections separately from unchanged
+ business rules. Inspect both maintained source and byte-identical deployment.
+3. Resolve or track the reproduced upstream CI failures and the open PR overlaps
+ before authorizing publication. Create/link the dedicated issue, then publish
+ exactly one Notes PR targeting official `dev`.
+4. Record the integrated revision and independent recipient reproduction to complete
+ H. The designated maintainer can then apply this method to future features.
+
+For Calendar, Documents, Email and later monoliths, characterize actual exports,
+URL identities, state writers, clock reads, I/O and lifecycle first. Extract pure
+rules, then adapters, then a single state owner/workflows. Use explicit callback
+ports to break coordinator cycles. Split UI by interactions and resource lifetime,
+not by arbitrary line ranges. Transfer source/output ownership and offline URLs
+with each boundary, and preserve source-sensitive assertions at their new owner.
+Those feature migrations are not part of this implementation.
diff --git a/docs/frontend-architecture/notes-changed-files.md b/docs/frontend-architecture/notes-changed-files.md
new file mode 100644
index 000000000..02f916e46
--- /dev/null
+++ b/docs/frontend-architecture/notes-changed-files.md
@@ -0,0 +1,165 @@
+# Notes complete changed-file inventory
+
+Changed files in PR #6713 (`refactor/notes-reference-decomposition`) against
+`dev`. 121 files: 16 modified and 105 added. No files are deleted. Deployment copies
+are byte-identical to their registered maintained sources. Image files are review
+evidence, not production dependencies.
+
+The unchanged foundation worktree, backend, app bootstrap, HTML, CSS, dependency
+lockfiles, Dockerfile and CI workflow are outside this diff. The only Compare
+change delegates its existing stateless confetti export to maintained shared UI.
+
+## Maintained source (42)
+
+| Status | File |
+| --- | --- |
+| A | [frontend/src/features/notes/application/agentActions.js](../../frontend/src/features/notes/application/agentActions.js) |
+| A | [frontend/src/features/notes/application/cardOperations.js](../../frontend/src/features/notes/application/cardOperations.js) |
+| A | [frontend/src/features/notes/application/checklistOperations.js](../../frontend/src/features/notes/application/checklistOperations.js) |
+| A | [frontend/src/features/notes/application/deletion.js](../../frontend/src/features/notes/application/deletion.js) |
+| A | [frontend/src/features/notes/application/drafts.js](../../frontend/src/features/notes/application/drafts.js) |
+| A | [frontend/src/features/notes/application/queries.js](../../frontend/src/features/notes/application/queries.js) |
+| A | [frontend/src/features/notes/application/reminders.js](../../frontend/src/features/notes/application/reminders.js) |
+| A | [frontend/src/features/notes/application/selection.js](../../frontend/src/features/notes/application/selection.js) |
+| A | [frontend/src/features/notes/application/state.js](../../frontend/src/features/notes/application/state.js) |
+| A | [frontend/src/features/notes/application/submission.js](../../frontend/src/features/notes/application/submission.js) |
+| A | [frontend/src/features/notes/application/workflows.js](../../frontend/src/features/notes/application/workflows.js) |
+| A | [frontend/src/features/notes/domain/noteRules.js](../../frontend/src/features/notes/domain/noteRules.js) |
+| A | [frontend/src/features/notes/domain/recurrence.js](../../frontend/src/features/notes/domain/recurrence.js) |
+| A | [frontend/src/features/notes/index.js](../../frontend/src/features/notes/index.js) |
+| A | [frontend/src/features/notes/infrastructure/http.js](../../frontend/src/features/notes/infrastructure/http.js) |
+| A | [frontend/src/features/notes/infrastructure/notifications.js](../../frontend/src/features/notes/infrastructure/notifications.js) |
+| A | [frontend/src/features/notes/infrastructure/storage.js](../../frontend/src/features/notes/infrastructure/storage.js) |
+| A | [frontend/src/features/notes/ui/cardChecklist.js](../../frontend/src/features/notes/ui/cardChecklist.js) |
+| A | [frontend/src/features/notes/ui/cardInteractions.js](../../frontend/src/features/notes/ui/cardInteractions.js) |
+| A | [frontend/src/features/notes/ui/cardRendering.js](../../frontend/src/features/notes/ui/cardRendering.js) |
+| A | [frontend/src/features/notes/ui/cardReorder.js](../../frontend/src/features/notes/ui/cardReorder.js) |
+| A | [frontend/src/features/notes/ui/checklist.js](../../frontend/src/features/notes/ui/checklist.js) |
+| A | [frontend/src/features/notes/ui/checklistReorder.js](../../frontend/src/features/notes/ui/checklistReorder.js) |
+| A | [frontend/src/features/notes/ui/clipboard.js](../../frontend/src/features/notes/ui/clipboard.js) |
+| A | [frontend/src/features/notes/ui/colors.js](../../frontend/src/features/notes/ui/colors.js) |
+| A | [frontend/src/features/notes/ui/draftEditor.js](../../frontend/src/features/notes/ui/draftEditor.js) |
+| A | [frontend/src/features/notes/ui/drawing.js](../../frontend/src/features/notes/ui/drawing.js) |
+| A | [frontend/src/features/notes/ui/editor.js](../../frontend/src/features/notes/ui/editor.js) |
+| A | [frontend/src/features/notes/ui/filters.js](../../frontend/src/features/notes/ui/filters.js) |
+| A | [frontend/src/features/notes/ui/layout.js](../../frontend/src/features/notes/ui/layout.js) |
+| A | [frontend/src/features/notes/ui/lifecycle.js](../../frontend/src/features/notes/ui/lifecycle.js) |
+| A | [frontend/src/features/notes/ui/mobileEditor.js](../../frontend/src/features/notes/ui/mobileEditor.js) |
+| A | [frontend/src/features/notes/ui/mobileReorder.js](../../frontend/src/features/notes/ui/mobileReorder.js) |
+| A | [frontend/src/features/notes/ui/panel.js](../../frontend/src/features/notes/ui/panel.js) |
+| A | [frontend/src/features/notes/ui/quickAdd.js](../../frontend/src/features/notes/ui/quickAdd.js) |
+| A | [frontend/src/features/notes/ui/reminderDisplay.js](../../frontend/src/features/notes/ui/reminderDisplay.js) |
+| A | [frontend/src/features/notes/ui/reminderPicker.js](../../frontend/src/features/notes/ui/reminderPicker.js) |
+| A | [frontend/src/features/notes/ui/selection.js](../../frontend/src/features/notes/ui/selection.js) |
+| A | [frontend/src/features/notes/ui/text.js](../../frontend/src/features/notes/ui/text.js) |
+| A | [frontend/src/features/notes/ui/toolbar.js](../../frontend/src/features/notes/ui/toolbar.js) |
+| A | [frontend/src/features/notes/ui/windowLayout.js](../../frontend/src/features/notes/ui/windowLayout.js) |
+| A | [frontend/src/shared/ui/confetti.js](../../frontend/src/shared/ui/confetti.js) |
+
+## Deployment copies (42)
+
+| Status | File |
+| --- | --- |
+| A | [static/js/features/notes/application/agentActions.js](../../static/js/features/notes/application/agentActions.js) |
+| A | [static/js/features/notes/application/cardOperations.js](../../static/js/features/notes/application/cardOperations.js) |
+| A | [static/js/features/notes/application/checklistOperations.js](../../static/js/features/notes/application/checklistOperations.js) |
+| A | [static/js/features/notes/application/deletion.js](../../static/js/features/notes/application/deletion.js) |
+| A | [static/js/features/notes/application/drafts.js](../../static/js/features/notes/application/drafts.js) |
+| A | [static/js/features/notes/application/queries.js](../../static/js/features/notes/application/queries.js) |
+| A | [static/js/features/notes/application/reminders.js](../../static/js/features/notes/application/reminders.js) |
+| A | [static/js/features/notes/application/selection.js](../../static/js/features/notes/application/selection.js) |
+| A | [static/js/features/notes/application/state.js](../../static/js/features/notes/application/state.js) |
+| A | [static/js/features/notes/application/submission.js](../../static/js/features/notes/application/submission.js) |
+| A | [static/js/features/notes/application/workflows.js](../../static/js/features/notes/application/workflows.js) |
+| A | [static/js/features/notes/domain/noteRules.js](../../static/js/features/notes/domain/noteRules.js) |
+| A | [static/js/features/notes/domain/recurrence.js](../../static/js/features/notes/domain/recurrence.js) |
+| A | [static/js/features/notes/index.js](../../static/js/features/notes/index.js) |
+| A | [static/js/features/notes/infrastructure/http.js](../../static/js/features/notes/infrastructure/http.js) |
+| A | [static/js/features/notes/infrastructure/notifications.js](../../static/js/features/notes/infrastructure/notifications.js) |
+| A | [static/js/features/notes/infrastructure/storage.js](../../static/js/features/notes/infrastructure/storage.js) |
+| A | [static/js/features/notes/ui/cardChecklist.js](../../static/js/features/notes/ui/cardChecklist.js) |
+| A | [static/js/features/notes/ui/cardInteractions.js](../../static/js/features/notes/ui/cardInteractions.js) |
+| A | [static/js/features/notes/ui/cardRendering.js](../../static/js/features/notes/ui/cardRendering.js) |
+| A | [static/js/features/notes/ui/cardReorder.js](../../static/js/features/notes/ui/cardReorder.js) |
+| A | [static/js/features/notes/ui/checklist.js](../../static/js/features/notes/ui/checklist.js) |
+| A | [static/js/features/notes/ui/checklistReorder.js](../../static/js/features/notes/ui/checklistReorder.js) |
+| A | [static/js/features/notes/ui/clipboard.js](../../static/js/features/notes/ui/clipboard.js) |
+| A | [static/js/features/notes/ui/colors.js](../../static/js/features/notes/ui/colors.js) |
+| A | [static/js/features/notes/ui/draftEditor.js](../../static/js/features/notes/ui/draftEditor.js) |
+| A | [static/js/features/notes/ui/drawing.js](../../static/js/features/notes/ui/drawing.js) |
+| A | [static/js/features/notes/ui/editor.js](../../static/js/features/notes/ui/editor.js) |
+| A | [static/js/features/notes/ui/filters.js](../../static/js/features/notes/ui/filters.js) |
+| A | [static/js/features/notes/ui/layout.js](../../static/js/features/notes/ui/layout.js) |
+| A | [static/js/features/notes/ui/lifecycle.js](../../static/js/features/notes/ui/lifecycle.js) |
+| A | [static/js/features/notes/ui/mobileEditor.js](../../static/js/features/notes/ui/mobileEditor.js) |
+| A | [static/js/features/notes/ui/mobileReorder.js](../../static/js/features/notes/ui/mobileReorder.js) |
+| A | [static/js/features/notes/ui/panel.js](../../static/js/features/notes/ui/panel.js) |
+| A | [static/js/features/notes/ui/quickAdd.js](../../static/js/features/notes/ui/quickAdd.js) |
+| A | [static/js/features/notes/ui/reminderDisplay.js](../../static/js/features/notes/ui/reminderDisplay.js) |
+| A | [static/js/features/notes/ui/reminderPicker.js](../../static/js/features/notes/ui/reminderPicker.js) |
+| A | [static/js/features/notes/ui/selection.js](../../static/js/features/notes/ui/selection.js) |
+| A | [static/js/features/notes/ui/text.js](../../static/js/features/notes/ui/text.js) |
+| A | [static/js/features/notes/ui/toolbar.js](../../static/js/features/notes/ui/toolbar.js) |
+| A | [static/js/features/notes/ui/windowLayout.js](../../static/js/features/notes/ui/windowLayout.js) |
+| A | [static/js/shared/ui/confetti.js](../../static/js/shared/ui/confetti.js) |
+
+## Compatibility and deployment configuration (5)
+
+| Status | File |
+| --- | --- |
+| M | [.gitattributes](../../.gitattributes) |
+| M | [frontend/modules.json](../../frontend/modules.json) |
+| M | [static/js/compare/vote.js](../../static/js/compare/vote.js) |
+| M | [static/js/notes.js](../../static/js/notes.js) |
+| M | [static/sw.js](../../static/sw.js) |
+
+## Tests (21)
+
+| Status | File |
+| --- | --- |
+| A | [tests/browser/notesNative.mjs](../../tests/browser/notesNative.mjs) |
+| A | [tests/browser/notesOffline.mjs](../../tests/browser/notesOffline.mjs) |
+| A | [tests/browser/notesReference.mjs](../../tests/browser/notesReference.mjs) |
+| A | [tests/fixtures/notesRecurrenceBaseline.mjs](../../tests/fixtures/notesRecurrenceBaseline.mjs) |
+| A | [tests/helpers/notes_source.py](../../tests/helpers/notes_source.py) |
+| A | [tests/notesApplication.test.mjs](../../tests/notesApplication.test.mjs) |
+| A | [tests/notesCharacterization.test.mjs](../../tests/notesCharacterization.test.mjs) |
+| M | [tests/notesDraftAutosave.test.mjs](../../tests/notesDraftAutosave.test.mjs) |
+| A | [tests/notesInfrastructure.test.mjs](../../tests/notesInfrastructure.test.mjs) |
+| A | [tests/notesRecurrence.test.mjs](../../tests/notesRecurrence.test.mjs) |
+| A | [tests/notesReminders.test.mjs](../../tests/notesReminders.test.mjs) |
+| A | [tests/notesWorkflows.test.mjs](../../tests/notesWorkflows.test.mjs) |
+| M | [tests/selectedNotesContext.test.mjs](../../tests/selectedNotesContext.test.mjs) |
+| M | [tests/test_notes_document_mutual_minimize.py](../../tests/test_notes_document_mutual_minimize.py) |
+| M | [tests/test_notes_dom_xss_helpers.py](../../tests/test_notes_dom_xss_helpers.py) |
+| M | [tests/test_notes_mobile_checklist_toggle_static.py](../../tests/test_notes_mobile_checklist_toggle_static.py) |
+| A | [tests/test_notes_reference_browser.py](../../tests/test_notes_reference_browser.py) |
+| A | [tests/test_notes_reference_contracts_js.py](../../tests/test_notes_reference_contracts_js.py) |
+| M | [tests/test_notes_search_reset_on_reopen_js.py](../../tests/test_notes_search_reset_on_reopen_js.py) |
+| M | [tests/test_notes_select_esc_listener_js.py](../../tests/test_notes_select_esc_listener_js.py) |
+| M | [tests/test_notes_sidebar_new_note.py](../../tests/test_notes_sidebar_new_note.py) |
+
+## Runtime validation (2)
+
+| Status | File |
+| --- | --- |
+| M | [scripts/verify_frontend_runtime.py](../../scripts/verify_frontend_runtime.py) |
+| A | [scripts/verify_notes_browser_runtime.py](../../scripts/verify_notes_browser_runtime.py) |
+
+## Documentation and execution receipts (9)
+
+| Status | File |
+| --- | --- |
+| A | [docs/frontend-architecture/evidence/notes/implementation.sha256](../../docs/frontend-architecture/evidence/notes/implementation.sha256) |
+| A | [docs/frontend-architecture/evidence/notes/native-desktop.png](../../docs/frontend-architecture/evidence/notes/native-desktop.png) |
+| A | [docs/frontend-architecture/evidence/notes/native-mobile.png](../../docs/frontend-architecture/evidence/notes/native-mobile.png) |
+| M | [docs/frontend-architecture/handbook.md](../../docs/frontend-architecture/handbook.md) |
+| A | [docs/frontend-architecture/notes-case-study.md](../../docs/frontend-architecture/notes-case-study.md) |
+| A | [docs/frontend-architecture/notes-changed-files.md](../../docs/frontend-architecture/notes-changed-files.md) |
+| A | [docs/frontend-architecture/notes-module-inventory.md](../../docs/frontend-architecture/notes-module-inventory.md) |
+| M | [docs/frontend-architecture/notes-roadmap.md](../../docs/frontend-architecture/notes-roadmap.md) |
+| A | [docs/frontend-architecture/notes-validation.md](../../docs/frontend-architecture/notes-validation.md) |
+
+See [the case study](notes-case-study.md) for ownership and handoff,
+[the module inventory](notes-module-inventory.md) for line counts, and
+[the validation report](notes-validation.md) for exact executed checks.
diff --git a/docs/frontend-architecture/notes-module-inventory.md b/docs/frontend-architecture/notes-module-inventory.md
new file mode 100644
index 000000000..5d8184858
--- /dev/null
+++ b/docs/frontend-architecture/notes-module-inventory.md
@@ -0,0 +1,56 @@
+# Notes source and deployment inventory
+
+The feature has 41 maintained modules. The unchanged F1 action-menu proof and
+shared confetti bring the full manifest to 43. Outputs are copied byte-for-byte;
+count maintained source once. The legacy entry is a five-line compatibility facade.
+
+| Source under frontend/src | Deployment under static | Lines | Layer |
+| --- | --- | ---: | --- |
+| [features/notes/application/agentActions.js](../../frontend/src/features/notes/application/agentActions.js) | [js/features/notes/application/agentActions.js](../../static/js/features/notes/application/agentActions.js) | 67 | application |
+| [features/notes/application/cardOperations.js](../../frontend/src/features/notes/application/cardOperations.js) | [js/features/notes/application/cardOperations.js](../../static/js/features/notes/application/cardOperations.js) | 79 | application |
+| [features/notes/application/checklistOperations.js](../../frontend/src/features/notes/application/checklistOperations.js) | [js/features/notes/application/checklistOperations.js](../../static/js/features/notes/application/checklistOperations.js) | 68 | application |
+| [features/notes/application/deletion.js](../../frontend/src/features/notes/application/deletion.js) | [js/features/notes/application/deletion.js](../../static/js/features/notes/application/deletion.js) | 51 | application |
+| [features/notes/application/drafts.js](../../frontend/src/features/notes/application/drafts.js) | [js/features/notes/application/drafts.js](../../static/js/features/notes/application/drafts.js) | 55 | application |
+| [features/notes/application/queries.js](../../frontend/src/features/notes/application/queries.js) | [js/features/notes/application/queries.js](../../static/js/features/notes/application/queries.js) | 66 | application |
+| [features/notes/application/reminders.js](../../frontend/src/features/notes/application/reminders.js) | [js/features/notes/application/reminders.js](../../static/js/features/notes/application/reminders.js) | 182 | application |
+| [features/notes/application/selection.js](../../frontend/src/features/notes/application/selection.js) | [js/features/notes/application/selection.js](../../static/js/features/notes/application/selection.js) | 39 | application |
+| [features/notes/application/state.js](../../frontend/src/features/notes/application/state.js) | [js/features/notes/application/state.js](../../static/js/features/notes/application/state.js) | 72 | application |
+| [features/notes/application/submission.js](../../frontend/src/features/notes/application/submission.js) | [js/features/notes/application/submission.js](../../static/js/features/notes/application/submission.js) | 69 | application |
+| [features/notes/application/workflows.js](../../frontend/src/features/notes/application/workflows.js) | [js/features/notes/application/workflows.js](../../static/js/features/notes/application/workflows.js) | 78 | application |
+| [features/notes/domain/noteRules.js](../../frontend/src/features/notes/domain/noteRules.js) | [js/features/notes/domain/noteRules.js](../../static/js/features/notes/domain/noteRules.js) | 87 | domain |
+| [features/notes/domain/recurrence.js](../../frontend/src/features/notes/domain/recurrence.js) | [js/features/notes/domain/recurrence.js](../../static/js/features/notes/domain/recurrence.js) | 269 | domain |
+| [features/notes/index.js](../../frontend/src/features/notes/index.js) | [js/features/notes/index.js](../../static/js/features/notes/index.js) | 518 | composition |
+| [features/notes/infrastructure/http.js](../../frontend/src/features/notes/infrastructure/http.js) | [js/features/notes/infrastructure/http.js](../../static/js/features/notes/infrastructure/http.js) | 29 | infrastructure |
+| [features/notes/infrastructure/notifications.js](../../frontend/src/features/notes/infrastructure/notifications.js) | [js/features/notes/infrastructure/notifications.js](../../static/js/features/notes/infrastructure/notifications.js) | 20 | infrastructure |
+| [features/notes/infrastructure/storage.js](../../frontend/src/features/notes/infrastructure/storage.js) | [js/features/notes/infrastructure/storage.js](../../static/js/features/notes/infrastructure/storage.js) | 63 | infrastructure |
+| [features/notes/ui/cardChecklist.js](../../frontend/src/features/notes/ui/cardChecklist.js) | [js/features/notes/ui/cardChecklist.js](../../static/js/features/notes/ui/cardChecklist.js) | 148 | ui |
+| [features/notes/ui/cardInteractions.js](../../frontend/src/features/notes/ui/cardInteractions.js) | [js/features/notes/ui/cardInteractions.js](../../static/js/features/notes/ui/cardInteractions.js) | 337 | ui |
+| [features/notes/ui/cardRendering.js](../../frontend/src/features/notes/ui/cardRendering.js) | [js/features/notes/ui/cardRendering.js](../../static/js/features/notes/ui/cardRendering.js) | 244 | ui |
+| [features/notes/ui/cardReorder.js](../../frontend/src/features/notes/ui/cardReorder.js) | [js/features/notes/ui/cardReorder.js](../../static/js/features/notes/ui/cardReorder.js) | 181 | ui |
+| [features/notes/ui/checklist.js](../../frontend/src/features/notes/ui/checklist.js) | [js/features/notes/ui/checklist.js](../../static/js/features/notes/ui/checklist.js) | 190 | ui |
+| [features/notes/ui/checklistReorder.js](../../frontend/src/features/notes/ui/checklistReorder.js) | [js/features/notes/ui/checklistReorder.js](../../static/js/features/notes/ui/checklistReorder.js) | 111 | ui |
+| [features/notes/ui/clipboard.js](../../frontend/src/features/notes/ui/clipboard.js) | [js/features/notes/ui/clipboard.js](../../static/js/features/notes/ui/clipboard.js) | 82 | ui |
+| [features/notes/ui/colors.js](../../frontend/src/features/notes/ui/colors.js) | [js/features/notes/ui/colors.js](../../static/js/features/notes/ui/colors.js) | 111 | ui |
+| [features/notes/ui/draftEditor.js](../../frontend/src/features/notes/ui/draftEditor.js) | [js/features/notes/ui/draftEditor.js](../../static/js/features/notes/ui/draftEditor.js) | 67 | ui |
+| [features/notes/ui/drawing.js](../../frontend/src/features/notes/ui/drawing.js) | [js/features/notes/ui/drawing.js](../../static/js/features/notes/ui/drawing.js) | 442 | ui |
+| [features/notes/ui/editor.js](../../frontend/src/features/notes/ui/editor.js) | [js/features/notes/ui/editor.js](../../static/js/features/notes/ui/editor.js) | 518 | ui |
+| [features/notes/ui/filters.js](../../frontend/src/features/notes/ui/filters.js) | [js/features/notes/ui/filters.js](../../static/js/features/notes/ui/filters.js) | 139 | ui |
+| [features/notes/ui/layout.js](../../frontend/src/features/notes/ui/layout.js) | [js/features/notes/ui/layout.js](../../static/js/features/notes/ui/layout.js) | 120 | ui |
+| [features/notes/ui/lifecycle.js](../../frontend/src/features/notes/ui/lifecycle.js) | [js/features/notes/ui/lifecycle.js](../../static/js/features/notes/ui/lifecycle.js) | 36 | ui |
+| [features/notes/ui/mobileEditor.js](../../frontend/src/features/notes/ui/mobileEditor.js) | [js/features/notes/ui/mobileEditor.js](../../static/js/features/notes/ui/mobileEditor.js) | 257 | ui |
+| [features/notes/ui/mobileReorder.js](../../frontend/src/features/notes/ui/mobileReorder.js) | [js/features/notes/ui/mobileReorder.js](../../static/js/features/notes/ui/mobileReorder.js) | 214 | ui |
+| [features/notes/ui/panel.js](../../frontend/src/features/notes/ui/panel.js) | [js/features/notes/ui/panel.js](../../static/js/features/notes/ui/panel.js) | 506 | ui |
+| [features/notes/ui/quickAdd.js](../../frontend/src/features/notes/ui/quickAdd.js) | [js/features/notes/ui/quickAdd.js](../../static/js/features/notes/ui/quickAdd.js) | 170 | ui |
+| [features/notes/ui/reminderDisplay.js](../../frontend/src/features/notes/ui/reminderDisplay.js) | [js/features/notes/ui/reminderDisplay.js](../../static/js/features/notes/ui/reminderDisplay.js) | 129 | ui |
+| [features/notes/ui/reminderPicker.js](../../frontend/src/features/notes/ui/reminderPicker.js) | [js/features/notes/ui/reminderPicker.js](../../static/js/features/notes/ui/reminderPicker.js) | 334 | ui |
+| [features/notes/ui/selection.js](../../frontend/src/features/notes/ui/selection.js) | [js/features/notes/ui/selection.js](../../static/js/features/notes/ui/selection.js) | 61 | ui |
+| [features/notes/ui/text.js](../../frontend/src/features/notes/ui/text.js) | [js/features/notes/ui/text.js](../../static/js/features/notes/ui/text.js) | 39 | ui |
+| [features/notes/ui/toolbar.js](../../frontend/src/features/notes/ui/toolbar.js) | [js/features/notes/ui/toolbar.js](../../static/js/features/notes/ui/toolbar.js) | 78 | ui |
+| [features/notes/ui/windowLayout.js](../../frontend/src/features/notes/ui/windowLayout.js) | [js/features/notes/ui/windowLayout.js](../../static/js/features/notes/ui/windowLayout.js) | 114 | ui |
+| [shared/ui/confetti.js](../../frontend/src/shared/ui/confetti.js) | [js/shared/ui/confetti.js](../../static/js/shared/ui/confetti.js) | 28 | shared UI |
+
+Maintained Notes feature total: 6440 lines. Original entry: 5,471 lines.
+Legacy facade after decomposition: five lines. Shared confetti: 28 lines.
+
+See [the case study](notes-case-study.md) for responsibilities and public/state/lifecycle
+contracts, and [the validation report](notes-validation.md) for executed evidence.
diff --git a/docs/frontend-architecture/notes-roadmap.md b/docs/frontend-architecture/notes-roadmap.md
new file mode 100644
index 000000000..522923dc2
--- /dev/null
+++ b/docs/frontend-architecture/notes-roadmap.md
@@ -0,0 +1,178 @@
+# Notes reference decomposition roadmap
+
+Status: N0 through N6 implemented as an unpublished Notes review diff after F1
+merged in PR #6701. Actual decisions, interfaces, module ownership, checkpoint
+receipts and execution limits are in the [case study](notes-case-study.md) and
+[validation report](notes-validation.md). The proposal below retains the original
+responsibility map for comparison. Notes integration and the recipient's independent
+H reproduction remain pending.
+F1 remains an entirely separate foundation-only PR. The complete Notes
+decomposition, regression tests, compatibility validation and final reference
+case study belong to one comprehensive draft PR targeting official `dev`.
+
+## Verified current responsibility and compatibility map
+
+Historical assessment baseline: `8feb50e89468235cd3e0986da80edbd3acaf2c40`.
+The implementation starts from merged F1 at
+`1cc56cb9d78f3e2399d1d61155b71d771a17b85b`.
+The module is `static/js/notes.js`, about 5,470 lines, with browser identity
+`/static/js/notes.js?v=20260911notesselectioncancel1`. Preserve that identity across
+the app import, HTML, SW and lazy consumers until a separately reviewed migration
+changes the contract everywhere.
+
+| Responsibility | Current evidence | Intended owner after its reviewed slice |
+| --- | --- | --- |
+| State and CRUD | `_notes`, selection/filter/editing/loading variables, `_undoStack`, `_fetchNotes`, `_saveNote`, `_patchNote`, `_archiveNoteById` | One application state owner and workflow operations; no second reminder/UI copy |
+| Dates and recurrence | `_normalizeRepeat`, `_advanceRecurring`, `_nthWeekdayOfMonth`, `_lastWeekdayOfMonth`, `_toLocalDatetimeStr`, repeat formatting helpers | Pure domain calculations with explicit clock inputs |
+| Network and persistence | Notes CRUD/reorder, upload, reminder firing, draft and reminder localStorage keys | Infrastructure adapters preserving request payloads, credentials and error contracts |
+| Reminders | `_checkReminders`, `_startReminderLoop`, `_initReminders`, notification permission/display and due/fired badge calculations | Application reminder workflow plus injected clock/storage/notification/API ports |
+| Draft autosave | `_draftKey`, `_collectFormDraft`, `_wireDraftAutosave`, `_applyDraftToNote`, `_commitOpenInPlaceEditor` | Draft workflow with editor view/persistence ports and serialized saves |
+| UI | `openPanel`, `closePanel`, `_renderNotes`, forms/cards/checklists, masonry, color/photo/drawing, mobile swipe/reorder | Scoped UI modules with explicit mount/dispose and application operations |
+| Agent context | `#notes-send-agent` handler, selected IDs, `odysseus:notes-context-selected` | Preserve event payload and synchronous acknowledgement; Chat owns attachment/session state |
+| Agent solve action | `_agentSolveNote`: default-chat lookup, session creation and chat stream | Separate existing workflow; do not conflate with selected-note attachment |
+| Compatibility coordinator | Default controller, named aliases, `window.notesModule`, delayed reminder startup | Stable legacy facade/composition bridge until consumers safely migrate |
+
+The default API currently includes `openPanel`, `closePanel`, `togglePanel`,
+`isPanelOpen`, `openNote`, `newNote`, `openNotes`, `closeNotes`, `isNotesOpen` and
+`refreshDueBadge`. Named exports also include `dismissFiredReminderDot` and the
+panel/open aliases. Characterization must pin the complete actual namespace and
+default object separately, including identity of aliases and the window bridge.
+
+Consumers include `static/app.js` sidebar/routes/badge polling,
+`chatStream.js` note tool updates, `chatRenderer.js` note links and
+`document.js` coordination. `static/index.html` and `static/sw.js` are entry/cache
+contracts. The shared UI, confetti, modal, color picker, drag, tiling, docking,
+z-order and Escape helpers are direct dependencies. Those legacy dependencies
+remain in the coordinator until their ownership is reviewed, rather than moving
+all UI coupling into domain modules.
+
+Import-time behavior includes window origin/storage reads and
+`setTimeout(_initReminders, 3000)`. The successful bootstrap loads Notes and starts
+a 30-second reminder interval. App composition separately refreshes the badge
+every five minutes. Panel/editing listeners, draft timers, highlight animations,
+ResizeObserver and drawing/touch handlers have shorter scopes. Record them before
+extraction; do not stop background reminders merely because a panel closes.
+Listener cleanup concerns require characterization, not an unrelated fix hidden
+inside an extraction.
+
+Persistence includes `odysseus-notes-view`, label collapse and hint preferences,
+fired/glowed/pending/active reminder markers, dismissed timestamp, and
+`odysseus-note-draft-` including `__new__`. Current direct APIs include Notes
+CRUD/reorder/fire-reminder and upload, plus default-chat/session/chat-stream for
+the existing solve action. Backend owner isolation and permission handling stay
+authoritative and are outside this frontend decomposition's implementation scope.
+
+## PR #6495 contract that every relevant slice preserves
+
+Notes sends `odysseus:notes-context-selected` with `{ noteIds, accepted: false }`.
+Chat's synchronous listener accepts only a valid active or pending chat, updates
+session/pending selection, sets `accepted`, and updates the context indicator.
+Notes clears select mode only after acceptance. Session lifecycle events
+`odysseus:session-changed` carry session/materialization information. Chat appends
+selected IDs as `selected_note_ids` when sending; server parsing validates IDs,
+filters by owner and treats the resulting prompt context as untrusted.
+
+Keep selection transfer to a materialized chat, reset on a new chat, rejection
+when no chat/model can accept it, aliases and indicator behavior. Do not broaden
+frontend selections into permissions or bypass the backend. See
+`tests/selectedNotesContext.test.mjs`, `tests/test_selected_notes_context.py`,
+`static/js/chat.js` selected-context listeners and send payload, and
+`static/js/sessions.js` lifecycle event producers.
+
+## One Notes branch, worktree and draft PR
+
+After F1 integration and authorization to begin Notes, create one worktree and
+branch, suggested name `refactor/notes-reference-decomposition`, from the latest
+official `upstream/dev`. N0 through N6 are sequential internal engineering
+checkpoints on that same branch. No independent GitHub PR is required for a
+checkpoint or a UI substage. Maintain one draft PR targeting official `dev`, with
+checkpoint evidence linked from its description. Keep it a draft until the
+complete decomposition passes all acceptance gates below.
+
+| Checkpoint | Responsibility | Deliverable and exit evidence |
+| --- | --- | --- |
+| N0 | Characterization | Public API/consumer, responsibility, state, lifecycle and network map; deterministic behavior tests; PR-overlap refresh; no extraction |
+| N1 | Recurrence domain | Only pure date/recurrence rules to `features/notes/domain/recurrence.js`; preserve old wrapper call contracts, time-read position and returned strings; new offline dependency registered |
+| N2 | Infrastructure | HTTP and storage adapters with exact request/error/key contracts; retain state ownership and backend authorization |
+| N3 | Application | Single state owner and CRUD/optimistic/undo workflows; UI/reminders call operations; no competing arrays or stores |
+| N4 | Reminders | Timer/notification/reminder orchestration through explicit ports; characterize startup, catch-up, deduplication, badge and background behavior |
+| N5 | UI substages | Bounded card/panel, editor/draft, checklist, drawing and mobile reviews within the same PR; explicit listener/observer disposal and the same application operations |
+| N6 | Compatibility and reference case study | Reduce coordinator; full API/consumer/lifecycle/offline comparison; retain legacy facade unless removal is proven safe; complete the final reference case study in the same PR |
+
+Do not create the Notes worktree, branch or PR during F1. N5 remains several
+bounded internal reviews rather than a second monolith move. Every checkpoint
+and UI substage must have its own focused tests, review evidence, lessons,
+exceptions and a rollback plan. Record the validated revision or reproducible
+patch/snapshot, prior known-good checkpoint, exact test commands/results and
+how to restore its matching source/output/facade/precache set while preserving
+unrelated work. Checkpoint commits require the applicable maintainer authority;
+no checkpoint or commit is created by this planning document.
+
+Advance only after the current checkpoint's required checks and review findings
+are resolved. A failed checkpoint returns to its prior validated state or receives
+a bounded correction on the same branch; it does not require a separate PR.
+If upstream changes require updating the baseline, update the same Notes branch,
+record that revision and rerun affected checkpoint and compatibility gates.
+
+## Complete Notes PR acceptance gates
+
+Before marking the single draft PR ready for review:
+
+- Complete N0 through N6, including all N5 substages, with their tests, review
+ receipts and reproducible checkpoint/rollback evidence.
+- Pass the required full Notes regression and compatibility checks on the final
+ combined revision, including PR #6495 selection/context behavior, public APIs,
+ module identities, single state ownership, storage formats, timers and teardown.
+- Pass source/output parity, LF attribute, architecture, import graph and exact
+ offline manifest gates; verify current bootstrap/lazy behavior and relevant
+ native/packaging contracts. Record platform limits and distinguish preserved
+ offline module behavior from separately certified root offline reload.
+- Resolve required gate failures and review findings; document unrelated existing
+ failures or coverage gaps explicitly rather than bypassing required checks.
+- Include the final reference case study in this PR: actual before/after APIs,
+ dependency/state/lifecycle maps, stage decisions and lessons, validation recipes,
+ temporary exceptions, known debt and tested rollback/compatibility procedures.
+
+These are readiness gates for the complete PR, not separate stage merges.
+The receiving maintainer may choose smaller independent PRs for future frontend
+features; this one-PR delivery decision applies to the Notes reference program.
+
+## N0 and N1 characterization requirements
+
+Pin recurrence normalization for legacy bare repeat values and explicit values;
+none/unknown/malformed input; daily/weekly/monthly/yearly advancement; month ends,
+leap years, nth/last weekdays including absent fifth occurrences; overdue catch-up
+and the 5,000-step guard; future anchors; local serialization and preserved hours;
+DST gaps/overlaps under explicit time zones. `_advanceRecurring` currently reads
+`Date.now()` after its first step. Inject a clock without changing that ordering.
+Record the existing behavior of invalid dates rather than inventing improvements.
+
+Characterize request error handling, optimistic rollback/undo, archive/delete,
+selection/filter/reset, ordering, uploads and notification permission errors.
+For drafts, preserve synchronous local backup before the 500 ms persistence
+timer, intentional empty text, checklist type fallback, serialized writes,
+failure recovery and refusal to clear a newer draft when an older save finishes.
+
+Use stub clocks/ports and temporary storage for unit behavior; browser tests for
+public namespace evaluation, DOM lifecycle, selected context and actual offline
+loading. Run real modules through their output paths. Do not rewrite source-range
+tests wholesale; migrate each only with its responsible slice and equivalent
+behavioral assertions. Existing source-sensitive Notes autosave tests currently
+read `notes.js`, so extraction has an explicit test-maintenance dependency.
+
+Before a slice, refresh #6585/#6647/#6652 backend behavior and #6470/#6695 shared
+UI/platform overlaps from the [assessment](assessment.md). Existing fixes may
+change characterization inputs, but this program does not merge or silently
+reimplement those PRs. The independent root-SW fix #6227 is required before a
+claim of full SPA offline reload readiness.
+
+## H completion and stopping rule
+
+The final reference case study is completed inside the Notes PR before it becomes
+ready for review. After that PR is integrated, finalize H with the integrated
+revision and checkpoint-to-integration receipts, outstanding dependencies and
+the recipient's independent reproduction. Have the receiving maintainer
+reproduce setup and validation independently and record that receipt. Transfer
+future feature ownership explicitly. Do not automatically begin Calendar,
+Documents, Email, Chat, Skills or Settings; the initiating architect continues
+with separately approved non-frontend monolith work.
diff --git a/docs/frontend-architecture/notes-validation.md b/docs/frontend-architecture/notes-validation.md
new file mode 100644
index 000000000..e4e701c6c
--- /dev/null
+++ b/docs/frontend-architecture/notes-validation.md
@@ -0,0 +1,261 @@
+# Notes implementation validation and checkpoint receipts
+
+Implementation baseline: `1cc56cb9d78f3e2399d1d61155b71d771a17b85b`, updated via
+non-destructive fast-forward to latest official `upstream/dev` at
+`86b886c611338282af6d4a717246ea4e256f58df` (incorporating PRs #6704 and #6693).
+Independent AGY audit returned CONDITIONAL PASS. Pre-publication corrective
+pass verified issue template, PR template, visual evidence paths, and em-dash removal.
+The official integration branch is `dev`. Tracking issue #6712; PR #6713.
+
+## Final executed evidence
+
+| Check | Result |
+| --- | --- |
+| Notes Python tests, discovered by filename, plus F1 publication/graph/offline/loader tests | 172 passed, one release-smoke skip without `APP_PORT` |
+| Node architecture, Notes oracle, domain, infrastructure, application, reminders, drafts, selection and workflow tests | 46 passed |
+| Native Python lifespan/static distribution probe | Passed for every mapped output, with source/Node absent |
+| Existing Docker image distribution probe | Passed with networking disabled and candidate files mounted read-only |
+| Real authenticated native app, desktop and touch-mobile | Passed CRUD persistence, owner identity, actual Chat selected-context indicator/reset and the original release smoke scenario |
+| Real Chromium first evaluation of Notes offline | Passed; every maintained output cached, facade/canonical API identity shared |
+| Source/output parity and F1 boundaries | Passed, 43 maintained modules and nine composition-only legacy exceptions |
+| Foundation-based full pytest execution | 13 failed, 13,909 passed, 60 skipped, six subtests passed, 192 warnings, 517.04 seconds |
+| Targeted unchanged F1 baseline reproduction | Same 13 failures, 77 passed, six warnings |
+| Targeted untouched latest `dev` reproduction | Three inherited failures, 87 passed, six warnings |
+| Final indexed latest `dev` plus Notes overlay, full pytest | Three same-environment baseline failures, 13,923 passed, 60 skipped, six subtests passed, 192 warnings, 512.09 seconds |
+| Untouched latest `dev` readiness checks, without the prewarm override | Five passed |
+
+The foundation-based full repository result is not green. Its failures reproduce against
+the unchanged foundation in a disposable archive, with the same interpreter and
+closed Chroma port. None was disabled, relabeled or fixed in this Notes change.
+The focused Notes suite and required source/deployment gates are green. The final
+code/test overlay is fingerprinted in [implementation.sha256](evidence/notes/implementation.sha256).
+The only post-full-suite test-source edit removes a terminal
+blank line from the browser wrapper; its content was compared ignoring terminal
+whitespace and all three focused contract/browser checks passed again. Raw command
+outputs are kept out of the repository; the counts above are the record.
+
+The first full run reported 19 failures. Six were introduced validation issues:
+the SW cache name did not follow the existing numeric convention; a temporary
+probe environment input was not registered by the configuration-reference checker;
+and a Notes source assertion still expected the original default object spelling.
+The cache name now follows the convention, the probe passes its output list as a
+command argument, and the assertion verifies the new public binding. All 58 tests
+in those affected files passed after correction. The foundation-based full run has only the
+13 reproduced baseline failures below.
+
+### Reproduced baseline failures
+
+- `tests/test_aux_llm_owner_scope.py::test_auto_compaction_utility_endpoint_keeps_chat_owner`
+- `tests/test_chatgpt_reasoning_and_grouping.py::test_history_and_chat_routes_support_reasoning_effort`
+- `tests/test_containment_enforcement.py::test_namespace_handshake_closes_model_stdin`
+- `tests/test_containment_enforcement.py::test_execution_environment_cannot_replace_probed_bwrap[False]`
+- `tests/test_context_compactor.py::TestMaybeCompactFourthMessage::test_does_not_crash_on_none_content_turn`
+- `tests/test_context_compactor.py::TestMaybeCompactFourthMessage::test_handles_multimodal_list_content`
+- `tests/test_css_computed_style_snapshot.py::test_computed_styles_match_the_committed_baseline`
+- `tests/test_history_compact_tool_calls.py::test_manual_compact_tolerates_chatmessage_with_none_content`
+- `tests/test_history_compact_tool_calls.py::test_manual_compact_tolerates_dict_message_with_none_content`
+- `tests/test_history_compact_tool_calls.py::test_registered_manual_compact_route_tolerates_none_content`
+- `tests/test_history_compact_tool_calls.py::test_registered_manual_compact_route_uses_session_owner`
+- `tests/test_model_helper_owner_scope.py::test_history_compact_resolves_with_owner_scope`
+- `tests/test_readiness.py::test_tool_index_is_reported_but_not_critical_by_default`
+
+These cover existing compaction fixtures/source assertions, namespace containment,
+settings-row CSS baseline drift and readiness expectations. The baseline reproduction used
+`git archive` into `/tmp/odysseus-notes-baseline-OitxsU`, not another branch/worktree.
+
+## Reproducible commands
+
+### Latest integration target
+
+Final upstream inspection found `86b886c611338282af6d4a717246ea4e256f58df`.
+PR #6704 repairs ten of the foundation's reproduced failures; PR #6693 adds
+remote-only skill gating. Neither changes a file owned by the Notes diff.
+The branch remains on the requested foundation, with no merge or rebase.
+An archive of that latest target plus the exact final Notes code/test overlay is
+validated in `/tmp/odysseus-notes-latest-VmZrgC` using the same full-suite command.
+The fixture has a local Git index, initialized from the latest target and updated
+with the review files, but no commit. This enables the tracked-publication checks.
+The first archive-only attempt had one Git-metadata failure and seven checkout-only
+skips. Both affected files subsequently passed all 19 tests with metadata present;
+the complete suite was then rerun in that indexed fixture.
+An untouched archive at `/tmp/odysseus-notes-latest-baseline-mfE4ss` reproduced
+the remaining two containment failures and the readiness failure: three failed,
+87 passed.
+
+These are reproduced local-environment failures, not a claim that official CI is
+currently failing. The readiness assertion expects prewarming enabled, whereas
+the full-run safety command explicitly sets `ODYSSEUS_TOOL_INDEX_PREWARM=0`.
+With that override absent, all five readiness tests pass on untouched latest `dev`.
+The two namespace tests receive extra `Failed to create stream fd` stderr in this
+host's contained process output. That same output occurs without the Notes overlay;
+no backend containment code was changed or a failing assertion weakened.
+Reproduce those two checks on the supported CI runner before claiming a green
+full-suite certification.
+
+In the final indexed full-suite run the only failures are `test_namespace_handshake_closes_model_stdin`,
+`test_execution_environment_cannot_replace_probed_bwrap[False]`, and
+`test_tool_index_is_reported_but_not_critical_by_default`. The missing-Git-metadata
+publication failure and the seven checkout-only skips are absent from this run.
+No Notes regression was reported. Feature code matched N6 at publication. Later
+commits on the PR changed `ui/reminderPicker.js` (date input value assigned through
+the DOM property) and, after review, `index.js`, `ui/layout.js` and
+`application/state.js`; `implementation.sha256` covers the current files.
+
+To reproduce the integration rehearsal, extract the latest target with `git archive`
+into a fresh fixture and copy only files in the changed-file inventory on top.
+Do not overlay foundation files that are unchanged in this PR. Install the locked
+development dependencies in the fixture, then run the commands below there.
+
+While this review diff is uncommitted, this prepares an equivalent Linux fixture
+without changing either task worktree:
+
+```sh
+notes_fixture=$(mktemp -d /tmp/ody-notes-integration-XXXXXX)
+git archive 86b886c611338282af6d4a717246ea4e256f58df | tar -x -C "$notes_fixture"
+{ git diff --name-only -z; git ls-files --others --exclude-standard -z; } |
+ tar --null -T - -cf - | tar -xf - -C "$notes_fixture"
+git -C "$notes_fixture" init -q
+git -C "$notes_fixture" fetch --no-write-fetch-head "$PWD" 86b886c611338282af6d4a717246ea4e256f58df
+git -C "$notes_fixture" read-tree 86b886c611338282af6d4a717246ea4e256f58df
+(cd "$notes_fixture" && npm ci --ignore-scripts --no-audit --no-fund && git add --all)
+# Run the validation commands below from notes_fixture, using an isolated Python environment.
+```
+
+Use a real dependency directory for this recipe; a symlink named `node_modules`
+can bypass the repository's directory-only ignore pattern. No checkpoint or
+fixture commit is needed. After integration, validate the actual integrated checkout
+directly, rather than relying on the uncommitted-diff recipe.
+
+### Commands
+
+Use the actual tested interpreter, or install the repository requirements in your
+own isolated virtualenv. Node development dependencies were installed with the
+existing lockfile and `npm ci --ignore-scripts --no-audit --no-fund`.
+
+```sh
+python3 scripts/build_frontend.py
+python3 scripts/build_frontend.py --check
+node scripts/check_frontend.mjs
+node scripts/check_frontend.mjs --inventory
+
+ENDPOINT_URL=http://127.0.0.1:1 node --test \
+ tests/frontendArchitecture.test.mjs tests/noteTestOracle.test.mjs \
+ tests/notesDraftAutosave.test.mjs tests/selectedNotesContext.test.mjs \
+ tests/notesCharacterization.test.mjs tests/notesRecurrence.test.mjs \
+ tests/notesInfrastructure.test.mjs tests/notesApplication.test.mjs \
+ tests/notesReminders.test.mjs tests/notesWorkflows.test.mjs
+
+CHROMADB_HOST=127.0.0.1 CHROMADB_PORT=1 \
+ python -m pytest -q -rs \
+ $(rg --files tests -g 'test_*note*.py') \
+ tests/test_frontend_build.py tests/test_frontend_foundation_offline_js.py \
+ tests/test_frontend_module_graph.py tests/test_frontend_module_version_parity.py \
+ tests/test_panel_loader_js.py
+
+python scripts/verify_frontend_runtime.py
+python scripts/verify_notes_browser_runtime.py
+
+docker run --rm --network none \
+ --mount type=bind,src="$PWD",dst=/candidate,readonly \
+ --workdir /candidate --entrypoint python \
+ scripts/verify_frontend_runtime.py
+
+CHROMADB_HOST=127.0.0.1 CHROMADB_PORT=1 \
+ ODYSSEUS_STARTUP_WARMUPS=0 ODYSSEUS_TOOL_INDEX_PREWARM=0 \
+ python -m pytest -q -rfs
+
+git diff --check
+```
+
+`ENDPOINT_URL` satisfies the existing oracle's import configuration; its endpoint-
+driving main does not run in these unit tests. Port 1 is the closed loopback target
+used for pytest; the two runtime scripts reserve their own non-listening Chroma port.
+The native browser script creates a private distribution/database and a temporary
+authenticated user, then terminates the server and removes that fixture. It uses
+the real application and Notes API rather than mocked browser routes.
+
+The deterministic browser harness uses stub API responses and the real Notes ESM,
+DOM and stylesheet graph. It verifies namespace/default methods and arities,
+aliases, remount/search reset, rejected/accepted attachments, draft persistence,
+drawing/undo and listener/portal cleanup. It also checks larger-touch reorder after
+re-render, active-drag close cleanup and cancellation of a mobile selection hold.
+It includes the mobile viewport meta tag,
+tap-to-read/edit behavior and the existing selection jiggle. The original monolith
+can be replayed with `NOTES_BASELINE=1`; it is read from the frozen F1 revision.
+
+## Browser and packaging evidence
+
+Actual app screenshots: [desktop](evidence/notes/native-desktop.png) and
+[mobile](evidence/notes/native-mobile.png). These are Chromium screenshots of the
+disposable authenticated app at 1440 x 1000 and 390 x 844, not rendered mockups.
+The deterministic before/after fixture had an identical mobile PNG and only 14
+changed desktop pixels in the header region; no layout/style change was observed.
+CSS, app bootstrap and HTML have no implementation diff.
+
+The native and Docker distribution probe serves all manifest outputs without
+`frontend/`, `node_modules/` or Node on the server path. It checks response bytes,
+JS MIME, revalidation, CSP, shell startup, static confinement and source-tree 404.
+Docker used existing image
+`sha256:cc2d47e2327d573af01c6b027f23d2ab0f2ee9b85d658e9eb8065bd02b9c3515`.
+This is not a fresh Dockerfile build or deployment.
+
+Tested locally: Linux, Python 3.14.4, Node 22.23.1 and Playwright/Chromium 1.62.1.
+CI's exact Python 3.11/Node 20 pair, Firefox/WebKit, macOS/Windows executable builds,
+live model/email notification delivery and full root offline reload were not run.
+The Docker runtime uses its own existing dependency versions. Shared active-window
+gesture interleavings are not exhaustively covered. No broader platform certification
+is claimed.
+
+The full-run safety overrides differ from official CI's plain pytest command.
+For the readiness default-contract check, use
+`env -u ODYSSEUS_TOOL_INDEX_PREWARM python -m pytest -q tests/test_readiness.py`.
+Keep explicit warmup/storage isolation on the disposable live-app probes.
+
+## Internal checkpoints
+
+Checkpoint snapshots are kept with the maintainer handoff, not in the repository.
+The hashes below identify them. They contain scoped source/output/facade/manifest/test
+overlays, not secrets or user data. Each starts from the same frozen baseline; they
+are not separate PRs or release candidates.
+
+| Stage | Boundary and executed exit evidence | Snapshot SHA-256 |
+| --- | --- | --- |
+| N0 | Public/consumer/state/lifecycle map; 95 baseline Python and 11 Node passes; four new characterization tests; desktop/touch harness; 33 F1 publication/graph checks | `db0a2e6e68fec3442ce350ffb0acf47bcdf2a5266f7c64c2bf910a1c41c4fb62` |
+| N1 | Pure recurrence/date rules; eight Node and nine focused Python passes; differential oracle in four time zones; parity/boundaries | `fd0638470744706fbbd5787cb47bd2078a93c9b854139f89f8fdc169c1f353c6` |
+| N2 | HTTP/storage adapters; fourteen Node and seven focused Python passes; exact requests, keys and fallback contracts | `30826fb7972d1b9e3a790f97ee81f66dcb3dc58eb7d23e24d4f46e6d841b7c73` |
+| N3 | Single state owner and CRUD/undo boundary; ten Node and seven focused Python passes; read-only state and archive rollback | `4bc5293519b8438d0126a61887bea64195dcdb7d59bcfaaba8ed4ae8c38be439` |
+| N4 | Page-owned reminder workflow; four reminder contract tests and seven focused Python passes; singleton interval, catch-up, markers and fallback | `febb835c4958c8758e4b7c23ce89f3ec8d103c2cc28f89817d258b3791a9fcdf` |
+| N5 | Complete UI/application integration; 44 Node passes, targeted source guards and actual browser checks; drawing binding correction, read-only state and disposal | `e147f645bdb2161a4b1dc6cf10c36ba6d0c214d8e12fccb478835043eaaf3e94` |
+| N6 | Final facade, identity, exact offline graph, native/Docker checks, final editor-deletion/reorder ownership review, touch cleanup regression checks and maintainer review package | `c450e91f9fbfe5f0cd805e596b92a76383f22a74e9515ca3e3f6154aebf5f61f` |
+
+The N6 overlay contained the final code, tests, manifest and attributes at
+publication, not the evidence directory itself. From the repository root, run
+`sha256sum -c docs/frontend-architecture/evidence/notes/implementation.sha256`
+to verify the current implementation files.
+
+No checkpoint commits were made. To reproduce an overlay, create a fresh temporary
+directory, extract `git archive 1cc56cb9...` there, then extract the desired
+snapshot from the handoff on top. Install the locked test dependencies
+in that fixture and run its relevant commands. Begin from the baseline rather than
+overlaying snapshots onto a later dirty tree. For live rollback, release a complete
+matching artifact through the authorized release workflow.
+
+Temporary mechanical extraction scripts are not part of the supported deliverable.
+They were archived locally, then removed. The first generated patch accidentally targeted
+the separate foundation worktree; only those edits were reversed, absolute paths
+were adopted, and that worktree's clean state was verified afterward.
+
+## Open PR overlaps and handoff limits
+
+The following remained open at the read-only GitHub refresh:
+
+- [#6585](https://github.com/odysseus-dev/odysseus/pull/6585): optional Notes field removal in the backend. Existing null-field behavior is retained here.
+- [#6647](https://github.com/odysseus-dev/odysseus/pull/6647): read-only Notes intent routing.
+- [#6652](https://github.com/odysseus-dev/odysseus/pull/6652): `manage_notes` registry dispatch.
+- [#6470](https://github.com/odysseus-dev/odysseus/pull/6470): shared theme, typography, sidebar and modal changes.
+- [#6695](https://github.com/odysseus-dev/odysseus/pull/6695): extension system/platform integration.
+
+Their changes were not merged or reimplemented. Shared UI exceptions, root-SW scope,
+the original last-completion fetch race, temporary-note correlation and canvas-draft
+limits are documented in the case study. Backend owner checks and PR #6495 contracts
+remain authoritative.
diff --git a/docs/frontend-architecture/validation.md b/docs/frontend-architecture/validation.md
new file mode 100644
index 000000000..1e85db081
--- /dev/null
+++ b/docs/frontend-architecture/validation.md
@@ -0,0 +1,453 @@
+# F1 implementation and review report
+
+Date: 2026-10-13. Recommendation: ready for controlled incremental adoption after
+maintainer review, with the platform/offline limits below. The foundation proof
+is implemented and tested; Notes decomposition and the completed H handoff are
+planned only. No commit, push, merge, PR or issue operation was performed.
+
+## Notes delivery documentation correction
+
+The maintainer's final delivery decision is one comprehensive Notes draft PR
+targeting official `dev`, after the separate foundation-only F1 PR is integrated.
+N0 through N6 are internal engineering checkpoints in one Notes worktree and
+branch. The complete decomposition, regression tests, compatibility validation
+and final reference case study belong to that single PR; it stays a draft until
+the complete acceptance gates pass. Each stage retains its own test results,
+review receipts and reproducible rollback/checkpoint strategy, without requiring
+an independent GitHub PR. The receiving maintainer may choose smaller independent
+PRs for future frontend features.
+
+This correction updates only `notes-roadmap.md`, `handbook.md` and this report.
+Implementation and test files retain their pre-correction bytes. All five
+foundation documents passed link, fence, whitespace, no-em-dash and delivery
+wording checks. `git diff --check` and the preserved-runtime diff check passed.
+A before/after snapshot confirmed exactly these three changed documents and
+15 unchanged existing F1 files. The implementation test results below remain
+the previous executed evidence; implementation tests were not rerun in this
+documentation-only pass.
+
+## Independent review correction
+
+The maintainer reports that the independent F1 review found no critical
+architectural defects. This pass preserves the reviewed native ESM architecture
+and scope. Its correction is to turn the documented LF checkout convention into
+a manifest-driven publisher/CI requirement. The full independent review text
+was not supplied; this report records the supplied finding and executed evidence.
+
+The correction changes only `scripts/build_frontend.py`,
+`tests/test_frontend_build.py`, the ADR, the handbook and this report. The
+`.gitattributes` rules, architecture checker, CI workflow, manifest, dependencies
+and stateless source remain as reviewed. The full F1 inventory below still has
+18 files, including `.gitattributes`.
+
+The publisher now evaluates both paths of every manifest entry through Git's
+actual attribute engine before parity evaluation or any deployment write. It
+requires `text: set` and `eol: lf` from applicable repository-owned attribute files,
+including nested overrides. A private temporary repository and isolated Git
+configuration prevent global attributes, local `.git/info/attributes`, templates
+or alternate Git directory settings from masking an omitted declaration. Paths
+are sent through NUL-delimited stdin, preserving spaces and using no shell/path
+quoting assumptions. The working repository's attributes, index and output are
+not changed by this check. Git is a publication/development prerequisite; the
+application does not invoke it to build or check frontend assets at startup.
+
+The production integration diff is the new `check_lf_attributes(root, paths)`
+helper, four standard-library imports, this call, and updated CLI help:
+
+```diff
+@@ synchronize
+ if unlisted:
+ raise ValueError(f"source modules missing from manifest: {sorted(map(str, unlisted))}")
++ check_lf_attributes(root, sources | outputs)
+ stale = []
+```
+
+The tests add fixture LF declarations and 14 cases. Ten parameterized cases
+reject missing LF, CRLF, auto-text and binary-text rules for source/output paths
+in both publish and check modes, even when bytes already match. The other four
+cover a future manifest pair failing before any output is published and passing
+after its LF declaration; nested rules and a spaced path; global/local settings
+failing to mask an omitted repository rule; and clear failure without development
+Git. Existing publication, ownership, confinement, parity and runtime tests remain.
+
+## Exact attributes diff and checkout evidence
+
+`git diff -- .gitattributes` is unchanged from the reviewed F1 diff:
+
+```diff
+diff --git a/.gitattributes b/.gitattributes
+index 8681aee1..dd49c4a0 100644
+--- a/.gitattributes
++++ b/.gitattributes
+@@ -10,6 +10,10 @@
+ entrypoint.sh text eol=lf
+ docker/entrypoint.sh text eol=lf
+
++# Maintained frontend modules and this lane's byte-identical deployment output.
++frontend/src/** text eol=lf
++static/js/actionMenuOrder.js text eol=lf
++
+ # Windows-native scripts stay CRLF.
+ *.ps1 text eol=crlf
+ *.cmd text eol=crlf
+```
+
+Exact command and results:
+
+```text
+$ git check-attr text eol -- frontend/src/shared/actionMenuOrder.js static/js/actionMenuOrder.js
+frontend/src/shared/actionMenuOrder.js: text: set
+frontend/src/shared/actionMenuOrder.js: eol: lf
+static/js/actionMenuOrder.js: text: set
+static/js/actionMenuOrder.js: eol: lf
+```
+
+The sampled legacy contracts were also inspected:
+
+| Path | text | eol |
+| --- | --- | --- |
+| `static/js/notes.js` | auto | unspecified |
+| `static/index.html` | auto | unspecified |
+| `launch-windows.ps1` | set | crlf |
+| `start-macos.sh` | set | lf |
+
+Beyond samples, all 2,479 unrelated tracked paths were compared against HEAD for
+both attributes and matched. The current Git 2.53.0 supports the diagnostic
+`--source=HEAD` option; the publisher uses only the longstanding plain
+`check-attr --stdin` interface, so it does not depend on that newer option.
+The read-only whole-tree comparison command was:
+
+```sh
+python3 - <<'PY'
+import subprocess
+paths = subprocess.check_output(['git', 'ls-files', '-z'])
+def attributes(source):
+ result = subprocess.run(
+ ['git', 'check-attr', *source, '-z', '--stdin', 'text', 'eol'],
+ input=paths, capture_output=True, check=True,
+ )
+ fields = result.stdout.decode().split('\0')[:-1]
+ return {(fields[i], fields[i + 1]): fields[i + 2]
+ for i in range(0, len(fields), 3)}
+before, after = attributes(['--source=HEAD']), attributes([])
+owned = lambda p: p.startswith('frontend/src/') or p == 'static/js/actionMenuOrder.js'
+changes = [(p, a, before[(p, a)], value) for (p, a), value in after.items()
+ if not owned(p) and before[(p, a)] != value]
+assert not changes, changes
+print(len({p for p, a in after if not owned(p)}), 'unrelated tracked paths unchanged')
+PY
+```
+
+## Ownership enforcement after correction
+
+| Contract | Enforcement and CI receipt |
+| --- | --- |
+| Canonical, contained source/output paths and unique ownership | Publisher validates the whole manifest before writing; `python-syntax` runs its `--check` |
+| Every maintained JS source is registered | Publisher rejects unlisted source; duplicate sources/outputs also fail |
+| Reproducible LF checkout of both mapped paths | Publisher queries isolated repository-owned attributes, even for already matching bytes; the same CI `--check` now enforces it |
+| Committed output equals maintained source | Publisher checks byte parity without rebuilding in CI; normal publication writes only stale owned outputs |
+| Feature API/layer direction, no new cycles, stable relative resolution and maintained identities | Existing architecture checker and Node self-tests in `node-syntax`; no checker changes needed |
+| Explicit exact-URL offline coverage | Architecture checker parses the existing SW arrays; real offline browser proof remains green |
+| Legacy runtime graph/URL identity and behavior | Existing focused pytest guards and the full CI pytest jobs remain in place |
+
+These gates enforce the documented maintained-JS contract together. They do not
+retroactively impose source ownership on all legacy static files, clean retired
+outputs or prove semantic state/lifecycle correctness. Those existing limits and
+the independent packaging/offline limitations below remain unchanged.
+
+## Final correction validation
+
+The full focused pytest command printed below was rerun with the same interpreter
+and all listed files: **193 passed, 1 skipped, 1 existing SQLAlchemy warning in
+12.33 s**. It includes all 27 publisher tests and the isolated native startup,
+static traversal and no-Node distribution probe. The new 14 tests account for
+the increase from the initial F1 run's 179 passes. No test failed in this pass.
+
+| Correction check | Actual result |
+| --- | --- |
+| Combined focused pytest command below | 193 passed, 1 unavailable-image skip |
+| `node --test tests/frontendArchitecture.test.mjs` | 10 passed |
+| Notes oracle/autosave/selected-context command below | 11 passed |
+| `python3 scripts/build_frontend.py` | Passed, zero output changes, attributes enforced |
+| `python3 scripts/build_frontend.py --check` | Passed, attributes and byte parity enforced |
+| `node scripts/check_frontend.mjs` | Passed, one maintained module |
+| Helper SHA-256 and `git check-attr` | Identical source/output hash; both text=set, eol=lf |
+| All unrelated tracked attributes versus HEAD | 2,479 paths unchanged |
+| `git diff --check` and preserved-runtime command below | Passed, no runtime/backend/packaging diff |
+| `python -m compileall -q scripts/build_frontend.py tests/test_frontend_build.py` | Passed using the recorded virtualenv interpreter |
+| Isolated Docker runtime command below | Passed, networking disabled; no source tree, node_modules or Node on PATH |
+| Complete inventory, whitespace and documentation links | All 18 changed files matched the inventory; checks passed |
+
+The one skip remains the existing test requiring `odysseus-odysseus:latest`.
+No new skip or waiver was introduced. Windows/macOS executable builds, a fresh
+full Dockerfile build, the full pytest suite, Firefox/WebKit and CI's exact
+Python 3.11/Node 20 versions remain unexecuted locally. Native Git semantics,
+nested overrides, paths with spaces and ignored `core.autocrlf`/global attribute
+settings are covered by executed Linux tests; actual Windows execution remains a
+platform-owner check. The existing `/static/` worker scope still prevents a claim
+of full root offline reload readiness. No service-worker scope change is included.
+
+The earlier local ChromaDB probe incident remains recorded under failures below.
+All runtime checks in this correction pass used the isolated distribution probe
+with reserved non-listening Chroma port and disabled warmups; Docker additionally
+had networking disabled. This pass performed no new unisolated ChromaDB probe and
+no attempt to restore or alter the existing local service's tool index.
+
+## Reviewer-ready PR summary
+
+Suggested title: `Establish frontend source ownership and native ESM deployment contracts`.
+
+Maintain a stateless helper under `frontend/src/` while publishing identical bytes
+at its existing static URL. Add manifest-owned publication, repository-owned LF
+attribute and byte-parity checks, parsed dependency/API/identity/offline gates,
+and a self-contained architecture handbook with the Notes decomposition roadmap.
+Startup and existing feature behavior retain their current runtime contracts.
+
+Validation: 193 focused Python tests passed with one existing Docker-image skip;
+10 architecture and 11 Notes compatibility tests passed; source/output parity,
+LF gates, preserved-runtime diff and isolated native/Docker runtime proofs passed.
+Desktop executable builds and full root offline reload remain explicit limits.
+All 18 files are inventoried below. The working diff is ready for review and is
+uncommitted; commit, push and PR creation require separate authorization.
+
+## Verified repository state
+
+Repository: `odysseus-dev/odysseus`. Branch:
+`refactor/frontend-architecture-foundation`. Worktree:
+`/home/alteixeira20/Projects/Odysseus/worktrees/architecture/frontend-foundation`.
+Initial worktree was clean. HEAD and local official `upstream/dev` are
+`8feb50e89468235cd3e0986da80edbd3acaf2c40`. The live official GitHub `dev` SHA
+matched at both initial and final verification. This is PR #6495's merge commit.
+The `origin` remote is the maintainer fork, not the integration target.
+
+Final changes are uncommitted F1 files only. Runtime JavaScript, Notes, HTML,
+SW, backend, Dockerfile and desktop startup/packaging implementations have no
+diff. The stateless source and existing deployed helper are both 1,688 bytes,
+SHA-256 `e17baec5d6ac381ce6234ab6f028a8208487280dd07d6950a3469f8488809684`.
+The final publisher run reported zero changed output modules.
+
+## Decisions and scope
+
+The [ADR](ADR-001-source-and-deployment.md) compares two executed approaches:
+controlled native ESM copying and esbuild 0.25.12 ESM compilation/bundling.
+Native byte copying wins on existing URL/module/cache compatibility and absence
+of runtime tooling. Commit explicit output beside maintained source, publish
+only manifest-owned modules and enforce parity in CI. Python startup never builds.
+
+The [handbook](handbook.md) defines feature public indexes, responsibility layers,
+state/lifecycle ownership, cross-feature ports/events, shared-code limits, legacy
+coexistence, module creation, validation, rollback and handoff contracts.
+The [assessment](assessment.md) records graph/bootstrap/state/storage/security,
+packaging assumptions and current open-PR overlaps. The
+[Notes roadmap](notes-roadmap.md) defines N0 through N6 as internal checkpoints
+for one comprehensive Notes draft PR, with the final reference case study in
+that PR and H recipient handoff after integration. None is implemented in F1.
+There is one maintained stateless leaf and zero legacy-import
+exceptions, with no empty feature scaffolding.
+
+Acorn 8.19.0 is the sole new, exact-pinned development dependency, used to parse
+architecture edges accurately. It is not loaded or distributed as runtime JS.
+esbuild was a pinned one-off spike and is not a project dependency. Existing
+frameworks, application entry points and backend contracts are unchanged.
+
+## Exact changed files
+
+| File | Change |
+| --- | --- |
+| `.gitattributes` | LF checkout for maintained source and the registered deployed proof |
+| `.github/workflows/ci.yml` | Parity check; locked parser install; source syntax and architecture self-tests |
+| `package.json` | Exact Acorn development dependency |
+| `package-lock.json` | Acorn lock/integrity entry |
+| `frontend/modules.json` | Explicit source/deployment ownership mapping |
+| `frontend/src/package.json` | Native ESM interpretation for source tests, no dependencies |
+| `frontend/src/shared/actionMenuOrder.js` | Authoritative stateless source, copied verbatim from the existing helper |
+| `scripts/build_frontend.py` | Validated source publisher with manifest-driven, repository-owned LF enforcement and non-mutating parity check |
+| `scripts/check_frontend.mjs` | Parsed import/layer/API/cycle/identity/precache guards and graph inventory |
+| `scripts/verify_frontend_runtime.py` | Isolated current-code distribution/runtime compatibility probe |
+| `tests/frontendArchitecture.test.mjs` | Behavioral API equivalence and positive/negative architecture gates |
+| `tests/test_frontend_build.py` | Publication/ownership/drift/runtime coverage plus positive and negative Git attribute enforcement tests |
+| `tests/test_frontend_foundation_offline_js.py` | Real SW precache, offline first evaluation, canonical namespace identity and lazy registry proof |
+| `docs/frontend-architecture/ADR-001-source-and-deployment.md` | Decision, alternatives and distribution/rollback contracts |
+| `docs/frontend-architecture/assessment.md` | Evidence-backed architecture and PR-overlap inventory |
+| `docs/frontend-architecture/handbook.md` | Permanent foundation and maintainer continuation methodology |
+| `docs/frontend-architecture/notes-roadmap.md` | Reference decomposition and final handoff plan |
+| `docs/frontend-architecture/validation.md` | This implementation/review/validation report |
+
+## Initial F1 validation before the review correction
+
+Environment: Linux; native Python 3.14.4; pytest 9.1.1; FastAPI 0.143.0;
+Starlette 1.8.0; Node 22.23.1; Playwright 1.62.1 with installed Chromium.
+CI remains Python 3.11 and Node 20; that exact interpreter pair was not executed
+locally. Use the repository virtualenv, not the system Python missing dependencies.
+The interpreter used here was
+`/home/alteixeira20/.venvs/odysseus-pr-6495/bin/python`.
+
+The historical counts below are coordinator-executed checks in this worktree, excluding
+delegated claims and earlier repeated subsets. Delegation was discontinued on
+user instruction; no delegated implementation was integrated.
+
+| Check | Actual result |
+| --- | --- |
+| Read-only baseline: graph, identity, helper, loader, MIME, nonce, runtime paths | 54 passed, one existing SQLAlchemy deprecation warning |
+| Final combined focused pytest command below | 179 passed, 1 skipped, one existing SQLAlchemy warning, 12.62 s |
+| Final `pytest -q -rs tests/test_frontend_build.py` review rerun | 13 passed, including native startup and encoded static traversal rejection |
+| `node --test tests/frontendArchitecture.test.mjs` | 10 passed, no skips or failures; rerun after final gate review |
+| Notes oracle/autosave/selected-context Node command below | 11 passed, no skips or failures |
+| `python3 scripts/build_frontend.py` and `--check` | Zero output changes; byte parity passed |
+| `node scripts/check_frontend.mjs` | Passed, one maintained module |
+| `node scripts/check_frontend.mjs --inventory` | 230 files, 707 static edges, 108 lazy literal edges, no missing targets, three existing static cyclic components |
+| `npm ci --ignore-scripts --no-audit --no-fund` | Locked development dependency installation succeeded |
+| Native `scripts/verify_frontend_runtime.py` | Real FastAPI lifespan and shell/static assertions passed without maintained source, node_modules or Node on PATH |
+| Docker runtime probe below | Same current-code assertions passed with networking disabled and source mount read-only |
+| esbuild spike | Two identical 1,554-byte bundle outputs; executed exports/icon/ordering equivalence passed |
+| JS syntax checks and Python compileall below | Passed |
+| `git diff --check`, preserved-scope diff check, hash/LF checks | Passed; no runtime/backend/packaging source diff |
+| Foundation documentation links, trailing whitespace and em-dash checks | All five files passed |
+
+The skipped test is
+`tests/test_docker_devops_hardening.py:187`, which requires the unavailable
+`odysseus-odysseus:latest` image. It was not relabeled or bypassed. F1's separate
+Docker runtime probe used the available `odysseus-maintainer-preview-odysseus:latest`,
+image ID `sha256:cc2d47e2327d573af01c6b027f23d2ab0f2ee9b85d658e9eb8065bd02b9c3515`,
+with Python 3.14.7, FastAPI 0.141.1 and Starlette 1.6.0. This proves compatibility
+of current candidate code/assets with that image's runtime dependencies, not a
+fresh build of the full repository Dockerfile or a deployment.
+
+Reproduce the final focused command with the actual tested interpreter:
+
+```sh
+/home/alteixeira20/.venvs/odysseus-pr-6495/bin/python -m pytest -q -rs \
+ tests/test_frontend_build.py tests/test_frontend_foundation_offline_js.py \
+ tests/test_frontend_module_graph.py tests/test_frontend_module_version_parity.py \
+ tests/test_action_menu_order.py tests/test_panel_loader_js.py \
+ tests/test_app_static_mime.py tests/test_serve_html_with_nonce.py \
+ tests/test_runtime_paths.py tests/test_ci_authoritative_validation.py \
+ tests/test_selected_notes_context.py tests/test_email_library_module_graph_js.py \
+ tests/test_settings_module_import_paths.py tests/test_app_config_shared_fetch_js.py \
+ tests/test_markdown_lazy_lib_loading_js.py tests/test_startup_shell_js.py \
+ tests/test_static_stylesheet_manifest.py tests/test_notes_dom_xss_helpers.py \
+ tests/test_notes_reminder_temporal_redos.py tests/test_notes_sidebar_new_note.py \
+ tests/test_notes_mobile_checklist_toggle_static.py \
+ tests/test_notes_document_mutual_minimize.py tests/test_docker_devops_hardening.py
+
+node --test tests/frontendArchitecture.test.mjs
+ENDPOINT_URL=http://127.0.0.1:1 node --test \
+ tests/noteTestOracle.test.mjs tests/notesDraftAutosave.test.mjs \
+ tests/selectedNotesContext.test.mjs
+
+python3 scripts/build_frontend.py --check
+node scripts/check_frontend.mjs
+/home/alteixeira20/.venvs/odysseus-pr-6495/bin/python scripts/verify_frontend_runtime.py
+
+docker run --rm --network none \
+ --mount type=bind,src=/home/alteixeira20/Projects/Odysseus/worktrees/architecture/frontend-foundation,dst=/candidate,readonly \
+ --workdir /candidate --entrypoint python \
+ odysseus-maintainer-preview-odysseus:latest scripts/verify_frontend_runtime.py
+```
+
+`ENDPOINT_URL` satisfies the existing oracle's import-time configuration requirement.
+Its unit-test imports exercise pure exported functions; its network-driving main
+is guarded by the executable-module check and does not run. The closed loopback
+address is not a live model endpoint. No oracle implementation was changed.
+
+Syntax commands executed:
+
+```sh
+bash -c 'shopt -s globstar nullglob; for f in static/app.js static/js/**/*.js frontend/src/**/*.js scripts/check_frontend.mjs tests/frontendArchitecture.test.mjs; do node --check "$f" || exit; done'
+/home/alteixeira20/.venvs/odysseus-pr-6495/bin/python -m compileall -q app.py core routes src services scripts tests
+git diff --check
+git diff --exit-code -- static app.py Dockerfile .dockerignore Odysseus.spec build-macos-app.sh build-windows-portable.ps1 launcher.py core routes src services
+git check-attr text eol -- frontend/src/shared/actionMenuOrder.js static/js/actionMenuOrder.js
+sha256sum frontend/src/shared/actionMenuOrder.js static/js/actionMenuOrder.js
+```
+
+Spike compiler invocation, executed twice with equality and Node import assertions:
+
+```sh
+npx --yes esbuild@0.25.12 frontend/src/shared/actionMenuOrder.js \
+ --bundle --format=esm --target=es2022 --platform=browser --log-level=error
+```
+
+The clean publication proof uses temporary roots in `test_frontend_build.py`,
+including an initially absent output tree. Real-checkout publication is idempotent.
+No emitted JS bytes, URLs, boot scripts or cache manifests changed in this lane.
+
+## Failures encountered and their resolution
+
+- An early architecture self-test expected an identity diagnostic but got an
+ unresolved source path for a query-bearing relative import. The checker now
+ rejects alternate identity before resolving that source path. All final tests
+ pass; no test requirement was weakened.
+- The initial Notes oracle command failed during import because `ENDPOINT_URL`
+ was missing. Inspection established that the unit-test path never runs its
+ endpoint-driving main. The explicit closed-address configuration above passed
+ all 11 tests. This prerequisite is recorded for N0 rather than hidden.
+- The first isolated distribution fixture omitted the existing `companion/`
+ package, so both probes failed with `ModuleNotFoundError`. The fixture now
+ includes that required runtime directory; neither application nor packaging
+ implementation was modified to make the tests pass.
+- The first exploratory native startup check connected to the existing local
+ ChromaDB and refreshed the built-in tool index. That was unintended. Subsequent
+ probes use a private distribution/data directory, a reserved non-listening
+ Chroma port, disabled existing warmup options and no Node on PATH. Docker also
+ disables networking. No attempt was made to overwrite or restore that service's
+ data; the earlier unisolated probe is not the reproducible validation recipe.
+
+## Remaining risks and limits
+
+Root offline reload is not certified: existing SW scope is `/static/`, and open
+[#6227](https://github.com/odysseus-dev/odysseus/pull/6227) proposes the independent
+scope/header correction. F1 preserves and tests actual offline module behavior
+at the current scope. No first-use offline guarantee is claimed for optional
+CDN libraries, Mermaid or server APIs.
+
+Windows/macOS packaged executables, a fresh full Dockerfile build, the full pytest
+suite, Firefox/WebKit offline behavior and CI's exact Python 3.11/Node 20 versions
+were not executed here. Existing packaging paths are inspected and unchanged;
+platform owners should run release validation before broader certification.
+The unavailable-image test remains a coverage gap. Legacy source still has
+cross-feature coupling, global side effects and static cycles. New boundaries
+are enforced on maintained source, not retrospectively on the entire legacy tree.
+
+The publisher intentionally does not clean retired outputs or provide atomic
+multi-file deployment. Review full source/output/facade/manifest changes and
+ship a coherent artifact. Domain syntax checks cannot prove all semantic purity
+or disposal; behavioral characterization remains required. Reconcile the package
+lock with #6627 and refresh all PR overlaps before integration.
+
+## Reviewer checklist
+
+- Verify the base contains #6495 and the official integration target is dev.
+- Confirm the deployed helper hash and runtime-scope diff are unchanged.
+- Review the layer matrix, public API rules, single-state ownership and zero
+ current legacy exceptions; verify negative tests actually reject violations.
+- Review the manifest mapping, byte-parity/LF policy, exact offline precache and
+ source/output relative-resolution guard; verify missing or overridden LF
+ declarations fail publication and CI even when output bytes already match.
+- Reproduce the focused tests and inspect the skipped-image prerequisite.
+- Confirm no frontend compiler/runtime dependency is required at startup and
+ inspect the isolated Python/Docker probe's limits.
+- Review overlap with #6470/#6695/#6227/#6627 and the Notes backend follow-ups.
+- Treat the ADR as awaiting adoption review, and the Notes/H documents as plans.
+- Authorize any commit/push/PR action separately. Do not begin Notes on this branch.
+
+## Required next reviews and continuation
+
+1. Review this F1 working diff. On explicit authorization, commit and submit only
+ the foundation-only F1 PR to official dev using the normal maintainer workflow.
+2. Coordinate the existing #6227 offline fix and platform release validation as
+ separate work. Do not bundle that behavioral change into F1.
+3. After F1 integration and Notes implementation authorization, create one Notes
+ worktree and branch from the latest official dev, preserving any subsequently
+ merged Notes changes. Use one comprehensive draft PR targeting official dev.
+4. Complete N0 through N6 from the [Notes roadmap](notes-roadmap.md) on that same
+ branch, recording tests, review and rollback evidence at each checkpoint. Include
+ the final reference case study in the same PR and keep it a draft until the full
+ decomposition and regression/compatibility acceptance gates pass. Recurrence
+ extraction follows characterization as an internal stage, not another PR.
+5. Complete H only after Notes integration and recipient reproduction. Transfer
+ future frontend work to the designated maintainer and stop this program.
+
+Another maintainer can start at the handbook, run the documented source/parity,
+architecture, runtime and behavior checks, inspect this report and select the
+next authorized slice without relying on unwritten architecture decisions.
diff --git a/docs/maintainers/README.md b/docs/maintainers/README.md
new file mode 100644
index 000000000..bd5e93f24
--- /dev/null
+++ b/docs/maintainers/README.md
@@ -0,0 +1,38 @@
+# Odysseus maintainer handbook
+
+Odysseus maintainers are trusted to act, not to wait for permission. The default is individual responsibility; additional review is required when the **risk** warrants it.
+
+This handbook records the project's maintainer governance and gives reviewers a reusable process. It complements [CONTRIBUTING.md](../../CONTRIBUTING.md) and [SECURITY.md](../../SECURITY.md); it does not replace the PR template, repository protections, or product decisions.
+
+## At a glance
+
+| Area | Working rule |
+|---|---|
+| Product direction | Pewds is the Product Owner |
+| Ordinary, reversible maintainer PR | Self-merge allowed after appropriate validation and applicable repository checks |
+| External contribution | Maintainer review required |
+| High-risk change | At least one **independent, qualified** maintainer review |
+| Access | Need-to-have, least privilege, separately granted per system |
+| Release | A designated Release Maintainer owns preparation and publish |
+| Inactivity | Access review after 2 months without activity, notice, or response |
+| Documentation | Repository Markdown is canonical |
+
+These are governance rules, not guarantees that a GitHub permission or branch-protection setting permits a particular action. Respect the stronger applicable automated gate.
+
+## Start here
+
+- [Roles and access](roles-and-access.md): responsibility, permissions, and continuity.
+- [Product and feature proposals](product-and-features.md): product approval versus technical ownership.
+- [Changes and review](changes-and-review.md): review thresholds, self-merge, contributor corrections.
+- [Practical review playbook](review-playbook.md): risk, provenance, CI, CodeQL, independent audit, and handoff evidence.
+- [Triage](triage.md): turning incoming reports into actionable work.
+- [Testing and releases](testing-and-releases.md): evidence, platform validation, promotion to main.
+- [Documentation](documentation.md): canonical sources, updates, and traceability.
+
+## Accountability
+
+Maintainers own the changes they take on, including validation, regression prevention, follow-up, and rollback when needed. Roles describe responsibilities, not a hierarchy of technical approval.
+
+Important product-direction decisions go through the Product Owner. Maintainers retain responsibility for feasibility, implementation, maintainability, and security.
+
+AI coding or review agents can help collect evidence, test hypotheses, and prepare changes, but they are not the qualified human reviewer required for high-risk changes. A maintainer must inspect and accept the evidence.
diff --git a/docs/maintainers/changes-and-review.md b/docs/maintainers/changes-and-review.md
new file mode 100644
index 000000000..664b2596a
--- /dev/null
+++ b/docs/maintainers/changes-and-review.md
@@ -0,0 +1,62 @@
+# Changes and review
+
+Review is **risk-based**. Trusted maintainers should be able to ship ordinary work without creating a queue of ceremonial approvals.
+
+## Required review
+
+| Change | Minimum review rule |
+|---|---|
+| Ordinary, reversible maintainer change | Independent approval optional; self-merge permitted after appropriate validation |
+| External contribution | Maintainer review required |
+| High-risk change | At least one independent, qualified maintainer review required |
+
+Repository branch protection and required checks also apply. Never treat this document as permission to bypass a live protection rule.
+
+## Ordinary maintainer changes
+
+1. Open a PR against `dev`, scoped to one coherent change.
+2. Explain intent, expected behavior, validation, and rollback if relevant.
+3. Run suitable tests and inspect the actual result.
+4. Ensure applicable required checks pass, address feedback, and merge when ready.
+
+Self-merge is allowed for ordinary reversible work. The author remains responsible for follow-up, correction, and rollback.
+
+## External contributions and small corrections
+
+External contributions receive maintainer review.
+
+A maintainer may directly fix a **small, obvious** problem in a contributor PR when the intended behavior is clear and the repair is faster than a separate round trip. Document what changed, preserve contributor attribution and history, avoid force-pushing, and re-run affected checks.
+
+Substantive or ambiguous corrections require discussion with the contributor or a separately scoped correction. A maintainer must not silently turn a contributor's PR into unrelated work. Any corrective commit changes the SHA being reviewed; update validation and audit evidence accordingly.
+
+## High-risk changes
+
+High-risk work requires **at least one independent qualified review**. The author cannot be the only approver. Examples:
+
+- Authentication, authorization, tenancy, sandboxing, agent tool permissions, or secrets.
+- Outbound network and SSRF defenses, sensitive integrations, and deployment access.
+- Destructive operations, deletion, filesystem ownership, and data migrations.
+- Persistence and concurrency invariants with possible data loss.
+- Major architectural contracts, release infrastructure, or changes hard to roll back.
+
+A high-risk review should verify the threat or failure model, exact final commit, reproducer or regression evidence, failure and rollback behavior, and the relevant CI/security findings. Use the [review playbook](review-playbook.md).
+
+## Cross-area changes and CODEOWNERS
+
+Touching multiple areas does **not** automatically require multiple approvals. Consult domain expertise when needed. `.github/CODEOWNERS` currently contains no ownership rules; the per-area map is under discussion in [issue #593](https://github.com/odysseus-dev/odysseus/issues/593). Once populated, it helps identify reviewers and accountable contacts; it is not a blanket approval requirement by itself.
+
+## Validation and UI evidence
+
+Automated tests count as runtime evidence when they truly exercise the changed behavior. Use manual validation when coverage is insufficient.
+
+For any change to visible UI behavior, follow the current [contributor UI checklist](../../CONTRIBUTING.md#style-and-visual-changes) and the repository PR template. Screenshots or clips are expected when they materially demonstrate the rendered result; screenshots alone do not replace behavioral tests.
+
+## Disagreement and escalation
+
+The maintainer doing the work owns ordinary implementation decisions within approved product direction and existing technical contracts. For substantive disagreements:
+
+1. Involve a qualified maintainer with relevant expertise.
+2. Escalate unresolved cross-cutting technical issues to trusted project-wide maintainers.
+3. Refer product-direction disagreements to the Product Owner.
+
+Security findings should be handled via [SECURITY.md](../../SECURITY.md), without disclosing exploit details in public issues. Repository protection rules should support these risk-based policies and should not accidentally force independent approval for every ordinary maintainer PR.
diff --git a/docs/maintainers/documentation.md b/docs/maintainers/documentation.md
new file mode 100644
index 000000000..36c88d81d
--- /dev/null
+++ b/docs/maintainers/documentation.md
@@ -0,0 +1,32 @@
+# Documentation
+
+Repository Markdown is the canonical source for project documentation. A public docs site may be generated from it; avoid maintaining an independent wiki copy unless there is a deliberate future decision to do so.
+
+## Where information belongs
+
+| Location | Purpose |
+|---|---|
+| `/design` | Product intent, proposals, and accepted decisions (when those paths are used) |
+| `/specs` | Technical contracts and invariants |
+| `/website` | User, setup, configuration, and deployment guidance (published as the docs site) |
+| `/docs` | Developer, architecture, security, and maintainer guidance |
+| Root Markdown | Discoverable entry points and policies |
+
+Keep root documents easy to find:
+
+- `README.md`
+- `CONTRIBUTING.md`
+- `SECURITY.md`
+- `THREAT_MODEL.md`
+
+Not every named directory exists today; do not invent a parallel documentation store just to match this map.
+
+## Updating documentation
+
+When behavior, architecture, a workflow, or its verification requirements change, update the canonical documentation in the same PR when appropriate.
+
+Separate **policy** from **examples**: examples may evolve with tooling; changes to role authority, review requirements, or product ownership require an explicit governance decision. Do not introduce a new mandatory approval rule through a checklist alone.
+
+Documentation PRs should link the relevant issue, record what was reviewed (links, commands, or affected features), and avoid publishing private channels, account names, local paths, secrets, or confidential incident details.
+
+For practical examples of review evidence, see the [review playbook](review-playbook.md). For contributor setup and PR requirements, use [CONTRIBUTING.md](../../CONTRIBUTING.md).
diff --git a/docs/maintainers/product-and-features.md b/docs/maintainers/product-and-features.md
new file mode 100644
index 000000000..d41055a7f
--- /dev/null
+++ b/docs/maintainers/product-and-features.md
@@ -0,0 +1,48 @@
+# Product and feature proposals
+
+Pewds ([@pewdiepie-archdaemon](https://github.com/pewdiepie-archdaemon)) is the Product Owner for Odysseus and has final authority over product direction. Maintainers own technical feasibility, implementation, and safety.
+
+## Which changes require product approval?
+
+**Product Owner approval before implementation:** substantial new features, changes to product direction, and product changes that are hard to reverse.
+
+**No separate product approval by default:** bug fixes, security fixes, maintenance, tests, CI, documentation, internal refactors, and small, reversible product changes within existing direction.
+
+Maintainers may make those smaller product decisions. Pewds can ask for changes or a rollback; the maintainer owns safe rollback or recovery.
+
+### Urgent security and reliability fixes
+
+Urgent fixes or containment may proceed without prior product approval, even if behavior temporarily changes. Keep the change to what stops the immediate problem, notify Pewds promptly, and record the reason and rollback or recovery plan. Agree on any lasting product-direction change with Pewds afterwards. Normal high-risk review and repository checks still apply.
+
+## Product Owner initiated
+
+```text
+Product Owner proposal or implementation
+ -> technical feasibility
+ -> plan and implementation
+ -> risk-based review and validation
+```
+
+A Product Owner proposal is already product-approved; it is not automatically technically approved or exempt from high-risk review.
+
+## Community or maintainer initiated
+
+Community proposals start as a Feature Request issue. Check [ROADMAP.md](../../ROADMAP.md) and existing issues first; take early ideas to [Discussions](https://github.com/odysseus-dev/odysseus/discussions/categories/ideas).
+
+```text
+Feature proposal
+ -> Product Owner accepts / rejects, where approval is required
+ -> technical feasibility
+ -> plan and implementation
+ -> risk-based review and validation
+```
+
+Record the decision in an issue, proposal, work item, or PR so future maintainers can discover it. Do not rely on a chat-only decision.
+
+## Decision boundaries
+
+The Product Owner decides **what belongs in Odysseus**. Maintainers decide **how approved work is built safely and maintainably**.
+
+A rejected or out-of-scope feature can be maintained independently in a contributor's fork.
+
+If the Product Owner is unavailable, work requiring prior product approval waits unless authority was explicitly delegated. Smaller decisions and urgent fixes follow the rules above.
diff --git a/docs/maintainers/review-playbook.md b/docs/maintainers/review-playbook.md
new file mode 100644
index 000000000..e9f0e6f99
--- /dev/null
+++ b/docs/maintainers/review-playbook.md
@@ -0,0 +1,129 @@
+# Practical PR review playbook
+
+Use this as a **repeatable review method**, not as an extra organizational approval ladder. The binding minimums remain in [changes and review](changes-and-review.md): ordinary maintainer changes may be self-merged, external PRs require maintainer review, and high-risk work requires at least one independent qualified maintainer review.
+
+No single checklist replaces engineering judgment. Increase depth with risk.
+
+## 1. Understand the PR and establish its review gates
+
+- Establish the problem, what the PR fundamentally proposes, and why the approach makes sense.
+- Check product direction, architecture fit, and scope before detailed review.
+- Write down the questions the review must answer, the evidence needed, and what would block further review or approval.
+- Confirm repository, source fork, target branch (`dev`), exact **HEAD SHA**, and current base.
+- Review the full effective diff, commit history, issue, prior feedback, and related upstream changes.
+- Confirm the branch is mergeable against the **current** `dev`, not an older local snapshot.
+- Identify the user-facing contract, affected data and users, security boundaries, and rollback plan.
+- Separate pre-existing upstream problems from regressions introduced or made reachable by the PR.
+
+Example read-only commands:
+
+```bash
+REPO="odysseus-dev/odysseus"
+PR=1234
+gh pr view "$PR" --repo "$REPO" --json title,state,isDraft,headRefOid,baseRefName,mergeable
+gh pr diff "$PR" --repo "$REPO"
+gh pr checks "$PR" --repo "$REPO"
+```
+
+A green check on an old commit does not verify the revised branch.
+
+## 2. Review the failure and threat model
+
+For the relevant change, ask what happens with malformed input, missing auth state, wrong owner, concurrent requests, stale caches, partial failure, retries, cancelled jobs, unavailable dependencies, and restart/recovery.
+
+Prioritize boundaries that can lose data or authority: identity, delegated API tokens, filesystem confinement, email deletion, persistence versioning, network/SSRF destinations, secrets, and agent tool execution.
+
+For security claims, demonstrate the source-to-sink path and the *actual* guard. Tests must represent production middleware or transport where a unit mock could conceal a bypass.
+
+## 3. Correct without obscuring contributor work
+
+For small, unambiguous issues, maintainers may add focused corrections directly to a contributor PR under [the contribution review policy](changes-and-review.md#external-contributions-and-small-corrections). Preserve provenance, explain the change, prefer normal commits and fast-forward pushes, and avoid unrelated rewrites.
+
+For substantive or ambiguous work, ask the contributor or prepare a clearly separated patch. Any code change means validating **the new SHA**, not approving based solely on the previous audit.
+
+## 4. Build an evidence record
+
+Run contributor code under the [runtime isolation rules](testing-and-releases.md#runtime-isolation).
+
+Useful evidence includes:
+
+- Pre-fix reproduction, expected outcome, and actual outcome.
+- Focused regression tests for the fix and broad suites relevant to cross-cutting effects.
+- Actual runtime checks (browser/UI, backend, Docker, supported OS) where necessary.
+- Exact executed commands, result counts, skipped cases, and environmental limitations.
+- GitHub required checks and conflict-free state on the exact final SHA.
+- Relevant operational consequences (data migration, rollback, compatibility).
+
+Keep audits reproducible. A screenshot alone is not a functional test, and a passing mocked test is not proof that a production integration path is safe.
+
+## 5. Independent review for high-risk changes
+
+A separate **qualified maintainer** must inspect high-risk changes; the implementing author cannot be the sole reviewer. Independent coding agents may be useful for adversarial tests and cross-checks, but **an AI agent is not itself a GitHub approver** and does not replace human accountability.
+
+To avoid confirmation bias, give the independent reviewer the current SHA, changed files, acceptance criteria, known reproduction, and explicit permission to challenge the proposed solution. Preserve unresolved findings and require a new audit when meaningful fixes change the diff.
+
+## CodeQL and security scanning
+
+A successful CodeQL workflow means analysis ran, not that the security dashboard is empty. Likewise, resolving a PR discussion does not necessarily resolve its code-scanning alert.
+
+For each relevant alert:
+
+1. Record the alert number, rule, severity, file/line, state, and source-to-sink trace if applicable.
+2. Compare with the current `dev` baseline; decide whether the PR introduced, exposed, or did not affect it.
+3. Reproduce or reason through the actual production behavior, including validation and authorization.
+4. **Fix** credible vulnerabilities, preferably with a regression test. Do not hide them by broad suppressions.
+5. **Recommend dismissal** only for a demonstrable false positive or a stale/invalid finding, with a precise technical explanation; only authorized maintainers should dismiss alerts.
+6. Document genuine but intentionally accepted risk separately. A true positive is not a false positive merely because it is deliberate.
+7. Rerun or inspect updated analysis on the final commit and confirm no blocking issues remain.
+
+Never publish exploit payloads, secrets, or credentials in public review comments. See [SECURITY.md](../../SECURITY.md).
+
+## 6. Decide and integrate
+
+Before approval or self-merge, verify:
+
+- Current branch and reviewed SHA are still the ones to be merged.
+- All applicable required checks are complete and successful.
+- High-risk independent review is present, where required.
+- No unresolved, credible P0/P1/P2 security or data-integrity defects remain in the change. Resolve or explicitly document P3 observations with a tracked owner and priority.
+- Review discussions, compatibility risks, and operational handoffs have been addressed.
+- The correct target is `dev`; `main` is curated for releases.
+
+This P0-P3 classification is [triage guidance](triage.md#practical-priority-language), not a replacement for branch protection or an excuse to self-approve high-risk work. Maintainers may apply a stricter bar where warranted.
+
+For a final manual merge, GitHub CLI supports an exact-head guard:
+
+```bash
+gh pr merge 1234 --repo odysseus-dev/odysseus --squash \
+ --match-head-commit
+```
+
+Use `--delete-branch` only when removing the source branch is appropriate and does not disrupt another workstream. Do not force a merge past review or security requirements.
+
+## 7. Post-merge follow-up
+
+Verify the PR actually merged and reference its integration commit. Record remaining operational work, such as schema migrations, backup/restore verification, service restarts, or compatibility documentation. A code change to a container mount does **not** by itself migrate existing runtime data.
+
+Do not silently mark a deferred data migration complete; track its owner, evidence, rollback, and execution separately.
+
+## Reusable reviewer handoff
+
+```text
+PR / target:
+Reviewed source HEAD SHA:
+Current target branch SHA:
+Scope and changed files:
+Impact and risk classification:
+Security / correctness invariants challenged:
+Pre-fix reproducer and post-fix evidence:
+Tests run, skipped, and environment:
+CodeQL / scanning alert dispositions:
+Required GitHub checks (exact SHA):
+Mergeability and remaining conflicts:
+Unresolved P0 / P1 / P2 / P3 findings:
+Rollback / operational follow-ups:
+Independent qualified review required? Completed?
+Verdict: APPROVED / CHANGES REQUIRED / BLOCKED
+```
+
+State what was actually verified. Do not write "all checks green" if only a subset of workflows was inspected.
diff --git a/docs/maintainers/roles-and-access.md b/docs/maintainers/roles-and-access.md
new file mode 100644
index 000000000..a98fd3258
--- /dev/null
+++ b/docs/maintainers/roles-and-access.md
@@ -0,0 +1,40 @@
+# Roles and access
+
+Roles clarify who is accountable. They do not create a management chain or automatically grant privileges.
+
+## Responsibility and typical access
+
+| Responsibility | Typical GitHub access | Purpose |
+|---|---|---|
+| Product Owner | No automatic repository access implied | Product direction |
+| Organization Owner | Organization Owner | Organization administration and continuity |
+| Repository Admin | Admin | Repository settings, permissions, and protection rules |
+| Maintainer | Write by default | Implement, review, merge, and maintain |
+| Triage | Triage | Organize intake, de-duplicate, and prepare work |
+| Contributor / Platform Tester | Public / Read as appropriate | Contribute code or provide validation |
+
+Maintain access may be granted when repository-management duties require it.
+
+## Maintainer focus
+
+- **Core Maintainer:** project-wide judgment, difficult technical decisions, governance support.
+- **Technical Maintainer:** implementation, architecture, validation, technical health.
+- **Project Maintainer:** review, contributor coordination, documentation, releases, organization.
+
+These are responsibility labels. No label automatically changes GitHub permissions or overrides the [review rules](changes-and-review.md).
+
+## Functional responsibilities
+
+Maintainers may coordinate Release, Security, Infrastructure and CI, Community, or Test and Validation. These are duties, not ranks. For each release, designate one Release Maintainer and record the handoff if ownership changes.
+
+## Least privilege and continuity
+
+Grant access because it is necessary for current work, not because of a title. GitHub, Matrix, Plane, infrastructure, SSH, deployment systems, secrets, and external services are separate access surfaces.
+
+For elevated or sensitive access, document a responsible owner and recovery route in an appropriate **private** administrative system. Do not publish tokens, SSH details, personal addresses, or credential locations in this handbook. Remove access promptly when it is no longer needed.
+
+## Inactivity
+
+Tell an admin when you expect to be unavailable; a communicated absence is fine.
+
+If there is no meaningful maintainer or triage activity for **two months**, no prior notice, and no response to reasonable follow-up, elevated access may be reviewed and removed. This is access hygiene, not punishment. Returning members may regain access appropriate to their active responsibilities.
diff --git a/docs/maintainers/testing-and-releases.md b/docs/maintainers/testing-and-releases.md
new file mode 100644
index 000000000..23ab33853
--- /dev/null
+++ b/docs/maintainers/testing-and-releases.md
@@ -0,0 +1,52 @@
+# Testing and releases
+
+Validation must match the actual change, and evidence must state what was **run**, **observed**, and **not tested**.
+
+`dev` is the integration and stabilization branch. `main` is the curated release destination. Changes land in `dev`; a release promotes a verified `dev` revision to `main`.
+
+## Runtime isolation
+
+Run contributor-controlled tests, builds, installs, and repros in an isolated, secretless environment. Use disposable containers or microVMs where appropriate, with no credentials, sensitive host files, production data, or host/container-management sockets exposed. If safe isolation is unavailable, record the check as not run.
+
+Agents may use a skill for the maintainer's preferred environment and handling; the same isolation requirements apply.
+
+## Change validation
+
+- Run focused tests that cover the modified behavior and failure cases.
+- Run broader regressions where risk crosses module boundaries.
+- For authentication, data loss, or similar high-risk work, include adversarial and rollback tests.
+- Reproduce the issue on the pre-fix version when safe and practical, then prove the correction.
+- For visual changes, run the application and attach the screenshots or clips required by [CONTRIBUTING.md](../../CONTRIBUTING.md).
+- Record exact commands, environment, result, skipped tests, and blockers. Never claim execution from a command you did not run.
+
+GitHub Actions success means a workflow finished successfully; it does **not** mean CodeQL found no alerts. Use [review playbook](review-playbook.md#codeql-and-security-scanning) to assess findings separately. A review must tie required CI and the final diff to the **same commit SHA**.
+
+## Supported-environment evidence
+
+Platform Testers may validate without maintainer permissions. Useful coverage includes:
+
+- Windows native and WSL.
+- macOS Apple Silicon.
+- macOS Intel while supported.
+- Linux native on the reference distribution.
+- Docker on supported hosts.
+
+Record the environment and configuration for each result. Do not imply that a platform was tested when it was not.
+
+## Release ownership
+
+A designated **Release Maintainer** owns preparation and the publish decision once the release criteria are met. Other maintainers and testers supply the evidence needed for the change set. If the Release Maintainer becomes unavailable, another maintainer explicitly takes over.
+
+## Release checklist
+
+Before promoting `dev` to `main`:
+
+1. Identify and freeze the release candidate SHA; check the actual content that will ship.
+2. Verify required checks and relevant supported-environment validation.
+3. Confirm high-risk and data-migration findings are resolved or addressed through an explicit approved plan.
+4. Document skipped coverage, known issues, compatibility and upgrade implications.
+5. Prepare the version, tag, artifacts, and release notes.
+6. Confirm rollback/recovery, including any manual persistence or data migration steps.
+7. Publish and record what was promoted, the verification evidence, and operational follow-ups.
+
+Publishing does not require ceremonial Core or domain sign-off when the criteria are met. Exceptional or disputed releases follow the normal high-risk escalation path.
diff --git a/docs/maintainers/triage.md b/docs/maintainers/triage.md
new file mode 100644
index 000000000..d2f47f8ab
--- /dev/null
+++ b/docs/maintainers/triage.md
@@ -0,0 +1,48 @@
+# Triage
+
+Triage turns reports into evidence-backed work that a maintainer can pick up without guessing.
+
+## Intake flow
+
+```text
+Report
+ -> reproduce / clarify
+ -> identify duplicates and affected versions
+ -> classify impact, urgency, and risk
+ -> prepare actionable work item
+ -> maintainer takes ownership
+ -> PR, verification, and follow-up
+```
+
+## A useful work item
+
+Record what is known and distinguish it from what remains unverified:
+
+- Original report and reproducible steps; installation method, OS, version/commit, and relevant environment.
+- Expected versus actual behavior, including user-visible impact.
+- Evidence: sanitized logs, screenshots, failing tests, or controlled reproduction.
+- Related issues, PRs, duplicates, or a known prior regression.
+- Scope, acceptance criteria, and non-goals.
+- Priority, ownership, and relevant domain expertise.
+- Remaining unknowns, risks, and safe recovery or workaround when available.
+
+Small and obvious fixes may go straight to a focused PR, consistent with [CONTRIBUTING.md](../../CONTRIBUTING.md) and [changes and review](changes-and-review.md).
+
+## Practical priority language
+
+Use P0-P3 as **triage shorthand**, not as a substitute for verified exploitability or the project's actual GitHub labels:
+
+| Priority | Typical impact | Expected response |
+|---|---|---|
+| P0 | Active exploitation, broad irreversible loss, catastrophic outage | Immediate containment and escalation |
+| P1 | Credible severe security or data-integrity vulnerability | Urgent owner assignment and validated fix |
+| P2 | Significant correctness, security, or operational regression | Prioritize and resolve before approving affected high-risk changes |
+| P3 | Limited impact, maintainability, or low-risk polish | Fix or explicitly track with rationale |
+
+Do not call a concern harmless merely because an automated check is green. Escalate privately when reproduction would disclose a vulnerability.
+
+## Where decisions live
+
+Matrix is for coordination; durable decisions belong in GitHub, Plane, a specification, or the relevant PR. Keep confidential security and access details in appropriate private channels. Do not leave important project decisions only in chat history.
+
+See the [review playbook](review-playbook.md) for converting triage into review evidence and handling contested or uncertain findings.
diff --git a/docs/searxng-trust-image.md b/docs/searxng-trust-image.md
new file mode 100644
index 000000000..e0f406e82
--- /dev/null
+++ b/docs/searxng-trust-image.md
@@ -0,0 +1,39 @@
+# Upstream SearXNG trust validation
+
+SearXNG owns independent system and Python certificate stores. Updating Odysseus's Python environment does not update this sidecar. The base and both standalone GPU Compose files now select the official `docker.io/searxng/searxng:2026.10.24-ef0ec03da` image at immutable multiarch digest `sha256:7c7cbe509429e82755104b2a95f52085a98633c95d53f44e4e905fa3a59f08c8`. Its system and certifi stores remove the affected eMudhra trust. The [upstream certifi update](https://github.com/searxng/searxng/pull/6881) is included in this release.
+
+Deploy the upstream image directly. The validation Dockerfile adds public fixtures and diagnostics only; no repair layer, custom runtime image or project registry publisher is required. `scripts/check_ca_trust.py` owns the known-certificate inventory for both the application and SearXNG checks.
+
+## Validate a pin update
+
+Run from the repository root on a disposable Docker host. The helper uses a fresh configuration volume, omits published ports and does not load the operator's `.env`. It retains the base Compose settings wrapper, healthcheck and capabilities. Outbound network access and working search engines are required for the live checks.
+
+```sh
+image=$(docker compose --env-file /dev/null -f docker-compose.yml config --format json |
+ python3 -c 'import json, sys; print(json.load(sys.stdin)["services"]["searxng"]["image"])')
+
+# Offline build-step checks, including actual entrypoint and loopback health.
+# Pulling the selected base still requires registry access.
+docker build --network=none --target validation \
+ --build-arg "SEARXNG_IMAGE=$image" -f docker/searxng/Dockerfile .
+
+# Exercise the exact unmodified deployment image after an anonymous pull.
+docker pull "$image"
+bash .github/scripts/validate-searxng-image.sh "$image"
+```
+
+The offline checks require all fourteen incident chains to fail certificate verification through the system PEM bundle, hashed CA directory and certifi. The affected positive-control roots must accept those same chains. Each fixture's DER fingerprint is verified first, and a fixed verification timestamp prevents expiry from hiding a broken mitigation. Checks run again after the real upstream root entrypoint regenerates trust.
+
+The live checks use SearXNG's actual curl client factory. Ordinary verified HTTPS must succeed, all fourteen incident hosts must fail with curl certificate error 60, and a JSON search must return results. DNS failures, timeouts and generic handshake failures are inconclusive and fail validation. The checks inspect the already-running service without changing its trust stores.
+
+The `ci / SearXNG trust` workflow runs these offline and Compose/live checks on native amd64 and arm64 runners. It selects the same immutable image as base Compose, pulls without registry credentials, and has read-only repository permissions. It neither publishes a replacement image nor requires package-write credentials. Update all three deployment pins together; the alignment regression guards the standalone GPU files.
+
+## Rollout and scope
+
+Changing a Compose pin does not replace running containers. After updating the checkout, run `docker compose pull searxng` and `docker compose up -d --no-deps searxng`, then inspect health, retained settings and actual Odysseus search integration. Use the appropriate standalone GPU Compose file when that is the deployment being managed.
+
+Operator-mounted trust, custom engines, persisted packages and independently managed clients need separate effective-client checks. An amd64 result does not establish arm64 behavior. The fixture-based check detects known certificate fingerprints; it does not model every native revocation mechanism or arbitrary reissued certificates sharing a compromised key. See [outbound TLS trust](tls-trust.md) for the application, bootstrap, Chromium and other runtime boundaries.
+
+## Public fixture provenance
+
+The public CA inventory comes from the incident's [roots](https://emudhra.we-have-a-problem.com/roots.json) and [intermediates](https://emudhra.we-have-a-problem.com/impacted-intermediates.json). The additional cross-signed issuer and fourteen chain fixtures come from [chains.zip](https://emudhra.we-have-a-problem.com/chains.zip), SHA-256 `7b949956955fc501a30f4d98d2f513d34c0bbbe92e29a968194c96e097ce2345`. Fixtures contain public certificates only. See [the fixture notes](../tests/fixtures/ca-trust/README.md).
diff --git a/docs/skills-audit-architecture.md b/docs/skills-audit-architecture.md
new file mode 100644
index 000000000..78227a763
--- /dev/null
+++ b/docs/skills-audit-architecture.md
@@ -0,0 +1,379 @@
+# Skills evaluation and audit architecture
+
+The Skills backend separates HTTP transport, model evaluation, agent execution,
+audit orchestration and publication policy. `services/skills/` coordinates those
+responsibilities; `services/memory/skills.py` remains the canonical persistence
+and lifecycle owner. The extraction preserves the existing HTTP and Python
+contracts. [PR #6711](https://github.com/odysseus-dev/odysseus/pull/6711) tracks
+this boundary change under [issue #6710](https://github.com/odysseus-dev/odysseus/issues/6710).
+
+## Responsibilities and dependency boundaries
+
+| Module | Responsibility |
+| --- | --- |
+| `routes/skills_routes.py` | FastAPI request models, endpoint declarations, authentication, ownership, HTTP errors, exact approval validation and Python compatibility bindings |
+| `services/skills/job_coordinator.py` | Transient job creation, continuation after approval validation, candidate selection, public polling projections and cancellation requests |
+| `services/skills/agent_runner.py` | Manual execution, audit arms, agent loop integration, transcripts, authority propagation, approval pauses and same-task stream closure |
+| `services/skills/audit_workflow.py` | Per-skill audit sequencing, self-edit retries, teacher escalation, sequential batches and scheduled execution |
+| `services/skills/evaluation.py` | Model grading, verdict parsing, necessity and retrieval checks, efficiency fields and markdown improvement generation |
+| `services/skills/publication.py` | Confidence and publishing policy, duplicate rules, batch finalization and markdown updates through SkillsManager |
+| `services/skills/model_selection.py` | Owner-scoped worker/teacher resolution, utility fallback, endpoint selection and credential lookup |
+| `services/skills/prompts.py` | Shared task construction and explicitly untrusted skill context |
+| `services/skills/dependencies.py` | Frozen `AuditDependencies` containing callable bindings and transient registry references |
+| `services/memory/skills.py` | Canonical skill identity, owner isolation, durable storage, indexing, retrieval and lifecycle state |
+
+The package initializer identifies the domain without adding a service facade.
+Evaluation does not schedule jobs or persist skills. Publication computes policy
+and applies updates through the supplied SkillsManager. Services do not import
+`routes.skills_routes`. The existing preferences adapter in `publication.py`
+still imports `routes.prefs_routes`; moving that adapter is a separate change.
+
+```mermaid
+flowchart TD
+ HTTP[Authenticated HTTP requests] --> Routes[skills_routes]
+ Builtins[builtin_actions callers] --> Routes
+ Routes --> Jobs[job_coordinator]
+ Routes --> Models[model_selection]
+ Routes --> Evaluation[evaluation]
+ Routes --> Runner[agent_runner]
+ Routes --> Workflow[audit_workflow]
+ Jobs -->|injected calls| Runner
+ Jobs -->|injected calls| Workflow
+ Workflow -->|injected calls| Runner
+ Workflow -->|injected calls| Evaluation
+ Workflow -->|injected calls| Publication[publication]
+ Runner -->|injected calls| Evaluation
+ Runner --> Runtime[Agent runtime and authority enforcement]
+ Runner --> Prompts[prompts and untrusted context]
+ Jobs --> Prompts
+ Workflow --> Prompts
+ Routes --> Manager[Canonical SkillsManager]
+ Runner --> Manager
+ Workflow --> Manager
+ Publication --> Manager
+ Publication --> Preferences[Existing preferences adapter]
+ Models --> Resolver[Endpoint resolver and owner-scoped credentials]
+```
+
+Arrows include injected calls, rather than only Python imports. The workflow
+imports `SkillAuditUnavailable` from the runner. Route wrappers construct
+`AuditDependencies` on entry from the current route bindings, so existing
+callers and monkeypatches reach the same collaborators without rebinding shared
+service globals.
+
+The manual test registry belongs to `agent_runner.py`; the audit registry belongs
+to `audit_workflow.py`. Routes expose aliases to those dictionaries. Registries
+hold process-local job state and are not durable skill stores. All durable
+metadata, confidence, markdown and publication changes use SkillsManager.
+Published-only retrieval and local exclusion of `remote-only` skills stay in
+the manager/index boundary. Service loggers use their module names; the route
+module retains its own logger. Root handlers supply the existing log output.
+
+## Execution and publication lifecycle
+
+1. The HTTP handler authenticates the caller, verifies ownership and validates
+ the request. Manual model choices retain registered-endpoint validation and
+ owner-scoped credential lookup.
+2. Job coordination creates the owner-keyed transient record and launches the
+ execution coroutine. Replacing a manual test retires its pending approval.
+ Polling exposes only the existing public fields, excluding credentials,
+ private transcripts, continuation state and asyncio tasks.
+3. The runner uses the originating request authority or the consumed sealed
+ approval authority. It captures the transcript and closes the async stream
+ with `aclosing` inside the task that opened it, including early approval
+ pauses, cancellation and exceptions.
+4. Manual approval pauses return to the HTTP validation boundary. Continuation
+ reconstructs context from the original untrusted skill and accumulated
+ untrusted transcript. Manual completion records audit metadata and adjusts
+ confidence (pass .95, needs_work .6, fail .4) without publishing.
+5. An automated audit checks deterministic duplicates, advisory necessity and,
+ when indicated, retrieval precision. It runs skill and no-skill arms on the
+ same task, grades the result, then may self-edit and retry. An optional
+ distinct teacher rewrites the skill; the worker performs the retry.
+6. Publication applies owner preferences, confidence thresholds, necessity,
+ utility and duplicate rules through SkillsManager. A normal sequential batch
+ finalizes its processed results. Cancellation or infrastructure unavailability
+ skips batch finalization and clears task/current state.
+
+A clean audit pass sets confidence to .95, a self-edit pass to .85 and a teacher
+rewrite pass to .8. Continued failure becomes draft at .35. Unknown and
+inconclusive verdicts preserve publication state. Automatic publishing requires
+an enabled owner policy, a passing verdict at or above the configured threshold,
+and no necessity, worse-baseline or duplicate blocker. The default threshold is
+.85; owner values are clamped to [0, 1]. Markdown edits pin the existing skill name
+so usage and audit sidecars remain attached to the same identity.
+
+Per-skill duplicate blocking and batch duplicate finalization have distinct
+selection rules and must not be consolidated without a behavior proposal.
+Batch finalization excludes builtins and binned records, changes only processed
+skills, protects approval-required results, and bins duplicate losers. Duplicate
+similarity uses the existing .38 threshold and name-suffix grouping.
+
+Batches run sequentially per owner, retain current/done/results and timestamps,
+and cap progress logs at 1,000 entries. Ordinary exceptions record inconclusive
+skill audits. Infrastructure failures stop the batch without inventing a skill
+verdict. Scheduled execution skips an active owner job, selects existing lifecycle
+candidates by oldest audit, caps the batch (default eight), and marks model phases
+as background work. These services retain the existing scheduling and
+cancellation semantics.
+
+## Security and approval invariants
+
+HTTP authentication and owner verification remain at the transport boundary.
+Manager reads and writes receive the owner. Ownerless builtins retain their
+existing visibility; an authenticated user cannot access an ownerless ordinary
+skill. Existing ownerless deployment behavior is preserved.
+
+The `/test-approval` handler validates the pending job, approval ID, decision,
+owner and empty session binding, then destructively consumes the sealed approval
+with `allow_continuation=False` before calling the coordinator. Stale, mismatched
+or reused approvals fail with 409. The consumed grant authorizes only its exact
+action. Services do not manufacture approval authority or relax process identity,
+workspace confinement or request-authority enforcement in the agent runtime.
+
+Skill markdown and resumed transcripts remain explicitly untrusted context,
+never trusted system instructions. Audit arms suppress saved skill injection.
+Unattended runs deny encountered approval records instead of leaving reusable
+grants. An initial approval-required audit result preserves the skill's publication
+and confidence and directs the user to manual approval. Retry handling has an
+inherited gap: an approval pause after a rewrite can still lead to demotion.
+Same-task stream closure preserves the originating ContextVar cleanup, but manual
+cancellation can retain private continuation state. These are separate hardening
+items, not guarantees supplied by the extraction.
+
+## Model selection and evaluation
+
+Audit resolution uses an explicit endpoint/model pair when supplied, looking up
+credentials among enabled owner-visible endpoints. A model-only choice uses the
+existing owner-scoped model resolver. Otherwise it resolves the utility model,
+including the resolver's default behavior, then takes the first configured
+utility fallback if the primary result is incomplete. A missing worker raises
+`ValueError`. Served-model normalization keeps an exact match, then a basename
+match, then the first served ID; discovery exceptions keep the resolved choice.
+
+An enabled teacher resolves separately with the same owner. Its credentials are
+not borrowed from the worker. Teacher resolution failure logs the existing warning
+and leaves the teacher absent. Manual tests retain their HTTP endpoint validation
+and registered fallback credentials.
+
+Owner reasoning effort is resolved for each evaluation or rewrite call. Workload
+flags, credentials, retries, prompts and permissive parsing remain unchanged:
+
+| Phase | Token budget | Timeout in seconds |
+| --- | --- | --- |
+| Run review, up to two attempts | 32768 | 180 |
+| Necessity | 8192 | 120 |
+| Retrieval precision | 4096 | 90 |
+| Markdown improvement | 16384 | 180 |
+
+Review parsing retains think-block stripping, trailing-comma recovery, last
+usable verdict selection, prose fallback, bounded fields and unknown outcomes.
+These model outputs are advisory and do not grant execution authority.
+
+## Public HTTP contract
+
+All paths below have prefix `/api/skills`. Successful status defaults to 200.
+Request models and endpoint declaration order remain fixed. A frozen
+OpenAPI and declaration-order fixture records
+the baseline contract independently of the extracted implementation.
+
+| Method and suffix | Successful response | Authorization and errors |
+| --- | --- | --- |
+| GET empty | `skills,count` | Owner-filtered load |
+| GET `/index` | `index,count` | Owner-scoped eligible index |
+| GET `/slash-catalog` | `skills,count` | Owner-scoped index; sorted slash entries |
+| GET `/builtin` | `builtin,count` and optional `error` | Existing shared capability text |
+| GET `/builtin/{name}` | `name,text,default,is_overridden` | 404 missing tool; 500 import failure |
+| PUT `/builtin/{name}` | `ok,name,is_overridden` | Admin; 404 unknown, 400 missing text |
+| DELETE `/builtin/{name}` | `ok,name,is_overridden` | Admin |
+| POST `/import-from-url` | `ok,skill,files` | Admin and current owner; 400 import, 502 HTTP, 500 other failure |
+| POST `/add` | `ok,deduped,skill` | Current owner passed to manager; unchanged old/new request fields |
+| POST `/{skill_id}/invoke` | `ok,type,name,command,message` | Eligible owner index only; 404 unavailable/source missing |
+| GET `/{skill_id}` | Full skill dictionary | Owner load; 404 missing |
+| GET `/{skill_id}/markdown` | `name,markdown` | Owner verification; 404 missing/source missing |
+| POST `/{skill_id}/test` | `ok,status,skill,model` | Owner verification, HTTP request authority, registered fallback credentials; 400 missing/invalid model |
+| POST `/{skill_id}/test-approval` | `ok,status,decision` | User approval request, owner verification, pending ID/owner/empty session match; 400 invalid body/decision, 409 stale/mismatch/consumed |
+| GET `/{skill_id}/test-status` | `status` or `status,task,model,log,verdict,approval` | Owner-keyed lookup; server continuation/credentials omitted |
+| POST `/audit-all` | `ok,status,total` plus running `done,model` or empty `results,log` | Owner-keyed singleton; 400 model resolution |
+| GET `/audit-all/status` | `status` or job progress/result/log/timestamps | Owner-keyed lookup; task and credentials omitted |
+| POST `/audit-all/cancel` | `ok,status` | Owner-keyed lookup and cancellation |
+| POST `/{skill_id}/markdown` | `ok,name` | Owner verification; 400 missing/parse, 404 missing, 500 update |
+| PUT `/{skill_id}` | `ok` | Owner verification and scoped manager update; 404 missing |
+| DELETE `/{skill_id}` | `ok` | Owner verification and scoped manager deletion; 404 missing |
+| POST `/search` | `skills,query,count` | Owner-filtered input; 400 empty query |
+
+Strict owner verification allows an ownerless builtin but denies an ownerless
+ordinary skill for an authenticated user. The existing ownerless deployment
+behavior remains. Global auth middleware is unchanged.
+
+## Python compatibility and frozen contracts
+
+`app.py` imports `setup_skills_routes`. `src/builtin_actions.py` uses the existing
+route helpers and audit registry. Route aliases and wrappers preserve the original
+28 inspectable interfaces, `SkillAuditUnavailable`, registry identity and patchable
+collaborators. Lazy model/agent imports and route-level effort injection keep
+existing offline test seams effective.
+
+The task and message callbacks are bound through `AuditDependencies` at service
+entry. Patches to route-level test tasks and test/baseline messages reach manual
+execution, approval continuation, both audit arms, worker retries and scheduled
+audits. The `_skill_baseline_task` compatibility alias delegates to the current
+route test-task builder. Execution continues to reuse one task for both arms,
+as in the original implementation; it does not independently derive a baseline
+task through that alias.
+
+`tests/fixtures/skills_api_baseline.json` records declaration order and structural
+signatures captured from pre-extraction revision
+`86b886c611338282af6d4a717246ea4e256f58df`. Signature records retain parameter
+names, order, kinds, defaults, default factories and annotations, including
+Pydantic constraint metadata. They compare typing origins and arguments instead
+of Python-version-dependent annotation representations. The expanded records also
+pin field validation aliases, alias priority, discriminators, `validate_default`,
+rebuilt field annotations and model configuration. Field order remains visible
+through the constructor parameter sequence. Only the known builtin factories
+`list`, `tuple`, `dict`, `set` and `frozenset` are supported. Custom factories,
+including closures and factories taking validated data, fail closed without being
+executed. Unsupported metadata/configuration values also raise rather than using
+unstable representations. This is a structural contract for supported interfaces,
+not proof of behavioral equivalence for arbitrary validators or Python code.
+
+The expanded fixture was derived again from the original revision above in a
+detached scratch worktree, with the updated comparator copied in. Python 3.11
+and 3.12 produced byte-identical snapshots. The previous parameter/return records,
+all 28 interface names, all 22 endpoint declarations and the original OpenAPI
+digest were checked unchanged before accepting the new field records.
+
+`tests/fixtures/skills_openapi_baseline.json` is the same baseline's complete
+Skills-router OpenAPI document, generated with a standalone FastAPI application.
+Sorted keys, ASCII escaping, two-space indentation and a final newline make the
+fixture deterministic. Tests require exact canonical equality and print a unified
+diff on mismatch. The redundant digest field and assertions have been removed;
+they provided no independent compatibility guarantee. The fixture pins model
+schemas and constraints. CI reads committed fixtures and needs no Git history
+for these tests. Baseline updates require an intentional compatibility decision, rather
+than regenerating fixtures from a failing implementation.
+
+The narrow `.gitleaks.toml` exception remains necessary for the historical public
+digest in earlier fixture and documentation revisions. It applies to the exact digest,
+the `generic-api-key` rule and the two named paths. Removing a current copy cannot
+remove findings from published history. Keep the exception unless the pinned
+full-history scan proves it unnecessary; do not rewrite history to remove it.
+The checksum-verified 8.30.1 scan without this exception still reports both
+historical copies in commit `a547c4d8`; retaining the exception passes the full
+PR/dev history scan.
+Reconsider it after squash merge only after verifying the resulting reachable
+history with the pinned full-history scan.
+
+The ReDoS source guard scans `services/skills/evaluation.py`, the canonical
+evaluation parser module, as well as the retained route and memory-extractor
+locations. Verdict regex runtime tests import the canonical module directly.
+The source guard must reject reintroducing the lazy think-block expression;
+the ordinary-input and adversarial-flood runtime tests remain in place. An isolated
+source mutation reproduced the old guard's false green for the evaluation module.
+The corrected guard rejected the vulnerable expression in each of the three
+locations and passed again after restoring the temporary copies. The mutated
+regex was never executed, and production parser behavior was not changed.
+
+## Reproducible validation
+
+From the repository root, use a virtual environment with `requirements-dev.txt`
+installed and the repository's frontend dependencies available. The examples use
+`.venv/bin/python`; repeat the contract tests with a Python 3.12 environment as
+well as Python 3.11. Record interpreter/dependency versions with results.
+
+```sh
+.venv/bin/python -m pytest -q \
+ tests/test_skills_audit_characterization.py tests/test_skills_audit_services.py
+.venv/bin/python -m compileall -q app.py core routes src services scripts tests
+.venv/bin/python -c 'import routes.skills_routes; import services.skills.agent_runner; import services.skills.audit_workflow'
+.venv/bin/python scripts/build_frontend.py --check
+node scripts/check_frontend.mjs
+node --test tests/skillsApproval.test.mjs tests/frontendArchitecture.test.mjs
+git diff --check
+```
+
+The focused Skills, authority and approval selection is reproducible with:
+
+```sh
+.venv/bin/python - <<'PYTHON'
+from pathlib import Path
+import subprocess
+import sys
+
+files = set()
+for path in Path("tests").rglob("test_*.py"):
+ text = path.read_text()
+ if ("skill" in path.name or "approval" in path.name
+ or "utility_reasoning" in path.name or "skills_routes" in text
+ or "review_endpoint_credentials" in path.name):
+ files.add(str(path))
+files.update([
+ "tests/test_request_authority.py",
+ "tests/test_endpoint_registered_authority.py",
+ "tests/test_redos_verdict_continuation.py",
+ "tests/test_redos_residual_python.py",
+])
+subprocess.run([sys.executable, "-m", "pytest", "-q", "-rs",
+ "--durations=15", *sorted(files)], check=True)
+PYTHON
+```
+
+The original selection contained 729 cases. Additional characterization cases
+increase that count without removing the original coverage. For the full suite,
+remove a development `APP_PORT` and put the environment's tools on PATH:
+
+```sh
+env -u APP_PORT PATH="$PWD/.venv/bin:$PATH" \
+ PLAYWRIGHT_BROWSERS_PATH="$PWD/.cache/ms-playwright" \
+ .venv/bin/python -m pytest -q -rs --durations=25
+```
+
+Run the checksum-verified Gitleaks binary pinned in
+`.github/workflows/secret-scan.yml` on full reachable history, including the PR
+head and fetched official `dev`. The current workflow pins 8.30.1. Its CI command
+is `gitleaks git --no-banner --redact --verbose .` with a full-history checkout.
+A local checkout can restrict refs to the relevant histories with
+`--log-opts='HEAD upstream/dev'`; do not restrict the commit range to just the
+latest patch. Scan uncommitted fixtures too before committing.
+
+## Historical evidence and validation limits
+
+The initial extraction validation at `a547c4d8` reported 42 characterization and
+service cases, 729 focused cases, 13 relevant Node cases and 17 isolated uvicorn
+HTTP checks passing. The historical repository-wide run reported 13,959 passed,
+60 skipped and three failures. These counts describe the extraction validation,
+not the current revision. The HTTP checks used isolated state and authentication
+and included second-owner denial, but exercised neither a configured live model
+nor an external tool action.
+
+The two containment failures reproduced on unchanged baseline `86b886c6` with
+extra `Failed to create stream fd: No such file or directory` stderr output:
+
+- `test_namespace_handshake_closes_model_stdin`
+- `test_execution_environment_cannot_replace_probed_bwrap[False]`
+
+`test_legacy_cleanup_against_a_private_real_tmux_server` failed under the original
+full-suite load and passed isolated reruns. Its cause was not fully diagnosed.
+These historical failures must be distinguished from new regressions; successful
+CI and maintainer review remain integration gates. Earlier AST comparisons and
+the [maintainer review](https://github.com/odysseus-dev/odysseus/pull/6711#issuecomment-6170115749)
+provide historical extraction evidence, not an independent review of later fixes.
+
+## Known limitations and follow-up boundaries
+
+[Issue #6635](https://github.com/odysseus-dev/odysseus/issues/6635) remains open:
+manual tests without an appropriate workspace can still fail to execute their
+proposed action. Stream cleanup and exact approvals are preserved, but do not
+supply a missing workspace.
+
+Jobs remain process-local and do not survive restarts. Durable jobs, moving the
+preferences adapter below transport, consolidating storage under the domain
+package, or changing duplicate/publication policies need separate designs.
+The canonical manager, skill format/lifecycle modules, provider implementations,
+agent authority enforcement and frontend contracts remain their existing owners.
+
+The [second-review correction report](skills-audit-second-review.md) records the
+restored prompt seams, independently expanded constructor baseline, actual
+validation results and a separate prioritized plan for the six inherited P2
+failure paths. Model-controlled lifecycle fields and preference-load failures
+require maintainer action before automatic rewrite/publication deployment.
diff --git a/docs/skills-audit-second-review.md b/docs/skills-audit-second-review.md
new file mode 100644
index 000000000..91fdaae43
--- /dev/null
+++ b/docs/skills-audit-second-review.md
@@ -0,0 +1,200 @@
+# Skills PR #6711 second-review corrections
+
+The correction scope is route prompt compatibility and structural constructor
+contracts. PR #6711 remains draft. Durable skill ownership stays with
+`SkillsManager`. No publication policy, authority mechanism, provider runtime,
+frontend behavior or protected manager/index implementation was changed.
+
+The reviewed head was `a6a33674ed4facf11f53e7cdd41f882ad0fa8482`. The independent
+original baseline is `86b886c611338282af6d4a717246ea4e256f58df`. Official `dev`
+integration was tested against `c3819e3cbf56c4f899eacc66b21115a77d9c570d`.
+
+## Compatibility corrections
+
+Service-local imports captured prompt builders outside the route namespace.
+Patching the public route symbols therefore stopped affecting execution after
+extraction. `AuditDependencies` now binds the current test-task, test-message and
+baseline-message builders. Manual execution, exact-approval continuation, initial
+audits, baseline arms, self/teacher retries and scheduled batches use those
+bindings. The route `_skill_baseline_task` wrapper again delegates to the current
+route `_skill_test_task`. Both execution arms still use one shared task, matching
+the original behavior. No service imports Skills routes.
+
+The signature checker treated a factory's module/qualified name as its identity
+and omitted Pydantic settings outside the generated Python signature. Closures
+with different captured values and default-validation changes were false
+negatives. New tests additionally demonstrated hidden validation-alias path and
+model-configuration changes. The checker now records public field validation
+settings, rebuilt annotations, defaults and inherited model configuration. See
+the [Pydantic FieldInfo reference](https://docs.pydantic.dev/latest/api/fields/)
+for the distinction between factories, validation aliases and `validate_default`.
+
+Only known builtin factories are supported by identity. Custom factories,
+including factories requiring validated field data, raise `TypeError` without
+being invoked during comparison. Unsupported metadata/configuration values also
+fail closed. No bytecode, arbitrary object representations or factory output is
+serialized. The comparator does not promise equivalence of arbitrary Python
+validators or factory implementations.
+
+The expanded fixture was generated from the original baseline in a new detached
+worktree, with only the revised test comparator copied in. Python 3.11 and 3.12
+produced byte-identical files. Every previous parameter/return record remains
+equal. All 28 interfaces and 22 endpoint declarations remain present. The
+canonical OpenAPI fixture is unchanged, and its original digest is unchanged.
+Independent native `inspect.signature` snapshots also match original versus
+corrected implementations on each interpreter.
+
+## Regression evidence and validation
+
+The new tests were run before production/comparator edits: 12 failed and four
+passed, demonstrating the six signature cases and six broken prompt cases. After
+correction, all 16 added cases pass. The prompt probes capture actual
+`stream_agent_loop` ingress rather than replacing the runners or coordination.
+They cover patched and normal execution, guard escaping and taint metadata,
+owner authority, exact-approval continuation, and worker retries after both
+self and teacher rewrites. The same ten prompt cases pass on the original
+implementation. The six signature cases reject custom factories without calling
+them and detect default validation, alias paths and model validation settings.
+
+Environments: Python 3.11.17 and 3.12.13, FastAPI 0.143.1, Pydantic 2.14.1,
+pytest 9.1.1. Python test commands set `FASTEMBED_MODEL=review-disabled` and
+`HF_HUB_OFFLINE=1` to exercise unavailable optional embeddings without model
+downloads. They do not validate live providers or embedding quality.
+
+| Executed scope | Result |
+| --- | --- |
+| 53-file Skills, approval, authority and lifecycle selection, Python 3.11 | 757 passed |
+| Same selection, Python 3.12 | 757 passed |
+| Both characterization/service files, included above | 70 passed |
+| Original baseline, available focused selection plus revised characterization | 724 passed |
+| Original baseline, revised characterization plus prompt probes, each interpreter | 47 passed |
+| Current-dev combined tree, focused selection plus eight intervening dev test files, each interpreter | 900 passed |
+| Repository-wide suite, Python 3.11 | 13,991 passed, 60 skipped, two inherited environment failures, six subtests passed |
+| Frontend publisher and architecture checks | Passed, zero changed modules |
+| Relevant Node tests | 13 passed |
+| Compilation, both Python versions | Passed |
+| Import graph and fresh service-first/route-first imports, both versions | Passed; acyclic; no reverse Skills route import |
+| Original normalized moved-body comparison | 26 of 26 matched after explicit dependency substitutions |
+| Pinned/checksum-verified Gitleaks 8.30.1, reachable HEAD and official dev histories | No leaks |
+| Same Gitleaks, tracked working files | No leaks |
+| Diff/whitespace and protected-source comparisons | Passed |
+
+The two repository-wide failures are
+`tests/test_containment_enforcement.py::test_namespace_handshake_closes_model_stdin`
+and `test_execution_environment_cannot_replace_probed_bwrap[False]`. Isolated
+reruns on both original and corrected implementations reproduce the same extra
+`Failed to create stream fd: No such file or directory` stderr. The independent
+review traced it to login-profile `im-config` calls to `systemd-cat` inside
+Bubblewrap without the journal stream socket. These environment failures remain;
+they were not hidden by excluding tests. A full Python 3.12 suite was not run.
+
+The combined test tree used the official merge revision `5419ed37`, whose tree
+exactly matches `git merge-tree --write-tree upstream/dev a6a33674`, with the
+correction diff applied in a detached scratch worktree. Published history was
+not rebased, amended, reset or rewritten.
+
+Local commands, independent fixture captures, baseline reproductions and full
+logs are retained under `/tmp/skills-6711-corrections/`. The independent review
+and adversarial probe source remain under `/tmp/skills-6711-second/`. These
+temporary evidence paths are not portable repository fixtures. CI should read
+the committed golden fixtures, not regenerate them from the implementation.
+
+## Separate inherited P2 hardening plan
+
+All six defects demonstrably exist on the official original baseline. The six
+safety assertions in `/tmp/skills-6711-second/test_adversarial.py` fail on both
+the original and corrected trees with the same outcomes. Logs are
+`inherited-original.log` and `inherited-head.log` in the correction evidence
+directory. The original/source body comparison also matches these paths after
+dependency substitutions. There is no demonstrated material worsening from the
+extraction. That finding does not make their security impact acceptable.
+
+Priorities below concern a separate hardening change. Items 1 and 2 are release
+blockers requiring maintainer resolution before deploying automatic skill
+rewrite/publication workflows. This recommendation is independent of whether
+the architecture PR is integrated. No tool-authority bypass or cross-owner
+credential disclosure was demonstrated, and no critical extraction regression
+was found that requires expanding this compatibility correction.
+
+1. **Model-controlled lifecycle/provenance fields.** Current source:
+ [publication.py:328](../services/skills/publication.py#L328), especially line
+ 342; the bypassed retrieval condition is
+ [skills.py:703](../services/memory/skills.py#L703). Original source:
+ [routes/skills_routes.py:1039](https://github.com/odysseus-dev/odysseus/blob/86b886c611338282af6d4a717246ea4e256f58df/routes/skills_routes.py#L1039).
+ `test_rewrite_cannot_promote_model_text_to_builtin` uses the real manager and
+ saves model markdown with `source: builtin`, `status: published` and
+ `confidence: 1`. Identity/owner remain pinned, but the lifecycle fields persist
+ and the skill becomes retrieval-eligible without a passing audit. Corrective
+ change: allowlist procedure and approved descriptive/retrieval fields during
+ model rewrites; preserve existing owner, provenance, publication, confidence,
+ audit and teacher lifecycle state. Only verified policy may update those
+ fields. Metadata-only fixes must preserve the procedure or trigger a retest.
+ Add real-manager tests for self, teacher and metadata-only rewrites.
+
+2. **Preference loading fails open for automatic publication.** Current source:
+ [publication.py:13](../services/skills/publication.py#L13) and
+ [skills.py:59](../services/memory/skills.py#L59). Original source:
+ [routes/skills_routes.py:710](https://github.com/odysseus-dev/odysseus/blob/86b886c611338282af6d4a717246ea4e256f58df/routes/skills_routes.py#L710).
+ `test_preferences_read_failure_does_not_enable_auto_publication` makes the
+ loader raise `PermissionError`; automatic publication is enabled rather than
+ preserving the owner's possible opt-out. Corrective change: distinguish a
+ successfully loaded empty preference store from an exception, log the failure
+ and disable automatic publication on exceptions. Align the manager retrieval
+ preference adapter in the separate fix. Test unreadable/malformed existing
+ preference files and the ordinary empty-store default independently.
+
+3. **Manual cancellation retains private credentials and stale running state.**
+ Current source:
+ [agent_runner.py:125](../services/skills/agent_runner.py#L125) and
+ [job_coordinator.py:49](../services/skills/job_coordinator.py#L49). Original:
+ [routes/skills_routes.py:635](https://github.com/odysseus-dev/odysseus/blob/86b886c611338282af6d4a717246ea4e256f58df/routes/skills_routes.py#L635).
+ `test_manual_cancellation_cleans_sensitive_continuation` suspends and cancels
+ the stream. The stream closes in its originating task, but job status remains
+ running and `_run.headers.Authorization` remains resident. Polling still hides
+ these fields; this is retention, not demonstrated disclosure. Corrective
+ change: handle `CancelledError`, mark cancelled, clear private continuation
+ data, retire only the attached exact approval and re-raise. Preserve state on
+ a normal awaiting-approval return. Retain task handles for coordinated
+ replacement/cancellation and test owner/approval isolation.
+
+4. **Approval pauses during retries lead to demotion.** Current source:
+ [audit_workflow.py:244](../services/skills/audit_workflow.py#L244), teacher
+ retry at line 280 and demotion at line 303. Original:
+ [routes/skills_routes.py:1448](https://github.com/odysseus-dev/odysseus/blob/86b886c611338282af6d4a717246ea4e256f58df/routes/skills_routes.py#L1448)
+ and lines 1484/1507. `test_retry_approval_preserves_publication_and_confidence`
+ begins published at .9, fails the first grade, then pauses the rewritten test
+ for approval. The result is flagged/draft/.35. The lower-level approval is
+ correctly denied; state handling afterwards is wrong. Corrective change:
+ immediately recognize `approval_required` after every retry, stop escalation
+ and demotion, and preserve the intended pre-pause lifecycle state. Coordinate
+ with item 1 so model rewrites cannot replace that saved state. Test both
+ self/teacher retries, repeated pauses and batch protection.
+
+5. **Duplicate losers are binned after keeper publication fails.** Current:
+ [publication.py:217](../services/skills/publication.py#L217), including loser
+ writes at line 228. Original:
+ [routes/skills_routes.py:914](https://github.com/odysseus-dev/odysseus/blob/86b886c611338282af6d4a717246ea4e256f58df/routes/skills_routes.py#L914).
+ `test_duplicate_losers_retained_if_keeper_write_fails` raises disk-full during
+ keeper publication and still observes a loser binned. Corrective change:
+ require confirmed keeper persistence before binning losers when automatic
+ publication is enabled. Treat both exceptions and False returns as failure,
+ retain candidates and report recovery information. Preserve existing keeper
+ selection and duplicate scoring rules; add failure/retry tests.
+
+6. **Reported publication status can disagree with canonical storage.** Current:
+ [publication.py:320](../services/skills/publication.py#L320). Original:
+ [routes/skills_routes.py:1017](https://github.com/odysseus-dev/odysseus/blob/86b886c611338282af6d4a717246ea4e256f58df/routes/skills_routes.py#L1017).
+ `test_publication_does_not_report_unpersisted_success` returns False from the
+ manager update; the helper reports published while the stored skill remains
+ draft. Exceptions are also swallowed by the inspected code. Corrective change:
+ check persistence success, log failures and return reloaded canonical state or
+ an explicit persistence error. Test False/exception outcomes and the job/UI
+ projection. Coordinate this change with item 5 without changing publication
+ thresholds or scoring.
+
+Maestrum's read-only triage delegation produced no usable result within its
+usefulness window and was cancelled. Cleanup completed and the session records
+an interrupted result, not a successful review. The coordinator reclaimed the
+remaining report work and verified the source references and reproduction logs
+above. No worker claim was used as proof. No GitHub issue, new PR, maintainer
+comment or PR-description edit was made.
diff --git a/docs/tls-trust.md b/docs/tls-trust.md
new file mode 100644
index 000000000..71f0fe76e
--- /dev/null
+++ b/docs/tls-trust.md
@@ -0,0 +1,75 @@
+# Outbound HTTPS trust
+
+Odysseus uses both Python package CA bundles and system trust. HTTPX uses certifi by default; the guarded web/PDF fetcher and webhook delivery explicitly use Python's system SSL context. A configured `LLM_CA_BUNDLE` adds certificates to system trust for model calls. Upgrading certifi alone cannot repair every outbound HTTPS path.
+
+For the October 2026 eMudhra incident, use certifi 2026.10.23 or newer, pip 26.2.2 or newer, and uv 0.13.5 or newer wherever uv is used. Pip has its own vendored certifi and also loads system roots. Update the operating system's certificate package separately. See the [Python security announcement](https://discuss.python.org/t/109576) and [incident details](https://emudhra.we-have-a-problem.com/).
+
+Before other pip installs, bootstrap the selected environment with the integrity-pinned wheels:
+
+```sh
+python -m pip install --require-hashes --only-binary=:all: --no-deps -r requirements-bootstrap.txt
+python -m pip install -r requirements.txt
+```
+
+The pinned bootstrap protects package integrity even when the old installer's certificate bundle is affected. It is not an operating-system trust-store update. Native Windows/macOS trust and command-line OpenSSL PEM stores may differ; follow the platform vendor's remediation for every store in use. Restart Odysseus and its subprocesses after updating trust.
+
+On Linux/OpenSSL deployments, inspect both the effective CA file and hashed CA directory, plus the two Python bundles:
+
+```sh
+python scripts/check_ca_trust.py --system --python --overrides --verbose
+```
+
+Explicit PEM bundles can also be passed as positional arguments. The check rejects the four published root fingerprints, all sixteen published intermediate certificates (including their cross-signs), the cross-signed G3 issuer in the published test chains, and malformed/empty bundles. Checking intermediates matters because adding one as a custom trust anchor can restore an affected chain even after its roots have been removed.
+
+`--overrides` checks every nonempty `LLM_CA_BUNDLE`, `SSL_CERT_FILE`, `REQUESTS_CA_BUNDLE`, `CURL_CA_BUNDLE`, `PIP_CERT`, `NODE_EXTRA_CA_CERTS` and `GRPC_DEFAULT_SSL_ROOTS_FILE_PATH` setting in the checker's process environment, including configured fallback settings. Requests/pip hashed-directory overrides are inspected too; `--system` covers `SSL_CERT_DIR`. Run with the application's environment and filesystem access. The script does not load `.env` or application configuration files; pass any CA paths configured only there explicitly, for example `python scripts/check_ca_trust.py --system --python /path/to/private-ca.pem`. Missing or invalid configured files fail the check. Selecting only `--overrides` with no configured paths also fails instead of reporting that stores were validated.
+
+`--verbose` reports the Python executable/prefix, user home, effective UID/GID where available, and resolved CA paths, including bundles selected from user-installed packages. Compare these with the running application's identity and interpreter. It does not dump environment variables or credentials.
+
+This is an offline inventory check of known certificate fingerprints. It does not modify stores, reject requests at runtime, model native OS revocation, or detect arbitrary reissued certificates sharing the compromised keys. Chromium's policy separately matches public keys. Check mounted or replaced CA files again after deployment, remove affected trust through the owning platform/client configuration, and restart clients that cache SSL contexts. A passing build cannot validate custom files introduced later.
+
+Both Docker build stages use Python 3.14.9, refresh system CA certificates and bootstrap pip/certifi before dependency installation. The build fails if known affected CA certificates remain. Node uses the corrected system store through `--use-openssl-ca`. Python gRPC uses that same PEM file through `GRPC_DEFAULT_SSL_ROOTS_FILE_PATH`; updating certifi alone does not replace gRPC's independent wheel bundle. After dependency installation, the image checks gRPC's selected file as well. An explicit gRPC override must be readable and free of known affected CA certificates. [grpcio 1.84.1](https://github.com/grpc/grpc/releases/tag/v1.84.1) includes the upstream root-bundle correction and is the application minimum. Retain the checked override as a consistent image trust selection; older persisted Python environments and explicit client roots still need independent checks.
+
+The image also bundles Docker CLI [29.9.2](https://github.com/moby/moby/releases/tag/docker-v29.9.2), built with Go 1.26.10's distrust of the compromised intermediate keys. Cookbook uses this client for optional Docker operations. Default Compose does not mount the host Docker socket; local daemon access requires the explicit [host-Docker overlay](../docker/host-docker.yml), whose usual Unix-socket connection does not use TLS. The client update is maintenance of a shipped tool, not evidence that these local calls were exposed. It does not update the host daemon or other containers' clients and trust stores; assess those separately.
+
+Chromium uses a separate trust store. The Docker image installs a managed `CADistrustedCertificates` policy for the eight compromised intermediate public keys, covering their cross-signs without depending on background revocation updates. It adds no trusted certificate and does not disable certificate verification. The policy and public-certificate provenance are documented in [the browser policy note](../docker/chromium-ca-policy.md). Native browser installations and independently managed profiles require their own platform policy or vendor update; this image policy does not configure host browsers.
+
+To replace only Odysseus in an already running Compose stack, build from the corrected checkout with a distinct local image tag. Use the same Compose files and project name as the existing deployment for every command below:
+
+```sh
+export ODYSSEUS_IMAGE="odysseus-local:ca-$(git rev-parse --short=12 HEAD)"
+docker compose build --pull --no-cache odysseus
+docker compose up -d --no-deps --pull never --no-build odysseus
+docker image inspect --format '{{.Id}}' "$ODYSSEUS_IMAGE"
+docker inspect --format '{{.Image}}' "$(docker compose ps -q odysseus)"
+```
+
+The two image IDs must match. Keep the selected `ODYSSEUS_IMAGE` in the deployment configuration for subsequent recreations. Compose can prefer the registry image when both `image` and `build` are present; the explicit pull/build flags keep this replacement on the local build. `--no-deps` leaves the existing sidecars running and is intended for an existing stack. For registry deployments, select a verified corrected immutable tag or digest. A merge to `dev` publishes `:dev`; it does not update `:latest`, which is published from `main`.
+
+Check the standard image as its configured app account, using the image's Python interpreter and the same user-bin PATH prefix as the entrypoint:
+
+```sh
+docker compose exec -T --user 0 odysseus sh -ec '
+ gosu_bin=$(command -v gosu)
+ app_user=$(getent passwd "${PUID:-1000}" | cut -d: -f1)
+ test -n "$app_user"
+ exec "$gosu_bin" "$app_user" env PATH="/app/.local/bin:$PATH" \
+ /usr/local/bin/python /app/scripts/check_ca_trust.py \
+ --system --python --grpc --overrides --verbose
+'
+```
+
+`gosu` selects the account's HOME and drops privileges before Python runs, so the check includes its persisted user packages. The entrypoint itself is not rerun. Plain `docker compose exec ... python` uses the image's default root user and can miss `/app/.local` packages. A custom service user, entrypoint, virtual environment or launch command requires matching that deployment's actual user, HOME and Python interpreter instead of copying the standard command unchanged. Docker exec inherits container-creation environment, not variables exported later by the app or entrypoint: reproduce any additional Python/TLS settings with exec's `--env` options, and pass CA paths configured only in application files explicitly. Confirm the verbose identity and selected paths before accepting the result.
+
+For containers started non-root or without the SETUID/SETGID capabilities needed by `gosu`, use `docker compose exec --user UID:GID --env HOME=/actual/app/home` with the deployment's actual numeric IDs, home, PATH and interpreter instead. Do not add capabilities merely to run this check.
+
+SearXNG is a separate HTTPS client and image; updating the Odysseus image does not patch it. Inspect its effective CA path and update or rebuild that image independently. Also inspect persisted `/app/.local` packages, remote Cookbook environments, and externally configured MCP runtimes. Image replacement does not necessarily replace those environments.
+
+For behavioral validation, all fourteen [published test chains](https://emudhra.we-have-a-problem.com/chains.zip), including the AAA cross-signs and two chains without Certificate Transparency entries, must fail certificate verification through the effective stores. Confirm that an ordinary known-good HTTPS request still succeeds. In Chromium, confirm the managed policy is loaded at `chrome://policy` and test the incident endpoints through the actual browser path with certificate verification enabled. The PEM checker cannot inspect Chromium's policy or its active verifier. Package versions and a successful image build alone do not prove that a running deployment selects the corrected store.
+
+## Follow-up releases
+
+The maintained bootstrap selects certifi 2026.10.23 with its verified wheel hash; pip remains 26.2.2. The certifi update removes the C1/C3 roots in addition to the earlier incident changes. CI uses uv 0.13.5, which adds verifier-level rejection of the compromised intermediate keys and updated managed CPython builds. Existing virtual environments do not update automatically. See the [certifi change](https://github.com/certifi/python-certifi/commit/b60466c9f2882d9cf088943c650b0faac06c080c), [uv release](https://github.com/astral-sh/uv/releases/tag/0.13.5), and [Python security releases](https://blog.python.org/2026/10/python-3151-3149-31317/). The pinned bootstrap still replaces the selected versions exactly; preserving newer installed versions and private-mirror support remain separate maintenance.
+
+SearXNG remains an independent trust owner. Use the [upstream-image validation and rollout instructions](searxng-trust-image.md); updating these application packages does not repair an existing sidecar. Host daemons, native browser policy, optional compiled clients and independently managed integrations require their own effective-client checks.
+
+CPython's [intermediate-key verifier block](https://github.com/python/cpython/pull/160042) and its [3.14 backport](https://github.com/python/cpython/pull/160569) merged on October 24. They are distinct from Python 3.14.9's bundled-pip update. No released 3.14 interpreter containing that verifier change was identified when this image pin was selected; retain the corrected effective trust stores and track the subsequent security release. hf-xet's [trust fix](https://github.com/huggingface/xet-core/pull/1038) is also merged but not included in the latest published 1.7.0 release at that check. Agent-browser 0.39.2 and primp 2.0.1 are not established incident fixes for their independent native trust paths. A version bump alone does not establish that the active client uses corrected trust.
diff --git a/frontend/modules.json b/frontend/modules.json
new file mode 100644
index 000000000..0f882adbd
--- /dev/null
+++ b/frontend/modules.json
@@ -0,0 +1,215 @@
+{
+ "version": 1,
+ "modules": [
+ {
+ "source": "shared/actionMenuOrder.js",
+ "deployment": "js/actionMenuOrder.js"
+ },
+ {
+ "source": "features/notes/domain/recurrence.js",
+ "deployment": "js/features/notes/domain/recurrence.js"
+ },
+ {
+ "source": "features/notes/infrastructure/http.js",
+ "deployment": "js/features/notes/infrastructure/http.js"
+ },
+ {
+ "source": "features/notes/infrastructure/storage.js",
+ "deployment": "js/features/notes/infrastructure/storage.js"
+ },
+ {
+ "source": "features/notes/application/state.js",
+ "deployment": "js/features/notes/application/state.js"
+ },
+ {
+ "source": "features/notes/application/workflows.js",
+ "deployment": "js/features/notes/application/workflows.js"
+ },
+ {
+ "source": "features/notes/application/reminders.js",
+ "deployment": "js/features/notes/application/reminders.js"
+ },
+ {
+ "source": "features/notes/infrastructure/notifications.js",
+ "deployment": "js/features/notes/infrastructure/notifications.js"
+ },
+ {
+ "source": "features/notes/ui/text.js",
+ "deployment": "js/features/notes/ui/text.js"
+ },
+ {
+ "source": "features/notes/ui/colors.js",
+ "deployment": "js/features/notes/ui/colors.js"
+ },
+ {
+ "source": "features/notes/ui/panel.js",
+ "deployment": "js/features/notes/ui/panel.js"
+ },
+ {
+ "source": "features/notes/ui/reminderDisplay.js",
+ "deployment": "js/features/notes/ui/reminderDisplay.js"
+ },
+ {
+ "source": "features/notes/ui/selection.js",
+ "deployment": "js/features/notes/ui/selection.js"
+ },
+ {
+ "source": "features/notes/ui/filters.js",
+ "deployment": "js/features/notes/ui/filters.js"
+ },
+ {
+ "source": "features/notes/ui/cardRendering.js",
+ "deployment": "js/features/notes/ui/cardRendering.js"
+ },
+ {
+ "source": "features/notes/ui/layout.js",
+ "deployment": "js/features/notes/ui/layout.js"
+ },
+ {
+ "source": "features/notes/ui/quickAdd.js",
+ "deployment": "js/features/notes/ui/quickAdd.js"
+ },
+ {
+ "source": "features/notes/ui/cardInteractions.js",
+ "deployment": "js/features/notes/ui/cardInteractions.js"
+ },
+ {
+ "source": "features/notes/ui/cardChecklist.js",
+ "deployment": "js/features/notes/ui/cardChecklist.js"
+ },
+ {
+ "source": "features/notes/ui/cardReorder.js",
+ "deployment": "js/features/notes/ui/cardReorder.js"
+ },
+ {
+ "source": "features/notes/ui/draftEditor.js",
+ "deployment": "js/features/notes/ui/draftEditor.js"
+ },
+ {
+ "source": "features/notes/ui/editor.js",
+ "deployment": "js/features/notes/ui/editor.js"
+ },
+ {
+ "source": "features/notes/ui/reminderPicker.js",
+ "deployment": "js/features/notes/ui/reminderPicker.js"
+ },
+ {
+ "source": "features/notes/ui/checklist.js",
+ "deployment": "js/features/notes/ui/checklist.js"
+ },
+ {
+ "source": "features/notes/ui/drawing.js",
+ "deployment": "js/features/notes/ui/drawing.js"
+ },
+ {
+ "source": "features/notes/ui/clipboard.js",
+ "deployment": "js/features/notes/ui/clipboard.js"
+ },
+ {
+ "source": "features/notes/ui/mobileEditor.js",
+ "deployment": "js/features/notes/ui/mobileEditor.js"
+ },
+ {
+ "source": "features/notes/ui/mobileReorder.js",
+ "deployment": "js/features/notes/ui/mobileReorder.js"
+ },
+ {
+ "source": "features/notes/ui/checklistReorder.js",
+ "deployment": "js/features/notes/ui/checklistReorder.js"
+ },
+ {
+ "source": "features/notes/application/queries.js",
+ "deployment": "js/features/notes/application/queries.js"
+ },
+ {
+ "source": "features/notes/application/agentActions.js",
+ "deployment": "js/features/notes/application/agentActions.js"
+ },
+ {
+ "source": "features/notes/application/deletion.js",
+ "deployment": "js/features/notes/application/deletion.js"
+ },
+ {
+ "source": "features/notes/domain/noteRules.js",
+ "deployment": "js/features/notes/domain/noteRules.js"
+ },
+ {
+ "source": "features/notes/index.js",
+ "deployment": "js/features/notes/index.js",
+ "legacyImports": [
+ {
+ "specifier": "/static/js/ui.js?v=20260916largetoolscroll1",
+ "reason": "Existing shared UI/platform identity, injected at Notes composition. Remove when that shared responsibility migrates to maintained source."
+ },
+ {
+ "specifier": "/static/js/modalManager.js",
+ "reason": "Existing shared UI/platform identity, injected at Notes composition. Remove when that shared responsibility migrates to maintained source."
+ },
+ {
+ "specifier": "/static/js/colorPicker.js?v=20260910eyedropper1",
+ "reason": "Existing shared UI/platform identity, injected at Notes composition. Remove when that shared responsibility migrates to maintained source."
+ },
+ {
+ "specifier": "/static/js/windowDrag.js",
+ "reason": "Existing shared UI/platform identity, injected at Notes composition. Remove when that shared responsibility migrates to maintained source."
+ },
+ {
+ "specifier": "/static/js/tileManager.js?v=20260910responsivebounds1",
+ "reason": "Existing shared UI/platform identity, injected at Notes composition. Remove when that shared responsibility migrates to maintained source."
+ },
+ {
+ "specifier": "/static/js/modalSnap.js",
+ "reason": "Existing shared UI/platform identity, injected at Notes composition. Remove when that shared responsibility migrates to maintained source."
+ },
+ {
+ "specifier": "/static/js/toolWindowZOrder.js",
+ "reason": "Existing shared UI/platform identity, injected at Notes composition. Remove when that shared responsibility migrates to maintained source."
+ },
+ {
+ "specifier": "/static/js/escMenuStack.js",
+ "reason": "Existing shared UI/platform identity, injected at Notes composition. Remove when that shared responsibility migrates to maintained source."
+ },
+ {
+ "specifier": "/static/js/tourHintDismiss.js",
+ "reason": "Existing shared UI/platform identity, injected at Notes composition. Remove when that shared responsibility migrates to maintained source."
+ }
+ ]
+ },
+ {
+ "source": "features/notes/application/submission.js",
+ "deployment": "js/features/notes/application/submission.js"
+ },
+ {
+ "source": "features/notes/application/drafts.js",
+ "deployment": "js/features/notes/application/drafts.js"
+ },
+ {
+ "source": "features/notes/ui/lifecycle.js",
+ "deployment": "js/features/notes/ui/lifecycle.js"
+ },
+ {
+ "source": "features/notes/application/cardOperations.js",
+ "deployment": "js/features/notes/application/cardOperations.js"
+ },
+ {
+ "source": "features/notes/application/checklistOperations.js",
+ "deployment": "js/features/notes/application/checklistOperations.js"
+ },
+ {
+ "source": "features/notes/application/selection.js",
+ "deployment": "js/features/notes/application/selection.js"
+ },
+ {
+ "source": "features/notes/ui/toolbar.js",
+ "deployment": "js/features/notes/ui/toolbar.js"
+ },
+ {
+ "source": "features/notes/ui/windowLayout.js",
+ "deployment": "js/features/notes/ui/windowLayout.js"
+ },
+ {
+ "source": "shared/ui/confetti.js",
+ "deployment": "js/shared/ui/confetti.js"
+ }
+ ]
+}
diff --git a/frontend/src/features/notes/application/agentActions.js b/frontend/src/features/notes/application/agentActions.js
new file mode 100644
index 000000000..d96828211
--- /dev/null
+++ b/frontend/src/features/notes/application/agentActions.js
@@ -0,0 +1,67 @@
+/** Create an agent session, link it to a note and drain its background stream. */
+import { _noteToAgentPrompt } from '../domain/noteRules.js';
+export function createAgentActions({
+ _patchNote,
+ _renderNotes,
+ api,
+ app,
+ createFormData,
+ state,
+ streamComplete,
+ uiModule
+}) {
+ async function _agentSolveNote(id) {
+ const note = state.notes.find(n => n.id === id);
+ if (!note) return;
+ const prompt = _noteToAgentPrompt(note);
+ if (!prompt) { uiModule.showToast('Nothing to solve — note is empty'); return; }
+ try {
+ const dc = await (await api.defaultChat()).json();
+ if (!dc.endpoint_url || !dc.model) { uiModule.showError('No default chat model configured'); return; }
+
+ // 1. Create the session server-side (no UI switch). skip_validation
+ // avoids re-probing : the default-chat endpoint is already known good.
+ const label = (note.title || (Array.isArray(note.items) && note.items[0]?.text) || 'todo').slice(0, 40);
+ const csFd = createFormData();
+ csFd.append('name', 'Agent: ' + label);
+ csFd.append('endpoint_url', dc.endpoint_url);
+ csFd.append('model', dc.model);
+ if (dc.endpoint_id) csFd.append('endpoint_id', dc.endpoint_id);
+ csFd.append('skip_validation', 'true');
+ const csRes = await api.createSession(csFd);
+ if (!csRes.ok) { uiModule.showError('Could not create agent session'); return; }
+ const sess = await csRes.json();
+ const sid = sess.id;
+
+ // 2. Link the session to the note right away so the tag appears.
+ const n = state.notes.find(x => x.id === id);
+ if (n) app.mergeNote(n, { agent_session_id: sid });
+ _renderNotes();
+ _patchNote(id, { agent_session_id: sid }).catch(() => {});
+
+ // 3. Kick off the agent run in the background. POST to chat_stream in
+ // agent mode and drain the SSE so the server runs the loop to
+ // completion + saves : without rendering anything in the chat UI.
+ const fd = createFormData();
+ fd.append('message', prompt);
+ fd.append('session', sid);
+ fd.append('mode', 'agent');
+ fd.append('disabled_tools', JSON.stringify(['manage_notes']));
+ api.startChat(fd)
+ .then(async (res) => {
+ if (!res.ok || !res.body) return;
+ const reader = res.body.getReader();
+ // Drain to completion (server finishes + persists the run).
+ while (true) { const { done } = await reader.read(); if (done) break; }
+ streamComplete(sid);
+ })
+ .catch(() => {});
+
+ uiModule.showToast('Agent working in background — tap the Agent tag when ready');
+ } catch (e) {
+ uiModule.showError('Agent failed: ' + (e.message || e));
+ }
+ }
+
+ return { _agentSolveNote };
+}
diff --git a/frontend/src/features/notes/application/cardOperations.js b/frontend/src/features/notes/application/cardOperations.js
new file mode 100644
index 000000000..1131d2ec0
--- /dev/null
+++ b/frontend/src/features/notes/application/cardOperations.js
@@ -0,0 +1,79 @@
+/** Optimistic card mutations and rollback. Animation completion is a UI-supplied boundary. */
+export function createCardOperations({
+ app,
+ api,
+ effects,
+ pushUndo,
+ undoArchive
+}) {
+ const state = app.state;
+ function togglePin(id) {
+ const note = state.notes.find(n => n.id === id);
+ if (!note) return;
+ const prevPinned = note.pinned, prevSortOrder = note.sort_order;
+ app.mergeNote(note, { pinned: !prevPinned });
+ const patch = { pinned: note.pinned };
+ if (note.pinned) {
+ const minPinned = state.notes.filter(n => n.pinned && n.id !== id).reduce((m, n) => Math.min(m, n.sort_order || 0), 0);
+ app.mergeNote(note, { sort_order: minPinned - 1 });
+ patch.sort_order = note.sort_order;
+ }
+ effects.render();
+ api.patchNote(id, patch).catch(() => {
+ app.mergeNote(note, { pinned: prevPinned, sort_order: prevSortOrder });
+ effects.render(); effects.showError('Failed to pin');
+ });
+ }
+ async function updateColor(id, color) {
+ try {
+ await api.patchNote(id, { color: color || null });
+ const note = state.notes.find(n => n.id === id);
+ if (note) app.mergeNote(note, { color });
+ } catch { effects.showError('Failed to update color'); }
+ }
+ function stageArchive(id) {
+ const index = state.notes.findIndex(n => n.id === id);
+ if (index < 0) return null;
+ const removed = app.removeNoteAt(index);
+ const undo = () => undoArchive(removed, index);
+ pushUndo({ label: 'archive', run: undo });
+ return () => {
+ effects.render();
+ api.patchNote(id, { archived: true }).then(() => effects.archived(undo)).catch(() => {
+ app.insertNoteAt(index, removed); effects.render(); effects.showError('Failed to archive');
+ });
+ };
+ }
+ function unarchive(id) {
+ const index = state.notes.findIndex(n => n.id === id);
+ if (index < 0) return;
+ const removed = app.removeNoteAt(index);
+ effects.render();
+ api.patchNote(id, { archived: false }).then(() => effects.showToast('Unarchived')).catch(() => {
+ app.insertNoteAt(index, removed); effects.render(); effects.showError('Failed to unarchive');
+ });
+ }
+ function deleteOptimistically(id, toast = false) {
+ const index = state.notes.findIndex(n => n.id === id);
+ if (index < 0) return;
+ const removed = app.removeNoteAt(index);
+ effects.render();
+ const deletion = api.deleteNote(id);
+ const completion = toast ? deletion.then(() => effects.showToast('Deleted')) : deletion;
+ completion.catch(() => {
+ app.insertNoteAt(index, removed); effects.render(); effects.showError('Failed to delete');
+ });
+ }
+ // Desktop deliberately persists without updating local sort_order, as before.
+ function persistOrder(ids) { return api.reorder(ids); }
+ async function commitMobileOrder(ids) {
+ try {
+ await api.reorder(ids);
+ ids.forEach((id, index) => {
+ const note = state.notes.find(note => note.id === id);
+ if (note) app.mergeNote(note, { sort_order: index });
+ });
+ } catch (error) { console.warn('reorder failed', error); }
+ }
+ return { togglePin, updateColor, stageArchive, unarchive, deleteOptimistically, persistOrder, commitMobileOrder };
+}
diff --git a/frontend/src/features/notes/application/checklistOperations.js b/frontend/src/features/notes/application/checklistOperations.js
new file mode 100644
index 000000000..b4a596b04
--- /dev/null
+++ b/frontend/src/features/notes/application/checklistOperations.js
@@ -0,0 +1,68 @@
+/** Checklist item workflows. Supplied feedback callbacks update the invoking view. */
+export function createChecklistOperations({
+ app,
+ api,
+ effects,
+ uid
+}) {
+ const state = app.state;
+ function itemNote(id, index) {
+ const note = state.notes.find(n => n.id === id);
+ return note && Array.isArray(note.items) && note.items[index] ? note : null;
+ }
+ function removeItem(id, index) {
+ const note = itemNote(id, index);
+ if (!note) return;
+ const removed = note.items[index];
+ app.mergeNote(note, { items: note.items.filter((_, i) => i !== index) });
+ effects.render();
+ api.patchNote(id, { items: note.items }).catch(() => {
+ app.spliceItems(note, index, 0, removed); effects.render(); effects.showError('Failed to remove item');
+ });
+ }
+ function editItem(note, index, text) {
+ const oldText = (note.items[index].text || '').trim();
+ if (text === oldText) { effects.render(); return; }
+ const oldItem = note.items[index];
+ if (!text) app.spliceItems(note, index, 1);
+ else app.updateItem(note, index, { text });
+ api.patchNote(note.id, { items: note.items }).catch(() => {
+ if (!text) app.spliceItems(note, index, 0, oldItem);
+ else app.updateItem(note, index, { text: oldText });
+ effects.render(); effects.showError('Failed to update item');
+ });
+ effects.render();
+ }
+ function addItem(id, text, added) {
+ const note = state.notes.find(n => n.id === id);
+ if (!note) return;
+ const items = Array.isArray(note.items) ? [...note.items] : [];
+ items.push({ id: uid(), text, done: false });
+ app.mergeNote(note, { items });
+ added(); effects.render();
+ return () => api.patchNote(id, { items }).catch(() => {
+ app.mergeNote(note, { items: items.slice(0, -1) }); effects.render(); effects.showError('Failed to add item');
+ });
+ }
+ function toggleItem(id, index, changed, completed) {
+ const note = itemNote(id, index);
+ if (!note) return;
+ const wasDone = note.items.length > 0 && note.items.every(it => it.done);
+ app.updateItem(note, index, { done: !note.items[index].done });
+ changed(note.items[index].done);
+ if (!wasDone && note.items.length > 0 && note.items.every(it => it.done)) completed();
+ api.patchNote(id, { items: note.items }).catch(() => {
+ app.updateItem(note, index, { done: !note.items[index].done }); changed(note.items[index].done);
+ });
+ }
+ async function toggleTodayStep(id, index, changed, completed) {
+ const note = itemNote(id, index);
+ if (!note) return;
+ app.updateItem(note, index, { done: !note.items[index].done }); changed();
+ try {
+ await api.patchNote(id, { items: note.items }); effects.render();
+ if (note.items.every(it => it.done)) completed();
+ } catch { app.updateItem(note, index, { done: !note.items[index].done }); }
+ }
+ return { removeItem, editItem, addItem, toggleItem, toggleTodayStep };
+}
diff --git a/frontend/src/features/notes/application/deletion.js b/frontend/src/features/notes/application/deletion.js
new file mode 100644
index 000000000..e31e9b422
--- /dev/null
+++ b/frontend/src/features/notes/application/deletion.js
@@ -0,0 +1,51 @@
+/** Confirmed deletion and past-reminder clearing workflows. */
+export function createDeletion({
+ app,
+ _deleteNoteApi,
+ _fetchNotes,
+ _isPastReminder,
+ _renderNotes,
+ effects,
+ state
+}) {
+ async function _deleteNote(id) {
+ const ok = effects.styledConfirm
+ ? await effects.styledConfirm('Delete this note?', { confirmText: 'Delete', danger: true })
+ : effects.confirm('Delete this note?');
+ if (!ok) return;
+ try { await _deleteNoteApi(id); await _fetchNotes(); _renderNotes(); effects.showToast('Deleted'); }
+ catch (err) { effects.showError(err.message); }
+ }
+
+ async function _clearPastReminders() {
+ const targets = state.notes.filter(n => !n.archived && _isPastReminder(n));
+ if (!targets.length) {
+ effects.showToast?.('No past reminders to clear');
+ return;
+ }
+ const ok = effects.styledConfirm
+ ? await effects.styledConfirm(`Delete ${targets.length} past reminder${targets.length === 1 ? '' : 's'}?`, { confirmText: 'Delete', danger: true })
+ : effects.confirm(`Delete ${targets.length} past reminder${targets.length === 1 ? '' : 's'}?`);
+ if (!ok) return;
+ await Promise.all(targets.map(n => _deleteNoteApi(n.id).catch(() => {})));
+ await _fetchNotes();
+ _renderNotes();
+ effects.showToast?.(`Cleared ${targets.length} past reminder${targets.length === 1 ? '' : 's'}`);
+ }
+
+ async function deleteFromEditor(id) {
+ const ok = effects.styledConfirm
+ ? await effects.styledConfirm('Delete this note?', { confirmText: 'Delete', danger: true })
+ : effects.confirm('Delete this note?');
+ if (!ok) return;
+ const index = state.notes.findIndex(note => note.id === id);
+ if (index >= 0) app.removeNoteAt(index);
+ app.setEditingId(null);
+ _renderNotes();
+ _deleteNoteApi(id).then(() => effects.showToast('Deleted')).catch(() => {
+ effects.showError('Failed to delete');
+ _fetchNotes().then(() => _renderNotes());
+ });
+ }
+ return { _deleteNote, _clearPastReminders, deleteFromEditor };
+}
diff --git a/frontend/src/features/notes/application/drafts.js b/frontend/src/features/notes/application/drafts.js
new file mode 100644
index 000000000..4f7a4715d
--- /dev/null
+++ b/frontend/src/features/notes/application/drafts.js
@@ -0,0 +1,55 @@
+/** Serialized autosave and synchronous local draft backup. DOM collection is a supplied port. */
+export function createNotesDrafts({
+ app,
+ api,
+ persistence,
+ scheduler,
+ effects
+}) {
+ const state = app.state;
+ const { _draftKey, _clearDraft } = persistence;
+ function bindDraft({ collect, id, view }) {
+ let t = null;
+ let pending = Promise.resolve();
+ let stopped = false;
+ let warned = false;
+ const save = () => {
+ const d = collect();
+ // An empty edit can be intentional: don't restore stale server text over it.
+ try { persistence.setItem(_draftKey(id), JSON.stringify(d)); }
+ catch {
+ if (!warned) effects.showError('Draft backup unavailable. Keep this note open until saved.');
+ warned = true;
+ }
+ return d;
+ };
+ const persist = (d) => {
+ if (!id || id === '__new__' || d.note_type === 'draw') return pending;
+ const { _ts, ...payload } = d;
+ payload.label = [...new Set(payload.label.split(/\s+/).map(s => s.replace(/^#+/, '')).filter(Boolean))].join(' ') || null;
+ pending = pending.then(async () => {
+ try {
+ await api.patchNote(id, payload);
+ view.failed = false;
+ const note = state.notes.find(n => n.id === id);
+ if (note) app.mergeNote(note, payload);
+ if (persistence.getItem(_draftKey(id)) === JSON.stringify(d)) _clearDraft(id);
+ } catch {
+ if (!view.failed) effects.showError('Note not synced. Your edits are kept on this device; retry Save.');
+ view.failed = true;
+ }
+ });
+ return pending;
+ };
+ const flush = () => { scheduler.clearTimeout(t); return save(); };
+ const stop = () => { stopped = true; scheduler.clearTimeout(t); return pending; };
+ const sched = () => {
+ const d = save();
+ if (stopped) return;
+ scheduler.clearTimeout(t);
+ t = scheduler.setTimeout(() => persist(d), 500);
+ };
+ return { flush, stop, schedule: sched };
+ }
+ return { bindDraft };
+}
diff --git a/frontend/src/features/notes/application/queries.js b/frontend/src/features/notes/application/queries.js
new file mode 100644
index 000000000..6a92250c9
--- /dev/null
+++ b/frontend/src/features/notes/application/queries.js
@@ -0,0 +1,66 @@
+/** Application-owned filtering, searching and note ordering. */
+import { _noteTags, _visibleNoteTags, _nextGoalStep, _isCalendarReminderNote } from '../domain/noteRules.js';
+import { _hasTimeComponent } from '../domain/recurrence.js';
+export function createQueries({
+ _hasActiveReminder,
+ state
+}) {
+ function _sortedVisibleNotes() {
+ const displayNotes = _userVisibleNotes();
+ let filtered = state.activeLabel ? displayNotes.filter(n => _noteTags(n).includes(state.activeLabel)) : displayNotes;
+ if (state.activeFilter === 'reminders') {
+ filtered = filtered.filter(n => n.due_date && _hasTimeComponent(n.due_date));
+ } else if (state.activeFilter === 'no-reminders') {
+ filtered = filtered.filter(n => !(n.due_date && _hasTimeComponent(n.due_date)));
+ } else if (state.activeFilter === 'default') {
+ filtered = filtered.filter(n => _visibleNoteTags(n).length === 0);
+ } else if (state.activeFilter === 'goals') {
+ filtered = filtered.filter(n => n.note_type === 'goal' && !n.archived);
+ } else if (state.activeFilter === 'today') {
+ // Today view: only goals that still have an unchecked step.
+ filtered = filtered.filter(n => n.note_type === 'goal' && !n.archived && _nextGoalStep(n));
+ }
+ if (state.searchQuery) {
+ filtered = filtered.filter(n => {
+ const q = state.searchQuery;
+ if ((n.title || '').toLowerCase().includes(q)) return true;
+ if ((n.content || '').toLowerCase().includes(q)) return true;
+ if ((n.label || '').toLowerCase().includes(q)) return true;
+ if (Array.isArray(n.items) && n.items.some(it => (it.text || '').toLowerCase().includes(q))) return true;
+ return false;
+ });
+ }
+ const sorted = [...filtered].sort((a, b) => {
+ // In reminders view: sort by due date ascending (soonest first)
+ if (state.activeFilter === 'reminders') {
+ const da = new Date(a.due_date || 0).getTime();
+ const db = new Date(b.due_date || 0).getTime();
+ return da - db;
+ }
+ // Archived view: newest archived first (ignore manual sort_order).
+ if (state.showingArchived) {
+ return new Date(b.updated_at || 0) - new Date(a.updated_at || 0);
+ }
+ if (a.pinned && !b.pinned) return -1;
+ if (!a.pinned && b.pinned) return 1;
+ // Active reminders (due date in the past, not done/archived) rank
+ // immediately under the pinned block.
+ const aActive = _hasActiveReminder(a);
+ const bActive = _hasActiveReminder(b);
+ if (aActive && !bActive) return -1;
+ if (!aActive && bActive) return 1;
+ const so = (a.sort_order || 0) - (b.sort_order || 0);
+ if (so !== 0) return so;
+ return new Date(b.updated_at || 0) - new Date(a.updated_at || 0);
+ });
+
+
+ return sorted;
+ }
+
+ function _userVisibleNotes() {
+ return state.notes.filter(n => !_isCalendarReminderNote(n));
+ }
+
+ return { _sortedVisibleNotes, _userVisibleNotes };
+}
diff --git a/frontend/src/features/notes/application/reminders.js b/frontend/src/features/notes/application/reminders.js
new file mode 100644
index 000000000..5e2475993
--- /dev/null
+++ b/frontend/src/features/notes/application/reminders.js
@@ -0,0 +1,182 @@
+/** Page-owned reminder scheduler and notification delivery workflow. */
+import { _hasTimeComponent, _isDueTodayOrOverdue, _advanceRecurring } from '../domain/recurrence.js';
+export function createNotesReminders({
+ app,
+ api,
+ persistence,
+ notifications,
+ clock,
+ scheduler,
+ effects,
+ fetchNotes,
+ isNoteFullyDone,
+ hasItems,
+ dismissedKey
+}) {
+ const state = app.state;
+ const { _loadFiredReminders, _saveFiredReminders } = persistence;
+ const _patchNote = api.patchNote;
+ const _fetchNotes = fetchNotes;
+ const _isNoteFullyDone = isNoteFullyDone;
+ const _hasItems = hasItems;
+ const REMINDER_DISMISSED_AT_KEY = dismissedKey;
+ const _updateRailBadge = effects.badge;
+ let _reminderTimer = null;
+ let startupTimer = null;
+ let started = false;
+ let disposed = false;
+ function _checkReminders() {
+ if (!state.notes.length) return;
+ const now = clock.now();
+ const fired = _loadFiredReminders();
+ let changed = false;
+ for (const note of state.notes) {
+ if (!note.due_date || note.archived) continue;
+ if (!_hasTimeComponent(note.due_date)) continue;
+ if (fired.has(note.id)) continue;
+ const due = new Date(note.due_date).getTime();
+ if (isNaN(due)) continue;
+ if (due <= now && due > now - 60000) {
+ _fireReminder(note);
+ // Recurring? advance the due_date instead of marking as fired
+ if (note.repeat && note.repeat !== 'none') {
+ const next = _advanceRecurring(note.due_date, note.repeat, clock);
+ if (next) {
+ app.mergeNote(note, { due_date: next });
+ _patchNote(note.id, { due_date: next }).catch(() => {});
+ // Don't add to fired : new due_date is in the future
+ continue;
+ }
+ }
+ fired.add(note.id);
+ changed = true;
+ } else if (due <= now - 60000) {
+ // Past, never seen : silently advance recurring or mark fired
+ if (note.repeat && note.repeat !== 'none') {
+ const next = _advanceRecurring(note.due_date, note.repeat, clock);
+ if (next) {
+ app.mergeNote(note, { due_date: next });
+ _patchNote(note.id, { due_date: next }).catch(() => {});
+ continue;
+ }
+ }
+ fired.add(note.id);
+ changed = true;
+ }
+ }
+ if (changed) _saveFiredReminders(fired);
+ // Always refresh badge : fired state may have changed visually without note mutation
+ _updateRailBadge();
+ }
+
+ function _fireReminder(note) {
+ const title = note.title || 'Note reminder';
+ // Include the verbatim note content so the email/notification actually
+ // shows what to do, not just a count. Cap the per-item lines (8 max) and
+ // total length so the body stays inbox-friendly.
+ let rawBody;
+ if (_hasItems(note)) {
+ const pending = (note.items || [])
+ .filter(i => !i.done && !i.checked)
+ .map(i => (i.text || '').trim())
+ .filter(Boolean);
+ if (pending.length) {
+ const shown = pending.slice(0, 8).map(t => `- ${t}`).join('\n');
+ const extra = pending.length > 8 ? `\n…and ${pending.length - 8} more` : '';
+ rawBody = `Pending (${pending.length}):\n${shown}${extra}`;
+ } else {
+ rawBody = `${(note.items || []).length} item${(note.items || []).length === 1 ? '' : 's'}`;
+ }
+ } else {
+ rawBody = (note.content || '').slice(0, 400);
+ }
+
+ // Ask the server to dispatch according to user settings. The server may
+ // return an LLM-written synthesis line and/or send an email. We still show
+ // a local browser notification so the user gets immediate feedback even if
+ // the server path is disabled or slow.
+ const showLocal = body => notifications.show(title, body, note.id);
+
+ // Fire-and-forget server dispatch. If synthesis comes back quickly enough,
+ // use it as the notification body; otherwise the local notification has
+ // already shown with the raw body.
+ let shown = false;
+ const timer = scheduler.setTimeout(() => { if (!shown) { shown = true; showLocal(rawBody); } }, 1500);
+
+ api.fireReminder({ note_id: note.id, title, body: rawBody })
+ .then(r => r.ok ? r.json() : null)
+ .then(data => {
+ scheduler.clearTimeout(timer);
+ if (shown) return;
+ shown = true;
+ const body = (data && data.synthesis) ? data.synthesis : rawBody;
+ showLocal(body);
+ })
+ .catch(() => {
+ scheduler.clearTimeout(timer);
+ if (!shown) { shown = true; showLocal(rawBody); }
+ });
+
+ // Pulse the card if visible; otherwise queue it so the next time the user
+ // opens the notes panel the card gets a brief glow.
+ effects.highlight(note.id);
+ }
+
+ function _startReminderLoop() {
+ if (disposed || _reminderTimer) return;
+ _reminderTimer = scheduler.setInterval(_checkReminders, 30000);
+ _checkReminders(); // run once immediately
+ }
+
+ function _countDueReminders() {
+ return state.notes.filter(n => !n.archived && _isDueTodayOrOverdue(n.due_date, clock) && !_isNoteFullyDone(n)).length;
+ }
+
+ function _countFiredReminders() {
+ // Reminders whose time has actually passed (not just date-today),
+ // and which fired after the last user dismissal.
+ const now = clock.now();
+ return state.notes.filter(n => {
+ if (n.archived || _isNoteFullyDone(n)) return false;
+ if (!n.due_date || !_hasTimeComponent(n.due_date)) return false;
+ const t = new Date(n.due_date).getTime();
+ if (isNaN(t) || t > now) return false;
+ return t > state.firedDotDismissedAt;
+ }).length;
+ }
+
+ function dismissFiredReminderDot() {
+ app.setFiredDotDismissedAt(clock.now());
+ try { persistence.setItem(REMINDER_DISMISSED_AT_KEY, String(state.firedDotDismissedAt)); } catch {}
+ _updateRailBadge();
+ }
+
+ async function refreshDueBadge(opts = {}) {
+ // Usually lightweight, but callers that just created a note reminder can
+ // force a refresh so the background reminder loop sees it immediately.
+ if (opts.force || state.notes.length === 0) {
+ try {
+ const wasArchived = state.showingArchived;
+ app.setShowingArchived(false);
+ await _fetchNotes();
+ app.setShowingArchived(wasArchived);
+ } catch {}
+ }
+ _updateRailBadge();
+ }
+
+ async function _initReminders() {
+ try {
+ const res = await api.listNotes(false);
+ if (res.ok && !disposed) {
+ const data = await res.json();
+ app.replaceNotes(data.notes || data || []);
+ _startReminderLoop();
+ }
+ } catch {}
+ }
+
+ function start() { if (started || disposed) return; started = true; startupTimer = scheduler.setTimeout(_initReminders, 3000); }
+ function dispose() { disposed = true; scheduler.clearTimeout(startupTimer); scheduler.clearInterval(_reminderTimer); _reminderTimer = null; }
+ return { start, dispose, _checkReminders, _fireReminder, _startReminderLoop, _countDueReminders, _countFiredReminders, dismissFiredReminderDot, refreshDueBadge, _initReminders };
+}
diff --git a/frontend/src/features/notes/application/selection.js b/frontend/src/features/notes/application/selection.js
new file mode 100644
index 000000000..6017025e2
--- /dev/null
+++ b/frontend/src/features/notes/application/selection.js
@@ -0,0 +1,39 @@
+/** Selected-note attachment retains synchronous acceptance; bulk requests retain partial-failure behavior. */
+export function createSelectionOperations({
+ app,
+ api,
+ effects,
+ sendContext,
+ exitSelection,
+ fetchNotes
+}) {
+ const state = app.state;
+ function attachSelected() {
+ const ids = [...state.selectedIds];
+ if (!ids.length) return;
+ const detail = { noteIds: ids, accepted: false };
+ sendContext(detail);
+ if (!detail.accepted) {
+ effects.showToast('Choose a chat or model before attaching notes');
+ return;
+ }
+ exitSelection();
+ }
+ async function archiveSelected() {
+ const ids = [...state.selectedIds];
+ if (!ids.length) return;
+ await Promise.all(ids.map(id => api.patchNote(id, { archived: true }).catch(() => {})));
+ exitSelection(); await fetchNotes(); effects.render(); effects.showToast(`Archived ${ids.length}`);
+ }
+ async function deleteSelected() {
+ const ids = [...state.selectedIds];
+ if (!ids.length) return;
+ if (effects.styledConfirm) {
+ const ok = await effects.styledConfirm(`Delete ${ids.length} note${ids.length === 1 ? '' : 's'}?`, { confirmText: 'Delete', danger: true });
+ if (!ok) return;
+ }
+ await Promise.all(ids.map(id => api.deleteNote(id).catch(() => {})));
+ exitSelection(); await fetchNotes(); effects.render(); effects.showToast(`Deleted ${ids.length}`);
+ }
+ return { attachSelected, archiveSelected, deleteSelected };
+}
diff --git a/frontend/src/features/notes/application/state.js b/frontend/src/features/notes/application/state.js
new file mode 100644
index 000000000..b87ef11c4
--- /dev/null
+++ b/frontend/src/features/notes/application/state.js
@@ -0,0 +1,83 @@
+/** The sole Notes state owner. Views have live read-only access; writes use operations. */
+export function createNotesState(initial = {}) {
+ const values = {
+ open: false, notes: [], editingId: null, selectedIds: new Set(),
+ activeLabel: null, activeFilter: null, reminderChipNext: 'reminders', searchQuery: '',
+ viewMode: initial.viewMode || 'list', showingArchived: false, selectMode: false,
+ suppressNextNoteTapId: null, labelsCollapsed: !!initial.labelsCollapsed,
+ loading: false, firedDotDismissedAt: initial.firedDotDismissedAt || 0,
+ };
+ // Preserve captured note identity across asynchronous completions without
+ // giving a view a writable reference to the application store.
+ const views = new WeakMap(), targets = new WeakMap();
+ const unwrap = value => targets.get(value) || value;
+ // Copies built from views (spread, filter, map) still hold nested views;
+ // store only raw data so the owner never keeps its own read-only views.
+ function unwrapDeep(value, seen = new WeakSet()) {
+ if (!value || typeof value !== 'object') return value;
+ if (targets.has(value)) return targets.get(value);
+ if (seen.has(value)) return value;
+ seen.add(value);
+ if (Array.isArray(value)) value.forEach((item, index) => { value[index] = unwrapDeep(item, seen); });
+ else if (Object.getPrototypeOf(value) === Object.prototype) for (const key of Object.keys(value)) value[key] = unwrapDeep(value[key], seen);
+ return value;
+ }
+ function readonly(value) {
+ if (!value || typeof value !== 'object') return value;
+ if (targets.has(value)) return value;
+ if (views.has(value)) return views.get(value);
+ const view = new Proxy(value, {
+ get(target, key) {
+ if (target instanceof Set) {
+ if (['add', 'delete', 'clear'].includes(key)) return () => { throw new TypeError('Use Notes selection operations'); };
+ if (key === 'valueOf') return () => views.get(target);
+ if (key === 'forEach') return (callback, thisArg) => target.forEach(value => callback.call(thisArg, value, value, views.get(target)));
+ const member = Reflect.get(target, key, target);
+ return typeof member === 'function' ? member.bind(target) : member;
+ }
+ return readonly(Reflect.get(target, key));
+ },
+ set() { throw new TypeError('Use Notes state operations'); },
+ deleteProperty() { throw new TypeError('Use Notes state operations'); },
+ defineProperty() { throw new TypeError('Use Notes state operations'); },
+ setPrototypeOf() { throw new TypeError('Use Notes state operations'); },
+ preventExtensions() { throw new TypeError('Use Notes state operations'); },
+ getOwnPropertyDescriptor(target, key) {
+ const descriptor = Reflect.getOwnPropertyDescriptor(target, key);
+ if (descriptor && 'value' in descriptor) return { ...descriptor, value: readonly(descriptor.value) };
+ return descriptor;
+ },
+ });
+ views.set(value, view); targets.set(view, value);
+ return view;
+ }
+ const state = Object.freeze(Object.fromEntries(Object.keys(values).map(key => [key, () => readonly(values[key])])));
+ const view = Object.freeze(Object.defineProperties({}, Object.fromEntries(Object.entries(state).map(([key, get]) => [key, { get, enumerable: true }]))));
+ return {
+ state: view,
+ setOpen: value => { values.open = value; },
+ setEditingId: value => { values.editingId = value; },
+ setActiveLabel: value => { values.activeLabel = value; },
+ setActiveFilter: value => { values.activeFilter = value; },
+ setReminderChipNext: value => { values.reminderChipNext = value; },
+ setSearchQuery: value => { values.searchQuery = value; },
+ setViewMode: value => { values.viewMode = value; },
+ setShowingArchived: value => { values.showingArchived = value; },
+ setSelectMode: value => { values.selectMode = value; },
+ setSuppressNextNoteTapId: value => { values.suppressNextNoteTapId = value; },
+ setLabelsCollapsed: value => { values.labelsCollapsed = value; },
+ setLoading: value => { values.loading = value; },
+ setFiredDotDismissedAt: value => { values.firedDotDismissedAt = value; },
+ replaceNotes: notes => { values.notes = notes; },
+ removeNoteAt: index => readonly(values.notes.splice(index, 1)[0]),
+ insertNoteAt: (index, note) => { values.notes.splice(index, 0, unwrapDeep(note)); },
+ prependNote: note => { values.notes.unshift(unwrapDeep(note)); },
+ replaceNoteAt: (index, note) => { values.notes[index] = unwrapDeep(note); },
+ mergeNote: (note, patch) => { for (const [key, value] of Object.entries(patch)) unwrap(note)[key] = unwrapDeep(value); },
+ updateItem: (note, index, patch) => { Object.assign(unwrap(unwrap(note).items[index]), unwrapDeep({ ...patch })); },
+ spliceItems: (note, ...args) => unwrap(unwrap(note).items).splice(...args.map(arg => unwrapDeep(arg))),
+ selectId: id => { values.selectedIds.add(id); },
+ deselectId: id => values.selectedIds.delete(id),
+ clearSelection: () => values.selectedIds.clear(),
+ };
+}
diff --git a/frontend/src/features/notes/application/submission.js b/frontend/src/features/notes/application/submission.js
new file mode 100644
index 000000000..4703eb7c1
--- /dev/null
+++ b/frontend/src/features/notes/application/submission.js
@@ -0,0 +1,69 @@
+/** Editor submission ordering, optimistic state, reminder rearming and save recovery. */
+export function createNotesSubmission({
+ app,
+ api,
+ persistence,
+ clock,
+ uid,
+ effects,
+ fetchNotes
+}) {
+ const state = app.state;
+ const { _loadFiredReminders, _saveFiredReminders, _loadGlowedReminders, _saveGlowedReminders, _loadDraft, _clearDraft } = persistence;
+ function submitNote(payload, note, isEdit) {
+ // Reset fired reminder if due_date changed (so re-arm works), and also
+ // clear the entry-glow seen flag so the new firing glows again on the
+ // next time the user opens the panel.
+ if (isEdit && note.due_date !== payload.due_date) {
+ const fired = _loadFiredReminders();
+ fired.delete(note.id);
+ _saveFiredReminders(fired);
+ const glowed = _loadGlowedReminders();
+ glowed.delete(note.id);
+ _saveGlowedReminders(glowed);
+ effects.clearGlow(note.id);
+ }
+ // Edited notes move to the top of their section (under pinned). Compute
+ // sort_order = (min unpinned sort_order) - 1 so the saved note sorts above
+ // siblings; the pin block keeps its own ordering above this.
+ if (!payload.pinned) {
+ // Both edits AND newly-created notes anchor above the rest of the
+ // unpinned section. Without this, freshly created notes sit at the
+ // bottom because manually-reordered siblings already carry negative
+ // sort_order values.
+ const minUnpinned = state.notes
+ .filter(n => !n.pinned && (!isEdit || n.id !== note.id))
+ .reduce((m, n) => Math.min(m, n.sort_order || 0), 0);
+ payload.sort_order = minUnpinned - 1;
+ }
+ // Optimistic update : update local state first, render, then save in background
+ app.setEditingId(null);
+ const draftId = isEdit ? note.id : '__new__';
+ const submittedDraft = JSON.stringify(_loadDraft(draftId));
+ if (isEdit) {
+ const idx = state.notes.findIndex(n => n.id === note.id);
+ if (idx >= 0) app.replaceNoteAt(idx, { ...state.notes[idx], ...payload });
+ } else {
+ app.prependNote({ ...payload, id: 'tmp_' + uid(), created_at: new Date(clock.now()).toISOString(), updated_at: new Date(clock.now()).toISOString() });
+ }
+ effects.render();
+ // Background save
+ api.saveNote(payload).then(saved => {
+ if (JSON.stringify(_loadDraft(draftId)) === submittedDraft) _clearDraft(draftId);
+ if (!isEdit && saved && saved.id) {
+ // Replace temp ID with real one from server. AND re-render : the
+ // existing card's `data-note-id="tmp_xxx"` is stale after Object.assign
+ // bumps the in-memory id, so all subsequent clicks (edit, done, copy,
+ // archive, delete) silently fail to find the note in `_notes`.
+ const tmp = state.notes.find(n => n.id.startsWith('tmp_'));
+ if (tmp) app.mergeNote(tmp, saved);
+ effects.render();
+ }
+ }).catch(err => {
+ effects.showError('Save failed: ' + err.message);
+ fetchNotes().then(() => effects.render());
+ });
+
+ }
+ return { submitNote };
+}
diff --git a/frontend/src/features/notes/application/workflows.js b/frontend/src/features/notes/application/workflows.js
new file mode 100644
index 000000000..018cbf8aa
--- /dev/null
+++ b/frontend/src/features/notes/application/workflows.js
@@ -0,0 +1,78 @@
+/** Notes CRUD, optimistic archive and in-memory undo workflows. */
+export function createNotesWorkflows({
+ app,
+ api,
+ effects
+}) {
+ const state = app.state;
+ const _undoStack = [];
+ const _renderNotes = effects.render;
+ const _patchNote = api.patchNote;
+ const uiModule = effects;
+ function _pushUndo(entry) {
+ _undoStack.push(entry);
+ if (_undoStack.length > 20) _undoStack.shift();
+ }
+
+ function _popAndRunUndo() {
+ const entry = _undoStack.pop();
+ if (entry) entry.run();
+ return !!entry;
+ }
+
+ function _undoArchive(note, prevIdx) {
+ // Re-insert at original position and clear archived flag on the server.
+ const safeIdx = Math.min(Math.max(prevIdx, 0), state.notes.length);
+ app.insertNoteAt(safeIdx, { ...note, archived: false });
+ _renderNotes();
+ _patchNote(note.id, { archived: false }).catch(() => {
+ // Roll back local insertion if the server refuses
+ const i = state.notes.findIndex(n => n.id === note.id);
+ if (i >= 0) app.removeNoteAt(i);
+ _renderNotes();
+ uiModule.showError('Undo failed');
+ });
+ }
+
+ function _archiveNoteById(id, { card = null, celebrate = false } = {}) {
+ if (!id) return false;
+ const idx = state.notes.findIndex(n => n.id === id);
+ if (idx < 0) return false;
+ const note = state.notes[idx];
+ if (celebrate && card && note) effects.celebrateArchive(note, card);
+ const removed = app.removeNoteAt(idx);
+ app.setEditingId(null);
+ _renderNotes();
+ const undo = () => _undoArchive(removed, idx);
+ _pushUndo({ label: 'archive', run: undo });
+ _patchNote(id, { archived: true }).then(() => {
+ effects.archived(undo);
+ }).catch(() => {
+ app.insertNoteAt(idx, removed);
+ _renderNotes();
+ uiModule.showError('Failed to archive');
+ });
+ return true;
+ }
+
+ async function _fetchNotes() {
+ app.setLoading(true);
+ try {
+ const res = await api.listNotes(state.showingArchived);
+ if (!res.ok) { app.replaceNotes([]); return; }
+ const data = await res.json();
+ app.replaceNotes(data.notes || data || []);
+ } catch (e) {
+ console.error('Failed to fetch notes:', e);
+ app.replaceNotes([]);
+ } finally {
+ app.setLoading(false);
+ }
+ }
+
+ function _saveNote(note) { return api.saveNote(note); }
+
+ function _deleteNoteApi(id) { return api.deleteNote(id); }
+
+ return { _pushUndo, _popAndRunUndo, _undoArchive, _archiveNoteById, _fetchNotes, _saveNote, _deleteNoteApi, _patchNote, undoCount: () => _undoStack.length };
+}
diff --git a/frontend/src/features/notes/domain/noteRules.js b/frontend/src/features/notes/domain/noteRules.js
new file mode 100644
index 000000000..ba3f8ae2f
--- /dev/null
+++ b/frontend/src/features/notes/domain/noteRules.js
@@ -0,0 +1,87 @@
+/** Pure Notes completion, tags, reminder and serialization rules. */
+import { _hasTimeComponent } from './recurrence.js';
+export function _isCalendarReminderNote(n) {
+ return n && n.source === 'calendar' && n.label === 'calendar';
+}
+
+export function _hasActiveReminder(n, clock) {
+ if (!n || n.archived || _isNoteFullyDone(n)) return false;
+ if (!n.due_date) return false;
+ const t = new Date(n.due_date).getTime();
+ return !isNaN(t) && t <= clock.now();
+}
+
+export function _isNoteFullyDone(note) {
+ if (_hasItems(note) && Array.isArray(note.items) && note.items.length > 0) {
+ return note.items.every(it => it.done);
+ }
+ return false;
+}
+
+export function _hasItems(note) {
+ return note && (note.note_type === 'todo' || note.note_type === 'goal' || note.note_type === 'checklist');
+}
+
+export function _goalProgress(note) {
+ if (!Array.isArray(note?.items) || note.items.length === 0) return '';
+ const done = note.items.filter(it => it.done).length;
+ return ` ${done}/${note.items.length}`;
+}
+
+export function _nextGoalStep(note) {
+ if (!Array.isArray(note?.items)) return null;
+ for (let i = 0; i < note.items.length; i++) {
+ if (!note.items[i].done) return { idx: i, item: note.items[i] };
+ }
+ return null;
+}
+
+export function _noteTags(n) {
+ const tags = [];
+ if (n?.label) tags.push(...n.label.trim().split(/\s+/).filter(Boolean));
+ if (n?.due_date && _hasTimeComponent(n.due_date)) tags.push('reminder');
+ return [...new Set(tags.map(t => t.replace(/^#+/, '').trim()).filter(Boolean))];
+}
+
+export function _visibleNoteTags(n) {
+ return _noteTags(n).filter(t => t !== 'reminder');
+}
+
+export function _isPastReminder(n, clock) {
+ if (!n?.due_date || !_hasTimeComponent(n.due_date)) return false;
+ const due = new Date(n.due_date).getTime();
+ return !isNaN(due) && due <= clock.now();
+}
+
+export function _serializeNoteForCopy(note) {
+ const lines = [];
+ if (note.title) lines.push(note.title);
+ if (note.content) lines.push(note.content);
+ if (Array.isArray(note.items) && note.items.length) {
+ if (lines.length) lines.push('');
+ for (const it of note.items) {
+ if (!it || !(it.text || '').trim()) continue;
+ lines.push(`- [${it.done ? 'x' : ' '}] ${(it.text || '').trim()}`);
+ }
+ }
+ return lines.join('\n').trim();
+}
+
+export function _noteToAgentPrompt(note) {
+ const parts = [];
+ if ((note.title || '').trim()) parts.push(note.title.trim());
+ if ((note.content || '').trim()) parts.push(note.content.trim());
+ if (Array.isArray(note.items)) {
+ note.items.filter(it => !it.done && (it.text || '').trim())
+ .forEach(it => parts.push('- ' + it.text.trim()));
+ }
+ const body = parts.join('\n');
+ return body ? `Help me get this done:\n\n${body}\n\nThe source note is read-only. Do not edit, replace, or update it.` : '';
+}
+
+export function _standardVisualVariant(note) {
+ const source = String(note?.id || note?.title || note?.created_at || 'standard-note');
+ let hash = 0;
+ for (let i = 0; i < source.length; i++) hash = ((hash << 5) - hash + source.charCodeAt(i)) | 0;
+ return Math.abs(hash) % 5;
+}
diff --git a/frontend/src/features/notes/domain/recurrence.js b/frontend/src/features/notes/domain/recurrence.js
new file mode 100644
index 000000000..f72498fbb
--- /dev/null
+++ b/frontend/src/features/notes/domain/recurrence.js
@@ -0,0 +1,269 @@
+// Local-time date and recurrence rules. Callers supply the clock at the original read sites.
+export const _ORDINALS = ['1st', '2nd', '3rd', '4th', '5th'];
+export const _DAYS = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
+export function _hasTimeComponent(dateStr) {
+ return typeof dateStr === 'string' && /T\d{2}:\d{2}/.test(dateStr);
+}
+
+export function _formatDueDate(dateStr, clock) {
+ if (!dateStr) return '';
+ const d = new Date(dateStr);
+ if (isNaN(d)) return '';
+ const now = new Date(clock.now());
+ const hasTime = _hasTimeComponent(dateStr);
+ const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
+ const due = new Date(d.getFullYear(), d.getMonth(), d.getDate());
+ const diffDays = Math.round((due - today) / 86400000);
+ const timeStr = hasTime ? d.toLocaleTimeString([], { hour: 'numeric', minute: '2-digit' }) : '';
+ if (hasTime && d < now) return 'overdue';
+ if (!hasTime && diffDays < 0) return 'overdue';
+ if (diffDays === 0) return hasTime ? timeStr : 'today';
+ if (diffDays === 1) return hasTime ? `tmrw ${timeStr}` : 'tomorrow';
+ const dateLabel = d.toLocaleDateString([], { month: 'short', day: 'numeric' });
+ return hasTime ? `${dateLabel} ${timeStr}` : dateLabel;
+}
+
+export function _isDueOverdue(dateStr, clock) {
+ if (!dateStr) return false;
+ const d = new Date(dateStr);
+ if (isNaN(d)) return false;
+ if (_hasTimeComponent(dateStr)) return d < new Date(clock.now());
+ return d < new Date(new Date(clock.now()).toDateString());
+}
+
+export function _isDueTodayOrOverdue(dateStr, clock) {
+ if (!dateStr) return false;
+ const d = new Date(dateStr);
+ const now = new Date(clock.now());
+ const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
+ const due = new Date(d.getFullYear(), d.getMonth(), d.getDate());
+ return due <= today;
+}
+
+export function _laterTodayDate(clock) {
+ const now = new Date(clock.now());
+ const eight = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 18, 0); // 6pm today
+ // If less than 1 hour before 6pm, push to "in 3 hours" instead
+ if (eight - now < 60 * 60 * 1000) return new Date(now.getTime() + 3 * 60 * 60 * 1000);
+ return eight;
+}
+
+export function _tomorrowDate(clock) {
+ const t = new Date(clock.now());
+ t.setDate(t.getDate() + 1);
+ t.setHours(8, 0, 0, 0);
+ return t;
+}
+
+export function _nextWeekDate(clock) {
+ const t = new Date(clock.now());
+ const daysUntilMon = (8 - t.getDay()) % 7 || 7;
+ t.setDate(t.getDate() + daysUntilMon);
+ t.setHours(8, 0, 0, 0);
+ return t;
+}
+
+export function _toLocalDatetimeStr(d) {
+ // Format as YYYY-MM-DDTHH:MM (local, no TZ)
+ const pad = n => String(n).padStart(2, '0');
+ return `${d.getFullYear()}-${pad(d.getMonth()+1)}-${pad(d.getDate())}T${pad(d.getHours())}:${pad(d.getMinutes())}`;
+}
+
+export function _formatReminderTag(dateStr, clock) {
+ if (!dateStr) return '';
+ const d = new Date(dateStr);
+ if (isNaN(d)) return '';
+ const now = new Date(clock.now());
+ const sameDay = d.toDateString() === now.toDateString();
+ const tomorrow = new Date(now); tomorrow.setDate(tomorrow.getDate() + 1);
+ const isTomorrow = d.toDateString() === tomorrow.toDateString();
+ const time = d.toLocaleTimeString([], { hour: 'numeric', minute: '2-digit' });
+ if (sameDay) return `Today, ${time}`;
+ if (isTomorrow) return `Tomorrow, ${time}`;
+ const dateLabel = d.toLocaleDateString([], { month: 'short', day: 'numeric' });
+ return `${dateLabel}, ${time}`;
+}
+
+export function _nthWeekdayLabel(d) {
+ const n = Math.ceil(d.getDate() / 7); // 1..5
+ return `${_ORDINALS[n - 1] || `${n}th`} ${_DAYS[d.getDay()]}`;
+}
+
+export function _isLastWeekdayOfMonth(d) {
+ const test = new Date(d);
+ test.setDate(d.getDate() + 7);
+ return test.getMonth() !== d.getMonth();
+}
+
+export function _nthWeekdayOfMonth(year, month, weekday, n) {
+ const first = new Date(year, month, 1);
+ const offset = (weekday - first.getDay() + 7) % 7;
+ let day = 1 + offset + (n - 1) * 7;
+ // Last day of month
+ const lastDay = new Date(year, month + 1, 0).getDate();
+ if (day > lastDay) day -= 7;
+ return new Date(year, month, day, 0, 0, 0);
+}
+
+export function _lastWeekdayOfMonth(year, month, weekday) {
+ const lastDay = new Date(year, month + 1, 0);
+ const back = (lastDay.getDay() - weekday + 7) % 7;
+ return new Date(year, month, lastDay.getDate() - back, 0, 0, 0);
+}
+
+export function _snapToRepeat(currentDate, normRepeat, clock) {
+ const hh = currentDate.getHours();
+ const mm = currentDate.getMinutes();
+ const now = clock.now();
+ const anchor = currentDate.getTime() > now ? currentDate : new Date(clock.now());
+ const parts = normRepeat.split(':');
+ const kind = parts[0];
+ if (kind === 'weekly') {
+ const targetWd = parseInt(parts[1], 10);
+ if (isNaN(targetWd)) return null;
+ const d = new Date(anchor.getFullYear(), anchor.getMonth(), anchor.getDate(), hh, mm, 0, 0);
+ const delta = (targetWd - d.getDay() + 7) % 7;
+ d.setDate(d.getDate() + delta);
+ if (d.getTime() <= now) d.setDate(d.getDate() + 7);
+ return d;
+ }
+ if (kind === 'monthly') {
+ const sub = parts[1];
+ let y = anchor.getFullYear();
+ let m = anchor.getMonth();
+ // Walk forward up to 14 months to find the next matching slot.
+ for (let tries = 0; tries < 14; tries++) {
+ let target;
+ if (sub === 'day') {
+ const wantDay = parseInt(parts[2], 10);
+ if (isNaN(wantDay)) return null;
+ const lastDay = new Date(y, m + 1, 0).getDate();
+ target = new Date(y, m, Math.min(wantDay, lastDay));
+ } else if (sub === 'nth') {
+ const n = parseInt(parts[2], 10);
+ const wd = parseInt(parts[3], 10);
+ if (isNaN(n) || isNaN(wd)) return null;
+ target = _nthWeekdayOfMonth(y, m, wd, n);
+ } else if (sub === 'last') {
+ const wd = parseInt(parts[2], 10);
+ if (isNaN(wd)) return null;
+ target = _lastWeekdayOfMonth(y, m, wd);
+ } else {
+ return null;
+ }
+ target.setHours(hh, mm, 0, 0);
+ if (target.getTime() > now && target.getTime() >= anchor.getTime()) return target;
+ m++;
+ if (m > 11) { m = 0; y++; }
+ }
+ return null;
+ }
+ return null;
+}
+
+export function _formatRepeatLabel(repeat, originalDate) {
+ if (!repeat || repeat === 'none') return '';
+ const norm = _normalizeRepeat(repeat, originalDate);
+ if (norm === 'daily') return 'Daily';
+ if (norm === 'yearly') return 'Yearly';
+ const parts = norm.split(':');
+ if (parts[0] === 'weekly') {
+ const wd = parseInt(parts[1], 10);
+ if (isNaN(wd)) return 'Weekly';
+ return `Weekly on ${_DAYS[wd]}s`;
+ }
+ if (parts[0] === 'monthly') {
+ if (parts[1] === 'day') return `Monthly on day ${parts[2]}`;
+ if (parts[1] === 'nth') {
+ const n = parseInt(parts[2], 10);
+ const wd = parseInt(parts[3], 10);
+ return `Monthly on ${_ORDINALS[n - 1] || `${n}th`} ${_DAYS[wd]}`;
+ }
+ if (parts[1] === 'last') {
+ const wd = parseInt(parts[2], 10);
+ return `Monthly on last ${_DAYS[wd]}`;
+ }
+ }
+ return norm;
+}
+
+export function _normalizeRepeat(repeat, originalDate) {
+ if (!repeat || repeat === 'none') return 'none';
+ if (repeat === 'daily' || repeat === 'yearly') return repeat;
+ if (/^(weekly|monthly):/.test(repeat)) return repeat;
+ // Legacy bare values: derive params from the original date
+ const wd = originalDate.getDay();
+ const n = Math.ceil(originalDate.getDate() / 7);
+ if (repeat === 'weekly') return `weekly:${wd}`;
+ if (repeat === 'monthly') return `monthly:day:${originalDate.getDate()}`;
+ if (repeat === 'monthly_nth_weekday') return `monthly:nth:${n}:${wd}`;
+ if (repeat === 'monthly_last_weekday') return `monthly:last:${wd}`;
+ return repeat;
+}
+
+export function _advanceRecurring(dateStr, repeat, clock) {
+ const orig = new Date(dateStr);
+ const hh = orig.getHours();
+ const mm = orig.getMinutes();
+ let d = new Date(orig);
+ const norm = _normalizeRepeat(repeat, orig);
+ if (norm === 'none') return null;
+
+ function step() {
+ if (norm === 'daily') {
+ d.setDate(d.getDate() + 1);
+ return;
+ }
+ if (norm === 'yearly') {
+ d.setFullYear(d.getFullYear() + 1);
+ return;
+ }
+ const parts = norm.split(':');
+ const kind = parts[0];
+ if (kind === 'weekly') {
+ // Snap to the requested weekday in the next 1-7 days
+ const targetWd = parseInt(parts[1], 10);
+ let delta = (targetWd - d.getDay() + 7) % 7;
+ if (delta === 0) delta = 7;
+ d.setDate(d.getDate() + delta);
+ d.setHours(hh, mm, 0, 0);
+ return;
+ }
+ if (kind === 'monthly') {
+ const sub = parts[1];
+ const ny = d.getFullYear() + (d.getMonth() === 11 ? 1 : 0);
+ const nm = (d.getMonth() + 1) % 12;
+ let target;
+ if (sub === 'day') {
+ const wantDay = parseInt(parts[2], 10);
+ const lastDay = new Date(ny, nm + 1, 0).getDate();
+ target = new Date(ny, nm, Math.min(wantDay, lastDay));
+ } else if (sub === 'nth') {
+ const n = parseInt(parts[2], 10);
+ const wd = parseInt(parts[3], 10);
+ target = _nthWeekdayOfMonth(ny, nm, wd, n);
+ } else if (sub === 'last') {
+ const wd = parseInt(parts[2], 10);
+ target = _lastWeekdayOfMonth(ny, nm, wd);
+ } else {
+ d = null; return;
+ }
+ target.setHours(hh, mm, 0, 0);
+ d = target;
+ return;
+ }
+ d = null;
+ }
+
+ step();
+ if (d === null) return null;
+ const now = clock.now();
+ // Cap catch-up to avoid runaway on a malformed/very-old date.
+ let guard = 5000;
+ while (d.getTime() <= now) {
+ if (--guard <= 0) return null;
+ step();
+ if (d === null) return null;
+ }
+ return _toLocalDatetimeStr(d);
+}
diff --git a/frontend/src/features/notes/index.js b/frontend/src/features/notes/index.js
new file mode 100644
index 000000000..146844b8a
--- /dev/null
+++ b/frontend/src/features/notes/index.js
@@ -0,0 +1,503 @@
+/** Notes composition and intentional public API. The legacy entry activates compatibility startup. */
+import { createSelectionOperations } from './application/selection.js';
+import { createToolbar } from './ui/toolbar.js';
+import { createWindowLayout } from './ui/windowLayout.js';
+import { createCardOperations } from './application/cardOperations.js';
+import { createChecklistOperations } from './application/checklistOperations.js';
+import { createNotesSubmission } from './application/submission.js';
+import { createNotesDrafts } from './application/drafts.js';
+import { createNotesLifecycle } from './ui/lifecycle.js';
+import * as noteRules from './domain/noteRules.js';
+import { createText } from './ui/text.js';
+import { createColors } from './ui/colors.js';
+import { createPanel } from './ui/panel.js';
+import { createReminderDisplay } from './ui/reminderDisplay.js';
+import { createSelection } from './ui/selection.js';
+import { createFilters } from './ui/filters.js';
+import { createCardRendering } from './ui/cardRendering.js';
+import { createLayout } from './ui/layout.js';
+import { createQuickAdd } from './ui/quickAdd.js';
+import { createCardInteractions } from './ui/cardInteractions.js';
+import { createCardChecklist } from './ui/cardChecklist.js';
+import { createCardReorder } from './ui/cardReorder.js';
+import { createDraftEditor } from './ui/draftEditor.js';
+import { createEditor } from './ui/editor.js';
+import { createReminderPicker } from './ui/reminderPicker.js';
+import { createChecklist } from './ui/checklist.js';
+import { createDrawing } from './ui/drawing.js';
+import { createClipboard } from './ui/clipboard.js';
+import { createMobileEditor } from './ui/mobileEditor.js';
+import { createMobileReorder } from './ui/mobileReorder.js';
+import { createChecklistReorder } from './ui/checklistReorder.js';
+import { createQueries } from './application/queries.js';
+import { createAgentActions } from './application/agentActions.js';
+import { createDeletion } from './application/deletion.js';
+import { createNotesReminders } from './application/reminders.js';
+import { createNotesNotifications } from './infrastructure/notifications.js';
+import { createNotesState } from './application/state.js';
+import { createNotesWorkflows } from './application/workflows.js';
+import { createNotesApi } from './infrastructure/http.js';
+import { createNotesPersistence, REMINDER_DISMISSED_AT_KEY, NOTES_FIRST_OPEN_HINT_KEY, NOTES_LABELS_COLLAPSED_KEY } from './infrastructure/storage.js';
+import * as dates from './domain/recurrence.js';
+import uiModule from '/static/js/ui.js?v=20260916largetoolscroll1';
+import { spawnConfetti } from '/static/js/shared/ui/confetti.js';
+import * as Modals from '/static/js/modalManager.js';
+import { attachColorPicker } from '/static/js/colorPicker.js?v=20260910eyedropper1';
+import { makeWindowDraggable } from '/static/js/windowDrag.js';
+import { snapModalToZone } from '/static/js/tileManager.js?v=20260910responsivebounds1';
+import { applyEdgeDock, clearDockSide } from '/static/js/modalSnap.js';
+import { topToolWindowZ, topPortalZ } from '/static/js/toolWindowZOrder.js';
+import { bindMenuDismiss, dismissOrRemove } from '/static/js/escMenuStack.js';
+import { bindTourHintDismiss } from '/static/js/tourHintDismiss.js';
+
+const api = createNotesApi({ origin: window.location.origin, request: (...args) => fetch(...args) });
+const persistence = createNotesPersistence({ storage: typeof localStorage === 'undefined' ? undefined : localStorage });
+const { _loadPendingHighlights, _loadGlowedReminders, _saveGlowedReminders, _loadActiveHighlights, _saveActiveHighlights, _savePendingHighlights, _loadFiredReminders, _saveFiredReminders, _draftKey, _loadDraft, _clearDraft } = persistence;
+const clock = { now: () => Date.now() };
+const app = createNotesState({
+ viewMode: (typeof localStorage !== 'undefined' && localStorage.getItem('odysseus-notes-view')) || 'list',
+ labelsCollapsed: typeof localStorage !== 'undefined' && localStorage.getItem(NOTES_LABELS_COLLAPSED_KEY) === '1',
+ firedDotDismissedAt: (() => { try { const v = parseInt(persistence.getItem(REMINDER_DISMISSED_AT_KEY) || '0', 10); return Number.isFinite(v) && v > 0 ? v : 0; } catch { return 0; } })(),
+});
+const state = app.state;
+const lifecycle = createNotesLifecycle();
+const scheduler = { setTimeout: (...args) => setTimeout(...args), clearTimeout: id => clearTimeout(id), setInterval: (...args) => setInterval(...args), clearInterval: id => clearInterval(id) };
+const notifications = createNotesNotifications({ browser: window, notify: window.Notification, openPanel: () => openPanel(), toast: title => uiModule?.showToast?.(title) });
+const reminders = createNotesReminders({
+ app,
+ api,
+ persistence,
+ notifications,
+ clock,
+ scheduler,
+ fetchNotes: () => _fetchNotes(),
+ isNoteFullyDone: note => _isNoteFullyDone(note),
+ hasItems: note => _hasItems(note),
+ dismissedKey: REMINDER_DISMISSED_AT_KEY,
+ effects: { badge: () => _updateRailBadge(), highlight: id => {
+ _setReminderCardGlow(id, true);
+ const card = document.querySelector(`.note-card[data-note-id="${id}"]`);
+ if (card) { card.classList.add('note-card-reminder-fired'); setTimeout(() => card.classList.remove('note-card-reminder-fired'), 3000); }
+ else _queuePendingHighlight(id);
+} }
+});
+const workflows = createNotesWorkflows({
+ app,
+ api,
+ effects: {
+ render: () => _renderNotes(),
+ showError: (...args) => uiModule.showError(...args),
+ archived: undo => uiModule.showToast('Archived', { duration: 6000, action: 'Undo', actionIcon: _NOTE_UNDO_ICON, onAction: undo, actionHint: 'Ctrl+Z' }),
+ celebrateArchive: (note, card) => { if (_hasItems(note) && !(note.items || []).some(i => !i.done)) { const r = card.getBoundingClientRect(); spawnConfetti(r.left + r.width / 2, r.top + r.height / 2, 80); } },
+}
+});
+const _NOTE_UNDO_ICON = '';
+function _pushUndo(entry) { return workflows._pushUndo(entry); }
+function _popAndRunUndo() { return workflows._popAndRunUndo(); }
+function _undoArchive(note, prevIdx) { return workflows._undoArchive(note, prevIdx); }
+function _archiveNoteById(id, options) { return workflows._archiveNoteById(id, options); }
+function _fetchNotes() { return workflows._fetchNotes(); }
+
+function _deleteNoteApi(id) { return workflows._deleteNoteApi(id); }
+function _patchNote(id, patch) { return workflows._patchNote(id, patch); }
+function _uid() { return Math.random().toString(36).slice(2, 10); }
+function _formatDueDate(dateStr) { return dates._formatDueDate(dateStr, clock); }
+function _isDueOverdue(dateStr) { return dates._isDueOverdue(dateStr, clock); }
+
+function _laterTodayDate() { return dates._laterTodayDate(clock); }
+function _tomorrowDate() { return dates._tomorrowDate(clock); }
+function _nextWeekDate() { return dates._nextWeekDate(clock); }
+function _formatReminderTag(dateStr) { return dates._formatReminderTag(dateStr, clock); }
+function _snapToRepeat(currentDate, normRepeat) { return dates._snapToRepeat(currentDate, normRepeat, clock); }
+function _ensureNotificationPermission() { return notifications.ensurePermission(); }
+
+function _startReminderLoop() { return reminders._startReminderLoop(); }
+
+function _countFiredReminders() { return reminders._countFiredReminders(); }
+
+function _hasActiveReminder(...args) { return noteRules._hasActiveReminder(...args, clock); }
+const _isNoteFullyDone = noteRules._isNoteFullyDone;
+const _hasItems = noteRules._hasItems;
+function _isPastReminder(...args) { return noteRules._isPastReminder(...args, clock); }
+function _esc(...args) { return text._esc(...args); }
+
+function _safeImgSrc(...args) { return text._safeImgSrc(...args); }
+function _linkify(...args) { return text._linkify(...args); }
+function _isBgImage(...args) { return colors._isBgImage(...args); }
+
+function _dotBg(...args) { return colors._dotBg(...args); }
+function _dotIsActive(...args) { return colors._dotIsActive(...args); }
+function _customColorStyle(...args) { return colors._customColorStyle(...args); }
+function _pickCustomBgImage(...args) { return colors._pickCustomBgImage(...args); }
+function _wireFormColors(...args) { return colors._wireFormColors(...args); }
+
+function openPanel(...args) { return panel.openPanel(...args); }
+
+function _smoothScrollToNoteCard(...args) { return panel._smoothScrollToNoteCard(...args); }
+function _clearViewedReminderGlows(...args) { return reminderDisplay._clearViewedReminderGlows(...args); }
+function _setReminderCardGlow(...args) { return reminderDisplay._setReminderCardGlow(...args); }
+function _queuePendingHighlight(...args) { return reminderDisplay._queuePendingHighlight(...args); }
+function _flushPendingHighlights(...args) { return reminderDisplay._flushPendingHighlights(...args); }
+function _updateRailBadge(...args) { return reminderDisplay._updateRailBadge(...args); }
+function _enterSelectMode(...args) { return selection._enterSelectMode(...args); }
+function _exitSelectMode(...args) { return selection._exitSelectMode(...args); }
+function _updateBulkBar(...args) { return selection._updateBulkBar(...args); }
+
+function _renderLabelsInto(...args) { return filters._renderLabelsInto(...args); }
+function _renderLoadingSkeleton(...args) { return cardRendering._renderLoadingSkeleton(...args); }
+function _renderNotes(...args) { return cardRendering._renderNotes(...args); }
+function _captureCardPositions(...args) { return layout._captureCardPositions(...args); }
+function _animateReflow(...args) { return layout._animateReflow(...args); }
+function _applyMasonry(...args) { return layout._applyMasonry(...args); }
+function _renderQuickAdd(...args) { return quickAdd._renderQuickAdd(...args); }
+
+function _editNote(...args) { return quickAdd._editNote(...args); }
+function _bindCardEvents(...args) { return cardInteractions._bindCardEvents(...args); }
+function _wireCardChecklist(...args) { return cardChecklist._wireCardChecklist(...args); }
+function _wireTodayView(...args) { return cardChecklist._wireTodayView(...args); }
+function _wireCardReorder(...args) { return cardReorder._wireCardReorder(...args); }
+
+function _wireDraftAutosave(...args) { return draftEditor._wireDraftAutosave(...args); }
+function _commitOpenInPlaceEditor(...args) { return draftEditor._commitOpenInPlaceEditor(...args); }
+function _applyDraftToNote(...args) { return draftEditor._applyDraftToNote(...args); }
+function _buildForm(...args) { return editor._buildForm(...args); }
+function _wireReminderPicker(...args) { return reminderPicker._wireReminderPicker(...args); }
+function _buildGoalHtml(...args) { return checklist._buildGoalHtml(...args); }
+function _wireGoalForm(...args) { return checklist._wireGoalForm(...args); }
+function _buildChecklistHtml(...args) { return checklist._buildChecklistHtml(...args); }
+function _wireRow(...args) { return checklist._wireRow(...args); }
+function _wireChecklist(...args) { return checklist._wireChecklist(...args); }
+function _collectItems(...args) { return checklist._collectItems(...args); }
+function _buildDrawHtml(...args) { return drawing._buildDrawHtml(...args); }
+function _wireCanvas(...args) { return drawing._wireCanvas(...args); }
+function _uploadCanvasAsPng(...args) { return drawing._uploadCanvasAsPng(...args); }
+function _openNoteCornerMenu(...args) { return clipboard._openNoteCornerMenu(...args); }
+function _copyNote(...args) { return clipboard._copyNote(...args); }
+function _isNotesMobileMode(...args) { return mobileEditor._isNotesMobileMode(...args); }
+function _openMobileFullscreenEdit(...args) { return mobileEditor._openMobileFullscreenEdit(...args); }
+function _closeMobileFullscreenEdit(...args) { return mobileEditor._closeMobileFullscreenEdit(...args); }
+
+function _bindLongPressDrag(...args) { return mobileReorder._bindLongPressDrag(...args); }
+
+function _wireChecklistTouchReorder(...args) { return checklistReorder._wireChecklistTouchReorder(...args); }
+
+function _sortedVisibleNotes(...args) { return queries._sortedVisibleNotes(...args); }
+function _userVisibleNotes(...args) { return queries._userVisibleNotes(...args); }
+function _agentSolveNote(...args) { return agentActions._agentSolveNote(...args); }
+
+function _clearPastReminders(...args) { return deletion._clearPastReminders(...args); }
+const text = createText({
+ uiModule
+});
+const colors = createColors({
+ api
+});
+const { COLORS, COLOR_HEX } = colors;
+const windowLayout = createWindowLayout({
+ makeWindowDraggable,
+ snapModalToZone,
+ clearDockSide,
+ applyEdgeDock,
+ topToolWindowZ
+});
+const toolbar = createToolbar({
+ app,
+ state,
+ persistence,
+ _renderNotes,
+ _fetchNotes,
+ _applyMasonry
+});
+const panel = createPanel({
+ wireToolbar: toolbar.wireToolbar,
+ wireSelectionActions: () => selection.wireSelectionActions(),
+ _wireNotesWindow: windowLayout._wireNotesWindow,
+ _restoreNotesSidebarDock: windowLayout._restoreNotesSidebarDock,
+ _bringNotesToFront: windowLayout._bringNotesToFront,
+ disposeUI: () => { layout.dispose(); mobileReorder.dispose(); checklistReorder.dispose(); lifecycle.dispose(); },
+ lifecycle,
+ Modals,
+ NOTES_FIRST_OPEN_HINT_KEY,
+ REMINDER_DISMISSED_AT_KEY,
+ _clearViewedReminderGlows,
+ _closeMobileFullscreenEdit,
+ _commitOpenInPlaceEditor,
+ _copyNote,
+ _enterSelectMode,
+ _exitSelectMode,
+ _fetchNotes,
+ _flushPendingHighlights,
+ _isNotesMobileMode,
+ _popAndRunUndo,
+ _renderLoadingSkeleton,
+ _renderNotes,
+ _startReminderLoop,
+ app,
+ bindTourHintDismiss,
+ dismissOrRemove,
+ persistence,
+ state,
+ workflows
+});
+const reminderDisplay = createReminderDisplay({
+ _countFiredReminders,
+ _hasActiveReminder,
+ _loadActiveHighlights,
+ _loadGlowedReminders,
+ _loadPendingHighlights,
+ _saveActiveHighlights,
+ _saveGlowedReminders,
+ _savePendingHighlights,
+ _smoothScrollToNoteCard,
+ state
+});
+const selectionOperations = createSelectionOperations({
+ app,
+ api,
+ fetchNotes: _fetchNotes,
+ exitSelection: _exitSelectMode,
+ sendContext: detail => window.dispatchEvent(new CustomEvent('odysseus:notes-context-selected', { detail })),
+ effects: { render: _renderNotes, styledConfirm: uiModule.styledConfirm, showToast: (...args) => uiModule.showToast(...args) }
+});
+const selection = createSelection({
+ operations: selectionOperations,
+ _renderNotes,
+ app,
+ state
+});
+const filters = createFilters({
+ NOTES_LABELS_COLLAPSED_KEY,
+ _clearPastReminders,
+ _esc,
+ _isPastReminder,
+ _renderNotes,
+ _userVisibleNotes,
+ app,
+ persistence,
+ state
+});
+const cardRendering = createCardRendering({
+ COLORS,
+ COLOR_HEX,
+ _animateReflow,
+ _applyMasonry,
+ _bindCardEvents,
+ _captureCardPositions,
+ _customColorStyle,
+ _dotBg,
+ _dotIsActive,
+ _esc,
+ _formatDueDate,
+ _formatReminderTag,
+ _hasActiveReminder,
+ _isBgImage,
+ _isDueOverdue,
+ _isNotesMobileMode,
+ _linkify,
+ _loadActiveHighlights,
+ _renderLabelsInto,
+ _renderQuickAdd,
+ _safeImgSrc,
+ _sortedVisibleNotes,
+ _updateRailBadge,
+ _wireTodayView,
+ state,
+ uiModule
+});
+const layout = createLayout({
+ isOpen: () => state.open
+});
+const quickAdd = createQuickAdd({
+ _applyDraftToNote,
+ _applyMasonry,
+ _buildForm,
+ app,
+ openPanel,
+ state,
+ uiModule
+});
+const cardOperations = createCardOperations({
+ app,
+ api,
+ pushUndo: _pushUndo,
+ undoArchive: _undoArchive,
+ effects: { render: _renderNotes, showError: (...args) => uiModule.showError(...args), showToast: (...args) => uiModule.showToast(...args), archived: undo => uiModule.showToast('Archived', { duration: 6000, action: 'Undo', actionIcon: _NOTE_UNDO_ICON, onAction: undo, actionHint: 'Ctrl+Z' }) }
+});
+const checklistOperations = createChecklistOperations({
+ app,
+ api,
+ uid: _uid,
+ effects: { render: _renderNotes, showError: (...args) => uiModule.showError(...args) }
+});
+const cardInteractions = createCardInteractions({
+ cardOperations,
+ COLORS,
+ _archiveNoteById,
+ _bindLongPressDrag,
+ _customColorStyle,
+ _dotBg,
+ _dotIsActive,
+ _editNote,
+ _isBgImage,
+ _isNotesMobileMode,
+ _openMobileFullscreenEdit,
+ _openNoteCornerMenu,
+ _pickCustomBgImage,
+ _renderNotes,
+ _setReminderCardGlow,
+ _smoothScrollToNoteCard,
+ _updateBulkBar,
+ _wireCardChecklist,
+ _wireCardReorder,
+ app,
+ spawnConfetti,
+ state,
+ uiModule
+});
+const cardChecklist = createCardChecklist({
+ checklistOperations,
+ _editNote,
+ _renderNotes,
+ app,
+ spawnConfetti,
+ state
+});
+const cardReorder = createCardReorder({
+ persistOrder: cardOperations.persistOrder,
+ lifecycle,
+ _isNotesMobileMode,
+ state
+});
+const draftEditor = createDraftEditor({
+ bindDraft: (...args) => drafts.bindDraft(...args),
+ _collectItems,
+ _loadDraft
+});
+const editor = createEditor({
+ deleteFromEditor: id => deletion.deleteFromEditor(id),
+ submitNote: (...args) => submission.submitNote(...args),
+ COLORS,
+ _applyMasonry,
+ _archiveNoteById,
+ _buildChecklistHtml,
+ _buildDrawHtml,
+ _buildGoalHtml,
+ _collectItems,
+ _customColorStyle,
+ _dotBg,
+ _dotIsActive,
+ _esc,
+ _isBgImage,
+ _renderNotes,
+ _safeImgSrc,
+ _uid,
+ _uploadCanvasAsPng,
+ _wireCanvas,
+ _wireChecklist,
+ _wireDraftAutosave,
+ _wireFormColors,
+ _wireGoalForm,
+ _wireReminderPicker,
+ api,
+ app,
+ state,
+ uiModule
+});
+const reminderPicker = createReminderPicker({
+ lifecycle,
+ _ensureNotificationPermission,
+ _esc,
+ _formatReminderTag,
+ _laterTodayDate,
+ _nextWeekDate,
+ _snapToRepeat,
+ _tomorrowDate,
+ bindMenuDismiss,
+ dismissOrRemove
+});
+const checklist = createChecklist({
+ _esc,
+ _uid,
+ spawnConfetti
+});
+const drawing = createDrawing({
+ lifecycle,
+ _safeImgSrc,
+ api,
+ attachColorPicker
+});
+const clipboard = createClipboard({
+ _agentSolveNote,
+ bindMenuDismiss,
+ dismissOrRemove,
+ state,
+ topPortalZ,
+ uiModule
+});
+const mobileEditor = createMobileEditor({
+ _applyDraftToNote,
+ _buildForm,
+ _fetchNotes,
+ _linkify,
+ _renderNotes,
+ _uid,
+ _wireChecklistTouchReorder,
+ _wireRow,
+ app,
+ state,
+ uiModule
+});
+const mobileReorder = createMobileReorder({
+ commitMobileOrder: cardOperations.commitMobileOrder,
+ lifecycle,
+ _applyMasonry,
+ _enterSelectMode,
+ app
+});
+const checklistReorder = createChecklistReorder({
+ lifecycle
+});
+const queries = createQueries({
+ _hasActiveReminder,
+ state
+});
+const agentActions = createAgentActions({
+ _patchNote,
+ _renderNotes,
+ api,
+ app,
+ createFormData: () => new FormData(),
+ state,
+ streamComplete: sid => { try { window.sessionModule?.markStreamComplete?.(sid); } catch {} },
+ uiModule
+});
+const deletion = createDeletion({
+ app,
+ _deleteNoteApi,
+ _fetchNotes,
+ _isPastReminder,
+ _renderNotes,
+ effects: { styledConfirm: uiModule.styledConfirm, confirm: message => confirm(message), showToast: (...args) => uiModule.showToast(...args), showError: (...args) => uiModule.showError(...args) },
+ state
+});
+const notesModule = { openPanel: panel.openPanel, closePanel: panel.closePanel, togglePanel: panel.togglePanel, isPanelOpen: panel.isPanelOpen, openNote: panel.openNote, newNote: quickAdd.newNote, openNotes: panel.openPanel, closeNotes: panel.closePanel, isNotesOpen: panel.isPanelOpen, refreshDueBadge: reminders.refreshDueBadge };
+const publicOpenPanel = panel.openPanel, publicClosePanel = panel.closePanel, publicTogglePanel = panel.togglePanel, publicIsPanelOpen = panel.isPanelOpen, publicOpenNote = panel.openNote, publicNewNote = quickAdd.newNote, publicRefreshDueBadge = reminders.refreshDueBadge, publicDismissFiredReminderDot = reminders.dismissFiredReminderDot;
+export { publicOpenPanel as openPanel, publicClosePanel as closePanel, publicTogglePanel as togglePanel, publicIsPanelOpen as isPanelOpen, publicOpenNote as openNote, publicNewNote as newNote, publicRefreshDueBadge as refreshDueBadge, publicDismissFiredReminderDot as dismissFiredReminderDot, publicOpenPanel as openNotes, publicClosePanel as closeNotes, publicIsPanelOpen as isNotesOpen };
+export function startNotesBackground() { reminders.start(); }
+export default notesModule;
+const submission = createNotesSubmission({
+ app,
+ api,
+ persistence,
+ clock,
+ uid: _uid,
+ fetchNotes: _fetchNotes,
+ effects: { render: _renderNotes, showError: (...args) => uiModule.showError(...args), clearGlow: id => _setReminderCardGlow(id, false) }
+});
+const drafts = createNotesDrafts({
+ app,
+ api,
+ persistence,
+ scheduler,
+ effects: { showError: (...args) => uiModule.showError(...args) }
+});
diff --git a/frontend/src/features/notes/infrastructure/http.js b/frontend/src/features/notes/infrastructure/http.js
new file mode 100644
index 000000000..eeafd1b0f
--- /dev/null
+++ b/frontend/src/features/notes/infrastructure/http.js
@@ -0,0 +1,29 @@
+/** Notes HTTP port. Response interpretation stays with the owning workflow. */
+export function createNotesApi({ origin, request }) {
+ const json = (method, body) => ({ method, credentials: 'same-origin', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) });
+ async function saveNote(note) {
+ const response = await request(note.id ? `${origin}/api/notes/${note.id}` : `${origin}/api/notes`, json(note.id ? 'PUT' : 'POST', note));
+ if (!response.ok) throw new Error('Failed to save note');
+ return await response.json();
+ }
+ async function patchNote(id, patch) {
+ const response = await request(`${origin}/api/notes/${id}`, json('PUT', patch));
+ if (!response.ok) throw new Error('Failed to update note');
+ return await response.json();
+ }
+ async function deleteNote(id) {
+ const response = await request(`${origin}/api/notes/${id}`, { method: 'DELETE', credentials: 'same-origin' });
+ if (!response.ok) throw new Error('HTTP ' + response.status);
+ }
+ return {
+ saveNote, patchNote, deleteNote,
+ listNotes: archived => request(`${origin}/api/notes${archived ? '?archived=true' : ''}`, { credentials: 'same-origin' }),
+ reorder: ids => request(`${origin}/api/notes/reorder`, json('POST', { ids })),
+ upload: body => request(`${origin}/api/upload`, { method: 'POST', body, credentials: 'same-origin' }),
+ uploadUrl: id => `${origin}/api/upload/${id}`,
+ fireReminder: body => request('/api/notes/fire-reminder', json('POST', body)),
+ defaultChat: () => request(`${origin}/api/default-chat`, { credentials: 'same-origin' }),
+ createSession: body => request(`${origin}/api/session`, { method: 'POST', body, credentials: 'same-origin' }),
+ startChat: body => request(`${origin}/api/chat_stream`, { method: 'POST', body, credentials: 'same-origin' }),
+ };
+}
diff --git a/frontend/src/features/notes/infrastructure/notifications.js b/frontend/src/features/notes/infrastructure/notifications.js
new file mode 100644
index 000000000..cd98eb702
--- /dev/null
+++ b/frontend/src/features/notes/infrastructure/notifications.js
@@ -0,0 +1,20 @@
+/** Browser notification permission/display port, independent of Notes rendering. */
+export function createNotesNotifications({ browser, notify, openPanel, toast }) {
+ async function ensurePermission() {
+ if (!('Notification' in browser)) return false;
+ if (notify.permission === 'granted') return true;
+ if (notify.permission === 'denied') return false;
+ try { return await notify.requestPermission() === 'granted'; }
+ catch { return false; }
+ }
+ function show(title, body, noteId) {
+ if ('Notification' in browser && notify.permission === 'granted') {
+ try {
+ const notification = new notify(title, { body, tag: 'note-' + noteId, icon: '/static/favicon.ico' });
+ notification.onclick = () => { browser.focus(); openPanel(); notification.close(); };
+ } catch {}
+ }
+ toast(title);
+ }
+ return { ensurePermission, show };
+}
diff --git a/frontend/src/features/notes/infrastructure/storage.js b/frontend/src/features/notes/infrastructure/storage.js
new file mode 100644
index 000000000..06aaa01ab
--- /dev/null
+++ b/frontend/src/features/notes/infrastructure/storage.js
@@ -0,0 +1,63 @@
+/** Browser persistence and unchanged Notes key/serialization contracts. */
+export const REMINDER_FIRED_KEY = 'odysseus-notes-reminder-fired';
+export const REMINDER_GLOWED_KEY = 'odysseus-notes-reminder-glowed';
+export const REMINDER_PENDING_HIGHLIGHT_KEY = 'odysseus-notes-reminder-pending-highlight';
+export const REMINDER_ACTIVE_HIGHLIGHT_KEY = 'odysseus-notes-reminder-active-highlight';
+export const REMINDER_DISMISSED_AT_KEY = 'odysseus-notes-reminder-dismissed-at';
+export const NOTES_FIRST_OPEN_HINT_KEY = 'odysseus-notes-first-open-hint-v1';
+export const NOTES_LABELS_COLLAPSED_KEY = 'odysseus-notes-labels-collapsed';
+export const _DRAFT_PREFIX = 'odysseus-note-draft-';
+
+export function createNotesPersistence({ storage: localStorage }) {
+function _loadPendingHighlights() {
+ try { return new Set(JSON.parse(localStorage.getItem(REMINDER_PENDING_HIGHLIGHT_KEY) || '[]')); }
+ catch { return new Set(); }
+}
+
+function _loadGlowedReminders() {
+ try { return new Set(JSON.parse(localStorage.getItem(REMINDER_GLOWED_KEY) || '[]')); }
+ catch { return new Set(); }
+}
+
+function _saveGlowedReminders(set) {
+ try { localStorage.setItem(REMINDER_GLOWED_KEY, JSON.stringify([...set])); } catch {}
+}
+
+function _loadActiveHighlights() {
+ try { return new Set(JSON.parse(localStorage.getItem(REMINDER_ACTIVE_HIGHLIGHT_KEY) || '[]')); }
+ catch { return new Set(); }
+}
+
+function _saveActiveHighlights(set) {
+ try { localStorage.setItem(REMINDER_ACTIVE_HIGHLIGHT_KEY, JSON.stringify([...set])); } catch {}
+}
+
+function _savePendingHighlights(set) {
+ try { localStorage.setItem(REMINDER_PENDING_HIGHLIGHT_KEY, JSON.stringify([...set])); }
+ catch {}
+}
+
+function _loadFiredReminders() {
+ try { return new Set(JSON.parse(localStorage.getItem(REMINDER_FIRED_KEY) || '[]')); }
+ catch { return new Set(); }
+}
+
+function _saveFiredReminders(set) {
+ try { localStorage.setItem(REMINDER_FIRED_KEY, JSON.stringify([...set])); }
+ catch {}
+}
+
+function _draftKey(id) { return _DRAFT_PREFIX + (id || '__new__'); }
+
+function _loadDraft(id) {
+ try { return JSON.parse(localStorage.getItem(_draftKey(id)) || 'null'); } catch { return null; }
+}
+
+function _clearDraft(id) { try { localStorage.removeItem(_draftKey(id)); } catch {} }
+
+return { _loadPendingHighlights, _loadGlowedReminders, _saveGlowedReminders, _loadActiveHighlights, _saveActiveHighlights, _savePendingHighlights, _loadFiredReminders, _saveFiredReminders, _draftKey, _loadDraft, _clearDraft,
+ getItem: key => localStorage.getItem(key),
+ setItem: (key, value) => localStorage.setItem(key, value),
+ removeItem: key => localStorage.removeItem(key),
+};
+}
diff --git a/frontend/src/features/notes/ui/cardChecklist.js b/frontend/src/features/notes/ui/cardChecklist.js
new file mode 100644
index 000000000..6bbf39326
--- /dev/null
+++ b/frontend/src/features/notes/ui/cardChecklist.js
@@ -0,0 +1,148 @@
+/** Card checklist editing and Today-step interactions. */
+export function createCardChecklist({
+ checklistOperations,
+ _editNote,
+ _renderNotes,
+ app,
+ spawnConfetti,
+ state
+}) {
+ function _wireCardChecklist(body) {
+ // Remove a single checklist item (hover X)
+ body.querySelectorAll('.note-checkbox-rm').forEach(btn => {
+ btn.addEventListener('click', (e) => {
+ e.stopPropagation();
+ if (state.selectMode) return;
+ const noteId = btn.dataset.noteId;
+ const idx = parseInt(btn.dataset.idx);
+ checklistOperations.removeItem(noteId, idx);
+ });
+ });
+
+ function _startChecklistItemEdit(noteId, idx, span) {
+ if (span.isContentEditable) return;
+ const note = state.notes.find(n => n.id === noteId);
+ if (!note || !Array.isArray(note.items) || !note.items[idx]) return;
+
+ span.textContent = note.items[idx].text || '';
+ span.contentEditable = "true";
+ span.spellcheck = false;
+ span.focus();
+
+ const selection = window.getSelection();
+ const range = document.createRange();
+ range.selectNodeContents(span);
+ selection.removeAllRanges();
+ selection.addRange(range);
+
+ const save = () => {
+ if (!span.isContentEditable) return;
+ span.contentEditable = "false";
+ const newText = span.textContent.trim();
+ checklistOperations.editItem(note, idx, newText);
+ };
+
+ const onKeydown = (e) => {
+ if (e.key === 'Enter') {
+ e.preventDefault();
+ save();
+ } else if (e.key === 'Escape') {
+ e.preventDefault();
+ span.contentEditable = "false";
+ _renderNotes();
+ }
+ };
+
+ span.addEventListener('blur', save, { once: true });
+ span.addEventListener('keydown', onKeydown);
+ }
+
+ // Edit a single checklist item (hover Edit button)
+ body.querySelectorAll('.note-checkbox-edit').forEach(btn => {
+ btn.addEventListener('click', (e) => {
+ e.stopPropagation();
+ if (state.selectMode) return;
+ const noteId = btn.dataset.noteId;
+ const idx = parseInt(btn.dataset.idx);
+ const span = btn.parentElement.querySelector('.note-check-text');
+ if (span) _startChecklistItemEdit(noteId, idx, span);
+ });
+ });
+
+ // Prevent clicks from toggling the row while actively editing inline
+ body.querySelectorAll('.note-check-text').forEach(span => {
+ span.addEventListener('click', (e) => {
+ if (span.isContentEditable) {
+ e.stopPropagation();
+ }
+ });
+ });
+
+ // Quick-add new checklist item (hover input at bottom of todo cards)
+ body.querySelectorAll('.note-cl-quickadd-input').forEach(input => {
+ input.addEventListener('click', (e) => e.stopPropagation());
+ input.addEventListener('keydown', async (e) => {
+ e.stopPropagation();
+ if (e.key !== 'Enter') return;
+ e.preventDefault();
+ const text = input.value.trim();
+ if (!text) return;
+ const noteId = input.dataset.noteId;
+ const persist = checklistOperations.addItem(noteId, text, () => { input.value = ''; });
+ if (!persist) return;
+ // Refocus the input on the same card
+ setTimeout(() => {
+ const next = document.querySelector(`.note-cl-quickadd-input[data-note-id="${noteId}"]`);
+ if (next) next.focus();
+ }, 0);
+ persist();
+ });
+ });
+
+ // Checkboxes (dot toggle, optimistic) : disabled in select mode
+ body.querySelectorAll('.note-checkbox').forEach(el => {
+ el.addEventListener('click', (e) => {
+ if (state.selectMode) return; // let card-level handler take over
+ e.preventDefault();
+ e.stopPropagation();
+ const noteId = el.dataset.noteId;
+ const idx = parseInt(el.dataset.idx);
+ checklistOperations.toggleItem(noteId, idx, done => el.classList.toggle('done', done), () => {
+ const card = el.closest('.note-card');
+ if (card) { const r = card.getBoundingClientRect(); spawnConfetti(r.left + r.width / 2, r.top + r.height / 2, 60); }
+ });
+ });
+ });
+
+
+ }
+
+ function _wireTodayView(body) {
+ body.querySelectorAll('.notes-today-row .note-check-dot').forEach(dot => {
+ dot.addEventListener('click', async (e) => {
+ e.stopPropagation();
+ const id = dot.dataset.noteId;
+ const idx = parseInt(dot.dataset.idx);
+ const row = dot.closest('.notes-today-row');
+ await checklistOperations.toggleTodayStep(id, idx, () => row?.classList.add('done'), () => {
+ const r = (row || dot).getBoundingClientRect();
+ spawnConfetti(r.left + r.width / 2, r.top + r.height / 2, 60);
+ });
+ });
+ });
+ body.querySelectorAll('.notes-today-title').forEach(el => {
+ el.addEventListener('click', () => {
+ const id = el.dataset.noteId;
+ if (!id) return;
+ // Drop the Today filter first so the regular card list is rendered;
+ // _editNote needs to find a .note-card in the DOM to replace with
+ // the editor form.
+ app.setActiveFilter(null);
+ _renderNotes();
+ _editNote(id);
+ });
+ });
+ }
+
+ return { _wireCardChecklist, _wireTodayView };
+}
diff --git a/frontend/src/features/notes/ui/cardInteractions.js b/frontend/src/features/notes/ui/cardInteractions.js
new file mode 100644
index 000000000..09e083c41
--- /dev/null
+++ b/frontend/src/features/notes/ui/cardInteractions.js
@@ -0,0 +1,337 @@
+/** Card taps, pin/color controls, menus and archive animation. */
+export function createCardInteractions({
+ cardOperations,
+ COLORS,
+ _archiveNoteById,
+ _bindLongPressDrag,
+ _customColorStyle,
+ _dotBg,
+ _dotIsActive,
+ _editNote,
+ _isBgImage,
+ _isNotesMobileMode,
+ _openMobileFullscreenEdit,
+ _openNoteCornerMenu,
+ _pickCustomBgImage,
+ _renderNotes,
+ _setReminderCardGlow,
+ _smoothScrollToNoteCard,
+ _updateBulkBar,
+ _wireCardChecklist,
+ _wireCardReorder,
+ app,
+ spawnConfetti,
+ state,
+ uiModule
+}) {
+ function _bindCardEvents(body) {
+ // Skip completed leading rows so the first unfinished checklist item is
+ // visible when a note preview has its own scroll area.
+ requestAnimationFrame(() => {
+ body.querySelectorAll('.note-checklist-preview').forEach(preview => {
+ const firstPending = preview.querySelector('.note-checkbox:not(.done)');
+ if (firstPending) preview.scrollTop = Math.max(0, firstPending.offsetTop - 4);
+ });
+ });
+ const tapToEditOrSelect = (cardEl) => {
+ const id = cardEl.dataset.noteId;
+ // A long-press enters select mode and re-renders the card. Ignore the
+ // synthetic click that mobile browsers emit when that same touch ends.
+ if (state.suppressNextNoteTapId === id) {
+ app.setSuppressNextNoteTapId(null);
+ return;
+ }
+ if (state.selectMode) {
+ const cb = cardEl.querySelector('.note-card-cb');
+ if (cb) {
+ cb.checked = !cb.checked;
+ cb.dispatchEvent(new Event('change'));
+ }
+ } else if (_isNotesMobileMode()) {
+ // Mobile: open the per-note fullscreen edit overlay instead of the
+ // in-place form. Tiles on mobile are read-only previews.
+ _openMobileFullscreenEdit(id, cardEl);
+ } else {
+ _editNote(id);
+ }
+ };
+ // Mobile: long-press anywhere on a note card → enter Select mode and
+ // select that card. Cancelled by movement (so it doesn't interfere with
+ // vertical scrolling) or by lifting the finger before the timer fires.
+ if (_isNotesMobileMode()) {
+ body.querySelectorAll('.note-card').forEach(card => _bindLongPressDrag(card));
+ }
+ body.querySelectorAll('.note-card.note-card-reminder-fired-sticky').forEach(card => {
+ card.addEventListener('click', () => _setReminderCardGlow(card.dataset.noteId, false), true);
+ });
+ // Click title : edit, or toggle select in select mode
+ body.querySelectorAll('.note-card-title[data-action="edit"]').forEach(el => {
+ el.addEventListener('click', (e) => {
+ e.stopPropagation();
+ _smoothScrollToNoteCard(el.closest('.note-card'));
+ tapToEditOrSelect(el.closest('.note-card'));
+ });
+ });
+ // Click content : edit, or toggle select in select mode
+ body.querySelectorAll('.note-content-preview').forEach(el => {
+ el.addEventListener('click', (e) => { e.stopPropagation(); tapToEditOrSelect(el.closest('.note-card')); });
+ });
+ // A saved drawing is the note's primary content. Open its editor directly
+ // when the preview is clicked, matching title/content preview behavior.
+ body.querySelectorAll('.note-card-drawing .note-card-image').forEach(el => {
+ el.addEventListener('click', (e) => {
+ e.stopPropagation();
+ tapToEditOrSelect(el.closest('.note-card'));
+ });
+ });
+ // Click empty area of checklist preview (not on checkbox/X) : edit
+ body.querySelectorAll('.note-checklist-preview').forEach(el => {
+ el.addEventListener('wheel', (e) => {
+ const atTop = el.scrollTop <= 0;
+ const atBottom = el.scrollTop + el.clientHeight >= el.scrollHeight - 1;
+ if ((e.deltaY < 0 && atTop) || (e.deltaY > 0 && atBottom)) {
+ const pane = el.closest('.notes-pane-body');
+ if (pane) {
+ pane.scrollTop += e.deltaY;
+ e.preventDefault();
+ }
+ }
+ }, { passive: false });
+ el.addEventListener('click', (e) => {
+ if (e.target.closest('.note-checkbox, .note-checkbox-rm, .note-cl-quickadd, input')) return;
+ e.stopPropagation();
+ tapToEditOrSelect(el.closest('.note-card'));
+ });
+ });
+ // Clicking todo item text now toggles its checkbox : let the click bubble
+ // up to the parent .note-checkbox row handler. To open the editor, the
+ // user clicks the pencil corner.
+ // (No-op block kept as a marker : removing the listener entirely means
+ // clicks naturally bubble to the row toggle below.)
+ // In select mode, clicking anywhere on the card toggles selection
+ if (state.selectMode) {
+ body.querySelectorAll('.note-card').forEach(card => {
+ card.addEventListener('click', (e) => {
+ if (e.target.closest('.note-card-cb')) return; // checkbox handles itself
+ e.stopPropagation();
+ tapToEditOrSelect(card);
+ });
+ });
+ }
+ // Mobile, non-select: tapping anywhere on the card body (not on an
+ // interactive child : buttons, pin, checkbox, color dot, reminder pill,
+ // agent tag, links) opens the fullscreen editor. Previously only the
+ // title / content preview triggered edit, so padding + empty gutters were
+ // dead zones that felt broken on mobile.
+ if (_isNotesMobileMode() && !state.selectMode) {
+ const _INTERACTIVE = 'button, a, input, label, .note-card-color-dot, .note-checkbox, .note-checkbox-rm, .note-cl-quickadd, .note-agent-tag, .note-card-pin, .note-card-corner-trash, .note-card-corner-menu, .note-card-corner-unarchive, .note-card-edit-corner, .note-card-reminder, .note-card-cb';
+ body.querySelectorAll('.note-card').forEach(card => {
+ card.addEventListener('click', (e) => {
+ if (e.target.closest(_INTERACTIVE)) return;
+ e.stopPropagation();
+ tapToEditOrSelect(card);
+ });
+ });
+ }
+ // Multi-select checkbox (only in select mode)
+ body.querySelectorAll('.note-card-cb').forEach(cb => {
+ cb.addEventListener('click', (e) => e.stopPropagation());
+ cb.addEventListener('change', () => {
+ const id = cb.dataset.noteId;
+ if (cb.checked) app.selectId(id);
+ else app.deselectId(id);
+ cb.closest('.note-card').classList.toggle('note-card-selected', cb.checked);
+ _updateBulkBar();
+ });
+ });
+ // Pin toggle (optimistic)
+ body.querySelectorAll('.note-card-pin').forEach(btn => {
+ btn.addEventListener('click', (e) => {
+ e.stopPropagation();
+ const id = btn.dataset.noteId;
+ cardOperations.togglePin(id);
+ });
+ });
+ // Color picker
+ const _applyCardColor = async (card, id, newColor) => {
+ const isBg = _isBgImage(newColor);
+ COLORS.forEach(c => { if (c.value && c.value !== 'custom') card.classList.remove('note-color-' + c.value); });
+ if (newColor && !isBg) card.classList.add('note-color-' + newColor);
+ if (isBg) card.setAttribute('style', _customColorStyle(newColor));
+ else card.removeAttribute('style');
+ card.querySelectorAll('.note-card-color-dot').forEach(d => {
+ d.classList.toggle('active', _dotIsActive(d.dataset.color, newColor));
+ d.style.background = _dotBg(d.dataset.color, newColor);
+ });
+ await cardOperations.updateColor(id, newColor);
+ };
+ body.querySelectorAll('.note-card-color-dot').forEach(dot => {
+ dot.addEventListener('click', (e) => {
+ e.stopPropagation();
+ const card = dot.closest('.note-card');
+ const id = card.dataset.noteId;
+ if (dot.dataset.color === 'custom') {
+ _pickCustomBgImage().then(url => { if (url) _applyCardColor(card, id, 'bg:' + url); });
+ return;
+ }
+ _applyCardColor(card, id, dot.dataset.color);
+ });
+ });
+ // Plain pencil corner → open editor. The unarchive corner shares the
+ // .note-card-edit-corner class for styling, so :not() keeps the edit
+ // handler off it.
+ body.querySelectorAll('.note-card-edit-corner:not(.note-card-unarchive-corner)').forEach(btn => {
+ btn.addEventListener('click', (e) => {
+ e.stopPropagation();
+ const id = btn.dataset.noteId;
+ if (id) _editNote(id);
+ });
+ });
+ // Copy corner : bottom-right, just left of the Done check. Shared with
+ // the Ctrl/Cmd+C shortcut wired further down so both code paths run the
+ // same serializer + feedback flash.
+ // ⋯ corner menu : Copy + Agent (solve-this-todo).
+ body.querySelectorAll('.note-card-corner-menu').forEach(btn => {
+ btn.addEventListener('click', (e) => {
+ e.preventDefault();
+ e.stopPropagation();
+ _openNoteCornerMenu(btn);
+ });
+ });
+ body.querySelectorAll('.note-card-label-chip').forEach(chip => {
+ chip.addEventListener('click', (e) => {
+ e.preventDefault();
+ e.stopPropagation();
+ const label = chip.dataset.noteLabelFilter;
+ if (!label) return;
+ if (state.activeLabel === label && state.activeFilter === null) {
+ app.setActiveLabel(null);
+ } else {
+ app.setActiveFilter(null);
+ app.setActiveLabel(label);
+ }
+ _renderNotes();
+ });
+ });
+ // Done (✓) at bottom-right : only visible on hover for active notes.
+ body.querySelectorAll('.note-card-done').forEach(btn => {
+ btn.addEventListener('click', (e) => {
+ e.stopPropagation();
+ const id = btn.dataset.noteId;
+ const card = btn.closest('.note-card');
+ const idx = state.notes.findIndex(n => n.id === id);
+ if (idx < 0) return;
+ // Celebrate completion : same confetti shower the bulk-archive uses.
+ if (card) {
+ const r = card.getBoundingClientRect();
+ spawnConfetti(r.left + r.width / 2, r.top + r.height / 2, 80);
+ }
+ const finish = cardOperations.stageArchive(id);
+ if (!finish) return;
+ if (card) {
+ card.classList.add('note-card-sliding-out');
+ let done = false;
+ const once = () => { if (done) return; done = true; finish(); };
+ card.addEventListener('transitionend', once, { once: true });
+ setTimeout(once, 400);
+ } else {
+ finish();
+ }
+ });
+ });
+ // Unarchive corner : only visible in archive view.
+ body.querySelectorAll('.note-card-corner-unarchive').forEach(btn => {
+ btn.addEventListener('click', (e) => {
+ e.stopPropagation();
+ const id = btn.dataset.noteId;
+ cardOperations.unarchive(id);
+ });
+ });
+ // Trash corner : archive view only. Permanent delete, no confirmation.
+ body.querySelectorAll('.note-card-corner-trash').forEach(btn => {
+ btn.addEventListener('click', (e) => {
+ e.stopPropagation();
+ const id = btn.dataset.noteId;
+ cardOperations.deleteOptimistically(id, true);
+ });
+ });
+
+ body.querySelectorAll('.note-card-archive').forEach(btn => {
+ btn.addEventListener('click', (e) => {
+ e.stopPropagation();
+ const id = btn.dataset.noteId;
+ if (!id) return;
+ const card = btn.closest('.note-card');
+ let done = false;
+ const finishRemove = () => {
+ if (done) return;
+ done = true;
+ _archiveNoteById(id, { card, celebrate: true });
+ };
+ if (card) {
+ card.classList.add('note-card-sliding-out');
+ card.addEventListener('transitionend', finishRemove, { once: true });
+ setTimeout(finishRemove, 400);
+ } else {
+ finishRemove();
+ }
+ });
+ });
+ // Unarchive (optimistic) : only present in archive view
+ body.querySelectorAll('.note-card-unarchive').forEach(btn => {
+ btn.addEventListener('click', (e) => {
+ e.stopPropagation();
+ const id = btn.dataset.noteId;
+ cardOperations.unarchive(id);
+ });
+ });
+ // Delete (optimistic)
+ body.querySelectorAll('.note-card-delete, .note-card-x').forEach(btn => {
+ btn.addEventListener('click', (e) => {
+ e.stopPropagation();
+ const id = btn.dataset.noteId;
+ cardOperations.deleteOptimistically(id);
+ });
+ });
+ // Copy entire checklist (title + items, markdown-style)
+ body.querySelectorAll('.note-card-copy').forEach(btn => {
+ btn.addEventListener('click', async (e) => {
+ e.preventDefault();
+ e.stopPropagation();
+ e.stopImmediatePropagation();
+ const id = btn.dataset.noteId;
+ const note = state.notes.find(n => n.id === id);
+ if (!note) return;
+ const lines = [];
+ if (note.title) lines.push(note.title);
+ if (note.content) lines.push(note.content);
+ if (lines.length) lines.push('');
+ for (const it of (note.items || [])) {
+ if (!it || !(it.text || '').trim()) continue;
+ lines.push(`- [${it.done ? 'x' : ' '}] ${(it.text || '').trim()}`);
+ }
+ const text = lines.join('\n').trim();
+ try {
+ await navigator.clipboard.writeText(text);
+ uiModule.showToast?.(`Copied ${(note.items || []).filter(i => (i?.text || '').trim()).length} items`);
+ } catch {
+ // Fallback for browsers blocking the async API
+ const ta = document.createElement('textarea');
+ ta.value = text;
+ ta.style.position = 'fixed'; ta.style.left = '-9999px';
+ document.body.appendChild(ta);
+ ta.select();
+ try { document.execCommand('copy'); uiModule.showToast?.('Copied'); }
+ catch { uiModule.showError?.('Copy failed'); }
+ ta.remove();
+ }
+ });
+ });
+
+ _wireCardChecklist(body);
+ _wireCardReorder(body);
+
+ }
+
+ return { _bindCardEvents };
+}
diff --git a/frontend/src/features/notes/ui/cardRendering.js b/frontend/src/features/notes/ui/cardRendering.js
new file mode 100644
index 000000000..315e47218
--- /dev/null
+++ b/frontend/src/features/notes/ui/cardRendering.js
@@ -0,0 +1,244 @@
+/** Render note cards from application queries and read-only state. */
+import { _nextGoalStep, _goalProgress, _hasItems, _standardVisualVariant, _visibleNoteTags } from '../domain/noteRules.js';
+import { _hasTimeComponent, _formatRepeatLabel } from '../domain/recurrence.js';
+export function createCardRendering({
+ COLORS,
+ COLOR_HEX,
+ _animateReflow,
+ _applyMasonry,
+ _bindCardEvents,
+ _captureCardPositions,
+ _customColorStyle,
+ _dotBg,
+ _dotIsActive,
+ _esc,
+ _formatDueDate,
+ _formatReminderTag,
+ _hasActiveReminder,
+ _isBgImage,
+ _isDueOverdue,
+ _isNotesMobileMode,
+ _linkify,
+ _loadActiveHighlights,
+ _renderLabelsInto,
+ _renderQuickAdd,
+ _safeImgSrc,
+ _sortedVisibleNotes,
+ _updateRailBadge,
+ _wireTodayView,
+ state,
+ uiModule
+}) {
+ function _renderLoadingSkeleton() {
+ const body = document.querySelector('#notes-pane .notes-pane-body');
+ if (!body) return;
+ body.innerHTML = '';
+ _renderLabelsInto(body);
+ _renderQuickAdd(body);
+ const skel = document.createElement('div');
+ skel.className = 'notes-skeleton';
+ skel.innerHTML = `
+
+
+
+
+ `;
+ body.appendChild(skel);
+ }
+
+ function _renderNotes() {
+ _updateRailBadge();
+ const body = document.querySelector('#notes-pane .notes-pane-body');
+ if (!body) return;
+ const prevPositions = _captureCardPositions();
+ const activeReminderHighlights = _loadActiveHighlights();
+
+ const sorted = _sortedVisibleNotes();
+
+ let html = '';
+ // Today view: render a compact card listing the next-unchecked step from
+ // each active goal. Tapping a step toggles it done (same idx-based wiring
+ // as regular checkboxes). Tapping the title opens the goal note for full
+ // editing.
+ if (state.activeFilter === 'today') {
+ body.innerHTML = '';
+ _renderLabelsInto(body);
+ _renderQuickAdd(body);
+ if (sorted.length === 0) {
+ body.insertAdjacentHTML('beforeend', `
All caught up — no pending goal steps right now.
`);
+ } else {
+ let todayHtml = `
+
+
+ Today · one step per goal
+
+
`;
+ for (const note of sorted) {
+ const next = _nextGoalStep(note);
+ if (!next) continue;
+ const progress = _goalProgress(note).trim();
+ todayHtml += `
+
+
+
${_esc(note.title || '(untitled goal)')}
+
${_linkify(next.item.text || '')}
+
+ ${_esc(progress)}
+
`;
+ }
+ todayHtml += `
`;
+ body.insertAdjacentHTML('beforeend', todayHtml);
+ }
+ _wireTodayView(body);
+ return;
+ }
+ for (const note of sorted) {
+ if (state.editingId === note.id) continue; // skip : form is shown instead
+ const borderColor = COLOR_HEX[note.color || ''] || 'var(--border)';
+ const dueFmt = _formatDueDate(note.due_date);
+ const overdue = _isDueOverdue(note.due_date);
+
+ let contentHtml = '';
+ if (_hasItems(note) && Array.isArray(note.items)) {
+ // Goal notes can carry a free-form description above the step list :
+ // todos rarely do, but the same render works for both.
+ if (note.note_type === 'goal' && (note.content || '').trim()) {
+ const fullText = note.content || '';
+ const preview = fullText.length > 300 ? fullText.slice(0, 300) + '…' : fullText;
+ contentHtml += `
${_esc(preview)}
`;
+ }
+ contentHtml += '
';
+ // Show ALL items : the preview container is scrollable (CSS caps
+ // its max-height + overflow-y:auto), so there's no need to truncate.
+ for (let i = 0; i < note.items.length; i++) {
+ const item = note.items[i];
+ const doneClass = item.done ? ' done' : '';
+ const indent = Math.min(item.indent || 0, 3);
+ contentHtml += `
+
+ ${_linkify(item.text)}
+
+
+
`;
+ }
+ contentHtml += '
';
+ } else {
+ const fullText = note.content || '';
+ const preview = fullText.length > 600 ? fullText.slice(0, 600) + '…' : fullText;
+ // _linkify already calls _esc internally, so URLs become clickable
+ // anchors (used by e.g. the "remind me to reply" email deep-link).
+ contentHtml = preview ? `