diff --git a/README.md b/README.md index cf71bc5d..2f205b5a 100644 --- a/README.md +++ b/README.md @@ -2,12 +2,12 @@ [![CI](https://github.com/ascalva/mind-palace/actions/workflows/ci.yml/badge.svg)](https://github.com/ascalva/mind-palace/actions/workflows/ci.yml) [![Lean](https://github.com/ascalva/mind-palace/actions/workflows/lean.yml/badge.svg)](https://github.com/ascalva/mind-palace/actions/workflows/lean.yml) -[![laws](https://img.shields.io/badge/laws-105_rows_in_16_families-blue)](docs/LAWS.md) -[![Lean statements](https://img.shields.io/badge/Lean-375_statements_judged-blue)](formal/README.md) +[![laws](https://img.shields.io/badge/laws-106_rows_in_16_families-blue)](docs/LAWS.md) +[![Lean statements](https://img.shields.io/badge/Lean-380_statements_judged-blue)](formal/README.md) [![sorry](https://img.shields.io/badge/sorry-0-brightgreen)](formal/sorry-budget) [![kernels](https://img.shields.io/badge/kernel_replay-6_checkers-6f42c1)](formal/check.sh) [![attacks](https://img.shields.io/badge/attacks-232_with_controls-blue)](formal/PalaceTest) -[![tests](https://img.shields.io/badge/tests-3673-brightgreen)](docs/runbook.md) +[![tests](https://img.shields.io/badge/tests-3721-brightgreen)](docs/runbook.md) [![coverage](https://img.shields.io/badge/coverage-77%25-green)](pyproject.toml) [![mypy](https://img.shields.io/badge/mypy-0_errors_in_core-brightgreen)](pyproject.toml) [![sealed core](https://img.shields.io/badge/sealed_core-zero_egress-6f42c1)](scripts/check_imports.py) @@ -33,7 +33,7 @@ read "reference:openai-math:Local-smoothing" chunk 3 There are five sorts: a *field* (a score on every node), a *region* (a set of nodes), *chains* (paths that spell a word over the edge types), a *witness* (the commit that minted an edge) and a *text* (one record). The verbs move between them: `near`, `diffuse`, `reach`, `relate`, `trace`, `walk … via`, `witness`, `read`. The connectives compose them: `and`, `or`, `minus`, `then`; `within`, `over` and `as of` restrict; `top k`, `atleast t`, `far` and `not` bound; `assume … in` evaluates a sentence under a hypothesis, and its answer is a `Hyp` beside the actual answer, never a fact. The grammar is `core/sentence/grammar.py`; [`docs/query/asking.md`](docs/query/asking.md) is the guide to writing a sentence. -Two surfaces share one grant. `mind-palace query ""` runs a sentence read-only from the live checkout. The Ambassador's MCP server has one read tool, `query`, and the Open WebUI bridge serves the same manifest. Both hold the Ambassador's grant with the hypothetical overlay the owner switched on; `--as ` labels the asker in the query log and grants nothing. A sentence that cannot be answered is refused with the reason: the production that failed to parse, the sort rule it broke, the plane no grant covers, the note that matched twice. It is not answered with nearest neighbours instead. +Two surfaces share one grant. `mind-palace query ""` runs a sentence read-only from the live checkout. The Ambassador's MCP server has one read tool, `query`, and the Open WebUI bridge serves the same manifest. Both hold the Ambassador's grant with the hypothetical overlay the owner switched on; `--as ` labels the asker in the query log and grants nothing. A third surface holds a narrower grant: `scripts/palace_mcp.py --role guest` serves an external agent `query` and `overview` alone, read-only over the dialogue, the repository's code and docs, the papers and the observed records, never the notes or the interpretations derived from them (SCO-9, `docs/design-notes/dn-guest-principal.md`); it is how the code instance below serves a coding agent. A sentence that cannot be answered is refused with the reason: the production that failed to parse, the sort rule it broke, the plane no grant covers, the note that matched twice. It is not answered with nearest neighbours instead. ## From a sentence to an answer @@ -121,12 +121,12 @@ A law has one row in [`docs/LAWS.md`](docs/LAWS.md): its statement, the structur | | | |---|---| | toolchain | Lean `v4.36.0-rc2`, Mathlib; Plausible for the attacks | -| the library | 38 proof modules, 37 models, 27 statement files; 25,652 lines of models and proofs, 3,810 of statements, 5,757 of attacks | -| theorems | 1,538 proved in `formal/Palace`; 375 statements in `formal/Spec` judged identical by the comparator | -| the ledger | 105 rows in 16 families, 381 cited declarations, 92 law markers checked against the rows | +| the library | 38 proof modules, 37 models, 27 statement files; 25,700 lines of models and proofs, 3,841 of statements, 5,757 of attacks | +| theorems | 1,544 proved in `formal/Palace`; 380 statements in `formal/Spec` judged identical by the comparator | +| the ledger | 106 rows in 16 families, 386 cited declarations, 93 law markers checked against the rows | | attacks | 232 Plausible attacks and 206 negative controls over 33 modules, fixed seeds | | axioms | `propext`, `Classical.choice`, `Quot.sound`; `sorry` 0 | -| the replay | 56,231 declarations accepted by all six checkers on the run of `formal/check.sh` this commit was built with | +| the replay | 56,238 declarations accepted by all six checkers on the run of `formal/check.sh` this commit was built with | | families | memberships · Laplacian, balance and spectral · cut and conductance · curvature · the global event clock · the shared prose plane · capability scopes · the abstraction ultrametric σ* · bridges · the retrieval curve · the query sentence algebra · the ingress · stored vectors · the growth readout · the utility field · the temporal snapshot | ## The mathematics @@ -177,7 +177,7 @@ The build's own history is a dataset. Every commit's structure is snapshotted in ```sh uv sync --extra dev -uv run pytest -q -m 'not live and not podman and not needs_vault and not needs_restic' # the deterministic tier: 3,673 tests +uv run pytest -q -m 'not live and not podman and not needs_vault and not needs_restic' # the deterministic tier: 3,721 tests uv run mypy # strict core: 0 errors (the 67 in tests/ are pinned) uv run python scripts/check_imports.py # the sealed core names no network module uv run python -m ops.type_gate # every core-reaching package is type-checked diff --git a/agents/ambassador/mcp.py b/agents/ambassador/mcp.py index 0f56904d..d00620fd 100644 --- a/agents/ambassador/mcp.py +++ b/agents/ambassador/mcp.py @@ -11,9 +11,18 @@ grant's W_Σ allows — dialogue capture (provenance fixed by role, never by the text) and interpreted relation edges. Long operations (dream, relate, sync) wake models and run on demand. +`--role guest` serves an external agent instead (dn-guest-principal): `query` under the read-only +`GUEST` grant, over the dialogue, the repo's code and docs, the papers and the observed records, +never the notes or their interpretations, and `overview`; no write tool, no request, no `status`. + Protocol: JSON-RPC 2.0, one message per line (MCP stdio transport). `initialize`, `ping`, -`tools/list`, `tools/call`; anything printed by an operation is captured and returned as the tool's -text, so stdout carries protocol messages only. Diagnostics go to stderr. +`tools/list`, `tools/call`; a line that is no request is answered with JSON-RPC's error for it, +a request whose reply cannot be written with an internal error, and the server reads on +(`_answer`, `serve`). Stdout carries protocol messages only. The launcher writes +the replies to a copy of file descriptor 1 and points the descriptor itself at stderr +(`protocol_stream`), and a tool runs with `sys.stdout` pointed at stderr (`Server.handle`), so +what an operation, a library under it or a child process writes joins the diagnostics on +stderr. The client that spawned the process holds both streams. """ from __future__ import annotations @@ -21,11 +30,15 @@ import contextlib import io import json +import math import sys import traceback from collections.abc import Callable from pathlib import Path -from typing import Any +from typing import TYPE_CHECKING, Any, TextIO + +if TYPE_CHECKING: + from core.query import QueryEngine PROTOCOL_VERSION = "2025-06-18" SERVER_INFO = {"name": "mind-palace", "version": "0.1.0"} @@ -33,6 +46,39 @@ # them — Open WebUI appends them to the system message whenever the palace tools are on — loads it # on every chat with no prompt to paste. One text for every client and for eval/ambassador_e2e.py. INSTRUCTIONS = (Path(__file__).with_name("brief.md")).read_text(encoding="utf-8").strip() +# The guest's surface (`palace_mcp.py --role guest`, dn-guest-principal) has instructions of its +# own: the brief speaks of tools the guest does not have. +GUEST_INSTRUCTIONS = ( + "A read-only view of a mind-palace instance. Ask with query: a sentence of the query algebra, " + "not keywords, over the strata this grant reads: the dialogue (chat turns, transcripts and the " + "documents written in them), reference (the repository's code and docs), curated (papers) and " + "observed. Name them with over, as in near \"\" over dialogue reference curated " + "observed: near, diffuse S and a causal walk's endpoints read the owner's notes unless over " + "names other strata, and over is a mask, so a walk from a turn to the files it wrote needs " + "over reference. A clause over the notes or the interpretations derived from them is " + "refused. So are assume, the version chains (trace, reach D) and every do request. Verbs: " + "near, diffuse S from, reach F|C from, walk from via , witness, " + "read \"\" (a repo path, code// for a file of a repository the instance " + "lands, transcript//, a dialogue ref, reference:). overview counts " + "what this grant reads, shows the grant, and says when the instance embeds nothing: near " + "then ranks by the lexical index, and S has no edges." +) +# What `overview` says of an instance that embeds nothing (dn-palace-lite), on either surface. +EMBEDDING_OFF = "off: this instance embeds nothing; near ranks by the lexical index" + + +def _planes(grant: Any) -> list[dict[str, Any]]: + """A grant's planes as `overview` shows them.""" + return [ + { + "strata": sorted(s.sigma.strata), + "edges": sorted(s.edges.fibers), + "clock": s.time.clock.value, + "write": bool(s.authority.store_write), + } + for s in grant.scopes + ] + class Ambassador: """Tool implementations. Stores and the launcher open lazily, once per process.""" @@ -74,24 +120,15 @@ def overview(self) -> dict[str, Any]: e.provenance for e in VaultCatalog(cfg.paths.vault_catalog).active_entries() ) edges = Counter(e.rel_type for e in self.engine._get("edges").all()) - planes = [ - { - "strata": sorted(s.sigma.strata), - "edges": sorted(s.edges.fibers), - "clock": s.time.clock.value, - "write": bool(s.authority.store_write), - } - for s in AMBASSADOR.scopes - ] out: dict[str, Any] = { "catalog_by_provenance": dict(catalog), "vector_rows": self.engine._get("vectors").count(), "relation_edges": dict(edges), "versions": self.engine._get("versions").count(), - "your_grant": planes, + "your_grant": _planes(AMBASSADOR), } if not cfg.embedding.enabled: # the lite profile: say so, and what ranks instead - out["embedding"] = "off: this instance embeds nothing; near ranks by the lexical index" + out["embedding"] = EMBEDDING_OFF lexical = self.engine._get("lexical") if lexical is not None: out["lexical_units"] = lexical.count() @@ -256,6 +293,172 @@ def code_sources(cfg: Any) -> list[dict[str, Any]]: return out +# What a scope refusal tells the guest would fix it: the grant's strata, named with `over`. +GUEST_SCOPE_HINT = ( + "; the guest grant reads dialogue, reference, curated and observed (name them with " + "`over dialogue reference curated observed`, or some of them), never the mirror or the " + "interpreted stratum, and has no overlay for `assume`, no version plane for `trace` or " + "`reach D`, and no write bit for `do`" +) + + +# What a refusal raised while a sentence ran tells the guest, by class: one fixed sentence each. +# The reason raised there may quote what a store holds, so it is never passed on (`_refused`). +GUEST_RAN = { + "lookup": ( + "a name in the sentence was not found in the strata this grant reads, or what it names " + "cannot be read as text: spell a ref as an answer's `ref` is spelled (a repo path from " + "the repository's root such as `core/query.py`, `code//` for a file of a " + "repository the instance lands, `transcript//`, a dialogue ref, " + "`reference:`), name with `over` the strata a title is to be found in, and ask " + "`near \"\" over dialogue reference curated observed` for refs to start from" + ), + "ambiguous": ( + "a name in the sentence fits more than one node of the strata this grant reads, or more " + "than one commit; write the ref in full in place of a title, and more of the sha after " + "`as of`" + ), + "unsupported": ( + "the sentence compiles and the stores cannot answer it as written: `as of` takes a " + "commit the citation graph holds a cut at, and a verb walks only the relations recorded " + "for the nodes it names; drop `as of` or change the relation" + ), + "scope": ( + "a ref in the sentence names something outside the strata its clauses read: a transcript " + "turn is read by walking C or under `over dialogue_transcript`, and `read` returns a " + "record only of the stratum its ref's spelling names" + ), + "sort": "the sentence's sorts did not compose when it ran; give each connective the sorts " + "its grammar takes", + "parse": "the sentence could not be read when it ran; write one sentence of the query " + "algebra", + "busy": "the instance is busy and took no request; ask again later", + "error": ( + "the sentence failed while it ran, for a reason this surface does not show; the " + "instance's query log keeps it for the owner" + ), +} +# What `overview` tells the guest when it fails, whatever failed. +GUEST_OVERVIEW_FAILED = ("the overview could not be counted on this instance, for a reason this " + "surface does not show; `query` may still answer") + + +class GuestRefusal(PermissionError): + """A refusal as the guest reads it: its class, then what the surface says of it, one of two + texts (`_refused` chooses). A sentence the compiler refuses is told the compiler's reason + with every quoted run replaced by its length (`redact_reason`): compiling reads the sentence + and the grant and no store, so that reason holds the asker's own words and nothing a store + holds. A sentence refused while it ran against the stores is told one fixed sentence for its + class (`GUEST_RAN`), never the reason, which may quote what a store holds and which the + redaction, pairing quotes by position, does not reliably hide. A scope refusal of either + kind adds what the grant reads.""" + + def __init__(self, kind: str, said: str) -> None: + super().__init__(f"{kind}: {said}" + (GUEST_SCOPE_HINT if kind == "scope" else "")) + + +def _refused(sentence: Any, e: BaseException, trace: Any = False) -> GuestRefusal: + """The refusal the guest reads for `e`, which asking `sentence` raised. The sentence is + compiled again, alone, with a trace when the call asked for one, as it was compiled the + first time: that reads the sentence and the grant and no store. If the compiler refuses it, + the refusal is the compiler's, and the guest reads its class and its reason, redacted. If it + compiles, `e` came from running it against the stores, and the guest reads `e`'s class and + that class's fixed sentence; `e`'s own words are never shown. Whatever fails in here is an + `error`, said in the fixed sentence.""" + kind = "error" + try: + from core.query import GUEST + from core.sentence.plan import compile_sentence + from core.sentence.surface import is_command, redact_reason, refusal_class + from core.sentence.trace import Trace + + kind = refusal_class(e) or "error" + # the trace renders the parse while it compiles, so a sentence can fail to compile with + # it alone: compiled again without it, that sentence would read as refused in the run + t = Trace() if bool(trace) else None + try: + compile_sentence(sentence, GUEST, role="guest" if is_command(sentence) else None, + trace=t) + except Exception as c: + return GuestRefusal(refusal_class(c) or "error", redact_reason(str(c))) + except Exception: + kind = "error" + return GuestRefusal(kind, GUEST_RAN.get(kind, GUEST_RAN["error"])) + + +class Guest: + """The guest's tools (dn-guest-principal): the one read under `GUEST`, and counts over the + strata it reads. No write tool, no request, and no `status`, which lists the owner's tasks. + A tool's body raises `GuestRefusal` and nothing else, whatever fails in it: the engine is + built on first use, inside the body, so a configuration or a store that cannot be opened is + a refusal too.""" + + def __init__(self) -> None: + self._engine: QueryEngine | None = None + + @property + def engine(self) -> QueryEngine: + if self._engine is None: + from core.query import QueryEngine + + self._engine = QueryEngine() + return self._engine + + @engine.setter + def engine(self, engine: QueryEngine) -> None: + self._engine = engine + + def query(self, sentence: str, trace: bool = False) -> dict[str, Any]: + """A sentence under `GUEST`, logged as `mcp`/`guest`. The universe withholds what the + stores say of the notes (`hide_mirror`); a refusal is a `GuestRefusal`, its text chosen + by `_refused`.""" + try: + from core.query import GUEST + from core.sentence.surface import ask_logged + + return ask_logged(sentence, GUEST, surface="mcp", role="guest", engine=self.engine, + trace=bool(trace)).to_dict() + except Exception as e: + raise _refused(sentence, e, trace) from None + + def overview(self) -> dict[str, Any]: + """The catalog's active entries of the classes the grant's strata hold, the curated + store's chunks, and the grant; then what the Ambassador's overview says of the lite + profile (dn-palace-lite), over the same classes: that the instance embeds nothing, when + it is so; the lexical index's current units of those classes; and each repository of a + lexical code source, with the commit it last landed and how far its ref has moved since. + Nothing of the mirror or the interpreted stratum is counted, not even in a total. A + failure is a `GuestRefusal` of one fixed sentence.""" + try: + from collections import Counter + + from core.kernel.clearance import classes_of + from core.query import GUEST + from core.stores.catalog import VaultCatalog + + cfg = self.engine.config + classes = classes_of(GUEST.strata) + admitted = {str(p) for p in classes} + entries = VaultCatalog(cfg.paths.vault_catalog).active_entries() + catalog = Counter(str(e.provenance) for e in entries if str(e.provenance) in admitted) + out: dict[str, Any] = { + "catalog_by_provenance": dict(catalog), + "literature_chunks": self.engine._get("curated").count(), + "your_grant": _planes(GUEST), + } + if not cfg.embedding.enabled: + out["embedding"] = EMBEDDING_OFF + lexical = self.engine._get("lexical") + if lexical is not None: # the units of the classes the grant reads, never a total + out["lexical_units"] = lexical.count(classes=classes) + code = code_sources(cfg) + if code: + out["code"] = code + return out + except Exception: + raise GuestRefusal("error", GUEST_OVERVIEW_FAILED) from None + + def _launch_agents() -> list[dict[str, str]]: """The stack's LaunchAgents: running (pid) or idle, and the last exit status.""" import subprocess @@ -390,30 +593,79 @@ def _schema(props: dict[str, Any], required: list[str]) -> dict[str, Any]: ), ] +# The guest's table: the one read and the counts, nothing that writes, requests or reads the +# owner's tasks (dn-guest-principal). +GUEST_TOOLS: list[tuple[str, str, dict[str, Any], str]] = [ + ( + "query", + "The one read, under a read-only grant over dialogue, reference (the repository's code and " + "docs), curated (papers) and observed: a sentence of the query algebra, not keywords. " + 'Verbs: near "text" | diffuse S from [beta b] | reach F|C from [depth n] ' + "[back|forward] | walk from [to ] via | witness \"" | read "" [chunk n]. Connectives and, or, minus, then; adjectives within ' + ", over ; top k, atleast t, far, not. Name the strata with over, " + 'separated by spaces: near "x" over dialogue reference curated observed. A refusal ' + "names what the grant reads; trace: true shows the work.", + TOOLS[0][2], + "query", + ), + ( + "overview", + "Counts over the strata this grant reads; your grant.", + _schema({}, []), + "overview", + ), +] + +ROLES = ("ambassador", "guest") # the principals this server can speak for + class Server: - def __init__(self) -> None: - self._amb: Ambassador | None = None + """The protocol, for one principal: the Ambassador's surface by default, or the guest's + (`role="guest"`: `GUEST_TOOLS`, `GUEST_INSTRUCTIONS`, the `Guest` tools).""" + + def __init__(self, role: str = "ambassador") -> None: + if role not in ROLES: + raise ValueError(f"role is one of {', '.join(ROLES)}, not {role!r}") + self.role = role + self.tools = GUEST_TOOLS if role == "guest" else TOOLS + self.instructions = GUEST_INSTRUCTIONS if role == "guest" else INSTRUCTIONS + self._amb: Ambassador | Guest | None = None @property - def amb(self) -> Ambassador: + def amb(self) -> Ambassador | Guest: if self._amb is None: - self._amb = Ambassador() + self._amb = Guest() if self.role == "guest" else Ambassador() return self._amb - def handle(self, msg: dict[str, Any]) -> dict[str, Any] | None: + def handle(self, msg: Any) -> dict[str, Any] | None: + """The reply to one message, `None` for a notification. A message that is not a request + object (an array, which this protocol version has no batch for, a number, a string, + null), an id that is no string or number, and params that are not an object are each + refused with JSON-RPC's invalid request, the id null when the request's cannot be used. + `initialize` answers with the protocol version the client asks for when it is a string + and with the server's own otherwise, as MCP answers a version a server does not support: + a value of another type is not repeated, so no nesting a client sends there makes a reply + that `json.dumps` cannot write.""" + if not isinstance(msg, dict): + return _err(None, -32600, "invalid request: a message is a JSON object") method, mid = msg.get("method"), msg.get("id") if mid is None: # a notification (e.g. notifications/initialized) return None + if not _is_id(mid): + return _err(None, -32600, "invalid request: an id is a string or a number") + if not isinstance(msg.get("params") or {}, dict): + return _err(mid, -32600, "invalid request: params is a JSON object") if method == "initialize": - client = (msg.get("params") or {}).get("protocolVersion") or PROTOCOL_VERSION + asked = (msg.get("params") or {}).get("protocolVersion") + version = asked if isinstance(asked, str) and asked else PROTOCOL_VERSION return _ok( mid, { - "protocolVersion": client, + "protocolVersion": version, "serverInfo": SERVER_INFO, "capabilities": {"tools": {"listChanged": False}}, - "instructions": INSTRUCTIONS, + "instructions": self.instructions, }, ) if method == "ping": @@ -423,7 +675,8 @@ def handle(self, msg: dict[str, Any]) -> dict[str, Any] | None: mid, { "tools": [ - {"name": n, "description": d, "inputSchema": s} for n, d, s, _ in TOOLS + {"name": n, "description": d, "inputSchema": s} + for n, d, s, _ in self.tools ] }, ) @@ -431,22 +684,28 @@ def handle(self, msg: dict[str, Any]) -> dict[str, Any] | None: return _ok(mid, {method.split("/")[0]: []}) if method == "tools/call": params = msg.get("params") or {} - spec = next((t for t in TOOLS if t[0] == params.get("name")), None) + spec = next((t for t in self.tools if t[0] == params.get("name")), None) if spec is None: return _err(mid, -32602, f"unknown tool {params.get('name')!r}") - try: - result = getattr(self.amb, spec[3])(**(params.get("arguments") or {})) - text = json.dumps(result, ensure_ascii=False, default=str) - return _ok(mid, {"content": [{"type": "text", "text": text}], "isError": False}) - except Exception as e: # a refused or failed call is a result, not a crash - print(traceback.format_exc(), file=sys.stderr) - return _ok( - mid, - { - "content": [{"type": "text", "text": f"{type(e).__name__}: {e}"}], - "isError": True, - }, - ) + # The tools are made, and the tool runs, with `sys.stdout` pointed at stderr: a line + # printed to stdout in there would be read by the client as a protocol message. The + # diagnostic is printed in here as well, so a process started with no stderr drops + # it; outside, `print` to a stderr that is None would fall back to stdout. + with contextlib.redirect_stdout(sys.stderr): + try: + result = getattr(self.amb, spec[3])(**(params.get("arguments") or {})) + text = json.dumps(result, ensure_ascii=False, default=str) + return _ok(mid, {"content": [{"type": "text", "text": text}], + "isError": False}) + except Exception as e: # a refused or failed call is a result, not a crash + print(traceback.format_exc(), file=sys.stderr) + return _ok( + mid, + { + "content": [{"type": "text", "text": f"{type(e).__name__}: {e}"}], + "isError": True, + }, + ) return _err(mid, -32601, f"method not found: {method}") @@ -458,19 +717,89 @@ def _err(mid: Any, code: int, message: str) -> dict[str, Any]: return {"jsonrpc": "2.0", "id": mid, "error": {"code": code, "message": message}} -def serve(stdin: Any = None, stdout: Any = None) -> None: +def _is_id(mid: Any) -> bool: + """A JSON-RPC id this server echoes: a string or a finite number, never a bool.""" + if isinstance(mid, float): + return math.isfinite(mid) + return isinstance(mid, str) or (isinstance(mid, int) and not isinstance(mid, bool)) + + +def _diagnose() -> None: + """The traceback of the exception being handled, on stderr when the process has one.""" + if sys.stderr is not None: # `print` to a stderr that is None writes to stdout + with contextlib.suppress(Exception): + print(traceback.format_exc(), file=sys.stderr) + + +def _answer(server: Server, line: str) -> dict[str, Any] | None: + """The reply to one line of the stream, `None` for a notification. A line that is not JSON + is a parse error; so is a number past Python's limit on the digits it converts, and nesting + past the stack, which `json.loads` raises as `ValueError` and `RecursionError`. Whatever + else fails while the message is handled is answered as an internal error, its traceback on + stderr when the process has one, and so is a reply `json.dumps` cannot write (`serve`). + Either way the server goes on to the next line.""" + try: + msg = json.loads(line) + except (ValueError, RecursionError): + return _err(None, -32700, "parse error") + try: + return server.handle(msg) + except Exception: + _diagnose() + mid = msg.get("id") if isinstance(msg, dict) else None + return _err(mid if _is_id(mid) else None, -32603, "internal error") + + +def protocol_stream() -> TextIO: + """The process's stdout, kept for the protocol alone. File descriptor 1 is copied to a + descriptor of its own for the replies, one a child process does not inherit, and then + pointed at stderr's file, or at the null device when the process has no stderr. Whatever + writes to descriptor 1 from then on, C code, a child process that inherits it or + `sys.__stdout__`, lands with the diagnostics and never in the stream the client reads; + `Server.handle` points `sys.stdout` at stderr as well, for a stream that is not + descriptor 1. The launcher (`scripts/palace_mcp.py`) serves on it.""" + import fcntl + import os + + if sys.stdout is not None: + sys.stdout.flush() + keep = fcntl.fcntl(1, fcntl.F_DUPFD_CLOEXEC, 3) + try: + os.fstat(2) + os.dup2(2, 1) + except OSError: # no stderr: what is written to descriptor 1 is dropped + null = os.open(os.devnull, os.O_WRONLY) + os.dup2(null, 1) + os.close(null) + return open(keep, "w", encoding="utf-8", newline="\n") + + +def serve(stdin: Any = None, stdout: Any = None, server: Server | None = None) -> None: + """Speak MCP on stdio for `server`, the Ambassador's surface when none is given.""" stdin, stdout = stdin or sys.stdin, stdout or sys.stdout - server = Server() + server = server if server is not None else Server() for line in stdin: if not line.strip(): continue - try: - msg = json.loads(line) - except json.JSONDecodeError: - stdout.write(json.dumps(_err(None, -32700, "parse error")) + "\n") - stdout.flush() - continue - reply = server.handle(msg) + reply = _answer(server, line) if reply is not None: - stdout.write(json.dumps(reply, ensure_ascii=False) + "\n") + try: + line = json.dumps(reply, ensure_ascii=False) + except Exception: + # a reply `json.dumps` cannot write, a value nested past the stack among the + # causes (`RecursionError`): the request is answered as an internal error with + # its id, which a reply carries only as a string, a number or null + _diagnose() + reply = _err(reply.get("id"), -32603, "internal error") + line = json.dumps(reply, ensure_ascii=False) + try: + # a lone surrogate, which UTF-8 does not encode: a sentence may hold one, and an + # answer repeats its sentence. Asked here, not left to the stream: one with + # `surrogateescape`, as Python's UTF-8 mode makes stdout, writes a surrogate from + # U+DC80 to U+DCFF as a byte that is not UTF-8 instead of refusing it + line.encode("utf-8") + stdout.write(line + "\n") + except UnicodeEncodeError: + # the same JSON, written as ASCII + stdout.write(json.dumps(reply, ensure_ascii=True) + "\n") stdout.flush() diff --git a/config/instances/code.toml b/config/instances/code.toml index df5a7ddc..095dd408 100644 --- a/config/instances/code.toml +++ b/config/instances/code.toml @@ -11,11 +11,13 @@ # tree. `palace repo-sync` lands each one's files as items of the reference stratum, a changed file # a new version and a file gone from the ref retired, with their lexical units and no vector; a # second run after no commit lands nothing. No daemon runs for this instance: it embeds nothing, -# and nothing in it wakes a model. +# and nothing in it wakes a model. An external agent is served the read-only guest's surface, +# `query` and `overview` alone (docs/design-notes/dn-guest-principal.md). # # MIND_PALACE_OVERLAY=config/instances/code.toml uv run scripts/palace.py repo-sync # MIND_PALACE_OVERLAY=config/instances/code.toml uv run scripts/palace.py query 'near "x" over reference' # MIND_PALACE_OVERLAY=config/instances/code.toml uv run python scripts/palace_mcp.py +# MIND_PALACE_OVERLAY=config/instances/code.toml uv run python scripts/palace_mcp.py --role guest [instance] id = "code" diff --git a/core/ingest/ingress.py b/core/ingest/ingress.py index 8c43b553..fc14009b 100644 --- a/core/ingest/ingress.py +++ b/core/ingest/ingress.py @@ -50,7 +50,7 @@ from core.ingest.files import check_dir, daemon_uid, read_bounded, real_dir, written_by_one from core.kernel.clearance import classes_of from core.kernel.config import Config, get_config -from core.query import AMBASSADOR, AMBASSADOR_OVERLAY, OPERATOR, Grant +from core.query import AMBASSADOR, AMBASSADOR_OVERLAY, GUEST, OPERATOR, Grant from core.sentence import ast from core.sentence.plan import Plan from core.sentence.types import IllScopedSentence, Sort @@ -69,6 +69,11 @@ # The open corpus's runner (dn-corpus-instance §3.2) speaks the corpus role under the same grant: # its role opens the corpus streams and writes `corpus/` in the observed place alone. _DAEMON_ROLES: dict[str, str] = {"inbox": "ambassador", "corpus": "ambassador"} +# The roles that only read: no spool, no table role, so a command can neither be compiled for one +# (its grant has the write bit on no plane, ING-1) nor spooled (`write_request` knows only the +# spools' roles). The guest is an external agent's principal (`core.query.GUEST`, +# dn-guest-principal). +_READ_ROLES: dict[str, str] = {"guest": "guest"} # The roles whose spool the palace group may write: the agents run under their own account # (plane-principals), and the Ambassador's grant is the least the ingress gives. The operator's # spool is the owner's account's alone. @@ -96,13 +101,15 @@ class Busy(RuntimeError): def grant_for(role: str) -> Grant: """The grant a role speaks under at the ingress, a spool's or one of the daemon's own jobs'. An unknown role is refused, never defaulted.""" - kind = _ROLE_GRANTS.get(role) or _DAEMON_ROLES.get(role) + kind = _ROLE_GRANTS.get(role) or _DAEMON_ROLES.get(role) or _READ_ROLES.get(role) if kind == "operator": return OPERATOR if kind == "ambassador": return AMBASSADOR_OVERLAY if get_config().query.hypotheticals else AMBASSADOR + if kind == "guest": + return GUEST raise IllScopedSentence(f"the ingress knows no role {role!r}; one of " - f"{', '.join(sorted({*_ROLE_GRANTS, *_DAEMON_ROLES}))}") + f"{', '.join(sorted({*_ROLE_GRANTS, *_DAEMON_ROLES, *_READ_ROLES}))}") @dataclass(frozen=True) diff --git a/core/origin_view.py b/core/origin_view.py index bc0b2e3a..b23f5396 100644 --- a/core/origin_view.py +++ b/core/origin_view.py @@ -50,6 +50,7 @@ from __future__ import annotations +from collections.abc import Callable from typing import Any from core.stores.causal_edges import CausalEdge, CausalEdgeStore @@ -77,12 +78,17 @@ def origin( *, causal_edges: CausalEdgeStore, reference_edges: ReferenceEdgeStore, + admit: Callable[[CausalEdge], bool] | None = None, ) -> CausalEdge | None: """The C-edge whose witnessed commit minted the durable edge `edge_id` — the derived regenerable two-hop join `C ∘ commit-keying` (dn-agentic-loop §2.4b EX-2). Returns `None` when `edge_id` is not a known reference edge, carries no commit key, or no causal edge witnessed that commit (a legitimate empty answer — e.g. a pre-integration commit; NOT a falsifier). + With `admit`, only the causal edges it accepts are candidates, judged before the lowest is + chosen: a reader that may not see an edge gets the answer of a store without it, never `None` + because that edge came first (dn-guest-principal §5). Without it every edge is a candidate. + Read-only over the two stores; mints nothing; the returned link is dispositional (E_disp — never enters `A_geom`/L). Scoped to reference-edge (X_cite) ids — the durable kind that carries a resolvable `commit_sha` (the recorded target-kind boundary, F-AL7 / §3 Q3).""" @@ -98,9 +104,10 @@ def origin( # `pair_cut_sha` = the full sha (finding-0111); file/doc edges carry '' and so never match a # non-empty key. Deterministic on the (rare) multi-witness case: lowest (event_order, edge_id). matches = [ - _causal_edge_from_row(row) - for row in causal_edges.all_edges() - if row["pair_cut_sha"] == commit_key + edge + for edge in (_causal_edge_from_row(row) for row in causal_edges.all_edges() + if row["pair_cut_sha"] == commit_key) + if admit is None or admit(edge) ] if not matches: return None diff --git a/core/query.py b/core/query.py index 6c10c6ad..1da5b572 100644 --- a/core/query.py +++ b/core/query.py @@ -15,7 +15,8 @@ What lives here now (2026-11-04, the owner's order retired the one-word executor): -* `Grant`, `AMBASSADOR` and the owner's `AMBASSADOR_OVERLAY` (`with_overlay`) — the grants in code. +* `Grant`, `AMBASSADOR` and the owner's `AMBASSADOR_OVERLAY` (`with_overlay`), the ingress's + `OPERATOR` and the read-only `GUEST` — the grants in code. * `Verb`, `required` and `mode_of` — the scope table of the eight one-word verbs, kept as the laws' anchor (SCO-8, QSA-8) and as `core/sentence/legacy.py`'s compatibility map; the sentence compiler (`core/sentence/types.py`) builds its clauses' scopes the same way and types them by @@ -140,6 +141,12 @@ def __post_init__(self) -> None: def admits(self, required: Scope) -> bool: return any(req_admissible(required, g) for g in self.scopes) + @property + def strata(self) -> frozenset[Stratum]: + """Every stratum some plane names, closed downward: what a reader under this grant may + see named (`core.sentence.universe` withholds a mirror endpoint outside it).""" + return frozenset().union(*(s.sigma.strata for s in self.scopes)) + def meet(self, other: Grant) -> Grant: """Safe delegation: the pairwise meets that exist. A cross-clock pair has no meet, and neither has a pair whose windows meet at a point across several strata with no shared @@ -211,6 +218,27 @@ def meet(self, other: Grant) -> Grant: ) +# The guest: an external agent's principal, read-only. The Ambassador's planes without the mirror's +# version plane, over the strata a guest may read: the dialogue (its transcripts and artifacts +# below it), the reference stratum (the repo's code and docs), the curated papers and the observed +# records. Never the mirror (the owner's notes) nor the interpreted stratum (readings derived from +# the notes, which can quote them), and the closure adds neither (SCO-1). No propose, no write, no +# overlay and no world reach, so it admits no command (ING-1) and no `assume` (QSA-5); SCO-9 states +# it. Its role, `guest`, holds no spool (`core/ingest/ingress.py`); its surface is +# `scripts/palace_mcp.py --role guest` (dn-guest-principal). +GUEST = Grant( + ( + scope( + {Stratum.DIALOGUE, Stratum.REFERENCE, Stratum.CURATED, Stratum.OBSERVED}, + {"F", "D"}, + Clock.PROJECTION_EVENT, + _ALL, + ), + scope({Stratum.REFERENCE, Stratum.DIALOGUE}, {"F", "C"}, Clock.COMMIT, _ALL), + ) +) + + def with_overlay(g: Grant) -> Grant: """`g` with the hypothetical overlay named on every plane — what the owner grants a client to evaluate `assume` sentences (dn-query-sentence-algebra §4 d; granted 2026-11-04). Σ is a diff --git a/core/sentence/execute.py b/core/sentence/execute.py index f587bdec..b6797e61 100644 --- a/core/sentence/execute.py +++ b/core/sentence/execute.py @@ -250,6 +250,26 @@ def _git(root: Path, *args: str) -> bytes | None: return out.stdout if out.returncode == 0 else None +def is_commit_sha(text: str) -> bool: + """Whether `text` is, whole, a hex sha as git prints or abbreviates one.""" + return _SHA.fullmatch(text) is not None + + +def tracked_paths(root: Path) -> frozenset[str]: + """The paths git tracks in the checkout at `root`, read from the tree at HEAD and spelled as + git spells them (repo-relative, `/` between components). The empty set when git fails, is + absent, or times out, so a caller that names only tracked paths then names none. A name that + is not UTF-8 is left out: no string spells it.""" + out = _git(root, "ls-tree", "-r", "-z", "--name-only", "HEAD") + names: set[str] = set() + for raw in (out or b"").split(b"\0"): + try: + names.add(raw.decode("utf-8")) + except UnicodeDecodeError: + continue + return frozenset(names - {""}) + + def _window(text: str, chunk: int | None, window: int) -> tuple[str, int, int, int]: """A window of `window` chunks of `REPO_CHUNK_LINES` lines around `chunk` (from the start when absent): the text, its first and last chunk, and the chunk count.""" diff --git a/core/sentence/grammar.py b/core/sentence/grammar.py index f6704995..b3db22cc 100644 --- a/core/sentence/grammar.py +++ b/core/sentence/grammar.py @@ -83,9 +83,14 @@ class Token: pos: int +# A string's body is written unrolled and possessive: a run of plain characters, then each escape +# with the run after it, none given back. It matches what `(?:[^"\\]|\\.)*` matches, since an +# escape is the one way past a quote or a backslash and the body can end only at its closing +# quote; that form kept a backtracking point for each character, some 150 bytes of memory for +# each character of a literal, and this one keeps none. _TOKEN = re.compile( r"""\s*(?: - "(?P(?:[^"\\]|\\.)*)" # a quoted string, with \" escapes + "(?P[^"\\]*+(?:\\.[^"\\]*+)*+)" # a quoted string, with \" escapes | (?P\d+(?:\.\d+)?(?![A-Za-z0-9_])) # an unsigned number, never the head of a word | (?P[A-Za-z0-9_][A-Za-z0-9_./:#@\-]*) # a word: a keyword, a letter, an atom, an id | (?P[(){}|*+?,\-]) # a symbol of a path or a signed weight @@ -106,7 +111,16 @@ class Token: _STOP_STRATA = KEYWORDS | {")"} -_UNESCAPE = re.compile(r'\\(["\\])') +def _unescape(body: str) -> str: + """A string literal's text from its body: `\\"` read as `"` and `\\\\` as `\\`, any other + escape kept as written. The body is plain characters and escape pairs (`_TOKEN`), each + backslash the head of a pair, so splitting it at each `\\\\` from the left finds the escaped + backslashes, and between them a backslash before a quote is an escaped quote. A regular + expression's substitution would make objects for each escape, some 20 bytes of memory for + each character of a literal of them; this makes few.""" + if "\\" not in body: + return body + return "\\".join(part.replace('\\"', '"') for part in body.split("\\\\")) def quote(s: str) -> str: @@ -125,7 +139,7 @@ def tokenize(text: str) -> list[Token]: break raise ParseError(f"tokens: unexpected character {text[pos]!r} at {pos}") if m.group("string") is not None: - tokens.append(Token("STRING", _UNESCAPE.sub(r"\1", m.group("string")), m.start())) + tokens.append(Token("STRING", _unescape(m.group("string")), m.start())) elif m.group("number") is not None: tokens.append(Token("NUMBER", m.group("number"), m.start())) elif m.group("word") is not None: diff --git a/core/sentence/surface.py b/core/sentence/surface.py index df494f37..ee59a383 100644 --- a/core/sentence/surface.py +++ b/core/sentence/surface.py @@ -10,10 +10,15 @@ `unsupported`) and its reason, or `requested` for a command the ingress spooled. The log holds no note text: a sentence is the asker's own words and the hits are counted, never named; a command's string literals, which may be corpus text (`do capture "…"`), are logged as their lengths -(`redact_command`). `summarize` reads the log back as the sensor the brainstorm asked for — which -strata serve which roles, which translations fail — and `palace query --log` renders it. A sensor -never breaks the instrument: a log that cannot be written is reported on stderr and the answer is -returned anyway. +(`redact_command`). A sentence is whatever its asker typed, and the asker may be a guest: a line +is ASCII, every other character written as its JSON escape, so nothing a sentence holds can end a +line, and the log keeps a sentence's head, up to `SENTENCE_MAX` characters and `SENTENCE_BYTES` +bytes as the line writes it (`_kept`). `summarize` reads the log back as the sensor the +brainstorm asked for — which strata serve which roles, which translations fail — in one pass over +a line at a time (`QueryLog.read`), and `palace query --log` renders it, each character that is +not printable as its escape, since the reader is a terminal. A sensor never breaks the +instrument: a log that cannot be written is reported on stderr and the answer is returned +anyway, and a line that is not an entry is skipped and counted. `run_query` is `palace query` (scripts/palace.py): read-only, under `sentence_grant()` — the Ambassador's grant with the hypothetical overlay the owner granted on 2026-11-04 (the note's @@ -24,11 +29,12 @@ from __future__ import annotations +import contextlib import json import sys import time -from collections import Counter -from collections.abc import Iterable, Mapping +from collections import Counter, deque +from collections.abc import Iterable, Iterator, Mapping from dataclasses import asdict, dataclass, fields from datetime import UTC, datetime from pathlib import Path @@ -42,6 +48,7 @@ from core.sentence.precedents import DEFAULT, Precedents from core.sentence.trace import Trace from core.sentence.types import ( + MIRROR_NAMES, AmbiguousSentence, IllScopedSentence, Sort, @@ -51,6 +58,10 @@ LOG_NAME = "query_log.jsonl" REASON_MAX = 240 # a refusal's reason, truncated: the log is a sensor, not a transcript +SENTENCE_MAX = 4096 # a sentence, cut at this many characters with a marker of its full length +# and at this many bytes as the log's ASCII line writes it, a character outside ASCII as its escape +# (six bytes, or twelve outside the BMP): a sentence of printable ASCII is never cut by it +SENTENCE_BYTES = 2 * SENTENCE_MAX MAX_COMMAND_BYTES = 32 * 1024 # the ingress's cap (`core/ingest/ingress.py`), checked first USAGE = ('usage: palace query "" [--json] [--no-plan] [--trace] [--as ]\n' " palace query --log [--json] the sensor: strata by role, failed translations") @@ -81,31 +92,73 @@ class Entry: _FIELDS = {f.name for f in fields(Entry)} +def _read_entry(line: str) -> Entry | None: + """One line of the log as an `Entry`, or `None` when it is not one: not JSON, not an object, + a field missing, or a field of another type. A field a later schema added is ignored.""" + try: + row = json.loads(line) + if not isinstance(row, dict): + return None + d = {k: v for k, v in row.items() if k in _FIELDS} + d["modes"], d["strata"] = tuple(d.get("modes", ())), tuple(d.get("strata", ())) + entry = Entry(**d) + except (TypeError, ValueError, RecursionError): + return None + texts = (entry.at, entry.surface, entry.role, entry.sentence, entry.outcome, entry.refusal, + entry.reason, entry.sort, *entry.modes, *entry.strata) + counts = isinstance(entry.hits, int) and isinstance(entry.ms, int) + if not (all(isinstance(t, str) for t in texts) and counts and isinstance(entry.hyp, bool)): + return None + return entry + + @dataclass(frozen=True) class QueryLog: - """An append-only JSON-lines file under the data dir; one `Entry` per sentence asked.""" + """An append-only JSON-lines file under the data dir; one `Entry` per sentence asked. A line + is ASCII, every other character written as its JSON escape, and ends at `\\n`, the one + separator: a sentence may hold any character, a line or paragraph separator or a lone + surrogate among them, and none of them ends a line or fails to encode.""" path: Path def record(self, entry: Entry) -> None: + """Append one entry. It cannot raise: the sensor never breaks the instrument, so a log + that cannot be written is reported on stderr and the answer is returned anyway.""" try: + line = json.dumps(asdict(entry), ensure_ascii=True) self.path.parent.mkdir(parents=True, exist_ok=True) with self.path.open("a", encoding="utf-8") as f: - f.write(json.dumps(asdict(entry), ensure_ascii=False) + "\n") - except OSError as e: # the sensor never breaks the instrument - print(f"query log not written ({self.path}): {e}", file=sys.stderr) + f.write(line + "\n") + except Exception as e: + with contextlib.suppress(Exception): + print(f"query log not written ({self.path}): {e}", file=sys.stderr) + + def read(self) -> Iterator[Entry]: + """The entries, oldest first, read a line at a time: a reader holds one line of the log, + never the whole file. The file is split at `\\n` alone: `str.splitlines` also splits at + U+2028, U+2029 and U+0085, which a line written before the log was ASCII may hold inside + a sentence. A line that is not an entry, torn or of another shape, is skipped, and when + the file has been read one line on stderr says how many were.""" + if not self.path.exists(): + return + skipped = 0 + with self.path.open("rb") as f: + for raw in f: # a binary file is split at b"\n" alone + line = raw.decode("utf-8", errors="replace") + if not line.strip(): + continue + entry = _read_entry(line) + if entry is None: + skipped += 1 + else: + yield entry + if skipped: + print(f"query log ({self.path}): {skipped} lines are not entries and were skipped", + file=sys.stderr) def entries(self) -> list[Entry]: - if not self.path.exists(): - return [] - out: list[Entry] = [] - for line in self.path.read_text(encoding="utf-8").splitlines(): - if not line.strip(): - continue - d = {k: v for k, v in json.loads(line).items() if k in _FIELDS} - d["modes"], d["strata"] = tuple(d.get("modes", ())), tuple(d.get("strata", ())) - out.append(Entry(**d)) - return out + """The entries, oldest first (`read`), as a list.""" + return list(self.read()) def default_log() -> QueryLog: @@ -195,9 +248,13 @@ def _command_word(text: str) -> str: def redact_reason(reason: str) -> str: - """A refusal's reason as the log keeps it for a command: every quoted run replaced by its - length, since a refusal may name a conversation or a text. A reason's own apostrophe opens - a run too, so the log may keep less of a reason than it says, never more.""" + """A refusal's reason as the log keeps it for a command: every run between two ASCII quotes + replaced by its length, since a refusal may name a conversation or a text. The runs are paired + by position, not by meaning. A reason's own apostrophe opens a run too and closes at the next + quote, so the log may keep less of a reason than it says, and what the reason quoted after + that apostrophe can be left in clear; text quoted in any other way is kept as it is. It hides + the words an asker quoted in a sentence. It does not hide what a reason quotes from a store: + a surface that must not pass that on says a fixed sentence instead of the reason.""" return _redact(reason) @@ -260,7 +317,10 @@ def ask_logged(text: str, grant: Grant, *, surface: str, role: str, else: from core.sentence.universe import build - u = build(engine or QueryEngine(), plan, precedents=precedents, trace=t) + # a grant that names no stratum of the mirror (the guest's) is shown no vault path: + # the universe withholds what the other stores say of the notes (dn-guest-principal) + hide = {"hide_mirror": True} if not grant.strata & MIRROR_NAMES else {} + u = build(engine or QueryEngine(), plan, precedents=precedents, trace=t, **hide) answer = execute(plan, u, precedents=precedents, trace=t) except Exception as e: reason = redact_reason(str(e)) if command else str(e) @@ -275,10 +335,30 @@ def ask_logged(text: str, grant: Grant, *, surface: str, role: str, def _entry(text: str, surface: str, role: str, started: float, plan: Plan | None, precedents: Precedents, **rest: Any) -> Entry: + """The log's entry for `text`: its shape read from the whole text, the sentence itself kept + as `_kept` keeps it.""" sort, modes, strata = _shape(text, plan, precedents) return Entry(at=datetime.now(UTC).replace(tzinfo=None).isoformat(timespec="seconds"), - surface=surface, role=role, sentence=text, sort=sort, modes=modes, strata=strata, - ms=int((time.perf_counter() - started) * 1000), **rest) + surface=surface, role=role, sentence=_kept(text), sort=sort, modes=modes, + strata=strata, ms=int((time.perf_counter() - started) * 1000), **rest) + + +def _kept(text: str) -> str: + """A sentence as the log keeps it: its head, up to `SENTENCE_MAX` characters and up to + `SENTENCE_BYTES` bytes as the line writes it, each character counted as its JSON escape; + then, when the sentence was longer, a marker of its full length and of where it was cut. A + line holds a few kilobytes of a sentence whatever characters it is made of.""" + head = text[:SENTENCE_MAX] + if len(json.dumps(head)) - 2 > SENTENCE_BYTES: + size = 0 + for i, c in enumerate(head): + size += len(json.dumps(c)) - 2 + if size > SENTENCE_BYTES: + head = head[:i] + break + if len(head) == len(text): + return text + return f"{head} <{len(text)} characters, cut at {len(head)}>" def _shape(text: str, plan: Plan | None, @@ -302,24 +382,53 @@ def _shape(text: str, plan: Plan | None, def summarize(entries: Iterable[Entry]) -> dict[str, Any]: - """Which strata served which roles, and which translations failed (the lessons loop).""" - rows = list(entries) + """Which strata served which roles, and which translations failed (the lessons loop). One + pass over the entries, keeping the counts and the last ten failures: given the log's `read`, + a reader holds those and one line, never the log.""" + asked = 0 + outcomes: Counter[str] = Counter() served: dict[str, Counter[str]] = {} - for e in rows: + refusals: Counter[str] = Counter() + failed: deque[dict[str, str]] = deque(maxlen=10) + for e in entries: + asked += 1 + outcomes[e.outcome] += 1 served.setdefault(f"{e.role} · {','.join(e.strata) or '∅'}", Counter())[e.outcome] += 1 + if e.outcome == "refused": + refusals[e.refusal] += 1 + if e.outcome in ("refused", "empty"): + failed.append({"at": e.at, "role": e.role, "sentence": e.sentence, + "why": f"{e.refusal}: {e.reason}" if e.outcome == "refused" + else "empty"}) return { - "asked": len(rows), - "outcomes": dict(sorted(Counter(e.outcome for e in rows).items())), + "asked": asked, + "outcomes": dict(sorted(outcomes.items())), "served": {k: dict(sorted(v.items())) for k, v in sorted(served.items())}, - "refusals": dict(sorted(Counter(e.refusal for e in rows - if e.outcome == "refused").items())), - "failed": [{"at": e.at, "role": e.role, "sentence": e.sentence, - "why": f"{e.refusal}: {e.reason}" if e.outcome == "refused" else "empty"} - for e in rows if e.outcome in ("refused", "empty")][-10:], + "refusals": dict(sorted(refusals.items())), + "failed": list(failed), } +def _escaped(line: str) -> str: + """`line` with each character that is not printable written as its escape (`\\x1b`, `\\n`, + `\\u202e`): a control, a line or paragraph separator, a bidi or other format mark, a lone + surrogate.""" + return "".join(c if c.isprintable() else c.encode("unicode_escape").decode("ascii") + for c in line) + + +def _json_text(obj: Any) -> str: + """`obj` as indented JSON for a terminal. Text outside ASCII stays readable, and each + character that is not printable, the indentation's own line breaks aside, is written as its + JSON escape: the output is the same JSON and holds no control, separator or lone surrogate.""" + text = json.dumps(obj, ensure_ascii=False, indent=1) + return "".join(c if c == "\n" or c.isprintable() else json.dumps(c)[1:-1] for c in text) + + def render_summary(s: Mapping[str, Any]) -> str: + """The sensor's summary as lines for a terminal. A sentence, a role and a reason are text + someone typed, a guest among them, so every line is escaped (`_escaped`): an entry stays on + its own line and writes no control sequence into the terminal that prints it.""" counts = " ".join(f"{k} {v}" for k, v in s["outcomes"].items()) lines = [f"asked: {s['asked']} {counts}".rstrip()] if s["served"]: @@ -331,7 +440,7 @@ def render_summary(s: Mapping[str, Any]) -> str: if s["failed"]: lines.append("failed translations (last 10):") lines += [f" {f['at']} {f['role']} {f['sentence']} — {f['why']}" for f in s["failed"]] - return "\n".join(lines) + return "\n".join(map(_escaped, lines)) # ── rendering ────────────────────────────────────────────────────────────────────────────────── @@ -403,9 +512,8 @@ def run_query(argv: list[str], *, out: TextIO | None = None, grant: Grant | None return 2 as_json = "--json" in flags if "--log" in flags: - s = summarize((log if log is not None else default_log()).entries()) - print(json.dumps(s, ensure_ascii=False, indent=1) if as_json else render_summary(s), - file=out) + s = summarize((log if log is not None else default_log()).read()) + print(_json_text(s) if as_json else render_summary(s), file=out) return 0 text = " ".join(words) try: diff --git a/core/sentence/universe.py b/core/sentence/universe.py index b5dd8aad..3100e786 100644 --- a/core/sentence/universe.py +++ b/core/sentence/universe.py @@ -24,6 +24,9 @@ nodes of the dialogue's transcript stratum, the endpoints as the reference graph's nodes (a checkout's or a worktree's path, repo-relative) or the mirror's (a vault path); an endpoint outside both, or an artifact id, is named as a node that `read` cannot open, never dropped. + A reader whose grant names no stratum of the mirror is shown an edge only when it ends at a + commit or at a file git tracks in this repo at HEAD; any other edge is withheld whole, since + an endpoint is a path and a path can be a note's (`_Builder._named`, dn-guest-principal §5). On the support the laws hold exactly: masks, products, thresholds (QSA-1 to QSA-4). What the support loses is bounded and one-sided: restricting the walk to a subgraph whose complement @@ -40,11 +43,13 @@ from __future__ import annotations +import os +import unicodedata from collections import deque from collections.abc import Callable, Iterable, Mapping, Sequence from dataclasses import dataclass, field from pathlib import Path -from typing import Any +from typing import TYPE_CHECKING, Any import numpy as np @@ -54,7 +59,14 @@ from core.sentence import ast from core.sentence.ast import Node, Rel from core.sentence.automaton import letters -from core.sentence.execute import Relation, Universe, membership, read_ref +from core.sentence.execute import ( + Relation, + Universe, + is_commit_sha, + membership, + read_ref, + tracked_paths, +) from core.sentence.plan import Plan from core.sentence.precedents import DEFAULT, Precedents from core.sentence.trace import Trace @@ -68,6 +80,9 @@ stratum_of_provenance, ) +if TYPE_CHECKING: + from core.stores.causal_edges import CausalEdge + # ── what the sentence names ──────────────────────────────────────────────────────────────────── @@ -196,6 +211,13 @@ def _int(x: object) -> int: return int(x) if isinstance(x, int | float | str) and str(x) != "" else 0 +def _folded(path: Path) -> tuple[str, ...]: + """A path's components as a file system that ignores letter case and normalisation compares + them: each one decomposed, case-folded and decomposed again.""" + return tuple(unicodedata.normalize("NFKD", unicodedata.normalize("NFKD", part).casefold()) + for part in path.parts) + + def is_repo_path(atom: str) -> bool: """A repo-relative path — the reference graph's node identity: relative, with a directory part, never a dialogue or transcript turn or a paper ref.""" @@ -215,13 +237,23 @@ def admitted_strata(plan: Plan, precedents: Precedents = DEFAULT) -> frozenset[S class _Builder: def __init__(self, engine: QueryEngine, precedents: Precedents, - strata: frozenset[Stratum] | None = None) -> None: + strata: frozenset[Stratum] | None = None, *, hide_mirror: bool = False) -> None: self.e, self.p = engine, precedents # what the sentence's admitted clauses read: a node outside it is never loaded, so no # answer, note or refusal can carry a row the grant did not admit (None: everything, for # a builder driven by hand) self.strata = strata self.admits = membership(strata) if strata is not None else (lambda label, prov: True) + # the reader's grant names no stratum of the mirror (the guest's): the note graph is not + # built, pending items are listed for the dialogue's classes alone, and a causal edge is + # shown only when its endpoint is a commit or a file git tracks here (`_named`), so a + # note's path the transcript stratum holds is withheld with its edge however it is spelled + self.hide_mirror = hide_mirror + self._named_of: dict[tuple[str, str], bool] = {} # `_named`, per (dst, dst_type) + self._citable_of: dict[str, bool] = {} # `_citable`, per citation neighbour + self._tracked_paths: frozenset[str] | None = None # `_tracked`, read once + self._vault_forms: frozenset[tuple[str, ...]] | None = None # the vault, folded + self.witnessed = False # some clause is a witness (its record is read in `universe`) self.nodes: dict[str, _Node] = {} self.f_edges: dict[str, set[str]] = {} self.c_edges: dict[str, set[str]] = {} @@ -293,8 +325,9 @@ def find(self, atom: str) -> _Node | None: def load_mirror(self) -> None: from core.kernel.provenance import Provenance - if self.admits("mirror", Provenance.AUTHORED_SOLO.value) or self.admits( - "dialogue", Provenance.AUTHORED_DIALOGUE.value): + reads_mirror = self.admits("mirror", Provenance.AUTHORED_SOLO.value) or self.admits( + "dialogue", Provenance.AUTHORED_DIALOGUE.value) + if reads_mirror and not self.hide_mirror: # the guest's dialogue loads below notes, mat, _ = self.e.note_graph() for i, n in enumerate(notes): prov = str(n.get("provenance", "")) @@ -343,7 +376,11 @@ def load_pending(self) -> None: catalog, plane = self.store("catalog"), self.store("vectors") except KeyError: return - for e in pending(catalog, plane, lexical=lexical): + from core.kernel.provenance import Provenance + + dialogue = (Provenance.AUTHORED_DIALOGUE, Provenance.OBSERVED) + for e in pending(catalog, plane, lexical=lexical, + classes=dialogue if self.hide_mirror else None): prov = str(e.provenance) label = stratum_of_provenance(prov) or "mirror" if label not in ("mirror", "dialogue") or not self.admits(label, prov): @@ -568,6 +605,91 @@ def _roots(self) -> list[Path]: roots.append(root.parent.parent.parent) return roots + def _tracked(self) -> frozenset[str]: + """The paths git tracks in this checkout at HEAD, read once per builder; the empty set + when git cannot be asked, so nothing is named then.""" + if self._tracked_paths is None: + from core.kernel.config import REPO_ROOT + + try: + self._tracked_paths = tracked_paths(Path(REPO_ROOT)) + except Exception: # fail closed: no path is tracked + self._tracked_paths = frozenset() + return self._tracked_paths + + def _in_vault(self, ref: str) -> bool: + """Whether a path is the vault or lies under it, in the spellings this folds: another + letter case, another Unicode normal form, `.` and `..` components, a symlink, `~`. The + components are compared folded (`_folded`), as a prefix, for the path as written (`~` + expanded), for its normal form and for its resolved form, against the configured vault + path and its resolved form. A path that cannot be read this way counts as inside, so the + test errs toward withholding. A file system also knows a note by names this does not + fold, a hard link or the path through another mount of its volume among them: such a + path is the allow list's to judge (`_named`), which names it only when it is a file git + tracks in a checkout, as it names any other.""" + try: + if self._vault_forms is None: + vault = Path(str(self.e.config.ingestion.vault.path)).expanduser() + self._vault_forms = frozenset({_folded(vault), _folded(vault.resolve())}) + p = Path(ref).expanduser() + forms = {_folded(p), _folded(Path(os.path.normpath(p))), _folded(p.resolve())} + except Exception: # fail closed: inside the vault + return True + return any(f[:len(v)] == v for v in self._vault_forms for f in forms) + + def _named(self, dst: str, dst_type: str) -> bool: + """Whether a causal edge's endpoint is one a reader whose grant names no stratum of the + mirror may see named (`hide_mirror`). An allow list, since an endpoint is whatever path or + id the action log recorded and a note's path has many spellings: a commit's edge is named + when its endpoint is a hex sha; any other edge only when its endpoint is not in the vault + (`_in_vault`) and resolves to a repo-relative path git tracks in this checkout at HEAD + (`_tracked`), from a doc's id (`_doc_path`) or from an absolute path under a checkout of + this repo (`_endpoint`). A relative path, one under `~`, a URI, a path outside the repo, + an untracked or deleted file, a doc's id that is not one tracked file or that holds a + glob's characters, and an endpoint of an unknown type are not named, nor is one that + cannot be judged. An edge that is not named is withheld whole, its id with it, as if the + store did not hold it: what the reader sees does not depend on it (dn-guest-principal + §5).""" + key = (dst, dst_type) + if key not in self._named_of: + try: + self._named_of[key] = self._allowed(dst, dst_type) + except Exception: # fail closed: not named, never raised + self._named_of[key] = False + return self._named_of[key] + + def _allowed(self, dst: str, dst_type: str) -> bool: + """`_named`'s rule for one endpoint, uncached; it may raise, and `_named` then withholds.""" + if dst_type == "commit": + return is_commit_sha(dst) + if self._in_vault(dst): + return False + rel: str | None = None + if dst_type == "doc" and "/" not in dst: + # `_doc_path` finds a finding's or a plan's file with a glob, and the id of a file + # under a `docs/design-notes/` folder is its name, whatever the folder is in: a name + # that holds a glob's characters could match one tracked doc and be shown as its id + rel = None if any(c in dst for c in "*?[") else _doc_path(dst) + elif dst_type in ("file", "doc") and Path(dst).is_absolute(): + node = self._endpoint(dst, dst_type) + rel = node.ref if node.stratum == "reference" else None + return rel is not None and rel in self._tracked() + + def _citable(self, ref: str) -> bool: + """Whether a citation neighbour is one the reader may see named. The citation graph is + projected from git history, so its refs are repo-relative paths and denote repo files; a + reader whose grant names no stratum of the mirror (`hide_mirror`) is shown a neighbour + only when it is spelled as one (not absolute, not under `~`, no URI, no `..` component) + and lies in the vault under no checkout of this repo. It need not be tracked at HEAD: the + graph is read at other cuts too.""" + if not self.hide_mirror: + return True + if ref not in self._citable_of: + plain = not (ref.startswith(("/", "~")) or "://" in ref or ".." in ref.split("/")) + self._citable_of[ref] = plain and not any( + self._in_vault(str(root / ref)) for root in self._roots()) + return self._citable_of[ref] + def _endpoint(self, dst: str, dst_type: str) -> _Node: """The node a causal endpoint names, not yet added. A path under a checkout of this repo (this one, the main one, or one of the main one's worktrees, @@ -653,11 +775,15 @@ def _causal(self) -> tuple[dict[str, list[tuple[str, dict[str, Any]]]], dict[str, list[tuple[str, dict[str, Any]]]]]: """The causal store read whole, once per sentence — one content-free row per proven action (a witness, an endpoint, an id) — and indexed in memory by turn (the endpoints a - turn produced) and by endpoint (the turns that produced it); the support is cut from it.""" + turn produced) and by endpoint (the turns that produced it); the support is cut from it. + For a reader whose grant names no stratum of the mirror only the edges whose endpoint it + may see named are indexed (`_named`).""" if self._causal_index is None: by_turn: dict[str, list[tuple[str, dict[str, Any]]]] = {} by_end: dict[str, list[tuple[str, dict[str, Any]]]] = {} for e in self.store("causal").all_edges(): + if self.hide_mirror and not self._named(str(e["dst"]), str(e["dst_type"])): + continue tref = producing_turn(e) eref = self._endpoint(str(e["dst"]), str(e["dst_type"])).ref by_turn.setdefault(tref, []).append((eref, e)) @@ -714,7 +840,7 @@ def seed_typed(self, atom: str, radius: int, moves: frozenset[Rel]) -> None: nbrs: list[tuple[str, Rel, Mapping[str, Any] | None]] = [] if Rel.F in moves and is_repo_path(node): nbrs += [(t, Rel.F, None) for t in self._cited( - node, (n for n, dd in frontier if dd < radius))] + node, (n for n, dd in frontier if dd < radius)) if self._citable(t)] if Rel.C in moves: nbrs += [(other, Rel.C, e) for other, e in self._causal_neighbours(node)] for nb, _rel, e in sorted(nbrs, key=lambda x: (x[0], x[1].value)): @@ -836,20 +962,36 @@ def history(atom: str) -> list[tuple[str, int, str, str]]: doc_id = catalog.doc_id_for(atom) if catalog.get(atom) is not None else atom return [(v.doc_id, v.version_seq, v.digest, v.at) for v in versions.history(doc_id)] + def may_see(edge: CausalEdge) -> bool: + return self._named(str(edge.dst), str(edge.dst_type)) + def witness(edge_id: str) -> Mapping[str, object] | None: + # an edge whose endpoint the reader may not see named is no record to it (`_named`): + # the answer is `None`, as for an id the store does not hold. Through `origin` it is + # no candidate either, judged before the first is chosen, so it cannot stand in front + # of an edge keyed to the same commit that the reader may see edge = origin(edge_id, causal_edges=self.store("causal"), - reference_edges=self.store("references")) + reference_edges=self.store("references"), + admit=may_see if self.hide_mirror else None) if edge is not None: + if self.hide_mirror and not may_see(edge): # fail closed all the same + return None return {k: str(v) for k, v in edge.__dict__.items()} row = self.store("causal").edge(edge_id) # a causal edge's own id: the witness if row is not None: + if self.hide_mirror and not self._named(str(row["dst"]), str(row["dst_type"])): + return None # the turn that produced it, by its ref; the raw transcript's digest is a # raw-store key and never leaves the store out = {k: str(v) for k, v in row.items() if k != "witness_digest"} out["transcript"] = producing_turn(row) return out # a landing's receipt names its attestation (dn-ingress D5, ING-6): the record - # of what landed, its role, its action and the digests it produced + # of what landed, its role, its action and the digests it produced. A reader that + # holds no receipt, one whose grant names no stratum of the mirror, is shown none: + # a note's landing is attested too + if self.hide_mirror: + return None try: att = self.e._get("attestations").get(edge_id) except KeyError: # an engine without the store @@ -879,6 +1021,12 @@ def text(ref: str, chunk: int | None, window: int) -> Mapping[str, object] | Non missing.append(f"causal: {unreadable} endpoints are commits, ids, or paths " "outside the repo and the vault: named in the transcript's " "stratum, not readable") + if self.hide_mirror and (Rel.C in self.moves or self.witnessed): + # the same words whether or not anything was withheld: a count would tell + missing.append("withheld: the grant names no stratum of the mirror, so a causal edge " + "is shown only when it ends at a commit or at a file git tracks in " + "this repo at HEAD; any other edge is not shown, its id with it, and " + "a witness answers no landing's attestation") missing.append("D moves at the note grain: the version chains are per note (use trace)") waiting = frozenset(i for i, n in enumerate(order) if n.ref in set(self.pending)) unembedded = frozenset(i for i, n in enumerate(order) if n.ref in set(self.unembedded)) @@ -931,14 +1079,19 @@ def scores(text: str) -> np.ndarray: def build(engine: QueryEngine, plan: Plan, *, precedents: Precedents = DEFAULT, - trace: Trace | None = None) -> Universe: + trace: Trace | None = None, hide_mirror: bool = False) -> Universe: """The universe a plan reads: the mirror and the dialogue, then what the sentence's texts and anchors reach in the indexed strata, the citation graph at the cut and, when the sentence - walks `C`, the causal edges. With a trace, the support's census is noted.""" + walks `C`, the causal edges. With a trace, the support's census is noted. `hide_mirror` is for + a reader whose grant names no stratum of the mirror (`ask_logged` sets it from the grant): + the note graph is not built, and of what the other stores hold a causal edge is shown only + when it ends at a commit or at a file git tracks in this repo at HEAD, a citation neighbour + only when it is a repo-relative path outside the vault.""" seeds = seeds_of(plan.term, precedents) - b = _Builder(engine, precedents, admitted_strata(plan, precedents)) + b = _Builder(engine, precedents, admitted_strata(plan, precedents), hide_mirror=hide_mirror) b.moves = frozenset(seeds.moves) b.transcript = seeds.transcript + b.witnessed = any(c.verb == "witness" for c in plan.clauses) b.load_mirror() b.load_pending() b.open_view(seeds.cut) diff --git a/docs/LAWS.md b/docs/LAWS.md index 4f011d2f..c14bae63 100644 --- a/docs/LAWS.md +++ b/docs/LAWS.md @@ -143,6 +143,7 @@ and §2.2. | SCO-6 | admissibility and the zone law are downward closed and survive every meet; a world-reaching scope that passes the zone law names only `world`, the denylist and the overlay, so it is cleared for no record class under any table that gives those three none; the zone law does not survive join (exact: finite sets) | down-sets of the scope order | `core/kernel/scope.py::zone_admissible` | Claim | `tests/unit/test_scope.py::test_zone_law_REFUSES_an_exhaust_read_with_world_reach`, `tests/unit/test_scope.py::test_zone_law_REFUSES_a_constructable_private_read_with_world_reach`, `tests/unit/test_scope.py::test_zone_law_admits_private_read_with_no_world_reach`, `tests/unit/test_scope.py::test_req_admissible_is_le` | `Scope.lean::admissible_meet`, `Scope.lean::zoneOk_meet`, `Scope.lean::world_reach_reads_nothing`, `Scope.lean::zone_join_fails`, `Scope.lean::exhaust_refused` | | SCO-7 | a grant's meet skips the pairs with no meet, lies under both grants plane by plane, never trips `InadmissibleGrant`, and admits only what both grants admit (exact: finite sets) | greatest lower bounds, taken plane by plane | `core/query.py::Grant.meet` | Claim | `tests/unit/test_ambassador_surface.py::test_grant_meet_skips_a_pair_whose_meet_has_no_consistent_cut` | `Scope.lean::grantMeet_le`, `Scope.lean::grantMeet_grantOk`, `Scope.lean::admits_of_grantMeet` | | SCO-8 | `required()` builds every search without raising `SliceError`, over any strata, with or without history: the single-read cut follows the strata after closure (exact: finite sets) | — (a law of one function; none named) | `core/query.py::required` | Claim | `tests/unit/test_ambassador_surface.py::test_every_strata_list_the_legacy_search_accepted_is_constructible` | `Scope.lean::search_never_slices`, `Scope.lean::search_reference` | +| SCO-9 | the guest's grant is one the code accepts (no plane names the foundation or reaches the world); none of its planes names the mirror, its authored refinement or the interpreted stratum, its closure included (SCO-1), so a clause that reads any of them is refused; no plane carries the write bit, so it admits no command (ING-1), and none names the overlay, so it admits no `assume` (QSA-5) (exact: finite sets) | the scope order; the down-sets of the refinement forest | `core/query.py::GUEST` | Claim | `tests/adversarial/test_guest_leaks.py::test_the_guest_grant_reads_neither_the_mirror_nor_the_interpreted_stratum`, `tests/adversarial/test_guest_leaks.py::test_the_guest_role_is_refused_every_request`, `tests/adversarial/test_guest_leaks.py::test_no_guest_output_carries_the_canary` | `Scope.lean::guest_grantOk`, `Scope.lean::guest_reads_no_note`, `Scope.lean::guest_refuses_note`, `Sentence.lean::Sentence.guest_no_assume`, `Ingress.lean::guest_admits_no_command` | ## VIII. The abstraction ultrametric σ* diff --git a/docs/design-notes/dn-guest-principal.md b/docs/design-notes/dn-guest-principal.md new file mode 100644 index 00000000..c38ca9ca --- /dev/null +++ b/docs/design-notes/dn-guest-principal.md @@ -0,0 +1,362 @@ +--- +type: design-note +id: dn-guest-principal +track: query-language +status: draft # provenance description, never a gate; the merge is ratification +implementation: built # the grant, the role, the surface, the universe's withholding, the leak tests and SCO-9 landed 2026-11-09; the lite profile's overview and tests 2026-11-11; the audit's repairs 2026-11-12 +created: 2026-11-09 +updated: 2026-11-12 +links: + - docs/design-notes/capability-scope-algebra.md # the scope lattice the grant is a point of + - docs/design-notes/dn-query-sentence-algebra.md # clause-wise admission (QSA-5), the universe as the support + - docs/design-notes/dn-ingress.md # the roles and their grants (`grant_for`), ING-1 + - docs/design-notes/plane-principals.md # the operating-system side, which this note does not change + - docs/design-notes/dn-palace-lite.md # an instance that embeds nothing; the code instance the guest serves + - formal/Palace/Scope.lean # SCO-9, with Sentence.lean and Ingress.lean + - papers/2026-11-09-guest-principal/paper.tex # the article +supersedes: null +superseded_by: null +warrant: null +--- + +# The guest principal: a read-only grant for an external agent + +> Agent-drafted on a branch; the merge is ratification. Grades as elsewhere: `[THEOREM]` is +> machine-checked in `formal/` and names its declaration; `[ESTABLISHED]` is a ratified note's or +> a fact of the repository; `[DERIVED]` is argued here; `[TESTED]` names the test that holds it. + +## 1. Purpose + +An agent that is not the owner's local model, run by someone else or on another machine, may ask +the palace over MCP. It should read the dialogue, the repository's code and docs, the curated +papers and the observed records, and never the owner's notes or what a model derived from them. +The Ambassador's grant reads the notes; a second grant is needed, and a surface that serves it. + +## 2. The grant + +`core/query.py::GUEST` follows the Ambassador's plane structure without the mirror's version +plane: + +| plane | strata named (closed downward) | fibers | clock | authority | +|---|---|---|---|---| +| projection events | dialogue (transcript, artifact), reference (reference_repo), curated, observed | F, D | projection_event | read | +| commits | reference (reference_repo), dialogue (transcript, artifact) | F, C | commit | read | + +`[THEOREM: SCO-9]` The grant is one the code accepts (`Scope.lean::guest_grantOk`); none of its +planes names the mirror, `mirror_authored` or the interpreted stratum, closure included +(`Scope.lean::guest_reads_no_note`), so a clause that reads any of them is refused +(`Scope.lean::guest_refuses_note`); no plane carries the write bit, so it admits no command +(`Ingress.lean::guest_admits_no_command`, from ING-1's `readonly_admits_no_command`); none names +the overlay, so it admits no `assume` (`Sentence.lean::Sentence.guest_no_assume`, from QSA-5's +`admissible_assume_overlay`). The closure is SCO-1's: a refinement closes downward within its own +tree, and the four strata's trees do not hold the mirror; `exhaust` is excluded by the closure and +`hypothetical` is named by no plane. + +The interpreted stratum is left out because its relations and dreams are readings of the notes +and can quote them. The version plane is left out because its chains are the notes' own. + +## 3. The role + +`grant_for("guest")` returns `GUEST` (`core/ingest/ingress.py`, `_READ_ROLES`). The role has no +spool and no role in the table: a request compiled for it is refused at admission (no plane has +the write bit) or by the script checker (the role opens no source), and `write_request` refuses +the role before it touches a directory. `[TESTED: test_the_guest_role_is_refused_every_request]` + +## 4. The surface + +`uv run --project python scripts/palace_mcp.py --role guest` speaks MCP on stdio after +sealing the core, like the Ambassador's server. With `MIND_PALACE_OVERLAY=config/instances/code.toml` +it serves the code instance (`dn-palace-lite` §4.4), whose files a sentence names as +`code//`. It lists two tools: + +- `query`: a sentence under `GUEST` through `ask_logged`, logged as surface `mcp`, role `guest`. + A refusal reaches the guest as `GuestRefusal: : `, and the text depends on where + the sentence was refused. The surface compiles the sentence again, alone, with the trace when + the call asked for one, as the first compile had it (the trace renders the parse, so a sentence + can fail to compile with it alone); that reads the sentence and the grant and no store. If the + compiler refuses it, the text is the compiler's reason with every quoted run replaced by its + length (`redact_reason`, the log's own redaction): that reason holds the asker's words and + nothing a store holds. If it compiles, the refusal was raised while the sentence ran against + the stores, and the text is one fixed sentence for its class (`GUEST_RAN`: lookup, ambiguous, + unsupported, scope, sort, parse, busy, error), never the reason. A reason raised in the run may + quote what a store holds, and the redaction pairs quotes by position: an apostrophe in a + reason's own words pairs with the opening quote of a quoted path and leaves the path in clear, + and text quoted any other way passes whole. The query log keeps the reason for the owner. A + scope refusal of either kind adds the strata the grant reads and how to name them with `over`. + `[TESTED: test_a_refusal_says_the_compilers_reason_or_its_classs_one_sentence, + test_a_sentence_the_compiler_refuses_under_the_trace_alone_reads_its_reason]` +- `overview`: the catalog's active entries of the classes the grant's strata hold, the curated + store's chunk count, and the grant's planes. On an instance of the lite profile + (`dn-palace-lite`) it says what the Ambassador's says of the profile, over the same classes: + that the instance embeds nothing, the lexical index's current units of those classes, and each + repository of the lexical code source by its name and ref, with the commit it last landed, + when, and how many commits the ref has moved past it. The Ambassador's overview also counts + every vector row, the relation edges, the versions and every lexical unit; each of those totals + counts the notes, so none is shown. An overview that fails says one fixed sentence. + +The body of each of the guest's tools raises `GuestRefusal` and nothing else. The engine is built +on first use, inside the body, so a configuration or a store that cannot be opened is a refusal +too, and a refusal is raised without its cause, so its traceback on stderr holds the refusal's +words only. The client reads stdout as the protocol stream, one message per line, and nothing +else reaches it: the launcher writes the replies to a copy of file descriptor 1 that no child +inherits and points the descriptor itself at stderr (`protocol_stream`), so what C code, a child +process or `sys.__stdout__` writes there lands on stderr, and a tool runs with `sys.stdout` +pointed at stderr as well (`Server.handle`). A reply that UTF-8 cannot encode, one repeating a +lone surrogate that a sentence held, is written as ASCII, the same JSON, whatever the stream's +error handler: Python's UTF-8 mode gives stdout `surrogateescape`, which would write some +surrogates as bytes that are not UTF-8. A line that is no request (JSON that is not an object, +params that are not one, an id that is no string or number, a number past Python's limit on the +digits it converts, nesting past the stack) is answered with JSON-RPC's error for it. +`initialize` repeats the protocol version a client asks for only when it is a string and answers +any other value with the server's own, so no reply carries a nesting the client sent, and a reply +that `json.dumps` cannot write all the same is answered as an internal error with the request's +id. Either way the server reads on. +`[TESTED: test_what_the_guests_tools_print_stays_off_the_protocol_stream, +test_what_a_tool_writes_to_the_descriptor_stays_off_the_protocol_stream, +test_a_line_that_is_no_request_is_answered_and_the_server_reads_on, +test_initialize_answers_the_version_asked_when_it_is_a_string_and_its_own_otherwise, +test_a_request_whose_reply_cannot_be_written_is_answered_as_an_internal_error]` + +`status` is left out: it lists the owner's open and due tasks and the running jobs, whose briefs +can name notes. No write tool is served (capture, tasks, reminders, link, dream, relate, the +syncs). The instructions are the guest's own; the brief describes tools the guest does not have. +With no `--role`, the server is the Ambassador's, its table and brief unchanged. + +## 5. What the other stores say of the notes + +`[ESTABLISHED]` Admission is clause-wise and the universe holds only the strata the admitted +clauses read (QSA-5, `core/sentence/universe.py`). That bounds rows. It does not bound what an +admitted row says. The causal store belongs to the transcript stratum, and an edge's endpoint is +a path: a turn that wrote a note names the note's vault path. Under a sentence that does not read +the mirror, the universe named such an endpoint as a node of the transcript stratum, path and +title alike, and `witness` of the edge returned its endpoint. For the Ambassador, whose grant +reads the mirror, that shows nothing new. For a grant without the mirror it is a leak. +`[TESTED]` With the change below switched off, five sentences of the guest's battery returned the +canary note's path: `reach C` and `walk … via C` from the turn, over strata that hold the +transcript, and `witness` of the edge. + +The change keys on the grant, not the sentence. `Grant.strata` is the union of a grant's planes. +When it holds no stratum of the mirror, `ask_logged` builds the universe with `hide_mirror`: + +1. the note graph is not built; the dialogue loads through its own clearance; +2. a causal edge is shown only when it ends at a commit, named by its hex sha, or at a file git + tracks in this checkout at HEAD (`_Builder._named`), written as an absolute path under a + checkout of the repository or as a doc's id that resolves to exactly one file. The vault is + asked first, and a path is withheld when it is the vault or lies under it with each component + folded for letter case and Unicode normal form, as written, normalized or resolved + (`_in_vault`). Every other edge is withheld whole, its id with it; +3. a citation neighbour is named only when it is spelled as a repo-relative path (not absolute, + not under `~`, no URI, no `..` component) and, joined to the root of each checkout, lies + outside the vault (`_citable`); +4. `witness` answers no withheld edge, asked by its own id or through the reference edge whose + commit it witnessed, and no landing's attestation (the guest holds no receipt, and a note's + landing is attested too). Through a reference edge it answers the first edge keyed to the + commit that the reader may see named: a withheld one is judged before the first is chosen, + so it never stands in front of a named one (`origin`'s `admit`); +5. the answer says so in one sentence whose words do not depend on what was withheld. + +`[DERIVED]` Withholding the whole edge, rather than naming the endpoint by a placeholder or +counting what was dropped, keeps the guest's answers a function of what its grant reads: a +placeholder or a count per edge would be a function of the notes. An edge's id is a content id +over its endpoint, so it is withheld too. A grant that reads the mirror builds the same universe +as before, by the same call. + +`[DERIVED]` Item 2 is an allow list, and fails closed. Its first form was a deny rule, which +withheld an edge whose endpoint lay lexically under the vault path, and a path has more +spellings than that rule knew. A red team found five that passed it, each showing the guest a +note's path or name as a hit and through `witness`: the vault directory in another letter case, +or the path in another Unicode normal form, which a file system that folds them treats as the +same file; a relative path; a `file://` URI; and the bare file name the event projector keeps for +a file written under a `docs/design-notes/` folder. A deny rule has to know every spelling of a +vault path. An allow list has to know only what may be shown, and what it cannot judge it +withholds: git that cannot be asked names no file, an endpoint that raises while it is judged is +not named, and a doc's id that holds a glob's characters resolves to no file (the projector keeps +a file name as the id, and a finding's or a plan's file is found by a glob). The vault check +folds letter case, the Unicode normal form, `.` and `..`, symlinks and `~`. A file system knows +a note by other names as well, a hard link or its path through another mount of the volume +(macOS's `/System/Volumes/Data`), which the check does not fold; the allow list judges such a +name as it judges any path, and names it only when it is a file git tracks in a checkout of the +repository. The cost falls on endpoints the rule cannot tie to a tracked file. The guest no +longer sees named an endpoint outside the repository, a relative path (one that names a tracked +file among them), a tracked file's path in another letter case or under another clone, a file +git does not track at HEAD (untracked, or deleted since), a file that exists only in another +worktree, or a doc's id that is not one tracked file; a grant that reads the mirror is shown +each of them as before. +`[TESTED: test_an_edge_is_shown_only_when_it_ends_at_a_commit_or_a_tracked_file]` Nine such +edges and four such citations added to the fixture change no guest output, byte for byte; +`witness` of each id answers nothing; the Ambassador is shown every one. + +`[DERIVED]` An instance that embeds nothing (`dn-palace-lite`) is what the guest is meant to +serve: an external coding agent reads the code instance (`config/instances/code.toml`). Such an +instance lands every item with its lexical units and no vector, a vault's notes among them, in +one index, and ranks `near` by BM25 over it, so a ranking whose unit count, mean length or +document frequencies were read over the whole index would be a function of the notes. They are +read over the classes a ranking asks for (`LexicalStore._score_units`), and every lexical path of +the universe asks for classes the grant reads: the reference seed for the code's, the curated +seed for the papers', the dialogue's vectorless items for the dialogue's (`load_pending` lists +no other class under `hide_mirror`), and the scores of a clause's vectorless nodes for the +classes of those nodes, which are the admitted strata's. A landed repository file is read from +the raw store only when the catalog holds it as code (`_read_landed_file`); any other ref falls +to git's tree at the cut, as before. The rules above hold unchanged. So the guest's ranks, +scores, notes and counts on such an instance are functions of what its grant reads. +`[TESTED: test_the_guest_cannot_tell_two_palaces_that_embed_nothing_apart]` Two such palaces +whose notes differ in their words and their length, and which are alike in all else the guest +reads, the second their repository landed included, give the guest the same answers to the +battery and the code source's refs, and the same overview; a ranking's statistics over every +class, the reference seed over every class or the overview's units as a total each fail the test, +and the Ambassador's answers and counts tell the two palaces apart. + +## 6. The laws the guarantee rests on + +SCO-1 (the closure of the four strata holds no mirror stratum), SCO-6 (admissibility and the zone +law), QSA-5 (a sentence is admitted clause by clause), ING-1 (a read-only grant admits no +command), PLN-1 (a read under a clearance returns only the classes it names), PLN-2 and BRG-5 +(noninterference through the plane), QSA-10 (`over` is the mask by the clearances' table), and +the new SCO-9 for this grant. The universe's withholding is code, held by the noninterference test +below and not by a theorem. + +## 7. The tests + +`tests/adversarial/test_guest_leaks.py` builds a palace on real stores holding a note with a +canary in its path, title and body, landed by the ingress; an interpreted relation from it to an +authored dialogue turn; an authored and an observed dialogue turn; a transcript turn whose causal +edges point at the note and at a repo file; a paper; a code atom; and a citation graph. As the +guest, it asks every verb, with and without `over`, every adjective and connective, `assume` and +the requests, with and without `trace`, then `overview` and `status`. + +- No output carries the canary, as a path, a title, a text, a count or a refusal; every sentence + that names the note is refused. +- The admitted strata answer: dialogue, code, papers, the transcript and the repo's files. +- Over a second palace whose note, relation, landing and vault edge differ, every guest output + is the same once the names the asker typed are normalized. +- The control: the Ambassador, asked the same, sees the canary in the `near`, `reach C`, + `witness`, `relate` and `read` answers. +- The note under other spellings: the causal store gains nine edges from the turn (the vault + directory upper-cased, the path in its other Unicode normal form, two relative paths, a + `file://` URI, the file name the projector keeps for a vault file under `docs/design-notes/`, + such a name that is a glob's pattern for a tracked finding, an untracked path in the checkout, + a path outside the repository), and the citation graph four from a repo file to the note's + path and three spellings of it. Asked the battery, each new id and each new endpoint, the guest + answers what it answered before, byte for byte; `witness` of each id answers nothing; the + Ambassador is shown every one. +- Refusals: a sentence the compiler refuses reads the compiler's reason, redacted, and so does + one it refuses under the trace alone; one refused while it ran reads its class's fixed + sentence, with and without the trace; a store's error whose reason quotes a path with an + apostrophe reaches the guest as its class alone, on the stream and on stderr, while the query + log keeps the reason; an `overview` that fails and an engine that cannot be built are each one + fixed sentence. +- The query log: a sentence with a line separator, one with an escape sequence and a forged + line, a bidi override, a lone surrogate, a sentence of 300,000 characters and one of 50,000 + characters outside the BMP each take one ASCII line of the log, the long ones cut, no line + longer than the cut allows, and both renderings of `palace query --log` print every such + character escaped. +- The protocol stream: a store that prints while the guest's tools run leaves one reply per + request on the stream the server writes and nothing else; what it printed is on stderr. The + launcher, spawned with a guest tool that writes a forged reply to file descriptor 1, runs a + child that prints and writes to `sys.__stdout__`, leaves one reply per request on stdout, and + every such line on stderr. +- The default server keeps the Ambassador's table and brief; the launcher serves the guest's + two tools and refuses an unknown role. + +`tests/unit/test_sentence_universe_withheld.py` holds the rule at the universe builder, over a +scratch git repository standing for the checkout: the tracked paths are the tree at HEAD and none +when git cannot answer; a vault path is recognised in another letter case, another Unicode normal +form, with `.` and `..`, through a symlink and under `~`, and a name the check does not fold, a +hard link or the path through another mount, is not named by the allow list; only a commit or a +tracked file is named, and only a commit when the tree cannot be read, and a configured vault +that is a symlink into the checkout withholds the tracked files under it; a turn whose edges are +all withheld is refused as a turn no edge names; the witness of a reference edge is judged like +any other, and a withheld edge keyed to its commit stands in front of no named one; the +withholding note is one sentence whatever the store holds; a citation neighbour is named only as +a repo-relative path outside the vault. A grant that reads the mirror is shown what it was shown +before, and `tests/unit/test_sentence_universe.py` passes unchanged. +`tests/unit/test_sentence_surface.py` holds the log (a line separator, a lone surrogate, the cut +in characters and in bytes, the escapes in both renderings, a line that is not an entry skipped +and counted, the log read a line at a time), `tests/unit/test_ambassador_surface.py` the stream +(what a tool prints goes to stderr; a process without stderr drops it; a reply UTF-8 does not +encode is written as ASCII, on a strict stream and on one with `surrogateescape`; a line that is +no request is answered and the server reads on; `initialize` repeats a version only when it is a +string; a request whose reply cannot be written is answered as an internal error and the server +reads on), and `tests/unit/test_sentence_grammar.py` that a string literal is read in memory its +text bounds. How deep `json` nests depends on the thread's stack (8 MB for a Linux main thread +under the usual `ulimit -s`, 16 MB for the main thread of a macOS framework build), so the tests +that need a nesting past it serve their lines on a thread whose stack they set to 1 MB. + +`tests/adversarial/test_guest_lite.py` asks the same of an instance that embeds nothing. Its +palace lands the note through `sync_vault` and a scratch repository's files through +`sync_repository`, each with its lexical units and no vector, and holds the dialogue and a paper +with lexical units alone and the same transcript turn, causal edges and citation graph. + +- The battery and the code source's refs (a lexical `near` over reference, `read` of a landed + file, `diffuse S` and `reach F` from one, `trace`, a file the repository does not have): no + output carries the canary; `S` has no edge there, so its walks are empty, and the paper, which + such an instance keeps in no plane, is ranked and not read; every sentence the battery refuses + is refused. +- Over a second such palace whose note differs in its words and its length, its repository's + landing dated to the same second as the first's, every guest output and the overview are the + same; the Ambassador ranks the first note first and counts more units. +- Every score and every count the lexical index makes while the guest asks names its classes, + each one the grant reads; the Ambassador's `near` over the notes names the notes' class. +- `near` over reference ranks the repository's files, each labelled `ranked_by`, its notes saying + the instance embeds nothing; `read` opens a landed file; `overview` says the profile, the units + of the admitted classes (fewer than the index's) and the repository with its landed commit. +- The launcher, spawned with an overlay made from the code instance's own after its repository + landed, lists the guest's tools and answers `overview`, a lexical `near`, a `read` and three + refusals in their fixed words, one reply per request on stdout; the instance's own query log + holds the guest's sentences, and no vector store is made. + +## 8. Limits + +- The dialogue is admitted as it is. A chat turn, a capture or an assistant reply that quoted a + note is a dialogue row, and the guest reads it. The grant bounds strata, not what an admitted + text says. Keeping such quotations out needs a narrower grant (reference and curated alone) or + a filtered dialogue; neither is part of this change. +- The isolation is in code. The guest's server opens the instance's stores under the account it + runs as. Serving an untrusted party should add the operating system's isolation as well + (`plane-principals`): its own account, read access to what the grant reads. +- Response times may depend on the size of the excluded strata (the overview scans the whole + catalog; the causal index reads every edge; a lexical ranking reads a term's postings in every + class before it keeps its own). So may a time the guest reads: the overview shows the second + each repository landed, a clock reading, and the daemon's one queue lands a vault's notes and + a repository's files in turn, so a landing of the notes queued first delays it. Timing is not + addressed. +- The reference stratum holds what the instance lands in it. A repository source is read through + git at its ref, and the loader compares a repository's path with no vault: a repository whose + tree tracks a vault's files would land the notes as code, and the guest reads code. The code + instance declares this repository alone. Refusing a repository at, inside or around a vault + this host reads belongs in the loader and is not part of this change. +- A vault file under a `docs/design-notes/`, `docs/findings/` or `docs/build-plans/` folder is + recorded by the event projector (`core/chat_events.py`) as a bare doc id, with no path. Its + edge is shown only when the id resolves to exactly one tracked doc of the repository, and then + as that doc: the guest learns that a turn wrote a file of that doc's name, never the vault's + path. The exact fix keeps the path at projection, or classifies a doc only under a checkout; + it belongs in the projector and is not part of this change. +- A citation neighbour is not checked against the tree at HEAD, since the citation graph is read + at other cuts. Its refs are repo-relative paths projected from the repository's history, so + they denote the repository's files; a citation store that held a relative path naming + anything else would show it. +- The client that spawned the server also reads its stderr: a refusal's traceback, which holds + the refusal's words only, and whatever a tool, a library under it or a child process writes + there or to file descriptor 1. What reaches stderr is not filtered. +- The guest's sentences enter the instance's query log with role `guest`, as every surface's do. + A line is ASCII, a sentence is kept up to 4,096 characters and up to 8,192 bytes of the line, + a character counted as its escape, and then a marker of its full length, and + `palace query --log` reads the log a line at a time and prints every character that is not + printable as its escape, so a sentence cannot break the log or write into the terminal that + reads it. Nothing bounds the log's size: each call appends a line of at most some 12 KB, and a + guest that calls without pause grows it by megabytes a second until the disk is full (2,000 + calls of 5,000 characters outside the BMP, through the launcher, appended 8,536 bytes each, + 17 MB in 2.8 s, at a one-minute load of 2.0). How it is bounded (a size past which it rotates + or stops, a budget per role) and what is dropped at the bound are the owner's to decide; this + change sets no bound. +- A sentence's size is not capped; only a command's is (`MAX_COMMAND_BYTES`). The server reads + a request's line whole and holds some five times its size while it answers: through the + launcher, a request refused as it parses took the server to 411 MB for a line of 50 MB and to + 1,169 MB for one of 200 MB, answered in 6.1 s (one-minute load 1.5 to 2.0), so a line of about + 0.8 GB would take it past 4 GB. A sentence refused as it parses is read three times: by the + compile, by the log's entry, which reads its shape, and by the surface's second compile. A + string literal is read in memory its text bounds: asked in process, a refused sentence of + 40 MB raised the server's peak by some 40 MB past the sentence itself and was answered in + 0.8 s, and one of 40 MB of escaped quotes by some 54 MB, in 1.3 s (one-minute load 3.4 to + 3.8). Whether a guest's sentence is capped, at what size, whether every surface takes the cap, + and whether the server's reader stops a line at it, are the owner's to decide. diff --git a/docs/design-notes/dn-palace-lite.md b/docs/design-notes/dn-palace-lite.md index afa8ac03..be3289aa 100644 --- a/docs/design-notes/dn-palace-lite.md +++ b/docs/design-notes/dn-palace-lite.md @@ -170,8 +170,11 @@ The MCP server runs against the instance by its overlay: The read is the one `query` tool; a lookup is `top 5 near "" over reference`, `read "code//"`, `trace "code//"`. The server's write tools spool requests that -no daemon of this instance lands; the read-only principal of the parallel guest work removes them -from the tool list once it merges. +no daemon of this instance lands. With `--role guest` it serves the read-only principal instead +(`dn-guest-principal`): `query` and `overview` alone, no write tool, and a grant with no version +plane, so `trace` is refused there and the other lookups answer as above. + + MIND_PALACE_OVERLAY=config/instances/code.toml uv run --project python /scripts/palace_mcp.py --role guest ## 5. The default instance's code, without embedding diff --git a/formal/Palace/Ingress.lean b/formal/Palace/Ingress.lean index 0d2062d6..66e1ebed 100644 --- a/formal/Palace/Ingress.lean +++ b/formal/Palace/Ingress.lean @@ -1148,4 +1148,11 @@ theorem ambassador_refuses_commit_command : · exact absurd hle.2.2.2.2.1 (by decide) · exact absurd hle.2.2.1.1 (by decide) +open Palace.Query in +/-- **SCO-9** No plane of the guest's grant carries the write bit, so it admits no command +(ING-1). -/ +theorem guest_admits_no_command {Rg H : Type*} (c : Clause) (hc : IsCommand c) : + ¬ Sentence.Admissible CQ.guest (Sentence.clause c : Sentence Rg H) := + readonly_admits_no_command CQ.guest (by decide) c hc + end Palace.Ingress diff --git a/formal/Palace/Scope.lean b/formal/Palace/Scope.lean index 885cb209..42ac0c10 100644 --- a/formal/Palace/Scope.lean +++ b/formal/Palace/Scope.lean @@ -966,6 +966,28 @@ theorem search_reference_history (authored : Bool) : revert authored decide +/-! ## The guest's grant (`core/query.py::GUEST`) -/ + +/-- **SCO-9** The guest's grant is one `Grant` accepts: no plane names the foundation, and none +reaches the world. -/ +theorem guest_grantOk : GrantOk guest := by + decide + +/-- **SCO-9** No plane of the guest's grant names the mirror, its authored refinement or the +interpreted stratum, closure included: not the owner's notes, nor the readings derived from +them. -/ +theorem guest_reads_no_note : + ∀ p ∈ guest, Disjoint p.sigma {.mirror, .mirrorAuthored, .interpreted} := by + decide + +/-- **SCO-9** So a scope that reads any of the three lies under no plane of the guest's grant: a +clause that requires one is refused. -/ +theorem guest_refuses_note (r : Scope) {s : Stratum} + (hs : s ∈ ({.mirror, .mirrorAuthored, .interpreted} : Finset Stratum)) (hr : s ∈ r.sigma) : + ¬ admits guest r := by + rintro ⟨p, hp, hle⟩ + exact disjoint_left.1 (guest_reads_no_note p hp) (hle.1 hr) hs + /-! ## Roles and conformance -/ /-- Every role is zone-admissible by construction, at any strata and any executor reach. -/ diff --git a/formal/Palace/Scope/Defs.lean b/formal/Palace/Scope/Defs.lean index 700f730b..3408a49e 100644 --- a/formal/Palace/Scope/Defs.lean +++ b/formal/Palace/Scope/Defs.lean @@ -408,6 +408,14 @@ def overlayGrant (g : List Scope) : List Scope := g.map Scope.nameOverlay grant of 2026-11-04 to the sentence surfaces. -/ def ambassadorOverlay : List Scope := overlayGrant ambassador +/-- The guest's grant `GUEST`: the Ambassador's first two planes over the strata a guest reads +(the dialogue, the reference stratum, the curated papers, the observed records), read-only, with +no world reach; `grant_for` resolves the role `guest` to it (`core/ingest/ingress.py`). -/ +def guest : List Scope := + [⟨close {.dialogue, .reference, .curated, .observed}, {.F, .D}, ⟨.projectionEvent, .all⟩, + ⟨0, 0, 0⟩, 1, none⟩, + ⟨close {.reference, .dialogue}, {.F, .C}, ⟨.commit, .all⟩, ⟨0, 0, 0⟩, 1, none⟩] + /-! ## Clearances (`core/kernel/clearance.py`) -/ /-- `Provenance`: the record classes. -/ diff --git a/formal/Palace/Sentence.lean b/formal/Palace/Sentence.lean index 38bda518..e24ce532 100644 --- a/formal/Palace/Sentence.lean +++ b/formal/Palace/Sentence.lean @@ -222,6 +222,17 @@ theorem ambassador_no_assume (h : H) (s : Sentence Rg H) : obtain ⟨p, hp, hmem⟩ := admissible_assume_overlay ha exact ambassador_no_overlay p hp hmem +/-- The guest's two planes name the overlay on none. -/ +theorem guest_no_overlay : ∀ p ∈ CQ.guest, CQ.Stratum.hypothetical ∉ p.sigma := by + decide + +/-- **SCO-9** so the guest's grant admits no hypothetical (QSA-5). -/ +theorem guest_no_assume (h : H) (s : Sentence Rg H) : + ¬ Admissible CQ.guest (.assume h s) := by + intro ha + obtain ⟨p, hp, hmem⟩ := admissible_assume_overlay ha + exact guest_no_overlay p hp hmem + /-- A scope under a plane stays under the plane with the overlay named. -/ theorem le_nameOverlay_of_le {r p : CQ.Scope} (h : r.Le p) : r.Le p.nameOverlay := by obtain ⟨h₁, h₂, h₃, h₄⟩ := h diff --git a/formal/README.md b/formal/README.md index 3fd1b08f..7e94c4dd 100644 --- a/formal/README.md +++ b/formal/README.md @@ -386,7 +386,7 @@ Roundoff and FloatModel, so it has no statements of its own): delegation's noninterference through the plane, and BRG-6 Forman's curvature as the Weitzenböck term of `L₁`. - `comparator.json`: what `lake comparator` judges: `Spec` against `Palace`, the cited theorems - (375 theorems), and the three standard axioms. + (380 theorems), and the three standard axioms. - `Compare.lean`: the comparator's comparison step, run in-process where its sandbox is unavailable (macOS has no `bwrap`); CI runs the comparator itself. It is weaker than the comparator: it compares the statements' types and the definitions' values, not constructors, recursor rules or @@ -472,6 +472,7 @@ Roundoff and FloatModel, so it has no statements of its own): | SCO-6 (firewalls, zone) | admissibility and the zone law are downward closed and survive every meet; a world-reaching scope that passes the zone law names only `world`, the denylist and the overlay, so is cleared for no class under any table that gives those three none; the zone law does not survive join | proved, with a witness; attack survived 306 | | SCO-7 (grants) | a grant's meet skips the pairs with no meet, lies under both grants plane by plane, never trips `InadmissibleGrant`, and admits only what both admit | proved, with a witness | | SCO-8 (`search`) | `search` never raises `SliceError`, over any strata, with or without history; over `reference` alone it builds with the single-read cut and the Ambassador's grant admits it | proved; attack survived 500 | +| SCO-9 (the guest) | the guest's grant is accepted, names no stratum of the mirror and not the interpreted stratum, closure included, so it refuses any clause over them, and admits no command and no `assume` | proved, by `decide` and by ING-1 and QSA-5 | | SIG-1 | Kruskal's forest has, at every threshold, the graph's components: one forest yields every pairwise σ* | proved; attack survived 500 | | SIG-2 | what the loop keeps is a forest, `\|F\| + c(F) = \|V\|`, and its labels are its components | proved; attack survived 500 | | SIG-3 | σ* is a symmetric ultrametric | proved; attack survived 500 | diff --git a/formal/Spec/Ingress.lean b/formal/Spec/Ingress.lean index 5c3b983c..625a5441 100644 --- a/formal/Spec/Ingress.lean +++ b/formal/Spec/Ingress.lean @@ -55,6 +55,13 @@ theorem ambassador_refuses_commit_command : ¬ CQ.admits CQ.ambassador (commandScope {.reference} .commit) := sorry +open Palace.Query in +/-- **SCO-9** No plane of the guest's grant carries the write bit, so it admits no command +(ING-1). -/ +theorem guest_admits_no_command {Rg H : Type*} (c : Clause) (hc : IsCommand c) : + ¬ Sentence.Admissible CQ.guest (Sentence.clause c : Sentence Rg H) := + sorry + /-- **ING-7** With the key written last, a fresh run interrupted after any step converges: the next run lands exactly the uninterrupted run's state. -/ theorem ingest_prefix_converges (x : Source R D G) (s : State R D G) (hs : Fresh x s) (k : ℕ) : diff --git a/formal/Spec/Scope.lean b/formal/Spec/Scope.lean index 05797fc7..b849f69c 100644 --- a/formal/Spec/Scope.lean +++ b/formal/Spec/Scope.lean @@ -221,6 +221,25 @@ theorem search_reference (authored : Bool) : required .search [.reference] false authored = .ok r ∧ admits ambassador r := sorry +/-- **SCO-9** The guest's grant is one `Grant` accepts: no plane names the foundation, and none +reaches the world. -/ +theorem guest_grantOk : GrantOk guest := + sorry + +/-- **SCO-9** No plane of the guest's grant names the mirror, its authored refinement or the +interpreted stratum, closure included: not the owner's notes, nor the readings derived from +them. -/ +theorem guest_reads_no_note : + ∀ p ∈ guest, Disjoint p.sigma {.mirror, .mirrorAuthored, .interpreted} := + sorry + +/-- **SCO-9** So a scope that reads any of the three lies under no plane of the guest's grant: a +clause that requires one is refused. -/ +theorem guest_refuses_note (r : Scope) {s : Stratum} + (hs : s ∈ ({.mirror, .mirrorAuthored, .interpreted} : Finset Stratum)) (hr : s ∈ r.sigma) : + ¬ admits guest r := + sorry + /-! ## Witnesses: what the model found, and what the fixes changed -/ namespace Witness diff --git a/formal/Spec/Sentence.lean b/formal/Spec/Sentence.lean index 9d151117..ffc23e79 100644 --- a/formal/Spec/Sentence.lean +++ b/formal/Spec/Sentence.lean @@ -106,6 +106,11 @@ theorem ambassador_no_assume (h : H) (s : Sentence Rg H) : ¬ Admissible CQ.ambassador (.assume h s) := sorry +/-- **SCO-9** so the guest's grant admits no hypothetical (QSA-5). -/ +theorem guest_no_assume (h : H) (s : Sentence Rg H) : + ¬ Admissible CQ.guest (.assume h s) := + sorry + /-- **QSA-5** every sentence admissible under a grant is admissible under the grant with the overlay named: the owner's grant widens, never narrows. -/ theorem admissible_overlayGrant_of_admissible {s : Sentence Rg H} (h : Admissible g s) : diff --git a/formal/comparator.json b/formal/comparator.json index aff69491..bb76128d 100644 --- a/formal/comparator.json +++ b/formal/comparator.json @@ -51,6 +51,9 @@ "Palace.CQ.close_mono", "Palace.CQ.grantMeet_grantOk", "Palace.CQ.grantMeet_le", + "Palace.CQ.guest_grantOk", + "Palace.CQ.guest_reads_no_note", + "Palace.CQ.guest_refuses_note", "Palace.CQ.search_never_slices", "Palace.CQ.search_reference", "Palace.CQ.subset_close", @@ -137,6 +140,7 @@ "Palace.Ingress.ambassador_admits_projection_command", "Palace.Ingress.ambassador_refuses_commit_command", "Palace.Ingress.command_admissible_iff_write", + "Palace.Ingress.guest_admits_no_command", "Palace.Ingress.ingest_after_nonkey", "Palace.Ingress.ingest_prefix_converges", "Palace.Ingress.key_early_does_not_converge", @@ -186,6 +190,7 @@ "Palace.Query.Sentence.ambassadorOverlay_admits_assume_iff", "Palace.Query.Sentence.ambassadorOverlay_no_world", "Palace.Query.Sentence.ambassador_no_assume", + "Palace.Query.Sentence.guest_no_assume", "Palace.Query.Sentence.not_isInv_assume", "Palace.Query.admissible_assume", "Palace.Query.admissible_iff_prodOk", diff --git a/papers/2026-11-09-guest-principal/paper.tex b/papers/2026-11-09-guest-principal/paper.tex new file mode 100644 index 00000000..cb21eaa7 --- /dev/null +++ b/papers/2026-11-09-guest-principal/paper.tex @@ -0,0 +1,410 @@ +% A self-contained article for one pull request: the guest principal. +\documentclass[11pt]{article} +\usepackage[T1]{fontenc} +\usepackage{lmodern} +\usepackage{microtype} +\usepackage[margin=1in]{geometry} +\usepackage{amsmath,amssymb,amsthm,mathtools} +\usepackage{algorithm} +\usepackage{algpseudocode} +\usepackage{booktabs} +\usepackage[numbers,sort&compress]{natbib} +\usepackage[hidelinks]{hyperref} +\usepackage[capitalise,noabbrev]{cleveref} + +\theoremstyle{plain} +\newtheorem{theorem}{Theorem}[section] +\newtheorem{lemma}[theorem]{Lemma} +\newtheorem{proposition}[theorem]{Proposition} +\newtheorem{corollary}[theorem]{Corollary} +\theoremstyle{definition} +\newtheorem{definition}[theorem]{Definition} +\theoremstyle{remark} +\newtheorem{remark}[theorem]{Remark} + +\newcommand{\lean}[1]{\texttt{#1}} +\newcommand{\str}[1]{\textsf{#1}} + +\title{A Read-Only Guest Principal for a Personal Knowledge Store} +\author{Alberto Serrano-Calva} +\date{9 November 2026} + +\begin{document} +\maketitle + +\begin{abstract} +A personal knowledge store answers sentences of a typed query algebra under a grant: a set of +scopes, one per clock, and a sentence is admitted when every clause's required scope lies under +some granted plane. The store's local model holds a grant that reads the owner's notes. We add a +second principal for an agent outside that trust boundary: a read-only grant over the dialogue, +the repository's code and documents, curated papers and observed records, and never the notes or +the model readings derived from them. The grant's properties are a finite check, proved in Lean: +it names no stratum of the notes after downward closure, so every clause over them is refused, and +it admits no command and no hypothetical. Admission bounds which rows a sentence reads; it does not +bound what an admitted row says. The transcript stratum records the path of every file a +conversation wrote, a note's included. An adversarial battery of 71 sentences over a fixture store +found five that returned a note's path, through a causal edge's endpoint and through +\texttt{witness}. A first repair withheld every edge that ends under the vault's path, and a red +team found five other spellings of a note's path that passed it. For a grant without the notes, +the universe a sentence reads now shows a causal edge only when it ends at a commit or at a file +the repository tracks, and withholds every other edge whole; a refusal raised while a sentence +runs reaches the guest as one fixed sentence for its class. After the change no output of the +battery, with or without its trace, carries a canary token placed in a note's path, title and +body, and the guest's outputs over two stores that differ only in the notes are identical. The +same holds over a store that embeds nothing and ranks by one lexical index holding the notes' +units beside the code's, the case of an external coding agent reading the repository: the guest's +rankings read the statistics of the classes its grant reads. +\end{abstract} + +\section{Introduction} + +The store \citep{palace2026} keeps several strata: the \emph{mirror} (the owner's notes), +\emph{interpreted} relations and readings that models derive from the notes, the \emph{dialogue} +(chat turns, the transcripts of agent sessions and the documents written in them), the +\emph{reference} stratum (the repository's code and documents), \emph{curated} papers, and +\emph{observed} records. Every read is one sentence of a query algebra, compiled under the +reader's grant; a clause whose required scope no plane covers is refused before any store +opens. Until now two principals held grants: the local model (the Ambassador) and the owner's own +surfaces. Both read the notes. + +An agent run by someone else, or on another machine, should be able to ask about the code, the +papers and the conversations without reading the notes. The request is least privilege +\citep{saltzer1975protection}: a principal holds the authority its task needs and no more. In a +capability system \citep{dennis1966semantics} that is a smaller capability, and here it is a +grant. The contributions are: +\begin{itemize} + \item a grant \str{GUEST} and a role \str{guest} that resolves to it, with its properties proved + in Lean (row SCO-9 of the store's laws ledger); + \item an MCP surface \citep{mcp2025} for the role, with two tools, \texttt{query} and + \texttt{overview}, and refusals that pass on no reason raised against the stores; + \item a leak found by an adversarial battery, an overt reference from an admitted stratum to an + excluded one, and its repair in the universe builder, an allow list that fails closed; + \item a noninterference test: the guest cannot tell two stores apart that differ only in what + its grant excludes, whether the store embeds its items or ranks them lexically. +\end{itemize} + +\section{Background and related work} + +\paragraph{Scopes and grants.} +A scope is a point $(\Sigma, E, T, A)$ of a product lattice: a downward-closed set of strata +$\Sigma$ in a refinement forest (\str{mirror\_authored} below \str{mirror}, +\str{dialogue\_transcript} and \str{dialogue\_artifact} below \str{dialogue}, +\str{reference\_repo} below \str{reference}), a set of edge fibers $E \subseteq \{F, D, C\}$ +(citation, version, causal), a clock and window $T$, and an authority $A$ (read or propose, a +write bit, a world reach). The order is componentwise. A grant is a list of scopes, one per +clock, because windows on different clocks have no meet. A sentence's clauses each require a +scope; the sentence is admissible under a grant iff each requirement lies under some plane +(QSA-5). + +\paragraph{Clearances.} +Rows carry provenance classes, and a read is made under a clearance, a set of classes; a read +under a clearance returns rows of those classes only (PLN-1), and a reader cannot distinguish +states that differ outside its clearance through the shared vector plane (PLN-2, BRG-5). These +are Goguen and Meseguer's noninterference \citep{goguen1982security} for one store, in the +lattice model of information flow \citep{denning1976lattice}; language-based treatments type the +same property \citep{volpano1996sound,sabelfeld2003language}. + +\paragraph{The universe.} +A sentence is evaluated on its \emph{support}: the nodes of the strata its admitted clauses read, +the nearest units to its texts in the indexed strata, and the citation and causal neighbourhoods +of its anchors. Nothing outside the admitted strata is loaded as a node. + +\section{Theory} + +\begin{definition}[The guest's grant] +Let $\operatorname{cl}(S) = S \cup \{c \ne \str{exhaust} : \operatorname{parent}(c) \in S\}$. The +guest's grant is the list of two planes +\begin{align*} + p_1 &= \bigl(\operatorname{cl}\{\str{dialogue}, \str{reference}, \str{curated}, + \str{observed}\},\ \{F, D\},\ (\text{projection events}, \top),\ \text{read}\bigr),\\ + p_2 &= \bigl(\operatorname{cl}\{\str{reference}, \str{dialogue}\},\ \{F, C\},\ + (\text{commits}, \top),\ \text{read}\bigr), +\end{align*} +where \emph{read} is the least authority: no propose, no write bit, no world reach. It is the +local model's first two planes over these strata, without the third plane, which reads the +notes' version chains. +\end{definition} + +\begin{theorem}[SCO-9]\label{thm:guest} +Let $M = \{\str{mirror}, \str{mirror\_authored}, \str{interpreted}\}$. +\begin{enumerate} + \item The grant is one the code accepts: no plane names the foundation, and none reaches the + world (\lean{guest\_grantOk}). + \item $\Sigma_{p} \cap M = \emptyset$ for both planes (\lean{guest\_reads\_no\_note}). + \item Every scope $r$ with $\Sigma_r \cap M \ne \emptyset$ lies under no plane, so a clause that + requires it is refused (\lean{guest\_refuses\_note}). + \item No command is admitted (\lean{guest\_admits\_no\_command}). + \item No sentence under \texttt{assume} is admitted (\lean{Sentence.guest\_no\_assume}). +\end{enumerate} +\end{theorem} + +\begin{proof}[Proof sketch] +(1) and (2) are finite checks, closed by evaluation (\lean{decide}); for (2) the closure adds +\str{dialogue\_transcript}, \str{dialogue\_artifact} and \str{reference\_repo}, whose parents are +in the set, and nothing whose parent is \str{mirror}. (3) $r \sqsubseteq p$ requires +$\Sigma_r \subseteq \Sigma_p$, which (2) contradicts. (4) A command requires the write bit, and a +grant whose planes all lack it admits none (ING-1, \lean{readonly\_admits\_no\_command}). (5) A +clause under \texttt{assume} requires the overlay stratum, so an admitting grant names it on some +plane (QSA-5, \lean{admissible\_assume\_overlay}); neither plane does. Lean 4 checks each statement +\citep{demoura2021lean4,mathlib2020}; the store's comparator judges the five against their +statements in \texttt{formal/Spec}, and six independent kernels replay the library. +\end{proof} + +The theorem bounds what a sentence may \emph{require}. What it may \emph{return} depends also on +the data in the admitted strata. + +\begin{definition}[Views and noninterference] +For a grant $g$ and a store state $\sigma$, let $\operatorname{ans}_g(s, \sigma)$ be the answer to +sentence $s$: its hits, notes and plan, or its refusal. Two states are $g$-equivalent, +$\sigma \sim_g \sigma'$, when they hold the same rows in every stratum $g$ names, and the same +edges among nodes of those strata. The grant is noninterfering when +$\sigma \sim_g \sigma' \Rightarrow \operatorname{ans}_g(s, \sigma) = \operatorname{ans}_g(s, +\sigma')$ for every $s$. +\end{definition} + +A causal edge $(t, v)$ joins a transcript turn $t$ to a file $v$ the turn's action wrote. When $v$ +is a note, the edge is a fact of the transcript stratum that names a node of the mirror. In the +lattice model its label is the join $\ell(t) \sqcup \ell(v) = \str{dialogue\_transcript} \sqcup +\str{mirror}$, which the guest's clearance does not dominate. Two $g$-equivalent states may differ +in such edges, so an answer that shows them, or counts them, interferes. + +\section{Concepts and intuition} + +Admission is a check on requirements. A clause over the notes is refused, and the universe never +loads a note as a node. The leak was not a note: it was a \emph{reference} to a note held by a row +the guest may read. The causal store records, for every action of an agent session, the path it +produced. A session that edited a note recorded the note's path, and the path carries the note's +name. The store already named such an endpoint, when the sentence did not read the mirror, as a +node of the transcript stratum: honest for the local model, whose grant reads the mirror anyway, +and a leak for any grant that does not. \texttt{witness} of the edge returned the same path. + +The repair keys on the grant rather than the sentence. A grant's strata are the union of its +planes'. When they hold no stratum of the mirror, the reader may not see a mirror node named, and +an edge it may not see is withheld whole: not named by a placeholder, not counted, its +content-addressed id withheld with it. A placeholder per edge or a count would be a function of the +excluded data. The answer still says that edges are withheld, in one sentence whose words do not +depend on whether any were. + +Which edges the reader may see is decided by an allow list. The first repair was a deny rule: it +withheld an edge whose endpoint lay under the vault's path, compared as text. A red team found +five spellings of a note's path that passed it: the vault's directory in another letter case and +the path in another Unicode normal form, each the same file on a file system that folds them; a +relative path; a \texttt{file://} URI; and the bare file name that the event projector keeps for a +file written under a \texttt{docs/design-notes} folder. A deny rule has to know every spelling of +a vault path, and an allow list only what may be shown. The reader is shown a causal edge only +when it ends at a commit, named by its hex sha, or at a file git tracks in the checkout at HEAD; +the vault is asked first, with every component folded for case and normal form, for the path as +written, normalized and resolved. A file system knows a note by names that check does not fold, +a hard link or its path through another mount of the volume; such a name is judged as any path +is, and shown only when it is a file git tracks in a checkout of the repository. What cannot be +judged, because git cannot be asked or the endpoint cannot be read, is withheld. The cost falls +on endpoints the rule cannot tie to a tracked file: a path outside the repository, a relative +path (even one that names a tracked file), a tracked file's path in another letter case or under +another clone, and an untracked or deleted file are no longer named to this reader. + +\section{Implementation} + +\Cref{alg:hide} is the change to the universe builder. The grant's strata are computed once per +sentence by the surface; a grant that reads the mirror builds the same universe as before, by the +same call. + +\begin{algorithm} +\caption{Withholding the mirror from a reader whose grant does not name it.}\label{alg:hide} +\begin{algorithmic}[1] +\Require a plan $P$, the reader's grant $g$, the stores +\State $\mathit{hide} \gets \operatorname{strata}(g) \cap \{\str{mirror}, \str{mirror\_authored}\} = \emptyset$ +\Function{Named}{$v$} \Comment{a causal endpoint; once per endpoint, false on any failure} + \If{$v$ is a commit} \Return $v$ is a hex sha \EndIf + \If{$v$ is the vault or under it, folded for case and normal form} \Return false \EndIf + \State $r \gets$ the repo path of $v$: a doc id's one file, or an absolute path under a checkout + \State \Return $r$ exists $\wedge$ git tracks $r$ at HEAD +\EndFunction +\Function{Citable}{$v$} + \State \Return $v$ is a plain repo-relative path $\wedge$ no checkout's $v$ is in the vault +\EndFunction +\If{not $\mathit{hide}$} build the note graph \Comment{the dialogue otherwise loads under its own clearance} +\EndIf +\State index the causal edges $(t, v)$ with $\neg\mathit{hide} \vee \Call{Named}{v}$ \Comment{whole edges, ids with them} +\State expand citation neighbours $v$ with $\neg\mathit{hide} \vee \Call{Citable}{v}$ +\State $\operatorname{witness}(e) \gets \bot$ when $\mathit{hide}$ and $e$ is an edge $(t, v)$ with $\neg\Call{Named}{v}$ or an attestation +\State through a reference edge, $\operatorname{witness}$ chooses among the edges keyed to its commit those with $\neg\mathit{hide} \vee \Call{Named}{v}$ +\If{$\mathit{hide}$ and $P$ walks $C$ or witnesses} add the fixed withholding note \EndIf +\end{algorithmic} +\end{algorithm} + +The role \str{guest} resolves to the grant at the ingress and holds no spool, so a request is +refused when it is compiled and could not be spooled. The surface is the store's MCP server with +\texttt{--role guest}: it seals the core against network egress, as the local model's server +does, and serves \texttt{query} and \texttt{overview}. The overview counts catalog entries of the +classes the grant's strata hold and the curated chunks; the local model's totals of vector rows, +relation edges and versions each count the notes and are not shown. On a store that embeds +nothing it also says so, counts the lexical index's units of the same classes, and names each +repository it lands with the commit it landed and how far the repository has moved since; the +local model's count of every lexical unit counts the notes' too. The \texttt{status} tool is not +served, since it lists the owner's open tasks and running jobs. + +A refusal reaches the guest with its class and a text chosen by where it was raised. The surface +compiles the sentence again, with the trace when the call asked for one, since the trace renders +the parse and a sentence can fail to compile with it alone; that reads the sentence and the grant +and no store. If the compiler refuses it, the guest reads the compiler's reason with every quoted +run replaced by its length: the reason holds the asker's words. If it compiles, the refusal was +raised in the run, against the stores, and the guest reads one fixed sentence for its class, +never the reason, which may quote what a store holds. A redaction that pairs quotes by position +does not hide such a quotation reliably: an apostrophe in the reason's own words pairs with the +opening quote of a quoted path and leaves the path in clear. A scope refusal of either kind adds +the strata the grant reads. The server writes its replies to a copy of standard output's file +descriptor and points the descriptor itself at standard error, and a tool runs with Python's +standard output pointed there too, so the protocol stream carries replies only, whatever a library +or a child process writes. The query log, which the owner reads on a terminal, writes a guest's +sentence into one ASCII line, its first 4{,}096 characters, at most 8{,}192 bytes of the line, +and a marker of its length, and prints it with every character that is not printable escaped. + +\section{Evaluation} + +\paragraph{The fixture.} +A store on real stores (the vector plane, the catalog, the version and relation stores, the +attestations, the causal store and the chat log) holds a note whose path, title and body carry a +canary token made at run time, landed by the store's own ingress; an interpreted relation from the +note to an authored dialogue turn; an authored and an observed dialogue turn; a transcript turn +whose causal edges point at the note and at a repository file; a paper; a code atom; and a +citation graph at one cut. The test is \texttt{tests/adversarial/test\_guest\_leaks.py}. + +\paragraph{The battery.} +It has 71 sentences: every verb (\texttt{near} with and without \texttt{over}, \texttt{diffuse}, +\texttt{reach} over $F$, $C$ and $D$ in both directions, \texttt{relate}, \texttt{trace}, +\texttt{walk} with paths over $S$, $F$, $C$ and $D$, \texttt{witness} of the note's edge, of the +file's edge and of the note's landing, \texttt{read}), \texttt{assume}, the adjectives and +connectives (\texttt{within}, \texttt{over}, \texttt{as of}, \texttt{top}, \texttt{atleast}, +\texttt{far}, \texttt{not}, \texttt{and}, \texttt{or}, \texttt{minus}, \texttt{then}) and four +requests. Twenty name the note by its path or title. Each is asked through the MCP surface with +and without the trace. + +\begin{table}[h] +\centering +\begin{tabular}{lrr} +\toprule +& before the repair & after \\ +\midrule +sentences admitted and answered & 34 & 30 \\ +admitted, no hits & 3 & 7 \\ +refused (31 scope, 2 lookup, 1 error from the script checker) & 34 & 34 \\ +sentences whose output carries the canary & 5 & 0 \\ +\bottomrule +\end{tabular} +\caption{The guest's battery on the fixture store, without the trace (with it, the counts are the +same). ``Before'' is the same code with the withholding switched off. The five leaks: +\texttt{reach C} and \texttt{walk \dots\ via C} from the turn, over strata that hold the +transcript (four sentences), and \texttt{witness} of the note's edge. The four sentences that +move from answered to no hits are the two witnesses of the note's edge and landing, and the two +whose only hit was the note's path.}\label{tab:battery} +\end{table} + +\paragraph{The spellings.} +The fixture stands under a directory whose name has two Unicode normal forms. To it the test adds +nine causal edges from the turn, each holding the canary: the note's path with the vault's +directory upper-cased, the path in its other normal form, two relative paths, a \texttt{file://} +URI, the file name the projector keeps for a vault file under \texttt{docs/design-notes}, such a +name that is a glob's pattern for a tracked finding, an untracked path in the checkout and a path +outside the repository; and four citations from a repository file to the note's path and three +other spellings of it. The guest is asked the battery, a \texttt{witness} of each new edge and a +\texttt{reach C} back from each new endpoint, with and without the trace, and the overview, before +the edges are added and after: 181 outputs. Unit tests hold the rule at the universe builder over +a scratch git repository, and others hold the refusal texts, the query log and the protocol +stream. + +\paragraph{Results.} +After the repair no output carries the canary, as a path, a title, a text, a count or a refusal, +and every sentence that names the note is refused (\cref{tab:battery}). The admitted strata +answer: \texttt{near} over all four returns the dialogue turns, the code file and the paper; +\texttt{read} returns a dialogue turn, a transcript turn, the paper and the file; \texttt{reach C} +from the turn over \str{reference} returns the file and not the note. Over a second store whose +note, relation, landing and vault edge differ, all 142 guest outputs and the overview are equal, +byte for byte, once the names the asker typed are normalized. As a control, the local model asked +the same 71 sentences receives the canary in 31 answers, through \texttt{near}, +\texttt{reach C}, \texttt{witness}, \texttt{relate} and \texttt{read} among others, so the battery +reaches the channels it is meant to close. With the nine edges and four citations added, the 181 +outputs are those before, byte for byte, no output of the battery carries the canary, and +\texttt{witness} of each new edge answers nothing; the local model is shown all thirteen. A +store's error whose reason quotes a path holding an apostrophe, which the redaction leaves in +clear, reaches the guest as its class and that class's sentence, and the path is on neither the +stream nor standard error. The default server keeps the local model's tool table and +instructions, and the store's deterministic test tier passes (3{,}699 tests). The commands are in +the repository: \texttt{uv run pytest} over \texttt{tests/adversarial/test\_guest\_leaks.py}, +\texttt{tests/adversarial/test\_guest\_lite.py} and +\texttt{tests/unit/test\_sentence\_universe\_withheld.py}, and \texttt{sh formal/check.sh}. + +\paragraph{A store that embeds nothing.} +The guest is meant to serve an external coding agent, and the store's code instance embeds +nothing: every item lands with its lexical units and no vector, a repository's files as items of +the reference stratum, and \texttt{near} ranks by BM25 \citep{robertson2009bm25} over one index. +A store of that profile can hold a vault, whose notes' units then share the index with the +code's and the dialogue's, so a ranking whose unit count, mean length or document frequencies +were read over the whole index would be a function of the notes. They are read over the classes +a ranking asks for, and each lexical path of the universe asks for classes the grant reads. A +second fixture embeds nothing: the note lands through the ingress, a scratch repository's three +files through its repository source, and the dialogue turns and the paper with lexical units +alone. Asked the 71 sentences and eleven of the code source's own (a lexical \texttt{near} over +the reference stratum, \texttt{read} of a landed file, \texttt{trace}, a file the repository does +not have), with and without the trace, the guest's 164 outputs carry no canary. Over a second +such store whose note's body says none of the queried words, in four terms where the first's +runs to over three hundred, and which is alike in all else the guest reads, its repository's +landing dated to the same second, they and the overview are identical, while the local model +ranks the first note first and counts more units in the first store. Three mutations checked by +hand each fail the test: a unit count and mean length read over every class, a reference seed +that searches every class, and an overview that counts every unit. The launcher, spawned over an +overlay made from the code instance's, answers \texttt{overview}, a lexical \texttt{near}, a +\texttt{read} and three refusals in their fixed words, one reply per request on standard output. + +\section{Limitations}\label{sec:limits} + +The grant bounds strata, not what admitted text says. A chat turn, a capture or an assistant reply +that quoted a note is a dialogue row, and the guest reads it; keeping such quotations out needs a +narrower grant (reference and curated alone) or a filtered dialogue. The withholding is code, +held by tests, not by a theorem: the Lean model states what a grant admits, not what the universe +builder returns. The isolation is in the process: the guest's server opens the stores under the +account it runs as, and an untrusted party should also be separated by the operating system. +Response times may depend on the size of the excluded strata; a lexical ranking, for one, reads a +term's postings in every class before it keeps its own. So may a time the guest reads: the +overview shows when each repository landed, and a landing of the notes queued before it in the +daemon's one queue delays it. The query log grows by a line for every sentence a guest asks, at +most some 12~KB each, and nothing bounds its size; nor is a sentence's size capped, though a +string literal is read in memory in proportion to its text. Both bounds are left to the owner. +The reference stratum holds what a store lands in it: a repository source is read through git at +its ref, and a repository whose tree tracked a vault's files would land the notes as code, which +the guest reads. The configuration does not refuse such a repository; the code instance declares +only the store's own. + +Three limits follow from the allow list and the process. First, the event projector records a +file written under a \texttt{docs/design-notes}, \texttt{docs/findings} or +\texttt{docs/build-plans} folder by a bare doc id, with no path, wherever the folder is. A vault +file there is shown only when its id resolves to exactly one tracked document of the repository, +and then as that document: the guest learns that a turn wrote a file of that name, not where. The +exact fix keeps the path at projection; it belongs in the projector and is not in this change. +Second, a citation neighbour is not checked against the tree at HEAD, since the citation graph is +read at other cuts; its refs are repository-relative paths projected from the repository's +history, so they denote its files. Third, the client that spawns the server also reads its +standard error, where a refusal's traceback and whatever a library or a child process writes go +unfiltered. + +\section{Future work} + +The cleaner repair labels each edge at the store with the join of its endpoints' strata, so that +every reader, not only the universe builder, applies the rule; the noninterference statement could +then be proved over a model of the stores, as PLN-2 is for the vector plane. An event projector +that keeps a written file's path would let a doc's id never stand for a vault file. A dialogue +filtered of turns that quote notes would let a guest read conversations without trusting their +contents. + +\section{Conclusion} + +A second principal for an external agent is a small grant: two planes, read-only, over four +strata. Its refusals are a finite check and are proved. The adversarial battery found that the +check was not enough, because an admitted row named an excluded node, and a red team found that a +test against the vault's path was not enough either, because a path has many spellings. Showing +only what an allow list names and withholding every other reference whole makes the guest's +answers independent of the notes, within the limits of \cref{sec:limits}, and a two-store test +and a test of the spellings hold that in place. + +\bibliographystyle{plainnat} +\bibliography{refs} +\end{document} diff --git a/papers/2026-11-09-guest-principal/refs.bib b/papers/2026-11-09-guest-principal/refs.bib new file mode 100644 index 00000000..39a981d1 --- /dev/null +++ b/papers/2026-11-09-guest-principal/refs.bib @@ -0,0 +1,100 @@ +@inproceedings{goguen1982security, + author = {Goguen, Joseph A. and Meseguer, Jos{\'e}}, + title = {Security Policies and Security Models}, + booktitle = {Proceedings of the 1982 IEEE Symposium on Security and Privacy}, + pages = {11--20}, + year = {1982} +} + +@article{denning1976lattice, + author = {Denning, Dorothy E.}, + title = {A Lattice Model of Secure Information Flow}, + journal = {Communications of the ACM}, + volume = {19}, + number = {5}, + pages = {236--243}, + year = {1976} +} + +@article{dennis1966semantics, + author = {Dennis, Jack B. and Van Horn, Earl C.}, + title = {Programming Semantics for Multiprogrammed Computations}, + journal = {Communications of the ACM}, + volume = {9}, + number = {3}, + pages = {143--155}, + year = {1966} +} + +@article{saltzer1975protection, + author = {Saltzer, Jerome H. and Schroeder, Michael D.}, + title = {The Protection of Information in Computer Systems}, + journal = {Proceedings of the IEEE}, + volume = {63}, + number = {9}, + pages = {1278--1308}, + year = {1975} +} + +@article{sabelfeld2003language, + author = {Sabelfeld, Andrei and Myers, Andrew C.}, + title = {Language-Based Information-Flow Security}, + journal = {IEEE Journal on Selected Areas in Communications}, + volume = {21}, + number = {1}, + pages = {5--19}, + year = {2003} +} + +@article{volpano1996sound, + author = {Volpano, Dennis and Irvine, Cynthia and Smith, Geoffrey}, + title = {A Sound Type System for Secure Flow Analysis}, + journal = {Journal of Computer Security}, + volume = {4}, + number = {2--3}, + pages = {167--187}, + year = {1996} +} + +@inproceedings{demoura2021lean4, + author = {de Moura, Leonardo and Ullrich, Sebastian}, + title = {The {Lean} 4 Theorem Prover and Programming Language}, + booktitle = {Automated Deduction -- {CADE} 28}, + series = {Lecture Notes in Computer Science}, + volume = {12699}, + pages = {625--635}, + publisher = {Springer}, + year = {2021} +} + +@inproceedings{mathlib2020, + author = {{The mathlib Community}}, + title = {The {Lean} Mathematical Library}, + booktitle = {Proceedings of the 9th ACM SIGPLAN International Conference on Certified Programs and Proofs}, + pages = {367--381}, + year = {2020} +} + +@misc{mcp2025, + key = {Model Context Protocol}, + title = {Model Context Protocol Specification, version 2025-06-18}, + howpublished = {\url{https://modelcontextprotocol.io/specification/2025-06-18}}, + year = {2025} +} + +@misc{palace2026, + author = {Serrano-Calva, Alberto}, + title = {mind-palace}, + howpublished = {\url{https://github.com/ascalva/mind-palace}}, + year = {2026} +} + +@article{robertson2009bm25, + author = {Robertson, Stephen and Zaragoza, Hugo}, + title = {The Probabilistic Relevance Framework: {BM25} and Beyond}, + journal = {Foundations and Trends in Information Retrieval}, + volume = {3}, + number = {4}, + pages = {333--389}, + year = {2009} +} diff --git a/scripts/palace_mcp.py b/scripts/palace_mcp.py index dba82c0b..b02e325c 100644 --- a/scripts/palace_mcp.py +++ b/scripts/palace_mcp.py @@ -1,13 +1,17 @@ #!/usr/bin/env python -"""The Ambassador's MCP server on stdio — spawned by a harness (OpenCode), never a listener. +"""The palace's MCP server on stdio — spawned by a harness (OpenCode), never a listener. uv run --project ~/mind-palace python scripts/palace_mcp.py + uv run --project ~/mind-palace python scripts/palace_mcp.py --role guest uv run --project ~/mind-palace python scripts/palace_mcp.py --manifest > edge/palace_tools.json -Seals the core first (Invariant 1), then speaks MCP over stdin/stdout; see -`agents/ambassador/mcp.py` for the tools and the scoping they enforce. `--manifest` prints the -Open WebUI bridge's tool list instead (`agents.ambassador.handoff.web_manifest`): regenerate the -committed file whenever the tool table changes. +Seals the core first (Invariant 1), then speaks MCP over stdin/stdout, stdout kept for the +protocol (`protocol_stream`); see `agents/ambassador/mcp.py` for the tools and the scoping they +enforce. With no `--role`, or `--role ambassador`, it is the Ambassador's surface; `--role guest` +is an external agent's, read-only under the `GUEST` grant (`query` and `overview`, +dn-guest-principal). `--manifest` prints the Open WebUI bridge's tool list instead +(`agents.ambassador.handoff.web_manifest`): regenerate the committed file whenever the +Ambassador's tool table changes. """ from __future__ import annotations @@ -24,16 +28,36 @@ from core.sealing import seal # noqa: E402 +def role_of(args: list[str]) -> str: + """`--role ` or `--role=`; the Ambassador's when absent, '' when the flag has no + value (refused below).""" + for i, a in enumerate(args): + if a == "--role": + return args[i + 1] if i + 1 < len(args) else "" + if a.startswith("--role="): + return a.removeprefix("--role=") + return "ambassador" + + def main() -> None: if "--manifest" in sys.argv[1:]: # a read of the config and the tool table; no store, no seal from agents.ambassador.handoff import web_manifest print(json.dumps(web_manifest(), ensure_ascii=False, indent=1)) return + role = role_of(sys.argv[1:]) seal() # structural egress guard first (Invariant 1); only loopback model servers are reachable - from agents.ambassador.mcp import serve + from agents.ambassador.mcp import ROLES, Server, protocol_stream, serve - serve() + if role not in ROLES: + sys.exit(f"palace_mcp: --role is one of {', '.join(ROLES)}") + # the replies go to a copy of stdout, and stdout itself to stderr: what anything else in the + # process writes there, a library's C code or a child process, cannot reach the client + stream = protocol_stream() + if role == "ambassador": + serve(stdout=stream) + else: + serve(stdout=stream, server=Server(role)) if __name__ == "__main__": diff --git a/tests/adversarial/test_guest_leaks.py b/tests/adversarial/test_guest_leaks.py new file mode 100644 index 00000000..4d84759f --- /dev/null +++ b/tests/adversarial/test_guest_leaks.py @@ -0,0 +1,837 @@ +"""The guest principal does not leak the owner's notes (dn-guest-principal, SCO-9). + +A palace on real stores (the ingress's fixture palace: the vault, the plane, the catalog, the +versions, the relation edges, the attestations; the causal store and the chatlog beside them) +holds a note with a canary in its path, title and body, landed by the ingress, an interpreted +relation from it to an authored dialogue turn, and items in every stratum the guest reads: an +authored and an observed dialogue turn, a transcript turn whose causal edge points at the note +and a second at a repo file, a curated paper, a code atom, and the citation graph at a cut. As +the guest, over its MCP surface, every verb of the sentence algebra is asked, the ones that name +the note included, with every adjective and connective, `assume` and every request, then +`overview` and `status`. No output carries the canary: no path, title, text, count or refusal. +The admitted strata answer. And the guest's outputs are the same, byte for byte once the names +the asker typed are normalized, over a second palace whose note, relation and vault edge differ +(noninterference). The Ambassador, asked the same, sees the canary: the fixture is live, and the +withholding is what closes the causal and witness channels. + +The causal and citation stores may also hold the note's path as a file system or an action log +spells it (another letter case, another Unicode normal form, a relative path, a URI, a bare file +name, a file name that is a glob's pattern), and paths that are not the repo's. Adding such edges +to a palace changes no guest output, and `witness` of each answers nothing; the Ambassador sees +every one.""" + +from __future__ import annotations + +import hashlib +import io +import json +import os +import subprocess +import sys +import unicodedata +from dataclasses import dataclass, replace +from pathlib import Path +from typing import Any + +import pytest + +from core.chat_events import _classify_file_write +from core.ingest import ingress +from core.integrator import _WRITE_KIND_TO_DST +from core.kernel.complex_types import EdgeSign +from core.kernel.config import REPO_ROOT +from core.kernel.provenance import Provenance +from core.kernel.scope import Privilege, Stratum, StratumScope, WorldReach +from core.query import AMBASSADOR, GUEST, OPERATOR, QueryEngine +from core.sentence import compile_sentence +from core.sentence.surface import SENTENCE_BYTES, SENTENCE_MAX, QueryLog, run_query +from core.sentence.types import IllScopedSentence +from core.sentence.universe import _doc_path +from core.stores.causal_edges import CausalEdge, open_causal_edge_store +from core.stores.chatlog import ChatUtterance, open_chatlog_store +from core.stores.vectorstore import LAYER_CODE_AST +from tests.fixtures.embedding import DIM, FakeEmbedder +from tests.fixtures.ingress import palace_at, write_file +from tests.unit.test_sentence_universe import _Edge, _Refs + +EMB = FakeEmbedder() +AUTHORED = "dialogue/tea/2026-11-09T10:00 (user)" +OBSERVED = "dialogue/tea/2026-11-09T10:01 (assistant)" +TURN = "transcript/s1/1" +PAPER = "reference:orchard-paper" +CODE = "core/query.py" +NOT_THE_MIRROR = {Stratum.MIRROR, Stratum.MIRROR_AUTHORED, Stratum.INTERPRETED} + + +def _canary(seed: str) -> str: + """A token found in no file: made at run time, the same length for every seed.""" + return "cnry" + hashlib.sha256(seed.encode()).hexdigest()[:16] + + +def _eid(*parts: object) -> str: + return hashlib.sha256("|".join(map(str, parts)).encode()).hexdigest()[:32] + + +@dataclass +class Fixture: + canary: str + engine: QueryEngine + root: Path + note: str # the note's path, under the vault + title: str # the note's title + vault_edge: str # the causal edge whose endpoint is the note + repo_edge: str # the causal edge whose endpoint is a repo file + attestation: str # the attestation of the note's landing + + +def _dialogue(p: Any, path: str, text: str, prov: Provenance) -> str: + digest, _ = p.stores.raw.add_text(text) + p.stores.catalog.record(path, digest, text[:24], provenance=prov) + p.stores.plane.add([{"source_path": path, "digest": digest, "provenance": prov.value, + "title": text[:24], "chunk_index": 0, "text": text, "layer": "prose", + "vector": EMB.embed_query(text)}]) + return digest + + +def _edges(f: Fixture) -> list[CausalEdge]: + """The two proven edges of session s1: the turn's action wrote the note and a repo file (the + projector stamps an action with the next utterance's index, so turn 1's actions carry + witness_turn 2).""" + return [CausalEdge(f.vault_edge, "s1", 1, "C", "file", f.note, "wd1", 2), + CausalEdge(f.repo_edge, "s1", 2, "C", "file", f"{REPO_ROOT}/{CODE}", "wd1", 2)] + + +def _palace(base: Path, canary: str) -> Fixture: + p = palace_at(base, "p") + root = p.root + write_file(p.vault, f"{canary}.md", + f"# {canary} title\n\nThe {canary} body: a walnut orchard, a private plan.\n") + p.run("do sync_vault") + (entry,) = p.stores.catalog.active_entries() + assert canary in entry.source_path and canary in entry.title # the canary is everywhere + assert canary in p.stores.raw.get(entry.digest).decode() + authored = _dialogue(p, AUTHORED, "walnut orchard notes from the chat", + Provenance.AUTHORED_DIALOGUE) + _dialogue(p, OBSERVED, "a summary of the orchard plan", Provenance.OBSERVED) + # an interpreted relation from the note to the authored turn (a `link`'s product) + assert p.stores.edges is not None + p.stores.edges.add(entry.digest, authored, sign=EdgeSign.SUPPORT, rel_type="supports") + (attestation,) = [a.id for a in p.att.all() if entry.digest in a.output_hashes] + + cfg = replace(p.cfg, embedding=replace(p.cfg.embedding, dim=DIM), paths=replace( + p.cfg.paths, raw_store=root / "raw", vector_store=root / "vectors", + derived_store=root / "derived.sqlite", vault_catalog=root / "catalog.sqlite", + attestation_store=root / "att.sqlite", curated_store=root / "curated.lance", + telemetry_db=root / "telemetry.sqlite")) + engine = QueryEngine(cfg) + engine._cache.update({ + "vectors": p.stores.plane, "catalog": p.stores.catalog, "embedder": p.stores.embedder, + "edges": p.stores.edges, "versions": p.stores.versions, "attestations": p.att, + "references": _Refs([_Edge("docs/guide.md", CODE, "c1"), + _Edge(CODE, "core/kernel/scope.py", "c1")]), + }) + # a code atom and a paper, in the indexes `near … over reference` and `over curated` read + p.stores.plane.add([{"id": "atom-guest", "digest": "dcode", "title": CODE, + "source_path": CODE, "chunk_index": 0, "provenance": "code", + "text": "GUEST = Grant(...)", "layer": LAYER_CODE_AST, + "qualname": "GUEST", "line_start": 1, "line_end": 9, "current": True, + "vector": EMB.embed_query("walnut orchard code")}]) + engine._get("curated").add([{"source_path": PAPER, "digest": "dpaper", + "provenance": "curated", "title": "Orchard irrigation", + "chunk_index": 0, "text": "irrigation of walnut orchards", + "layer": "prose", + "vector": EMB.embed_query("irrigation of walnut orchards")}]) + # a transcript turn whose action wrote the note and a repo file + note = entry.source_path + f = Fixture(canary, engine, root, note, entry.title, _eid("s1", 1, note), _eid("s1", 2, CODE), + attestation) + open_causal_edge_store(cfg).replace_session("s1", _edges(f), "wd1") + open_chatlog_store(cfg).add_batch([ChatUtterance("s1", 1, "owner", "please write the plan", + "wd1")]) + return f + + +@pytest.fixture +def base(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path: + """Where a test's palaces stand, the citation graph's cut and the query log fixed.""" + import core.reference_view as rv + from core.sentence import surface + + monkeypatch.setattr(rv, "_resolve_default_commit", lambda cfg: "c1") + monkeypatch.setattr(surface, "default_log", lambda: QueryLog(tmp_path / "q.jsonl")) + return tmp_path + + +@pytest.fixture +def palaces(base: Path) -> tuple[Fixture, Fixture]: + return _palace(base / "a", _canary("a")), _palace(base / "b", _canary("b")) + + +@pytest.fixture +def spelled(base: Path) -> Fixture: + """A palace under a directory whose name has two Unicode normal forms, so its note's path + has a second spelling there.""" + return _palace(base / unicodedata.normalize("NFC", "w\u00e9"), _canary("s")) + + +# ── the surfaces ─────────────────────────────────────────────────────────────────────────────── + + +def _server(f: Fixture, role: str) -> Any: + from agents.ambassador import mcp + + server = mcp.Server(role) + tools: Any = mcp.Guest() if role == "guest" else mcp.Ambassador() + tools.engine = f.engine + server._amb = tools + return server + + +def _call(server: Any, tool: str, **arguments: Any) -> tuple[bool, str]: + reply = server.handle({"jsonrpc": "2.0", "id": 1, "method": "tools/call", + "params": {"name": tool, "arguments": arguments}}) + if "error" in reply: + return True, json.dumps(reply["error"]) + return reply["result"]["isError"], reply["result"]["content"][0]["text"] + + +class _Failing: + """A store whose every read raises `error`.""" + + def __init__(self, error: Exception) -> None: + self.error = error + + def __getattr__(self, name: str) -> Any: + def fail(*args: Any, **kwargs: Any) -> Any: + raise self.error + + return fail + + +def _battery(f: Fixture) -> list[tuple[str, str]]: + """Every verb and connective, as (sentence, expected): `answered` (admitted, with hits), + `admitted` (with or without hits), `empty` (admitted, no hits) or `refused`. Every sentence + that names the note is refused; the admitted ones never carry the canary in their own words, + so an answer's echo of its sentence cannot carry it either.""" + n, t = f.note, f.title + over = "over dialogue reference curated observed" + return [ + # near, with and without `over` + ('near "walnut orchard"', "refused"), + (f'near "walnut orchard" {over}', "answered"), + ('top 3 near "walnut orchard" over dialogue', "answered"), + ('near "walnut orchard" over observed', "answered"), + ('near "walnut orchard" over mirror', "refused"), + ('near "walnut orchard" over mirror_authored', "refused"), + ('near "walnut orchard" over interpreted', "refused"), + # diffuse + (f'diffuse S from "{AUTHORED}" over dialogue', "answered"), + (f'diffuse S from "{PAPER}" over curated', "admitted"), + (f'diffuse S from "{n}"', "refused"), + (f'diffuse S from "{n}" over dialogue', "refused"), + (f'diffuse S from "{t}" over dialogue', "refused"), + (f'diffuse F from "{CODE}"', "answered"), + # reach F, C and D, forward and back + (f'reach F from "{CODE}"', "answered"), + (f'reach F from "{CODE}" forward', "answered"), + (f'reach F from "{CODE}" depth 2 back', "answered"), + (f'reach F from "{n}"', "refused"), + (f'reach C from "{TURN}" over dialogue', "admitted"), # a mask: no file + (f'reach C from "{TURN}" over reference', "answered"), + (f'reach C from "{TURN}" forward over reference', "answered"), + (f'reach C from "{TURN}" depth 2 over dialogue_transcript reference', "answered"), + (f'reach C from "{TURN}"', "refused"), + (f'reach C from "{CODE}" back over dialogue', "answered"), + (f'reach C from "{n}" back over dialogue', "refused"), + (f'reach C from "{t}" back over dialogue', "refused"), + (f'reach D from "{n}"', "refused"), + (f'reach D from "{n}" back', "refused"), + (f'reach D from "{AUTHORED}" over dialogue', "refused"), + # relate, trace + (f'relate "{n}"', "refused"), + (f'relate "{AUTHORED}"', "refused"), + (f'trace "{n}"', "refused"), + (f'trace "{AUTHORED}" back', "refused"), + # walk, a regular expression over S, F, D, C + (f'walk from "{TURN}" via C over dialogue', "admitted"), + (f'walk from "{TURN}" via C over dialogue reference', "answered"), + (f'walk from "{TURN}" via CF over reference dialogue_transcript', "answered"), + (f'walk from "{TURN}" to "{CODE}" via C over reference', "answered"), + (f'walk from "{CODE}" via F+', "answered"), + (f'walk from "{AUTHORED}" via S over dialogue', "answered"), + (f'walk from "{TURN}" via C', "refused"), + (f'walk from "{TURN}" via CD over dialogue', "refused"), + (f'walk from "{n}" via S', "refused"), + (f'walk from "{TURN}" to "{n}" via C over dialogue', "refused"), + # witness: the vault edge and the note's landing are no record to the guest + (f'witness "{f.vault_edge}"', "empty"), + (f'witness "{f.repo_edge}"', "answered"), + (f'witness "{f.attestation}"', "empty"), + # read + (f'read "{n}"', "refused"), + (f'read "{t}"', "refused"), + (f'read "~/{Path(n).name}"', "refused"), + (f'read "{AUTHORED}"', "answered"), + (f'read "{OBSERVED}"', "answered"), + (f'read "{TURN}"', "answered"), + (f'read "{PAPER}"', "answered"), + (f'read "{CODE}"', "answered"), + # assume: no overlay + (f'assume S "{AUTHORED}" "{OBSERVED}" +0.5 in near "walnut" over dialogue', "refused"), + (f'assume sever F "docs/guide.md" "{CODE}" in reach F from "{CODE}"', "refused"), + (f'assume contradict "{n}" "{AUTHORED}" in near "walnut" over dialogue', "refused"), + # the adjectives and connectives + (f'top 2 near "walnut" over dialogue within reach C from "{TURN}" over dialogue', + "admitted"), + ('far near "walnut" over dialogue', "answered"), + (f'not reach F from "{CODE}"', "admitted"), + ('atleast 0.1 near "walnut" over curated', "answered"), + (f'near "walnut" over dialogue and diffuse S from "{AUTHORED}" over dialogue', + "answered"), + (f'reach F from "{CODE}" then near "walnut" over reference', "admitted"), + (f'top 5 near "walnut" over dialogue minus reach C from "{TURN}" over dialogue', + "answered"), + ('near "walnut" over dialogue or near "walnut" over curated', "answered"), + (f'reach F from "{CODE}" as of "c1"', "answered"), + (f'near "walnut" over dialogue within relate "{n}"', "refused"), + (f'top 3 near "walnut" over dialogue within reach F from "{n}"', "refused"), + # requests: none, whatever they name + ("do dream", "refused"), + ("do sync_vault", "refused"), + (f'do capture(text: "{f.canary}", conversation: "x")', "refused"), + (f'do link(a: "{n}", b: "{AUTHORED}", relation: "supports")', "refused"), + ] + + +def _outcome(error: bool, text: str) -> str: + if error: + return "refused" + return "answered" if json.loads(text).get("hits") else "empty" + + +def _meets(seen: str, expected: str) -> bool: + return seen == expected or (expected == "admitted" and seen != "refused") + + +# ── the grant ────────────────────────────────────────────────────────────────────────────────── + + +def test_the_guest_grant_reads_neither_the_mirror_nor_the_interpreted_stratum() -> None: + """SCO-9, as the code holds it: the closure of the four strata adds their refinements and + nothing of the mirror (SCO-1); no plane proposes, writes or reaches the world, none names the + overlay; the role resolves to it and has no spool.""" + assert StratumScope.of(Stratum.DIALOGUE, Stratum.REFERENCE, Stratum.CURATED, + Stratum.OBSERVED).strata == GUEST.strata == frozenset({ + Stratum.DIALOGUE, Stratum.DIALOGUE_TRANSCRIPT, Stratum.DIALOGUE_ARTIFACT, + Stratum.REFERENCE, Stratum.REFERENCE_REPO, Stratum.CURATED, Stratum.OBSERVED}) + assert not GUEST.strata & (NOT_THE_MIRROR | {Stratum.HYPOTHETICAL, Stratum.EXHAUST}) + for plane in GUEST.scopes: + a = plane.authority + assert (a.privilege, a.store_write, a.world) == (Privilege.READ, 0, WorldReach.NONE) + # the Ambassador's planes without the mirror's version plane: same clocks and fibers + assert [(s.time.clock, s.edges.fibers) for s in GUEST.scopes] == [ + (s.time.clock, s.edges.fibers) for s in AMBASSADOR.scopes[:2]] + assert ingress.grant_for("guest") is GUEST and "guest" not in ingress.roles() + assert AMBASSADOR.strata & NOT_THE_MIRROR and OPERATOR.strata & NOT_THE_MIRROR + + +def test_the_guest_role_is_refused_every_request() -> None: + """ING-1: no plane carries the write bit, so a request compiled for the role is refused, + and the spool knows no such role, so one compiled for another could not be spooled.""" + from core.kernel.config import get_config + from core.sentence.interpret import ScriptError + + for text in ("do dream", "do sync_vault", 'do capture(text: "t")', + 'do { store "x" in "observed" at "dialogue/x" }'): + with pytest.raises((IllScopedSentence, ScriptError)): + compile_sentence(text, ingress.grant_for("guest"), role="guest") + plan = compile_sentence('do capture(text: "t")', ingress.grant_for("ambassador"), + role="ambassador") + with pytest.raises(IllScopedSentence, match="knows no role"): # refused before any spool + ingress.write_request(get_config(), role="guest", plan=plan) + + +# ── the leak battery ─────────────────────────────────────────────────────────────────────────── + + +def test_no_guest_output_carries_the_canary(palaces: tuple[Fixture, Fixture]) -> None: + a, b = palaces + guest = _server(a, "guest") + seen: dict[str, str] = {} + for sentence, _ in _battery(a): + for trace in (False, True): + error, text = _call(guest, "query", sentence=sentence, trace=trace) + assert a.canary not in text and b.canary not in text, (sentence, text) + assert a.note not in text and a.title not in text, sentence + seen[sentence] = _outcome(error, text) + if error: + assert text.startswith("GuestRefusal: "), text + wrong = {s: (seen[s], e) for s, e in _battery(a) if not _meets(seen[s], e)} + assert not wrong, wrong + + +def test_refusals_name_the_fix_and_echo_nothing(palaces: tuple[Fixture, Fixture]) -> None: + from agents.ambassador import mcp + + a, _ = palaces + guest = _server(a, "guest") + error, text = _call(guest, "query", sentence='near "walnut orchard"') + assert error and "scope:" in text and "mirror_authored" in text + assert "`over dialogue reference curated observed`" in text + # refused while it ran (the title is no node of the dialogue): the class and its one + # sentence, which says how a ref is spelled and is the same whatever name was asked for + error, text = _call(guest, "query", sentence=f'diffuse S from "{a.title}" over dialogue') + assert (error, text) == (True, "GuestRefusal: lookup: " + mcp.GUEST_RAN["lookup"]) + assert "transcript//" in text and "not found in the strata" in text + assert _call(guest, "query", + sentence='diffuse S from "no such name" over dialogue') == (True, text) + error, text = _call(guest, "query", sentence=f'read "{a.note}"') + assert error and "scope:" in text and a.note not in text + error, text = _call(guest, "query", sentence=f'do capture(text: "{a.canary}")') + assert error and a.canary not in text and "no write bit for `do`" in text + + +def test_a_refusal_says_the_compilers_reason_or_its_classs_one_sentence( + palaces: tuple[Fixture, Fixture], base: Path, capsys: pytest.CaptureFixture[str]) -> None: + """dn-guest-principal §4. Compiling reads the sentence and the grant and no store, so a + sentence the compiler refuses is told its reason, the asker's quoted words as lengths. A + sentence that compiles and is refused while it runs is told its class and that class's one + sentence, whatever the reason said. A store's error that names a note's path, in a reason + the redaction would pass, reaches the guest as its class and nothing else, on stdout and on + stderr; the owner's query log keeps the reason.""" + from agents.ambassador import mcp + from core.sentence.surface import redact_reason + + a, _ = palaces + guest = _server(a, "guest") + ran = {kind: f"GuestRefusal: {kind}: {said}" + (mcp.GUEST_SCOPE_HINT if kind == "scope" else "") + for kind, said in mcp.GUEST_RAN.items()} + assert set(ran) == {"lookup", "ambiguous", "unsupported", "scope", "sort", "parse", "busy", + "error"} + + # refused by the compiler + for sentence, start in ( + ('nearby "walnut"', "parse: clause: expected a verb"), + ('not near "walnut" over dialogue', "sort: not: regions only"), + (f'near "{a.canary}" over nowhere', 'ambiguous: over: "<7>" is not a stratum'), + ('top 5000 near "walnut" over dialogue', "parse: top 5000: at most 1000"), + (f'walk from "{TURN}" via (C over reference', "parse: via: expected"), + (f'read "{a.note}"', "scope: read: "), + (f'do capture(text: "{a.canary}")', "scope: store in observed: ")): + error, text = _call(guest, "query", sentence=sentence) + assert error and text.startswith("GuestRefusal: " + start), text + assert text not in ran.values() and a.canary not in text + + # refused while it ran: no such node, no such file, no such turn, two cuts that start so, + # no cut at all, a turn the sentence does not read + a.engine._cache["references"].edges.append(_Edge("docs/old.md", CODE, "c0")) + for sentence, kind in ( + (f'diffuse S from "{a.title}" over dialogue', "lookup"), + ('read "docs/no-such-file.md"', "lookup"), + ('reach C from "transcript/s9/9" over dialogue', "lookup"), + (f'reach F from "{CODE}" as of "c"', "ambiguous"), + (f'reach F from "{CODE}" as of "nope"', "unsupported"), + (f'diffuse S from "{TURN}" over curated', "scope")): + for trace in (False, True): + assert _call(guest, "query", sentence=sentence, trace=trace) == (True, ran[kind]), ( + sentence) + + # a store's error whose reason names a path with an apostrophe: the redaction pairs the + # apostrophe with the opening quote and leaves the rest of the path in clear + secret = f"/srv/vault/the owner's {a.canary}.md" + reason = f"unable to open '{secret}'" + assert a.canary in redact_reason(reason) + capsys.readouterr() + plane = a.engine._cache["vectors"] + for raised, kind in ((OSError(reason), "error"), (RuntimeError(reason), "error"), + (KeyError(secret), "lookup"), (IllScopedSentence(reason), "scope")): + a.engine._cache["vectors"] = _Failing(raised) + for trace in (False, True): + assert _call(guest, "query", sentence='near "walnut" over dialogue', + trace=trace) == (True, ran[kind]), kind + a.engine._cache["vectors"] = plane + assert a.canary not in capsys.readouterr().err # nor in the server's own diagnostics + logged = QueryLog(base / "q.jsonl").entries()[-1] + assert (logged.role, logged.refusal) == ("guest", "scope") and a.canary in logged.reason + + # `overview` that fails says its one sentence + a.engine._cache["curated"] = _Failing(OSError(reason)) + assert _call(guest, "overview") == (True, "GuestRefusal: error: " + mcp.GUEST_OVERVIEW_FAILED) + assert a.canary not in capsys.readouterr().err + + +def test_a_sentence_the_compiler_refuses_under_the_trace_alone_reads_its_reason( + palaces: tuple[Fixture, Fixture], monkeypatch: pytest.MonkeyPatch) -> None: + """The trace renders the parse while a sentence compiles, so a sentence nested deep enough + compiles without the trace and fails with it, its rendering past the recursion limit. The + surface compiles a refused sentence again with the trace the call asked for, so that refusal + is the compiler's: the guest reads the compiler's reason, as for any sentence the compiler + refuses, and not the fixed sentence of a refusal raised in the run. Asked without the trace, + the sentence is answered. The rendering's failure is made here for a plain sentence.""" + from agents.ambassador import mcp + from core.sentence.trace import Trace + + a, _ = palaces + guest = _server(a, "guest") + note = Trace.note + + def deep(self: Trace, stage: str, what: str, law: str = "") -> None: + if stage == "parse": # as rendering a parse past the limit fails + raise RecursionError("maximum recursion depth exceeded") + note(self, stage, what, law) + + monkeypatch.setattr(Trace, "note", deep) + sentence = f'reach F from "{CODE}"' + error, text = _call(guest, "query", sentence=sentence) + assert not error and json.loads(text)["hits"] + told = _call(guest, "query", sentence=sentence, trace=True) + assert told == (True, "GuestRefusal: error: maximum recursion depth exceeded") + assert told[1] != "GuestRefusal: error: " + mcp.GUEST_RAN["error"] + + +def test_the_guests_engine_is_built_inside_the_call_that_needs_it( + base: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]) -> None: + """Making the guest's tools opens nothing, and a tool's body raises `GuestRefusal` and + nothing else: a configuration that cannot be read is a refusal from the call that needed + the engine, in that call's fixed words.""" + import core.query + from agents.ambassador import mcp + + def unreadable() -> Any: + raise OSError("cannot read '/srv/notes/the owner's plan.toml'") + + monkeypatch.setattr(core.query, "QueryEngine", unreadable) + server = mcp.Server("guest") + assert isinstance(server.amb, mcp.Guest) and server.amb._engine is None + assert _call(server, "overview") == (True, "GuestRefusal: error: " + mcp.GUEST_OVERVIEW_FAILED) + assert _call(server, "query", sentence='near "walnut" over dialogue') == ( + True, "GuestRefusal: error: " + mcp.GUEST_RAN["error"]) + assert "plan.toml" not in capsys.readouterr().err + + +def test_the_admitted_strata_answer(palaces: tuple[Fixture, Fixture]) -> None: + a, _ = palaces + guest = _server(a, "guest") + + def hits(sentence: str) -> list[dict[str, Any]]: + error, text = _call(guest, "query", sentence=sentence) + assert not error, text + return list(json.loads(text)["hits"]) + + found = hits('top 10 near "walnut orchard" over dialogue reference curated observed') + assert {h["stratum"] for h in found} == {"dialogue", "reference", "curated"} + assert {AUTHORED, OBSERVED, PAPER, CODE} <= {h["ref"] for h in found} + assert "walnut" in hits(f'read "{AUTHORED}"')[0]["text"] + assert hits(f'read "{CODE}"')[0]["stratum"] == "reference" + assert hits(f'read "{PAPER}"')[0]["text"] == "irrigation of walnut orchards" + assert hits(f'read "{TURN}"')[0]["text"] == "please write the plan" + assert {h["ref"] for h in hits(f'reach F from "{CODE}" back')} >= {"docs/guide.md"} + # the turn's other action, a repo file, stays visible; the note's is withheld whole + (end,) = hits(f'reach C from "{TURN}" over reference') + assert end["ref"] == CODE and end["detail"]["witness"] == a.repo_edge + assert hits(f'witness "{a.repo_edge}"')[0]["detail"]["transcript"] == TURN + error, text = _call(guest, "query", sentence=f'reach C from "{TURN}" over reference') + assert "withheld: the grant names no stratum of the mirror" in text + + +def test_the_guest_cannot_tell_two_palaces_apart(palaces: tuple[Fixture, Fixture]) -> None: + """Noninterference: the palaces differ in the note (path, title, body), its relation, its + landing and the vault edge, and in nothing a guest reads. Every output is the same once the + names each asker typed are put back to one placeholder.""" + a, b = palaces + + def norm(f: Fixture, text: str) -> str: + for name, mark in ((f.note, ""), (f.title, ""), (f.canary, "<canary>"), + (f.vault_edge, "<edge>"), (f.attestation, "<att>"), + (str(f.root), "<root>")): + text = text.replace(name, mark) + return text + + ga, gb = _server(a, "guest"), _server(b, "guest") + for (sa, _), (sb, _) in zip(_battery(a), _battery(b), strict=True): + for trace in (False, True): + ea, ta = _call(ga, "query", sentence=sa, trace=trace) + eb, tb = _call(gb, "query", sentence=sb, trace=trace) + assert (ea, norm(a, ta)) == (eb, norm(b, tb)), sa + assert _call(ga, "overview") == _call(gb, "overview") + + +# ── the note under other spellings, and endpoints that are not the repo's ────────────────────── + + +def _spellings(f: Fixture) -> dict[str, tuple[str, str]]: + """Causal endpoints a guest must not see named, as (dst_type, dst): the note's path as a + file system may treat it or an action log record it, a path in the checkout that git does + not track, and a path outside the repo. Each holds the canary.""" + vault = Path(str(f.engine.config.ingestion.vault.path)) + name = Path(f.note).name + # a vault file under a `docs/design-notes/` folder: the projector keeps its file name alone + kind, doc = _classify_file_write(str(vault / "docs" / "design-notes" / name)) + # and one there whose name is a glob's pattern for one of the repo's findings: looked up as + # a pattern the name is that finding, a file git tracks + finding = min((Path(REPO_ROOT) / "docs" / "findings").glob("finding-*.md")).stem + _, pattern = _classify_file_write(str( + vault / "docs" / "design-notes" / f"{finding[:8]}[{f.canary}{finding[8]}]{finding[9:]}.md")) + assert _doc_path(pattern) == f"docs/findings/{finding}.md" + out = { + "case": ("file", f.note.replace(str(vault), str(vault.parent / vault.name.upper()))), + "nfd": ("file", unicodedata.normalize("NFD", f.note)), + "relative": ("file", os.path.relpath(f.note)), # from this directory + "relative, elsewhere": ("file", f"{vault.parent.name}/{vault.name}/{name}"), + "uri": ("file", f"file://{f.note}"), + "doc": (_WRITE_KIND_TO_DST[kind], doc), + "doc, a pattern": (_WRITE_KIND_TO_DST[kind], pattern), + "untracked": ("file", f"{REPO_ROOT}/data/{f.canary}-untracked.md"), + "outside": ("file", str(f.root.parent / "elsewhere" / f"{f.canary}-outside.txt")), + } + assert out["doc"] == ("doc", name) and len({dst for _, dst in out.values()} | {f.note}) == 10 + assert all(f.canary in dst for _, dst in out.values()) + return out + + +def _answers(server: Any, sentences: list[str]) -> list[tuple[bool, str]]: + """Each sentence asked without and with its trace, then the overview.""" + asked = [_call(server, "query", sentence=s, trace=t) for s in sentences for t in (False, True)] + return [*asked, _call(server, "overview")] + + +def test_an_edge_is_shown_only_when_it_ends_at_a_commit_or_a_tracked_file( + spelled: Fixture) -> None: + """The universe's allow list (dn-guest-principal §5). The causal store gains nine edges from + the fixture's turn, and the citation graph four from a repo file to the note's path, as it + is and in three spellings that are no repo-relative path. Asked the battery, each new edge's + id and each new endpoint by its own name, the guest answers what it answered before they + were added, byte for byte; no answer holds the canary; `witness` of each id is empty. The + Ambassador is shown all of them.""" + f = spelled + extra = _spellings(f) + ids = {name: _eid("s1", 10 + k, dst) for k, (name, (_, dst)) in enumerate(extra.items())} + cited = [f.note, extra["case"][1], extra["nfd"][1], f"~/{Path(f.note).name}"] + battery = [s for s, _ in _battery(f)] + probes = [f'witness "{i}"' for i in ids.values()] + [ + f'reach C from "{dst}" back over dialogue' for _, dst in extra.values()] + [ + f'reach F from "{CODE}" depth 2 over reference'] + guest = _server(f, "guest") + before = _answers(guest, battery + probes) + + open_causal_edge_store(f.engine.config).replace_session("s1", _edges(f) + [ + CausalEdge(ids[name], "s1", 10 + k, "C", kind, dst, "wd1", 2) + for k, (name, (kind, dst)) in enumerate(extra.items())], "wd1") + f.engine._cache["references"].edges += [_Edge(CODE, dst, "c1") for dst in cited] + + after = _answers(guest, battery + probes) + assert after == before # noninterference, no name normalized + for _, text in after[:2 * len(battery)]: # the battery, each sentence twice + assert f.canary not in text, text # every new endpoint holds it + for name, edge in ids.items(): + assert _outcome(*_call(guest, "query", sentence=f'witness "{edge}"')) == "empty", name + (end,) = json.loads(_call(guest, "query", + sentence=f'reach C from "{TURN}" over dialogue reference')[1])["hits"] + assert end["ref"] == CODE and end["detail"]["witness"] == f.repo_edge + + # the control: the edges are in the stores, and a grant that reads the mirror is shown them + amb = _server(f, "ambassador") + for name, (_, dst) in extra.items(): + error, text = _call(amb, "query", sentence=f'witness "{ids[name]}"') + assert not error and json.loads(text)["hits"][0]["detail"]["dst"] == dst, name + error, text = _call(amb, "query", sentence=f'reach C from "{TURN}" over dialogue reference') + assert {h["detail"].get("witness") for h in json.loads(text)["hits"]} >= set(ids.values()) + error, text = _call(amb, "query", sentence=f'reach F from "{CODE}"') + assert {h["ref"] for h in json.loads(text)["hits"]} >= set(cited) + + +# ── the query log, which the owner reads on a terminal ───────────────────────────────────────── + + +def test_a_guests_sentence_cannot_break_the_log_or_write_into_its_reader( + palaces: tuple[Fixture, Fixture], base: Path) -> None: + """dn-guest-principal §8. A guest's sentences enter the instance's query log, and + `palace query --log` prints the failed ones on the owner's terminal. A sentence with a line + separator, with an escape sequence and a forged line, with a bidi override, with a lone + surrogate, one of 300,000 characters and one of 50,000 characters the line writes as + twelve-byte escapes each take one ASCII line of the log, the long ones cut, neither line + longer than the cut allows; the log reads back whole, and both renderings print every such + character escaped.""" + a, _ = palaces + guest = _server(a, "guest") + esc = "\x1b" + hostile = ['near "x\u2028y" over dialogue', + f'near "x" over dialogue\n{esc}[2J{esc}[31mFAKE: the owner approved{esc}[0m', + 'nearby "walnut" \u202eeugolaid revo', + 'near "\ud800" over dialogue', + 'near "' + "A" * 300_000 + '" over mirror', + 'nearby "' + "\U0001f600" * 50_000 + '"'] + for sentence in hostile: + _call(guest, "query", sentence=sentence) + raw = (base / "q.jsonl").read_text(encoding="utf-8") + assert raw.isascii() and len(raw.splitlines()) == len(hostile) == raw.count("\n") + assert len(raw) < len(hostile) * (SENTENCE_MAX + 1000) + assert max(map(len, raw.splitlines())) < SENTENCE_BYTES + 1000 + log = QueryLog(base / "q.jsonl") + entries = log.entries() + assert [e.role for e in entries] == ["guest"] * len(hostile) + assert [e.sentence for e in entries][:4] == hostile[:4] + assert entries[4].sentence.endswith(f"<300019 characters, cut at {SENTENCE_MAX}>") + assert entries[5].sentence.endswith("<50009 characters, cut at 689>") + for flags in ([], ["--json"]): + out = io.StringIO() + assert run_query(["--log", *flags], out=out, log=log) == 0 + text = out.getvalue() + text.encode("utf-8") # no lone surrogate reaches the terminal + assert all(c == "\n" or c.isprintable() for c in text) + assert not any(line.lstrip().startswith("FAKE") for line in text.splitlines()) + assert "FAKE: the owner approved" in text # escaped in place, not dropped + assert json.loads(text)["asked"] == len(hostile) + + +# ── the protocol stream, which the client reads as JSON ──────────────────────────────────────── + + +class _Printing: + """A store that prints a line on every read, as a library under it may, then answers.""" + + def __init__(self, store: Any, line: str) -> None: + self._store, self._line = store, line + + def __getattr__(self, name: str) -> Any: + inner = getattr(self._store, name) + if not callable(inner): + return inner + + def loud(*args: Any, **kwargs: Any) -> Any: + print(self._line) + return inner(*args, **kwargs) + + return loud + + +def test_what_the_guests_tools_print_stays_off_the_protocol_stream( + palaces: tuple[Fixture, Fixture], capfd: pytest.CaptureFixture[str]) -> None: + """The client reads the server's stdout as JSON-RPC, one message per line. A store that + prints while the guest's `query` and `overview` run, and a refusal with its traceback, each + leave one reply per request on the stream the server was given and nothing else. What was + printed is on stderr, and the process's own stdout is not written at all.""" + from agents.ambassador import mcp + + a, _ = palaces + line = "a library's progress line" + a.engine._cache["curated"] = _Printing(a.engine._cache["curated"], line) + asked = [("query", {"sentence": 'near "walnut" over curated'}), + ("overview", {}), + ("query", {"sentence": f'read "{a.note}"'}), + ("status", {})] + requests = "".join(json.dumps({"jsonrpc": "2.0", "id": i, "method": "tools/call", + "params": {"name": tool, "arguments": arguments}}) + "\n" + for i, (tool, arguments) in enumerate(asked, 1)) + stream = io.StringIO() + mcp.serve(io.StringIO(requests), stream, _server(a, "guest")) + out, err = capfd.readouterr() + assert out == "" # nothing reached the real stdout + written = stream.getvalue() + replies = [json.loads(reply) for reply in written.splitlines()] + assert [r["id"] for r in replies] == [1, 2, 3, 4] and written.count("\n") == len(asked) + assert [r["result"]["isError"] for r in replies[:3]] == [False, False, True] + assert "unknown tool" in replies[3]["error"]["message"] + answer = json.loads(replies[0]["result"]["content"][0]["text"]) + assert answer["hits"][0]["ref"] == PAPER + assert err.count(line) >= 2 and line not in written # the query's read and the overview's + assert "GuestRefusal: scope: read: " in err and a.canary not in written + err + + +def test_what_a_tool_writes_to_the_descriptor_stays_off_the_protocol_stream() -> None: + """`sys.stdout` pointed elsewhere does not move file descriptor 1: C code, a child process + that inherits it and `sys.__stdout__` write there. The launcher writes its replies to a copy + of the descriptor and points the descriptor at stderr (`protocol_stream`). Spawned as a + client spawns it, with a guest tool that writes a forged reply to the descriptor, runs a + child that prints and writes to `sys.__stdout__`, the server's stdout holds one reply per + request and nothing else, and stderr holds every one of those lines.""" + script = str(Path(REPO_ROOT) / "scripts" / "palace_mcp.py") + program = "\n".join([ + "import os, runpy, subprocess, sys", + f"sys.path.insert(0, {str(REPO_ROOT)!r})", + "sys.argv = ['palace_mcp.py', '--role', 'guest']", + "from agents.ambassador import mcp", + "def loud(self):", + " os.write(1, b'{\"jsonrpc\": \"2.0\", \"id\": 2, \"result\": \"forged by fd 1\"}\\n')", + " subprocess.run(['echo', 'forged by a child'], check=True)", + " sys.__stdout__.write('forged by sys.__stdout__\\n')", + " sys.__stdout__.flush()", + " print('forged by print')", + " return {'ok': True}", + "mcp.Guest.overview = loud", + f"runpy.run_path({script!r}, run_name='__main__')", + ]) + asked = [("initialize", {}), ("tools/call", {"name": "overview", "arguments": {}}), + ("ping", {})] + requests = "".join(json.dumps({"jsonrpc": "2.0", "id": i, "method": m, "params": p}) + "\n" + for i, (m, p) in enumerate(asked, 1)) + out = subprocess.run([sys.executable, "-c", program], capture_output=True, text=True, + input=requests, timeout=60) + assert out.returncode == 0, out.stderr + replies = [json.loads(line) for line in out.stdout.splitlines()] + assert [r["id"] for r in replies] == [1, 2, 3] and out.stdout.count("\n") == len(asked) + assert replies[1]["result"] == {"content": [{"type": "text", "text": '{"ok": true}'}], + "isError": False} + assert "forged" not in out.stdout + for written in ("forged by fd 1", "forged by a child", "forged by sys.__stdout__", + "forged by print"): + assert written in out.stderr, written + + +def test_overview_counts_only_what_the_grant_reads_and_status_is_absent( + palaces: tuple[Fixture, Fixture]) -> None: + a, _ = palaces + guest = _server(a, "guest") + error, text = _call(guest, "overview") + assert not error and a.canary not in text + body = json.loads(text) + assert set(body) == {"catalog_by_provenance", "literature_chunks", "your_grant"} + assert body["catalog_by_provenance"] == {"authored-dialogue": 1, "observed": 1} + assert body["literature_chunks"] == 1 + assert all(not set(p["strata"]) & {s.value for s in NOT_THE_MIRROR} and not p["write"] + for p in body["your_grant"]) + # the Ambassador's overview counts the note and its relation: what the guest's leaves out + error, amb = _call(_server(a, "ambassador"), "overview") + assert json.loads(amb)["catalog_by_provenance"]["authored-solo"] == 1 + assert json.loads(amb)["relation_edges"] == {"supports": 1} + for tool in ("status", "capture", "task_list", "task_add", "remind", "link", "dream", + "relate", "sync_dialogue", "sync_notes", "task_update"): + error, text = _call(guest, tool) + assert error and "unknown tool" in text + + +def test_the_ambassador_sees_what_the_guest_is_denied(palaces: tuple[Fixture, Fixture]) -> None: + """The positive control: the same palace, asked by the Ambassador, carries the canary in + the channels the guest's battery tried, so the battery would have caught a leak.""" + a, _ = palaces + amb = _server(a, "ambassador") + for sentence in ('near "walnut orchard"', f'reach C from "{TURN}" over dialogue', + f'witness "{a.vault_edge}"', f'relate "{a.note}"', f'read "{a.note}"'): + error, text = _call(amb, "query", sentence=sentence) + assert not error and a.canary in text, (sentence, text) + + +def test_the_default_server_is_the_ambassadors() -> None: + from agents.ambassador import mcp + + default, guest = mcp.Server(), mcp.Server("guest") + assert default.tools is mcp.TOOLS and default.instructions == mcp.INSTRUCTIONS + assert [t[0] for t in guest.tools] == ["query", "overview"] + assert guest.instructions == mcp.GUEST_INSTRUCTIONS != mcp.INSTRUCTIONS + with pytest.raises(ValueError, match="role is one of"): + mcp.Server("intruder") + + +def test_the_launcher_serves_the_guest_on_stdio() -> None: + """The command line an MCP client spawns: `palace_mcp.py --role guest` seals, then lists + the guest's two tools; an unknown role is refused before anything is served.""" + script = str(Path(REPO_ROOT) / "scripts" / "palace_mcp.py") + lines = [{"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {}}, + {"jsonrpc": "2.0", "id": 2, "method": "tools/list"}] + out = subprocess.run([sys.executable, script, "--role", "guest"], capture_output=True, + text=True, input="\n".join(map(json.dumps, lines)) + "\n", timeout=60) + replies = [json.loads(x) for x in out.stdout.splitlines()] + assert [t["name"] for t in replies[1]["result"]["tools"]] == ["query", "overview"] + bad = subprocess.run([sys.executable, script, "--role", "intruder"], capture_output=True, + text=True, input="", timeout=60) + assert bad.returncode == 1 and "--role is one of ambassador, guest" in bad.stderr diff --git a/tests/adversarial/test_guest_lite.py b/tests/adversarial/test_guest_lite.py new file mode 100644 index 00000000..629eaa17 --- /dev/null +++ b/tests/adversarial/test_guest_lite.py @@ -0,0 +1,417 @@ +"""The guest over an instance that embeds nothing (dn-guest-principal §5, dn-palace-lite). + +The guest's intended use is an external coding agent reading the code instance +(`config/instances/code.toml`), which embeds nothing: its items land with their lexical units and +no vector, `near` ranks them by the lexical index and says so, `read` opens a landed repository +file from the raw store, and `overview` says how current each repository is. An instance that +embeds nothing can also hold a vault: its notes land in the same lexical index as the code and the +dialogue, so the index's document frequencies, unit count and mean length would be a function of +the notes if a ranking read them over every class. + +A palace that embeds nothing holds a note with a canary in its path, title and body, landed by the +ingress, a repository's files landed by `sync_repository`, a dialogue turn of each kind and a +paper with lexical units and no vector, and the fixture's transcript turn, causal edges and +citation graph. As the guest, the battery of `test_guest_leaks.py` is asked again with the code +source's own refs: no output carries the canary, the admitted strata answer lexically, and over a +second such palace whose note differs in its words and its length every output, `overview` +included, is the same once the names each asker typed are put back to one placeholder. The +Ambassador, asked the same, sees the note and counts its units. Last, the launcher serves the +guest over an overlay made from the code instance's own, its landed repository answering through +the protocol stream and nothing else reaching it. +""" + +from __future__ import annotations + +import json +import os +import subprocess +import sys +import tomllib +from pathlib import Path +from typing import Any + +import pytest + +from core.attestation.store import open_attestation_store +from core.ingest import ingress +from core.kernel.config import REPO_ROOT +from core.kernel.ingest.chunk import Chunk +from core.kernel.provenance import Provenance +from core.query import GUEST, QueryEngine +from core.sentence.surface import QueryLog +from core.stores.causal_edges import open_causal_edge_store +from core.stores.chatlog import ChatUtterance, open_chatlog_store +from core.stores.landings import LANDING_LOG_KEY +from tests.adversarial.test_guest_leaks import ( + AUTHORED, + CODE, + OBSERVED, + PAPER, + Fixture, + _battery, + _call, + _canary, + _edges, + _eid, + _meets, + _outcome, + _server, +) +from tests.conftest import LANDING_LOG_TEST_KEY +from tests.fixtures.ingress import write_file +from tests.integration.test_palace_lite import lite_config +from tests.unit.test_sentence_universe import _Edge, _Refs + +REPO = "toy" +FILE = f"code/{REPO}/pkg/orchard.py" +# The note of the first palace says the battery's words often, in over 300 terms; the second's +# says none of them, in four, so a ranking that counted the notes' units would differ between them. +WORDY = "The {c} body: a walnut orchard, a private plan. " + "Walnut orchard rows, walnut " * 80 +TERSE = "The {c} body: errands." + + +def _git(repo: Path, *args: str) -> str: + return subprocess.run(["git", "-C", str(repo), *args], check=True, capture_output=True, + text=True).stdout.strip() + + +@pytest.fixture +def repo(tmp_path: Path) -> Path: + """A repository on `main` whose three files say the battery's words in different measure.""" + r = tmp_path / "repo" + (r / "pkg").mkdir(parents=True) + (r / "docs").mkdir() + _git(r.parent, "init", "-q", "-b", "main", str(r)) + (r / "pkg" / "orchard.py").write_text( + 'def walnut_orchard(rows):\n """Irrigate a walnut orchard, row by row."""\n' + " return rows\n") + (r / "pkg" / "plan.py").write_text( + "from pkg.orchard import walnut_orchard\n\n\ndef plan():\n" + ' """The plan for the orchard."""\n return walnut_orchard([])\n') + (r / "docs" / "guide.md").write_text("# The guide\n\nHow the orchard is planned.\n") + _git(r, "add", "-A") + _git(r, "-c", "user.email=t@example.org", "-c", "user.name=t", "commit", "-q", "-m", "one") + return r + + +def _land(stores: Any, path: str, text: str, prov: Provenance) -> None: + """An item as a landing that embeds nothing leaves it: its bytes, its catalog entry and its + lexical units, and no vector.""" + digest, _ = stores.raw.add_text(text) + stores.catalog.record(path, digest, text[:24], provenance=prov) + stores.lexical.land(source_path=path, digest=digest, provenance=prov.value, title=text[:24], + chunks=[Chunk(0, text)]) + + +def _lite(root: Path, canary: str, repo: Path, body: str) -> Fixture: + """A palace under `root` that embeds nothing: the note landed by `sync_vault`, the + repository by `sync_repository`, the dialogue and a paper with lexical units alone, and the + fixture's transcript turn, causal edges and citation graph.""" + cfg = lite_config(root, repo) + stores = ingress.build_stores(cfg) + write_file(cfg.ingestion.vault.path, f"{canary}.md", + f"# {canary} title\n\n{body.format(c=canary)}\n") + assert ingress.run_library(cfg, "sync_vault", stores=stores)["effects"] == {"landed": 1} + assert ingress.run_library(cfg, "sync_repository", {"name": REPO}, + stores=stores)["effects"] == {"landed": 3} + (entry,) = [e for e in stores.catalog.active_entries() + if str(e.provenance) == Provenance.AUTHORED_SOLO.value] + assert canary in entry.source_path and canary in entry.title + _land(stores, AUTHORED, "walnut orchard notes from the chat", Provenance.AUTHORED_DIALOGUE) + _land(stores, OBSERVED, "a summary of the orchard plan", Provenance.OBSERVED) + _land(stores, PAPER, "irrigation of walnut orchards", Provenance.CURATED) + (attestation,) = [a.id for a in open_attestation_store(cfg).all() + if entry.digest in a.output_hashes] + engine = QueryEngine(config=cfg) + engine._cache["references"] = _Refs([_Edge("docs/guide.md", CODE, "c1"), + _Edge(CODE, "core/kernel/scope.py", "c1")]) + note = entry.source_path + f = Fixture(canary, engine, root, note, entry.title, _eid("s1", 1, note), + _eid("s1", 2, CODE), attestation) + open_causal_edge_store(cfg).replace_session("s1", _edges(f), "wd1") + open_chatlog_store(cfg).add_batch([ChatUtterance("s1", 1, "owner", "please write the plan", + "wd1")]) + return f + + +@pytest.fixture +def lite(tmp_path: Path, repo: Path, monkeypatch: pytest.MonkeyPatch) -> tuple[Fixture, Fixture]: + """Two palaces that embed nothing, over one repository, whose notes differ in path, title, + words and length; the citation graph's cut and the query log fixed. Each lands the + repository, and its mark keeps the second the landing ended, which `overview` shows. The + two landings end a fraction of a second apart, now and then in two seconds, so the second + palace's mark is given the first's second: the palaces then differ in their notes alone.""" + import core.reference_view as rv + from core.ingest.readers import read_mark + from core.ingest.table import repository_mark + from core.sentence import surface + + monkeypatch.setattr(rv, "_resolve_default_commit", lambda cfg: "c1") + monkeypatch.setattr(surface, "default_log", lambda: QueryLog(tmp_path / "q.jsonl")) + a = _lite(tmp_path / "a", _canary("a"), repo, WORDY) + b = _lite(tmp_path / "b", _canary("b"), repo, TERSE) + first, second = (repository_mark(f.engine.config, REPO) for f in (a, b)) + landed, other = read_mark(first), read_mark(second) + assert landed is not None and other is not None and landed["commit"] == other["commit"] + second.write_text(json.dumps({**other, "at": landed["at"]})) + return a, b + + +def _lite_battery(f: Fixture) -> list[tuple[str, str]]: + """The battery as an instance that embeds nothing answers it, then the code source's refs. + No node keeps a vector, so `S` has no edge and its walks are empty; a paper is ranked by its + lexical units and read from the curated plane, which such an instance does not have; every + sentence the battery refuses is refused here too.""" + differs = { + f'diffuse S from "{AUTHORED}" over dialogue': "empty", + f'diffuse S from "{PAPER}" over curated': "refused", + f'walk from "{AUTHORED}" via S over dialogue': "empty", + f'read "{PAPER}"': "refused", + f'near "walnut" over dialogue and diffuse S from "{AUTHORED}" over dialogue': "empty", + } + battery = [(s, differs.get(s, e)) for s, e in _battery(f)] + assert set(differs) <= {s for s, _ in battery} + return battery + [ + ('top 3 near "walnut orchard" over reference', "answered"), + ('top 5 near "walnut orchard" over dialogue reference curated observed', "answered"), + ('near "orchard plan" over reference observed', "answered"), + (f'read "{FILE}"', "answered"), + (f'read "{FILE}" chunk 1', "answered"), + (f'diffuse S from "{FILE}" over reference', "empty"), + (f'reach F from "{FILE}"', "empty"), + (f'trace "{FILE}"', "refused"), + (f'near "walnut" over reference within reach F from "{FILE}"', "admitted"), + ('near "walnut orchard"', "refused"), + (f'read "code/{REPO}/pkg/absent.py"', "refused"), + ] + + +def test_no_guest_output_carries_the_canary_where_nothing_is_embedded( + lite: tuple[Fixture, Fixture]) -> None: + a, b = lite + guest = _server(a, "guest") + seen: dict[str, str] = {} + for sentence, _ in _lite_battery(a): + for trace in (False, True): + error, text = _call(guest, "query", sentence=sentence, trace=trace) + assert a.canary not in text and b.canary not in text, (sentence, text) + assert a.note not in text and a.title not in text, sentence + seen[sentence] = _outcome(error, text) + if error: + assert text.startswith("GuestRefusal: "), text + wrong = {s: (seen[s], e) for s, e in _lite_battery(a) if not _meets(seen[s], e)} + assert not wrong, wrong + error, text = _call(guest, "overview") + assert not error and a.canary not in text + + +def test_the_guest_cannot_tell_two_palaces_that_embed_nothing_apart( + lite: tuple[Fixture, Fixture]) -> None: + """Noninterference over the lexical index: the notes differ in their words and their length, + and nothing the guest receives does, its ranks and scores and `overview`'s counts included. + The Ambassador's answers and counts tell the two apart: the difference is in the stores.""" + a, b = lite + + def norm(f: Fixture, text: str) -> str: + for name, mark in ((f.note, "<note>"), (f.title, "<title>"), (f.canary, "<canary>"), + (f.vault_edge, "<edge>"), (f.attestation, "<att>"), + (str(f.root), "<root>")): + text = text.replace(name, mark) + return text + + ga, gb = _server(a, "guest"), _server(b, "guest") + for (sa, _), (sb, _) in zip(_lite_battery(a), _lite_battery(b), strict=True): + for trace in (False, True): + ea, ta = _call(ga, "query", sentence=sa, trace=trace) + eb, tb = _call(gb, "query", sentence=sb, trace=trace) + assert (ea, norm(a, ta)) == (eb, norm(b, tb)), sa + assert _call(ga, "overview") == _call(gb, "overview") + + # the control: a grant that reads the mirror ranks the wordy note first and counts its units + aa, ab = _server(a, "ambassador"), _server(b, "ambassador") + error, text = _call(aa, "query", sentence='top 1 near "walnut orchard"') + assert not error and json.loads(text)["hits"][0]["ref"] == a.note + error, text = _call(ab, "query", sentence='top 1 near "walnut orchard"') + assert not error and b.canary not in text + units = [json.loads(_call(s, "overview")[1])["lexical_units"] for s in (aa, ab)] + assert units[0] > units[1] + + +def test_every_lexical_read_the_guest_causes_names_classes_its_grant_reads( + lite: tuple[Fixture, Fixture], monkeypatch: pytest.MonkeyPatch) -> None: + """The mechanism under the noninterference test. A ranking's statistics are read over the + classes it names, and over the whole index when it names none; a count likewise. While the + guest asks the battery, the code source's refs and the overview, every score and every count + the lexical index makes names its classes, and each is a class the grant reads. The + Ambassador's `near` over the notes names the notes' class: the recorder sees it.""" + from core.kernel.clearance import classes_of + from core.stores.lexical import LexicalStore + + asked: list[frozenset[str] | None] = [] + score, count = LexicalStore._score_units, LexicalStore.count + + def named(classes: Any) -> frozenset[str] | None: + return None if classes is None else frozenset(str(c) for c in classes) + + def scored(self: LexicalStore, query: str, *, classes: Any, paths: Any) -> dict[int, float]: + asked.append(named(classes)) + return score(self, query, classes=classes, paths=paths) + + def counted(self: LexicalStore, *, classes: Any = None) -> int: + asked.append(named(classes)) + return count(self, classes=classes) + + monkeypatch.setattr(LexicalStore, "_score_units", scored) + monkeypatch.setattr(LexicalStore, "count", counted) + a, _ = lite + guest = _server(a, "guest") + for sentence, _ in _lite_battery(a): + _call(guest, "query", sentence=sentence) + _call(guest, "overview") + readable = {p.value for p in classes_of(GUEST.strata)} + assert len(asked) > 10 + assert all(c is not None and c <= readable for c in asked), asked + asked.clear() + _call(_server(a, "ambassador"), "query", sentence='near "walnut orchard"') + assert any(c is not None and Provenance.AUTHORED_SOLO.value in c for c in asked), asked + + +def test_the_guest_reads_the_code_source_lexically(lite: tuple[Fixture, Fixture]) -> None: + """What the code instance is for: `near` over reference ranks the repository's files by the + lexical index and labels each hit, its notes say the instance embeds nothing, `read` opens a + landed file from the raw store, `trace` is refused with the grant's hint, and `overview` says + the profile, the units of the classes the grant reads and the commit each repository landed.""" + from agents.ambassador import mcp + from core.kernel.clearance import classes_of + from core.stores.lexical import open_lexical_store + + a, _ = lite + guest = _server(a, "guest") + + def answer(sentence: str) -> dict[str, Any]: + error, text = _call(guest, "query", sentence=sentence) + assert not error, text + return dict(json.loads(text)) + + near = answer('top 3 near "walnut orchard" over reference') + assert near["hits"][0]["ref"] == FILE + assert {h["ref"] for h in near["hits"]} <= {FILE, f"code/{REPO}/pkg/plan.py", + f"code/{REPO}/docs/guide.md"} + assert all(h["detail"]["ranked_by"] == "lexical: the item keeps no vector" + for h in near["hits"]) + assert any("the instance embeds nothing" in n for n in near["notes"]) + (read,) = answer(f'read "{FILE}"')["hits"] + assert read["stratum"] == "reference" and "def walnut_orchard" in read["text"] + dialogue = answer('near "walnut orchard" over dialogue')["hits"] + assert [h["ref"] for h in dialogue][:1] == [AUTHORED] + error, text = _call(guest, "query", sentence=f'trace "{FILE}"') + assert error and text.endswith(mcp.GUEST_SCOPE_HINT) and "no version plane" in text + error, text = _call(guest, "query", sentence=f'read "code/{REPO}/pkg/absent.py"') + assert (error, text) == (True, "GuestRefusal: lookup: " + mcp.GUEST_RAN["lookup"]) + assert "code/<name>/<path>" in text + + error, text = _call(guest, "overview") + assert not error + body = json.loads(text) + head = _git(Path(a.engine.config.ingestion.code.repositories[0].path), "rev-parse", "main") + assert body["embedding"] == mcp.EMBEDDING_OFF + assert body["code"] == [{"repository": REPO, "ref": "main", "landed": head[:12], + "at": body["code"][0]["at"], "behind": 0}] + assert body["catalog_by_provenance"] == {"code": 3, "authored-dialogue": 1, "observed": 1, + "curated": 1} + assert body["literature_chunks"] == 0 + lexical = open_lexical_store(a.engine.config) + assert body["lexical_units"] == lexical.count(classes=classes_of(GUEST.strata)) \ + < lexical.count() + + +# ── the launcher over the code instance's overlay ────────────────────────────────────────────── + + +def _code_overlay(tmp_path: Path, repo: Path) -> Path: + """The code instance's overlay (`config/instances/code.toml`) as a test runs it: every + setting the same but the id, which one overlay may declare, the root, which is the owner's, + and the repository, which is the fixture's.""" + declared = tomllib.loads((Path(REPO_ROOT) / "config" / "instances" / "code.toml").read_text()) + assert declared["embedding"] == {"enabled": False} + assert declared["ingestion"]["vault"] == {"enabled": False} + root = tmp_path / "home" / "code-guest" + lines = ["[instance]", 'id = "code-guest"', f'root = "{root}"', ""] + for section, values in declared.items(): + if section == "instance": + continue + for name, table in ([(f"{section}.{k}", v) for k, v in values.items()] + if section == "ingestion" else [(section, values)]): + lines.append(f"[{name}]") + lines += [f"{k} = {json.dumps(v)}" for k, v in table.items() + if k != "repositories"] + lines.append("") + lines += ["[[ingestion.code.repositories]]", f'name = "{REPO}"', f'path = "{repo}"', + 'ref = "main"', ""] + overlay = tmp_path / "code-guest.toml" + overlay.write_text("\n".join(lines)) + return overlay + + +def test_the_launcher_serves_the_guest_over_the_code_instances_overlay( + tmp_path: Path, repo: Path, monkeypatch: pytest.MonkeyPatch) -> None: + """`MIND_PALACE_OVERLAY=<the code overlay> palace_mcp.py --role guest`, as an MCP client + spawns it, after the repository landed: one reply per request on stdout and nothing else, + the landed files found and read, the refusals in their fixed words, the instance's own query + log written with the guest's role, and no vector store made.""" + from agents.ambassador import mcp + from core.kernel.config.loader import load_config + + overlay = _code_overlay(tmp_path, repo) + monkeypatch.setenv("MIND_PALACE_OVERLAY", str(overlay)) + cfg = load_config() + assert cfg.instance.id == "code-guest" and not cfg.embedding.enabled + # A named instance reads its own landing-log item, `<id>.landing-log-key`, which the + # suite's fixture does not set: the sync below writes the catalog, and the launcher opens it. + monkeypatch.setenv(cfg.instance.secret(LANDING_LOG_KEY), LANDING_LOG_TEST_KEY) + assert ingress.run_library(cfg, "sync_repository", {"name": REPO}, + stores=ingress.build_stores(cfg))["effects"] == {"landed": 3} + asked = [("initialize", {}), ("tools/list", {}), + ("tools/call", {"name": "overview", "arguments": {}}), + ("tools/call", {"name": "query", "arguments": { + "sentence": 'top 3 near "walnut orchard" over reference'}}), + ("tools/call", {"name": "query", "arguments": {"sentence": f'read "{FILE}"'}}), + ("tools/call", {"name": "query", "arguments": {"sentence": 'near "walnut"'}}), + ("tools/call", {"name": "query", "arguments": {"sentence": f'trace "{FILE}"'}}), + ("tools/call", {"name": "query", "arguments": { + "sentence": f'read "code/{REPO}/pkg/absent.py"'}}), + ("tools/call", {"name": "status", "arguments": {}})] + requests = "".join(json.dumps({"jsonrpc": "2.0", "id": i, "method": method, "params": params}) + + "\n" for i, (method, params) in enumerate(asked, 1)) + out = subprocess.run([sys.executable, str(Path(REPO_ROOT) / "scripts" / "palace_mcp.py"), + "--role", "guest"], capture_output=True, text=True, input=requests, + timeout=120, env={**os.environ, "MIND_PALACE_OVERLAY": str(overlay)}) + assert out.returncode == 0, out.stderr + replies = [json.loads(line) for line in out.stdout.splitlines()] + assert [r["id"] for r in replies] == list(range(1, len(asked) + 1)) + assert out.stdout.count("\n") == len(asked) + assert replies[0]["result"]["instructions"] == mcp.GUEST_INSTRUCTIONS + assert [t["name"] for t in replies[1]["result"]["tools"]] == ["query", "overview"] + + def text(i: int) -> tuple[bool, str]: + result = replies[i]["result"] + return result["isError"], result["content"][0]["text"] + + error, body = text(2) + overview = json.loads(body) + assert not error and overview["embedding"] == mcp.EMBEDDING_OFF + assert overview["catalog_by_provenance"] == {"code": 3} + assert [(c["repository"], c["behind"]) for c in overview["code"]] == [(REPO, 0)] + error, body = text(3) + assert not error and json.loads(body)["hits"][0]["ref"] == FILE + error, body = text(4) + assert not error and "def walnut_orchard" in json.loads(body)["hits"][0]["text"] + error, body = text(5) + assert error and body.startswith("GuestRefusal: scope: ") + error, body = text(6) + assert error and body.endswith(mcp.GUEST_SCOPE_HINT) + assert text(7) == (True, "GuestRefusal: lookup: " + mcp.GUEST_RAN["lookup"]) + assert "unknown tool" in replies[8]["error"]["message"] + logged = QueryLog(cfg.paths.data_dir / "query_log.jsonl").entries() + assert [e.role for e in logged] == ["guest"] * 5 + assert not list(cfg.instance.root.rglob("*.lance")) diff --git a/tests/unit/test_ambassador_surface.py b/tests/unit/test_ambassador_surface.py index 341a3efb..a199f039 100644 --- a/tests/unit/test_ambassador_surface.py +++ b/tests/unit/test_ambassador_surface.py @@ -7,6 +7,8 @@ import json import sqlite3 import sys +import threading +from collections.abc import Callable from pathlib import Path from typing import Any, cast @@ -358,6 +360,133 @@ def test_mcp_handshake_lists_tools_and_ignores_notifications(): assert replies[2]["error"]["code"] == -32601 +def _on_a_small_stack(run: Callable[[], None]) -> None: + """`run` on a thread whose C stack is 1 MB, what it raises raised again here. How deep + `json.loads` and `json.dumps` nest is bounded by the stack, which differs between machines: + 8 MB for a Linux main thread under the usual `ulimit -s`, 16 MB for the main thread of a + macOS framework build, which sets its own. A test that needs a nesting past the stack runs + on a stack it chose. In 1 MB, on arm64, `json.loads` reaches some 8,000 levels and + `json.dumps` some 6,400; a nesting 100,000 deep would fit only at under 11 bytes a level.""" + failed: list[BaseException] = [] + + def guarded() -> None: + try: + run() + except BaseException as e: + failed.append(e) + + before = threading.stack_size(1 << 20) + try: + thread = threading.Thread(target=guarded) + thread.start() + thread.join() + finally: + threading.stack_size(before) + if failed: + raise failed[0] + + +def test_a_line_that_is_no_request_is_answered_and_the_server_reads_on( + capsys: pytest.CaptureFixture[str]) -> None: + """The stream may carry JSON that is no request: an array (one holding another among them), + a number, a string, null, params that are not an object, an id that is no string or number. + Each is answered with JSON-RPC's invalid request, the id null when the request's cannot be + used. A line `json.loads` cannot read is a parse error: one that is not JSON, a number past + Python's limit on the digits it converts, and an array nested 100,000 deep, past the stack + the lines are served on (`_on_a_small_stack`). After each, the next request is answered as + ever. A server that fails while it handles a request answers an internal error and reads + on, its traceback on stderr.""" + from agents.ambassador import mcp + + ping = json.dumps({"jsonrpc": "2.0", "id": 7, "method": "ping"}) + lines = ["[]", "1", '"x"', "null", "[1, 2]", "[[1]]", + json.dumps({"jsonrpc": "2.0", "id": 1, "method": "tools/list", "params": [1]}), + json.dumps({"jsonrpc": "2.0", "id": 2, "method": "initialize", "params": "x"}), + json.dumps({"jsonrpc": "2.0", "id": [3], "method": "ping"}), + json.dumps({"jsonrpc": "2.0", "id": True, "method": "ping"}), + '{"jsonrpc": "2.0", "id": ' + "1" * 5000 + ', "method": "ping"}', "not json", + "[" * 100_000 + "]" * 100_000] + stream, out = io.StringIO("".join(f"{x}\n{ping}\n" for x in lines)), io.StringIO() + _on_a_small_stack(lambda: mcp.serve(stream, out, mcp.Server("guest"))) + replies = [json.loads(r) for r in out.getvalue().splitlines()] + assert len(replies) == 2 * len(lines) + assert all(r == {"jsonrpc": "2.0", "id": 7, "result": {}} for r in replies[1::2]) + refused = replies[0::2] + assert [r["error"]["code"] for r in refused] == [-32600] * 10 + [-32700] * 3 + assert [r["id"] for r in refused] == [None] * 6 + [1, 2] + [None] * 5 + + class Failing(mcp.Server): + def handle(self, msg: Any) -> dict[str, Any] | None: + if msg.get("method") == "tools/list": + raise RuntimeError("the table could not be read") + return super().handle(msg) + + out = io.StringIO() + listed = json.dumps({"jsonrpc": "2.0", "id": 4, "method": "tools/list"}) + mcp.serve(io.StringIO(f"{listed}\n{ping}\n"), out, Failing("guest")) + first, second = (json.loads(r) for r in out.getvalue().splitlines()) + assert first == {"jsonrpc": "2.0", "id": 4, + "error": {"code": -32603, "message": "internal error"}} + assert second["id"] == 7 and "the table could not be read" in capsys.readouterr().err + + +def test_initialize_answers_the_version_asked_when_it_is_a_string_and_its_own_otherwise() -> None: + """`initialize` answers with the protocol version a client asks for when it is a string, and + with the server's own for any other value, as MCP answers a version a server does not + support. The value was repeated as it came, and one nested past what `json.dumps` writes, + though not past what `json.loads` reads, made a reply the server could not write: the + process ended there, and the requests after it went unanswered.""" + from agents.ambassador import mcp + + def answered(asked: Any) -> Any: + reply = mcp.Server("guest").handle({"jsonrpc": "2.0", "id": 1, "method": "initialize", + "params": {"protocolVersion": asked}}) + assert reply is not None + return reply["result"]["protocolVersion"] + + assert answered("2025-03-26") == "2025-03-26" + for asked in (["2025-06-18"], [[1]], {"version": "2025-06-18"}, 20250618, 1.5, True, None, + ""): + assert answered(asked) == mcp.PROTOCOL_VERSION + + +def test_a_request_whose_reply_cannot_be_written_is_answered_as_an_internal_error( + capsys: pytest.CaptureFixture[str]) -> None: + """A reply `json.dumps` cannot write, one that holds itself or one nested past the stack, is + replaced by JSON-RPC's internal error with the request's id, its traceback on stderr, and + the next request is answered as ever: the server writes a reply inside a guard too. The + lines are served on a stack of 1 MB (`_on_a_small_stack`), which a reply nested 100,000 + deep is past.""" + from agents.ambassador import mcp + + holds_itself: list[Any] = [] + holds_itself.append(holds_itself) + deep: list[Any] = [] + for _ in range(100_000): + deep = [deep] + + class Unwritable(mcp.Server): + def handle(self, msg: Any) -> dict[str, Any] | None: + if msg.get("method") == "tools/list": + tools = holds_itself if msg["id"] == 4 else deep + return {"jsonrpc": "2.0", "id": msg["id"], "result": {"tools": tools}} + return super().handle(msg) + + ping = json.dumps({"jsonrpc": "2.0", "id": 7, "method": "ping"}) + stream = io.StringIO("".join( + json.dumps({"jsonrpc": "2.0", "id": i, "method": "tools/list"}) + f"\n{ping}\n" + for i in (4, 5))) + out = io.StringIO() + _on_a_small_stack(lambda: mcp.serve(stream, out, Unwritable("guest"))) + internal = {"code": -32603, "message": "internal error"} + pong = {"jsonrpc": "2.0", "id": 7, "result": {}} + assert [json.loads(r) for r in out.getvalue().splitlines()] == [ + {"jsonrpc": "2.0", "id": 4, "error": internal}, pong, + {"jsonrpc": "2.0", "id": 5, "error": internal}, pong] + err = capsys.readouterr().err + assert "Circular reference detected" in err and "RecursionError" in err + + def test_a_failing_tool_is_an_error_result_not_a_crash(monkeypatch: pytest.MonkeyPatch): from agents.ambassador import mcp @@ -382,6 +511,120 @@ def query(self, **_: Any) -> None: assert "refused" in reply["result"]["content"][0]["text"] +def _calls(*calls: tuple[str, dict[str, Any]]) -> io.StringIO: + return io.StringIO("".join(json.dumps({ + "jsonrpc": "2.0", "id": i, "method": "tools/call", + "params": {"name": name, "arguments": arguments}}) + "\n" + for i, (name, arguments) in enumerate(calls, 1))) + + +class _Chatty: + """Tools that print: when they are made, while one runs, and before one fails.""" + + def __init__(self) -> None: + print("opening the stores") + + def query(self, sentence: str) -> dict[str, Any]: + print("a progress line") + sys.stdout.write('{"jsonrpc": "2.0", "id": 1, "result": "forged"}\n') + return {"sentence": sentence} + + def overview(self) -> dict[str, Any]: + print("about to fail") + raise RuntimeError("no overview") + + +def test_what_a_tool_prints_goes_to_stderr_and_stdout_carries_replies_only( + monkeypatch: pytest.MonkeyPatch, capfd: pytest.CaptureFixture[str]) -> None: + """A tool runs with `sys.stdout` pointed at stderr (`Server.handle`). What making the tools + prints, what a tool prints and what a failing tool prints reach stderr; the stream the client + reads holds one reply per request and nothing else, and `sys.stdout` is put back.""" + from agents.ambassador import mcp + + monkeypatch.setattr(mcp, "Ambassador", _Chatty) + before = sys.stdout + mcp.serve(_calls(("query", {"sentence": "x"}), ("overview", {})), sys.stdout, mcp.Server()) + assert sys.stdout is before + out, err = capfd.readouterr() + replies = [json.loads(line) for line in out.splitlines()] + assert [r["id"] for r in replies] == [1, 2] and out.count("\n") == 2 + assert json.loads(replies[0]["result"]["content"][0]["text"]) == {"sentence": "x"} + assert replies[1]["result"] == {"content": [{"type": "text", + "text": "RuntimeError: no overview"}], + "isError": True} + for printed in ("opening the stores", "a progress line", "forged", "about to fail"): + assert printed in err and printed not in out + + +def test_a_process_with_no_stderr_drops_what_a_tool_prints( + monkeypatch: pytest.MonkeyPatch) -> None: + """Started with stderr closed, `sys.stderr` is None, and `print` to it would fall back to + stdout. The tool's lines and the failure's traceback are dropped; stdout still holds the + replies alone.""" + from agents.ambassador import mcp + + monkeypatch.setattr(mcp, "Ambassador", _Chatty) + out = io.StringIO() + monkeypatch.setattr(sys, "stdout", out) + monkeypatch.setattr(sys, "stderr", None) + mcp.serve(_calls(("overview", {}), ("overview", {})), out, mcp.Server()) + replies = [json.loads(line) for line in out.getvalue().splitlines()] + assert [(r["id"], r["result"]["isError"]) for r in replies] == [(1, True), (2, True)] + assert "Traceback" not in out.getvalue() and "about to fail" not in out.getvalue() + + +def test_a_reply_no_encoding_carries_is_written_as_ascii() -> None: + """A sentence may hold a lone surrogate, and an answer repeats its sentence. The stream is + UTF-8, which has no encoding for one: the reply is written as ASCII, the same JSON, and the + server goes on to the next request. A reply the stream can encode is written as it was.""" + from agents.ambassador import mcp + + class Echo: + def query(self, sentence: str) -> dict[str, Any]: + return {"sentence": sentence} + + server = mcp.Server() + server._amb = Echo() # type: ignore[assignment] + raw = io.BytesIO() + stream = io.TextIOWrapper(raw, encoding="utf-8") + hostile, plain = 'near "\ud800"', 'near "café ∅"' + mcp.serve(_calls(("query", {"sentence": hostile}), ("query", {"sentence": plain})), stream, + server) + first, second = raw.getvalue().decode("utf-8").splitlines() + assert first.isascii() and "\\ud800" in first + assert "café ∅" in second # not escaped: readable as before + for line, sentence in ((first, hostile), (second, plain)): + text = json.loads(line)["result"]["content"][0]["text"] + assert json.loads(text) == {"sentence": sentence} + + +def test_a_reply_is_utf8_on_a_stream_that_would_escape_a_surrogate() -> None: + """Python's UTF-8 mode gives stdout the `surrogateescape` handler, which does not refuse a + lone surrogate from U+DC80 to U+DCFF: it writes the byte the surrogate stands for, and that + byte is not UTF-8. A reply holding one is written as ASCII all the same, so every line the + client reads decodes as UTF-8 and is the same JSON.""" + from agents.ambassador import mcp + + class Echo: + def query(self, sentence: str) -> dict[str, Any]: + return {"sentence": sentence} + + server = mcp.Server() + server._amb = Echo() # type: ignore[assignment] + raw = io.BytesIO() + stream = io.TextIOWrapper(raw, encoding="utf-8", errors="surrogateescape") + hostile, plain = 'near "\udc80\udcff" over dialogue', 'near "café ∅"' + assert hostile.encode("utf-8", "surrogateescape") == b'near "\x80\xff" over dialogue' + mcp.serve(_calls(("query", {"sentence": hostile}), ("query", {"sentence": plain})), stream, + server) + first, second = raw.getvalue().decode("utf-8").splitlines() # strict: every byte is UTF-8 + assert first.isascii() and "\\udc80\\udcff" in first + assert "café ∅" in second # not escaped: readable as before + for line, sentence in ((first, hostile), (second, plain)): + text = json.loads(line)["result"]["content"][0]["text"] + assert json.loads(text) == {"sentence": sentence} + + def test_the_opencode_reader_keeps_text_parts_of_top_level_sessions(tmp_path: Path) -> None: from edge.opencode_sessions import export_sessions diff --git a/tests/unit/test_sentence_grammar.py b/tests/unit/test_sentence_grammar.py index 073fcac1..4d77a972 100644 --- a/tests/unit/test_sentence_grammar.py +++ b/tests/unit/test_sentence_grammar.py @@ -153,6 +153,36 @@ def test_quote_is_the_tokenizers_inverse(text: str) -> None: "text": text, "conversation": "tea"} +def test_a_long_string_literal_is_read_in_memory_its_text_bounds() -> None: + """A sentence may be a guest's, of any length. Reading a string literal takes memory in + proportion to its text, a few bytes a character: plain, its escapes plain, quotes escaped, + backslashes escaped, characters outside the BMP, the literal closed or never closed. The + pattern's earlier form kept a backtracking point for each character, some 80 to 160 bytes, + and a regular expression's unescape some 20 more for a literal of escapes.""" + import tracemalloc + + from core.sentence.grammar import tokenize + + n = 200_000 + for body in ("a" * n, "\\a" * (n // 2), 'x\\"' * (n // 3), "\\\\" * (n // 2), + "\U0001f600" * n): + for closed in (True, False): + text = 'near "' + body + ('" over dialogue' if closed else "") + tracemalloc.start() + try: + if closed: + assert len(tokenize(text)) == 5 + else: + with pytest.raises(ParseError, match="unexpected character"): + tokenize(text) + peak = tracemalloc.get_traced_memory()[1] + finally: + tracemalloc.stop() + assert peak < 16 * len(text), (body[:4], closed, peak / len(text)) + # an escaped quote and an escaped backslash are read, any other escape kept as written + assert tokenize('near "x\\"y\\\\z\\a\\\\\\""')[1].text == 'x"y\\z\\a\\"' + + def test_the_command_words_are_not_keywords_elsewhere() -> None: # `dialogue` and `code` keep working as a stratum and as a bare atom assert parse('near "x" over dialogue') == ast.Over(ast.Near("x"), ("dialogue",)) diff --git a/tests/unit/test_sentence_surface.py b/tests/unit/test_sentence_surface.py index 18627091..c9c2e360 100644 --- a/tests/unit/test_sentence_surface.py +++ b/tests/unit/test_sentence_surface.py @@ -10,7 +10,7 @@ import re from collections.abc import Mapping from pathlib import Path -from typing import Any +from typing import Any, cast import numpy as np import pytest @@ -20,7 +20,14 @@ from core.sentence.ast import Rel from core.sentence.execute import Relation, Universe from core.sentence.precedents import DEFAULT -from core.sentence.surface import Entry, QueryLog, run_query, summarize +from core.sentence.surface import ( + SENTENCE_BYTES, + SENTENCE_MAX, + Entry, + QueryLog, + run_query, + summarize, +) ROOT = Path(__file__).resolve().parents[2] @@ -277,6 +284,171 @@ def test_entries_ignore_fields_a_later_schema_adds(tmp_path: Path) -> None: outcome="answered", hits=1, modes=("semantic",), strata=("mirror_authored",)) +# ── the log holds whatever a sentence holds, and the reader is a terminal ────────────────────── + + +def test_a_line_separator_in_a_sentence_does_not_break_the_log(tmp_path: Path) -> None: + """U+2028, U+2029 and U+0085 are line breaks to `str.splitlines` and plain text to JSON. A + sentence that holds them is one line of the log, whether the log wrote it as ASCII or, as it + did before, with the separators raw inside the string; `--log` reads both back whole.""" + log = QueryLog(tmp_path / "q.jsonl") + hostile = 'near "x\u2028y\u2029z\x85w"' + assert len(hostile.splitlines()) == 4 + rc, _ = _run([hostile], log) + assert rc == 0 + raw = (tmp_path / "q.jsonl").read_text(encoding="utf-8") + assert raw.isascii() and raw.count("\n") == 1 and len(raw.splitlines()) == 1 + (e,) = log.entries() + assert e.sentence == hostile and e.outcome == "answered" + old = {"at": "2026-11-09T00:00:00", "surface": "mcp", "role": "guest", "sentence": hostile, + "outcome": "empty"} + with (tmp_path / "q.jsonl").open("a", encoding="utf-8") as f: + f.write(json.dumps(old, ensure_ascii=False) + "\n") + assert [x.sentence for x in log.entries()] == [hostile, hostile] + rc, text = _run(["--log"], log) + assert rc == 0 and text.splitlines()[0] == "asked: 2 answered 1 empty 1" + + +def test_a_lone_surrogate_is_logged_and_both_renderings_can_be_encoded( + tmp_path: Path, capsys: Any) -> None: + """A sentence may hold a lone surrogate (a JSON `\\ud800`, an undecodable byte of argv), + which no encoding of a file or a terminal carries. The log writes its escape, so `record` + does not raise, and `--log` prints its escape, as text and as JSON. `record` raises for + nothing else either: an entry that cannot be written is reported on stderr.""" + log = QueryLog(tmp_path / "q.jsonl") + hostile = 'nearby "\ud800"' + rc, text = _run([hostile], log) # refused, and logged all the same + assert rc == 1 and text.startswith("refused (parse): ") + (e,) = log.entries() + assert (e.sentence, e.outcome, e.refusal) == (hostile, "refused", "parse") + for argv in (["--log"], ["--log", "--json"]): + rc, text = _run(argv, log) + assert rc == 0 and "\\ud800" in text + text.encode("utf-8") # would raise on a lone surrogate + assert json.loads(_run(["--log", "--json"], log)[1]) == summarize(log.entries()) + assert capsys.readouterr().err == "" + log.record(Entry(at="t", surface="cli", role="cli", sentence=cast(str, b"not text"), + outcome="answered")) + assert "query log not written" in capsys.readouterr().err and len(log.entries()) == 1 + + +def test_the_log_keeps_the_head_of_a_long_sentence(tmp_path: Path) -> None: + """A sentence is logged up to `SENTENCE_MAX` characters, then a marker of its full length; + its sort, modes and strata are read from the whole of it.""" + log = QueryLog(tmp_path / "q.jsonl") + long = 'near "' + "walnut " * 2000 + '"' + rc, _ = _run([long], log) + (e,) = log.entries() + assert rc == 0 and (e.outcome, e.sort, e.modes) == ("answered", "field", ("semantic",)) + assert len(long) == 14_007 + assert e.sentence == f"{long[:SENTENCE_MAX]} <14007 characters, cut at {SENTENCE_MAX}>" + assert len((tmp_path / "q.jsonl").read_text(encoding="utf-8")) < SENTENCE_MAX + 400 + whole = 'near "' + "a" * (SENTENCE_MAX - 7) + '"' + _run([whole], log) + assert len(whole) == SENTENCE_MAX and log.entries()[-1].sentence == whole + + +def test_the_log_bounds_a_sentence_by_the_bytes_its_line_writes(tmp_path: Path) -> None: + """A character outside ASCII is written as its escape, six bytes or twelve, and so is a + control. The log keeps a sentence's head up to `SENTENCE_BYTES` bytes of the line as well as + `SENTENCE_MAX` characters, so a sentence costs the log a few kilobytes whatever it is made + of, and the marker says where it was cut. A sentence of printable ASCII is cut by + characters alone, its quotes and backslashes included.""" + log = QueryLog(tmp_path / "q.jsonl") + ascii_whole = 'near "' + '\\"' * ((SENTENCE_MAX - 7) // 2) + '"' + hostile = ['near "' + "\U0001f600" * 5000 + '" over dialogue', + 'near "' + "é" * 5000 + '"', 'nearby "' + "\ud800" * 3000 + '"', + 'near "' + "\x1b" * 2000 + '"', ascii_whole] + for sentence in hostile: + _run([sentence], log) + lines = (tmp_path / "q.jsonl").read_text(encoding="utf-8").splitlines() + assert len(lines) == len(hostile) and all(line.isascii() for line in lines) + assert max(map(len, lines)) < SENTENCE_BYTES + 700 + for sentence, e in zip(hostile[:4], log.entries()[:4], strict=True): + head, marker = e.sentence.rsplit(" <", 1) + assert sentence.startswith(head) and marker == ( + f"{len(sentence)} characters, cut at {len(head)}>") + written = len(json.dumps(head)) - 2 + assert written <= SENTENCE_BYTES < written + len(json.dumps(sentence[len(head)])) - 2 + assert len(ascii_whole) <= SENTENCE_MAX and log.entries()[4].sentence == ascii_whole + + +def test_the_log_is_read_a_line_at_a_time(tmp_path: Path) -> None: + """`palace query --log` summarizes the log in one pass over its lines (`QueryLog.read`), so + the reader's memory is the summary's and one line's, not a multiple of the file's: over a + log of some 8 MB it stays under 3 MB. The summary is the one the whole list gives.""" + import tracemalloc + + p = tmp_path / "q.jsonl" + row = {"at": "2026-11-12T00:00:00", "surface": "mcp", "role": "guest", "outcome": "refused", + "refusal": "parse", "reason": "clause: expected a verb", "strata": ["dialogue"]} + with p.open("w", encoding="utf-8") as f: + for i in range(2000): + f.write(json.dumps({**row, "sentence": f"nearby {i} " + "x" * 4000}) + "\n") + assert p.stat().st_size > 8_000_000 + log = QueryLog(p) + tracemalloc.start() + try: + rc, text = _run(["--log", "--json"], log) + peak = tracemalloc.get_traced_memory()[1] + finally: + tracemalloc.stop() + assert rc == 0 and peak < 3_000_000, peak + assert json.loads(text) == summarize(log.entries()) + assert json.loads(text)["asked"] == 2000 and len(json.loads(text)["failed"]) == 10 + + +def test_the_summary_escapes_what_a_terminal_would_obey(tmp_path: Path) -> None: + """`--log` prints sentences on the owner's terminal, and a sentence may be a guest's. An + escape sequence, a newline that would start a forged line, a bidi override that would + reorder the line, a bell, a delete and a C1 control are printed as their escapes, in the + text and in the JSON, and so is a role. The JSON is the same JSON.""" + log = QueryLog(tmp_path / "q.jsonl") + esc, bel, rlo, lri = "\x1b", "\x07", "\u202e", "\u2066" + hostile = (f'nearby "x"\n{esc}[2J{esc}[31m 2026-11-09T00:00:00 cli do dream{esc}[0m' + f'{rlo}gnp.exe{lri}{bel}\x7f\x9b') + assert _run([hostile, "--as", f"guest{esc}]0;title{bel}"], log)[0] == 1 + rc, text = _run(["--log"], log) + assert rc == 0 + for raw in (esc, bel, rlo, lri, "\x7f", "\x9b"): + assert raw not in text + lines = text.splitlines() + assert lines[:2] == ["asked: 1 refused 1", "served (role · strata):"] and len(lines) == 6 + assert lines[2] == " guest\\x1b]0;title\\x07 · ∅: refused 1" + failed = lines[-1] # one entry, one line + assert ('nearby "x"\\n\\x1b[2J\\x1b[31m 2026-11-09T00:00:00 cli do dream\\x1b[0m' + "\\u202egnp.exe\\u2066\\x07\\x7f\\x9b — parse: ") in failed + rc, js = _run(["--log", "--json"], log) + assert rc == 0 and json.loads(js) == summarize(log.entries()) + assert all(c == "\n" or c.isprintable() for c in js) + assert "\\u001b[2J" in js and "\\u202egnp.exe\\u2066\\u0007\\u007f\\u009b" in js + assert " · ∅" in js # printable text stays as it is + + +def test_a_line_that_is_not_an_entry_is_skipped_and_counted(tmp_path: Path, + capsys: Any) -> None: + """A torn write, a line of another shape and bytes that are not UTF-8 do not stop the + sensor: the entries around them are read, and one line on stderr counts the rest.""" + p = tmp_path / "q.jsonl" + good = {"at": "2026-11-09T00:00:00", "surface": "cli", "role": "owner", "sentence": 'near "x"', + "outcome": "answered", "hits": 1} + damaged = ['{"at": "2026-11-09T00:00:01", "surface": "cli", "role": "ow', # torn + json.dumps([1, 2, 3]), json.dumps("near"), "null", "not json at all", + json.dumps({"at": "t", "surface": "cli"}), # fields missing + json.dumps({**good, "sentence": 7}), json.dumps({**good, "modes": 5}), + json.dumps({**good, "strata": [1]}), json.dumps({**good, "hits": "many"}), + json.dumps({**good, "hyp": "no"}), "[" * 200_000] + lines = [json.dumps(good), *damaged, json.dumps({**good, "sentence": 'near "y"'})] + p.write_text("\n".join(lines) + "\n", encoding="utf-8") + assert [e.sentence for e in QueryLog(p).entries()] == ['near "x"', 'near "y"'] + err = capsys.readouterr().err + assert err.count("\n") == 1 and f"{len(damaged)} lines are not entries and were skipped" in err + rc, text = _run(["--log"], QueryLog(p)) + assert rc == 0 and text.startswith("asked: 2 answered 2") + p.write_bytes(json.dumps(good).encode() + b"\n\xff\xfe{torn\n") + assert [e.sentence for e in QueryLog(p).entries()] == ['near "x"'] + + # ── the Ambassador's `query` tool: the one read ──────────────────────────────────────────────── diff --git a/tests/unit/test_sentence_universe_withheld.py b/tests/unit/test_sentence_universe_withheld.py new file mode 100644 index 00000000..7f5e8936 --- /dev/null +++ b/tests/unit/test_sentence_universe_withheld.py @@ -0,0 +1,471 @@ +"""What the universe names to a reader whose grant holds no stratum of the mirror +(`core/sentence/universe.py` under `hide_mirror`, dn-guest-principal §5): a causal edge only when +it ends at a commit or at a file git tracks in the repo at HEAD, a citation neighbour only when it +is a repo-relative path outside the vault, and a vault path in whatever spelling it was recorded. +A reader whose grant holds the mirror is shown what it was shown before. Hermetic: the store fakes +of test_sentence_universe, a vault under tmp_path and a scratch git repo standing for the +checkout.""" + +from __future__ import annotations + +import os +import subprocess +import unicodedata +from dataclasses import replace +from pathlib import Path +from types import SimpleNamespace +from typing import Any, cast + +import pytest + +from core.kernel.config import get_config +from core.query import AMBASSADOR_OVERLAY, GUEST, QueryEngine +from core.sentence import compile_sentence, execute +from core.sentence.precedents import DEFAULT +from core.sentence.universe import _Builder, _doc_path, build +from tests.unit.test_sentence_universe import ( + _Causal, + _cedge, + _Chatlog, + _Curated, + _Edge, + _Engine, + _Memberships, + _Refs, + _vec, + _Vectors, +) + +SHA = "0123456789abcdef0123456789abcdef01234567" +WITHHELD = "withheld: the grant names no stratum of the mirror" + + +def _config(vault: Path) -> Any: + base = get_config() + return replace(base, ingestion=replace(base.ingestion, + vault=replace(base.ingestion.vault, path=vault))) + + +def _builder(vault: Path, *, hide: bool = True) -> _Builder: + """A builder with a configuration alone: enough for the tests of a path, which open no store.""" + engine = SimpleNamespace(config=_config(vault)) + return _Builder(cast(QueryEngine, engine), DEFAULT, hide_mirror=hide) + + +@pytest.fixture +def repo(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path: + """A git repo standing for the checkout: two files, a design note and a finding committed; + a file and a design note written after the commit, which git does not track.""" + import core.kernel.config as config + + root = tmp_path / "repo" + for d in ("core", "docs/design-notes", "docs/findings"): + (root / d).mkdir(parents=True) + (root / "core" / "x.py").write_text("x = 1\n") + (root / "docs" / "a.md").write_text("a\n") + (root / "docs" / "design-notes" / "dn-kept.md").write_text("kept\n") + (root / "docs" / "findings" / "finding-0007-seven.md").write_text("seven\n") + git = ["git", "-C", str(root), "-c", "user.name=t", "-c", "user.email=t@t"] + subprocess.run([*git, "init", "-q"], check=True, capture_output=True) + subprocess.run([*git, "add", "core", "docs"], check=True, capture_output=True) + subprocess.run([*git, "commit", "-q", "-m", "tree"], check=True, capture_output=True) + (root / "core" / "new.py").write_text("y = 2\n") + (root / "docs" / "design-notes" / "dn-draft.md").write_text("draft\n") + monkeypatch.setattr(config, "REPO_ROOT", root) + return root + + +# ── the tracked paths ────────────────────────────────────────────────────────────────────────── + + +def test_tracked_paths_are_the_tree_at_head_and_none_when_git_cannot_answer( + repo: Path, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + import importlib + + ex = importlib.import_module("core.sentence.execute") # the package exports `execute` + assert ex.tracked_paths(repo) == {"core/x.py", "docs/a.md", "docs/design-notes/dn-kept.md", + "docs/findings/finding-0007-seven.md"} + subprocess.run(["git", "-C", str(repo), "add", "core/new.py"], check=True, capture_output=True) + assert "core/new.py" not in ex.tracked_paths(repo) # staged is not yet at HEAD + bare = tmp_path / "not-a-repo" + bare.mkdir() + assert ex.tracked_paths(bare) == frozenset() + assert ex.tracked_paths(tmp_path / "absent") == frozenset() + # a name that is not UTF-8 is spelled by no string, so it is left out, not approximated + monkeypatch.setattr(ex, "_git", lambda root, *args: b"docs/a.md\0docs/\xff.md\0") + assert ex.tracked_paths(repo) == {"docs/a.md"} + monkeypatch.setattr(ex, "_git", lambda root, *args: None) + assert ex.tracked_paths(repo) == frozenset() + for sha in ("0123abc", SHA, "a" * 64): + assert ex.is_commit_sha(sha) + for text in ("", "0123ab", "0123ABC", "0123abc\n", "g123abc", f"{SHA}/x", "a" * 65, + "docs/a.md"): + assert not ex.is_commit_sha(text), text + + +# ── the vault, in the spellings the check folds ──────────────────────────────────────────────── + + +def test_a_vault_path_is_recognised_in_the_spellings_it_folds( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + """Spellings a file system may treat as one file, whether or not this one does: another + letter case, another Unicode normal form, `.` and `..`, a symlink, `~`, a path relative to + the working directory. The comparison is by component, so a sibling whose name starts with + the vault's is outside. The names it does not fold are the next test's.""" + home = tmp_path / unicodedata.normalize("NFC", "w\u00e9") + vault = home / "vault" + (vault / "sub").mkdir(parents=True) + (tmp_path / "link").symlink_to(vault) + (tmp_path / "deep" / "er").mkdir(parents=True) + (home / "hop").symlink_to(tmp_path / "deep" / "er") + monkeypatch.setenv("HOME", str(home)) + monkeypatch.chdir(home) + b = _builder(vault) + note = str(vault / "sub" / "n.md") + nfd = unicodedata.normalize("NFD", note) + assert nfd != note + inside = [note, str(vault), f"{vault}/", str(home / "VAULT" / "Sub" / "N.md"), nfd, + nfd.replace("/vault/", "/VAULT/"), f"{home}/other/../vault/n.md", + f"{vault}/../vault/n.md", f"/{note}", f"{vault}/./n.md", + str(tmp_path / "link" / "n.md"), "~/vault/n.md", "~/Vault/n.md", "vault/n.md", + "./vault/sub/../n.md", "../" + home.name + "/vault/n.md", + str(home / "\uff56ault" / "n.md"), # a compatibility form of the name + # in the vault by its normal form alone: resolved, the link is followed before the + # `..` and the path leaves; the three forms are each asked, so it is withheld + f"{home}/hop/../vault/n.md"] + for ref in inside: + assert b._in_vault(ref), ref + assert (home / "hop" / ".." / "vault").resolve() == (tmp_path / "deep" / "vault").resolve() + outside = [str(home / "vault-2" / "n.md"), f"{vault}.md", str(home), str(home / "n.md"), + "/srv/repo/core/x.py", "core/x.py", "~/n.md", "dn-kept.md", + f"file://{note}"] # a URI is no path: named by no rule + for ref in outside: + assert not b._in_vault(ref), ref + # a path that cannot be read counts as inside + for ref in (f"{vault}\0/n.md", "a\0b", "~no-such-user-of-this-test/n.md"): + assert b._in_vault(ref), ref + unset = _Builder(cast(QueryEngine, SimpleNamespace(config=None)), DEFAULT, hide_mirror=True) + assert unset._in_vault("/srv/repo/core/x.py") # any failure: inside + + +def test_a_name_the_vault_check_does_not_fold_is_left_to_the_allow_list( + repo: Path, tmp_path: Path) -> None: + """A file system knows a note by names the vault check does not fold: a hard link to it, + outside the vault or in the checkout, and its path through another mount of the volume + (macOS's data volume, `/System/Volumes/Data`). None of them is a file git tracks in a + checkout, so the allow list does not name it.""" + vault = tmp_path / "vault" + vault.mkdir() + note = vault / "n.md" + note.write_text("private\n") + outside, inside = tmp_path / "elsewhere.md", repo / "core" / "n.md" + os.link(note, outside) + os.link(note, inside) + mounted = f"/System/Volumes/Data{note}" + assert os.path.samefile(outside, note) and os.path.samefile(inside, note) + if Path("/System/Volumes/Data").is_dir(): # macOS: the same file again + assert os.path.samefile(mounted, note) + b = _builder(vault) + for dst in (str(outside), str(inside), mounted): + assert not b._named(dst, "file"), dst + + +# ── a causal edge's endpoint ─────────────────────────────────────────────────────────────────── + + +def test_only_a_commit_or_a_tracked_file_is_named(repo: Path, tmp_path: Path, + monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setenv("HOME", str(tmp_path)) + vault = tmp_path / "vault" + vault.mkdir() + (repo / "into-vault").symlink_to(vault) + b = _builder(vault) + named = [(SHA, "commit"), ("0123abc", "commit"), + (f"{repo}/core/x.py", "file"), (f"{repo}/docs/a.md", "file"), + (f"{repo}//core/x.py", "file"), (f"{repo}/core/x.py/", "file"), + (f"{repo}/.claude/worktrees/wt/core/x.py", "file"), # a worktree's copy of it + (f"{repo}/docs/design-notes/dn-kept.md", "doc"), + ("dn-kept.md", "doc"), ("dn-kept", "doc"), ("finding-0007", "doc")] + for dst, kind in named: + assert b._named(dst, kind), (dst, kind) + withheld = [ + ("not-a-sha", "commit"), ("", "commit"), (f"{SHA}\n", "commit"), ("core/x.py", "commit"), + (f"{vault}/n.md", "file"), (f"{tmp_path}/VAULT/n.md", "file"), + (f"{repo}/into-vault/n.md", "file"), # under the checkout, in the vault + (f"{repo}/core/new.py", "file"), # in the checkout, not tracked + (f"{repo}/core/gone.py", "file"), # no such file + (f"{repo}/CORE/x.py", "file"), # not as git spells it + (f"{repo}/core/../core/x.py", "file"), (f"{repo}/core", "file"), (str(repo), "file"), + ("/private/tmp/scratch/out.txt", "file"), ("/elsewhere/.claude/worktrees/w/core/x.py", + "file"), + ("core/x.py", "file"), ("./core/x.py", "file"), ("~/core/x.py", "file"), + (f"file://{repo}/core/x.py", "file"), ("", "file"), + ("dn-draft.md", "doc"), ("dn-none", "doc"), ("plan.md", "doc"), ("finding-0008", "doc"), + ("docs/design-notes/dn-kept.md", "doc"), + (f"{repo}/core/x.py", "artifact"), (f"{repo}/core/x.py", ""), ("dn-kept.md", "file"), + ] + for dst, kind in withheld: + assert not b._named(dst, kind), (dst, kind) + # a doc's id is read as a name, never as a pattern. The projector records a file under any + # `docs/design-notes/` folder by its file name, and a file name may hold a glob's characters: + # each of these, looked up as the glob it is, finds the one tracked finding, and is not named + for pattern in ("finding-*", "finding-000?.md", "finding-0007[-]seven.md", + "finding-0007*[the private plan].md"): + assert _doc_path(pattern) == "docs/findings/finding-0007-seven.md" + assert not b._named(pattern, "doc"), pattern + assert b._named_of[(f"{repo}/core/x.py", "file")] is True # judged once per endpoint + # the vault is asked first: a file git tracks is not named when it lies in the vault + inner = _builder(repo / "docs") + assert not inner._named(f"{repo}/docs/a.md", "file") + assert inner._named(f"{repo}/core/x.py", "file") + # and so when the configured vault is a symlink to that directory: a path is compared with + # the vault's resolved form too, and a citation neighbour under it, tracked or not, is not + # named either + (tmp_path / "vault-link").symlink_to(repo / "docs") + linked = _builder(tmp_path / "vault-link") + assert not linked._named(f"{repo}/docs/a.md", "file") + assert not linked._citable("docs/a.md") and not linked._citable("docs/n.md") + assert linked._named(f"{repo}/core/x.py", "file") and linked._citable("core/x.py") + + +def test_nothing_but_a_commit_is_named_when_the_tree_cannot_be_read( + repo: Path, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + """Fail closed: git absent or failing, or any error while an endpoint is judged, withholds + the edge; it never raises into the sentence.""" + import core.sentence.universe as universe + + vault = tmp_path / "vault" + assert _builder(vault)._named(f"{repo}/core/x.py", "file") # the control + failing = _builder(vault) + monkeypatch.setattr(failing, "_endpoint", lambda dst, dst_type: 1 / 0) + assert not failing._named(f"{repo}/core/x.py", "file") + + def no_git(root: Path) -> frozenset[str]: + raise OSError("git: not found") + + monkeypatch.setattr(universe, "tracked_paths", no_git) + b = _builder(vault) + assert not b._named(f"{repo}/core/x.py", "file") and not b._named("dn-kept.md", "doc") + assert b._named(SHA, "commit") and b._tracked() == frozenset() + + +def _engine(repo: Path, vault: Path, monkeypatch: pytest.MonkeyPatch, causal: list[dict[str, Any]], + refs: list[_Edge]) -> _Engine: + import core.reference_view as rv + + monkeypatch.setattr(rv, "_resolve_default_commit", lambda cfg: "c1") + e = _Engine( + refs=_Refs(refs), + vectors=_Vectors(dialogue=[{"source_path": "dialogue/c/t1", "title": "turn 1", + "digest": "dt1", "provenance": "observed", + "vector": _vec(2)}], atoms=[]), + curated=_Curated([]), memberships=_Memberships({}), embed={}, + causal=_Causal(causal), + chatlog=_Chatlog([{"session_id": "s1", "turn_index": 3, "speaker": "owner", + "text": "please write x", "transcript_digest": "td1", + "provenance": "observed"}])) + e.config = _config(vault) + return e + + +def test_the_universe_shows_the_named_edges_and_withholds_the_rest_whole( + repo: Path, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + """One turn with fifteen proven edges. The reader without the mirror is shown the four that + end at a tracked file, a tracked doc or a commit: as hits, in the counts and by `witness`. + The others are not counted, and `witness` of their ids answers as for an id the store does + not hold. The reader with the mirror is shown all fifteen, as before.""" + vault = tmp_path / "vault" + vault.mkdir() + shown = {"e-file": ("file", f"{repo}/core/x.py"), "e-doc": ("doc", "dn-kept.md"), + "e-finding": ("doc", "finding-0007"), "e-commit": ("commit", SHA)} + hidden = {"h-untracked": ("file", f"{repo}/core/new.py"), + "h-outside": ("file", "/private/tmp/scratch/out.txt"), + "h-note": ("file", f"{vault}/n.md"), + "h-case": ("file", f"{tmp_path}/VAULT/n.md"), + "h-relative": ("file", "core/x.py"), + "h-uri": ("file", f"file://{repo}/core/x.py"), + "h-draft": ("doc", "dn-draft.md"), + "h-name": ("doc", "plan-0.md"), + "h-pattern": ("doc", "finding-0007*[the private plan].md"), + "h-word": ("commit", "not-a-sha"), + "h-kind": ("artifact", f"{repo}/core/x.py")} + edges = [_cedge(eid, "s1", 3, dst, dst_type=kind, order=i) + for i, (eid, (kind, dst)) in enumerate({**shown, **hidden}.items())] + engine = _engine(repo, vault, monkeypatch, edges, [_Edge("docs/a.md", "core/x.py", "c1")]) + sentence = 'reach C from "transcript/s1/3" depth 1 over dialogue_transcript reference' + + plan = compile_sentence(sentence, GUEST) + u = build(cast(QueryEngine, engine), plan, hide_mirror=True) + hits = {h.ref: h for h in execute(plan, u).hits} + assert set(hits) == {"core/x.py", "docs/design-notes/dn-kept.md", + "docs/findings/finding-0007-seven.md", SHA} + assert hits["core/x.py"].detail["witness"] == "e-file" + assert hits["docs/design-notes/dn-kept.md"].detail["id"] == "dn-kept.md" + assert any("causal: 4 proven edges from 1 transcript turns to 4 endpoints" in m + for m in u.missing) + assert sum(m.startswith(WITHHELD) for m in u.missing) == 1 + for eid, (_kind, dst) in shown.items(): + record = u.witness(eid) + assert record is not None and record["dst"] == dst + for eid in hidden: + assert u.witness(eid) is None, eid + assert u.witness("no-such-edge") is None + + # the same store with every hidden edge taken out: the same universe, word for word + bare = _engine(repo, vault, monkeypatch, edges[:len(shown)], + [_Edge("docs/a.md", "core/x.py", "c1")]) + v = build(cast(QueryEngine, bare), plan, hide_mirror=True) + assert (u.notes, u.missing, u.edges) == (v.notes, v.missing, v.edges) + + # a grant that reads the mirror builds what it built before: every edge, every record + wide = compile_sentence(sentence, AMBASSADOR_OVERLAY) + w = build(cast(QueryEngine, engine), wide) + assert any("causal: 15 proven edges from 1 transcript turns" in m for m in w.missing) + assert not any(m.startswith(WITHHELD) for m in w.missing) + for eid, (_kind, dst) in {**shown, **hidden}.items(): + record = w.witness(eid) + assert record is not None and record["dst"] == dst + + +def test_a_turn_whose_edges_are_all_withheld_is_no_turn_to_the_reader( + repo: Path, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + """The lookup refusal for a turn with only withheld edges is the one for a turn no edge names, + and an endpoint asked for by name has no turn behind it.""" + vault = tmp_path / "vault" + vault.mkdir() + edges = [_cedge("h1", "s9", 1, f"{vault}/n.md"), _cedge("h2", "s9", 1, "notes/n.md"), + _cedge("h3", "s9", 1, f"{repo}/core/new.py")] + engine = _engine(repo, vault, monkeypatch, edges, []) + plan = compile_sentence('reach C from "transcript/s9/1" over dialogue_transcript', GUEST) + with pytest.raises(LookupError) as with_edges: + build(cast(QueryEngine, engine), plan, hide_mirror=True) + with pytest.raises(LookupError) as without: + build(cast(QueryEngine, _engine(repo, vault, monkeypatch, [], [])), plan, + hide_mirror=True) + assert str(with_edges.value) == str(without.value) + back = compile_sentence('reach C from "notes/n.md" back over dialogue', GUEST) + assert execute(back, build(cast(QueryEngine, engine), back, hide_mirror=True)).hits == () + back_new = compile_sentence('reach C from "core/new.py" back over dialogue', GUEST) + assert execute(back_new, build(cast(QueryEngine, engine), back_new, + hide_mirror=True)).hits == () + + +class _Minted(_Refs): + """A reference store whose edges are found by id: each id names the commit that minted it.""" + + def __init__(self, minted: dict[str, str]) -> None: + super().__init__([]) + self.minted = minted + + def edge(self, edge_id: str) -> _Edge | None: + sha = self.minted.get(edge_id) + return None if sha is None else _Edge("docs/a.md", "core/x.py", sha) + + +def test_the_witness_of_a_reference_edge_is_judged_like_any_other( + repo: Path, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + """`witness` of a reference edge's id answers the causal edge keyed to the commit that + minted it (`origin`). The reader without the mirror is answered only when that edge is one + it may see named, a commit by its sha; a row keyed to a commit whose endpoint is anything + else is no record to it, as an id the stores do not hold. The reader with the mirror is + answered both.""" + vault = tmp_path / "vault" + vault.mkdir() + other = "f" * 40 + engine = _engine(repo, vault, monkeypatch, [ + {**_cedge("c-commit", "s1", 3, SHA, dst_type="commit", order=2), "pair_cut_sha": SHA}, + {**_cedge("c-note", "s1", 3, f"{vault}/n.md", order=1), "pair_cut_sha": other}], []) + engine._cache["references"] = _Minted({"r-commit": SHA, "r-note": other}) + plan = compile_sentence('witness "r-commit"', GUEST) + u = build(cast(QueryEngine, engine), plan, hide_mirror=True) + record = u.witness("r-commit") + assert record is not None and (record["edge_id"], record["dst"]) == ("c-commit", SHA) + assert u.witness("r-note") is None and u.witness("r-none") is None + assert execute(compile_sentence('witness "r-note"', GUEST), u).hits == () + w = build(cast(QueryEngine, engine), compile_sentence('witness "r-note"', AMBASSADOR_OVERLAY)) + record = w.witness("r-note") + assert record is not None and record["dst"] == f"{vault}/n.md" + + +def test_a_withheld_edge_keyed_to_a_commit_stands_in_front_of_no_named_one( + repo: Path, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + """Two causal edges keyed to the commit that minted a reference edge: one ends at a vault + path and comes first, the other ends at the commit. `origin` answers the first of the edges + it may choose from. The reader without the mirror may not choose the withheld one, so it is + answered the commit's edge, in whatever order the store holds the two: the answer of a store + without the withheld edge. The reader with the mirror is answered the first, as before.""" + vault = tmp_path / "vault" + vault.mkdir() + shown = {**_cedge("c-commit", "s1", 3, SHA, dst_type="commit", order=2), "pair_cut_sha": SHA} + hidden = {**_cedge("c-note", "s1", 3, f"{vault}/n.md", order=1), "pair_cut_sha": SHA} + plan = compile_sentence('witness "r"', GUEST) + seen = [] + for causal in ([shown], [shown, hidden], [hidden, shown]): + engine = _engine(repo, vault, monkeypatch, causal, []) + engine._cache["references"] = _Minted({"r": SHA}) + u = build(cast(QueryEngine, engine), plan, hide_mirror=True) + record = u.witness("r") + assert record is not None and (record["edge_id"], record["dst"]) == ("c-commit", SHA) + seen.append((record, [h.__dict__ for h in execute(plan, u).hits], u.missing)) + assert seen[1] == seen[2] == seen[0] + wide = build(cast(QueryEngine, engine), compile_sentence('witness "r"', AMBASSADOR_OVERLAY)) + record = wide.witness("r") + assert record is not None and (record["edge_id"], record["dst"]) == ("c-note", f"{vault}/n.md") + + +def test_the_withheld_note_is_one_sentence_whatever_the_store_holds( + repo: Path, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + """The note that says what is withheld rides with every sentence that walks C or asks a + witness, in the same words over a store with no edge, with edges that are shown, and with + edges that are withheld: its presence and its words tell nothing of the store. A sentence + that does neither carries no such note.""" + vault = tmp_path / "vault" + vault.mkdir() + edges = [_cedge("e1", "s1", 3, f"{repo}/core/x.py"), + _cedge("h1", "s1", 3, f"{vault}/n.md", order=1)] + said = set() + for causal in ([], edges[:1], edges[1:], edges): + engine = _engine(repo, vault, monkeypatch, causal, []) + for sentence in ('reach C from "core/x.py" back over dialogue', 'witness "e1"', + 'witness "h1"', + 'walk from "core/x.py" via (C|F) over reference dialogue_transcript'): + plan = compile_sentence(sentence, GUEST) + u = build(cast(QueryEngine, engine), plan, hide_mirror=True) + (note,) = [m for m in u.missing if m.startswith(WITHHELD)] + said.add(note) + quiet = compile_sentence('reach F from "core/x.py"', GUEST) + assert not any(m.startswith(WITHHELD) for m in build( + cast(QueryEngine, engine), quiet, hide_mirror=True).missing) + assert len(said) == 1 and "at a commit or at a file git tracks" in said.pop() + + +# ── a citation neighbour ─────────────────────────────────────────────────────────────────────── + + +def test_a_citation_neighbour_is_named_only_as_a_repo_path_outside_the_vault( + repo: Path, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + """The citation graph's refs are repo-relative paths. A neighbour spelled any other way, or + one that lies in the vault under the checkout, is not named; one that git does not track at + HEAD is, since the graph is read at other cuts too.""" + vault = repo / "private" # a vault kept inside the checkout + plain = ["core/y.py", "docs/b.md", "README.md", "docs/design-notes/dn-kept.md"] + other = [f"{tmp_path}/vault/n.md", "/srv/notes/n.md", "~/notes/n.md", "file:///srv/n.md", + "docs/../../notes/n.md", "../notes/n.md", "private/n.md", "PRIVATE/sub/n.md", + "docs/../private/n.md"] + refs = [_Edge("core/x.py", t, "c1") for t in plain + other] + engine = _engine(repo, vault, monkeypatch, [], refs) + sentence = 'reach F from "core/x.py" depth 1' + + plan = compile_sentence(sentence, GUEST) + u = build(cast(QueryEngine, engine), plan, hide_mirror=True) + assert sorted(h.ref for h in execute(plan, u).hits) == sorted(plain) + assert not {n["source_path"] for n in u.notes} & set(other) + hidden = _builder(vault) + assert all(hidden._citable(t) for t in plain) + assert not any(hidden._citable(t) for t in other) + + # a grant that reads the mirror is shown every neighbour, as before + wide = compile_sentence(sentence, AMBASSADOR_OVERLAY) + w = build(cast(QueryEngine, engine), wide) + assert sorted(h.ref for h in execute(wide, w).hits) == sorted(plain + other) + assert all(_builder(vault, hide=False)._citable(t) for t in plain + other)