pakem-cli 0.0.0-stage → 1.3.0
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.
- package/CHANGELOG.md +280 -0
- package/LICENSE +21 -0
- package/README-ID.md +666 -0
- package/README.md +665 -2
- package/SKILL.md +264 -0
- package/adapters/git-worktree/v1/README.md +17 -0
- package/adapters/identity/v1/README.md +26 -0
- package/adapters/mcp/v1/README.md +56 -0
- package/adapters/storage-sqlite/v1/README.md +5 -0
- package/assets/banner.svg +275 -0
- package/assets/divider.svg +82 -0
- package/assets/footer.svg +174 -0
- package/assets/templates/BUG-HISTORY.md +18 -0
- package/assets/templates/CONTEXT.md +26 -0
- package/assets/templates/DECISIONS.md +8 -0
- package/assets/templates/MODULE-MAP.md +14 -0
- package/assets/templates/POLICY.json +15 -0
- package/assets/templates/PROJECT.md +42 -0
- package/conformance/v1/README.md +15 -0
- package/coordination/v1/README.md +14 -0
- package/coordination/v1/board.schema.json +59 -0
- package/coordination/v1/event.schema.json +26 -0
- package/coordination/v1/status.schema.json +49 -0
- package/evals/README.md +63 -0
- package/evals/evals.json +276 -0
- package/identity/v1/README.md +14 -0
- package/identity/v1/agent-identity.schema.json +95 -0
- package/identity/v1/identity-registry.schema.json +29 -0
- package/identity/v1/signed-payload.schema.json +42 -0
- package/intelligence/v1/README.md +19 -0
- package/intelligence/v1/dependency-graph.schema.json +82 -0
- package/intelligence/v1/impact-analysis.schema.json +51 -0
- package/intelligence/v1/reconciliation.schema.json +156 -0
- package/npm/bin/pakem.js +272 -0
- package/npm/check-version.js +26 -0
- package/package.json +58 -4
- package/policy/v1/README.md +15 -0
- package/policy/v1/policy.schema.json +20 -0
- package/protocol/v1/README.md +68 -0
- package/protocol/v1/capabilities.schema.json +17 -0
- package/protocol/v1/event.schema.json +114 -0
- package/protocol/v1/session.schema.json +51 -0
- package/references/artifacts.md +96 -0
- package/references/conventions.md +83 -0
- package/references/reviews.md +44 -0
- package/runtime/v1/README.md +21 -0
- package/runtime/v1/approval.schema.json +100 -0
- package/runtime/v1/checkpoint.schema.json +17 -0
- package/runtime/v1/hook-decision.schema.json +34 -0
- package/runtime/v1/hook-payload.schema.json +12 -0
- package/runtime/v1/task-evidence.schema.json +38 -0
- package/runtime/v1/work-report.schema.json +123 -0
- package/runtime/v1/workflow.schema.json +21 -0
- package/scripts/__pycache__/pakem.cpython-312.pyc +0 -0
- package/scripts/pakem.py +4911 -0
- package/scripts/pakem_core/__init__.py +3 -0
- package/scripts/pakem_core/__pycache__/__init__.cpython-312.pyc +0 -0
- package/scripts/pakem_core/__pycache__/coordination.cpython-312.pyc +0 -0
- package/scripts/pakem_core/__pycache__/git_worktree.cpython-312.pyc +0 -0
- package/scripts/pakem_core/__pycache__/identity.cpython-312.pyc +0 -0
- package/scripts/pakem_core/__pycache__/intelligence.cpython-312.pyc +0 -0
- package/scripts/pakem_core/__pycache__/mcp_server.cpython-312.pyc +0 -0
- package/scripts/pakem_core/__pycache__/protocol.cpython-312.pyc +0 -0
- package/scripts/pakem_core/__pycache__/reconcile.cpython-312.pyc +0 -0
- package/scripts/pakem_core/__pycache__/runtime.cpython-312.pyc +0 -0
- package/scripts/pakem_core/coordination.py +977 -0
- package/scripts/pakem_core/git_worktree.py +265 -0
- package/scripts/pakem_core/identity.py +494 -0
- package/scripts/pakem_core/intelligence.py +684 -0
- package/scripts/pakem_core/mcp_server.py +308 -0
- package/scripts/pakem_core/protocol.py +61 -0
- package/scripts/pakem_core/reconcile.py +119 -0
- package/scripts/pakem_core/runtime.py +457 -0
- package/scripts/run_evals.py +289 -0
- package/storage/v1/README.md +14 -0
- package/storage/v1/team-storage.schema.json +27 -0
|
@@ -0,0 +1,457 @@
|
|
|
1
|
+
"""Pakem Autonomous Runtime primitives (stdlib-only, no agent execution).
|
|
2
|
+
|
|
3
|
+
This module stores workflow state, checkpoints, policy decisions and lifecycle
|
|
4
|
+
hook receipts. It deliberately does not execute commands, deploy code, or spawn
|
|
5
|
+
agents; those remain responsibilities of a host runtime.
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import hashlib
|
|
10
|
+
import json
|
|
11
|
+
import os
|
|
12
|
+
import re
|
|
13
|
+
import subprocess
|
|
14
|
+
import tempfile
|
|
15
|
+
import uuid
|
|
16
|
+
from datetime import datetime, timedelta, timezone
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
from typing import Any
|
|
19
|
+
|
|
20
|
+
RUNTIME_SCHEMA_VERSION = 1
|
|
21
|
+
POLICY_SCHEMA_VERSION = 1
|
|
22
|
+
STATES = {
|
|
23
|
+
"initialized", "planning", "ready", "executing", "verifying",
|
|
24
|
+
"blocked", "recovering", "completed", "failed",
|
|
25
|
+
}
|
|
26
|
+
TERMINAL_STATES = {"completed", "failed"}
|
|
27
|
+
TRANSITIONS = {
|
|
28
|
+
"initialized": {"planning", "ready", "blocked", "failed"},
|
|
29
|
+
"planning": {"ready", "blocked", "failed"},
|
|
30
|
+
"ready": {"planning", "executing", "blocked", "failed"},
|
|
31
|
+
"executing": {"verifying", "blocked", "failed", "recovering"},
|
|
32
|
+
"verifying": {"completed", "executing", "blocked", "failed", "recovering"},
|
|
33
|
+
"blocked": {"planning", "ready", "executing", "recovering", "failed"},
|
|
34
|
+
"recovering": {"planning", "ready", "executing", "verifying", "blocked", "failed"},
|
|
35
|
+
"failed": {"recovering", "planning"},
|
|
36
|
+
"completed": set(),
|
|
37
|
+
}
|
|
38
|
+
CATEGORIES = {"read", "write", "command", "destructive", "deploy", "security", "policy_change", "gate_change"}
|
|
39
|
+
RISKS = {"low", "medium", "high", "critical"}
|
|
40
|
+
RISK_RANK = {"low": 0, "medium": 1, "high": 2, "critical": 3}
|
|
41
|
+
AUTONOMY_MODES = {"manual", "assisted", "guarded_autonomous"}
|
|
42
|
+
HOOKS = {"session.start", "task.before", "task.after", "verification.before", "session.finish", "handover"}
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def now() -> str:
|
|
46
|
+
return datetime.now(timezone.utc).astimezone().isoformat(timespec="seconds")
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _atomic_json(path: Path, data: dict, private: bool = True) -> None:
|
|
50
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
51
|
+
fd, tmp = tempfile.mkstemp(prefix=f".{path.name}.", suffix=".tmp", dir=str(path.parent))
|
|
52
|
+
try:
|
|
53
|
+
if private:
|
|
54
|
+
try:
|
|
55
|
+
os.chmod(tmp, 0o600)
|
|
56
|
+
except OSError:
|
|
57
|
+
pass
|
|
58
|
+
with os.fdopen(fd, "w", encoding="utf-8", newline="\n") as stream:
|
|
59
|
+
json.dump(data, stream, ensure_ascii=False, indent=2)
|
|
60
|
+
stream.write("\n")
|
|
61
|
+
stream.flush()
|
|
62
|
+
os.fsync(stream.fileno())
|
|
63
|
+
os.replace(tmp, path)
|
|
64
|
+
finally:
|
|
65
|
+
if os.path.exists(tmp):
|
|
66
|
+
try:
|
|
67
|
+
os.unlink(tmp)
|
|
68
|
+
except OSError:
|
|
69
|
+
pass
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _read_json(path: Path, default=None):
|
|
73
|
+
if not path.is_file():
|
|
74
|
+
return default
|
|
75
|
+
try:
|
|
76
|
+
return json.loads(path.read_text(encoding="utf-8"))
|
|
77
|
+
except (OSError, json.JSONDecodeError) as exc:
|
|
78
|
+
raise ValueError(f"invalid runtime JSON in {path.name}: {exc}") from exc
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def runtime_dir(root: Path) -> Path:
|
|
82
|
+
return root / ".pakem" / "runtime"
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def workflow_path(root: Path) -> Path:
|
|
86
|
+
return runtime_dir(root) / "workflow.json"
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def policy_path(root: Path) -> Path:
|
|
90
|
+
return root / ".pakem" / "POLICY.json"
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def approvals_path(root: Path) -> Path:
|
|
94
|
+
return runtime_dir(root) / "approvals.json"
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def default_policy() -> dict:
|
|
98
|
+
return {
|
|
99
|
+
"schemaVersion": POLICY_SCHEMA_VERSION,
|
|
100
|
+
"autonomy": "assisted",
|
|
101
|
+
"maxAutonomousRisk": "medium",
|
|
102
|
+
"approvalRequiredFor": ["destructive", "deploy", "security", "policy_change", "gate_change"],
|
|
103
|
+
"deniedCategories": [],
|
|
104
|
+
"approvalTtlSeconds": 900,
|
|
105
|
+
"description": "Normal project edits may proceed; sensitive or high-risk actions require host-mediated approval.",
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def validate_policy(policy: object) -> list[str]:
|
|
110
|
+
if not isinstance(policy, dict):
|
|
111
|
+
return ["policy must be a JSON object"]
|
|
112
|
+
errors = []
|
|
113
|
+
allowed = {"schemaVersion", "autonomy", "maxAutonomousRisk", "approvalRequiredFor", "deniedCategories", "approvalTtlSeconds", "description"}
|
|
114
|
+
unknown = sorted(set(policy) - allowed)
|
|
115
|
+
if unknown:
|
|
116
|
+
errors.append("unknown policy fields: " + ", ".join(unknown))
|
|
117
|
+
if not isinstance(policy.get("schemaVersion"), int) or isinstance(policy.get("schemaVersion"), bool) or policy.get("schemaVersion") != POLICY_SCHEMA_VERSION:
|
|
118
|
+
errors.append("schemaVersion must be the integer 1")
|
|
119
|
+
if policy.get("autonomy") not in AUTONOMY_MODES:
|
|
120
|
+
errors.append("autonomy must be manual, assisted, or guarded_autonomous")
|
|
121
|
+
if policy.get("maxAutonomousRisk") not in RISKS:
|
|
122
|
+
errors.append("maxAutonomousRisk is not known")
|
|
123
|
+
for key in ("approvalRequiredFor", "deniedCategories"):
|
|
124
|
+
values = policy.get(key)
|
|
125
|
+
if not isinstance(values, list) or any(v not in CATEGORIES for v in values) or len(values) != len(set(values)):
|
|
126
|
+
errors.append(f"{key} must be an array of unique valid Pakem categories")
|
|
127
|
+
ttl = policy.get("approvalTtlSeconds")
|
|
128
|
+
if not isinstance(ttl, int) or isinstance(ttl, bool) or not 30 <= ttl <= 86400:
|
|
129
|
+
errors.append("approvalTtlSeconds must be an integer between 30 and 86400")
|
|
130
|
+
return errors
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def ensure_policy(root: Path, template: Path | None = None) -> bool:
|
|
134
|
+
dst = policy_path(root)
|
|
135
|
+
if dst.exists():
|
|
136
|
+
return False
|
|
137
|
+
policy = default_policy()
|
|
138
|
+
if template and template.is_file():
|
|
139
|
+
loaded = _read_json(template)
|
|
140
|
+
if not validate_policy(loaded):
|
|
141
|
+
policy = loaded
|
|
142
|
+
_atomic_json(dst, policy, private=False)
|
|
143
|
+
return True
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def load_policy(root: Path) -> dict:
|
|
147
|
+
policy = _read_json(policy_path(root), default_policy())
|
|
148
|
+
errors = validate_policy(policy)
|
|
149
|
+
if errors:
|
|
150
|
+
raise ValueError("POLICY.json is invalid: " + "; ".join(errors))
|
|
151
|
+
return policy
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def _git_snapshot(root: Path) -> dict:
|
|
155
|
+
def git(*args):
|
|
156
|
+
try:
|
|
157
|
+
result = subprocess.run(["git", *args], cwd=root, capture_output=True,
|
|
158
|
+
text=True, timeout=5, check=False)
|
|
159
|
+
return result.stdout.strip() if result.returncode == 0 else None
|
|
160
|
+
except (OSError, subprocess.TimeoutExpired):
|
|
161
|
+
return None
|
|
162
|
+
return {"head": git("rev-parse", "HEAD"),
|
|
163
|
+
"status": (git("status", "--short") or "").splitlines() if git("rev-parse", "--is-inside-work-tree") else None}
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def load_workflow(root: Path) -> dict | None:
|
|
167
|
+
workflow = _read_json(workflow_path(root))
|
|
168
|
+
if workflow is None:
|
|
169
|
+
return None
|
|
170
|
+
errors = validate_workflow(workflow)
|
|
171
|
+
if errors:
|
|
172
|
+
raise ValueError("workflow state is invalid: " + "; ".join(errors))
|
|
173
|
+
return workflow
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def validate_workflow(workflow: object) -> list[str]:
|
|
177
|
+
if not isinstance(workflow, dict):
|
|
178
|
+
return ["workflow must be a JSON object"]
|
|
179
|
+
errors = []
|
|
180
|
+
if workflow.get("schemaVersion") != RUNTIME_SCHEMA_VERSION:
|
|
181
|
+
errors.append("workflow schemaVersion must be 1")
|
|
182
|
+
if not isinstance(workflow.get("workflowId"), str) or not workflow.get("workflowId"):
|
|
183
|
+
errors.append("workflowId must be a string")
|
|
184
|
+
if workflow.get("state") not in STATES:
|
|
185
|
+
errors.append("workflow state is not known")
|
|
186
|
+
if not isinstance(workflow.get("revision"), int) or isinstance(workflow.get("revision"), bool) or workflow.get("revision", 0) < 1:
|
|
187
|
+
errors.append("workflow revision must be a positive integer")
|
|
188
|
+
if not isinstance(workflow.get("checkpointIds", []), list):
|
|
189
|
+
errors.append("checkpointIds must be an array")
|
|
190
|
+
return errors
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def init_workflow(root: Path, goal: str = "", new: bool = False) -> dict:
|
|
194
|
+
current = load_workflow(root)
|
|
195
|
+
path = workflow_path(root)
|
|
196
|
+
if current and not new:
|
|
197
|
+
raise ValueError(f"workflow already exists (state={current['state']}); use runtime status or --new")
|
|
198
|
+
if current and current["state"] not in TERMINAL_STATES:
|
|
199
|
+
raise ValueError("an active workflow must not be overwritten; complete it or mark it failed before --new")
|
|
200
|
+
if current:
|
|
201
|
+
archive = runtime_dir(root) / "archives" / f"{current['workflowId']}.json"
|
|
202
|
+
if not archive.exists():
|
|
203
|
+
_atomic_json(archive, current)
|
|
204
|
+
workflow = {
|
|
205
|
+
"schemaVersion": RUNTIME_SCHEMA_VERSION,
|
|
206
|
+
"workflowId": str(uuid.uuid4()),
|
|
207
|
+
"state": "planning",
|
|
208
|
+
"goal": goal.strip(),
|
|
209
|
+
"revision": 1,
|
|
210
|
+
"createdAt": now(),
|
|
211
|
+
"updatedAt": now(),
|
|
212
|
+
"activeSessionId": None,
|
|
213
|
+
"currentTaskId": None,
|
|
214
|
+
"checkpointIds": [],
|
|
215
|
+
"lastTransition": {"from": None, "to": "planning", "reason": "workflow initialized", "at": now()},
|
|
216
|
+
}
|
|
217
|
+
_atomic_json(path, workflow)
|
|
218
|
+
return workflow
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
def _checkpoint(root: Path, workflow: dict, label: str) -> dict:
|
|
222
|
+
cid = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%S") + "-" + uuid.uuid4().hex[:8]
|
|
223
|
+
snapshot = {
|
|
224
|
+
"schemaVersion": 1,
|
|
225
|
+
"checkpointId": cid,
|
|
226
|
+
"workflowId": workflow["workflowId"],
|
|
227
|
+
"label": label[:120],
|
|
228
|
+
"createdAt": now(),
|
|
229
|
+
"workflow": workflow,
|
|
230
|
+
"repository": _git_snapshot(root),
|
|
231
|
+
}
|
|
232
|
+
directory = runtime_dir(root) / "checkpoints"
|
|
233
|
+
_atomic_json(directory / f"{cid}.json", snapshot)
|
|
234
|
+
ids = list(workflow.get("checkpointIds", []))
|
|
235
|
+
ids.append(cid)
|
|
236
|
+
workflow["checkpointIds"] = ids[-100:]
|
|
237
|
+
return snapshot
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
def create_checkpoint(root: Path, label: str = "manual") -> dict:
|
|
241
|
+
workflow = load_workflow(root)
|
|
242
|
+
if not workflow:
|
|
243
|
+
raise ValueError("no workflow yet; run pakem runtime init")
|
|
244
|
+
snap = _checkpoint(root, workflow, label or "manual")
|
|
245
|
+
workflow["revision"] += 1
|
|
246
|
+
workflow["updatedAt"] = now()
|
|
247
|
+
workflow["lastCheckpointId"] = snap["checkpointId"]
|
|
248
|
+
_atomic_json(workflow_path(root), workflow)
|
|
249
|
+
return snap
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
def transition_workflow(root: Path, target: str, reason: str = "", task_id: str | None = None) -> tuple[dict, dict | None]:
|
|
253
|
+
workflow = load_workflow(root)
|
|
254
|
+
if not workflow:
|
|
255
|
+
raise ValueError("no workflow yet; run pakem runtime init")
|
|
256
|
+
if target not in STATES:
|
|
257
|
+
raise ValueError(f"unknown state: {target}")
|
|
258
|
+
source = workflow["state"]
|
|
259
|
+
if target not in TRANSITIONS[source]:
|
|
260
|
+
raise ValueError(f"transition not allowed: {source} -> {target}")
|
|
261
|
+
snap = None
|
|
262
|
+
if source in {"executing", "verifying", "blocked", "recovering"}:
|
|
263
|
+
snap = _checkpoint(root, workflow, f"before-{source}-to-{target}")
|
|
264
|
+
workflow["state"] = target
|
|
265
|
+
workflow["revision"] += 1
|
|
266
|
+
workflow["updatedAt"] = now()
|
|
267
|
+
workflow["lastTransition"] = {"from": source, "to": target,
|
|
268
|
+
"reason": reason.strip()[:500], "at": now()}
|
|
269
|
+
if task_id is not None:
|
|
270
|
+
workflow["currentTaskId"] = task_id
|
|
271
|
+
if target == "completed":
|
|
272
|
+
workflow["completedAt"] = now()
|
|
273
|
+
_atomic_json(workflow_path(root), workflow)
|
|
274
|
+
return workflow, snap
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
def _safe_checkpoint_path(root: Path, checkpoint_id: str) -> Path:
|
|
278
|
+
if not re.fullmatch(r"[A-Za-z0-9T_-]{1,80}", checkpoint_id):
|
|
279
|
+
raise ValueError("checkpoint ID is not valid")
|
|
280
|
+
return runtime_dir(root) / "checkpoints" / f"{checkpoint_id}.json"
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
def recover_workflow(root: Path, checkpoint_id: str | None = None) -> tuple[dict, dict]:
|
|
284
|
+
workflow = load_workflow(root)
|
|
285
|
+
if not workflow:
|
|
286
|
+
raise ValueError("no workflow yet; run pakem runtime init")
|
|
287
|
+
ids = workflow.get("checkpointIds", [])
|
|
288
|
+
selected = checkpoint_id or (ids[-1] if ids else None)
|
|
289
|
+
if not selected:
|
|
290
|
+
raise ValueError("no checkpoint to recover from")
|
|
291
|
+
checkpoint = _read_json(_safe_checkpoint_path(root, selected))
|
|
292
|
+
if not isinstance(checkpoint, dict) or checkpoint.get("workflowId") != workflow["workflowId"]:
|
|
293
|
+
raise ValueError("checkpoint not found or does not belong to the active workflow")
|
|
294
|
+
saved = checkpoint.get("workflow")
|
|
295
|
+
errors = validate_workflow(saved)
|
|
296
|
+
if errors:
|
|
297
|
+
raise ValueError("checkpoint snapshot is corrupt: " + "; ".join(errors))
|
|
298
|
+
before = workflow["state"]
|
|
299
|
+
restored = dict(saved)
|
|
300
|
+
restored["state"] = "recovering"
|
|
301
|
+
restored["revision"] = workflow["revision"] + 1
|
|
302
|
+
restored["updatedAt"] = now()
|
|
303
|
+
restored["lastTransition"] = {"from": before, "to": "recovering",
|
|
304
|
+
"reason": f"recovered from checkpoint {selected}", "at": now()}
|
|
305
|
+
restored["recoveredFrom"] = selected
|
|
306
|
+
restored["checkpointIds"] = list(dict.fromkeys(ids + [selected]))[-100:]
|
|
307
|
+
current_repo = _git_snapshot(root)
|
|
308
|
+
saved_repo = checkpoint.get("repository") or {}
|
|
309
|
+
drift = {"head_changed": bool(saved_repo.get("head") and current_repo.get("head") and
|
|
310
|
+
saved_repo.get("head") != current_repo.get("head")),
|
|
311
|
+
"working_tree_changed": saved_repo.get("status") != current_repo.get("status")}
|
|
312
|
+
_atomic_json(workflow_path(root), restored)
|
|
313
|
+
return restored, {"checkpoint_id": selected, "drift": drift,
|
|
314
|
+
"saved_repository": saved_repo, "current_repository": current_repo}
|
|
315
|
+
|
|
316
|
+
|
|
317
|
+
def _approval_scope(category: str, risk: str, target: str, workflow_id: str | None) -> str:
|
|
318
|
+
raw = json.dumps([category, risk, target.strip(), workflow_id or ""], separators=(",", ":"))
|
|
319
|
+
return hashlib.sha256(raw.encode("utf-8")).hexdigest()
|
|
320
|
+
|
|
321
|
+
|
|
322
|
+
def _load_approvals(root: Path) -> list[dict]:
|
|
323
|
+
data = _read_json(approvals_path(root), {"schemaVersion": 1, "approvals": []})
|
|
324
|
+
if not isinstance(data, dict) or data.get("schemaVersion") != 1 or not isinstance(data.get("approvals"), list):
|
|
325
|
+
raise ValueError("runtime approvals store is not valid")
|
|
326
|
+
return data["approvals"]
|
|
327
|
+
|
|
328
|
+
|
|
329
|
+
def grant_approval(root: Path, category: str, risk: str, target: str = "", reason: str = "") -> dict:
|
|
330
|
+
if category not in CATEGORIES or risk not in RISKS:
|
|
331
|
+
raise ValueError("unknown category or risk")
|
|
332
|
+
if not reason.strip():
|
|
333
|
+
raise ValueError("approval requires --reason")
|
|
334
|
+
policy = load_policy(root)
|
|
335
|
+
workflow = load_workflow(root)
|
|
336
|
+
workflow_id = workflow.get("workflowId") if workflow else None
|
|
337
|
+
approval = {
|
|
338
|
+
"approvalId": uuid.uuid4().hex,
|
|
339
|
+
"category": category,
|
|
340
|
+
"risk": risk,
|
|
341
|
+
"targetHash": hashlib.sha256(target.strip().encode("utf-8")).hexdigest() if target.strip() else None,
|
|
342
|
+
"scopeHash": _approval_scope(category, risk, target, workflow_id),
|
|
343
|
+
"workflowId": workflow_id,
|
|
344
|
+
"reason": reason.strip()[:500],
|
|
345
|
+
"grantedAt": now(),
|
|
346
|
+
"expiresAt": (datetime.now(timezone.utc) + timedelta(seconds=policy["approvalTtlSeconds"])).isoformat(timespec="seconds"),
|
|
347
|
+
"consumedAt": None,
|
|
348
|
+
}
|
|
349
|
+
approvals = _load_approvals(root)
|
|
350
|
+
approvals.append(approval)
|
|
351
|
+
_atomic_json(approvals_path(root), {"schemaVersion": 1, "approvals": approvals[-500:]})
|
|
352
|
+
return approval
|
|
353
|
+
|
|
354
|
+
|
|
355
|
+
def evaluate_policy(root: Path, category: str, risk: str, target: str = "",
|
|
356
|
+
approval_id: str | None = None) -> dict:
|
|
357
|
+
if category not in CATEGORIES:
|
|
358
|
+
raise ValueError(f"unknown category: {category}")
|
|
359
|
+
if risk not in RISKS:
|
|
360
|
+
raise ValueError(f"unknown risk: {risk}")
|
|
361
|
+
policy = load_policy(root)
|
|
362
|
+
workflow = load_workflow(root)
|
|
363
|
+
workflow_id = workflow.get("workflowId") if workflow else None
|
|
364
|
+
denied = category in policy["deniedCategories"]
|
|
365
|
+
approval_required = category in policy["approvalRequiredFor"]
|
|
366
|
+
if policy["autonomy"] == "manual" and category != "read":
|
|
367
|
+
approval_required = True
|
|
368
|
+
if policy["autonomy"] == "assisted" and category == "command" and risk != "low":
|
|
369
|
+
approval_required = True
|
|
370
|
+
if RISK_RANK[risk] > RISK_RANK[policy["maxAutonomousRisk"]]:
|
|
371
|
+
approval_required = True
|
|
372
|
+
if denied:
|
|
373
|
+
return {"decision": "deny", "allowed": False, "requiresApproval": False,
|
|
374
|
+
"reason": f"category {category} is denied by policy", "category": category, "risk": risk}
|
|
375
|
+
|
|
376
|
+
consumed = None
|
|
377
|
+
if approval_id:
|
|
378
|
+
approvals = _load_approvals(root)
|
|
379
|
+
for item in approvals:
|
|
380
|
+
if item.get("approvalId") != approval_id:
|
|
381
|
+
continue
|
|
382
|
+
expected = _approval_scope(category, risk, target, workflow_id)
|
|
383
|
+
try:
|
|
384
|
+
expired = datetime.fromisoformat(item.get("expiresAt", "")) <= datetime.now(timezone.utc)
|
|
385
|
+
except (TypeError, ValueError):
|
|
386
|
+
expired = True
|
|
387
|
+
valid = (not item.get("consumedAt") and not expired and
|
|
388
|
+
item.get("scopeHash") == expected and item.get("workflowId") == workflow_id)
|
|
389
|
+
if valid:
|
|
390
|
+
item["consumedAt"] = now()
|
|
391
|
+
_atomic_json(approvals_path(root), {"schemaVersion": 1, "approvals": approvals})
|
|
392
|
+
consumed = approval_id
|
|
393
|
+
break
|
|
394
|
+
if consumed:
|
|
395
|
+
return {"decision": "allow", "allowed": True, "requiresApproval": False,
|
|
396
|
+
"reason": "explicit approval matches, is not expired, and is consumed once",
|
|
397
|
+
"category": category, "risk": risk, "approvalId": consumed}
|
|
398
|
+
return {"decision": "require_approval", "allowed": False, "requiresApproval": True,
|
|
399
|
+
"reason": "approval ID is not valid, expired, already used, or scope does not match",
|
|
400
|
+
"category": category, "risk": risk}
|
|
401
|
+
|
|
402
|
+
if approval_required:
|
|
403
|
+
return {"decision": "require_approval", "allowed": False, "requiresApproval": True,
|
|
404
|
+
"reason": "category or risk level requires explicit approval",
|
|
405
|
+
"category": category, "risk": risk}
|
|
406
|
+
return {"decision": "allow", "allowed": True, "requiresApproval": False,
|
|
407
|
+
"reason": f"allowed by mode {policy['autonomy']} for risk {risk}",
|
|
408
|
+
"category": category, "risk": risk}
|
|
409
|
+
|
|
410
|
+
|
|
411
|
+
def dispatch_hook(root: Path, hook: str, payload: dict | None = None,
|
|
412
|
+
approval_id: str | None = None) -> dict:
|
|
413
|
+
if hook not in HOOKS:
|
|
414
|
+
raise ValueError(f"unknown hook: {hook}; choose one of: {', '.join(sorted(HOOKS))}")
|
|
415
|
+
if payload is None:
|
|
416
|
+
payload = {}
|
|
417
|
+
if not isinstance(payload, dict):
|
|
418
|
+
raise ValueError("hook payload must be a JSON object")
|
|
419
|
+
defaults = {
|
|
420
|
+
"session.start": ("read", "low"),
|
|
421
|
+
"task.before": ("write", "medium"),
|
|
422
|
+
"task.after": ("read", "low"),
|
|
423
|
+
"verification.before": ("command", "low"),
|
|
424
|
+
"session.finish": ("read", "low"),
|
|
425
|
+
"handover": ("write", "medium"),
|
|
426
|
+
}
|
|
427
|
+
default_category, default_risk = defaults[hook]
|
|
428
|
+
category = payload.get("category", default_category)
|
|
429
|
+
risk = payload.get("risk", default_risk)
|
|
430
|
+
target = payload.get("target", "")
|
|
431
|
+
if not isinstance(target, str):
|
|
432
|
+
raise ValueError("payload.target must be a string")
|
|
433
|
+
result = evaluate_policy(root, category, risk, target, approval_id=approval_id)
|
|
434
|
+
encoded_payload = json.dumps(payload, ensure_ascii=False, sort_keys=True, separators=(",", ":"))
|
|
435
|
+
receipt = {
|
|
436
|
+
"hook": hook, "occurredAt": now(), "decision": result["decision"],
|
|
437
|
+
"category": category, "risk": risk,
|
|
438
|
+
"targetHash": hashlib.sha256(target.encode("utf-8")).hexdigest() if target else None,
|
|
439
|
+
"payloadHash": hashlib.sha256(encoded_payload.encode("utf-8")).hexdigest(),
|
|
440
|
+
"reason": result["reason"],
|
|
441
|
+
}
|
|
442
|
+
path = runtime_dir(root) / "hooks.jsonl"
|
|
443
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
444
|
+
line = (json.dumps(receipt, ensure_ascii=False, separators=(",", ":")) + "\n").encode("utf-8")
|
|
445
|
+
fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_APPEND, 0o600)
|
|
446
|
+
try:
|
|
447
|
+
view = memoryview(line)
|
|
448
|
+
while view:
|
|
449
|
+
written = os.write(fd, view)
|
|
450
|
+
if written <= 0:
|
|
451
|
+
raise OSError("runtime hook ledger write made no progress")
|
|
452
|
+
view = view[written:]
|
|
453
|
+
os.fsync(fd)
|
|
454
|
+
finally:
|
|
455
|
+
os.close(fd)
|
|
456
|
+
return {"protocol": "pakem", "runtime_version": 1, "hook": hook, **result,
|
|
457
|
+
"receipt": {k: v for k, v in receipt.items() if k != "payloadHash"}}
|