factory-framework 0.3.1__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.
- factory_framework-0.3.1.dist-info/METADATA +205 -0
- factory_framework-0.3.1.dist-info/RECORD +24 -0
- factory_framework-0.3.1.dist-info/WHEEL +4 -0
- factory_framework-0.3.1.dist-info/entry_points.txt +3 -0
- factory_framework-0.3.1.dist-info/licenses/LICENSE +21 -0
- ff/__init__.py +18 -0
- ff/__main__.py +7 -0
- ff/cli.py +320 -0
- ff/export.py +234 -0
- ff/gitio.py +229 -0
- ff/lint.py +202 -0
- ff/mcp.py +138 -0
- ff/models.py +372 -0
- ff/parse.py +457 -0
- ff/proofs.py +178 -0
- ff/py.typed +0 -0
- ff/query.py +118 -0
- ff/runner.py +239 -0
- ff/scaffold.py +239 -0
- ff/schemas.py +141 -0
- ff/skill/SKILL.md +47 -0
- ff/skill/references/authoring.md +59 -0
- ff/skill/references/checks.md +69 -0
- ff/skill/references/workflow.md +55 -0
ff/models.py
ADDED
|
@@ -0,0 +1,372 @@
|
|
|
1
|
+
"""Core constants, errors, sanitization, JSON/file helpers, and contract dataclasses."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import hashlib
|
|
6
|
+
import json
|
|
7
|
+
import math
|
|
8
|
+
import os
|
|
9
|
+
import re
|
|
10
|
+
import stat
|
|
11
|
+
import tempfile
|
|
12
|
+
import unicodedata
|
|
13
|
+
from contextlib import suppress
|
|
14
|
+
from dataclasses import dataclass, field, fields
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
from typing import Any, Literal
|
|
17
|
+
|
|
18
|
+
FORMAT, MAX_FILE, JSON_WIDTH = 1, 4 << 20, 120
|
|
19
|
+
SEG_PAT = r"[a-z0-9]+(?:-[a-z0-9]+)*"
|
|
20
|
+
INTENT_ID_PAT, SPEC_ID_PAT = rf"^intent_{SEG_PAT}(?:_{SEG_PAT})*$", rf"^spec_{SEG_PAT}(?:_{SEG_PAT})*$"
|
|
21
|
+
CHECK_ID_PAT = r"^test_[a-z0-9]+(?:_[a-z0-9]+)*(?:__[a-z0-9]+(?:_[a-z0-9]+)*)?$"
|
|
22
|
+
CHANGE_FILE_ID_PAT = r"^\d{4}-\d{2}-\d{2}_[a-z0-9]+(?:-[a-z0-9]+)*$"
|
|
23
|
+
CHANGE_ID_PAT = rf"^(?:{CHANGE_FILE_ID_PAT[1:-1]}|gh-[1-9][0-9]*)$"
|
|
24
|
+
DOMAIN_PAT, METRIC_PAT = rf"^{SEG_PAT}$", r"^[a-zA-Z0-9][a-zA-Z0-9_.-]{0,63}$"
|
|
25
|
+
RUNNER_EXT_PAT = r"^\.[a-z0-9]+$"
|
|
26
|
+
DOMAIN_RE, RUNNER_EXT_RE = re.compile(DOMAIN_PAT), re.compile(RUNNER_EXT_PAT)
|
|
27
|
+
INTENT_ID_RE, SPEC_ID_RE = re.compile(INTENT_ID_PAT), re.compile(SPEC_ID_PAT)
|
|
28
|
+
CHECK_ID_RE, CHANGE_FILE_ID_RE = re.compile(CHECK_ID_PAT), re.compile(CHANGE_FILE_ID_PAT)
|
|
29
|
+
CHANGE_ID_RE, METRIC_RE = re.compile(CHANGE_ID_PAT), re.compile(METRIC_PAT)
|
|
30
|
+
GATE_TOKENS = ("error", "failing", "unproven", "unclear", "uncovered", "partial")
|
|
31
|
+
DEFAULT_FAIL_ON = GATE_TOKENS[:-1]
|
|
32
|
+
CHANGE_TYPES = ("feat", "fix", "refactor", "perf", "docs", "test", "build", "ci", "chore", "revert")
|
|
33
|
+
CHANGE_STATES = ("open", "done", "dropped")
|
|
34
|
+
DEFAULT_RUNNERS: dict[str, tuple[str, ...]] = {
|
|
35
|
+
".py": ("python3", "{file}"),
|
|
36
|
+
".sh": ("bash", "{file}"),
|
|
37
|
+
**dict.fromkeys((".js", ".mjs", ".cjs"), ("node", "{file}")),
|
|
38
|
+
}
|
|
39
|
+
_DENY_EXACT = {"PYTHONPATH", "PYTHONHOME", "PYTHONSTARTUP", "NODE_OPTIONS", "BASH_ENV", "ENV", "CDPATH", "IFS"}
|
|
40
|
+
ENV_DENY_EXACT = frozenset(_DENY_EXACT)
|
|
41
|
+
ENV_DENY_PREFIXES = ("LD_", "DYLD_", "FF_")
|
|
42
|
+
|
|
43
|
+
_FMT = r"\u00ad\u0600-\u0605\u061c\u06dd\u070f\u0890\u0891\u08e2\u180e\u200b-\u200f\u202a-\u202e\u2060-\u2064\u2066-\u206f\ufeff\ufff9-\ufffb"
|
|
44
|
+
_TERMINAL_RE, _UNPRINTABLE_RE = (
|
|
45
|
+
re.compile(rf"[\x7f-\x9f\u2028\u2029{_FMT}]"),
|
|
46
|
+
re.compile(rf"[\x00-\x1f\x7f-\x9f\u2028\u2029{_FMT}]"),
|
|
47
|
+
)
|
|
48
|
+
_MD_LINK_RE, _MD_CODE_RE = re.compile(r"!?\[([^\]]+)\]\([^)]*\)"), re.compile(r"`([^`]+)`")
|
|
49
|
+
_MD_EMPH_RE, _NON_ALNUM_RE = re.compile(r"[*_~]+"), re.compile(r"[^a-z0-9]+")
|
|
50
|
+
|
|
51
|
+
Severity = Literal["error", "warning", "info"]
|
|
52
|
+
LinkSource = Literal["convention", "override"]
|
|
53
|
+
CheckKind = Literal["pytest", "runner", "argv"]
|
|
54
|
+
ChangesSource = Literal["files", "github"]
|
|
55
|
+
RecordStatus = Literal["pass", "fail", "error"]
|
|
56
|
+
SpecStatus = Literal["PROVEN", "FAILING", "ERROR", "UNPROVEN", "UNCLEAR"]
|
|
57
|
+
IntentStatus = Literal["PROVEN", "PARTIAL", "FAILING", "ERROR", "UNPROVEN", "UNCLEAR", "UNCOVERED"]
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
class Error(Exception):
|
|
61
|
+
"""Operational or contract failure (exit code 1)."""
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
class InputError(Error):
|
|
65
|
+
"""Invalid CLI usage, missing factory, or bad input arguments (exit code 2)."""
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def _esc(match: re.Match[str]) -> str:
|
|
69
|
+
u = match[0].encode("utf-16-be").hex()
|
|
70
|
+
return "".join(f"\\u{u[i : i + 4]}" for i in range(0, len(u), 4))
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def printable(text: str) -> str:
|
|
74
|
+
"""Escape control and invisible characters for single-line stderr diagnostics."""
|
|
75
|
+
return _UNPRINTABLE_RE.sub(_esc, text)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _jstr(val: object) -> str:
|
|
79
|
+
return json.dumps(val, ensure_ascii=False, allow_nan=False)
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def encode_compact(value: object) -> bytes:
|
|
83
|
+
"""Serialize `value` to compact sorted-key UTF-8 JSON ending in newline."""
|
|
84
|
+
try:
|
|
85
|
+
raw = json.dumps(value, ensure_ascii=False, allow_nan=False, sort_keys=True, separators=(",", ":"))
|
|
86
|
+
return f"{raw}\n".encode()
|
|
87
|
+
except (TypeError, ValueError, UnicodeEncodeError) as exc:
|
|
88
|
+
raise Error("JSON payload must contain finite UTF-8 values") from exc
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def terminal_json(value: object) -> bytes:
|
|
92
|
+
"""Serialize `value` to compact UTF-8 JSON with terminal control sequences escaped."""
|
|
93
|
+
text = encode_compact(value).decode("utf-8")
|
|
94
|
+
return (_TERMINAL_RE.sub(_esc, text) if _TERMINAL_RE.search(text) else text).encode()
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _fmt_node(val: Any, ind: int = 0, col: int = 0, comma: int = 0) -> str:
|
|
98
|
+
pad, inn = " " * ind, " " * (ind + 2)
|
|
99
|
+
if isinstance(val, dict):
|
|
100
|
+
if not val:
|
|
101
|
+
return "{}"
|
|
102
|
+
kvs, n = sorted(val.items(), key=lambda kv: str(kv[0])), len(val) - 1
|
|
103
|
+
rows = [
|
|
104
|
+
f"{(p := f'{inn}{_jstr(str(k))}: ')}{_fmt_node(v, ind + 2, len(p), i < n)}{',' * (i < n)}"
|
|
105
|
+
for i, (k, v) in enumerate(kvs)
|
|
106
|
+
]
|
|
107
|
+
return "\n".join(["{", *rows, f"{pad}}}"])
|
|
108
|
+
if isinstance(val, (list, tuple)):
|
|
109
|
+
if not val:
|
|
110
|
+
return "[]"
|
|
111
|
+
flat = all(not isinstance(x, (dict, list, tuple)) for x in val)
|
|
112
|
+
inline = f"[{', '.join(_jstr(x) for x in val)}]" if flat else ""
|
|
113
|
+
if inline and (col or ind) + len(inline) + comma <= JSON_WIDTH:
|
|
114
|
+
return inline
|
|
115
|
+
n = len(val) - 1
|
|
116
|
+
rows = [f"{inn}{_fmt_node(x, ind + 2, ind + 2, i < n)}{',' * (i < n)}" for i, x in enumerate(val)]
|
|
117
|
+
return "\n".join(["[", *rows, f"{pad}]"])
|
|
118
|
+
return _jstr(val)
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def format_json(value: object) -> str:
|
|
122
|
+
"""Format `value` as deterministic, dprint-compatible pretty UTF-8 JSON."""
|
|
123
|
+
return _fmt_node(value) + "\n"
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def sha256_hex(data: bytes) -> str:
|
|
127
|
+
return f"sha256:{hashlib.sha256(data).hexdigest()}"
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def slugify_heading(title: str) -> str:
|
|
131
|
+
raw = _MD_EMPH_RE.sub("", _MD_CODE_RE.sub(r"\1", _MD_LINK_RE.sub(r"\1", title)))
|
|
132
|
+
ascii_t = unicodedata.normalize("NFKD", raw).encode("ascii", "ignore").decode("ascii").lower()
|
|
133
|
+
return _NON_ALNUM_RE.sub("-", ascii_t).strip("-")
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def is_denied_env(name: str) -> bool:
|
|
137
|
+
bad_chars = not name or "=" in name or any(c.isspace() for c in name)
|
|
138
|
+
return bad_chars or name in ENV_DENY_EXACT or name.startswith(ENV_DENY_PREFIXES)
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def is_finite_number(value: object) -> bool:
|
|
142
|
+
return not isinstance(value, bool) and isinstance(value, (int, float)) and math.isfinite(float(value))
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def read_safe_bytes(path: Path, label: str = "") -> bytes:
|
|
146
|
+
"""Read `path` after enforcing symlink refusal and `MAX_FILE` byte cap."""
|
|
147
|
+
tag = label or path.name
|
|
148
|
+
if path.is_symlink():
|
|
149
|
+
raise Error(f"{tag}: symlinks inside factory/ are forbidden")
|
|
150
|
+
if len(data := path.read_bytes()) > MAX_FILE:
|
|
151
|
+
raise Error(f"{tag}: file exceeds {MAX_FILE} bytes")
|
|
152
|
+
return data
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def read_json_obj(path: Path, label: str = "") -> dict[str, Any]:
|
|
156
|
+
"""Read and parse a UTF-8 JSON object from `path` safely."""
|
|
157
|
+
tag = label or path.name
|
|
158
|
+
try:
|
|
159
|
+
parsed = json.loads(read_safe_bytes(path, tag).decode("utf-8"))
|
|
160
|
+
except (UnicodeDecodeError, json.JSONDecodeError) as exc:
|
|
161
|
+
raise Error(f"{tag}: invalid JSON ({exc})") from exc
|
|
162
|
+
if not isinstance(parsed, dict):
|
|
163
|
+
raise Error(f"{tag}: expected JSON object")
|
|
164
|
+
return parsed
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def atomic_write(path: Path, data: bytes) -> None:
|
|
168
|
+
if path.is_symlink():
|
|
169
|
+
raise Error(f"{path}: refusing to overwrite symlink")
|
|
170
|
+
with suppress(FileNotFoundError):
|
|
171
|
+
if not stat.S_ISREG(os.lstat(path).st_mode):
|
|
172
|
+
raise Error(f"{path}: refusing to overwrite non-regular file")
|
|
173
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
174
|
+
fd, tmp_name = tempfile.mkstemp(dir=path.parent, prefix=f".{path.name}.", suffix=".tmp")
|
|
175
|
+
try:
|
|
176
|
+
with os.fdopen(fd, "wb") as handle:
|
|
177
|
+
handle.write(data)
|
|
178
|
+
Path(tmp_name).replace(path)
|
|
179
|
+
except BaseException:
|
|
180
|
+
Path(tmp_name).unlink(missing_ok=True)
|
|
181
|
+
raise
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def _dc_val(v: Any) -> Any:
|
|
185
|
+
if isinstance(v, tuple):
|
|
186
|
+
return list(v)
|
|
187
|
+
if isinstance(v, dict):
|
|
188
|
+
return {k: x.to_dict() if hasattr(x, "to_dict") else x for k, x in sorted(v.items())}
|
|
189
|
+
return v
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def _dc_dict(obj: Any, *drop: str) -> dict[str, Any]:
|
|
193
|
+
return {f.name: _dc_val(getattr(obj, f.name)) for f in fields(obj) if f.name not in drop}
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
@dataclass(frozen=True, slots=True)
|
|
197
|
+
class MetricRule:
|
|
198
|
+
min: float | int | None = None
|
|
199
|
+
max: float | int | None = None
|
|
200
|
+
precision: int | None = None
|
|
201
|
+
unit: str = ""
|
|
202
|
+
|
|
203
|
+
def evaluate(self, raw: float | int) -> tuple[float | int, bool]:
|
|
204
|
+
if isinstance(raw, bool):
|
|
205
|
+
raise TypeError("metric value must not be bool")
|
|
206
|
+
v = raw if isinstance(raw, int) else float(raw)
|
|
207
|
+
val: float | int = v if self.precision is None else round(float(v), self.precision or None)
|
|
208
|
+
return val, (self.min is None or val >= self.min) and (self.max is None or val <= self.max)
|
|
209
|
+
|
|
210
|
+
def to_dict(self) -> dict[str, Any]:
|
|
211
|
+
return _dc_dict(self)
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
@dataclass(frozen=True, slots=True)
|
|
215
|
+
class SpecOverride:
|
|
216
|
+
serves: tuple[str, ...] | None = None
|
|
217
|
+
metrics: dict[str, MetricRule] = field(default_factory=dict)
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
@dataclass(frozen=True, slots=True)
|
|
221
|
+
class CheckOverride:
|
|
222
|
+
file: str = ""
|
|
223
|
+
argv: tuple[str, ...] | None = None
|
|
224
|
+
proves: tuple[str, ...] | None = None
|
|
225
|
+
metrics: dict[str, MetricRule] = field(default_factory=dict)
|
|
226
|
+
timeout: int | None = None
|
|
227
|
+
serial: bool = False
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
@dataclass(frozen=True, slots=True)
|
|
231
|
+
class DomainCheckConfig:
|
|
232
|
+
domain: str
|
|
233
|
+
file: str = ""
|
|
234
|
+
specs: dict[str, SpecOverride] = field(default_factory=dict)
|
|
235
|
+
checks: dict[str, CheckOverride] = field(default_factory=dict)
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
@dataclass(frozen=True, slots=True)
|
|
239
|
+
class Config:
|
|
240
|
+
version: int = FORMAT
|
|
241
|
+
name: str = ""
|
|
242
|
+
fail_on: tuple[str, ...] = DEFAULT_FAIL_ON
|
|
243
|
+
changes_source: ChangesSource = "files"
|
|
244
|
+
github_label: str = "ff-change"
|
|
245
|
+
pytest_argv: tuple[str, ...] = ("pytest",)
|
|
246
|
+
runners: dict[str, tuple[str, ...]] = field(default_factory=dict)
|
|
247
|
+
jobs: int = 0
|
|
248
|
+
timeout: int = 120
|
|
249
|
+
env: tuple[str, ...] = ()
|
|
250
|
+
|
|
251
|
+
def effective_runners(self) -> dict[str, tuple[str, ...]]:
|
|
252
|
+
"""Merge default polyglot extension runners with `run.runners` overrides."""
|
|
253
|
+
return DEFAULT_RUNNERS | self.runners
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
@dataclass(frozen=True, slots=True)
|
|
257
|
+
class Intent:
|
|
258
|
+
id: str
|
|
259
|
+
domain: str
|
|
260
|
+
title: str
|
|
261
|
+
headings: tuple[str, ...]
|
|
262
|
+
body: str
|
|
263
|
+
path: str
|
|
264
|
+
line: int
|
|
265
|
+
unclear: bool
|
|
266
|
+
specs: tuple[str, ...] = ()
|
|
267
|
+
|
|
268
|
+
def to_dict(self) -> dict[str, Any]:
|
|
269
|
+
return _dc_dict(self, "body")
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
@dataclass(frozen=True, slots=True)
|
|
273
|
+
class Spec:
|
|
274
|
+
id: str
|
|
275
|
+
domain: str
|
|
276
|
+
title: str
|
|
277
|
+
headings: tuple[str, ...]
|
|
278
|
+
body: str
|
|
279
|
+
path: str
|
|
280
|
+
line: int
|
|
281
|
+
unclear: bool
|
|
282
|
+
serves: tuple[str, ...] = ()
|
|
283
|
+
link_source: LinkSource = "convention"
|
|
284
|
+
metrics: dict[str, MetricRule] = field(default_factory=dict)
|
|
285
|
+
checks: tuple[str, ...] = ()
|
|
286
|
+
|
|
287
|
+
def to_dict(self) -> dict[str, Any]:
|
|
288
|
+
return _dc_dict(self, "body")
|
|
289
|
+
|
|
290
|
+
|
|
291
|
+
@dataclass(frozen=True, slots=True)
|
|
292
|
+
class Check:
|
|
293
|
+
id: str
|
|
294
|
+
domain: str
|
|
295
|
+
kind: CheckKind
|
|
296
|
+
path: str
|
|
297
|
+
line: int
|
|
298
|
+
target: str
|
|
299
|
+
argv: tuple[str, ...] | None
|
|
300
|
+
proves: tuple[str, ...]
|
|
301
|
+
link_source: LinkSource
|
|
302
|
+
timeout: int
|
|
303
|
+
serial: bool
|
|
304
|
+
doc: str = ""
|
|
305
|
+
|
|
306
|
+
def to_dict(self) -> dict[str, Any]:
|
|
307
|
+
return _dc_dict(self)
|
|
308
|
+
|
|
309
|
+
|
|
310
|
+
@dataclass(frozen=True, slots=True)
|
|
311
|
+
class Change:
|
|
312
|
+
id: str
|
|
313
|
+
type: str
|
|
314
|
+
touches: tuple[str, ...]
|
|
315
|
+
state: str
|
|
316
|
+
path: str
|
|
317
|
+
title: str
|
|
318
|
+
motivation: str
|
|
319
|
+
changes: str
|
|
320
|
+
impact: str = ""
|
|
321
|
+
url: str = ""
|
|
322
|
+
|
|
323
|
+
def to_dict(self) -> dict[str, Any]:
|
|
324
|
+
head = {"id": self.id, "type": self.type, "state": self.state, "title": self.title, "path": self.path}
|
|
325
|
+
return head | {"touches": list(self.touches)} | ({"url": self.url} if self.url else {})
|
|
326
|
+
|
|
327
|
+
|
|
328
|
+
@dataclass(frozen=True, slots=True)
|
|
329
|
+
class Diagnostic:
|
|
330
|
+
code: str
|
|
331
|
+
severity: Severity
|
|
332
|
+
message: str
|
|
333
|
+
path: str = ""
|
|
334
|
+
line: int = 0
|
|
335
|
+
item_id: str = ""
|
|
336
|
+
hint: str = ""
|
|
337
|
+
|
|
338
|
+
def to_dict(self) -> dict[str, Any]:
|
|
339
|
+
h = {"code": self.code, "hint": self.hint or None, "item_id": self.item_id or None, "line": self.line or None}
|
|
340
|
+
return h | {"message": self.message, "path": self.path or None, "severity": self.severity}
|
|
341
|
+
|
|
342
|
+
|
|
343
|
+
@dataclass(frozen=True, slots=True)
|
|
344
|
+
class CheckRecord:
|
|
345
|
+
check: str
|
|
346
|
+
status: RecordStatus
|
|
347
|
+
summary: str
|
|
348
|
+
metrics: dict[str, float | int] = field(default_factory=dict)
|
|
349
|
+
evidence: tuple[str, ...] = ()
|
|
350
|
+
proves: tuple[str, ...] = ()
|
|
351
|
+
|
|
352
|
+
def to_record_dict(self) -> dict[str, Any]:
|
|
353
|
+
return _dc_dict(self, "proves")
|
|
354
|
+
|
|
355
|
+
def to_proof_entry(self) -> dict[str, Any]:
|
|
356
|
+
return _dc_dict(self)
|
|
357
|
+
|
|
358
|
+
|
|
359
|
+
@dataclass(frozen=True, slots=True)
|
|
360
|
+
class Factory:
|
|
361
|
+
root: Path
|
|
362
|
+
factory_dir: Path
|
|
363
|
+
name: str
|
|
364
|
+
config: Config
|
|
365
|
+
intents: dict[str, Intent]
|
|
366
|
+
specs: dict[str, Spec]
|
|
367
|
+
checks: dict[str, Check]
|
|
368
|
+
changes: dict[str, Change]
|
|
369
|
+
domains: tuple[str, ...]
|
|
370
|
+
files: dict[str, str]
|
|
371
|
+
domain_files: dict[str, dict[str, str]]
|
|
372
|
+
diagnostics: tuple[Diagnostic, ...] = ()
|