Files
interactive-story/backend/tools/m11_webdriver.py
JesseMarkowitzandClaude Opus 5 144406cd48 M11: what the server will actually read
The release-validation milestone, and the thing it had to settle first was
whether any of the earlier evidence meant what it said. M8 measured a deployment
enforcing a 4,096-token input window while the application budgeted 16,384.
Every request returned 200. What Ollama does with the excess is drop the oldest
tokens, and the oldest tokens here are the system block — the narrator's rules
and the campaign canon. A hundred-turn certification against that server would
have looked perfect and proved nothing, which is why this milestone could not
begin with a hundred turns.

So the application asks now. Ollama's window is a property of how a model was
loaded rather than of the request — sending num_ctx is accepted, ignored, and
worse, reloads the model at the server's own default — so the only honest move
is to find out and then tell the truth about it. /api/ps reports what a resident
model is being served with, /api/show what an unloaded one will load with, both
on the same host inference already uses, through the same endpoint policy and
the same TLS trust store. A verified window is a ceiling on the budget; an
unverified one leaves the budget alone and is recorded as unverified in the
turn's own provenance, so an old turn can be asked afterwards whether it was
built against a checked window. There is no third behaviour, and in particular
no hard-coded 4,096: a number the server did not say would be right on one
machine and wrong on the next.

The proof that this is doing something is a campaign whose canon sits at the
front of the prompt, 120 turns of history, and a 4,096-token window. The canon
is still there afterwards and the oldest history is gone. The same campaign
built the old way produces a prompt more than twice the window — the defect,
reproduced, so the fix is measured against it rather than asserted.

Two defects the validation found on its own, and they are the same defect twice:
something was true and nobody was told. A manual state correction of four
changes with one bad reference applied three, returned 201, and said nothing —
while recording the refusal on the audit row nobody reads. It came to light
because the identity diagnostic's own fixture was refused that way and the whole
run proceeded on a campaign with no scene, which would have read as a model
failure. And the narration-length setting moved no number: brief, medium and
long each became one English sentence, while the numeric hint the model actually
reads was derived from the global reply cap and said the same thing for all
three. Both now say what they did.

The other two post-M8 findings are closed as well. The tab said AI D&D, which no
document had ever claimed it did not; it says Interactive Story now, with the
open campaign first, and the name is the owner's decision rather than a
find-and-replace to something narrower than the engine. After an Undo the reader
could not tell where they had landed; the control row now ends with
"Moment 11 · later story ahead", from the server's own answer, in the word the
transcript already uses, with none of head, branch or depth anywhere near it.

The identity diagnostic exists and the root cause does not. That campaign was
destroyed, so no cause can be established — what M11 owes the finding is
something that can classify the next occurrence, and a diagnostic that makes only
the judgements a program can honestly make: duplicate keys, shared names,
protagonist drift, state and context disagreeing. Whether prose misattributed a
line is left to a person reading it beside its prompt, because a regex cannot
read dialogue and one that pretended to would produce exactly the confident wrong
answer this finding is about. Its detectors are proved to fire against a planted
second Alice.

Two entities may still share a display name. That was checked first, as the
finding asked, and left permitted: a mother and a daughter, or a stranger giving
a false name, are ordinary fiction, and refusing them to guard against a model
mistake would refuse the wrong thing. What was missing was that it happened
silently. It is reported now.

Evidence, not inference: a hundred accepted turns against a real narrator with
genuine process restarts; a real browser against the built SPA; a container with
no network at all; a campaign moved into a data directory that never existed.
Each was discarded and re-run whenever the product changed under it, and the runs
that were thrown away are listed in the report with the reason, along with ten
defects in the harnesses themselves — because a harness that has only ever
agreed with itself is not evidence, and two of M8's five harness defects were
masking real ones.

No dependency was added, removed or upgraded. No acceptance test was retired,
relaxed or reclassified. M11 is implemented and verified; it is not accepted, and
there is no release tag.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Qyn3oRd4D6pi72nKBG725B
2026-09-07 14:01:20 -04:00

