kontexta 4.7.1 → 5.0.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 (176) hide show
  1. package/bundle/standalone/CHANGELOG.md +29 -0
  2. package/bundle/standalone/apps/web/.next/BUILD_ID +1 -1
  3. package/bundle/standalone/apps/web/.next/app-build-manifest.json +54 -54
  4. package/bundle/standalone/apps/web/.next/app-path-routes-manifest.json +13 -13
  5. package/bundle/standalone/apps/web/.next/build-manifest.json +2 -2
  6. package/bundle/standalone/apps/web/.next/prerender-manifest.json +13 -13
  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 +1 -1
  10. package/bundle/standalone/apps/web/.next/server/app/api/about/route.js.nft.json +1 -1
  11. package/bundle/standalone/apps/web/.next/server/app/api/about/route_client-reference-manifest.js +1 -1
  12. package/bundle/standalone/apps/web/.next/server/app/api/auth/login/route.js.nft.json +1 -1
  13. package/bundle/standalone/apps/web/.next/server/app/api/auth/login/route_client-reference-manifest.js +1 -1
  14. package/bundle/standalone/apps/web/.next/server/app/api/auth/logout/route_client-reference-manifest.js +1 -1
  15. package/bundle/standalone/apps/web/.next/server/app/api/auth/setup/route.js.nft.json +1 -1
  16. package/bundle/standalone/apps/web/.next/server/app/api/auth/setup/route_client-reference-manifest.js +1 -1
  17. package/bundle/standalone/apps/web/.next/server/app/api/auth/status/route.js.nft.json +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.js.nft.json +1 -1
  20. package/bundle/standalone/apps/web/.next/server/app/api/auth/token/route_client-reference-manifest.js +1 -1
  21. package/bundle/standalone/apps/web/.next/server/app/api/calendar/conflicts/route.js.nft.json +1 -1
  22. package/bundle/standalone/apps/web/.next/server/app/api/calendar/conflicts/route_client-reference-manifest.js +1 -1
  23. package/bundle/standalone/apps/web/.next/server/app/api/calendar/entities/[id]/route.js.nft.json +1 -1
  24. package/bundle/standalone/apps/web/.next/server/app/api/calendar/entities/[id]/route_client-reference-manifest.js +1 -1
  25. package/bundle/standalone/apps/web/.next/server/app/api/calendar/entities/route.js.nft.json +1 -1
  26. package/bundle/standalone/apps/web/.next/server/app/api/calendar/entities/route_client-reference-manifest.js +1 -1
  27. package/bundle/standalone/apps/web/.next/server/app/api/calendar/events/[id]/route.js.nft.json +1 -1
  28. package/bundle/standalone/apps/web/.next/server/app/api/calendar/events/[id]/route_client-reference-manifest.js +1 -1
  29. package/bundle/standalone/apps/web/.next/server/app/api/calendar/events/route.js.nft.json +1 -1
  30. package/bundle/standalone/apps/web/.next/server/app/api/calendar/events/route_client-reference-manifest.js +1 -1
  31. package/bundle/standalone/apps/web/.next/server/app/api/calendar/ics/route.js.nft.json +1 -1
  32. package/bundle/standalone/apps/web/.next/server/app/api/calendar/ics/route_client-reference-manifest.js +1 -1
  33. package/bundle/standalone/apps/web/.next/server/app/api/calendar/links/route.js.nft.json +1 -1
  34. package/bundle/standalone/apps/web/.next/server/app/api/calendar/links/route_client-reference-manifest.js +1 -1
  35. package/bundle/standalone/apps/web/.next/server/app/api/calendar/settings/route.js.nft.json +1 -1
  36. package/bundle/standalone/apps/web/.next/server/app/api/calendar/settings/route_client-reference-manifest.js +1 -1
  37. package/bundle/standalone/apps/web/.next/server/app/api/clip/route.js.nft.json +1 -1
  38. package/bundle/standalone/apps/web/.next/server/app/api/clip/route_client-reference-manifest.js +1 -1
  39. package/bundle/standalone/apps/web/.next/server/app/api/docker-config/route.js.nft.json +1 -1
  40. package/bundle/standalone/apps/web/.next/server/app/api/docker-config/route_client-reference-manifest.js +1 -1
  41. package/bundle/standalone/apps/web/.next/server/app/api/export/zip/route.js.nft.json +1 -1
  42. package/bundle/standalone/apps/web/.next/server/app/api/export/zip/route_client-reference-manifest.js +1 -1
  43. package/bundle/standalone/apps/web/.next/server/app/api/files/[id]/backlinks/route.js.nft.json +1 -1
  44. package/bundle/standalone/apps/web/.next/server/app/api/files/[id]/backlinks/route_client-reference-manifest.js +1 -1
  45. package/bundle/standalone/apps/web/.next/server/app/api/files/[id]/download/route.js.nft.json +1 -1
  46. package/bundle/standalone/apps/web/.next/server/app/api/files/[id]/download/route_client-reference-manifest.js +1 -1
  47. package/bundle/standalone/apps/web/.next/server/app/api/files/[id]/export-html/route.js.nft.json +1 -1
  48. package/bundle/standalone/apps/web/.next/server/app/api/files/[id]/export-html/route_client-reference-manifest.js +1 -1
  49. package/bundle/standalone/apps/web/.next/server/app/api/files/[id]/export-pdf/route.js.nft.json +1 -1
  50. package/bundle/standalone/apps/web/.next/server/app/api/files/[id]/export-pdf/route_client-reference-manifest.js +1 -1
  51. package/bundle/standalone/apps/web/.next/server/app/api/files/[id]/history/restore/route.js.nft.json +1 -1
  52. package/bundle/standalone/apps/web/.next/server/app/api/files/[id]/history/restore/route_client-reference-manifest.js +1 -1
  53. package/bundle/standalone/apps/web/.next/server/app/api/files/[id]/history/route.js.nft.json +1 -1
  54. package/bundle/standalone/apps/web/.next/server/app/api/files/[id]/history/route_client-reference-manifest.js +1 -1
  55. package/bundle/standalone/apps/web/.next/server/app/api/files/[id]/move/route.js.nft.json +1 -1
  56. package/bundle/standalone/apps/web/.next/server/app/api/files/[id]/move/route_client-reference-manifest.js +1 -1
  57. package/bundle/standalone/apps/web/.next/server/app/api/files/[id]/route.js.nft.json +1 -1
  58. package/bundle/standalone/apps/web/.next/server/app/api/files/[id]/route_client-reference-manifest.js +1 -1
  59. package/bundle/standalone/apps/web/.next/server/app/api/files/route.js.nft.json +1 -1
  60. package/bundle/standalone/apps/web/.next/server/app/api/files/route_client-reference-manifest.js +1 -1
  61. package/bundle/standalone/apps/web/.next/server/app/api/files/upload/route.js.nft.json +1 -1
  62. package/bundle/standalone/apps/web/.next/server/app/api/files/upload/route_client-reference-manifest.js +1 -1
  63. package/bundle/standalone/apps/web/.next/server/app/api/folders/route.js.nft.json +1 -1
  64. package/bundle/standalone/apps/web/.next/server/app/api/folders/route_client-reference-manifest.js +1 -1
  65. package/bundle/standalone/apps/web/.next/server/app/api/git/remote/route.js.nft.json +1 -1
  66. package/bundle/standalone/apps/web/.next/server/app/api/git/remote/route_client-reference-manifest.js +1 -1
  67. package/bundle/standalone/apps/web/.next/server/app/api/git/sync-all/route.js.nft.json +1 -1
  68. package/bundle/standalone/apps/web/.next/server/app/api/git/sync-all/route_client-reference-manifest.js +1 -1
  69. package/bundle/standalone/apps/web/.next/server/app/api/hands/test-pattern/route.js.nft.json +1 -1
  70. package/bundle/standalone/apps/web/.next/server/app/api/hands/test-pattern/route_client-reference-manifest.js +1 -1
  71. package/bundle/standalone/apps/web/.next/server/app/api/hands/validate/route.js.nft.json +1 -1
  72. package/bundle/standalone/apps/web/.next/server/app/api/hands/validate/route_client-reference-manifest.js +1 -1
  73. package/bundle/standalone/apps/web/.next/server/app/api/health/route.js.nft.json +1 -1
  74. package/bundle/standalone/apps/web/.next/server/app/api/health/route_client-reference-manifest.js +1 -1
  75. package/bundle/standalone/apps/web/.next/server/app/api/install-snippets/route.js.nft.json +1 -1
  76. package/bundle/standalone/apps/web/.next/server/app/api/install-snippets/route_client-reference-manifest.js +1 -1
  77. package/bundle/standalone/apps/web/.next/server/app/api/mcp-tools/route.js +1 -1
  78. package/bundle/standalone/apps/web/.next/server/app/api/mcp-tools/route.js.nft.json +1 -1
  79. package/bundle/standalone/apps/web/.next/server/app/api/mcp-tools/route_client-reference-manifest.js +1 -1
  80. package/bundle/standalone/apps/web/.next/server/app/api/profile/route.js.nft.json +1 -1
  81. package/bundle/standalone/apps/web/.next/server/app/api/profile/route_client-reference-manifest.js +1 -1
  82. package/bundle/standalone/apps/web/.next/server/app/api/projects/[id]/hands-config/route.js.nft.json +1 -1
  83. package/bundle/standalone/apps/web/.next/server/app/api/projects/[id]/hands-config/route_client-reference-manifest.js +1 -1
  84. package/bundle/standalone/apps/web/.next/server/app/api/projects/[id]/journal-config/route.js.nft.json +1 -1
  85. package/bundle/standalone/apps/web/.next/server/app/api/projects/[id]/journal-config/route_client-reference-manifest.js +1 -1
  86. package/bundle/standalone/apps/web/.next/server/app/api/projects/[id]/journal-status/route.js.nft.json +1 -1
  87. package/bundle/standalone/apps/web/.next/server/app/api/projects/[id]/journal-status/route_client-reference-manifest.js +1 -1
  88. package/bundle/standalone/apps/web/.next/server/app/api/projects/[id]/onboard/route.js.nft.json +1 -1
  89. package/bundle/standalone/apps/web/.next/server/app/api/projects/[id]/onboard/route_client-reference-manifest.js +1 -1
  90. package/bundle/standalone/apps/web/.next/server/app/api/projects/[id]/refresh/route.js.nft.json +1 -1
  91. package/bundle/standalone/apps/web/.next/server/app/api/projects/[id]/refresh/route_client-reference-manifest.js +1 -1
  92. package/bundle/standalone/apps/web/.next/server/app/api/projects/[id]/route.js.nft.json +1 -1
  93. package/bundle/standalone/apps/web/.next/server/app/api/projects/[id]/route_client-reference-manifest.js +1 -1
  94. package/bundle/standalone/apps/web/.next/server/app/api/projects/[id]/sync/route.js.nft.json +1 -1
  95. package/bundle/standalone/apps/web/.next/server/app/api/projects/[id]/sync/route_client-reference-manifest.js +1 -1
  96. package/bundle/standalone/apps/web/.next/server/app/api/projects/onboard/route.js.nft.json +1 -1
  97. package/bundle/standalone/apps/web/.next/server/app/api/projects/onboard/route_client-reference-manifest.js +1 -1
  98. package/bundle/standalone/apps/web/.next/server/app/api/projects/route.js +1 -1
  99. package/bundle/standalone/apps/web/.next/server/app/api/projects/route.js.nft.json +1 -1
  100. package/bundle/standalone/apps/web/.next/server/app/api/projects/route_client-reference-manifest.js +1 -1
  101. package/bundle/standalone/apps/web/.next/server/app/api/publish/html/route.js.nft.json +1 -1
  102. package/bundle/standalone/apps/web/.next/server/app/api/publish/html/route_client-reference-manifest.js +1 -1
  103. package/bundle/standalone/apps/web/.next/server/app/api/publish/route.js.nft.json +1 -1
  104. package/bundle/standalone/apps/web/.next/server/app/api/publish/route_client-reference-manifest.js +1 -1
  105. package/bundle/standalone/apps/web/.next/server/app/api/refresh/route.js.nft.json +1 -1
  106. package/bundle/standalone/apps/web/.next/server/app/api/refresh/route_client-reference-manifest.js +1 -1
  107. package/bundle/standalone/apps/web/.next/server/app/api/reindex/route.js.nft.json +1 -1
  108. package/bundle/standalone/apps/web/.next/server/app/api/reindex/route_client-reference-manifest.js +1 -1
  109. package/bundle/standalone/apps/web/.next/server/app/api/reports/resources/[name]/route.js.nft.json +1 -1
  110. package/bundle/standalone/apps/web/.next/server/app/api/reports/resources/[name]/route_client-reference-manifest.js +1 -1
  111. package/bundle/standalone/apps/web/.next/server/app/api/search/route.js.nft.json +1 -1
  112. package/bundle/standalone/apps/web/.next/server/app/api/search/route_client-reference-manifest.js +1 -1
  113. package/bundle/standalone/apps/web/.next/server/app/api/tags/route.js.nft.json +1 -1
  114. package/bundle/standalone/apps/web/.next/server/app/api/tags/route_client-reference-manifest.js +1 -1
  115. package/bundle/standalone/apps/web/.next/server/app/api/version-check/route_client-reference-manifest.js +1 -1
  116. package/bundle/standalone/apps/web/.next/server/app/api/welcome/route.js.nft.json +1 -1
  117. package/bundle/standalone/apps/web/.next/server/app/api/welcome/route_client-reference-manifest.js +1 -1
  118. package/bundle/standalone/apps/web/.next/server/app/api/ws-config/route_client-reference-manifest.js +1 -1
  119. package/bundle/standalone/apps/web/.next/server/app/calendar/page.js.nft.json +1 -1
  120. package/bundle/standalone/apps/web/.next/server/app/calendar/page_client-reference-manifest.js +1 -1
  121. package/bundle/standalone/apps/web/.next/server/app/login/page.js.nft.json +1 -1
  122. package/bundle/standalone/apps/web/.next/server/app/login/page_client-reference-manifest.js +1 -1
  123. package/bundle/standalone/apps/web/.next/server/app/page.js +2 -2
  124. package/bundle/standalone/apps/web/.next/server/app/page.js.nft.json +1 -1
  125. package/bundle/standalone/apps/web/.next/server/app/page_client-reference-manifest.js +1 -1
  126. package/bundle/standalone/apps/web/.next/server/app/preview/motifs/page_client-reference-manifest.js +1 -1
  127. package/bundle/standalone/apps/web/.next/server/app/preview/motifs.html +2 -2
  128. package/bundle/standalone/apps/web/.next/server/app/preview/motifs.rsc +1 -1
  129. package/bundle/standalone/apps/web/.next/server/app-paths-manifest.json +13 -13
  130. package/bundle/standalone/apps/web/.next/server/pages/404.html +1 -1
  131. package/bundle/standalone/apps/web/.next/server/pages/500.html +1 -1
  132. package/bundle/standalone/apps/web/.next/server/server-reference-manifest.json +1 -1
  133. package/bundle/standalone/apps/web/.next/static/chunks/app/page-98057182511ba7e4.js +1 -0
  134. package/bundle/standalone/apps/web/package.json +5 -5
  135. package/bundle/standalone/apps/web/src/lib/mcp-tools.json +233 -542
  136. package/bundle/standalone/node_modules/kontexta-mcp/dist/agent-rules/rules-block.md +22 -35
  137. package/bundle/standalone/node_modules/kontexta-mcp/dist/calendar-tools.js +1 -1
  138. package/bundle/standalone/node_modules/kontexta-mcp/dist/hands/formatter.js +1 -1
  139. package/bundle/standalone/node_modules/kontexta-mcp/dist/hands/formatter.js.map +1 -1
  140. package/bundle/standalone/node_modules/kontexta-mcp/dist/hands/schema-doc.js +1 -1
  141. package/bundle/standalone/node_modules/kontexta-mcp/dist/index.js +448 -471
  142. package/bundle/standalone/node_modules/kontexta-mcp/dist/index.js.map +1 -1
  143. package/bundle/standalone/node_modules/kontexta-mcp/dist/journal-capture.js +1 -1
  144. package/bundle/standalone/node_modules/kontexta-mcp/dist/journal-tools.d.ts.map +1 -1
  145. package/bundle/standalone/node_modules/kontexta-mcp/dist/journal-tools.js +1 -27
  146. package/bundle/standalone/node_modules/kontexta-mcp/dist/journal-tools.js.map +1 -1
  147. package/bundle/standalone/node_modules/kontexta-mcp/package.json +2 -2
  148. package/bundle/standalone/node_modules/kxta-core/dist/agent-rules/index.js +1 -1
  149. package/bundle/standalone/node_modules/kxta-core/dist/agent-rules/index.js.map +1 -1
  150. package/bundle/standalone/node_modules/kxta-core/dist/agent-rules/rules-block.md +22 -35
  151. package/bundle/standalone/node_modules/kxta-core/dist/db/index.d.ts.map +1 -1
  152. package/bundle/standalone/node_modules/kxta-core/dist/db/index.js +16 -4
  153. package/bundle/standalone/node_modules/kxta-core/dist/db/index.js.map +1 -1
  154. package/bundle/standalone/node_modules/kxta-core/dist/journal/patterns/exploration.d.ts.map +1 -1
  155. package/bundle/standalone/node_modules/kxta-core/dist/journal/patterns/exploration.js +3 -14
  156. package/bundle/standalone/node_modules/kxta-core/dist/journal/patterns/exploration.js.map +1 -1
  157. package/bundle/standalone/node_modules/kxta-core/dist/journal/patterns/read-only-investigation.d.ts.map +1 -1
  158. package/bundle/standalone/node_modules/kxta-core/dist/journal/patterns/read-only-investigation.js +2 -13
  159. package/bundle/standalone/node_modules/kxta-core/dist/journal/patterns/read-only-investigation.js.map +1 -1
  160. package/bundle/standalone/node_modules/kxta-core/dist/journal/patterns/tool-classes.d.ts +3 -0
  161. package/bundle/standalone/node_modules/kxta-core/dist/journal/patterns/tool-classes.d.ts.map +1 -0
  162. package/bundle/standalone/node_modules/kxta-core/dist/journal/patterns/tool-classes.js +64 -0
  163. package/bundle/standalone/node_modules/kxta-core/dist/journal/patterns/tool-classes.js.map +1 -0
  164. package/bundle/standalone/node_modules/kxta-core/dist/journal/strict-mode.d.ts.map +1 -1
  165. package/bundle/standalone/node_modules/kxta-core/dist/journal/strict-mode.js +2 -17
  166. package/bundle/standalone/node_modules/kxta-core/dist/journal/strict-mode.js.map +1 -1
  167. package/bundle/standalone/node_modules/kxta-core/dist/util/paths.d.ts.map +1 -1
  168. package/bundle/standalone/node_modules/kxta-core/dist/util/paths.js +16 -0
  169. package/bundle/standalone/node_modules/kxta-core/dist/util/paths.js.map +1 -1
  170. package/bundle/standalone/node_modules/kxta-core/package.json +2 -2
  171. package/bundle/standalone/node_modules/kxta-publish/package.json +3 -3
  172. package/bundle/standalone/package.json +2 -2
  173. package/package.json +2 -2
  174. package/bundle/standalone/apps/web/.next/static/chunks/app/page-eccc7438c998fcce.js +0 -1
  175. /package/bundle/standalone/apps/web/.next/static/{DWDlM7S8dTnMlrhKW9K_X → hUyNKiBOk3HaC0S0gE_N8}/_buildManifest.js +0 -0
  176. /package/bundle/standalone/apps/web/.next/static/{DWDlM7S8dTnMlrhKW9K_X → hUyNKiBOk3HaC0S0gE_N8}/_ssgManifest.js +0 -0
