diff --git a/lab/server/README.md b/lab/server/README.md index e67810ac60..dbd196334c 100644 --- a/lab/server/README.md +++ b/lab/server/README.md @@ -26,6 +26,8 @@ tickets and events in SQLite. Nothing presses a button yet: that is Slice 5. | `pa_lab/db.py` | The SQLite file: migrations (`PRAGMA user_version`), owner-only file, `BEGIN IMMEDIATE` writes | | `pa_lab/control.py` | Leases, idempotent requests, tickets, events, `next_events`, reconciliation, compaction | | `tests/test_{db,control,control_concurrency,control_mcp}.py` | Slice 3's tests: restarts, threads and processes racing, kills mid-write | +| `pa_lab/status.py`, `pa_lab/stdio_server.py`, `smoke_readonly.py` | Read-only stdio mode for `.mcp.json`: `console_status` ([below](#read-only-stdio-mode-mcpjson)) | +| `tests/test_status_readonly.py` | `console_status` and the read-only gate against a fake profile | Stdlib only (Python 3.8+), so no venv: the MCP transport is small enough to write on `http.server`. Run the tests from the repo root: @@ -218,6 +220,31 @@ up to 5 s + 2 s for the journal, and reads `state.json` again. Arguments are clo | a reply from another instance | `app_unavailable`, `evidence.reason` `instance_replaced` | | no journal within 7 s | `timeout`; the request is withdrawn from the inbox | +## Read-only stdio mode (`.mcp.json`) + +`python -m pa_lab serve-stdio --profile-dir ` serves MCP over stdio for a Claude Code +`.mcp.json` entry: no port, token or daemon. It is read-only by construction (`LabMcp(read_only=True)`): +the `console://B/state` and `/save` resources and one tool, `console_status` +(`pa_lab/status.py`), which reports what `~/BDSPLab/checkin.sh` does: the app's pid and deployment, +the legacy `Lab/state` fields (owner token dropped), `console://B/state`, the last `Program State:` +and run lines, the last press, the last `keepawake.log` line, the newest failure frame and +screenshot paths and the last log lines. `shot`, `describe_program`, `game_open` (they write into +`Lab/inbox`) and every control tool are neither listed nor callable. `serve --read-only` gives the +same tool set over HTTP. + +The project entry in `~/Projects/Arduino-Source/.mcp.json` (local, never committed): + +```json +{"mcpServers": {"pa-lab": {"type": "stdio", "command": "/Users/difan/.venvs/lab-claude/bin/python", + "args": ["-m", "pa_lab", "serve-stdio", + "--profile-dir", "/Users/difan/Library/Application Support/SerialPrograms/Profiles/lab-B", + "--keepawake-log", "/Users/difan/BDSPLab/keepawake.log"], + "env": {"PYTHONPATH": "/Users/difan/Projects/Arduino-Source-agents/lab/server"}}}} +``` + +Smoke test (reads files only): `~/.venvs/lab-claude/bin/python lab/server/smoke_readonly.py [profile]` +starts the server as `.mcp.json` does and prints `console_status` once. Tests: `tests/test_status_readonly.py`. + ## Slice 3: the durable control plane SQLite (`db_file` in the config, default `~/.local/state/pa-lab/control.sqlite`, created `0600`) diff --git a/lab/server/pa_lab/__main__.py b/lab/server/pa_lab/__main__.py index f12b07518d..725f098dcd 100644 --- a/lab/server/pa_lab/__main__.py +++ b/lab/server/pa_lab/__main__.py @@ -4,7 +4,8 @@ python3 -m pa_lab describe app_state python3 -m pa_lab kinds python3 -m pa_lab init-token ~/.config/pa-lab/token - python3 -m pa_lab serve --config ~/.config/pa-lab/server.json + python3 -m pa_lab serve --config ~/.config/pa-lab/server.json [--read-only] + python3 -m pa_lab serve-stdio --profile-dir ~/Library/Application\\ Support/SerialPrograms/Profiles/lab-B python3 -m pa_lab lease --config ~/.config/pa-lab/server.json show|claim-user|release-user Run from lab/server (or with lab/server on PYTHONPATH). Exit 0 valid, 1 invalid, 2 usage. @@ -32,6 +33,11 @@ def main(argv=None) -> int: init_token.add_argument('path') serve = sub.add_parser('serve', help='run the read-only MCP server (Streamable HTTP on 127.0.0.1)') serve.add_argument('--config', required=True) + serve.add_argument('--read-only', action='store_true', + help='serve only console_status and the resources: no inbox tools, no control plane') + stdio = sub.add_parser('serve-stdio', help='run the read-only MCP server on stdio (for .mcp.json)') + stdio.add_argument('--profile-dir', required=True, help="the console's SerialPrograms profile folder") + stdio.add_argument('--keepawake-log', default='~/BDSPLab/keepawake.log') lease = sub.add_parser('lease', help="show console B's lease, or (operator) claim or release it for the user") lease.add_argument('--config', required=True) lease.add_argument('action', choices=('show', 'claim-user', 'release-user')) @@ -71,14 +77,17 @@ def main(argv=None) -> int: print('wrote {}'.format(args.path)) return 0 if args.command == 'serve': - return _serve(args.config) + return _serve(args.config, args.read_only) + if args.command == 'serve-stdio': + from pa_lab import stdio_server + return stdio_server.main(args.profile_dir, args.keepawake_log) if args.command == 'lease': return _lease(args.config, args.action, args.console) parser.print_help() return 2 -def _serve(path: str) -> int: +def _serve(path: str, read_only: bool = False) -> int: from pa_lab import lab_reader, mcp_server try: cfg = config.load(path) @@ -87,6 +96,15 @@ def _serve(path: str) -> int: print('error {}'.format(e)) return 1 logging.basicConfig(level=logging.INFO, format='%(asctime)s %(name)s %(message)s') + if read_only: + from pathlib import Path + from pa_lab import status + statuses = {name: status.ProfileStatus(name, Path(entry.lab_dir).parent, + keepawake_log=Path.home() / 'BDSPLab' / 'keepawake.log') + for name, entry in cfg.consoles.items()} + readers = {name: s.reader for name, s in statuses.items()} + server = mcp_server.make_server(cfg.port, token, readers, statuses=statuses, read_only=True) + return _serve_forever(server, readers, mcp_server.ENDPOINT) from pa_lab import control, db plane = control.ControlPlane(db.Database(cfg.db_file), sorted(cfg.consoles)) readers = {name: lab_reader.ConsoleReader(name, entry.lab_dir, profile=entry.profile, control=plane) @@ -95,9 +113,13 @@ def _serve(path: str) -> int: reader.console_state() plane.compact() server = mcp_server.make_server(cfg.port, token, readers, control_plane=plane) + return _serve_forever(server, readers, mcp_server.ENDPOINT) + + +def _serve_forever(server, readers, endpoint: str) -> int: logging.getLogger('pa_lab.server').info('serving %s on http://127.0.0.1:%d%s', ', '.join(sorted(readers)), server.server_address[1], - mcp_server.ENDPOINT) + endpoint) try: server.serve_forever() except KeyboardInterrupt: diff --git a/lab/server/pa_lab/mcp_server.py b/lab/server/pa_lab/mcp_server.py index ac00a68b34..8eb6c0ced1 100644 --- a/lab/server/pa_lab/mcp_server.py +++ b/lab/server/pa_lab/mcp_server.py @@ -9,6 +9,10 @@ Tools: `shot`, `ensure_game`, `describe_program`, `game_open`; with a control plane also `acquire_console`, `renew_console`, `release_console`, `next_events` and `request_status`. Nothing here presses a button or starts or stops a program: that is not served yet. + +Read-only mode (`read_only=True`, `serve-stdio`): only `console_status` and the resources. Every tool +that writes into `Lab/inbox` (`shot`, `describe_program`, `game_open`) and every control tool is +neither listed nor callable. """ from __future__ import annotations @@ -25,7 +29,7 @@ import threading from typing import Any, Callable, Dict, Optional, Tuple -from pa_lab import app_query, contracts, control, shot, tools +from pa_lab import app_query, contracts, control, shot, status, tools from pa_lab.lab_reader import ConsoleReader, Unavailable LOG = logging.getLogger('pa_lab.server') @@ -119,6 +123,27 @@ }, ] +CONSOLE_STATUS_TOOL = { + 'name': 'console_status', + 'title': 'Console status (check-in)', + 'description': "What ~/BDSPLab/checkin.sh reports, read from the console's profile folder: the lab app's pid " + 'and deployment, the Lab/state fields, console://B/state, the last Program State line, the last ' + 'run lines (checkpoint passed/failed, Starting Program), the last press time, the last ' + 'keepawake line, the newest failure frame and screenshot paths, and the last log lines. Reads ' + 'files only; sends nothing to the app.', + 'inputSchema': { + 'type': 'object', + 'properties': { + 'console': {'type': 'string', 'enum': ['B']}, + 'log_lines': {'type': 'integer', 'minimum': 0, 'maximum': status.MAX_LOG_LINES, + 'default': status.DEFAULT_LOG_LINES}, + }, + 'required': ['console'], + 'additionalProperties': False, + }, + 'annotations': {'readOnlyHint': True, 'destructiveHint': False, 'idempotentHint': True}, +} + APP_QUERIES = {'describe_program': app_query.describe_program, 'game_open': app_query.game_open} @@ -184,14 +209,29 @@ def _json_text(value: Any) -> str: class LabMcp: - """JSON-RPC methods, without the transport. `consoles` is the allowlist: console id -> reader.""" + """JSON-RPC methods, without the transport. `consoles` is the allowlist: console id -> reader. + + `statuses` (console id -> ProfileStatus) adds `console_status`. `read_only` serves only that tool + and the resources: no inbox tools, no control plane.""" def __init__(self, consoles: Dict[str, ConsoleReader], take_shot: Callable[..., Dict[str, Any]] = shot.take_shot, - control_plane: Optional[control.ControlPlane] = None): + control_plane: Optional[control.ControlPlane] = None, + statuses: Optional[Dict[str, status.ProfileStatus]] = None, + read_only: bool = False): + if read_only and control_plane is not None: + raise ValueError('a read-only server has no control plane') self.consoles = consoles self.take_shot = take_shot self.control = control_plane + self.statuses = statuses or {} + self.read_only = read_only + + def tool_list(self): + status_tools = [CONSOLE_STATUS_TOOL] if self.statuses else [] + if self.read_only: + return status_tools + return TOOL_LIST + status_tools + (CONTROL_TOOL_LIST if self.control is not None else []) def call(self, method: str, params: Dict[str, Any], client: str = 'unnamed') -> Dict[str, Any]: if method == 'ping': @@ -203,8 +243,12 @@ def call(self, method: str, params: Dict[str, Any], client: str = 'unnamed') -> if method == 'resources/read': return self._read_resource(params.get('uri')) if method == 'tools/list': - return {'tools': TOOL_LIST + (CONTROL_TOOL_LIST if self.control is not None else [])} + return {'tools': self.tool_list()} if method == 'tools/call': + if params.get('name') not in [t['name'] for t in self.tool_list()]: + raise RpcError(INVALID_PARAMS, 'Unknown tool: {}'.format(params.get('name'))) + if params.get('name') == 'console_status': + return self._call_status(params.get('arguments', {})) if self.control is not None and params.get('name') in [t['name'] for t in CONTROL_TOOL_LIST]: return self._call_control(client, params.get('name'), params.get('arguments', {})) return self._call_tool(params.get('name'), params.get('arguments', {})) @@ -284,6 +328,29 @@ def _call_tool(self, name: Any, arguments: Any) -> Dict[str, Any]: {'type': 'text', 'text': _json_text(result)}], 'structuredContent': result, 'isError': False} + def _call_status(self, arguments: Any) -> Dict[str, Any]: + name = 'console_status' + if not isinstance(arguments, dict): + return self._refused(name, {'code': 'invalid_arguments', 'field': 'arguments', + 'message': 'expected an object'}) + unknown = sorted(set(arguments) - {'console', 'log_lines'}) + if unknown: + return self._refused(name, {'code': 'invalid_arguments', 'field': unknown[0], + 'message': 'unknown argument'}) + reader = self.statuses.get(arguments.get('console')) if isinstance(arguments.get('console'), str) else None + if reader is None: + return self._refused(name, {'code': 'console_not_allowed', 'message': + 'Console {!r} is not served; only {}.'.format( + arguments.get('console'), ', '.join(sorted(self.statuses)))}) + log_lines = arguments.get('log_lines', status.DEFAULT_LOG_LINES) + if isinstance(log_lines, bool) or not isinstance(log_lines, int) or \ + not 0 <= log_lines <= status.MAX_LOG_LINES: + return self._refused(name, {'code': 'invalid_arguments', 'field': 'log_lines', + 'message': 'expected 0..{}'.format(status.MAX_LOG_LINES)}) + result = reader.console_status(log_lines) + return {'content': [{'type': 'text', 'text': _json_text(result)}], 'structuredContent': result, + 'isError': False} + def _call_control(self, client: str, name: str, arguments: Any) -> Dict[str, Any]: if not isinstance(arguments, dict): return self._refused(name, {'code': 'invalid_arguments', 'field': 'arguments', diff --git a/lab/server/pa_lab/status.py b/lab/server/pa_lab/status.py new file mode 100644 index 0000000000..ef90687857 --- /dev/null +++ b/lab/server/pa_lab/status.py @@ -0,0 +1,175 @@ +"""`console_status`: what `~/BDSPLab/checkin.sh` reports, read from one profile folder. + +The lane tick's console-state read. It only reads files (and lists processes with `pgrep`): the +legacy `Lab/state`, the `Lab/state.json` resource when the app writes one, the tail of +`SerialPrograms.log`, `~/BDSPLab/keepawake.log` and the newest screenshots. It never writes into +`Lab/inbox`, presses a button or starts or stops anything. + +| checkin.sh line | field | +|---|---| +| `lab app: ` | `app` | +| `Program State:` line | `program_state` | +| `[Checkpoint] ...: passed/failed`, `Starting Program:` | `last_run` (last two) | +| `last press` | `last_press` | +| `newest failure frame` | `newest_failure_frame` | +""" + +from __future__ import annotations + +import os +from pathlib import Path +import re +import subprocess +from typing import Any, Callable, Dict, List, Optional + +from pa_lab import legacy, timestamps +from pa_lab.lab_reader import ConsoleReader + +LOG_TAIL_BYTES = 2_000_000 +MAX_LOG_LINES = 200 +DEFAULT_LOG_LINES = 20 +MAX_LINE_CHARS = 300 +SHOT_SUFFIXES = ('.png', '.jpg', '.jpeg') +MAX_DIR_ENTRIES = 5000 + +RUN_RE = re.compile(r'\[Checkpoint\] [0-9.a-z]+: (passed|failed)|Starting Program:') +DEPLOYMENT_RE = re.compile(r'deployments/([^/]+/[^/]+)/') + + +def _tail_lines(path: Path, max_bytes: int = LOG_TAIL_BYTES) -> List[str]: + """The complete lines in the last `max_bytes` of a file; [] when it cannot be read.""" + try: + with open(path, 'rb') as f: + f.seek(0, os.SEEK_END) + size = f.tell() + f.seek(max(0, size - max_bytes)) + data = f.read(max_bytes) + except OSError: + return [] + lines = data.decode('utf-8', errors='replace').splitlines() + if size > max_bytes and lines: + lines = lines[1:] # the first line was cut + return lines + + +def _clip(line: str) -> str: + return line if len(line) <= MAX_LINE_CHARS else line[:MAX_LINE_CHARS] + '...' + + +def _log_time(line: str) -> Optional[str]: + """`2026-11-15 00:12:15.959076 - ...` -> `00:12:15`.""" + return line[11:19] if len(line) >= 19 and line[4] == '-' and line[13] == ':' else None + + +def _newest(paths: List[Path]) -> Optional[Path]: + best, best_mtime = None, -1.0 + for path in paths: + try: + mtime = path.stat().st_mtime + except OSError: + continue + if mtime > best_mtime: + best, best_mtime = path, mtime + return best + + +def _files(directory: Path) -> List[Path]: + out = [] + try: + with os.scandir(directory) as entries: + for i, entry in enumerate(entries): + if i >= MAX_DIR_ENTRIES: + break + if entry.is_file() and entry.name.lower().endswith(SHOT_SUFFIXES): + out.append(Path(entry.path)) + except OSError: + pass + return out + + +def _subdirs(directory: Path) -> List[Path]: + try: + with os.scandir(directory) as entries: + return [Path(e.path) for e in entries if e.is_dir()] + except OSError: + return [] + + +def pgrep_app(profile: str) -> Optional[Dict[str, Any]]: + """The lab app running with `--profile `, as checkin.sh finds it.""" + try: + out = subprocess.run(['pgrep', '-lf', 'SerialPrograms --profile ' + profile], + capture_output=True, text=True, timeout=5).stdout + except (OSError, subprocess.SubprocessError): + return None + for line in out.splitlines(): + pid, _, command = line.partition(' ') + if not pid.isdigit() or not command.endswith('--profile ' + profile) or 'lablock.sh' in command: + continue + match = DEPLOYMENT_RE.search(command) + return {'pid': int(pid), 'deployment': match.group(1) if match else None} + return None + + +class ProfileStatus: + """One profile folder (e.g. `.../Profiles/lab-B`) read the way checkin.sh reads it.""" + + def __init__(self, console: str, profile_dir: Path, keepawake_log: Optional[Path] = None, + find_app: Callable[[str], Optional[Dict[str, Any]]] = pgrep_app, + now: Callable[[], float] = timestamps.wall_clock): + self.console = console + self.profile_dir = Path(profile_dir) + self.keepawake_log = keepawake_log + self.find_app = find_app + self.now = now + self.reader = ConsoleReader(console, self.profile_dir / 'Lab', profile=self.profile_dir.name, now=now) + + def _lab_state(self) -> Optional[Dict[str, Any]]: + path = self.profile_dir / 'Lab' / 'state' + try: + text = path.read_text(encoding='utf-8') + mtime = path.stat().st_mtime + except OSError: + return None + try: + fields = legacy.parse_legacy_state(text) + except ValueError as e: + return {'error': str(e)} + fields.pop('owner', None) # the owner token stays in the app's file + fields['written_at'] = timestamps.format(mtime) + return fields + + def _screenshots(self) -> Dict[str, Optional[str]]: + root = self.profile_dir / 'Screenshots' + failures = _newest(_files(root / 'AutoStory' / 'failures')) + candidates = _files(root) + for sub in _subdirs(root): + candidates += _files(sub) + for subsub in _subdirs(sub): + candidates += _files(subsub) + newest = _newest(candidates) + return {'newest_failure_frame': str(failures) if failures else None, + 'newest_screenshot': str(newest) if newest else None} + + def console_status(self, log_lines: int = DEFAULT_LOG_LINES) -> Dict[str, Any]: + log_lines = max(0, min(MAX_LOG_LINES, log_lines)) + lines = _tail_lines(self.profile_dir / 'SerialPrograms.log') + program_state = [l for l in lines if 'Program State:' in l] + runs = [l for l in lines if RUN_RE.search(l)] + presses = [l for l in lines if 'issue_' in l and 'nop' not in l] + keepawake = _tail_lines(self.keepawake_log, 4096) if self.keepawake_log else [] + doc = { + 'console': self.console, + 'observed_at': timestamps.format(self.now()), + 'profile_dir': str(self.profile_dir), + 'app': self.find_app(self.profile_dir.name), + 'lab_state': self._lab_state(), + 'console_state': self.reader.console_state(), + 'program_state': _clip(program_state[-1]) if program_state else None, + 'last_run': [_clip(l) for l in runs[-2:]], + 'last_press': _log_time(presses[-1]) if presses else None, + 'keepawake': keepawake[-1] if keepawake else None, + 'log_tail': [_clip(l) for l in lines[-log_lines:]] if log_lines else [], + } + doc.update(self._screenshots()) + return doc diff --git a/lab/server/pa_lab/stdio_server.py b/lab/server/pa_lab/stdio_server.py new file mode 100644 index 0000000000..147fca2128 --- /dev/null +++ b/lab/server/pa_lab/stdio_server.py @@ -0,0 +1,91 @@ +"""The read-only lab server over MCP's stdio transport, for a Claude Code `.mcp.json` entry. + +Claude Code starts it as a child process and talks newline-delimited JSON-RPC on stdin/stdout, so +it needs no port, token or daemon. It is always read-only: `LabMcp(read_only=True)` serves +`console_status` and the `console://B/state` and `/save` resources, nothing that writes into +`Lab/inbox`, and no control plane. Logs go to stderr; stdout carries only protocol messages. + + python -m pa_lab serve-stdio --profile-dir "$HOME/Library/Application Support/SerialPrograms/Profiles/lab-B" +""" + +from __future__ import annotations + +import json +import logging +from pathlib import Path +import sys +from typing import Any, Dict, IO, Optional + +from pa_lab.mcp_server import (INVALID_PARAMS, INVALID_REQUEST, PARSE_ERROR, PROTOCOL_VERSIONS, SERVER_INFO, + LabMcp, RpcError) +from pa_lab import status + +LOG = logging.getLogger('pa_lab.stdio') + +INSTRUCTIONS = ( + 'Read-only view of lab console B. console_status returns what ~/BDSPLab/checkin.sh reports ' + '(app pid, Lab/state, last run lines, last press, newest failure frame and screenshot, log tail). ' + 'Nothing here presses a button, starts or stops a program, or writes to the app.') + + +def make_mcp(profile_dir: Path, console: str = 'B', keepawake_log: Optional[Path] = None) -> LabMcp: + profile_status = status.ProfileStatus(console, profile_dir, keepawake_log=keepawake_log) + return LabMcp({console: profile_status.reader}, statuses={console: profile_status}, read_only=True) + + +def handle(mcp: LabMcp, message: Any) -> Optional[Dict[str, Any]]: + """One JSON-RPC message in, the reply out (None for notifications and client responses).""" + if not isinstance(message, dict) or message.get('jsonrpc') != '2.0': + return {'jsonrpc': '2.0', 'id': None, 'error': {'code': INVALID_REQUEST, 'message': + 'Expected one JSON-RPC 2.0 message'}} + if 'method' not in message or 'id' not in message: + return None + method = message['method'] + params = message.get('params') or {} + if not isinstance(params, dict): + return {'jsonrpc': '2.0', 'id': message['id'], + 'error': {'code': INVALID_PARAMS, 'message': 'params must be an object'}} + try: + if method == 'initialize': + asked = params.get('protocolVersion') + result = {'protocolVersion': asked if asked in PROTOCOL_VERSIONS else PROTOCOL_VERSIONS[0], + 'capabilities': {'resources': {}, 'tools': {}}, + 'serverInfo': dict(SERVER_INFO, name='pa-lab-readonly'), 'instructions': INSTRUCTIONS} + else: + result = mcp.call(method, params, client='stdio') + except RpcError as e: + error = {'code': e.code, 'message': e.message} + if e.data is not None: + error['data'] = e.data + return {'jsonrpc': '2.0', 'id': message['id'], 'error': error} + except Exception: + LOG.exception('method %s failed', method) + return {'jsonrpc': '2.0', 'id': message['id'], 'error': {'code': -32603, 'message': 'Internal error'}} + return {'jsonrpc': '2.0', 'id': message['id'], 'result': result} + + +def serve(mcp: LabMcp, stdin: IO[str], stdout: IO[str]) -> None: + for line in stdin: + if not line.strip(): + continue + try: + message = json.loads(line) + except ValueError: + reply = {'jsonrpc': '2.0', 'id': None, 'error': {'code': PARSE_ERROR, 'message': 'Parse error'}} + else: + reply = handle(mcp, message) + if reply is not None: + stdout.write(json.dumps(reply, ensure_ascii=False) + '\n') + stdout.flush() + + +def main(profile_dir: str, keepawake_log: Optional[str]) -> int: + logging.basicConfig(level=logging.INFO, format='%(asctime)s %(name)s %(message)s', stream=sys.stderr) + path = Path(profile_dir).expanduser() + if not path.is_dir(): + print('error --profile-dir {} is not a directory'.format(path), file=sys.stderr) + return 1 + mcp = make_mcp(path, keepawake_log=Path(keepawake_log).expanduser() if keepawake_log else None) + LOG.info('serving console B read-only from %s on stdio', path) + serve(mcp, sys.stdin, sys.stdout) + return 0 diff --git a/lab/server/smoke_readonly.py b/lab/server/smoke_readonly.py new file mode 100644 index 0000000000..80ae9ed6e3 --- /dev/null +++ b/lab/server/smoke_readonly.py @@ -0,0 +1,62 @@ +"""Smoke test: start the read-only stdio server the way .mcp.json does and call console_status once. + + ~/.venvs/lab-claude/bin/python lab/server/smoke_readonly.py [PROFILE_DIR] + +It only reads files: the server it starts serves no tool that writes into Lab/inbox. Prints the +tool list and the console_status result; exit 0 when both came back, 1 otherwise. +""" + +import json +import os +from pathlib import Path +import select +import subprocess +import sys + +SERVER_DIR = Path(__file__).resolve().parent +DEFAULT_PROFILE = Path.home() / 'Library/Application Support/SerialPrograms/Profiles/lab-B' +REPLY_TIMEOUT_S = 15 + + +def main(argv) -> int: + profile = Path(argv[1]) if len(argv) > 1 else DEFAULT_PROFILE + env = dict(os.environ, PYTHONPATH=str(SERVER_DIR)) + proc = subprocess.Popen([sys.executable, '-m', 'pa_lab', 'serve-stdio', '--profile-dir', str(profile)], + stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, + text=True, env=env) + + def ask(message): + proc.stdin.write(json.dumps(message) + '\n') + proc.stdin.flush() + if 'id' not in message: + return None + ready, _, _ = select.select([proc.stdout], [], [], REPLY_TIMEOUT_S) + if not ready: + raise TimeoutError('no reply to {} within {} s'.format(message['method'], REPLY_TIMEOUT_S)) + return json.loads(proc.stdout.readline()) + + try: + init = ask({'jsonrpc': '2.0', 'id': 1, 'method': 'initialize', + 'params': {'protocolVersion': '2025-06-18', 'capabilities': {}, + 'clientInfo': {'name': 'smoke'}}}) + print('server:', init['result']['serverInfo']) + ask({'jsonrpc': '2.0', 'method': 'notifications/initialized'}) + tools = ask({'jsonrpc': '2.0', 'id': 2, 'method': 'tools/list'}) + print('tools:', [t['name'] for t in tools['result']['tools']]) + reply = ask({'jsonrpc': '2.0', 'id': 3, 'method': 'tools/call', + 'params': {'name': 'console_status', 'arguments': {'console': 'B', 'log_lines': 5}}}) + print(json.dumps(reply['result']['structuredContent'], indent=2, ensure_ascii=False)) + return 1 if reply['result']['isError'] else 0 + except (TimeoutError, KeyError, ValueError) as e: + print('smoke failed: {}'.format(e)) + return 1 + finally: + proc.stdin.close() + try: + proc.wait(timeout=5) + except subprocess.TimeoutExpired: + proc.kill() + + +if __name__ == '__main__': + sys.exit(main(sys.argv)) diff --git a/lab/server/tests/test_status_readonly.py b/lab/server/tests/test_status_readonly.py new file mode 100644 index 0000000000..34480afcf5 --- /dev/null +++ b/lab/server/tests/test_status_readonly.py @@ -0,0 +1,132 @@ +"""console_status and the read-only stdio server against a fake profile folder. + +Run from the repo root: python3 -m unittest discover -s lab/server/tests -t lab/server -v +""" + +import io +import json +import os +from pathlib import Path +import tempfile +import unittest + +from pa_lab import control, db, mcp_server, status, stdio_server + +LOG = """2026-11-15 00:10:00.000001 - [Console 0]: Program State: RUNNING +2026-11-15 00:10:01.000001 - [Console 0]: Starting Program: PokemonFRLG:AutoStory +2026-11-15 00:10:05.000001 - [Console 0]: issue_buttons(): B, delay = 580ms, hold = 80ms, cooldown = 0ms +2026-11-15 00:10:06.000001 - [Console 0]: issue_nop(): delay = 80ms +2026-11-15 00:11:00.000001 - [Console 0]: [Checkpoint] 10.01: failed after 54 s +2026-11-15 00:11:01.000001 - [Console 0]: Program State: STOPPED +""" + + +def fake_profile(root: Path) -> Path: + profile = root / 'lab-B' + (profile / 'Lab' / 'inbox').mkdir(parents=True) + (profile / 'Lab' / 'state').write_text( + 'seq=keepawake35\nstate=STOPPED\nprogram=PokemonFRLG:AutoStory\ncontroller=ready\nowner=secret\nerror=\n') + (profile / 'SerialPrograms.log').write_text(LOG) + failures = profile / 'Screenshots' / 'AutoStory' / 'failures' + failures.mkdir(parents=True) + (failures / 'old.png').write_bytes(b'x') + os.utime(failures / 'old.png', (1000, 1000)) + (failures / 'new.png').write_bytes(b'x') + os.utime(failures / 'new.png', (2000, 2000)) + (profile / 'Screenshots' / 'shot.jpg').write_bytes(b'x') + os.utime(profile / 'Screenshots' / 'shot.jpg', (3000, 3000)) + return profile + + +class ConsoleStatusTest(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.root = Path(self.tmp.name) + self.profile = fake_profile(self.root) + keepawake = self.root / 'keepawake.log' + keepawake.write_text('00:09:14 idle 182s: pressed B\n00:12:15 idle 181s: pressed B\n') + self.status = status.ProfileStatus('B', self.profile, keepawake_log=keepawake, + find_app=lambda profile: {'pid': 42, 'deployment': 'slot-B/x'}) + + def tearDown(self): + self.tmp.cleanup() + + def test_reports_what_checkin_reports(self): + doc = self.status.console_status(3) + self.assertEqual(doc['app'], {'pid': 42, 'deployment': 'slot-B/x'}) + self.assertEqual(doc['lab_state']['state'], 'STOPPED') + self.assertNotIn('owner', doc['lab_state']) + self.assertIn('Program State: STOPPED', doc['program_state']) + self.assertEqual(len(doc['last_run']), 2) + self.assertIn('Starting Program', doc['last_run'][0]) + self.assertIn('10.01: failed', doc['last_run'][1]) + self.assertEqual(doc['last_press'], '00:10:05') + self.assertEqual(doc['keepawake'], '00:12:15 idle 181s: pressed B') + self.assertTrue(doc['newest_failure_frame'].endswith('failures/new.png')) + self.assertTrue(doc['newest_screenshot'].endswith('Screenshots/shot.jpg')) + self.assertEqual(len(doc['log_tail']), 3) + self.assertEqual(doc['console_state']['availability'], + {'state': 'unavailable', 'reason': 'no_state_file'}) + + def test_empty_profile_reports_nothing_known(self): + empty = self.root / 'empty' + empty.mkdir() + doc = status.ProfileStatus('B', empty, find_app=lambda profile: None).console_status() + self.assertIsNone(doc['lab_state']) + self.assertIsNone(doc['program_state']) + self.assertEqual(doc['last_run'], []) + self.assertIsNone(doc['newest_failure_frame']) + self.assertIsNone(doc['newest_screenshot']) + + +class ReadOnlyServerTest(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.profile = fake_profile(Path(self.tmp.name)) + self.mcp = stdio_server.make_mcp(self.profile) + + def tearDown(self): + self.tmp.cleanup() + + def test_lists_only_console_status(self): + self.assertEqual([t['name'] for t in self.mcp.call('tools/list', {})['tools']], ['console_status']) + + def test_inbox_and_control_tools_are_refused_and_write_nothing(self): + for name in ('shot', 'describe_program', 'game_open', 'ensure_game', 'acquire_console', 'next_events'): + with self.assertRaises(mcp_server.RpcError, msg=name): + self.mcp.call('tools/call', {'name': name, 'arguments': {'console': 'B'}}) + self.assertEqual(list((self.profile / 'Lab' / 'inbox').iterdir()), []) + + def test_read_only_refuses_a_control_plane(self): + with tempfile.TemporaryDirectory() as d: + plane = control.ControlPlane(db.Database(Path(d) / 'c.sqlite'), ['B']) + with self.assertRaises(ValueError): + mcp_server.LabMcp({}, control_plane=plane, read_only=True) + + def test_console_status_refuses_bad_arguments(self): + for arguments in ({'console': 'A'}, {'console': 'B', 'log_lines': 1000}, {'console': 'B', 'x': 1}): + result = self.mcp.call('tools/call', {'name': 'console_status', 'arguments': arguments}) + self.assertTrue(result['isError'], arguments) + + def test_stdio_round_trip(self): + requests = [ + {'jsonrpc': '2.0', 'id': 1, 'method': 'initialize', + 'params': {'protocolVersion': '2025-06-18', 'capabilities': {}, 'clientInfo': {'name': 't'}}}, + {'jsonrpc': '2.0', 'method': 'notifications/initialized'}, + {'jsonrpc': '2.0', 'id': 2, 'method': 'tools/call', + 'params': {'name': 'console_status', 'arguments': {'console': 'B', 'log_lines': 1}}}, + {'jsonrpc': '2.0', 'id': 3, 'method': 'resources/read', 'params': {'uri': 'console://B/state'}}, + ] + out = io.StringIO() + stdio_server.serve(self.mcp, io.StringIO(''.join(json.dumps(r) + '\n' for r in requests) + 'not json\n'), out) + replies = [json.loads(line) for line in out.getvalue().splitlines()] + self.assertEqual([r['id'] for r in replies], [1, 2, 3, None]) + self.assertEqual(replies[0]['result']['serverInfo']['name'], 'pa-lab-readonly') + self.assertFalse(replies[1]['result']['isError']) + self.assertEqual(replies[1]['result']['structuredContent']['lab_state']['state'], 'STOPPED') + self.assertIn('no_state_file', replies[2]['result']['contents'][0]['text']) + self.assertEqual(replies[3]['error']['code'], mcp_server.PARSE_ERROR) + + +if __name__ == '__main__': + unittest.main() diff --git a/skills/dispatch/SKILL.md b/skills/dispatch/SKILL.md index cc598456f5..93da178e4b 100644 --- a/skills/dispatch/SKILL.md +++ b/skills/dispatch/SKILL.md @@ -89,6 +89,11 @@ A lane never goes `idle` without a `next`; if the queue is empty, `next` = "plan 4. ASK → repeat the open question to the user in one line (once per 2 h), keep the lane waiting-user. 5. Pulse sentence names what the tick started. Skip the tick while the user is driving B or mid-conversation. +Console B state for the tick: call the pa-lab MCP tool `console_status` (`{"console": "B"}`; read-only, it +only reads lab-B's files) when the server is loaded (`/mcp` lists `pa-lab`); otherwise run `sh ~/BDSPLab/checkin.sh`. +Both report the same app pid, Lab/state, last run lines, last press and newest failure frame; checkin.sh adds +PR checks, spend and disk. Server setup: [lab/server/README.md](../../lab/server/README.md#read-only-stdio-mode-mcpjson). + ### Loop Install with `/loop 10m` and this prompt, verbatim: