Files
opencyber/scripts/generate-limit-docs.py
mitkox 8dd13cefdf Start OpenCyber 0.5.0 private beta
Reviewed source snapshot with MCP 2.x, bounded execution and durable approvals,
private beta onboarding, and immutable candidate qualification gates.

Signed-off-by: mitkox <[email protected]>
2026-10-26 00:24:46 +02:00

149 lines
5.0 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
"""Generate the limits reference from ``opencyber.limits``.
``docs/LIMITS.md`` is the human-readable companion to the ``limit`` facts a
refusal carries. The registry owns the numbers, units, sources, and recovery
text; this script only renders them, so the reference cannot drift from the
server. ``--check`` fails when the tracked file is stale.
"""
from __future__ import annotations
import argparse
import json
from pathlib import Path
import sys
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "src"))
sys.path.insert(0, str(ROOT / "scripts"))
from lib.generated import StaleGeneratedFile, ensure_generated_file # noqa: E402
from opencyber.limits import describe # noqa: E402
MARKDOWN = ROOT / "docs" / "LIMITS.md"
GENERATE_COMMAND = "python scripts/generate-limit-docs.py"
def _bounds(row: dict) -> str:
low = "unbounded" if row["minimum"] is None else row["minimum"]
high = "unbounded" if row["maximum"] is None else row["maximum"]
if row["minimum"] is None and row["maximum"] is None:
return "fixed"
return f"{low} to {high}"
def _escape(value: str) -> str:
return value.replace("|", "\\|")
def render() -> str:
rows = describe()
lines = [
"<!-- Generated by scripts/generate-limit-docs.py. Do not edit by hand. -->",
"",
"# Limits and recovery",
"",
"Every resource ceiling the server enforces is registered in",
"`src/opencyber/limits.py`. When a request hits one, the refusal carries",
"machine-readable facts instead of a sentence:",
"",
"```json",
json.dumps(
{
"id": "workspace.read_max_bytes",
"unit": "bytes",
"effective": 1048576,
"requested": None,
"default": 1048576,
"minimum": 1,
"maximum": 67108864,
"source": "argument",
"setting": None,
"parameter": "max_bytes",
"recovery": "Pass a larger max_bytes value, or page with the returned offset.",
"does_not_raise": "The client's own response or context budget.",
},
indent=2,
),
"```",
"",
"Read `effective` to learn what was enforced, `source` and `setting` or",
"`parameter` to learn where to change it, `recovery` to learn the next",
"action, and `does_not_raise` to avoid changing the wrong thing. A limit",
"is not a suggestion: values outside `minimum`–`maximum` are rejected",
"rather than silently clamped.",
"",
"Regenerate after changing the registry:",
"",
"```sh",
GENERATE_COMMAND,
"```",
"",
"## Registry",
"",
"| Limit | Unit | Default | Bounds | Source | Applies to |",
"| --- | --- | --- | --- | --- | --- |",
]
for row in rows:
setting = f" (`{row['setting']}`)" if row["setting"] else ""
lines.append(
f"| `{row['id']}` | {row['unit']} | {row['default']} | {_bounds(row)} | "
f"{row['source']}{setting} | {_escape(row['applies_to'])} |"
)
lines.extend(
[
"",
"## Meaning and recovery",
"",
"| Limit | What it bounds | What raises it | What it does not raise |",
"| --- | --- | --- | --- |",
]
)
for row in rows:
lines.append(
f"| `{row['id']}` | {_escape(row['description'])} | {_escape(row['recovery'])} | "
f"{_escape(row['does_not_raise'])} |"
)
lines.extend(
[
"",
"## Adding a limit",
"",
"1. Add a `Limit` to `_LIMITS` in `src/opencyber/limits.py`.",
"2. Enforce it in the owning module and build the failure with",
" `opencyber.limits.raise_exceeded()` or pass",
" `opencyber.limits.facts()` as `details.limit`.",
"3. Cross-check the numeric default against the owning module constant in",
" `tests/test_limits.py`.",
"4. Regenerate this page.",
"",
"A ceiling that exists in code but not in this registry is a review bug:",
"the caller then has to parse prose to discover what stopped the call.",
"",
]
)
return "\n".join(lines)
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--check", action="store_true", help="fail if the tracked file is stale instead of writing it")
args = parser.parse_args()
try:
wrote = ensure_generated_file(MARKDOWN, render(), check=args.check, generate_command=GENERATE_COMMAND)
except StaleGeneratedFile as error:
print(str(error), file=sys.stderr)
return 1
if args.check:
print(f"{MARKDOWN.relative_to(ROOT)} is current")
else:
print(f"{'wrote' if wrote else 'unchanged'} {MARKDOWN.relative_to(ROOT)}")
return 0
if __name__ == "__main__":
raise SystemExit(main())