-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathneuron-loop.py
More file actions
1916 lines (1615 loc) · 79.6 KB
/
neuron-loop.py
File metadata and controls
1916 lines (1615 loc) · 79.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
Neuron-Loop: Coding ↔ Review ↔ Test Loop Orchestrator
A multi-model code review and fix pipeline that:
1. Runs tests (if configured)
2. Sends code to multiple reviewer models in parallel
3. Triages findings using gate rules
4. Sends actionable findings to a coder model for fixes
5. Loops until convergence (no more findings) or max iterations
Usage:
python3 neuron-loop.py --task TASK.md --files script.lua [script2.py ...]
python3 neuron-loop.py --task TASK.md --files script.lua --config config.yaml
python3 neuron-loop.py --task TASK.md --files script.lua --test "bash run_tests.sh"
"""
import argparse
import json
import os
import sys
import time
import hashlib
import subprocess
import re
import logging
import copy
from pathlib import Path
from datetime import datetime, timezone
from concurrent.futures import ThreadPoolExecutor, as_completed
# ─── Constants ──────────────────────────────────────────────
SCRIPT_DIR = Path(__file__).parent
DEFAULT_CONFIG = SCRIPT_DIR / "config.yaml"
OPENCLAW_MODELS = Path.home() / ".openclaw/agents/main/agent/models.json"
VERSION = "0.6.0"
# ─── Pricing (per million tokens) ──────────────────────────
# Source: provider pricing pages as of 2026-03.
# Models not listed here are treated as $0 (local/free).
MODEL_PRICING = {
# Anthropic
"claude-opus-4-6": {"input": 15.0, "output": 75.0},
"claude-opus-4-5": {"input": 15.0, "output": 75.0},
"claude-sonnet-4-6": {"input": 3.0, "output": 15.0},
"claude-sonnet-4-5": {"input": 3.0, "output": 15.0},
# OpenAI
"gpt-5.4": {"input": 2.50, "output": 10.0},
"gpt-5-mini": {"input": 0.40, "output": 1.60},
# Free/local
"glm-5:cloud": {"input": 0.0, "output": 0.0},
}
# ─── Logging Setup ──────────────────────────────────────────
import urllib.request
import urllib.error
import ssl
class CostTracker:
"""Track token usage and estimated costs per iteration and role."""
def __init__(self):
self.iterations = {} # iter_num → {role → {model, input_tokens, output_tokens, calls, cost}}
self.totals = {} # model → {input_tokens, output_tokens, calls, cost}
def _get_pricing(self, model):
"""Look up pricing for a model name (tries exact match then suffix)."""
if model in MODEL_PRICING:
return MODEL_PRICING[model]
# Try matching just the model name (strip provider prefix)
base = model.split("/")[-1] if "/" in model else model
if base in MODEL_PRICING:
return MODEL_PRICING[base]
return {"input": 0.0, "output": 0.0}
def record(self, iteration, role, model, usage):
"""Record token usage for one API call.
Args:
iteration: iteration number
role: "reviewer", "coder", or "verifier"
model: model name string
usage: dict with input/output token counts
"""
if not usage:
return
# Normalize token keys (Anthropic uses input_tokens, OpenAI uses prompt_tokens)
inp = usage.get("input_tokens", usage.get("prompt_tokens", 0)) or 0
out = usage.get("output_tokens", usage.get("completion_tokens", 0)) or 0
pricing = self._get_pricing(model)
cost = (inp * pricing["input"] + out * pricing["output"]) / 1_000_000
# Per-iteration tracking
if iteration not in self.iterations:
self.iterations[iteration] = {}
key = f"{role}/{model}"
if key not in self.iterations[iteration]:
self.iterations[iteration][key] = {
"role": role, "model": model,
"input_tokens": 0, "output_tokens": 0, "calls": 0, "cost": 0.0
}
entry = self.iterations[iteration][key]
entry["input_tokens"] += inp
entry["output_tokens"] += out
entry["calls"] += 1
entry["cost"] += cost
# Global totals
if model not in self.totals:
self.totals[model] = {"input_tokens": 0, "output_tokens": 0, "calls": 0, "cost": 0.0}
t = self.totals[model]
t["input_tokens"] += inp
t["output_tokens"] += out
t["calls"] += 1
t["cost"] += cost
def iteration_cost(self, iteration):
"""Get total cost for one iteration."""
if iteration not in self.iterations:
return 0.0
return sum(e["cost"] for e in self.iterations[iteration].values())
def total_cost(self):
"""Get total cost across all iterations."""
return sum(t["cost"] for t in self.totals.values())
def total_tokens(self):
"""Get total input + output tokens."""
return sum(t["input_tokens"] + t["output_tokens"] for t in self.totals.values())
def summary_dict(self):
"""Return a serializable summary for events/JSON."""
return {
"total_cost_usd": round(self.total_cost(), 4),
"total_input_tokens": sum(t["input_tokens"] for t in self.totals.values()),
"total_output_tokens": sum(t["output_tokens"] for t in self.totals.values()),
"per_iteration": {
str(it): {
"cost_usd": round(sum(e["cost"] for e in entries.values()), 4),
"input_tokens": sum(e["input_tokens"] for e in entries.values()),
"output_tokens": sum(e["output_tokens"] for e in entries.values()),
"calls": sum(e["calls"] for e in entries.values()),
}
for it, entries in sorted(self.iterations.items())
},
"per_model": {
model: {
"input_tokens": t["input_tokens"],
"output_tokens": t["output_tokens"],
"calls": t["calls"],
"cost_usd": round(t["cost"], 4),
}
for model, t in sorted(self.totals.items())
},
}
def print_summary(self):
"""Print a human-readable cost summary."""
if not self.totals:
return
print(f"\n Token Usage & Cost:")
print(f" {'Model':<30s} {'Input':>10s} {'Output':>10s} {'Calls':>6s} {'Cost':>10s}")
print(f" {'─'*30} {'─'*10} {'─'*10} {'─'*6} {'─'*10}")
for model, t in sorted(self.totals.items(), key=lambda x: -x[1]["cost"]):
cost_str = f"${t['cost']:.4f}" if t["cost"] > 0 else "free"
print(f" {model:<30s} {t['input_tokens']:>10,} {t['output_tokens']:>10,} "
f"{t['calls']:>6} {cost_str:>10s}")
total = self.total_cost()
total_in = sum(t["input_tokens"] for t in self.totals.values())
total_out = sum(t["output_tokens"] for t in self.totals.values())
total_calls = sum(t["calls"] for t in self.totals.values())
print(f" {'─'*30} {'─'*10} {'─'*10} {'─'*6} {'─'*10}")
print(f" {'TOTAL':<30s} {total_in:>10,} {total_out:>10,} "
f"{total_calls:>6} {'$'+f'{total:.4f}':>10s}")
if len(self.iterations) > 1:
print(f"\n Per-Iteration Cost:")
for it in sorted(self.iterations.keys()):
ic = self.iteration_cost(it)
it_calls = sum(e["calls"] for e in self.iterations[it].values())
print(f" Iteration {it}: ${ic:.4f} ({it_calls} calls)")
class StructuredLogger:
"""Structured logging with both human-readable console and JSON file output."""
def __init__(self, run_dir, verbose=True):
self.run_dir = Path(run_dir)
self.run_dir.mkdir(parents=True, exist_ok=True)
self.verbose = verbose
# JSON event log — every structured event
self.events_path = self.run_dir / "events.jsonl"
self.events_file = open(self.events_path, "a")
# Human-readable log
self.log_path = self.run_dir / "neuron-loop.log"
self.log_file = open(self.log_path, "a")
self._event_id = 0
def _ts(self):
return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
def _write_event(self, event_type, data):
self._event_id += 1
event = {
"id": self._event_id,
"ts": self._ts(),
"type": event_type,
**data,
}
self.events_file.write(json.dumps(event, default=str) + "\n")
self.events_file.flush()
return event
def _write_log(self, level, msg):
ts = self._ts()
line = f"[{ts}] [{level}] {msg}"
self.log_file.write(line + "\n")
self.log_file.flush()
if self.verbose:
print(line)
def info(self, msg, **data):
self._write_log("INFO", msg)
if data:
self._write_event("info", {"message": msg, **data})
def warn(self, msg, **data):
self._write_log("WARN", msg)
self._write_event("warning", {"message": msg, **data})
def error(self, msg, **data):
self._write_log("ERROR", msg)
self._write_event("error", {"message": msg, **data})
def event(self, event_type, **data):
self._write_event(event_type, data)
def close(self):
self.events_file.close()
self.log_file.close()
# ─── Run Directory Structure ────────────────────────────────
class RunStorage:
"""Manages structured storage for a single Neuron-Loop run.
Directory layout:
runs/
YYYY-MM-DD_HHMMSS_{task_name}/
config.json — frozen config snapshot (no secrets)
task.md — copy of task prompt
events.jsonl — structured event log
neuron-loop.log — human-readable log
summary.json — final summary
files/
original/ — original file snapshots
iter-01/ — files after iteration 1 fixes
iter-02/ — ...
reviews/
iter-01/
sonnet-raw.md — raw response
sonnet-findings.json — extracted findings
gpt54-raw.md
gpt54-findings.json
iter-02/
...
triage/
iter-01.json — triaged/deduplicated findings
fixes/
iter-01-request.md — prompt sent to coder
iter-01-response.md — raw coder response
tests/
iter-01-pre.txt — pre-review test output
iter-01-post.txt — post-fix test output
"""
def __init__(self, base_dir, task_name):
ts = datetime.now().strftime("%Y-%m-%d_%H%M%S")
safe_name = re.sub(r'[^\w-]', '_', task_name)[:40]
self.run_dir = Path(base_dir) / f"{ts}_{safe_name}"
self.run_dir.mkdir(parents=True, exist_ok=True)
# Sub-directories
for subdir in ["files/original", "reviews", "triage", "fixes", "tests"]:
(self.run_dir / subdir).mkdir(parents=True, exist_ok=True)
def save_config(self, config):
"""Save config snapshot (strip any accidentally included secrets)."""
safe = copy.deepcopy(config)
# Remove anything that looks like a key
for key in list(safe.keys()):
if "key" in key.lower() or "secret" in key.lower() or "token" in key.lower():
safe[key] = "***REDACTED***"
(self.run_dir / "config.json").write_text(json.dumps(safe, indent=2, default=str))
def save_task(self, task_text):
(self.run_dir / "task.md").write_text(task_text)
def save_original_file(self, filename, content):
(self.run_dir / "files" / "original" / filename).write_text(content)
def save_iteration_file(self, iteration, filename, content):
iter_dir = self.run_dir / "files" / f"iter-{iteration:02d}"
iter_dir.mkdir(parents=True, exist_ok=True)
(iter_dir / filename).write_text(content)
def save_review(self, iteration, label, raw_response, findings):
review_dir = self.run_dir / "reviews" / f"iter-{iteration:02d}"
review_dir.mkdir(parents=True, exist_ok=True)
(review_dir / f"{label}-raw.md").write_text(raw_response or "(no response)")
(review_dir / f"{label}-findings.json").write_text(
json.dumps(findings, indent=2, default=str)
)
def save_triage(self, iteration, triaged):
(self.run_dir / "triage" / f"iter-{iteration:02d}.json").write_text(
json.dumps(triaged, indent=2, default=str)
)
def save_fix_request(self, iteration, prompt):
(self.run_dir / "fixes" / f"iter-{iteration:02d}-request.md").write_text(prompt)
def save_fix_response(self, iteration, response):
(self.run_dir / "fixes" / f"iter-{iteration:02d}-response.md").write_text(
response or "(no response)"
)
def save_test_output(self, iteration, phase, success, output):
(self.run_dir / "tests" / f"iter-{iteration:02d}-{phase}.txt").write_text(
f"# Result: {'PASS' if success else 'FAIL'}\n\n{output}"
)
def save_summary(self, summary):
(self.run_dir / "summary.json").write_text(json.dumps(summary, indent=2, default=str))
def save_checkpoint(self, iteration, files_content, model_stats, addressed_fingerprints,
last_good_files):
"""Save checkpoint state for resume capability."""
checkpoint = {
"version": VERSION,
"iteration": iteration,
"files_content": files_content,
"last_good_files": last_good_files,
"model_stats": {k: {kk: vv for kk, vv in v.items() if not kk.startswith("_")}
for k, v in model_stats.items()},
"addressed_fingerprints": list(addressed_fingerprints),
"saved_at": datetime.now(timezone.utc).isoformat(),
}
(self.run_dir / "checkpoint.json").write_text(
json.dumps(checkpoint, indent=2, default=str))
@staticmethod
def load_checkpoint(run_dir):
"""Load checkpoint from a previous run directory."""
cp_path = Path(run_dir) / "checkpoint.json"
if not cp_path.exists():
return None
return json.loads(cp_path.read_text())
# ─── Provider API Clients ──────────────────────────────────
def load_openclaw_providers():
"""Load provider configs from OpenClaw's models.json."""
if not OPENCLAW_MODELS.exists():
print("[ERROR] Cannot find OpenClaw models.json at", OPENCLAW_MODELS)
sys.exit(1)
with open(OPENCLAW_MODELS) as f:
data = json.load(f)
return data.get("providers", {})
def api_call_openai_compat(base_url, api_key, model, messages, max_tokens=8192, timeout=300):
"""Call an OpenAI-compatible API (OpenAI, xAI, Ollama Cloud, OpenRouter)."""
url = f"{base_url.rstrip('/')}/chat/completions"
is_openai = "api.openai.com" in base_url
is_ollama_cloud = "ollama.com" in base_url
token_key = "max_completion_tokens" if is_openai else "max_tokens"
payload = {
"model": model,
"messages": messages,
token_key: max_tokens,
"temperature": 0.2,
}
# Disable thinking for Ollama Cloud qwen models (content comes back empty otherwise)
if is_ollama_cloud:
payload["reasoning_effort"] = "none"
body = json.dumps(payload).encode("utf-8")
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {api_key}",
"User-Agent": f"neuron-loop/{VERSION}",
}
req = urllib.request.Request(url, data=body, headers=headers, method="POST")
ctx = ssl.create_default_context()
try:
with urllib.request.urlopen(req, timeout=timeout, context=ctx) as resp:
data = json.loads(resp.read().decode("utf-8"))
usage = data.get("usage", {})
content = data["choices"][0]["message"]["content"]
return content, usage
except urllib.error.HTTPError as e:
error_body = e.read().decode("utf-8", errors="replace")[:500]
raise RuntimeError(f"HTTP {e.code}: {error_body}")
except urllib.error.URLError as e:
raise RuntimeError(f"Connection failed: {e.reason}")
def api_call_anthropic(api_key, model, messages, max_tokens=8192, timeout=300):
"""Call Anthropic's native API."""
url = "https://api.anthropic.com/v1/messages"
system_msg = ""
anthropic_messages = []
for m in messages:
if m["role"] == "system":
system_msg = m["content"]
else:
anthropic_messages.append({"role": m["role"], "content": m["content"]})
body = json.dumps({
"model": model,
"max_tokens": max_tokens,
"messages": anthropic_messages,
"system": system_msg,
"temperature": 0.2,
}).encode("utf-8")
headers = {
"Content-Type": "application/json",
"x-api-key": api_key,
"anthropic-version": "2023-06-01",
}
req = urllib.request.Request(url, data=body, headers=headers, method="POST")
ctx = ssl.create_default_context()
try:
with urllib.request.urlopen(req, timeout=timeout, context=ctx) as resp:
data = json.loads(resp.read().decode("utf-8"))
content_blocks = data.get("content", [])
text_parts = [b["text"] for b in content_blocks if b.get("type") == "text"]
usage = data.get("usage", {})
return "\n".join(text_parts), usage
except urllib.error.HTTPError as e:
error_body = e.read().decode("utf-8", errors="replace")[:500]
raise RuntimeError(f"HTTP {e.code}: {error_body}")
except urllib.error.URLError as e:
raise RuntimeError(f"Connection failed: {e.reason}")
def api_call_ollama(base_url, model, messages, max_tokens=8192, timeout=600):
"""Call Ollama's native /api/chat endpoint."""
url = f"{base_url.rstrip('/')}/api/chat"
body = json.dumps({
"model": model,
"messages": messages,
"stream": False,
"think": False,
"options": {
"num_predict": max_tokens,
"temperature": 0.2,
},
}).encode("utf-8")
headers = {"Content-Type": "application/json"}
req = urllib.request.Request(url, data=body, headers=headers, method="POST")
try:
with urllib.request.urlopen(req, timeout=timeout) as resp:
data = json.loads(resp.read().decode("utf-8"))
content = data.get("message", {}).get("content", "")
usage = {
"prompt_tokens": data.get("prompt_eval_count", 0),
"completion_tokens": data.get("eval_count", 0),
}
return content, usage
except Exception as e:
raise RuntimeError(f"Ollama call failed: {e}")
class ModelClient:
"""Unified interface for calling any configured model."""
def __init__(self, providers, logger):
self.providers = providers
self.logger = logger
def call(self, provider_name, model_id, messages, max_tokens=8192, timeout=300):
"""Call a model. Returns (content, usage_dict). Raises RuntimeError on failure."""
prov = self.providers.get(provider_name)
if not prov:
raise RuntimeError(f"Unknown provider: {provider_name}")
api_type = prov.get("api", "openai-completions")
api_key = prov.get("apiKey", "")
base_url = prov.get("baseUrl", "")
t0 = time.time()
try:
if api_type == "anthropic":
content, usage = api_call_anthropic(api_key, model_id, messages, max_tokens, timeout)
elif api_type == "ollama":
content, usage = api_call_ollama(base_url, model_id, messages, max_tokens, timeout)
else:
content, usage = api_call_openai_compat(base_url, api_key, model_id, messages, max_tokens, timeout)
elapsed = time.time() - t0
self.logger.event("api_call", provider=provider_name, model=model_id,
elapsed_s=round(elapsed, 1), usage=usage, success=True)
return content, usage
except RuntimeError as e:
elapsed = time.time() - t0
self.logger.event("api_call", provider=provider_name, model=model_id,
elapsed_s=round(elapsed, 1), success=False, error=str(e))
raise
# ─── Config Loading ─────────────────────────────────────────
def load_config(config_path):
"""Load YAML config."""
try:
import yaml
with open(config_path) as f:
return yaml.safe_load(f)
except ImportError:
return default_config()
def default_config():
"""Return default configuration."""
return {
"tiers": {
"coder": {"model": "anthropic/claude-opus-4-6", "role": "coder"},
"tier1": [
{"provider": "anthropic", "model": "claude-sonnet-4-6", "label": "sonnet"},
{"provider": "openai", "model": "gpt-5.4", "label": "gpt54"},
],
"tier2": [
{"provider": "ollama-cloud", "model": "glm-5:cloud", "label": "glm5"},
{"provider": "openrouter", "model": "auto", "label": "openrouter"},
],
},
"gate": {
"auto_fix_threshold": 2,
"tier1_single_action": "fix",
"tier2_single_action": "skip_unless_critical",
},
"loop": {
"max_iterations": 15,
"max_coder_rounds": 20,
"convergence_threshold": 0,
"max_growth_percent": 25,
"timeout_seconds": 3600,
},
"test": {
"command": "",
"before_review": True,
"after_fix": True,
},
"output": {
"dir": "./runs",
"keep_intermediates": True,
"verbose": True,
},
}
# ─── Prompt Building ───────────────────────────────────────
def load_prompt_template(name):
"""Load a prompt template from the prompts directory."""
path = SCRIPT_DIR / "prompts" / f"{name}.md"
if path.exists():
return path.read_text()
return ""
def build_review_prompt(files_content, context="", standards="", diff_text=""):
"""Build the review prompt with file contents injected."""
template = load_prompt_template("reviewer")
if not template:
template = "Review the following code for bugs and security issues.\n\n{file_list}"
file_list = ""
for name, content in files_content.items():
file_list += f"\n### {name}\n```\n{content}\n```\n"
diff_section = ""
if diff_text:
diff_section = (f"\n## Changes Since Last Iteration\n"
f"Pay special attention to these recent changes:\n"
f"```diff\n{diff_text}\n```\n")
result = template
result = result.replace("{file_list}", file_list)
result = result.replace("{diff_section}", diff_section)
result = result.replace("{context}", context or "General code review.")
result = result.replace("{standards}", standards or "N/A")
return result
def build_fix_prompt(files_content, findings_text, context=""):
"""Build the coder fix prompt."""
template = load_prompt_template("coder")
if not template:
template = "Fix the following issues.\n\n{findings}\n\n{code}"
code = ""
for name, content in files_content.items():
code += f"\n### {name}\n```\n{content}\n```\n"
result = template
result = result.replace("{code}", code)
result = result.replace("{findings}", findings_text)
result = result.replace("{context}", context or "Fix the reported issues.")
return result
def build_improve_prompt(files_content, context=""):
"""Build the improve prompt — coder reviews and improves the script itself."""
template = load_prompt_template("improver")
if not template:
template = """Review and improve the following script. You are both reviewer and coder.
## Task Context
{context}
## Instructions
1. Carefully review the script for bugs, security issues, edge cases, and correctness
2. Produce an improved version using SEARCH/REPLACE blocks
3. Focus on: logic errors, security vulnerabilities, error handling, edge cases, platform compatibility
4. Do NOT rewrite the entire script — make targeted improvements
5. Do NOT change the script's interface (CLI flags, exit codes) unless fixing a bug
6. Preserve the script's style and structure where possible
## Current Script
{code}
Return ONLY SEARCH/REPLACE blocks using <<<SEARCH, >>>REPLACE, <<<END delimiters.
Label each fix with a brief comment (e.g. ### Fix 1: description)."""
code = ""
for name, content in files_content.items():
code += f"\n### {name}\n```\n{content}\n```\n"
result = template
result = result.replace("{code}", code)
result = result.replace("{context}", context or "Review and improve this script.")
return result
# ─── Finding Extraction ────────────────────────────────────
def extract_findings(response_text):
"""Extract structured findings from a model's review response."""
if not response_text:
return []
findings = []
# Method 1: Find JSON array with severity fields
json_match = re.search(r'\[[\s\S]*?\{[\s\S]*?"severity"[\s\S]*?\}[\s\S]*?\]', response_text)
if json_match:
try:
parsed = json.loads(json_match.group())
if isinstance(parsed, list):
return parsed
except json.JSONDecodeError:
pass
# Method 2: Find individual JSON objects
for m in re.finditer(r'\{[^{}]*"severity"\s*:\s*"[^"]+?"[^{}]*\}', response_text):
try:
obj = json.loads(m.group())
findings.append(obj)
except json.JSONDecodeError:
pass
if findings:
return findings
# Method 3: Parse structured text (fallback)
text_findings = []
current = None
for line in response_text.split("\n"):
sev_match = re.match(r'.*?\b(CRITICAL|HIGH|MEDIUM|LOW)\b', line, re.IGNORECASE)
if sev_match and (re.match(r'^\s*[\d#*-]', line) or "finding" in line.lower()):
if current:
text_findings.append(current)
current = {
"severity": sev_match.group(1).upper(),
"title": line.strip().lstrip("#*- 0123456789."),
"description": "",
}
elif current:
current["description"] += line + "\n"
if current:
text_findings.append(current)
return text_findings
def normalize_finding(finding):
"""Normalize a finding to a consistent structure."""
return {
"id": finding.get("id", "?"),
"severity": finding.get("severity", "MEDIUM").upper(),
"location": finding.get("location", "unknown"),
"title": finding.get("title", "Untitled finding"),
"description": finding.get("description", ""),
"impact": finding.get("impact", ""),
"suggestion": finding.get("suggestion", ""),
"false_positive_risk": finding.get("false_positive_risk", "low"),
}
# ─── Finding Deduplication & Triage ────────────────────────
def fingerprint_finding(f):
"""Create a fuzzy fingerprint for deduplication."""
text = f"{f.get('severity','')} {f.get('title','')} {f.get('location','')}".lower()
stopwords = {"the", "a", "an", "is", "in", "for", "of", "to", "and", "or", "not",
"no", "does", "are", "has", "have", "with", "on", "by", "it"}
words = [w for w in text.split() if w not in stopwords and len(w) > 2]
return " ".join(sorted(set(words)))
def similarity(fp1, fp2):
"""Jaccard similarity between two fingerprints."""
w1 = set(fp1.split())
w2 = set(fp2.split())
if not w1 or not w2:
return 0.0
return len(w1 & w2) / len(w1 | w2)
def deduplicate_findings(all_findings_by_model, gate_config, addressed_fingerprints=None):
"""Cross-reference findings across models and apply gate rules.
addressed_fingerprints: set of fingerprints from prior iterations that were already
sent to the coder. Findings matching these are downgraded to 'skip' unless they
were explicitly marked as not fixed.
"""
auto_fix = gate_config.get("auto_fix_threshold", 2)
t1_action = gate_config.get("tier1_single_action", "fix")
t2_action = gate_config.get("tier2_single_action", "skip_unless_critical")
if addressed_fingerprints is None:
addressed_fingerprints = set()
SIMILARITY_THRESHOLD = 0.35
# Collect all findings with metadata
all_entries = []
for model_label, (findings, tier) in all_findings_by_model.items():
for f in findings:
nf = normalize_finding(f)
fp = fingerprint_finding(nf)
all_entries.append((nf, model_label, tier, fp))
# Cluster by similarity
clusters = [] # Each cluster: list of (finding, model, tier, fingerprint)
used = set()
for i, (f1, m1, t1, fp1) in enumerate(all_entries):
if i in used:
continue
cluster = [(f1, m1, t1, fp1)]
used.add(i)
for j, (f2, m2, t2, fp2) in enumerate(all_entries):
if j in used:
continue
if similarity(fp1, fp2) >= SIMILARITY_THRESHOLD:
cluster.append((f2, m2, t2, fp2))
used.add(j)
clusters.append(cluster)
# Apply gate rules per cluster
triaged = []
for cluster in clusters:
models = list(set(e[1] for e in cluster))
tiers = set(e[2] for e in cluster)
n_models = len(models)
# Use the highest-severity finding as canonical
sev_order = {"CRITICAL": 0, "HIGH": 1, "MEDIUM": 2, "LOW": 3}
best = min(cluster, key=lambda e: sev_order.get(e[0]["severity"], 99))
finding = best[0]
if n_models >= auto_fix:
action = "fix"
elif 1 in tiers:
action = t1_action
else:
if t2_action == "skip_unless_critical" and finding["severity"] == "CRITICAL":
action = "fix"
elif t2_action == "skip_unless_critical":
action = "skip"
else:
action = t2_action
# Check if this finding was already addressed in a prior iteration
cluster_fp = fingerprint_finding(finding)
already_addressed = any(
similarity(cluster_fp, afp) >= SIMILARITY_THRESHOLD
for afp in addressed_fingerprints
)
if already_addressed and action == "fix":
action = "skip"
finding["_skip_reason"] = "already addressed in prior iteration"
triaged.append({
"finding": finding,
"models": models,
"n_models": n_models,
"tiers": sorted(tiers),
"action": action,
"cluster_size": len(cluster),
"fingerprint": cluster_fp,
})
# Sort: fix first, then by severity
sev_order = {"CRITICAL": 0, "HIGH": 1, "MEDIUM": 2, "LOW": 3}
triaged.sort(key=lambda t: (
0 if t["action"] == "fix" else 1,
sev_order.get(t["finding"]["severity"], 99),
))
return triaged
# ─── Test Runner ────────────────────────────────────────────
def run_tests(test_cmd, workdir=None):
"""Run tests. Returns (success, output)."""
if not test_cmd:
return True, "(no tests configured)"
try:
result = subprocess.run(
test_cmd, shell=True, capture_output=True, text=True,
timeout=300, cwd=workdir,
)
output = result.stdout + "\n" + result.stderr
return result.returncode == 0, output.strip()
except subprocess.TimeoutExpired:
return False, "Tests timed out (300s)"
except Exception as e:
return False, f"Test execution failed: {e}"
# ─── Code Extraction & Diff Application ────────────────────
def extract_code_from_response(response, filename):
"""Extract code blocks from coder response (legacy full-file mode)."""
if not response:
return None
blocks = re.findall(r'```(?:\w+)?\n(.*?)```', response, re.DOTALL)
if not blocks:
return None
if len(blocks) == 1:
return blocks[0]
pattern = re.compile(
r'(?:^|\n)#+\s*' + re.escape(filename) + r'.*?\n```(?:\w+)?\n(.*?)```',
re.DOTALL
)
m = pattern.search(response)
if m:
return m.group(1)
return max(blocks, key=len)
def parse_search_replace_blocks(response):
"""Parse SEARCH/REPLACE blocks from coder response.
Returns list of (search_text, replace_text, finding_info) tuples.
"""
if not response:
return []
blocks = []
# Pattern: <<<SEARCH ... >>>REPLACE ... <<<END (also accept >>>END)
pattern = re.compile(
r'<<<SEARCH\s*\n(.*?)>>>REPLACE\s*\n(.*?)(?:<<<END|>>>END)',
re.DOTALL
)
for m in pattern.finditer(response):
search = m.group(1)
replace = m.group(2)
# Strip trailing newline (the block delimiter adds one)
if search.endswith('\n'):
search = search[:-1]
if replace.endswith('\n'):
replace = replace[:-1]
# Find the associated finding header (look backwards for ### Finding N)
preceding = response[:m.start()]
finding_match = re.search(r'###\s*Finding\s*(\d+)\s*:\s*(\w+)', preceding[::-1][:500][::-1])
finding_info = finding_match.group(0) if finding_match else "unknown"
blocks.append((search, replace, finding_info))
return blocks
def parse_wont_fix(response):
"""Parse WONT_FIX responses from coder.
Returns (is_wont_fix, reason, limitation_line) or (False, None, None).
"""
if not response:
return False, None, None
# Check for WONT_FIX in finding header
wf_match = re.search(r'###\s*Finding.*?:\s*WONT_FIX', response, re.IGNORECASE)
if not wf_match:
return False, None, None
# Extract reason
reason_match = re.search(r'\*\*Reason\*\*:\s*(.+?)(?:\n|$)', response)
reason = reason_match.group(1).strip() if reason_match else "Platform limitation"
# Extract limitation line
lim_match = re.search(r'\*\*Limitation\*\*:\s*(.+?)(?:\n|$)', response)
limitation = lim_match.group(1).strip() if lim_match else reason
return True, reason, limitation
def sanitize_replacement(text):
"""Strip stray SEARCH/REPLACE format markers from replacement text.
These can leak when the coder echoes its own format into code."""
markers = ['<<<SEARCH', '>>>REPLACE', '<<<END', '>>>END']
for marker in markers:
text = text.replace(marker, '')
return text
def apply_search_replace(content, blocks, logger):
"""Apply SEARCH/REPLACE blocks to file content.
Returns (new_content, applied_count, failed_count).
"""
applied = 0
failed = 0
for search, replace, info in blocks:
replace = sanitize_replacement(replace)
if search in content:
content = content.replace(search, replace, 1)
applied += 1
logger.info(f" Applied: {info}")
else:
# Try with whitespace normalization
search_normalized = re.sub(r'[ \t]+', ' ', search)
content_normalized = re.sub(r'[ \t]+', ' ', content)
if search_normalized in content_normalized:
# Find the actual position and replace
idx = content_normalized.index(search_normalized)
# Count newlines to find line range
line_start = content[:idx].count('\n')
line_end = line_start + search.count('\n')
logger.warn(f" Fuzzy match for {info} (lines {line_start}-{line_end})")
# Do the replacement on original content using line-based matching
orig_lines = content.split('\n')
search_lines = search.split('\n')
replace_lines = replace.split('\n')
# Find matching line range
found = False
for i in range(len(orig_lines) - len(search_lines) + 1):
chunk = orig_lines[i:i + len(search_lines)]
if all(a.strip() == b.strip() for a, b in zip(chunk, search_lines)):
orig_lines[i:i + len(search_lines)] = replace_lines
content = '\n'.join(orig_lines)
applied += 1
found = True