diffdesk 0.1.0__py3-none-any.whl

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 (59) hide show
  1. diffdesk/__init__.py +3 -0
  2. diffdesk/agent.py +414 -0
  3. diffdesk/agent_guide.md +112 -0
  4. diffdesk/cli.py +329 -0
  5. diffdesk/config.py +130 -0
  6. diffdesk/gitio.py +391 -0
  7. diffdesk/index.py +635 -0
  8. diffdesk/mcp.py +472 -0
  9. diffdesk/server.py +750 -0
  10. diffdesk/static/app.js +402 -0
  11. diffdesk/static/index.html +129 -0
  12. diffdesk/static/js/api.js +58 -0
  13. diffdesk/static/js/boot.js +12 -0
  14. diffdesk/static/js/diffview.js +359 -0
  15. diffdesk/static/js/dom.js +82 -0
  16. diffdesk/static/js/editor-cm.js +225 -0
  17. diffdesk/static/js/editor-monaco.js +116 -0
  18. diffdesk/static/js/flow.js +227 -0
  19. diffdesk/static/js/hunks.js +40 -0
  20. diffdesk/static/js/markdown.js +102 -0
  21. diffdesk/static/js/settings.js +228 -0
  22. diffdesk/static/js/subject.js +127 -0
  23. diffdesk/static/js/tree.js +492 -0
  24. diffdesk/static/js/treemap.js +217 -0
  25. diffdesk/static/style.css +508 -0
  26. diffdesk/static/vendor/LICENSES.txt +603 -0
  27. diffdesk/static/vendor/codemirror.js +24 -0
  28. diffdesk/static/vendor/fonts/KaTeX_AMS-Regular.woff2 +0 -0
  29. diffdesk/static/vendor/fonts/KaTeX_Caligraphic-Bold.woff2 +0 -0
  30. diffdesk/static/vendor/fonts/KaTeX_Caligraphic-Regular.woff2 +0 -0
  31. diffdesk/static/vendor/fonts/KaTeX_Fraktur-Bold.woff2 +0 -0
  32. diffdesk/static/vendor/fonts/KaTeX_Fraktur-Regular.woff2 +0 -0
  33. diffdesk/static/vendor/fonts/KaTeX_Main-Bold.woff2 +0 -0
  34. diffdesk/static/vendor/fonts/KaTeX_Main-BoldItalic.woff2 +0 -0
  35. diffdesk/static/vendor/fonts/KaTeX_Main-Italic.woff2 +0 -0
  36. diffdesk/static/vendor/fonts/KaTeX_Main-Regular.woff2 +0 -0
  37. diffdesk/static/vendor/fonts/KaTeX_Math-BoldItalic.woff2 +0 -0
  38. diffdesk/static/vendor/fonts/KaTeX_Math-Italic.woff2 +0 -0
  39. diffdesk/static/vendor/fonts/KaTeX_SansSerif-Bold.woff2 +0 -0
  40. diffdesk/static/vendor/fonts/KaTeX_SansSerif-Italic.woff2 +0 -0
  41. diffdesk/static/vendor/fonts/KaTeX_SansSerif-Regular.woff2 +0 -0
  42. diffdesk/static/vendor/fonts/KaTeX_Script-Regular.woff2 +0 -0
  43. diffdesk/static/vendor/fonts/KaTeX_Size1-Regular.woff2 +0 -0
  44. diffdesk/static/vendor/fonts/KaTeX_Size2-Regular.woff2 +0 -0
  45. diffdesk/static/vendor/fonts/KaTeX_Size3-Regular.woff2 +0 -0
  46. diffdesk/static/vendor/fonts/KaTeX_Size4-Regular.woff2 +0 -0
  47. diffdesk/static/vendor/fonts/KaTeX_Typewriter-Regular.woff2 +0 -0
  48. diffdesk/static/vendor/fonts/OFL.txt +102 -0
  49. diffdesk/static/vendor/katex.css +2 -0
  50. diffdesk/static/vendor/katex.js +258 -0
  51. diffdesk/static/vendor/marked.js +72 -0
  52. diffdesk/subject.schema.json +59 -0
  53. diffdesk-0.1.0.dist-info/METADATA +520 -0
  54. diffdesk-0.1.0.dist-info/RECORD +59 -0
  55. diffdesk-0.1.0.dist-info/WHEEL +4 -0
  56. diffdesk-0.1.0.dist-info/entry_points.txt +2 -0
  57. diffdesk-0.1.0.dist-info/licenses/LICENSE +21 -0
  58. diffdesk-0.1.0.dist-info/licenses/src/diffdesk/static/vendor/LICENSES.txt +603 -0
  59. diffdesk-0.1.0.dist-info/licenses/src/diffdesk/static/vendor/fonts/OFL.txt +102 -0
