continuum-toolkit 1.0.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 (72) hide show
  1. cli/__init__.py +12 -0
  2. cli/main.py +415 -0
  3. confidence/__init__.py +13 -0
  4. confidence/calculator.py +308 -0
  5. confidence/models.py +40 -0
  6. context/__init__.py +17 -0
  7. context/models.py +108 -0
  8. context/pruner.py +228 -0
  9. context/selector.py +193 -0
  10. continuum_toolkit-1.0.0.dist-info/METADATA +511 -0
  11. continuum_toolkit-1.0.0.dist-info/RECORD +72 -0
  12. continuum_toolkit-1.0.0.dist-info/WHEEL +5 -0
  13. continuum_toolkit-1.0.0.dist-info/entry_points.txt +2 -0
  14. continuum_toolkit-1.0.0.dist-info/licenses/LICENSE +21 -0
  15. continuum_toolkit-1.0.0.dist-info/top_level.txt +13 -0
  16. contradictions/__init__.py +19 -0
  17. contradictions/detector.py +442 -0
  18. contradictions/models.py +75 -0
  19. core/__init__.py +97 -0
  20. core/enums.py +130 -0
  21. core/evidence.py +117 -0
  22. core/interfaces.py +209 -0
  23. core/schema.py +391 -0
  24. core/serializer.py +84 -0
  25. core/state_models.py +530 -0
  26. daemon/__init__.py +12 -0
  27. daemon/service.py +170 -0
  28. extractors/__init__.py +51 -0
  29. extractors/base.py +117 -0
  30. extractors/config/parsers.py +288 -0
  31. extractors/config/secret_sanitizer.py +91 -0
  32. extractors/config_extractor.py +172 -0
  33. extractors/conversation/analyzers.py +193 -0
  34. extractors/conversation/models.py +148 -0
  35. extractors/conversation_extractor.py +166 -0
  36. extractors/git_extractor.py +305 -0
  37. extractors/parsers/base.py +91 -0
  38. extractors/parsers/comment_parser.py +51 -0
  39. extractors/parsers/js_ts_parser.py +171 -0
  40. extractors/parsers/python_parser.py +180 -0
  41. extractors/verification/runners.py +278 -0
  42. extractors/verification_extractor.py +263 -0
  43. extractors/workspace_extractor.py +221 -0
  44. graph/__init__.py +24 -0
  45. graph/diff.py +109 -0
  46. graph/manager.py +473 -0
  47. graph/models.py +62 -0
  48. graph/propagator.py +194 -0
  49. graph/query.py +86 -0
  50. graph/snapshot.py +85 -0
  51. handoff/__init__.py +28 -0
  52. handoff/adapters/__init__.py +45 -0
  53. handoff/adapters/base.py +90 -0
  54. handoff/adapters/claude_adapter.py +176 -0
  55. handoff/adapters/codex_gpt_adapter.py +151 -0
  56. handoff/adapters/gemini_adapter.py +151 -0
  57. handoff/adapters/local_model_adapter.py +130 -0
  58. handoff/models.py +88 -0
  59. handoff/packager.py +288 -0
  60. pipeline/__init__.py +9 -0
  61. pipeline/orchestrator.py +260 -0
  62. resolution/__init__.py +15 -0
  63. resolution/resolver.py +311 -0
  64. storage/__init__.py +18 -0
  65. storage/hooks.py +125 -0
  66. storage/manager.py +127 -0
  67. storage/models.py +39 -0
  68. storage/recovery.py +98 -0
  69. watcher/__init__.py +17 -0
  70. watcher/detector.py +136 -0
  71. watcher/models.py +62 -0
  72. watcher/updater.py +163 -0
