algo-cli-runtime 0.14.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 (237) hide show
  1. algo_cli/__init__.py +3 -0
  2. algo_cli/__main__.py +7 -0
  3. algo_cli/_internal/__init__.py +12 -0
  4. algo_cli/_internal/policy_chain.py +259 -0
  5. algo_cli/action_registry.py +1047 -0
  6. algo_cli/agent_blocks.py +550 -0
  7. algo_cli/agent_pipeline.py +1457 -0
  8. algo_cli/agent_threads.py +308 -0
  9. algo_cli/animations.py +316 -0
  10. algo_cli/cache_admission.py +209 -0
  11. algo_cli/capability_mask.py +66 -0
  12. algo_cli/chat_protocol.py +116 -0
  13. algo_cli/chatgpt_auth.py +510 -0
  14. algo_cli/chatgpt_client.py +657 -0
  15. algo_cli/code_rag.py +479 -0
  16. algo_cli/config.py +651 -0
  17. algo_cli/context_budget.py +679 -0
  18. algo_cli/credential_helpers.py +315 -0
  19. algo_cli/deliberation.py +29 -0
  20. algo_cli/display.py +1470 -0
  21. algo_cli/evals/__init__.py +21 -0
  22. algo_cli/evals/algorithm_effectiveness.py +560 -0
  23. algo_cli/evals/competitive_harness_rating.py +702 -0
  24. algo_cli/evals/cot_quality.py +220 -0
  25. algo_cli/evals/harness_retrieval_benchmark.py +401 -0
  26. algo_cli/evals/performance_regression.py +136 -0
  27. algo_cli/evals/scorecard_grading.py +308 -0
  28. algo_cli/evals/session_distribution.py +84 -0
  29. algo_cli/execution_guardrails.py +806 -0
  30. algo_cli/extensions_manifest.py +84 -0
  31. algo_cli/git_evidence.py +227 -0
  32. algo_cli/google_workspace.py +407 -0
  33. algo_cli/google_workspace_auth.py +523 -0
  34. algo_cli/harness.py +2587 -0
  35. algo_cli/identity.py +557 -0
  36. algo_cli/index_compute_lab.py +228 -0
  37. algo_cli/inference_harness.py +70 -0
  38. algo_cli/intelligence/__init__.py +1103 -0
  39. algo_cli/intelligence/acrobat_config.py +307 -0
  40. algo_cli/intelligence/acrobat_manifests.py +338 -0
  41. algo_cli/intelligence/acrobat_models.py +195 -0
  42. algo_cli/intelligence/acrobat_pipeline.py +295 -0
  43. algo_cli/intelligence/acrobat_runtime.py +302 -0
  44. algo_cli/intelligence/acrobat_security.py +261 -0
  45. algo_cli/intelligence/acrobat_workflows.py +226 -0
  46. algo_cli/intelligence/actionability.py +165 -0
  47. algo_cli/intelligence/adversarial_audit.py +136 -0
  48. algo_cli/intelligence/agent_arena.py +92 -0
  49. algo_cli/intelligence/agent_benchmark.py +236 -0
  50. algo_cli/intelligence/agent_runtime.py +171 -0
  51. algo_cli/intelligence/agents_as_tools.py +70 -0
  52. algo_cli/intelligence/artifact_binding.py +80 -0
  53. algo_cli/intelligence/autonomous_engineer.py +1976 -0
  54. algo_cli/intelligence/backpressure.py +99 -0
  55. algo_cli/intelligence/bloom_filter.py +186 -0
  56. algo_cli/intelligence/bonferroni.py +66 -0
  57. algo_cli/intelligence/boundary_compaction.py +98 -0
  58. algo_cli/intelligence/catalog_verifier.py +172 -0
  59. algo_cli/intelligence/cavecrew.py +118 -0
  60. algo_cli/intelligence/changelog.py +176 -0
  61. algo_cli/intelligence/checkpoint_resume.py +92 -0
  62. algo_cli/intelligence/circuit_breaker.py +88 -0
  63. algo_cli/intelligence/clarification_gate.py +101 -0
  64. algo_cli/intelligence/code_graph.py +180 -0
  65. algo_cli/intelligence/coderank.py +97 -0
  66. algo_cli/intelligence/consistent_hash.py +150 -0
  67. algo_cli/intelligence/consortium_synthesis.py +139 -0
  68. algo_cli/intelligence/construction/__init__.py +241 -0
  69. algo_cli/intelligence/construction/common.py +273 -0
  70. algo_cli/intelligence/construction/documents.py +496 -0
  71. algo_cli/intelligence/construction/labor_units.py +1395 -0
  72. algo_cli/intelligence/construction/payments.py +470 -0
  73. algo_cli/intelligence/construction/risk.py +784 -0
  74. algo_cli/intelligence/content_extractor.py +132 -0
  75. algo_cli/intelligence/context_adaptive.py +102 -0
  76. algo_cli/intelligence/context_ops.py +95 -0
  77. algo_cli/intelligence/count_min.py +145 -0
  78. algo_cli/intelligence/cow_state.py +103 -0
  79. algo_cli/intelligence/critic_loop.py +119 -0
  80. algo_cli/intelligence/cross_source.py +113 -0
  81. algo_cli/intelligence/daemon_mode.py +99 -0
  82. algo_cli/intelligence/dag_orchestration.py +151 -0
  83. algo_cli/intelligence/deep_research.py +155 -0
  84. algo_cli/intelligence/degenerate_detector.py +78 -0
  85. algo_cli/intelligence/delta_report.py +92 -0
  86. algo_cli/intelligence/discovery_event_log.py +92 -0
  87. algo_cli/intelligence/document_ingest.py +298 -0
  88. algo_cli/intelligence/dual_layer_validate.py +151 -0
  89. algo_cli/intelligence/echo_fidelity.py +73 -0
  90. algo_cli/intelligence/ema_tuning.py +104 -0
  91. algo_cli/intelligence/event_log.py +92 -0
  92. algo_cli/intelligence/evidence_graph.py +114 -0
  93. algo_cli/intelligence/extension_host.py +162 -0
  94. algo_cli/intelligence/extension_manifest.py +115 -0
  95. algo_cli/intelligence/falsification_suite.py +178 -0
  96. algo_cli/intelligence/finance/__init__.py +169 -0
  97. algo_cli/intelligence/finance/anomalies.py +135 -0
  98. algo_cli/intelligence/finance/ap_ar.py +351 -0
  99. algo_cli/intelligence/finance/cash.py +162 -0
  100. algo_cli/intelligence/finance/close.py +332 -0
  101. algo_cli/intelligence/finance/common.py +244 -0
  102. algo_cli/intelligence/finance/construction.py +135 -0
  103. algo_cli/intelligence/finance/controls.py +172 -0
  104. algo_cli/intelligence/finance/evidence.py +119 -0
  105. algo_cli/intelligence/finance/exceptions.py +157 -0
  106. algo_cli/intelligence/finance/reconciliations.py +254 -0
  107. algo_cli/intelligence/finance/revenue.py +109 -0
  108. algo_cli/intelligence/finance/tax.py +74 -0
  109. algo_cli/intelligence/finance/workpapers.py +111 -0
  110. algo_cli/intelligence/finding_record.py +120 -0
  111. algo_cli/intelligence/flow_dag.py +267 -0
  112. algo_cli/intelligence/gatherer.py +223 -0
  113. algo_cli/intelligence/golden_master.py +98 -0
  114. algo_cli/intelligence/graph_rag.py +195 -0
  115. algo_cli/intelligence/group_chat.py +143 -0
  116. algo_cli/intelligence/hash_dedup.py +145 -0
  117. algo_cli/intelligence/hyperloglog.py +128 -0
  118. algo_cli/intelligence/incremental_index.py +316 -0
  119. algo_cli/intelligence/index_store.py +16 -0
  120. algo_cli/intelligence/iteration_plan.py +133 -0
  121. algo_cli/intelligence/kernel_plugins.py +167 -0
  122. algo_cli/intelligence/lesson_catalog.py +135 -0
  123. algo_cli/intelligence/llm_fallback.py +169 -0
  124. algo_cli/intelligence/log2_histogram.py +267 -0
  125. algo_cli/intelligence/lsp_integration.py +147 -0
  126. algo_cli/intelligence/memory_evolution.py +117 -0
  127. algo_cli/intelligence/minhash_lsh.py +182 -0
  128. algo_cli/intelligence/multi_model_score.py +174 -0
  129. algo_cli/intelligence/multi_tier_grade.py +211 -0
  130. algo_cli/intelligence/negative_controls.py +113 -0
  131. algo_cli/intelligence/numeric_clamp.py +63 -0
  132. algo_cli/intelligence/occ_editor.py +66 -0
  133. algo_cli/intelligence/output_normalize.py +112 -0
  134. algo_cli/intelligence/parallel_delegation.py +98 -0
  135. algo_cli/intelligence/parallel_fanout.py +104 -0
  136. algo_cli/intelligence/permission_modes.py +105 -0
  137. algo_cli/intelligence/pre_push_gate.py +68 -0
  138. algo_cli/intelligence/prefetch.py +171 -0
  139. algo_cli/intelligence/process_framework.py +217 -0
  140. algo_cli/intelligence/project_graph.py +387 -0
  141. algo_cli/intelligence/query_expansion.py +146 -0
  142. algo_cli/intelligence/ralph_loop.py +117 -0
  143. algo_cli/intelligence/rate_limiter.py +153 -0
  144. algo_cli/intelligence/refactor_transaction.py +94 -0
  145. algo_cli/intelligence/research_workspace.py +108 -0
  146. algo_cli/intelligence/retraction_ledger.py +72 -0
  147. algo_cli/intelligence/saga_pattern.py +88 -0
  148. algo_cli/intelligence/session_fork.py +100 -0
  149. algo_cli/intelligence/shadow_editor.py +67 -0
  150. algo_cli/intelligence/shell_session.py +213 -0
  151. algo_cli/intelligence/source_registry.py +143 -0
  152. algo_cli/intelligence/spawn_scales.py +99 -0
  153. algo_cli/intelligence/stat_stability.py +104 -0
  154. algo_cli/intelligence/structural_validator.py +148 -0
  155. algo_cli/intelligence/subagent_spawner.py +111 -0
  156. algo_cli/intelligence/symmetric_verify.py +70 -0
  157. algo_cli/intelligence/task_classifier.py +129 -0
  158. algo_cli/intelligence/team_execution.py +122 -0
  159. algo_cli/intelligence/tiered_access.py +121 -0
  160. algo_cli/intelligence/utility_registry.py +159 -0
  161. algo_cli/intuition_engine.py +560 -0
  162. algo_cli/intuition_injector.py +82 -0
  163. algo_cli/kernels/__init__.py +5 -0
  164. algo_cli/kernels/manifest.py +763 -0
  165. algo_cli/main.py +3903 -0
  166. algo_cli/memory_candidates.py +541 -0
  167. algo_cli/memory_echo_veil.py +394 -0
  168. algo_cli/memory_runtime.py +112 -0
  169. algo_cli/model_info.py +548 -0
  170. algo_cli/model_profile.py +160 -0
  171. algo_cli/model_routing.py +74 -0
  172. algo_cli/oneshot.py +331 -0
  173. algo_cli/perf_telemetry.py +389 -0
  174. algo_cli/plugins.py +245 -0
  175. algo_cli/private_event_store.py +654 -0
  176. algo_cli/quantization/__init__.py +24 -0
  177. algo_cli/quantization/lloyd_max.py +98 -0
  178. algo_cli/quantization/turbo_quant.py +308 -0
  179. algo_cli/reasoning/__init__.py +46 -0
  180. algo_cli/reasoning/combinatorial.py +356 -0
  181. algo_cli/reasoning/graph_of_thought.py +297 -0
  182. algo_cli/reasoning/mcts.py +220 -0
  183. algo_cli/reasoning/neuro_symbolic.py +250 -0
  184. algo_cli/reasoning/react.py +246 -0
  185. algo_cli/reasoning/reflexion.py +225 -0
  186. algo_cli/reasoning/tree_of_thought.py +241 -0
  187. algo_cli/reasoning_bridge.py +150 -0
  188. algo_cli/reconciliation.py +284 -0
  189. algo_cli/reflex.py +385 -0
  190. algo_cli/resources/docs/ALGO.md +13958 -0
  191. algo_cli/resources/docs/algo-cli-algorithm-evidence-contract.md +60 -0
  192. algo_cli/resources/docs/algo-cli-execution-verification-contract.md +59 -0
  193. algo_cli/resources/docs/algo-cli-memory-lifecycle-contract.md +72 -0
  194. algo_cli/resources/docs/harness-extension-cleanup-recommendation.md +41 -0
  195. algo_cli/resources/docs/index-compute-lab-integration.md +32 -0
  196. algo_cli/resources/docs/inference-harness-loop-blueprint-2026-06.md +55 -0
  197. algo_cli/resources/docs/main-split-map.md +35 -0
  198. algo_cli/resources/docs/privacy-and-context.md +48 -0
  199. algo_cli/resources/docs/reflex-loop-v0.2.md +354 -0
  200. algo_cli/resources/skills/README.md +26 -0
  201. algo_cli/resources/skills/algo-cli.md +59 -0
  202. algo_cli/resources/skills/edit-file-precision.md +49 -0
  203. algo_cli/resources/skills/harness-search-first.md +47 -0
  204. algo_cli/resources/skills/memory-recall-ritual.md +51 -0
  205. algo_cli/resources/skills/qol-algorithms.md +224 -0
  206. algo_cli/resources/skills/smart-error-recovery.md +56 -0
  207. algo_cli/resources/skills/tool-selection-cheatsheet.md +65 -0
  208. algo_cli/retrieval_algorithms.py +127 -0
  209. algo_cli/runtime_qos.py +236 -0
  210. algo_cli/runtime_services.py +320 -0
  211. algo_cli/session_commands.py +95 -0
  212. algo_cli/session_mode.py +113 -0
  213. algo_cli/skills.py +430 -0
  214. algo_cli/slash_dispatch.py +1265 -0
  215. algo_cli/small_context.py +206 -0
  216. algo_cli/spawn_budget.py +89 -0
  217. algo_cli/task_ledger.py +84 -0
  218. algo_cli/task_router.py +197 -0
  219. algo_cli/tool_context.py +94 -0
  220. algo_cli/tool_contract.py +99 -0
  221. algo_cli/tool_policy.py +357 -0
  222. algo_cli/tool_runtime.py +647 -0
  223. algo_cli/tools.py +3056 -0
  224. algo_cli/url_scheme.py +174 -0
  225. algo_cli/verify.py +154 -0
  226. algo_cli/version_manifest.py +178 -0
  227. algo_cli/vision_screenshot_verify.py +76 -0
  228. algo_cli/workspace_resolver.py +68 -0
  229. algo_cli/x_account.py +209 -0
  230. algo_cli/xai_auth.py +374 -0
  231. algo_cli/xai_client.py +600 -0
  232. algo_cli_runtime-0.14.0.dist-info/METADATA +369 -0
  233. algo_cli_runtime-0.14.0.dist-info/RECORD +237 -0
  234. algo_cli_runtime-0.14.0.dist-info/WHEEL +4 -0
  235. algo_cli_runtime-0.14.0.dist-info/entry_points.txt +3 -0
  236. algo_cli_runtime-0.14.0.dist-info/licenses/LICENSE +21 -0
  237. ollama_cli/__init__.py +67 -0
