letitloop 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (175) hide show
  1. letitloop-0.2.0.dist-info/METADATA +232 -0
  2. letitloop-0.2.0.dist-info/RECORD +175 -0
  3. letitloop-0.2.0.dist-info/WHEEL +5 -0
  4. letitloop-0.2.0.dist-info/entry_points.txt +4 -0
  5. letitloop-0.2.0.dist-info/licenses/LICENSE +21 -0
  6. letitloop-0.2.0.dist-info/top_level.txt +1 -0
  7. orchestrator/SKILL.md +292 -0
  8. orchestrator/__init__.py +151 -0
  9. orchestrator/anti_ouroboros.py +78 -0
  10. orchestrator/approval.py +139 -0
  11. orchestrator/ast_node_splicer.py +130 -0
  12. orchestrator/ast_splicer.py +94 -0
  13. orchestrator/audit.py +88 -0
  14. orchestrator/budget.py +195 -0
  15. orchestrator/checkpoint.py +248 -0
  16. orchestrator/cli.py +1971 -0
  17. orchestrator/codebase_introspector.py +66 -0
  18. orchestrator/component_slicer.py +185 -0
  19. orchestrator/config.py +152 -0
  20. orchestrator/contract.py +404 -0
  21. orchestrator/dag_validator.py +172 -0
  22. orchestrator/elasticity_governor.py +80 -0
  23. orchestrator/env_doctor.py +166 -0
  24. orchestrator/errors.py +211 -0
  25. orchestrator/events.py +120 -0
  26. orchestrator/evidence.py +203 -0
  27. orchestrator/exceptions.py +37 -0
  28. orchestrator/experimental/arena_arbiter.py +260 -0
  29. orchestrator/experimental/fuzz_engine.py +206 -0
  30. orchestrator/experimental/mutation_tester.py +382 -0
  31. orchestrator/failure.py +226 -0
  32. orchestrator/fast_sandbox.py +126 -0
  33. orchestrator/feasibility_gate.py +115 -0
  34. orchestrator/feedback.py +302 -0
  35. orchestrator/fixtures/__init__.py +0 -0
  36. orchestrator/fixtures/example_contract.json +50 -0
  37. orchestrator/fixtures/generated/evidence-cli-run-test-step-1.json +47 -0
  38. orchestrator/fixtures/generated/evidence-cli-run-test-step-2.json +47 -0
  39. orchestrator/fixtures/generated/evidence-inject-test-a.json +47 -0
  40. orchestrator/fixtures/generated/evidence-inject-test-b.json +47 -0
  41. orchestrator/fixtures/generated/evidence-inject-test-c.json +47 -0
  42. orchestrator/fixtures/generated/evidence-json-test-a.json +47 -0
  43. orchestrator/fixtures/generated/evidence-json-test-b.json +47 -0
  44. orchestrator/fixtures/generated/fail-report-fail-task-1.json +47 -0
  45. orchestrator/fixtures/generated/fail-report-json-task-1.json +47 -0
  46. orchestrator/fixtures/generated/fail-report-success-task-1.json +47 -0
  47. orchestrator/fixtures/generated/fuzz-engine-design.json +63 -0
  48. orchestrator/fixtures/generated/fuzz-engine-impl.json +62 -0
  49. orchestrator/fixtures/generated/fuzz-engine-tests.json +62 -0
  50. orchestrator/fixtures/generated/fuzz-engine-verify.json +62 -0
  51. orchestrator/fixtures/generated/goal-orch-step-1.json +63 -0
  52. orchestrator/fixtures/generated/goal-orch-step-2.json +62 -0
  53. orchestrator/fixtures/generated/goal-orch-step-3.json +62 -0
  54. orchestrator/fixtures/generated/goal-orch-step-4.json +62 -0
  55. orchestrator/fixtures/generated/goal-orch-step-5.json +62 -0
  56. orchestrator/fixtures/generated/goal-orch-step-6.json +63 -0
  57. orchestrator/fixtures/generated/implement-a-thread-safe-token-bucket-rat-task-1.json +53 -0
  58. orchestrator/fixtures/generated/orchestrator-checkpoint-rollback-3.json +63 -0
  59. orchestrator/fixtures/generated/orchestrator-checkpoint-rollback.json +62 -0
  60. orchestrator/fixtures/generated/orchestrator-live-telemetry-2.json +62 -0
  61. orchestrator/fixtures/generated/orchestrator-live-telemetry.json +62 -0
  62. orchestrator/fixtures/generated/orchestrator-spec-synthesis-1.json +62 -0
  63. orchestrator/fixtures/generated/orchestrator-spec-synthesis.json +62 -0
  64. orchestrator/fixtures/generated/orchestrator-test-verification-4.json +62 -0
  65. orchestrator/fixtures/generated/orchestrator-test-verification.json +62 -0
  66. orchestrator/fixtures/generated/perf-step-1.json +61 -0
  67. orchestrator/fixtures/generated/perf-step-2.json +62 -0
  68. orchestrator/fixtures/generated/perf-step-3.json +62 -0
  69. orchestrator/fixtures/generated/perf-step-4.json +62 -0
  70. orchestrator/fixtures/generated/perf-step-5.json +63 -0
  71. orchestrator/fixtures/generated/phase2-proof-two-step-step-1.json +47 -0
  72. orchestrator/fixtures/generated/phase2-proof-two-step-step-2.json +47 -0
  73. orchestrator/fixtures/generated/planner-spec-synthesis-impl.json +59 -0
  74. orchestrator/fixtures/generated/self-evolution-ast-formatter.json +69 -0
  75. orchestrator/fixtures/generated/self-evolution-checkpoint-rollback.json +70 -0
  76. orchestrator/fixtures/generated/self-evolution-spec-synthesis.json +70 -0
  77. orchestrator/fixtures/generated/self-evolution-step-1.json +70 -0
  78. orchestrator/fixtures/generated/self-evolution-step-2.json +70 -0
  79. orchestrator/fixtures/generated/self-evolution-step-3.json +70 -0
  80. orchestrator/fixtures/generated/self-evolution-step-4.json +70 -0
  81. orchestrator/fixtures/generated/self-evolution-step-5.json +65 -0
  82. orchestrator/fixtures/generated/self-evolution-telemetry.json +70 -0
  83. orchestrator/fixtures/generated/self-evolution-tests.json +71 -0
  84. orchestrator/fixtures/generated/spec-telemetry-research-design.json +64 -0
  85. orchestrator/fixtures/generated/spec-telemetry-step-1.json +62 -0
  86. orchestrator/fixtures/generated/spec-telemetry-step-2.json +62 -0
  87. orchestrator/fixtures/generated/spec-telemetry-step-3.json +62 -0
  88. orchestrator/fixtures/generated/spec-telemetry-step-4.json +62 -0
  89. orchestrator/fixtures/generated/spec-telemetry-step-5.json +62 -0
  90. orchestrator/fixtures/generated/spec-telemetry-verification.json +58 -0
  91. orchestrator/fixtures/generated/token-bucket-impl.json +69 -0
  92. orchestrator/fixtures/generated/token-bucket-step-1.json +70 -0
  93. orchestrator/fixtures/generated/token-bucket-step-2.json +70 -0
  94. orchestrator/fixtures/generated/token-bucket-step-3.json +60 -0
  95. orchestrator/fixtures/generated/token-bucket-tests.json +70 -0
  96. orchestrator/fixtures/generated/token-bucket-verify.json +61 -0
  97. orchestrator/fixtures/generated/trace-ux-tests-step-1.json +64 -0
  98. orchestrator/fixtures/generated/trace-ux-tests-step-2.json +64 -0
  99. orchestrator/fixtures/generated/trace-ux-tests-step-3.json +62 -0
  100. orchestrator/fixtures/generated/tui-live-telemetry-impl.json +59 -0
  101. orchestrator/fixtures/phase1_proof_escalation_contract.json +41 -0
  102. orchestrator/fixtures/phase1_proof_happy_path_contract.json +83 -0
  103. orchestrator/fixtures/phase1_proof_qc_contract.json +41 -0
  104. orchestrator/fixtures/phase1_proof_repair_contract.json +41 -0
  105. orchestrator/fixtures/phase2_proof_two_step_goal.json +15 -0
  106. orchestrator/fixtures/run_proofs.py +299 -0
  107. orchestrator/fixtures/test_normalizer.py +16 -0
  108. orchestrator/generator.py +239 -0
  109. orchestrator/goal.py +245 -0
  110. orchestrator/handoff.py +86 -0
  111. orchestrator/hybrid_worker.py +840 -0
  112. orchestrator/impossibility.py +162 -0
  113. orchestrator/limits.py +60 -0
  114. orchestrator/live_evolution_engine.py +247 -0
  115. orchestrator/llm.py +291 -0
  116. orchestrator/local_tool_calling.py +285 -0
  117. orchestrator/lock.py +404 -0
  118. orchestrator/mcp_client.py +571 -0
  119. orchestrator/mcp_server.py +344 -0
  120. orchestrator/memory_bridge.py +182 -0
  121. orchestrator/metrics.py +159 -0
  122. orchestrator/micro_epoch.py +42 -0
  123. orchestrator/models.py +350 -0
  124. orchestrator/parsing.py +237 -0
  125. orchestrator/patch_applier.py +154 -0
  126. orchestrator/plan_preview.py +138 -0
  127. orchestrator/plan_quality.py +357 -0
  128. orchestrator/planner.py +532 -0
  129. orchestrator/preferences.py +115 -0
  130. orchestrator/preflight.py +141 -0
  131. orchestrator/process_guard.py +357 -0
  132. orchestrator/prometheus_exporter.py +207 -0
  133. orchestrator/prompts.py +275 -0
  134. orchestrator/proposal_ledger.py +194 -0
  135. orchestrator/provenance.py +263 -0
  136. orchestrator/provider_scheduler.py +394 -0
  137. orchestrator/qc/__init__.py +153 -0
  138. orchestrator/qc/aggregator.py +330 -0
  139. orchestrator/qc/parsing.py +287 -0
  140. orchestrator/qc/personas.py +242 -0
  141. orchestrator/qc/runner.py +569 -0
  142. orchestrator/qc_overrule.py +87 -0
  143. orchestrator/qc_review.py +282 -0
  144. orchestrator/quality_lenses.py +314 -0
  145. orchestrator/quality_plan.py +449 -0
  146. orchestrator/quality_plane.py +103 -0
  147. orchestrator/reconcile.py +191 -0
  148. orchestrator/replanner.py +433 -0
  149. orchestrator/research.py +176 -0
  150. orchestrator/review_artifact.py +672 -0
  151. orchestrator/safety.py +271 -0
  152. orchestrator/schemas.py +230 -0
  153. orchestrator/scope.py +466 -0
  154. orchestrator/sensory_radar.py +79 -0
  155. orchestrator/skill_installer.py +140 -0
  156. orchestrator/sse_server.py +160 -0
  157. orchestrator/state.py +871 -0
  158. orchestrator/subprocess_helper.py +131 -0
  159. orchestrator/supervisor/__init__.py +184 -0
  160. orchestrator/supervisor/_shared.py +164 -0
  161. orchestrator/supervisor/cleanup.py +185 -0
  162. orchestrator/supervisor/core.py +1680 -0
  163. orchestrator/supervisor/recovery.py +367 -0
  164. orchestrator/supervisor/reporting.py +251 -0
  165. orchestrator/surgical_extractor.py +119 -0
  166. orchestrator/telemetry.py +61 -0
  167. orchestrator/templates.py +268 -0
  168. orchestrator/token_gate.py +245 -0
  169. orchestrator/tui.py +649 -0
  170. orchestrator/verifier.py +1103 -0
  171. orchestrator/webhooks.py +168 -0
  172. orchestrator/worker.py +469 -0
  173. orchestrator/worker_adapters.py +815 -0
  174. orchestrator/worker_pool.py +121 -0
  175. orchestrator/worktree.py +364 -0