@@ -12,7 +12,7 @@ import { HandsRegistry } from "./hands/registry.js";
12
12
  import { buildSchemaDoc } from "./hands/schema-doc.js";
13
13
  import { formatExecResult } from "./hands/formatter.js";
14
14
  import { killAllActiveChildren } from "./hands/executor.js";
15
- import { initCapture, shutdownCapture, wrapHandler, startGitPoller } from "./journal-capture.js";
15
+ import { initCapture, shutdownCapture, wrapHandler, startGitPoller, appendVoluntaryEvent, getCurrentAgent, getCurrentSid } from "./journal-capture.js";
16
16
  import { registerJournalTools } from "./journal-tools.js";
17
17
  import { registerCommitUpgradesTool } from "./journal-commit-upgrades-tool.js";
18
18
  import { registerHousekeepTool } from "./journal-housekeep-tool.js";
@@ -35,24 +35,43 @@ function getAgentRulesWarning(projectId) {
35
35
  else {
36
36
  projects = db.prepare("SELECT id, path, name FROM projects").all();
37
37
  }
38
+ // Projects with zero detected context files have NEVER been onboarded —
39
+ // distinct from "outdated" (a file exists but predates the current
40
+ // rulesVersion). Both need admin.onboard_agent, so both are surfaced
41
+ // here; without this, a project that skipped its one-shot
42
+ // projects.register nudge would never get flagged again.
43
+ const missingProjects = [];
38
44
  const outdatedProjects = [];
39
45
  for (const p of projects) {
40
46
  if (!p || !p.path || !existsSync(p.path))
41
47
  continue;
42
48
  const contextFiles = detectAgentContextFiles(p.path);
43
- if (contextFiles.length === 0)
49
+ if (contextFiles.length === 0) {
50
+ missingProjects.push(p.name);
44
51
  continue;
52
+ }
45
53
  const statuses = checkAgentRulesStatus(p.path, contextFiles);
46
54
  if (statuses.some((s) => !s.upToDate)) {
47
55
  outdatedProjects.push(p.name);
48
56
  }
49
57
  }
50
- if (outdatedProjects.length === 0)
51
- return null;
58
+ const sentences = [];
59
+ if (missingProjects.length === 1) {
60
+ sentences.push(`Project "${missingProjects[0]}" has no agent instructions file yet.`);
61
+ }
62
+ else if (missingProjects.length > 1) {
63
+ sentences.push(`${missingProjects.length} projects have no agent instructions file yet.`);
64
+ }
52
65
  if (outdatedProjects.length === 1) {
53
- return `Project "${outdatedProjects[0]}" has outdated agent rules (v${RULE_BLOCK_VERSION} available). Run onboard_agent to update.`;
66
+ sentences.push(`Project "${outdatedProjects[0]}" has outdated agent rules (v${RULE_BLOCK_VERSION} available).`);
54
67
  }
55
- return `${outdatedProjects.length} projects have outdated agent rules (v${RULE_BLOCK_VERSION} available). Run onboard_agent for each to update.`;
68
+ else if (outdatedProjects.length > 1) {
69
+ sentences.push(`${outdatedProjects.length} projects have outdated agent rules (v${RULE_BLOCK_VERSION} available).`);
70
+ }
71
+ if (sentences.length === 0)
72
+ return null;
73
+ sentences.push("Run admin.onboard_agent to fix.");
74
+ return sentences.join(" ");
56
75
  }
