pakem-cli 0.0.0-stage → 1.2.1

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 (76) hide show
  1. package/CHANGELOG.md +271 -0
  2. package/LICENSE +21 -0
  3. package/README-ID.md +665 -0
  4. package/README.md +664 -2
  5. package/SKILL.md +264 -0
  6. package/adapters/git-worktree/v1/README.md +17 -0
  7. package/adapters/identity/v1/README.md +26 -0
  8. package/adapters/mcp/v1/README.md +56 -0
  9. package/adapters/storage-sqlite/v1/README.md +5 -0
  10. package/assets/banner.svg +275 -0
  11. package/assets/divider.svg +82 -0
  12. package/assets/footer.svg +174 -0
  13. package/assets/templates/BUG-HISTORY.md +18 -0
  14. package/assets/templates/CONTEXT.md +26 -0
  15. package/assets/templates/DECISIONS.md +8 -0
  16. package/assets/templates/MODULE-MAP.md +14 -0
  17. package/assets/templates/POLICY.json +15 -0
  18. package/assets/templates/PROJECT.md +42 -0
  19. package/conformance/v1/README.md +15 -0
  20. package/coordination/v1/README.md +14 -0
  21. package/coordination/v1/board.schema.json +59 -0
  22. package/coordination/v1/event.schema.json +26 -0
  23. package/coordination/v1/status.schema.json +49 -0
  24. package/evals/README.md +63 -0
  25. package/evals/evals.json +276 -0
  26. package/identity/v1/README.md +14 -0
  27. package/identity/v1/agent-identity.schema.json +95 -0
  28. package/identity/v1/identity-registry.schema.json +29 -0
  29. package/identity/v1/signed-payload.schema.json +42 -0
  30. package/intelligence/v1/README.md +19 -0
  31. package/intelligence/v1/dependency-graph.schema.json +82 -0
  32. package/intelligence/v1/impact-analysis.schema.json +51 -0
  33. package/intelligence/v1/reconciliation.schema.json +156 -0
  34. package/npm/bin/pakem.js +150 -0
  35. package/npm/check-version.js +26 -0
  36. package/package.json +55 -4
  37. package/policy/v1/README.md +15 -0
  38. package/policy/v1/policy.schema.json +20 -0
  39. package/protocol/v1/README.md +68 -0
  40. package/protocol/v1/capabilities.schema.json +17 -0
  41. package/protocol/v1/event.schema.json +114 -0
  42. package/protocol/v1/session.schema.json +51 -0
  43. package/references/artifacts.md +96 -0
  44. package/references/conventions.md +83 -0
  45. package/references/reviews.md +44 -0
  46. package/runtime/v1/README.md +21 -0
  47. package/runtime/v1/approval.schema.json +100 -0
  48. package/runtime/v1/checkpoint.schema.json +17 -0
  49. package/runtime/v1/hook-decision.schema.json +34 -0
  50. package/runtime/v1/hook-payload.schema.json +12 -0
  51. package/runtime/v1/task-evidence.schema.json +38 -0
  52. package/runtime/v1/work-report.schema.json +123 -0
  53. package/runtime/v1/workflow.schema.json +21 -0
  54. package/scripts/__pycache__/pakem.cpython-312.pyc +0 -0
  55. package/scripts/pakem.py +4911 -0
  56. package/scripts/pakem_core/__init__.py +3 -0
  57. package/scripts/pakem_core/__pycache__/__init__.cpython-312.pyc +0 -0
  58. package/scripts/pakem_core/__pycache__/coordination.cpython-312.pyc +0 -0
  59. package/scripts/pakem_core/__pycache__/git_worktree.cpython-312.pyc +0 -0
  60. package/scripts/pakem_core/__pycache__/identity.cpython-312.pyc +0 -0
  61. package/scripts/pakem_core/__pycache__/intelligence.cpython-312.pyc +0 -0
  62. package/scripts/pakem_core/__pycache__/mcp_server.cpython-312.pyc +0 -0
  63. package/scripts/pakem_core/__pycache__/protocol.cpython-312.pyc +0 -0
  64. package/scripts/pakem_core/__pycache__/reconcile.cpython-312.pyc +0 -0
  65. package/scripts/pakem_core/__pycache__/runtime.cpython-312.pyc +0 -0
  66. package/scripts/pakem_core/coordination.py +977 -0
  67. package/scripts/pakem_core/git_worktree.py +265 -0
  68. package/scripts/pakem_core/identity.py +494 -0
  69. package/scripts/pakem_core/intelligence.py +684 -0
  70. package/scripts/pakem_core/mcp_server.py +308 -0
  71. package/scripts/pakem_core/protocol.py +61 -0
  72. package/scripts/pakem_core/reconcile.py +119 -0
  73. package/scripts/pakem_core/runtime.py +457 -0
  74. package/scripts/run_evals.py +289 -0
  75. package/storage/v1/README.md +14 -0
  76. package/storage/v1/team-storage.schema.json +27 -0