@@ -0,0 +1,275 @@
1
+ """Prompt templates for hybrid worker Implementer and Critic roles."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any, Dict, List, Optional
6
+
7
+
8
+ def build_implementer_prompt(
9
+ title: str,
10
+ objective: str,
11
+ output_paths: List[str],
12
+ acceptance_summary: str,
13
+ prior_failures: Optional[List[Dict[str, Any]]] = None,
14
+ critic_feedback: Optional[str] = None,
15
+ verifier_feedback: Optional[str] = None,
16
+ max_turns: int = 3,
17
+ current_turn: int = 1,
18
+ quality_spec: Optional[Dict[str, Any]] = None,
19
+ supervisor_attempt: int = 1,
20
+ strategy_fingerprint: str = "",
21
+ prior_fingerprint: str = "",
22
+ ) -> str:
23
+ """Build a strict bounded prompt for the Implementer role.
24
+
25
+ The Implementer must return JSON-formatted file artifacts.
26
+ No prose, no explanation, no extra files.
27
+ """
28
+ parts = [
29
+ "SYSTEM: You are the Implementer. Your job is to produce file content only.",
30
+ "",
31
+ "RULES:",
32
+ "- Return ONLY valid JSON matching the schema below.",
33
+ "- No markdown fences around the JSON.",
34
+ "- No explanatory text before or after.",
35
+ "- Write complete file content. Do not use placeholders.",
36
+ "- Do not add extra files beyond the required output paths.",
37
+ "",
38
+ ]
39
+
40
+ parts.extend(
41
+ [
42
+ f"TASK: {title}",
43
+ f"OBJECTIVE: {objective}",
44
+ "",
45
+ "REQUIRED OUTPUT PATHS:",
46
+ ]
47
+ )
48
+ for p in output_paths:
49
+ parts.append(f" - {p}")
50
+ parts.append("")
51
+
52
+ parts.extend(
53
+ [
54
+ "ACCEPTANCE CRITERIA:",
55
+ acceptance_summary,
56
+ "",
57
+ ]
58
+ )
59
+
60
+ if quality_spec:
61
+ parts.append("QUALITY SPECIFICATION:")
62
+ if quality_spec.get("required_sections"):
63
+ parts.append(f" Required sections: {quality_spec['required_sections']}")
64
+ if quality_spec.get("quality_dimensions"):
65
+ parts.append(f" Quality dimensions: {quality_spec['quality_dimensions']}")
66
+ if quality_spec.get("hard_failures"):
67
+ parts.append(f" Hard failures: {quality_spec['hard_failures']}")
68
+ if quality_spec.get("minimum_score"):
69
+ parts.append(f" Target minimum score: {quality_spec['minimum_score']}")
70
+ parts.append("")
71
+
72
+ # prior_failures describe a PREVIOUS SUPERVISOR attempt (only exist on
73
+ # attempt > 1) — gate them. critic/verifier feedback is repair-TURN
74
+ # feedback within the current attempt and must always be injected.
75
+ if supervisor_attempt > 1 and prior_failures:
76
+ parts.append("PREVIOUS SUPERVISOR ATTEMPT FAILED:")
77
+ for f in prior_failures:
78
+ msg = f.get("message", str(f))
79
+ parts.append(f" - {msg}")
80
+ parts.append("")
81
+
82
+ # Perpetual-loop r2: if the failure signature is identical to the prior
83
+ # attempt, the retry is structurally the same — demand a real change.
84
+ if (
85
+ supervisor_attempt > 1
86
+ and prior_fingerprint
87
+ and strategy_fingerprint
88
+ and prior_fingerprint == strategy_fingerprint
89
+ ):
90
+ parts.append("RETRY WAS IDENTICAL: adjust the approach — same failure signature as the prior attempt")
91
+ parts.append("")
92
+
93
+ # Deterministic attempt-indexed directives — cheaper and safer than AST
94
+ # fingerprinting.
95
+ # cheaper and safer than AST fingerprinting.
96
+ if supervisor_attempt == 2:
97
+ parts.append(
98
+ "RETRY GUIDANCE (attempt 2): do not repeat the prior approach. First state the changed strategy, then decompose the failing logic explicitly."
99
+ )
100
+ parts.append("")
101
+ elif supervisor_attempt >= 3:
102
+ parts.append(
103
+ "RETRY GUIDANCE (attempt 3+): apply a minimal defensive patch. Remove speculative rewrites and preserve already-passing behavior."
104
+ )
105
+ parts.append("")
106
+
107
+ def _truncate_feedback(fb: str, max_chars: int = 600) -> str:
108
+ if not fb or len(fb) <= max_chars:
109
+ return fb
110
+ head = fb[: max_chars // 2]
111
+ tail = fb[-max_chars // 2 :]
112
+ return f"{head}\n... [truncated] ...\n{tail}"
113
+
114
+ if critic_feedback:
115
+ parts.append("CRITIC FEEDBACK FROM LAST TURN:")
116
+ parts.append(f" {_truncate_feedback(critic_feedback)}")
117
+ parts.append("")
118
+
119
+ if verifier_feedback:
120
+ parts.append("VERIFIER FEEDBACK FROM LAST TURN:")
121
+ parts.append(f" {_truncate_feedback(verifier_feedback)}")
122
+ parts.append("")
123
+
124
+ parts.extend(
125
+ [
126
+ f"SUPERVISOR ATTEMPT {supervisor_attempt}; TURN {current_turn} of {max_turns}.",
127
+ "",
128
+ "OUTPUT SCHEMA (Search/Replace Delta Blocks):",
129
+ "To edit existing code, return ONLY Search/Replace delta blocks:",
130
+ "<<<<<<< SEARCH",
131
+ "[exact lines from original file to replace]",
132
+ "=======",
133
+ "[new replacement lines]",
134
+ ">>>>>>> REPLACE",
135
+ "",
136
+ "Alternatively, for brand-new files only, return JSON:",
137
+ "[",
138
+ ' {"path": "relative/path.ext", "content": "complete file content"}',
139
+ "]",
140
+ "",
141
+ "Return ONLY the requested output format. No markdown commentary outside fences.",
142
+ "",
143
+ "[CONTEXT_COMPLETE]",
144
+ ]
145
+ )
146
+
147
+ return "\n".join(parts)
148
+
149
+
150
+ def build_critic_prompt(
151
+ title: str,
152
+ objective: str,
153
+ output_paths: List[str],
154
+ acceptance_summary: str,
155
+ artifact_summaries: List[Dict[str, Any]],
156
+ verifier_results: Optional[List[Dict[str, Any]]] = None,
157
+ quality_spec: Optional[Dict[str, Any]] = None,
158
+ ) -> str:
159
+ """Build an adversarial critic prompt.
160
+
161
+ The Critic must return PASS/FAIL JSON.
162
+ Evidence-first reasoning. No praise. No implementation.
163
+ """
164
+ parts = [
165
+ "SYSTEM: You are an adversarial code reviewer (the Critic).",
166
+ "",
167
+ "RULES:",
168
+ "- Evaluate whether the proposed artifacts satisfy the task objective, quality spec, and acceptance criteria.",
169
+ "- Assume all submitted artifacts contain subtle defects until proven otherwise.",
170
+ "- Cite exact file paths and specific content in your findings.",
171
+ "- Return ONLY valid JSON matching the schema below.",
172
+ "- No markdown fences around the JSON.",
173
+ "- No explanatory text.",
174
+ "",
175
+ ]
176
+
177
+ parts.extend(
178
+ [
179
+ f"TASK: {title}",
180
+ f"OBJECTIVE: {objective}",
181
+ "",
182
+ "REQUIRED OUTPUT PATHS:",
183
+ ]
184
+ )
185
+ for p in output_paths:
186
+ parts.append(f" - {p}")
187
+ parts.append("")
188
+
189
+ parts.extend(
190
+ [
191
+ "ACCEPTANCE CRITERIA:",
192
+ acceptance_summary,
193
+ "",
194
+ ]
195
+ )
196
+
197
+ if quality_spec:
198
+ parts.append("QUALITY SPECIFICATION:")
199
+ if quality_spec.get("required_sections"):
200
+ parts.append(f" Required sections: {quality_spec['required_sections']}")
201
+ if quality_spec.get("quality_dimensions"):
202
+ parts.append(f" Quality dimensions: {quality_spec['quality_dimensions']}")
203
+ if quality_spec.get("hard_failures"):
204
+ parts.append(f" Hard failures: {quality_spec['hard_failures']}")
205
+ if quality_spec.get("minimum_score"):
206
+ parts.append(f" Minimum score: {quality_spec['minimum_score']}")
207
+ parts.append("")
208
+
209
+ parts.append("PROPOSED ARTIFACTS:")
210
+ for a in artifact_summaries:
211
+ path = a.get("path", "?")
212
+ content = a.get("content", "")
213
+ preview = content[:2000] if content else "(empty)"
214
+ parts.append(f"--- {path} ---")
215
+ parts.append(preview)
216
+ parts.append("")
217
+ if len(content) > 2000:
218
+ parts.append(f"[truncated, full length: {len(content)} chars]")
219
+ parts.append("")
220
+
221
+ if verifier_results:
222
+ parts.append("DETERMINISTIC VERIFIER RESULTS:")
223
+ for r in verifier_results:
224
+ status = "PASS" if r.get("passed") else "FAIL"
225
+ parts.append(f" [{status}] {r.get('check_id', '?')}: {r.get('message', '')}")
226
+ parts.append("")
227
+
228
+ parts.extend(
229
+ [
230
+ "OUTPUT SCHEMA:",
231
+ "{",
232
+ ' "status": "PASS" or "FAIL" or "INSUFFICIENT_EVIDENCE",',
233
+ ' "summary": "One-line audit summary",',
234
+ ' "score": 0.0-1.0,',
235
+ ' "issues": [',
236
+ " {",
237
+ ' "severity": "CRITICAL" | "MAJOR" | "MINOR",',
238
+ ' "location": "path:line",',
239
+ ' "description": "...",',
240
+ ' "suggested_remediation": "..."',
241
+ " }",
242
+ " ],",
243
+ ' "implementer_guidance": "Short actionable instruction for repair"',
244
+ "}",
245
+ "",
246
+ "Return ONLY valid JSON in the above format. No markdown. No commentary.",
247
+ "Cap issues to top 3 severity items. If PASS, issues should be empty.",
248
+ "If you cannot determine quality from evidence, return INSUFFICIENT_EVIDENCE.",
249
+ "",
250
+ "[CONTEXT_COMPLETE]",
251
+ ]
252
+ )
253
+
254
+ return "\n".join(parts)
255
+
256
+
257
+ def summarize_acceptance(checks: List[Dict[str, Any]]) -> str:
258
+ """Compact one-line-per-check summary of acceptance criteria."""
259
+ lines = []
260
+ for c in checks:
261
+ kind = c.get("kind", "?")
262
+ path = c.get("path", c.get("command", ""))
263
+ exp = c.get("expected", "")
264
+ exp_str = f" expected={exp}" if exp else ""
265
+ lines.append(f" [{kind}] {path}{exp_str}")
266
+ return "\n".join(lines)
267
+
268
+
269
+ def summarize_verifier_results(results: List[Dict[str, Any]]) -> str:
270
+ """Compact summary of deterministic verifier outcomes."""
271
+ lines = []
272
+ for r in results:
273
+ status = "PASS" if r.get("passed") else "FAIL"
274
+ lines.append(f" [{status}] {r.get('check_id', '?')}: {r.get('message', '')}")
275
+ return "\n".join(lines)
@@ -0,0 +1,194 @@
1
+ """
2
+ orchestrator/proposal_ledger.py
3
+ Human-in-the-Loop (HITL) Architectural Proposal Ledger & Escalation Manager.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import json
9
+ import re
10
+ import time
11
+ from dataclasses import asdict, dataclass, field
12
+ from pathlib import Path
13
+ from typing import Any, Dict, List, Optional
14
+
15
+
16
+ @dataclass
17
+ class ProposalResearchItem:
18
+ title: str
19
+ summary: str
20
+ source_url: str
21
+ provider_name: str
22
+
23
+
24
+ @dataclass
25
+ class ArchitecturalProposal:
26
+ proposal_id: str
27
+ target_module: str
28
+ target_function: str
29
+ complexity_score: float
30
+ deliberation_verdict: str
31
+ risk_score: float
32
+ rationale: str
33
+ suggested_strategy: str
34
+ research_findings: List[Dict[str, str]] = field(default_factory=list)
35
+ proposed_approach: str = ""
36
+ status: str = "PENDING_HUMAN_REVIEW" # PENDING_HUMAN_REVIEW, APPROVED, EXECUTED, REJECTED, FAILED_VERIFICATION
37
+ created_at: float = field(default_factory=time.time)
38
+ updated_at: float = field(default_factory=time.time)
39
+
40
+ def to_dict(self) -> Dict[str, Any]:
41
+ return asdict(self)
42
+
43
+ @classmethod
44
+ def from_dict(cls, data: Dict[str, Any]) -> ArchitecturalProposal:
45
+ return cls(**data)
46
+
47
+ def to_markdown(self) -> str:
48
+ res_md = ""
49
+ if self.research_findings:
50
+ res_md = "\n".join(
51
+ f"- **[{f.get('provider_name', 'Web')}] [{f.get('title', 'Link')}]({f.get('source_url', '#')})**:\n {f.get('summary', '')}"
52
+ for f in self.research_findings
53
+ )
54
+ else:
55
+ res_md = "_No external research findings required or recorded._"
56
+
57
+ return f"""# Architectural Proposal: `{self.proposal_id}`
58
+
59
+ - **Target Symbol**: `{self.target_module}::{self.target_function}`
60
+ - **McCabe Complexity Score**: {self.complexity_score:.1f}
61
+ - **Status**: `{self.status}`
62
+ - **Risk Score**: {self.risk_score:.2f} ({self.deliberation_verdict})
63
+ - **Created**: {time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(self.created_at))}
64
+
65
+ ---
66
+
67
+ ## 1. Feasibility Deliberation & Protection Rationale
68
+ > **Verdict**: `{self.deliberation_verdict}` (Risk Score: {self.risk_score:.2f})
69
+ > **Rationale**: {self.rationale}
70
+
71
+ ## 2. Recommended Refactoring Strategy
72
+ {self.suggested_strategy}
73
+
74
+ ## 3. Prior Art & External Research
75
+ {res_md}
76
+
77
+ ## 4. Proposed Architectural Action
78
+ ```
79
+ {self.proposed_approach or self.suggested_strategy}
80
+ ```
81
+
82
+ ---
83
+
84
+ ## Human Approval Directive
85
+ To approve and execute this refactoring in the isolated sandbox, run:
86
+ ```powershell
87
+ python scripts/run_live_self_evolution.py --approve-proposal "{self.proposal_id}"
88
+ ```
89
+ """
90
+
91
+
92
+ class ProposalLedger:
93
+ """Manages persistence and lifecycle of architectural proposals staged for human review."""
94
+
95
+ def __init__(self, workspace_root: Path):
96
+ self.workspace_root = workspace_root
97
+ self.proposals_dir = workspace_root / "scratch" / "evolution_state" / "proposals"
98
+ self.proposals_dir.mkdir(parents=True, exist_ok=True)
99
+
100
+ @staticmethod
101
+ def sanitize_id(module_path: str, function_name: str) -> str:
102
+ clean_mod = re.sub(r"[^\w\-]", "_", module_path.replace(".py", ""))
103
+ clean_fn = re.sub(r"[^\w\-]", "_", function_name)
104
+ return f"PROP-{clean_mod}-{clean_fn}"
105
+
106
+ def record_proposal(
107
+ self,
108
+ target_module: str,
109
+ target_function: str,
110
+ complexity_score: float,
111
+ deliberation_verdict: str,
112
+ risk_score: float,
113
+ rationale: str,
114
+ suggested_strategy: str,
115
+ research_findings: Optional[List[Any]] = None,
116
+ proposed_approach: str = "",
117
+ ) -> ArchitecturalProposal:
118
+ """Create or update an architectural proposal staged for human review."""
119
+ proposal_id = self.sanitize_id(target_module, target_function)
120
+
121
+ clean_research: List[Dict[str, str]] = []
122
+ if research_findings:
123
+ for item in research_findings:
124
+ if hasattr(item, "__dict__"):
125
+ clean_research.append(
126
+ {
127
+ "title": getattr(item, "title", "Web Finding"),
128
+ "summary": getattr(item, "summary", ""),
129
+ "source_url": getattr(item, "source_url", ""),
130
+ "provider_name": getattr(item, "provider_name", "Research"),
131
+ }
132
+ )
133
+ elif isinstance(item, dict):
134
+ clean_research.append(item)
135
+
136
+ existing = self.get_proposal(proposal_id)
137
+ created_at = existing.created_at if existing else time.time()
138
+
139
+ proposal = ArchitecturalProposal(
140
+ proposal_id=proposal_id,
141
+ target_module=target_module,
142
+ target_function=target_function,
143
+ complexity_score=complexity_score,
144
+ deliberation_verdict=deliberation_verdict,
145
+ risk_score=risk_score,
146
+ rationale=rationale,
147
+ suggested_strategy=suggested_strategy,
148
+ research_findings=clean_research,
149
+ proposed_approach=proposed_approach or suggested_strategy,
150
+ status="PENDING_HUMAN_REVIEW",
151
+ created_at=created_at,
152
+ updated_at=time.time(),
153
+ )
154
+
155
+ self._save(proposal)
156
+ return proposal
157
+
158
+ def _save(self, proposal: ArchitecturalProposal) -> None:
159
+ json_path = self.proposals_dir / f"{proposal.proposal_id}.json"
160
+ md_path = self.proposals_dir / f"{proposal.proposal_id}.md"
161
+
162
+ json_path.write_text(json.dumps(proposal.to_dict(), indent=2), encoding="utf-8")
163
+ md_path.write_text(proposal.to_markdown(), encoding="utf-8")
164
+
165
+ def get_proposal(self, proposal_id: str) -> Optional[ArchitecturalProposal]:
166
+ json_path = self.proposals_dir / f"{proposal_id}.json"
167
+ if not json_path.exists():
168
+ return None
169
+ try:
170
+ data = json.loads(json_path.read_text(encoding="utf-8"))
171
+ return ArchitecturalProposal.from_dict(data)
172
+ except Exception:
173
+ return None
174
+
175
+ def list_proposals(self, status_filter: Optional[str] = None) -> List[ArchitecturalProposal]:
176
+ proposals: List[ArchitecturalProposal] = []
177
+ for json_file in sorted(self.proposals_dir.glob("*.json")):
178
+ try:
179
+ data = json.loads(json_file.read_text(encoding="utf-8"))
180
+ prop = ArchitecturalProposal.from_dict(data)
181
+ if status_filter is None or prop.status == status_filter:
182
+ proposals.append(prop)
183
+ except Exception:
184
+ continue
185
+ return proposals
186
+
187
+ def mark_status(self, proposal_id: str, new_status: str) -> bool:
188
+ prop = self.get_proposal(proposal_id)
189
+ if not prop:
190
+ return False
191
+ prop.status = new_status
192
+ prop.updated_at = time.time()
193
+ self._save(prop)
194
+ return True