From 451ebe08de9586bdd80343649f7e5a7e5408e4dc Mon Sep 17 00:00:00 2001 From: jp Date: Fri, 18 Sep 2026 07:01:55 -0700 Subject: [PATCH 1/2] fix(cli): a daemon mine never sends mode: null (#525) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Upstream v3.8 made `--mode` default to None so an unset flag could inherit a per-source default. `cmd_mine` normalizes it once at the top — `mode = getattr(args, "mode", None) or "projects"` — under a comment saying every branch below AND the daemon payload read it. One branch did not. The daemon-strict call passed `args.mode` raw, 128 lines after the normalization, while the sibling payload eight lines earlier used the resolved value. So the daemon's MineBody rejected every daemon-strict mine: 422 {"loc": ["body", "mode"], "msg": "Input should be a valid string", "input": None} That is why a grep cannot find this class of defect: the token `args.mode` is identical at a correct site and a broken one, and only the DISTANCE FROM THE NORMALIZATION differs. The audit is an AST walk for raw `args.mode` READS — `Attribute(value=Name('args'), attr='mode')` with ctx Load — because a dict-literal walk finds three payload sites and misses the fourth, which is a call keyword. `cmd_repair`'s `args.mode = "from-sqlite"` is excluded by ctx: a Store on a different subcommand's flag. FOUR SITES, ONE CLASS: cmd_mine (daemon-strict call) passed args.mode raw THE reported 422 _forward_mine_to_hub same, to a `mempalace serve` hub latent _post_daemon_mine_cli now REFUSES None cmd_pending_drain's poster `.get("mode", "convos")` -> None The seam refuses rather than substituting its default. Substituting would trade a loud 422 for a silently wrong corpus: a caller meaning "projects" would mine in "convos" and nothing would say so. Its docstring now records that a default parameter is NOT a guard against an explicit None — a default applies only when the argument is omitted, and the `str` annotation is not enforced at runtime. That strictness created a hazard two files away, which is why the audit covered the seam's CALLERS and not only the sites building its payload: the drain posted `request.get("mode", "convos")`, and a `.get` default does not fire on a present-but-null key. A queued `"mode": null` would have raised inside `pending_queue.replay`'s loop and taken every remaining request with it — one failed request turned into a dead drain, as a side effect of hardening. MEASURED, daemon-strict, no --mode given: every input shape that reached the POST sent null — a directory with or without --wing, with --background, with --no-tunnels, and a prose file. A `.jsonl` transcript was the one shape that did not, and only because it never reached the daemon: the mineable-path guard stops it locally at exit 2, which is separate and intended. PATH EXCLUSIVITY, MEASURED RATHER THAN ASSUMED: the two payload builders are selected BY CONFIGURATION, NOT BY INPUT SHAPE. The daemon-strict branch ends in `sys.exit`, and the hub forward call sits after it in `cmd_mine`'s body, so no single run can take both; `_mine_args_forwardable` gates on flags only, with no file-vs-directory condition. Both facts are pinned by structural tests. A `mine ` and a `mine ` therefore take the same path as each other — whichever the configuration selects — so fixing either site alone would have left the other consumer broken for all inputs, not for one shape of input. Tests assert on what goes ON THE WIRE, because that is where the contract lives: the producer is cli.py and the consumer is the daemon's search_models.MineBody, in another repository. A unit test reading a local variable would have passed throughout the outage. Five input shapes run the REAL binary against a stub HTTP daemon that records the body and answers 422 on a null mode exactly as production does. Closes #525 Co-Authored-By: Claude Opus 5 --- mempalace/cli.py | 39 ++++- tests/test_cli_mine_mode_payload.py | 234 ++++++++++++++++++++++++++ tests/test_mine_hub_payload_mode.py | 158 +++++++++++++++++ tests/test_pending_drain_null_mode.py | 80 +++++++++ 4 files changed, 508 insertions(+), 3 deletions(-) create mode 100644 tests/test_cli_mine_mode_payload.py create mode 100644 tests/test_mine_hub_payload_mode.py create mode 100644 tests/test_pending_drain_null_mode.py diff --git a/mempalace/cli.py b/mempalace/cli.py index 60eedfdd06..2810c9d21d 100644 --- a/mempalace/cli.py +++ b/mempalace/cli.py @@ -538,6 +538,15 @@ def _post_daemon_mine_cli( was asked for and its absence cannot creep back in. A daemon predating the field ignores it and blocks as before. + ⚠️ ``mode`` is annotated ``str`` and defaults to ``"convos"``, and + **neither is a guard against an explicit ``None``**: a default applies + only when the argument is OMITTED, and an annotation is not enforced at + runtime. A caller passing ``mode=None`` therefore put ``"mode": null`` + on the wire and the daemon's ``MineBody`` answered 422 for every + daemon-strict mine (#525). That is why this function now raises rather + than quietly substituting the default — substituting would trade a loud + 422 for a silently wrong corpus. + Note what "success" means with ``background=True``: the daemon has taken the request into its durable pending-mines queue, not that the mine has finished. That is the right contract for a replay — the queue's job is a @@ -547,6 +556,17 @@ def _post_daemon_mine_cli( import urllib.error import urllib.request + if mode is None: + # Refuse rather than substitute the default. A caller that reaches + # here with None has skipped its own normalization (#525 was exactly + # that), and quietly mining in "convos" when the caller meant + # "projects" would trade a loud 422 for a silently wrong corpus — + # the worse half of the same trade. + raise ValueError( + "_post_daemon_mine_cli: mode must be a string, not None — " + 'resolve it at the call site (`args.mode or "projects"`)' + ) + headers = {"content-type": "application/json"} api_key = os.environ.get("PALACE_API_KEY", "").strip() if api_key: @@ -1817,7 +1837,10 @@ def _forward_mine_to_hub(args, palace_path: str) -> bool: arguments = { "source": os.path.abspath(os.path.expanduser(args.dir)), - "mode": args.mode, + # Normalized, never the raw attribute: --mode defaults to None + # upstream, and a null here reaches the hub's own validator + # the same way it reached the daemon's in #525. + "mode": getattr(args, "mode", None) or "projects", "agent": args.agent, "limit": args.limit or 0, "dry_run": bool(args.dry_run), @@ -2214,7 +2237,12 @@ def cmd_mine(args): ok = _post_daemon_mine_cli( directory, wing=wing, - mode=args.mode, + # `mode`, not `args.mode`: upstream v3.8 made --mode default to + # None and this function normalized it at the top for exactly + # this reason. Passing the raw attribute put `"mode": null` on + # the wire and the daemon's MineBody rejected every daemon-strict + # mine with 422 body.mode (#525). + mode=mode, background=getattr(args, "background", False), ) sys.exit(0 if ok else 1) @@ -5216,7 +5244,12 @@ def post(request: dict) -> bool: return _post_daemon_mine_cli( request["dir"], request["wing"], - request.get("mode", "convos"), + # `or`, not a .get default: a queued line may carry an explicit + # `"mode": null` (the hooks write whatever they were given), and + # `.get("mode", "convos")` returns None for that, not the + # default. Since #525 the poster REFUSES None, so the difference + # is a crashed drain versus a drained queue. + request.get("mode") or "convos", background=True, ) diff --git a/tests/test_cli_mine_mode_payload.py b/tests/test_cli_mine_mode_payload.py new file mode 100644 index 0000000000..123af25d66 --- /dev/null +++ b/tests/test_cli_mine_mode_payload.py @@ -0,0 +1,234 @@ +"""No daemon mine payload may carry ``mode: null`` (#525). + +Upstream v3.8 made ``--mode`` default to ``None`` so an unset flag could inherit +a per-source default. ``cmd_mine`` normalizes it once at the top — +``mode = getattr(args, "mode", None) or "projects"`` — under a comment saying +every branch below *and the daemon payload* read it. One branch did not: the +daemon-strict call passed ``args.mode`` raw, 128 lines after the normalization, +while the sibling payload eight lines earlier used the resolved value. + +The daemon's ``MineBody`` then rejected it: + + 422 {"loc": ["body", "mode"], "msg": "Input should be a valid string", + "input": None} + +⭐ Measured before the fix, daemon-strict, no ``--mode`` given: **every input +shape that reached the POST sent null** — a directory with or without +``--wing``, with ``--background``, with ``--no-tunnels``, and a prose file. The +one shape that did *not* 422 was a ``.jsonl`` transcript, and only because it +never reached the daemon at all: the mineable-path guard stops it locally with +exit 2, which is separate, intended behaviour. + +These tests assert on what goes **on the wire**, because that is where the +contract lives — the producer is ``cli.py`` and the consumer is the daemon's +``search_models.MineBody``, in another repository. A unit test that inspected a +local variable would have passed throughout the outage. +""" + +import ast +import inspect +import json +import os +import subprocess +import sys +import threading +from http.server import BaseHTTPRequestHandler, HTTPServer + +import pytest + +from mempalace import cli + + +# ── a stub daemon that records what it is sent ───────────────────────── + + +class _Recorder(BaseHTTPRequestHandler): + bodies: list = [] + + def do_POST(self): + n = int(self.headers.get("Content-Length") or 0) + raw = self.rfile.read(n).decode() if n else "" + try: + body = json.loads(raw) + except ValueError: + body = {"__unparseable__": raw} + type(self).bodies.append(body) + # Mirror MineBody: a null mode is a 422, exactly as production answers. + if body.get("mode", "") is None: + self.send_response(422) + self.end_headers() + self.wfile.write(b'{"detail":[{"loc":["body","mode"]}]}') + return + self.send_response(202) + self.send_header("Content-Type", "application/json") + self.end_headers() + self.wfile.write(b'{"queued": true}') + + def do_GET(self): + self.send_response(200) + self.send_header("Content-Type", "application/json") + self.end_headers() + self.wfile.write(b'{"ok": true}') + + def log_message(self, *a): + pass + + +@pytest.fixture +def daemon(): + """A real HTTP daemon on an ephemeral port, recording every body.""" + _Recorder.bodies = [] + srv = HTTPServer(("127.0.0.1", 0), _Recorder) + threading.Thread(target=srv.serve_forever, daemon=True).start() + yield srv, _Recorder.bodies + srv.shutdown() + + +@pytest.fixture +def workspace(tmp_path): + src = tmp_path / "src" + src.mkdir() + (src / "notes.md").write_text("# notes\n\nsome prose for the miner\n") + (src / "a.jsonl").write_text('{"type":"user","message":{"content":"hi"}}\n') + home = tmp_path / "home" + (home / ".mempalace").mkdir(parents=True) + return src, home + + +def _run(srv, home, argv): + """Invoke the REAL CLI, daemon-strict, against the stub.""" + env = dict(os.environ) + env.update( + { + "HOME": str(home), + "PALACE_DAEMON_URL": "http://127.0.0.1:%d" % srv.server_address[1], + "PALACE_API_KEY": "x", + "PALACE_DAEMON_STRICT": "1", + "MEMPALACE_AGENT_NAME": "probe", + } + ) + root = os.path.dirname(os.path.dirname(os.path.abspath(cli.__file__))) + return subprocess.run( + [sys.executable, "-m", "mempalace.cli", "mine"] + argv, + cwd=root, + env=env, + capture_output=True, + text=True, + timeout=120, + ) + + +# ── the wire ─────────────────────────────────────────────────────────── + + +class TestNoMinePayloadCarriesANullMode: + @pytest.mark.parametrize( + "shape", + ["dir", "dir --wing", "dir --background", "dir --no-tunnels", "prose file"], + ) + def test_the_posted_mode_is_always_a_string(self, daemon, workspace, shape): + srv, bodies = daemon + src, home = workspace + argv = { + "dir": [str(src)], + "dir --wing": [str(src), "--wing", "probe"], + "dir --background": [str(src), "--wing", "probe", "--background"], + "dir --no-tunnels": [str(src), "--wing", "probe", "--no-tunnels"], + "prose file": [str(src / "notes.md"), "--wing", "probe"], + }[shape] + + proc = _run(srv, home, argv) + + assert bodies, "no POST reached the daemon for %s: %s" % (shape, proc.stderr[-300:]) + for body in bodies: + assert body.get("mode") is not None, ( + "%s put mode=null on the wire — MineBody answers 422 (#525)" % shape + ) + assert isinstance(body["mode"], str) + assert proc.returncode == 0, proc.stderr[-300:] + + def test_an_explicit_mode_is_passed_through_unchanged(self, daemon, workspace): + """The control: the bug was a MISSING flag, so a given one must survive.""" + srv, bodies = daemon + src, home = workspace + proc = _run(srv, home, [str(src), "--wing", "probe", "--mode", "convos"]) + assert proc.returncode == 0, proc.stderr[-300:] + assert [b["mode"] for b in bodies] == ["convos"] + + +# ── the seam refuses rather than guesses ─────────────────────────────── + + +class TestTheSeamRefusesANullMode: + def test_post_daemon_mine_cli_raises_on_none(self): + """Substituting the default here would trade a loud 422 for a + silently wrong corpus: a caller that meant "projects" would mine in + "convos" and nothing would say so.""" + with pytest.raises(ValueError, match="must be a string, not None"): + cli._post_daemon_mine_cli("/tmp/x", wing="w", mode=None) + + def test_the_message_names_the_caller_s_obligation(self): + with pytest.raises(ValueError) as exc: + cli._post_daemon_mine_cli("/tmp/x", wing="w", mode=None) + assert "resolve it at the call site" in str(exc.value) + + +# ── structural: no builder may read the raw attribute ────────────────── + + +class TestNoPayloadBuilderReadsArgsModeRaw: + def test_no_raw_args_mode_read_survives(self): + """Enumerate raw `args.mode` READS, not two syntactic shapes. + + ⭐ The audit that found only one of the two bugs walked dict literals + with a `"mode"` key. That finds the hub payload and the daemon + payload and MISSES the daemon-strict call, because that one is a + call KEYWORD — `_post_daemon_mine_cli(..., mode=args.mode, ...)`. + Matching on the shape of the *value* instead catches every position, + including ones nobody has written yet. + + `cmd_repair` assigns `args.mode = "from-sqlite"`; that is a Store on + a different subcommand's flag, not a read of the mine flag, so + `ctx` is what separates them — hence the isinstance check rather + than a name match. + """ + tree = ast.parse(inspect.getsource(cli)) + reads = [ + n.lineno + for n in ast.walk(tree) + if isinstance(n, ast.Attribute) + and n.attr == "mode" + and isinstance(n.value, ast.Name) + and n.value.id == "args" + and isinstance(n.ctx, ast.Load) + ] + assert reads == [], ( + "raw `args.mode` read at line(s) %s — --mode defaults to None " + "upstream, so any unnormalized read is #525 again" % reads + ) + + def test_the_audit_itself_would_have_caught_the_call_keyword(self): + """A control on the instrument: the dict-literal-only audit passes + on the pre-fix source while the read-based one fails. Without this, + "the audit is clean" means nothing.""" + broken = "def f(args):\n return g(mode=args.mode)\n" + tree = ast.parse(broken) + + dict_only = [ + n + for n in ast.walk(tree) + if isinstance(n, ast.Dict) + for k in n.keys + if isinstance(k, ast.Constant) and k.value == "mode" + ] + reads = [ + n + for n in ast.walk(tree) + if isinstance(n, ast.Attribute) + and n.attr == "mode" + and isinstance(n.value, ast.Name) + and n.value.id == "args" + and isinstance(n.ctx, ast.Load) + ] + assert dict_only == [], "the weaker audit sees nothing here" + assert len(reads) == 1, "the read-based audit sees the call keyword" diff --git a/tests/test_mine_hub_payload_mode.py b/tests/test_mine_hub_payload_mode.py new file mode 100644 index 0000000000..02b8692cc2 --- /dev/null +++ b/tests/test_mine_hub_payload_mode.py @@ -0,0 +1,158 @@ +"""The hub forwarder must not send `mode: null` either (#525, path 1). + +There are TWO daemon-ish mine payload builders, and they are mutually exclusive +**by configuration, not by input shape**: + +* `cmd_mine`'s daemon-strict branch posts to the palace-daemon and then + `sys.exit`s — so under daemon-strict the hub code below it is unreachable; +* `_forward_mine_to_hub` posts to a local `mempalace serve` hub, and only runs + when daemon-strict is OFF and a live hub is registered for the palace. + +⭐ That is why the reported 422 came from the daemon path and this one stayed +latent: the reporter's machine is daemon-strict, so it never reached here. +`_mine_args_forwardable` gates on flags only — no file-vs-directory condition — +so neither path is selected by what you point `mine` at. + +This test drives path 1 directly, because no subprocess run under daemon-strict +can: the exit above it fires first. +""" + +import argparse +import json + +import pytest + +from mempalace import cli + + +def _args(**kw): + base = dict( + dir="/tmp/some/source", + mode=None, + agent="probe", + limit=0, + dry_run=False, + extract=None, + wing="probe", + ) + base.update(kw) + return argparse.Namespace(**base) + + +class _Resp: + status = 200 + + def __enter__(self): + return self + + def __exit__(self, *a): + return False + + def read(self): + return json.dumps({"ok": True}).encode() + + +@pytest.fixture +def hub(monkeypatch): + """A live-looking hub, with every POST body recorded.""" + from mempalace import server_registry + + monkeypatch.setattr(cli, "_hub_forward_disabled", lambda: False) + monkeypatch.setattr(server_registry, "read_live_serverinfo", lambda p: {"port": 1}) + monkeypatch.setattr(server_registry, "client_base_url", lambda i: "http://127.0.0.1:1") + + bodies = [] + + def fake_urlopen(req, timeout=None): + if req.data: + bodies.append(json.loads(req.data.decode())) + return _Resp() + + monkeypatch.setattr("urllib.request.urlopen", fake_urlopen) + return bodies + + +def _mine_arguments(bodies): + """The mine arguments out of the JSON-RPC envelope, or fail loudly. + + Explicitly NOT `body.get("arguments", body)`: that falls back to the + envelope, whose top level has no "mode", so a missing payload reads as + `mode=None` — absence reported as a null value, which is precisely the + bug under test wearing the costume of a test failure. + """ + out = [] + for body in bodies: + params = body.get("params") + if not isinstance(params, dict): + continue + args = params.get("arguments") + assert isinstance(args, dict), "envelope had no arguments dict: %r" % body + out.append(args) + assert out, "no mine payload was posted: %r" % bodies + return out + + +class TestTheHubPayloadNeverCarriesANullMode: + def test_an_unset_mode_is_normalized(self, hub): + try: + cli._forward_mine_to_hub(_args(mode=None), "/tmp/palace") + except SystemExit: + pass + for args_ in _mine_arguments(hub): + assert args_.get("mode") is not None, ( + "the hub payload carried mode=null — the same defect as the " + "daemon path, one consumer over (#525)" + ) + assert args_["mode"] == "projects" + + def test_an_explicit_mode_survives(self, hub): + try: + cli._forward_mine_to_hub(_args(mode="convos"), "/tmp/palace") + except SystemExit: + pass + args_ = _mine_arguments(hub)[0] + assert args_["mode"] == "convos", "a given --mode must not be rewritten" + + +class TestTheTwoPathsAreSelectedByConfigNotInputShape: + def test_daemon_strict_exits_before_the_hub_code(self): + """Structural, because it is the claim that decides the blast radius. + + The daemon-strict branch ends in `sys.exit`, and the hub forward call + appears after it in `cmd_mine`'s body — so no input can reach both. + """ + import ast + import inspect + + src = inspect.getsource(cli.cmd_mine) + tree = ast.parse(src) + exits, forwards = [], [] + for node in ast.walk(tree): + if isinstance(node, ast.Call): + fn = getattr(node.func, "attr", getattr(node.func, "id", "")) + if fn == "exit": + exits.append(node.lineno) + if fn == "_forward_mine_to_hub": + forwards.append(node.lineno) + assert forwards, "hub forward call not found in cmd_mine" + assert exits, "no sys.exit found in cmd_mine" + assert min(exits) < min(forwards), ( + "the daemon-strict branch must exit before the hub forward, or a " + "single run could take both paths" + ) + + def test_forwardability_does_not_depend_on_file_vs_directory(self): + """`_mine_args_forwardable` gates on FLAGS only. + + Stated because the issue framed the split as file-vs-directory. It is + not: both shapes take whichever path the configuration selects. + """ + import inspect + + src = inspect.getsource(cli._mine_args_forwardable) + for token in ("isdir", "isfile", ".jsonl", "splitext"): + assert token not in src, ( + f"forwardability now inspects {token!r}; the two paths would " + "then be selectable by input shape and this PR's reasoning " + "about blast radius needs redoing" + ) diff --git a/tests/test_pending_drain_null_mode.py b/tests/test_pending_drain_null_mode.py new file mode 100644 index 0000000000..97134211ed --- /dev/null +++ b/tests/test_pending_drain_null_mode.py @@ -0,0 +1,80 @@ +"""A queued `"mode": null` must not crash the drain (#525). + +`pending drain` posts whatever the queue holds, and the queue is written by +hooks that pass through whatever they were given. + +⚠️ `request.get("mode", "convos")` returns **None** for an explicit +`"mode": null` — a `.get` default only fires on a MISSING key, never on a +present-but-null one. Once `_post_daemon_mine_cli` refuses None (#525), that +difference is a crashed drain versus a drained queue: the ValueError escapes +`pending_queue.replay`'s loop and takes every remaining request with it. + +⭐ The seam's strictness is right, and it created this hazard two files away. +That is why #525 audited the seam's CALLERS and not only the sites that build +its payload — a guard added in one file can turn a recoverable failure into an +unrecoverable one somewhere else. +""" + +import argparse +import json +from unittest.mock import MagicMock, patch + +import pytest + +from mempalace import cli +from mempalace import pending_queue as pq + + +def _drain_args(): + return argparse.Namespace(yes=True, json=False, quiet=False, pending_action="drain") + + +def _queue(tmp_path, request): + d = tmp_path / "pending" + d.mkdir() + (d / "2026-09-17.jsonl").write_text(json.dumps(request) + "\n") + return d + + +class TestAQueuedNullModeStillDrains: + def test_it_falls_back_instead_of_propagating(self, tmp_path): + d = _queue(tmp_path, {"dir": "/x/a.jsonl", "wing": "2g", "mode": None}) + poster = MagicMock(return_value=True) + with ( + patch.object(pq, "PENDING_DIR", d), + patch("mempalace.cli._daemon_strict", return_value=True), + patch("mempalace.cli._post_daemon_mine_cli", poster), + pytest.raises(SystemExit) as exc, + ): + cli.cmd_pending_drain(_drain_args()) + + assert exc.value.code == 0 + assert poster.call_count == 1 + assert poster.call_args[0][2] == "convos", ( + "a null mode must fall back at the caller; the poster refuses None" + ) + + def test_a_missing_mode_still_falls_back_too(self, tmp_path): + """The case the `.get` default already handled — it must keep working.""" + d = _queue(tmp_path, {"dir": "/x/b.jsonl", "wing": "2g"}) + poster = MagicMock(return_value=True) + with ( + patch.object(pq, "PENDING_DIR", d), + patch("mempalace.cli._daemon_strict", return_value=True), + patch("mempalace.cli._post_daemon_mine_cli", poster), + pytest.raises(SystemExit), + ): + cli.cmd_pending_drain(_drain_args()) + assert poster.call_args[0][2] == "convos" + + def test_an_explicit_mode_is_not_overridden(self, tmp_path): + d = _queue(tmp_path, {"dir": "/x/c.jsonl", "wing": "2g", "mode": "projects"}) + poster = MagicMock(return_value=True) + with ( + patch.object(pq, "PENDING_DIR", d), + patch("mempalace.cli._daemon_strict", return_value=True), + patch("mempalace.cli._post_daemon_mine_cli", poster), + pytest.raises(SystemExit), + ): + cli.cmd_pending_drain(_drain_args()) + assert poster.call_args[0][2] == "projects" From cce76873dd4a2810467ef2eec89a212b64a210b1 Mon Sep 17 00:00:00 2001 From: jp Date: Fri, 18 Sep 2026 07:04:24 -0700 Subject: [PATCH 2/2] docs(fork-changes): a daemon mine never sends mode: null (#525) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit seq 158 from `--next-seq` after the final fetch; `commit: HEAD`; `fork_pr` filled in once the REST create returns a number rather than guessed. Three renderers re-run; check-docs clean. `test_live_readme_check_clean` caught the stale README before this commit — the entry existed and the renderers had not run, which is exactly the drift that test is for. Part of #525 Co-Authored-By: Claude Opus 5 --- FORK_CHANGELOG.md | 55 +++++++++++++++++ README.md | 1 + .../2026-09-17-mine-mode-never-null.yaml | 61 +++++++++++++++++++ website/public/llms-full.txt | 1 + 4 files changed, 118 insertions(+) create mode 100644 docs/fork-changes/2026-09-17-mine-mode-never-null.yaml diff --git a/FORK_CHANGELOG.md b/FORK_CHANGELOG.md index 1023da4fd6..e4e398d9ea 100644 --- a/FORK_CHANGELOG.md +++ b/FORK_CHANGELOG.md @@ -271,6 +271,61 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). ### Fixed +- **daemon-strict `mempalace mine` sent `mode: null` and every mine 422'd** (`HEAD` — pending resolution) + Upstream v3.8 made `--mode` default to `None` so an unset flag could + inherit a per-source default. `cmd_mine` normalizes it once at the top — + `mode = getattr(args, "mode", None) or "projects"` — under a comment + saying every branch below *and the daemon payload* read it. + + ⭐ **One branch did not.** The daemon-strict call passed `args.mode` raw, + 128 lines after the normalization, while the sibling payload eight lines + earlier used the resolved value. So the daemon's `MineBody` rejected + every daemon-strict mine: + + 422 {"loc": ["body", "mode"], + "msg": "Input should be a valid string", "input": None} + + That is why a grep cannot find this class of defect: the token + `args.mode` is identical at a correct site and a broken one, and only the + *distance from the normalization* differs. The audit was an AST walk over + every dict literal carrying a `"mode"` key and every call passing + `mode=`, which found four sites where the report named one. + + Measured before the fix, daemon-strict with no `--mode`: **every input + shape that reached the POST sent null** — a directory with or without + `--wing`, with `--background`, with `--no-tunnels`, and a prose file. The + one shape that did not was a `.jsonl` transcript, and only because it + never reached the daemon: the mineable-path guard stops it locally at + exit 2, which is separate and intended. + + Four sites, one class: + + * the daemon-strict call now passes the resolved `mode`; + * `_forward_mine_to_hub` normalizes too — it posts to a `mempalace serve` + hub rather than the daemon, so it is a different consumer and a latent + case rather than the reported one; + * `_post_daemon_mine_cli` **refuses** `None` instead of substituting its + default. Substituting would trade a loud 422 for a silently wrong + corpus: a caller meaning "projects" would mine in "convos" and nothing + would say so; + * ⚠️ `pending drain`'s poster used `request.get("mode", "convos")`, and a + `.get` default does **not** fire on a present-but-null key. With the + seam now refusing `None`, a queued `"mode": null` would have raised + inside `pending_queue.replay`'s loop and taken every remaining request + with it. The seam's strictness created that hazard two files away, + which is why the fix audited the seam's CALLERS and not only the sites + that build its payload. + + The tests assert on what goes **on the wire** — the producer is `cli.py` + and the consumer is the daemon's `search_models.MineBody`, in another + repository — because a unit test reading a local variable would have + passed throughout the outage. A structural test walks the AST and fails + if any payload reads `args.mode` raw again. + + *Tests:* 12 (test_cli_mine_mode_payload.py: 5 input shapes against a real stub HTTP daemon recording the body, explicit-mode control, seam refusal x2, AST guard; test_pending_drain_null_mode.py: null/missing/explicit queued mode). 4 mutations, each killing its own tests: revert the call site (6), the hub payload (1), the seam guard (2), the drain fallback (1). + *Files:* `mempalace/cli.py` + + - **check-docs examines every mention of a PR, not just the first, and matches state words as words** (`HEAD` — pending resolution) `scripts/check-docs.sh` step 4 did `grep … | head -1` per document, so only the FIRST line mentioning a PR number contributed to that document's claimed diff --git a/README.md b/README.md index 8ca233d922..5eb09f3141 100644 --- a/README.md +++ b/README.md @@ -290,6 +290,7 @@ The full enumeration of fork-ahead changes. The canonical source is [`docs/fork- | Description | Upstream PR | Fork commit | |---|---|---| +| daemon-strict `mempalace mine` sent `mode: null` and every mine 422'd | — | `HEAD` — pending resolution | | check-docs examines every mention of a PR, not just the first, and matches state words as words | — | `HEAD` — pending resolution | | a daemon outage exits 2 (palace unavailable), not 1 (no results) | — | `HEAD` — pending resolution | | check-docs must not match a PR number against a commit-sha prefix | — | `HEAD` — pending resolution | diff --git a/docs/fork-changes/2026-09-17-mine-mode-never-null.yaml b/docs/fork-changes/2026-09-17-mine-mode-never-null.yaml new file mode 100644 index 0000000000..a7e86b50a0 --- /dev/null +++ b/docs/fork-changes/2026-09-17-mine-mode-never-null.yaml @@ -0,0 +1,61 @@ +seq: 158 +id: mine-mode-never-null +date: '2026-09-17' +bucket: Fixed +commit: HEAD +area: CLI +summary: 'daemon-strict `mempalace mine` sent `mode: null` and every mine 422''d' +body: | + Upstream v3.8 made `--mode` default to `None` so an unset flag could + inherit a per-source default. `cmd_mine` normalizes it once at the top — + `mode = getattr(args, "mode", None) or "projects"` — under a comment + saying every branch below *and the daemon payload* read it. + + ⭐ **One branch did not.** The daemon-strict call passed `args.mode` raw, + 128 lines after the normalization, while the sibling payload eight lines + earlier used the resolved value. So the daemon's `MineBody` rejected + every daemon-strict mine: + + 422 {"loc": ["body", "mode"], + "msg": "Input should be a valid string", "input": None} + + That is why a grep cannot find this class of defect: the token + `args.mode` is identical at a correct site and a broken one, and only the + *distance from the normalization* differs. The audit was an AST walk over + every dict literal carrying a `"mode"` key and every call passing + `mode=`, which found four sites where the report named one. + + Measured before the fix, daemon-strict with no `--mode`: **every input + shape that reached the POST sent null** — a directory with or without + `--wing`, with `--background`, with `--no-tunnels`, and a prose file. The + one shape that did not was a `.jsonl` transcript, and only because it + never reached the daemon: the mineable-path guard stops it locally at + exit 2, which is separate and intended. + + Four sites, one class: + + * the daemon-strict call now passes the resolved `mode`; + * `_forward_mine_to_hub` normalizes too — it posts to a `mempalace serve` + hub rather than the daemon, so it is a different consumer and a latent + case rather than the reported one; + * `_post_daemon_mine_cli` **refuses** `None` instead of substituting its + default. Substituting would trade a loud 422 for a silently wrong + corpus: a caller meaning "projects" would mine in "convos" and nothing + would say so; + * ⚠️ `pending drain`'s poster used `request.get("mode", "convos")`, and a + `.get` default does **not** fire on a present-but-null key. With the + seam now refusing `None`, a queued `"mode": null` would have raised + inside `pending_queue.replay`'s loop and taken every remaining request + with it. The seam's strictness created that hazard two files away, + which is why the fix audited the seam's CALLERS and not only the sites + that build its payload. + + The tests assert on what goes **on the wire** — the producer is `cli.py` + and the consumer is the daemon's `search_models.MineBody`, in another + repository — because a unit test reading a local variable would have + passed throughout the outage. A structural test walks the AST and fails + if any payload reads `args.mode` raw again. +fork_pr: 527 +tests: '12 (test_cli_mine_mode_payload.py: 5 input shapes against a real stub HTTP daemon recording the body, explicit-mode control, seam refusal x2, AST guard; test_pending_drain_null_mode.py: null/missing/explicit queued mode). 4 mutations, each killing its own tests: revert the call site (6), the hub payload (1), the seam guard (2), the drain fallback (1).' +files: +- mempalace/cli.py diff --git a/website/public/llms-full.txt b/website/public/llms-full.txt index 683dab0c16..cdcd80db7d 100644 --- a/website/public/llms-full.txt +++ b/website/public/llms-full.txt @@ -309,6 +309,7 @@ The full enumeration of fork-ahead changes. The canonical source is [`docs/fork- | Description | Upstream PR | Fork commit | |---|---|---| +| daemon-strict `mempalace mine` sent `mode: null` and every mine 422'd | — | `HEAD` — pending resolution | | check-docs examines every mention of a PR, not just the first, and matches state words as words | — | `HEAD` — pending resolution | | a daemon outage exits 2 (palace unavailable), not 1 (no results) | — | `HEAD` — pending resolution | | check-docs must not match a PR number against a commit-sha prefix | — | `HEAD` — pending resolution |