57
76
  catch (e) {
58
77
  console.error("Error checking agent rules status:", e);
@@ -141,12 +160,43 @@ catch (e) {
141
160
  if (!pkgVersionFound) {
142
161
  console.warn("Could not locate kontexta-mcp package.json by walking up from module dir; defaulting version to 0.0.0");
143
162
  }
144
- function resolveKindFolder({ destination, folder, kind }) {
145
- if (destination !== "knowledge")
163
+ function resolveKindFolder({ destination, folder, kind, format, title }) {
164
+ if (destination !== "knowledge") {
165
+ // HTML reports only make sense in the KB's html/ bucket (see
166
+ // resources.export_report) — silently allowing destination='project'
167
+ // here means a report lands inside the user's own repo instead, with
168
+ // no error and no way to find it via the reports UI.
169
+ if (format === "html") {
170
+ return { error: "format='html' requires destination='knowledge' — HTML reports must live in the KB's html/ bucket, not a project or kontexta destination." };
171
+ }
146
172
  return { folder };
173
+ }
174
+ const norm = folder?.replace(/^\/+|\/+$/g, "") ?? "";
175
+ // Escape hatch: a bare `profile.md` at KB root bypasses kind-routing.
176
+ // It's the one file layout.ts permits directly under knowledge/, and
177
+ // otherwise there is no way to reach KB root through this tool.
178
+ if (norm === "" && title?.trim().toLowerCase() === "profile") {
179
+ return { folder: undefined };
180
+ }
181
+ // HTML reports always live under html/, never nested inside
182
+ // knowledge/dictionary or knowledge/notes (layout.ts requires .md
183
+ // there). `kind` doesn't apply — content_class for html/ paths is
184
+ // inferred as "note" from the path alone (see computeContentClass).
185
+ if (format === "html") {
186
+ const alreadyHtmlScoped = norm === "html" || norm.startsWith("html/");
187
+ return { folder: alreadyHtmlScoped ? folder : (norm ? `html/${norm}` : "html") };
188
+ }
189
+ // Same gap, same fix, for mermaid diagrams: knowledge/ requires .md
190
+ // (layout.ts), so an unrouted .mmd file would always fail at write
191
+ // time. Unlike html, mermaid diagrams committed inside a project's own
192
+ // repo are a legitimate use case, so this only applies to destination
193
+ // === "knowledge" — no destination restriction like html has.
194
+ if (format === "mmd") {
195
+ const alreadyMermaidScoped = norm === "mermaid" || norm.startsWith("mermaid/");
196
+ return { folder: alreadyMermaidScoped ? folder : (norm ? `mermaid/${norm}` : "mermaid") };
197
+ }
147
198
  if (!kind)
148
199
  return { error: "kind is required for destination='knowledge': must be 'dictionary' or 'note'" };
149
- const norm = folder?.replace(/^\/+|\/+$/g, "") ?? "";
150
200
  // Non-KB buckets (html/mermaid) also skip rewrite — their layout forbids nesting under knowledge/.
151
201
  const CLASS_PREFIXES = ["knowledge/dictionary", "knowledge/notes", "knowledge/urlclips", "journal", "html", "mermaid"];
152
202
  const alreadyClassScoped = CLASS_PREFIXES.some((p) => norm === p || norm.startsWith(p + "/"));
@@ -237,7 +287,13 @@ function loadProfileInstructions() {
237
287
  : `📋 PROFILE\n (not set up yet — nudge the user to fill it in at knowledge/profile.md or the dashboard's profile pane)`;
238
288
  const calendarBlock = buildCalendarSection(now);
239
289
  const freshness = profileExists ? profileFreshnessNote(path, empty) : "";
240
- return [header, "", profileBlock, "", calendarBlock, freshness].filter(Boolean).join("\n");
290
+ // Recurring nudge — projects.register's onboarding prompt fires once, at
291
+ // register time; if the calling agent doesn't relay it in the moment
292
+ // there was previously no second chance to see it. Surfacing it here
293
+ // means it comes back every session until admin.onboard_agent is run.
294
+ const rulesWarning = getAgentRulesWarning();
295
+ const rulesBlock = rulesWarning ? `\n⚠️ ${rulesWarning}` : "";
296
+ return [header, "", profileBlock, "", calendarBlock, freshness, rulesBlock].filter(Boolean).join("\n");
241
297
  }
242
298
  const server = new McpServer({ name: "kontexta", version: pkgVersion }, { instructions: loadProfileInstructions() });
243
299
  server.tool("admin.refresh_session_context", "Re-read the session context (profile, upcoming events within 7d, conflicts, freshness nudge) as it stands NOW. Call this when the user just edited their profile or added/moved calendar events and you want the current picture instead of the snapshot taken at session start. Read-only; no side effects. Returns the same block Kontexta sent as MCP instructions at session start.", {}, async () => ({
@@ -294,11 +350,12 @@ process.on("SIGTERM", () => { if (!_shutdownInFlight) {
294
350
  _shutdownInFlight = true;
295
351
  void handleShutdownSignal("SIGTERM");
296
352
  } });
297
- // Auto-wrap every tool registration that follows. journal_append (legacy) is excluded
298
- // because it will be removed in Task 15. Auto-wrap covers all current and future tools.
353
+ // Auto-wrap every tool registration that follows. journal.write is excluded
354
+ // because the auto-wrap re-enters journal recording, and journal.write itself
355
+ // records journal events — including it would loop.
299
356
  const _origServerTool = server.tool.bind(server);
300
357
  server.tool = function (name, ...rest) {
301
- if (name === "journal.append") {
358
+ if (name === "journal.write") {
302
359
  return _origServerTool(name, ...rest);
303
360
  }
304
361
  const handler = rest[rest.length - 1];
@@ -307,86 +364,145 @@ server.tool = function (name, ...rest) {
307
364
  }
308
365
  return _origServerTool(name, ...rest);
309
366
  };
310
- // Legacy journal_append tool — excluded from wrapHandler (line 223) so it
311
- // does NOT get the journal-backlog envelope injected. Kept for backward-compat.
312
- server.tool("journal.append", "Append a timestamped text entry to today's daily journal file in the Knowledge Base. Creates the file if it doesn't already exist. Both calls on the same calendar day return the same file_id. Returns { file_id }.", {
313
- text: z.string().describe("Text to append to today's journal entry"),
314
- project_id: z.number().optional().describe("Optional project ID context"),
315
- }, async ({ text }) => {
316
- try {
317
- const today = new Date().toISOString().slice(0, 10); // YYYY-MM-DD
318
- const journalFolder = "journal";
319
- const title = `journal-${today}`;
320
- const db = getDatabase();
321
- // Try to find an existing journal file for today.
322
- const knowledgeDir = join(dataDir, "knowledge");
323
- const expectedPath = join(knowledgeDir, journalFolder, `${title}.md`);
324
- const existingRow = db
325
- .prepare("SELECT id, path FROM files WHERE path = ? AND project_id IS NULL")
326
- .get(expectedPath);
327
- if (existingRow) {
328
- // Append to existing file.
329
- const existing = readFile(existingRow.id);
330
- const timestamp = new Date().toISOString().replace("T", " ").slice(0, 19);
331
- const newContent = `${existing.content}\n---\n**${timestamp}** ${text}\n`;
332
- await updateFile(existingRow.id, newContent, dataDir);
367
+ // Excluded from wrapHandler (see above) so it does NOT get the
368
+ // journal-backlog envelope injected — it IS the journal write path.
369
+ server.tool("journal.write", "Write one event to the current project's journal. `kind: 'append'` = timestamped entry in today's daily journal file in the Knowledge Base (creates the file if it doesn't exist; both calls on the same calendar day return the same file_id; returns `{file_id}`). `kind: 'note'` = free-form decision/abandonment/observation, stored as an `agent_note` event in Layer 1 (surfaces in distilled task entries; returns `{ok, recorded_at}`). `kind: 'intent'` = topic/intent pivot — use when the user redirects what you're working on so the distillation step splits task buckets correctly (returns `{ok, recorded_at}`). Required fields depend on `kind`: 'append'/'note' need `text`; 'intent' needs `summary`.", {
370
+ kind: z.enum(["append", "note", "intent"]).describe("Event kind. Selects which body fields are required and how the event is stored."),
371
+ text: z.string().optional().describe("Required for kind='append' or kind='note'. Body of the entry."),
372
+ summary: z.string().optional().describe("Required for kind='intent'. One-line summary of the new intent."),
373
+ tags: z.array(z.string()).optional().describe("Optional for kind='note'. Tags for the note."),
374
+ project_id: z.number().optional().describe("Optional for kind='append'. Project ID context."),
375
+ }, async ({ kind, text, summary, tags }) => {
376
+ if (kind === "append") {
377
+ if (!text) {
378
+ return { isError: true, content: [{ type: "text", text: JSON.stringify({ error: "kind='append' requires `text`" }, null, 2) }] };
379
+ }
380
+ try {
381
+ const today = new Date().toISOString().slice(0, 10); // YYYY-MM-DD
382
+ const journalFolder = "journal";
383
+ const title = `journal-${today}`;
384
+ const db = getDatabase();
385
+ // Try to find an existing journal file for today.
386
+ const knowledgeDir = join(dataDir, "knowledge");
387
+ const expectedPath = join(knowledgeDir, journalFolder, `${title}.md`);
388
+ const existingRow = db
389
+ .prepare("SELECT id, path FROM files WHERE path = ? AND project_id IS NULL")
390
+ .get(expectedPath);
391
+ if (existingRow) {
392
+ // Append to existing file.
393
+ const existing = readFile(existingRow.id);
394
+ const timestamp = new Date().toISOString().replace("T", " ").slice(0, 19);
395
+ const newContent = `${existing.content}\n---\n**${timestamp}** ${text}\n`;
396
+ await updateFile(existingRow.id, newContent, dataDir);
397
+ return {
398
+ content: [{ type: "text", text: JSON.stringify({ file_id: existingRow.id }, null, 2) }],
399
+ };
400
+ }
401
+ else {
402
+ // Create a new daily journal file.
403
+ const timestamp = new Date().toISOString().replace("T", " ").slice(0, 19);
404
+ const content = `# Journal — ${today}\n\n---\n**${timestamp}** ${text}\n`;
405
+ const result = await createFile({
406
+ title,
407
+ content,
408
+ destination: "knowledge",
409
+ folder: journalFolder,
410
+ dataDir,
411
+ });
412
+ return {
413
+ content: [{ type: "text", text: JSON.stringify({ file_id: result.id }, null, 2) }],
414
+ };
415
+ }
416
+ }
417
+ catch (e) {
333
418
  return {
334
- content: [{ type: "text", text: JSON.stringify({ file_id: existingRow.id }, null, 2) }],
419
+ isError: true,
420
+ content: [{ type: "text", text: JSON.stringify({ error: e?.message ?? String(e) }, null, 2) }],
335
421
  };
336
422
  }
337
- else {
338
- // Create a new daily journal file.
339
- const timestamp = new Date().toISOString().replace("T", " ").slice(0, 19);
340
- const content = `# Journal — ${today}\n\n---\n**${timestamp}** ${text}\n`;
423
+ }
424
+ if (kind === "note") {
425
+ if (!text) {
426
+ return { isError: true, content: [{ type: "text", text: JSON.stringify({ error: "kind='note' requires `text`" }, null, 2) }] };
427
+ }
428
+ const ev = {
429
+ ts: new Date().toISOString(),
430
+ agent: getCurrentAgent(),
431
+ sid: getCurrentSid(),
432
+ event: "agent_note",
433
+ summary: text,
434
+ tags: tags ?? [],
435
+ };
436
+ appendVoluntaryEvent(ev);
437
+ return { content: [{ type: "text", text: JSON.stringify({ ok: true, recorded_at: ev.ts }) }] };
438
+ }
439
+ // kind === "intent"
440
+ if (!summary) {
441
+ return { isError: true, content: [{ type: "text", text: JSON.stringify({ error: "kind='intent' requires `summary`" }, null, 2) }] };
442
+ }
443
+ const ev = {
444
+ ts: new Date().toISOString(),
445
+ agent: getCurrentAgent(),
446
+ sid: getCurrentSid(),
447
+ event: "user_intent",
448
+ summary,
449
+ };
450
+ appendVoluntaryEvent(ev);
451
+ return { content: [{ type: "text", text: JSON.stringify({ ok: true, recorded_at: ev.ts }) }] };
452
+ });
453
+ server.tool("files.create", "Create one or more markdown, mermaid, or HTML files in the knowledge base or project (up to 200 per call). Pass a single-element `files` array for the one-file case. This operation writes each file to disk and adds it to the local SQLite FTS5 index. Destination can be 'knowledge' (global KB), 'project' (reference file inside a project repo), or 'kontexta' (internal Kontexta schema file). If destination is 'project' or 'kontexta', project_id is strictly required. If destination is 'knowledge', 'kind' is strictly required for md files — pick 'dictionary' (authoritative source-of-truth) or 'note' (informational snapshot); see the kind param for the rubric. No external auth required. Rate limits do not apply (local operation). Per-item failures are isolated to `errors[]` — the rest of the batch still commits; a single-item call still reports its failure the same way. Returns `{created_count, error_count, created, errors}`. If a destination directory does not exist, it will be created automatically. To modify an existing file, use 'files.update' instead. Pass format='mmd' on an item to create a Mermaid diagram file (.mmd) — for destination='knowledge' it's auto-routed to the KB's `mermaid/` bucket (`kind` ignored, not required); for destination='project' it's written wherever `folder` says, same as any project file. Pass format='html' for an HTML report — `destination` MUST be 'knowledge' (html reports are auto-routed to the KB's `html/` bucket; `kind` is ignored and not required for html). Format defaults to 'md'.", {
454
+ files: z
455
+ .array(z.object({
456
+ title: z.string().describe("Title of the file"),
457
+ content: z.string().describe("Content of the file"),
458
+ destination: z.enum(["knowledge", "project", "kontexta"]).describe("Destination type"),
459
+ project_id: z.number().optional().describe("Project ID (required for project/kontexta destinations)"),
460
+ folder: z.string().optional().describe("Optional folder path"),
461
+ tags: z.array(z.string()).optional().describe("Optional array of tags"),
462
+ format: z.enum(["md", "mmd", "html"]).optional().describe("File extension to write. Defaults to 'md'. Use 'html' for HTML reports."),
463
+ kind: z.enum(["dictionary", "note"]).optional()
464
+ .describe("REQUIRED for destination='knowledge'. 'dictionary' = source of truth (mappings, glossaries, runbooks, PR templates). 'note' = snapshot (meeting notes, sprint reviews, PR findings, post-mortems). Test: if this file disagreed with the code, who wins? File wins → dictionary; file loses → note. Ignored for destination='project' or 'kontexta'."),
465
+ }))
466
+ .min(1)
467
+ .max(200)
468
+ .describe("Files to create. Single-element array = one-file case. Max 200 per call."),
469
+ }, async ({ files }) => {
470
+ const created = [];
471
+ const errors = [];
472
+ for (let i = 0; i < files.length; i++) {
473
+ const f = files[i];
474
+ try {
475
+ const resolved = resolveKindFolder({ destination: f.destination, folder: f.folder, kind: f.kind, format: f.format, title: f.title });
476
+ if ("error" in resolved) {
477
+ errors.push({ index: i, title: f.title, error: resolved.error });
478
+ continue;
479
+ }
341
480
  const result = await createFile({
342
- title,
343
- content,
344
- destination: "knowledge",
345
- folder: journalFolder,
481
+ title: f.title,
482
+ content: f.content,
483
+ destination: f.destination,
484
+ projectId: f.project_id,
485
+ folder: resolved.folder,
486
+ tags: f.tags,
346
487
  dataDir,
488
+ format: f.format,
347
489
  });
348
- return {
349
- content: [{ type: "text", text: JSON.stringify({ file_id: result.id }, null, 2) }],
350
- };
490
+ const payload = annotateTokens(result);
491
+ if (resolved.warning)
492
+ payload.warning = resolved.warning;
493
+ created.push(payload);
494
+ }
495
+ catch (e) {
496
+ errors.push({ index: i, title: f.title, error: e?.message ?? String(e) });
351
497
  }
352
498
  }
353
- catch (e) {
354
- return {
355
- isError: true,
356
- content: [{ type: "text", text: JSON.stringify({ error: e?.message ?? String(e) }, null, 2) }],
357
- };
358
- }
359
- });
360
- server.tool("files.create", "Create a new markdown, mermaid, or HTML file in the knowledge base or project. This operation writes a new file to disk and adds it to the local SQLite FTS5 index. Destination can be 'knowledge' (global KB), 'project' (reference file inside a project repo), or 'kontexta' (internal Kontexta schema file). If destination is 'project' or 'kontexta', project_id is strictly required. If destination is 'knowledge', 'kind' is strictly required — pick 'dictionary' (authoritative source-of-truth) or 'note' (informational snapshot); see the kind param for the rubric. No external auth required. Rate limits do not apply (local operation). Returns the created file metadata including its new ID, path, and estimated tokens. If the destination directory does not exist, it will be created automatically. Use this tool to instantiate new contextual documents or notes. To modify an existing file, use 'files.update' instead. Parameters: 'destination' dictates required fields; if 'project' or 'kontexta', 'project_id' must be a valid integer; if 'knowledge', 'kind' must be 'dictionary' or 'note'. 'tags' and 'folder' are optional. Pass format='mmd' to create a Mermaid diagram file (.mmd) or format='html' for HTML reports; defaults to 'md'.", {
361
- title: z.string().describe("Title of the file"),
362
- content: z.string().describe("Content of the file"),
363
- destination: z.enum(["knowledge", "project", "kontexta"]).describe("Destination type"),
364
- project_id: z.number().optional().describe("Project ID (required for project/kontexta destinations)"),
365
- folder: z.string().optional().describe("Optional folder path"),
366
- tags: z.array(z.string()).optional().describe("Optional array of tags"),
367
- format: z.enum(["md", "mmd", "html"]).optional().describe("File extension to write. Defaults to 'md'. Use 'html' for HTML reports."),
368
- kind: z.enum(["dictionary", "note"]).optional()
369
- .describe("REQUIRED for destination='knowledge'. 'dictionary' = source of truth (mappings, glossaries, runbooks, PR templates). 'note' = snapshot (meeting notes, sprint reviews, PR findings, post-mortems). Test: if this file disagreed with the code, who wins? File wins → dictionary; file loses → note. Ignored for destination='project' or 'kontexta'."),
370
- }, async ({ title, content, destination, project_id, folder, tags, format, kind }) => {
371
- const resolved = resolveKindFolder({ destination, folder, kind });
372
- if ("error" in resolved) {
373
- return { isError: true, content: [{ type: "text", text: JSON.stringify({ error: resolved.error }, null, 2) }] };
374
- }
375
- const result = await createFile({
376
- title,
377
- content,
378
- destination,
379
- projectId: project_id,
380
- folder: resolved.folder,
381
- tags,
382
- dataDir,
383
- format,
384
- });
385
- const payload = annotateTokens(result);
386
- if (resolved.warning)
387
- payload.warning = resolved.warning;
388
499
  return {
389
- content: [{ type: "text", text: JSON.stringify(payload, null, 2) }],
500
+ content: [
501
+ {
502
+ type: "text",
503
+ text: JSON.stringify({ created_count: created.length, error_count: errors.length, created, errors }, null, 2),
504
+ },
505
+ ],
390
506
  };
391
507
  });
392
508
  server.tool("resources.add_report", "Write an image or other binary resource into the shared reports/resources/ folder. Returns { filename, size, src, url } — embed the report's <img>/<a> tags with `src` exactly as given (e.g. `<img src=\"resources/chart.png\">`); it is the only form that resolves correctly both in the dashboard viewer and in PDF/PNG export. Do not use `url` inside report HTML — it only works in the dashboard. Bytes are passed base64-encoded.", {
@@ -427,33 +543,102 @@ server.tool("resources.export_report", "Export an existing HTML report as PDF or
427
543
  return { content: [{ type: "text", text: JSON.stringify({ url, note: `inline_bytes unavailable in this install: ${e?.message ?? String(e)}` }, null, 2) }] };
428
544
  }
429
545
  });
430
- server.tool("files.read", "Read one file's full body and metadata by ID. Read-only; no side effects, auth, or rate limits. Returns title, path, content, tags, est_tokens (so you can budget context before opening more files), and timestamps. Throws if the ID is unknown. Use for a single known file. Prefer `files.describe` to inspect without paying body tokens; `files.read_many` for batches; `files.read_lines`/`files.read_section` for partial reads; `files.read_by_path` when you only have the absolute path.", {
431
- id: z.number().describe("File ID"),
432
- }, async ({ id }) => {
433
- const result = readFile(id);
434
- return {
435
- content: [{ type: "text", text: JSON.stringify(annotateTokens(result), null, 2) }],
436
- };
437
- });
438
- server.tool("files.read_many", "Batch read up to 200 files by ID in one call. Returns per-file annotated records, an aggregate `total_est_tokens`, and an isolated `errors[]` (one bad ID does NOT abort the batch). Read-only; no side effects, auth, or rate limits. Use instead of looping `files.read` to halve round-trips and get the combined token cost upfront. For >200 IDs, page yourself.", {
439
- ids: z.array(z.number()).min(1).max(200).describe("File IDs to read (max 200 per call)"),
440
- }, async ({ ids }) => {
441
- const files = [];
442
- const errors = [];
443
- let total_est_tokens = 0;
444
- for (const id of ids) {
445
- try {
446
- const r = annotateTokens(readFile(id));
447
- files.push(r);
448
- total_est_tokens += r.est_tokens ?? 0;
546
+ server.tool("files.read", "Read one or more files, in full or in part. Modes: single-by-id (`id`), single-by-path (`path`, absolute on-disk path — must be exactly as indexed), batch-by-id (`ids`, up to 200), partial-by-heading (`id`+`section`), partial-by-line-range (`id`+`lines`). Exactly one of `id`/`path`/`ids` is required. `section` and `lines` are mutually exclusive and only valid with `id` (not `ids` or `path`). Read-only; no side effects, auth, or rate limits. Response shape: a single file object (with `content`, tags, est_tokens) for `id`/`path`; a partial-content object for `section`/`lines`; `{files, total_est_tokens, error_count, errors}` for `ids` (per-ID failures isolated, batch never partial-throws). Prefer `files.describe` to inspect without paying body tokens.", {
547
+ id: z.number().int().positive().optional().describe("Single file by ID."),
548
+ path: z.string().optional().describe("Single file by absolute on-disk path (must match exactly what Kontexta indexed)."),
549
+ ids: z.array(z.number()).min(1).max(200).optional().describe("Batch mode: multiple file IDs (max 200 per call); returns an array plus aggregate token cost."),
550
+ section: z.string().optional().describe("Partial read: return only this heading's body (case-insensitive exact-string after trim). Requires `id`; mutually exclusive with `lines`."),
551
+ lines: z.object({
552
+ from: z.number().int().positive().describe("First line (1-indexed, inclusive)"),
553
+ to: z.number().int().positive().describe("Last line (1-indexed, inclusive)"),
554
+ }).optional().describe("Partial read: 1-indexed inclusive line range. Requires `id`; mutually exclusive with `section`."),
555
+ }, async ({ id, path, ids, section, lines }) => {
556
+ const modeCount = [id !== undefined, path !== undefined, ids !== undefined].filter(Boolean).length;
557
+ if (modeCount !== 1) {
558
+ return { isError: true, content: [{ type: "text", text: JSON.stringify({ error: "Exactly one of `id`, `path`, or `ids` must be present" }, null, 2) }] };
559
+ }
560
+ if (section !== undefined && lines !== undefined) {
561
+ return { isError: true, content: [{ type: "text", text: JSON.stringify({ error: "`section` and `lines` are mutually exclusive" }, null, 2) }] };
562
+ }
563
+ if ((section !== undefined || lines !== undefined) && ids !== undefined) {
564
+ return { isError: true, content: [{ type: "text", text: JSON.stringify({ error: "`section`/`lines` require `id` (single-file mode), not `ids`" }, null, 2) }] };
565
+ }
566
+ if ((section !== undefined || lines !== undefined) && path !== undefined) {
567
+ return { isError: true, content: [{ type: "text", text: JSON.stringify({ error: "`section`/`lines` require `id`, not `path`" }, null, 2) }] };
568
+ }
569
+ try {
570
+ if (ids !== undefined) {
571
+ const files = [];
572
+ const errors = [];
573
+ let total_est_tokens = 0;
574
+ for (const rid of ids) {
575
+ try {
576
+ const r = annotateTokens(readFile(rid));
577
+ files.push(r);
578
+ total_est_tokens += r.est_tokens ?? 0;
579
+ }
580
+ catch (e) {
581
+ errors.push({ id: rid, error: e?.message ?? String(e) });
582
+ }
583
+ }
584
+ return {
585
+ content: [{ type: "text", text: JSON.stringify({ files, total_est_tokens, error_count: errors.length, errors }, null, 2) }],
586
+ };
449
587
  }
450
- catch (e) {
451
- errors.push({ id, error: e?.message ?? String(e) });
588
+ let resolvedId;
589
+ if (path !== undefined) {
590
+ if (path.length === 0)
591
+ throw new Error("path is required");
592
+ const row = getDatabase().prepare("SELECT id FROM files WHERE path = ?").get(path);
593
+ if (!row) {
594
+ return { isError: true, content: [{ type: "text", text: JSON.stringify({ error: `No file indexed at path: ${path}` }, null, 2) }] };
595
+ }
596
+ resolvedId = row.id;
597
+ }
598
+ else {
599
+ resolvedId = id;
452
600
  }
601
+ if (section !== undefined) {
602
+ const file = readFile(resolvedId);
603
+ const node = findSection(file.content, section);
604
+ if (!node) {
605
+ return { isError: true, content: [{ type: "text", text: JSON.stringify({ error: `Section not found: ${section}` }, null, 2) }] };
606
+ }
607
+ const buf = Buffer.from(file.content, "utf8");
608
+ const body = buf.subarray(node.contentStart, node.contentEnd).toString("utf8");
609
+ return {
610
+ content: [{ type: "text", text: JSON.stringify({
611
+ file_id: resolvedId, path: file.path, heading: node.text, level: node.level, line: node.line,
612
+ content: body, size_bytes: Buffer.byteLength(body, "utf8"), est_tokens: estimateTokensFromBuffer(Buffer.from(body, "utf8")),
613
+ }, null, 2) }],
614
+ };
615
+ }
616
+ if (lines !== undefined) {
617
+ if (lines.to < lines.from)
618
+ throw new Error("`lines.to` must be >= `lines.from`");
619
+ const file = readFile(resolvedId);
620
+ const allLines = file.content.split("\n");
621
+ const start = Math.max(0, lines.from - 1);
622
+ const end = Math.min(allLines.length, lines.to);
623
+ const slice = allLines.slice(start, end).join("\n");
624
+ return {
625
+ content: [{ type: "text", text: JSON.stringify({
626
+ file_id: resolvedId, path: file.path, from: start + 1, to: end, total_lines: allLines.length,
627
+ content: slice, size_bytes: Buffer.byteLength(slice, "utf8"), est_tokens: estimateTokensFromBuffer(Buffer.from(slice, "utf8")),
628
+ }, null, 2) }],
629
+ };
630
+ }
631
+ const result = readFile(resolvedId);
632
+ return {
633
+ content: [{ type: "text", text: JSON.stringify(annotateTokens(result), null, 2) }],
634
+ };
635
+ }
636
+ catch (e) {
637
+ return {
638
+ isError: true,
639
+ content: [{ type: "text", text: JSON.stringify({ error: e?.message ?? String(e) }, null, 2) }],
640
+ };
453
641
  }
454
- return {
455
- content: [{ type: "text", text: JSON.stringify({ files, total_est_tokens, error_count: errors.length, errors }, null, 2) }],
456
- };
457
642
  });
458
643
  server.tool("files.describe", "Return everything ABOUT a file without pulling its content (no token cost from the body). Tags, size, est_tokens, history depth, related-file ids, backlinks, project, folder, last edited. Operates locally with no auth or rate limits. Use this when you'd otherwise chain files.read + tags.list + files.get_history + files.find_related just to decide whether to actually read the file. Parameters: 'id' must be a valid integer file ID.", {
459
644
  id: z.number().describe("File ID"),
@@ -575,101 +760,17 @@ server.tool("files.describe", "Return everything ABOUT a file without pulling it
575
760
  };
576
761
  }
577
762
  });
578
- server.tool("files.read_lines", "Return a 1-indexed inclusive line slice of a file. Out-of-range bounds clamp silently to the file's actual length; `to < from` throws. Read-only; no side effects, auth, or rate limits. Returns the snippet plus its size_bytes and est_tokens. Use to inspect a stack-trace region or a chunk of a large file without pulling the whole body. Prefer `read_section` if you know the heading, `grep_in_file` if you know a pattern but not the line number.", {
579
- id: z.number().describe("File ID"),
580
- from: z.number().int().positive().describe("First line (1-indexed, inclusive)"),
581
- to: z.number().int().positive().describe("Last line (1-indexed, inclusive)"),
582
- }, async ({ id, from, to }) => {
583
- try {
584
- if (to < from)
585
- throw new Error("`to` must be >= `from`");
586
- const file = readFile(id);
587
- const lines = file.content.split("\n");
588
- const start = Math.max(0, from - 1);
589
- const end = Math.min(lines.length, to);
590
- const slice = lines.slice(start, end).join("\n");
591
- return {
592
- content: [
593
- {
594
- type: "text",
595
- text: JSON.stringify({
596
- file_id: id,
597
- path: file.path,
598
- from: start + 1,
599
- to: end,
600
- total_lines: lines.length,
601
- content: slice,
602
- size_bytes: Buffer.byteLength(slice, "utf8"),
603
- est_tokens: estimateTokensFromBuffer(Buffer.from(slice, "utf8")),
604
- }, null, 2),
605
- },
606
- ],
607
- };
608
- }
609
- catch (e) {
610
- return {
611
- isError: true,
612
- content: [{ type: "text", text: JSON.stringify({ error: e?.message ?? String(e) }, null, 2) }],
613
- };
614
- }
615
- });
616
- server.tool("files.grep", "Match a JS regex against one file's lines and return matched lines with line numbers (capped: default 100, max 500). Catches what FTS misses: URLs, hyphenated terms, code identifiers. Read-only; no side effects, auth, or rate limits. Invalid regex throws `invalid regex`. Returns `{matches, match_count, truncated}`. Use after `files.read_outline` when you know the file but need a specific reference; for cross-file regex use `files.regex_search`; for keyword/concept search use `files.search`.", {
617
- id: z.number().describe("File ID"),
618
- pattern: z.string().describe("Pattern to match. Treated as a JavaScript RegExp source."),
619
- case_insensitive: z.boolean().optional().describe("Add the 'i' flag (default false)"),
620
- max_matches: z.number().int().positive().max(500).optional().describe("Cap on returned hits (default 100)"),
621
- }, async ({ id, pattern, case_insensitive, max_matches }) => {
622
- try {
623
- let re;
624
- try {
625
- re = new RE2Class(pattern, case_insensitive ? "i" : "");
626
- }
627
- catch (e) {
628
- throw new Error(`invalid regex: ${e?.message ?? e}`);
629
- }
630
- const file = readFile(id);
631
- const lines = file.content.split("\n");
632
- const cap = max_matches ?? 100;
633
- const matches = [];
634
- for (let i = 0; i < lines.length; i++) {
635
- if (re.test(lines[i])) {
636
- matches.push({ line: i + 1, text: lines[i] });
637
- if (matches.length >= cap)
638
- break;
639
- }
640
- }
641
- return {
642
- content: [
643
- {
644
- type: "text",
645
- text: JSON.stringify({
646
- file_id: id,
647
- path: file.path,
648
- pattern,
649
- match_count: matches.length,
650
- truncated: matches.length === cap,
651
- matches,
652
- }, null, 2),
653
- },
654
- ],
655
- };
656
- }
657
- catch (e) {
658
- return {
659
- isError: true,
660
- content: [{ type: "text", text: JSON.stringify({ error: e?.message ?? String(e) }, null, 2) }],
661
- };
662
- }
663
- });
664
- server.tool("files.regex_search", "Match a JS regex against the body of every file in scope (project, KB, or all) and return per-file hits with line numbers. Slower than FTS `search` because it reads each file's content; use only when FTS misses substrings, URLs, or code identifiers. Read-only; no side effects, auth, or rate limits. Capped at 500 files / 10 hits per file by default; the response reports `files_truncated` and per-file truncation so the agent can re-scope. `project_id: null` = KB only; omit = everywhere; `kind` narrows to one content class. Invalid regex throws.", {
763
+ server.tool("files.regex_search", "Match a JS regex against file bodies. Default mode scans every file in scope (project, KB, or all) and returns per-file hits with line numbers — slower than FTS `files.search` because it reads each file's content; use only when FTS misses substrings, URLs, or code identifiers. Pass `file_id` to instead scan just that one file (catches what FTS misses within a single known file); response shape changes to `{file_id, path, pattern, match_count, truncated, matches}`. Read-only; no side effects, auth, or rate limits. Multi-file mode capped at 500 files / 10 hits per file by default (`files_truncated` reports the cap); single-file mode capped at 100 hits by default, max 500. `project_id`/`kind` are ignored when `file_id` is set. Invalid regex throws.", {
665
764
  pattern: z.string().describe("JavaScript RegExp source"),
666
- project_id: z.number().nullable().optional().describe("Scope to one project, null for KB-only, omit for everything"),
765
+ file_id: z.number().optional().describe("Scan only this file instead of every file in scope. When set, `project_id`/`kind`/`max_files`/`max_matches_per_file` are ignored in favor of `max_matches`."),
766
+ project_id: z.number().nullable().optional().describe("Scope to one project, null for KB-only, omit for everything. Ignored when `file_id` is set."),
667
767
  case_insensitive: z.boolean().optional().describe("If true, match pattern case-insensitively (RegExp 'i' flag). Default false."),
668
- max_files: z.number().int().positive().max(2000).optional().describe("Cap on files scanned (default 500)"),
669
- max_matches_per_file: z.number().int().positive().max(100).optional().describe("Per-file hit cap (default 10)"),
768
+ max_files: z.number().int().positive().max(2000).optional().describe("Cap on files scanned (default 500). Ignored when `file_id` is set."),
769
+ max_matches_per_file: z.number().int().positive().max(100).optional().describe("Per-file hit cap in multi-file mode (default 10). Ignored when `file_id` is set."),
770
+ max_matches: z.number().int().positive().max(500).optional().describe("Cap on returned hits in single-file mode (default 100). Only used when `file_id` is set."),
670
771
  kind: z.enum(["dictionary", "note", "journal", "project"]).optional()
671
- .describe("Filter by content class before scanning."),
672
- }, async ({ pattern, project_id, case_insensitive, max_files, max_matches_per_file, kind }) => {
772
+ .describe("Filter by content class before scanning. Ignored when `file_id` is set."),
773
+ }, async ({ pattern, file_id, project_id, case_insensitive, max_files, max_matches_per_file, max_matches, kind }) => {
673
774
  try {
674
775
  let re;
675
776
  try {
@@ -678,6 +779,34 @@ server.tool("files.regex_search", "Match a JS regex against the body of every fi
678
779
  catch (e) {
679
780
  throw new Error(`invalid regex: ${e?.message ?? e}`);
680
781
  }
782
+ if (file_id !== undefined) {
783
+ const file = readFile(file_id);
784
+ const lines = file.content.split("\n");
785
+ const cap = max_matches ?? 100;
786
+ const matches = [];
787
+ for (let i = 0; i < lines.length; i++) {
788
+ if (re.test(lines[i])) {
789
+ matches.push({ line: i + 1, text: lines[i] });
790
+ if (matches.length >= cap)
791
+ break;
792
+ }
793
+ }
794
+ return {
795
+ content: [
796
+ {
797
+ type: "text",
798
+ text: JSON.stringify({
799
+ file_id,
800
+ path: file.path,
801
+ pattern,
802
+ match_count: matches.length,
803
+ truncated: matches.length === cap,
804
+ matches,
805
+ }, null, 2),
806
+ },
807
+ ],
808
+ };
809
+ }
681
810
  const fileCap = max_files ?? 500;
682
811
  const perFileCap = max_matches_per_file ?? 10;
683
812
  const db = getDatabase();
@@ -745,24 +874,53 @@ server.tool("files.regex_search", "Match a JS regex against the body of every fi
745
874
  };
746
875
  }
747
876
  });
748
- server.tool("files.update", "Update the entire content of an existing file by its ID. This replaces the file's content on disk and triggers an FTS5 re-index. Returns the updated file metadata including new estimated token counts. Operates locally with no external auth or rate limits. If you only need to modify a single section without replacing the entire file, use 'files.update_section' instead to save context budget. Parameters: 'id' must be a valid integer file ID. 'content' is the complete markdown string that will replace the file.", {
877
+ server.tool("files.update", "Rewrite a file. Default = full-body replacement: `content` becomes the entire file, triggering disk write + FTS5 re-index. Pass `section` to instead rewrite ONLY that heading's body (case-insensitive exact-string after trim; the heading line itself is preserved, siblings untouched) — saves context budget vs resending the whole file. Throws if `section` is set but the heading doesn't exist (this mode will NOT create a new section — append the section text via a full-body update first). Operates locally with no external auth or rate limits. Returns the updated file metadata including new estimated token counts.", {
749
878
  id: z.number().describe("File ID"),
750
- content: z.string().describe("New content"),
751
- }, async ({ id, content }) => {
752
- const result = await updateFile(id, content, dataDir);
753
- return {
754
- content: [{ type: "text", text: JSON.stringify(annotateTokens(result), null, 2) }],
755
- };
879
+ content: z.string().describe("New content. With `section` set, this replaces just that heading's body; otherwise it becomes the entire file body."),
880
+ section: z.string().optional().describe("Case-insensitive exact-string heading. When set, only this heading's body is rewritten instead of the whole file."),
881
+ }, async ({ id, content, section }) => {
882
+ try {
883
+ let newBody = content;
884
+ if (section !== undefined) {
885
+ const file = readFile(id);
886
+ newBody = replaceSection(file.content, section, content);
887
+ }
888
+ const result = await updateFile(id, newBody, dataDir);
889
+ return {
890
+ content: [{ type: "text", text: JSON.stringify(annotateTokens(result), null, 2) }],
891
+ };
892
+ }
893
+ catch (e) {
894
+ return {
895
+ isError: true,
896
+ content: [{ type: "text", text: JSON.stringify({ error: e?.message ?? String(e) }, null, 2) }],
897
+ };
898
+ }
756
899
  });
757
- server.tool("files.delete", "DESTRUCTIVE. Permanently delete one file by ID. KB files are unlinked from disk AND removed from the FTS5 index; project reference files only have their index entry removed (the file on disk is left alone so the watcher does not fight your editor). Not idempotent — deleting an unknown ID throws. No external auth or rate limits. Returns `{success: true}`. Use only when the file is truly obsolete; to deprioritise without losing data, untag (`tags.remove`) or unfavorite (`tags.set_favorite`) instead. Bulk variant: `files.delete_many`.", {
758
- id: z.number().describe("File ID"),
759
- }, async ({ id }) => {
760
- await deleteFile(id, dataDir);
900
+ server.tool("files.delete", "DESTRUCTIVE. Permanently delete one or more files by ID (up to 500 per call). Pass a single-element `ids` array for the one-file case. KB files are unlinked from disk AND removed from the FTS5 index; project reference files only have their index entry removed (the file on disk is left alone so the watcher does not fight your editor). Not idempotent — deleting an unknown ID surfaces as a per-item error. No external auth or rate limits. Per-ID failures are isolated to `errors[]` and the rest of the batch still commits — partial success is the norm, always inspect `error_count`. Returns `{deleted_count, error_count, deleted, errors}`. Use only when the file is truly obsolete; to deprioritise without losing data, untag (`tags.remove`) or unfavorite (`tags.set_favorite`) instead. To preview the set before deleting, run `files.list` with the same filter and confirm the IDs.", {
901
+ ids: z.array(z.number()).min(1).max(500).describe("File IDs to delete. Single-element array = one-file case. Max 500 per call."),
902
+ }, async ({ ids }) => {
903
+ const deleted = [];
904
+ const errors = [];
905
+ for (const id of ids) {
906
+ try {
907
+ await deleteFile(id, dataDir);
908
+ deleted.push(id);
909
+ }
910
+ catch (e) {
911
+ errors.push({ id, error: e?.message ?? String(e) });
912
+ }
913
+ }
761
914
  return {
762
- content: [{ type: "text", text: JSON.stringify({ success: true }, null, 2) }],
915
+ content: [
916
+ {
917
+ type: "text",
918
+ text: JSON.stringify({ deleted_count: deleted.length, error_count: errors.length, deleted, errors }, null, 2),
919
+ },
920
+ ],
763
921
  };
764
922
  });
765
- server.tool("files.list", "List file metadata with optional filters (project_id, tag, favorite, folder, untagged, kind) and pagination. Read-only; no side effects, auth, or rate limits. Each row is annotated with tags, est_tokens, size_bytes, and content_class; the response includes `total_est_tokens` so you can budget before reading bodies. `project_id: null` returns ONLY Knowledge Base files; omit the field to span everything; `kind` narrows to one content class. Use to browse known structure; for keyword/content lookup use `search`; for a denser whole-vault dump use `project_map`.", {
923
+ server.tool("files.list", "List file metadata with optional filters (project_id, tag, favorite, folder, untagged, kind) and pagination. Read-only; no side effects, auth, or rate limits. Each row is annotated with tags, est_tokens, size_bytes, and content_class; the response includes `total_est_tokens` so you can budget before reading bodies. `project_id: null` returns ONLY Knowledge Base files; omit the field to span everything; `kind` narrows to one content class. Use to browse known structure; for keyword/content lookup use `files.search`; for a denser whole-vault dump use `projects.map`.", {
766
924
  project_id: z.number().nullable().optional().describe("Filter by project ID. Pass null to list ONLY Knowledge Base files (project_id IS NULL)."),
767
925
  tag: z.string().optional().describe("Filter by tag name"),
768
926
  favorite: z.boolean().optional().describe("Filter by favorite status"),
@@ -797,14 +955,17 @@ server.tool("files.list", "List file metadata with optional filters (project_id,
797
955
  content: [{ type: "text", text: JSON.stringify({ files: annotated, total_est_tokens }, null, 2) }],
798
956
  };
799
957
  });
800
- server.tool("files.search", "Full-text (SQLite FTS5) keyword search across files. Returns ranked matches with inline match_excerpt and title_highlight (no follow-up `read_file` needed for snippets) plus tags, est_tokens, size_bytes, content_class, and aggregate `total_est_tokens`. Read-only; no side effects, auth, or rate limits. Ordering: dictionary hits sort above everything else for the same query (dictionary-wins on conflict), then BM25 rank. FTS is tokenised: it WILL miss URLs, hyphenated terms, and partial substrings — fall back to `files.regex_search` for those. `project_id: null` searches only the KB; omit the field to span everything; `tags[]` requires ALL listed tags to match; `kind` narrows to one content class. For prompt-ready bundled bodies use `files.bundle_search`.", {
958
+ server.tool("files.search", "Full-text (SQLite FTS5) keyword search across files. Default mode returns ranked matches with inline match_excerpt and title_highlight (no follow-up `files.read` needed for snippets) plus tags, est_tokens, size_bytes, content_class, and aggregate `total_est_tokens`. Pass `include_bodies: true` to instead get a single prompt-ready bundle: matched bodies concatenated into XML `<document>` blocks or markdown headers + fences (see `format`/`max_tokens`), capped at the token budget — files are added in rank order until the next would exceed it, the rest going to `meta.skipped[]`. Use `include_bodies` instead of `files.search` + N×`files.read` when you need several related files as one context blob. Read-only; no side effects, auth, or rate limits. Ordering: dictionary hits sort above everything else for the same query (dictionary-wins on conflict), then BM25 rank. FTS is tokenised: it WILL miss URLs, hyphenated terms, and partial substrings — fall back to `files.regex_search` for those. `project_id: null` searches only the KB; omit the field to span everything; `tags[]` requires ALL listed tags to match; `kind` narrows to one content class.", {
801
959
  query: z.string().describe("Search query"),
802
960
  project_id: z.number().nullable().optional().describe("Filter by project ID. Pass null to search ONLY Knowledge Base files."),
803
961
  tags: z.array(z.string()).optional().describe("Filter by tags (all must match)"),
804
962
  favorite: z.boolean().optional().describe("Filter by favorite status"),
805
963
  kind: z.enum(["dictionary", "note", "journal", "project"]).optional()
806
964
  .describe("Filter by content class. dictionary = authoritative KB (system IDs, mappings, glossaries), note = informational KB, journal = time-log, project = project file. Omit to see all classes with dictionary-first ordering."),
807
- }, async ({ query, project_id, tags, favorite, kind }) => {
965
+ include_bodies: z.boolean().optional().describe("If true, return a single prompt-ready bundle of matched bodies instead of a match list. Response shape changes to `{bundle, meta: {included, skipped, ...}}`. Default false."),
966
+ format: z.enum(["xml", "markdown"]).optional().describe("Bundle format when `include_bodies` is true. xml = Anthropic-recommended <document> tags (default); markdown = ## headers + fenced blocks. Ignored otherwise."),
967
+ max_tokens: z.number().int().positive().optional().describe("Token budget when `include_bodies` is true (default 50000). Files added in rank order until the next would exceed; remainder go to `meta.skipped[]`. Ignored otherwise."),
968
+ }, async ({ query, project_id, tags, favorite, kind, include_bodies, format, max_tokens }) => {
808
969
  const filters = { query };
809
970
  if (project_id !== undefined)
810
971
  filters.project_id = project_id;
@@ -814,6 +975,21 @@ server.tool("files.search", "Full-text (SQLite FTS5) keyword search across files
814
975
  filters.favorite = favorite;
815
976
  if (kind !== undefined)
816
977
  filters.content_class = kind;
978
+ if (include_bodies) {
979
+ let bundleResult;
980
+ try {
981
+ bundleResult = await bundleSearch(filters, { format: format ?? "xml", max_tokens: max_tokens ?? 50000 });
982
+ }
983
+ catch (e) {
984
+ if (e instanceof FtsQueryError) {
985
+ return { isError: true, content: [{ type: "text", text: e.message }] };
986
+ }
987
+ throw e;
988
+ }
989
+ return {
990
+ content: [{ type: "text", text: JSON.stringify(bundleResult, null, 2) }],
991
+ };
992
+ }
817
993
  let result;
818
994
  try {
819
995
  result = search(filters);
@@ -830,42 +1006,7 @@ server.tool("files.search", "Full-text (SQLite FTS5) keyword search across files
830
1006
  content: [{ type: "text", text: JSON.stringify({ matches: annotated, total_est_tokens }, null, 2) }],
831
1007
  };
832
1008
  });
833
- server.tool("files.bundle_search", "Run an FTS search and concatenate matched bodies into a single prompt-ready bundle (XML `<document>` blocks or markdown headers + fences) capped at `max_tokens`. Files are added in rank order (dictionary-wins first, then BM25) until the next would exceed the budget; the rest go to `skipped[]`. Read-only; no side effects, auth, or rate limits. Use instead of `files.search` + N×`files.read` when you need several related files as one context blob. Defaults: format=xml, max_tokens=50000. `project_id: null` = KB only; `tags[]` requires ALL to match; `kind` narrows to one content class.", {
834
- query: z.string().describe("Full-text search query"),
835
- project_id: z.number().nullable().optional().describe("Filter by project ID. Pass null to bundle ONLY Knowledge Base files."),
836
- tags: z.array(z.string()).optional().describe("Filter by tags (all must match)"),
837
- favorite: z.boolean().optional().describe("Filter by favorite status"),
838
- format: z.enum(["xml", "markdown"]).default("xml")
839
- .describe("Bundle format. xml = Anthropic-recommended <document> tags; markdown = ## headers + fenced blocks"),
840
- max_tokens: z.number().int().positive().default(50000)
841
- .describe("Token budget. Files added in rank order until the next would exceed; remainder go to skipped[]"),
842
- kind: z.enum(["dictionary", "note", "journal", "project"]).optional()
843
- .describe("Filter by content class. dictionary = authoritative KB, note = informational KB, journal = time-log, project = project file."),
844
- }, async ({ query, project_id, tags, favorite, format, max_tokens, kind }) => {
845
- const filters = { query };
846
- if (project_id !== undefined)
847
- filters.project_id = project_id;
848
- if (tags !== undefined)
849
- filters.tags = tags;
850
- if (favorite !== undefined)
851
- filters.favorite = favorite;
852
- if (kind !== undefined)
853
- filters.content_class = kind;
854
- let result;
855
- try {
856
- result = await bundleSearch(filters, { format, max_tokens });
857
- }
858
- catch (e) {
859
- if (e instanceof FtsQueryError) {
860
- return { isError: true, content: [{ type: "text", text: e.message }] };
861
- }
862
- throw e;
863
- }
864
- return {
865
- content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
866
- };
867
- });
868
- server.tool("tags.add", "Append tags to ONE file. Additive — existing tags are preserved; re-adding an existing tag is a no-op (idempotent per tag). New tag names auto-create rows in the global `tags` table. Persists to local SQLite. No external auth or rate limits. Returns `{success: true}`; throws if file_id is unknown. Use to label a single file. To tag every file matching a query in one call use `tag_search_results`; to remove tags use `remove_tags`.", {
1009
+ server.tool("tags.add", "Append tags to ONE file. Additive — existing tags are preserved; re-adding an existing tag is a no-op (idempotent per tag). New tag names auto-create rows in the global `tags` table. Persists to local SQLite. No external auth or rate limits. Returns `{success: true}`; throws if file_id is unknown. Use to label a single file. To tag every file matching a query in one call use `tags.search`; to remove tags use `tags.remove`.", {
869
1010
  file_id: z.number().describe("File ID"),
870
1011
  tags: z.array(z.string()).describe("Array of tag names to add"),
871
1012
  }, async ({ file_id, tags }) => {
@@ -874,7 +1015,7 @@ server.tool("tags.add", "Append tags to ONE file. Additive — existing tags are
874
1015
  content: [{ type: "text", text: JSON.stringify({ success: true }, null, 2) }],
875
1016
  };
876
1017
  });
877
- server.tool("tags.remove", "Detach one or more tag IDs from ONE file. Destructive on the link only — does NOT delete the file or the global tag definition (orphan tags survive in `list_tags`). Idempotent: removing an already-absent tag is a no-op. No external auth or rate limits. Returns `{success: true}`. Note: takes tag IDs (integers), not names — fetch them via `list_tags`. To remove ALL tags from many files via a query, see `tag_search_results` (additive only) — there is no bulk-untag-by-query tool.", {
1018
+ server.tool("tags.remove", "Detach one or more tag IDs from ONE file. Destructive on the link only — does NOT delete the file or the global tag definition (orphan tags survive in `tags.list`). Idempotent: removing an already-absent tag is a no-op. No external auth or rate limits. Returns `{success: true}`. Note: takes tag IDs (integers), not names — fetch them via `tags.list`. To remove ALL tags from many files via a query, see `tags.search` (additive only) — there is no bulk-untag-by-query tool.", {
878
1019
  file_id: z.number().describe("File ID"),
879
1020
  tag_ids: z.array(z.number()).describe("Array of tag IDs to remove"),
880
1021
  }, async ({ file_id, tag_ids }) => {
@@ -883,7 +1024,7 @@ server.tool("tags.remove", "Detach one or more tag IDs from ONE file. Destructiv
883
1024
  content: [{ type: "text", text: JSON.stringify({ success: true }, null, 2) }],
884
1025
  };
885
1026
  });
886
- server.tool("tags.set_favorite", "Set or clear the favorite flag on one file (idempotent — re-setting the same value is a no-op; not a toggle, you pass the desired state). Persists to local SQLite. No external auth or rate limits. Returns `{success: true}`. Use to curate quick-access pins; `list_files`/`search`/`bundle_search` accept `favorite: true` to filter to the pinned set.", {
1027
+ server.tool("tags.set_favorite", "Set or clear the favorite flag on one file (idempotent — re-setting the same value is a no-op; not a toggle, you pass the desired state). Persists to local SQLite. No external auth or rate limits. Returns `{success: true}`. Use to curate quick-access pins; `files.list` / `files.search` accept `favorite: true` to filter to the pinned set.", {
887
1028
  file_id: z.number().describe("File ID"),
888
1029
  favorite: z.boolean().describe("Favorite status"),
889
1030
  }, async ({ file_id, favorite }) => {
@@ -892,13 +1033,13 @@ server.tool("tags.set_favorite", "Set or clear the favorite flag on one file (id
892
1033
  content: [{ type: "text", text: JSON.stringify({ success: true }, null, 2) }],
893
1034
  };
894
1035
  });
895
- server.tool("tags.list", "List every tag in the global SQLite database with id, name, and applied count. Read-only; no side effects, auth, or rate limits. Returns the entire taxonomy (not paginated). Use to discover existing labels before tagging (so you reuse rather than fork) or to find tag IDs to feed into `remove_tags`. For tags on a specific file, use `describe_file`.", {}, async () => {
1036
+ server.tool("tags.list", "List every tag in the global SQLite database with id, name, and applied count. Read-only; no side effects, auth, or rate limits. Returns the entire taxonomy (not paginated). Use to discover existing labels before tagging (so you reuse rather than fork) or to find tag IDs to feed into `tags.remove`. For tags on a specific file, use `files.describe`.", {}, async () => {
896
1037
  const result = listTags();
897
1038
  return {
898
1039
  content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
899
1040
  };
900
1041
  });
901
- server.tool("projects.list", "List every registered project with id, name, absolute path, and a derived `has_hands` flag (true when the path exists on disk AND contains a `kontexta.json`). Read-only; no side effects, auth, or rate limits. Use to find the project_id to pass to scoped tools (`search`, `list_files`, `commit_backup`, `refresh_index`, etc.). To register a new project use `register_project`; to inspect its Hands tools use `list_hands`.", {}, async () => {
1042
+ server.tool("projects.list", "List every registered project with id, name, absolute path, and a derived `has_hands` flag (true when the path exists on disk AND contains a `kontexta.json`). Read-only; no side effects, auth, or rate limits. Use to find the project_id to pass to scoped tools (`files.search`, `files.list`, `admin.commit_backup`, `projects.refresh_index`, etc.). To register a new project use `projects.register`; to inspect its Hands tools use `hands.list`.", {}, async () => {
902
1043
  const result = listProjects();
903
1044
  const augmented = result.map((p) => {
904
1045
  const has_hands = !!(p.path && existsSync(p.path) && existsSync(`${p.path}/kontexta.json`));
@@ -1329,7 +1470,7 @@ function repoDirForFile(file) {
1329
1470
  }
1330
1471
  return dataDir;
1331
1472
  }
1332
- server.tool("files.get_history", "Return the git commit history for one file (newest first), each entry with hash, message, date, and author. Reads the file's owning repo: the project's git repo for project files, the KB backup repo for KB files. Read-only; no side effects, auth, or rate limits. Returns `{file_id, path, history}`; an empty array means the file has not been committed yet. Use to understand a file's evolution before editing or restoring. Pair with `get_diff` to see exact line changes; use `restore_file` to roll back.", {
1473
+ server.tool("files.get_history", "Return the git commit history for one file (newest first), each entry with hash, message, date, and author. Reads the file's owning repo: the project's git repo for project files, the KB backup repo for KB files. Read-only; no side effects, auth, or rate limits. Returns `{file_id, path, history}`; an empty array means the file has not been committed yet. Use to understand a file's evolution before editing or restoring. Pair with `files.get_diff` to see exact line changes; use `files.restore` to roll back.", {
1333
1474
  file_id: z.number().describe("ID of the file"),
1334
1475
  }, async ({ file_id }) => {
1335
1476
  const file = readFile(file_id);
@@ -1343,7 +1484,7 @@ server.tool("files.get_history", "Return the git commit history for one file (ne
1343
1484
  ],
1344
1485
  };
1345
1486
  });
1346
- server.tool("files.get_diff", "Return the unified diff of one file between two commit hashes (typically obtained from `get_history` for the same file). Read-only; no side effects, auth, or rate limits. Order matters — `commit_a` is treated as the earlier side; reversing the args inverts the diff. Throws if either hash is unknown to the file's repo. Use after `get_history` to see WHAT changed, not just THAT it changed.", {
1487
+ server.tool("files.get_diff", "Return the unified diff of one file between two commit hashes (typically obtained from `files.get_history` for the same file). Read-only; no side effects, auth, or rate limits. Order matters — `commit_a` is treated as the earlier side; reversing the args inverts the diff. Throws if either hash is unknown to the file's repo. Use after `files.get_history` to see WHAT changed, not just THAT it changed.", {
1347
1488
  file_id: z.number().describe("ID of the file"),
1348
1489
  commit_a: z.string().describe("Earlier commit hash (from get_history)"),
1349
1490
  commit_b: z.string().describe("Later commit hash (from get_history)"),
@@ -1359,7 +1500,7 @@ server.tool("files.get_diff", "Return the unified diff of one file between two c
1359
1500
  ],
1360
1501
  };
1361
1502
  });
1362
- server.tool("files.restore", "DESTRUCTIVE. Overwrite a file's current on-disk content with the version recorded at a specific git commit, then re-index FTS. The hash MUST come from `get_history` for THIS file (foreign hashes throw). The current uncommitted content is lost unless it was already committed elsewhere. The file watcher may also pick up the change before this returns. No external auth or rate limits. Returns `{file_id, path, hash, success, message}`. Use only to undo accidental edits or recover a known-good version.", {
1503
+ server.tool("files.restore", "DESTRUCTIVE. Overwrite a file's current on-disk content with the version recorded at a specific git commit, then re-index FTS. The hash MUST come from `files.get_history` for THIS file (foreign hashes throw). The current uncommitted content is lost unless it was already committed elsewhere. The file watcher may also pick up the change before this returns. No external auth or rate limits. Returns `{file_id, path, hash, success, message}`. Use only to undo accidental edits or recover a known-good version.", {
1363
1504
  file_id: z.number().describe("ID of the file"),
1364
1505
  hash: z.string().describe("Commit hash to restore from (from get_history)"),
1365
1506
  }, async ({ file_id, hash }) => {
@@ -1388,7 +1529,7 @@ server.tool("files.restore", "DESTRUCTIVE. Overwrite a file's current on-disk co
1388
1529
  };
1389
1530
  }
1390
1531
  });
1391
- server.tool("files.read_outline", "Return a flat list of markdown headings for one file (level, text, line, byteStart, byteEnd). Read-only; no side effects, auth, or rate limits. Use as a cheap probe before `read_section` or `update_file_section` so you don't spend tokens on the full body just to learn what sections exist. Empty outline means the file has no markdown headings (it may still have content — fall back to `read_file` or `read_file_lines`).", {
1532
+ server.tool("files.read_outline", "Return a flat list of markdown headings for one file (level, text, line, byteStart, byteEnd). Read-only; no side effects, auth, or rate limits. Use as a cheap probe before `files.read({ id, section })` or `files.update({ file_id, section, content })` so you don't spend tokens on the full body just to learn what sections exist. Empty outline means the file has no markdown headings (it may still have content — fall back to `files.read` in full or `files.read({ id, lines })`).", {
1392
1533
  file_id: z.number().describe("File ID"),
1393
1534
  }, async ({ file_id }) => {
1394
1535
  try {
@@ -1416,66 +1557,6 @@ server.tool("files.read_outline", "Return a flat list of markdown headings for o
1416
1557
  };
1417
1558
  }
1418
1559
  });
1419
- server.tool("files.read_section", "Return the body of ONE heading (the heading line itself is excluded) plus level, line, size_bytes, and est_tokens. Heading match is case-insensitive but exact-string after trim — fuzzy / partial matches do NOT resolve. Returns isError if the heading is absent. Read-only; no side effects, auth, or rate limits. Pair with `read_file_outline` when you are unsure which headings exist; for non-heading line ranges use `read_file_lines`.", {
1420
- file_id: z.number().describe("File ID"),
1421
- heading: z.string().describe("Heading text to extract (case-insensitive)"),
1422
- }, async ({ file_id, heading }) => {
1423
- try {
1424
- const file = readFile(file_id);
1425
- const node = findSection(file.content, heading);
1426
- if (!node) {
1427
- return {
1428
- isError: true,
1429
- content: [{ type: "text", text: JSON.stringify({ error: `Section not found: ${heading}` }, null, 2) }],
1430
- };
1431
- }
1432
- const buf = Buffer.from(file.content, "utf8");
1433
- const body = buf.subarray(node.contentStart, node.contentEnd).toString("utf8");
1434
- return {
1435
- content: [
1436
- {
1437
- type: "text",
1438
- text: JSON.stringify({
1439
- file_id,
1440
- path: file.path,
1441
- heading: node.text,
1442
- level: node.level,
1443
- line: node.line,
1444
- content: body,
1445
- size_bytes: Buffer.byteLength(body, "utf8"),
1446
- est_tokens: estimateTokensFromBuffer(Buffer.from(body, "utf8")),
1447
- }, null, 2),
1448
- },
1449
- ],
1450
- };
1451
- }
1452
- catch (e) {
1453
- return {
1454
- isError: true,
1455
- content: [{ type: "text", text: JSON.stringify({ error: e?.message ?? String(e) }, null, 2) }],
1456
- };
1457
- }
1458
- });
1459
- server.tool("files.update_section", "Surgical write — replace the body of ONE heading without touching siblings. The heading line itself is preserved verbatim; only its body is rewritten. Persists via the same path as `update_file` (writes to disk → FTS reindex → git commit). Throws if the heading does not exist (this tool will NOT create a new section — append the section text via `update_file` first). Heading match is case-insensitive exact-string. No external auth or rate limits. Returns the updated file metadata. Use to make targeted edits without re-sending the whole body; for full-file replacement use `update_file`.", {
1460
- file_id: z.number().describe("File ID"),
1461
- heading: z.string().describe("Heading whose body to replace (case-insensitive)"),
1462
- content: z.string().describe("New body content (heading line is preserved automatically)"),
1463
- }, async ({ file_id, heading, content }) => {
1464
- try {
1465
- const file = readFile(file_id);
1466
- const updated = replaceSection(file.content, heading, content);
1467
- const result = await updateFile(file_id, updated, dataDir);
1468
- return {
1469
- content: [{ type: "text", text: JSON.stringify(annotateTokens(result), null, 2) }],
1470
- };
1471
- }
1472
- catch (e) {
1473
- return {
1474
- isError: true,
1475
- content: [{ type: "text", text: JSON.stringify({ error: e?.message ?? String(e) }, null, 2) }],
1476
- };
1477
- }
1478
- });
1479
1560
  function resolveFolderBase(projectId) {
1480
1561
  if (projectId === undefined || projectId === null) {
1481
1562
  return join(dataDir, "knowledge");
@@ -1501,7 +1582,7 @@ function validateFolderName(name) {
1501
1582
  throw new Error("name must not contain '..' segments");
1502
1583
  }
1503
1584
  }
1504
- server.tool("folders.list", "List folder paths under a project root (or the Knowledge Base when `project_id` is null/omitted). Returns `{folders: string[], base_path}` where `folders` are RELATIVE to `base_path`. Read-only; no side effects, auth, or rate limits. Throws if `project_id` references an unknown project. Use to discover where to drop a new file via `create_file`'s `folder` argument or to navigate vault structure; to actually create one use `create_folder`.", {
1585
+ server.tool("folders.list", "List folder paths under a project root (or the Knowledge Base when `project_id` is null/omitted). Returns `{folders: string[], base_path}` where `folders` are RELATIVE to `base_path`. Read-only; no side effects, auth, or rate limits. Throws if `project_id` references an unknown project. Use to discover where to drop a new file via `files.create`'s `folder` argument or to navigate vault structure; to actually create one use `folders.create`.", {
1505
1586
  project_id: z.number().nullable().optional().describe("Project ID. Pass null or omit to list KB folders."),
1506
1587
  }, async ({ project_id }) => {
1507
1588
  try {
@@ -1538,7 +1619,7 @@ server.tool("folders.create", "Create a folder under a project root or the KB. I
1538
1619
  };
1539
1620
  }
1540
1621
  });
1541
- server.tool("folders.delete", "DESTRUCTIVE — recursively delete a folder under the KB AND every file inside it (disk + FTS rows). REFUSES (returns isError) when `project_id` is supplied: deleting inside a registered project would race the file watcher and re-ingest the contents — remove project content via your editor instead. Same name validation as `create_folder`. Not recoverable from Kontexta after the call (only the git backup, if configured, retains it). No external auth or rate limits. Returns `{success: true}`.", {
1622
+ server.tool("folders.delete", "DESTRUCTIVE — recursively delete a folder under the KB AND every file inside it (disk + FTS rows). REFUSES (returns isError) when `project_id` is supplied: deleting inside a registered project would race the file watcher and re-ingest the contents — remove project content via your editor instead. Same name validation as `folders.create`. Not recoverable from Kontexta after the call (only the git backup, if configured, retains it). No external auth or rate limits. Returns `{success: true}`.", {
1542
1623
  project_id: z.number().nullable().optional().describe("Project ID. Pass null or omit to delete from the KB. Project IDs are rejected."),
1543
1624
  name: z.string().describe("Folder name (relative)"),
1544
1625
  }, async ({ project_id, name }) => {
@@ -1695,84 +1776,6 @@ server.tool("files.find_related", "Find other files sharing tags with the given
1695
1776
  ],
1696
1777
  };
1697
1778
  });
1698
- server.tool("files.create_many", "Batch variant of `files.create` — create up to 200 markdown, mermaid, or HTML files in one call. Each item follows the same rules: `project_id` required if `destination` is `project`/`kontexta`; `kind` ('dictionary' or 'note') required if `destination` is `knowledge`. SIDE EFFECTS: writes new files to disk and inserts FTS5 rows; missing folders are mkdir'd. Per-item failures are isolated to `errors[]` and the rest of the batch still commits — partial success is the norm, always inspect `error_count`. No external auth or rate limits. Returns `{created_count, error_count, created, errors}`. Use for bulk ingestion; for >200 items, page yourself. Pass format='mmd' on an item to create a Mermaid diagram file (.mmd) or 'html' for HTML reports; defaults to 'md'.", {
1699
- files: z
1700
- .array(z.object({
1701
- title: z.string().describe("File title."),
1702
- content: z.string().describe("File body content (markdown, mermaid, or HTML depending on format)."),
1703
- destination: z.enum(["knowledge", "project", "kontexta"]).describe("Storage destination: 'knowledge' for KB, 'project' for a project, 'kontexta' for app-internal."),
1704
- project_id: z.number().optional().describe("Project ID — required when destination is 'project' or 'kontexta'."),
1705
- folder: z.string().optional().describe("Relative folder path within the destination (e.g. 'notes/daily')."),
1706
- tags: z.array(z.string()).optional().describe("Tags to apply to this file."),
1707
- format: z.enum(["md", "mmd", "html"]).optional().describe("File format: 'md' (default), 'mmd' (Mermaid diagram), or 'html' (report)."),
1708
- kind: z.enum(["dictionary", "note"]).optional()
1709
- .describe("REQUIRED per-item for destination='knowledge'. See files.create for the dictionary/note rubric."),
1710
- }))
1711
- .min(1)
1712
- .max(200)
1713
- .describe("Files to create (max 200 per call)"),
1714
- }, async ({ files }) => {
1715
- const created = [];
1716
- const errors = [];
1717
- for (let i = 0; i < files.length; i++) {
1718
- const f = files[i];
1719
- try {
1720
- const resolved = resolveKindFolder({ destination: f.destination, folder: f.folder, kind: f.kind });
1721
- if ("error" in resolved) {
1722
- errors.push({ index: i, title: f.title, error: resolved.error });
1723
- continue;
1724
- }
1725
- const result = await createFile({
1726
- title: f.title,
1727
- content: f.content,
1728
- destination: f.destination,
1729
- projectId: f.project_id,
1730
- folder: resolved.folder,
1731
- tags: f.tags,
1732
- dataDir,
1733
- format: f.format,
1734
- });
1735
- const payload = annotateTokens(result);
1736
- if (resolved.warning)
1737
- payload.warning = resolved.warning;
1738
- created.push(payload);
1739
- }
1740
- catch (e) {
1741
- errors.push({ index: i, title: f.title, error: e?.message ?? String(e) });
1742
- }
1743
- }
1744
- return {
1745
- content: [
1746
- {
1747
- type: "text",
1748
- text: JSON.stringify({ created_count: created.length, error_count: errors.length, created, errors }, null, 2),
1749
- },
1750
- ],
1751
- };
1752
- });
1753
- server.tool("files.delete_many", "DESTRUCTIVE batch — delete up to 500 files by ID in one call. Same physical-deletion rules as `files.delete` (KB files unlinked from disk; project reference files only de-indexed). Per-ID failures isolated to `errors[]`; the batch keeps going — partial success is the norm. Not idempotent — unknown IDs surface as per-item errors. No external auth or rate limits. Returns `{deleted_count, error_count, deleted, errors}`. To preview the set before deleting, run `files.list` with the same filter and confirm the IDs.", {
1754
- ids: z.array(z.number()).min(1).max(500).describe("File IDs to delete (max 500 per call)"),
1755
- }, async ({ ids }) => {
1756
- const deleted = [];
1757
- const errors = [];
1758
- for (const id of ids) {
1759
- try {
1760
- await deleteFile(id, dataDir);
1761
- deleted.push(id);
1762
- }
1763
- catch (e) {
1764
- errors.push({ id, error: e?.message ?? String(e) });
1765
- }
1766
- }
1767
- return {
1768
- content: [
1769
- {
1770
- type: "text",
1771
- text: JSON.stringify({ deleted_count: deleted.length, error_count: errors.length, deleted, errors }, null, 2),
1772
- },
1773
- ],
1774
- };
1775
- });
1776
1779
  server.tool("tags.search", "Bulk-tag — run an FTS `search` and append `add_tags` to every matching file in one call. Side effect: each match gets `addTags` applied (additive, idempotent per tag); the matched files themselves are NOT modified beyond their tag links. Per-file failures isolated to `errors[]`. No external auth or rate limits. There is NO dry-run flag, so ALWAYS run `files.search` with the same query first to verify the match set before tagging. The `tags[]` filter requires existing tags to ALL match (it scopes the search; it does not control which tags get added). Returns `{matched_count, tagged_count, tags_applied, tagged_ids, errors}`.", {
1777
1780
  query: z.string().describe("Full-text search query"),
1778
1781
  add_tags: z.array(z.string()).min(1).describe("Tags to add to every matching file"),
@@ -1823,47 +1826,56 @@ server.tool("tags.search", "Bulk-tag — run an FTS `search` and append `add_tag
1823
1826
  ],
1824
1827
  };
1825
1828
  });
1826
- server.tool("files.read_by_path", "Look up a file by its absolute on-disk path and return the same shape as `files.read`. The path must EXACTLY match what Kontexta indexed — no symlink resolution, no path normalisation beyond what the OS does, no trailing-slash tolerance. Returns isError if no row matches (the file may exist on disk but not be indexed — try `projects.refresh_index`). Read-only; no side effects, auth, or rate limits. Use when an agent has a path from its working directory but no file ID; if you have the ID, prefer `files.read`.", {
1827
- path: z.string().describe("Absolute path on disk (must match the path stored in Kontexta)"),
1828
- }, async ({ path }) => {
1829
- try {
1830
- if (typeof path !== "string" || path.length === 0) {
1831
- throw new Error("path is required");
1829
+ server.tool("admin.overview", "Vault-state snapshot. `mode: 'stats'` = aggregate counts for a scope: `file_count`, `untagged_count`, `favorite_count`, `top_tags`. With `project_id` omitted (everything), also returns `by_project` breakdown. `include_token_total: true` stat()s every matching file on disk to compute a body-size estimate — measurably slower on large vaults; default false. `mode: 'whats_new'` = list files created or modified since a checkpoint (`since`, REQUIRED for this mode — ISO-8601 like `2025-01-15T00:00:00Z` or relative durations like `1h`/`7d`/`2w`; invalid formats throw); CAVEAT: hard-deleted files are NOT surfaced, only mtime-driven changes. Both modes: `project_id: null` = KB only; omit = everything. Read-only; no side effects, auth, or rate limits. Use `stats` as a cheap dashboard or to spot untagged content for cleanup (for live disk-vs-index drift use `files.diff_against_disk`); use `whats_new` at session start to catch up.", {
1830
+ mode: z.enum(["stats", "whats_new"]).describe("Which snapshot to return. 'whats_new' requires `since`."),
1831
+ project_id: z.number().nullable().optional().describe("Filter to a single project. Pass null for KB-only. Omit for everything."),
1832
+ top_tags: z.number().int().positive().max(100).optional().describe("mode='stats' only: how many top tags to return (default 10)"),
1833
+ include_token_total: z.boolean().optional().describe("mode='stats' only: if true, stat every matching file on disk to compute total est_tokens. Default false (cheap)."),
1834
+ since: z.string().optional().describe("REQUIRED for mode='whats_new'. ISO 8601 timestamp or relative duration (e.g. \"1h\", \"7d\", \"2w\")."),
1835
+ include_tags: z.boolean().optional().describe("mode='whats_new' only: attach tags[] to each file. Default true."),
1836
+ limit: z.number().optional().describe("mode='whats_new' only: max files returned. Default 200."),
1837
+ }, async ({ mode, project_id, top_tags, include_token_total, since, include_tags, limit }) => {
1838
+ if (mode === "whats_new") {
1839
+ if (!since) {
1840
+ return { isError: true, content: [{ type: "text", text: JSON.stringify({ error: "mode='whats_new' requires `since`" }, null, 2) }] };
1832
1841
  }
1833
- const row = getDatabase()
1834
- .prepare("SELECT id FROM files WHERE path = ?")
1835
- .get(path);
1836
- if (!row) {
1842
+ try {
1843
+ const opts = { since };
1844
+ if (project_id !== undefined)
1845
+ opts.project_id = project_id;
1846
+ if (include_tags !== undefined)
1847
+ opts.include_tags = include_tags;
1848
+ if (limit !== undefined)
1849
+ opts.limit = limit;
1850
+ const result = whatsNew(opts);
1851
+ const annotated = result.files.map(annotateTokens);
1852
+ const total_est_tokens = annotated.reduce((s, f) => s + (f.est_tokens ?? 0), 0);
1837
1853
  return {
1838
- isError: true,
1839
1854
  content: [
1840
1855
  {
1841
1856
  type: "text",
1842
- text: JSON.stringify({ error: `No file indexed at path: ${path}` }, null, 2),
1857
+ text: JSON.stringify({
1858
+ since: result.since,
1859
+ until: result.until,
1860
+ count: result.count,
1861
+ total_est_tokens,
1862
+ files: annotated,
1863
+ }, null, 2),
1843
1864
  },
1844
1865
  ],
1845
1866
  };
1846
1867
  }
1847
- const result = readFile(row.id);
1848
- return {
1849
- content: [{ type: "text", text: JSON.stringify(annotateTokens(result), null, 2) }],
1850
- };
1851
- }
1852
- catch (e) {
1853
- return {
1854
- isError: true,
1855
- content: [{ type: "text", text: JSON.stringify({ error: e?.message ?? String(e) }, null, 2) }],
1856
- };
1868
+ catch (e) {
1869
+ return {
1870
+ isError: true,
1871
+ content: [{ type: "text", text: JSON.stringify({ error: e.message }, null, 2) }],
1872
+ };
1873
+ }
1857
1874
  }
1858
- });
1859
- server.tool("admin.stats", "Aggregate counts for a scope: `file_count`, `untagged_count`, `favorite_count`, `top_tags`. With `project_id` omitted (everything), also returns `by_project` breakdown. `include_token_total: true` stat()s every matching file on disk to compute a body-size estimate — measurably slower on large vaults; default false. `project_id: null` = KB only; omit = all. Read-only; no side effects, auth, or rate limits. Use as a cheap dashboard or to spot untagged content for cleanup; for live disk-vs-index drift use `files.diff_against_disk`.", {
1860
- project_id: z.number().nullable().optional().describe("Filter to a single project. Pass null for KB-only. Omit for everything."),
1861
- top_tags: z.number().int().positive().max(100).optional().describe("How many top tags to return (default 10)"),
1862
- include_token_total: z.boolean().optional().describe("If true, stat every matching file on disk to compute total est_tokens. Default false (cheap)."),
1863
- }, async ({ project_id, top_tags, include_token_total }) => {
1875
+ // mode === "stats"
1864
1876
  try {
1865
1877
  const db = getDatabase();
1866
- const limit = top_tags ?? 10;
1878
+ const limitTags = top_tags ?? 10;
1867
1879
  let scopeWhere = "";
1868
1880
  const scopeParams = [];
1869
1881
  if (project_id === null) {
@@ -1891,7 +1903,7 @@ server.tool("admin.stats", "Aggregate counts for a scope: `file_count`, `untagge
1891
1903
  GROUP BY t.id
1892
1904
  ORDER BY count DESC, t.name ASC
1893
1905
  LIMIT ?`)
1894
- .all(...scopeParams, limit);
1906
+ .all(...scopeParams, limitTags);
1895
1907
  const byProject = project_id === undefined
1896
1908
  ? db
1897
1909
  .prepare(`SELECT p.id, p.name, COUNT(files.id) AS files
@@ -2153,45 +2165,6 @@ server.tool("projects.refresh_index", "Reconcile the FTS index against disk. For
2153
2165
  };
2154
2166
  }
2155
2167
  });
2156
- server.tool("admin.whats_new", "List files created or modified since a checkpoint. `since` accepts ISO-8601 (`2025-01-15T00:00:00Z`) or relative durations (`1h`, `7d`, `2w`); invalid formats throw. Read-only; no side effects, auth, or rate limits. Returns annotated rows plus aggregate `total_est_tokens` so you can decide what to read next. CAVEAT: hard-deleted files are NOT surfaced — only mtime-driven changes. Defaults: include_tags=true, limit=200. `project_id: null` = KB only; omit = everything. Use at session start to catch up.", {
2157
- since: z.string().describe("ISO 8601 timestamp or relative duration (e.g. \"1h\", \"7d\", \"2w\")."),
2158
- project_id: z.number().nullable().optional().describe("Filter to a single project. Pass null for knowledge-base-only files. Omit for all."),
2159
- include_tags: z.boolean().optional().describe("Attach tags[] to each file. Default true."),
2160
- limit: z.number().optional().describe("Max files returned. Default 200."),
2161
- }, async ({ since, project_id, include_tags, limit }) => {
2162
- try {
2163
- const opts = { since };
2164
- if (project_id !== undefined)
2165
- opts.project_id = project_id;
2166
- if (include_tags !== undefined)
2167
- opts.include_tags = include_tags;
2168
- if (limit !== undefined)
2169
- opts.limit = limit;
2170
- const result = whatsNew(opts);
2171
- const annotated = result.files.map(annotateTokens);
2172
- const total_est_tokens = annotated.reduce((s, f) => s + (f.est_tokens ?? 0), 0);
2173
- return {
2174
- content: [
2175
- {
2176
- type: "text",
2177
- text: JSON.stringify({
2178
- since: result.since,
2179
- until: result.until,
2180
- count: result.count,
2181
- total_est_tokens,
2182
- files: annotated,
2183
- }, null, 2),
2184
- },
2185
- ],
2186
- };
2187
- }
2188
- catch (e) {
2189
- return {
2190
- isError: true,
2191
- content: [{ type: "text", text: JSON.stringify({ error: e.message }, null, 2) }],
2192
- };
2193
- }
2194
- });
2195
2168
  server.tool("projects.map", "Return a compact indented outline of folders, file titles, tags, and IDs in a single dense block — substantially fewer tokens than the equivalent `files.list` JSON for the same scope. Read-only; no side effects, auth, or rate limits. Capped at `max_lines` (default 5000); the response reports `est_tokens` and emits a `warning` field if it exceeds `KONTEXTA_PROJECT_TOKEN_WARN`. `project_id: null` = KB only; omit = everything. Defaults: include_tags=true, show_titles=true. Use to orient yourself in an unfamiliar vault or project; for keyword lookup use `files.search`.", {
2196
2169
  project_id: z.number().nullable().optional().describe("Restrict to a single project. Pass null for knowledge-base-only files. Omit for everything."),
2197
2170
  include_tags: z.boolean().optional().describe("Append #tags inline. Default true. Set false to shrink the outline."),
@@ -2271,11 +2244,16 @@ server.resource("File Content", new ResourceTemplate("kontexta://files/{id}", {
2271
2244
  ],
2272
2245
  };
2273
2246
  });
2274
- server.tool("hands.list", "List every Hands command tool currently registered, with project scope, tool name, danger level, confirmation flag, and description. Hands tools come from per-project `kontexta.json` files loaded at register time. Read-only; no side effects, auth, or rate limits. Use to discover what side-effectful project commands the agent is permitted to run; for the `kontexta.json` schema see `hands.describe_schema`; reload after editing one with `hands.reload`.", {}, async () => {
2247
+ server.tool("hands.list", "List every Hands command tool currently registered, with project scope, tool name, danger level, confirmation flag, and description. Hands tools come from per-project `kontexta.json` files loaded at register time. Pass `schema: true` to instead get the complete `kontexta.json` authoring reference (JSON schema, validation rules, security guarantees, limitations, annotated example) — a static document, unrelated to any specific registered hand. Read-only; no side effects, auth, or rate limits. Use the default list mode to discover what side-effectful project commands the agent is permitted to run; use `schema: true` when helping a user write or fix a `kontexta.json`; reload after editing one with `hands.reload`.", {
2248
+ schema: z.boolean().optional().describe("If true, return the kontexta.json authoring reference document instead of the registered-hands list. Default false."),
2249
+ }, async ({ schema }) => {
2250
+ if (schema) {
2251
+ return { content: [{ type: "text", text: buildSchemaDoc() }] };
2252
+ }
2275
2253
  const items = handsRegistry.list();
2276
2254
  return { content: [{ type: "text", text: JSON.stringify({ hands: items }, null, 2) }] };
2277
2255
  });
2278
- server.tool("hands.reload", "Re-scan every registered project's `kontexta.json` and rebuild the live Hands tool registry — newly-declared tools become callable immediately, removed tools disappear from `tools/list`. SIDE EFFECT is on the running MCP session's tool inventory only (no disk writes). Idempotent. No external auth or rate limits. Takes no parameters. Returns per-project load results (counts of registered/disabled tools and any validation warnings). Use after editing a `kontexta.json` mid-session; for the schema see `hands.describe_schema`.", {}, async () => {
2256
+ server.tool("hands.reload", "Re-scan every registered project's `kontexta.json` and rebuild the live Hands tool registry — newly-declared tools become callable immediately, removed tools disappear from `tools/list`. SIDE EFFECT is on the running MCP session's tool inventory only (no disk writes). Idempotent. No external auth or rate limits. Takes no parameters. Returns per-project load results (counts of registered/disabled tools and any validation warnings). Use after editing a `kontexta.json` mid-session; for the schema see `hands.list({ schema: true })`.", {}, async () => {
2279
2257
  const projects = listProjects()
2280
2258
  .filter((p) => p.path && existsSync(p.path))
2281
2259
  .map((p) => ({ name: p.name, root: p.path }));
@@ -2295,7 +2273,6 @@ server.tool("hands.confirm", "Approve and EXECUTE a previously-issued Hands invo
2295
2273
  return { content: [{ type: "text", text: `Execution failed after approval: ${e?.message ?? e}` }] };
2296
2274
  }
2297
2275
  });
2298
- server.tool("hands.describe_schema", "Return the complete authoring reference for `kontexta.json`: JSON schema, validation rules, security guarantees, limitations, and an annotated example. Static document — does not read any project file or DB row. Read-only; no side effects, auth, or rate limits. Takes no parameters. Use when helping a user write or fix a `kontexta.json`; to see the loaded tools themselves use `hands.list`; to apply edits use `hands.reload`.", {}, async () => ({ content: [{ type: "text", text: buildSchemaDoc() }] }));
2299
2276
  server.tool("admin.get_profile", "Return the user profile stored in the Knowledge Base. The profile helps AI agents understand the user's context, role, preferences, and goals. Read-only; no side effects, auth, or rate limits. Returns existence status, full content, list of missing required sections, and a hint for new users. Use at session start to understand who you're working with.", {}, async () => {
2300
2277
  const result = handleGetProfile(dataDir);
2301
2278
  return {