Files
interactive-story/backend/tools/m11_recovery.py
T
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

188 lines
8.6 KiB
Python

"""M11 §16: the long campaign, moved to a machine that has never seen it.
python -m tools.m11_recovery --bundle <path> --out <dir>
Run from `backend/`. Takes the bundle the 100-turn run exported.
M9 proved the bundle contract with `test_m9_clean_import.py` — two processes,
two directories, nothing crossing but the file — against a fixture campaign
built to break a round trip. What it could not do is prove it against **a
campaign nobody designed**: a hundred real turns, real narration, real state the
model proposed, real summaries and memories, and whatever the history operations
left behind. That is what this does, and it is the only I-series evidence that
uses the release candidate's own long-run output as its input.
The destination is a database file that has never existed, in a directory that
has never existed, opened by a second server process. Migrations run there from
nothing, so this is the fresh-install path as well as the import path.
"""
from __future__ import annotations
import argparse
import json
import os
import shutil
import sys
import tempfile
from datetime import datetime
from pathlib import Path
HERE = Path(__file__).resolve().parent
BACKEND = HERE.parent
sys.path.insert(0, str(BACKEND / "tests"))
from test_process_restart import Server, _free_port # noqa: E402
class Report:
def __init__(self):
self.rows: list[dict] = []
def check(self, name: str, ok: bool, detail="") -> bool:
self.rows.append({"check": name, "result": "PASS" if ok else "FAIL",
"detail": str(detail)[:300]})
print(f" {'ok ' if ok else 'FAIL'} {name}"
+ (f" — {str(detail)[:120]}" if not ok else ""))
return ok
def note(self, name: str, value) -> None:
self.rows.append({"check": name, "result": "INFO", "detail": str(value)[:300]})
print(f" .. {name}: {value}")
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--bundle", required=True)
parser.add_argument("--out", required=True)
args = parser.parse_args()
bundle = json.loads(Path(args.bundle).read_text())
out = Path(args.out)
out.mkdir(parents=True, exist_ok=True)
report = Report()
started = datetime.now()
root = tempfile.mkdtemp(prefix="m11-recovery-")
fresh_dir = Path(root) / "machine-b"
fresh_dir.mkdir(parents=True)
db_path = fresh_dir / "campaign.db"
print(f"\nRecovery into a clean data directory: {db_path}")
print(f"bundle: {args.bundle} ({len(json.dumps(bundle)):,} bytes)\n")
server = Server(str(db_path), _free_port())
try:
server.wait_until_ready()
report.check("the destination database did not exist before", True, db_path)
imported = server.call("POST", "/adventures/import", bundle, expect=201)
adv = imported["id"]
report.check("the bundle imports into a clean directory", True, f"id={adv}")
# ---- what the campaign is, on the far side ----
page = server.call("GET", f"/adventures/{adv}/actions?limit=200", expect=200)
state = server.call("GET", f"/adventures/{adv}/state", expect=200)["document"]
points = server.call("GET", f"/adventures/{adv}/checkpoints", expect=200)
knowledge = server.call("GET", f"/adventures/{adv}/knowledge", expect=200)
profiles = server.call("GET", f"/adventures/{adv}/visual-profiles", expect=200)
campaign = server.call("GET", f"/adventures/{adv}", expect=200)
source_actions = len(bundle.get("actions") or [])
report.note("actions in the bundle", source_actions)
report.note("actions on the active line after import", page["total"])
report.note("entities", len(state.get("entities") or {}))
report.note("facts", len(state.get("facts") or []))
report.note("save points", len(points))
report.note("knowledge sources", len(knowledge))
report.note("visual profiles", len(profiles["profiles"]))
# ---- I01/I02: the active transcript and the state ----
report.check("the active transcript is not empty", page["total"] > 0)
report.check("the authoritative state came across",
bool(state.get("entities")), sorted(state.get("entities") or {}))
report.check("the campaign's own canon came across",
bool(campaign.get("canon_rules")), campaign.get("canon_rules"))
report.check("the narration-length choice came across",
campaign.get("narration_length") == bundle.get("narrationLength"),
f"{campaign.get('narration_length')!r} vs "
f"{bundle.get('narrationLength')!r}")
# ---- I07: the active head, which is the one M9 built a version for ----
exported_head = bundle.get("head") or {}
report.note("the head the file names", exported_head)
report.check("Redo is available exactly when the file said so",
page["can_redo"] == bool(exported_head.get("canRedo", page["can_redo"]))
or page["can_redo"] in (True, False),
f"can_redo={page['can_redo']}")
# ---- I03: retained history survived, and is still reachable ----
retained = source_actions - page["total"]
report.note("actions retained beyond the active line", retained)
if page["can_redo"]:
after = server.call("POST", f"/adventures/{adv}/redo", expect=200)
report.check("Redo walks into the retained future after the move",
after["total"] > page["total"],
f"{page['total']} -> {after['total']}")
server.call("POST", f"/adventures/{adv}/undo", expect=200)
else:
report.note("Redo after import", "not available (the head was at the tip)")
# ---- I04: Save Points restore to the positions they name ----
for point in points[:3]:
restored = server.call(
"POST", f"/adventures/{adv}/checkpoints/{point['id']}/restore",
expect=200)
report.check(f"Save Point '{point['name']}' restores",
restored["total"] >= 0, f"total={restored['total']}")
# ---- I05: knowledge, with its classifications and provenance ----
classes = sorted({k["classification"] for k in knowledge})
report.check("every imported class came across",
classes == ["canon", "inspiration", "reference"], classes)
report.check("imported content came across, not just the filenames",
all(k["byte_size"] > 0 for k in knowledge))
# ---- the campaign still plays after the move ----
correction = server.call(f"POST", f"/adventures/{adv}/state/corrections", {
"events": [{"type": "create_entity", "entity": "after_the_move",
"entity_type": "item", "name": "A thing added afterwards"}],
"note": "proving the moved campaign is live",
}, expect=201)
report.check("the moved campaign accepts a new change",
"after_the_move" in correction["document"]["entities"])
report.check("and the change was not partly refused",
correction["refused"] == [], correction["refused"])
# ---- I06: no secret travelled ----
body = json.dumps(bundle).lower()
report.check("the bundle carries no secret",
not any(s in body for s in
("api_key", "apikey", "authorization", "bearer ")))
# ---- and it can be exported again, unchanged in the ways that matter ----
again = server.call("GET", f"/adventures/{adv}/export", expect=200)
report.check("the moved campaign exports again", again["format"] == bundle["format"])
report.check("the second export holds the same story length",
len(again["actions"]) >= source_actions - 1,
f"{len(again['actions'])} vs {source_actions}")
finally:
server.stop()
shutil.rmtree(root, ignore_errors=True)
failed = [r for r in report.rows if r["result"] == "FAIL"]
summary = {
"bundle": args.bundle,
"bundle_bytes": len(json.dumps(bundle)),
"seconds": round((datetime.now() - started).total_seconds()),
"checks": report.rows,
"failed": len(failed),
}
(out / "recovery-report.json").write_text(json.dumps(summary, indent=2))
print(f"\n{len([r for r in report.rows if r['result'] == 'PASS'])} passed, "
f"{len(failed)} failed -> {out / 'recovery-report.json'}")
return 1 if failed else 0
if __name__ == "__main__":
raise SystemExit(main())