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,308 @@
|
|
|
1
|
+
"""Minimal Pakem MCP stdio server for the MCP 2026-07-28 stateless protocol.
|
|
2
|
+
|
|
3
|
+
Only JSON-RPC messages are written to stdout. Diagnostics go to stderr.
|
|
4
|
+
No arbitrary shell/command execution is exposed. Mutating team tools are
|
|
5
|
+
available only when the trusted host explicitly starts the server with
|
|
6
|
+
--allow-write and a fixed --agent-id.
|
|
7
|
+
"""
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import contextlib
|
|
11
|
+
import io
|
|
12
|
+
import json
|
|
13
|
+
import sys
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
from typing import Any
|
|
16
|
+
|
|
17
|
+
MCP_VERSION = "2026-07-28"
|
|
18
|
+
SERVER_NAME = "pakem"
|
|
19
|
+
SERVER_VERSION = "1.3.0"
|
|
20
|
+
META_VERSION = "io.modelcontextprotocol/protocolVersion"
|
|
21
|
+
META_CLIENT_CAPS = "io.modelcontextprotocol/clientCapabilities"
|
|
22
|
+
META_CLIENT_INFO = "io.modelcontextprotocol/clientInfo"
|
|
23
|
+
SERVER_INFO = "io.modelcontextprotocol/serverInfo"
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _tool(name: str, description: str, schema: dict) -> dict:
|
|
27
|
+
return {"name": name, "description": description, "inputSchema": schema}
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _object(properties: dict | None = None, required: list[str] | None = None) -> dict:
|
|
31
|
+
out = {"type": "object", "properties": properties or {}, "additionalProperties": False}
|
|
32
|
+
if required:
|
|
33
|
+
out["required"] = required
|
|
34
|
+
return out
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def tool_catalog(allow_write: bool, bound_agent_id: str | None, bound_role: str | None = None) -> list[dict]:
|
|
38
|
+
tools = [
|
|
39
|
+
_tool("pakem.context", "Read the current Pakem project, session, runtime, and team context snapshot.", _object()),
|
|
40
|
+
_tool("pakem.protocol.info", "Read the stable Pakem Protocol version and negotiated capability catalogue.", _object()),
|
|
41
|
+
_tool("pakem.team.status", "Read the shared multi-agent board, current tasks, agents, and lease status.", _object()),
|
|
42
|
+
_tool("pakem.team.events", "Read recent append-only multi-agent coordination events.", _object({"limit": {"type": "integer", "minimum": 0, "maximum": 500}})),
|
|
43
|
+
_tool("pakem.graph", "Build a best-effort static dependency graph of local project files.", _object({"include_tests": {"type": "boolean"}})),
|
|
44
|
+
_tool("pakem.impact", "Analyze changed files, affected dependents, test candidates, and risk signals.", _object({
|
|
45
|
+
"files": {"type": "array", "items": {"type": "string"}, "maxItems": 200},
|
|
46
|
+
"base": {"type": "string"}, "staged": {"type": "boolean"}
|
|
47
|
+
})),
|
|
48
|
+
_tool("pakem.policy.check", "Evaluate a Pakem policy decision. This tool does not execute the requested action.", _object({
|
|
49
|
+
"category": {"type": "string", "enum": ["read", "write", "command", "destructive", "deploy", "security", "policy_change", "gate_change"]},
|
|
50
|
+
"risk": {"type": "string", "enum": ["low", "medium", "high", "critical"]},
|
|
51
|
+
"target": {"type": "string", "maxLength": 300}
|
|
52
|
+
}, ["category"])),
|
|
53
|
+
]
|
|
54
|
+
if allow_write and bound_agent_id:
|
|
55
|
+
tools.extend([
|
|
56
|
+
_tool("pakem.team.claim", "Claim a task as the server-bound agent; the caller cannot override its identity.", _object({
|
|
57
|
+
"task_id": {"type": "string"}, "lease_seconds": {"type": "integer", "minimum": 30, "maximum": 86400}
|
|
58
|
+
}, ["task_id"])),
|
|
59
|
+
_tool("pakem.team.heartbeat", "Renew the active task lease for the server-bound agent.", _object({
|
|
60
|
+
"task_id": {"type": "string"}, "lease_seconds": {"type": "integer", "minimum": 30, "maximum": 86400}
|
|
61
|
+
}, ["task_id"])),
|
|
62
|
+
_tool("pakem.team.submit", "Submit a claimed task for independent review with evidence references.", _object({
|
|
63
|
+
"task_id": {"type": "string"}, "summary": {"type": "string", "maxLength": 2000},
|
|
64
|
+
"evidence": {"type": "array", "items": {"type": "string"}, "minItems": 1, "maxItems": 50}
|
|
65
|
+
}, ["task_id", "summary", "evidence"])),
|
|
66
|
+
])
|
|
67
|
+
# Review and assignment are exposed only when the bound board role permits it.
|
|
68
|
+
if bound_role in {"reviewer", "lead", "coordinator"}:
|
|
69
|
+
tools.append(_tool("pakem.team.review", "Approve or request rework for a submitted task as the server-bound reviewer.", _object({
|
|
70
|
+
"task_id": {"type": "string"}, "decision": {"type": "string", "enum": ["approve", "rework"]},
|
|
71
|
+
"note": {"type": "string", "maxLength": 1000}
|
|
72
|
+
}, ["task_id", "decision"])))
|
|
73
|
+
tools.extend([
|
|
74
|
+
_tool("pakem.session.start", "Start (or resume) a Pakem work session as the server-bound agent.", _object({
|
|
75
|
+
"goal": {"type": "string", "minLength": 1, "maxLength": 300},
|
|
76
|
+
"new": {"type": "boolean"}
|
|
77
|
+
}, ["goal"])),
|
|
78
|
+
_tool("pakem.session.step", "Record a finished step and the next step for the active session.", _object({
|
|
79
|
+
"text": {"type": "string", "minLength": 1, "maxLength": 500},
|
|
80
|
+
"next": {"type": "string", "maxLength": 500}
|
|
81
|
+
}, ["text"])),
|
|
82
|
+
_tool("pakem.session.finish", "Run every Pakem gate and close the session when they pass. Gate failures are returned, not raised.", _object({
|
|
83
|
+
"summary": {"type": "string", "maxLength": 2000},
|
|
84
|
+
"next": {"type": "string", "maxLength": 500}
|
|
85
|
+
})),
|
|
86
|
+
])
|
|
87
|
+
if bound_role in {"lead", "coordinator"}:
|
|
88
|
+
tools.append(_tool("pakem.team.assign", "Assign a task as the server-bound lead/coordinator.", _object({
|
|
89
|
+
"task_id": {"type": "string"}, "agent_id": {"type": "string"}
|
|
90
|
+
}, ["task_id", "agent_id"])))
|
|
91
|
+
return tools
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _rpc_error(request_id: Any, code: int, message: str, data: Any = None) -> dict:
|
|
95
|
+
error = {"code": code, "message": message}
|
|
96
|
+
if data is not None:
|
|
97
|
+
error["data"] = data
|
|
98
|
+
return {"jsonrpc": "2.0", "id": request_id, "error": error}
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def _result(request_id: Any, result: dict) -> dict:
|
|
102
|
+
result.setdefault("resultType", "complete")
|
|
103
|
+
result.setdefault("_meta", {SERVER_INFO: {"name": SERVER_NAME, "version": SERVER_VERSION}})
|
|
104
|
+
return {"jsonrpc": "2.0", "id": request_id, "result": result}
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def _validate_modern_meta(params: dict) -> tuple[str | None, dict | None]:
|
|
108
|
+
meta = params.get("_meta")
|
|
109
|
+
if not isinstance(meta, dict):
|
|
110
|
+
return "params._meta is required", None
|
|
111
|
+
version = meta.get(META_VERSION)
|
|
112
|
+
caps = meta.get(META_CLIENT_CAPS)
|
|
113
|
+
if not isinstance(version, str) or not version:
|
|
114
|
+
return f"_meta.{META_VERSION} must be a string", None
|
|
115
|
+
if not isinstance(caps, dict):
|
|
116
|
+
return f"_meta.{META_CLIENT_CAPS} must be an object", None
|
|
117
|
+
client_info = meta.get(META_CLIENT_INFO)
|
|
118
|
+
if client_info is not None and not isinstance(client_info, dict):
|
|
119
|
+
return f"_meta.{META_CLIENT_INFO} must be an object", None
|
|
120
|
+
return None, meta
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def _run_context(root: Path) -> dict:
|
|
124
|
+
script = Path(__file__).resolve().parents[1] / "pakem.py"
|
|
125
|
+
# In installed projects the CLI is vendored beside pakem_core.
|
|
126
|
+
vendored = root / ".pakem" / "pakem.py"
|
|
127
|
+
cli = vendored if vendored.is_file() else script
|
|
128
|
+
result = __import__("subprocess").run([sys.executable, str(cli), "context", "--json"],
|
|
129
|
+
cwd=root, text=True, capture_output=True,
|
|
130
|
+
timeout=25, check=False)
|
|
131
|
+
if result.returncode not in (0, 1):
|
|
132
|
+
raise RuntimeError((result.stderr or result.stdout or "pakem context failed").strip())
|
|
133
|
+
try:
|
|
134
|
+
return json.loads(result.stdout)
|
|
135
|
+
except json.JSONDecodeError as exc:
|
|
136
|
+
raise RuntimeError(f"context output is not valid JSON: {exc}") from exc
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def _run_cli(root: Path, *args: str, timeout: int = 180) -> dict:
|
|
140
|
+
"""Run the Pakem CLI installed in the project; this is not a free shell."""
|
|
141
|
+
import subprocess
|
|
142
|
+
|
|
143
|
+
vendored = root / ".pakem" / "pakem.py"
|
|
144
|
+
cli = vendored if vendored.is_file() else Path(__file__).resolve().parents[1] / "pakem.py"
|
|
145
|
+
if not cli.is_file():
|
|
146
|
+
raise RuntimeError("Pakem CLI not found in this project")
|
|
147
|
+
result = subprocess.run([sys.executable, str(cli), *args], cwd=root, text=True,
|
|
148
|
+
capture_output=True, timeout=timeout, check=False)
|
|
149
|
+
return {"ok": result.returncode == 0, "exit": result.returncode,
|
|
150
|
+
"output": (result.stdout or "").strip(),
|
|
151
|
+
"error": (result.stderr or "").strip()}
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def _call_tool(name: str, args: dict, root: Path, allow_write: bool,
|
|
155
|
+
bound_agent_id: str | None) -> dict:
|
|
156
|
+
if not isinstance(args, dict):
|
|
157
|
+
raise ValueError("arguments must be an object")
|
|
158
|
+
from pakem_core import coordination, intelligence, protocol, runtime
|
|
159
|
+
|
|
160
|
+
if name == "pakem.context":
|
|
161
|
+
return _run_context(root)
|
|
162
|
+
if name == "pakem.protocol.info":
|
|
163
|
+
return {"protocol": protocol.PROTOCOL_NAME, "version": protocol.PROTOCOL_VERSION,
|
|
164
|
+
"supported_versions": list(protocol.SUPPORTED_VERSIONS),
|
|
165
|
+
"capabilities": protocol.CAPABILITIES}
|
|
166
|
+
if name == "pakem.team.status":
|
|
167
|
+
return coordination.status(root)
|
|
168
|
+
if name == "pakem.team.events":
|
|
169
|
+
return coordination.read_events(root, int(args.get("limit", 50)))
|
|
170
|
+
if name == "pakem.graph":
|
|
171
|
+
return intelligence.build_dependency_graph(root, bool(args.get("include_tests", True)))
|
|
172
|
+
if name == "pakem.impact":
|
|
173
|
+
files = args.get("files")
|
|
174
|
+
if files is not None and (not isinstance(files, list) or any(not isinstance(x, str) for x in files)):
|
|
175
|
+
raise ValueError("files must be an array of strings")
|
|
176
|
+
if args.get("base") and args.get("staged"):
|
|
177
|
+
raise ValueError("base and staged cannot be used together")
|
|
178
|
+
changed = intelligence.changed_files_for_impact(root, files, args.get("base"), bool(args.get("staged", False)))
|
|
179
|
+
graph = intelligence.build_dependency_graph(root)
|
|
180
|
+
return intelligence.analyze_impact(root, changed, graph)
|
|
181
|
+
if name == "pakem.policy.check":
|
|
182
|
+
category = args.get("category")
|
|
183
|
+
risk = args.get("risk", "medium")
|
|
184
|
+
target = args.get("target", "")
|
|
185
|
+
return runtime.evaluate_policy(root, category, risk, target)
|
|
186
|
+
|
|
187
|
+
if not allow_write or not bound_agent_id:
|
|
188
|
+
raise PermissionError("mutating tools are not enabled; the host must use --allow-write and --agent-id")
|
|
189
|
+
task_id = args.get("task_id")
|
|
190
|
+
if name == "pakem.team.claim":
|
|
191
|
+
return coordination.claim_task(root, task_id, bound_agent_id, int(args.get("lease_seconds", 900)))
|
|
192
|
+
if name == "pakem.team.heartbeat":
|
|
193
|
+
return coordination.heartbeat(root, task_id, bound_agent_id, int(args.get("lease_seconds", 900)))
|
|
194
|
+
if name == "pakem.team.submit":
|
|
195
|
+
return coordination.submit_task(root, task_id, bound_agent_id, args.get("summary", ""), args.get("evidence", []))
|
|
196
|
+
if name == "pakem.team.review":
|
|
197
|
+
return coordination.review_task(root, task_id, bound_agent_id, args.get("decision"), args.get("note", ""))
|
|
198
|
+
if name == "pakem.session.start":
|
|
199
|
+
argv = ["start", str(args.get("goal", "")).strip()]
|
|
200
|
+
if bound_agent_id:
|
|
201
|
+
argv += ["--agent", bound_agent_id]
|
|
202
|
+
if args.get("new"):
|
|
203
|
+
argv.append("--new")
|
|
204
|
+
return _run_cli(root, *argv)
|
|
205
|
+
if name == "pakem.session.step":
|
|
206
|
+
argv = ["step", str(args.get("text", "")).strip()]
|
|
207
|
+
if args.get("next"):
|
|
208
|
+
argv += ["--next", str(args["next"]).strip()]
|
|
209
|
+
return _run_cli(root, *argv)
|
|
210
|
+
if name == "pakem.session.finish":
|
|
211
|
+
argv = ["finish"]
|
|
212
|
+
if args.get("summary"):
|
|
213
|
+
argv += ["--summary", str(args["summary"]).strip()]
|
|
214
|
+
if args.get("next"):
|
|
215
|
+
argv += ["--next", str(args["next"]).strip()]
|
|
216
|
+
return _run_cli(root, *argv, timeout=600)
|
|
217
|
+
if name == "pakem.team.assign":
|
|
218
|
+
return coordination.assign_task(root, task_id, args.get("agent_id"), bound_agent_id)
|
|
219
|
+
raise KeyError(f"tool not found: {name}")
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
def handle_message(message: dict, root: str | Path, allow_write: bool = False,
|
|
223
|
+
bound_agent_id: str | None = None) -> dict | None:
|
|
224
|
+
"""Process one modern MCP request. Notifications return None."""
|
|
225
|
+
if not isinstance(message, dict) or message.get("jsonrpc") != "2.0":
|
|
226
|
+
return _rpc_error(message.get("id") if isinstance(message, dict) else None, -32600, "Invalid Request")
|
|
227
|
+
method = message.get("method")
|
|
228
|
+
request_id = message.get("id")
|
|
229
|
+
if not isinstance(method, str) or not method:
|
|
230
|
+
return _rpc_error(request_id, -32600, "Invalid Request")
|
|
231
|
+
is_notification = "id" not in message
|
|
232
|
+
if is_notification:
|
|
233
|
+
return None
|
|
234
|
+
if isinstance(request_id, bool) or not isinstance(request_id, (str, int)):
|
|
235
|
+
return _rpc_error(request_id, -32600, "Request id must be a string or integer")
|
|
236
|
+
params = message.get("params", {})
|
|
237
|
+
if not isinstance(params, dict):
|
|
238
|
+
return _rpc_error(request_id, -32602, "params must be an object")
|
|
239
|
+
meta_error, meta = _validate_modern_meta(params)
|
|
240
|
+
if meta_error:
|
|
241
|
+
return _rpc_error(request_id, -32602, meta_error)
|
|
242
|
+
peer_version = meta[META_VERSION]
|
|
243
|
+
if peer_version != MCP_VERSION:
|
|
244
|
+
return _rpc_error(request_id, -32022, "Unsupported protocol version",
|
|
245
|
+
{"supported": [MCP_VERSION], "requested": peer_version})
|
|
246
|
+
root = Path(root).resolve()
|
|
247
|
+
try:
|
|
248
|
+
if method == "server/discover":
|
|
249
|
+
return _result(request_id, {
|
|
250
|
+
"supportedVersions": [MCP_VERSION],
|
|
251
|
+
"capabilities": {"tools": {"listChanged": False}},
|
|
252
|
+
"instructions": "Pakem provides project context, static intelligence, policy decisions, and optional team coordination. No arbitrary shell execution is exposed.",
|
|
253
|
+
"ttlMs": 3600000,
|
|
254
|
+
"cacheScope": "public",
|
|
255
|
+
})
|
|
256
|
+
if method == "tools/list":
|
|
257
|
+
bound_role = None
|
|
258
|
+
if allow_write and bound_agent_id:
|
|
259
|
+
from pakem_core.coordination import status as team_status
|
|
260
|
+
bound_role = next((agent.get("role") for agent in team_status(root).get("agents", [])
|
|
261
|
+
if agent.get("agentId") == bound_agent_id), None)
|
|
262
|
+
return _result(request_id, {"tools": tool_catalog(allow_write, bound_agent_id, bound_role), "cacheScope": "private", "ttlMs": 60000})
|
|
263
|
+
if method == "tools/call":
|
|
264
|
+
name = params.get("name")
|
|
265
|
+
arguments = params.get("arguments", {})
|
|
266
|
+
if not isinstance(name, str) or not name:
|
|
267
|
+
return _rpc_error(request_id, -32602, "tools/call requires params.name")
|
|
268
|
+
bound_role = None
|
|
269
|
+
if allow_write and bound_agent_id:
|
|
270
|
+
from pakem_core.coordination import status as team_status
|
|
271
|
+
bound_role = next((agent.get("role") for agent in team_status(root).get("agents", [])
|
|
272
|
+
if agent.get("agentId") == bound_agent_id), None)
|
|
273
|
+
known = {tool["name"] for tool in tool_catalog(allow_write, bound_agent_id, bound_role)}
|
|
274
|
+
if name not in known:
|
|
275
|
+
return _rpc_error(request_id, -32602, f"tool is not available: {name}")
|
|
276
|
+
try:
|
|
277
|
+
data = _call_tool(name, arguments, root, allow_write, bound_agent_id)
|
|
278
|
+
return _result(request_id, {"content": [{"type": "text", "text": json.dumps(data, ensure_ascii=False)}],
|
|
279
|
+
"structuredContent": data, "isError": False})
|
|
280
|
+
except PermissionError as exc:
|
|
281
|
+
return _result(request_id, {"content": [{"type": "text", "text": str(exc)}], "isError": True})
|
|
282
|
+
except (ValueError, RuntimeError, OSError, KeyError, TypeError) as exc:
|
|
283
|
+
return _result(request_id, {"content": [{"type": "text", "text": str(exc)}], "isError": True})
|
|
284
|
+
return _rpc_error(request_id, -32601, f"Method not found: {method}")
|
|
285
|
+
except Exception as exc: # keep the stdio process alive on a failed request
|
|
286
|
+
return _rpc_error(request_id, -32603, "Internal error", str(exc))
|
|
287
|
+
|
|
288
|
+
|
|
289
|
+
def serve_stdio(root: str | Path, allow_write: bool = False,
|
|
290
|
+
bound_agent_id: str | None = None) -> int:
|
|
291
|
+
root = Path(root).resolve()
|
|
292
|
+
if allow_write and not bound_agent_id:
|
|
293
|
+
print("[pakem-mcp] --allow-write requires a host-bound --agent-id.", file=sys.stderr)
|
|
294
|
+
return 2
|
|
295
|
+
for line in sys.stdin:
|
|
296
|
+
if len(line.encode("utf-8", errors="replace")) > 8 * 1024 * 1024:
|
|
297
|
+
response = _rpc_error(None, -32600, "Message too large (max 8 MiB)")
|
|
298
|
+
else:
|
|
299
|
+
try:
|
|
300
|
+
message = json.loads(line)
|
|
301
|
+
except json.JSONDecodeError as exc:
|
|
302
|
+
response = _rpc_error(None, -32700, f"Parse error: {exc.msg}")
|
|
303
|
+
else:
|
|
304
|
+
response = handle_message(message, root, allow_write, bound_agent_id)
|
|
305
|
+
if response is not None:
|
|
306
|
+
sys.stdout.write(json.dumps(response, ensure_ascii=False, separators=(",", ":")) + "\n")
|
|
307
|
+
sys.stdout.flush()
|
|
308
|
+
return 0
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
"""Stable Pakem Protocol contracts and peer capability negotiation.
|
|
2
|
+
|
|
3
|
+
Pakem protocol versioning is independent from external transports such as MCP.
|
|
4
|
+
The v1.0 event/session wire contract is frozen; new features are negotiated as
|
|
5
|
+
capabilities rather than silently changing existing event envelopes.
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from typing import Iterable
|
|
10
|
+
|
|
11
|
+
PROTOCOL_NAME = "pakem"
|
|
12
|
+
PROTOCOL_VERSION = "1.0"
|
|
13
|
+
SUPPORTED_VERSIONS = ("1.0",)
|
|
14
|
+
CAPABILITIES = {
|
|
15
|
+
"events.v1": "Append-only JSONL event envelope v1",
|
|
16
|
+
"events.integrity.v1": "Hash-chained ledger events with optional Ed25519 seals",
|
|
17
|
+
"sessions.v1": "Persistent session metadata v1",
|
|
18
|
+
"context.snapshot.v1": "Read-only structured project and workflow context snapshot",
|
|
19
|
+
"runtime.v1": "Workflow state machine, checkpoints, and policy decisions",
|
|
20
|
+
"intelligence.graph.v1": "Static local dependency graph",
|
|
21
|
+
"intelligence.impact.v1": "Change impact analysis",
|
|
22
|
+
"coordination.v1": "Shared multi-agent task board and leases",
|
|
23
|
+
"coordination.review.v1": "Independent review before task completion",
|
|
24
|
+
"git.worktree.v1": "Isolated Git worktree lifecycle adapter",
|
|
25
|
+
"mcp.stdio.2026-07-28": "MCP modern stateless stdio adapter",
|
|
26
|
+
"identity.ed25519.v1": "Agent public-key identity and signed Pakem attestations",
|
|
27
|
+
"identity.delegation.v1": "Audience/action-scoped Ed25519 delegation tokens with expiry",
|
|
28
|
+
"coordination.sqlite.v1": "Transactional local SQLite coordination backend",
|
|
29
|
+
"conformance.v1": "Protocol and runtime conformance test profile v1",
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def negotiate(peer_version: str, peer_capabilities: Iterable[str] | None = None) -> dict:
|
|
34
|
+
"""Negotiate a Pakem protocol version and feature intersection."""
|
|
35
|
+
if not isinstance(peer_version, str) or not peer_version.strip():
|
|
36
|
+
raise ValueError("peer_version must be a non-empty string")
|
|
37
|
+
peer_version = peer_version.strip()
|
|
38
|
+
peer = []
|
|
39
|
+
for item in peer_capabilities or []:
|
|
40
|
+
if not isinstance(item, str) or not item.strip():
|
|
41
|
+
raise ValueError("peer_capabilities must contain non-empty strings")
|
|
42
|
+
if item.strip() not in peer:
|
|
43
|
+
peer.append(item.strip())
|
|
44
|
+
compatible = peer_version in SUPPORTED_VERSIONS
|
|
45
|
+
common = sorted(set(peer) & set(CAPABILITIES))
|
|
46
|
+
unsupported = sorted(set(peer) - set(CAPABILITIES))
|
|
47
|
+
return {
|
|
48
|
+
"protocol": PROTOCOL_NAME,
|
|
49
|
+
"local_version": PROTOCOL_VERSION,
|
|
50
|
+
"peer_version": peer_version,
|
|
51
|
+
"compatible": compatible,
|
|
52
|
+
"selected_version": PROTOCOL_VERSION if compatible else None,
|
|
53
|
+
"supported_versions": list(SUPPORTED_VERSIONS),
|
|
54
|
+
"common_capabilities": common,
|
|
55
|
+
"unsupported_peer_capabilities": unsupported,
|
|
56
|
+
"local_capabilities": sorted(CAPABILITIES),
|
|
57
|
+
"notes": [
|
|
58
|
+
"Event envelope v1.0 stays stable; new extensions are negotiated through capabilities.",
|
|
59
|
+
"A capability only declares contract support, not authorization to perform side effects.",
|
|
60
|
+
],
|
|
61
|
+
}
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
"""Artifact reconciliation: what plan/spec claims versus what actually changed.
|
|
2
|
+
|
|
3
|
+
The functions here are pure: they do not read the disk and do not touch git. The
|
|
4
|
+
caller (CLI) collects `changed_files`, `tasks`, and `acceptance`, then hands them
|
|
5
|
+
in here. That makes the logic testable without a repo and without subprocesses.
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import fnmatch
|
|
10
|
+
from pathlib import PurePosixPath
|
|
11
|
+
|
|
12
|
+
from .intelligence import CODE_EXTS
|
|
13
|
+
|
|
14
|
+
SCHEMA_VERSION = "pakem.reconciliation/v1"
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def is_code_path(path: str) -> bool:
|
|
18
|
+
return PurePosixPath(path).suffix.lower() in CODE_EXTS
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def matches(path: str, scope: str) -> bool:
|
|
22
|
+
"""Match one git path against one task scope entry.
|
|
23
|
+
|
|
24
|
+
A scope entry may be an exact file, a directory (with or without a trailing
|
|
25
|
+
slash), or a simple glob pattern. Matching is always against a relative
|
|
26
|
+
POSIX-formatted path.
|
|
27
|
+
"""
|
|
28
|
+
entry = str(scope).strip().replace("\\", "/").rstrip("/")
|
|
29
|
+
if not entry:
|
|
30
|
+
return False
|
|
31
|
+
if path == entry:
|
|
32
|
+
return True
|
|
33
|
+
if path.startswith(entry + "/"):
|
|
34
|
+
return True
|
|
35
|
+
return fnmatch.fnmatch(path, entry)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def declared_scope(tasks: list[dict]) -> list[str]:
|
|
39
|
+
seen = []
|
|
40
|
+
for task in tasks:
|
|
41
|
+
for entry in task.get("files", []) or []:
|
|
42
|
+
entry = str(entry).strip()
|
|
43
|
+
if entry and entry not in seen:
|
|
44
|
+
seen.append(entry)
|
|
45
|
+
return seen
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def reconcile(changed_files: list[str], tasks: list[dict] | None = None,
|
|
49
|
+
acceptance: list[dict] | None = None) -> dict:
|
|
50
|
+
"""Compare actual changes against the plan scope and the spec acceptance criteria."""
|
|
51
|
+
tasks = tasks or []
|
|
52
|
+
acceptance = acceptance or []
|
|
53
|
+
changed = sorted({str(p).strip().replace("\\", "/") for p in changed_files if str(p).strip()})
|
|
54
|
+
scope = declared_scope(tasks)
|
|
55
|
+
|
|
56
|
+
in_scope = [p for p in changed if any(matches(p, entry) for entry in scope)]
|
|
57
|
+
out_of_scope = [p for p in changed if p not in in_scope]
|
|
58
|
+
code_out = [p for p in out_of_scope if is_code_path(p)]
|
|
59
|
+
|
|
60
|
+
per_task = []
|
|
61
|
+
for task in tasks:
|
|
62
|
+
entries = [str(f).strip() for f in (task.get("files") or []) if str(f).strip()]
|
|
63
|
+
touched = [p for p in changed if any(matches(p, entry) for entry in entries)]
|
|
64
|
+
per_task.append({
|
|
65
|
+
"taskId": task.get("taskId") or task.get("id"),
|
|
66
|
+
"done": bool(task.get("done")),
|
|
67
|
+
"declared": entries,
|
|
68
|
+
"changed": touched,
|
|
69
|
+
"untouched": [e for e in entries if not any(matches(p, e) for p in changed)],
|
|
70
|
+
})
|
|
71
|
+
|
|
72
|
+
unchecked = [item for item in acceptance if not item.get("checked")]
|
|
73
|
+
return {
|
|
74
|
+
"schema_version": SCHEMA_VERSION,
|
|
75
|
+
"changed_files": changed,
|
|
76
|
+
"declared_scope": scope,
|
|
77
|
+
"in_scope": in_scope,
|
|
78
|
+
"out_of_scope": out_of_scope,
|
|
79
|
+
"code_out_of_scope": code_out,
|
|
80
|
+
"tasks": per_task,
|
|
81
|
+
"acceptance": {
|
|
82
|
+
"total": len(acceptance),
|
|
83
|
+
"checked": len(acceptance) - len(unchecked),
|
|
84
|
+
"unchecked": [str(item.get("text", "")).strip() for item in unchecked],
|
|
85
|
+
},
|
|
86
|
+
"summary": {
|
|
87
|
+
"changed": len(changed),
|
|
88
|
+
"in_scope": len(in_scope),
|
|
89
|
+
"out_of_scope": len(out_of_scope),
|
|
90
|
+
"code_out_of_scope": len(code_out),
|
|
91
|
+
"acceptance_unchecked": len(unchecked),
|
|
92
|
+
},
|
|
93
|
+
"ok": not code_out and not unchecked,
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def render_text(result: dict) -> str:
|
|
98
|
+
summary = result["summary"]
|
|
99
|
+
lines = [f"RECONCILIATION {summary['changed']} files changed, "
|
|
100
|
+
f"{summary['in_scope']} in scope, {summary['out_of_scope']} out of scope"]
|
|
101
|
+
if not result["declared_scope"] and summary["changed"]:
|
|
102
|
+
lines.append(" (no PLAN.md/task scope; all changes counted as out of scope)")
|
|
103
|
+
if result["code_out_of_scope"]:
|
|
104
|
+
lines.append(" out of scope (code):")
|
|
105
|
+
lines.extend(f" - {p}" for p in result["code_out_of_scope"])
|
|
106
|
+
other = [p for p in result["out_of_scope"] if p not in result["code_out_of_scope"]]
|
|
107
|
+
if other:
|
|
108
|
+
lines.append(" out of scope (non-code, usually safe):")
|
|
109
|
+
lines.extend(f" - {p}" for p in other)
|
|
110
|
+
acceptance = result["acceptance"]
|
|
111
|
+
if acceptance["total"]:
|
|
112
|
+
lines.append(f" acceptance: {acceptance['checked']}/{acceptance['total']} checked")
|
|
113
|
+
lines.extend(f" [ ] {text}" for text in acceptance["unchecked"][:10])
|
|
114
|
+
for task in result["tasks"]:
|
|
115
|
+
if task["untouched"] and task["done"]:
|
|
116
|
+
lines.append(f" note: {task['taskId']} done but scope untouched: "
|
|
117
|
+
+ ", ".join(task["untouched"]))
|
|
118
|
+
lines.append(" VERDICT: " + ("aligned" if result["ok"] else "not aligned"))
|
|
119
|
+
return "\n".join(lines)
|