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.
Files changed (76) hide show
  1. package/CHANGELOG.md +280 -0
  2. package/LICENSE +21 -0
  3. package/README-ID.md +666 -0
  4. package/README.md +665 -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 +272 -0
  35. package/npm/check-version.js +26 -0
  36. package/package.json +58 -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,265 @@
1
+ """Safe, explicit Git worktree helpers for isolated multi-agent task work.
2
+
3
+ This module creates/removes worktrees only. It never merges, pushes, resets, or
4
+ runs project commands. The project root and managed worktree directory are
5
+ validated before every operation.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ import re
11
+ import subprocess
12
+ from pathlib import Path
13
+ from typing import Any
14
+
15
+ _ID = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$")
16
+
17
+
18
+ def _safe_id(value: str, label: str) -> str:
19
+ if not isinstance(value, str) or not _ID.fullmatch(value) or value in {".", ".."}:
20
+ raise ValueError(f"{label} is not valid")
21
+ return value
22
+
23
+
24
+ def _git(root: Path, *args: str, timeout: int = 30) -> str:
25
+ result = subprocess.run(["git", *args], cwd=root, text=True, capture_output=True,
26
+ timeout=timeout, check=False)
27
+ if result.returncode:
28
+ message = (result.stderr or result.stdout or "git command failed").strip()
29
+ raise RuntimeError(message)
30
+ return result.stdout.strip()
31
+
32
+
33
+ def _root(root: str | Path) -> Path:
34
+ value = Path(root).resolve()
35
+ if not (value / ".git").exists():
36
+ # Linked worktrees have a .git file; bare repos are not suitable.
37
+ raise ValueError("worktree command must run inside a Git working tree")
38
+ return value
39
+
40
+
41
+ def _managed_dir(root: Path) -> Path:
42
+ return root / ".pakem" / "worktrees"
43
+
44
+
45
+ def _is_within(path: Path, parent: Path) -> bool:
46
+ try:
47
+ path.resolve(strict=False).relative_to(parent.resolve(strict=False))
48
+ return True
49
+ except ValueError:
50
+ return False
51
+
52
+
53
+ def create(root: str | Path, task_id: str, agent_id: str,
54
+ base_ref: str = "HEAD") -> dict[str, Any]:
55
+ root = _root(root)
56
+ task_id = _safe_id(task_id, "task ID")
57
+ agent_id = _safe_id(agent_id, "agent ID")
58
+ if not isinstance(base_ref, str) or not base_ref.strip() or base_ref.startswith("-"):
59
+ raise ValueError("base_ref is not valid")
60
+ pakem_dir = root / ".pakem"
61
+ if pakem_dir.is_symlink():
62
+ raise ValueError(".pakem must not be a symlink for worktree operations")
63
+ folder = _managed_dir(root)
64
+ if folder.is_symlink():
65
+ raise ValueError(".pakem/worktrees must not be a symlink")
66
+ folder.mkdir(parents=True, exist_ok=True)
67
+ destination = folder / f"{task_id}--{agent_id}"
68
+ if destination.exists():
69
+ raise ValueError(f"worktree already exists: {destination.relative_to(root).as_posix()}")
70
+ branch = f"pakem/{task_id}/{agent_id}"
71
+ _git(root, "check-ref-format", "--branch", branch)
72
+ # Verify ref exists before creating a branch or directory.
73
+ _git(root, "rev-parse", "--verify", f"{base_ref}^{{commit}}")
74
+ _git(root, "worktree", "add", "-b", branch, str(destination), base_ref)
75
+ return {
76
+ "created": True,
77
+ "task_id": task_id,
78
+ "agent_id": agent_id,
79
+ "branch": branch,
80
+ "path": destination.relative_to(root).as_posix(),
81
+ "base_ref": base_ref,
82
+ "merge_performed": False,
83
+ }
84
+
85
+
86
+ def list_worktrees(root: str | Path) -> dict[str, Any]:
87
+ root = _root(root)
88
+ raw = _git(root, "worktree", "list", "--porcelain")
89
+ records: list[dict[str, Any]] = []
90
+ current: dict[str, Any] = {}
91
+ for line in raw.splitlines() + [""]:
92
+ if not line:
93
+ if current:
94
+ path = Path(current.get("path", ""))
95
+ current["managed_by_pakem"] = bool(path and _is_within(path, _managed_dir(root)))
96
+ records.append(current)
97
+ current = {}
98
+ continue
99
+ key, _, value = line.partition(" ")
100
+ if key == "worktree":
101
+ current["path"] = value
102
+ elif key == "HEAD":
103
+ current["head"] = value
104
+ elif key == "branch":
105
+ current["branch"] = value.removeprefix("refs/heads/")
106
+ elif key == "detached":
107
+ current["detached"] = True
108
+ elif key == "bare":
109
+ current["bare"] = True
110
+ elif key == "locked":
111
+ current["locked"] = value or True
112
+ elif key == "prunable":
113
+ current["prunable"] = value or True
114
+ return {"worktrees": records, "managed_count": sum(1 for x in records if x["managed_by_pakem"])}
115
+
116
+
117
+ def remove(root: str | Path, path: str, force: bool = False) -> dict[str, Any]:
118
+ root = _root(root)
119
+ raw_candidate = (root / path) if not Path(path).is_absolute() else Path(path)
120
+ if raw_candidate.is_symlink():
121
+ raise ValueError("symlink is not allowed as a worktree target")
122
+ candidate = raw_candidate.resolve(strict=False)
123
+ pakem_dir = root / ".pakem"
124
+ managed = _managed_dir(root)
125
+ if pakem_dir.is_symlink() or managed.is_symlink():
126
+ raise ValueError(".pakem/worktrees must not be a symlink")
127
+ if not _is_within(candidate, managed) or candidate == managed.resolve(strict=False):
128
+ raise ValueError("Pakem may only remove worktrees inside .pakem/worktrees/")
129
+ if not candidate.exists():
130
+ raise ValueError("worktree not found")
131
+ if not force:
132
+ dirty = subprocess.run(["git", "status", "--porcelain"], cwd=candidate, text=True,
133
+ capture_output=True, timeout=30, check=False)
134
+ if dirty.returncode == 0 and dirty.stdout.strip():
135
+ raise ValueError("worktree still has uncommitted changes; "
136
+ "commit or stash them first, or use --force to discard them")
137
+ args = ["worktree", "remove"]
138
+ if force:
139
+ args.append("--force")
140
+ args.append(str(candidate))
141
+ _git(root, *args)
142
+ return {"removed": True, "path": candidate.relative_to(root).as_posix(),
143
+ "force": bool(force), "branch_deleted": False}
144
+
145
+
146
+ def resolve(root: str | Path, name: str) -> Path:
147
+ """Translate a managed worktree name into a validated Path.
148
+
149
+ Accepts `T1--solo` (folder name), `T1/solo` (task/agent), or a relative or
150
+ absolute path. Only worktrees inside `.pakem/worktrees/` are accepted.
151
+ """
152
+ root = _root(root)
153
+ managed = _managed_dir(root).resolve(strict=False)
154
+ raw = str(name or "").strip().replace("\\", "/").rstrip("/")
155
+ if not raw:
156
+ raise ValueError("worktree name is empty")
157
+ p = Path(raw)
158
+ candidates = [p] if p.is_absolute() else [root / raw, managed / raw]
159
+ if "/" in raw and not raw.startswith("."):
160
+ task, agent = raw.split("/", 1)
161
+ candidates.append(managed / f"{task}--{agent}")
162
+ for candidate in candidates:
163
+ try:
164
+ resolved = candidate.resolve(strict=True)
165
+ except OSError:
166
+ continue
167
+ if resolved == managed or not _is_within(resolved, managed):
168
+ continue
169
+ if not (resolved / ".git").exists():
170
+ continue
171
+ return resolved
172
+ existing = sorted(x.name for x in managed.iterdir() if x.is_dir()) if managed.is_dir() else []
173
+ hint = f" Available: {', '.join(existing)}." if existing else ""
174
+ raise ValueError(f"managed worktree not found: {raw}.{hint}")
175
+
176
+
177
+ def changed_files(root: str | Path, name: str, base: str | None = None) -> list[str]:
178
+ """Files changed in a worktree relative to its branch point from the root.
179
+
180
+ `git diff <merge-base>` counts commits on the branch plus uncommitted changes
181
+ at once; untracked files are added from status. Paths are always relative and
182
+ POSIX-formatted, ready to compare against the task scope.
183
+ """
184
+ root = _root(root)
185
+ worktree = resolve(root, name)
186
+ head = _git(worktree, "rev-parse", "--verify", "HEAD")
187
+ ref = base
188
+ if not ref:
189
+ try:
190
+ ref = _git(root, "merge-base", "HEAD", head)
191
+ except RuntimeError:
192
+ ref = head # unrelated history: compare against the worktree HEAD only
193
+ raw = _git(worktree, "diff", "--name-only", "--no-renames", ref)
194
+ paths = [line.strip() for line in raw.splitlines() if line.strip()]
195
+ status = _git(worktree, "status", "--porcelain", "--untracked-files=all")
196
+ for line in status.splitlines():
197
+ if line.startswith("?? "):
198
+ entry = line[3:].strip()
199
+ if entry.startswith('"') and entry.endswith('"'):
200
+ entry = entry[1:-1]
201
+ if entry:
202
+ paths.append(entry.replace("\\", "/"))
203
+ return sorted({p for p in paths if p})
204
+
205
+ def cleanup_for_task(root: str | Path, task_id: str, dry_run: bool = False) -> list[dict[str, Any]]:
206
+ """Clean up the worktree owned by one task when it is safe.
207
+
208
+ Only worktrees that are clean and whose commits are already part of HEAD are
209
+ removed. Worktrees with unmerged commits or uncommitted files are left alone
210
+ and reported: that is unfinished work, not garbage.
211
+ """
212
+ root = _root(root)
213
+ task_id = _safe_id(task_id, "task ID")
214
+ head = _git(root, "rev-parse", "HEAD").strip()
215
+ report: list[dict[str, Any]] = []
216
+ for record in list_worktrees(root)["worktrees"]:
217
+ branch = record.get("branch") or ""
218
+ if not branch.startswith(f"pakem/{task_id}/"):
219
+ continue
220
+ path = Path(record["path"])
221
+ item = {"task_id": task_id, "branch": branch,
222
+ "path": path.relative_to(root).as_posix() if _is_within(path, root) else str(path),
223
+ "action": "keep", "reason": ""}
224
+ if record.get("locked") or record.get("prunable"):
225
+ item["reason"] = "worktree is locked or prunable"
226
+ elif record.get("detached"):
227
+ item["reason"] = "HEAD detached"
228
+ else:
229
+ worktree_head = record.get("head") or ""
230
+ merged = subprocess.run(["git", "-C", str(path), "merge-base", "--is-ancestor",
231
+ worktree_head, head], capture_output=True, text=True,
232
+ timeout=30, check=False)
233
+ dirty = subprocess.run(["git", "-C", str(path), "status", "--porcelain"],
234
+ capture_output=True, text=True, timeout=30, check=False)
235
+ if merged.returncode != 0:
236
+ item["reason"] = f"commit {worktree_head[:8]} not merged into HEAD"
237
+ elif dirty.returncode == 0 and dirty.stdout.strip():
238
+ item["reason"] = "uncommitted changes remain"
239
+ elif dry_run:
240
+ item["action"] = "would-remove"
241
+ else:
242
+ try:
243
+ _git(root, "worktree", "remove", str(path))
244
+ except RuntimeError as exc:
245
+ item["reason"] = f"failed to remove: {exc}"
246
+ else:
247
+ deleted = subprocess.run(["git", "-C", str(root), "branch", "-D", branch],
248
+ capture_output=True, text=True, timeout=30, check=False)
249
+ item.update({"action": "removed", "branch_deleted": deleted.returncode == 0})
250
+ report.append(item)
251
+ return report
252
+
253
+
254
+ def cleanup_merged(root: str | Path, dry_run: bool = False) -> list[dict[str, Any]]:
255
+ """Clean up every pakem/* worktree that is safe to remove."""
256
+ root = _root(root)
257
+ seen: list[str] = []
258
+ for record in list_worktrees(root)["worktrees"]:
259
+ parts = (record.get("branch") or "").split("/")
260
+ if len(parts) >= 3 and parts[0] == "pakem" and parts[1] not in seen:
261
+ seen.append(parts[1])
262
+ report: list[dict[str, Any]] = []
263
+ for task_id in seen:
264
+ report.extend(cleanup_for_task(root, task_id, dry_run=dry_run))
265
+ return report