letitloop 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.
- letitloop-0.2.0.dist-info/METADATA +232 -0
- letitloop-0.2.0.dist-info/RECORD +175 -0
- letitloop-0.2.0.dist-info/WHEEL +5 -0
- letitloop-0.2.0.dist-info/entry_points.txt +4 -0
- letitloop-0.2.0.dist-info/licenses/LICENSE +21 -0
- letitloop-0.2.0.dist-info/top_level.txt +1 -0
- orchestrator/SKILL.md +292 -0
- orchestrator/__init__.py +151 -0
- orchestrator/anti_ouroboros.py +78 -0
- orchestrator/approval.py +139 -0
- orchestrator/ast_node_splicer.py +130 -0
- orchestrator/ast_splicer.py +94 -0
- orchestrator/audit.py +88 -0
- orchestrator/budget.py +195 -0
- orchestrator/checkpoint.py +248 -0
- orchestrator/cli.py +1971 -0
- orchestrator/codebase_introspector.py +66 -0
- orchestrator/component_slicer.py +185 -0
- orchestrator/config.py +152 -0
- orchestrator/contract.py +404 -0
- orchestrator/dag_validator.py +172 -0
- orchestrator/elasticity_governor.py +80 -0
- orchestrator/env_doctor.py +166 -0
- orchestrator/errors.py +211 -0
- orchestrator/events.py +120 -0
- orchestrator/evidence.py +203 -0
- orchestrator/exceptions.py +37 -0
- orchestrator/experimental/arena_arbiter.py +260 -0
- orchestrator/experimental/fuzz_engine.py +206 -0
- orchestrator/experimental/mutation_tester.py +382 -0
- orchestrator/failure.py +226 -0
- orchestrator/fast_sandbox.py +126 -0
- orchestrator/feasibility_gate.py +115 -0
- orchestrator/feedback.py +302 -0
- orchestrator/fixtures/__init__.py +0 -0
- orchestrator/fixtures/example_contract.json +50 -0
- orchestrator/fixtures/generated/evidence-cli-run-test-step-1.json +47 -0
- orchestrator/fixtures/generated/evidence-cli-run-test-step-2.json +47 -0
- orchestrator/fixtures/generated/evidence-inject-test-a.json +47 -0
- orchestrator/fixtures/generated/evidence-inject-test-b.json +47 -0
- orchestrator/fixtures/generated/evidence-inject-test-c.json +47 -0
- orchestrator/fixtures/generated/evidence-json-test-a.json +47 -0
- orchestrator/fixtures/generated/evidence-json-test-b.json +47 -0
- orchestrator/fixtures/generated/fail-report-fail-task-1.json +47 -0
- orchestrator/fixtures/generated/fail-report-json-task-1.json +47 -0
- orchestrator/fixtures/generated/fail-report-success-task-1.json +47 -0
- orchestrator/fixtures/generated/fuzz-engine-design.json +63 -0
- orchestrator/fixtures/generated/fuzz-engine-impl.json +62 -0
- orchestrator/fixtures/generated/fuzz-engine-tests.json +62 -0
- orchestrator/fixtures/generated/fuzz-engine-verify.json +62 -0
- orchestrator/fixtures/generated/goal-orch-step-1.json +63 -0
- orchestrator/fixtures/generated/goal-orch-step-2.json +62 -0
- orchestrator/fixtures/generated/goal-orch-step-3.json +62 -0
- orchestrator/fixtures/generated/goal-orch-step-4.json +62 -0
- orchestrator/fixtures/generated/goal-orch-step-5.json +62 -0
- orchestrator/fixtures/generated/goal-orch-step-6.json +63 -0
- orchestrator/fixtures/generated/implement-a-thread-safe-token-bucket-rat-task-1.json +53 -0
- orchestrator/fixtures/generated/orchestrator-checkpoint-rollback-3.json +63 -0
- orchestrator/fixtures/generated/orchestrator-checkpoint-rollback.json +62 -0
- orchestrator/fixtures/generated/orchestrator-live-telemetry-2.json +62 -0
- orchestrator/fixtures/generated/orchestrator-live-telemetry.json +62 -0
- orchestrator/fixtures/generated/orchestrator-spec-synthesis-1.json +62 -0
- orchestrator/fixtures/generated/orchestrator-spec-synthesis.json +62 -0
- orchestrator/fixtures/generated/orchestrator-test-verification-4.json +62 -0
- orchestrator/fixtures/generated/orchestrator-test-verification.json +62 -0
- orchestrator/fixtures/generated/perf-step-1.json +61 -0
- orchestrator/fixtures/generated/perf-step-2.json +62 -0
- orchestrator/fixtures/generated/perf-step-3.json +62 -0
- orchestrator/fixtures/generated/perf-step-4.json +62 -0
- orchestrator/fixtures/generated/perf-step-5.json +63 -0
- orchestrator/fixtures/generated/phase2-proof-two-step-step-1.json +47 -0
- orchestrator/fixtures/generated/phase2-proof-two-step-step-2.json +47 -0
- orchestrator/fixtures/generated/planner-spec-synthesis-impl.json +59 -0
- orchestrator/fixtures/generated/self-evolution-ast-formatter.json +69 -0
- orchestrator/fixtures/generated/self-evolution-checkpoint-rollback.json +70 -0
- orchestrator/fixtures/generated/self-evolution-spec-synthesis.json +70 -0
- orchestrator/fixtures/generated/self-evolution-step-1.json +70 -0
- orchestrator/fixtures/generated/self-evolution-step-2.json +70 -0
- orchestrator/fixtures/generated/self-evolution-step-3.json +70 -0
- orchestrator/fixtures/generated/self-evolution-step-4.json +70 -0
- orchestrator/fixtures/generated/self-evolution-step-5.json +65 -0
- orchestrator/fixtures/generated/self-evolution-telemetry.json +70 -0
- orchestrator/fixtures/generated/self-evolution-tests.json +71 -0
- orchestrator/fixtures/generated/spec-telemetry-research-design.json +64 -0
- orchestrator/fixtures/generated/spec-telemetry-step-1.json +62 -0
- orchestrator/fixtures/generated/spec-telemetry-step-2.json +62 -0
- orchestrator/fixtures/generated/spec-telemetry-step-3.json +62 -0
- orchestrator/fixtures/generated/spec-telemetry-step-4.json +62 -0
- orchestrator/fixtures/generated/spec-telemetry-step-5.json +62 -0
- orchestrator/fixtures/generated/spec-telemetry-verification.json +58 -0
- orchestrator/fixtures/generated/token-bucket-impl.json +69 -0
- orchestrator/fixtures/generated/token-bucket-step-1.json +70 -0
- orchestrator/fixtures/generated/token-bucket-step-2.json +70 -0
- orchestrator/fixtures/generated/token-bucket-step-3.json +60 -0
- orchestrator/fixtures/generated/token-bucket-tests.json +70 -0
- orchestrator/fixtures/generated/token-bucket-verify.json +61 -0
- orchestrator/fixtures/generated/trace-ux-tests-step-1.json +64 -0
- orchestrator/fixtures/generated/trace-ux-tests-step-2.json +64 -0
- orchestrator/fixtures/generated/trace-ux-tests-step-3.json +62 -0
- orchestrator/fixtures/generated/tui-live-telemetry-impl.json +59 -0
- orchestrator/fixtures/phase1_proof_escalation_contract.json +41 -0
- orchestrator/fixtures/phase1_proof_happy_path_contract.json +83 -0
- orchestrator/fixtures/phase1_proof_qc_contract.json +41 -0
- orchestrator/fixtures/phase1_proof_repair_contract.json +41 -0
- orchestrator/fixtures/phase2_proof_two_step_goal.json +15 -0
- orchestrator/fixtures/run_proofs.py +299 -0
- orchestrator/fixtures/test_normalizer.py +16 -0
- orchestrator/generator.py +239 -0
- orchestrator/goal.py +245 -0
- orchestrator/handoff.py +86 -0
- orchestrator/hybrid_worker.py +840 -0
- orchestrator/impossibility.py +162 -0
- orchestrator/limits.py +60 -0
- orchestrator/live_evolution_engine.py +247 -0
- orchestrator/llm.py +291 -0
- orchestrator/local_tool_calling.py +285 -0
- orchestrator/lock.py +404 -0
- orchestrator/mcp_client.py +571 -0
- orchestrator/mcp_server.py +344 -0
- orchestrator/memory_bridge.py +182 -0
- orchestrator/metrics.py +159 -0
- orchestrator/micro_epoch.py +42 -0
- orchestrator/models.py +350 -0
- orchestrator/parsing.py +237 -0
- orchestrator/patch_applier.py +154 -0
- orchestrator/plan_preview.py +138 -0
- orchestrator/plan_quality.py +357 -0
- orchestrator/planner.py +532 -0
- orchestrator/preferences.py +115 -0
- orchestrator/preflight.py +141 -0
- orchestrator/process_guard.py +357 -0
- orchestrator/prometheus_exporter.py +207 -0
- orchestrator/prompts.py +275 -0
- orchestrator/proposal_ledger.py +194 -0
- orchestrator/provenance.py +263 -0
- orchestrator/provider_scheduler.py +394 -0
- orchestrator/qc/__init__.py +153 -0
- orchestrator/qc/aggregator.py +330 -0
- orchestrator/qc/parsing.py +287 -0
- orchestrator/qc/personas.py +242 -0
- orchestrator/qc/runner.py +569 -0
- orchestrator/qc_overrule.py +87 -0
- orchestrator/qc_review.py +282 -0
- orchestrator/quality_lenses.py +314 -0
- orchestrator/quality_plan.py +449 -0
- orchestrator/quality_plane.py +103 -0
- orchestrator/reconcile.py +191 -0
- orchestrator/replanner.py +433 -0
- orchestrator/research.py +176 -0
- orchestrator/review_artifact.py +672 -0
- orchestrator/safety.py +271 -0
- orchestrator/schemas.py +230 -0
- orchestrator/scope.py +466 -0
- orchestrator/sensory_radar.py +79 -0
- orchestrator/skill_installer.py +140 -0
- orchestrator/sse_server.py +160 -0
- orchestrator/state.py +871 -0
- orchestrator/subprocess_helper.py +131 -0
- orchestrator/supervisor/__init__.py +184 -0
- orchestrator/supervisor/_shared.py +164 -0
- orchestrator/supervisor/cleanup.py +185 -0
- orchestrator/supervisor/core.py +1680 -0
- orchestrator/supervisor/recovery.py +367 -0
- orchestrator/supervisor/reporting.py +251 -0
- orchestrator/surgical_extractor.py +119 -0
- orchestrator/telemetry.py +61 -0
- orchestrator/templates.py +268 -0
- orchestrator/token_gate.py +245 -0
- orchestrator/tui.py +649 -0
- orchestrator/verifier.py +1103 -0
- orchestrator/webhooks.py +168 -0
- orchestrator/worker.py +469 -0
- orchestrator/worker_adapters.py +815 -0
- orchestrator/worker_pool.py +121 -0
- orchestrator/worktree.py +364 -0
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
import ast
|
|
2
|
+
from typing import Any, Dict
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
def extract_comprehensive_signature(func_node: ast.FunctionDef | ast.AsyncFunctionDef) -> Dict[str, Any]:
|
|
6
|
+
args = func_node.args
|
|
7
|
+
pos_args = [a.arg for a in args.args]
|
|
8
|
+
pos_types = [ast.unparse(a.annotation) if a.annotation else None for a in args.args]
|
|
9
|
+
kwonly_args = [a.arg for a in args.kwonlyargs]
|
|
10
|
+
kwonly_types = [ast.unparse(a.annotation) if a.annotation else None for a in args.kwonlyargs]
|
|
11
|
+
decorators = [ast.unparse(d) for d in func_node.decorator_list]
|
|
12
|
+
returns = ast.unparse(func_node.returns) if func_node.returns else None
|
|
13
|
+
|
|
14
|
+
return {
|
|
15
|
+
"pos_args": pos_args,
|
|
16
|
+
"pos_types": pos_types,
|
|
17
|
+
"kwonly_args": kwonly_args,
|
|
18
|
+
"kwonly_types": kwonly_types,
|
|
19
|
+
"num_defaults": len(args.defaults),
|
|
20
|
+
"num_kw_defaults": len([d for d in args.kw_defaults if d is not None]),
|
|
21
|
+
"has_vararg": bool(args.vararg),
|
|
22
|
+
"has_kwarg": bool(args.kwarg),
|
|
23
|
+
"decorators": decorators,
|
|
24
|
+
"returns": returns,
|
|
25
|
+
"is_async": isinstance(func_node, ast.AsyncFunctionDef),
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _find_function_node(tree: ast.AST, target_name: str) -> ast.FunctionDef | ast.AsyncFunctionDef | None:
|
|
30
|
+
"""Locates function node respecting lexical scope and preventing nested closure shadowing."""
|
|
31
|
+
parts = target_name.split(".")
|
|
32
|
+
if len(parts) == 1:
|
|
33
|
+
# Top-level module functions first (avoids mutating inner closure with same name)
|
|
34
|
+
if isinstance(tree, ast.Module):
|
|
35
|
+
for node in tree.body:
|
|
36
|
+
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) and node.name == target_name:
|
|
37
|
+
return node
|
|
38
|
+
# Fallback if tree is not a Module or function is nested
|
|
39
|
+
for node in ast.walk(tree):
|
|
40
|
+
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) and node.name == target_name:
|
|
41
|
+
return node
|
|
42
|
+
return None
|
|
43
|
+
elif len(parts) == 2:
|
|
44
|
+
class_name, func_name = parts
|
|
45
|
+
for node in ast.walk(tree):
|
|
46
|
+
if isinstance(node, ast.ClassDef) and node.name == class_name:
|
|
47
|
+
for member in node.body:
|
|
48
|
+
if isinstance(member, (ast.FunctionDef, ast.AsyncFunctionDef)) and member.name == func_name:
|
|
49
|
+
return member
|
|
50
|
+
return None
|
|
51
|
+
else:
|
|
52
|
+
curr_nodes = [tree]
|
|
53
|
+
for part in parts[:-1]:
|
|
54
|
+
next_nodes = []
|
|
55
|
+
for parent in curr_nodes:
|
|
56
|
+
for child in getattr(parent, "body", []):
|
|
57
|
+
if isinstance(child, (ast.ClassDef, ast.FunctionDef, ast.AsyncFunctionDef)) and child.name == part:
|
|
58
|
+
next_nodes.append(child)
|
|
59
|
+
curr_nodes = next_nodes
|
|
60
|
+
for parent in curr_nodes:
|
|
61
|
+
for child in getattr(parent, "body", []):
|
|
62
|
+
if isinstance(child, (ast.FunctionDef, ast.AsyncFunctionDef)) and child.name == parts[-1]:
|
|
63
|
+
return child
|
|
64
|
+
return None
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def splice_ast_function(
|
|
68
|
+
source_code: str, target_name: str, replacement_code: str, enforce_strict_signature: bool = True
|
|
69
|
+
) -> str:
|
|
70
|
+
source_tree = ast.parse(source_code)
|
|
71
|
+
replacement_tree = ast.parse(replacement_code)
|
|
72
|
+
|
|
73
|
+
# 1. Locate replacement node
|
|
74
|
+
rep_node = _find_function_node(replacement_tree, target_name)
|
|
75
|
+
if not rep_node:
|
|
76
|
+
# Fallback to simple name if target_name was qualified
|
|
77
|
+
simple_name = target_name.split(".")[-1]
|
|
78
|
+
rep_node = _find_function_node(replacement_tree, simple_name)
|
|
79
|
+
|
|
80
|
+
if not rep_node:
|
|
81
|
+
raise ValueError(f"Replacement code does not contain function definition for '{target_name}'")
|
|
82
|
+
|
|
83
|
+
# 2. Locate original node
|
|
84
|
+
orig_node = _find_function_node(source_tree, target_name)
|
|
85
|
+
|
|
86
|
+
if not orig_node:
|
|
87
|
+
raise ValueError(f"Target function '{target_name}' was not found in source AST.")
|
|
88
|
+
|
|
89
|
+
# 3. Validate signature invariance
|
|
90
|
+
if enforce_strict_signature:
|
|
91
|
+
orig_sig = extract_comprehensive_signature(orig_node)
|
|
92
|
+
rep_sig = extract_comprehensive_signature(rep_node)
|
|
93
|
+
if orig_sig != rep_sig:
|
|
94
|
+
raise ValueError(f"Signature drift detected for '{target_name}': expected {orig_sig}, got {rep_sig}")
|
|
95
|
+
|
|
96
|
+
# 4. Calculate source span including decorator stack
|
|
97
|
+
if orig_node.decorator_list:
|
|
98
|
+
start_lineno = min([d.lineno for d in orig_node.decorator_list])
|
|
99
|
+
else:
|
|
100
|
+
start_lineno = orig_node.lineno
|
|
101
|
+
|
|
102
|
+
source_lines = source_code.splitlines(keepends=True)
|
|
103
|
+
start_line = start_lineno - 1
|
|
104
|
+
end_line = orig_node.end_lineno
|
|
105
|
+
|
|
106
|
+
# Calculate original indentation prefix
|
|
107
|
+
orig_start_line = source_lines[start_line]
|
|
108
|
+
indent_len = len(orig_start_line) - len(orig_start_line.lstrip())
|
|
109
|
+
indent_prefix = orig_start_line[:indent_len]
|
|
110
|
+
|
|
111
|
+
# Format replacement code with matching base indentation
|
|
112
|
+
rep_lines = replacement_code.strip().splitlines()
|
|
113
|
+
if rep_lines:
|
|
114
|
+
rep_base_indent = len(rep_lines[0]) - len(rep_lines[0].lstrip())
|
|
115
|
+
formatted_lines = []
|
|
116
|
+
for line in rep_lines:
|
|
117
|
+
if line.strip():
|
|
118
|
+
# If replacement line is less indented than base, align it
|
|
119
|
+
stripped = line[rep_base_indent:] if line.startswith(" " * rep_base_indent) else line.lstrip()
|
|
120
|
+
formatted_lines.append(indent_prefix + stripped + "\n")
|
|
121
|
+
else:
|
|
122
|
+
formatted_lines.append("\n")
|
|
123
|
+
rep_formatted = "".join(formatted_lines)
|
|
124
|
+
else:
|
|
125
|
+
rep_formatted = "\n"
|
|
126
|
+
|
|
127
|
+
before = source_lines[:start_line]
|
|
128
|
+
after = source_lines[end_line:]
|
|
129
|
+
|
|
130
|
+
return "".join(before) + rep_formatted + "".join(after)
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
"""
|
|
2
|
+
orchestrator/ast_splicer.py
|
|
3
|
+
AST Signature, Decorator, and Invariant Validator (Pure In-Memory Checker).
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import ast
|
|
9
|
+
from dataclasses import dataclass
|
|
10
|
+
from typing import List, Optional
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
@dataclass
|
|
14
|
+
class InvariantValidationResult:
|
|
15
|
+
valid: bool
|
|
16
|
+
violations: List[str]
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class ASTInvariantValidator:
|
|
20
|
+
"""Validates structural invariants between original and candidate AST nodes."""
|
|
21
|
+
|
|
22
|
+
@classmethod
|
|
23
|
+
def validate(cls, original_code: str, modified_code: str, target_symbol: str) -> InvariantValidationResult:
|
|
24
|
+
violations = []
|
|
25
|
+
|
|
26
|
+
try:
|
|
27
|
+
orig_tree = ast.parse(original_code)
|
|
28
|
+
except SyntaxError as e:
|
|
29
|
+
return InvariantValidationResult(valid=False, violations=[f"Original code syntax error: {e}"])
|
|
30
|
+
|
|
31
|
+
try:
|
|
32
|
+
mod_tree = ast.parse(modified_code)
|
|
33
|
+
except SyntaxError as e:
|
|
34
|
+
return InvariantValidationResult(valid=False, violations=[f"Modified code syntax error: {e}"])
|
|
35
|
+
|
|
36
|
+
orig_node = cls._find_func(orig_tree, target_symbol)
|
|
37
|
+
mod_node = cls._find_func(mod_tree, target_symbol)
|
|
38
|
+
|
|
39
|
+
if not orig_node:
|
|
40
|
+
return InvariantValidationResult(
|
|
41
|
+
valid=False, violations=[f"Target '{target_symbol}' not found in original."]
|
|
42
|
+
)
|
|
43
|
+
if not mod_node:
|
|
44
|
+
return InvariantValidationResult(
|
|
45
|
+
valid=False, violations=[f"Target '{target_symbol}' deleted or missing in patch."]
|
|
46
|
+
)
|
|
47
|
+
|
|
48
|
+
# 1. Coroutine Type Invariance
|
|
49
|
+
if isinstance(orig_node, ast.AsyncFunctionDef) != isinstance(mod_node, ast.AsyncFunctionDef):
|
|
50
|
+
violations.append(f"Coroutine mismatch: {target_symbol} changed between async/sync.")
|
|
51
|
+
|
|
52
|
+
# 2. Parameter Signature Invariance (Positional, Keyword-Only, VarArgs)
|
|
53
|
+
orig_args = orig_node.args
|
|
54
|
+
mod_args = mod_node.args
|
|
55
|
+
|
|
56
|
+
orig_pos = [a.arg for a in getattr(orig_args, "posonlyargs", [])] + [a.arg for a in orig_args.args]
|
|
57
|
+
mod_pos = [a.arg for a in getattr(mod_args, "posonlyargs", [])] + [a.arg for a in mod_args.args]
|
|
58
|
+
if orig_pos != mod_pos:
|
|
59
|
+
violations.append(f"Positional parameters altered: expected {orig_pos}, got {mod_pos}.")
|
|
60
|
+
|
|
61
|
+
orig_kwonly = [a.arg for a in orig_args.kwonlyargs]
|
|
62
|
+
mod_kwonly = [a.arg for a in mod_args.kwonlyargs]
|
|
63
|
+
if orig_kwonly != mod_kwonly:
|
|
64
|
+
violations.append(f"Keyword-only parameters altered: expected {orig_kwonly}, got {mod_kwonly}.")
|
|
65
|
+
|
|
66
|
+
if bool(orig_args.vararg) != bool(mod_args.vararg):
|
|
67
|
+
violations.append(f"*args signature altered on {target_symbol}.")
|
|
68
|
+
if bool(orig_args.kwarg) != bool(mod_args.kwarg):
|
|
69
|
+
violations.append(f"**kwargs signature altered on {target_symbol}.")
|
|
70
|
+
|
|
71
|
+
# 3. Decorator Stack Invariance
|
|
72
|
+
orig_decs = [cls._get_decorator_name(d) for d in orig_node.decorator_list]
|
|
73
|
+
mod_decs = [cls._get_decorator_name(d) for d in mod_node.decorator_list]
|
|
74
|
+
if orig_decs != mod_decs:
|
|
75
|
+
violations.append(f"Decorator stack stripped or altered: expected {orig_decs}, got {mod_decs}.")
|
|
76
|
+
|
|
77
|
+
return InvariantValidationResult(valid=len(violations) == 0, violations=violations)
|
|
78
|
+
|
|
79
|
+
@classmethod
|
|
80
|
+
def _find_func(cls, tree: ast.AST, name: str) -> Optional[ast.AST]:
|
|
81
|
+
for node in ast.walk(tree):
|
|
82
|
+
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) and node.name == name:
|
|
83
|
+
return node
|
|
84
|
+
return None
|
|
85
|
+
|
|
86
|
+
@classmethod
|
|
87
|
+
def _get_decorator_name(cls, dec: ast.AST) -> str:
|
|
88
|
+
if isinstance(dec, ast.Name):
|
|
89
|
+
return dec.id
|
|
90
|
+
if isinstance(dec, ast.Attribute):
|
|
91
|
+
return dec.attr
|
|
92
|
+
if isinstance(dec, ast.Call):
|
|
93
|
+
return cls._get_decorator_name(dec.func)
|
|
94
|
+
return ast.dump(dec)
|
orchestrator/audit.py
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
"""Immutable append-only audit log for operator actions."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import os
|
|
5
|
+
from datetime import datetime, timezone
|
|
6
|
+
from typing import Any, Dict, List, Optional
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def _log_path(run_dir: str) -> str:
|
|
10
|
+
return os.path.join(run_dir, "audit.jsonl")
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def record_action(
|
|
14
|
+
run_dir: str,
|
|
15
|
+
action_type: str,
|
|
16
|
+
goal_id: str = "",
|
|
17
|
+
task_id: str = "",
|
|
18
|
+
actor: str = "operator",
|
|
19
|
+
details: Optional[Dict[str, Any]] = None,
|
|
20
|
+
) -> None:
|
|
21
|
+
"""Append an immutable audit entry to the JSONL log."""
|
|
22
|
+
entry = {
|
|
23
|
+
"timestamp": datetime.now(timezone.utc).isoformat(),
|
|
24
|
+
"action_type": action_type,
|
|
25
|
+
"goal_id": goal_id,
|
|
26
|
+
"task_id": task_id,
|
|
27
|
+
"actor": actor,
|
|
28
|
+
"details": details or {},
|
|
29
|
+
}
|
|
30
|
+
os.makedirs(run_dir, exist_ok=True)
|
|
31
|
+
path = _log_path(run_dir)
|
|
32
|
+
with open(path, "a", encoding="utf-8") as f:
|
|
33
|
+
f.write(json.dumps(entry, ensure_ascii=False) + "\n")
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def load_audit_log(run_dir: str) -> List[Dict[str, Any]]:
|
|
37
|
+
"""Load all audit entries from the log."""
|
|
38
|
+
path = _log_path(run_dir)
|
|
39
|
+
if not os.path.isfile(path):
|
|
40
|
+
return []
|
|
41
|
+
entries = []
|
|
42
|
+
with open(path, "r", encoding="utf-8") as f:
|
|
43
|
+
for line in f:
|
|
44
|
+
line = line.strip()
|
|
45
|
+
if line:
|
|
46
|
+
try:
|
|
47
|
+
entries.append(json.loads(line))
|
|
48
|
+
except json.JSONDecodeError:
|
|
49
|
+
pass
|
|
50
|
+
return entries
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def query_audit(
|
|
54
|
+
run_dir: str,
|
|
55
|
+
goal_id: Optional[str] = None,
|
|
56
|
+
action_type: Optional[str] = None,
|
|
57
|
+
task_id: Optional[str] = None,
|
|
58
|
+
) -> List[Dict[str, Any]]:
|
|
59
|
+
"""Filter audit log by goal_id, action_type, or task_id."""
|
|
60
|
+
entries = load_audit_log(run_dir)
|
|
61
|
+
if goal_id:
|
|
62
|
+
entries = [e for e in entries if e.get("goal_id") == goal_id]
|
|
63
|
+
if action_type:
|
|
64
|
+
entries = [e for e in entries if e.get("action_type") == action_type]
|
|
65
|
+
if task_id:
|
|
66
|
+
entries = [e for e in entries if e.get("task_id") == task_id]
|
|
67
|
+
return entries
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def format_audit_entries(entries: List[Dict[str, Any]]) -> str:
|
|
71
|
+
"""Return a human-readable summary of audit entries."""
|
|
72
|
+
if not entries:
|
|
73
|
+
return "No audit entries."
|
|
74
|
+
lines = [f"Audit log: {len(entries)} entries"]
|
|
75
|
+
for e in entries:
|
|
76
|
+
ts = e.get("timestamp", "?")[11:19]
|
|
77
|
+
at = e.get("action_type", "?")
|
|
78
|
+
gid = e.get("goal_id", "")
|
|
79
|
+
tid = e.get("task_id", "")
|
|
80
|
+
det = e.get("details", {})
|
|
81
|
+
detail_str = ""
|
|
82
|
+
if det:
|
|
83
|
+
detail_str = f" — {det}"
|
|
84
|
+
target = f"goal={gid}" if gid else ""
|
|
85
|
+
if tid:
|
|
86
|
+
target += f" task={tid}" if target else f"task={tid}"
|
|
87
|
+
lines.append(f" [{ts}] {at} {target}{detail_str}")
|
|
88
|
+
return "\n".join(lines)
|
orchestrator/budget.py
ADDED
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
"""Budget enforcement and loop detection for hybrid worker inner loop.
|
|
2
|
+
|
|
3
|
+
Provides:
|
|
4
|
+
- UsageLedger for tracking token/cost per LLM call
|
|
5
|
+
- BudgetGuard for pre-flight checks against hard caps
|
|
6
|
+
- LoopDetector for stuck/oscillation detection
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import hashlib
|
|
12
|
+
from dataclasses import dataclass, field
|
|
13
|
+
from typing import Dict, List, Optional
|
|
14
|
+
|
|
15
|
+
DEFAULT_ESTIMATED_INPUT_USD_PER_M = 0.15
|
|
16
|
+
DEFAULT_ESTIMATED_OUTPUT_USD_PER_M = 0.60
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
@dataclass
|
|
20
|
+
class UsageRecord:
|
|
21
|
+
role: str
|
|
22
|
+
model: str
|
|
23
|
+
prompt_tokens: int
|
|
24
|
+
completion_tokens: int
|
|
25
|
+
estimated_cost_usd: float
|
|
26
|
+
|
|
27
|
+
def to_dict(self) -> Dict:
|
|
28
|
+
return {
|
|
29
|
+
"role": self.role,
|
|
30
|
+
"model": self.model,
|
|
31
|
+
"prompt_tokens": self.prompt_tokens,
|
|
32
|
+
"completion_tokens": self.completion_tokens,
|
|
33
|
+
"estimated_cost_usd": self.estimated_cost_usd,
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
@dataclass
|
|
38
|
+
class UsageLedger:
|
|
39
|
+
records: List[UsageRecord] = field(default_factory=list)
|
|
40
|
+
|
|
41
|
+
@property
|
|
42
|
+
def total_prompt_tokens(self) -> int:
|
|
43
|
+
return sum(r.prompt_tokens for r in self.records)
|
|
44
|
+
|
|
45
|
+
@property
|
|
46
|
+
def total_completion_tokens(self) -> int:
|
|
47
|
+
return sum(r.completion_tokens for r in self.records)
|
|
48
|
+
|
|
49
|
+
@property
|
|
50
|
+
def total_tokens(self) -> int:
|
|
51
|
+
return self.total_prompt_tokens + self.total_completion_tokens
|
|
52
|
+
|
|
53
|
+
@property
|
|
54
|
+
def total_cost_usd(self) -> float:
|
|
55
|
+
return sum(r.estimated_cost_usd for r in self.records)
|
|
56
|
+
|
|
57
|
+
@property
|
|
58
|
+
def call_count(self) -> int:
|
|
59
|
+
return len(self.records)
|
|
60
|
+
|
|
61
|
+
def record(self, role: str, model: str, prompt_tokens: int, completion_tokens: int) -> None:
|
|
62
|
+
estimated_cost = (prompt_tokens / 1_000_000) * DEFAULT_ESTIMATED_INPUT_USD_PER_M + (
|
|
63
|
+
completion_tokens / 1_000_000
|
|
64
|
+
) * DEFAULT_ESTIMATED_OUTPUT_USD_PER_M
|
|
65
|
+
self.records.append(
|
|
66
|
+
UsageRecord(
|
|
67
|
+
role=role,
|
|
68
|
+
model=model,
|
|
69
|
+
prompt_tokens=prompt_tokens,
|
|
70
|
+
completion_tokens=completion_tokens,
|
|
71
|
+
estimated_cost_usd=estimated_cost,
|
|
72
|
+
)
|
|
73
|
+
)
|
|
74
|
+
|
|
75
|
+
def estimate_cost(
|
|
76
|
+
self,
|
|
77
|
+
prompt_tokens: int,
|
|
78
|
+
completion_tokens: int,
|
|
79
|
+
) -> float:
|
|
80
|
+
return (prompt_tokens / 1_000_000) * DEFAULT_ESTIMATED_INPUT_USD_PER_M + (
|
|
81
|
+
completion_tokens / 1_000_000
|
|
82
|
+
) * DEFAULT_ESTIMATED_OUTPUT_USD_PER_M
|
|
83
|
+
|
|
84
|
+
def to_dict(self) -> Dict:
|
|
85
|
+
return {
|
|
86
|
+
"records": [r.to_dict() for r in self.records],
|
|
87
|
+
"total_prompt_tokens": self.total_prompt_tokens,
|
|
88
|
+
"total_completion_tokens": self.total_completion_tokens,
|
|
89
|
+
"total_tokens": self.total_tokens,
|
|
90
|
+
"total_cost_usd": self.total_cost_usd,
|
|
91
|
+
"call_count": self.call_count,
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
class BudgetExhaustedError(Exception):
|
|
96
|
+
pass
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
@dataclass
|
|
100
|
+
class BudgetGuard:
|
|
101
|
+
max_tokens: int = 100_000
|
|
102
|
+
max_cost_usd: float = 0.50
|
|
103
|
+
ledger: UsageLedger = field(default_factory=UsageLedger)
|
|
104
|
+
|
|
105
|
+
def check_before_call(
|
|
106
|
+
self,
|
|
107
|
+
estimated_prompt_tokens: int = 10_000,
|
|
108
|
+
estimated_completion_tokens: int = 2_000,
|
|
109
|
+
) -> None:
|
|
110
|
+
if self.ledger.total_cost_usd >= self.max_cost_usd:
|
|
111
|
+
raise BudgetExhaustedError(f"cost ceiling ${self.ledger.total_cost_usd:.4f} >= ${self.max_cost_usd:.2f}")
|
|
112
|
+
if self.ledger.total_tokens + estimated_prompt_tokens + estimated_completion_tokens > self.max_tokens:
|
|
113
|
+
raise BudgetExhaustedError(
|
|
114
|
+
f"token budget would exceed: {self.ledger.total_tokens} + "
|
|
115
|
+
f"{estimated_prompt_tokens + estimated_completion_tokens} > {self.max_tokens}"
|
|
116
|
+
)
|
|
117
|
+
new_cost = self.ledger.total_cost_usd + self.ledger.estimate_cost(
|
|
118
|
+
estimated_prompt_tokens,
|
|
119
|
+
estimated_completion_tokens,
|
|
120
|
+
)
|
|
121
|
+
if new_cost > self.max_cost_usd:
|
|
122
|
+
raise BudgetExhaustedError(f"projected cost ${new_cost:.4f} would exceed ceiling ${self.max_cost_usd:.2f}")
|
|
123
|
+
|
|
124
|
+
def remaining_pct(self) -> float:
|
|
125
|
+
cost_ratio = self.ledger.total_cost_usd / self.max_cost_usd if self.max_cost_usd > 0 else 1.0
|
|
126
|
+
token_ratio = self.ledger.total_tokens / self.max_tokens if self.max_tokens > 0 else 1.0
|
|
127
|
+
consumed = max(cost_ratio, token_ratio)
|
|
128
|
+
return max(0.0, 1.0 - consumed)
|
|
129
|
+
|
|
130
|
+
def to_dict(self) -> Dict:
|
|
131
|
+
return {
|
|
132
|
+
"max_tokens": self.max_tokens,
|
|
133
|
+
"max_cost_usd": self.max_cost_usd,
|
|
134
|
+
"ledger": self.ledger.to_dict(),
|
|
135
|
+
"remaining_pct": self.remaining_pct(),
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
class LoopDetector:
|
|
140
|
+
"""Detect stuck/oscillation patterns in the inner loop.
|
|
141
|
+
|
|
142
|
+
Detects:
|
|
143
|
+
1. Repeated identical output hashes (same artifact content)
|
|
144
|
+
2. Repeated identical failure reasons
|
|
145
|
+
3. Repeated identical critic verdicts
|
|
146
|
+
"""
|
|
147
|
+
|
|
148
|
+
def __init__(
|
|
149
|
+
self,
|
|
150
|
+
max_identical_outputs: int = 2,
|
|
151
|
+
max_identical_failures: int = 2,
|
|
152
|
+
max_identical_verdicts: int = 2,
|
|
153
|
+
):
|
|
154
|
+
self.max_identical_outputs = max_identical_outputs
|
|
155
|
+
self.max_identical_failures = max_identical_failures
|
|
156
|
+
self.max_identical_verdicts = max_identical_verdicts
|
|
157
|
+
self.output_hashes: List[str] = []
|
|
158
|
+
self.failure_reasons: List[str] = []
|
|
159
|
+
self.critic_verdicts: List[str] = []
|
|
160
|
+
|
|
161
|
+
def _hash_content(self, content: str) -> str:
|
|
162
|
+
return hashlib.sha256(content.encode()).hexdigest()[:16]
|
|
163
|
+
|
|
164
|
+
def record_outputs(self, contents: List[str]) -> Optional[str]:
|
|
165
|
+
combined = "|".join(sorted(contents))
|
|
166
|
+
h = self._hash_content(combined)
|
|
167
|
+
self.output_hashes.append(h)
|
|
168
|
+
if len(self.output_hashes) >= self.max_identical_outputs:
|
|
169
|
+
recent = self.output_hashes[-self.max_identical_outputs :]
|
|
170
|
+
if len(set(recent)) == 1:
|
|
171
|
+
return "identical output repeated"
|
|
172
|
+
return None
|
|
173
|
+
|
|
174
|
+
def record_failure(self, reason: str) -> Optional[str]:
|
|
175
|
+
self.failure_reasons.append(reason)
|
|
176
|
+
if len(self.failure_reasons) >= self.max_identical_failures:
|
|
177
|
+
recent = self.failure_reasons[-self.max_identical_failures :]
|
|
178
|
+
if len(set(recent)) == 1:
|
|
179
|
+
return "identical failure repeated"
|
|
180
|
+
return None
|
|
181
|
+
|
|
182
|
+
def record_critic_verdict(self, verdict: str) -> Optional[str]:
|
|
183
|
+
self.critic_verdicts.append(verdict)
|
|
184
|
+
if len(self.critic_verdicts) >= self.max_identical_verdicts:
|
|
185
|
+
recent = self.critic_verdicts[-self.max_identical_verdicts :]
|
|
186
|
+
if len(set(recent)) == 1:
|
|
187
|
+
return "identical critic verdict repeated"
|
|
188
|
+
return None
|
|
189
|
+
|
|
190
|
+
def to_dict(self) -> Dict:
|
|
191
|
+
return {
|
|
192
|
+
"output_hashes": list(self.output_hashes),
|
|
193
|
+
"failure_reasons": list(self.failure_reasons),
|
|
194
|
+
"critic_verdicts": list(self.critic_verdicts),
|
|
195
|
+
}
|