resolution/resolver.py ADDED
@@ -0,0 +1,311 @@
1
+ """
2
+ Project Continuum - Evidence Resolution Engine
3
+ ==============================================
4
+ Milestone 3 - Phase 6: Truth Resolution & Seniority-Based Arbitration.
5
+ Resolves multi-source evidence into consistent, explainable conclusions
6
+ using the 5-level Evidence Hierarchy Matrix while preserving conflicting proof.
7
+ """
8
+
9
+ from dataclasses import dataclass, field
10
+ from typing import Any, Dict, List, Optional, Set, Tuple
11
+
12
+ from core.enums import EvidenceLevel, EvidenceType, Status
13
+ from core.evidence import Evidence
14
+ from core.interfaces import IEvidenceResolver
15
+ from core.state_models import (
16
+ AgentClaim,
17
+ CanonicalProjectState,
18
+ ProjectState,
19
+ Requirement,
20
+ )
21
+
22
+
23
+ @dataclass
24
+ class EvidenceCandidate:
25
+ """An individual piece of evidence evaluated for a specific target component/task."""
26
+ evidence: Evidence
27
+ inferred_status: Status
28
+ level: EvidenceLevel
29
+ relevance_weight: float = 1.0
30
+ notes: str = ""
31
+
32
+ def to_dict(self) -> Dict[str, Any]:
33
+ return {
34
+ "evidence_id": self.evidence.id,
35
+ "evidence_type": self.evidence.type.value,
36
+ "level": int(self.level.value),
37
+ "inferred_status": self.inferred_status.value,
38
+ "relevance_weight": self.relevance_weight,
39
+ "notes": self.notes
40
+ }
41
+
42
+
43
+ @dataclass
44
+ class ResolutionResult:
45
+ """The synthesized resolution conclusion with complete audit provenance."""
46
+ target_id: str
47
+ resolved_status: Status
48
+ winning_evidence: Optional[Evidence]
49
+ competing_evidence: List[Evidence] = field(default_factory=list)
50
+ conflict_detected: bool = False
51
+ rationale: str = ""
52
+ hierarchy_level_used: Optional[EvidenceLevel] = None
53
+ all_candidates: List[EvidenceCandidate] = field(default_factory=list)
54
+
55
+ def to_dict(self) -> Dict[str, Any]:
56
+ return {
57
+ "target_id": self.target_id,
58
+ "resolved_status": self.resolved_status.value,
59
+ "winning_evidence_id": self.winning_evidence.id if self.winning_evidence else None,
60
+ "competing_evidence_ids": [e.id for e in self.competing_evidence],
61
+ "conflict_detected": self.conflict_detected,
62
+ "rationale": self.rationale,
63
+ "hierarchy_level_used": int(self.hierarchy_level_used.value) if self.hierarchy_level_used else None,
64
+ "candidates": [c.to_dict() for c in self.all_candidates]
65
+ }
66
+
67
+
68
+ class EvidenceResolver(IEvidenceResolver):
69
+ """
70
+ Arbitrates multi-source evidence based on the Seniority Matrix:
71
+ Level 1: Runtime status & automated tests (Highest)
72
+ Level 2: AST symbols, code syntax, package manifests
73
+ Level 3: Git working tree status, staged/unstaged, commits
74
+ Level 4: Architecture docs, comments, READMEs
75
+ Level 5: Conversational statements and agent claims (Lowest)
76
+ """
77
+
78
+ def resolve_status(
79
+ self,
80
+ target_id: str,
81
+ evidence_list: List[Evidence],
82
+ claims: Optional[List[Dict[str, Any]]] = None
83
+ ) -> Tuple[Status, Optional[Evidence], str]:
84
+ """
85
+ Implements IEvidenceResolver interface method.
86
+ Returns (Status, WinningEvidence, Rationale).
87
+ """
88
+ res = self.resolve_candidates(target_id, evidence_list, claims)
89
+ return res.resolved_status, res.winning_evidence, res.rationale
90
+
91
+ def resolve_candidates(
92
+ self,
93
+ target_id: str,
94
+ evidence_list: List[Evidence],
95
+ claims: Optional[List[Dict[str, Any]]] = None
96
+ ) -> ResolutionResult:
97
+ """
98
+ Full resolution returning complete ResolutionResult audit record.
99
+ """
100
+ if not evidence_list:
101
+ # Check if only claims exist
102
+ if claims:
103
+ claim_statuses = [Status(c.get("claimed_status", Status.VERIFIED.value)) for c in claims]
104
+ return ResolutionResult(
105
+ target_id=target_id,
106
+ resolved_status=Status.UNVERIFIED,
107
+ winning_evidence=None,
108
+ competing_evidence=[],
109
+ conflict_detected=False,
110
+ rationale=f"Target '{target_id}' has {len(claims)} conversational claim(s), but ZERO physical evidence. Classified as UNVERIFIED.",
111
+ hierarchy_level_used=EvidenceLevel.LEVEL_5_CONVERSATION
112
+ )
113
+ return ResolutionResult(
114
+ target_id=target_id,
115
+ resolved_status=Status.UNKNOWN,
116
+ winning_evidence=None,
117
+ competing_evidence=[],
118
+ conflict_detected=False,
119
+ rationale=f"No evidence or claims available for '{target_id}'. Classified as UNKNOWN.",
120
+ hierarchy_level_used=None
121
+ )
122
+
123
+ # 1. Classify each piece of evidence into candidates
124
+ candidates: List[EvidenceCandidate] = []
125
+ for ev in evidence_list:
126
+ inferred_st, notes = self._infer_status_from_evidence(ev, target_id)
127
+ candidates.append(EvidenceCandidate(
128
+ evidence=ev,
129
+ inferred_status=inferred_st,
130
+ level=ev.level,
131
+ notes=notes
132
+ ))
133
+
134
+ # 2. Sort candidates by Seniority (Level 1 < Level 2 < Level 3 < Level 4 < Level 5)
135
+ candidates.sort(key=lambda c: (int(c.level.value), -c.relevance_weight))
136
+
137
+ # 3. Detect Conflicts (do candidates disagree on success vs failure/pending?)
138
+ distinct_statuses = {c.inferred_status for c in candidates if c.inferred_status != Status.UNKNOWN}
139
+ has_conflict = len(distinct_statuses) > 1
140
+
141
+ # 4. Group by highest seniority tier present
142
+ highest_level = candidates[0].level
143
+ top_tier_candidates = [c for c in candidates if c.level == highest_level]
144
+
145
+ # 5. Arbitrate within top tier
146
+ winning_candidate = self._arbitrate_tier(top_tier_candidates)
147
+ winning_evidence = winning_candidate.evidence
148
+ resolved_status = winning_candidate.inferred_status
149
+
150
+ # 6. Compose explainability rationale
151
+ competing = [c.evidence for c in candidates if c.evidence.id != winning_evidence.id]
152
+ rationale = self._build_rationale(
153
+ target_id=target_id,
154
+ winning=winning_candidate,
155
+ highest_level=highest_level,
156
+ candidates=candidates,
157
+ has_conflict=has_conflict
158
+ )
159
+
160
+ return ResolutionResult(
161
+ target_id=target_id,
162
+ resolved_status=resolved_status,
163
+ winning_evidence=winning_evidence,
164
+ competing_evidence=competing,
165
+ conflict_detected=has_conflict,
166
+ rationale=rationale,
167
+ hierarchy_level_used=highest_level,
168
+ all_candidates=candidates
169
+ )
170
+
171
+ def _infer_status_from_evidence(self, ev: Evidence, target_id: str) -> Tuple[Status, str]:
172
+ """Infers the indicated status from an Evidence item."""
173
+ payload = ev.raw_payload
174
+
175
+ # Level 1: Test & Build results
176
+ if ev.type in {EvidenceType.TEST_RUN, EvidenceType.BUILD_LOG, EvidenceType.RUNTIME_LOG}:
177
+ exit_code = payload.get("exit_code", 0)
178
+ if exit_code == 0:
179
+ return Status.VERIFIED, f"Test/Build '{ev.summary}' passed (exit code 0)"
180
+ else:
181
+ return Status.FAILED, f"Test/Build '{ev.summary}' failed (exit code {exit_code})"
182
+
183
+ # Level 2: Source Code & AST Symbols
184
+ if ev.type == EvidenceType.AST_SYMBOL:
185
+ symbols = payload.get("symbols", [])
186
+ has_target = any(target_id.lower() in s.get("name", "").lower() for s in symbols) if target_id else bool(symbols)
187
+ errors = payload.get("errors", [])
188
+ if errors:
189
+ return Status.FAILED, f"AST contains parse errors in {payload.get('file_path')}"
190
+ if has_target:
191
+ return Status.PARTIAL, f"AST symbol '{target_id}' found implemented in code"
192
+ return Status.PARTIAL, f"Source code present ({len(symbols)} symbols)"
193
+
194
+ if ev.type == EvidenceType.SOURCE_CODE:
195
+ return Status.PARTIAL, f"Physical source file present: {payload.get('file_list', [])[:3]}"
196
+
197
+ if ev.type == EvidenceType.CONFIG_FILE:
198
+ return Status.VERIFIED, f"Configuration/manifest valid: {payload.get('manifest_type', 'config')}"
199
+
200
+ # Level 3: Git State
201
+ if ev.type == EvidenceType.GIT_STATUS:
202
+ is_dirty = payload.get("is_dirty", False)
203
+ if is_dirty:
204
+ return Status.IN_PROGRESS, "Git working tree has uncommitted modifications in progress"
205
+ return Status.VERIFIED, "Git repository working tree is clean and committed"
206
+
207
+ if ev.type == EvidenceType.GIT_DIFF:
208
+ return Status.IN_PROGRESS, "Git diff shows active in-flight code changes"
209
+
210
+ if ev.type == EvidenceType.GIT_COMMIT:
211
+ return Status.VERIFIED, "Git commit history records past changes"
212
+
213
+ # Level 4: Documentation
214
+ if ev.type == EvidenceType.DOCUMENTATION:
215
+ return Status.UNVERIFIED, "Documented in markdown/README (requires code verification)"
216
+
217
+ # Level 5: Conversational Assertions & Claims
218
+ if ev.type in {EvidenceType.AGENT_CLAIM, EvidenceType.CONVERSATION_ASSERTION}:
219
+ claimed_status = payload.get("claim", {}).get("claimed_status") or payload.get("claimed_status", Status.VERIFIED.value)
220
+ return Status.UNVERIFIED, f"Agent claimed '{claimed_status}' in chat (unverified until physical proof is provided)"
221
+
222
+ if ev.type == EvidenceType.USER_REQUIREMENT:
223
+ return Status.PENDING, "User requirement defined in conversation (pending implementation)"
224
+
225
+ return Status.UNKNOWN, "Unknown evidence type"
226
+
227
+ def _arbitrate_tier(self, candidates: List[EvidenceCandidate]) -> EvidenceCandidate:
228
+ """
229
+ Arbitrates among candidates within the same seniority tier.
230
+ Prioritizes hard failures over partial success (fail-safe verification principle).
231
+ """
232
+ # If any test failed within Level 1, failure takes precedence
233
+ failing = [c for c in candidates if c.inferred_status == Status.FAILED]
234
+ if failing:
235
+ return failing[0]
236
+
237
+ # Next prioritize verified
238
+ verified = [c for c in candidates if c.inferred_status == Status.VERIFIED]
239
+ if verified:
240
+ return verified[0]
241
+
242
+ # Otherwise return the highest weighted candidate
243
+ return candidates[0]
244
+
245
+ def _build_rationale(
246
+ self,
247
+ target_id: str,
248
+ winning: EvidenceCandidate,
249
+ highest_level: EvidenceLevel,
250
+ candidates: List[EvidenceCandidate],
251
+ has_conflict: bool
252
+ ) -> str:
253
+ level_names = {
254
+ EvidenceLevel.LEVEL_1_RUNTIME_TEST: "Level 1 (Automated Test / Runtime)",
255
+ EvidenceLevel.LEVEL_2_CODE_AST: "Level 2 (Source Code / AST / Manifest)",
256
+ EvidenceLevel.LEVEL_3_GIT_STATE: "Level 3 (Git State / History)",
257
+ EvidenceLevel.LEVEL_4_DOCUMENTATION: "Level 4 (Documentation)",
258
+ EvidenceLevel.LEVEL_5_CONVERSATION: "Level 5 (Conversational Claims)"
259
+ }
260
+
261
+ tier_name = level_names.get(highest_level, f"Level {highest_level.value}")
262
+ rationale = f"Resolved '{target_id}' to status [{winning.inferred_status.value}] via {tier_name}. {winning.notes}"
263
+
264
+ if has_conflict:
265
+ overridden = [c for c in candidates if c.level != highest_level]
266
+ if overridden:
267
+ overridden_desc = ", ".join([f"{level_names.get(c.level, 'L' + str(c.level.value))} ({c.inferred_status.value})" for c in overridden[:3]])
268
+ rationale += f" Overrode conflicting lower-tier evidence: {overridden_desc}."
269
+
270
+ return rationale
271
+
272
+ def resolve_project_state(self, canonical_state: CanonicalProjectState) -> Dict[str, ResolutionResult]:
273
+ """
274
+ Runs comprehensive evidence resolution across all requirements, components,
275
+ and agent claims registered in CanonicalProjectState.
276
+ """
277
+ results: Dict[str, ResolutionResult] = {}
278
+ evidence_pool = canonical_state.evidence_pool
279
+
280
+ # 1. Resolve User Requirements
281
+ for req in canonical_state.conversational_state.user_requirements:
282
+ matching_ev = [
283
+ ev for ev in evidence_pool.values()
284
+ if req.title.lower() in ev.summary.lower()
285
+ or (req.evidence_id and ev.id == req.evidence_id)
286
+ ]
287
+ res = self.resolve_candidates(req.id, matching_ev)
288
+ results[req.id] = res
289
+ req.status = res.resolved_status
290
+
291
+ # 2. Resolve Agent Claims
292
+ for claim in canonical_state.conversational_state.agent_claims:
293
+ target = claim.target_component or claim.claim_text
294
+ matching_ev = [
295
+ ev for ev in evidence_pool.values()
296
+ if target.lower() in ev.summary.lower()
297
+ or target.lower() in str(ev.raw_payload).lower()
298
+ ]
299
+ res = self.resolve_candidates(claim.id, matching_ev, claims=[claim.to_dict()])
300
+ results[claim.id] = res
301
+
302
+ # 3. Resolve AST Symbols
303
+ for sym in canonical_state.project_state.symbols:
304
+ matching_ev = [
305
+ ev for ev in evidence_pool.values()
306
+ if sym.name in ev.summary or (sym.evidence_id and ev.id == sym.evidence_id)
307
+ ]
308
+ res = self.resolve_candidates(sym.name, matching_ev)
309
+ results[sym.name] = res
310
+
311
+ return results
storage/__init__.py ADDED
@@ -0,0 +1,18 @@
1
+ """
2
+ Project Continuum - Storage Subsystem Exports
3
+ =============================================
4
+ Milestone 7 - Phase 17: Git Hooks & Persistent State Management.
5
+ """
6
+
7
+ from storage.models import StorageMetadata, RecoveryResult
8
+ from storage.manager import ContinuumStorageManager
9
+ from storage.recovery import StateRecoveryManager
10
+ from storage.hooks import GitHookManager
11
+
12
+ __all__ = [
13
+ "StorageMetadata",
14
+ "RecoveryResult",
15
+ "ContinuumStorageManager",
16
+ "StateRecoveryManager",
17
+ "GitHookManager",
18
+ ]
storage/hooks.py ADDED
@@ -0,0 +1,125 @@
1
+ """
2
+ Project Continuum - Git Hook Manager
3
+ ====================================
4
+ Milestone 7 - Phase 17: Git Hooks & Persistent State Management.
5
+ Installs and orchestrates non-blocking Git hooks (post-commit, pre-commit) to safely
6
+ capture repository changes into Continuum memory without interfering with Git operations.
7
+ """
8
+
9
+ import os
10
+ from pathlib import Path
11
+ import stat
12
+ from typing import Dict, List, Optional
13
+
14
+ from storage.manager import ContinuumStorageManager
15
+
16
+
17
+ class GitHookManager:
18
+ """
19
+ Manages non-destructive Git hook scripts inside `.git/hooks/`.
20
+ Guarantees:
21
+ - Never blocks or disrupts standard Git commands.
22
+ - Captures post-commit HEAD changes and saves snapshots to `.continuum/`.
23
+ """
24
+
25
+ POST_COMMIT_SCRIPT = """#!/bin/sh
26
+ # Project Continuum - Automated Post-Commit Snapshot Hook
27
+ # Non-blocking background state capture
28
+
29
+ if command -v py >/dev/null 2>&1; then
30
+ py -c "import sys; from extractors.git_extractor import GitExtractor; from storage.manager import ContinuumStorageManager; ContinuumStorageManager('.').initialize_storage()" 2>/dev/null || true
31
+ elif command -v python3 >/dev/null 2>&1; then
32
+ python3 -c "import sys; from extractors.git_extractor import GitExtractor; from storage.manager import ContinuumStorageManager; ContinuumStorageManager('.').initialize_storage()" 2>/dev/null || true
33
+ fi
34
+ exit 0
35
+ """
36
+
37
+ PRE_COMMIT_SCRIPT = """#!/bin/sh
38
+ # Project Continuum - Automated Pre-Commit Safety Hook
39
+ # Never blocks commit; records pre-commit working tree baseline
40
+ exit 0
41
+ """
42
+
43
+ def __init__(self, workspace_root: str):
44
+ self.workspace_root = Path(workspace_root).resolve()
45
+ self.git_dir = self.workspace_root / ".git"
46
+ self.hooks_dir = self.git_dir / "hooks"
47
+
48
+ def is_git_repo(self) -> bool:
49
+ """Checks if target workspace is an initialized Git repo."""
50
+ return self.git_dir.exists() and self.git_dir.is_dir()
51
+
52
+ def install_hooks(self) -> Dict[str, bool]:
53
+ """
54
+ Installs non-blocking post-commit and pre-commit hooks into .git/hooks/.
55
+ Returns dict of hook_name -> success.
56
+ """
57
+ if not self.is_git_repo():
58
+ return {"post-commit": False, "pre-commit": False}
59
+
60
+ self.hooks_dir.mkdir(parents=True, exist_ok=True)
61
+ results = {}
62
+
63
+ # 1. Post-commit hook
64
+ post_commit_path = self.hooks_dir / "post-commit"
65
+ try:
66
+ post_commit_path.write_text(self.POST_COMMIT_SCRIPT, encoding="utf-8")
67
+ self._make_executable(post_commit_path)
68
+ results["post-commit"] = True
69
+ except Exception:
70
+ results["post-commit"] = False
71
+
72
+ # 2. Pre-commit hook
73
+ pre_commit_path = self.hooks_dir / "pre-commit"
74
+ try:
75
+ pre_commit_path.write_text(self.PRE_COMMIT_SCRIPT, encoding="utf-8")
76
+ self._make_executable(pre_commit_path)
77
+ results["pre-commit"] = True
78
+ except Exception:
79
+ results["pre-commit"] = False
80
+
81
+ return results
82
+
83
+ def are_hooks_installed(self) -> Dict[str, bool]:
84
+ """Checks installation status of hooks."""
85
+ if not self.is_git_repo() or not self.hooks_dir.exists():
86
+ return {"post-commit": False, "pre-commit": False}
87
+
88
+ post_commit = self.hooks_dir / "post-commit"
89
+ pre_commit = self.hooks_dir / "pre-commit"
90
+
91
+ return {
92
+ "post-commit": post_commit.exists() and "Project Continuum" in post_commit.read_text(encoding="utf-8", errors="ignore"),
93
+ "pre-commit": pre_commit.exists() and "Project Continuum" in pre_commit.read_text(encoding="utf-8", errors="ignore"),
94
+ }
95
+
96
+ def uninstall_hooks(self) -> Dict[str, bool]:
97
+ """Removes Continuum hooks cleanly."""
98
+ if not self.is_git_repo() or not self.hooks_dir.exists():
99
+ return {"post-commit": True, "pre-commit": True}
100
+
101
+ results = {}
102
+ for hook_name in ["post-commit", "pre-commit"]:
103
+ hook_file = self.hooks_dir / hook_name
104
+ if hook_file.exists():
105
+ content = hook_file.read_text(encoding="utf-8", errors="ignore")
106
+ if "Project Continuum" in content:
107
+ try:
108
+ hook_file.unlink()
109
+ results[hook_name] = True
110
+ except Exception:
111
+ results[hook_name] = False
112
+ else:
113
+ results[hook_name] = True # Did not own this hook
114
+ else:
115
+ results[hook_name] = True
116
+
117
+ return results
118
+
119
+ def _make_executable(self, path: Path) -> None:
120
+ """Adds executable permissions on POSIX systems."""
121
+ try:
122
+ current_stat = path.stat()
123
+ path.chmod(current_stat.st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)
124
+ except Exception:
125
+ pass
storage/manager.py ADDED
@@ -0,0 +1,127 @@
1
+ """
2
+ Project Continuum - Persistent Storage Manager
3
+ ==============================================
4
+ Milestone 7 - Phase 17: Git Hooks & Persistent State Management.
5
+ Manages the local `.continuum/` directory structure, versioned history snapshots,
6
+ and atomic state file persistence.
7
+ """
8
+
9
+ from datetime import datetime, timezone
10
+ import json
11
+ import os
12
+ from pathlib import Path
13
+ import shutil
14
+ import time
15
+ from typing import Any, Dict, List, Optional
16
+
17
+ from core.schema import validate_canonical_state_dict
18
+ from core.serializer import CanonicalStateSerializer
19
+ from core.state_models import CanonicalProjectState
20
+ from storage.models import StorageMetadata
21
+
22
+
23
+ class ContinuumStorageManager:
24
+ """
25
+ Manages persistent state on disk inside `<workspace_root>/.continuum/`:
26
+ - `.continuum/state.json`: Active canonical project state
27
+ - `.continuum/history/`: Versioned snapshots (timestamped)
28
+ - `.continuum/backup/`: Pre-modification safety backups
29
+ """
30
+
31
+ MAX_HISTORY_SNAPSHOTS = 100
32
+
33
+ def __init__(self, workspace_root: str):
34
+ self.workspace_root = Path(workspace_root).resolve()
35
+ self.continuum_dir = self.workspace_root / ".continuum"
36
+ self.history_dir = self.continuum_dir / "history"
37
+ self.backup_dir = self.continuum_dir / "backup"
38
+ self.active_state_file = self.continuum_dir / "state.json"
39
+
40
+ def initialize_storage(self) -> None:
41
+ """Ensures .continuum directory and subfolders exist."""
42
+ self.continuum_dir.mkdir(parents=True, exist_ok=True)
43
+ self.history_dir.mkdir(parents=True, exist_ok=True)
44
+ self.backup_dir.mkdir(parents=True, exist_ok=True)
45
+
46
+ def save_state(
47
+ self,
48
+ state: CanonicalProjectState,
49
+ create_history_snapshot: bool = True,
50
+ commit_tag: Optional[str] = None
51
+ ) -> str:
52
+ """
53
+ Atomically saves state to .continuum/state.json, backing up the previous
54
+ state and optionally storing a versioned history snapshot.
55
+ Returns the path of the saved active state file.
56
+ """
57
+ self.initialize_storage()
58
+
59
+ # 1. Backup existing active state if present
60
+ if self.active_state_file.exists():
61
+ backup_target = self.backup_dir / "state.json.bak"
62
+ shutil.copy2(self.active_state_file, backup_target)
63
+
64
+ # 2. Write state atomically to active_state_file
65
+ CanonicalStateSerializer.save_to_file(state, self.active_state_file, indent=2)
66
+
67
+ # 3. Create versioned history snapshot if requested
68
+ if create_history_snapshot:
69
+ ts = datetime.now(timezone.utc).strftime("%Y%m%d_%H%M%S_%f")
70
+ tag_suffix = f"_{commit_tag}" if commit_tag else ""
71
+ snapshot_filename = f"state_{ts}{tag_suffix}.json"
72
+ snapshot_path = self.history_dir / snapshot_filename
73
+ CanonicalStateSerializer.save_to_file(state, snapshot_path, indent=2)
74
+ self._prune_history()
75
+
76
+ return str(self.active_state_file.resolve())
77
+
78
+ def load_state(self, validate: bool = True) -> CanonicalProjectState:
79
+ """
80
+ Loads and deserializes the active state from .continuum/state.json.
81
+ Raises FileNotFoundError if no active state exists.
82
+ """
83
+ if not self.active_state_file.exists():
84
+ raise FileNotFoundError(f"No active Continuum state found at {self.active_state_file}")
85
+
86
+ return CanonicalStateSerializer.load_from_file(self.active_state_file, validate=validate)
87
+
88
+ def state_exists(self) -> bool:
89
+ """Checks if active state file exists."""
90
+ return self.active_state_file.exists()
91
+
92
+ def get_metadata(self) -> StorageMetadata:
93
+ """Returns metadata regarding active storage, history count, and backups."""
94
+ history_files = list(self.history_dir.glob("state_*.json")) if self.history_dir.exists() else []
95
+ backup_files = list(self.backup_dir.glob("*.bak")) if self.backup_dir.exists() else []
96
+
97
+ last_saved = None
98
+ if self.active_state_file.exists():
99
+ last_saved = datetime.fromtimestamp(
100
+ self.active_state_file.stat().st_mtime, timezone.utc
101
+ ).isoformat()
102
+
103
+ return StorageMetadata(
104
+ workspace_root=str(self.workspace_root),
105
+ continuum_dir=str(self.continuum_dir),
106
+ active_state_file=str(self.active_state_file),
107
+ history_count=len(history_files),
108
+ backup_count=len(backup_files),
109
+ last_saved_at=last_saved
110
+ )
111
+
112
+ def list_history_snapshots(self) -> List[Path]:
113
+ """Returns sorted list of history snapshot filepaths (newest first)."""
114
+ if not self.history_dir.exists():
115
+ return []
116
+ snapshots = list(self.history_dir.glob("state_*.json"))
117
+ return sorted(snapshots, key=lambda p: p.name, reverse=True)
118
+
119
+ def _prune_history(self) -> None:
120
+ """Prunes history directory if count exceeds MAX_HISTORY_SNAPSHOTS."""
121
+ snapshots = self.list_history_snapshots()
122
+ if len(snapshots) > self.MAX_HISTORY_SNAPSHOTS:
123
+ for excess in snapshots[self.MAX_HISTORY_SNAPSHOTS:]:
124
+ try:
125
+ excess.unlink()
126
+ except OSError:
127
+ pass
storage/models.py ADDED
@@ -0,0 +1,39 @@
1
+ """
2
+ Project Continuum - Persistent Storage & Git Hook Models
3
+ =========================================================
4
+ Milestone 7 - Phase 17: Git Hooks & Persistent State Management.
5
+ Defines models for storage management, backup metadata, and recovery reports.
6
+ """
7
+
8
+ from dataclasses import dataclass, field, asdict
9
+ from datetime import datetime, timezone
10
+ from typing import Any, Dict, List, Optional
11
+
12
+
13
+ @dataclass
14
+ class StorageMetadata:
15
+ """Metadata regarding local .continuum/ storage and history."""
16
+ workspace_root: str
17
+ continuum_dir: str
18
+ active_state_file: str
19
+ history_count: int = 0
20
+ backup_count: int = 0
21
+ last_saved_at: Optional[str] = None
22
+ last_snapshot_hash: Optional[str] = None
23
+
24
+ def to_dict(self) -> Dict[str, Any]:
25
+ return asdict(self)
26
+
27
+
28
+ @dataclass
29
+ class RecoveryResult:
30
+ """Result of state integrity check and auto-recovery operation."""
31
+ success: bool
32
+ recovered_from: Optional[str] = None
33
+ error_message: Optional[str] = None
34
+ state_restored: bool = False
35
+ details: Dict[str, Any] = field(default_factory=dict)
36
+ timestamp: str = field(default_factory=lambda: datetime.now(timezone.utc).isoformat())
37
+
38
+ def to_dict(self) -> Dict[str, Any]:
39
+ return asdict(self)