248 lines
9.5 KiB
Python

"""A W3C WebDriver client in one file, so browser evidence needs no dependency.
M8 and M9 drove Firefox from a harness that lived outside the repository, which
made their browser evidence unrepeatable by anyone else. This is the same thing
kept inside it, and deliberately dependency-free: WebDriver is an HTTP protocol,
`urllib` speaks HTTP, and adding Selenium to the release candidate to press
buttons would put a package in the audit surface (§23) for no capability.
Only what the release scenarios need is implemented. Anything missing is missing
because nothing used it, not because it was hard.
**One environment note, established by measurement.** Firefox here is a snap, and
its sandbox refuses a file the browser was told to open from `/tmp` — which is
what M9 recorded as "this machine cannot drive a file into the browser". The
narrower and more useful statement is that it refuses `/tmp`: a path under the
user's home works. `stage()` exists to put evidence files there, so knowledge
import can be exercised through the real file input rather than in two halves.
"""
from __future__ import annotations
import json
import os
import shutil
import socket
import subprocess
import time
import urllib.error
import urllib.request
from pathlib import Path
GECKODRIVER = shutil.which("geckodriver") or "/snap/bin/geckodriver"
#: Where files the browser must open are staged. Under $HOME because the snap
#: sandbox denies /tmp; see the module docstring.
STAGE = Path.home() / "m11-evidence"
def stage(name: str, body: str | bytes) -> str:
STAGE.mkdir(parents=True, exist_ok=True)
path = STAGE / name
if isinstance(body, bytes):
path.write_bytes(body)
else:
path.write_text(body)
return str(path)
def free_port() -> int:
with socket.socket() as s:
s.bind(("127.0.0.1", 0))
return s.getsockname()[1]
class WebDriverError(RuntimeError):
pass
class Browser:
"""One headless Firefox, driven over the wire protocol."""
def __init__(self, *, headless: bool = True, log: Path | None = None):
self.port = free_port()
handle = open(log, "ab") if log else subprocess.DEVNULL
self.proc = subprocess.Popen(
[GECKODRIVER, "--port", str(self.port)],
stdout=handle, stderr=subprocess.STDOUT,
)
self.base = f"http://127.0.0.1:{self.port}"
self._wait_for_driver()
args = ["-headless"] if headless else []
answer = self._call("POST", "/session", {"capabilities": {"alwaysMatch": {
"browserName": "firefox",
"moz:firefoxOptions": {"args": args},
# Never silently accept a bad certificate: the endpoint policy and
# the TLS trust union are release claims (H12, A06), and a browser
# that ignored certificates would hide a failure of either.
"acceptInsecureCerts": False,
}}})["value"]
self.session = answer["sessionId"]
self.version = answer["capabilities"].get("browserVersion", "?")
# ------------------------------------------------------------- plumbing
def _wait_for_driver(self) -> None:
deadline = time.monotonic() + 30
while time.monotonic() < deadline:
try:
urllib.request.urlopen(self.base + "/status", timeout=2)
return
except Exception:
time.sleep(0.2)
raise WebDriverError("geckodriver never became ready")
def _call(self, method: str, path: str, payload=None, timeout=120):
data = json.dumps(payload).encode() if payload is not None else None
request = urllib.request.Request(
self.base + path, data=data, method=method,
headers={"Content-Type": "application/json"},
)
try:
with urllib.request.urlopen(request, timeout=timeout) as response:
return json.loads(response.read().decode() or "{}")
except urllib.error.HTTPError as exc:
body = exc.read().decode()[:400]
raise WebDriverError(f"{method} {path} -> {exc.code}: {body}") from None
def _s(self, path: str) -> str:
return f"/session/{self.session}{path}"
def quit(self) -> None:
try:
self._call("DELETE", self._s(""))
except Exception:
pass
self.proc.terminate()
try:
self.proc.wait(timeout=10)
except subprocess.TimeoutExpired:
self.proc.kill()
# ------------------------------------------------------------ commands
def go(self, url: str) -> None:
self._call("POST", self._s("/url"), {"url": url})
@property
def url(self) -> str:
return self._call("GET", self._s("/url"))["value"]
@property
def title(self) -> str:
return self._call("GET", self._s("/title"))["value"]
def source(self) -> str:
return self._call("GET", self._s("/source"))["value"]
def js(self, script: str, *args):
return self._call("POST", self._s("/execute/sync"),
{"script": script, "args": list(args)})["value"]
def find(self, css: str, *, required=True):
try:
answer = self._call("POST", self._s("/element"),
{"using": "css selector", "value": css})
except WebDriverError:
if required:
raise
return None
return list(answer["value"].values())[0]
def find_all(self, css: str) -> list[str]:
answer = self._call("POST", self._s("/elements"),
{"using": "css selector", "value": css})
return [list(v.values())[0] for v in answer["value"]]
def text(self, element: str) -> str:
return self._call("GET", self._s(f"/element/{element}/text"))["value"]
def attr(self, element: str, name: str):
return self._call("GET", self._s(f"/element/{element}/attribute/{name}"))["value"]
def prop(self, element: str, name: str):
return self._call("GET", self._s(f"/element/{element}/property/{name}"))["value"]
def click(self, element: str) -> None:
self._call("POST", self._s(f"/element/{element}/click"), {})
def clear(self, element: str) -> None:
self._call("POST", self._s(f"/element/{element}/clear"), {})
def type(self, element: str, text: str) -> None:
self._call("POST", self._s(f"/element/{element}/value"), {"text": text})
def keys(self, text: str) -> None:
"""Sends keys to whatever has focus — the only way to test tab order."""
self._call("POST", self._s("/actions"), {"actions": [{
"type": "key", "id": "keyboard",
"actions": [a for ch in text for a in (
{"type": "keyDown", "value": ch}, {"type": "keyUp", "value": ch})],
}]})
def active(self):
answer = self._call("GET", self._s("/element/active"))
return list(answer["value"].values())[0]
# ------------------------------------------------------------- waiting
def wait_for(self, css: str, *, timeout=90, gone=False):
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
found = self.find(css, required=False)
if (found is None) if gone else (found is not None):
return found
time.sleep(0.25)
raise WebDriverError(
f"{'still present' if gone else 'never appeared'}: {css}")
def wait_until(self, script: str, *, timeout=90, what=""):
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
if self.js(f"return ({script})"):
return True
time.sleep(0.25)
raise WebDriverError(f"condition never held: {what or script}")
class Site:
"""The application, served the production-shaped way, for the browser."""
def __init__(self, backend: Path, db_path: Path, log: Path, env=None):
self.port = free_port()
handle = open(log, "ab")
self.proc = subprocess.Popen(
[str(backend / ".venv/bin/uvicorn"), "app.main:app",
"--host", "127.0.0.1", "--port", str(self.port)],
cwd=str(backend), stdout=handle, stderr=subprocess.STDOUT,
env={**os.environ, "AIDND_DB_PATH": str(db_path),
"AIDND_DATABASE_URL": "", "DATABASE_URL": "", **(env or {})},
)
self.url = f"http://127.0.0.1:{self.port}"
deadline = time.monotonic() + 90
while time.monotonic() < deadline:
if self.proc.poll() is not None:
raise WebDriverError(f"server exited early; see {log}")
try:
urllib.request.urlopen(self.url + "/api/settings", timeout=2)
return
except Exception:
time.sleep(0.15)
raise WebDriverError(f"server never became ready; see {log}")
def api(self, method: str, path: str, payload=None, timeout=600):
data = json.dumps(payload).encode() if payload is not None else None
request = urllib.request.Request(
f"{self.url}/api{path}", data=data, method=method,
headers={"Content-Type": "application/json"} if data else {})
with urllib.request.urlopen(request, timeout=timeout) as response:
body = response.read().decode()
return json.loads(body) if body else None
def stop(self) -> None:
if self.proc.poll() is None:
self.proc.terminate()
try:
self.proc.wait(timeout=20)
except subprocess.TimeoutExpired:
self.proc.kill()