From 03f391eb6fdd2e0f7533314b18fdb6d386888339 Mon Sep 17 00:00:00 2001 From: Alex Chapin Date: Sun, 20 Sep 2026 18:16:36 +0000 Subject: [PATCH 1/4] Add foreman MCP decision tool (ask_foreman) Implements #13: a stdio MCP server exposing the foreman as an autonomous decision-maker inside interactive coding sessions. - New decision models: AbstainCategory (destructive/irreversible/external/ credentials), DecisionRequest, Decision, plus a FOREMAN_DECIDED event type. - ForemanModel protocol gains decide(); JevForemanModel implements it with a dedicated Noul prompt (option scores, per-category risk scores, explicit should-abstain); FakeForemanModel gets a deterministic stub for offline tests. - New decision_policy module: effective policy merges the server baseline with the request tighten-only (max threshold, union denylist); apply_policy answers only confident, valid, denylist-clean verdicts, otherwise abstains. - New foreman.mcp stdio JSON-RPC 2.0 server with an ask_foreman tool; every decision is logged to .foreman/runs//events.jsonl. - foreman mcp CLI command; foreman inspect renders FOREMAN_DECIDED events. - Config: FOREMAN_DECISION_THRESHOLD (default 0.80) and FOREMAN_ALWAYS_ABSTAIN (comma-separated, default all four categories). - Tests: test_decision_policy.py, test_mcp_server.py; docs/mcp.md. --- README.md | 7 + docs/mcp.md | 78 +++++++++ src/foreman/cli.py | 35 ++++ src/foreman/config.py | 26 +++ src/foreman/decision_policy.py | 86 ++++++++++ src/foreman/foreman/base.py | 12 +- src/foreman/foreman/jev.py | 203 +++++++++++++++++++++-- src/foreman/foreman/simulation.py | 33 +++- src/foreman/mcp/__init__.py | 5 + src/foreman/mcp/server.py | 267 ++++++++++++++++++++++++++++++ src/foreman/models/__init__.py | 4 + src/foreman/models/decision.py | 60 +++++++ src/foreman/models/events.py | 1 + tests/test_decision_policy.py | 126 ++++++++++++++ tests/test_mcp_server.py | 178 ++++++++++++++++++++ 15 files changed, 1107 insertions(+), 14 deletions(-) create mode 100644 docs/mcp.md create mode 100644 src/foreman/decision_policy.py create mode 100644 src/foreman/mcp/__init__.py create mode 100644 src/foreman/mcp/server.py create mode 100644 src/foreman/models/decision.py create mode 100644 tests/test_decision_policy.py create mode 100644 tests/test_mcp_server.py diff --git a/README.md b/README.md index 3f9803c..3252cc1 100644 --- a/README.md +++ b/README.md @@ -127,6 +127,13 @@ exec backend. Live steering into an active turn is only available with the Codex backend; other backends degrade to stop/retry. See [Worker backends](docs/workers.md) for the `Worker` protocol and how to add your own. +### Foreman inside your own session + +`foreman mcp` exposes the foreman as an MCP decision tool (`ask_foreman`) for +interactive coding sessions you drive yourself: the agent delegates its +multiple-choice questions to the foreman instead of asking you. See +[Foreman as an MCP decision tool](docs/mcp.md). + ## What Foreman watches Each observation is compact and bounded. It contains: diff --git a/docs/mcp.md b/docs/mcp.md new file mode 100644 index 0000000..eb12c69 --- /dev/null +++ b/docs/mcp.md @@ -0,0 +1,78 @@ +# Foreman as an MCP decision tool + +`foreman mcp` starts a stdio MCP server (minimal JSON-RPC 2.0, no extra +dependencies) exposing one tool, `ask_foreman`. Add it to your coding +agent's MCP configuration and the agent can delegate multiple-choice +questions to the foreman instead of asking you: + +```bash +foreman mcp --repo ./my-project +``` + +The server needs `TYPESAFE_API_KEY` like `foreman run` does (from the +repo's `.env` or the environment). + +## The `ask_foreman` tool + +```json +{ + "question": "Should I use a join or a subquery here?", + "options": ["join", "subquery"], + "context": "Refactoring the slow report query; both pass the tests.", + "session_id": "optional, defaults to one id per server process", + "risk_hint": "optional advisory hint about what the question involves", + "extra_abstain_categories": ["external"], + "min_confidence": 0.9 +} +``` + +The foreman classifies the question, picks one of the options (or abstains +outright), and reports its confidence. The response is one of: + +```json +{"status": "answered", "choice": "join", "rationale": "..."} +{"status": "abstained", "rationale": "..."} +``` + +When the foreman abstains, hand the question to the human. Abstaining never +terminates or escalates anything — unlike the supervision loop's `ESCALATE`, +which stops the run. + +## Policy semantics + +An answer is returned only when **all** of these hold: + +1. the model did not abstain on its own, +2. its confidence is at or above the effective threshold, +3. the choice is one of the offered options, +4. the question's classification does not intersect the effective denylist. + +The policy is layered and tighten-only: + +- **Server-side baseline** (the safety floor): `FOREMAN_DECISION_THRESHOLD` + (default `0.80`) and `FOREMAN_ALWAYS_ABSTAIN` (comma-separated list, + default all four categories). The caller cannot weaken these. +- **Per-call** `min_confidence` and `extra_abstain_categories` can only + tighten: the effective threshold is the maximum of the two, and the + effective denylist is the union of both. + +Question classification happens server-side in the decision prompt; the +caller's `risk_hint` is advisory. A dead decision model degrades to an +abstention, not a crash. + +## Abstain categories + +| Category | Meaning | +|----------------|----------------------------------------------------------------| +| `destructive` | Deletes or corrupts data or state | +| `irreversible` | Cannot be taken back: publishing, notifying, merging | +| `external` | Side effects beyond the local machine, incl. cost and exfiltration | +| `credentials` | Authentication material, permission grants, signing | + +## Decision log + +Every decision and abstention is appended as a `FOREMAN_DECIDED` event to +the repository's `.foreman/runs//events.jsonl`, recording the +question, classification, choice, confidence, and the effective policy — so +`foreman inspect ` shows the MCP-mode history and you can tune +the threshold and denylist from evidence. diff --git a/src/foreman/cli.py b/src/foreman/cli.py index cf930ba..83b82ee 100644 --- a/src/foreman/cli.py +++ b/src/foreman/cli.py @@ -13,6 +13,7 @@ from foreman.config import FactoryConfig from foreman.foreman import FakeForemanModel, JevForemanModel +from foreman.mcp import MCPServer from foreman.models import EventType, FactoryStatus, WorkerType from foreman.persistence import PersistenceError, RunStore from foreman.runtime import FactoryRuntime @@ -67,6 +68,33 @@ def run( raise typer.Exit(code=1) +@app.command() +def mcp( + repo: Annotated[ + Path, + typer.Option("--repo", exists=True, file_okay=False, resolve_path=True), + ] = Path("."), +) -> None: + """Start a stdio MCP server exposing the foreman as a decision tool.""" + + load_dotenv(repo / ".env", override=False) + load_dotenv(override=False) + if not os.getenv("TYPESAFE_API_KEY"): + console.print( + "Missing TYPESAFE_API_KEY. Copy .env.example to .env and add your TypeSafe API key." + ) + raise typer.Exit(code=2) + config = FactoryConfig.from_environment() + model = JevForemanModel(timeout_seconds=config.jev_timeout_seconds) + server = MCPServer(repository=repo, model=model, config=config) + try: + asyncio.run(server.serve_stdio()) + except KeyboardInterrupt: + raise typer.Exit(code=130) from None + finally: + asyncio.run(model.close()) + + @app.command() def demo( repo: Annotated[ @@ -178,6 +206,13 @@ def inspect_run( console.print(f" {label:<16} {float(assessment[key]):.2f}") elif event.event_type is EventType.FOREMAN_INTERVENED: console.print(f" {payload.get('action')}: {payload.get('reason', '')}") + elif event.event_type is EventType.FOREMAN_DECIDED: + status = "answered" if payload.get("answered") else "abstained" + console.print(f"{prefix} Foreman decided: {status}") + console.print(f" choice: {payload.get('choice')}") + console.print( + f" confidence: {float(payload.get('confidence', 0.0)):.2f}" + ) elif event.event_type in {EventType.WORKER_STEERED, EventType.WORKER_STEER_FAILED}: label = "steered" if event.event_type is EventType.WORKER_STEERED else "steer failed" console.print(f"{prefix} {payload.get('worker_id')} {label}") diff --git a/src/foreman/config.py b/src/foreman/config.py index dfeb251..1b42d5f 100644 --- a/src/foreman/config.py +++ b/src/foreman/config.py @@ -6,6 +6,8 @@ from pydantic import BaseModel, ConfigDict, Field +from foreman.models import AbstainCategory + def _environment_bool(value: str) -> bool: normalized = value.strip().lower() @@ -16,6 +18,24 @@ def _environment_bool(value: str) -> bool: raise ValueError(f"invalid boolean environment value: {value!r}") +def _environment_abstain_categories(value: str) -> list[AbstainCategory]: + """Parse a comma-separated FOREMAN_ALWAYS_ABSTAIN value.""" + + categories: list[AbstainCategory] = [] + for raw in value.split(","): + name = raw.strip().lower() + if not name: + continue + try: + categories.append(AbstainCategory(name)) + except ValueError as error: + valid = ", ".join(category.value for category in AbstainCategory) + raise ValueError( + f"invalid abstain category {raw!r}; expected one of: {valid}" + ) from error + return categories + + class FactoryConfig(BaseModel): model_config = ConfigDict(extra="forbid") @@ -40,6 +60,10 @@ class FactoryConfig(BaseModel): off_track_threshold: float = Field(default=0.80, ge=0.0, le=1.0) agents_drift_threshold: float = Field(default=0.80, ge=0.0, le=1.0) stuck_threshold: float = Field(default=0.80, ge=0.0, le=1.0) + decision_threshold: float = Field(default=0.80, ge=0.0, le=1.0) + always_abstain: list[AbstainCategory] = Field( + default_factory=lambda: list(AbstainCategory) + ) verification_threshold: float = Field(default=0.65, ge=0.0, le=1.0) finish_threshold: float = Field(default=0.75, ge=0.0, le=1.0) requirements_threshold: float = Field(default=0.75, ge=0.0, le=1.0) @@ -71,6 +95,8 @@ def from_environment(cls) -> FactoryConfig: "max_consecutive_assessment_failures", int, ), + "FOREMAN_DECISION_THRESHOLD": ("decision_threshold", float), + "FOREMAN_ALWAYS_ABSTAIN": ("always_abstain", _environment_abstain_categories), "FOREMAN_CODEX_BACKEND": ("codex_backend", str), "FOREMAN_STEERING_ENABLED": ( "steering_enabled", diff --git a/src/foreman/decision_policy.py b/src/foreman/decision_policy.py new file mode 100644 index 0000000..118d7fb --- /dev/null +++ b/src/foreman/decision_policy.py @@ -0,0 +1,86 @@ +from __future__ import annotations + +from collections.abc import Collection, Sequence +from dataclasses import dataclass + +from foreman.config import FactoryConfig +from foreman.models import AbstainCategory, Decision, DecisionRequest + + +@dataclass(frozen=True, slots=True) +class EffectivePolicy: + """The merged safety policy for one decision request. + + The caller's request can only tighten the baseline: the effective + threshold is the maximum of the two, and the effective denylist is the + union of both. A caller can never loosen foreman's safety floor. + """ + + threshold: float + denylist: frozenset[AbstainCategory] + + +@dataclass(frozen=True, slots=True) +class PolicyOutcome: + answered: bool + choice: str | None + rationale: str + + +def effective_policy( + config: FactoryConfig, request: DecisionRequest +) -> EffectivePolicy: + """Merge the configured baseline with one request, tighten-only.""" + + requested = ( + request.min_confidence if request.min_confidence is not None else 0.0 + ) + return EffectivePolicy( + threshold=max(config.decision_threshold, requested), + denylist=frozenset(config.always_abstain) + | frozenset(request.extra_abstain_categories), + ) + + +def apply_policy( + decision: Decision, + *, + threshold: float, + denylist: Collection[AbstainCategory], + options: Sequence[str], +) -> PolicyOutcome: + """Decide whether the model's verdict may be returned as an answer. + + Anything short of a confident, valid, denylist-clean verdict becomes an + abstention: the question goes back to the human, and nothing is + terminated or escalated. + """ + + problems: list[str] = [] + if decision.abstained: + problems.append("the foreman model abstained") + if decision.confidence < threshold: + problems.append( + f"confidence {decision.confidence:.2f} is below the " + f"{threshold:.2f} threshold" + ) + if decision.choice is None or decision.choice not in options: + problems.append("the choice is not one of the offered options") + denied = set(decision.classification) & set(denylist) + if denied: + names = ", ".join(sorted(category.value for category in denied)) + problems.append(f"the question is classified as {names}, which must abstain") + if problems: + return PolicyOutcome( + answered=False, + choice=None, + rationale=( + "Abstained: " + "; ".join(problems) + ". " + f"Model rationale: {decision.rationale}" + ), + ) + return PolicyOutcome( + answered=True, + choice=decision.choice, + rationale=decision.rationale, + ) diff --git a/src/foreman/foreman/base.py b/src/foreman/foreman/base.py index 43923d0..0ab8d30 100644 --- a/src/foreman/foreman/base.py +++ b/src/foreman/foreman/base.py @@ -2,7 +2,7 @@ from typing import Protocol -from foreman.models import FactoryAssessment +from foreman.models import Decision, DecisionRequest, FactoryAssessment from foreman.observation import FactoryObservation @@ -13,5 +13,13 @@ class ForemanModelError(RuntimeError): class ForemanModel(Protocol): async def assess(self, observation: FactoryObservation) -> FactoryAssessment: ... - async def close(self) -> None: ... + async def decide(self, request: DecisionRequest) -> Decision: + """Answer one multiple-choice question or abstain. + + The returned Decision is the model's raw judgment; the decision + policy applies the configured confidence threshold and abstain + denylist before any answer reaches the caller. + """ + ... + async def close(self) -> None: ... diff --git a/src/foreman/foreman/jev.py b/src/foreman/foreman/jev.py index f3eff0c..b3dd5f6 100644 --- a/src/foreman/foreman/jev.py +++ b/src/foreman/foreman/jev.py @@ -6,7 +6,7 @@ from typing import Any from foreman.foreman.base import ForemanModelError -from foreman.models import FactoryAssessment +from foreman.models import AbstainCategory, Decision, DecisionRequest, FactoryAssessment from foreman.observation import FactoryObservation ASSESSMENT_QUESTIONS: dict[str, str] = { @@ -85,6 +85,136 @@ def parse_jev_response(response: Any) -> FactoryAssessment: return normalize_assessment(values) +ABSTAIN_CATEGORY_QUESTIONS: dict[AbstainCategory, str] = { + AbstainCategory.DESTRUCTIVE: ( + "Would answering this question, or acting on the answer, delete or corrupt " + "data or state (removing files, dropping databases, force-pushing, tearing " + "down infrastructure)?" + ), + AbstainCategory.IRREVERSIBLE: ( + "Would answering this question, or acting on the answer, do something that " + "cannot be taken back (publishing a release, sending notifications or " + "email, merging)?" + ), + AbstainCategory.EXTERNAL: ( + "Would answering this question, or acting on the answer, cause side effects " + "beyond the local machine (mutating remote APIs, deployments, webhooks, " + "anything cost-incurring, exfiltration of code or data to third parties)?" + ), + AbstainCategory.CREDENTIALS: ( + "Would answering this question, or acting on the answer, touch " + "authentication material (reading or using tokens and secrets, granting " + "permissions, signing artifacts)?" + ), +} + +SHOULD_ABSTAIN_INSTRUCTIONS = ( + "Should this question be left to the human instead of answered autonomously? " + "Answer yes when the question is ambiguous, the options are all poor, the " + "stakes are high, or the right answer depends on judgment only the human has." +) + +_SHOULD_ABSTAIN_NAME = "should_abstain" +_CLASSIFICATION_THRESHOLD = 0.5 + + +def _decision_option_name(index: int) -> str: + return f"option_{index}" + + +def _decision_risk_name(category: AbstainCategory) -> str: + return f"risk_{category.value}" + + +def _extract_noul_score(response: Any, name: str) -> float: + """Read one Noul probability from an SDK response or a test double.""" + + raw: Any = None + nouls = getattr(response, "nouls", None) + if nouls is not None: + answer = nouls.get(name) + if answer is not None: + raw = getattr(answer, "noul", None) + elif isinstance(response, Mapping): + answers = response.get("answers", response) + if isinstance(answers, Mapping): + answer = answers.get(name) + if isinstance(answer, Mapping): + raw = answer.get("noul") + elif answer is not None: + raw = answer + if isinstance(raw, bool) or not isinstance(raw, (int, float)): + raise ForemanModelError(f"Jev decision answer {name!r} is not numeric") + value = float(raw) + if not isfinite(value): + raise ForemanModelError(f"Jev decision answer {name!r} is not finite") + return min(1.0, max(0.0, value)) + + +def build_decision( + *, + options: list[str], + option_scores: list[float], + risk_scores: dict[AbstainCategory, float], + abstain_score: float, +) -> Decision: + """Translate raw Noul scores into a Decision. + + The model classifies the question, picks the best-scoring option, and may + abstain outright. The decision policy still applies the configured + confidence threshold and denylist afterwards. + """ + + classification = [ + category + for category in AbstainCategory + if risk_scores[category] >= _CLASSIFICATION_THRESHOLD + ] + best_index = max(range(len(options)), key=lambda index: option_scores[index]) + scored = ", ".join( + f"{option!r}={score:.2f}" + for option, score in zip(options, option_scores, strict=True) + ) + if abstain_score >= _CLASSIFICATION_THRESHOLD: + return Decision( + choice=None, + confidence=abstain_score, + rationale=( + f"abstained (should_abstain={abstain_score:.2f}); best option " + f"{options[best_index]!r} scored {option_scores[best_index]:.2f}; " + f"options: {scored}" + ), + classification=classification, + abstained=True, + ) + return Decision( + choice=options[best_index], + confidence=option_scores[best_index], + rationale=( + f"chose {options[best_index]!r} " + f"(score {option_scores[best_index]:.2f}); options: {scored}" + ), + classification=classification, + abstained=False, + ) + + +def _noul_type(client: Any | None) -> Any: + """Return the SDK Noul class, or a test-double stand-in when injected.""" + + try: + from typesafe_sdk import Noul + except ImportError as error: + if client is None: + raise ForemanModelError("typesafe-sdk is not installed") from error + + class Noul: # type: ignore[no-redef] + def __init__(self, *, instructions: str) -> None: + self.instructions = instructions + + return Noul + + class JevForemanModel: """Adapter for TypeSafe's official asynchronous Python SDK.""" @@ -99,7 +229,6 @@ def __init__( self.timeout_seconds = timeout_seconds self.model = model self._owns_client = client is None - def _make_client(self) -> Any: try: from typesafe_sdk import AsyncTypeSafeClient, RetryPolicy @@ -119,15 +248,7 @@ def _make_client(self) -> Any: ) async def assess(self, observation: FactoryObservation) -> FactoryAssessment: - try: - from typesafe_sdk import Noul - except ImportError as error: - if self._client is None: - raise ForemanModelError("typesafe-sdk is not installed") from error - - class Noul: # type: ignore[no-redef] - def __init__(self, *, instructions: str) -> None: - self.instructions = instructions + Noul = _noul_type(self._client) # One API call evaluates all atomic dimensions in parallel against the same state. questions = { @@ -157,6 +278,66 @@ def __init__(self, *, instructions: str) -> None: message = f"Jev assessment failed: {type(error).__name__}: {error}" raise ForemanModelError(message) from error + async def decide(self, request: DecisionRequest) -> Decision: + """Classify the question, pick the best option, or abstain. + + One API call scores every option, every abstain category, and an + explicit should-abstain question in parallel. The decision policy + applies the configured confidence threshold and denylist afterwards. + """ + + Noul = _noul_type(self._client) + questions = { + _decision_option_name(index): Noul( + instructions=( + f"Is {option!r} the best answer to the question? Consider the " + "question, the other options, and the context." + ) + ) + for index, option in enumerate(request.options) + } + for category, instructions in ABSTAIN_CATEGORY_QUESTIONS.items(): + questions[_decision_risk_name(category)] = Noul(instructions=instructions) + questions[_SHOULD_ABSTAIN_NAME] = Noul( + instructions=SHOULD_ABSTAIN_INSTRUCTIONS + ) + + client = self._client or self._make_client() + if self._client is None: + self._client = client + try: + response = await asyncio.wait_for( + client.system_one( + state=request.model_dump(mode="json"), + questions=questions, + model=self.model, + timeout=self.timeout_seconds, + ), + timeout=self.timeout_seconds + 0.5, + ) + option_scores = [ + _extract_noul_score(response, _decision_option_name(index)) + for index in range(len(request.options)) + ] + risk_scores = { + category: _extract_noul_score(response, _decision_risk_name(category)) + for category in AbstainCategory + } + abstain_score = _extract_noul_score(response, _SHOULD_ABSTAIN_NAME) + return build_decision( + options=request.options, + option_scores=option_scores, + risk_scores=risk_scores, + abstain_score=abstain_score, + ) + except TimeoutError as error: + raise ForemanModelError("Jev decision timed out") from error + except ForemanModelError: + raise + except Exception as error: + message = f"Jev decision failed: {type(error).__name__}: {error}" + raise ForemanModelError(message) from error + async def close(self) -> None: if self._owns_client and self._client is not None: close = getattr(self._client, "aclose", None) diff --git a/src/foreman/foreman/simulation.py b/src/foreman/foreman/simulation.py index 35bab62..eff9802 100644 --- a/src/foreman/foreman/simulation.py +++ b/src/foreman/foreman/simulation.py @@ -3,7 +3,7 @@ import asyncio from collections.abc import Sequence -from foreman.models import FactoryAssessment +from foreman.models import Decision, DecisionRequest, FactoryAssessment from foreman.observation import FactoryObservation DEMO_ASSESSMENTS = [ @@ -65,16 +65,20 @@ def __init__( self, assessments: Sequence[FactoryAssessment] | None = None, *, + decisions: Sequence[Decision] | None = None, delay_seconds: float = 0.0, repeat_last: bool = True, ) -> None: self.assessments = list(assessments or DEMO_ASSESSMENTS) if not self.assessments: raise ValueError("at least one fake assessment is required") + self.decisions = list(decisions or []) self.delay_seconds = delay_seconds self.repeat_last = repeat_last self.calls: list[FactoryObservation] = [] + self.decision_calls: list[DecisionRequest] = [] self._index = 0 + self._decision_index = 0 async def assess(self, observation: FactoryObservation) -> FactoryAssessment: self.calls.append(observation) @@ -90,3 +94,30 @@ async def assess(self, observation: FactoryObservation) -> FactoryAssessment: async def close(self) -> None: return None + + async def decide(self, request: DecisionRequest) -> Decision: + """Return a queued decision, or a deterministic default. + + Without queued decisions the fake answers with the first option at + high confidence, so offline tests exercise the answered path unless + they say otherwise. + """ + + self.decision_calls.append(request) + if self.delay_seconds: + await asyncio.sleep(self.delay_seconds) + if self.decisions: + if self._decision_index >= len(self.decisions): + if not self.repeat_last: + raise RuntimeError("fake decision sequence exhausted") + return self.decisions[-1].model_copy(deep=True) + decision = self.decisions[self._decision_index].model_copy(deep=True) + self._decision_index += 1 + return decision + return Decision( + choice=request.options[0], + confidence=0.95, + rationale="deterministic fake decision", + classification=[], + abstained=False, + ) diff --git a/src/foreman/mcp/__init__.py b/src/foreman/mcp/__init__.py new file mode 100644 index 0000000..da2a8e7 --- /dev/null +++ b/src/foreman/mcp/__init__.py @@ -0,0 +1,5 @@ +"""Foreman as an MCP decision tool for interactive coding sessions.""" + +from foreman.mcp.server import MCPServer + +__all__ = ["MCPServer"] diff --git a/src/foreman/mcp/server.py b/src/foreman/mcp/server.py new file mode 100644 index 0000000..8a6b7d7 --- /dev/null +++ b/src/foreman/mcp/server.py @@ -0,0 +1,267 @@ +from __future__ import annotations + +import asyncio +import json +import sys +from pathlib import Path +from typing import Any +from uuid import uuid4 + +from pydantic import ValidationError + +from foreman.config import FactoryConfig +from foreman.decision_policy import apply_policy, effective_policy +from foreman.foreman.base import ForemanModel, ForemanModelError +from foreman.models import ( + AbstainCategory, + Decision, + DecisionRequest, + EventType, + FactoryEvent, +) +from foreman.persistence import PersistenceError, RunStore +from foreman.version import __version__ + +MCP_PROTOCOL_VERSION = "2024-11-05" + +ASK_FOREMAN_TOOL: dict[str, Any] = { + "name": "ask_foreman", + "description": ( + "Ask the foreman to autonomously answer a multiple-choice question on " + "your behalf. The foreman classifies the question, picks one of the " + "options, and reports its confidence; a configured confidence threshold " + "and abstain denylist decide whether the answer is returned. When the " + "foreman abstains, hand the question to the human instead. Abstaining " + "never terminates or escalates anything." + ), + "inputSchema": { + "type": "object", + "properties": { + "question": { + "type": "string", + "description": "The question to decide, as asked to the human.", + }, + "options": { + "type": "array", + "items": {"type": "string"}, + "minItems": 1, + "description": "The offered answers; the foreman picks one or abstains.", + }, + "context": { + "type": "string", + "description": "What the agent is doing and why the question arose.", + }, + "session_id": { + "type": "string", + "description": ( + "Decision log session; defaults to one id per server process." + ), + }, + "risk_hint": { + "type": "string", + "description": "Advisory hint about what the question involves.", + }, + "extra_abstain_categories": { + "type": "array", + "items": { + "type": "string", + "enum": [category.value for category in AbstainCategory], + }, + "description": ( + "Extra abstain categories for this call only. These can only " + "tighten the server's denylist, never loosen it." + ), + }, + "min_confidence": { + "type": "number", + "minimum": 0, + "maximum": 1, + "description": ( + "Minimum confidence for this call only. The effective " + "threshold is the maximum of this and the server's." + ), + }, + }, + "required": ["question", "options"], + }, +} + + +def _error_response( + request_id: Any, code: int, message: str +) -> dict[str, Any]: + return { + "jsonrpc": "2.0", + "id": request_id, + "error": {"code": code, "message": message}, + } + + +def _result_response(request_id: Any, result: dict[str, Any]) -> dict[str, Any]: + return {"jsonrpc": "2.0", "id": request_id, "result": result} + + +class MCPServer: + """Minimal stdio JSON-RPC 2.0 MCP server exposing the foreman decider.""" + + def __init__( + self, + *, + repository: Path | str, + model: ForemanModel, + config: FactoryConfig | None = None, + session_id: str | None = None, + ) -> None: + self.repository = Path(repository).resolve() + self.model = model + self.config = config or FactoryConfig.from_environment() + self.session_id = session_id or uuid4().hex[:12] + self.store = RunStore(self.repository) + + def _resolve_session_id(self, requested: Any) -> str: + if isinstance(requested, str) and requested: + try: + self.store.run_dir(requested) + return requested + except PersistenceError: + pass + return self.session_id + + async def handle(self, message: Any) -> dict[str, Any] | None: + """Dispatch one JSON-RPC message; notifications get no response.""" + + if not isinstance(message, dict) or message.get("jsonrpc") != "2.0": + return _error_response(None, -32600, "invalid request") + method = message.get("method") + if not isinstance(method, str): + return _error_response(message.get("id"), -32600, "invalid request") + request_id = message.get("id") + if request_id is None: + # Notification: nothing in this server needs them. + return None + if method == "initialize": + return _result_response( + request_id, + { + "protocolVersion": MCP_PROTOCOL_VERSION, + "capabilities": {"tools": {}}, + "serverInfo": {"name": "foreman", "version": __version__}, + }, + ) + if method == "tools/list": + return _result_response(request_id, {"tools": [ASK_FOREMAN_TOOL]}) + if method == "tools/call": + return await self._handle_tool_call(request_id, message.get("params")) + return _error_response(request_id, -32601, f"unknown method {method!r}") + + async def _handle_tool_call( + self, request_id: Any, params: Any + ) -> dict[str, Any]: + if not isinstance(params, dict) or params.get("name") != "ask_foreman": + return _error_response(request_id, -32602, "unknown tool") + arguments = params.get("arguments") + if not isinstance(arguments, dict): + return _error_response(request_id, -32602, "tool arguments must be an object") + try: + decision_request = DecisionRequest( + question=arguments["question"], + options=arguments["options"], + context=arguments.get("context", ""), + risk_hint=arguments.get("risk_hint", ""), + extra_abstain_categories=arguments.get("extra_abstain_categories", []), + min_confidence=arguments.get("min_confidence"), + ) + except (KeyError, ValidationError) as error: + return _error_response(request_id, -32602, f"invalid params: {error}") + session_id = self._resolve_session_id(arguments.get("session_id")) + + policy = effective_policy(self.config, decision_request) + try: + decision = await self.model.decide(decision_request) + except ForemanModelError as error: + # A dead decider is not a crash: the question goes back to the human. + decision = Decision( + choice=None, + confidence=0.0, + rationale=f"decision model unavailable: {error}", + classification=[], + abstained=True, + ) + outcome = apply_policy( + decision, + threshold=policy.threshold, + denylist=policy.denylist, + options=decision_request.options, + ) + self.store.append_event( + FactoryEvent( + run_id=session_id, + event_type=EventType.FOREMAN_DECIDED, + payload={ + "question": decision_request.question, + "options": decision_request.options, + "classification": [ + category.value for category in decision.classification + ], + "choice": decision.choice, + "confidence": decision.confidence, + "answered": outcome.answered, + "rationale": outcome.rationale, + "effective_threshold": policy.threshold, + "effective_denylist": sorted( + category.value for category in policy.denylist + ), + }, + ) + ) + if outcome.answered: + result = { + "status": "answered", + "choice": outcome.choice, + "rationale": outcome.rationale, + } + else: + result = {"status": "abstained", "rationale": outcome.rationale} + return _result_response( + request_id, {"content": [{"type": "text", "text": json.dumps(result)}]} + ) + + async def serve_stdio(self) -> None: + """Serve JSON-RPC over stdio with LSP-style Content-Length framing.""" + + loop = asyncio.get_running_loop() + stdin = sys.stdin.buffer + stdout = sys.stdout.buffer + while True: + headers: dict[str, str] = {} + while True: + line = await loop.run_in_executor(None, stdin.readline) + if not line: + return + stripped = line.strip() + if not stripped: + break + name, _, value = stripped.decode("latin-1").partition(":") + headers[name.strip().lower()] = value.strip() + try: + length = int(headers.get("content-length", "0")) + except ValueError: + continue + body = await loop.run_in_executor(None, stdin.read, length) + if not body: + return + try: + message = json.loads(body) + except json.JSONDecodeError: + response: dict[str, Any] | None = _error_response( + None, -32700, "parse error" + ) + else: + response = await self.handle(message) + if response is None: + continue + payload = json.dumps(response).encode("utf-8") + stdout.write( + f"Content-Length: {len(payload)}\r\n\r\n".encode("latin-1") + payload + ) + stdout.flush() diff --git a/src/foreman/models/__init__.py b/src/foreman/models/__init__.py index d191223..2ddf74d 100644 --- a/src/foreman/models/__init__.py +++ b/src/foreman/models/__init__.py @@ -1,9 +1,13 @@ from foreman.models.assessment import FactoryAssessment +from foreman.models.decision import AbstainCategory, Decision, DecisionRequest from foreman.models.events import EventType, FactoryEvent, Intervention, InterventionType from foreman.models.state import FactoryState, FactoryStatus, VerificationResult from foreman.models.worker import WorkerRecord, WorkerStatus, WorkerType __all__ = [ + "AbstainCategory", + "Decision", + "DecisionRequest", "EventType", "FactoryAssessment", "FactoryEvent", diff --git a/src/foreman/models/decision.py b/src/foreman/models/decision.py new file mode 100644 index 0000000..3169eba --- /dev/null +++ b/src/foreman/models/decision.py @@ -0,0 +1,60 @@ +from __future__ import annotations + +from enum import StrEnum + +from pydantic import BaseModel, ConfigDict, Field + + +class AbstainCategory(StrEnum): + """Question categories the foreman must never answer on its own. + + These form the safety floor for autonomous decisions: a question + classified into a denylisted category is handed back to the human + instead of being answered, no matter how confident the model is. + """ + + DESTRUCTIVE = "destructive" + """Deletes or corrupts data or state: removing files, dropping databases, + force-pushing, tearing down infrastructure.""" + + IRREVERSIBLE = "irreversible" + """Cannot be taken back once done, even if nothing is destroyed: + publishing a release, sending notifications or email, merging.""" + + EXTERNAL = "external" + """Side effects beyond the local machine: mutating remote APIs, + deployments, webhooks, anything cost-incurring, and exfiltration of + code or data to third parties.""" + + CREDENTIALS = "credentials" + """Touches authentication material: reading or using tokens and secrets, + granting permissions, signing artifacts.""" + + +class DecisionRequest(BaseModel): + """A single question handed to the foreman for an autonomous decision.""" + + model_config = ConfigDict(extra="forbid") + + question: str = Field(min_length=1, max_length=10_000) + options: list[str] = Field(min_length=1, max_length=20) + context: str = Field(default="", max_length=20_000) + risk_hint: str = Field(default="", max_length=2_000) + extra_abstain_categories: list[AbstainCategory] = Field(default_factory=list) + min_confidence: float | None = Field(default=None, ge=0.0, le=1.0) + + +class Decision(BaseModel): + """The foreman model's raw verdict on a DecisionRequest. + + This is the model's judgment only; the decision policy applies the + configured threshold and denylist before an answer is returned. + """ + + model_config = ConfigDict(extra="forbid") + + choice: str | None = Field(default=None, max_length=5_000) + confidence: float = Field(ge=0.0, le=1.0) + rationale: str = Field(min_length=1, max_length=5_000) + classification: list[AbstainCategory] = Field(default_factory=list) + abstained: bool = False diff --git a/src/foreman/models/events.py b/src/foreman/models/events.py index 8afb856..c89a7b9 100644 --- a/src/foreman/models/events.py +++ b/src/foreman/models/events.py @@ -22,6 +22,7 @@ class EventType(StrEnum): FOREMAN_OBSERVED = "FOREMAN_OBSERVED" FOREMAN_ASSESSED = "FOREMAN_ASSESSED" FOREMAN_INTERVENED = "FOREMAN_INTERVENED" + FOREMAN_DECIDED = "FOREMAN_DECIDED" VERIFICATION_STARTED = "VERIFICATION_STARTED" VERIFICATION_COMPLETED = "VERIFICATION_COMPLETED" FACTORY_FINISHED = "FACTORY_FINISHED" diff --git a/tests/test_decision_policy.py b/tests/test_decision_policy.py new file mode 100644 index 0000000..053b276 --- /dev/null +++ b/tests/test_decision_policy.py @@ -0,0 +1,126 @@ +from __future__ import annotations + +from foreman.config import FactoryConfig +from foreman.decision_policy import EffectivePolicy, apply_policy, effective_policy +from foreman.models import AbstainCategory, Decision, DecisionRequest + + +def _request(**overrides) -> DecisionRequest: + fields: dict = {"question": "Which approach?", "options": ["a", "b"]} + fields.update(overrides) + return DecisionRequest(**fields) + + +def _decision(**overrides) -> Decision: + fields: dict = { + "choice": "a", + "confidence": 0.9, + "rationale": "a is best", + "classification": [], + "abstained": False, + } + fields.update(overrides) + return Decision(**fields) + + +def _config(**overrides) -> FactoryConfig: + fields: dict = { + "decision_threshold": 0.8, + "always_abstain": [AbstainCategory.DESTRUCTIVE], + } + fields.update(overrides) + return FactoryConfig(**fields) + + +def test_effective_policy_defaults_to_baseline(): + policy = effective_policy(_config(), _request()) + assert policy == EffectivePolicy( + threshold=0.8, denylist=frozenset({AbstainCategory.DESTRUCTIVE}) + ) + + +def test_effective_policy_request_can_raise_threshold_but_not_lower_it(): + raised = effective_policy(_config(), _request(min_confidence=0.95)) + assert raised.threshold == 0.95 + lowered = effective_policy(_config(), _request(min_confidence=0.2)) + assert lowered.threshold == 0.8 + + +def test_effective_policy_denylist_is_union_and_never_shrinks(): + policy = effective_policy( + _config(), _request(extra_abstain_categories=[AbstainCategory.EXTERNAL]) + ) + assert policy.denylist == frozenset( + {AbstainCategory.DESTRUCTIVE, AbstainCategory.EXTERNAL} + ) + # No way for the caller to remove a baseline category. + tight = effective_policy(_config(always_abstain=list(AbstainCategory)), _request()) + assert tight.denylist == frozenset(AbstainCategory) + + +def test_apply_policy_answers_confident_clean_decision(): + outcome = apply_policy( + _decision(), + threshold=0.8, + denylist={AbstainCategory.DESTRUCTIVE}, + options=["a", "b"], + ) + assert outcome.answered is True + assert outcome.choice == "a" + assert outcome.rationale == "a is best" + + +def test_apply_policy_abstains_when_model_abstained(): + outcome = apply_policy( + _decision(abstained=True, choice=None, confidence=0.99), + threshold=0.8, + denylist=set(), + options=["a", "b"], + ) + assert outcome.answered is False + assert outcome.choice is None + assert "abstained" in outcome.rationale + + +def test_apply_policy_abstains_below_threshold(): + outcome = apply_policy( + _decision(confidence=0.79), + threshold=0.8, + denylist=set(), + options=["a", "b"], + ) + assert outcome.answered is False + assert "0.79" in outcome.rationale + + +def test_apply_policy_rejects_choice_not_in_options(): + for bad in (None, "c"): + outcome = apply_policy( + _decision(choice=bad), + threshold=0.8, + denylist=set(), + options=["a", "b"], + ) + assert outcome.answered is False + assert "not one of the offered options" in outcome.rationale + + +def test_apply_policy_abstains_on_denylisted_classification(): + outcome = apply_policy( + _decision(classification=[AbstainCategory.CREDENTIALS], confidence=0.99), + threshold=0.8, + denylist={AbstainCategory.CREDENTIALS}, + options=["a", "b"], + ) + assert outcome.answered is False + assert "credentials" in outcome.rationale + + +def test_apply_policy_ignores_classification_not_denylisted(): + outcome = apply_policy( + _decision(classification=[AbstainCategory.EXTERNAL]), + threshold=0.8, + denylist={AbstainCategory.DESTRUCTIVE}, + options=["a", "b"], + ) + assert outcome.answered is True diff --git a/tests/test_mcp_server.py b/tests/test_mcp_server.py new file mode 100644 index 0000000..c8da10d --- /dev/null +++ b/tests/test_mcp_server.py @@ -0,0 +1,178 @@ +from __future__ import annotations + +import json +from pathlib import Path + +from foreman.config import FactoryConfig +from foreman.foreman import FakeForemanModel +from foreman.foreman.base import ForemanModelError +from foreman.mcp import MCPServer +from foreman.models import AbstainCategory, Decision, DecisionRequest, EventType +from foreman.persistence import RunStore + + +def _server(tmp_path: Path, model=None, **config_overrides) -> MCPServer: + config = FactoryConfig(**config_overrides) + return MCPServer( + repository=tmp_path, model=model or FakeForemanModel(), config=config + ) + + +def _call(question="Which approach?", options=("a", "b"), **arguments): + params = {"question": question, "options": list(options)} + params.update(arguments) + return { + "jsonrpc": "2.0", + "id": 1, + "method": "tools/call", + "params": {"name": "ask_foreman", "arguments": params}, + } + + +def _content_text(response) -> dict: + return json.loads(response["result"]["content"][0]["text"]) + + +async def test_initialize_and_tools_list(tmp_path): + server = _server(tmp_path) + init = await server.handle({"jsonrpc": "2.0", "id": 1, "method": "initialize"}) + assert init["result"]["protocolVersion"] == "2024-11-05" + assert init["result"]["serverInfo"]["name"] == "foreman" + + listed = await server.handle({"jsonrpc": "2.0", "id": 2, "method": "tools/list"}) + tools = listed["result"]["tools"] + assert [tool["name"] for tool in tools] == ["ask_foreman"] + schema = tools[0]["inputSchema"] + assert set(schema["required"]) == {"question", "options"} + + +async def test_notification_gets_no_response(tmp_path): + server = _server(tmp_path) + assert await server.handle({"jsonrpc": "2.0", "method": "whatever"}) is None + + +async def test_unknown_method_and_bad_params(tmp_path): + server = _server(tmp_path) + unknown = await server.handle({"jsonrpc": "2.0", "id": 1, "method": "nope"}) + assert unknown["error"]["code"] == -32601 + missing = await server.handle( + { + "jsonrpc": "2.0", + "id": 2, + "method": "tools/call", + "params": {"name": "ask_foreman", "arguments": {"options": ["a"]}}, + } + ) + assert missing["error"]["code"] == -32602 + + +async def test_tool_call_answered_path_and_event_logged(tmp_path): + server = _server(tmp_path) + response = await server.handle(_call()) + result = _content_text(response) + assert result["status"] == "answered" + assert result["choice"] == "a" + assert result["rationale"] + + events = RunStore(tmp_path).load_events(server.session_id) + assert len(events) == 1 + event = events[0] + assert event.event_type is EventType.FOREMAN_DECIDED + assert event.payload["answered"] is True + assert event.payload["choice"] == "a" + assert event.payload["effective_threshold"] == 0.8 + + +async def test_tool_call_abstain_path_leaves_session_alive(tmp_path): + model = FakeForemanModel( + decisions=[ + Decision( + choice=None, + confidence=0.9, + rationale="too ambiguous", + classification=[], + abstained=True, + ) + ] + ) + server = _server(tmp_path, model=model) + response = await server.handle(_call()) + result = _content_text(response) + assert result["status"] == "abstained" + assert "rationale" in result + + # Abstaining never terminates anything: the server answers the next call. + response2 = await server.handle(_call()) + assert _content_text(response2)["status"] == "abstained" + + +async def test_tool_call_rejects_choice_not_in_options(tmp_path): + model = FakeForemanModel( + decisions=[ + Decision( + choice="zzz", + confidence=0.99, + rationale="rogue choice", + classification=[], + abstained=False, + ) + ] + ) + server = _server(tmp_path, model=model) + result = _content_text(await server.handle(_call())) + assert result["status"] == "abstained" + assert "not one of the offered options" in result["rationale"] + + +async def test_caller_cannot_weaken_baseline(tmp_path): + model = FakeForemanModel( + decisions=[ + Decision( + choice="a", + confidence=0.99, + rationale="confident but dangerous", + classification=[AbstainCategory.DESTRUCTIVE], + abstained=False, + ) + ] + ) + server = _server( + tmp_path, model=model, always_abstain=[AbstainCategory.DESTRUCTIVE] + ) + result = _content_text( + await server.handle( + _call(min_confidence=0.0, extra_abstain_categories=[]) + ) + ) + assert result["status"] == "abstained" + assert "destructive" in result["rationale"] + + +async def test_low_confidence_abstains(tmp_path): + server = _server(tmp_path, decision_threshold=0.99) + result = _content_text(await server.handle(_call())) + assert result["status"] == "abstained" + assert "below the 0.99 threshold" in result["rationale"] + + +async def test_session_id_override_is_logged_separately(tmp_path): + server = _server(tmp_path) + await server.handle(_call(session_id="custom-session")) + events = RunStore(tmp_path).load_events("custom-session") + assert len(events) == 1 + assert events[0].event_type is EventType.FOREMAN_DECIDED + + +class _BrokenModel: + async def decide(self, request: DecisionRequest) -> Decision: + raise ForemanModelError("boom") + + async def close(self) -> None: + return None + + +async def test_model_failure_becomes_abstain_not_crash(tmp_path): + server = _server(tmp_path, model=_BrokenModel()) + result = _content_text(await server.handle(_call())) + assert result["status"] == "abstained" + assert "decision model unavailable" in result["rationale"] From 51b3628931e832ec99d1ad3a9bb514ca0472dd77 Mon Sep 17 00:00:00 2001 From: Alex Chapin Date: Sun, 20 Sep 2026 15:08:37 -0400 Subject: [PATCH 2/4] Fix MCP stdio framing to use newline-delimited JSON - Switch MCPServer.serve_stdio from LSP Content-Length framing to standard MCP newline-delimited JSON (ndjson) transport. - Route foreman mcp startup error messages to stderr to prevent stdout corruption in stdio mode. - Add tests for serve_stdio ndjson request/response handling and parse errors. - Fix non-deterministic directory ordering in test_persistence. --- src/foreman/cli.py | 3 ++- src/foreman/mcp/server.py | 45 ++++++++++++++++----------------------- tests/test_mcp_server.py | 39 +++++++++++++++++++++++++++++++++ tests/test_persistence.py | 4 ++-- 4 files changed, 61 insertions(+), 30 deletions(-) diff --git a/src/foreman/cli.py b/src/foreman/cli.py index 83b82ee..774a761 100644 --- a/src/foreman/cli.py +++ b/src/foreman/cli.py @@ -26,6 +26,7 @@ no_args_is_help=True, ) console = Console() +err_console = Console(stderr=True) def _run_async(runtime: FactoryRuntime) -> FactoryStatus: @@ -80,7 +81,7 @@ def mcp( load_dotenv(repo / ".env", override=False) load_dotenv(override=False) if not os.getenv("TYPESAFE_API_KEY"): - console.print( + err_console.print( "Missing TYPESAFE_API_KEY. Copy .env.example to .env and add your TypeSafe API key." ) raise typer.Exit(code=2) diff --git a/src/foreman/mcp/server.py b/src/foreman/mcp/server.py index 8a6b7d7..808a280 100644 --- a/src/foreman/mcp/server.py +++ b/src/foreman/mcp/server.py @@ -4,7 +4,7 @@ import json import sys from pathlib import Path -from typing import Any +from typing import Any, BinaryIO from uuid import uuid4 from pydantic import ValidationError @@ -226,32 +226,25 @@ async def _handle_tool_call( request_id, {"content": [{"type": "text", "text": json.dumps(result)}]} ) - async def serve_stdio(self) -> None: - """Serve JSON-RPC over stdio with LSP-style Content-Length framing.""" + async def serve_stdio( + self, + stdin: BinaryIO | None = None, + stdout: BinaryIO | None = None, + ) -> None: + """Serve JSON-RPC over stdio using MCP newline-delimited JSON framing.""" loop = asyncio.get_running_loop() - stdin = sys.stdin.buffer - stdout = sys.stdout.buffer + in_stream = stdin if stdin is not None else sys.stdin.buffer + out_stream = stdout if stdout is not None else sys.stdout.buffer while True: - headers: dict[str, str] = {} - while True: - line = await loop.run_in_executor(None, stdin.readline) - if not line: - return - stripped = line.strip() - if not stripped: - break - name, _, value = stripped.decode("latin-1").partition(":") - headers[name.strip().lower()] = value.strip() - try: - length = int(headers.get("content-length", "0")) - except ValueError: - continue - body = await loop.run_in_executor(None, stdin.read, length) - if not body: + line = await loop.run_in_executor(None, in_stream.readline) + if not line: return + line = line.strip() + if not line: + continue try: - message = json.loads(body) + message = json.loads(line) except json.JSONDecodeError: response: dict[str, Any] | None = _error_response( None, -32700, "parse error" @@ -260,8 +253,6 @@ async def serve_stdio(self) -> None: response = await self.handle(message) if response is None: continue - payload = json.dumps(response).encode("utf-8") - stdout.write( - f"Content-Length: {len(payload)}\r\n\r\n".encode("latin-1") + payload - ) - stdout.flush() + payload = json.dumps(response, separators=(",", ":")).encode("utf-8") + b"\n" + out_stream.write(payload) + out_stream.flush() diff --git a/tests/test_mcp_server.py b/tests/test_mcp_server.py index c8da10d..337243b 100644 --- a/tests/test_mcp_server.py +++ b/tests/test_mcp_server.py @@ -1,5 +1,6 @@ from __future__ import annotations +import io import json from pathlib import Path @@ -176,3 +177,41 @@ async def test_model_failure_becomes_abstain_not_crash(tmp_path): result = _content_text(await server.handle(_call())) assert result["status"] == "abstained" assert "decision model unavailable" in result["rationale"] + + +async def test_serve_stdio_newline_delimited_json(tmp_path): + server = _server(tmp_path) + init_req = json.dumps({"jsonrpc": "2.0", "id": 1, "method": "initialize"}) + notification = json.dumps({"jsonrpc": "2.0", "method": "notifications/initialized"}) + tools_req = json.dumps({"jsonrpc": "2.0", "id": 2, "method": "tools/list"}) + + input_data = f"{init_req}\n\n{notification}\n{tools_req}\n".encode() + stdin = io.BytesIO(input_data) + stdout = io.BytesIO() + + await server.serve_stdio(stdin=stdin, stdout=stdout) + + lines = stdout.getvalue().splitlines() + assert len(lines) == 2 + + init_res = json.loads(lines[0]) + assert init_res["id"] == 1 + assert init_res["result"]["serverInfo"]["name"] == "foreman" + + tools_res = json.loads(lines[1]) + assert tools_res["id"] == 2 + assert [t["name"] for t in tools_res["result"]["tools"]] == ["ask_foreman"] + + +async def test_serve_stdio_parse_error(tmp_path): + server = _server(tmp_path) + stdin = io.BytesIO(b"not valid json\n") + stdout = io.BytesIO() + + await server.serve_stdio(stdin=stdin, stdout=stdout) + + lines = stdout.getvalue().splitlines() + assert len(lines) == 1 + res = json.loads(lines[0]) + assert res["error"]["code"] == -32700 + diff --git a/tests/test_persistence.py b/tests/test_persistence.py index 9aff6e3..ccce3d2 100644 --- a/tests/test_persistence.py +++ b/tests/test_persistence.py @@ -34,10 +34,10 @@ def test_state_write_leaves_no_temporary_file(state, tmp_path) -> None: store = RunStore(tmp_path) store.initialize(state) store.save_state(state) - assert [path.name for path in store.run_dir(state.run_id).iterdir()] == [ + assert {path.name for path in store.run_dir(state.run_id).iterdir()} == { "state.json", "events.jsonl", - ] + } def test_jsonl_events(state, tmp_path) -> None: From f564abe02aa2fc316dde2e25117e649846eae4af Mon Sep 17 00:00:00 2001 From: Alex Chapin Date: Sun, 20 Sep 2026 17:00:18 -0400 Subject: [PATCH 3/4] docs(mcp): document agent integration patterns, AGENTS.md template, and decision boundaries --- README.md | 1 + docs/README.md | 2 + docs/mcp.md | 106 +++++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 109 insertions(+) diff --git a/README.md b/README.md index 3252cc1..930d31e 100644 --- a/README.md +++ b/README.md @@ -49,6 +49,7 @@ conventional coding-agent harness. - [Runtime and event flow](docs/runtime.md) - [Live steering](docs/steering.md) - [Worker backends](docs/workers.md) +- [Foreman as an MCP decision tool](docs/mcp.md) ## Contributing diff --git a/docs/README.md b/docs/README.md index 0308779..7c91934 100644 --- a/docs/README.md +++ b/docs/README.md @@ -7,5 +7,7 @@ These notes explain the experiment behind the implementation: - [What Foreman is proving](what-foreman-proves.md) states the hypotheses and evidence boundaries. - [Runtime and event flow](runtime.md) is the implementation guide. - [Live steering](steering.md) explains how Jev guidance reaches an active Codex turn. +- [Worker backends](workers.md) details supported backends (Codex, OpenCode). +- [Foreman as an MCP decision tool](mcp.md) describes using Foreman for multiple-choice decision delegation. The root [README](../README.md) remains the installation and command reference. diff --git a/docs/mcp.md b/docs/mcp.md index eb12c69..7ce4ea7 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -76,3 +76,109 @@ the repository's `.foreman/runs//events.jsonl`, recording the question, classification, choice, confidence, and the effective policy — so `foreman inspect ` shows the MCP-mode history and you can tune the threshold and denylist from evidence. + +## Client configuration + +Add `foreman mcp` to your coding client's MCP configuration: + +### OpenCode (`opencode.json` / `~/.config/opencode/opencode.json`) + +```json +{ + "mcp": { + "foreman": { + "type": "local", + "command": ["foreman", "mcp", "--repo", "."] + } + } +} +``` + +### Claude Desktop / Claude Code (`claude_desktop_config.json`) + +```json +{ + "mcpServers": { + "foreman": { + "command": "foreman", + "args": ["mcp", "--repo", "."] + } + } +} +``` + +### Cursor (`.cursor/mcp.json`) + +```json +{ + "mcpServers": { + "foreman": { + "command": "foreman", + "args": ["mcp", "--repo", "."] + } + } +} +``` + +Ensure `TYPESAFE_API_KEY` is exported in your shell environment or provided in your project `.env`. + +## Instructing coding workers (`AGENTS.md`) + +To direct coding agents to consult the foreman autonomously, include a scoped instruction in your repository or global agent prompt (e.g. `AGENTS.md`, `.cursorrules`, or custom system instructions): + +```markdown + +# Semantic Decision Supervision (foreman-mcp) + +When the `ask_foreman` tool is available from the `foreman` MCP server, delegate operational and technical multiple-choice decisions to the Foreman before interrupting the human. + +## When to use `ask_foreman` +- **Technical trade-offs:** Choosing between valid implementation approaches (e.g. join vs subquery, library selection, algorithm choice). +- **Error recovery & test fixes:** Deciding whether to retry, mock, refactor, or adjust test fixtures. +- **Autonomous workflows:** Any decision point during background loops, wave runs, or unattended tasks. + +## When NOT to use `ask_foreman` (Ask the human directly) +- **User intent & product requirements:** Clarifying what feature the user wants or personal preferences. +- **Open-ended questions:** Questions without discrete, concrete options. +- **Credentials & authorization:** Handling secrets, API keys, or permission grants. +- **Irreversible / destructive actions:** Deployments, dropping databases, or deleting repositories. + +## Protocol +1. Frame the decision as a multiple-choice question with discrete `options` and detailed `context`. +2. Call `ask_foreman(question=..., options=[...], context=...)`. +3. If Foreman returns `{"status": "answered", "choice": "..."}`: + - Adopt the choice and cite Foreman's rationale in your explanation. +4. If Foreman returns `{"status": "abstained"}` or is unavailable: + - Present the question, options, and context to the human user. + +``` + +## Decision boundaries: Foreman vs. Human + +Foreman is designed to decide bounded technical questions where clear options exist. It does not replace the human product owner. + +| Category | Delegate to Foreman (`ask_foreman`) | Ask the Human Directly | +|---|---|---| +| **Product & Scope** | ❌ (Foreman cannot know user intent) | What features to include; UX preferences; domain logic | +| **Technical Trade-offs** | Join vs subquery; polling vs webhook; data structure choice | Major architectural rewrites; external vendor selection | +| **Test Failures & CI** | Flaky test retry vs mock; fixing fixture vs code; gate alignment | Deprecating entire test suites | +| **Merge & Branching** | Auto-resolving rebase conflicts; selecting merge strategy | Resolving semantic conflicts touching sensitive business logic | +| **Safety & Ops** | ❌ (Blocked by default abstain denylist) | Deployments; database drops; credential changes | + +## Autonomous pipelines and multi-agent workflows + +When orchestrating autonomous agents (e.g. wave orchestrators, PR review bots, overnight improvement loops), the "Foreman First" pattern prevents pipelines from stalling on operational questions: + +1. **Unattended Execution:** Before raising an escalation or asking the user for input, the agent calls `ask_foreman`. +2. **Deterministic Fallback:** If Foreman answers, the agent proceeds immediately and logs the decision event. If Foreman abstains, the agent either logs an escalated blocker in its state file (in `--auto` mode) or pauses to prompt the operator. +3. **Sub-agent Delegation:** Sub-agents shepherding PRs or running tests can use `ask_foreman` to classify CI errors (transient runner queue vs reproducible code regression) and decide whether to retry or escalate without human intervention. + +## Question formulation best practices + +To maximize decision accuracy and avoid unnecessary abstentions: + +- **Provide 2–4 mutually exclusive options:** Always ensure options are discrete and actionable (e.g. `["Retry with clean worktree", "Skip issue to continue wave", "Escalate to human"]`). +- **Provide rich context:** Pass relevant test output snippets, file paths, and the trade-offs of each option in the `context` parameter. The decider relies heavily on context to evaluate risk. +- **Set advisory `risk_hint`:** If the operation carries potential side effects, provide an advisory string (e.g. `risk_hint="CI retry"` or `risk_hint="merge conflict"`). +- **Graceful degradation:** Always check `status`. If `abstained`, treat it as an indication that the decision belongs with a human — abstaining is a safety feature, not an error. + From ebbf53aab43be1697e4079998958dc4dc7756d8b Mon Sep 17 00:00:00 2001 From: Alex Chapin Date: Mon, 21 Sep 2026 13:12:50 -0400 Subject: [PATCH 4/4] feat(mcp): tune decision policy defaults and add decisions analytics CLI - Tune FactoryConfig defaults: lower decision_threshold from 0.80 to 0.70 and scope always_abstain to destructive,credentials to improve autonomous answer rates for technical trade-offs and workflow coordination. - Add foreman decisions CLI command to compute and display decision metrics (answer rate, average confidence, abstain breakdown) with Rich table and --json output, supporting single repo or multi-repo auto-discovery. - Fix foreman inspect to support event-only runs (MCP sessions without state.json). - Add RunStore.list_run_ids() and RunStore.load_decision_events(). - Enrich question formulation guidelines and AGENTS.md template in docs/mcp.md to discourage open-ended meta-questions and administrative gate bypass queries. - Add test coverage in tests/test_cli.py and tests/test_persistence.py. --- .env.example | 4 + docs/mcp.md | 37 ++++-- src/foreman/cli.py | 243 +++++++++++++++++++++++++++++++++++-- src/foreman/config.py | 7 +- src/foreman/persistence.py | 30 ++++- tests/test_cli.py | 188 ++++++++++++++++++++++++++++ tests/test_mcp_server.py | 2 +- tests/test_persistence.py | 40 ++++++ 8 files changed, 524 insertions(+), 27 deletions(-) create mode 100644 tests/test_cli.py diff --git a/.env.example b/.env.example index 07a0b9d..ce265e0 100644 --- a/.env.example +++ b/.env.example @@ -13,3 +13,7 @@ TYPESAFE_API_KEY= # FOREMAN_STEERING_ENABLED=true # FOREMAN_MAX_STEERS_PER_WORKER=1 # FOREMAN_STEERING_GRACE_SECONDS=30 + +# MCP Decision Server policy configuration (baseline safety floor) +# FOREMAN_DECISION_THRESHOLD=0.70 +# FOREMAN_ALWAYS_ABSTAIN=destructive,credentials diff --git a/docs/mcp.md b/docs/mcp.md index 7ce4ea7..196c9f7 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -50,8 +50,8 @@ An answer is returned only when **all** of these hold: The policy is layered and tighten-only: - **Server-side baseline** (the safety floor): `FOREMAN_DECISION_THRESHOLD` - (default `0.80`) and `FOREMAN_ALWAYS_ABSTAIN` (comma-separated list, - default all four categories). The caller cannot weaken these. + (default `0.70`) and `FOREMAN_ALWAYS_ABSTAIN` (comma-separated list, + default `destructive,credentials`). The caller cannot weaken these. - **Per-call** `min_confidence` and `extra_abstain_categories` can only tighten: the effective threshold is the maximum of the two, and the effective denylist is the union of both. @@ -69,13 +69,27 @@ abstention, not a crash. | `external` | Side effects beyond the local machine, incl. cost and exfiltration | | `credentials` | Authentication material, permission grants, signing | -## Decision log +## Decision log and analytics Every decision and abstention is appended as a `FOREMAN_DECIDED` event to the repository's `.foreman/runs//events.jsonl`, recording the -question, classification, choice, confidence, and the effective policy — so -`foreman inspect ` shows the MCP-mode history and you can tune -the threshold and denylist from evidence. +question, classification, choice, confidence, and the effective policy. + +You can inspect individual sessions or calculate aggregate statistics: + +- **Inspect an individual session:** + ```bash + foreman inspect --repo ./my-project + ``` +- **Aggregate metrics and decision logs:** + ```bash + foreman decisions --repo ./my-project + ``` + Options: + - `--run-id `: Filter decisions for a single session. + - `--all` / `-a`: Display full question text and rationales without truncation. + - `--json`: Output machine-readable JSON metrics and decision records. + - Multi-repo discovery: If `--repo` points to a parent directory (e.g. `~/Projects`), it automatically aggregates decisions across all child project stores. ## Client configuration @@ -139,9 +153,10 @@ When the `ask_foreman` tool is available from the `foreman` MCP server, delegate ## When NOT to use `ask_foreman` (Ask the human directly) - **User intent & product requirements:** Clarifying what feature the user wants or personal preferences. -- **Open-ended questions:** Questions without discrete, concrete options. +- **Open-ended prioritization or planning:** Meta-questions like "What should I work on next?" or "What do you recommend?" (the decision model is trained to abstain on open-ended strategy). +- **Administrative permission & policy bypasses:** Asking to bypass security or CI gates (e.g. "Should I bypass CI with --admin?"). - **Credentials & authorization:** Handling secrets, API keys, or permission grants. -- **Irreversible / destructive actions:** Deployments, dropping databases, or deleting repositories. +- **Destructive actions:** Deleting repositories, dropping databases, or force-pushing. ## Protocol 1. Frame the decision as a multiple-choice question with discrete `options` and detailed `context`. @@ -177,8 +192,10 @@ When orchestrating autonomous agents (e.g. wave orchestrators, PR review bots, o To maximize decision accuracy and avoid unnecessary abstentions: -- **Provide 2–4 mutually exclusive options:** Always ensure options are discrete and actionable (e.g. `["Retry with clean worktree", "Skip issue to continue wave", "Escalate to human"]`). -- **Provide rich context:** Pass relevant test output snippets, file paths, and the trade-offs of each option in the `context` parameter. The decider relies heavily on context to evaluate risk. +- **Provide 2–4 mutually exclusive options:** Always ensure options are discrete, concrete, and actionable (e.g. `["Retry with clean worktree", "Skip issue to continue wave", "Escalate to human"]`). Never leave choices open-ended. +- **Frame as technical implementation or error-recovery trade-offs:** Foreman excels when choosing between concrete approaches (e.g., Option A: pass parameter through boundary conditions vs. Option B: use specialized constant). Avoid open-ended questions like "what should I do next?". +- **Provide rich context:** Pass relevant test output snippets, file paths, error messages, and the trade-offs of each option in the `context` parameter. The decider relies heavily on context to evaluate risk and reach the confidence threshold. +- **Frame CI/test issues around code and mocks:** Rather than asking for administrative gate-bypasses (`--admin`), formulate test triage as concrete technical choices: `["Mock network transport in fixture", "Update assertion to match new return type", "Escalate to human"]`. - **Set advisory `risk_hint`:** If the operation carries potential side effects, provide an advisory string (e.g. `risk_hint="CI retry"` or `risk_hint="merge conflict"`). - **Graceful degradation:** Always check `status`. If `abstained`, treat it as an indication that the decision belongs with a human — abstaining is a safety feature, not an error. diff --git a/src/foreman/cli.py b/src/foreman/cli.py index 774a761..77794ea 100644 --- a/src/foreman/cli.py +++ b/src/foreman/cli.py @@ -1,10 +1,11 @@ from __future__ import annotations import asyncio +import json import os -from datetime import UTC +from datetime import UTC, datetime from pathlib import Path -from typing import Annotated +from typing import Annotated, Any import typer from dotenv import load_dotenv @@ -155,24 +156,40 @@ def inspect_run( store = RunStore(repo) try: - state = store.load_state(run_id) events = store.load_events(run_id) except PersistenceError as error: console.print(str(error)) raise typer.Exit(code=2) from error - finished = state.finished_at or state.updated_at - duration = max(0.0, (finished - state.started_at).total_seconds()) - console.print(f"[bold]FOREMAN RUN: {state.run_id}[/bold]") - console.print("Job:") - console.print(state.job) - console.print(f"Duration: {duration_label(duration)}") - console.print(f"Workers: {len(state.workers)}") - console.print(f"Assessments: {len(state.assessment_history)}") - console.print(f"Result: {state.status.value}") + try: + state = store.load_state(run_id) + except PersistenceError: + state = None + + if state is not None: + finished = state.finished_at or state.updated_at + duration = max(0.0, (finished - state.started_at).total_seconds()) + console.print(f"[bold]FOREMAN RUN: {state.run_id}[/bold]") + console.print("Job:") + console.print(state.job) + console.print(f"Duration: {duration_label(duration)}") + console.print(f"Workers: {len(state.workers)}") + console.print(f"Assessments: {len(state.assessment_history)}") + console.print(f"Result: {state.status.value}") + started_at = state.started_at + else: + started_at = events[0].timestamp if events else datetime.now(UTC) + duration = ( + max(0.0, (events[-1].timestamp - started_at).total_seconds()) + if len(events) > 1 + else 0.0 + ) + console.print(f"[bold]FOREMAN RUN: {run_id}[/bold]") + console.print(f"Duration: {duration_label(duration)}") + console.print(f"Events: {len(events)}") for event in events: - offset = (event.timestamp - state.started_at).total_seconds() + offset = (event.timestamp - started_at).total_seconds() prefix = elapsed_label(offset) payload = event.payload if event.event_type is EventType.FACTORY_STARTED: @@ -210,10 +227,16 @@ def inspect_run( elif event.event_type is EventType.FOREMAN_DECIDED: status = "answered" if payload.get("answered") else "abstained" console.print(f"{prefix} Foreman decided: {status}") + if payload.get("question"): + q = str(payload.get("question")).replace("\n", " ") + console.print(f" question: {q[:80] + '...' if len(q) > 80 else q}") console.print(f" choice: {payload.get('choice')}") console.print( f" confidence: {float(payload.get('confidence', 0.0)):.2f}" ) + if payload.get("rationale"): + r = str(payload.get("rationale")).replace("\n", " ") + console.print(f" rationale: {r[:100] + '...' if len(r) > 100 else r}") elif event.event_type in {EventType.WORKER_STEERED, EventType.WORKER_STEER_FAILED}: label = "steered" if event.event_type is EventType.WORKER_STEERED else "steer failed" console.print(f"{prefix} {payload.get('worker_id')} {label}") @@ -242,5 +265,199 @@ def runs( console.print(table) +def _find_stores(base_path: Path) -> list[tuple[str, RunStore]]: + """Locate RunStore instances in base_path or its immediate child repositories.""" + base_store = RunStore(base_path) + if base_store.runs_dir.exists(): + return [(base_path.name, base_store)] + + sub_stores: list[tuple[str, RunStore]] = [] + try: + for child in sorted(base_path.iterdir()): + if child.is_dir() and not child.name.startswith("."): + child_store = RunStore(child) + if child_store.runs_dir.exists(): + sub_stores.append((child.name, child_store)) + except (OSError, PermissionError): + pass + return sub_stores + + +@app.command("decisions") +def decisions( + repo: Annotated[ + Path, + typer.Option( + "--repo", + exists=True, + file_okay=False, + resolve_path=True, + help="Repository or directory containing .foreman stores", + ), + ] = Path("."), + run_id: Annotated[ + str | None, + typer.Option("--run-id", help="Limit results to a specific session or run ID"), + ] = None, + json_output: Annotated[ + bool, + typer.Option("--json", help="Output machine-readable JSON"), + ] = False, + show_all: Annotated[ + bool, + typer.Option("--all", "-a", help="Show full question and rationale without truncating"), + ] = False, +) -> None: + """Analyze and display autonomous decisions made by the Foreman MCP tool.""" + + stores = _find_stores(repo) + if not stores: + if json_output: + console.print(json.dumps({"total": 0, "decisions": []})) + return + console.print(f"No .foreman runs found in [bold]{repo}[/bold].") + return + + records: list[dict[str, Any]] = [] + for repo_name, store in stores: + for event in store.load_decision_events(run_id=run_id): + p = event.payload + records.append( + { + "repo": repo_name, + "run_id": event.run_id, + "timestamp": event.timestamp.isoformat(), + "question": str(p.get("question", "")), + "options": p.get("options", []), + "answered": bool(p.get("answered", False)), + "choice": p.get("choice"), + "confidence": float(p.get("confidence", 0.0)), + "effective_threshold": float(p.get("effective_threshold", 0.70)), + "classification": p.get("classification", []), + "effective_denylist": p.get("effective_denylist", []), + "rationale": str(p.get("rationale", "")), + } + ) + + if not records: + if json_output: + console.print(json.dumps({"total": 0, "decisions": []})) + return + target = f"run {run_id}" if run_id else f"repository {repo}" + console.print(f"No decisions recorded for [bold]{target}[/bold].") + return + + total = len(records) + answered_count = sum(1 for r in records if r["answered"]) + abstained_count = total - answered_count + answered_pct = (answered_count / total * 100) if total else 0.0 + abstained_pct = (abstained_count / total * 100) if total else 0.0 + avg_conf = sum(r["confidence"] for r in records) / total if total else 0.0 + + denylist_count = sum( + 1 + for r in records + if not r["answered"] + and bool(set(r["classification"]) & set(r["effective_denylist"])) + ) + low_conf_count = sum( + 1 + for r in records + if not r["answered"] and r["confidence"] < r["effective_threshold"] + ) + self_abstained_count = sum( + 1 for r in records if not r["answered"] and r["choice"] is None + ) + + if json_output: + summary_data = { + "total": total, + "answered": answered_count, + "answered_percentage": round(answered_pct, 2), + "abstained": abstained_count, + "abstained_percentage": round(abstained_pct, 2), + "average_confidence": round(avg_conf, 3), + "abstain_reasons": { + "denylist_interceptions": denylist_count, + "below_threshold": low_conf_count, + "model_self_abstained": self_abstained_count, + }, + "decisions": records, + } + console.print(json.dumps(summary_data, indent=2)) + return + + summary_table = Table( + title="Foreman MCP Decisions Summary", + show_header=True, + header_style="bold cyan", + ) + summary_table.add_column("Metric") + summary_table.add_column("Value", justify="right") + summary_table.add_row("Total Decisions", str(total)) + summary_table.add_row( + "Answered", + f"[bold green]{answered_count}[/bold green] ({answered_pct:.1f}%)", + ) + summary_table.add_row( + "Abstained / Declined", + f"[bold yellow]{abstained_count}[/bold yellow] ({abstained_pct:.1f}%)", + ) + summary_table.add_row("Average Confidence", f"{avg_conf:.2f}") + summary_table.add_row(" - Denylist Interceptions", str(denylist_count)) + summary_table.add_row(" - Confidence Below Threshold", str(low_conf_count)) + summary_table.add_row(" - Model Self-Abstained", str(self_abstained_count)) + console.print(summary_table) + + table = Table(title="Decision Log", show_header=True, header_style="bold magenta") + if len(stores) > 1: + table.add_column("Repo", style="dim") + table.add_column("Run / Session", style="cyan") + table.add_column("Status") + table.add_column("Conf / Thresh", justify="right") + table.add_column("Choice / Verdict") + table.add_column("Question") + table.add_column("Rationale") + + for r in records: + status_text = ( + "[bold green]ANSWERED[/bold green]" + if r["answered"] + else "[bold yellow]ABSTAINED[/bold yellow]" + ) + choice_text = str(r["choice"]) if r["choice"] else "[dim]None[/dim]" + conf_thresh = f"{r['confidence']:.2f} / {r['effective_threshold']:.2f}" + q_clean = r["question"].replace("\n", " ") + rat_clean = r["rationale"].replace("\n", " ") + q_display = ( + q_clean + if show_all + else (q_clean[:60] + "..." if len(q_clean) > 60 else q_clean) + ) + rat_display = ( + rat_clean + if show_all + else (rat_clean[:70] + "..." if len(rat_clean) > 70 else rat_clean) + ) + + row_args = [] + if len(stores) > 1: + row_args.append(r["repo"]) + row_args.extend( + [ + r["run_id"], + status_text, + conf_thresh, + choice_text, + q_display, + rat_display, + ] + ) + table.add_row(*row_args) + + console.print(table) + + + if __name__ == "__main__": app() diff --git a/src/foreman/config.py b/src/foreman/config.py index 1b42d5f..bff714b 100644 --- a/src/foreman/config.py +++ b/src/foreman/config.py @@ -60,9 +60,12 @@ class FactoryConfig(BaseModel): off_track_threshold: float = Field(default=0.80, ge=0.0, le=1.0) agents_drift_threshold: float = Field(default=0.80, ge=0.0, le=1.0) stuck_threshold: float = Field(default=0.80, ge=0.0, le=1.0) - decision_threshold: float = Field(default=0.80, ge=0.0, le=1.0) + decision_threshold: float = Field(default=0.70, ge=0.0, le=1.0) always_abstain: list[AbstainCategory] = Field( - default_factory=lambda: list(AbstainCategory) + default_factory=lambda: [ + AbstainCategory.DESTRUCTIVE, + AbstainCategory.CREDENTIALS, + ] ) verification_threshold: float = Field(default=0.65, ge=0.0, le=1.0) finish_threshold: float = Field(default=0.75, ge=0.0, le=1.0) diff --git a/src/foreman/persistence.py b/src/foreman/persistence.py index ae9d32c..8f51255 100644 --- a/src/foreman/persistence.py +++ b/src/foreman/persistence.py @@ -8,7 +8,7 @@ from pydantic import ValidationError -from foreman.models import FactoryEvent, FactoryState +from foreman.models import EventType, FactoryEvent, FactoryState class PersistenceError(RuntimeError): @@ -126,6 +126,34 @@ def list_states(self) -> Iterable[FactoryState]: continue return states + def list_run_ids(self) -> list[str]: + if not self.runs_dir.exists(): + return [] + paths = sorted( + [ + path + for path in self.runs_dir.iterdir() + if path.is_dir() and not path.name.startswith(".") + ], + key=lambda item: (item.stat().st_mtime, item.name), + reverse=True, + ) + return [path.name for path in paths] + + def load_decision_events(self, run_id: str | None = None) -> list[FactoryEvent]: + """Load FOREMAN_DECIDED events for one run or across all runs in this store.""" + target_ids = [run_id] if run_id is not None else self.list_run_ids() + events: list[FactoryEvent] = [] + for rid in target_ids: + try: + run_events = self.load_events(rid, tolerate_malformed=True) + except PersistenceError: + continue + for event in run_events: + if event.event_type is EventType.FOREMAN_DECIDED: + events.append(event) + return sorted(events, key=lambda event: event.timestamp) + def recent_event_dicts(self, run_id: str, limit: int) -> list[dict[str, object]]: events = self.load_events(run_id, tolerate_malformed=True)[-limit:] return [json.loads(event.model_dump_json()) for event in events] diff --git a/tests/test_cli.py b/tests/test_cli.py new file mode 100644 index 0000000..5f4a2ec --- /dev/null +++ b/tests/test_cli.py @@ -0,0 +1,188 @@ +from __future__ import annotations + +import json +from pathlib import Path + +from typer.testing import CliRunner + +from foreman.cli import app +from foreman.models import EventType, FactoryEvent, FactoryState +from foreman.persistence import RunStore + +runner = CliRunner() + + +def test_inspect_factory_run_with_state(tmp_path: Path, state: FactoryState) -> None: + store = RunStore(tmp_path) + store.initialize(state) + event = FactoryEvent( + run_id=state.run_id, + event_type=EventType.FACTORY_STARTED, + payload={}, + ) + store.append_event(event) + + result = runner.invoke(app, ["inspect", state.run_id, "--repo", str(tmp_path)]) + assert result.exit_code == 0 + assert f"FOREMAN RUN: {state.run_id}" in result.output + assert "Factory started" in result.output + + +def test_inspect_mcp_run_without_state(tmp_path: Path) -> None: + store = RunStore(tmp_path) + event = FactoryEvent( + run_id="mcp-session-123", + event_type=EventType.FOREMAN_DECIDED, + payload={ + "question": "Use join or subquery?", + "answered": True, + "choice": "join", + "confidence": 0.88, + "rationale": "chose join", + }, + ) + store.append_event(event) + + result = runner.invoke(app, ["inspect", "mcp-session-123", "--repo", str(tmp_path)]) + assert result.exit_code == 0 + assert "FOREMAN RUN: mcp-session-123" in result.output + assert "Foreman decided: answered" in result.output + assert "choice: join" in result.output + assert "confidence: 0.88" in result.output + + +def test_inspect_nonexistent_run(tmp_path: Path) -> None: + result = runner.invoke(app, ["inspect", "does-not-exist", "--repo", str(tmp_path)]) + assert result.exit_code == 2 + assert "not found" in result.output + + +def test_decisions_no_runs(tmp_path: Path) -> None: + result = runner.invoke(app, ["decisions", "--repo", str(tmp_path)]) + assert result.exit_code == 0 + assert "No .foreman runs found" in result.output + + +def test_decisions_empty_runs_json(tmp_path: Path) -> None: + result = runner.invoke(app, ["decisions", "--repo", str(tmp_path), "--json"]) + assert result.exit_code == 0 + data = json.loads(result.output) + assert data["total"] == 0 + assert data["decisions"] == [] + + +def test_decisions_summary_and_table(tmp_path: Path) -> None: + store = RunStore(tmp_path) + event1 = FactoryEvent( + run_id="sess-1", + event_type=EventType.FOREMAN_DECIDED, + payload={ + "question": "Should we optimize the query?", + "options": ["yes", "no"], + "answered": True, + "choice": "yes", + "confidence": 0.85, + "effective_threshold": 0.80, + "classification": [], + "effective_denylist": ["destructive", "irreversible", "external", "credentials"], + "rationale": "Confidence is high", + }, + ) + event2 = FactoryEvent( + run_id="sess-2", + event_type=EventType.FOREMAN_DECIDED, + payload={ + "question": "Should we force push to main?", + "options": ["yes", "no"], + "answered": False, + "choice": None, + "confidence": 0.50, + "effective_threshold": 0.80, + "classification": ["destructive"], + "effective_denylist": ["destructive", "irreversible", "external", "credentials"], + "rationale": "Classified as destructive", + }, + ) + store.append_event(event1) + store.append_event(event2) + + # Standard table output + result = runner.invoke(app, ["decisions", "--repo", str(tmp_path)]) + assert result.exit_code == 0 + assert "Total Decisions" in result.output + assert "2" in result.output + assert "ANSWERED" in result.output + assert "ABSTAINED" in result.output + assert "optimize" in result.output + + # With --all flag + all_result = runner.invoke(app, ["decisions", "--repo", str(tmp_path), "--all"]) + assert all_result.exit_code == 0 + assert "optimize" in all_result.output + assert "query?" in all_result.output + + # JSON output + json_result = runner.invoke(app, ["decisions", "--repo", str(tmp_path), "--json"]) + assert json_result.exit_code == 0 + data = json.loads(json_result.output) + assert data["total"] == 2 + assert data["answered"] == 1 + assert data["abstained"] == 1 + assert data["abstain_reasons"]["denylist_interceptions"] == 1 + assert data["abstain_reasons"]["below_threshold"] == 1 + assert data["abstain_reasons"]["model_self_abstained"] == 1 + assert len(data["decisions"]) == 2 + + +def test_decisions_filter_by_run_id(tmp_path: Path) -> None: + store = RunStore(tmp_path) + event1 = FactoryEvent( + run_id="sess-1", + event_type=EventType.FOREMAN_DECIDED, + payload={"question": "Q1", "answered": True, "choice": "A", "confidence": 0.9}, + ) + event2 = FactoryEvent( + run_id="sess-2", + event_type=EventType.FOREMAN_DECIDED, + payload={"question": "Q2", "answered": False, "choice": None, "confidence": 0.4}, + ) + store.append_event(event1) + store.append_event(event2) + + result = runner.invoke( + app, + ["decisions", "--repo", str(tmp_path), "--run-id", "sess-1", "--json"], + ) + assert result.exit_code == 0 + data = json.loads(result.output) + assert data["total"] == 1 + assert data["decisions"][0]["run_id"] == "sess-1" + + +def test_decisions_multi_repo_discovery(tmp_path: Path) -> None: + repo1 = tmp_path / "repo1" + repo2 = tmp_path / "repo2" + store1 = RunStore(repo1) + store2 = RunStore(repo2) + + store1.append_event( + FactoryEvent( + run_id="r1-sess", + event_type=EventType.FOREMAN_DECIDED, + payload={"question": "Repo1 Q", "answered": True, "choice": "A", "confidence": 0.95}, + ) + ) + store2.append_event( + FactoryEvent( + run_id="r2-sess", + event_type=EventType.FOREMAN_DECIDED, + payload={"question": "Repo2 Q", "answered": False, "choice": None, "confidence": 0.5}, + ) + ) + + result = runner.invoke(app, ["decisions", "--repo", str(tmp_path), "--json"]) + assert result.exit_code == 0 + data = json.loads(result.output) + assert data["total"] == 2 + repos = {d["repo"] for d in data["decisions"]} + assert repos == {"repo1", "repo2"} diff --git a/tests/test_mcp_server.py b/tests/test_mcp_server.py index 337243b..474f97a 100644 --- a/tests/test_mcp_server.py +++ b/tests/test_mcp_server.py @@ -81,7 +81,7 @@ async def test_tool_call_answered_path_and_event_logged(tmp_path): assert event.event_type is EventType.FOREMAN_DECIDED assert event.payload["answered"] is True assert event.payload["choice"] == "a" - assert event.payload["effective_threshold"] == 0.8 + assert event.payload["effective_threshold"] == 0.7 async def test_tool_call_abstain_path_leaves_session_alive(tmp_path): diff --git a/tests/test_persistence.py b/tests/test_persistence.py index ccce3d2..4ad9d40 100644 --- a/tests/test_persistence.py +++ b/tests/test_persistence.py @@ -118,3 +118,43 @@ def test_initialize_locally_excludes_runtime_directory(state, tmp_path) -> None: ).stdout assert ".foreman" not in status assert "/.foreman/" in (tmp_path / ".git" / "info" / "exclude").read_text() + + +def test_list_run_ids_and_load_decision_events(tmp_path) -> None: + store = RunStore(tmp_path) + assert store.list_run_ids() == [] + assert store.load_decision_events() == [] + + # Create two runs: one factory run and one MCP run (no state.json) + event1 = FactoryEvent( + run_id="run-1", + event_type=EventType.FOREMAN_DECIDED, + payload={"question": "Q1", "answered": True, "choice": "A", "confidence": 0.85}, + ) + event2 = FactoryEvent( + run_id="run-2", + event_type=EventType.FACTORY_STARTED, + payload={}, + ) + event3 = FactoryEvent( + run_id="run-2", + event_type=EventType.FOREMAN_DECIDED, + payload={"question": "Q2", "answered": False, "choice": None, "confidence": 0.60}, + ) + + store.append_event(event1) + store.append_event(event2) + store.append_event(event3) + + run_ids = store.list_run_ids() + assert set(run_ids) == {"run-1", "run-2"} + + # All decisions across runs + decisions = store.load_decision_events() + assert len(decisions) == 2 + assert {d.payload["question"] for d in decisions} == {"Q1", "Q2"} + + # Decisions for specific run + run1_decisions = store.load_decision_events(run_id="run-1") + assert len(run1_decisions) == 1 + assert run1_decisions[0].payload["question"] == "Q1"