kontexta 6.1.0 → 6.1.2

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 (109) hide show
  1. package/bundle/standalone/CHANGELOG.md +21 -0
  2. package/bundle/standalone/apps/web/.next/BUILD_ID +1 -1
  3. package/bundle/standalone/apps/web/.next/app-build-manifest.json +15 -15
  4. package/bundle/standalone/apps/web/.next/app-path-routes-manifest.json +3 -3
  5. package/bundle/standalone/apps/web/.next/build-manifest.json +2 -2
  6. package/bundle/standalone/apps/web/.next/prerender-manifest.json +23 -23
  7. package/bundle/standalone/apps/web/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
  8. package/bundle/standalone/apps/web/.next/server/app/_not-found.html +1 -1
  9. package/bundle/standalone/apps/web/.next/server/app/_not-found.rsc +4 -4
  10. package/bundle/standalone/apps/web/.next/server/app/api/about/route_client-reference-manifest.js +1 -1
  11. package/bundle/standalone/apps/web/.next/server/app/api/agents/[id]/hooks/route_client-reference-manifest.js +1 -1
  12. package/bundle/standalone/apps/web/.next/server/app/api/agents/[id]/mcp/route_client-reference-manifest.js +1 -1
  13. package/bundle/standalone/apps/web/.next/server/app/api/agents/[id]/route_client-reference-manifest.js +1 -1
  14. package/bundle/standalone/apps/web/.next/server/app/api/agents/route_client-reference-manifest.js +1 -1
  15. package/bundle/standalone/apps/web/.next/server/app/api/auth/login/route_client-reference-manifest.js +1 -1
  16. package/bundle/standalone/apps/web/.next/server/app/api/auth/logout/route_client-reference-manifest.js +1 -1
  17. package/bundle/standalone/apps/web/.next/server/app/api/auth/setup/route_client-reference-manifest.js +1 -1
  18. package/bundle/standalone/apps/web/.next/server/app/api/auth/status/route_client-reference-manifest.js +1 -1
  19. package/bundle/standalone/apps/web/.next/server/app/api/auth/token/route_client-reference-manifest.js +1 -1
  20. package/bundle/standalone/apps/web/.next/server/app/api/calendar/conflicts/route_client-reference-manifest.js +1 -1
  21. package/bundle/standalone/apps/web/.next/server/app/api/calendar/entities/[id]/route_client-reference-manifest.js +1 -1
  22. package/bundle/standalone/apps/web/.next/server/app/api/calendar/entities/route_client-reference-manifest.js +1 -1
  23. package/bundle/standalone/apps/web/.next/server/app/api/calendar/events/[id]/route_client-reference-manifest.js +1 -1
  24. package/bundle/standalone/apps/web/.next/server/app/api/calendar/events/route_client-reference-manifest.js +1 -1
  25. package/bundle/standalone/apps/web/.next/server/app/api/calendar/ics/route_client-reference-manifest.js +1 -1
  26. package/bundle/standalone/apps/web/.next/server/app/api/calendar/links/route_client-reference-manifest.js +1 -1
  27. package/bundle/standalone/apps/web/.next/server/app/api/calendar/settings/route_client-reference-manifest.js +1 -1
  28. package/bundle/standalone/apps/web/.next/server/app/api/clip/route_client-reference-manifest.js +1 -1
  29. package/bundle/standalone/apps/web/.next/server/app/api/docker-config/route_client-reference-manifest.js +1 -1
  30. package/bundle/standalone/apps/web/.next/server/app/api/export/zip/route_client-reference-manifest.js +1 -1
  31. package/bundle/standalone/apps/web/.next/server/app/api/files/[id]/backlinks/route_client-reference-manifest.js +1 -1
  32. package/bundle/standalone/apps/web/.next/server/app/api/files/[id]/download/route_client-reference-manifest.js +1 -1
  33. package/bundle/standalone/apps/web/.next/server/app/api/files/[id]/export-html/route_client-reference-manifest.js +1 -1
  34. package/bundle/standalone/apps/web/.next/server/app/api/files/[id]/export-pdf/route_client-reference-manifest.js +1 -1
  35. package/bundle/standalone/apps/web/.next/server/app/api/files/[id]/history/restore/route_client-reference-manifest.js +1 -1
  36. package/bundle/standalone/apps/web/.next/server/app/api/files/[id]/history/route_client-reference-manifest.js +1 -1
  37. package/bundle/standalone/apps/web/.next/server/app/api/files/[id]/move/route_client-reference-manifest.js +1 -1
  38. package/bundle/standalone/apps/web/.next/server/app/api/files/[id]/route_client-reference-manifest.js +1 -1
  39. package/bundle/standalone/apps/web/.next/server/app/api/files/route_client-reference-manifest.js +1 -1
  40. package/bundle/standalone/apps/web/.next/server/app/api/files/upload/route_client-reference-manifest.js +1 -1
  41. package/bundle/standalone/apps/web/.next/server/app/api/folders/route_client-reference-manifest.js +1 -1
  42. package/bundle/standalone/apps/web/.next/server/app/api/git/remote/route_client-reference-manifest.js +1 -1
  43. package/bundle/standalone/apps/web/.next/server/app/api/git/sync-all/route_client-reference-manifest.js +1 -1
  44. package/bundle/standalone/apps/web/.next/server/app/api/hands/test-pattern/route_client-reference-manifest.js +1 -1
  45. package/bundle/standalone/apps/web/.next/server/app/api/hands/validate/route_client-reference-manifest.js +1 -1
  46. package/bundle/standalone/apps/web/.next/server/app/api/health/route_client-reference-manifest.js +1 -1
  47. package/bundle/standalone/apps/web/.next/server/app/api/install-snippets/route_client-reference-manifest.js +1 -1
  48. package/bundle/standalone/apps/web/.next/server/app/api/mcp-tools/route.js +1 -1
  49. package/bundle/standalone/apps/web/.next/server/app/api/mcp-tools/route_client-reference-manifest.js +1 -1
  50. package/bundle/standalone/apps/web/.next/server/app/api/profile/route_client-reference-manifest.js +1 -1
  51. package/bundle/standalone/apps/web/.next/server/app/api/projects/[id]/hands-config/route_client-reference-manifest.js +1 -1
  52. package/bundle/standalone/apps/web/.next/server/app/api/projects/[id]/journal-config/route_client-reference-manifest.js +1 -1
  53. package/bundle/standalone/apps/web/.next/server/app/api/projects/[id]/journal-status/route_client-reference-manifest.js +1 -1
  54. package/bundle/standalone/apps/web/.next/server/app/api/projects/[id]/onboard/route_client-reference-manifest.js +1 -1
  55. package/bundle/standalone/apps/web/.next/server/app/api/projects/[id]/refresh/route_client-reference-manifest.js +1 -1
  56. package/bundle/standalone/apps/web/.next/server/app/api/projects/[id]/route_client-reference-manifest.js +1 -1
  57. package/bundle/standalone/apps/web/.next/server/app/api/projects/[id]/sync/route_client-reference-manifest.js +1 -1
  58. package/bundle/standalone/apps/web/.next/server/app/api/projects/onboard/route_client-reference-manifest.js +1 -1
  59. package/bundle/standalone/apps/web/.next/server/app/api/projects/route_client-reference-manifest.js +1 -1
  60. package/bundle/standalone/apps/web/.next/server/app/api/publish/html/route_client-reference-manifest.js +1 -1
  61. package/bundle/standalone/apps/web/.next/server/app/api/publish/route_client-reference-manifest.js +1 -1
  62. package/bundle/standalone/apps/web/.next/server/app/api/refresh/route_client-reference-manifest.js +1 -1
  63. package/bundle/standalone/apps/web/.next/server/app/api/reindex/route_client-reference-manifest.js +1 -1
  64. package/bundle/standalone/apps/web/.next/server/app/api/reports/resources/[name]/route_client-reference-manifest.js +1 -1
  65. package/bundle/standalone/apps/web/.next/server/app/api/search/route_client-reference-manifest.js +1 -1
  66. package/bundle/standalone/apps/web/.next/server/app/api/tags/route_client-reference-manifest.js +1 -1
  67. package/bundle/standalone/apps/web/.next/server/app/api/version-check/route_client-reference-manifest.js +1 -1
  68. package/bundle/standalone/apps/web/.next/server/app/api/welcome/route_client-reference-manifest.js +1 -1
  69. package/bundle/standalone/apps/web/.next/server/app/api/ws-config/route_client-reference-manifest.js +1 -1
  70. package/bundle/standalone/apps/web/.next/server/app/calendar/page_client-reference-manifest.js +1 -1
  71. package/bundle/standalone/apps/web/.next/server/app/login/page_client-reference-manifest.js +1 -1
  72. package/bundle/standalone/apps/web/.next/server/app/page.js +1 -1
  73. package/bundle/standalone/apps/web/.next/server/app/page_client-reference-manifest.js +1 -1
  74. package/bundle/standalone/apps/web/.next/server/app/preview/motifs/page_client-reference-manifest.js +1 -1
  75. package/bundle/standalone/apps/web/.next/server/app/preview/motifs.html +2 -2
  76. package/bundle/standalone/apps/web/.next/server/app/preview/motifs.rsc +4 -4
  77. package/bundle/standalone/apps/web/.next/server/app-paths-manifest.json +3 -3
  78. package/bundle/standalone/apps/web/.next/server/chunks/3668.js +2 -2
  79. package/bundle/standalone/apps/web/.next/server/pages/404.html +1 -1
  80. package/bundle/standalone/apps/web/.next/server/pages/500.html +1 -1
  81. package/bundle/standalone/apps/web/.next/server/server-reference-manifest.json +1 -1
  82. package/bundle/standalone/apps/web/.next/static/chunks/app/{layout-da10917c290d5da7.js → layout-b3fc3a7cf96952bd.js} +1 -1
  83. package/bundle/standalone/apps/web/.next/static/chunks/app/{page-86e385abedf10ccd.js → page-78f80e866f105a66.js} +1 -1
  84. package/bundle/standalone/apps/web/.next/static/css/{d6e83b3f51ebdda3.css → c9d10f1f97d629ff.css} +1 -1
  85. package/bundle/standalone/apps/web/package.json +5 -5
  86. package/bundle/standalone/apps/web/src/lib/mcp-tools.json +1 -1
  87. package/bundle/standalone/node_modules/kontexta-mcp/dist/index.js +29 -5
  88. package/bundle/standalone/node_modules/kontexta-mcp/dist/index.js.map +1 -1
  89. package/bundle/standalone/node_modules/kontexta-mcp/package.json +2 -2
  90. package/bundle/standalone/node_modules/kxta-core/dist/agent-rules/index.d.ts +8 -0
  91. package/bundle/standalone/node_modules/kxta-core/dist/agent-rules/index.d.ts.map +1 -1
  92. package/bundle/standalone/node_modules/kxta-core/dist/agent-rules/index.js +13 -0
  93. package/bundle/standalone/node_modules/kxta-core/dist/agent-rules/index.js.map +1 -1
  94. package/bundle/standalone/node_modules/kxta-core/dist/index.d.ts +1 -1
  95. package/bundle/standalone/node_modules/kxta-core/dist/index.d.ts.map +1 -1
  96. package/bundle/standalone/node_modules/kxta-core/dist/index.js +1 -1
  97. package/bundle/standalone/node_modules/kxta-core/dist/index.js.map +1 -1
  98. package/bundle/standalone/node_modules/kxta-core/package.json +2 -2
  99. package/bundle/standalone/node_modules/kxta-publish/package.json +3 -3
  100. package/bundle/standalone/package.json +2 -2
  101. package/dist/index.js +5 -0
  102. package/dist/skill-GG5D7ZPL.js +90 -0
  103. package/package.json +3 -2
  104. package/skills/kontexta/README.md +71 -0
  105. package/skills/kontexta/SKILL.md +51 -0
  106. package/skills/kontexta/scripts/kxta.py +474 -0
  107. package/skills/kontexta/tests/test_rules.py +88 -0
  108. /package/bundle/standalone/apps/web/.next/static/{0ZL7PJwYf_7ZTTXE_AM0S → LhhhyfIf5XBGWk0Wbz_mM}/_buildManifest.js +0 -0
  109. /package/bundle/standalone/apps/web/.next/static/{0ZL7PJwYf_7ZTTXE_AM0S → LhhhyfIf5XBGWk0Wbz_mM}/_ssgManifest.js +0 -0
