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
@@ -0,0 +1,125 @@
1
+ """
2
+ Polynomial Regression via Least Squares (Vandermonde Design Matrix).
3
+
4
+ A polynomial regression solver using Gaussian elimination on the Vandermonde matrix.
5
+ Fits a degree-d polynomial to (x, y) data by solving the normal equations directly.
6
+ Use when you need interpretable polynomial fit without external libraries.
7
+ """
8
+ # △ AURA Pattern Library — © Reality Optimizer ⟦AE1.PMRGG3ZCHIRFEZLBNRUXI6JAJ5YHI2LNNF5GK4RCFQRG2IR2EJAUKTKBKJFTCIRMEJXCEORCGARCYITQNFSCEORCEIWCE5DNEI5CEQKVKJASAUDBOR2GK4TOEBGGSYTSMFZHSIRMEJ3CEORRPWYSJPXO⟧
9
+ # ⁣​‌​‌​​​​​‌​​‌‌​‌​‌​‌​​‌​​‌​​​‌‌‌​‌​​​‌‌‌​​‌‌​​‌‌​‌​‌‌​‌​​‌​​​​‌‌​‌​​‌​​​​‌​​‌​​‌​‌​‌​​‌​​‌​​​‌‌​​‌​​​‌​‌​‌​‌‌​‌​​‌​​‌‌​​​‌​​​​‌​​‌​​‌‌‌​​‌​‌​​‌​​‌​‌​‌​‌​‌​‌‌​​​​‌​​‌​​‌​​‌‌​‌‌​​‌​​‌​‌​​‌​​​​​‌​‌​​‌​‌​​​‌‌​‌​‌​‌​‌‌​​‌​‌​​‌​​​​‌​​‌​​‌​​‌‌​​‌​​‌​​‌‌​​​‌​​‌‌‌​​‌​​‌‌‌​​‌​​​‌‌​​​‌‌​‌​‌​‌​​​‌‌‌​‌​​‌​‌‌​​‌‌​‌​​​‌​‌​​‌​​‌​​​​‌‌​‌​​​‌‌​​‌​‌​​​‌​‌​‌​​‌​​‌​​​‌‌‌​​‌‌​​‌​​‌​​‌​​‌​‌​‌​​‌​​​‌‌​​‌​​‌​​​‌​‌​‌​​‌​‌​​‌​​​​​‌​‌​‌​‌​‌​‌​​‌​‌‌​‌​‌​‌​​​‌​​‌​‌‌​‌​​​​‌​​‌​​‌​‌‌​‌​​‌​‌​​‌​​​‌‌​​‌​‌​‌​​​‌​​​​‌‌​‌​​‌​​‌​‌​‌​​‌​​‌​​‌‌​‌​‌​​​‌​‌​‌​​‌​‌​​‌​‌‌​​​​‌​​​​‌‌​‌​​​‌​‌​‌​​‌‌‌‌​‌​‌​​‌​​‌​​​​‌‌​‌​​​‌‌‌​‌​​​​​‌​‌​‌​​‌​​‌​​​​‌‌​‌​‌‌​​‌​‌​​‌​​‌​‌​‌​‌​​​‌​‌​​​‌​‌​​‌‌‌​​‌​​​‌‌​​‌​‌​​‌‌​‌​​​​‌‌​‌​​​‌​‌​‌​​‌‌‌‌​‌​‌​​‌​​‌​​​​‌‌​‌​​​‌​‌​‌​​‌​​‌​‌​‌​‌‌‌​‌​​​​‌‌​‌​​​‌​‌​​‌‌​‌​‌​‌​​​‌​​​‌​​‌‌‌​​‌​​​‌​‌​‌​​‌​​‌​​‌‌​‌​‌​‌​​​​‌‌​‌​​​‌​‌​‌​‌​​​‌​‌​​‌​‌‌​‌​‌​‌‌​​‌​​‌​‌‌​‌​​‌​‌​​‌​​​​​‌​‌​‌​​‌‌​‌​​​​​‌​‌​‌​‌​‌​‌​​​‌​​​‌​​​​‌​​‌​​‌‌‌‌​‌​‌​​‌​​​‌‌​​‌​​‌​​​‌‌‌​‌​​‌​‌‌​​‌‌​‌​​​‌​‌​‌​​​‌​​‌‌‌‌​‌​​​‌​‌​‌​​​​‌​​‌​​​‌‌‌​‌​​​‌‌‌​‌​‌​​‌‌​‌​‌‌​​‌​‌​‌​‌​​​‌​‌​​‌‌​‌​​‌‌​‌​‌​​​‌‌​​‌​‌‌​‌​​‌​​‌​​​​‌​‌​​‌‌​‌​​‌​​‌​‌​‌​​‌​​‌​​‌‌​‌​‌​​​‌​‌​‌​​‌​‌​​​‌‌​​‌‌​‌​​​​‌‌​‌​​​‌​‌​‌​​‌‌‌‌​‌​‌​​‌​​‌​‌​​‌​​‌​‌​​​​​‌​‌​‌‌‌​‌​‌‌​​‌​‌​‌​​‌‌​‌​​‌​‌​​‌​‌​​​​​‌​‌‌​​​​‌​​‌‌‌‌⁣
10
+ _AURA_MARK = "AE1.PMRGG3ZCHIRFEZLBNRUXI6JAJ5YHI2LNNF5GK4RCFQRG2IR2EJAUKTKBKJFTCIRMEJXCEORCGARCYITQNFSCEORCEIWCE5DNEI5CEQKVKJASAUDBOR2GK4TOEBGGSYTSMFZHSIRMEJ3CEORRPWYSJPXO"
11
+
12
+ import random
13
+ import math
14
+ from typing import List, Tuple
15
+
16
+
17
+ def gaussian_elimination(A: List[List[float]], b: List[float]) -> List[float]:
18
+ """Solve Ax=b via Gaussian elimination with partial pivoting."""
19
+ n = len(A)
20
+ # Augment A with b
21
+ aug = [A[i][:] + [b[i]] for i in range(n)]
22
+
23
+ # Forward elimination
24
+ for col in range(n):
25
+ # Find pivot
26
+ max_row = col
27
+ for row in range(col + 1, n):
28
+ if abs(aug[row][col]) > abs(aug[max_row][col]):
29
+ max_row = row
30
+ aug[col], aug[max_row] = aug[max_row], aug[col]
31
+
32
+ if abs(aug[col][col]) < 1e-12:
33
+ raise ValueError("Matrix is singular")
34
+
35
+ # Eliminate below
36
+ for row in range(col + 1, n):
37
+ factor = aug[row][col] / aug[col][col]
38
+ for j in range(col, n + 1):
39
+ aug[row][j] -= factor * aug[col][j]
40
+
41
+ # Back substitution
42
+ x = [0.0] * n
43
+ for i in range(n - 1, -1, -1):
44
+ x[i] = aug[i][n]
45
+ for j in range(i + 1, n):
46
+ x[i] -= aug[i][j] * x[j]
47
+ x[i] /= aug[i][i]
48
+
49
+ return x
50
+
51
+
52
+ def vandermonde_matrix(x_vals: List[float], degree: int) -> List[List[float]]:
53
+ """Build Vandermonde design matrix for polynomial regression."""
54
+ n = len(x_vals)
55
+ V = [[0.0] * (degree + 1) for _ in range(n)]
56
+ for i in range(n):
57
+ for j in range(degree + 1):
58
+ V[i][j] = x_vals[i] ** j
59
+ return V
60
+
61
+
62
+ def fit_polynomial(x_vals: List[float], y_vals: List[float], degree: int) -> List[float]:
63
+ """Fit polynomial of given degree. Returns coefficients [c0, c1, ..., cd]."""
64
+ V = vandermonde_matrix(x_vals, degree)
65
+
66
+ # Compute V^T * V and V^T * y
67
+ n_cols = degree + 1
68
+ VtV = [[0.0] * n_cols for _ in range(n_cols)]
69
+ Vty = [0.0] * n_cols
70
+
71
+ for j in range(n_cols):
72
+ for k in range(n_cols):
73
+ for i in range(len(x_vals)):
74
+ VtV[j][k] += V[i][j] * V[i][k]
75
+ for i in range(len(x_vals)):
76
+ Vty[j] += V[i][j] * y_vals[i]
77
+
78
+ # Solve normal equations
79
+ coeffs = gaussian_elimination(VtV, Vty)
80
+ return coeffs
81
+
82
+
83
+ def eval_poly(coeffs: List[float], x: float) -> float:
84
+ """Evaluate polynomial at x given coefficients."""
85
+ result = 0.0
86
+ power = 1.0
87
+ for c in coeffs:
88
+ result += c * power
89
+ power *= x
90
+ return result
91
+
92
+
93
+ def mse(y_true: List[float], y_pred: List[float]) -> float:
94
+ """Mean squared error."""
95
+ return sum((yt - yp) ** 2 for yt, yp in zip(y_true, y_pred)) / len(y_true)
96
+
97
+
98
+ if __name__ == "__main__":
99
+ random.seed(42)
100
+
101
+ # Plant a quadratic: y = 2 + 3*x + 0.5*x^2 + noise
102
+ true_coeffs = [2.0, 3.0, 0.5]
103
+ x_vals = [float(i) * 0.5 for i in range(20)]
104
+ y_vals = [eval_poly(true_coeffs, x) + random.gauss(0, 0.1) for x in x_vals]
105
+
106
+ # Fit degree 2
107
+ fitted_coeffs_2 = fit_polynomial(x_vals, y_vals, 2)
108
+
109
+ # Fit degree 1 (linear)
110
+ fitted_coeffs_1 = fit_polynomial(x_vals, y_vals, 1)
111
+
112
+ y_pred_2 = [eval_poly(fitted_coeffs_2, x) for x in x_vals]
113
+ y_pred_1 = [eval_poly(fitted_coeffs_1, x) for x in x_vals]
114
+
115
+ mse_2 = mse(y_vals, y_pred_2)
116
+ mse_1 = mse(y_vals, y_pred_1)
117
+
118
+ # Verify fitted coefficients recover planted values within tolerance
119
+ for i, (true_c, fit_c) in enumerate(zip(true_coeffs, fitted_coeffs_2)):
120
+ assert abs(true_c - fit_c) < 0.2, f"Coeff {i}: true={true_c}, fit={fit_c}"
121
+
122
+ # Verify quadratic beats linear
123
+ assert mse_2 < mse_1, f"Quadratic MSE {mse_2} should beat linear {mse_1}"
124
+
125
+ print(f"polynomial_regression.py: fitted_coeffs={fitted_coeffs_2}, mse_2={mse_2:.4f}, mse_1={mse_1:.4f} PASS")
@@ -0,0 +1,165 @@
1
+ """
2
+ Ridge Regression via Normal Equations (from scratch).
3
+
4
+ Core idea: Linear regression with L2 regularization: minimize ||Xw - y||^2 + λ||w||^2.
5
+ Solved analytically via normal equations: w = (X^T X + λI)^(-1) X^T y.
6
+ Implement matrix operations (transpose, multiply, Gaussian elimination) from scratch.
7
+
8
+ When to use: Regression with collinearity; small to medium data; interpretable model.
9
+ """
10
+ # △ AURA Pattern Library — © Reality Optimizer ⟦AE1.PMRGG3ZCHIRFEZLBNRUXI6JAJ5YHI2LNNF5GK4RCFQRG2IR2EJAUKTKBKJFTCIRMEJXCEORCGARCYITQNFSCEORCEIWCE5DNEI5CEQKVKJASAUDBOR2GK4TOEBGGSYTSMFZHSIRMEJ3CEORRPWYSJPXO⟧
11
+ # ⁣​‌​‌​​​​​‌​​‌‌​‌​‌​‌​​‌​​‌​​​‌‌‌​‌​​​‌‌‌​​‌‌​​‌‌​‌​‌‌​‌​​‌​​​​‌‌​‌​​‌​​​​‌​​‌​​‌​‌​‌​​‌​​‌​​​‌‌​​‌​​​‌​‌​‌​‌‌​‌​​‌​​‌‌​​​‌​​​​‌​​‌​​‌‌‌​​‌​‌​​‌​​‌​‌​‌​‌​‌​‌‌​​​​‌​​‌​​‌​​‌‌​‌‌​​‌​​‌​‌​​‌​​​​​‌​‌​​‌​‌​​​‌‌​‌​‌​‌​‌‌​​‌​‌​​‌​​​​‌​​‌​​‌​​‌‌​​‌​​‌​​‌‌​​​‌​​‌‌‌​​‌​​‌‌‌​​‌​​​‌‌​​​‌‌​‌​‌​‌​​​‌‌‌​‌​​‌​‌‌​​‌‌​‌​​​‌​‌​​‌​​‌​​​​‌‌​‌​​​‌‌​​‌​‌​​​‌​‌​‌​​‌​​‌​​​‌‌‌​​‌‌​​‌​​‌​​‌​​‌​‌​‌​​‌​​​‌‌​​‌​​‌​​​‌​‌​‌​​‌​‌​​‌​​​​​‌​‌​‌​‌​‌​‌​​‌​‌‌​‌​‌​‌​​​‌​​‌​‌‌​‌​​​​‌​​‌​​‌​‌‌​‌​​‌​‌​​‌​​​‌‌​​‌​‌​‌​​​‌​​​​‌‌​‌​​‌​​‌​‌​‌​​‌​​‌​​‌‌​‌​‌​​​‌​‌​‌​​‌​‌​​‌​‌‌​​​​‌​​​​‌‌​‌​​​‌​‌​‌​​‌‌‌‌​‌​‌​​‌​​‌​​​​‌‌​‌​​​‌‌‌​‌​​​​​‌​‌​‌​​‌​​‌​​​​‌‌​‌​‌‌​​‌​‌​​‌​​‌​‌​‌​‌​​​‌​‌​​​‌​‌​​‌‌‌​​‌​​​‌‌​​‌​‌​​‌‌​‌​​​​‌‌​‌​​​‌​‌​‌​​‌‌‌‌​‌​‌​​‌​​‌​​​​‌‌​‌​​​‌​‌​‌​​‌​​‌​‌​‌​‌‌‌​‌​​​​‌‌​‌​​​‌​‌​​‌‌​‌​‌​‌​​​‌​​​‌​​‌‌‌​​‌​​​‌​‌​‌​​‌​​‌​​‌‌​‌​‌​‌​​​​‌‌​‌​​​‌​‌​‌​‌​​​‌​‌​​‌​‌‌​‌​‌​‌‌​​‌​​‌​‌‌​‌​​‌​‌​​‌​​​​​‌​‌​‌​​‌‌​‌​​​​​‌​‌​‌​‌​‌​‌​​​‌​​​‌​​​​‌​​‌​​‌‌‌‌​‌​‌​​‌​​​‌‌​​‌​​‌​​​‌‌‌​‌​​‌​‌‌​​‌‌​‌​​​‌​‌​‌​​​‌​​‌‌‌‌​‌​​​‌​‌​‌​​​​‌​​‌​​​‌‌‌​‌​​​‌‌‌​‌​‌​​‌‌​‌​‌‌​​‌​‌​‌​‌​​​‌​‌​​‌‌​‌​​‌‌​‌​‌​​​‌‌​​‌​‌‌​‌​​‌​​‌​​​​‌​‌​​‌‌​‌​​‌​​‌​‌​‌​​‌​​‌​​‌‌​‌​‌​​​‌​‌​‌​​‌​‌​​​‌‌​​‌‌​‌​​​​‌‌​‌​​​‌​‌​‌​​‌‌‌‌​‌​‌​​‌​​‌​‌​​‌​​‌​‌​​​​​‌​‌​‌‌‌​‌​‌‌​​‌​‌​‌​​‌‌​‌​​‌​‌​​‌​‌​​​​​‌​‌‌​​​​‌​​‌‌‌‌⁣
12
+ _AURA_MARK = "AE1.PMRGG3ZCHIRFEZLBNRUXI6JAJ5YHI2LNNF5GK4RCFQRG2IR2EJAUKTKBKJFTCIRMEJXCEORCGARCYITQNFSCEORCEIWCE5DNEI5CEQKVKJASAUDBOR2GK4TOEBGGSYTSMFZHSIRMEJ3CEORRPWYSJPXO"
13
+
14
+ from typing import List, Tuple
15
+
16
+
17
+ def matrix_transpose(A: List[List[float]]) -> List[List[float]]:
18
+ """Transpose a matrix."""
19
+ if not A:
20
+ return []
21
+ m = len(A)
22
+ n = len(A[0])
23
+ return [[A[i][j] for i in range(m)] for j in range(n)]
24
+
25
+
26
+ def matrix_multiply(A: List[List[float]], B: List[List[float]]) -> List[List[float]]:
27
+ """Multiply two matrices A (m x n) and B (n x p) -> result (m x p)."""
28
+ m = len(A)
29
+ n = len(A[0]) if A else 0
30
+ p = len(B[0]) if B else 0
31
+
32
+ result = [[0.0] * p for _ in range(m)]
33
+ for i in range(m):
34
+ for j in range(p):
35
+ for k in range(n):
36
+ result[i][j] += A[i][k] * B[k][j]
37
+ return result
38
+
39
+
40
+ def matrix_vector_multiply(A: List[List[float]], v: List[float]) -> List[float]:
41
+ """Multiply matrix A (m x n) by vector v (n,) -> result (m,)."""
42
+ result = [0.0] * len(A)
43
+ for i in range(len(A)):
44
+ for j in range(len(v)):
45
+ result[i] += A[i][j] * v[j]
46
+ return result
47
+
48
+
49
+ def add_identity_scaled(A: List[List[float]], lambda_val: float) -> List[List[float]]:
50
+ """Add λ*I to matrix A."""
51
+ n = len(A)
52
+ result = [row[:] for row in A]
53
+ for i in range(n):
54
+ result[i][i] += lambda_val
55
+ return result
56
+
57
+
58
+ def gaussian_elimination(A: List[List[float]], b: List[float]) -> List[float]:
59
+ """
60
+ Solve Ax = b using Gaussian elimination with partial pivoting.
61
+ Modifies A and b in place.
62
+ """
63
+ n = len(A)
64
+
65
+ # Forward elimination with partial pivoting
66
+ for col in range(n):
67
+ # Find pivot
68
+ max_row = col
69
+ for row in range(col + 1, n):
70
+ if abs(A[row][col]) > abs(A[max_row][col]):
71
+ max_row = row
72
+
73
+ # Swap rows
74
+ A[col], A[max_row] = A[max_row], A[col]
75
+ b[col], b[max_row] = b[max_row], b[col]
76
+
77
+ # Eliminate below
78
+ for row in range(col + 1, n):
79
+ if A[col][col] != 0:
80
+ factor = A[row][col] / A[col][col]
81
+ for j in range(col, n):
82
+ A[row][j] -= factor * A[col][j]
83
+ b[row] -= factor * b[col]
84
+
85
+ # Back substitution
86
+ x = [0.0] * n
87
+ for i in range(n - 1, -1, -1):
88
+ x[i] = b[i]
89
+ for j in range(i + 1, n):
90
+ x[i] -= A[i][j] * x[j]
91
+ if A[i][i] != 0:
92
+ x[i] /= A[i][i]
93
+
94
+ return x
95
+
96
+
97
+ def ridge_regression_normal_eq(
98
+ X: List[List[float]],
99
+ y: List[float],
100
+ lambda_reg: float = 0.01
101
+ ) -> List[float]:
102
+ """
103
+ Fit ridge regression using normal equations.
104
+
105
+ Args:
106
+ X: list of feature vectors (n_samples x n_features)
107
+ y: list of target values
108
+ lambda_reg: regularization parameter (λ)
109
+
110
+ Returns:
111
+ weights: fitted coefficients
112
+ """
113
+ # Compute X^T * X
114
+ X_T = matrix_transpose(X)
115
+ XTX = matrix_multiply(X_T, X)
116
+
117
+ # Compute X^T * y
118
+ XTy = matrix_vector_multiply(X_T, y)
119
+
120
+ # Compute (X^T * X + λI)
121
+ XTX_regularized = add_identity_scaled(XTX, lambda_reg)
122
+
123
+ # Solve (X^T * X + λI) w = X^T * y
124
+ weights = gaussian_elimination(XTX_regularized, XTy)
125
+
126
+ return weights
127
+
128
+
129
+ def ridge_regression_predict(
130
+ X: List[List[float]],
131
+ weights: List[float]
132
+ ) -> List[float]:
133
+ """Predict using fitted weights."""
134
+ return matrix_vector_multiply(X, weights)
135
+
136
+
137
+ if __name__ == "__main__":
138
+ import random
139
+
140
+ random.seed(42)
141
+
142
+ # Generate synthetic regression data
143
+ n_samples = 30
144
+ n_features = 3
145
+ X = [[random.uniform(-5, 5) for _ in range(n_features)] for _ in range(n_samples)]
146
+
147
+ # True weights: [2, 3, -1]
148
+ true_weights = [2.0, 3.0, -1.0]
149
+ y = [sum(true_weights[j] * X[i][j] for j in range(n_features)) + random.gauss(0, 0.5)
150
+ for i in range(n_samples)]
151
+
152
+ # Fit ridge regression
153
+ weights = ridge_regression_normal_eq(X, y, lambda_reg=0.01)
154
+
155
+ # Compute R² on training data
156
+ predictions = ridge_regression_predict(X, weights)
157
+ ss_res = sum((predictions[i] - y[i]) ** 2 for i in range(n_samples))
158
+ ss_tot = sum((y[i] - sum(y) / len(y)) ** 2 for i in range(n_samples))
159
+ r2 = 1.0 - (ss_res / ss_tot) if ss_tot > 0 else 0.0
160
+
161
+ assert r2 > 0.8, f"R² = {r2} is too low"
162
+ assert all(abs(weights[i] - true_weights[i]) < 1.0 for i in range(n_features)), \
163
+ f"Weights {weights} too far from true {true_weights}"
164
+
165
+ print(f"RIDGE_REGRESSION_NORMAL_EQ PASS: R² = {r2:.3f}, weights = {[f'{w:.2f}' for w in weights]}")
forgeproof/runner.py ADDED
@@ -0,0 +1,147 @@
1
+ """Subprocess runner for gate execution.
2
+
3
+ Reuses the spirit of `library_verify.run_gate`: execute a Python file with
4
+ python3, bounded by timeout, and capture stdout/stderr/exit code.
5
+
6
+ Additional constraints for user code:
7
+ - fixed random seed (inside the fixture)
8
+ - 60-second timeout
9
+ - no network (best-effort via unshare when available)
10
+ - CPU / memory cgroup limits when running as root (optional)
11
+ """
12
+ from __future__ import annotations
13
+
14
+ import os
15
+ import resource
16
+ import shutil
17
+ import subprocess
18
+ import sys
19
+ import tempfile
20
+ from dataclasses import dataclass
21
+ from pathlib import Path
22
+ from typing import List, Optional
23
+
24
+
25
+ @dataclass(frozen=True)
26
+ class RunResult:
27
+ """Result of executing one file in a subprocess."""
28
+
29
+ exit_code: int
30
+ stdout: str
31
+ stderr: str
32
+ duration_ms: int
33
+ timed_out: bool
34
+ oom_killed: bool = False
35
+
36
+
37
+ _UNSHARE_OK: Optional[bool] = None
38
+
39
+
40
+ def _has_unshare() -> bool:
41
+ global _UNSHARE_OK
42
+ if _UNSHARE_OK is not None:
43
+ return _UNSHARE_OK
44
+ if shutil.which("unshare") is None:
45
+ _UNSHARE_OK = False
46
+ return False
47
+ # Test whether unshare --net works in this environment.
48
+ try:
49
+ c = subprocess.run(
50
+ ["unshare", "--net", "true"],
51
+ capture_output=True,
52
+ text=True,
53
+ timeout=5,
54
+ )
55
+ _UNSHARE_OK = c.returncode == 0
56
+ except Exception:
57
+ _UNSHARE_OK = False
58
+ return _UNSHARE_OK
59
+
60
+
61
+ def _build_cmd(target: Path, extra_args: Optional[List[str]] = None) -> List[str]:
62
+ from forgeproof.config import python
63
+
64
+ runner = python()
65
+ cmd = [runner, "-u", str(target)]
66
+ if extra_args:
67
+ cmd.extend(extra_args)
68
+ return cmd
69
+
70
+
71
+ def run_file(
72
+ target: Path,
73
+ *,
74
+ timeout: float = 60.0,
75
+ extra_args: Optional[List[str]] = None,
76
+ no_network: bool = True,
77
+ memory_mb: int = 512,
78
+ cpu_seconds: int = 60,
79
+ ) -> RunResult:
80
+ """Run a Python file in a fresh subprocess and capture everything.
81
+
82
+ Args:
83
+ target: Python file to execute.
84
+ timeout: seconds before SIGKILL.
85
+ extra_args: arguments to pass to the script.
86
+ no_network: if True and `unshare` is available, drop the network namespace.
87
+ memory_mb: soft memory limit in MB (set via RLIMIT_AS when not root).
88
+ cpu_seconds: soft CPU limit in seconds (set via RLIMIT_CPU when not root).
89
+ """
90
+ cmd = _build_cmd(target, extra_args)
91
+
92
+ env = os.environ.copy()
93
+ # Reduce determinism-breaking env leakage.
94
+ env.pop("PYTHONPATH", None)
95
+ env["PYTHONDONTWRITEBYTECODE"] = "1"
96
+
97
+ def _preexec():
98
+ # Limit resources in the child. These are soft limits; the child can
99
+ # still be killed by the kernel if it exceeds them.
100
+ try:
101
+ max_mem = memory_mb * 1024 * 1024
102
+ resource.setrlimit(resource.RLIMIT_AS, (max_mem, max_mem))
103
+ resource.setrlimit(resource.RLIMIT_CPU, (cpu_seconds, cpu_seconds))
104
+ except (OSError, ValueError):
105
+ pass
106
+
107
+ start = os.times()
108
+ try:
109
+ if no_network and _has_unshare():
110
+ # Drop network namespace for the python process only.
111
+ cmd = ["unshare", "--net", "--"] + cmd
112
+
113
+ proc = subprocess.run(
114
+ cmd,
115
+ capture_output=True,
116
+ text=True,
117
+ timeout=timeout,
118
+ env=env,
119
+ preexec_fn=_preexec if sys.platform != "win32" else None,
120
+ )
121
+ end = os.times()
122
+ duration_ms = int((end.elapsed - start.elapsed) * 1000)
123
+ return RunResult(
124
+ exit_code=proc.returncode,
125
+ stdout=proc.stdout,
126
+ stderr=proc.stderr,
127
+ duration_ms=duration_ms,
128
+ timed_out=False,
129
+ )
130
+ except subprocess.TimeoutExpired as exc:
131
+ end = os.times()
132
+ duration_ms = int((end.elapsed - start.elapsed) * 1000)
133
+ return RunResult(
134
+ exit_code=-9,
135
+ stdout=exc.stdout or "",
136
+ stderr=exc.stderr or "",
137
+ duration_ms=duration_ms,
138
+ timed_out=True,
139
+ )
140
+ except FileNotFoundError as exc:
141
+ return RunResult(
142
+ exit_code=127,
143
+ stdout="",
144
+ stderr=f"Runner not found: {exc}",
145
+ duration_ms=0,
146
+ timed_out=False,
147
+ )
@@ -0,0 +1,7 @@
1
+ """forgeproof scout (design v1.4.5). Build step 3a: report cards and namespaced ids only."""
2
+ from .ids import BadScoutId, ScoutId, is_scout_id, make_id, parse_id
3
+ from .cards import BadCard, check_scout_card, check_validator_shape, load_report, make_card, write_report
4
+
5
+ __all__ = ["BadScoutId", "ScoutId", "is_scout_id", "make_id", "parse_id",
6
+ "BadCard", "check_scout_card", "check_validator_shape", "load_report",
7
+ "make_card", "write_report"]