From f2b9ba922f4e244a2056f57a4dda91c17550a307 Mon Sep 17 00:00:00 2001 From: Eric Law <39393654+acn-ericlaw@users.noreply.github.com> Date: Fri, 20 Nov 2026 15:56:20 +0800 Subject: [PATCH 1/2] feat(host): static web content from resources/public - the engines' static.html.folder, served for the paths nothing else claims The host serves the files of static.html.folder (the Java engine's key) from resources/public next to the application file by default (the Rust engine's location, under the packs' resources rule) for any GET or HEAD that no host path, extension route or function claims: index.html for a folder, so a folder's index.html replaces the embedded landing page at /; the content type by extension from the engines' table; an ETag with 304 on If-None-Match; Cache-Control: no-cache for HTML; a hidden segment, a symbolic link out of the folder or anything that is not a regular file not found, in the engines' error shape. AppConfig.app_dir names the application file's folder. Docs, README and CHANGELOG updated; the 2026-08-24 "no static file service" note withdrawn. Co-Authored-By: Claude Fable 5.1 --- CHANGELOG.md | 16 ++ README.md | 18 +- docs/guides/config-logging-actuators.md | 19 +- docs/guides/configuration-reference.md | 1 + docs/guides/http-surface-reference.md | 12 +- src/mercury_composable/actuator.py | 4 +- src/mercury_composable/config.py | 8 + src/mercury_composable/server.py | 29 ++- src/mercury_composable/static_content.py | 147 +++++++++++++++ tests/test_config.py | 13 ++ tests/test_static_content.py | 231 +++++++++++++++++++++++ 11 files changed, 485 insertions(+), 13 deletions(-) create mode 100644 src/mercury_composable/static_content.py create mode 100644 tests/test_static_content.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 1a6fb52..2be7060 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -136,6 +136,22 @@ mode, the PostgreSQL statements on a recording fake, the hooks and the boot; a live PostgreSQL gated on `AGENT_QUESTION_TEST_URL`). **Upgrade note:** none - a new application; the main flow lists it in `ask.channels`. +7. **Static web content: the host serves the files of `static.html.folder` - the Java engine's key, with the Rust + engine's location as its default, `resources/public` next to the application file (Eric, 2026-11-20).** A `GET` or + `HEAD` that no host path, extension route or function claims is answered with the file the path names inside the + folder, `index.html` for a folder, so a folder's `index.html` replaces the embedded landing page at `/` while + `/info`, `/health` and the other host paths stay the host's. The content type comes from the engines' table by + extension (`text/javascript`, `text/css`, `image/svg+xml`, the fonts and images a bundle ships; + `application/octet-stream` otherwise); every file carries an ETag and answers `If-None-Match` with 304, and + `text/html` is served `Cache-Control: no-cache`, so a redeployed page is revalidated while hashed assets stay + cached. A path with a hidden segment (one starting with `.`, so `..` too), a symbolic link that leaves the folder, + or anything that is not a regular file is not found, in the engines' error shape as before. A relative value of + the key is under the application file's folder, never the working directory (`AppConfig.app_dir` names that + folder now); `file:` prefixes an absolute path as in the Java engine; an empty value turns the service off. Not + ported: the Java engine's static-content filter, its `no-cache-pages` list and its `mime.types` section. The + first consumer is the agent-question app's React front-end, built in the Node.js pack and deployed into both + packs' `resources/public`; the 2026-08-24 note that the wrappers serve no static files is withdrawn. + ### Fixed 1. **The agent-question app keeps the first accepted decision when two devices decide one card at the same moment** diff --git a/README.md b/README.md index 486b81a..d1f3a17 100644 --- a/README.md +++ b/README.md @@ -138,6 +138,7 @@ The same conventions as the engines, so a polyglot installation stays uniform: | `rest.server.port` | Event API port | `8085` | | `log.format` | `text`, `json` (pretty-printed) or `compact` (single-line JSONL) | `text` | | `log.level` | log level (`LOG_LEVEL` env var wins) | `INFO` | +| `static.html.folder` | the folder of static web content the host serves (HTML, CSS, JS, images), relative to the application file | `resources/public` | Configuration lives in the `resources` folder next to the application file, mirroring the engines' classpath resources: `resources/application.yml` (or `.yaml` / `.properties`) beside @@ -167,7 +168,7 @@ Kubernetes probes and dashboards treat a Python app exactly like a Java or Rust | Endpoint | Purpose | |----------|---------| -| `GET /` | minimal index page linking the endpoints below | +| `GET /` | the static folder's `index.html`, else a minimal index page linking the endpoints below | | `GET /info` | app identity, runtime, origin id, start time, uptime | | `GET /info/routes` | registered routes split by visibility, with instance counts | | `GET /env` | selected environment variables and configuration parameters | @@ -196,6 +197,21 @@ unknown paths answer the engines' error shape Kubernetes wiring: point `livenessProbe` at `/livenessprobe` and `readinessProbe` at `/health`. +## Static content + +The host serves the files of `static.html.folder` — the Java engine's key, with the Rust engine's +location as its default, `resources/public` next to the application file — for any `GET` or `HEAD` +that no host path, extension route or function claims, so an application can ship a web front-end +beside its functions the way the engines' Playground does. A folder is served as its `index.html`, +so `resources/public/index.html` replaces the landing page at `/`. The content type follows the +engines' table by extension (`text/javascript`, `text/css`, `image/svg+xml`, fonts and images; +`application/octet-stream` otherwise); every file carries an ETag and answers `If-None-Match` with +304, and HTML is served `Cache-Control: no-cache`, so a redeployed page is revalidated while hashed +assets stay cached. A hidden entry, a `..` segment, a symbolic link that leaves the folder or +anything that is not a regular file is not found, in the engines' error shape. A relative value of +the key is under the application file's folder, never the working directory; `file:` prefixes an +absolute path as in the Java engine; an empty value turns the service off. + ## Wire compatibility The codec implements the diff --git a/docs/guides/config-logging-actuators.md b/docs/guides/config-logging-actuators.md index cb73f71..0e43a6c 100644 --- a/docs/guides/config-logging-actuators.md +++ b/docs/guides/config-logging-actuators.md @@ -111,7 +111,7 @@ The host serves the engines' endpoints on the same port as `/api/event`: | Endpoint | Purpose | |----------|---------| -| `GET /` | minimal index page linking the endpoints below | +| `GET /` | the static folder's `index.html`, else a minimal index page linking the endpoints below | | `GET /info` | app identity, runtime, origin id, start time, uptime | | `GET /info/routes` | registered routes split by visibility, with instance counts | | `GET /env` | selected environment variables and configuration parameters (opt-in lists) | @@ -141,6 +141,23 @@ async def health_check(headers: dict[str, str], _body: Body): Optional dependencies never change the overall status; mandatory ones decide `UP`/`DOWN`, and the most recent outcome drives `/livenessprobe`. +## Static content — the engines' `public` folder + +The host serves the files of `static.html.folder` for any `GET` or `HEAD` that no host path, +extension route or function claims — the Java engine's key, with the Rust engine's location as +its default: `resources/public` next to the application file, under the resources rule above (a +relative value is under the application file's folder, never the working directory; `file:` +prefixes an absolute path as in the Java engine; an empty value turns the service off). A folder +is served as its `index.html`, so `resources/public/index.html` replaces the landing page at `/` +while `/info`, `/health` and the other host paths stay the host's. The content type follows the +engines' table by extension — `text/javascript`, `text/css`, `image/svg+xml`, the fonts and images +a bundle ships — and is `application/octet-stream` otherwise; every file carries an ETag and +answers `If-None-Match` with 304, and HTML is served `Cache-Control: no-cache`, so a redeployed +page is revalidated while hashed assets stay cached. Never found, in the engines' error shape: a +hidden entry (a segment starting with `.`, so `..` too), a symbolic link that leaves the folder, +anything that is not a regular file. Not ported from the Java engine: the static-content filter, +the `no-cache-pages` list and the `mime.types` section. + ## Kubernetes wiring ```yaml diff --git a/docs/guides/configuration-reference.md b/docs/guides/configuration-reference.md index 775f7be..8a82035 100644 --- a/docs/guides/configuration-reference.md +++ b/docs/guides/configuration-reference.md @@ -33,6 +33,7 @@ keywords: [configuration, reference, keys, substitution, overrides] | `show.application.properties` | opt-in list of configuration keys shown by `/env` | (empty) | | `mandatory.health.dependencies` | routes of health check functions that decide `/health` | (empty) | | `optional.health.dependencies` | health check routes reported but never affecting status | (empty) | +| `static.html.folder` | the folder of static web content the host serves for the paths nothing else claims — relative to the application file's folder ([guide](config-logging-actuators.md#static-content-the-engines-public-folder)) | `resources/public` | | `otel.forwarding` | the OpenTelemetry forwarder's master switch ([guide](config-logging-actuators.md#distributed-tracing-the-opentelemetry-forwarder-opt-in)) | `false` | | `otel.exporter.otlp.endpoint` | the OTLP/HTTP traces URL including the signal path | `http://localhost:4318/v1/traces` | | `otel.exporter.otlp.headers` | request headers, `k=v` or `k: v`, comma-separated (re-read per export) | (none) | diff --git a/docs/guides/http-surface-reference.md b/docs/guides/http-surface-reference.md index 836a5b5..553a8a7 100644 --- a/docs/guides/http-surface-reference.md +++ b/docs/guides/http-surface-reference.md @@ -32,7 +32,7 @@ charset=utf-8` (the engines' default-serializer presentation). | Endpoint | Content type | Shape | |----------|--------------|-------| -| `GET /` | `text/html` | minimal index page linking the endpoints | +| `GET /` | `text/html` | the static folder's `index.html`, else a minimal index page linking the endpoints | | `GET /info` | JSON | `{app{name,version,description}, runtime{language,python,mercury_composable}, origin, time{start,current}, up_time}` | | `GET /info/routes` | JSON | `{app, routing{public{route: instances}, private{...}}}` | | `GET /env` | JSON | `{app, env{environment{...}, properties{...}}}` (opt-in lists) | @@ -47,6 +47,16 @@ reports `status_code: 404` with `Please check - Route X not found`. uuid (the Java reference engine's format). - `up_time` — the engines' rendering (`59 seconds`, `1 minute 1 second`, …). +## Static content + +A `GET` or `HEAD` of any other path is answered with the file it names inside `static.html.folder` +(`resources/public` next to the application file by default; `index.html` for a folder) when there +is one: the content type by extension from the engines' table, an `ETag` (`If-None-Match` answers +304 with no body) and, for HTML, `Cache-Control: no-cache`. A path that names nothing — including a +hidden entry, a link out of the folder or a folder without an index page — falls through to the +error signature below. See the +[guide](config-logging-actuators.md#static-content-the-engines-public-folder). + ## Error signature (host-level) Unknown paths and non-GET methods on known paths answer the engines' shape — diff --git a/src/mercury_composable/actuator.py b/src/mercury_composable/actuator.py index 00c0b46..1a60bf5 100644 --- a/src/mercury_composable/actuator.py +++ b/src/mercury_composable/actuator.py @@ -63,8 +63,8 @@ async def health(headers: dict[str, str], _body: Body) -> Body: HEALTH_TIMEOUT_MS = 10000 # engine value for the type=health probe UNHEALTHY = "Unhealthy. Please check '/health' endpoint." -# The engines' minimal landing page (platform-core public/index.html style); -# the wrappers embed it - no static file service by design. +# The engines' minimal landing page (platform-core public/index.html style), embedded: served +# at / unless the static content folder (static_content.py) has an index.html of its own. INDEX_HTML = """ diff --git a/src/mercury_composable/config.py b/src/mercury_composable/config.py index c3125e6..643adef 100644 --- a/src/mercury_composable/config.py +++ b/src/mercury_composable/config.py @@ -104,6 +104,7 @@ def __init__(self, path: str | None = None, argv: list[str] | None = None, self._overrides: dict[str, Any] = parse_d_args(sys.argv[1:] if argv is None else argv) self._source = "none" self._resources_dir: str | None = None + self._app_dir: str | None = app_dir if app_dir is not None else main_script_dir() if path: if not os.path.isfile(path): raise FileNotFoundError(f"Configuration file not found - {path}") @@ -146,6 +147,13 @@ def resources_dir(self) -> str | None: None when there is neither.""" return self._resources_dir + @property + def app_dir(self) -> str | None: + """The application file's folder - the ``app_dir`` given (the CLI passes the application + file's), else the folder of the script Python ran; None in an interactive session. The + ``resources`` folder and the static content folder are resolved under it.""" + return self._app_dir + def set(self, key: str, value: Any) -> None: """Runtime override, checked first on every read (f:setConfig analog).""" if not key or not str(key).strip(): diff --git a/src/mercury_composable/server.py b/src/mercury_composable/server.py index bdbcf1d..9386dac 100644 --- a/src/mercury_composable/server.py +++ b/src/mercury_composable/server.py @@ -58,6 +58,7 @@ ) from .log import get_logger from .registry import FunctionRegistry, ServiceDef, default_registry +from .static_content import StaticContent, resolve_folder from .trace import MY_CID_TAG, MY_CORRELATION_ID OCTET_STREAM = "application/octet-stream" @@ -223,6 +224,9 @@ class EventApiServer: def __init__(self, registry: FunctionRegistry | None = None): self.registry = registry or default_registry self.actuator = Actuator(self.registry) + # the static content folder is resolved from the configuration at construction, as the + # Actuator's settings are + self.static = StaticContent(resolve_folder(app_config())) async def handle_event(self, request: web.Request) -> web.StreamResponse: raw = await request.read() @@ -420,24 +424,33 @@ async def _next_segment(response: web.StreamResponse, def create_app(self, routes: Iterable[RouteMounter] = ()) -> web.Application: """The Event API application: ``POST /api/event``, the actuator paths, then the routes - of the extensions given (``Platform.add_routes``) and, last, the catch-all that answers - the engines' error shape - so the host's paths always win and an extension's path wins - over the catch-all.""" + of the extensions given (``Platform.add_routes``), then the static content folder for a + GET or HEAD and, last, the catch-all that answers the engines' error shape - so the host's + paths always win, an extension's path wins over a file and a file wins over the catch-all. + A folder's ``index.html`` replaces the engines' landing page at ``/``.""" app = web.Application(client_max_size=16 * 1024 * 1024) app.router.add_post("/api/event", self.handle_event) - # the engines' landing page + actuator endpoints (see actuator.py) - for path in ("/", "/info", "/info/routes", "/env", "/health", "/livenessprobe"): + # the engines' landing page (or the static folder's index.html) + actuator endpoints + # (see actuator.py) + app.router.add_get("/", self.handle_other) + for path in ("/info", "/info/routes", "/env", "/health", "/livenessprobe"): app.router.add_get(path, self.actuator.handle) # an extension's own routes - a reply page, a stream a browser holds - registered # after the host's and before the catch-all for mount in routes: mount(app) - # any other path or method answers the engines' error shape, not - # aiohttp's default text page (exact routes above win - they are + # any other path: a static file for a GET or HEAD that names one, else the engines' + # error shape, not aiohttp's default text page (exact routes above win - they are # registered first) - app.router.add_route("*", "/{unknown:.*}", self.actuator.handle) + app.router.add_route("*", "/{unknown:.*}", self.handle_other) return app + async def handle_other(self, request: web.Request) -> web.StreamResponse: + """A path no route claimed, and ``/``: the static folder's file (``index.html`` for a + folder) when a GET or HEAD names one, else the actuator - the landing page at ``/``, the + engines' error shape elsewhere.""" + return self.static.serve(request) or await self.actuator.handle(request) + class Platform: """Runs the Event API host for the default (or a given) registry.""" diff --git a/src/mercury_composable/static_content.py b/src/mercury_composable/static_content.py new file mode 100644 index 0000000..8fc49ae --- /dev/null +++ b/src/mercury_composable/static_content.py @@ -0,0 +1,147 @@ +"""Static web content: the engines' ``static.html.folder``, served by the host. + +The Java engine serves the files of ``static.html.folder`` (default ``classpath:/public``) for a GET +no REST endpoint claims - ``index.html`` for a folder, a content type by extension, an ETag so a +browser revalidates - and the Rust engine serves a fixed ``resources/public``. The packs serve the +same way: the key is the Java engine's and its default the Rust engine's location, ``resources/public`` +next to the application file, under the packs' resources rule (a relative folder is under the +application file's folder, never the working directory; ``file:`` is the engine's prefix for an +absolute path). The host's own paths and an extension's routes win over a file, a file wins over the +catch-all, and a folder's ``index.html`` replaces the embedded landing page at ``/``. + +Served: GET and HEAD of a regular file inside the folder, ``index.html`` for a folder. Not found: a +path with a hidden segment (one starting with ``.``, so ``..`` too), a symbolic link that leaves the +folder, anything that is not a regular file. ``text/html`` is served ``Cache-Control: no-cache`` so a +redeployed page is revalidated on every load; every file carries an ETag and ``If-None-Match`` answers +304, so a browser keeps the rest and asks only whether it changed. Not ported: the Java engine's +static-content filter, its ``no-cache-pages`` list and its ``mime.types`` section - the table here +covers what a web bundle ships; anything else is ``application/octet-stream``. +""" + +from __future__ import annotations + +import os + +from aiohttp import web + +from .config import AppConfig +from .log import get_logger + +log = get_logger("mercury.static") + +STATIC_FOLDER = "static.html.folder" +DEFAULT_FOLDER = "resources/public" +INDEX_HTML = "index.html" +FILE_PREFIX = "file:" +CLASSPATH_PREFIX = "classpath:" +OCTET_STREAM = "application/octet-stream" + +# the engines' minimalist table (platform-core's built-in types and its mime-types.yml) plus what a +# web bundle ships; the text types carry their charset, as the host's own responses do +CONTENT_TYPES: dict[str, str] = { + "html": "text/html; charset=utf-8", + "htm": "text/html; charset=utf-8", + "css": "text/css; charset=utf-8", + "js": "text/javascript; charset=utf-8", + "mjs": "text/javascript; charset=utf-8", + "json": "application/json; charset=utf-8", + "map": "application/json; charset=utf-8", + "webmanifest": "application/manifest+json", + "txt": "text/plain; charset=utf-8", + "xml": "application/xml", + "svg": "image/svg+xml", + "svgz": "image/svg+xml", + "png": "image/png", + "jpg": "image/jpeg", + "jpeg": "image/jpeg", + "jpe": "image/jpeg", + "gif": "image/gif", + "webp": "image/webp", + "ico": "image/vnd.microsoft.icon", + "woff": "font/woff", + "woff2": "font/woff2", + "ttf": "font/ttf", + "otf": "font/otf", + "ttc": "font/collection", + "pdf": "application/pdf", + "wasm": "application/wasm", +} + + +def content_type(name: str) -> str: + """The content type of a file name, by its extension - the engine's rule: a name without a + dot, or ending in one, is ``application/octet-stream``, as is an extension the table lacks.""" + stem, dot, ext = name.rpartition(".") + if dot and stem and ext: + return CONTENT_TYPES.get(ext.lower(), OCTET_STREAM) + return OCTET_STREAM + + +def resolve_folder(config: AppConfig) -> str | None: + """The folder ``static.html.folder`` names, absolute, or None when there is nothing to serve: + an empty value turns the service off; a relative value is under the application file's folder + (none known - an interactive session - serves nothing); ``file:`` is stripped; ``classpath:`` + has no meaning in a pack, so the default stands and a warning names the value.""" + value = (config.get_property(STATIC_FOLDER, DEFAULT_FOLDER) or "").strip() + if not value: + return None + if value.startswith(CLASSPATH_PREFIX): + log.warning("%s '%s' names a classpath, which a pack does not have - serving %s", + STATIC_FOLDER, value, DEFAULT_FOLDER) + value = DEFAULT_FOLDER + elif value.startswith(FILE_PREFIX): + value = value[len(FILE_PREFIX):] + if not os.path.isabs(value): + if config.app_dir is None: + return None + value = os.path.join(config.app_dir, value) + return os.path.normpath(value) + + +class StaticContent: + """The files of one folder, served by the host for the paths nothing else claims.""" + + def __init__(self, folder: str | None) -> None: + self.folder: str | None = folder if folder and os.path.isdir(folder) else None + self._root = os.path.realpath(self.folder) if self.folder else None + if self.folder: + log.info("Static content folder: %s", self.folder) + + @property + def enabled(self) -> bool: + return self._root is not None + + def locate(self, path: str) -> str | None: + """The regular file a request path names inside the folder (``index.html`` for a folder), + resolved, or None: a hidden segment, a link out of the folder, a missing or special file.""" + root = self._root + if root is None: + return None + segments = [segment for segment in path.split("/") if segment] + if any(segment.startswith(".") for segment in segments): + return None + try: + target = os.path.realpath(os.path.join(root, *segments)) if segments else root + if os.path.isdir(target): + target = os.path.realpath(os.path.join(target, INDEX_HTML)) + if not target.startswith(root + os.sep) or not os.path.isfile(target): + return None + return target + except OSError: + return None + + def response(self, file: str) -> web.FileResponse: + """The file with its type and its caching: html ``no-cache``, everything with an ETag + (aiohttp's FileResponse answers If-None-Match with 304 and serves HEAD without a body).""" + kind = content_type(os.path.basename(file)) + headers = {"Content-Type": kind} + if kind.startswith("text/html"): + headers["Cache-Control"] = "no-cache" + return web.FileResponse(file, headers=headers) + + def serve(self, request: web.Request) -> web.StreamResponse | None: + """The response for a GET or HEAD that names a file, or None when the path is not ours.""" + if request.method not in ("GET", "HEAD"): + return None + file = self.locate(request.path) + return self.response(file) if file else None diff --git a/tests/test_config.py b/tests/test_config.py index df7e074..030eb7b 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -161,3 +161,16 @@ def test_env_substitution_with_default(tmp_path: Path, monkeypatch: pytest.Monke monkeypatch.setenv("PEER_PORT", "9090") assert config.get("peer.url") == "http://127.0.0.1:9090/api/event" assert config.get("missing") is None # unresolved whole-value ref -> None + + +def test_the_application_folder_is_known(tmp_path: Path): + app_dir = tmp_path / "app" + write(str(app_dir / "resources" / "application.yml"), "application:\n name: 'demo-app'\n") + assert AppConfig(argv=[], app_dir=str(app_dir)).app_dir == str(app_dir) + # an explicit file keeps the application folder it was given - the static content folder + # resolves under it, the companions beside the file + other = tmp_path / "conf" / "other.yml" + write(str(other), "application:\n name: 'other'\n") + config = AppConfig(str(other), argv=[], app_dir=str(app_dir)) + assert config.app_dir == str(app_dir) + assert config.resources_dir == str(tmp_path / "conf") diff --git a/tests/test_static_content.py b/tests/test_static_content.py new file mode 100644 index 0000000..fb6d588 --- /dev/null +++ b/tests/test_static_content.py @@ -0,0 +1,231 @@ +"""Static content pins: the engines' ``static.html.folder``, served by the host for the paths +nothing else claims - the folder's index.html at /, the types, the ETag, what is never found, and +what wins over a file.""" + +from __future__ import annotations + +import os +from collections.abc import AsyncIterator, Callable, Iterator +from contextlib import AbstractAsyncContextManager, asynccontextmanager +from pathlib import Path + +import aiohttp +import pytest +from aiohttp import web +from yarl import URL + +from mercury_composable import AppConfig, FunctionRegistry, app_config, load_config +from mercury_composable.server import EventApiServer +from mercury_composable.static_content import ( + OCTET_STREAM, + StaticContent, + content_type, + resolve_folder, +) + +Serve = Callable[[FunctionRegistry], AbstractAsyncContextManager[str]] +NOT_FOUND = {"status": 404, "message": "Resource not found", "type": "error"} + + +def write(path: Path, text: str) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(text, encoding="utf-8") + + +def bundle(public: Path, outside: Path) -> None: + """A web bundle the way a build deploys one, plus the entries that must never be served.""" + write(public / "index.html", "

