failfirst 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- failfirst/__init__.py +10 -0
- failfirst/__main__.py +5 -0
- failfirst/agent/AGENTS.md +52 -0
- failfirst/agent/llms.txt +12 -0
- failfirst/agent/schemas/baseline-report.schema.json +127 -0
- failfirst/agent/schemas/describe.schema.json +130 -0
- failfirst/agent/schemas/error.schema.json +33 -0
- failfirst/agent/schemas/verify-report.schema.json +134 -0
- failfirst/agent/schemas/version.schema.json +19 -0
- failfirst/agent/tools.json +43 -0
- failfirst/agent.py +109 -0
- failfirst/cli.py +119 -0
- failfirst/core.py +177 -0
- failfirst/mcp.py +77 -0
- failfirst/model.py +167 -0
- failfirst/py.typed +0 -0
- failfirst/runner.py +101 -0
- failfirst-0.1.0.dist-info/METADATA +58 -0
- failfirst-0.1.0.dist-info/RECORD +23 -0
- failfirst-0.1.0.dist-info/WHEEL +5 -0
- failfirst-0.1.0.dist-info/entry_points.txt +2 -0
- failfirst-0.1.0.dist-info/licenses/LICENSE +21 -0
- failfirst-0.1.0.dist-info/top_level.txt +1 -0
failfirst/cli.py
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
"""Command line: failfirst baseline | verify | describe | mcp.
|
|
2
|
+
|
|
3
|
+
Agent-safe: never prompts, never reads stdin (except ``mcp``, which speaks the protocol on it),
|
|
4
|
+
never emits ANSI colour. Expected failures print ``{"error": {code, message, hint}}`` on stdout
|
|
5
|
+
with ``--json`` (human text on stderr otherwise) and exit 2.
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import argparse
|
|
10
|
+
import json
|
|
11
|
+
import sys
|
|
12
|
+
from typing import Any, NoReturn
|
|
13
|
+
|
|
14
|
+
from . import __version__
|
|
15
|
+
from .agent import CliError, describe, load_tools, run_operation
|
|
16
|
+
from .core import DEFAULT_LOCK, format_report
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class _Parser(argparse.ArgumentParser):
|
|
20
|
+
def error(self, message: str) -> NoReturn:
|
|
21
|
+
raise CliError("FF_E_USAGE", message)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _dump(obj: Any, compact: bool) -> str:
|
|
25
|
+
if compact:
|
|
26
|
+
return json.dumps(obj, ensure_ascii=False, separators=(",", ":"))
|
|
27
|
+
return json.dumps(obj, ensure_ascii=False, indent=2)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _quiet_line(report: dict[str, Any]) -> str:
|
|
31
|
+
summ = ", ".join(f"{n} {k}" for k, n in sorted(report["summary"].items()))
|
|
32
|
+
return f"failfirst {report['phase']}: {report['status']} ({summ})"
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _build_parser() -> argparse.ArgumentParser:
|
|
36
|
+
p = _Parser(prog="failfirst", description="Acceptance criteria that must fail before they may pass. "
|
|
37
|
+
"Exit: 0 pass, 1 fail, 2 usage/input error, 3 awaiting human review, 70 internal.")
|
|
38
|
+
p.add_argument("--version", action="store_true", help="print the version (with --json: {tool, version})")
|
|
39
|
+
p.add_argument("--json", action="store_true", help=argparse.SUPPRESS)
|
|
40
|
+
sub = p.add_subparsers(dest="cmd", parser_class=_Parser)
|
|
41
|
+
for name, helptext in (("baseline", "run criteria on the unfixed state and write the lockfile"),
|
|
42
|
+
("verify", "re-run criteria and check they were proven")):
|
|
43
|
+
s = sub.add_parser(name, help=helptext)
|
|
44
|
+
s.add_argument("criteria", nargs="?", help="criteria file (.json/.yaml)")
|
|
45
|
+
s.add_argument("--lock", help=f"lockfile path (default: {DEFAULT_LOCK} next to the criteria file)")
|
|
46
|
+
s.add_argument("--json", action="store_true", help="print the JSON report")
|
|
47
|
+
s.add_argument("--quiet", action="store_true", help="one-line summary (compact JSON with --json)")
|
|
48
|
+
s.add_argument("--report", help="also write the JSON report to this file")
|
|
49
|
+
if name == "baseline":
|
|
50
|
+
s.add_argument("--force", action="store_true", help="overwrite an existing lockfile")
|
|
51
|
+
s.add_argument("--dry-run", action="store_true", help="run and report, write no lockfile or report file")
|
|
52
|
+
d = sub.add_parser("describe", help="print tool definitions (Anthropic, OpenAI, MCP)")
|
|
53
|
+
d.add_argument("--json", action="store_true", help="print the definitions as JSON")
|
|
54
|
+
d.add_argument("--quiet", action="store_true", help="compact JSON")
|
|
55
|
+
m = sub.add_parser("mcp", help="run an MCP server on stdio")
|
|
56
|
+
m.add_argument("--json", action="store_true", help="accepted and ignored; MCP is always JSON-RPC")
|
|
57
|
+
return p
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _run(argv: list[str]) -> int:
|
|
61
|
+
args = _build_parser().parse_args(argv)
|
|
62
|
+
if args.version:
|
|
63
|
+
print(_dump({"tool": "failfirst", "version": __version__}, False) if args.json
|
|
64
|
+
else f"failfirst {__version__}")
|
|
65
|
+
return 0
|
|
66
|
+
if args.cmd is None:
|
|
67
|
+
raise CliError("FF_E_USAGE", "a command is required (baseline, verify, describe, mcp)")
|
|
68
|
+
quiet, as_json = getattr(args, "quiet", False), args.json
|
|
69
|
+
if args.cmd == "describe":
|
|
70
|
+
doc = describe()
|
|
71
|
+
if as_json:
|
|
72
|
+
print(_dump(doc, quiet))
|
|
73
|
+
else:
|
|
74
|
+
for t in load_tools()["tools"]:
|
|
75
|
+
print(f"{t['name']}: {t['description'].split('. ')[0].rstrip('.')}.")
|
|
76
|
+
return 0
|
|
77
|
+
if args.cmd == "mcp":
|
|
78
|
+
from .mcp import serve
|
|
79
|
+
return serve()
|
|
80
|
+
tool_args: dict[str, Any] = {}
|
|
81
|
+
if args.criteria:
|
|
82
|
+
tool_args["criteria"] = args.criteria
|
|
83
|
+
if args.lock:
|
|
84
|
+
tool_args["lock"] = args.lock
|
|
85
|
+
if args.cmd == "baseline":
|
|
86
|
+
tool_args.update(force=args.force, dry_run=args.dry_run)
|
|
87
|
+
report, code = run_operation("failfirst_" + args.cmd, tool_args)
|
|
88
|
+
if args.report and not (args.cmd == "baseline" and args.dry_run):
|
|
89
|
+
try:
|
|
90
|
+
with open(args.report, "w", encoding="utf-8") as fh:
|
|
91
|
+
json.dump(report, fh, indent=2, ensure_ascii=False)
|
|
92
|
+
except OSError as exc:
|
|
93
|
+
raise CliError("FF_E_IO", f"cannot write {args.report}: {exc.strerror}") from exc
|
|
94
|
+
if as_json:
|
|
95
|
+
print(_dump(report, quiet))
|
|
96
|
+
else:
|
|
97
|
+
print(_quiet_line(report) if quiet else format_report(report))
|
|
98
|
+
return code
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def main(argv: list[str] | None = None) -> int:
|
|
102
|
+
"""Entry point; returns the process exit status."""
|
|
103
|
+
args = list(sys.argv[1:] if argv is None else argv)
|
|
104
|
+
as_json = "--json" in args
|
|
105
|
+
try:
|
|
106
|
+
return _run(args)
|
|
107
|
+
except CliError as exc:
|
|
108
|
+
err = exc
|
|
109
|
+
except Exception as exc: # noqa: BLE001 - never leak a bare stack trace
|
|
110
|
+
err = CliError("FF_E_INTERNAL", f"{type(exc).__name__}: {exc}")
|
|
111
|
+
info = err.payload()["error"]
|
|
112
|
+
print(f"failfirst: {info['code']}: {info['message']}\n hint: {info['hint']}", file=sys.stderr)
|
|
113
|
+
if as_json:
|
|
114
|
+
print(_dump(err.payload(), False))
|
|
115
|
+
return err.exit_code
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
if __name__ == "__main__": # pragma: no cover
|
|
119
|
+
sys.exit(main())
|
failfirst/core.py
ADDED
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
"""The two-phase protocol: baseline and verify (see spec/SPEC.md)."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import datetime
|
|
5
|
+
import json
|
|
6
|
+
import os
|
|
7
|
+
from typing import Callable
|
|
8
|
+
|
|
9
|
+
from . import __version__
|
|
10
|
+
from .model import SPEC_VERSION, criterion_hash
|
|
11
|
+
from .runner import evaluate, observe as default_observe
|
|
12
|
+
|
|
13
|
+
EXIT_OK, EXIT_FAIL, EXIT_USAGE, EXIT_REVIEW = 0, 1, 2, 3
|
|
14
|
+
DEFAULT_LOCK = ".failfirst.lock.json"
|
|
15
|
+
|
|
16
|
+
Observer = Callable[[dict], dict]
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class LockError(Exception):
|
|
20
|
+
"""The lockfile is missing, unreadable, or would be overwritten.
|
|
21
|
+
|
|
22
|
+
``code`` is the stable error code: FF_E_LOCK_EXISTS, FF_E_NO_LOCK or FF_E_BAD_LOCK.
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
def __init__(self, message: str, code: str = "FF_E_BAD_LOCK") -> None:
|
|
26
|
+
super().__init__(message)
|
|
27
|
+
self.code = code
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _observer(observe: Observer | None, base_dir: str) -> Observer:
|
|
31
|
+
return observe if observe is not None else (lambda c: default_observe(c, base_dir))
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def baseline(criteria: list[dict], lock_path: str, observe: Observer | None = None,
|
|
35
|
+
base_dir: str = ".", force: bool = False, dry_run: bool = False) -> tuple[dict, int]:
|
|
36
|
+
"""Run criteria against the current (unfixed) state and write the lockfile.
|
|
37
|
+
|
|
38
|
+
With ``dry_run`` the criteria are run and reported but no lockfile is written.
|
|
39
|
+
Returns (report, exit_code). Exit is 0 only if every non-judgment criterion FAILED
|
|
40
|
+
(valid proof of a gap); passed ones are vacuous, errored ones are unusable.
|
|
41
|
+
"""
|
|
42
|
+
if os.path.exists(lock_path) and not force:
|
|
43
|
+
raise LockError(f"{lock_path} already exists; baseline would erase the failure evidence "
|
|
44
|
+
"(use --force to overwrite deliberately)", code="FF_E_LOCK_EXISTS")
|
|
45
|
+
obs_fn = _observer(observe, base_dir)
|
|
46
|
+
locked, rows = {}, []
|
|
47
|
+
for c in criteria:
|
|
48
|
+
entry = {"hash": criterion_hash(c), "judgment": c["judgment"]}
|
|
49
|
+
if c["judgment"]:
|
|
50
|
+
entry["baseline"] = {"status": "n/a", "detail": "judgment: awaiting human review"}
|
|
51
|
+
else:
|
|
52
|
+
entry["baseline"] = evaluate(c, obs_fn(c))
|
|
53
|
+
locked[c["id"]] = entry
|
|
54
|
+
rows.append({"id": c["id"], "statement": c["statement"], "judgment": c["judgment"],
|
|
55
|
+
"baseline": entry["baseline"]})
|
|
56
|
+
lock = {"failfirst_lock": SPEC_VERSION, "created_at": datetime.datetime.now(
|
|
57
|
+
datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"), "criteria": locked}
|
|
58
|
+
if not dry_run:
|
|
59
|
+
with open(lock_path, "w", encoding="utf-8") as fh:
|
|
60
|
+
json.dump(lock, fh, indent=2, sort_keys=True)
|
|
61
|
+
fh.write("\n")
|
|
62
|
+
auto = [r for r in rows if not r["judgment"]]
|
|
63
|
+
bad = [r for r in auto if r["baseline"]["status"] != "failed"]
|
|
64
|
+
counts = {"failed": 0, "passed": 0, "error": 0, "judgment": len(rows) - len(auto)}
|
|
65
|
+
for r in auto:
|
|
66
|
+
counts[r["baseline"]["status"]] += 1
|
|
67
|
+
code = EXIT_OK if auto and not bad else EXIT_FAIL
|
|
68
|
+
report = {"tool": "failfirst", "version": __version__, "phase": "baseline",
|
|
69
|
+
"status": "ok" if code == EXIT_OK else "warning", "exit_code": code,
|
|
70
|
+
"summary": {"failed_as_required": counts["failed"],
|
|
71
|
+
"vacuous": counts["passed"], "errored": counts["error"],
|
|
72
|
+
"judgment": counts["judgment"]},
|
|
73
|
+
"criteria": [dict(r, vacuous=(not r["judgment"] and r["baseline"]["status"] == "passed"))
|
|
74
|
+
for r in rows]}
|
|
75
|
+
if dry_run:
|
|
76
|
+
report["dry_run"] = True
|
|
77
|
+
return report, code
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def read_lock(lock_path: str) -> dict:
|
|
81
|
+
try:
|
|
82
|
+
with open(lock_path, "r", encoding="utf-8") as fh:
|
|
83
|
+
lock = json.load(fh)
|
|
84
|
+
except FileNotFoundError:
|
|
85
|
+
raise LockError(f"no lockfile at {lock_path}; run `failfirst baseline` before the work",
|
|
86
|
+
code="FF_E_NO_LOCK") from None
|
|
87
|
+
except (OSError, ValueError) as exc:
|
|
88
|
+
raise LockError(f"cannot read lockfile {lock_path}: {exc}") from exc
|
|
89
|
+
if not isinstance(lock, dict) or lock.get("failfirst_lock") != SPEC_VERSION \
|
|
90
|
+
or not isinstance(lock.get("criteria"), dict):
|
|
91
|
+
raise LockError(f"{lock_path} is not a failfirst v{SPEC_VERSION} lockfile")
|
|
92
|
+
return lock
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def verify(criteria: list[dict], lock_path: str, observe: Observer | None = None,
|
|
96
|
+
base_dir: str = ".") -> tuple[dict, int]:
|
|
97
|
+
"""Re-run criteria; a criterion counts only if failed at baseline, unchanged, and passes now."""
|
|
98
|
+
lock = read_lock(lock_path)
|
|
99
|
+
locked = lock["criteria"]
|
|
100
|
+
obs_fn = _observer(observe, base_dir)
|
|
101
|
+
rows, current_ids = [], set()
|
|
102
|
+
for c in criteria:
|
|
103
|
+
current_ids.add(c["id"])
|
|
104
|
+
base = locked.get(c["id"])
|
|
105
|
+
row = {"id": c["id"], "statement": c["statement"], "judgment": c["judgment"]}
|
|
106
|
+
if c["judgment"]:
|
|
107
|
+
row.update(verdict="awaiting_review", reason="judgment criteria are never auto-passed")
|
|
108
|
+
elif base is None:
|
|
109
|
+
row.update(verdict="unbaselined", reason="not present at baseline; it never had a chance to fail")
|
|
110
|
+
elif base["hash"] != criterion_hash(c):
|
|
111
|
+
row.update(verdict="modified", reason="criterion changed since baseline; goalposts moved",
|
|
112
|
+
baseline=base["baseline"])
|
|
113
|
+
elif base["judgment"]:
|
|
114
|
+
row.update(verdict="modified", reason="was a judgment criterion at baseline")
|
|
115
|
+
else:
|
|
116
|
+
row["baseline"] = base["baseline"]
|
|
117
|
+
bstat = base["baseline"]["status"]
|
|
118
|
+
if bstat == "passed":
|
|
119
|
+
row.update(verdict="vacuous", reason="already passed at baseline; carries no information")
|
|
120
|
+
elif bstat == "error":
|
|
121
|
+
row.update(verdict="baseline_error", reason="baseline run errored; failure was never demonstrated")
|
|
122
|
+
else:
|
|
123
|
+
now = evaluate(c, obs_fn(c))
|
|
124
|
+
row["now"] = now
|
|
125
|
+
if now["status"] == "passed":
|
|
126
|
+
row.update(verdict="proven", reason="failed at baseline, passes now, unchanged")
|
|
127
|
+
elif now["status"] == "failed":
|
|
128
|
+
row.update(verdict="still_failing", reason=now["detail"])
|
|
129
|
+
else:
|
|
130
|
+
row.update(verdict="error", reason=now["detail"])
|
|
131
|
+
rows.append(row)
|
|
132
|
+
for cid, base in locked.items():
|
|
133
|
+
if cid not in current_ids:
|
|
134
|
+
rows.append({"id": cid, "statement": "", "judgment": base["judgment"], "baseline": base["baseline"],
|
|
135
|
+
"verdict": "removed", "reason": "present at baseline but missing now"})
|
|
136
|
+
counts: dict[str, int] = {}
|
|
137
|
+
for r in rows:
|
|
138
|
+
counts[r["verdict"]] = counts.get(r["verdict"], 0) + 1
|
|
139
|
+
auto = [r for r in rows if r["verdict"] != "awaiting_review"]
|
|
140
|
+
if not auto or any(r["verdict"] != "proven" for r in auto):
|
|
141
|
+
status, code = "fail", EXIT_FAIL
|
|
142
|
+
elif counts.get("awaiting_review"):
|
|
143
|
+
status, code = "awaiting_review", EXIT_REVIEW
|
|
144
|
+
else:
|
|
145
|
+
status, code = "pass", EXIT_OK
|
|
146
|
+
report = {"tool": "failfirst", "version": __version__, "phase": "verify", "status": status,
|
|
147
|
+
"exit_code": code, "summary": counts, "criteria": rows}
|
|
148
|
+
return report, code
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def format_report(report: dict) -> str:
|
|
152
|
+
"""Human-readable summary of a baseline or verify report."""
|
|
153
|
+
lines = []
|
|
154
|
+
if report["phase"] == "baseline":
|
|
155
|
+
lines.append("failfirst baseline")
|
|
156
|
+
for r in report["criteria"]:
|
|
157
|
+
if r["judgment"]:
|
|
158
|
+
tag = "JUDGMENT "
|
|
159
|
+
else:
|
|
160
|
+
tag = {"failed": "FAILS ok ", "passed": "VACUOUS ", "error": "ERROR "}[r["baseline"]["status"]]
|
|
161
|
+
lines.append(f" {tag} {r['id']}: {r['statement'] or r['baseline']['detail']}")
|
|
162
|
+
s = report["summary"]
|
|
163
|
+
lines.append(f"{s['failed_as_required']} failed as required, {s['vacuous']} vacuous, "
|
|
164
|
+
f"{s['errored']} errored, {s['judgment']} awaiting judgment")
|
|
165
|
+
if report["exit_code"]:
|
|
166
|
+
lines.append("WARNING: some criteria did not fail at baseline; they will not count.")
|
|
167
|
+
else:
|
|
168
|
+
lines.append("failfirst verify")
|
|
169
|
+
for r in report["criteria"]:
|
|
170
|
+
lines.append(f" {r['verdict'].upper():16} {r['id']}: {r['reason']}")
|
|
171
|
+
summ = ", ".join(f"{n} {k}" for k, n in sorted(report["summary"].items()))
|
|
172
|
+
lines.append(f"{summ}")
|
|
173
|
+
lines.append({"pass": "PASS: every criterion was proven (failed first, passes now).",
|
|
174
|
+
"fail": "FAIL: not every criterion is proven.",
|
|
175
|
+
"awaiting_review": "AWAITING REVIEW: all machine checks proven; judgment criteria need a human."
|
|
176
|
+
}[report["status"]])
|
|
177
|
+
return "\n".join(lines)
|
failfirst/mcp.py
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
"""Minimal MCP server over stdio (newline-delimited JSON-RPC 2.0): ``failfirst mcp``.
|
|
2
|
+
|
|
3
|
+
Exposes the tools in tools.json. Implements initialize, ping, tools/list and tools/call; other
|
|
4
|
+
requests get JSON-RPC error -32601. Never reads anything but the protocol stream.
|
|
5
|
+
"""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import json
|
|
9
|
+
import sys
|
|
10
|
+
from typing import Any, TextIO
|
|
11
|
+
|
|
12
|
+
from . import __version__
|
|
13
|
+
from .agent import CliError, describe, run_operation
|
|
14
|
+
|
|
15
|
+
SUPPORTED = ("2025-06-18", "2025-03-26", "2024-11-05")
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def _result(rid: Any, result: dict[str, Any]) -> dict[str, Any]:
|
|
19
|
+
return {"jsonrpc": "2.0", "id": rid, "result": result}
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _error(rid: Any, code: int, message: str) -> dict[str, Any]:
|
|
23
|
+
return {"jsonrpc": "2.0", "id": rid, "error": {"code": code, "message": message}}
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _call(params: dict[str, Any]) -> dict[str, Any]:
|
|
27
|
+
name, args = params.get("name"), params.get("arguments") or {}
|
|
28
|
+
try:
|
|
29
|
+
report, _code = run_operation(str(name), args)
|
|
30
|
+
text = json.dumps(report, ensure_ascii=False, indent=2)
|
|
31
|
+
return {"content": [{"type": "text", "text": text}], "structuredContent": report, "isError": False}
|
|
32
|
+
except CliError as exc:
|
|
33
|
+
payload = exc.payload()
|
|
34
|
+
return {"content": [{"type": "text", "text": json.dumps(payload, ensure_ascii=False, indent=2)}],
|
|
35
|
+
"structuredContent": payload, "isError": True}
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def handle(msg: Any) -> dict[str, Any] | None:
|
|
39
|
+
"""Handle one decoded JSON-RPC message; returns the response, or None for notifications."""
|
|
40
|
+
if not isinstance(msg, dict) or "method" not in msg:
|
|
41
|
+
return _error(msg.get("id") if isinstance(msg, dict) else None, -32600, "invalid request")
|
|
42
|
+
if "id" not in msg:
|
|
43
|
+
return None
|
|
44
|
+
rid, method, params = msg["id"], msg["method"], msg.get("params") or {}
|
|
45
|
+
if method == "initialize":
|
|
46
|
+
asked = params.get("protocolVersion")
|
|
47
|
+
return _result(rid, {"protocolVersion": asked if asked in SUPPORTED else SUPPORTED[0],
|
|
48
|
+
"capabilities": {"tools": {}},
|
|
49
|
+
"serverInfo": {"name": "failfirst", "version": __version__}})
|
|
50
|
+
if method == "ping":
|
|
51
|
+
return _result(rid, {})
|
|
52
|
+
if method == "tools/list":
|
|
53
|
+
return _result(rid, {"tools": describe()["mcp"]})
|
|
54
|
+
if method == "tools/call":
|
|
55
|
+
if not isinstance(params, dict) or params.get("name") not in {t["name"] for t in describe()["mcp"]}:
|
|
56
|
+
return _error(rid, -32602, f"unknown tool {params.get('name')!r}")
|
|
57
|
+
return _result(rid, _call(params))
|
|
58
|
+
return _error(rid, -32601, f"method not found: {method}")
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def serve(stdin: TextIO | None = None, stdout: TextIO | None = None) -> int:
|
|
62
|
+
"""Serve until stdin closes."""
|
|
63
|
+
stdin, stdout = stdin or sys.stdin, stdout or sys.stdout
|
|
64
|
+
if stdin is None or stdout is None: # a closed standard stream: nothing to serve
|
|
65
|
+
return 0
|
|
66
|
+
for line in stdin:
|
|
67
|
+
line = line.strip()
|
|
68
|
+
if not line:
|
|
69
|
+
continue
|
|
70
|
+
try:
|
|
71
|
+
reply = handle(json.loads(line))
|
|
72
|
+
except ValueError:
|
|
73
|
+
reply = _error(None, -32700, "parse error")
|
|
74
|
+
if reply is not None:
|
|
75
|
+
stdout.write(json.dumps(reply, ensure_ascii=False, separators=(",", ":")) + "\n")
|
|
76
|
+
stdout.flush()
|
|
77
|
+
return 0
|
failfirst/model.py
ADDED
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
"""Criterion model: validation, normalisation and content hashing (see spec/SPEC.md)."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import hashlib
|
|
5
|
+
import json
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
SPEC_VERSION = 1
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class SpecError(Exception):
|
|
12
|
+
"""The criteria file (or a criterion in it) is malformed."""
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
_CHECK_FIELDS = {
|
|
16
|
+
"command": {"type", "cmd", "argv", "cwd", "timeout", "expect_exit",
|
|
17
|
+
"expect_contains", "expect_not_contains"},
|
|
18
|
+
"file_contains": {"type", "path", "expect_contains", "expect_not_contains"},
|
|
19
|
+
"http": {"type", "url", "method", "timeout", "expect_status",
|
|
20
|
+
"expect_contains", "expect_not_contains"},
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _is_int(v: Any) -> bool:
|
|
25
|
+
return isinstance(v, int) and not isinstance(v, bool)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _str_list(cid: str, key: str, v: Any) -> list[str]:
|
|
29
|
+
if v is None:
|
|
30
|
+
return []
|
|
31
|
+
if isinstance(v, str):
|
|
32
|
+
return [v]
|
|
33
|
+
if isinstance(v, list) and all(isinstance(x, str) for x in v):
|
|
34
|
+
return list(v)
|
|
35
|
+
raise SpecError(f"criterion {cid!r}: {key} must be a string or list of strings")
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _int_field(cid: str, key: str, v: Any, default: int, minimum: int | None = None) -> int:
|
|
39
|
+
if v is None:
|
|
40
|
+
return default
|
|
41
|
+
if not _is_int(v):
|
|
42
|
+
raise SpecError(f"criterion {cid!r}: {key} must be an integer")
|
|
43
|
+
if minimum is not None and v < minimum:
|
|
44
|
+
raise SpecError(f"criterion {cid!r}: {key} must be >= {minimum}")
|
|
45
|
+
return v
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def normalize_criterion(raw: Any) -> dict:
|
|
49
|
+
"""Validate one criterion and return it with every default filled in."""
|
|
50
|
+
if not isinstance(raw, dict):
|
|
51
|
+
raise SpecError("each criterion must be an object")
|
|
52
|
+
allowed = {"id", "statement", "judgment", "check"}
|
|
53
|
+
extra = set(raw) - allowed
|
|
54
|
+
cid = raw.get("id")
|
|
55
|
+
if not isinstance(cid, str) or not cid:
|
|
56
|
+
raise SpecError("each criterion needs a non-empty string id")
|
|
57
|
+
if extra:
|
|
58
|
+
raise SpecError(f"criterion {cid!r}: unknown field(s) {sorted(extra)}")
|
|
59
|
+
statement = raw.get("statement", "")
|
|
60
|
+
if not isinstance(statement, str):
|
|
61
|
+
raise SpecError(f"criterion {cid!r}: statement must be a string")
|
|
62
|
+
judgment = raw.get("judgment", False)
|
|
63
|
+
if not isinstance(judgment, bool):
|
|
64
|
+
raise SpecError(f"criterion {cid!r}: judgment must be true or false")
|
|
65
|
+
check = raw.get("check")
|
|
66
|
+
if judgment:
|
|
67
|
+
if check is not None:
|
|
68
|
+
raise SpecError(f"criterion {cid!r}: a judgment criterion must not have a check")
|
|
69
|
+
return {"id": cid, "statement": statement, "judgment": True, "check": None}
|
|
70
|
+
if not isinstance(check, dict):
|
|
71
|
+
raise SpecError(f"criterion {cid!r}: needs a check object (or judgment: true)")
|
|
72
|
+
return {"id": cid, "statement": statement, "judgment": False,
|
|
73
|
+
"check": _normalize_check(cid, check)}
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _normalize_check(cid: str, check: dict) -> dict:
|
|
77
|
+
ctype = check.get("type", "command" if ("cmd" in check or "argv" in check) else None)
|
|
78
|
+
if ctype not in _CHECK_FIELDS:
|
|
79
|
+
raise SpecError(f"criterion {cid!r}: check.type must be one of {sorted(_CHECK_FIELDS)}")
|
|
80
|
+
extra = set(check) - _CHECK_FIELDS[ctype]
|
|
81
|
+
if extra:
|
|
82
|
+
raise SpecError(f"criterion {cid!r}: unknown check field(s) {sorted(extra)}")
|
|
83
|
+
out: dict[str, Any] = {"type": ctype}
|
|
84
|
+
has = _str_list(cid, "expect_contains", check.get("expect_contains"))
|
|
85
|
+
hasnt = _str_list(cid, "expect_not_contains", check.get("expect_not_contains"))
|
|
86
|
+
if ctype == "command":
|
|
87
|
+
cmd, argv = check.get("cmd"), check.get("argv")
|
|
88
|
+
if (cmd is None) == (argv is None):
|
|
89
|
+
raise SpecError(f"criterion {cid!r}: command check needs exactly one of cmd or argv")
|
|
90
|
+
if cmd is not None:
|
|
91
|
+
if not isinstance(cmd, str) or not cmd.strip():
|
|
92
|
+
raise SpecError(f"criterion {cid!r}: cmd must be a non-empty string")
|
|
93
|
+
out["cmd"] = cmd
|
|
94
|
+
else:
|
|
95
|
+
if not (isinstance(argv, list) and argv and all(isinstance(a, str) for a in argv)):
|
|
96
|
+
raise SpecError(f"criterion {cid!r}: argv must be a non-empty list of strings")
|
|
97
|
+
out["argv"] = list(argv)
|
|
98
|
+
cwd = check.get("cwd", ".")
|
|
99
|
+
if not isinstance(cwd, str):
|
|
100
|
+
raise SpecError(f"criterion {cid!r}: cwd must be a string")
|
|
101
|
+
out["cwd"] = cwd
|
|
102
|
+
out["timeout"] = _int_field(cid, "timeout", check.get("timeout"), 60, 1)
|
|
103
|
+
out["expect_exit"] = _int_field(cid, "expect_exit", check.get("expect_exit"), 0)
|
|
104
|
+
elif ctype == "file_contains":
|
|
105
|
+
path = check.get("path")
|
|
106
|
+
if not isinstance(path, str) or not path:
|
|
107
|
+
raise SpecError(f"criterion {cid!r}: file_contains needs a path")
|
|
108
|
+
if not has and not hasnt:
|
|
109
|
+
raise SpecError(f"criterion {cid!r}: file_contains needs expect_contains or expect_not_contains")
|
|
110
|
+
out["path"] = path
|
|
111
|
+
else:
|
|
112
|
+
url = check.get("url")
|
|
113
|
+
if not isinstance(url, str) or not url:
|
|
114
|
+
raise SpecError(f"criterion {cid!r}: http check needs a url")
|
|
115
|
+
out["url"] = url
|
|
116
|
+
method = check.get("method", "GET")
|
|
117
|
+
if not isinstance(method, str):
|
|
118
|
+
raise SpecError(f"criterion {cid!r}: method must be a string")
|
|
119
|
+
out["method"] = method.upper()
|
|
120
|
+
out["timeout"] = _int_field(cid, "timeout", check.get("timeout"), 30, 1)
|
|
121
|
+
out["expect_status"] = _int_field(cid, "expect_status", check.get("expect_status"), 200)
|
|
122
|
+
out["expect_contains"] = has
|
|
123
|
+
out["expect_not_contains"] = hasnt
|
|
124
|
+
return out
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def normalize_criteria(raw_list: Any) -> list[dict]:
|
|
128
|
+
if not isinstance(raw_list, list) or not raw_list:
|
|
129
|
+
raise SpecError("criteria must be a non-empty list")
|
|
130
|
+
out, seen = [], set()
|
|
131
|
+
for r in raw_list:
|
|
132
|
+
c = normalize_criterion(r)
|
|
133
|
+
if c["id"] in seen:
|
|
134
|
+
raise SpecError(f"duplicate criterion id {c['id']!r}")
|
|
135
|
+
seen.add(c["id"])
|
|
136
|
+
out.append(c)
|
|
137
|
+
return out
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def canonical_json(obj: Any) -> str:
|
|
141
|
+
"""Sorted keys, no whitespace, non-ASCII emitted raw. Identical across implementations."""
|
|
142
|
+
return json.dumps(obj, sort_keys=True, separators=(",", ":"), ensure_ascii=False)
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def criterion_hash(normalized: dict) -> str:
|
|
146
|
+
"""sha256 (hex) of the canonical JSON of a normalised criterion."""
|
|
147
|
+
return hashlib.sha256(canonical_json(normalized).encode("utf-8")).hexdigest()
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def load_criteria(path: str) -> list[dict]:
|
|
151
|
+
"""Load and normalise a criteria file (.json, .yaml or .yml)."""
|
|
152
|
+
with open(path, "r", encoding="utf-8") as fh:
|
|
153
|
+
text = fh.read()
|
|
154
|
+
try:
|
|
155
|
+
if path.lower().endswith((".yaml", ".yml")):
|
|
156
|
+
import yaml # lazy: only needed for YAML files
|
|
157
|
+
|
|
158
|
+
doc = yaml.safe_load(text)
|
|
159
|
+
else:
|
|
160
|
+
doc = json.loads(text)
|
|
161
|
+
except Exception as exc: # noqa: BLE001 - surface any parse error as SpecError
|
|
162
|
+
raise SpecError(f"cannot parse {path}: {exc}") from exc
|
|
163
|
+
if not isinstance(doc, dict) or "criteria" not in doc:
|
|
164
|
+
raise SpecError("criteria file must be an object with a 'criteria' list")
|
|
165
|
+
if doc.get("version", SPEC_VERSION) != SPEC_VERSION:
|
|
166
|
+
raise SpecError(f"unsupported criteria version {doc.get('version')!r}")
|
|
167
|
+
return normalize_criteria(doc["criteria"])
|
failfirst/py.typed
ADDED
|
File without changes
|
failfirst/runner.py
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
"""Observation (running a check) and evaluation (judging an observation)."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import os
|
|
5
|
+
import signal
|
|
6
|
+
import subprocess
|
|
7
|
+
import urllib.error
|
|
8
|
+
import urllib.request
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def observe(criterion: dict, base_dir: str = ".") -> dict:
|
|
12
|
+
"""Run a criterion's check and return a raw observation (see spec/SPEC.md section 5)."""
|
|
13
|
+
check = criterion["check"]
|
|
14
|
+
kind = check["type"]
|
|
15
|
+
if kind == "command":
|
|
16
|
+
return _observe_command(check, base_dir)
|
|
17
|
+
if kind == "file_contains":
|
|
18
|
+
path = os.path.join(base_dir, check["path"])
|
|
19
|
+
try:
|
|
20
|
+
with open(path, "rb") as fh:
|
|
21
|
+
return {"content": fh.read().decode("utf-8", "replace")}
|
|
22
|
+
except FileNotFoundError:
|
|
23
|
+
return {"missing": True}
|
|
24
|
+
except OSError as exc:
|
|
25
|
+
return {"error": f"cannot read file: {exc}"}
|
|
26
|
+
return _observe_http(check)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _observe_command(check: dict, base_dir: str) -> dict:
|
|
30
|
+
cwd = os.path.join(base_dir, check["cwd"])
|
|
31
|
+
posix = os.name == "posix"
|
|
32
|
+
try:
|
|
33
|
+
proc = subprocess.Popen(
|
|
34
|
+
check["argv"] if "argv" in check else check["cmd"],
|
|
35
|
+
shell="argv" not in check,
|
|
36
|
+
cwd=cwd,
|
|
37
|
+
stdin=subprocess.DEVNULL,
|
|
38
|
+
stdout=subprocess.PIPE,
|
|
39
|
+
stderr=subprocess.PIPE,
|
|
40
|
+
start_new_session=posix,
|
|
41
|
+
)
|
|
42
|
+
except OSError as exc:
|
|
43
|
+
return {"error": f"cannot start: {exc}"}
|
|
44
|
+
try:
|
|
45
|
+
out, err = proc.communicate(timeout=check["timeout"])
|
|
46
|
+
except subprocess.TimeoutExpired:
|
|
47
|
+
if posix:
|
|
48
|
+
try:
|
|
49
|
+
os.killpg(proc.pid, signal.SIGKILL)
|
|
50
|
+
except OSError:
|
|
51
|
+
pass
|
|
52
|
+
else:
|
|
53
|
+
proc.kill()
|
|
54
|
+
proc.communicate()
|
|
55
|
+
return {"error": f"timeout after {check['timeout']}s"}
|
|
56
|
+
text = out.decode("utf-8", "replace") + err.decode("utf-8", "replace")
|
|
57
|
+
return {"exit": proc.returncode, "output": text}
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _observe_http(check: dict) -> dict:
|
|
61
|
+
req = urllib.request.Request(check["url"], method=check["method"])
|
|
62
|
+
try:
|
|
63
|
+
with urllib.request.urlopen(req, timeout=check["timeout"]) as resp:
|
|
64
|
+
return {"status": resp.status, "body": resp.read().decode("utf-8", "replace")}
|
|
65
|
+
except urllib.error.HTTPError as exc:
|
|
66
|
+
return {"status": exc.code, "body": exc.read().decode("utf-8", "replace")}
|
|
67
|
+
except Exception as exc: # noqa: BLE001 - network failure is an error, not a pass/fail
|
|
68
|
+
return {"error": f"request failed: {exc}"}
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _text_checks(check: dict, text: str) -> str | None:
|
|
72
|
+
for s in check["expect_contains"]:
|
|
73
|
+
if s not in text:
|
|
74
|
+
return f"output missing expected text {s!r}"
|
|
75
|
+
for s in check["expect_not_contains"]:
|
|
76
|
+
if s in text:
|
|
77
|
+
return f"output contains forbidden text {s!r}"
|
|
78
|
+
return None
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def evaluate(criterion: dict, obs: dict) -> dict:
|
|
82
|
+
"""Turn an observation into {"status": passed|failed|error, "detail": str}."""
|
|
83
|
+
check = criterion["check"]
|
|
84
|
+
if "error" in obs:
|
|
85
|
+
return {"status": "error", "detail": str(obs["error"])}
|
|
86
|
+
kind = check["type"]
|
|
87
|
+
if kind == "command":
|
|
88
|
+
if obs["exit"] != check["expect_exit"]:
|
|
89
|
+
return {"status": "failed", "detail": f"exit {obs['exit']}, expected {check['expect_exit']}"}
|
|
90
|
+
problem = _text_checks(check, obs.get("output", ""))
|
|
91
|
+
elif kind == "file_contains":
|
|
92
|
+
if obs.get("missing"):
|
|
93
|
+
return {"status": "failed", "detail": "file does not exist"}
|
|
94
|
+
problem = _text_checks(check, obs.get("content", ""))
|
|
95
|
+
else:
|
|
96
|
+
if obs["status"] != check["expect_status"]:
|
|
97
|
+
return {"status": "failed", "detail": f"status {obs['status']}, expected {check['expect_status']}"}
|
|
98
|
+
problem = _text_checks(check, obs.get("body", ""))
|
|
99
|
+
if problem:
|
|
100
|
+
return {"status": "failed", "detail": problem}
|
|
101
|
+
return {"status": "passed", "detail": "ok"}
|