Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 8 additions & 6 deletions src/sovereign_cortex/approvals.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@

from .events import PatchOperation, ProposedPatch
from .git_audit import GitAudit
from .patch_restore import restore_patch_target_on_error
from .policy import PolicyDecision
from .vault import Vault
from .workspace import WorkspaceRegistry
Expand Down Expand Up @@ -114,13 +115,14 @@ def approve(self, approval_id: str) -> ApprovalRequest:
workspace = registry.get(request.workspace)
vault = Vault(workspace.vault_root)
self._ensure_patch_is_current(request, workspace.vault_root)
vault.apply_patch(request.patch)

git = GitAudit(self.repo_root)
commit_hash = git.commit_paths(
[f"vault/{request.workspace}/{request.patch.relative_path}"],
f"Approve Cortex patch: {request.patch.summary}",
)
with restore_patch_target_on_error(workspace.vault_root, request.patch):
vault.apply_patch(request.patch)
git = GitAudit(self.repo_root)
commit_hash = git.commit_paths(
[f"vault/{request.workspace}/{request.patch.relative_path}"],
f"Approve Cortex patch: {request.patch.summary}",
)

updated = request.model_copy(
update={
Expand Down
28 changes: 15 additions & 13 deletions src/sovereign_cortex/orchestrator.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
TaskResult,
)
from .git_audit import GitAudit
from .patch_restore import restore_patch_target_on_error
from .policy import PolicyEngine
from .vault import Vault, render_markdown
from .workspace import WorkspaceRegistry
Expand Down Expand Up @@ -159,21 +160,22 @@ def handle_command(
patches=[patch],
)

vault.apply_patch(patch)
events.append(
self._event(
EventType.PATCH_APPLIED,
"agent/orchestrator",
"vault/demo-project",
{"relative_path": patch.relative_path},
correlation_id=command_event.correlation_id,
with restore_patch_target_on_error(workspace.vault_root, patch):
vault.apply_patch(patch)
events.append(
self._event(
EventType.PATCH_APPLIED,
"agent/orchestrator",
"vault/demo-project",
{"relative_path": patch.relative_path},
correlation_id=command_event.correlation_id,
)
)
)

commit_hash = self.git.commit_paths(
[f"vault/{self.workspace_name}/{patch.relative_path}"],
f"Apply Cortex patch: {patch.summary}",
)
commit_hash = self.git.commit_paths(
[f"vault/{self.workspace_name}/{patch.relative_path}"],
f"Apply Cortex patch: {patch.summary}",
)
events.append(
self._event(
EventType.AUDIT_COMMITTED,
Expand Down
48 changes: 48 additions & 0 deletions src/sovereign_cortex/patch_restore.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
from __future__ import annotations

from contextlib import contextmanager
from dataclasses import dataclass
from pathlib import Path
from typing import Iterator

from .events import ProposedPatch


@dataclass(frozen=True)
class PatchTargetSnapshot:
path: Path
existed: bool
content: str | None


@contextmanager
def restore_patch_target_on_error(vault_root: Path, patch: ProposedPatch) -> Iterator[None]:
snapshot = _snapshot_patch_target(vault_root, patch)
try:
yield
except Exception:
_restore_patch_target(snapshot)
Comment on lines +23 to +24

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Restore the Git index when rolling back a failed commit

If GitAudit.commit_paths() fails after its git add step (for example, because a commit hook rejects the commit), this handler restores only the working-tree file. The patched content remains staged in the Git index, so a later unrelated audit commit can silently commit the failed or still-pending patch. The rollback needs to restore both the target file and its prior index state.

Useful? React with 👍 / 👎.

raise


def _snapshot_patch_target(vault_root: Path, patch: ProposedPatch) -> PatchTargetSnapshot:
path = _resolve(vault_root, patch.relative_path)
existed = path.exists()
content = path.read_text(encoding="utf-8") if existed else None
return PatchTargetSnapshot(path=path, existed=existed, content=content)


def _restore_patch_target(snapshot: PatchTargetSnapshot) -> None:
if snapshot.existed:
snapshot.path.parent.mkdir(parents=True, exist_ok=True)
snapshot.path.write_text(snapshot.content or "", encoding="utf-8")
elif snapshot.path.exists():
snapshot.path.unlink()


def _resolve(vault_root: Path, relative_path: str) -> Path:
path = (vault_root / relative_path).resolve()
root = vault_root.resolve()
if root not in path.parents and path != root:
raise ValueError(f"Patch path escapes the workspace: {relative_path}")
return path
49 changes: 49 additions & 0 deletions tests/test_approvals.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,10 @@ def _rewrite_request(path: Path, request) -> None:
path.write_text(request.model_dump_json(indent=2) + "\n", encoding="utf-8")


def _raise_commit_error(self, paths, message):
raise RuntimeError("commit unavailable")


def test_orchestrator_saves_pending_approval(tmp_path):
repo_root = _copy_repo(tmp_path)
result = LocalOrchestrator(repo_root).handle_command(
Expand Down Expand Up @@ -74,6 +78,51 @@ def test_approval_approve_applies_patch_and_moves_request(tmp_path):
assert "Cortex Notes" in task_text


def test_approval_keeps_updated_file_current_when_commit_is_unavailable(tmp_path, monkeypatch):
repo_root = _copy_repo(tmp_path)
result = LocalOrchestrator(repo_root).handle_command(
"Move the website launch task to next Friday and explain the dependency impact",
auto_approve=False,
)
task_path = repo_root / "vault" / "demo-project" / "tasks" / "launch-website.md"
before = task_path.read_text(encoding="utf-8")
monkeypatch.setattr("sovereign_cortex.approvals.GitAudit.commit_paths", _raise_commit_error)

with pytest.raises(RuntimeError, match="commit unavailable"):
ApprovalStore(repo_root).approve(result.approval_id)

assert task_path.read_text(encoding="utf-8") == before
assert (repo_root / "approval_requests" / "pending" / f"{result.approval_id}.json").exists()
assert not (repo_root / "approval_requests" / "approved" / f"{result.approval_id}.json").exists()


def test_approval_removes_created_file_when_commit_is_unavailable(tmp_path, monkeypatch):
repo_root = _copy_repo(tmp_path)
target = repo_root / "vault" / "demo-project" / "tasks" / "new-audit-task.md"
store = ApprovalStore(repo_root)
request = store.create(
workspace="demo-project",
command_text="Create a new audit task",
correlation_id="test-correlation",
patch=ProposedPatch(
operation=PatchOperation.CREATE_FILE,
relative_path="tasks/new-audit-task.md",
before=None,
after="---\nid: new-audit-task\ntitle: New Audit Task\n---\n# New Audit Task\n",
summary="Create new audit task.",
),
policy_decision=PolicyDecision(allowed=True, approval_required=True, reason="ok"),
)
monkeypatch.setattr("sovereign_cortex.approvals.GitAudit.commit_paths", _raise_commit_error)

with pytest.raises(RuntimeError, match="commit unavailable"):
store.approve(request.approval_id)

assert not target.exists()
assert (repo_root / "approval_requests" / "pending" / f"{request.approval_id}.json").exists()
assert not (repo_root / "approval_requests" / "approved" / f"{request.approval_id}.json").exists()


def test_approval_rejects_stale_update_and_keeps_request_pending(tmp_path):
repo_root = _copy_repo(tmp_path)
result = LocalOrchestrator(repo_root).handle_command(
Expand Down
26 changes: 26 additions & 0 deletions tests/test_orchestrator.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,23 @@
import shutil
from pathlib import Path

import pytest

from sovereign_cortex.orchestrator import LocalOrchestrator


def _copy_repo(tmp_path: Path) -> Path:
source = Path(__file__).resolve().parents[1]
target = tmp_path / "repo"
ignore = shutil.ignore_patterns(".git", ".pytest_cache", "__pycache__", "approval_requests")
shutil.copytree(source, target, ignore=ignore)
return target


def _raise_commit_error(self, paths, message):
raise RuntimeError("commit unavailable")


def test_orchestrator_proposes_launch_patch():
repo_root = Path(__file__).resolve().parents[1]
result = LocalOrchestrator(repo_root).handle_command(
Expand All @@ -13,3 +28,14 @@ def test_orchestrator_proposes_launch_patch():
assert result.patches
assert result.approval_id
assert "Launch Website" in result.patches[0].after


def test_auto_approve_removes_created_file_when_commit_is_unavailable(tmp_path, monkeypatch):
repo_root = _copy_repo(tmp_path)
target = repo_root / "vault" / "demo-project" / "tasks" / "audit-check.md"
monkeypatch.setattr("sovereign_cortex.orchestrator.GitAudit.commit_paths", _raise_commit_error)

with pytest.raises(RuntimeError, match="commit unavailable"):
LocalOrchestrator(repo_root).handle_command("Create task Audit Check", auto_approve=True)

assert not target.exists()
Loading