bundle

") + write(public / "app.js", "console.log('bundle')") + write(public / "style.css", "body { margin: 0 }") + write(public / "assets" / "logo.svg", "") + write(public / "sub" / "index.html", "

sub

") + write(public / "plain" / "readme.txt", "a folder without an index page") + write(public / ".secret", "hidden") + write(public / "info", "a file named like the actuator's path") + write(public / "hello", "a file named like an extension's route") + write(outside, "outside the folder") + os.symlink(outside, public / "link.txt") + + +@pytest.fixture +def app_dir(tmp_path: Path) -> Iterator[Path]: + """An application folder whose resources/public holds a bundle, loaded as the shared + configuration (the host resolves the folder from it at construction); a fresh default + configuration afterwards.""" + folder = tmp_path / "app" + bundle(folder / "resources" / "public", tmp_path / "outside.txt") + load_config(app_dir=str(folder)) + yield folder + load_config() + + +async def fetch(url: str | URL, method: str = "GET", + headers: dict[str, str] | None = None) -> tuple[int, dict[str, str], bytes]: + async with ( + aiohttp.ClientSession() as session, + session.request(method, url, headers=headers) as response, + ): + return (response.status, {k.lower(): v for k, v in response.headers.items()}, + await response.read()) + + +async def fetch_json(url: str | URL) -> tuple[int, object]: + async with aiohttp.ClientSession() as session, session.get(url) as response: + return response.status, await response.json(content_type=None) + + +@asynccontextmanager +async def serve_with_routes(registry: FunctionRegistry, + mount: Callable[[web.Application], None]) -> AsyncIterator[str]: + runner = web.AppRunner(EventApiServer(registry).create_app([mount])) + await runner.setup() + site = web.TCPSite(runner, "127.0.0.1", 0) + await site.start() + try: + yield f"http://127.0.0.1:{runner.addresses[0][1]}" + finally: + await runner.cleanup() + await registry.bus.close() + + +# --- the table and the folder ----------------------------------------------------------------- + + +def test_the_content_type_follows_the_engines_table(): + assert content_type("index.html") == "text/html; charset=utf-8" + assert content_type("app.JS") == "text/javascript; charset=utf-8" + assert content_type("bundle.mjs") == "text/javascript; charset=utf-8" + assert content_type("style.css") == "text/css; charset=utf-8" + assert content_type("logo.svg") == "image/svg+xml" + assert content_type("favicon.ico") == "image/vnd.microsoft.icon" + assert content_type("font.woff2") == "font/woff2" + assert content_type("app.js.map") == "application/json; charset=utf-8" + # the engine's rule: no dot, a trailing dot or an unknown extension is an octet stream + assert content_type("README") == OCTET_STREAM + assert content_type("trailing.") == OCTET_STREAM + assert content_type("archive.tgz") == OCTET_STREAM + + +def test_the_folder_is_resolved_under_the_application_file(tmp_path: Path): + config = AppConfig(argv=[], app_dir=str(tmp_path)) + assert resolve_folder(config) == str(tmp_path / "resources" / "public") + config.set("static.html.folder", "web/site") + assert resolve_folder(config) == str(tmp_path / "web" / "site") + config.set("static.html.folder", f"file:{tmp_path / 'absolute'}") + assert resolve_folder(config) == str(tmp_path / "absolute") + config.set("static.html.folder", str(tmp_path / "elsewhere") + "/") + assert resolve_folder(config) == str(tmp_path / "elsewhere") + # a classpath has no meaning in a pack - the default stands + config.set("static.html.folder", "classpath:/public") + assert resolve_folder(config) == str(tmp_path / "resources" / "public") + # an empty value turns the service off + config.set("static.html.folder", "") + assert resolve_folder(config) is None + + +def test_a_missing_folder_serves_nothing(tmp_path: Path): + assert not StaticContent(str(tmp_path / "absent")).enabled + assert not StaticContent(None).enabled + assert StaticContent(None).locate("/index.html") is None + + +# --- through the host --------------------------------------------------------------------------- + + +async def test_the_folders_index_page_replaces_the_landing_page(app_dir: Path, serve: Serve): + async with serve(FunctionRegistry()) as base: + status, headers, body = await fetch(f"{base}/") + assert status == 200 + assert body == b"

bundle

" + assert headers["content-type"] == "text/html; charset=utf-8" + assert headers["cache-control"] == "no-cache" + assert headers["etag"] + # HEAD: the same headers, no body + status, headers, body = await fetch(f"{base}/", "HEAD") + assert status == 200 + assert headers["content-type"] == "text/html; charset=utf-8" + assert body == b"" + + +async def test_a_file_is_served_with_its_type_and_an_etag(app_dir: Path, serve: Serve): + async with serve(FunctionRegistry()) as base: + status, headers, body = await fetch(f"{base}/app.js") + assert (status, body) == (200, b"console.log('bundle')") + assert headers["content-type"] == "text/javascript; charset=utf-8" + assert "cache-control" not in headers # a browser revalidates by the ETag + etag = headers["etag"] + status, _, body = await fetch(f"{base}/app.js", headers={"If-None-Match": etag}) + assert (status, body) == (304, b"") + status, headers, _ = await fetch(f"{base}/style.css") + assert (status, headers["content-type"]) == (200, "text/css; charset=utf-8") + status, headers, _ = await fetch(f"{base}/assets/logo.svg") + assert (status, headers["content-type"]) == (200, "image/svg+xml") + + +async def test_a_folder_serves_its_index_page(app_dir: Path, serve: Serve): + async with serve(FunctionRegistry()) as base: + for path in ("/sub", "/sub/"): + status, _, body = await fetch(f"{base}{path}") + assert (status, body) == (200, b"

sub

"), path + # a folder without one is not found, in the engines' error shape + assert await fetch_json(f"{base}/plain") == (404, NOT_FOUND) + + +async def test_what_is_never_found(app_dir: Path, serve: Serve): + async with serve(FunctionRegistry()) as base: + for path in ( + "/missing.js", # no such file + "/.secret", # a hidden entry + "/link.txt", # a symbolic link out of the folder + "/%2e%2e/outside.txt", # a traversal, percent-encoded + "/sub/%2e%2e/%2e%2e/outside.txt", + "/assets/", # a folder without an index page + ): + status, payload = await fetch_json(URL(f"{base}{path}", encoded=True)) + assert (status, payload) == (404, NOT_FOUND), path + # the folder itself is never listed, and another method is not a file request + status, payload = await fetch_json(f"{base}/assets") + assert (status, payload) == (404, NOT_FOUND) + status, _, body = await fetch(f"{base}/app.js", "POST") + assert status == 404 + assert b"Resource not found" in body + + +async def test_the_hosts_paths_and_an_extensions_routes_win_over_a_file(app_dir: Path): + def mount(app: web.Application) -> None: + async def hello(_request: web.Request) -> web.Response: + return web.Response(text="the route") + app.router.add_get("/hello", hello) + + async with serve_with_routes(FunctionRegistry(), mount) as base: + status, payload = await fetch_json(f"{base}/info") + assert status == 200 + assert isinstance(payload, dict) and "app" in payload # the actuator, not public/info + status, _, body = await fetch(f"{base}/hello") + assert (status, body) == (200, b"the route") # the extension, not public/hello + + +async def test_the_key_names_another_folder(tmp_path: Path, serve: Serve): + elsewhere = tmp_path / "elsewhere" + write(elsewhere / "index.html", "

elsewhere

") + load_config(app_dir=str(tmp_path / "app")) + try: + app_config().set("static.html.folder", str(elsewhere)) + async with serve(FunctionRegistry()) as base: + status, _, body = await fetch(f"{base}/") + assert (status, body) == (200, b"

elsewhere

") + finally: + load_config() + + +async def test_without_a_folder_the_landing_page_stays(tmp_path: Path, serve: Serve): + load_config(app_dir=str(tmp_path / "app")) # no resources/public + try: + async with serve(FunctionRegistry()) as base: + status, headers, body = await fetch(f"{base}/") + assert status == 200 + assert headers["content-type"].startswith("text/html") + assert b"INFO endpoint" in body + assert await fetch_json(f"{base}/app.js") == (404, NOT_FOUND) + finally: + load_config() From 2bf53bd3fa71d616b17fedbbb7480aaec1533d3b Mon Sep 17 00:00:00 2001 From: Eric Law <39393654+acn-ericlaw@users.noreply.github.com> Date: Fri, 20 Nov 2026 15:59:15 +0800 Subject: [PATCH 2/2] memory: static content opened as PR #73 - the sprint's blueprint thread and the decision Co-Authored-By: Claude Fable 5.1 --- memory/continuity.md | 18 +++++++++ .../thread-bp-question-record-and-ui.md | 31 ++++++++++++++ memory/sessions/2026-11-20-075621.md | 40 +++++++++++++++++++ 3 files changed, 89 insertions(+) create mode 100644 memory/open-threads/thread-bp-question-record-and-ui.md create mode 100644 memory/sessions/2026-11-20-075621.md diff --git a/memory/continuity.md b/memory/continuity.md index 63c1bf0..7c40582 100644 --- a/memory/continuity.md +++ b/memory/continuity.md @@ -292,6 +292,24 @@ second front-end here. +- **The host serves static web content from `resources/public` next to the application file - the engines' `public` + folder (Eric, 2026-11-20; PR #73, the Node twin mercury-nodejs #138).** `static.html.folder` is honoured as the Java + engine's key with the Rust engine's location as its default, under the resources rule + ([[conv-resources-next-to-the-application-file]]): a GET or HEAD that no host path, extension route or function claims + is answered with the file it names, `index.html` for a folder (so a folder's `index.html` replaces the embedded + landing page at `/`), the content type from the engines' table by extension, an ETag with 304 on `If-None-Match`, + `Cache-Control: no-cache` for HTML; a hidden segment, a link out of the folder or anything that is not a regular file + is not found, in the engines' error shape; `file:` prefixes an absolute path, an empty value turns the service off; + `AppConfig.app_dir` names the application file's folder. Withdraws the 2026-08-24 note that the wrappers serve no + static files (session 2026-08-24-015208): a pack application now ships a web front-end beside its functions as the + engines' Playground does - the first is the agent-question app's React UI, built in the Node pack and deployed into + both packs' `resources/public`, served by each backend from its own origin, so no CORS ([[bp-question-record-and-ui]]). + Not ported: the Java engine's static-content filter, its `no-cache-pages` list and its `mime.types` section. + **How to apply:** a web bundle goes into `resources/public` next to the application file and nothing else is + configured; a host path or an extension route always wins over a file of the same name; a relative folder is never + the working directory's. + + ## Conventions - **Quality gates (adopted 2026-08-23, Eric's IDE review round): ruff + basedpyright + diff --git a/memory/open-threads/thread-bp-question-record-and-ui.md b/memory/open-threads/thread-bp-question-record-and-ui.md new file mode 100644 index 0000000..ef289f8 --- /dev/null +++ b/memory/open-threads/thread-bp-question-record-and-ui.md @@ -0,0 +1,31 @@ +- [ ] **(blueprint) The 2026-11-20 sprint: the question record joins the audit log, the agent-question backend serves + the React UI's reads, and the hosts serve static content (Eric's three items, reviewed and agreed 2026-11-20).** + The agreed design, in build order. **(1) Static content** - `static.html.folder`, default `resources/public` next to + the application file, in both hosts: BUILT, PR #73 (the Node twin mercury-nodejs #138), [[static-content-resources-public]]. + **(2) The question record** - the main flow records, the channels deliver: every question and advice passes + `person.ask` and every answer, from any channel, passes `POST /ask/reply`, so the recorder is a private one-instance + function of the ask-person process behind drop-n-forget local events, the helper's `transcript.audit` pattern + ([[transcript-audit-store-python]]) - not the helper itself, since a deterministic flow has no helper in its path. The + table is today's inbox row moved into the audit database: one row per wait upserted on graph, correlation id and + turn, one row per advice appended, the answer columns written once under the first-decision rule, the change sequence + kept for the feed, the message as received kept as the audit copy, linked to the transcript by correlation id and + graph id (no new column). A published store contract (Eric: PostgreSQL out of the box, a memory implementation as the + pattern for unit tests, the interface published so a field implements another database), and the engines' published + schema page gains a question section (ADR-0035). The writes order-independent from the start with an `.instances` key: + the mailbox's ordering replaced by a per-conversation row lock, a monotonic guard on the row and a forward-only mark - + the same relaxation proposed for `transcript.audit` (follow-up, `llm.transcript.audit.instances`, default 1). `seen` + leaves the record (a device's state, kept in the UI). The deterministic node is the generalized record only: a flow + that asks at a stage sends its id as `graph_id` and the stage as `turn`, its continuation an allowlisted entry. The + agent-question app becomes a reader of the table under the store's read role plus the click, its intake a wake-up of + connected devices; the reads for the UI, in both packs and in the shared vectors: `GET /questions?before=` for + the history's infinite scroll, `GET /transcripts` and `GET /transcripts/{conversation}` over the audit store, + `GET /questions/config` for the sign-in. **(3) The React UI**, in the Node pack only (mercury-nodejs thread + `agent-question-react-ui`), deployed into both packs' `resources/public`, same origin, no CORS. Identity `none` and + `oauth2` only - `proxy` removed here and from the reply endpoint (Eric: the field's installations use 3-legged SSO and + OAuth 2.0 access tokens): Authorization Code with PKCE in the browser, the bearer on every call, the stream read with + `fetch` since `EventSource` carries no bearer, the reply page signing in the same way; a Keycloak development + container plus a mock issuer fixture for the tests; the vanilla page retired in both packs when the UI lands; no + source maps. RFC-0014 gets a round-4 amendment in mercury-composable before the record is built. Status: step 1 of 3 + built (PR #73); next the RFC amendment, then the record. + → serves: vision-mercury-python + diff --git a/memory/sessions/2026-11-20-075621.md b/memory/sessions/2026-11-20-075621.md new file mode 100644 index 0000000..13a9f93 --- /dev/null +++ b/memory/sessions/2026-11-20-075621.md @@ -0,0 +1,40 @@ +# Session (2026-11-20T07:56:21.000Z) + +**Agent:** Claude Code +**Title:** The hosts serve static web content from `resources/public` - step 1 of the 2026-11-20 sprint +**User:** Eric - "let's resume AI SDLC work. In this sprint, we will do the following: 1. make the question-inbox for questions, answers and advices as part of transcript audit log ... 2. upgrade the agent-question-UI from plain javascript into a full React application ... 3. Check if the language packs (python and nodejs) are capable of serving static HTML/JS/CSS content like what the engines do. If not, add the functionality." Then "agree with your recommendations" with two refinements - no `proxy` mode (the field's installations use 3-legged SSO and OAuth 2.0 access tokens) and a published store contract (PostgreSQL out of the box, a memory implementation as the unit-test pattern, another database by the contract) - and a question on relaxing the audit writer's single instance. + +## What We Did + +- **The review** (no code): the three items against the code of the four repositories; the agreed design, in build + order, is the new blueprint thread [[bp-question-record-and-ui]] - the main flow records and the channels deliver, the + record in the audit database under a published contract, the React UI in the Node pack deployed into both packs' + `resources/public` and served same-origin (Eric: no CORS), identity `none` and `oauth2` only with PKCE in the browser, + static content first because the UI depends on it. +- **Static content, built here and in the Node twin:** `src/mercury_composable/static_content.py` - `static.html.folder` + (the Java engine's key), default `resources/public` next to the application file (the Rust engine's location); + `AppConfig.app_dir` names that folder; the host's `/` serves the folder's `index.html` else the embedded landing page, + and the catch-all serves the file a GET or HEAD names else the engines' error shape; the engines' content-type table, + ETag with 304 and HEAD through aiohttp's FileResponse, `no-cache` for HTML; a hidden segment, a link out of the folder + or a special file not found. 12 tests (`tests/test_static_content.py`, one in `tests/test_config.py`); README, the + three guides, CHANGELOG Added 7; the 2026-08-24 "no static file service" note withdrawn. Gates: ruff OK, basedpyright + 0 errors, pytest 763 passed / 75 skipped. Driven live through `mercury-serve` with a bundle in a scratch + `resources/public`: the page with `no-cache` and an ETag, the script as `text/javascript`, HEAD, 304, the actuator + and the error shape untouched (a first empty curl was the smoke script's startup race, not the host). +- **Decision recorded:** [[static-content-resources-public]]. +- **Eric's optimization question** - may the audit writer run several instances since every write is timestamped? - + answered in the conversation: viable, with the mailbox's ordering replaced by a per-conversation row lock (the + conversation upsert first in the transaction), a monotonic guard on the conversation row and a forward-only audited + mark, a check racing a write tolerated; a key `llm.transcript.audit.instances` with default 1, worth raising only + where the database is remote. The question recorder of step 2 is to be built order-independent from the start. +- Opened as PR #73 (the Node twin mercury-nodejs #138). + +## Memory References + +- Referenced: engine-consistent-conventions (the key carries the Java engine's name and the default the Rust engine's + location), conv-resources-next-to-the-application-file (the default under the application file, never the working + directory), scope-wrapper-no-orchestration (checked: serving files is neither orchestration nor persistence), + agent-question-app (the first consumer - the React UI deployed into its resources/public), conv-python-quality-gates + (ran them), ask-person-main-flow (the recorder's home in the agreed design), transcript-audit-store-python (the + recorder's pattern and the multi-instance guards) +- Created: static-content-resources-public (tier: working), bp-question-record-and-ui (tier: working, blueprint thread)