forgeproof-cli 0.2.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.
Files changed (89) hide show
  1. forge_gate/__init__.py +44 -0
  2. forge_gate/_deprecated_cli.py +16 -0
  3. forgeproof/__init__.py +3 -0
  4. forgeproof/catalog.py +110 -0
  5. forgeproof/cli.py +560 -0
  6. forgeproof/config.py +339 -0
  7. forgeproof/data/gate_catalog.json +66 -0
  8. forgeproof/data/host_sets.json +7 -0
  9. forgeproof/debug_caller.py +271 -0
  10. forgeproof/debug_core.py +368 -0
  11. forgeproof/fixture_engine.py +81 -0
  12. forgeproof/fixtures/__init__.py +19 -0
  13. forgeproof/fixtures/decision_tree_id3.py +90 -0
  14. forgeproof/fixtures/gradient_descent_momentum.py +73 -0
  15. forgeproof/fixtures/kmeans_clustering.py +98 -0
  16. forgeproof/fixtures/knn_classifier.py +79 -0
  17. forgeproof/fixtures/linear_regression_gd.py +77 -0
  18. forgeproof/fixtures/logistic_regression.py +85 -0
  19. forgeproof/fixtures/naive_bayes_text.py +114 -0
  20. forgeproof/fixtures/perceptron.py +84 -0
  21. forgeproof/fixtures/polynomial_regression.py +67 -0
  22. forgeproof/fixtures/ridge_regression_normal_eq.py +75 -0
  23. forgeproof/ledger.py +633 -0
  24. forgeproof/lens_tools/__init__.py +11 -0
  25. forgeproof/lens_tools/guard_lens.py +1250 -0
  26. forgeproof/lens_tools/invariant_contracts/linear_regression_gd.json +74 -0
  27. forgeproof/lens_tools/invariant_contracts/polynomial_regression.json +86 -0
  28. forgeproof/lens_tools/invariant_contracts/ridge_regression_normal_eq.json +86 -0
  29. forgeproof/lens_tools/invariant_gate.py +199 -0
  30. forgeproof/lens_tools/metamorphic/__init__.py +9 -0
  31. forgeproof/lens_tools/metamorphic/relations.py +962 -0
  32. forgeproof/lens_tools/metamorphic/runner.py +112 -0
  33. forgeproof/lens_tools/twin_consensus.py +395 -0
  34. forgeproof/lenses.py +923 -0
  35. forgeproof/paths.py +56 -0
  36. forgeproof/reference/ORIGIN.md +29 -0
  37. forgeproof/reference/decision_tree_id3.py +197 -0
  38. forgeproof/reference/gradient_descent_momentum.py +141 -0
  39. forgeproof/reference/kmeans_clustering.py +139 -0
  40. forgeproof/reference/knn_classifier.py +118 -0
  41. forgeproof/reference/linear_regression_gd.py +106 -0
  42. forgeproof/reference/logistic_regression.py +141 -0
  43. forgeproof/reference/naive_bayes_text.py +152 -0
  44. forgeproof/reference/perceptron.py +123 -0
  45. forgeproof/reference/polynomial_regression.py +125 -0
  46. forgeproof/reference/ridge_regression_normal_eq.py +165 -0
  47. forgeproof/runner.py +147 -0
  48. forgeproof/scout/__init__.py +7 -0
  49. forgeproof/scout/behaviour.py +365 -0
  50. forgeproof/scout/box.py +581 -0
  51. forgeproof/scout/cards.py +180 -0
  52. forgeproof/scout/contract.py +37 -0
  53. forgeproof/scout/corpus.py +104 -0
  54. forgeproof/scout/embed.py +217 -0
  55. forgeproof/scout/engines/__init__.py +1 -0
  56. forgeproof/scout/engines/chaos.py +454 -0
  57. forgeproof/scout/engines/chaos_port.py +1331 -0
  58. forgeproof/scout/engines/chaos_runner.py +178 -0
  59. forgeproof/scout/engines/executor_port.py +239 -0
  60. forgeproof/scout/envfit.py +54 -0
  61. forgeproof/scout/experience.py +161 -0
  62. forgeproof/scout/fetchproxy.py +368 -0
  63. forgeproof/scout/ghcache.py +395 -0
  64. forgeproof/scout/ghpool.py +253 -0
  65. forgeproof/scout/ghsearch.py +248 -0
  66. forgeproof/scout/ids.py +82 -0
  67. forgeproof/scout/intent_lens.py +170 -0
  68. forgeproof/scout/learn.py +583 -0
  69. forgeproof/scout/meaning_lens.py +231 -0
  70. forgeproof/scout/outcomes.py +42 -0
  71. forgeproof/scout/plant.py +327 -0
  72. forgeproof/scout/ratify.py +214 -0
  73. forgeproof/scout/report.py +448 -0
  74. forgeproof/scout/rule2.py +177 -0
  75. forgeproof/scout/shape.py +107 -0
  76. forgeproof/scout/shape_lens.py +71 -0
  77. forgeproof/scout/signature.py +52 -0
  78. forgeproof/scout/slots.py +39 -0
  79. forgeproof/scout/upstream_facts.py +536 -0
  80. forgeproof/unsupported.py +83 -0
  81. forgeproof/verifier.py +208 -0
  82. forgeproof/view_coverage.py +166 -0
  83. forgeproof_cli-0.2.0.dist-info/METADATA +285 -0
  84. forgeproof_cli-0.2.0.dist-info/RECORD +89 -0
  85. forgeproof_cli-0.2.0.dist-info/WHEEL +5 -0
  86. forgeproof_cli-0.2.0.dist-info/entry_points.txt +3 -0
  87. forgeproof_cli-0.2.0.dist-info/licenses/LICENSE +201 -0
  88. forgeproof_cli-0.2.0.dist-info/licenses/NOTICE +23 -0
  89. forgeproof_cli-0.2.0.dist-info/top_level.txt +2 -0
