Repository navigation
Expand file tree
/
Copy pathpact_loop.py
More file actions
1358 lines (1146 loc) · 49.3 KB
/
Copy pathpact_loop.py
File metadata and controls
1358 lines (1146 loc) · 49.3 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
"""
pact_loop -- recursive self-improvement loop with ML convergence criterion.
Runs pact on any target (including itself) until formal convergence:
violations → 0 OR |Δfitness| < ε for 3 consecutive iterations
Philosophy (from project history and ADR-036/ADR-037):
- Failures are the signal. Every parse fail, empty result, low confirm
rate = prompt improvement trigger. Errors are training data.
- Git history IS the prior. CHANGES.rst "Fixed…" lines are confirmed
invariants. They weight find.md toward what actually broke.
- Z3/Hypothesis/TLA+ derive the taxonomy. We don't invent categories;
formal tools find them. The taxonomy IS the set of properties that
Hypothesis falsifies and Z3 proves.
- Stunspot principle: prompts may evolve into alien encodings. We
validate against rubrics, not readability. The rubric is the invariant.
- CEGIS oracle loop: synthesize → verify → oracle → revert/accept →
feedback. The oracle (target test suite) cannot collude with pact.
- Graph-first (ADR-001): violations = constraints on call-graph paths,
not pattern matches. blast radius × topology score → priority order.
- Sheaf cohomology (pact_sheaf.py): Ȟ¹ rank = minimum independent fixes.
- TDA (pact_tda.py): β₁ Betti numbers of neighborhood → topology score.
- ADR generation: every architectural decision the loop makes is recorded.
Fitness function (ML loss analog, range [0, 1], higher = better):
f = 0.25 * (1 − violation_rate) # code cleanliness vs. initial
+ 0.20 * heal_accept_rate # CEGIS patch quality
+ 0.15 * oracle_confirm_rate # oracle trust (ground truth)
+ 0.15 * find_confirm_rate # real bug detection (Hypothesis)
+ 0.10 * topo_score # topology health (β₁ of call graph)
+ 0.10 * avg_prompt_score # prompt quality (from improve runs)
+ 0.05 * sheaf_score # Ȟ¹ rank reduction (interprocedural)
Termination conditions (any one):
PROVED_CLEAN violation_count == 0 and sheaf rank == 0
CONVERGED |Δfitness| < ε for 3 consecutive iterations
STUCK heal accepts 0 patches for 2 consecutive iterations
TIMEOUT iter >= max_iters
Usage:
pact loop <target_dir> --test-cmd "pytest tests/ -q"
python -m pact.pact_loop . --test-cmd "pytest -q" --verbose
"""
from __future__ import annotations
import ast
import dataclasses
import json
import os
import sys
import textwrap
import time
import warnings
from dataclasses import dataclass, field
from pathlib import Path
from typing import Optional
_DEFAULT_MODEL = "claude-sonnet-4-6"
_API_KEY = os.environ.get("ANTHROPIC_API_KEY", "")
_EPSILON = 0.01
_WINDOW = 3
_MAX_ITERS = 20
_STUCK_WINDOW = 2
# ---------------------------------------------------------------------------
# State
# ---------------------------------------------------------------------------
@dataclass
class MeasureResult:
"""Full measurement snapshot from all analyzers."""
checker_total: int = 0
checker_by_mode: dict = field(default_factory=dict)
interproc_total: int = 0
interproc_transitive: int = 0
sheaf_rank: int = 0 # Ȟ¹ = min independent fixes (pact_sheaf)
z3_proved: int = 0 # violations proved by Z3 datalog
topo_score: float = 0.0 # β₁-based topology health (pact_tda)
blast_top: list = field(default_factory=list) # top-3 blast-radius fns
scc_count: int = 0 # strongly-connected components
hub_count: int = 0 # high-fan-in functions
find_attempted: int = 0
find_confirmed: int = 0
find_parse_failures: int = 0
violations_doc: dict = field(default_factory=dict)
@dataclass
class IterationState:
iteration: int
timestamp: float = field(default_factory=time.time)
measure: MeasureResult = field(default_factory=MeasureResult)
total_violations: int = 0
heal_attempted: int = 0
heal_accepted: int = 0
oracle_confirmed: int = 0
heal_accept_rate: float = 0.0
oracle_confirm_rate: float = 0.0
find_confirm_rate: float = 0.0
heal_prompt_score: float = 1.0
find_prompt_score: float = 1.0
context_prompt_score: float = 1.0
avg_prompt_score: float = 1.0
topo_score: float = 0.0
sheaf_score: float = 1.0 # 1.0 = no sheaf issues; 0.0 = max rank
fitness: float = 0.0
termination: Optional[str] = None
adr_generated: Optional[str] = None
@dataclass
class LoopResult:
target: str
test_cmd: str
iterations: list[IterationState] = field(default_factory=list)
termination: str = ""
initial_violations: int = 0
final_violations: int = 0
final_fitness: float = 0.0
elapsed_seconds: float = 0.0
def summary(self) -> str:
lines = [
f"[loop] target: {self.target}",
f"[loop] termination: {self.termination}",
f"[loop] violations: {self.initial_violations} → {self.final_violations}",
f"[loop] fitness: {self.final_fitness:.3f}",
f"[loop] iterations: {len(self.iterations)}",
f"[loop] elapsed: {self.elapsed_seconds:.1f}s",
]
if len(self.iterations) > 1:
scores = [f"{s.fitness:.3f}" for s in self.iterations]
lines.append(f"[loop] history: {' → '.join(scores)}")
return "\n".join(lines)
# ---------------------------------------------------------------------------
# Fitness
# ---------------------------------------------------------------------------
def compute_fitness(state: IterationState, initial_violations: int) -> float:
"""
Composite fitness in [0, 1]. This is the loop's loss function.
Weights from ADR-037 (pact-self-loop-architecture):
violation_rate (0.25): primary goal — clean code
heal_accept_rate (0.20): CEGIS synthesis quality
oracle_confirm_rate (0.15): ground truth signal
find_confirm_rate (0.15): real bug detection, not hallucinations
topo_score (0.10): graph topology health (β₁ Betti)
avg_prompt_score (0.10): prompt quality → future improvement capacity
sheaf_score (0.05): Ȟ¹ rank reduction (interprocedural safety)
"""
iv = max(initial_violations, 1)
v_score = max(0.0, 1.0 - state.total_violations / iv)
return (
0.25 * v_score
+ 0.20 * state.heal_accept_rate
+ 0.15 * state.oracle_confirm_rate
+ 0.15 * state.find_confirm_rate
+ 0.10 * state.topo_score
+ 0.10 * state.avg_prompt_score
+ 0.05 * state.sheaf_score
)
def _converged(history: list[float], epsilon: float, window: int) -> bool:
if len(history) < window:
return False
recent = history[-window:]
return (max(recent) - min(recent)) < epsilon
def _stuck(accepted_history: list[int], window: int) -> bool:
if len(accepted_history) < window:
return False
return all(a == 0 for a in accepted_history[-window:])
# ---------------------------------------------------------------------------
# Phase 1: MEASURE — all analyzers
# ---------------------------------------------------------------------------
def _measure_checker(target: Path, verbose: bool) -> tuple[int, dict, dict]:
"""Static AST checker (all Python modes). Returns (count, by_mode, violations_doc)."""
from .checker import check_codebase
from .graphify_graph import CallGraph
from collections import defaultdict, Counter
results = check_codebase(target)
cg = CallGraph.load(target) # None if no graph.json present
by_mode = dict(
Counter(
getattr(r, "mode_name", getattr(r, "context", "?")) for r in results
).most_common()
)
inv_templates = {
"bare_except": "Exception handlers must be typed and not silently swallow errors",
"json_loads_unguarded": "json.loads() must be wrapped in try/except json.JSONDecodeError",
"subprocess_exit_code_unchecked": "subprocess.run() must check returncode",
"llm_response_unguarded": "LLM response access must be guarded against None/empty choices",
"optional_dereference": "Optional values must be checked before attribute access",
"save_without_update_fields": "Model.save() must pass update_fields to prevent race conditions",
"missing_await": "Coroutines must be awaited or they silently do nothing",
"sheaf_llm_unguarded": "LLM response path is interprocedurally unguarded",
"model_constraint": "Required model fields must be provided at call sites",
"unvalidated_lookup_chain": "ORM lookup chains must handle DoesNotExist",
"falsy_or_zero_elision": "'or default' pattern silently elides zero/empty-string",
"mutable_default_arg": "Mutable default argument is shared across all calls",
"required_arg_missing": "Required positional argument omitted at call site",
"empty_catch": "Empty except block swallows all exceptions silently",
"asyncio_run_in_async": "asyncio.run() called inside async function creates deadlock",
}
file_viols: dict = defaultdict(list)
for r in results:
ctx = getattr(r, "context", getattr(r, "mode_name", "?"))
inv_id = f"{ctx}_{Path(r.file).stem}"
severity = (
"high"
if ctx
in (
"bare_except",
"json_loads_unguarded",
"llm_response_unguarded",
"missing_await",
"model_constraint",
"required_arg_missing",
)
else "medium"
)
community_id = cg.community_of("", r.file) if cg else None
community_label = (
cg.community_label_for(community_id)
if cg and community_id is not None
else ""
)
file_viols[r.file].append(
{
"invariant_id": inv_id,
"file": r.file,
"line": r.line,
"severity": severity,
"evidence": r.call,
"explanation": "; ".join(r.missing) if r.missing else "",
"_inv": inv_templates.get(ctx, f"Violation: {ctx}"),
**(
{"community_id": community_id, "community_label": community_label}
if community_id is not None
else {}
),
}
)
modules = []
for fpath, viols in sorted(file_viols.items()):
seen: dict = {}
invs = []
for v in viols:
iid = v["invariant_id"]
if iid not in seen:
invs.append(
{
"id": iid,
"type": iid.rsplit("_", 1)[0],
"statement": v.pop("_inv"),
"severity": v["severity"],
"confidence": 0.9,
}
)
seen[iid] = True
else:
v.pop("_inv", None)
modules.append(
{
"path": fpath,
"invariants": invs,
"violations": [
{k: vl for k, vl in v.items() if k != "_inv"} for v in viols
],
}
)
doc = {"project": target.name, "generated_by": "pact.checker", "modules": modules}
if verbose:
print(
f" checker: {len(results)} violations — top modes: "
+ ", ".join(f"{m}({c})" for m, c in list(by_mode.items())[:4])
)
if cg:
community_counts: dict[int, int] = Counter(
v["community_id"]
for mod in modules
for v in mod["violations"]
if "community_id" in v
)
top_clusters = community_counts.most_common(3)
if top_clusters:
parts = []
for cid, cnt in top_clusters:
label = cg.community_label_for(cid)
parts.append(
f"cluster {cid}({cnt})" + (f"={label}" if label else "")
)
print(" graphify clusters: " + ", ".join(parts))
return len(results), by_mode, doc, results
def _measure_interproc(target: Path, verbose: bool) -> tuple[int, int]:
"""Z3 Fixedpoint interprocedural analysis."""
try:
from .pact_interproc import analyze_codebase
results = analyze_codebase(target, verbose=False)
transitive = sum(1 for r in results if r.propagation_depth > 0)
if verbose:
print(
f" interproc: {len(results)} ({transitive} transitive via call graph)"
)
return len(results), transitive
except Exception as exc:
if verbose:
print(f" interproc: skipped ({exc})")
return 0, 0
def _measure_sheaf(target: Path, verbose: bool) -> int:
"""Sheaf-cohomological analysis. Returns Ȟ¹ rank (min independent fixes)."""
try:
from .pact_sheaf import _harvest_sites
py_files = list(target.rglob("*.py"))
py_files = [
f
for f in py_files
if not any(p in f.parts for p in ("__pycache__", ".venv", "node_modules"))
]
total_rank = 0
for fpath in py_files[:30]: # sample — sheaf is expensive
try:
source = fpath.read_text(encoding="utf-8", errors="replace")
sg = _harvest_sites(str(fpath), source)
error_sites = sg.error_sites()
if error_sites:
total_rank += len(error_sites)
except Exception as _file_exc:
import warnings
warnings.warn(
f"pact_sheaf: skipped {fpath} ({_file_exc})",
RuntimeWarning,
stacklevel=2,
)
if verbose:
print(f" sheaf: Ȟ¹ rank ≈ {total_rank} (min independent fixes)")
return total_rank
except Exception as exc:
if verbose:
print(f" sheaf: skipped ({exc})")
return 0
def _measure_tda(target: Path, violations_doc: dict, verbose: bool) -> float:
"""Topological data analysis — β₁ Betti of call graph neighborhood → topo_score."""
try:
from .pact_tda import score_violations
from .graphify_graph import CallGraph
cg = CallGraph.load(target)
if cg is None:
if verbose:
print(" tda: no graphify call graph — skipping")
return 0.5 # neutral when graph unavailable
# Collect all violations
all_viols = []
for mod in violations_doc.get("modules", []):
for v in mod.get("violations", []):
all_viols.append(v)
if not all_viols:
return 1.0
pairs = score_violations(cg, all_viols)
scores = [ts for _, ts in pairs if ts is not None]
if not scores:
return 0.5
avg = sum(s.severity() for s in scores) / len(scores)
# severity ∈ [0,1]; higher = worse topology. Invert for fitness.
topo_health = 1.0 - avg
if verbose:
print(
f" tda: β₁-based topo_score={topo_health:.3f} "
f"({len(scores)} violations scored)"
)
return max(0.0, min(1.0, topo_health))
except Exception as exc:
if verbose:
print(f" tda: skipped ({exc})")
return 0.5
def _measure_z3(target: Path, violations_doc: dict, verbose: bool) -> int:
"""Z3 Datalog engine — count formally proved violations."""
try:
from .z3_engine import LLMResponseEngine
proved = 0
py_files = list(target.rglob("*.py"))[:20]
for fpath in py_files:
try:
eng = LLMResponseEngine()
source = fpath.read_text(encoding="utf-8", errors="replace")
tree = ast.parse(source)
# Feed facts and query
viols = eng.check(fpath, source, tree)
proved += len(viols) if viols else 0
except Exception as exc: # noqa: BLE001
import warnings
warnings.warn(
f"z3-engine: skipped {fpath} ({exc})",
RuntimeWarning,
stacklevel=2,
)
if verbose and proved:
print(f" z3-engine: {proved} formally proved violations")
return proved
except Exception as exc:
if verbose:
print(f" z3-engine: skipped ({exc})")
return 0
def _measure_blast_radii(
target: Path, checker_violations: list, verbose: bool
) -> tuple[list, int, int]:
"""Blast radius + SCC + hub analysis from reduce.py."""
try:
from .reduce import (
compute_blast_radii,
find_bridge_violations,
find_sccs,
find_hubs,
_build_digraph,
)
from .extractor import extract_from_codebase
_, functions, call_sites = extract_from_codebase(target)
blast = compute_blast_radii(functions, call_sites, checker_violations)
top3 = [str(b) for b in sorted(blast, key=lambda b: -b.blast_radius)[:3]]
bridges = find_bridge_violations(functions, call_sites, checker_violations)
G, func_by_name = _build_digraph(functions, call_sites)
sccs_list = find_sccs(G, func_by_name, checker_violations) if G else []
hubs_list = find_hubs(G, func_by_name, checker_violations) if G else []
if verbose:
bridge_str = (
f"{len(bridges)} bridge violations "
f"(top: {bridges[0].enclosing_func} btw={bridges[0].betweenness:.3f})"
if bridges
else "0 bridge violations"
)
print(
f" reduce: {len(sccs_list)} SCCs, {len(hubs_list)} hubs, "
f"{bridge_str}, "
f"top blast: {top3[0][:60] if top3 else 'n/a'}"
)
return top3, len(sccs_list), len(hubs_list)
except Exception as exc:
if verbose:
print(f" reduce: skipped ({exc})")
return [], 0, 0
def _measure_find(
target: Path, model: str, key: str, improve: bool, verbose: bool
) -> tuple[int, int, int, float]:
"""LLM property-driven finder — sample top-3 hottest files."""
try:
from .find import find_violations
from .checker import check_codebase
from collections import Counter
hot = Counter(r.file for r in check_codebase(target)).most_common(3)
if not hot:
return 0, 0, 0, 0.0
att = conf = fails = 0
for fpath_str, _ in hot:
fpath = Path(fpath_str)
if not fpath.exists():
continue
try:
res = find_violations(
path=fpath,
model=model,
api_key=key,
verbose=verbose,
use_context=True,
improve=improve,
)
for m in res.get("modules", []):
viols = m.get("violations", [])
att += len(viols)
conf += sum(1 for v in viols if v.get("hypothesis_confirmed"))
except Exception as exc:
fails += 1
if verbose:
print(f" find: {fpath.name} failed: {exc}")
rate = conf / max(att, 1)
if verbose:
print(f" find: {att} properties, {conf} Hypothesis-confirmed ({rate:.0%})")
return att, conf, fails, rate
except ImportError:
return 0, 0, 0, 0.0
def _topology_priority(violations_doc: dict, target: Path) -> dict[str, float]:
"""Score each file by combined PageRank + betweenness_centrality.
PageRank (60%): high-rank files infect many callers if violated.
Betweenness (40%): high-betweenness files are structural bottlenecks —
fixing them breaks the most transitive violation chains.
"""
try:
import networkx as nx
from .graphify_graph import CallGraph
cg = CallGraph.load(target)
if cg is None:
return {}
# Build directed call graph: caller → callee
G: nx.DiGraph = nx.DiGraph()
for src, targets in cg._out_edges.items():
for tgt in targets:
G.add_edge(src, tgt)
if G.number_of_nodes() == 0:
return {}
pr: dict[str, float] = nx.pagerank(G, alpha=0.85)
# Betweenness on undirected projection (faster; captures structural bridges)
G_undirected = G.to_undirected()
btw: dict[str, float] = nx.betweenness_centrality(G_undirected, normalized=True)
func_to_file: dict[str, str] = {
nid: meta["file"] for nid, meta in cg._id_meta.items() if meta.get("file")
}
# Per-file score: max over all functions in the file
file_pr: dict[str, float] = {}
file_btw: dict[str, float] = {}
for nid in G.nodes():
fpath = func_to_file.get(nid, "")
if not fpath:
continue
file_pr[fpath] = max(file_pr.get(fpath, 0.0), pr.get(nid, 0.0))
file_btw[fpath] = max(file_btw.get(fpath, 0.0), btw.get(nid, 0.0))
# Normalize each signal to [0, 1]
def _norm(d: dict[str, float]) -> dict[str, float]:
mx = max(d.values()) if d else 1.0
return {k: v / (mx or 1.0) for k, v in d.items()}
pr_n = _norm(file_pr)
btw_n = _norm(file_btw)
priorities: dict[str, float] = {}
for mod in violations_doc.get("modules", []):
fpath = mod["path"]
priorities[fpath] = 0.60 * pr_n.get(fpath, 0.0) + 0.40 * btw_n.get(
fpath, 0.0
)
if priorities:
mx = max(priorities.values()) or 1.0
priorities = {k: v / mx for k, v in priorities.items()}
return priorities
except Exception:
return {}
def _z3_optimal_heal_order(violations_doc: dict, top_k: int = 5) -> list[str] | None:
"""Use z3.Optimize to find the k files that cover the most violations.
Models max-coverage: maximize sum of violations in selected files subject to
selecting ≤ top_k files. Returns ordered file list (highest coverage first),
or None if z3 unavailable or violations < 2 files.
"""
try:
import z3
modules = violations_doc.get("modules", [])
if len(modules) <= 1:
return None
file_viols = [(m["path"], len(m.get("violations", []))) for m in modules]
file_viols = [(f, v) for f, v in file_viols if v > 0]
if len(file_viols) <= 1:
return None
opt = z3.Optimize()
# Boolean variable for each file: selected[i] = True ↔ file i is healed
selected = [z3.Bool(f"sel_{i}") for i in range(len(file_viols))]
# Constraint: pick at most top_k files
opt.add(z3.PbLe([(s, 1) for s in selected], top_k))
# Maximize: total violations in selected files
coverage = z3.Sum(
[
z3.If(selected[i], z3.IntVal(v), z3.IntVal(0))
for i, (_, v) in enumerate(file_viols)
]
)
opt.maximize(coverage)
if opt.check() == z3.sat:
model = opt.model()
# Sort: selected files first (by violation count desc), then rest
order = sorted(
range(len(file_viols)),
key=lambda i: (
z3.is_true(model[selected[i]]),
file_viols[i][1],
),
reverse=True,
)
return [file_viols[i][0] for i in order]
except Exception as exc:
warnings.warn(f"violation ordering failed: {exc}", RuntimeWarning)
return None
def _reprioritize(violations_doc: dict, priorities: dict[str, float]) -> dict:
if not priorities:
return violations_doc
doc = dict(violations_doc)
doc["modules"] = sorted(
doc.get("modules", []),
key=lambda m: priorities.get(m["path"], 0.0),
reverse=True,
)
return doc
def measure(
target: Path, model: str, key: str, run_find: bool, improve: bool, verbose: bool
) -> MeasureResult:
m = MeasureResult()
print("\n[loop:measure]")
# 1. Static checker (all modes, all languages)
m.checker_total, m.checker_by_mode, m.violations_doc, _checker_raw = (
_measure_checker(target, verbose)
)
# 2. Z3 interprocedural (Fixedpoint CHC)
m.interproc_total, m.interproc_transitive = _measure_interproc(target, verbose)
# 3. Sheaf cohomology (Ȟ¹ rank)
m.sheaf_rank = _measure_sheaf(target, verbose)
# 4. Z3 Datalog engine (formal proofs)
m.z3_proved = _measure_z3(target, m.violations_doc, verbose)
# 5. TDA — topology score
m.topo_score = _measure_tda(target, m.violations_doc, verbose)
# 6. Blast radii + SCCs + hubs
m.blast_top, m.scc_count, m.hub_count = _measure_blast_radii(
target, _checker_raw, verbose
)
# 7. LLM property-driven find (optional — expensive)
if run_find:
print("\n[loop:find]")
m.find_attempted, m.find_confirmed, m.find_parse_failures, _ = _measure_find(
target, model, key, improve, verbose
)
return m
# ---------------------------------------------------------------------------
# Phase 2: HEAL
# ---------------------------------------------------------------------------
def _record_heal_failure(
violations_doc: dict, target: Path, error_msg: str, verbose: bool
) -> None:
"""Save a tool-loop-exhausted failure as a spec_learner training example.
Accumulates in corpus/spec_gaps.jsonl. When ≥2 bad records exist,
spec_learner.improve() will trigger heal-prompt self-improvement.
"""
try:
from .spec_learner import SpecGapRecord, save
tla_path = Path(__file__).parent / "docs" / "tla" / "PactLoop.tla"
tla_text = tla_path.read_text() if tla_path.exists() else ""
# Pick the first violated file as the representative failure site
modules = violations_doc.get("modules", [])
bug_file = modules[0]["path"] if modules else str(target)
bug_line = (
modules[0]["violations"][0]["line"]
if modules and modules[0].get("violations")
else 0
)
mode = (
modules[0]["violations"][0].get("invariant_id", "unknown").rsplit("_", 1)[0]
if modules and modules[0].get("violations")
else "unknown"
)
record = SpecGapRecord(
bug_description=(
f"CEGIS tool loop exhausted while healing {mode} violation in {Path(bug_file).name}. "
f"The LLM read the file repeatedly but never produced a valid patch, "
f"exhausting all tool rounds without progress."
),
bug_file=bug_file,
bug_line=bug_line,
bug_manifestation=error_msg,
bug_fix="Not yet fixed — training example for HealMustTerminateOrFail invariant",
tla_spec_path=str(tla_path),
tla_spec_text=tla_text,
)
save(record)
if verbose:
print(
" spec_learner: recorded tool-loop-exhausted failure as training example"
)
except Exception as save_exc:
if verbose:
print(f" spec_learner: failed to record failure ({save_exc})")
def heal(
violations_doc: dict,
target: Path,
test_cmd: str,
model: str,
key: str,
severity: list[str],
improve: bool,
verbose: bool,
) -> tuple[int, int, int]:
"""CEGIS repair cycle. Returns (attempted, accepted, oracle_confirmed)."""
import tempfile
from .heal import heal_project
# 1. PageRank-based priority (call-graph importance)
priorities = _topology_priority(violations_doc, target)
violations_doc = _reprioritize(violations_doc, priorities)
# 2. Z3 Optimize — override order for top-k files (max-coverage set)
optimal_order = _z3_optimal_heal_order(violations_doc, top_k=5)
if optimal_order:
path_rank = {p: i for i, p in enumerate(optimal_order)}
violations_doc = dict(violations_doc)
violations_doc["modules"] = sorted(
violations_doc.get("modules", []),
key=lambda m: path_rank.get(m["path"], len(optimal_order)),
)
if verbose:
print(f" heal: z3-optimal order ({len(optimal_order)} files)")
tmp = Path(tempfile.mktemp(suffix=".json"))
try:
tmp.write_text(json.dumps(violations_doc), encoding="utf-8")
result = heal_project(
violations_path=tmp,
api_key=key,
severity_filter=severity,
apply=True,
test_cmd=test_cmd,
project_root=target,
verbose=verbose,
)
att = len(result.results)
acc = sum(1 for r in result.results if r.verify_verdict == "ACCEPT")
orc = sum(1 for r in result.results if getattr(r, "oracle_confirmed", False))
if improve and att > 0 and acc / att < 0.85:
# Trigger heal prompt self-improvement
from .heal import _improve_heal_prompt
_improve_heal_prompt(result.results, model, key, verbose)
return att, acc, orc
except Exception as exc:
if verbose:
print(f" heal: failed: {exc}")
# Record tool-loop exhaustion as a spec_learner training example so
# the TLA+ model can eventually learn a HealMustTerminateOrFail invariant.
if "Tool loop exhausted" in str(exc) and key:
_record_heal_failure(violations_doc, target, str(exc), verbose)
return 0, 0, 0
finally:
tmp.unlink(missing_ok=True)
# ---------------------------------------------------------------------------
# Phase 3: ADR generation
# ---------------------------------------------------------------------------
def _next_adr_number(adr_dir: Path) -> int:
existing = list(adr_dir.glob("ADR-*.md"))
nums = []
for f in existing:
try:
nums.append(int(f.stem.split("-")[1]))
except (IndexError, ValueError):
pass
return max(nums, default=36) + 1
def generate_adr(
state: IterationState,
target: Path,
adr_dir: Path,
initial_violations: int,
) -> Optional[str]:
"""
Generate an ADR documenting the architectural decision this iteration made.
Returns the ADR filename if generated, None otherwise.
"""
# Only generate when something significant happened
sig = (
state.heal_accepted > 0
or state.measure.sheaf_rank > 0
or state.termination is not None
)
if not sig:
return None
adr_dir.mkdir(parents=True, exist_ok=True)
n = _next_adr_number(adr_dir)
date = time.strftime("%Y-%m-%d")
title = f"pact-loop iteration {state.iteration} on {target.name}"
if state.termination:
title = f"pact-loop convergence: {state.termination} on {target.name}"
elif state.heal_accepted > 0:
title = (
f"pact-loop healed {state.heal_accepted}/{state.heal_attempted} "
f"violations in {target.name}"
)
top_modes = list(state.measure.checker_by_mode.items())[:5]
body = textwrap.dedent(f"""\
# ADR-{n:03d}: {title}
**Status**: Auto-generated by pact_loop
**Date**: {date}
**Iteration**: {state.iteration}
---
## Context
pact_loop ran on `{target}` targeting `{initial_violations}` initial violations.
**Violation profile (iteration {state.iteration})**:
- Total: {state.total_violations} (was {initial_violations})
- Checker modes: {', '.join(f'{m}({c})' for m, c in top_modes)}
- Interprocedural (Z3 transitive): {state.measure.interproc_transitive}
- Sheaf Ȟ¹ rank: {state.measure.sheaf_rank}
- Topology score (β₁): {state.topo_score:.3f}
- SCCs: {state.measure.scc_count}, Hubs: {state.measure.hub_count}
**CEGIS heal results**:
- Attempted: {state.heal_attempted}
- Accepted (LLM verify ≥ 0.8): {state.heal_accepted}
- Oracle confirmed (test suite): {state.oracle_confirmed}
- Accept rate: {state.heal_accept_rate:.0%}
- Oracle trust: {state.oracle_confirm_rate:.0%}
**Prompt quality**:
- heal.md score: {state.heal_prompt_score:.2f}
- find.md score: {state.find_prompt_score:.2f}
- Average: {state.avg_prompt_score:.2f}
**Fitness**: {state.fitness:.3f}
---
## Decision
{"Loop terminated: " + state.termination if state.termination else "Loop continues to next iteration."}
{"All violations resolved. Codebase is formally clean." if state.total_violations == 0 else
"Remaining violations require further iterations or manual review."}
{"Prompts were rewritten (score < 0.8)." if state.avg_prompt_score < 0.8 else
"Prompts are performing well (score ≥ 0.8); no rewrite triggered."}
---
## Consequences
- The fitness function weights this iteration at **{state.fitness:.3f}**.
- {"Convergence declared — loop exits." if state.termination in ("PROVED_CLEAN", "CONVERGED") else
"Next iteration will re-run measure phase with updated codebase."}
- ADR auto-generated by `pact_loop.generate_adr()`.
- Blast-radius top violations: {state.measure.blast_top[:2]}
---
*Generated by pact_loop.py — do not edit manually*
""")
filename = f"ADR-{n:03d}-loop-iter-{state.iteration}-{target.name}.md"
(adr_dir / filename).write_text(body, encoding="utf-8")
return filename
# ---------------------------------------------------------------------------
# Phase 4: TLA+ spec for the loop itself
# ---------------------------------------------------------------------------
def generate_tla_spec(max_iters: int, output_dir: Path) -> Path:
spec = textwrap.dedent("""\
---- MODULE PactLoop ----
(*
* TLA+ model of pact_loop.py
*
* Proves three properties:
* OracleSafety -- patches only applied after oracle passes
* Termination -- loop always halts
* FitnessProgress -- fitness non-decreasing on average
*
* See ADR-037 and docs/tla/ for context.
*)
EXTENDS Naturals, Sequences
CONSTANTS MAX_ITERS, WINDOW
VARIABLES
iter,
violations,
fitness_history,
oracle_passed,
patches_applied,
phase,
termination
TypeInvariant ==
/\\ iter \\in 0..MAX_ITERS
/\\ violations \\in Nat
/\\ phase \\in {"measure","heal","improve","check"}
/\\ termination \\in {"","PROVED_CLEAN","CONVERGED","STUCK","TIMEOUT"}
/\\ patches_applied \\subseteq oracle_passed
Init ==
/\\ iter = 0
/\\ violations = 0
/\\ fitness_history = <<>>
/\\ oracle_passed = {}
/\\ patches_applied = {}
/\\ phase = "measure"
/\\ termination = ""
Measure ==
/\\ phase = "measure" /\\ termination = ""
/\\ phase' = "heal"
/\\ UNCHANGED <<iter, violations, fitness_history,
oracle_passed, patches_applied, termination>>
Heal(patch, oracle_ok) ==
/\\ phase = "heal"
/\\ IF oracle_ok