@@ -0,0 +1,977 @@
1
+ """Pakem Multi-Agent Coordination primitives.
2
+
3
+ The module coordinates cooperative agents through a shared task board, leases,
4
+ explicit handoffs, and independent review. It does not authenticate agent IDs,
5
+ spawn agents, merge branches, or execute commands; a trusted host runtime must
6
+ bind caller identity and enforce the returned state/policy.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import contextlib
11
+ import json
12
+ import os
13
+ import re
14
+ import sqlite3
15
+ import tempfile
16
+ import time
17
+ import uuid
18
+ from datetime import datetime, timedelta, timezone
19
+ from pathlib import Path, PurePosixPath, PureWindowsPath
20
+ from typing import Any
21
+
22
+ SCHEMA_VERSION = 1
23
+ TASK_STATES = {"open", "claimed", "review", "done", "blocked"}
24
+ COORDINATION_EVENTS = {
25
+ "team.agent.registered", "team.task.created", "team.task.assigned",
26
+ "team.task.claimed", "team.task.heartbeat", "team.task.released",
27
+ "team.task.handed_off", "team.task.submitted", "team.task.reviewed",
28
+ "team.task.blocked", "team.task.unblocked",
29
+ }
30
+ AGENT_ROLES = {"worker", "reviewer", "lead", "coordinator", "observer"}
31
+ RISKS = {"low", "medium", "high", "critical"}
32
+ RISK_RANK = {"low": 0, "medium": 1, "high": 2, "critical": 3}
33
+ _ID_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$")
34
+
35
+
36
+ def now() -> str:
37
+ return datetime.now(timezone.utc).astimezone().isoformat(timespec="seconds")
38
+
39
+
40
+ def _parse_time(value: str) -> datetime:
41
+ parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))
42
+ if parsed.tzinfo is None:
43
+ parsed = parsed.replace(tzinfo=timezone.utc)
44
+ return parsed.astimezone(timezone.utc)
45
+
46
+
47
+ def _safe_id(value: object, label: str) -> str:
48
+ if not isinstance(value, str) or not _ID_RE.fullmatch(value) or value in {".", ".."}:
49
+ raise ValueError(f"{label} must be 1-64 characters: letters, digits, dot, underscore, or hyphen")
50
+ return value
51
+
52
+
53
+ def _text(value: object, label: str, maximum: int, required: bool = True) -> str:
54
+ if not isinstance(value, str):
55
+ raise ValueError(f"{label} must be text")
56
+ value = value.strip()
57
+ if required and not value:
58
+ raise ValueError(f"{label} is required")
59
+ if len(value) > maximum:
60
+ raise ValueError(f"{label} must be at most {maximum} characters")
61
+ return value
62
+
63
+
64
+ def _string_list(values: object, label: str, maximum: int = 100) -> list[str]:
65
+ if values is None:
66
+ return []
67
+ if not isinstance(values, list) or len(values) > maximum:
68
+ raise ValueError(f"{label} must be an array with at most {maximum} items")
69
+ result = []
70
+ for value in values:
71
+ if not isinstance(value, str) or not value.strip() or len(value.strip()) > 500:
72
+ raise ValueError(f"item {label} must be non-empty text of at most 500 characters")
73
+ item = value.strip()
74
+ if item not in result:
75
+ result.append(item)
76
+ return result
77
+
78
+
79
+ def team_dir(root: Path) -> Path:
80
+ return root / ".pakem" / "team"
81
+
82
+
83
+ def board_path(root: Path) -> Path:
84
+ return team_dir(root) / "board.json"
85
+
86
+
87
+ def events_path(root: Path) -> Path:
88
+ return team_dir(root) / "events.jsonl"
89
+
90
+
91
+ def storage_config_path(root: Path) -> Path:
92
+ return team_dir(root) / "storage.json"
93
+
94
+
95
+ def sqlite_path(root: Path) -> Path:
96
+ return team_dir(root) / "team.sqlite3"
97
+
98
+
99
+ def _storage_backend(root: Path) -> str:
100
+ path = storage_config_path(root)
101
+ if path.is_symlink():
102
+ raise ValueError("team storage config must not be a symlink")
103
+ if not path.is_file():
104
+ return "jsonl"
105
+ try:
106
+ config = json.loads(path.read_text(encoding="utf-8"))
107
+ except (OSError, json.JSONDecodeError) as exc:
108
+ raise ValueError(f"team storage config is invalid: {exc}") from exc
109
+ if not isinstance(config, dict) or config.get("schemaVersion") != 1:
110
+ raise ValueError("team storage config must use schemaVersion 1")
111
+ backend = config.get("backend")
112
+ if backend not in {"jsonl", "sqlite"}:
113
+ raise ValueError("team storage backend must be jsonl or sqlite")
114
+ if backend == "sqlite" and config.get("backupFilesRetained") is not True:
115
+ raise ValueError("SQLite storage config must mark JSON backups as retained")
116
+ return backend
117
+
118
+
119
+ def _sqlite_connect(root: Path, create: bool = True) -> sqlite3.Connection:
120
+ path = sqlite_path(root)
121
+ if path.is_symlink():
122
+ raise ValueError("team SQLite database must not be a symlink")
123
+ if not create and not path.is_file():
124
+ raise ValueError("SQLite backend is configured but the database is missing; restore from backup before continuing")
125
+ path.parent.mkdir(parents=True, exist_ok=True)
126
+ connection = sqlite3.connect(path, timeout=30, isolation_level=None)
127
+ connection.row_factory = sqlite3.Row
128
+ connection.execute("PRAGMA busy_timeout=30000")
129
+ connection.execute("PRAGMA journal_mode=WAL")
130
+ connection.execute("PRAGMA synchronous=FULL")
131
+ connection.execute("""CREATE TABLE IF NOT EXISTS pakem_state (
132
+ singleton INTEGER PRIMARY KEY CHECK(singleton = 1),
133
+ board_json TEXT NOT NULL,
134
+ updated_at TEXT NOT NULL
135
+ )""")
136
+ connection.execute("""CREATE TABLE IF NOT EXISTS pakem_events (
137
+ seq INTEGER PRIMARY KEY AUTOINCREMENT,
138
+ event_id TEXT NOT NULL UNIQUE,
139
+ occurred_at TEXT NOT NULL,
140
+ event_name TEXT NOT NULL,
141
+ event_json TEXT NOT NULL
142
+ )""")
143
+ connection.execute("CREATE INDEX IF NOT EXISTS idx_pakem_events_name ON pakem_events(event_name)")
144
+ # Team records may contain task descriptions and operational metadata.
145
+ # Keep the database and SQLite sidecar files private on POSIX systems.
146
+ for candidate in (path, Path(str(path) + "-wal"), Path(str(path) + "-shm")):
147
+ if candidate.exists():
148
+ try:
149
+ os.chmod(candidate, 0o600)
150
+ except OSError:
151
+ pass
152
+ return connection
153
+
154
+
155
+ def _make_coordination_event(event: str, payload: dict) -> dict:
156
+ if event not in COORDINATION_EVENTS:
157
+ raise ValueError(f"unknown coordination event: {event}")
158
+ actor_name = (payload.get("actorId") or payload.get("by") or payload.get("reviewerId")
159
+ or payload.get("fromAgent") or payload.get("agentId") or "pakem-team")
160
+ return {
161
+ "protocol": "pakem", "protocol_version": "1.0", "event_id": str(uuid.uuid4()),
162
+ "event": event, "occurred_at": now(), "session_id": None,
163
+ "actor": {"type": "system" if actor_name == "pakem-team" else "agent", "name": str(actor_name)},
164
+ "payload": payload,
165
+ }
166
+
167
+
168
+ @contextlib.contextmanager
169
+ def _board_lock(root: Path):
170
+ """Cross-process advisory lock (flock on POSIX, msvcrt on Windows)."""
171
+ directory = team_dir(root)
172
+ directory.mkdir(parents=True, exist_ok=True)
173
+ lock_path = directory / ".board.lock"
174
+ stream = open(lock_path, "a+b")
175
+ try:
176
+ if os.name == "nt":
177
+ import msvcrt
178
+ stream.seek(0)
179
+ if stream.read(1) == b"":
180
+ stream.seek(0)
181
+ stream.write(b"0")
182
+ stream.flush()
183
+ stream.seek(0)
184
+ while True:
185
+ try:
186
+ msvcrt.locking(stream.fileno(), msvcrt.LK_NBLCK, 1)
187
+ break
188
+ except OSError:
189
+ time.sleep(0.05)
190
+ try:
191
+ yield
192
+ finally:
193
+ stream.seek(0)
194
+ msvcrt.locking(stream.fileno(), msvcrt.LK_UNLCK, 1)
195
+ else:
196
+ import fcntl
197
+ fcntl.flock(stream.fileno(), fcntl.LOCK_EX)
198
+ try:
199
+ yield
200
+ finally:
201
+ fcntl.flock(stream.fileno(), fcntl.LOCK_UN)
202
+ finally:
203
+ stream.close()
204
+
205
+
206
+ def _atomic_json(path: Path, data: dict) -> None:
207
+ path.parent.mkdir(parents=True, exist_ok=True)
208
+ fd, tmp = tempfile.mkstemp(prefix=f".{path.name}.", suffix=".tmp", dir=str(path.parent))
209
+ try:
210
+ try:
211
+ os.chmod(tmp, 0o600)
212
+ except OSError:
213
+ pass
214
+ with os.fdopen(fd, "w", encoding="utf-8", newline="\n") as stream:
215
+ json.dump(data, stream, ensure_ascii=False, indent=2)
216
+ stream.write("\n")
217
+ stream.flush()
218
+ os.fsync(stream.fileno())
219
+ os.replace(tmp, path)
220
+ finally:
221
+ if os.path.exists(tmp):
222
+ try:
223
+ os.unlink(tmp)
224
+ except OSError:
225
+ pass
226
+
227
+
228
+ def _default_board() -> dict:
229
+ stamp = now()
230
+ return {
231
+ "schemaVersion": SCHEMA_VERSION,
232
+ "boardId": str(uuid.uuid4()),
233
+ "revision": 1,
234
+ "createdAt": stamp,
235
+ "updatedAt": stamp,
236
+ "agents": {},
237
+ "tasks": {},
238
+ }
239
+
240
+
241
+ def _load_board_unlocked(root: Path, create: bool = False) -> dict | None:
242
+ if _storage_backend(root) == "sqlite":
243
+ connection = _sqlite_connect(root, create=create)
244
+ try:
245
+ row = connection.execute("SELECT board_json FROM pakem_state WHERE singleton=1").fetchone()
246
+ if row is None:
247
+ if not create:
248
+ return None
249
+ board = _default_board()
250
+ connection.execute("INSERT INTO pakem_state(singleton, board_json, updated_at) VALUES(1, ?, ?)",
251
+ (json.dumps(board, ensure_ascii=False), board["updatedAt"]))
252
+ return board
253
+ try:
254
+ board = json.loads(row["board_json"])
255
+ except json.JSONDecodeError as exc:
256
+ raise ValueError(f"invalid SQLite team board: {exc}") from exc
257
+ errors = validate_board(board)
258
+ if errors:
259
+ raise ValueError("invalid SQLite team board: " + "; ".join(errors))
260
+ return board
261
+ finally:
262
+ connection.close()
263
+ path = board_path(root)
264
+ if not path.is_file():
265
+ if not create:
266
+ return None
267
+ board = _default_board()
268
+ _atomic_json(path, board)
269
+ return board
270
+ try:
271
+ board = json.loads(path.read_text(encoding="utf-8"))
272
+ except (OSError, json.JSONDecodeError) as exc:
273
+ raise ValueError(f"invalid team board: {exc}") from exc
274
+ errors = validate_board(board)
275
+ if errors:
276
+ raise ValueError("invalid team board: " + "; ".join(errors))
277
+ return board
278
+
279
+
280
+ def validate_board(board: object) -> list[str]:
281
+ if not isinstance(board, dict):
282
+ return ["board must be an object"]
283
+ errors = []
284
+ if board.get("schemaVersion") != SCHEMA_VERSION:
285
+ errors.append("schemaVersion must be 1")
286
+ if not isinstance(board.get("boardId"), str) or not board.get("boardId"):
287
+ errors.append("boardId is required")
288
+ if not isinstance(board.get("revision"), int) or isinstance(board.get("revision"), bool) or board.get("revision", 0) < 1:
289
+ errors.append("revision must be a positive integer")
290
+ for key in ("agents", "tasks"):
291
+ if not isinstance(board.get(key), dict):
292
+ errors.append(f"{key} must be an object")
293
+ if errors:
294
+ return errors
295
+ for agent_id, agent in board["agents"].items():
296
+ try:
297
+ _safe_id(agent_id, "agent ID")
298
+ except ValueError as exc:
299
+ errors.append(str(exc))
300
+ if not isinstance(agent, dict) or agent.get("agentId") != agent_id:
301
+ errors.append(f"invalid agent {agent_id}")
302
+ continue
303
+ if agent.get("role") not in AGENT_ROLES:
304
+ errors.append(f"invalid role for agent {agent_id}")
305
+ capabilities = agent.get("capabilities", [])
306
+ if not isinstance(capabilities, list) or any(not isinstance(x, str) for x in capabilities):
307
+ errors.append(f"capabilities for agent {agent_id} must be an array of strings")
308
+ for task_id, task in board["tasks"].items():
309
+ try:
310
+ _safe_id(task_id, "task ID")
311
+ except ValueError as exc:
312
+ errors.append(str(exc))
313
+ if not isinstance(task, dict) or task.get("taskId") != task_id:
314
+ errors.append(f"invalid task {task_id}")
315
+ continue
316
+ if task.get("state") not in TASK_STATES:
317
+ errors.append(f"invalid state for task {task_id}")
318
+ if task.get("risk", "medium") not in RISKS:
319
+ errors.append(f"invalid risk for task {task_id}")
320
+ dependencies = task.get("dependsOn", [])
321
+ if not isinstance(dependencies, list) or any(not isinstance(x, str) for x in dependencies):
322
+ errors.append(f"dependsOn for task {task_id} must be an array of strings")
323
+ for task_id, task in board["tasks"].items():
324
+ if not isinstance(task, dict):
325
+ continue
326
+ for dependency in task.get("dependsOn", []):
327
+ if isinstance(dependency, str) and dependency not in board["tasks"]:
328
+ errors.append(f"dependency {dependency} for {task_id} not found")
329
+ assigned = task.get("assignedAgent")
330
+ owner = task.get("ownerAgent")
331
+ if assigned is not None and assigned not in board["agents"]:
332
+ errors.append(f"assignedAgent {assigned} for {task_id} is not registered")
333
+ if owner is not None and owner not in board["agents"]:
334
+ errors.append(f"ownerAgent {owner} for {task_id} is not registered")
335
+ if task.get("state") == "claimed":
336
+ if not owner or not task.get("leaseExpiresAt"):
337
+ errors.append(f"claimed task {task_id} must have ownerAgent and leaseExpiresAt")
338
+ elif isinstance(task.get("leaseExpiresAt"), str):
339
+ try:
340
+ _parse_time(task["leaseExpiresAt"])
341
+ except (TypeError, ValueError):
342
+ errors.append(f"leaseExpiresAt for {task_id} is not a valid date-time")
343
+ elif owner is not None or task.get("leaseExpiresAt") is not None:
344
+ errors.append(f"non-claimed task {task_id} must not have an active owner/lease")
345
+ if task.get("state") == "review" and not isinstance(task.get("submission"), dict):
346
+ errors.append(f"review task {task_id} must have a submission")
347
+ if task.get("state") == "done":
348
+ review = task.get("lastReview")
349
+ if not isinstance(task.get("submission"), dict) or not isinstance(review, dict) or review.get("decision") != "approve":
350
+ errors.append(f"done task {task_id} must have a submission and an approve review")
351
+ if not errors:
352
+ try:
353
+ _validate_dependency_graph(board["tasks"])
354
+ except (ValueError, TypeError) as exc:
355
+ errors.append(str(exc))
356
+ return errors
357
+
358
+
359
+ def _event_unlocked(root: Path, event: str, payload: dict) -> None:
360
+ record = _make_coordination_event(event, payload)
361
+ data = (json.dumps(record, ensure_ascii=False, separators=(",", ":")) + "\n").encode("utf-8")
362
+ path = events_path(root)
363
+ path.parent.mkdir(parents=True, exist_ok=True)
364
+ fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_APPEND, 0o600)
365
+ try:
366
+ view = memoryview(data)
367
+ while view:
368
+ written = os.write(fd, view)
369
+ if written <= 0:
370
+ raise OSError("event ledger write made no progress")
371
+ view = view[written:]
372
+ os.fsync(fd)
373
+ finally:
374
+ os.close(fd)
375
+
376
+
377
+ def _commit(root: Path, board: dict, event: str, payload: dict) -> dict:
378
+ board["revision"] += 1
379
+ board["updatedAt"] = now()
380
+ if _storage_backend(root) == "sqlite":
381
+ record = _make_coordination_event(event, payload)
382
+ connection = _sqlite_connect(root, create=False)
383
+ try:
384
+ connection.execute("BEGIN IMMEDIATE")
385
+ connection.execute("""INSERT INTO pakem_state(singleton, board_json, updated_at)
386
+ VALUES(1, ?, ?) ON CONFLICT(singleton) DO UPDATE SET
387
+ board_json=excluded.board_json, updated_at=excluded.updated_at""",
388
+ (json.dumps(board, ensure_ascii=False, separators=(",", ":")), board["updatedAt"]))
389
+ connection.execute("INSERT INTO pakem_events(event_id, occurred_at, event_name, event_json) VALUES(?, ?, ?, ?)",
390
+ (record["event_id"], record["occurred_at"], event,
391
+ json.dumps(record, ensure_ascii=False, separators=(",", ":"))))
392
+ connection.commit()
393
+ except Exception:
394
+ connection.rollback()
395
+ raise
396
+ finally:
397
+ connection.close()
398
+ return board
399
+ _atomic_json(board_path(root), board)
400
+ try:
401
+ _event_unlocked(root, event, payload)
402
+ except OSError as exc:
403
+ raise RuntimeError(f"state was saved, but the event ledger write failed: {exc}") from exc
404
+ return board
405
+
406
+
407
+ def storage_info(root: Path) -> dict:
408
+ backend = _storage_backend(root)
409
+ result = {"backend": backend, "supported_backends": ["jsonl", "sqlite"],
410
+ "transactional_state_and_events": backend == "sqlite"}
411
+ if backend == "sqlite":
412
+ result["database"] = sqlite_path(root).relative_to(root).as_posix()
413
+ connection = _sqlite_connect(root, create=False)
414
+ try:
415
+ result["event_count"] = connection.execute("SELECT COUNT(*) FROM pakem_events").fetchone()[0]
416
+ finally:
417
+ connection.close()
418
+ else:
419
+ result["board"] = board_path(root).relative_to(root).as_posix()
420
+ result["event_ledger"] = events_path(root).relative_to(root).as_posix()
421
+ return result
422
+
423
+
424
+ def backup_sqlite(root: Path, output: str | Path, force: bool = False) -> dict:
425
+ """Create a consistent SQLite online backup without stopping the coordinator."""
426
+ if _storage_backend(root) != "sqlite":
427
+ raise ValueError("online SQLite backup is only available when the sqlite backend is active")
428
+ destination = Path(output).expanduser().resolve()
429
+ if destination == sqlite_path(root).resolve():
430
+ raise ValueError("backup output must not be the active database")
431
+ if destination.exists() and not force:
432
+ raise ValueError(f"backup file already exists: {destination}; use --force to replace")
433
+ destination.parent.mkdir(parents=True, exist_ok=True)
434
+ fd, temp_name = tempfile.mkstemp(prefix=f".{destination.name}.", suffix=".tmp", dir=str(destination.parent))
435
+ os.close(fd)
436
+ os.unlink(temp_name)
437
+ temporary = Path(temp_name)
438
+ try:
439
+ with _board_lock(root):
440
+ source_connection = _sqlite_connect(root, create=False)
441
+ target_connection = sqlite3.connect(temporary)
442
+ try:
443
+ source_connection.backup(target_connection)
444
+ target_connection.commit()
445
+ finally:
446
+ target_connection.close()
447
+ source_connection.close()
448
+ try:
449
+ os.chmod(temporary, 0o600)
450
+ except OSError:
451
+ pass
452
+ os.replace(temporary, destination)
453
+ finally:
454
+ if temporary.exists():
455
+ temporary.unlink()
456
+ return {"created": True, "path": str(destination), "backend": "sqlite", "consistent_snapshot": True}
457
+
458
+
459
+ def migrate_storage(root: Path, target: str = "sqlite") -> dict:
460
+ """Migrate the local JSON board/ledger to SQLite without deleting originals."""
461
+ if target != "sqlite":
462
+ raise ValueError("only migration to sqlite is supported; the original JSON files are retained as backup")
463
+ with _board_lock(root):
464
+ current = _storage_backend(root)
465
+ if current == "sqlite":
466
+ return {"migrated": False, "backend": "sqlite", "reason": "already_using_sqlite"}
467
+ board = _load_board_unlocked(root, create=True)
468
+ event_source = read_events(root, limit=0)
469
+ old_events = event_source.get("events", [])
470
+ skipped_corrupt_events = len(event_source.get("corruptLines", []))
471
+ db_path = sqlite_path(root)
472
+ if db_path.exists() and db_path.stat().st_size:
473
+ raise ValueError(f"SQLite database already exists; not overwritten: {db_path}")
474
+ connection = _sqlite_connect(root)
475
+ try:
476
+ connection.execute("BEGIN IMMEDIATE")
477
+ connection.execute("INSERT OR REPLACE INTO pakem_state(singleton, board_json, updated_at) VALUES(1, ?, ?)",
478
+ (json.dumps(board, ensure_ascii=False, separators=(",", ":")), board["updatedAt"]))
479
+ for record in old_events:
480
+ connection.execute("INSERT OR IGNORE INTO pakem_events(event_id, occurred_at, event_name, event_json) VALUES(?, ?, ?, ?)",
481
+ (record.get("event_id") or str(uuid.uuid4()), record.get("occurred_at") or now(),
482
+ record["event"], json.dumps(record, ensure_ascii=False, separators=(",", ":"))))
483
+ connection.commit()
484
+ except Exception:
485
+ connection.rollback()
486
+ raise
487
+ finally:
488
+ connection.close()
489
+ try:
490
+ _atomic_json(storage_config_path(root), {"schemaVersion": 1, "backend": "sqlite",
491
+ "migratedAt": now(), "backupFilesRetained": True})
492
+ except OSError as exc:
493
+ # The JSON source remains authoritative until the backend marker is durable.
494
+ for candidate in (db_path, Path(str(db_path) + "-wal"), Path(str(db_path) + "-shm")):
495
+ try:
496
+ candidate.unlink(missing_ok=True)
497
+ except OSError:
498
+ pass
499
+ raise RuntimeError(f"database migration was created but the backend marker write failed; JSON files remain authoritative: {exc}") from exc
500
+ return {"migrated": True, "backend": "sqlite", "agents": len(board["agents"]),
501
+ "tasks": len(board["tasks"]), "events": len(old_events),
502
+ "corrupt_events_skipped": skipped_corrupt_events,
503
+ "database": db_path.relative_to(root).as_posix(),
504
+ "json_backups_retained": [x.relative_to(root).as_posix() for x in (board_path(root), events_path(root)) if x.exists()]}
505
+
506
+
507
+ def initialize(root: Path) -> dict:
508
+ with _board_lock(root):
509
+ board = _load_board_unlocked(root, create=True)
510
+ return board
511
+
512
+
513
+ def status(root: Path) -> dict:
514
+ with _board_lock(root):
515
+ board = _load_board_unlocked(root, create=False)
516
+ if board is None:
517
+ return {"initialized": False, "agents": [], "tasks": [], "summary": {"open": 0, "claimed": 0, "review": 0, "done": 0, "blocked": 0}}
518
+ instant = datetime.now(timezone.utc)
519
+ tasks = []
520
+ counts = {state: 0 for state in TASK_STATES}
521
+ for item in board["tasks"].values():
522
+ task = dict(item)
523
+ expired = bool(task.get("leaseExpiresAt") and _parse_time(task["leaseExpiresAt"]) <= instant)
524
+ task["leaseExpired"] = expired
525
+ tasks.append(task)
526
+ counts[task["state"]] += 1
527
+ return {
528
+ "initialized": True,
529
+ "boardId": board["boardId"],
530
+ "revision": board["revision"],
531
+ "updatedAt": board["updatedAt"],
532
+ "agents": sorted(board["agents"].values(), key=lambda x: x["agentId"]),
533
+ "tasks": sorted(tasks, key=lambda x: x["taskId"]),
534
+ "summary": counts,
535
+ "note": "Tasks in state claimed with leaseExpired=true can be re-claimed; status is read without mutation.",
536
+ }
537
+
538
+
539
+ def register_agent(root: Path, agent_id: str, role: str = "worker", display_name: str = "",
540
+ capabilities: list[str] | None = None, fingerprint: str | None = None) -> dict:
541
+ agent_id = _safe_id(agent_id, "agent ID")
542
+ if role not in AGENT_ROLES:
543
+ raise ValueError("role must be worker, reviewer, lead, coordinator, or observer")
544
+ display_name = _text(display_name or agent_id, "display name", 120)
545
+ caps = _string_list(capabilities or [], "capabilities")
546
+ if fingerprint is not None:
547
+ fingerprint = str(fingerprint).strip().lower()
548
+ if not re.fullmatch(r"[a-f0-9]{64}", fingerprint):
549
+ raise ValueError("identity fingerprint must be 64 hex characters")
550
+ with _board_lock(root):
551
+ board = _load_board_unlocked(root, create=True)
552
+ existing = board["agents"].get(agent_id)
553
+ stamp = now()
554
+ agent = {
555
+ "agentId": agent_id,
556
+ "displayName": display_name,
557
+ "role": role,
558
+ "capabilities": caps,
559
+ "status": "active",
560
+ "registeredAt": existing.get("registeredAt", stamp) if existing else stamp,
561
+ "lastSeenAt": stamp,
562
+ }
563
+ if fingerprint:
564
+ agent["fingerprint"] = fingerprint
565
+ board["agents"][agent_id] = agent
566
+ _commit(root, board, "team.agent.registered", {"agentId": agent_id, "role": role, "capabilities": caps})
567
+ return agent
568
+
569
+
570
+ def _require_agent(board: dict, agent_id: str) -> dict:
571
+ agent_id = _safe_id(agent_id, "agent ID")
572
+ agent = board["agents"].get(agent_id)
573
+ if not agent or agent.get("status") != "active":
574
+ raise ValueError(f"agent {agent_id} is not registered as active; run team register")
575
+ return agent
576
+
577
+
578
+ def _validate_dependency_graph(tasks: dict) -> None:
579
+ visiting: set[str] = set()
580
+ visited: set[str] = set()
581
+
582
+ def visit(task_id: str):
583
+ if task_id in visiting:
584
+ raise ValueError(f"dependency cycle detected at task {task_id}")
585
+ if task_id in visited:
586
+ return
587
+ visiting.add(task_id)
588
+ task = tasks.get(task_id, {})
589
+ for dep in task.get("dependsOn", []):
590
+ if dep not in tasks:
591
+ raise ValueError(f"dependency {dep} for {task_id} not found")
592
+ visit(dep)
593
+ visiting.remove(task_id)
594
+ visited.add(task_id)
595
+
596
+ for item in tasks:
597
+ visit(item)
598
+
599
+
600
+ def add_task(root: Path, task_id: str, title: str, description: str = "", depends_on: list[str] | None = None,
601
+ files: list[str] | None = None, risk: str = "medium", required_capabilities: list[str] | None = None) -> dict:
602
+ task_id = _safe_id(task_id, "task ID")
603
+ title = _text(title, "title", 200)
604
+ description = _text(description, "description", 2000, required=False)
605
+ deps = [_safe_id(x, "dependency ID") for x in (depends_on or [])]
606
+ if task_id in deps or len(deps) != len(set(deps)):
607
+ raise ValueError("dependencies must not self-reference or duplicate")
608
+ file_list = _string_list(files or [], "files")
609
+ for file_name in file_list:
610
+ normalized = file_name.replace("\\", "/")
611
+ path = PurePosixPath(normalized)
612
+ windows_path = PureWindowsPath(file_name)
613
+ if path.is_absolute() or windows_path.is_absolute() or windows_path.drive or ".." in path.parts or not path.parts or "\x00" in file_name:
614
+ raise ValueError(f"file scope must be a relative path without '..' or an absolute drive: {file_name}")
615
+ if risk not in RISKS:
616
+ raise ValueError("risk must be low, medium, high, or critical")
617
+ caps = _string_list(required_capabilities or [], "required capabilities")
618
+ with _board_lock(root):
619
+ board = _load_board_unlocked(root, create=True)
620
+ if task_id in board["tasks"]:
621
+ raise ValueError(f"task {task_id} already exists")
622
+ missing = [dep for dep in deps if dep not in board["tasks"]]
623
+ if missing:
624
+ raise ValueError("dependencies not present yet: " + ", ".join(missing))
625
+ stamp = now()
626
+ task = {
627
+ "taskId": task_id,
628
+ "title": title,
629
+ "description": description,
630
+ "state": "open",
631
+ "dependsOn": deps,
632
+ "files": file_list,
633
+ "risk": risk,
634
+ "requiredCapabilities": caps,
635
+ "assignedAgent": None,
636
+ "ownerAgent": None,
637
+ "leaseExpiresAt": None,
638
+ "createdAt": stamp,
639
+ "updatedAt": stamp,
640
+ "submission": None,
641
+ "lastReview": None,
642
+ "lastHandoff": None,
643
+ "blockedReason": None,
644
+ }
645
+ board["tasks"][task_id] = task
646
+ _validate_dependency_graph(board["tasks"])
647
+ _commit(root, board, "team.task.created", {"taskId": task_id, "dependsOn": deps, "risk": risk})
648
+ return task
649
+
650
+
651
+ def assign_task(root: Path, task_id: str, agent_id: str, by: str) -> dict:
652
+ task_id, agent_id, by = _safe_id(task_id, "task ID"), _safe_id(agent_id, "agent ID"), _safe_id(by, "coordinator ID")
653
+ with _board_lock(root):
654
+ board = _load_board_unlocked(root, create=False)
655
+ if board is None or task_id not in board["tasks"]:
656
+ raise ValueError(f"task {task_id} not found")
657
+ coordinator = _require_agent(board, by)
658
+ if coordinator["role"] not in {"lead", "coordinator"}:
659
+ raise ValueError("only agents with role lead/coordinator may assign tasks")
660
+ agent = _require_agent(board, agent_id)
661
+ task = board["tasks"][task_id]
662
+ if task["state"] == "claimed":
663
+ expiry = _parse_time(task["leaseExpiresAt"]) if task.get("leaseExpiresAt") else datetime.now(timezone.utc)
664
+ if expiry > datetime.now(timezone.utc):
665
+ raise ValueError(f"task still has an active lease until {task['leaseExpiresAt']}")
666
+ task.update({"state": "open", "ownerAgent": None, "leaseExpiresAt": None})
667
+ elif task["state"] not in {"open", "blocked"}:
668
+ raise ValueError(f"task cannot be assigned while state={task['state']}")
669
+ missing_caps = sorted(set(task.get("requiredCapabilities", [])) - set(agent.get("capabilities", [])))
670
+ if missing_caps:
671
+ raise ValueError("agent is missing capabilities: " + ", ".join(missing_caps))
672
+ task["assignedAgent"] = agent_id
673
+ task["updatedAt"] = now()
674
+ _commit(root, board, "team.task.assigned", {"taskId": task_id, "agentId": agent_id, "by": by})
675
+ return task
676
+
677
+
678
+ def _deps_ready(board: dict, task: dict) -> list[str]:
679
+ return [dep for dep in task.get("dependsOn", []) if board["tasks"][dep]["state"] != "done"]
680
+
681
+
682
+ def claim_task(root: Path, task_id: str, agent_id: str, lease_seconds: int = 900) -> dict:
683
+ task_id, agent_id = _safe_id(task_id, "task ID"), _safe_id(agent_id, "agent ID")
684
+ if not isinstance(lease_seconds, int) or isinstance(lease_seconds, bool) or not 30 <= lease_seconds <= 86400:
685
+ raise ValueError("lease-seconds must be an integer 30..86400")
686
+ with _board_lock(root):
687
+ board = _load_board_unlocked(root, create=False)
688
+ if board is None or task_id not in board["tasks"]:
689
+ raise ValueError(f"task {task_id} not found")
690
+ agent = _require_agent(board, agent_id)
691
+ task = board["tasks"][task_id]
692
+ if task["state"] == "done":
693
+ raise ValueError("task is already done")
694
+ if task["state"] == "review":
695
+ raise ValueError("task is awaiting review")
696
+ if task["state"] == "blocked":
697
+ raise ValueError("task is blocked; unblock it first")
698
+ if task.get("assignedAgent") and task["assignedAgent"] != agent_id:
699
+ raise ValueError(f"task is assigned to {task['assignedAgent']}")
700
+ missing_caps = sorted(set(task.get("requiredCapabilities", [])) - set(agent.get("capabilities", [])))
701
+ if missing_caps:
702
+ raise ValueError("agent is missing capabilities: " + ", ".join(missing_caps))
703
+ blockers = _deps_ready(board, task)
704
+ if blockers:
705
+ raise ValueError("dependencies not done yet: " + ", ".join(blockers))
706
+ stamp = datetime.now(timezone.utc)
707
+ if task["state"] == "claimed":
708
+ expiry = _parse_time(task["leaseExpiresAt"]) if task.get("leaseExpiresAt") else stamp
709
+ if expiry > stamp and task.get("ownerAgent") != agent_id:
710
+ raise ValueError(f"task is claimed by {task.get('ownerAgent')} until {task.get('leaseExpiresAt')}")
711
+ task["state"] = "claimed"
712
+ task["ownerAgent"] = agent_id
713
+ task["leaseExpiresAt"] = (stamp + timedelta(seconds=lease_seconds)).astimezone().isoformat(timespec="seconds")
714
+ task["updatedAt"] = now()
715
+ agent["lastSeenAt"] = now()
716
+ _commit(root, board, "team.task.claimed", {"taskId": task_id, "agentId": agent_id, "leaseExpiresAt": task["leaseExpiresAt"]})
717
+ return task
718
+
719
+
720
+ def heartbeat(root: Path, task_id: str, agent_id: str, lease_seconds: int = 900) -> dict:
721
+ task_id, agent_id = _safe_id(task_id, "task ID"), _safe_id(agent_id, "agent ID")
722
+ if not isinstance(lease_seconds, int) or isinstance(lease_seconds, bool) or not 30 <= lease_seconds <= 86400:
723
+ raise ValueError("lease-seconds must be an integer 30..86400")
724
+ with _board_lock(root):
725
+ board = _load_board_unlocked(root, create=False)
726
+ if board is None or task_id not in board["tasks"]:
727
+ raise ValueError(f"task {task_id} not found")
728
+ agent = _require_agent(board, agent_id)
729
+ task = board["tasks"][task_id]
730
+ if task["state"] != "claimed" or task.get("ownerAgent") != agent_id:
731
+ raise ValueError("only the active claim owner may heartbeat")
732
+ if not task.get("leaseExpiresAt") or _parse_time(task["leaseExpiresAt"]) <= datetime.now(timezone.utc):
733
+ raise ValueError("lease has expired; re-claim the task")
734
+ task["leaseExpiresAt"] = (datetime.now(timezone.utc) + timedelta(seconds=lease_seconds)).astimezone().isoformat(timespec="seconds")
735
+ task["updatedAt"] = now()
736
+ agent["lastSeenAt"] = now()
737
+ _commit(root, board, "team.task.heartbeat", {"taskId": task_id, "agentId": agent_id, "leaseExpiresAt": task["leaseExpiresAt"]})
738
+ return task
739
+
740
+
741
+ def release_task(root: Path, task_id: str, agent_id: str, reason: str) -> dict:
742
+ task_id, agent_id = _safe_id(task_id, "task ID"), _safe_id(agent_id, "agent ID")
743
+ reason = _text(reason, "reason", 500)
744
+ with _board_lock(root):
745
+ board = _load_board_unlocked(root, create=False)
746
+ if board is None or task_id not in board["tasks"]:
747
+ raise ValueError(f"task {task_id} not found")
748
+ task = board["tasks"][task_id]
749
+ if task["state"] != "claimed" or task.get("ownerAgent") != agent_id:
750
+ raise ValueError("only the claim owner may release the task")
751
+ task.update({"state": "open", "ownerAgent": None, "leaseExpiresAt": None, "updatedAt": now(), "lastReleaseReason": reason})
752
+ _commit(root, board, "team.task.released", {"taskId": task_id, "agentId": agent_id})
753
+ return task
754
+
755
+
756
+ def handoff_task(root: Path, task_id: str, from_agent: str, to_agent: str, note: str) -> dict:
757
+ task_id = _safe_id(task_id, "task ID")
758
+ from_agent = _safe_id(from_agent, "from-agent")
759
+ to_agent = _safe_id(to_agent, "to-agent")
760
+ note = _text(note, "handoff note", 1000)
761
+ with _board_lock(root):
762
+ board = _load_board_unlocked(root, create=False)
763
+ if board is None or task_id not in board["tasks"]:
764
+ raise ValueError(f"task {task_id} not found")
765
+ _require_agent(board, to_agent)
766
+ task = board["tasks"][task_id]
767
+ if task["state"] != "claimed" or task.get("ownerAgent") != from_agent:
768
+ raise ValueError("only the active claim owner may hand off")
769
+ missing_caps = sorted(set(task.get("requiredCapabilities", [])) - set(board["agents"][to_agent].get("capabilities", [])))
770
+ if missing_caps:
771
+ raise ValueError("target agent is missing capabilities: " + ", ".join(missing_caps))
772
+ task.update({"state": "open", "ownerAgent": None, "assignedAgent": to_agent,
773
+ "leaseExpiresAt": None, "updatedAt": now(),
774
+ "lastHandoff": {"from": from_agent, "to": to_agent, "note": note, "at": now()}})
775
+ _commit(root, board, "team.task.handed_off", {"taskId": task_id, "fromAgent": from_agent, "toAgent": to_agent})
776
+ return task
777
+
778
+
779
+ def submission_payload(task_id: str, agent_id: str, summary: str, evidence: list[str]) -> dict:
780
+ """Canonical payload for the submit signature. Rebuilt during verification."""
781
+ return {"type": "pakem.team.submission.v1", "taskId": task_id, "agentId": agent_id,
782
+ "summary": summary, "evidence": list(evidence)}
783
+
784
+
785
+ def review_payload(task_id: str, reviewer_id: str, decision: str, note: str, implementer: str) -> dict:
786
+ return {"type": "pakem.team.review.v1", "taskId": task_id, "reviewerId": reviewer_id,
787
+ "decision": decision, "note": note, "implementer": implementer}
788
+
789
+
790
+ def tasks_map(board: dict) -> dict:
791
+ """`status()` returns tasks as a list; some callers need a map keyed by taskId."""
792
+ tasks = board.get("tasks") or []
793
+ if isinstance(tasks, dict):
794
+ return tasks
795
+ return {task.get("taskId"): task for task in tasks if task.get("taskId")}
796
+
797
+
798
+ def signed_actions(root: Path) -> list[dict]:
799
+ """Collect every signed action, together with the payload it should have.
800
+
801
+ The reconstructed payload is compared with the envelope payload, so changing
802
+ board content (summary, evidence, decision) breaks the signature.
803
+ """
804
+ actions = []
805
+ for task_id, task in tasks_map(status(root)).items():
806
+ submission = task.get("submission") or {}
807
+ if submission.get("signature") and submission.get("agentId"):
808
+ actions.append({
809
+ "kind": "submission", "taskId": task_id, "agentId": submission["agentId"],
810
+ "expected": submission_payload(task_id, submission["agentId"],
811
+ submission.get("summary", ""),
812
+ submission.get("evidence") or []),
813
+ "envelope": submission["signature"],
814
+ })
815
+ review = task.get("lastReview") or {}
816
+ if review.get("signature"):
817
+ actions.append({
818
+ "kind": "review", "taskId": task_id, "agentId": review.get("reviewerId"),
819
+ "expected": review_payload(task_id, review.get("reviewerId", ""),
820
+ review.get("decision", ""), review.get("note", ""),
821
+ (task.get("submission") or {}).get("agentId", "")),
822
+ "envelope": review["signature"],
823
+ })
824
+ return actions
825
+
826
+
827
+ def submit_task(root: Path, task_id: str, agent_id: str, summary: str, evidence: list[str],
828
+ signature: dict | None = None) -> dict:
829
+ task_id, agent_id = _safe_id(task_id, "task ID"), _safe_id(agent_id, "agent ID")
830
+ summary = _text(summary, "summary", 2000)
831
+ proofs = _string_list(evidence, "evidence", 50)
832
+ if not proofs:
833
+ raise ValueError("at least one evidence reference is required")
834
+ with _board_lock(root):
835
+ board = _load_board_unlocked(root, create=False)
836
+ if board is None or task_id not in board["tasks"]:
837
+ raise ValueError(f"task {task_id} not found")
838
+ _require_agent(board, agent_id)
839
+ task = board["tasks"][task_id]
840
+ if task["state"] != "claimed" or task.get("ownerAgent") != agent_id:
841
+ raise ValueError("only the active claim owner may submit")
842
+ if not task.get("leaseExpiresAt") or _parse_time(task["leaseExpiresAt"]) <= datetime.now(timezone.utc):
843
+ raise ValueError("lease has expired; re-claim before submitting")
844
+ task.update({"state": "review", "ownerAgent": None, "leaseExpiresAt": None, "updatedAt": now(),
845
+ "submission": {"agentId": agent_id, "summary": summary, "evidence": proofs,
846
+ "submittedAt": now(),
847
+ **({"signature": signature} if signature else {})}})
848
+ _commit(root, board, "team.task.submitted", {"taskId": task_id, "agentId": agent_id, "evidenceCount": len(proofs)})
849
+ return task
850
+
851
+
852
+ def review_task(root: Path, task_id: str, reviewer_id: str, decision: str, note: str = "",
853
+ signature: dict | None = None) -> dict:
854
+ task_id, reviewer_id = _safe_id(task_id, "task ID"), _safe_id(reviewer_id, "reviewer ID")
855
+ if decision not in {"approve", "rework"}:
856
+ raise ValueError("decision must be approve or rework")
857
+ note = _text(note, "review note", 1000, required=False)
858
+ with _board_lock(root):
859
+ board = _load_board_unlocked(root, create=False)
860
+ if board is None or task_id not in board["tasks"]:
861
+ raise ValueError(f"task {task_id} not found")
862
+ reviewer = _require_agent(board, reviewer_id)
863
+ if reviewer["role"] not in {"reviewer", "lead", "coordinator"}:
864
+ raise ValueError("reviewer must have role reviewer, lead, or coordinator")
865
+ task = board["tasks"][task_id]
866
+ if task["state"] != "review" or not task.get("submission"):
867
+ raise ValueError("task is not awaiting review")
868
+ implementer = task["submission"]["agentId"]
869
+ if reviewer_id == implementer:
870
+ raise ValueError("independent review is required: reviewer must not be the implementer")
871
+ result = {"reviewerId": reviewer_id, "decision": decision, "note": note, "reviewedAt": now()}
872
+ if signature:
873
+ result["signature"] = signature
874
+ task["lastReview"] = result
875
+ task["updatedAt"] = now()
876
+ if decision == "approve":
877
+ task["state"] = "done"
878
+ else:
879
+ task["state"] = "open"
880
+ task["assignedAgent"] = implementer
881
+ task["submission"] = None
882
+ _commit(root, board, "team.task.reviewed", {"taskId": task_id, "reviewerId": reviewer_id, "decision": decision})
883
+ return task
884
+
885
+
886
+ def block_task(root: Path, task_id: str, actor_id: str, reason: str) -> dict:
887
+ task_id, actor_id = _safe_id(task_id, "task ID"), _safe_id(actor_id, "actor ID")
888
+ reason = _text(reason, "reason", 1000)
889
+ with _board_lock(root):
890
+ board = _load_board_unlocked(root, create=False)
891
+ if board is None or task_id not in board["tasks"]:
892
+ raise ValueError(f"task {task_id} not found")
893
+ _require_agent(board, actor_id)
894
+ task = board["tasks"][task_id]
895
+ if task["state"] == "done":
896
+ raise ValueError("a done task cannot be blocked")
897
+ if task["state"] == "claimed" and task.get("ownerAgent") != actor_id:
898
+ raise ValueError("the task claim belongs to another agent")
899
+ task.update({"state": "blocked", "ownerAgent": None, "leaseExpiresAt": None,
900
+ "blockedReason": reason, "updatedAt": now()})
901
+ _commit(root, board, "team.task.blocked", {"taskId": task_id, "actorId": actor_id})
902
+ return task
903
+
904
+
905
+ def unblock_task(root: Path, task_id: str, by: str, reason: str) -> dict:
906
+ task_id, by = _safe_id(task_id, "task ID"), _safe_id(by, "coordinator ID")
907
+ reason = _text(reason, "reason", 500)
908
+ with _board_lock(root):
909
+ board = _load_board_unlocked(root, create=False)
910
+ if board is None or task_id not in board["tasks"]:
911
+ raise ValueError(f"task {task_id} not found")
912
+ coordinator = _require_agent(board, by)
913
+ if coordinator["role"] not in {"lead", "coordinator"}:
914
+ raise ValueError("only lead/coordinator may unblock")
915
+ task = board["tasks"][task_id]
916
+ if task["state"] != "blocked":
917
+ raise ValueError("task is not in state blocked")
918
+ task.update({"state": "open", "blockedReason": None, "updatedAt": now(), "unblockedReason": reason})
919
+ _commit(root, board, "team.task.unblocked", {"taskId": task_id, "by": by})
920
+ return task
921
+
922
+
923
+ def _valid_coordination_event(record: object) -> bool:
924
+ if not isinstance(record, dict):
925
+ return False
926
+ actor = record.get("actor")
927
+ return bool(record.get("protocol") == "pakem"
928
+ and record.get("protocol_version") == "1.0"
929
+ and record.get("event") in COORDINATION_EVENTS
930
+ and isinstance(record.get("event_id"), str)
931
+ and isinstance(record.get("occurred_at"), str)
932
+ and isinstance(actor, dict)
933
+ and isinstance(actor.get("name"), str)
934
+ and isinstance(record.get("payload"), dict))
935
+
936
+
937
+ def read_events(root: Path, limit: int = 50) -> dict:
938
+ if limit < 0:
939
+ raise ValueError("limit must not be negative")
940
+ if _storage_backend(root) == "sqlite":
941
+ connection = _sqlite_connect(root, create=False)
942
+ try:
943
+ rows = connection.execute("SELECT seq, event_json FROM pakem_events ORDER BY seq").fetchall()
944
+ valid, corrupt = [], []
945
+ for row in rows:
946
+ try:
947
+ record = json.loads(row["event_json"])
948
+ if not _valid_coordination_event(record):
949
+ raise ValueError("invalid Pakem Protocol v1 envelope")
950
+ valid.append(record)
951
+ except (json.JSONDecodeError, ValueError):
952
+ corrupt.append(row["seq"])
953
+ selected = valid[-limit:] if limit else valid
954
+ return {"events": selected, "corruptLines": corrupt, "total": len(rows), "backend": "sqlite"}
955
+ except sqlite3.Error as exc:
956
+ raise ValueError(f"failed to read SQLite coordination ledger: {exc}") from exc
957
+ finally:
958
+ connection.close()
959
+ path = events_path(root)
960
+ if not path.is_file():
961
+ return {"events": [], "corruptLines": [], "total": 0, "backend": "jsonl"}
962
+ events, corrupt = [], []
963
+ try:
964
+ lines = path.read_text(encoding="utf-8").splitlines()
965
+ except OSError as exc:
966
+ raise ValueError(f"failed to read coordination ledger: {exc}") from exc
967
+ for number, line in enumerate(lines, 1):
968
+ try:
969
+ record = json.loads(line)
970
+ if not _valid_coordination_event(record):
971
+ raise ValueError("invalid Pakem Protocol v1 envelope")
972
+ events.append(record)
973
+ except (json.JSONDecodeError, ValueError):
974
+ corrupt.append(number)
975
+ selected = events[-limit:] if limit else events
976
+ return {"events": selected, "corruptLines": corrupt, "total": len(events), "backend": "jsonl"}
977
+