diffdesk/mcp.py ADDED
@@ -0,0 +1,472 @@
1
+ """MCP server on standard input and output (``diffdesk mcp``).
2
+
3
+ The server supports both eras of the Model Context Protocol:
4
+
5
+ - Revision 2026-07-28: every request carries its protocol version in
6
+ ``params._meta`` and is answered without session state. ``server/discover``
7
+ lists the supported versions.
8
+ - Revisions 2025-11-25 and 2025-06-18: the client opens with ``initialize``,
9
+ and the negotiated version holds for the life of the process.
10
+
11
+ Each message is one line of UTF-8 JSON. Standard output carries protocol
12
+ messages only; logs go to standard error. The server exits at end of input.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import json
18
+ import logging
19
+ import sys
20
+ from collections.abc import Callable
21
+ from pathlib import Path
22
+ from typing import Any
23
+
24
+ from . import __version__
25
+ from .agent import GUIDE_PATH, collect_reviews, create_subject, schema_errors, validate_subjects
26
+ from .config import load_config
27
+ from .gitio import GitError, InvalidInput
28
+ from .index import STATUSES
29
+
30
+ log = logging.getLogger(__name__)
31
+
32
+ MODERN_VERSIONS = ("2026-07-28",)
33
+ # Newest first: an ``initialize`` that asks for another version gets the first.
34
+ LEGACY_VERSIONS = ("2025-11-25", "2025-06-18")
35
+
36
+ META_VERSION = "io.modelcontextprotocol/protocolVersion"
37
+ META_CAPABILITIES = "io.modelcontextprotocol/clientCapabilities"
38
+ META_SERVER = "io.modelcontextprotocol/serverInfo"
39
+
40
+ PARSE_ERROR = -32700
41
+ INVALID_REQUEST = -32600
42
+ METHOD_NOT_FOUND = -32601
43
+ INVALID_PARAMS = -32602
44
+ INTERNAL_ERROR = -32603
45
+ UNSUPPORTED_VERSION = -32022
46
+
47
+ SERVER_INFO = {"name": "diffdesk", "version": __version__}
48
+ # Caching hints of 2026-07-28 for ``server/discover`` and ``tools/list``. The
49
+ # answers change only when diffdesk is upgraded, and any positive time-to-live
50
+ # would be an arbitrary number, so the server makes no freshness claim.
51
+ CACHE_HINTS = {"ttlMs": 0, "cacheScope": "public"}
52
+
53
+ INSTRUCTIONS = (
54
+ "diffdesk is a review desk for commits: you write one subject per commit, "
55
+ "a person reviews it, and you read the verdicts back. Call get_agent_guide "
56
+ "once before your first add_subject call. After each commit, call add_subject. "
57
+ "Later, call list_reviews to read the verdicts, comments and edits. For each "
58
+ "subject with status change or rejected, do what the comment and the edits ask, "
59
+ "make a new commit and call add_subject for it with a new id. Name the old "
60
+ "subject id in why."
61
+ )
62
+
63
+ _TEXT = {"type": "string", "minLength": 1}
64
+
65
+ TOOLS: list[dict[str, Any]] = [
66
+ {
67
+ "name": "add_subject",
68
+ "title": "Add a review subject",
69
+ "description": (
70
+ "Write a review subject for one git commit or a commit range, so that a "
71
+ "person can review the change in diffdesk. Make the commit first. diffdesk "
72
+ "reads the full commit IDs, the work tree path and the changed files from "
73
+ "git, checks the subject against the schema and writes "
74
+ "<review root>/subjects/<package>/<id>.json. Returns the file path and the "
75
+ "subject. By default the diff is HEAD^..HEAD. An existing subject is not "
76
+ "replaced unless force is true."
77
+ ),
78
+ "inputSchema": {
79
+ "type": "object",
80
+ "properties": {
81
+ "repo": {
82
+ **_TEXT,
83
+ "description": (
84
+ "Absolute path of a folder inside the git work tree that holds the commit."
85
+ ),
86
+ },
87
+ "id": {
88
+ **_TEXT,
89
+ "description": (
90
+ "Subject ID, unique inside its package. Letters, digits, '.', "
91
+ "'_' and '-'; starts with a letter or digit; no '..'. "
92
+ "Example: FIX-12."
93
+ ),
94
+ },
95
+ "title": {**_TEXT, "description": "One-line title of the change."},
96
+ "commit": {
97
+ **_TEXT,
98
+ "description": (
99
+ "Commit to review against its first parent. Default: HEAD. "
100
+ "Do not give it together with base and head."
101
+ ),
102
+ },
103
+ "base": {**_TEXT, "description": "Old side of a commit range. Give head too."},
104
+ "head": {**_TEXT, "description": "New side of a commit range. Give base too."},
105
+ "package": {
106
+ **_TEXT,
107
+ "description": (
108
+ "Package name, same rules as id. Default: the name of the work "
109
+ "tree folder."
110
+ ),
111
+ },
112
+ "summary": {
113
+ **_TEXT,
114
+ "description": "One sentence: what is wrong and what the change does.",
115
+ },
116
+ "why": {
117
+ **_TEXT,
118
+ "description": (
119
+ "Reasons for the change, in Markdown, with the headings that "
120
+ "get_agent_guide gives: Problem, Evidence, Fix logic, Test, "
121
+ "Tradeoffs."
122
+ ),
123
+ },
124
+ "priority": {**_TEXT, "description": "For example P1, P2 or P3."},
125
+ "recommended": {
126
+ **_TEXT,
127
+ "description": "Suggested verdict: accept, reject or user-decision.",
128
+ },
129
+ "tags": {
130
+ "type": "array",
131
+ "items": {"type": "string"},
132
+ "description": "Free labels.",
133
+ },
134
+ "branch": {
135
+ **_TEXT,
136
+ "description": "Branch name for the review tree. Default: none.",
137
+ },
138
+ "force": {
139
+ "type": "boolean",
140
+ "description": (
141
+ "Replace an existing subject with the same package and ID, for "
142
+ "example after a rebase or an amend. Default: false."
143
+ ),
144
+ },
145
+ },
146
+ "required": ["repo", "id", "title"],
147
+ "additionalProperties": False,
148
+ },
149
+ "annotations": {"readOnlyHint": False, "openWorldHint": False},
150
+ },
151
+ {
152
+ "name": "list_reviews",
153
+ "title": "List reviews and edits",
154
+ "description": (
155
+ "Read the review state of the subjects, in the order of the review tree. "
156
+ "Each item has id, package, title, status (pending, accepted, rejected or "
157
+ "change), the last verdict, comment and time, history_count, repo, head, "
158
+ "and edits: [{path, edit_file}]. An edit file holds the full new content of "
159
+ "one file as the person changed it, not a patch: compare it with that file "
160
+ "at the subject's head commit. To find the work to do, ask for the "
161
+ "statuses change and rejected. For each request, do what the comment and "
162
+ "the edits ask, make a new commit and call add_subject for it with a new "
163
+ "id. Name the old subject id in why."
164
+ ),
165
+ "inputSchema": {
166
+ "type": "object",
167
+ "properties": {
168
+ "statuses": {
169
+ "type": "array",
170
+ "items": {"type": "string", "enum": list(STATUSES)},
171
+ "description": "Keep only subjects with one of these statuses. Default: all.",
172
+ },
173
+ "package": {**_TEXT, "description": "Keep only subjects of this package."},
174
+ "id": {**_TEXT, "description": "Keep only subjects with this ID."},
175
+ },
176
+ "additionalProperties": False,
177
+ },
178
+ "annotations": {"readOnlyHint": True, "openWorldHint": False},
179
+ },
180
+ {
181
+ "name": "get_agent_guide",
182
+ "title": "Get the agent guide",
183
+ "description": (
184
+ "Return the diffdesk guide for coding agents, in Markdown: the steps, how to "
185
+ "write 'why', the fields of each review and the subject fields. Read it once "
186
+ "before the first add_subject call. The guide shows shell commands; these "
187
+ "tools do the same work: 'diffdesk add' is add_subject, 'diffdesk reviews' "
188
+ "is list_reviews and 'diffdesk validate' is validate_subjects."
189
+ ),
190
+ "inputSchema": {"type": "object", "additionalProperties": False},
191
+ "annotations": {"readOnlyHint": True, "openWorldHint": False},
192
+ },
193
+ {
194
+ "name": "validate_subjects",
195
+ "title": "Validate all subjects",
196
+ "description": (
197
+ "Check every subject file of the review root against the subject schema, "
198
+ "and check that no two files hold the same package and ID. Returns root, "
199
+ "files (the number of subject files), problems and warnings. Each problem "
200
+ "starts with the file path relative to the root. Problems do not make "
201
+ "this call fail."
202
+ ),
203
+ "inputSchema": {"type": "object", "additionalProperties": False},
204
+ "annotations": {"readOnlyHint": True, "openWorldHint": False},
205
+ },
206
+ ]
207
+ TOOLS_BY_NAME = {tool["name"]: tool for tool in TOOLS}
208
+ MODERN_METHODS = ("server/discover", "tools/list", "tools/call")
209
+
210
+
211
+ def _add_subject(root: Path, args: dict[str, Any]) -> dict[str, Any]:
212
+ path, subject = create_subject(
213
+ load_config(root),
214
+ repo=args["repo"],
215
+ subject_id=args["id"],
216
+ title=args["title"],
217
+ commit=args.get("commit"),
218
+ base=args.get("base"),
219
+ head=args.get("head"),
220
+ package=args.get("package"),
221
+ summary=args.get("summary"),
222
+ why=args.get("why"),
223
+ priority=args.get("priority"),
224
+ recommended=args.get("recommended"),
225
+ tags=args.get("tags"),
226
+ branch=args.get("branch"),
227
+ force=args.get("force", False),
228
+ )
229
+ return {"path": str(path), "subject": subject}
230
+
231
+
232
+ def _list_reviews(root: Path, args: dict[str, Any]) -> list[dict[str, Any]]:
233
+ return collect_reviews(
234
+ load_config(root),
235
+ statuses=args.get("statuses"),
236
+ package=args.get("package"),
237
+ subject_id=args.get("id"),
238
+ )
239
+
240
+
241
+ def _validate_subjects(root: Path, args: dict[str, Any]) -> dict[str, Any]:
242
+ config = load_config(root)
243
+ return {"root": str(config.root), **validate_subjects(config)}
244
+
245
+
246
+ HANDLERS: dict[str, Callable[[Path, dict[str, Any]], Any]] = {
247
+ "add_subject": _add_subject,
248
+ "list_reviews": _list_reviews,
249
+ "get_agent_guide": lambda root, args: GUIDE_PATH.read_text(encoding="utf-8"),
250
+ "validate_subjects": _validate_subjects,
251
+ }
252
+
253
+
254
+ class ProtocolError(Exception):
255
+ """A request that gets a JSON-RPC error response instead of a result."""
256
+
257
+ def __init__(self, code: int, message: str, data: Any = None) -> None:
258
+ super().__init__(message)
259
+ self.code = code
260
+ self.message = message
261
+ self.data = data
262
+
263
+
264
+ def _error(msg_id: Any, code: int, message: str, data: Any = None) -> dict[str, Any]:
265
+ error: dict[str, Any] = {"code": code, "message": message}
266
+ if data is not None:
267
+ error["data"] = data
268
+ return {"jsonrpc": "2.0", "id": msg_id, "error": error}
269
+
270
+
271
+ class McpServer:
272
+ """Answer MCP messages for one review root.
273
+
274
+ Parameters
275
+ ----------
276
+ root : Path
277
+ The review root. Its ``diffdesk.toml`` is read again on each tool
278
+ call, so a bad file makes that call fail, not the server.
279
+
280
+ Attributes
281
+ ----------
282
+ legacy_version : str or None
283
+ Version negotiated by ``initialize``, or `None` before it.
284
+ """
285
+
286
+ def __init__(self, root: Path) -> None:
287
+ self.root = root
288
+ self.legacy_version: str | None = None
289
+
290
+ def handle(self, message: Any) -> dict[str, Any] | None:
291
+ """Return the response to one decoded message.
292
+
293
+ Parameters
294
+ ----------
295
+ message : Any
296
+ One decoded JSON value from the client.
297
+
298
+ Returns
299
+ -------
300
+ dict or None
301
+ The response, or `None` for a notification or a response from
302
+ the client, which get no reply.
303
+ """
304
+ if not isinstance(message, dict):
305
+ return _error(None, INVALID_REQUEST, "A message must be one JSON-RPC object")
306
+ msg_id = message.get("id")
307
+ has_id = "id" in message
308
+ if "method" not in message and ("result" in message or "error" in message):
309
+ log.debug("ignored a response from the client (id %r)", msg_id)
310
+ return None
311
+ method = message.get("method")
312
+ if not has_id and isinstance(method, str):
313
+ log.debug("notification %s", method)
314
+ return None
315
+ valid_id = isinstance(msg_id, str | int) and not isinstance(msg_id, bool)
316
+ if message.get("jsonrpc") != "2.0" or not isinstance(method, str) or not valid_id:
317
+ return _error(
318
+ msg_id if valid_id else None,
319
+ INVALID_REQUEST,
320
+ "Invalid request: needs jsonrpc '2.0', a string method and a string or integer id",
321
+ )
322
+ params = message.get("params", {})
323
+ if not isinstance(params, dict):
324
+ return _error(msg_id, INVALID_PARAMS, "params must be an object")
325
+ log.debug("request %s (id %r)", method, msg_id)
326
+ try:
327
+ result = self.dispatch(method, params)
328
+ except ProtocolError as exc:
329
+ return _error(msg_id, exc.code, exc.message, exc.data)
330
+ except Exception:
331
+ log.exception("request %s failed", method)
332
+ return _error(
333
+ msg_id, INTERNAL_ERROR, f"Internal error in {method}; see the server log"
334
+ )
335
+ return {"jsonrpc": "2.0", "id": msg_id, "result": result}
336
+
337
+ def dispatch(self, method: str, params: dict[str, Any]) -> dict[str, Any]:
338
+ """Return the result of one request.
339
+
340
+ A request whose ``_meta`` holds a protocol version follows revision
341
+ 2026-07-28. Other requests follow the version negotiated by
342
+ ``initialize``.
343
+
344
+ Raises
345
+ ------
346
+ ProtocolError
347
+ If the request gets a JSON-RPC error.
348
+ """
349
+ meta = params.get("_meta")
350
+ if isinstance(meta, dict) and META_VERSION in meta:
351
+ return self._modern(method, params, meta)
352
+ if method == "initialize":
353
+ return self._initialize(params)
354
+ if method == "ping":
355
+ return {}
356
+ if self.legacy_version is None:
357
+ if method in MODERN_METHODS:
358
+ raise ProtocolError(
359
+ INVALID_PARAMS,
360
+ f"Missing _meta field '{META_VERSION}'. Send 'initialize' first "
361
+ f"(protocol {' or '.join(LEGACY_VERSIONS)}), or give the request _meta "
362
+ f"of protocol {' or '.join(MODERN_VERSIONS)}.",
363
+ )
364
+ raise ProtocolError(METHOD_NOT_FOUND, f"Method not found: {method}")
365
+ if method == "tools/list":
366
+ return {"tools": TOOLS}
367
+ if method == "tools/call":
368
+ return self._call(params)
369
+ raise ProtocolError(METHOD_NOT_FOUND, f"Method not found: {method}")
370
+
371
+ def _initialize(self, params: dict[str, Any]) -> dict[str, Any]:
372
+ requested = params.get("protocolVersion")
373
+ if not isinstance(requested, str):
374
+ raise ProtocolError(INVALID_PARAMS, "initialize needs 'protocolVersion' (a string)")
375
+ # 2025-11-25 lifecycle: answer with the requested version if supported,
376
+ # else with another supported version, which SHOULD be the latest.
377
+ self.legacy_version = requested if requested in LEGACY_VERSIONS else LEGACY_VERSIONS[0]
378
+ log.info("initialize: client asked for %s, using %s", requested, self.legacy_version)
379
+ return {
380
+ "protocolVersion": self.legacy_version,
381
+ "capabilities": {"tools": {}},
382
+ "serverInfo": SERVER_INFO,
383
+ "instructions": INSTRUCTIONS,
384
+ }
385
+
386
+ def _modern(self, method: str, params: dict[str, Any], meta: dict[str, Any]) -> dict[str, Any]:
387
+ version = meta.get(META_VERSION)
388
+ if not isinstance(version, str) or not isinstance(meta.get(META_CAPABILITIES), dict):
389
+ raise ProtocolError(
390
+ INVALID_PARAMS,
391
+ f"_meta needs '{META_VERSION}' (a string) and '{META_CAPABILITIES}' (an object)",
392
+ )
393
+ if version not in MODERN_VERSIONS:
394
+ raise ProtocolError(
395
+ UNSUPPORTED_VERSION,
396
+ "Unsupported protocol version",
397
+ {"supported": list(MODERN_VERSIONS), "requested": version},
398
+ )
399
+ if method == "server/discover":
400
+ result = {
401
+ "supportedVersions": list(MODERN_VERSIONS),
402
+ "capabilities": {"tools": {}},
403
+ "instructions": INSTRUCTIONS,
404
+ **CACHE_HINTS,
405
+ }
406
+ elif method == "tools/list":
407
+ result = {"tools": TOOLS, **CACHE_HINTS}
408
+ elif method == "tools/call":
409
+ result = self._call(params)
410
+ else:
411
+ raise ProtocolError(METHOD_NOT_FOUND, f"Method not found: {method}")
412
+ return {"resultType": "complete", **result, "_meta": {META_SERVER: SERVER_INFO}}
413
+
414
+ def _call(self, params: dict[str, Any]) -> dict[str, Any]:
415
+ name = params.get("name")
416
+ args = params.get("arguments", {})
417
+ if not isinstance(name, str) or not isinstance(args, dict):
418
+ raise ProtocolError(
419
+ INVALID_PARAMS, "tools/call needs 'name' (a string) and 'arguments' (an object)"
420
+ )
421
+ tool = TOOLS_BY_NAME.get(name)
422
+ if tool is None:
423
+ raise ProtocolError(INVALID_PARAMS, f"Unknown tool: {name}")
424
+ schema = tool["inputSchema"]
425
+ errors = schema_errors(args, schema, schema, "arguments")
426
+ if errors:
427
+ return _tool_result("; ".join(errors), is_error=True)
428
+ try:
429
+ value = HANDLERS[name](self.root, args)
430
+ except (InvalidInput, GitError, OSError, ValueError) as exc:
431
+ log.info("tool %s failed: %s", name, exc)
432
+ return _tool_result(str(exc), is_error=True)
433
+ text = value if isinstance(value, str) else json.dumps(value, ensure_ascii=False)
434
+ return _tool_result(text, is_error=False)
435
+
436
+
437
+ def _tool_result(text: str, *, is_error: bool) -> dict[str, Any]:
438
+ return {"content": [{"type": "text", "text": text}], "isError": is_error}
439
+
440
+
441
+ def serve_stdio(root: Path) -> int:
442
+ """Answer MCP messages on standard input until it ends.
443
+
444
+ Parameters
445
+ ----------
446
+ root : Path
447
+ The review root.
448
+
449
+ Returns
450
+ -------
451
+ int
452
+ Exit code 0.
453
+ """
454
+ root = root.resolve()
455
+ server = McpServer(root)
456
+ stdin, stdout = sys.stdin.buffer, sys.stdout.buffer
457
+ log.info("diffdesk %s MCP server on stdio (root: %s)", __version__, root)
458
+ for line in iter(stdin.readline, b""):
459
+ if not line.strip():
460
+ continue
461
+ try:
462
+ message = json.loads(line)
463
+ except (ValueError, RecursionError) as exc:
464
+ reply = _error(None, PARSE_ERROR, f"Parse error: {exc}")
465
+ else:
466
+ reply = server.handle(message)
467
+ if reply is not None:
468
+ # ASCII JSON without indentation has no line breaks inside.
469
+ stdout.write(json.dumps(reply).encode("ascii") + b"\n")
470
+ stdout.flush()
471
+ log.info("end of input; MCP server stops")
472
+ return 0