-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmcp_server.py
More file actions
2841 lines (2513 loc) · 104 KB
/
Copy pathmcp_server.py
File metadata and controls
2841 lines (2513 loc) · 104 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
from __future__ import annotations
import hashlib
import json
import os
import re
import shutil
import subprocess
import tempfile
import threading
import time
import uuid
from contextlib import contextmanager
from dataclasses import dataclass, field
from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Dict, Optional
from mcp.server.fastmcp import FastMCP
# ws5 / SI-5 Phase 1-C: std/ graph helpers live in std_graph_lib so that
# visualizer/generate_graph.py (and any other consumer) can use them
# without pulling in FastMCP. The underscore-prefixed names are the
# legacy aliases and are re-exported here to keep existing
# `from mcp_server import _scan_std_imports` callers working.
from std_graph_lib import ( # noqa: F401 (re-exported for back-compat)
_classify_health,
_collect_trusted_atoms,
_count_atoms_per_file,
_render_std_graph_dot,
_render_std_graph_mermaid,
_sanitize_node_id,
_scan_std_imports,
_trusted_by_file_counts,
)
# P26: proof-graph conversion is shared with the Streamlit view in
# visualizer/app.py, so it lives in a Streamlit-free pure module.
from visualizer.proof_graph_lib import ( # noqa: E402
PROOF_GRAPH_FILENAME,
load_proof_graph,
render_proof_graph_dot,
)
mcp = FastMCP("Mumei-Forge")
REPO_ROOT = Path(__file__).parent.absolute()
SPEC_GUIDELINE_SUMMARY: dict[str, Any] = {
"decidable_fragment": {
"linear_arithmetic": [
"Use i64/Nat addition, subtraction, comparisons, and constant multiplication.",
"Avoid variable-variable multiplication, symbolic division/modulo, and exponentiation.",
],
"array_access": [
"Add explicit bounds for every access: 0 <= i && i < len(a).",
"Keep index expressions simple and near their requires/forall bounds.",
],
"bounded_quantifiers": [
"Use forall only over bounded integer ranges or finite collections.",
"Prefer constructible witnesses over exists; avoid forall/exists alternation.",
],
"finite_state_machines": [
"Model temporal effects with explicit finite states and transitions.",
"Avoid implicit history, regex-like traces, and large transition graphs.",
],
},
"common_failure_patterns": [
{
"tag": "nonlinear_arithmetic",
"patterns": ["x * y", "x / y", "x % y", "pow(x, y)"],
"guidance": "Rewrite to linear bounds or mark as a Lean escalation candidate.",
},
{
"tag": "quantifier_alternation",
"patterns": ["forall i. exists j. ...", "exists x. forall y. ..."],
"guidance": "Split the spec or return a constructible witness.",
},
{
"tag": "nested_aliasing",
"patterns": ["multiple ref mut parameters", "nested mutable acquire scopes"],
"guidance": "Serialize mutation through one owner or split the atom.",
},
{
"tag": "regex_semantics",
"patterns": ["regex_match(s, pattern)", "matches(s, pattern)"],
"guidance": "Use prefix/contains/bounded finite cases, or escalate to Lean.",
},
{
"tag": "array_without_bounds",
"patterns": ["a[i] without 0 <= i && i < len(a)"],
"guidance": "Add explicit index bounds in requires, ensures, or bounded forall.",
},
],
"recommended_templates": {
"bounded_array_access": "requires: 0 <= i && i < len(a); ensures: result == a[i];",
"bounded_forall": "forall(i, 0, len(a), a[i] >= 0)",
"constructible_witness": "Return the witness and prove 0 <= result && result < bound.",
"explicit_fsm": "Declare states, initial state, and each transition explicitly.",
},
"doc": "docs/SPEC_GUIDE.md",
}
# Module-level session state for effect boundary overrides
_session_effects: dict = {
"allowed": [],
"denied": [],
"source": "default", # "default" | "mumei.toml" | "session_override"
}
@mcp.tool()
def get_spec_guideline() -> str:
"""Return agent-facing Mumei spec-writing guidelines as JSON."""
return json.dumps(SPEC_GUIDELINE_SUMMARY, ensure_ascii=False, indent=2)
@mcp.tool()
def get_spec_guidelines() -> dict:
"""Return decidable fragment guidelines for spec writing."""
return SPEC_GUIDELINE_SUMMARY
def _env_nonempty(name: str) -> str | None:
value = os.environ.get(name)
if value is None or value == "":
return None
return value
def _harness_metadata_from_env() -> dict[str, Any]:
metadata: dict[str, Any] = {}
harness_contract = _env_nonempty("MUMEI_HARNESS_CONTRACT")
if harness_contract is not None:
metadata["harness_contract"] = harness_contract
intent_prompt_hash = _env_nonempty("MUMEI_INTENT_PROMPT_HASH")
spec_traceability_score = _env_nonempty("MUMEI_SPEC_TRACEABILITY_SCORE")
semantic_drift_detected = _env_nonempty("MUMEI_SEMANTIC_DRIFT_DETECTED")
manual_review_required = _env_nonempty("MUMEI_MANUAL_REVIEW_REQUIRED")
intent_fidelity: dict[str, Any] = {}
if intent_prompt_hash is not None:
intent_fidelity["natural_language_prompt_hash"] = intent_prompt_hash
if spec_traceability_score is not None:
try:
intent_fidelity["spec_traceability_score"] = float(spec_traceability_score)
except ValueError:
pass
if semantic_drift_detected is not None:
intent_fidelity["semantic_drift_detected"] = (
semantic_drift_detected.lower() == "true"
)
if manual_review_required is not None:
intent_fidelity["manual_review_required"] = (
manual_review_required.lower() == "true"
)
if intent_fidelity:
metadata["intent_fidelity"] = intent_fidelity
artifact_paths = _env_nonempty("MUMEI_ARTIFACT_PATHS")
if artifact_paths is not None:
parsed_paths = [
path.strip() for path in artifact_paths.split(",") if path.strip()
]
if parsed_paths:
metadata["artifact_paths"] = parsed_paths
budget_policy_fingerprint = _env_nonempty("MUMEI_BUDGET_POLICY_FINGERPRINT")
if budget_policy_fingerprint is not None:
metadata["budget_policy_fingerprint"] = budget_policy_fingerprint
return metadata
def _harness_env_vars_from_env() -> dict[str, str]:
env_vars: dict[str, str] = {}
for name in (
"MUMEI_HARNESS_CONTRACT",
"MUMEI_INTENT_PROMPT_HASH",
"MUMEI_SPEC_TRACEABILITY_SCORE",
"MUMEI_SEMANTIC_DRIFT_DETECTED",
"MUMEI_MANUAL_REVIEW_REQUIRED",
"MUMEI_ARTIFACT_PATHS",
"MUMEI_BUDGET_POLICY_FINGERPRINT",
):
value = _env_nonempty(name)
if value is not None:
env_vars[name] = value
return env_vars
def _attach_harness_metadata(payload: dict[str, Any]) -> dict[str, Any]:
metadata = _harness_metadata_from_env()
for key, value in metadata.items():
payload.setdefault(key, value)
return payload
@contextmanager
def _temp_source_input(source_code: str):
with tempfile.TemporaryDirectory() as tmpdir:
tmp_path = Path(tmpdir)
source_path = tmp_path / "input.mm"
source_path.write_text(source_code, encoding="utf-8")
yield tmp_path, source_path
@dataclass
class Z3WorkerContext:
worker_id: str
solver_config_fingerprint: str
process: subprocess.Popen | None = None
start_time: float = field(default_factory=time.time)
@dataclass
class VerificationTask:
task_id: str
source_hash: str
cache_key: str
status: str = "pending"
result: dict | None = None
cancel_reason: str | None = None
worker_id: str | None = None
created_at: float = field(default_factory=time.time)
completed_at: float | None = None
class VerificationTaskRegistry:
def __init__(self):
self._tasks: dict[str, VerificationTask] = {}
self._cache: dict[str, dict] = {}
self._lock = threading.RLock()
def register_task(self, source_hash: str, cache_key: str) -> str:
task_id = f"verify-{uuid.uuid4().hex}"
task = VerificationTask(task_id=task_id, source_hash=source_hash, cache_key=cache_key)
with self._lock:
self._tasks[task_id] = task
return task_id
def get_task(self, task_id: str) -> VerificationTask | None:
with self._lock:
return self._tasks.get(task_id)
def complete_task(self, task_id: str, result: dict, cache_result: bool = True):
with self._lock:
task = self._tasks.get(task_id)
if task is None:
return
task.status = "completed"
task.result = result
task.completed_at = time.time()
task.cancel_reason = None
task.worker_id = None
if cache_result:
self._cache[task.cache_key] = result
def cancel_task(self, task_id: str, reason: str):
with self._lock:
task = self._tasks.get(task_id)
if task is None:
return
task.status = "cancelled"
task.cancel_reason = reason
task.completed_at = time.time()
task.worker_id = None
def mark_running(self, task_id: str, worker_id: str):
with self._lock:
task = self._tasks.get(task_id)
if task is None:
return
task.status = "running"
task.worker_id = worker_id
def get_cached_result(self, cache_key: str) -> dict | None:
with self._lock:
return self._cache.get(cache_key)
class Z3WorkerPool:
def __init__(self, max_workers: int = 4, timeout_ms: int = 30000, memory_limit_mb: int = 1024):
self.max_workers = max(1, max_workers)
self.timeout_ms = timeout_ms
self.memory_limit_mb = memory_limit_mb
self._workers = [
Z3WorkerContext(
worker_id=f"z3-worker-{index}",
solver_config_fingerprint=_compute_mcp_solver_config_fingerprint(
timeout_ms,
memory_limit_mb,
),
)
for index in range(self.max_workers)
]
self._available = list(self._workers)
self._busy: dict[str, Z3WorkerContext] = {}
self._task_workers: dict[str, str] = {}
self._condition = threading.Condition()
def acquire_worker(self) -> Z3WorkerContext:
with self._condition:
while not self._available:
self._condition.wait()
worker = self._available.pop(0)
worker.start_time = time.time()
self._busy[worker.worker_id] = worker
return worker
def release_worker(self, worker_id: str):
with self._condition:
worker = self._busy.pop(worker_id, None)
if worker is None:
return
if worker.process is not None and worker.process.poll() is None:
worker.process.terminate()
worker.process = None
self._task_workers = {
task_id: mapped_worker_id
for task_id, mapped_worker_id in self._task_workers.items()
if mapped_worker_id != worker_id
}
self._available.append(worker)
self._condition.notify()
def cancel_task(self, task_id: str):
with self._condition:
worker_id = self._task_workers.get(task_id)
if worker_id is None:
return False
worker = self._busy.get(worker_id)
if worker is None or worker.process is None:
return False
if worker.process.poll() is None:
worker.process.terminate()
return True
def bind_task(self, task_id: str, worker_id: str):
with self._condition:
self._task_workers[task_id] = worker_id
def shutdown(self):
with self._condition:
for worker in self._workers:
if worker.process is not None and worker.process.poll() is None:
worker.process.terminate()
worker.process = None
self._available = list(self._workers)
self._busy.clear()
self._task_workers.clear()
self._condition.notify_all()
def _detect_mcp_solver_features(source_code: str) -> dict[str, bool]:
return {
"has_string_constraints": bool(
re.search(r"\b(Str|string|String)\b|starts_with|ends_with|contains", source_code)
),
"has_array_forall": bool(
re.search(
r"forall\s*\([^\n;)]*\[[^\n;)]*\)|forall\s*\([^)]*\)[^\n;]*\[",
source_code,
re.DOTALL,
)
),
}
def _compute_mcp_solver_config_fingerprint(
timeout_ms: int,
memory_limit_mb: int,
mbqi: bool = True,
has_string_constraints: bool = False,
has_array_forall: bool = False,
enable_spurious_detection: bool = True,
) -> str:
payload = json.dumps(
{
"engine": "mumei-z3",
"timeout_ms": timeout_ms,
"memory_limit_mb": memory_limit_mb,
"smt.mbqi": mbqi,
"string_constraints": has_string_constraints,
"array_forall": has_array_forall,
"spurious_detection": enable_spurious_detection,
},
sort_keys=True,
separators=(",", ":"),
)
return hashlib.sha256(payload.encode("utf-8")).hexdigest()
def _limit_worker_memory(memory_limit_mb: int):
if os.name != "posix":
return None
def _set_limit():
try:
import resource
limit_bytes = memory_limit_mb * 1024 * 1024
resource.setrlimit(resource.RLIMIT_AS, (limit_bytes, limit_bytes))
except (ImportError, OSError, ValueError):
pass
return _set_limit
def _resume_task_validation_error(
task_id: str | None,
resumed_task: VerificationTask | None,
source_hash: str,
cache_key: str,
) -> dict | None:
if task_id is None:
return None
if resumed_task is None:
return {"status": "error", "task_id": task_id, "error": "task_id not found"}
if resumed_task.source_hash != source_hash or resumed_task.cache_key != cache_key:
return {
"status": "error",
"task_id": task_id,
"error": "task_id does not match source_hash or solver configuration",
"expected_source_hash": resumed_task.source_hash,
"requested_source_hash": source_hash,
"expected_cache_key": resumed_task.cache_key,
"requested_cache_key": cache_key,
}
return None
_task_registry = VerificationTaskRegistry()
_z3_worker_pool = Z3WorkerPool()
def _format_data_flow_trace(trace: dict) -> str:
parts = ["### Data Flow Trace"]
parts.append("**Initial State:**")
for var in trace.get("initial_state", []):
parts.append(f"- {var['name']} = {var['value']} (line {var['line']})")
parts.append("\n**Execution Path:**")
for step in trace.get("execution_path", []):
parts.append(f"- Line {step['line']}: {step['expression']}")
for mut in step.get("mutations", []):
parts.append(f" - {mut['name']}: {mut['before']} → {mut['after']}")
violation = trace.get("violation", {})
parts.append(f"\n**Violation at line {violation.get('line')}:**")
parts.append(f"- {violation.get('contract_type')}: {violation.get('expression')}")
parts.append(f"- Evaluated as: {violation.get('evaluated_as')}")
return "\n".join(parts)
def _format_semantic_feedback(report_json: str) -> str:
"""Parse report.json and format semantic_feedback into a readable section.
Returns empty string if no semantic_feedback is present (backward compatible).
Includes a machine_readable JSON block for AI agent consumption."""
try:
report = json.loads(report_json)
except (json.JSONDecodeError, TypeError):
return ""
feedback = report.get("semantic_feedback")
trace = report.get("data_flow_trace")
if not feedback:
if isinstance(trace, dict):
return _format_data_flow_trace(trace)
return ""
parts = ["### Semantic Feedback"]
violated = feedback.get("violated_constraints", [])
for vc in violated:
param = vc.get("param", "?")
typ = vc.get("type", "")
value = vc.get("value", "?")
constraint = vc.get("constraint", "")
explanation = vc.get("explanation", "")
suggestion = vc.get("suggestion", "")
parts.append(f"- **{param}** (type `{typ}`, value `{value}`): constraint `{constraint}` violated")
if explanation:
parts.append(f" - {explanation}")
if suggestion:
parts.append(f" - Suggestion: {suggestion}")
# Sub-constraint decomposition display
sub_constraints = vc.get("sub_constraints", [])
if sub_constraints:
for sc in sub_constraints:
sc_idx = sc.get("index", 0)
sc_total = len(sub_constraints)
sc_raw = sc.get("raw", "")
sc_satisfied = sc.get("satisfied", False)
sc_explanation = sc.get("explanation", "")
status_icon = "\u2705" if sc_satisfied else "\u274c"
status_text = "satisfied" if sc_satisfied else "violated"
line = f" - Sub-constraint [{sc_idx + 1}/{sc_total}] `{sc_raw}`: {status_icon} {status_text}"
if not sc_satisfied and sc_explanation:
line += f" \u2014 {sc_explanation}"
parts.append(line)
# Unsat core: conflicting constraints (contradiction detection)
conflicting = feedback.get("conflicting_constraints", [])
if conflicting:
parts.append("\n**Conflicting Constraints (Unsat Core):**")
for c in conflicting:
parts.append(f"- {c}")
explanation = feedback.get("explanation", "")
if explanation:
parts.append(f"\n {explanation}")
# Linearity violations
violations = feedback.get("violations", [])
for v in violations:
desc = v.get("description", "")
expl = v.get("explanation", "")
if desc:
parts.append(f"- {desc}")
if expl:
parts.append(f" - {expl}")
# Division-by-zero specific
# Check both top-level report and semantic_feedback sub-object for failure_type,
# since build_division_by_zero_feedback embeds failure_type in the feedback object.
report_failure_type = report.get("failure_type", "")
feedback_failure_type = feedback.get("failure_type", "")
effective_failure_type = report_failure_type or feedback_failure_type
if effective_failure_type == "division_by_zero":
# counter_example may be in feedback sub-object (from build_division_by_zero_feedback)
ce = feedback.get("counter_example", {})
if ce:
parts.append(f"- Counter-example: dividend = {ce.get('dividend', '?')}, divisor = {ce.get('divisor', '?')}")
# Effect violations
if effective_failure_type == "effect_not_allowed":
parts.append(f"- Attempted effect: `{feedback.get('attempted_effect', '?')}`")
parts.append(f"- Allowed effects: {feedback.get('allowed_effects', [])}")
parts.append(f"- Missing effects: {feedback.get('missing_effects', [])}")
# Data flow display (Feature 2e)
data_flow = feedback.get("data_flow", [])
if data_flow:
parts.append("\n**Data Flow:**")
for entry in data_flow:
step = entry.get("step", "?")
line = entry.get("line", 0)
col = entry.get("col", 0)
desc = entry.get("description", "")
constraint = entry.get("constraint", "")
flow_line = f"- [{step}] line {line}:{col}"
if desc:
flow_line += f" — {desc}"
if constraint:
flow_line += f" (constraint: `{constraint}`)"
parts.append(flow_line)
# Related locations display (Feature 3g)
related_locations = feedback.get("related_locations", [])
if related_locations:
parts.append("\n**Related Locations:**")
for loc in related_locations:
loc_file = loc.get("file", "?")
loc_line = loc.get("line", 0)
loc_label = loc.get("label", "")
parts.append(f"- {loc_file}:{loc_line} — {loc_label}")
ctx = feedback.get("context", {})
if ctx:
parts.append("\n**Context:**")
if ctx.get("requires"):
parts.append(f"- requires: `{ctx['requires']}`")
if ctx.get("ensures"):
parts.append(f"- ensures: `{ctx['ensures']}`")
if effective_failure_type:
parts.append(f"\n**Failure type:** `{effective_failure_type}`")
suggestion = report.get("suggestion", "")
if suggestion:
parts.append(f"**Suggestion:** {suggestion}")
span = report.get("span")
if span:
parts.append(f"**Location:** {span.get('file', '?')}:{span.get('line', '?')}:{span.get('col', '?')}")
if isinstance(trace, dict):
parts.append(_format_data_flow_trace(trace))
# Machine-readable section for AI agents
machine_readable = _build_machine_readable(report, feedback)
if machine_readable:
parts.append(f"\n### Machine Readable\n```json\n{json.dumps(machine_readable, indent=2)}\n```")
return "\n".join(parts)
def _build_machine_readable(report: dict, feedback: dict) -> "dict | None":
"""Build a machine-readable JSON block from report and feedback for AI agents."""
failure_type = report.get("failure_type", "")
if not failure_type:
return None
result = {
"failure_type": failure_type,
"atom": report.get("atom", ""),
}
span = report.get("span", {})
if span:
result["file"] = span.get("file", "")
result["line"] = span.get("line", 0)
violated = feedback.get("violated_constraints", [])
if violated:
actions = []
for vc in violated:
action = {
"action": "fix_constraint",
"param": vc.get("param", ""),
"current_value": vc.get("value", ""),
"constraint": vc.get("constraint", ""),
}
# Include sub_constraints in machine-readable output
if vc.get("sub_constraints"):
action["sub_constraints"] = vc["sub_constraints"]
actions.append(action)
result["actions"] = actions
if feedback.get("counter_example"):
result["counter_example"] = feedback["counter_example"]
conflicting = feedback.get("conflicting_constraints", [])
if conflicting:
result["conflicting_constraints"] = conflicting
result["raw_unsat_core"] = feedback.get("raw_unsat_core", [])
# Include data_flow in machine-readable output (Feature 2e)
data_flow = feedback.get("data_flow", [])
if data_flow:
result["data_flow"] = data_flow
data_flow_trace = report.get("data_flow_trace")
if data_flow_trace:
result["data_flow_trace"] = data_flow_trace
# Include related_locations in machine-readable output (Feature 3g)
related_locations = feedback.get("related_locations", [])
if related_locations:
result["related_locations"] = related_locations
result["suggestion"] = report.get("suggestion", "")
return result
def _structured_feedback_from_report(report_json: str) -> dict:
try:
report = json.loads(report_json)
except (json.JSONDecodeError, TypeError):
return {
"status": "verification_failed",
"error_type": None,
"location": None,
"reconstruction_loss": None,
"feedback_instruction": "Verification failed. Review the verifier report and repair the atom.",
}
structured_feedback = report.get("structured_feedback")
if isinstance(structured_feedback, dict):
return structured_feedback
failure_type = report.get("failure_type")
span = report.get("span") if isinstance(report.get("span"), dict) else {}
location = None
if span:
location = {
"file": span.get("file", ""),
"line": span.get("line", 0),
}
semantic_feedback = report.get("semantic_feedback")
reconstruction_loss = None
if isinstance(semantic_feedback, dict):
reconstruction_loss = semantic_feedback.get("reconstruction_loss")
failure_type = failure_type or semantic_feedback.get("failure_type")
violation_type = report.get("violation_type")
if not failure_type and isinstance(violation_type, str):
failure_type = (
"effect_not_allowed"
if violation_type.startswith("effect_")
else violation_type
)
passed = report.get("status") in {"success", "passed", "verified", "trusted", "unverified"}
suggestion = report.get("suggestion") or "Review the verifier report and repair the atom."
return {
"status": "verification_passed" if passed else "verification_failed",
"error_type": None if passed else failure_type,
"location": location,
"reconstruction_loss": reconstruction_loss,
"feedback_instruction": (
"Verification passed; no fix is required." if passed else suggestion
),
}
def _normalize_spec_metadata(spec_metadata: Optional[Dict[str, str]] = None) -> dict:
if spec_metadata is None:
return {}
if isinstance(spec_metadata, str):
try:
parsed = json.loads(spec_metadata)
except json.JSONDecodeError:
return {"value": spec_metadata}
if isinstance(parsed, dict):
spec_metadata = parsed
else:
return {"value": str(parsed)}
if not isinstance(spec_metadata, dict):
return {"value": str(spec_metadata)}
return {str(key): str(value) for key, value in spec_metadata.items()}
def _traceability_payload(
source_code: str,
trace_id: Optional[str] = None,
spec_metadata: Optional[Dict[str, str]] = None,
) -> dict:
normalized_metadata = _normalize_spec_metadata(spec_metadata)
requires = re.findall(r"\brequires\s*:\s*([^;]*);", source_code, re.S)
ensures = re.findall(r"\bensures\s*:\s*([^;]*);", source_code, re.S)
hasher = hashlib.sha256()
hasher.update((trace_id or "").encode("utf-8"))
for key, value in sorted(normalized_metadata.items()):
hasher.update(key.encode("utf-8"))
hasher.update(b"=")
hasher.update(value.encode("utf-8"))
hasher.update(b";")
hasher.update(" && ".join(item.strip() for item in requires).encode("utf-8"))
hasher.update(" && ".join(item.strip() for item in ensures).encode("utf-8"))
covered = sum([
bool((trace_id or "").strip()),
bool(normalized_metadata),
any(item.strip() and item.strip() != "true" for item in requires),
any(item.strip() and item.strip() != "true" for item in ensures),
])
return {
"trace_id": trace_id or None,
"spec_metadata": normalized_metadata,
"traceability_hash": hasher.hexdigest(),
"traceability_coverage": covered / 4.0,
}
def _traceability_env(trace_payload: dict) -> dict:
env = os.environ.copy()
if trace_payload["trace_id"]:
env["MUMEI_TRACE_ID"] = trace_payload["trace_id"]
env["MUMEI_SPEC_METADATA"] = json.dumps(trace_payload["spec_metadata"], sort_keys=True)
return env
def _format_traceability_feedback(trace_payload: dict) -> str:
return "### Traceability\n```json\n" + json.dumps(trace_payload, indent=2, sort_keys=True) + "\n```"
def _format_effect_feedback(report_json: str) -> str:
"""Format effect-specific violation feedback from report.json.
Returns empty string if no effect violation is present.
Handles both mismatch (required_effect/source_operation) and
propagation (caller/callee/missing_effects) violation structures."""
try:
report = json.loads(report_json)
except (json.JSONDecodeError, TypeError):
return ""
effect_violation = report.get("effect_violation")
if not effect_violation:
return ""
parts = ["### Effect Violation Details"]
violation_type = report.get("violation_type", "")
if violation_type == "effect_propagation":
# save_effect_propagation_report structure: caller/callee/missing_effects
parts.append(f"- **Caller atom:** `{effect_violation.get('caller', '?')}`")
parts.append(f"- **Callee atom:** `{effect_violation.get('callee', '?')}`")
parts.append(f"- **Caller declared effects:** {effect_violation.get('caller_effects', [])}")
parts.append(f"- **Callee required effects:** {effect_violation.get('callee_effects', [])}")
parts.append(f"- **Missing effects:** {effect_violation.get('missing_effects', [])}")
else:
# save_effect_violation_report structure (effect_mismatch): required_effect/source_operation
parts.append(f"- **Declared effects:** {effect_violation.get('declared_effects', [])}")
parts.append(f"- **Required effect:** `{effect_violation.get('required_effect', '?')}`")
parts.append(f"- **Source operation:** `{effect_violation.get('source_operation', '?')}`")
suggested_fixes = effect_violation.get("suggested_fixes", [])
if suggested_fixes:
parts.append("\n**Suggested Fixes:**")
for fix in suggested_fixes:
parts.append(f"- {fix}")
resolution_paths = effect_violation.get("resolution_paths", [])
if resolution_paths:
parts.append("\n**Resolution Paths:**")
for rp in resolution_paths:
parts.append(f"- **{rp.get('strategy', '?')}**: {rp.get('description', '')}")
return "\n".join(parts)
@mcp.tool()
def forge_blade(
source_code: str,
output_name: str = "katana",
trace_id: Optional[str] = None,
spec_metadata: Optional[Dict[str, str]] = None,
) -> str:
"""
Verify Mumei code and generate LLVM IR output.
The build command writes report.json to the -o directory, so reports are isolated per request.
Optional trace_id/spec_metadata are forwarded into proof certificates.
"""
trace_payload = _traceability_payload(source_code, trace_id, spec_metadata)
# 1. Create fully isolated temp directory per request
with _temp_source_input(source_code) as (tmp_path, source_path):
# 2. Run compiler (output to temp directory)
output_base = tmp_path / output_name
result = subprocess.run(
["cargo", "run", "--", "build", str(source_path), "-o", str(output_base)],
cwd=REPO_ROOT,
capture_output=True,
text=True,
env=_traceability_env(trace_payload),
)
response_parts = [_format_traceability_feedback(trace_payload)]
# Inject effect boundary context if restricted
effects_ctx = json.loads(get_allowed_effects(str(REPO_ROOT)))
if not effects_ctx.get("unrestricted", True):
response_parts.append(
f"### Effect Boundary\n{effects_ctx['summary']}\n"
)
# report.json is written to output_dir (parent of -o path) = tmp_path
report_file = tmp_path / "report.json"
if report_file.exists():
report_data = report_file.read_text(encoding="utf-8")
response_parts.append(f"### Verification Report\n```json\n{report_data}\n```")
# Include semantic feedback section (always present for AI agents)
sf_section = _format_semantic_feedback(report_data)
if sf_section:
response_parts.append(sf_section)
else:
response_parts.append(
'### Semantic Feedback\n'
'```json\n{"status": "all_constraints_satisfied"}\n```'
)
# Include effect-specific feedback if present
ef_section = _format_effect_feedback(report_data)
if ef_section:
response_parts.append(ef_section)
structured_feedback = _structured_feedback_from_report(report_data)
response_parts.append(
"### Structured Feedback\n```json\n"
+ json.dumps(structured_feedback, indent=2)
+ "\n```"
)
else:
response_parts.append(
'### Semantic Feedback\n'
'```json\n{"status": "no_report_available"}\n```'
)
if result.returncode == 0:
response_parts.insert(0, f"Forge succeeded: '{output_name}'")
# Collect generated per-atom LLVM IR artifacts (e.g. katana_increment.ll)
for ll_file in sorted(tmp_path.glob(f"{output_name}*.ll")):
content = ll_file.read_text(encoding="utf-8")
response_parts.append(f"\n### Generated: {ll_file.name}\n```llvm\n{content}\n```")
return "\n".join(response_parts)
else:
# On failure: return evidence (report) and error log together
response_parts.insert(0, f"Forge failed: logical flaw detected.")
if result.stderr:
response_parts.append(f"\n### Error Details\n{result.stderr}")
return "\n".join(response_parts)
@mcp.tool()
def validate_logic(
source_code: str,
trace_id: Optional[str] = None,
spec_metadata: Optional[Dict[str, str]] = None,
) -> str:
"""
Run formal verification (Z3) only on Mumei code.
No code generation — returns verification results and counter-examples.
Used as the verification step when AI iteratively fixes .mm code.
Uses --report-dir to write report.json directly into a per-request temp
directory, making concurrent calls safe.
Optional trace_id/spec_metadata are forwarded into proof certificates.
"""
trace_payload = _traceability_payload(source_code, trace_id, spec_metadata)
with _temp_source_input(source_code) as (tmp_path, source_path):
# Run mumei verify with --report-dir to write report.json directly
# into the per-request temp directory (concurrent-safe).
result = subprocess.run(
["cargo", "run", "--", "verify",
"--report-dir", str(tmp_path),
str(source_path)],
cwd=REPO_ROOT,
capture_output=True,
text=True,
env=_traceability_env(trace_payload),
)
response_parts = [_format_traceability_feedback(trace_payload)]
# Inject effect boundary context if restricted
effects_ctx = json.loads(get_allowed_effects(str(REPO_ROOT)))
if not effects_ctx.get("unrestricted", True):
response_parts.append(
f"### Effect Boundary\n{effects_ctx['summary']}\n"
)
report_file = tmp_path / "report.json"
if report_file.exists():
report_data = report_file.read_text(encoding="utf-8")
response_parts.append(
f"### Verification Report\n```json\n{report_data}\n```"
)
# Include semantic feedback section (always present for AI agents)
sf_section = _format_semantic_feedback(report_data)
if sf_section:
response_parts.append(sf_section)
else:
# Even on success, include a semantic_feedback status for AI agents
response_parts.append(
'### Semantic Feedback\n'
'```json\n{"status": "all_constraints_satisfied"}\n```'
)
# Include effect-specific feedback if present
ef_section = _format_effect_feedback(report_data)
if ef_section:
response_parts.append(ef_section)
structured_feedback = _structured_feedback_from_report(report_data)
response_parts.append(
"### Structured Feedback\n```json\n"
+ json.dumps(structured_feedback, indent=2)
+ "\n```"
)
else:
# No report file — still include semantic feedback status
response_parts.append(
'### Semantic Feedback\n'
'```json\n{"status": "no_report_available"}\n```'
)
# Extract Z3 counter-example info from stderr
if result.stderr:
counterexamples = re.findall(
r'Counter-example:.*', result.stderr
)
if counterexamples:
response_parts.append("### Z3 Counter-examples")
for ce in counterexamples:
response_parts.append(f"- `{ce.strip()}`")
if result.returncode == 0:
response_parts.insert(
0, "Verification passed: no logical flaws detected."
)
else:
response_parts.insert(
0, "Verification failed: logical flaw detected."
)
if result.stderr:
response_parts.append(
f"\n### Error Details\n```\n{result.stderr}\n```"
)
return "\n".join(response_parts)
@mcp.tool()
def get_structured_feedback(source_code: str) -> str:
"""Return the P9-E structured feedback JSON for Mumei source code."""
with _temp_source_input(source_code) as (tmp_path, source_path):
output_path = tmp_path / "structured_feedback.json"
result = subprocess.run(
[
"cargo",
"run",
"--",
"verify",
"--emit",
"structured-feedback",
"--output",
str(output_path),