forgeproof/verifier.py ADDED
@@ -0,0 +1,208 @@
1
+ """Verdict engine: compare user execution against the AURA oracle.
2
+
3
+ Returns one of four states:
4
+ PASS — user code ran and matched the oracle within tolerance.
5
+ FAIL — user code ran but output differed, an assertion fired, or it crashed.
6
+ UNSTABLE — the run was non-deterministic (oracle itself varied) or resource limits hit.
7
+ UNSUPPORTED — the pattern or oracle is not available / not gate-ready.
8
+
9
+ NO LLM judgment is used. The verdict is derived entirely from subprocess exit
10
+ codes and structured numeric comparison.
11
+ """
12
+ from __future__ import annotations
13
+
14
+ import json
15
+ import re
16
+ from dataclasses import dataclass, field
17
+ from pathlib import Path
18
+ from typing import Any, Dict, List, Optional, Tuple
19
+
20
+ from .runner import RunResult
21
+
22
+
23
+ @dataclass(frozen=True)
24
+ class Verdict:
25
+ """Final gate verdict for one user file against one pattern."""
26
+
27
+ status: str # PASS | FAIL | UNSTABLE | UNSUPPORTED
28
+ pattern: str
29
+ user_file: str
30
+ reason: str
31
+ oracle_exit: int = -1
32
+ user_exit: int = -1
33
+ metrics: Dict[str, Any] = field(default_factory=dict)
34
+
35
+
36
+ def _parse_gate_json(stdout: str) -> Optional[Dict]:
37
+ """Look for a JSON object emitted by the fixture harness."""
38
+ for line in reversed(stdout.splitlines()):
39
+ line = line.strip()
40
+ if line.startswith("FORGE_GATE_RESULT "):
41
+ payload = line[len("FORGE_GATE_RESULT "):]
42
+ try:
43
+ return json.loads(payload)
44
+ except json.JSONDecodeError:
45
+ continue
46
+ if line.startswith("{") and line.endswith("}"):
47
+ try:
48
+ return json.loads(line)
49
+ except json.JSONDecodeError:
50
+ continue
51
+ return None
52
+
53
+
54
+ def _extract_numbers(text: str) -> List[Tuple[str, float]]:
55
+ """Extract named numeric metrics from stdout, e.g. `accuracy = 0.950`."""
56
+ pairs: List[Tuple[str, float]] = []
57
+ for line in text.splitlines():
58
+ for m in re.finditer(r"(\w+)\s*=\s*([-+]?[0-9]*\.?[0-9]+(?:[eE][-+]?[0-9]+)?)", line):
59
+ name = m.group(1)
60
+ val = float(m.group(2))
61
+ if name.lower() in {"exit", "code", "line", "seed"}:
62
+ continue
63
+ pairs.append((name, val))
64
+ return pairs
65
+
66
+
67
+ def _compare_metrics(
68
+ oracle_metrics: Dict[str, Any],
69
+ user_metrics: Dict[str, Any],
70
+ tolerance: float = 1e-6,
71
+ ) -> Tuple[bool, str]:
72
+ """Compare two metric dictionaries within tolerance. Returns (ok, reason)."""
73
+ if not oracle_metrics and not user_metrics:
74
+ return True, "no numeric metrics to compare"
75
+
76
+ for key in oracle_metrics:
77
+ if key not in user_metrics:
78
+ return False, f"metric '{key}' missing from user output"
79
+ o = oracle_metrics[key]
80
+ u = user_metrics[key]
81
+ if isinstance(o, (int, float)) and isinstance(u, (int, float)):
82
+ denom = max(abs(o), abs(u), 1.0)
83
+ if abs(o - u) / denom > tolerance:
84
+ return False, f"metric '{key}' differs: oracle={o}, user={u}"
85
+ elif o != u:
86
+ return False, f"metric '{key}' differs: oracle={o!r}, user={u!r}"
87
+ return True, "metrics match within tolerance"
88
+
89
+
90
+ def verdict(
91
+ pattern: str,
92
+ user_file: Path,
93
+ oracle_result: RunResult,
94
+ user_result: RunResult,
95
+ tolerance: float = 1e-5,
96
+ ) -> Verdict:
97
+ """Render a verdict from oracle and user run results."""
98
+
99
+ # UNSUPPORTED: oracle itself did not run successfully.
100
+ if oracle_result.timed_out or oracle_result.exit_code != 0:
101
+ return Verdict(
102
+ status="UNSTABLE",
103
+ pattern=pattern,
104
+ user_file=str(user_file),
105
+ reason="Oracle run failed or timed out; the pattern may not be gate-ready.",
106
+ oracle_exit=oracle_result.exit_code,
107
+ user_exit=user_result.exit_code,
108
+ metrics={
109
+ "oracle_stdout": oracle_result.stdout[-500:],
110
+ "oracle_stderr": oracle_result.stderr[-500:],
111
+ },
112
+ )
113
+
114
+ oracle_json = _parse_gate_json(oracle_result.stdout)
115
+ user_json = _parse_gate_json(user_result.stdout)
116
+
117
+ # The fixture is the authoritative judge of the user's implementation on
118
+ # the seed-locked fixture. It applies pattern-specific correctness properties.
119
+ if user_json:
120
+ user_status = user_json.get("status", "FAIL")
121
+ user_reason = user_json.get("reason", "user fixture reported failure")
122
+ user_metrics = user_json.get("metrics", {})
123
+
124
+ if user_status == "FAIL":
125
+ return Verdict(
126
+ status="FAIL",
127
+ pattern=pattern,
128
+ user_file=str(user_file),
129
+ reason=user_reason,
130
+ oracle_exit=oracle_result.exit_code,
131
+ user_exit=user_result.exit_code,
132
+ metrics=user_metrics,
133
+ )
134
+
135
+ # user_status == PASS: trust the fixture's property-based verdict.
136
+ # canonical_match is reported by the fixture as an informational metric,
137
+ # not a gating condition.
138
+ return Verdict(
139
+ status="PASS",
140
+ pattern=pattern,
141
+ user_file=str(user_file),
142
+ reason=user_reason,
143
+ oracle_exit=oracle_result.exit_code,
144
+ user_exit=user_result.exit_code,
145
+ metrics=user_metrics,
146
+ )
147
+
148
+ # No user JSON — fall back to exit-code / raw-number comparison.
149
+ if user_result.timed_out:
150
+ return Verdict(
151
+ status="UNSTABLE",
152
+ pattern=pattern,
153
+ user_file=str(user_file),
154
+ reason=f"User code timed out after {user_result.duration_ms} ms.",
155
+ oracle_exit=oracle_result.exit_code,
156
+ user_exit=user_result.exit_code,
157
+ metrics={"duration_ms": user_result.duration_ms},
158
+ )
159
+
160
+ if user_result.exit_code != 0:
161
+ return Verdict(
162
+ status="FAIL",
163
+ pattern=pattern,
164
+ user_file=str(user_file),
165
+ reason="User process exited non-zero (assertion failed or crashed).",
166
+ oracle_exit=oracle_result.exit_code,
167
+ user_exit=user_result.exit_code,
168
+ metrics={"stderr": user_result.stderr[-500:]},
169
+ )
170
+
171
+ oracle_nums = dict(_extract_numbers(oracle_result.stdout))
172
+ user_nums = dict(_extract_numbers(user_result.stdout))
173
+
174
+ # PASS requires the user to actually produce metrics. A file that exits 0
175
+ # but prints nothing numeric is the classic "no-op" cheat and must fail.
176
+ if not user_nums:
177
+ if not oracle_nums:
178
+ # Pattern genuinely produced no metrics from either side — not gate-ready.
179
+ return Verdict(
180
+ status="UNSTABLE",
181
+ pattern=pattern,
182
+ user_file=str(user_file),
183
+ reason="Pattern produced no extractable metrics; oracle not gate-ready for numeric verification.",
184
+ oracle_exit=oracle_result.exit_code,
185
+ user_exit=user_result.exit_code,
186
+ metrics={"oracle_stdout": oracle_result.stdout[-500:]},
187
+ )
188
+ return Verdict(
189
+ status="FAIL",
190
+ pattern=pattern,
191
+ user_file=str(user_file),
192
+ reason="User produced none of the expected metrics.",
193
+ oracle_exit=oracle_result.exit_code,
194
+ user_exit=user_result.exit_code,
195
+ metrics={"expected_keys": list(oracle_nums.keys())},
196
+ )
197
+
198
+ ok, reason = _compare_metrics(oracle_nums, user_nums, tolerance)
199
+ status = "PASS" if ok else "FAIL"
200
+ return Verdict(
201
+ status=status,
202
+ pattern=pattern,
203
+ user_file=str(user_file),
204
+ reason=reason,
205
+ oracle_exit=oracle_result.exit_code,
206
+ user_exit=user_result.exit_code,
207
+ metrics={"oracle": oracle_nums, "user": user_nums},
208
+ )
@@ -0,0 +1,166 @@
1
+ """VIEW_COVERAGE — static declaration-vs-adapter agreement for lens inputs.
2
+
3
+ STRICT: a mismatch fails the self-test. Advisory was rejected (6E 3b) because
4
+ the pre-campaign ADVISORY_LENSES label lied for 32 days and misled a reader.
5
+
6
+ SCOPED OUT (v1, 6E 3c): the walker covers adapter bodies in lenses.py only.
7
+ Tool-internal consumption drift (e.g. metamorphic/runner.py stops using
8
+ ``pattern``) is INVISIBLE to this check. The declaration means "the adapter
9
+ forwards this input to its tool," not "the tool uses it." Extending the walk
10
+ into tool entry functions is a mechanical follow-up, not a new shape.
11
+
12
+ CONCEPTUAL INPUTS: some declared inputs (``canonical_oracle``, ``twin``) are
13
+ not adapter parameters — they are consumed inside the tool, not the adapter.
14
+ The walker detects them via _TOOL_INPUTS, a mapping from tool-call names to
15
+ the conceptual inputs they consume. This bridges the gap without walking tool
16
+ internals.
17
+ """
18
+ from __future__ import annotations
19
+
20
+ import ast
21
+ import inspect
22
+ import textwrap
23
+ from typing import Dict, FrozenSet, List, Tuple, Set, Optional
24
+
25
+ # Tool calls that consume conceptual inputs (not adapter parameters).
26
+ # When the walker sees a call to one of these functions, it adds the mapped
27
+ # inputs to the derived view. This is the only place tool-specific knowledge
28
+ # enters the walker — it is a call-name → input mapping, not a tool walk.
29
+ _TOOL_INPUTS: Dict[str, FrozenSet[str]] = {
30
+ "consensus_verify": frozenset({"canonical_oracle", "twin"}),
31
+ "resolve_pattern": frozenset({"canonical_oracle"}),
32
+ }
33
+
34
+
35
+ def _callee_name(call: ast.Call) -> Optional[str]:
36
+ """Extract the function name from a call expression."""
37
+ func = call.func
38
+ if isinstance(func, ast.Name):
39
+ return func.id
40
+ if isinstance(func, ast.Attribute):
41
+ return func.attr
42
+ return None
43
+
44
+
45
+ def _fn_params(fn_def: ast.FunctionDef) -> Set[str]:
46
+ """Extract parameter names from an AST function definition."""
47
+ params: Set[str] = set()
48
+ for arg in fn_def.args.posonlyargs + fn_def.args.args:
49
+ params.add(arg.arg)
50
+ if fn_def.args.vararg:
51
+ params.add(fn_def.args.vararg.arg)
52
+ for arg in fn_def.args.kwonlyargs:
53
+ params.add(arg.arg)
54
+ if fn_def.args.kwarg:
55
+ params.add(fn_def.args.kwarg.arg)
56
+ return params
57
+
58
+
59
+ def _walk_params(node: ast.AST, params: Set[str], found: Set[str]) -> None:
60
+ """Walk *node*'s children, collecting parameter-name reads.
61
+
62
+ Skips nested FunctionDef / AsyncFunctionDef (they have their own params).
63
+ Does NOT do transitive closure — parameter reads are collected from the
64
+ adapter body only, not from utility functions the adapter calls.
65
+ """
66
+ for child in ast.iter_child_nodes(node):
67
+ if isinstance(child, (ast.FunctionDef, ast.AsyncFunctionDef)):
68
+ continue
69
+ if isinstance(child, ast.Name) and isinstance(child.ctx, ast.Load):
70
+ if child.id in params:
71
+ found.add(child.id)
72
+ _walk_params(child, params, found)
73
+
74
+
75
+ def _walk_tool_inputs(
76
+ node: ast.AST,
77
+ module_funcs: Dict[str, ast.FunctionDef],
78
+ found: Set[str],
79
+ seen: Set[str],
80
+ ) -> None:
81
+ """Walk *node*'s children, collecting conceptual inputs from tool calls.
82
+
83
+ Skips nested FunctionDef / AsyncFunctionDef. Does transitive closure for
84
+ same-module calls (cycle-guarded) so that a helper like _run_determinism_once
85
+ calling resolve_pattern is detected from _run_determinism's body.
86
+ """
87
+ for child in ast.iter_child_nodes(node):
88
+ if isinstance(child, (ast.FunctionDef, ast.AsyncFunctionDef)):
89
+ continue
90
+ if isinstance(child, ast.Call):
91
+ name = _callee_name(child)
92
+ if name and name in _TOOL_INPUTS:
93
+ found |= _TOOL_INPUTS[name]
94
+ if name and name in module_funcs and name not in seen:
95
+ seen.add(name)
96
+ _walk_tool_inputs(
97
+ module_funcs[name], module_funcs, found, seen
98
+ )
99
+ _walk_tool_inputs(child, module_funcs, found, seen)
100
+
101
+
102
+ def derive_view(fn) -> FrozenSet[str]:
103
+ """AST-walk a function body, return the set of input names consumed.
104
+
105
+ Returns parameter names actually read (excluding writes, imports), plus
106
+ conceptual inputs detected via _TOOL_INPUTS tool-call patterns. Handles
107
+ nested scopes (skip inner defs) and transitive calls within the same
108
+ module.
109
+ """
110
+ try:
111
+ source = inspect.getsource(fn)
112
+ except (OSError, TypeError):
113
+ return frozenset()
114
+
115
+ tree = ast.parse(textwrap.dedent(source))
116
+ fn_def = tree.body[0] if tree.body else None
117
+ if not isinstance(fn_def, (ast.FunctionDef, ast.AsyncFunctionDef)):
118
+ return frozenset()
119
+
120
+ # Collect all module-level functions for transitive closure.
121
+ module = inspect.getmodule(fn)
122
+ module_funcs: Dict[str, ast.FunctionDef] = {}
123
+ if module:
124
+ try:
125
+ mod_source = inspect.getsource(module)
126
+ mod_tree = ast.parse(textwrap.dedent(mod_source))
127
+ for node in mod_tree.body:
128
+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
129
+ module_funcs[node.name] = node
130
+ except (OSError, TypeError):
131
+ pass
132
+
133
+ params = _fn_params(fn_def)
134
+ found: Set[str] = set()
135
+ _walk_params(fn_def, params, found)
136
+ _walk_tool_inputs(fn_def, module_funcs, found, set())
137
+ return frozenset(found)
138
+
139
+
140
+ def check_all(module) -> List[Tuple[str, str]]:
141
+ """For each VIEW_COVERAGE entry, compare derive_view against the declared set.
142
+
143
+ Returns a list of ``(function_name, reason)`` mismatches. An empty list
144
+ means every declaration agrees with its adapter body in BOTH directions:
145
+ no undeclared reads AND no declared-but-unread inputs.
146
+ """
147
+ from forgeproof.lenses import VIEW_COVERAGE
148
+
149
+ mismatches: List[Tuple[str, str]] = []
150
+ for name, declared in VIEW_COVERAGE.items():
151
+ fn = getattr(module, name, None)
152
+ if fn is None:
153
+ mismatches.append((name, f"function {name} not found in module"))
154
+ continue
155
+ derived = derive_view(fn)
156
+ undeclared = derived - declared
157
+ unread = declared - derived
158
+ if undeclared:
159
+ mismatches.append(
160
+ (name, f"undeclared reads: {sorted(undeclared)}")
161
+ )
162
+ if unread:
163
+ mismatches.append(
164
+ (name, f"declared but unread: {sorted(unread)}")
165
+ )
166
+ return mismatches
@@ -0,0 +1,285 @@
1
+ Metadata-Version: 2.4
2
+ Name: forgeproof-cli
3
+ Version: 0.2.0
4
+ Summary: Deterministic regression gate for code-generating agents, with reference implementations from the AURA pattern library.
5
+ Author-email: Illia Hladkyi <ihladkyi@realityoptimizer.app>
6
+ License: Apache-2.0
7
+ Keywords: ai-agent,verification,regression-testing,code-quality,deterministic-oracle
8
+ Classifier: Development Status :: 3 - Alpha
9
+ Classifier: Intended Audience :: Developers
10
+ Classifier: License :: OSI Approved :: Apache Software License
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: Python :: 3.10
13
+ Classifier: Programming Language :: Python :: 3.11
14
+ Classifier: Programming Language :: Python :: 3.12
15
+ Classifier: Topic :: Software Development :: Testing
16
+ Requires-Python: >=3.10
17
+ Description-Content-Type: text/markdown
18
+ License-File: LICENSE
19
+ License-File: NOTICE
20
+ Requires-Dist: tomli>=2.0; python_version < "3.11"
21
+ Provides-Extra: dev
22
+ Requires-Dist: pytest; extra == "dev"
23
+ Requires-Dist: pytest-timeout; extra == "dev"
24
+ Requires-Dist: setuptools>=61; extra == "dev"
25
+ Dynamic: license-file
26
+
27
+ # ForgeProof
28
+
29
+ > **Renamed.** Forge Gate is now **ForgeProof** (2026-11-25). The name `forgegate` was already
30
+ > taken on PyPI and npm by another tool for AI agents, so we changed ours before the first release.
31
+ > For one release the old `forge-gate` command and `forge_gate` import still work and print a notice
32
+ > (see [`CHANGELOG.md`](CHANGELOG.md)). Links to the old repository address redirect here.
33
+ >
34
+ > **What the name means.** Read it like *waterproof* or *foolproof*: forged code does not get
35
+ > through. "Forge" keeps the project's history. "Proof" comes from the gunsmiths' proof house,
36
+ > where every barrel is test-fired with an extra-strong charge before it may be sold. ForgeProof
37
+ > does the same with code: it runs it, plants known faults as controls, and stamps a receipt.
38
+ > Other projects also use the name ForgeProof; this one checks AI-written code **by running it**.
39
+
40
+ ForgeProof checks code written by AI by **running it** next to a known-correct version on the
41
+ same inputs, and reports whether it behaves correctly. The known-correct versions come from the
42
+ signed AURA pattern library and ship inside the package. No language model takes part in any
43
+ verdict.
44
+
45
+ **New here? Start with [`docs/getting-started.md`](docs/getting-started.md):** from a clean clone
46
+ to a real PASS and a real FAIL in a few minutes.
47
+
48
+ ## Why it exists
49
+
50
+ An AI agent can write code, write the tests for it, and report that the tests are green. All three
51
+ come from the same author, so a green run proves less than it seems. A test that cannot fail
52
+ passes, and a suite that never looks at the broken line passes too.
53
+
54
+ ForgeProof asks two questions that do not depend on trusting the author:
55
+
56
+ 1. **Does this code behave like a correct implementation?** It runs your file and a reference
57
+ implementation on the same seed-locked input, and judges the result through several
58
+ independent lenses (below).
59
+ 2. **Would the tests notice if the code were wrong?** The shared tools in `tools/` plant small
60
+ deliberate bugs ("mutants"), re-run the tests, and report which bugs the suite missed.
61
+
62
+ ## Status
63
+
64
+ Alpha (0.2.0). Not on PyPI yet: install from a checkout. On PyPI the package will be called
65
+ `forgeproof-cli` (`forgeproof` is too close to an existing project there); the command and the
66
+ import stay `forgeproof`. The verify gate covers 10 Python
67
+ patterns. Several commands (`scout`, `learn`, `ledger`, `chaos-calibrate`) are advisory or
68
+ plumbing today. **`KNOWN-DEBT.md` lists every known gap**: what it
69
+ is, where, what "fixed" will look like, and who owns it.
70
+
71
+ ## Install
72
+
73
+ ```bash
74
+ git clone https://github.com/myfjin/forgeproof.git && cd forgeproof
75
+ python3 -m venv .venv && .venv/bin/pip install . pytest pytest-timeout "setuptools>=61"
76
+ PYTHONPATH=src .venv/bin/python -m pytest -q # default tier: fixtures only, no network, no library
77
+ npm ci # only for the JS oracle (TypeScript type gate)
78
+ ```
79
+
80
+ An install runs every lens on its own: the lens tools ship inside the package (`KNOWN-DEBT.md`,
81
+ KD-2, fixed 2026-11-25), so no `FORGE_GATE_HOME` is needed for a verdict. The clone is needed for
82
+ the tests, the shared tools in `tools/` and the JS oracle.
83
+
84
+ Python 3.10 or newer. Without `npm ci` the JS oracle's type gate reports `unavailable`. The JS
85
+ oracle is a checkout gate (`pytest -m js`), not a `verify` lens, so a pip install does not have it.
86
+
87
+ ## Configuration
88
+
89
+ ForgeProof reads no other project unless you tell it where. Each setting is an
90
+ environment variable, or a key in `config.toml` `[paths]` (per host, not tracked; copy
91
+ `config.example.toml`). The environment wins.
92
+
93
+ | key | needed for | default |
94
+ |---|---|---|
95
+ | `FORGE_GATE_LIBRARY_DIR` | the twin-consensus lens, `pytest -m live`, library tools | none: unset, those fail naming the key |
96
+ | `FORGE_GATE_HOME` | where `config.toml` is read, and `github-facts`' test runner (a checkout tool); no lens needs it | the checkout |
97
+ | `FORGE_GATE_PYTHON` | child runs (oracles, fixtures, lenses) | the interpreter running ForgeProof |
98
+ | `FORGE_GATE_NODE`, `_BUN`, `_QJS` | the JS oracle's three engines | `PATH` |
99
+ | `FORGE_GATE_SCRATCH` | short-lived lens scripts | `<checkout>/tmp` |
100
+
101
+ `deps.lock` pins what each outside route was checked against.
102
+
103
+ ## Usage
104
+
105
+ ```bash
106
+ # List gate-ready patterns
107
+ forgeproof list
108
+
109
+ # Verify a user implementation against a seed-locked oracle
110
+ forgeproof verify myfile.py --pattern linear_regression_gd
111
+ ```
112
+
113
+ A verdict is `PASS`, `FAIL`, `UNSTABLE` or `UNSUPPORTED`, with one line per lens. `UNSUPPORTED`
114
+ means a lens could not measure here and says why; it is never a pass in disguise. `UNSTABLE`
115
+ means a lens errored or the references disagreed, so no verdict could be trusted.
116
+
117
+ ## The lenses
118
+
119
+ | lens | the question it asks |
120
+ |---|---|
121
+ | property-primary | do the results have the properties a correct implementation must have? |
122
+ | metamorphic | if the input changes in a known way, does the output change the way it must? |
123
+ | invariant | do the rules that must always hold, hold? |
124
+ | twin-consensus | do implementations of the same pattern in other languages agree? |
125
+ | determinism | do repeated runs with a fixed seed give the same answer? |
126
+ | guard | given NaN (not-a-number) as input, does the code pass it on honestly, or quietly return a plausible number? Infinity is tried too, but only recorded. Needs no reference at all (`docs/GUARD_LENS.md`) |
127
+
128
+ ## Examples
129
+
130
+ The `examples/` directory contains self-contained reference implementations for
131
+ gate-ready patterns. Run them standalone, or pass them to the gate to see a live
132
+ `PASS`/`FAIL` verdict:
133
+
134
+ ```bash
135
+ python examples/linear_regression_gd_good.py
136
+ forgeproof verify examples/linear_regression_gd_good.py --pattern linear_regression_gd
137
+ forgeproof verify examples/linear_regression_gd_bad.py --pattern linear_regression_gd
138
+ ```
139
+
140
+ Every one of the 10 catalog patterns has a pair: `<pattern>_good.py` and `<pattern>_bad.py`.
141
+ The `_good` files implement the algorithm correctly and print `PASS` via the gate. The `_bad`
142
+ files each contain one deliberate bug and print `FAIL`.
143
+
144
+ Known oddity: `kmeans_clustering_good.py` shows `determinism FAIL` inside a `PASS`. k-means can
145
+ settle on different valid answers from run to run, so that lens is advisory for this one pattern;
146
+ the line does not say so yet (`KNOWN-DEBT.md`, KD-6).
147
+
148
+ ## What `verify` does
149
+
150
+ 1. Resolves the pattern name in the shipped catalog (`forgeproof/data/gate_catalog.json`).
151
+ 2. Loads the shipped reference implementation (`forgeproof/reference/`, byte copies of
152
+ AURA library patterns; commit and sha256 in `reference/ORIGIN.md`).
153
+ 3. Runs the user's file in a separate process: fixed seed, 60 s timeout; network cut off where
154
+ the system supports it (Linux `unshare`), not on macOS.
155
+ 4. Runs the AURA oracle on the same fixture.
156
+ 5. Compares exit codes and numeric outputs within tolerance, and runs the lenses.
157
+ 6. Returns PASS / FAIL / UNSTABLE / UNSUPPORTED.
158
+
159
+ No LLM judgment is used in the verdict path. The gate is execution-backed.
160
+
161
+ ## Catalog
162
+
163
+ Python-only v1 ships with 10 curated seed-locked oracles:
164
+
165
+ - `kmeans_clustering`
166
+ - `linear_regression_gd`
167
+ - `knn_classifier`
168
+ - `logistic_regression`
169
+ - `naive_bayes_text`
170
+ - `polynomial_regression`
171
+ - `decision_tree_id3`
172
+ - `perceptron`
173
+ - `ridge_regression_normal_eq`
174
+ - `gradient_descent_momentum`
175
+
176
+ ## Shared tools: does your test suite test anything?
177
+
178
+ Two tools in `tools/` work on any Python project kept in git and tested with pytest, not only
179
+ ForgeProof (`docs/shared-tools.md`):
180
+
181
+ - **`tools/fg_gate.py`** runs the tests and calls a run green only when it can prove what ran:
182
+ counts from the run's own fresh result file, the tree unchanged by the tests, and any tests you
183
+ name actually run. Stopping it with Ctrl-C stops the tests too.
184
+ - **`tools/fg_mutrun.py`** plants the small bugs you describe, one at a time, runs the tests,
185
+ restores the code, and reports which bugs the tests caught and which survived.
186
+
187
+ ForgeProof's own recent changes were gated this way: each step was reviewed by a separate AI
188
+ agent session, not the one that built it, before it was merged.
189
+
190
+ ## Where the code to check comes from
191
+
192
+ ForgeProof doesn't care who wrote a file. It runs it and measures what comes out. In practice,
193
+ code reaches it from four kinds of source, and each one is trusted differently.
194
+
195
+ - **Your own file, or what your AI assistant just wrote.** This is the main case: a script from
196
+ Claude Code, Copilot, Cursor or any other agent, or one you wrote yourself. If it implements one
197
+ of the 10 catalog patterns, `forgeproof verify yourfile.py --pattern <name>` runs it against the
198
+ shipped reference and gives a verdict. Code that matches no catalog pattern gets no verdict; the
199
+ shared tools above can still tell you whether its own tests would notice a bug.
200
+ - **The examples in `examples/`.** A known-good and a known-bad file for every pattern. Use them
201
+ to see what a real `PASS` and a real `FAIL` look like before trusting a verdict on your own code.
202
+ - **The signed reference implementations** in `src/forgeproof/reference/`. These are byte copies
203
+ from the AURA pattern library, a signed collection of self-testing code patterns. They are the
204
+ oracles: ForgeProof compares your code with them and does not judge them.
205
+ - **Pools that `scout` and `learn` read** (advisory today, see Status). A pool is a body of
206
+ existing code that scout searches to answer "what is this code related to?". There are two so
207
+ far. One is a **GitHub pool**: public repositories on a list signed with two keys, each pinned
208
+ to one commit and read from a private cache (KD-13). Today only python/cpython at v3.14.10 is
209
+ on it. The other is the **crew corpus**, described next. Scout reads pool code as
210
+ text and never runs it while searching.
211
+
212
+ ### Crew code collector: how we gather the code our own agents write
213
+
214
+ AURA is built by a small crew of AI agents working with one person. Over months they have written
215
+ thousands of scripts: backups, monitors, test harnesses, data tools. Most were written once,
216
+ worked, and were forgotten, and the next agent wrote the same thing again. The **code collector**
217
+ gathers that code so that it can be found, measured, and in the end proven or thrown away.
218
+
219
+ How it works:
220
+
221
+ 1. **It harvests after the fact.** Agents don't change how they work. The collector reads the
222
+ session records they already leave behind, and takes out every piece of code they produced:
223
+ files written or edited, scripts passed inline to a shell, and longer shell commands.
224
+ 2. **Exclude, scrub, then store, always in that order.** Work done for outside clients is dropped
225
+ first. Secrets, keys, host names, addresses, user names and e-mail addresses are then removed in
226
+ memory, and a second pass checks the scrubbing. Only then is anything written to disk. The store
227
+ refuses any write a secret detector still matches. A separate scanner, sharing no code with the
228
+ scrubber, sweeps the result.
229
+ 3. **Every run proves it can fail.** Each run starts by planting fake secrets, fake client files
230
+ and a corrupt record. If they don't land exactly as expected, the run is marked invalid.
231
+ 4. **Each item keeps its evidence.** Who wrote it, when, and in which session. Did it **run**, and
232
+ with what exit code? Was it ever **proven red**, meaning run with a deliberately planted bug and
233
+ seen to fail? Is it still **scheduled**, still on disk, or gone? Every answer keeps the evidence
234
+ string it came from. "Not seen running" is recorded as *unknown*, never as *no*, and words alone
235
+ never upgrade an item to proven.
236
+ 5. **Near-copies are grouped.** Items with the same shape fall into one cluster. A cluster that
237
+ turns up in two or more projects is a sign the code is worth keeping. A cluster whose members
238
+ drifted apart is kept as a before/after pair. When an agent is about to write a new script, a
239
+ hook can show it the closest existing shapes first: *this already exists, here*.
240
+ 6. **Collected is not verified.** The corpus is raw input with the lowest trust. Scout reads it
241
+ only from an export whose manifest and checksums all match; anything else counts as blind, never
242
+ as clean. `forgeproof learn` can test a corpus item, but today only the chaos engine can give it
243
+ a `PASS` (KD-11, KD-12). Code reaches the signed pattern library only through that battery and a
244
+ reviewed harvest, never straight from the corpus.
245
+
246
+ The corpus itself is **private**. It is built from private working conversations, so it is not
247
+ published, and neither is the collector. What this repository ships is the reading side: scout's
248
+ intake checks, and the ledgers that record whether reused code later held up (`KNOWN-DEBT.md`,
249
+ KD-7, KD-11, KD-14).
250
+
251
+ ## Where ForgeProof is going
252
+
253
+ ForgeProof is alpha. This is the order we plan to work in, and each step lands only with its
254
+ tests and its known-debt entry.
255
+
256
+ 1. **Learn from what scout measures.** Scout already records facts: how well a GitHub project's
257
+ own tests catch planted bugs (`forgeproof github-facts`), and whether code from the crew corpus
258
+ was ever seen running. `learn` reads only the crew corpus today. Next it also reads the GitHub
259
+ facts, first by hand on a copy, and only then on a schedule (`KNOWN-DEBT.md`, KD-17 (a)).
260
+ 2. **More reviewed GitHub projects.** About one project every one to two weeks, chosen for a long
261
+ history and real tests rather than for stars. Each one is pinned to one commit, licence-checked
262
+ file by file, and signed before scout reads it.
263
+ 3. **All six languages.** The pattern library holds Python, R, Rust, Go, C++ and JavaScript. The
264
+ scores scout reads exist for Python, R and Rust today; Go, C++ and JavaScript need their own
265
+ extractors first.
266
+ 4. **A first release on PyPI**, as `forgeproof-cli`. Its condition is met: since KD-2 was fixed
267
+ (2026-11-25), an installed copy runs every lens without a source checkout.
268
+ 5. **A free web service.** Paste code and have it checked in an isolated sandbox, with no account.
269
+ You choose whether we may keep your code to improve the checks, and we never show one person's
270
+ code to anyone else. Prefer to keep everything private? Run this repository on your own
271
+ machine. This is a direction, not yet a design: it starts after the steps above, with a legal
272
+ review first.
273
+
274
+ ForgeProof is directed by one person and largely written with AI agents. Every commit says so.
275
+
276
+ ## How this repository is made
277
+
278
+ Most of this tree is published from a private working repository by a script that
279
+ scrubs it and refuses to publish when any of its checks fails. `CONTRIBUTING.md` says
280
+ which files are edited here directly, and how a pull request to published code is
281
+ carried back.
282
+
283
+ ## Licence
284
+
285
+ Apache-2.0. Copyright 2026 Illia Hladkyi. See `LICENSE` and `NOTICE`.