@@ -0,0 +1,211 @@
1
+ """H26 — Multi-Tier Grading.
2
+
3
+ Strict / lenient / structured grading tiers for solution evaluation.
4
+ Mined from GLOSSOPETRAE experiments/lib/grade_rigor.mjs.
5
+
6
+ - gradeStrict: unforgiving — any error fails
7
+ - gradeLenient: attempts surface recovery before grading
8
+ - gradeStructured: requires control flow presence, rejects degenerate precompute
9
+ """
10
+ from __future__ import annotations
11
+
12
+ import ast
13
+ from dataclasses import dataclass, field
14
+
15
+
16
+ @dataclass
17
+ class GradeResult:
18
+ """Result of grading a solution."""
19
+
20
+ tier: str # "strict", "lenient", "structured"
21
+ passed: bool
22
+ score: float # 0.0 - 1.0
23
+ correct_output: bool = False
24
+ has_required_constructs: bool = False
25
+ is_degenerate: bool = False
26
+ recovered: bool = False
27
+ notes: list[str] = field(default_factory=list)
28
+
29
+
30
+ def _check_output_correctness(actual: str, expected: str) -> bool:
31
+ """Check if actual output matches expected."""
32
+ return actual.strip() == expected.strip()
33
+
34
+
35
+ def _has_required_constructs(code: str) -> bool:
36
+ """Check if code has loops, functions, or conditionals."""
37
+ try:
38
+ tree = ast.parse(code)
39
+ except SyntaxError:
40
+ return False
41
+
42
+ has_loop = False
43
+ has_func = False
44
+ has_conditional = False
45
+
46
+ for node in ast.walk(tree):
47
+ if isinstance(node, (ast.For, ast.While)):
48
+ has_loop = True
49
+ elif isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.Lambda)):
50
+ has_func = True
51
+ elif isinstance(node, (ast.If, ast.IfExp)):
52
+ has_conditional = True
53
+
54
+ return has_loop or has_func or has_conditional
55
+
56
+
57
+ def _is_degenerate_precompute(code: str) -> bool:
58
+ """Check if code precomputes the answer without required constructs."""
59
+ try:
60
+ tree = ast.parse(code)
61
+ except SyntaxError:
62
+ return False
63
+
64
+ has_loop = any(isinstance(n, (ast.For, ast.While)) for n in ast.walk(tree))
65
+ has_func_def = any(
66
+ isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef))
67
+ for n in ast.walk(tree)
68
+ )
69
+ has_conditional = any(isinstance(n, (ast.If, ast.IfExp)) for n in ast.walk(tree))
70
+ has_call = any(isinstance(n, ast.Call) for n in ast.walk(tree))
71
+
72
+ # Degenerate: has no loops, no function defs, no conditionals, and no function calls
73
+ return not (has_loop or has_func_def or has_conditional or has_call)
74
+
75
+
76
+ def grade_strict(
77
+ code: str,
78
+ actual_output: str,
79
+ expected_output: str,
80
+ ) -> GradeResult:
81
+ """Grade strictly — any error fails."""
82
+ correct = _check_output_correctness(actual_output, expected_output)
83
+ return GradeResult(
84
+ tier="strict",
85
+ passed=correct,
86
+ score=1.0 if correct else 0.0,
87
+ correct_output=correct,
88
+ notes=["Strict: output must match exactly"],
89
+ )
90
+
91
+
92
+ def grade_lenient(
93
+ code: str,
94
+ actual_output: str,
95
+ expected_output: str,
96
+ ) -> GradeResult:
97
+ """Grade leniently — attempt surface recovery before grading."""
98
+ # Try exact match first (no normalization)
99
+ if actual_output == expected_output:
100
+ return GradeResult(
101
+ tier="lenient",
102
+ passed=True,
103
+ score=1.0,
104
+ correct_output=True,
105
+ recovered=False,
106
+ notes=["Lenient: exact match"],
107
+ )
108
+
109
+ # Try surface recovery: normalize whitespace
110
+ recovered_output = actual_output.strip()
111
+ recovered_expected = expected_output.strip()
112
+
113
+ # Try exact match after strip
114
+ correct = recovered_output == recovered_expected
115
+ if correct:
116
+ return GradeResult(
117
+ tier="lenient",
118
+ passed=True,
119
+ score=1.0,
120
+ correct_output=True,
121
+ recovered=True,
122
+ notes=["Lenient: whitespace stripped"],
123
+ )
124
+
125
+ # Try case-insensitive match (recovery)
126
+ correct = recovered_output.lower() == recovered_expected.lower()
127
+
128
+ # Try removing extra whitespace
129
+ if not correct:
130
+ import re
131
+ norm_actual = re.sub(r"\s+", " ", recovered_output).strip()
132
+ norm_expected = re.sub(r"\s+", " ", recovered_expected).strip()
133
+ correct = norm_actual == norm_expected
134
+ recovered = correct
135
+ else:
136
+ recovered = True
137
+
138
+ return GradeResult(
139
+ tier="lenient",
140
+ passed=correct,
141
+ score=1.0 if correct else 0.0,
142
+ correct_output=correct,
143
+ recovered=recovered,
144
+ notes=["Lenient: whitespace and case normalized"] if recovered else ["Lenient: output does not match"],
145
+ )
146
+
147
+
148
+ def grade_structured(
149
+ code: str,
150
+ actual_output: str,
151
+ expected_output: str,
152
+ ) -> GradeResult:
153
+ """Grade with structure requirements — must have control flow, no degenerate precompute."""
154
+ correct = _check_output_correctness(actual_output, expected_output)
155
+ has_constructs = _has_required_constructs(code)
156
+ degenerate = _is_degenerate_precompute(code)
157
+
158
+ notes: list[str] = []
159
+ if degenerate:
160
+ notes.append("Degenerate precompute: no loops, functions, or conditionals found")
161
+ if not has_constructs:
162
+ notes.append("Missing required constructs (loops, functions, or conditionals)")
163
+
164
+ # Structured: must be correct AND have constructs AND not be degenerate
165
+ passed = correct and has_constructs and not degenerate
166
+
167
+ if passed:
168
+ score = 1.0
169
+ elif correct and not degenerate:
170
+ score = 0.7 # Correct but missing some constructs
171
+ elif correct:
172
+ score = 0.3 # Correct but degenerate
173
+ else:
174
+ score = 0.0
175
+
176
+ return GradeResult(
177
+ tier="structured",
178
+ passed=passed,
179
+ score=score,
180
+ correct_output=correct,
181
+ has_required_constructs=has_constructs,
182
+ is_degenerate=degenerate,
183
+ notes=notes,
184
+ )
185
+
186
+
187
+ def grade(
188
+ code: str,
189
+ actual_output: str,
190
+ expected_output: str,
191
+ tier: str = "strict",
192
+ ) -> GradeResult:
193
+ """Grade a solution at the specified tier.
194
+
195
+ Args:
196
+ code: The solution code.
197
+ actual_output: What the code produced.
198
+ expected_output: What was expected.
199
+ tier: "strict", "lenient", or "structured".
200
+
201
+ Returns:
202
+ GradeResult with detailed grading information.
203
+ """
204
+ if tier == "strict":
205
+ return grade_strict(code, actual_output, expected_output)
206
+ elif tier == "lenient":
207
+ return grade_lenient(code, actual_output, expected_output)
208
+ elif tier == "structured":
209
+ return grade_structured(code, actual_output, expected_output)
210
+ else:
211
+ raise ValueError(f"Unknown grading tier: {tier}")
@@ -0,0 +1,113 @@
1
+ """H17 — Negative Control Samples.
2
+
3
+ Known-clean samples to measure false positive rate.
4
+ Mined from T3MP3ST bench/cve-hunt/ DECOY samples.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ from dataclasses import dataclass, field
9
+ from typing import Any
10
+
11
+
12
+ @dataclass
13
+ class ControlSample:
14
+ """A single negative control sample."""
15
+
16
+ id: str
17
+ content: str
18
+ label: str = "clean"
19
+ expected_finding: bool = False
20
+ metadata: dict[str, Any] = field(default_factory=dict)
21
+
22
+
23
+ @dataclass
24
+ class ConfusionMatrix:
25
+ """Confusion matrix from running a detector against control samples."""
26
+
27
+ true_positives: int = 0
28
+ false_positives: int = 0
29
+ true_negatives: int = 0
30
+ false_negatives: int = 0
31
+
32
+ @property
33
+ def total(self) -> int:
34
+ return self.true_positives + self.false_positives + self.true_negatives + self.false_negatives
35
+
36
+ @property
37
+ def false_positive_rate(self) -> float:
38
+ tn_fp = self.true_negatives + self.false_positives
39
+ return self.false_positives / tn_fp if tn_fp > 0 else 0.0
40
+
41
+ @property
42
+ def false_negative_rate(self) -> float:
43
+ tp_fn = self.true_positives + self.false_negatives
44
+ return self.false_negatives / tp_fn if tp_fn > 0 else 0.0
45
+
46
+ @property
47
+ def accuracy(self) -> float:
48
+ if self.total == 0:
49
+ return 0.0
50
+ return (self.true_positives + self.true_negatives) / self.total
51
+
52
+ def to_dict(self) -> dict[str, Any]:
53
+ return {
54
+ "true_positives": self.true_positives,
55
+ "false_positives": self.false_positives,
56
+ "true_negatives": self.true_negatives,
57
+ "false_negatives": self.false_negatives,
58
+ "false_positive_rate": self.false_positive_rate,
59
+ "false_negative_rate": self.false_negative_rate,
60
+ "accuracy": self.accuracy,
61
+ }
62
+
63
+
64
+ class NegativeControlSuite:
65
+ """Manage negative control samples and compute confusion matrices."""
66
+
67
+ def __init__(self) -> None:
68
+ self._samples: list[ControlSample] = []
69
+
70
+ def add_sample(
71
+ self,
72
+ id: str,
73
+ content: str,
74
+ expected_finding: bool = False,
75
+ label: str = "clean",
76
+ metadata: dict[str, Any] | None = None,
77
+ ) -> ControlSample:
78
+ sample = ControlSample(
79
+ id=id,
80
+ content=content,
81
+ label=label,
82
+ expected_finding=expected_finding,
83
+ metadata=metadata or {},
84
+ )
85
+ self._samples.append(sample)
86
+ return sample
87
+
88
+ def evaluate(self, detector_results: dict[str, bool]) -> ConfusionMatrix:
89
+ """Evaluate detector results against expected findings."""
90
+ cm = ConfusionMatrix()
91
+ for sample in self._samples:
92
+ detected = detector_results.get(sample.id, False)
93
+ if sample.expected_finding and detected:
94
+ cm.true_positives += 1
95
+ elif sample.expected_finding and not detected:
96
+ cm.false_negatives += 1
97
+ elif not sample.expected_finding and detected:
98
+ cm.false_positives += 1
99
+ else:
100
+ cm.true_negatives += 1
101
+ return cm
102
+
103
+ def get_sample(self, sample_id: str) -> ControlSample | None:
104
+ for s in self._samples:
105
+ if s.id == sample_id:
106
+ return s
107
+ return None
108
+
109
+ def all_samples(self) -> list[ControlSample]:
110
+ return list(self._samples)
111
+
112
+ def count(self) -> int:
113
+ return len(self._samples)
@@ -0,0 +1,63 @@
1
+ """H10 — Numeric Clamp Guard.
2
+
3
+ Prevents impossible telemetry values by clamping to a valid range and
4
+ recording warnings when out-of-range values are encountered.
5
+
6
+ Source: GLOSSOPETRAE ``clampCheck()``.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ from dataclasses import dataclass
11
+
12
+
13
+ @dataclass
14
+ class ClampWarning:
15
+ """Recorded when a value is clamped."""
16
+
17
+ original: float
18
+ clamped: float
19
+ lo: float
20
+ hi: float
21
+
22
+
23
+ class NumericClampGuard:
24
+ """Clamp numeric values to [lo, hi] and record out-of-range events."""
25
+
26
+ def __init__(self, lo: float = 0.0, hi: float = 1.0) -> None:
27
+ if lo > hi:
28
+ raise ValueError(f"lo ({lo}) must be <= hi ({hi})")
29
+ self.lo = lo
30
+ self.hi = hi
31
+ self.warnings: list[ClampWarning] = []
32
+
33
+ def clamp(self, value: float) -> float:
34
+ """Clamp *value* to [lo, hi]. Records a warning if clamping occurred."""
35
+ if value < self.lo:
36
+ self.warnings.append(
37
+ ClampWarning(original=value, clamped=self.lo, lo=self.lo, hi=self.hi)
38
+ )
39
+ return self.lo
40
+ if value > self.hi:
41
+ self.warnings.append(
42
+ ClampWarning(original=value, clamped=self.hi, lo=self.lo, hi=self.hi)
43
+ )
44
+ return self.hi
45
+ return value
46
+
47
+ def clamp_many(self, values: list[float]) -> list[float]:
48
+ """Clamp a batch of values."""
49
+ return [self.clamp(v) for v in values]
50
+
51
+ def has_warnings(self) -> bool:
52
+ return len(self.warnings) > 0
53
+
54
+ def clear_warnings(self) -> None:
55
+ self.warnings.clear()
56
+
57
+ def stats(self) -> dict:
58
+ return {
59
+ "lo": self.lo,
60
+ "hi": self.hi,
61
+ "warnings": len(self.warnings),
62
+ "clamped_count": len(self.warnings),
63
+ }
@@ -0,0 +1,66 @@
1
+ """B80. Optimistic Concurrency Control for Edits.
2
+
3
+ SHA-256 version hashes prevent conflicting writes and stale-data overwrites.
4
+ Source: Pathfinder pattern.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import hashlib
9
+ from dataclasses import dataclass
10
+ from pathlib import Path
11
+
12
+
13
+ @dataclass
14
+ class WriteResult:
15
+ success: bool
16
+ version: str = ""
17
+ error: str = ""
18
+ current_version: str = ""
19
+ message: str = ""
20
+
21
+
22
+ class OCCEditor:
23
+ """Optimistic concurrency control for file edits."""
24
+
25
+ def __init__(self) -> None:
26
+ self._versions: dict[str, str] = {}
27
+
28
+ def read(self, path: str) -> tuple[str, str]:
29
+ """Read file and return (content, version_hash)."""
30
+ content = Path(path).read_text(encoding="utf-8")
31
+ version = self._hash(content)
32
+ self._versions[path] = version
33
+ return content, version
34
+
35
+ def write(self, path: str, content: str, expected_version: str) -> WriteResult:
36
+ """Write with OCC — fails if file changed since read."""
37
+ try:
38
+ current = Path(path).read_text(encoding="utf-8")
39
+ except FileNotFoundError:
40
+ current = ""
41
+ current_version = self._hash(current)
42
+
43
+ if current_version != expected_version:
44
+ return WriteResult(
45
+ success=False,
46
+ error="VERSION_MISMATCH",
47
+ current_version=current_version,
48
+ message=f"File changed since you read it. Expected {expected_version[:8]}, got {current_version[:8]}.",
49
+ )
50
+
51
+ Path(path).write_text(content, encoding="utf-8")
52
+ new_version = self._hash(content)
53
+ self._versions[path] = new_version
54
+ return WriteResult(success=True, version=new_version)
55
+
56
+ def check_version(self, path: str, expected_version: str) -> bool:
57
+ """Check if file still matches expected version."""
58
+ try:
59
+ content = Path(path).read_text(encoding="utf-8")
60
+ except FileNotFoundError:
61
+ return False
62
+ return self._hash(content) == expected_version
63
+
64
+ @staticmethod
65
+ def _hash(content: str) -> str:
66
+ return hashlib.sha256(content.encode("utf-8")).hexdigest()
@@ -0,0 +1,112 @@
1
+ """H22 — Sequential Output Normalization Pipeline.
2
+
3
+ Toggleable pipeline stages for output normalization.
4
+ Mined from G0DM0D3 PAPER.md §3.5 STM.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import re
9
+ from dataclasses import dataclass
10
+ from typing import Callable
11
+
12
+
13
+ @dataclass
14
+ class PipelineStage:
15
+ """A single normalization stage."""
16
+
17
+ name: str
18
+ enabled: bool = True
19
+ transform: Callable[[str], str] = lambda x: x
20
+ description: str = ""
21
+
22
+
23
+ class OutputNormalizationPipeline:
24
+ """Sequential pipeline of toggleable normalization stages."""
25
+
26
+ def __init__(self) -> None:
27
+ self._stages: list[PipelineStage] = []
28
+
29
+ def add_stage(
30
+ self,
31
+ name: str,
32
+ transform: Callable[[str], str],
33
+ enabled: bool = True,
34
+ description: str = "",
35
+ ) -> PipelineStage:
36
+ stage = PipelineStage(
37
+ name=name, enabled=enabled, transform=transform, description=description
38
+ )
39
+ self._stages.append(stage)
40
+ return stage
41
+
42
+ def enable(self, name: str) -> bool:
43
+ stage = self._find(name)
44
+ if stage is None:
45
+ return False
46
+ stage.enabled = True
47
+ return True
48
+
49
+ def disable(self, name: str) -> bool:
50
+ stage = self._find(name)
51
+ if stage is None:
52
+ return False
53
+ stage.enabled = False
54
+ return True
55
+
56
+ def _find(self, name: str) -> PipelineStage | None:
57
+ for s in self._stages:
58
+ if s.name == name:
59
+ return s
60
+ return None
61
+
62
+ def run(self, text: str) -> str:
63
+ """Run all enabled stages in sequence."""
64
+ result = text
65
+ for stage in self._stages:
66
+ if stage.enabled:
67
+ result = stage.transform(result)
68
+ return result
69
+
70
+ def get_stage_names(self) -> list[str]:
71
+ return [s.name for s in self._stages]
72
+
73
+ def get_enabled_stages(self) -> list[str]:
74
+ return [s.name for s in self._stages if s.enabled]
75
+
76
+ def count(self) -> int:
77
+ return len(self._stages)
78
+
79
+ def remove_stage(self, name: str) -> bool:
80
+ stage = self._find(name)
81
+ if stage is None:
82
+ return False
83
+ self._stages.remove(stage)
84
+ return True
85
+
86
+
87
+ # Built-in transforms
88
+ def hedge_reducer(text: str) -> str:
89
+ """Reduce hedging language."""
90
+ text = re.sub(r"\bI think\b", "", text, flags=re.IGNORECASE)
91
+ text = re.sub(r"\bmaybe\b", "", text, flags=re.IGNORECASE)
92
+ text = re.sub(r"\bperhaps\b", "", text, flags=re.IGNORECASE)
93
+ text = re.sub(r"\bpossibly\b", "", text, flags=re.IGNORECASE)
94
+ text = re.sub(r"\s+", " ", text)
95
+ return text.strip()
96
+
97
+
98
+ def direct_mode(text: str) -> str:
99
+ """Convert indirect requests to direct."""
100
+ text = re.sub(r"\bCould you\b", "", text, flags=re.IGNORECASE)
101
+ text = re.sub(r"\bWould you\b", "", text, flags=re.IGNORECASE)
102
+ text = re.sub(r"\bCan you\b", "", text, flags=re.IGNORECASE)
103
+ text = re.sub(r"\s+", " ", text)
104
+ return text.strip()
105
+
106
+
107
+ def casual_mode(text: str) -> str:
108
+ """Make output more casual."""
109
+ text = re.sub(r"\bTherefore\b", "So", text, flags=re.IGNORECASE)
110
+ text = re.sub(r"\bHowever\b", "But", text, flags=re.IGNORECASE)
111
+ text = re.sub(r"\s+", " ", text)
112
+ return text.strip()
@@ -0,0 +1,98 @@
1
+ """B70. Parallel Delegation + Subject Hygiene.
2
+
3
+ Launch 2-4 subagents simultaneously, each with a clear traceable subject.
4
+ Source: awesome-agentic-patterns.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import time
9
+ from concurrent.futures import ThreadPoolExecutor, as_completed
10
+ from dataclasses import dataclass
11
+ from typing import Callable
12
+
13
+
14
+ @dataclass
15
+ class DelegatedTask:
16
+ subject: str # clear, traceable identifier
17
+ description: str
18
+ agent_id: str = ""
19
+ priority: int = 5
20
+
21
+
22
+ @dataclass
23
+ class DelegationResult:
24
+ subject: str
25
+ output: str = ""
26
+ success: bool = True
27
+ error: str | None = None
28
+ duration_s: float = 0.0
29
+
30
+
31
+ class ParallelDelegator:
32
+ """Delegate tasks to multiple agents in parallel with subject hygiene."""
33
+
34
+ def __init__(self, max_workers: int = 4) -> None:
35
+ self._max_workers = max_workers
36
+
37
+ def delegate_all(
38
+ self,
39
+ tasks: list[DelegatedTask],
40
+ run_fn: Callable[[DelegatedTask], str],
41
+ ) -> list[DelegationResult]:
42
+ """Run all tasks in parallel, wait for all to complete."""
43
+ results: list[DelegationResult] = []
44
+
45
+ with ThreadPoolExecutor(max_workers=self._max_workers) as pool:
46
+ future_to_task = {pool.submit(self._run, task, run_fn): task for task in tasks}
47
+ for future in as_completed(future_to_task):
48
+ results.append(future.result())
49
+
50
+ # Sort by original task order
51
+ subject_order = {t.subject: i for i, t in enumerate(tasks)}
52
+ results.sort(key=lambda r: subject_order.get(r.subject, 999))
53
+ return results
54
+
55
+ def delegate_race(
56
+ self,
57
+ tasks: list[DelegatedTask],
58
+ run_fn: Callable[[DelegatedTask], str],
59
+ ) -> DelegationResult | None:
60
+ """Run tasks in parallel, return first successful result."""
61
+ with ThreadPoolExecutor(max_workers=self._max_workers) as pool:
62
+ futures = {pool.submit(self._run, task, run_fn): task for task in tasks}
63
+ for future in as_completed(futures):
64
+ result = future.result()
65
+ if result.success:
66
+ # Cancel remaining
67
+ for f in futures:
68
+ f.cancel()
69
+ return result
70
+ return None
71
+
72
+ def _run(self, task: DelegatedTask, run_fn: Callable[[DelegatedTask], str]) -> DelegationResult:
73
+ start = time.time()
74
+ try:
75
+ output = run_fn(task)
76
+ return DelegationResult(
77
+ subject=task.subject, output=output,
78
+ duration_s=time.time() - start,
79
+ )
80
+ except Exception as e:
81
+ return DelegationResult(
82
+ subject=task.subject, success=False, error=str(e),
83
+ duration_s=time.time() - start,
84
+ )
85
+
86
+ @staticmethod
87
+ def validate_subjects(tasks: list[DelegatedTask]) -> list[str]:
88
+ """Ensure subjects are unique and descriptive. Return issues."""
89
+ issues: list[str] = []
90
+ subjects = [t.subject for t in tasks]
91
+ if len(set(subjects)) != len(subjects):
92
+ issues.append("Duplicate subjects found")
93
+ for t in tasks:
94
+ if len(t.subject) < 3:
95
+ issues.append(f"Subject too short: '{t.subject}'")
96
+ if len(t.description) < 10:
97
+ issues.append(f"Description too short for '{t.subject}'")
98
+ return issues