@@ -0,0 +1,474 @@
1
+ #!/usr/bin/env python3
2
+ """Stdio MCP client for the Kontexta (kxta) server, via a persistent per-cwd daemon."""
3
+ import hashlib
4
+ import hmac
5
+ import json
6
+ import os
7
+ import re
8
+ import secrets
9
+ import shlex
10
+ import shutil
11
+ import socket
12
+ import subprocess
13
+ import sys
14
+ import threading
15
+ import time
16
+
17
+ IS_WINDOWS = os.name == "nt"
18
+ if IS_WINDOWS:
19
+ import msvcrt
20
+ else:
21
+ import fcntl
22
+
23
+ # KXTA_SERVER: a .js entrypoint (run with node) or a full command line; defaults to the published CLI.
24
+ SERVER = os.environ.get("KXTA_SERVER", "npx -y --package=kontexta@latest kontexta mcp")
25
+ IDLE_SECONDS = int(os.environ.get("KXTA_IDLE_SECONDS", "1800"))
26
+ RUN_DIR = os.path.join(os.environ.get("LOCALAPPDATA") or os.path.expanduser("~/.cache"), "kxta")
27
+
28
+
29
+ def server_argv():
30
+ path = os.path.abspath(os.path.expanduser(SERVER))
31
+ if path.endswith((".js", ".mjs")) and os.path.isfile(path):
32
+ return ["node", path]
33
+ if IS_WINDOWS:
34
+ # Non-POSIX split keeps backslashes in paths but leaves the quotes on, so strip them.
35
+ return [a[1:-1] if len(a) > 1 and a[0] == a[-1] == '"' else a for a in shlex.split(SERVER, posix=False)]
36
+ return shlex.split(SERVER)
37
+
38
+
39
+ def spawnable(argv):
40
+ # Windows can't exec npx.cmd-style shims directly; resolve via PATH/PATHEXT and route through cmd.
41
+ exe = shutil.which(argv[0]) or argv[0]
42
+ if IS_WINDOWS and exe.lower().endswith((".cmd", ".bat")):
43
+ return ["cmd.exe", "/c", exe, *argv[1:]]
44
+ return [exe, *argv[1:]]
45
+
46
+
47
+ def state_path(cwd):
48
+ key = os.path.normcase(os.path.abspath(cwd))
49
+ return os.path.join(RUN_DIR, hashlib.sha1(key.encode()).hexdigest()[:12] + ".json")
50
+
51
+
52
+ class FileLock:
53
+ def __init__(self, path):
54
+ self.f = open(path, "a+")
55
+
56
+ def __enter__(self):
57
+ if IS_WINDOWS:
58
+ while True:
59
+ try:
60
+ self.f.seek(0)
61
+ msvcrt.locking(self.f.fileno(), msvcrt.LK_LOCK, 1)
62
+ return self
63
+ except OSError:
64
+ time.sleep(0.1)
65
+ fcntl.flock(self.f, fcntl.LOCK_EX)
66
+ return self
67
+
68
+ def __exit__(self, *exc):
69
+ try:
70
+ if IS_WINDOWS:
71
+ self.f.seek(0)
72
+ msvcrt.locking(self.f.fileno(), msvcrt.LK_UNLCK, 1)
73
+ else:
74
+ fcntl.flock(self.f, fcntl.LOCK_UN)
75
+ finally:
76
+ self.f.close()
77
+
78
+
79
+ def write_line(stream, obj):
80
+ stream.write((json.dumps(obj) + "\n").encode("utf-8"))
81
+ stream.flush()
82
+
83
+
84
+ class McpClient:
85
+ def __init__(self, cwd):
86
+ env = dict(os.environ)
87
+ env.setdefault("KONTEXTA_AGENT", "claude-code")
88
+ argv = json.loads(env.pop("KXTA_SERVER_ARGV")) if "KXTA_SERVER_ARGV" in env else server_argv()
89
+ self.proc = subprocess.Popen(
90
+ spawnable(argv),
91
+ cwd=cwd,
92
+ env=env,
93
+ stdin=subprocess.PIPE,
94
+ stdout=subprocess.PIPE,
95
+ stderr=subprocess.DEVNULL,
96
+ creationflags=subprocess.CREATE_NO_WINDOW if IS_WINDOWS else 0,
97
+ )
98
+ self.next_id = 0
99
+ self.lock = threading.Lock()
100
+ self.init = self.request("initialize", {
101
+ "protocolVersion": "2024-11-05",
102
+ "capabilities": {},
103
+ "clientInfo": {"name": "kxta-skill", "version": "2.0"},
104
+ })
105
+ write_line(self.proc.stdin, {"jsonrpc": "2.0", "method": "notifications/initialized"})
106
+
107
+ def request(self, method, params):
108
+ with self.lock:
109
+ self.next_id += 1
110
+ rid = self.next_id
111
+ write_line(self.proc.stdin, {"jsonrpc": "2.0", "id": rid, "method": method, "params": params})
112
+ for line in self.proc.stdout:
113
+ try:
114
+ msg = json.loads(line.decode("utf-8"))
115
+ except (json.JSONDecodeError, UnicodeDecodeError):
116
+ continue
117
+ # Server-initiated requests (ping, roots/list) must be answered or the server stalls.
118
+ if "method" in msg and "id" in msg:
119
+ if msg["method"] == "ping":
120
+ write_line(self.proc.stdin, {"jsonrpc": "2.0", "id": msg["id"], "result": {}})
121
+ else:
122
+ write_line(self.proc.stdin, {"jsonrpc": "2.0", "id": msg["id"], "error": {"code": -32601, "message": "unsupported"}})
123
+ continue
124
+ if msg.get("id") != rid:
125
+ continue
126
+ if "error" in msg:
127
+ raise RuntimeError(f"MCP error {msg['error'].get('code')}: {msg['error'].get('message')}")
128
+ return msg["result"]
129
+ raise RuntimeError("kxta server exited without responding")
130
+
131
+ def alive(self):
132
+ return self.proc.poll() is None
133
+
134
+ def close(self):
135
+ try:
136
+ self.proc.stdin.close()
137
+ self.proc.wait(timeout=5)
138
+ except Exception:
139
+ self.proc.kill()
140
+
141
+
142
+ def dispatch(client, req):
143
+ op = req["op"]
144
+ if op == "context":
145
+ return {"text": client.init.get("instructions", "")}
146
+ if op == "tools":
147
+ return {"tools": client.request("tools/list", {})["tools"]}
148
+ if op == "call":
149
+ return {"result": client.request("tools/call", {"name": req["tool"], "arguments": req.get("args") or {}})}
150
+ raise RuntimeError(f"unknown op: {op}")
151
+
152
+
153
+ def serve(cwd):
154
+ path = state_path(cwd)
155
+ client = McpClient(cwd)
156
+ token = secrets.token_hex(16)
157
+ srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
158
+ srv.bind(("127.0.0.1", 0))
159
+ srv.listen(16)
160
+ srv.settimeout(0.5)
161
+ tmp = path + ".tmp"
162
+ with open(tmp, "w") as f:
163
+ json.dump({"port": srv.getsockname()[1], "token": token, "pid": os.getpid()}, f)
164
+ if not IS_WINDOWS:
165
+ os.chmod(tmp, 0o600)
166
+ os.replace(tmp, path)
167
+ last = [time.time()]
168
+ stop = threading.Event()
169
+
170
+ def handle(conn):
171
+ with conn, conn.makefile("rwb") as f:
172
+ for line in f:
173
+ last[0] = time.time()
174
+ try:
175
+ req = json.loads(line.decode("utf-8"))
176
+ if not hmac.compare_digest(str(req.get("token", "")), token):
177
+ resp = {"ok": False, "error": "bad token"}
178
+ elif req.get("op") == "stop":
179
+ stop.set()
180
+ resp = {"ok": True}
181
+ else:
182
+ resp = {"ok": True, **dispatch(client, req)}
183
+ except Exception as e:
184
+ resp = {"ok": False, "error": str(e)}
185
+ write_line(f, resp)
186
+ last[0] = time.time()
187
+
188
+ try:
189
+ while not stop.is_set() and client.alive() and time.time() - last[0] < IDLE_SECONDS:
190
+ try:
191
+ conn, _ = srv.accept()
192
+ except socket.timeout:
193
+ continue
194
+ conn.settimeout(None)
195
+ threading.Thread(target=handle, args=(conn,), daemon=True).start()
196
+ finally:
197
+ srv.close()
198
+ try:
199
+ os.remove(path)
200
+ except OSError:
201
+ pass
202
+ client.close()
203
+
204
+
205
+ def connect(cwd):
206
+ with open(state_path(cwd)) as f:
207
+ state = json.load(f)
208
+ s = socket.create_connection(("127.0.0.1", state["port"]), timeout=5)
209
+ s.settimeout(None)
210
+ return s, state["token"]
211
+
212
+
213
+ def spawn_daemon(cwd):
214
+ kwargs = {}
215
+ if IS_WINDOWS:
216
+ kwargs["creationflags"] = subprocess.DETACHED_PROCESS | subprocess.CREATE_NEW_PROCESS_GROUP | subprocess.CREATE_NO_WINDOW
217
+ else:
218
+ kwargs["start_new_session"] = True
219
+ return subprocess.Popen(
220
+ [sys.executable, os.path.abspath(__file__), "_serve", cwd],
221
+ env={**os.environ, "KXTA_SERVER_ARGV": json.dumps(server_argv())},
222
+ stdin=subprocess.DEVNULL,
223
+ stdout=subprocess.DEVNULL,
224
+ stderr=subprocess.DEVNULL,
225
+ **kwargs,
226
+ )
227
+
228
+
229
+ def ensure_daemon(cwd):
230
+ try:
231
+ return connect(cwd)
232
+ except (OSError, ValueError):
233
+ pass
234
+ os.makedirs(RUN_DIR, exist_ok=True)
235
+ # Serialize spawns so parallel callers don't start duplicate daemons.
236
+ with FileLock(state_path(cwd) + ".lock"):
237
+ try:
238
+ return connect(cwd)
239
+ except (OSError, ValueError):
240
+ try:
241
+ os.remove(state_path(cwd))
242
+ except OSError:
243
+ pass
244
+ daemon = spawn_daemon(cwd)
245
+ # First npx run may download the package.
246
+ deadline = time.time() + 120
247
+ while time.time() < deadline and daemon.poll() is None:
248
+ try:
249
+ return connect(cwd)
250
+ except (OSError, ValueError):
251
+ time.sleep(0.1)
252
+ raise RuntimeError(f"kxta server failed to start: {' '.join(server_argv())} (check Node 22+ or set KXTA_SERVER)")
253
+
254
+
255
+ class Session:
256
+ def __init__(self, cwd):
257
+ self.sock, self.token = ensure_daemon(cwd)
258
+ self.f = self.sock.makefile("rwb")
259
+
260
+ def ask(self, req):
261
+ write_line(self.f, {**req, "token": self.token})
262
+ line = self.f.readline()
263
+ if not line:
264
+ raise RuntimeError("kxta daemon closed the connection")
265
+ resp = json.loads(line.decode("utf-8"))
266
+ if not resp.get("ok"):
267
+ raise RuntimeError(resp.get("error"))
268
+ return resp
269
+
270
+
271
+ # Same fence the server's rules block uses, so the staleness check and nudges cover this block too.
272
+ RULES_BEGIN_RE = re.compile(r"<!--\s*BEGIN\s+kontexta:rules\s+v(\d+\.\d+\.\d+)\s*-->")
273
+ RULES_END_RE = re.compile(r"<!--\s*END\s+kontexta:rules(?:\s+v\d+\.\d+\.\d+)?\s*-->")
274
+ FLAVOR_TAG = "<!-- kontexta:flavor skill-bridge -->"
275
+ # Bridge-adapted copy of the core constraints in packages/core/src/agent-rules/rules-block.md; keep the two in step.
276
+ CORE_RULES = [
277
+ "**Session start:** call `admin_refresh_session_context` on turn 1 and print a 1-3 line greeting (date, profile, conflicts). Skip if the first message is a task.",
278
+ "**All KB writes go through kxta** (`files_create` / `files_update` / `journal_write`). Never edit KB files with raw filesystem tools, and never write context artifacts (diagrams, specs, notes, `.mmd`) into the project repo: use `files_create` with `destination: \"knowledge\"`.",
279
+ "**Search before reading:** `files_search` (no bodies first) or `files_regex_search`, then `files_read` the top hit. Batch reads with `files_read` `ids`; don't loop single reads.",
280
+ "**Act on `journal.suggested_action`** in tool responses before the next call, or pass `journal_acknowledge: true` to dismiss.",
281
+ "**Tag new KB files** at creation (`tags` on `files_create`, or `tags_add`). Diagrams are `.mmd` via `files_create` with `format: \"mmd\"`.",
282
+ "**Confirm Hands tokens within 60 seconds** with `hands_confirm`; don't run `stop` in between.",
283
+ "**Log decisions** with `journal_write` `kind: \"note\"` and **topic pivots** with `kind: \"intent\"`.",
284
+ "**Destructive or side-effectful tools** (`files_delete`, `folders_delete`, `files_restore`, `admin_commit_backup`, `hands_confirm`, ...) need the user's confirmation first.",
285
+ ]
286
+
287
+
288
+ def short_desc(desc, limit=140):
289
+ text = " ".join((desc or "").split())
290
+ m = re.search(r"[.!?](?:\s|$)", text)
291
+ if m and m.end() <= limit:
292
+ return text[:m.end()].strip()
293
+ if len(text) <= limit:
294
+ return text
295
+ return text[:limit].rsplit(" ", 1)[0].rstrip(",;:(") + "..."
296
+
297
+
298
+ def bridge_command(cwd=None):
299
+ script = os.path.abspath(__file__)
300
+ home = os.path.expanduser("~")
301
+ root = os.path.abspath(cwd) if cwd else None
302
+ # Project installs (.claude/skills under the project) stay relative so the committed block works for teammates.
303
+ if root and script.startswith(root + os.sep):
304
+ script = os.path.relpath(script, root).replace(os.sep, "/")
305
+ elif script.startswith(home + os.sep):
306
+ script = "~" + script[len(home):].replace(os.sep, "/")
307
+ return f"{'python' if IS_WINDOWS else 'python3'} {script}"
308
+
309
+
310
+ def render_rules_block(version, tools, cmd):
311
+ lines = [
312
+ f"<!-- BEGIN kontexta:rules v{version} -->",
313
+ FLAVOR_TAG,
314
+ # The server quotes this in rules-version nudges, so it matches this install's path and python.
315
+ f"<!-- kontexta:refresh {cmd} rules --write -->",
316
+ "## kxta tools (via skill bridge)",
317
+ "",
318
+ "To call any tool below, run:",
319
+ f"`{cmd} call <tool> '<json-args>'`",
320
+ "",
321
+ f"Inspect inputs with `{cmd} schema <tool>`.",
322
+ "",
323
+ "Core rules:",
324
+ ]
325
+ lines += [f"- {r}" for r in CORE_RULES]
326
+ lines += [
327
+ "",
328
+ "Full workflow rules and the tool routing matrix: [KONTEXTA.md](./KONTEXTA.md) when present; read it before KB-heavy work.",
329
+ "",
330
+ "Tools:",
331
+ ]
332
+ lines += [f"- `{t['name']}` · {short_desc(t.get('description'), 120)}" for t in tools]
333
+ lines += ["", f"<!-- END kontexta:rules v{version} -->"]
334
+ return "\n".join(lines) + "\n"
335
+
336
+
337
+ def apply_rules_block(content, block):
338
+ """Insert or replace the fenced block. Returns (action, new_content); action is created, updated or unchanged."""
339
+ begins = list(RULES_BEGIN_RE.finditer(content))
340
+ if not begins:
341
+ sep = "" if not content or content.endswith("\n\n") else "\n" if content.endswith("\n") else "\n\n"
342
+ return "created", content + sep + block
343
+ if len(begins) > 1:
344
+ raise RuntimeError("duplicate kontexta rules marker found; fix the file by hand")
345
+ begin = begins[0]
346
+ end = RULES_END_RE.search(content, begin.end())
347
+ if not end:
348
+ raise RuntimeError("kontexta rules marker is malformed (BEGIN with no matching END)")
349
+ if content[begin.start():end.end()] == block.rstrip("\n"):
350
+ return "unchanged", content
351
+ return "updated", content[:begin.start()] + block.rstrip("\n") + content[end.end():]
352
+
353
+
354
+ def rules_version(sess):
355
+ projects = json.loads(result_text(sess.ask({"op": "call", "tool": "projects_list", "args": {}})["result"]))
356
+ for p in projects:
357
+ v = (p.get("agent_rules") or {}).get("latest_version")
358
+ if v:
359
+ return v
360
+ raise RuntimeError("could not read the rules version from the server (projects_list returned no projects)")
361
+
362
+
363
+ def write_rules(path, block):
364
+ if os.path.islink(path):
365
+ raise RuntimeError(f"refusing to write through symlink: {path}")
366
+ content = ""
367
+ if os.path.exists(path):
368
+ with open(path, encoding="utf-8", newline="") as f:
369
+ content = f.read()
370
+ action, new = apply_rules_block(content, block)
371
+ if action != "unchanged":
372
+ tmp = f"{path}.tmp.{os.getpid()}"
373
+ with open(tmp, "w", encoding="utf-8", newline="") as f:
374
+ f.write(new)
375
+ os.replace(tmp, path)
376
+ return action
377
+
378
+
379
+ def result_text(result):
380
+ out = []
381
+ for item in result.get("content", []):
382
+ out.append(item["text"] if item.get("type") == "text" else json.dumps(item))
383
+ return "\n".join(out)
384
+
385
+
386
+ def main():
387
+ # Windows consoles default to a legacy code page; kxta output contains emoji and non-ASCII text.
388
+ for stream in (sys.stdin, sys.stdout, sys.stderr):
389
+ if hasattr(stream, "reconfigure"):
390
+ stream.reconfigure(encoding="utf-8", errors="replace")
391
+ args = sys.argv[1:]
392
+ if args and args[0] == "_serve":
393
+ serve(args[1])
394
+ return
395
+ if not args or args[0] in ("-h", "--help"):
396
+ print("usage: kxta.py context | list | rules [--write [file]] | schema <tool> | call <tool> [json-args | -] | batch | stop")
397
+ return
398
+ cwd = os.environ.get("KXTA_CWD", os.getcwd())
399
+ cmd = args[0]
400
+ if cmd == "stop":
401
+ try:
402
+ sock, token = connect(cwd)
403
+ except (OSError, ValueError):
404
+ print("no daemon running")
405
+ return
406
+ with sock, sock.makefile("rwb") as f:
407
+ write_line(f, {"op": "stop", "token": token})
408
+ f.readline()
409
+ deadline = time.time() + 10
410
+ while os.path.exists(state_path(cwd)) and time.time() < deadline:
411
+ time.sleep(0.1)
412
+ print("stopped")
413
+ return
414
+ try:
415
+ sess = Session(cwd)
416
+ if cmd == "context":
417
+ print(sess.ask({"op": "context"})["text"])
418
+ elif cmd == "list":
419
+ for t in sess.ask({"op": "tools"})["tools"]:
420
+ desc = " ".join((t.get("description") or "").split())
421
+ print(f"{t['name']}: {desc[:140]}")
422
+ elif cmd == "rules":
423
+ # Versioned, minimal CLAUDE.md block (bridge prefix + tool list); lighter than admin_onboard_agent's.
424
+ opts = args[1:]
425
+ write = "--write" in opts
426
+ rest = [a for a in opts if a != "--write"]
427
+ if any(a.startswith("-") for a in rest) or len(rest) > 1 or (rest and not write):
428
+ sys.exit("usage: kxta.py rules [--write [file]] (default file: CLAUDE.md in the current directory)")
429
+ block = render_rules_block(rules_version(sess), sess.ask({"op": "tools"})["tools"], bridge_command(cwd))
430
+ if not write:
431
+ sys.stdout.write(block)
432
+ else:
433
+ path = os.path.join(cwd, rest[0] if rest else "CLAUDE.md")
434
+ print(f"{os.path.relpath(path, cwd)}: {write_rules(path, block)}")
435
+ elif cmd == "schema":
436
+ tools = {t["name"]: t for t in sess.ask({"op": "tools"})["tools"]}
437
+ tool = tools.get(args[1]) if len(args) > 1 else None
438
+ if not tool:
439
+ sys.exit(f"unknown tool: {args[1] if len(args) > 1 else ''}")
440
+ print(json.dumps(tool, indent=2))
441
+ elif cmd == "call":
442
+ if len(args) < 2:
443
+ sys.exit("call needs a tool name")
444
+ raw = args[2] if len(args) > 2 else "{}"
445
+ if raw == "-":
446
+ raw = sys.stdin.read()
447
+ result = sess.ask({"op": "call", "tool": args[1], "args": json.loads(raw)})["result"]
448
+ print(result_text(result))
449
+ if result.get("isError"):
450
+ sys.exit(1)
451
+ elif cmd == "batch":
452
+ # stdin: one {"tool": ..., "args": {...}} per line; stdout: one {"tool", "isError", "text"} per line
453
+ failed = False
454
+ for line in sys.stdin:
455
+ if not line.strip():
456
+ continue
457
+ item = json.loads(line)
458
+ try:
459
+ result = sess.ask({"op": "call", "tool": item["tool"], "args": item.get("args")})["result"]
460
+ out = {"tool": item["tool"], "isError": bool(result.get("isError")), "text": result_text(result)}
461
+ except RuntimeError as e:
462
+ out = {"tool": item["tool"], "isError": True, "text": str(e)}
463
+ failed = failed or out["isError"]
464
+ print(json.dumps(out), flush=True)
465
+ if failed:
466
+ sys.exit(1)
467
+ else:
468
+ sys.exit(f"unknown command: {cmd}")
469
+ except RuntimeError as e:
470
+ sys.exit(str(e))
471
+
472
+
473
+ if __name__ == "__main__":
474
+ main()
@@ -0,0 +1,88 @@
1
+ import importlib.util
2
+ import os
3
+ import tempfile
4
+ import unittest
5
+
6
+ HERE = os.path.dirname(os.path.abspath(__file__))
7
+ spec = importlib.util.spec_from_file_location("kxta", os.path.join(HERE, "..", "scripts", "kxta.py"))
8
+ kxta = importlib.util.module_from_spec(spec)
9
+ spec.loader.exec_module(kxta)
10
+
11
+ TOOLS = [
12
+ {"name": "files_search", "description": "Full-text keyword search. Returns ranked matches with excerpts."},
13
+ {"name": "journal_write", "description": "Write one event to the journal."},
14
+ ]
15
+
16
+
17
+ def block(version="3.2.0", tools=TOOLS):
18
+ return kxta.render_rules_block(version, tools, "python3 ~/.claude/skills/kontexta/scripts/kxta.py")
19
+
20
+
21
+ class RulesBlock(unittest.TestCase):
22
+ def test_block_uses_server_marker_so_staleness_check_sees_it(self):
23
+ b = block("3.2.0")
24
+ self.assertTrue(kxta.RULES_BEGIN_RE.search(b))
25
+ self.assertEqual(kxta.RULES_BEGIN_RE.search(b).group(1), "3.2.0")
26
+ self.assertTrue(kxta.RULES_END_RE.search(b))
27
+ self.assertIn(kxta.FLAVOR_TAG, b)
28
+
29
+ def test_block_records_refresh_command_and_core_rules(self):
30
+ b = kxta.render_rules_block("3.2.0", TOOLS, "python .claude/skills/kontexta/scripts/kxta.py")
31
+ self.assertIn("<!-- kontexta:refresh python .claude/skills/kontexta/scripts/kxta.py rules --write -->", b)
32
+ self.assertIn("admin_refresh_session_context", b)
33
+ self.assertIn("KONTEXTA.md", b)
34
+
35
+ def test_short_desc_cuts_at_sentence_not_mid_word(self):
36
+ self.assertEqual(kxta.short_desc("Full-text search. More detail here."), "Full-text search.")
37
+ long = "word " * 80
38
+ out = kxta.short_desc(long, 40)
39
+ self.assertTrue(out.endswith("..."))
40
+ self.assertLessEqual(len(out), 43)
41
+
42
+ def test_append_then_rerun_is_idempotent(self):
43
+ action, once = kxta.apply_rules_block("# Project\n", block())
44
+ self.assertEqual(action, "created")
45
+ action, twice = kxta.apply_rules_block(once, block())
46
+ self.assertEqual(action, "unchanged")
47
+ self.assertEqual(once, twice)
48
+ self.assertEqual(once.count("BEGIN kontexta:rules"), 1)
49
+
50
+ def test_version_bump_replaces_in_place_and_keeps_surrounding_content(self):
51
+ _, old = kxta.apply_rules_block("# Project\n", block("3.2.0"))
52
+ content = old + "\n## Mine\nkeep me\n"
53
+ action, new = kxta.apply_rules_block(content, block("3.3.0"))
54
+ self.assertEqual(action, "updated")
55
+ self.assertIn("BEGIN kontexta:rules v3.3.0", new)
56
+ self.assertNotIn("v3.2.0", new)
57
+ self.assertIn("# Project", new)
58
+ self.assertIn("keep me", new)
59
+
60
+ def test_tool_list_change_at_same_version_still_updates(self):
61
+ _, old = kxta.apply_rules_block("", block("3.2.0", TOOLS[:1]))
62
+ action, _ = kxta.apply_rules_block(old, block("3.2.0", TOOLS))
63
+ self.assertEqual(action, "updated")
64
+
65
+ def test_duplicate_and_malformed_markers_are_refused(self):
66
+ with self.assertRaises(RuntimeError):
67
+ kxta.apply_rules_block(block() + "\n" + block(), block())
68
+ with self.assertRaises(RuntimeError):
69
+ kxta.apply_rules_block("<!-- BEGIN kontexta:rules v3.2.0 -->\nno end", block())
70
+
71
+ def test_write_rules_refuses_symlink_and_writes_utf8(self):
72
+ with tempfile.TemporaryDirectory() as d:
73
+ target = os.path.join(d, "real.md")
74
+ open(target, "w").close()
75
+ link = os.path.join(d, "CLAUDE.md")
76
+ try:
77
+ os.symlink(target, link)
78
+ except (OSError, NotImplementedError):
79
+ self.skipTest("symlinks unavailable")
80
+ with self.assertRaises(RuntimeError):
81
+ kxta.write_rules(link, block())
82
+ plain = os.path.join(d, "AGENTS.md")
83
+ self.assertEqual(kxta.write_rules(plain, block()), "created")
84
+ self.assertEqual(kxta.write_rules(plain, block()), "unchanged")
85
+
86
+
87
+ if __name__ == "__main__":
88
+ unittest.main()