@bevel-software/platform-core-backend 0.23.0 → 0.24.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 (227) hide show
  1. package/dist/core/create-core-server.d.ts.map +1 -1
  2. package/dist/core/create-core-server.js +17 -3
  3. package/dist/core/create-core-server.js.map +1 -1
  4. package/dist/core/create-core-services.d.ts +3 -0
  5. package/dist/core/create-core-services.d.ts.map +1 -1
  6. package/dist/core/create-core-services.js +25 -1
  7. package/dist/core/create-core-services.js.map +1 -1
  8. package/dist/core/lifecycle.d.ts +12 -0
  9. package/dist/core/lifecycle.d.ts.map +1 -1
  10. package/dist/core/lifecycle.js +10 -0
  11. package/dist/core/lifecycle.js.map +1 -1
  12. package/dist/core-config.d.ts +16 -0
  13. package/dist/core-config.d.ts.map +1 -1
  14. package/dist/core-config.js +17 -0
  15. package/dist/core-config.js.map +1 -1
  16. package/dist/index.d.ts +3 -2
  17. package/dist/index.d.ts.map +1 -1
  18. package/dist/index.js +10 -2
  19. package/dist/index.js.map +1 -1
  20. package/dist/modules/access/access.routes.d.ts.map +1 -1
  21. package/dist/modules/access/access.routes.js +4 -1
  22. package/dist/modules/access/access.routes.js.map +1 -1
  23. package/dist/modules/access/directory-sync-bot.d.ts.map +1 -1
  24. package/dist/modules/access/directory-sync-bot.js +7 -3
  25. package/dist/modules/access/directory-sync-bot.js.map +1 -1
  26. package/dist/modules/agent-instructions/agent-instructions.routes.d.ts +8 -1
  27. package/dist/modules/agent-instructions/agent-instructions.routes.d.ts.map +1 -1
  28. package/dist/modules/agent-instructions/agent-instructions.routes.js +8 -2
  29. package/dist/modules/agent-instructions/agent-instructions.routes.js.map +1 -1
  30. package/dist/modules/agent-instructions/compose.d.ts +38 -6
  31. package/dist/modules/agent-instructions/compose.d.ts.map +1 -1
  32. package/dist/modules/agent-instructions/compose.js +39 -6
  33. package/dist/modules/agent-instructions/compose.js.map +1 -1
  34. package/dist/modules/agent-instructions/index.d.ts +2 -1
  35. package/dist/modules/agent-instructions/index.d.ts.map +1 -1
  36. package/dist/modules/agent-instructions/index.js +2 -1
  37. package/dist/modules/agent-instructions/index.js.map +1 -1
  38. package/dist/modules/agent-instructions/shared-file-rules.d.ts +115 -0
  39. package/dist/modules/agent-instructions/shared-file-rules.d.ts.map +1 -0
  40. package/dist/modules/agent-instructions/shared-file-rules.js +272 -0
  41. package/dist/modules/agent-instructions/shared-file-rules.js.map +1 -0
  42. package/dist/modules/audit/agent-audit.service.d.ts.map +1 -1
  43. package/dist/modules/audit/agent-audit.service.js +4 -2
  44. package/dist/modules/audit/agent-audit.service.js.map +1 -1
  45. package/dist/modules/auth/account-erasure.service.d.ts.map +1 -1
  46. package/dist/modules/auth/account-erasure.service.js +57 -16
  47. package/dist/modules/auth/account-erasure.service.js.map +1 -1
  48. package/dist/modules/auth/auth.service.d.ts.map +1 -1
  49. package/dist/modules/auth/auth.service.js +25 -15
  50. package/dist/modules/auth/auth.service.js.map +1 -1
  51. package/dist/modules/code-mode/code-mode.tool.d.ts +20 -2
  52. package/dist/modules/code-mode/code-mode.tool.d.ts.map +1 -1
  53. package/dist/modules/code-mode/code-mode.tool.js +66 -35
  54. package/dist/modules/code-mode/code-mode.tool.js.map +1 -1
  55. package/dist/modules/database/connection.d.ts +16 -0
  56. package/dist/modules/database/connection.d.ts.map +1 -1
  57. package/dist/modules/database/connection.js +117 -0
  58. package/dist/modules/database/connection.js.map +1 -1
  59. package/dist/modules/database/core-schema.d.ts +296 -96
  60. package/dist/modules/database/core-schema.d.ts.map +1 -1
  61. package/dist/modules/database/core-schema.js +81 -31
  62. package/dist/modules/database/core-schema.js.map +1 -1
  63. package/dist/modules/database/migrate.d.ts +8 -0
  64. package/dist/modules/database/migrate.d.ts.map +1 -1
  65. package/dist/modules/database/migrate.js +271 -1
  66. package/dist/modules/database/migrate.js.map +1 -1
  67. package/dist/modules/mcp/mcp.service.d.ts +8 -0
  68. package/dist/modules/mcp/mcp.service.d.ts.map +1 -1
  69. package/dist/modules/mcp/mcp.service.js +38 -8
  70. package/dist/modules/mcp/mcp.service.js.map +1 -1
  71. package/dist/modules/plugins/join-request-records.store.d.ts.map +1 -1
  72. package/dist/modules/plugins/join-request-records.store.js +7 -4
  73. package/dist/modules/plugins/join-request-records.store.js.map +1 -1
  74. package/dist/modules/tool-auth/external-api-key.service.d.ts.map +1 -1
  75. package/dist/modules/tool-auth/external-api-key.service.js +8 -2
  76. package/dist/modules/tool-auth/external-api-key.service.js.map +1 -1
  77. package/dist/modules/tool-manuals/tool-manuals.tools.d.ts.map +1 -1
  78. package/dist/modules/tool-manuals/tool-manuals.tools.js +42 -31
  79. package/dist/modules/tool-manuals/tool-manuals.tools.js.map +1 -1
  80. package/dist/modules/tool-registry/description-length.d.ts +80 -0
  81. package/dist/modules/tool-registry/description-length.d.ts.map +1 -0
  82. package/dist/modules/tool-registry/description-length.js +108 -0
  83. package/dist/modules/tool-registry/description-length.js.map +1 -0
  84. package/dist/modules/workflow/git/git.service.d.ts +25 -0
  85. package/dist/modules/workflow/git/git.service.d.ts.map +1 -1
  86. package/dist/modules/workflow/git/git.service.js +40 -1
  87. package/dist/modules/workflow/git/git.service.js.map +1 -1
  88. package/dist/modules/workflow/pending-commits.service.d.ts.map +1 -1
  89. package/dist/modules/workflow/pending-commits.service.js +5 -1
  90. package/dist/modules/workflow/pending-commits.service.js.map +1 -1
  91. package/dist/modules/workflow/recovery-bot.d.ts.map +1 -1
  92. package/dist/modules/workflow/recovery-bot.js +7 -3
  93. package/dist/modules/workflow/recovery-bot.js.map +1 -1
  94. package/dist/modules/workflow/review-workflow/review-workflow.service.d.ts.map +1 -1
  95. package/dist/modules/workflow/review-workflow/review-workflow.service.js +12 -3
  96. package/dist/modules/workflow/review-workflow/review-workflow.service.js.map +1 -1
  97. package/dist/modules/workflow/workflow.service.d.ts.map +1 -1
  98. package/dist/modules/workflow/workflow.service.js +4 -1
  99. package/dist/modules/workflow/workflow.service.js.map +1 -1
  100. package/dist/modules/workspace/agent-upload.routes.d.ts +77 -0
  101. package/dist/modules/workspace/agent-upload.routes.d.ts.map +1 -0
  102. package/dist/modules/workspace/agent-upload.routes.js +210 -0
  103. package/dist/modules/workspace/agent-upload.routes.js.map +1 -0
  104. package/dist/modules/workspace/agent-upload.store.d.ts +284 -0
  105. package/dist/modules/workspace/agent-upload.store.d.ts.map +1 -0
  106. package/dist/modules/workspace/agent-upload.store.js +553 -0
  107. package/dist/modules/workspace/agent-upload.store.js.map +1 -0
  108. package/dist/modules/workspace/startup/steps/seed-tree.d.ts.map +1 -1
  109. package/dist/modules/workspace/startup/steps/seed-tree.js +3 -3
  110. package/dist/modules/workspace/startup/steps/seed-tree.js.map +1 -1
  111. package/dist/modules/workspace/startup/steps/template-source.d.ts +40 -0
  112. package/dist/modules/workspace/startup/steps/template-source.d.ts.map +1 -1
  113. package/dist/modules/workspace/startup/steps/template-source.js +46 -4
  114. package/dist/modules/workspace/startup/steps/template-source.js.map +1 -1
  115. package/dist/modules/workspace/upload-limits.d.ts +13 -0
  116. package/dist/modules/workspace/upload-limits.d.ts.map +1 -0
  117. package/dist/modules/workspace/upload-limits.js +13 -0
  118. package/dist/modules/workspace/upload-limits.js.map +1 -0
  119. package/dist/modules/workspace/workspace.routes.d.ts.map +1 -1
  120. package/dist/modules/workspace/workspace.routes.js +1 -1
  121. package/dist/modules/workspace/workspace.routes.js.map +1 -1
  122. package/dist/modules/workspace/workspace.service.d.ts +13 -0
  123. package/dist/modules/workspace/workspace.service.d.ts.map +1 -1
  124. package/dist/modules/workspace/workspace.service.js +61 -33
  125. package/dist/modules/workspace/workspace.service.js.map +1 -1
  126. package/dist/modules/workspace/workspace.tools.d.ts +11 -9
  127. package/dist/modules/workspace/workspace.tools.d.ts.map +1 -1
  128. package/dist/modules/workspace/workspace.tools.js +512 -113
  129. package/dist/modules/workspace/workspace.tools.js.map +1 -1
  130. package/dist/modules/workspace/write-denial.d.ts +0 -6
  131. package/dist/modules/workspace/write-denial.d.ts.map +1 -1
  132. package/dist/modules/workspace/write-denial.js +0 -6
  133. package/dist/modules/workspace/write-denial.js.map +1 -1
  134. package/dist/modules/workspace/zip-entry-rules.d.ts +114 -0
  135. package/dist/modules/workspace/zip-entry-rules.d.ts.map +1 -0
  136. package/dist/modules/workspace/zip-entry-rules.js +154 -0
  137. package/dist/modules/workspace/zip-entry-rules.js.map +1 -0
  138. package/dist/shared/column-crypto.d.ts +194 -0
  139. package/dist/shared/column-crypto.d.ts.map +1 -0
  140. package/dist/shared/column-crypto.js +144 -0
  141. package/dist/shared/column-crypto.js.map +1 -0
  142. package/dist/shared/token-crypto.d.ts.map +1 -1
  143. package/dist/shared/token-crypto.js +25 -1
  144. package/dist/shared/token-crypto.js.map +1 -1
  145. package/dist/tenancy/static-tenant-source.d.ts.map +1 -1
  146. package/dist/tenancy/static-tenant-source.js +1 -0
  147. package/dist/tenancy/static-tenant-source.js.map +1 -1
  148. package/dist/tenancy/tenant-secrets.d.ts +5 -1
  149. package/dist/tenancy/tenant-secrets.d.ts.map +1 -1
  150. package/dist/tenancy/tenant-secrets.js +4 -0
  151. package/dist/tenancy/tenant-secrets.js.map +1 -1
  152. package/kb-template/AGENTS.md +2 -0
  153. package/migrations/0016_pii_encryption.sql +20 -0
  154. package/migrations/meta/0016_snapshot.json +2327 -0
  155. package/migrations/meta/_journal.json +7 -0
  156. package/package.json +3 -3
  157. package/src/core/__tests__/lifecycle.test.ts +71 -4
  158. package/src/core/create-core-server.ts +21 -3
  159. package/src/core/create-core-services.ts +27 -1
  160. package/src/core/lifecycle.ts +19 -0
  161. package/src/core-config.ts +18 -0
  162. package/src/index.ts +18 -0
  163. package/src/modules/access/__tests__/users-db-double.ts +21 -12
  164. package/src/modules/access/access.routes.ts +4 -1
  165. package/src/modules/access/directory-sync-bot.ts +7 -3
  166. package/src/modules/agent-instructions/__tests__/agent-instructions.route.test.ts +8 -4
  167. package/src/modules/agent-instructions/__tests__/compose.test.ts +19 -10
  168. package/src/modules/agent-instructions/__tests__/shared-file-rules.test.ts +238 -0
  169. package/src/modules/agent-instructions/agent-instructions.routes.ts +12 -2
  170. package/src/modules/agent-instructions/compose.ts +50 -7
  171. package/src/modules/agent-instructions/index.ts +12 -0
  172. package/src/modules/agent-instructions/shared-file-rules.ts +314 -0
  173. package/src/modules/audit/agent-audit.service.ts +4 -2
  174. package/src/modules/auth/__tests__/account-deactivation.test.ts +2 -1
  175. package/src/modules/auth/__tests__/account-erasure.approval-gate.test.ts +6 -2
  176. package/src/modules/auth/__tests__/account.routes.test.ts +6 -3
  177. package/src/modules/auth/__tests__/auth.service.test.ts +3 -1
  178. package/src/modules/auth/account-erasure.service.ts +69 -18
  179. package/src/modules/auth/auth.service.ts +33 -23
  180. package/src/modules/code-mode/__tests__/chain-runtime.e2e.test.ts +335 -0
  181. package/src/modules/code-mode/__tests__/code-mode.tool.test.ts +46 -2
  182. package/src/modules/code-mode/code-mode.tool.ts +80 -34
  183. package/src/modules/database/__tests__/connection.test.ts +12 -0
  184. package/src/modules/database/__tests__/pii-backfill.pg.test.ts +561 -0
  185. package/src/modules/database/connection.ts +117 -0
  186. package/src/modules/database/core-schema.ts +81 -31
  187. package/src/modules/database/migrate.ts +353 -1
  188. package/src/modules/mcp/__tests__/mcp.e2e.test.ts +4 -3
  189. package/src/modules/mcp/__tests__/mcp.service.test.ts +47 -7
  190. package/src/modules/mcp/mcp.service.ts +46 -7
  191. package/src/modules/plugins/join-request-records.store.ts +7 -4
  192. package/src/modules/tool-auth/external-api-key.service.ts +8 -2
  193. package/src/modules/tool-manuals/tool-manuals.tools.ts +44 -31
  194. package/src/modules/tool-registry/__tests__/tool-description-length.test.ts +378 -0
  195. package/src/modules/tool-registry/description-length.ts +111 -0
  196. package/src/modules/workflow/git/__tests__/git.service.prFetchFailure.test.ts +170 -0
  197. package/src/modules/workflow/git/git.service.ts +47 -1
  198. package/src/modules/workflow/pending-commits.service.ts +5 -1
  199. package/src/modules/workflow/recovery-bot.ts +7 -3
  200. package/src/modules/workflow/review-workflow/__tests__/carry-approvals-forward.test.ts +4 -0
  201. package/src/modules/workflow/review-workflow/__tests__/erase-approver.test.ts +25 -3
  202. package/src/modules/workflow/review-workflow/review-workflow.service.ts +12 -3
  203. package/src/modules/workflow/workflow.service.ts +4 -1
  204. package/src/modules/workspace/__tests__/agent-uploads.test.ts +1604 -0
  205. package/src/modules/workspace/__tests__/escape-sequences.routes.test.ts +24 -14
  206. package/src/modules/workspace/__tests__/workspace.service.any-workspace-credentials.test.ts +156 -0
  207. package/src/modules/workspace/__tests__/workspace.service.replaced-repository.test.ts +77 -1
  208. package/src/modules/workspace/__tests__/workspace.service.test.ts +57 -0
  209. package/src/modules/workspace/__tests__/workspace.tools.agents-file.test.ts +39 -36
  210. package/src/modules/workspace/__tests__/workspace.tools.test.ts +84 -45
  211. package/src/modules/workspace/agent-upload.routes.ts +214 -0
  212. package/src/modules/workspace/agent-upload.store.ts +668 -0
  213. package/src/modules/workspace/startup/steps/__tests__/steps.test.ts +9 -9
  214. package/src/modules/workspace/startup/steps/seed-tree.ts +3 -6
  215. package/src/modules/workspace/startup/steps/template-source.ts +53 -5
  216. package/src/modules/workspace/upload-limits.ts +12 -0
  217. package/src/modules/workspace/workspace.routes.ts +1 -2
  218. package/src/modules/workspace/workspace.service.ts +63 -37
  219. package/src/modules/workspace/workspace.tools.ts +588 -127
  220. package/src/modules/workspace/write-denial.ts +0 -8
  221. package/src/modules/workspace/zip-entry-rules.ts +173 -0
  222. package/src/shared/__tests__/column-crypto.test.ts +217 -0
  223. package/src/shared/column-crypto.ts +218 -0
  224. package/src/shared/token-crypto.ts +28 -1
  225. package/src/tenancy/__tests__/static-tenant-source.test.ts +4 -0
  226. package/src/tenancy/static-tenant-source.ts +1 -0
  227. package/src/tenancy/tenant-secrets.ts +5 -1
@@ -1,6 +1,7 @@
1
1
  import { spawn } from 'node:child_process';
2
2
  import nodeFs from 'node:fs/promises';
3
3
  import { join } from 'node:path';
4
+ import AdmZip from 'adm-zip';
4
5
  import type { Router, RequestHandler } from 'express';
5
6
  import type { LocalFilesystem } from '@mastra/core/workspace';
6
7
  import type { IToolRegistry, JsonSchema } from '../tool-registry/tool.contract.js';
@@ -16,11 +17,17 @@ import type { IRoutineWritePolicy } from './routine-write-policy.js';
16
17
  import type { ToolHandlerFactory } from '../tool-helpers/tool-handler.js';
17
18
  import { requireInternalSource, requireExternalSource } from '../tool-auth/tool-auth.middleware.js';
18
19
  import { workspaceIdForBranch } from '../../shared/workspace-id.js';
19
- import { assertBranchProvided } from '../../shared/domain-errors.js';
20
+ import { assertBranchProvided, GitInternalsError, WorkflowValidationError } from '../../shared/domain-errors.js';
20
21
  // Leaf-level shared primitive (same exception `workspace.service.ts` already
21
22
  // relies on) — not a workflow service, so this stays inside the module boundary.
22
23
  import { assertValidBranchName } from '../kb-fs/branch-name.js';
23
- import { assertInsideRepo, assertRepoRootNameFreeArgs, normalizePathArgs } from '../kb-fs/repo-path.js';
24
+ import {
25
+ assertInsideRepo,
26
+ assertRepoRootNameFree,
27
+ assertRepoRootNameFreeArgs,
28
+ isInsideRepo,
29
+ normalizePathArgs,
30
+ } from '../kb-fs/repo-path.js';
24
31
  import { GitGuardedFilesystem } from '../kb-fs/git-guarded-filesystem.js';
25
32
  import { assertNoGitInternalsSegment, assertNotGitInternals, hasGitInternalsSegment } from '../../shared/git-internals.js';
26
33
  import { isRolesYamlPath } from '../access-model/roles-yaml-guard.js';
@@ -38,28 +45,36 @@ import { createFileReaderRegistry } from './file-readers/file-reader.registry.js
38
45
  import { DocumentReader } from './file-readers/document-reader.js';
39
46
  import { mcpImageResult } from '@bevel-software/platform-mcp-core';
40
47
  import {
41
- LEGACY_AGENTS_FILE,
42
48
  folderPlaceholderPath,
43
49
  isFolderPlaceholder,
44
50
  isPlatformFile,
45
51
  isPlatformFolder,
46
52
  platformFileCreationRefusal,
47
- platformFileNames,
48
53
  platformFileRefusal,
54
+ platformFileUploadRefusal,
49
55
  platformFolderRefusal,
50
56
  entryExistsMessage,
51
57
  type ExistingEntryKind,
52
- type KbLayout,
53
58
  } from '@bevel-software/platform-shared';
54
59
  import type { KbContext } from '../../shared/kb-context.js';
55
60
  import { AccessDeniedError } from '../access-model/access-errors.js';
56
61
  import { removeEmptyDirs } from './empty-dirs.js';
57
- import { PROPOSAL_ROUTE_NOTE, rethrowAsWriteDenial } from './write-denial.js';
62
+ import { rethrowAsWriteDenial } from './write-denial.js';
63
+ import { sharedRulesPointer } from '../agent-instructions/shared-file-rules.js';
58
64
  import type { IChangeReadGate } from '../access-model/change-gate.js';
59
65
  import { notFound, orDeclaredNotFound, orNotFound } from './not-found.js';
60
66
  import { logger } from '../../shared/logging.js';
61
67
  import { printable } from '../../shared/printable.js';
62
68
  import { DestinationTakenError, inspectDestination } from '../../shared/rename-no-replace.js';
69
+ import { AgentUploadStore, type ClaimedUpload } from './agent-upload.store.js';
70
+ import {
71
+ isSymlinkZipEntry,
72
+ isZipNoiseEntry,
73
+ readZipEntry,
74
+ zipEntryName,
75
+ zipEntryNameRefusal,
76
+ zipEntrySegments,
77
+ } from './zip-entry-rules.js';
63
78
 
64
79
  const log = logger('workspace-tools');
65
80
 
@@ -193,60 +208,26 @@ async function keepFolderOf(
193
208
  }
194
209
  }
195
210
 
196
- /**
197
- * Appended (centrally, in `mount`) to EVERY workspace tool description. The
198
- * platform's managed agent guide sits at the workspace root and documents the
199
- * conventions of that knowledge base; agents (ours and external) should consult
200
- * it before touching files. It rides on every entrypoint — reads (grep/
201
- * list_files/file_stat) included — because any of them can be a session's first
202
- * touch.
203
- *
204
- * `CLAUDE.md` is named as a fallback because knowledge bases seeded before the
205
- * rename still carry one, and the seeder never deletes a file it did not
206
- * expect. Naming both means an agent finds the conventions either way, instead
207
- * of reading none because it looked for the newer name and stopped.
208
- *
209
- * WHEN THE GUIDE HAS BEEN RENAMED the sentence names two files, ours first. The
210
- * second is the organisation's OWN `AGENTS.md`, which on such a deployment is
211
- * ordinary content the platform never touches — and which no harness reads for a
212
- * remote agent, because a remote agent has no checkout. Telling it to read both
213
- * is the only way the conventions the customer actually wrote reach the agent
214
- * working in their knowledge base. Under the default name the wording collapses
215
- * to the one file it has always named.
216
- *
217
- * A FUNCTION of the layout, called when a description is built: the name is a
218
- * deployment setting, and a module-scope string would snapshot the default.
219
- */
220
- function kbConventionsNote(layout: KbLayout): string {
221
- const agentsFile = layout.agentsFile ?? LEGACY_AGENTS_FILE;
222
- if (agentsFile === LEGACY_AGENTS_FILE) {
223
- return ' Before your first read or change in a workspace, read `AGENTS.md` at the KB root — or `CLAUDE.md` on a knowledge base seeded before it was renamed — if either exists: it holds the author\'s conventions for this knowledge base, and you should follow them.';
224
- }
225
- return (
226
- ` Before your first read or change in a workspace, read \`${agentsFile}\` at the KB root, then ` +
227
- '`AGENTS.md` if it also exists (the organisation\'s own conventions) — or `CLAUDE.md` on a knowledge base seeded before it was renamed: together they hold the conventions for this knowledge base, and you should follow them.'
228
- );
229
- }
230
-
231
- /** The platform files as a tool description lists them — the guide under its own name. */
232
- function platformFileList(layout: KbLayout): string {
233
- return platformFileNames(layout)
234
- .map((name) => `\`${name}\``)
235
- .join(', ');
236
- }
237
-
238
211
  const int = (description: string): JsonSchema => ({ type: 'integer', description });
239
212
 
240
213
  const str = (description: string): JsonSchema => ({ type: 'string', description });
241
214
 
242
215
  /**
243
- * Where pictures go, on the two tools that write pages. An agent in core cannot
244
- * upload bytes yet (TODOS.md), but it can write the page with the link a person
245
- * will satisfy, and this sentence is what keeps every page it writes on the
246
- * README's convention: images beside the page, linked relatively.
216
+ * The upload route, named on every tool that takes content as a JSON string.
217
+ *
218
+ * ONE sentence, and the tools' own: it is what stops the three failures the
219
+ * route was built for. An agent landing 27 files read each one and typed it
220
+ * out again as a tool argument: a 37 KB write was truncated mid-answer, a page
221
+ * of regex backslashes failed to parse as a JSON parameter, and a PNG could not
222
+ * be sent at all. None of that is discoverable from a refusal — a truncated
223
+ * write reports success — so the tools that invite it name where the bytes
224
+ * should go instead, in the description itself, for a client that reads
225
+ * nothing else. WHY, and how the route is used, is one of the shared rules
226
+ * (`agent-instructions/shared-file-rules.ts`): said in full on three
227
+ * descriptions it took each of them past the length a client cuts at.
247
228
  */
248
- const IMAGE_CONVENTION_NOTE =
249
- ' Images: keep them in an `assets/` folder next to the page that uses them and link them with a relative path, e.g. `![Approval screen](./assets/approval-screen.png)`; the page renders them inline.';
229
+ const UPLOAD_ROUTE_NOTE =
230
+ ' Large, escape-heavy or binary content does not go through here: use `request_file_upload` + `apply_file_upload`.';
250
231
 
251
232
  /**
252
233
  * A path input that names the clone folder, and says what happens when it does
@@ -285,6 +266,9 @@ const RESERVED_ROOT_NAME_TARGETS: Readonly<Record<string, readonly string[]>> =
285
266
  copy_file: ['dest'],
286
267
  move_file: ['dest'],
287
268
  unzip: ['destination'],
269
+ // The folder the upload lands in. Each of its own paths is checked again
270
+ // inside the handler — an archive chooses its entry names, not the caller.
271
+ apply_file_upload: ['destination'],
288
272
  };
289
273
 
290
274
  function asText(content: string | Buffer): string {
@@ -313,16 +297,6 @@ interface DocGrepState {
313
297
  skippedUncached: number;
314
298
  }
315
299
 
316
- /**
317
- * THE binary capability contract, stated once and appended (in `mount`) to
318
- * every file tool's description — which is also what `tools_info` returns.
319
- * The split it states is enforced by the reader registry: the text tools
320
- * refuse what their reader marks not `textEditable` (and binary content under
321
- * any name) with a `binary_not_writable` refusal; the byte tools never look.
322
- */
323
- export const CONTENT_RULE =
324
- ' Content rule (the same on every file tool): read_file returns text for text files and extracted text for documents (.docx/.pptx/.xlsx/.odt/.odp/.ods/.pdf, .eml/.msg); write_file, write_files and edit_file accept TEXT only — they refuse documents, images, archives and other binary files (legacy .doc/.ppt/.xls included) with kind `binary_not_writable`, naming the file\'s kind and the tool to use instead; copy_file, move_file, delete_file and unzip act on bytes of any kind; new binary content arrives through upload (`request_upload_token` + `apply_upload` where offered, otherwise Upload in the app). file_stat reports `contentMode` (`text` | `document` | `binary`) so you can decide before acting.';
325
-
326
300
  /** What a `binary_not_writable` refusal points to, in the order to try them. */
327
301
  const BINARY_USE_INSTEAD = ['upload', 'copy_file', 'move_file'] as const;
328
302
 
@@ -335,7 +309,7 @@ const BINARY_USE_INSTEAD = ['upload', 'copy_file', 'move_file'] as const;
335
309
  function binaryNotWritable(fileKind: FileKind, explanation: string): ToolError {
336
310
  return new ToolError(
337
311
  `${explanation} [binary_not_writable: this file's kind is ${fileKind}; write_file, write_files and edit_file accept text only. ` +
338
- 'Use upload for new bytes (`request_upload_token` + `apply_upload` where offered, otherwise Upload in the app), ' +
312
+ 'Use upload for new bytes (`request_file_upload` + `apply_file_upload`, or Upload in the app), ' +
339
313
  'or copy_file / move_file to place bytes that are already in the workspace.]',
340
314
  415,
341
315
  { kind: 'binary_not_writable', fileKind, useInstead: [...BINARY_USE_INSTEAD] },
@@ -427,34 +401,6 @@ const WRITE_MODE_INPUT: JsonSchema = {
427
401
  'EXISTING file and refuses (`missing`) a path that holds nothing.',
428
402
  };
429
403
 
430
- /** The same three modes, said once, for both tool descriptions. */
431
- const WRITE_MODE_NOTE =
432
- ' `mode` decides what may happen at a path and DEFAULTS TO `create`: `create` writes a new file and refuses a path that ' +
433
- 'already exists (`exists`, with the path — pass `mode: overwrite` to replace it), `overwrite` replaces what is there ' +
434
- '(creating it if there is nothing), `update` replaces an existing file and refuses a path that does not exist (`missing`). ' +
435
- 'A refused path is left exactly as it was.';
436
-
437
- /**
438
- * What an agent needs to know about escape sequences in the content it sends,
439
- * on the three tools that take content as a JSON string.
440
- *
441
- * The three write routes — the MCP endpoint, the `/api/agent/tools/<name>`
442
- * route and `call_tool_chain` — were measured end to end against raw requests
443
- * and a byte-level read of the stored file (see
444
- * `__tests__/escape-sequences.routes.test.ts`): each stores content exactly as
445
- * the JSON string value decodes ONCE. So when an escape arrives already
446
- * decoded, the decoding happened in the client that built the request, and no
447
- * tool here can tell that content from content that was meant to be decoded.
448
- * Hence a warning rather than a fix, and the pointer to the one route whose
449
- * payload is bytes rather than a JSON string.
450
- */
451
- const ESCAPE_SEQUENCE_NOTE =
452
- ' Escape sequences: some clients decode them in arguments before sending, so content meant to CONTAIN an escape rather ' +
453
- 'than what it stands for (the six characters backslash, `u`, `0`, `0`, `4`, `1`, say, rather than the letter `A`) can ' +
454
- 'reach this tool already decoded — what arrives is stored byte for byte, so when that distinction matters, verify what ' +
455
- 'landed (`read_file`, or a hash) and send such content through the upload route (`request_upload_token` + `apply_upload` ' +
456
- 'where offered, otherwise Upload in the app), which lands it unchanged.';
457
-
458
404
  /** The refusal `create` gives on a path that already holds something. */
459
405
  function pathExists(path: string): ToolError {
460
406
  return new ToolError(
@@ -486,6 +432,169 @@ function decideWrite(mode: WriteMode, path: string, exists: boolean): WriteOutco
486
432
  return exists ? 'replaced' : 'created';
487
433
  }
488
434
 
435
+ /**
436
+ * How many of an upload's paths the answer NAMES before it stops and says how
437
+ * many there were. A 300-file zip's full outcome list is pages of text an agent
438
+ * pays for on every call; 25 is enough to see the shape of what happened, and
439
+ * `total` plus `truncated` say that there is more. `all: true` asks for the
440
+ * rest, for a caller that really does have to read each one.
441
+ */
442
+ const APPLY_ANSWER_CAP = 25;
443
+
444
+ /**
445
+ * How many entries of one uploaded archive are landed, and how many bytes of
446
+ * uncompressed content in total.
447
+ *
448
+ * Tighter than `unzip`'s own caps on purpose. An apply lands its whole set as
449
+ * ONE commit, which means every entry's bytes are held in memory at once —
450
+ * the property that makes the commit atomic is the one that makes a zip bomb
451
+ * expensive. The upload itself is already bounded by the deployment's upload
452
+ * limit; these bound what that upload is allowed to expand into.
453
+ */
454
+ const APPLY_MAX_ENTRIES = 5_000;
455
+ const APPLY_MAX_TOTAL_BYTES = 128 * 1024 * 1024; // 128 MB uncompressed
456
+
457
+ /**
458
+ * One path of an upload, as `apply_file_upload` plans it: the bytes to write,
459
+ * or the reason this path is refused before any gate is asked. A refused path
460
+ * carries the name the archive held rather than a workspace path, because for
461
+ * those the whole problem is that no workspace path can be built from it.
462
+ */
463
+ interface PlannedUploadPath {
464
+ path: string;
465
+ content?: Buffer;
466
+ error?: string;
467
+ message?: string;
468
+ }
469
+
470
+ /**
471
+ * Turn a stored upload into one planned path per file.
472
+ *
473
+ * A single file is one path: the destination plus the name it was sent with.
474
+ * A zip is one path per member, with the member's folder structure kept under
475
+ * the destination — judged by the same entry rules `unzip` applies
476
+ * (`zip-entry-rules.ts`), plus one `unzip` does not have: an entry that is a
477
+ * symbolic LINK is refused outright. A zip stores a link as a member whose
478
+ * bytes are its target text, so a reader that ignored the mode bits would
479
+ * write that text out as a file — content nobody sent, under a name that was
480
+ * meant to point elsewhere.
481
+ */
482
+ /** The refusal an entry gets when the archive would expand past what one commit lands. */
483
+ function tooLargeToApply(): string {
484
+ return `This archive expands past the ${APPLY_MAX_TOTAL_BYTES} byte total the apply lands in one commit; this entry was not applied.`;
485
+ }
486
+
487
+ async function planUpload(
488
+ upload: ClaimedUpload,
489
+ destination: string,
490
+ kbDirName: string,
491
+ ): Promise<PlannedUploadPath[]> {
492
+ const bytes = await nodeFs.readFile(upload.absolutePath);
493
+ if (upload.kind !== 'zip') {
494
+ return [{ path: `${destination}/${upload.filename}`, content: bytes }];
495
+ }
496
+ let zip: AdmZip;
497
+ try {
498
+ zip = new AdmZip(bytes);
499
+ } catch (err) {
500
+ throw new ToolError(
501
+ `"${upload.filename}" could not be opened as a .zip archive: ${err instanceof Error ? err.message : String(err)}`,
502
+ 422,
503
+ { code: 'unreadable_archive' },
504
+ );
505
+ }
506
+ const planned: PlannedUploadPath[] = [];
507
+ let seen = 0;
508
+ let totalBytes = 0;
509
+ for (const entry of zip.getEntries()) {
510
+ const rawName = zipEntryName(entry.entryName);
511
+ if (isZipNoiseEntry(rawName)) continue;
512
+ if (seen >= APPLY_MAX_ENTRIES) {
513
+ planned.push({
514
+ path: rawName || '(empty)',
515
+ error: 'too_many_entries',
516
+ message: `This archive holds more than ${APPLY_MAX_ENTRIES} entries; the rest were not applied.`,
517
+ });
518
+ continue;
519
+ }
520
+ seen++;
521
+ const nameRefusal = zipEntryNameRefusal(rawName);
522
+ if (nameRefusal !== null) {
523
+ planned.push({ path: rawName || '(empty)', error: 'invalid_entry', message: nameRefusal });
524
+ continue;
525
+ }
526
+ if (isSymlinkZipEntry(entry)) {
527
+ planned.push({
528
+ path: rawName,
529
+ error: 'link',
530
+ message: `"${rawName}" is a symbolic link, not a file; an upload lands files, never links.`,
531
+ });
532
+ continue;
533
+ }
534
+ // A folder comes into being with the files under it (the write path mkdirs
535
+ // each parent), so a directory member has nothing of its own to land.
536
+ if (entry.isDirectory) continue;
537
+ const segments = zipEntrySegments(rawName);
538
+ const target = [destination, ...segments].join('/');
539
+ // Belt and braces: `zipEntryNameRefusal` already refuses a `..` segment
540
+ // and a root-anchored name, so nothing should reach here that climbs out.
541
+ // The check stays because the cost of being wrong about that is bytes
542
+ // landing outside the folder the caller named.
543
+ if (!target.startsWith(`${destination}/`) || !isInsideRepo(target, kbDirName)) {
544
+ planned.push({ path: rawName, error: 'invalid_entry', message: 'Path escapes destination' });
545
+ continue;
546
+ }
547
+ // Through the one bounded reader `unzip` uses too, capped at what is left
548
+ // of the budget: a deflate stream can expand a thousandfold, and the
549
+ // header's declared size is the archive's claim, not a fact — an entry
550
+ // declaring ZERO would otherwise be inflated with no cap at all (see
551
+ // `readZipEntry`). A read that fails is this entry's outcome and no more.
552
+ const read = readZipEntry(entry, APPLY_MAX_TOTAL_BYTES - totalBytes);
553
+ if (!read.ok) {
554
+ planned.push(
555
+ read.reason === 'too_large'
556
+ ? { path: rawName, error: 'too_large', message: tooLargeToApply() }
557
+ : { path: rawName, error: 'unreadable_entry', message: `"${rawName}" could not be read: ${read.detail}.` },
558
+ );
559
+ continue;
560
+ }
561
+ totalBytes += read.data.byteLength;
562
+ planned.push({ path: target, content: read.data });
563
+ }
564
+ return planned;
565
+ }
566
+
567
+ /**
568
+ * Record on `entry` that this path was refused, saying what the gate that
569
+ * refused it said. Four kinds of refusal count as one path's outcome: a
570
+ * typed tool refusal (`exists`, `platform_file`, the mode gate), a permission
571
+ * refusal (the caller may not write this path, where the DESTINATION was
572
+ * writable), the git folder in any spelling, and a path-shape refusal from the
573
+ * repository rules. Anything else
574
+ * is not a verdict about this path — it is a gate failing — so it travels on
575
+ * and the whole apply fails loudly, exactly as it does in `write_files`.
576
+ */
577
+ function refuseEntry(entry: Record<string, unknown>, err: unknown): void {
578
+ entry.outcome = 'refused';
579
+ if (err instanceof ToolError) {
580
+ const details = (err.details ?? {}) as { code?: string; kind?: string };
581
+ entry.error = details.code ?? details.kind ?? 'refused';
582
+ entry.message = err.message;
583
+ return;
584
+ }
585
+ if (err instanceof AccessDeniedError) {
586
+ entry.error = 'write-denied';
587
+ entry.message = err.message;
588
+ return;
589
+ }
590
+ if (err instanceof GitInternalsError || err instanceof WorkflowValidationError) {
591
+ entry.error = (err.payload as { kind?: string } | undefined)?.kind ?? 'refused';
592
+ entry.message = err.message;
593
+ return;
594
+ }
595
+ throw err;
596
+ }
597
+
489
598
  /** The three modes, as a set the handler can check a raw argument against. */
490
599
  const WRITE_MODES: readonly WriteMode[] = ['create', 'overwrite', 'update'];
491
600
 
@@ -730,6 +839,15 @@ export function registerWorkspaceTools(
730
839
  * verdict alone then decides, which differs only at a root.
731
840
  */
732
841
  changeGate?: IChangeReadGate,
842
+ /**
843
+ * The upload-token store behind `request_file_upload` / `apply_file_upload`
844
+ * — the route an agent lands bytes by, without their content passing
845
+ * through the model. Optional for the same reason the two above are: a tool
846
+ * harness that is about the file primitives need not stand one up. Every
847
+ * real composition wires it (`create-core-server.ts`), and without it the
848
+ * two tools are not mounted at all rather than mounted and broken.
849
+ */
850
+ uploads?: AgentUploadStore,
733
851
  ): void {
734
852
  const { kbDirName } = kb;
735
853
  /**
@@ -1347,10 +1465,14 @@ export function registerWorkspaceTools(
1347
1465
  handler: ToolHandler;
1348
1466
  }): void => {
1349
1467
  const path = `/api/agent/tools/${spec.name}`;
1350
- // Every workspace entrypoint carries the agent-guide reminder, every file
1351
- // tool the one content rule, and every tool a permission can refuse the
1352
- // proposal route — appended once here so no tool (especially the
1353
- // read-only ones a session hits first) can miss them.
1468
+ // Every description ends with ONE sentence pointing at the rules these
1469
+ // tools share — the content rule, the agent guide, the write modes, the
1470
+ // dry-run protocol, the proposal route. They used to be appended here in
1471
+ // FULL, which made a description several thousand characters of text the
1472
+ // agent had already read on the tool above, and clients cut a long
1473
+ // description from the END, where what is specific to the tool sits. The
1474
+ // rules themselves are in the handshake instructions and in the managed
1475
+ // guide (see `shared-file-rules.ts`), stated once and from one text.
1354
1476
  // Whether a call to this tool MUST name a branch, read off the tool's own
1355
1477
  // declaration rather than assumed of the family. Every tool mounted here
1356
1478
  // requires `branch` today; keying on the schema means a tool that declares
@@ -1359,10 +1481,8 @@ export function registerWorkspaceTools(
1359
1481
  const requiresBranch = ((spec.inputs as { required?: string[] }).required ?? []).includes('branch');
1360
1482
  const describe = (): string =>
1361
1483
  (typeof spec.description === 'function' ? spec.description() : spec.description) +
1362
- (spec.proposable ? PROPOSAL_ROUTE_NOTE : '') +
1363
- (spec.fileTool === false ? '' : CONTENT_RULE) +
1364
- kbConventionsNote(kb.layout) +
1365
- (spec.gated ? agentAccessGate.notes.gatedToolNote() : '');
1484
+ (spec.gated ? agentAccessGate.notes.gatedToolNote() : '') +
1485
+ sharedRulesPointer(kb.layout);
1366
1486
  const def = toolDef({
1367
1487
  name: spec.name,
1368
1488
  description: describe(),
@@ -1528,7 +1648,13 @@ export function registerWorkspaceTools(
1528
1648
  name: 'read_file',
1529
1649
  gated: true,
1530
1650
  description:
1531
- 'Read a workspace file as text. Returns `{ path, content }`. Images (.png/.jpg/.jpeg/.gif/.webp) return the IMAGE ITSELF as native MCP image content (plus a one-line text note naming the file), so you can look at the picture — up to 3.5 MB of raw image data; a larger image gets an honest refusal asking for a locally downscaled copy or a smaller export (`.svg` is text and reads as text). Images come back only on a DIRECT call: inside `call_tool_chain` an image read yields an `{ image_omitted, note }` stub instead. Office and OpenDocument files (.docx/.pptx/.xlsx, .odt/.odp/.ods) and PDFs return their EXTRACTED text under an honest `[extracted text of …]` header, with `[slide N]`/`[sheet: Name]`/`[page N]` markers — the extraction is READ-ONLY (layout/images omitted; such files cannot be edited as text, only replaced by uploading a new version). Email files (.eml/.msg) return their EXTRACTED text the same way: a `[from]`/`[to]`/`[subject]`/`[date]` header block, the body (plain-text part preferred; an HTML-only body is stripped to text), and an `[attachments]` name list — attachments are listed, never extracted. Other binary files return a one-line description instead of raw bytes. Optional `offset`/`limit` slice the content (characters for a file, bytes for a `__tool_chain_spill__/…` ref; ignored for an image) — use them to page through large files or a `call_tool_chain` spill rather than reading multi-MB in full. A spill ref is workspace-independent: `branch` is ignored for it.',
1651
+ 'Read a workspace file as text. Returns `{ path, content }`. What comes back for a document, an email file, an image ' +
1652
+ 'or any other binary file is the content rule\'s business (see the shared rules): text files as text, documents and ' +
1653
+ 'email files as extracted text, an image as the picture itself, anything else as a one-line description. ' +
1654
+ 'Optional `offset`/`limit` slice the content (characters for a file, bytes for a `__tool_chain_spill__/…` ref; ignored ' +
1655
+ 'for an image) — use them to page through large files or a `call_tool_chain` spill rather than reading multi-MB in full. ' +
1656
+ 'It also reads a `__tool_chain_spill__/…` ref back from a truncated `call_tool_chain`: such a ref belongs to no ' +
1657
+ 'workspace, so `branch` is ignored for it.',
1532
1658
  inputs: {
1533
1659
  type: 'object',
1534
1660
  properties: {
@@ -1635,13 +1761,18 @@ export function registerWorkspaceTools(
1635
1761
  mount({
1636
1762
  name: 'file_stat',
1637
1763
  gated: true,
1638
- description: () =>
1639
- 'Get a file/directory\'s metadata (name, type, size, …) without returning content. A file also reports `contentMode`: `text` (read, write and edit it as text), `document` (read returns an extraction; replace it by upload) or `binary` (bytes: copy, move, delete, or replace by upload), plus `kind` (`text` | `document` | `image` | `binary`), `mime`, `mimeSource` and `textEditable` — decided by the same file readers read_file, grep and the write tools use, so an extensionless text file is `text/plain`.' +
1640
- ' Every entry also reports what you may DO with it. ' +
1641
- `\`managed\` is true for a platform item — a platform file (${platformFileList(kb.layout)}) or a platform folder (the repository root or a reserved root folder such as \`KnowledgeBase/\`); managed items are never movable or deletable through these tools. ` +
1642
- '`access: { read, write, download, owner }` is your own verdict under the access rules; pass `explainAccess: true` to learn why, and who else holds each verb. `movable` and `deletable` say whether `move_file` / `delete_file` / `delete_folder` would be allowed for you, judged like their dry runs: not managed, no symbolic link, and on a protected branch you hold write on the item AND on every file under a folder (on a draft branch writes are not gated). `movable` judges the source side only; the destination is judged by a `move_file` dry run. ' +
1643
- 'For a folder, `descendants` is the number of files under it at any depth; counting stops at 10000 and `descendantsTruncated` says so, and past that point `movable` and `deletable` are false because a folder that large was not judged in full — run the `move_file` or `delete_folder` dry run for the real verdict. ' +
1644
- 'Call this before a move or delete to see what it would touch.',
1764
+ description:
1765
+ 'Get a file/directory\'s metadata (name, type, size, …) without returning content, and what you may DO with it. ' +
1766
+ 'A file also reports `contentMode`, `kind`, `mime`, `mimeSource` and `textEditable` — decided by the same readers ' +
1767
+ 'read_file, grep and the write tools use, so an extensionless text file is `text/plain`. ' +
1768
+ '`access: { read, write, download, owner }` is your own verdict under the access rules; pass `explainAccess: true` to ' +
1769
+ 'learn why, and who else holds each verb. ' +
1770
+ 'Call this before a move or delete: `managed`, `movable` and `deletable` answer the shared rules on what these tools ' +
1771
+ 'never move or delete, judged like the dry runs (on a draft branch writes are not gated); `movable` judges the SOURCE ' +
1772
+ 'side only, so the destination still wants a `move_file` dry run. ' +
1773
+ 'For a folder, `descendants` counts the files under it at any depth; counting stops at 10000 and ' +
1774
+ '`descendantsTruncated` says so, past which `movable` and `deletable` are false — a folder that large was not judged ' +
1775
+ 'in full, so run the `move_file` or `delete_folder` dry run for the real verdict.',
1645
1776
  inputs: {
1646
1777
  type: 'object',
1647
1778
  properties: {
@@ -1949,9 +2080,7 @@ export function registerWorkspaceTools(
1949
2080
  description:
1950
2081
  'Write a workspace TEXT file. The change is committed + pushed as you. Returns `{ path, bytes, outcome }`, where `outcome` is ' +
1951
2082
  '`created`, `replaced` or `updated`.' +
1952
- WRITE_MODE_NOTE +
1953
- IMAGE_CONVENTION_NOTE +
1954
- ESCAPE_SEQUENCE_NOTE,
2083
+ UPLOAD_ROUTE_NOTE,
1955
2084
  inputs: {
1956
2085
  type: 'object',
1957
2086
  properties: {
@@ -2039,9 +2168,7 @@ export function registerWorkspaceTools(
2039
2168
  '`created` / `replaced` / `updated` for a path it wrote, or `refused` with `error` (the code) and `message` (why) for a ' +
2040
2169
  'path it could not. `count` is how many were written. A path it refuses — the mode said no, or the file is not text — ' +
2041
2170
  'does not stop the others; read `files` to see what landed.' +
2042
- WRITE_MODE_NOTE +
2043
- IMAGE_CONVENTION_NOTE +
2044
- ESCAPE_SEQUENCE_NOTE,
2171
+ UPLOAD_ROUTE_NOTE,
2045
2172
  inputs: {
2046
2173
  type: 'object',
2047
2174
  properties: {
@@ -2211,7 +2338,7 @@ export function registerWorkspaceTools(
2211
2338
  gated: true,
2212
2339
  description:
2213
2340
  'Replace an exact string in a workspace TEXT file. `old_string` must appear exactly once unless `replace_all`. Committed + pushed as you.' +
2214
- ESCAPE_SEQUENCE_NOTE,
2341
+ UPLOAD_ROUTE_NOTE,
2215
2342
  inputs: {
2216
2343
  type: 'object',
2217
2344
  properties: {
@@ -2260,9 +2387,8 @@ export function registerWorkspaceTools(
2260
2387
  mount({
2261
2388
  name: 'delete_file',
2262
2389
  gated: true,
2263
- description: () =>
2264
- 'Delete ONE workspace file (a symbolic link is refused: links are never followed or removed). Committed + pushed as you. Its folder stays, even when this was its last file. Files only: a folder is refused with a pointer to `delete_folder`. ' +
2265
- `A platform file (\`access.md\` or \`.bevelignore\` in any folder, \`roles.yaml\` or \`${kb.layout.agentsFile}\` at the repository root) and git metadata are refused.`,
2390
+ description:
2391
+ 'Delete ONE workspace file. Committed + pushed as you. Its folder stays, even when this was its last file. Files only: a folder is refused with a pointer to `delete_folder`.',
2266
2392
  inputs: {
2267
2393
  type: 'object',
2268
2394
  properties: {
@@ -2315,10 +2441,12 @@ export function registerWorkspaceTools(
2315
2441
  gated: true,
2316
2442
  description:
2317
2443
  'Delete a workspace FOLDER and every file under it, at any depth; the whole folder lands as ONE committed + pushed change as you — all of it or none of it — then the empty folder is removed. This is the one way a folder goes away: the folder that held it stays, even if this was all it had, and a folder holding nothing but its empty-folder placeholder counts as empty. ' +
2318
- 'Preflight first: `dryRun: true` changes nothing and answers `{ path, kind: "folder", descendants, files, filesTruncated, allowed, reason? }` — `descendants` is the file count, `files` names up to 100 of them. ' +
2319
- 'A non-empty folder is deleted only with `confirm: true`; without it the call deletes nothing and returns the same impact with `confirmationRequired: true`. Do NOT set `confirm: true` on your first call — dry-run, check the impact, then confirm. ' +
2320
- 'Refused (in a dry run as `allowed: false` with the `reason`): a platform folder (the repository root or a reserved root folder such as `KnowledgeBase/`), git metadata, a folder holding a symbolic link (links are never removed), and a folder holding any file you may not write. A path that is a file is refused with a pointer to `delete_file`, and a path through a symbolic link is refused (links are never followed). ' +
2321
- 'The folder\'s own platform files (`access.md`, `.bevelignore`) go with it in that same one change, so its files are never left ungoverned part-way; you must be able to write those platform files too.',
2444
+ 'The dry run answers `{ path, kind: "folder", descendants, files, filesTruncated, allowed, reason? }` — `descendants` is ' +
2445
+ 'the file count, `files` names up to 100 of them — and a non-empty folder wants `confirm: true`. ' +
2446
+ 'Beyond what the shared rules refuse, a folder HOLDING a symbolic link, or any file you may not write, is refused ' +
2447
+ '(the link itself is never removed), and a path that is a FILE ' +
2448
+ 'is refused with a pointer to `delete_file`. You must be able to write the folder\'s own platform files too: they go ' +
2449
+ 'with it in that same one change, so its files are never left ungoverned part-way.',
2322
2450
  inputs: {
2323
2451
  type: 'object',
2324
2452
  properties: {
@@ -2481,11 +2609,15 @@ export function registerWorkspaceTools(
2481
2609
  mount({
2482
2610
  name: 'move_file',
2483
2611
  gated: true,
2484
- description: () =>
2612
+ // A plain string again: what refuses a move names the guide, and that is in
2613
+ // the shared rules now, which are rebuilt from the layout where they live.
2614
+ description:
2485
2615
  'Move or rename a workspace FILE or FOLDER; a folder moves recursively, with everything under it. `dest` is the full new path, not the folder to move into. Lands as a delete + create, committed + pushed as you. ' +
2486
- `Rules: the destination must not exist — a move never overwrites a file or merges into a folder; a platform file (\`access.md\` or \`.bevelignore\` in any folder, \`roles.yaml\` or \`${kb.layout.agentsFile}\` at the repository root) is refused with "<name> is a platform file and stays in its folder." — a folder that moves takes its own platform files along, still in their folder; a platform folder (the repository root or a reserved root folder such as \`KnowledgeBase/\`) and git metadata are refused; a move cannot create a platform file or folder at \`dest\` either (renaming a note to \`access.md\` is refused); a path through a symbolic link is refused, since links are never followed; on a protected branch you must be able to write both ends — for a folder, every file under it at its old and its new path. ` +
2487
- 'Access follows the destination folder. Preflight first: `dryRun: true` changes nothing and answers `{ src, dest, kind, descendants, access: { before, after }, accessChanges, allowed, reason? }` — `access` is your own `{ read, write, download, owner }` at the source and at the destination AS IT WILL BE once the move has landed, with every `access.md` inside a moved folder counted at its new place. ' +
2488
- 'A move whose `accessChanges` is true runs only with `confirm: true`; without it the call moves nothing and returns the same impact with `confirmationRequired: true`. Do NOT set `confirm: true` on your first call — dry-run, check the impact, then confirm.',
2616
+ 'The destination must not exist — a move never overwrites a file or merges into a folder. Access follows the ' +
2617
+ 'DESTINATION folder, so a move can change what you (and others) may do with the file: the dry run answers ' +
2618
+ '`{ src, dest, kind, descendants, access: { before, after }, accessChanges, allowed, reason? }`, where `access` is your ' +
2619
+ 'own `{ read, write, download, owner }` at the source and at the destination AS IT WILL BE once the move has landed, ' +
2620
+ 'with every `access.md` inside a moved folder counted at its new place, and a move whose `accessChanges` is true wants `confirm: true`.',
2489
2621
  inputs: {
2490
2622
  type: 'object',
2491
2623
  properties: {
@@ -2830,6 +2962,335 @@ export function registerWorkspaceTools(
2830
2962
  },
2831
2963
  });
2832
2964
 
2965
+ // ── uploads (bytes that never pass through the model) ───────────────────
2966
+ //
2967
+ // The pair exists because MCP tool arguments are JSON. Every byte an agent
2968
+ // sends through `write_file` is first typed out by the model, which
2969
+ // truncates long files, mangles backslash and `\u` escapes, and cannot carry
2970
+ // a PNG at all. `request_file_upload` answers an address; the agent POSTs
2971
+ // the file (or one zip holding many) there with any HTTP client;
2972
+ // `apply_file_upload` lands it on a branch in one commit. The bytes go from
2973
+ // the agent's disk to the server's and never enter a prompt.
2974
+ //
2975
+ /**
2976
+ * Why one of an upload's paths may not be landed, judged on the path ALONE —
2977
+ * or undefined when nothing about the name itself refuses it.
2978
+ *
2979
+ * The platform files are the whole of it. `access.md` governs who may read
2980
+ * and write the folder it sits in, `roles.yaml` says which roles exist, and
2981
+ * the agent guide is read as instructions: each is configuration the platform
2982
+ * obeys, and each has a write path that CHECKS the change (the roles gate
2983
+ * refuses an edit that would lock every admin out; a folder's access rules
2984
+ * are judged against who is asking). Bytes arriving by upload meet none of
2985
+ * those gates — they are a buffer the sender chose — so an upload never
2986
+ * lands one, whatever else the caller may write. `unzip` has refused
2987
+ * `roles.yaml` from an archive for the same reason; this is that rule, over
2988
+ * all four names.
2989
+ */
2990
+ const platformFileReason = (wsPath: string): string | undefined => {
2991
+ const rel = toKbRelative(wsPath, kbDirName);
2992
+ return rel !== null && isPlatformFile(rel, kb.layout) ? platformFileUploadRefusal(rel) : undefined;
2993
+ };
2994
+
2995
+ /**
2996
+ * `apply_file_upload`'s handler: resolve the stored bytes into one path per
2997
+ * file, judge each path the way `write_files` judges its own, and land the
2998
+ * survivors as ONE commit.
2999
+ *
3000
+ * The judging is deliberately the same shape as `write_files`, down to the
3001
+ * second verdict under the lock, because the promise the ticket makes is
3002
+ * that an upload is judged "exactly as `write_file` would judge it". Three
3003
+ * gates run per path and a path that fails one is that path's outcome and no
3004
+ * more: the deployment's write hook, the platform-file rule above, and the
3005
+ * `mode`. What is judged ONCE for the whole call is the destination — a
3006
+ * caller who may not write the folder at all gets one refusal naming the
3007
+ * change-request route, rather than the same refusal repeated per entry.
3008
+ */
3009
+ const applyFileUpload = async (
3010
+ a: Record<string, unknown>,
3011
+ ctx: ToolContext,
3012
+ uploads: AgentUploadStore,
3013
+ ): Promise<unknown> => {
3014
+ const branch = a.branch as string;
3015
+ const token = a.token;
3016
+ if (typeof token !== 'string' || token === '') {
3017
+ throw new ToolError(
3018
+ 'Name the `token` `request_file_upload` answered with, after POSTing the file to its `uploadUrl`.',
3019
+ 400,
3020
+ { code: 'token-required' },
3021
+ );
3022
+ }
3023
+ const mode = modeOf(a);
3024
+ const destination = (a.destination as string).replace(/\/+$/, '');
3025
+ assertInsideRepo(destination, kbDirName);
3026
+ // CLAIMED, not consumed: an apply refused whole (a protected destination,
3027
+ // an archive that will not open) leaves the token alive so the caller can
3028
+ // retry somewhere else rather than send the bytes again. The claim is what
3029
+ // keeps it single-use meanwhile — a second apply finds the token in use.
3030
+ const upload = uploads.claim(token, ctx.user.id);
3031
+ let spent = false;
3032
+ try {
3033
+ const fs = await ctx.getFilesystem(branch);
3034
+ const root = await workspaceRoot(branch, ctx);
3035
+ // The destination, once, for the whole call. On a protected branch a
3036
+ // caller who may not write the folder gets the lock gate's own refusal —
3037
+ // which `rethrowAsWriteDenial` turns into `write-denied` with the
3038
+ // change-request steps — and nothing lands.
3039
+ const blockedDest = await writeBlocked(branch, ctx, [destination]);
3040
+ if (blockedDest.length > 0) throw await writeRefusal(branch, blockedDest[0], 'dir');
3041
+ if ((await kindOf(fs, destination)) === 'file') {
3042
+ throw new ToolError(
3043
+ `"${displayPath(destination)}" is a file, not a folder — \`destination\` names the folder the upload lands in.`,
3044
+ 409,
3045
+ { code: 'not_a_folder' },
3046
+ );
3047
+ }
3048
+
3049
+ const planned = await planUpload(upload, destination, kbDirName);
3050
+ const paths = planned.filter((p) => p.content !== undefined).map((p) => p.path as string);
3051
+ // One batched access read for every path, like `write_files` — empty on
3052
+ // a draft branch, where changes reach a protected branch only through a
3053
+ // change request.
3054
+ const blocked = new Set(await writeBlocked(branch, ctx, paths));
3055
+
3056
+ const writes: { path: string; content: Buffer }[] = [];
3057
+ const outcomes: Record<string, unknown>[] = [];
3058
+ /** The `files` entry for `writes[i]`, so the under-lock verdict can revise it. */
3059
+ const entryOf: Record<string, unknown>[] = [];
3060
+ for (const item of planned) {
3061
+ const entry: Record<string, unknown> = { path: item.path };
3062
+ outcomes.push(entry);
3063
+ if (item.content === undefined) {
3064
+ entry.outcome = 'refused';
3065
+ entry.error = item.error;
3066
+ entry.message = item.message;
3067
+ continue;
3068
+ }
3069
+ const wsPathOf = item.path;
3070
+ try {
3071
+ if (blocked.has(wsPathOf)) throw await writeRefusal(branch, wsPathOf);
3072
+ const platform = platformFileReason(wsPathOf);
3073
+ if (platform !== undefined) throw new ToolError(platform, 422, { code: 'platform_file' });
3074
+ // The git folder is never a workspace path, in any spelling. A ZIP
3075
+ // entry's name has already met this rule in `zipEntryNameRefusal`; a
3076
+ // SINGLE uploaded file's has not — `.git` is a name the upload
3077
+ // route's `validateFilename` accepts — and the preflight that reads
3078
+ // the caller's own arguments never sees it either, because the name
3079
+ // came from the upload, not from the call. Asked here so that path
3080
+ // is REFUSED like any other, with the rest of the upload landing,
3081
+ // rather than failing the whole apply from inside `writeFiles`.
3082
+ assertNoGitInternalsSegment(wsPathOf);
3083
+ assertRepoRootNameFree(wsPathOf, kbDirName);
3084
+ // A link already on disk under the destination must not redirect
3085
+ // these bytes — the rule `unzip` applies per entry, applied here on
3086
+ // the path the write will take.
3087
+ const link = await symlinkOnPath(root, wsPathOf);
3088
+ if (link !== undefined) {
3089
+ throw new ToolError(
3090
+ `"${wsPathOf}" goes through the symbolic link "${link}"; an upload never follows links.`,
3091
+ 400,
3092
+ { code: 'symlink' },
3093
+ );
3094
+ }
3095
+ writePolicy.assertPathWritable(ctx.sessionId, wsPathOf);
3096
+ await assertAgentWriteAllowed(agentAccessGate, ctx, branch, wsPathOf);
3097
+ // An earlier entry of this same upload counts as existing, as it
3098
+ // does in `write_files`: two `create` entries for one path are a
3099
+ // mistake the commit would otherwise hide.
3100
+ const exists =
3101
+ writes.some((w) => w.path === wsPathOf) || (await kindOf(fs, wsPathOf)) !== null;
3102
+ entry.outcome = decideWrite(mode, wsPathOf, exists);
3103
+ writes.push({ path: wsPathOf, content: item.content });
3104
+ entryOf.push(entry);
3105
+ } catch (err) {
3106
+ refuseEntry(entry, err);
3107
+ }
3108
+ }
3109
+
3110
+ // The mode gate again, with every path's lock held — the verdict the
3111
+ // answer carries, for the reason `write_file` states at length. A path
3112
+ // whose verdict changed under the lock is dropped from the batch and
3113
+ // reported refused, leaving the rest to land.
3114
+ const recheck = async (
3115
+ pending: readonly { path: string; content: Buffer }[],
3116
+ ): Promise<{ path: string; content: Buffer }[]> => {
3117
+ const kept: { path: string; content: Buffer }[] = [];
3118
+ for (let i = 0; i < pending.length; i++) {
3119
+ const entry = entryOf[i];
3120
+ try {
3121
+ const exists =
3122
+ kept.some((k) => k.path === pending[i].path) || (await kindOf(fs, pending[i].path)) !== null;
3123
+ entry.outcome = decideWrite(mode, pending[i].path, exists);
3124
+ kept.push(pending[i]);
3125
+ } catch (err) {
3126
+ refuseEntry(entry, err);
3127
+ }
3128
+ }
3129
+ return kept;
3130
+ };
3131
+ if (writes.length > 0) {
3132
+ // `write: true` guarantees a LockingFilesystem here; `writeFiles` lands
3133
+ // the whole set as ONE commit and takes a Buffer as content, so bytes
3134
+ // reach disk exactly as they were sent — no text decode anywhere on
3135
+ // the way, which is what makes a PNG and a backslash-heavy page land
3136
+ // with the checksum they were uploaded with.
3137
+ const batching = fs as unknown as {
3138
+ writeFiles(
3139
+ writes: { path: string; content: Buffer }[],
3140
+ summary: string,
3141
+ deletes: string[],
3142
+ check: (
3143
+ pending: readonly { path: string; content: Buffer }[],
3144
+ ) => Promise<{ path: string; content: Buffer }[]>,
3145
+ ): Promise<void>;
3146
+ };
3147
+ // In the DESTINATION folder's TURN, which `delete_folder` takes over the
3148
+ // same subtree (and `keepFolderOf` with it). `writeFiles` creates the
3149
+ // destination, and any folder above a zip entry on the way to it, as
3150
+ // part of landing the batch — and a folder delete running between that
3151
+ // creation and the commit enumerates the folder's files BEFORE these
3152
+ // exist and then removes the folder they are landing in, which is an
3153
+ // answer saying `created` for bytes that are already gone. The turn is
3154
+ // taken OUTSIDE `writeFiles`, so it is held across the under-lock
3155
+ // recheck and the commit both, and in the same order the delete takes
3156
+ // its own (the folder's turn first, then each path's lock), which is
3157
+ // what keeps two callers from waiting on each other's half.
3158
+ await ctx.workspaceService.withFolderTurn(workspaceIdForBranch(branch), destination, async () => {
3159
+ await batching.writeFiles(writes, `Apply upload of ${writes.length} file(s)`, [], recheck);
3160
+ });
3161
+ }
3162
+ // The token is spent once an ANSWER exists, even an answer in which
3163
+ // every path was refused: the apply ran and said what happened at each
3164
+ // path, and re-running it would say the same. Only a refusal that landed
3165
+ // nothing AND answered nothing (thrown above) gives the token back.
3166
+ spent = true;
3167
+ await uploads.consume(token);
3168
+ const listed = a.all === true ? outcomes : outcomes.slice(0, APPLY_ANSWER_CAP);
3169
+ return {
3170
+ destination,
3171
+ count: outcomes.filter((o) => o.outcome !== 'refused').length,
3172
+ total: outcomes.length,
3173
+ files: listed,
3174
+ ...(listed.length < outcomes.length ? { truncated: true } : {}),
3175
+ };
3176
+ } finally {
3177
+ if (!spent) uploads.release(token);
3178
+ }
3179
+ };
3180
+
3181
+ // Mounted only when the composition supplied a store — see the `uploads`
3182
+ // parameter. Core always does.
3183
+ if (uploads) {
3184
+ mount({
3185
+ name: 'request_file_upload',
3186
+ fileTool: false,
3187
+ description:
3188
+ // Within the description cap (`tool-registry/description-length.ts`):
3189
+ // why a file goes this way is one of the shared rules, and the header
3190
+ // spelling of the token is on the `uploadUrl` output, where the
3191
+ // address it changes is.
3192
+ 'Ask for a one-time address to send FILE BYTES to, so their content never passes through this conversation. ' +
3193
+ 'Use it for anything `write_file` cannot carry faithfully: a large file, a file full of backslashes or `\\u` ' +
3194
+ 'escapes, a binary file (a PNG, a PDF, a zip), or many files at once (zip them). ' +
3195
+ 'Returns `{ uploadUrl, token, expiresAt, expiresInSeconds, maxBytes }`. THEN: ' +
3196
+ '(1) POST the file as the raw request body to `uploadUrl` with `?filename=<name>` — ' +
3197
+ '`curl -X POST --data-binary @skill.zip "<uploadUrl>?filename=skill.zip"` — which answers what it received; ' +
3198
+ '(2) call `apply_file_upload` with the same `token`, a `branch` and a destination folder. ' +
3199
+ 'One token carries one file or one zip, is bound to you and expires at `expiresAt`: an upload nobody applies ' +
3200
+ 'by then is deleted, and one over `maxBytes` is refused when you send it, naming the limit.',
3201
+ inputs: { type: 'object', properties: {}, additionalProperties: false },
3202
+ outputs: {
3203
+ type: 'object',
3204
+ properties: {
3205
+ uploadUrl: str(
3206
+ 'The absolute URL to POST the bytes to. Carries the token; add `?filename=<name>`. To keep the token out ' +
3207
+ 'of a URL — when the command line you send from is logged or shared — POST to this address without its ' +
3208
+ 'last (token) segment and send the token in an `x-upload-token` header instead.',
3209
+ ),
3210
+ token: str(
3211
+ 'The token itself — what `apply_file_upload` takes, and what an `x-upload-token` header carries when you ' +
3212
+ 'would rather it not sit in a URL. Treat it as a credential.',
3213
+ ),
3214
+ expiresAt: str('ISO-8601 instant after which the token, and any bytes sent with it, are gone.'),
3215
+ expiresInSeconds: int('Seconds from now until `expiresAt`.'),
3216
+ maxBytes: int('The largest upload this deployment accepts, in bytes.'),
3217
+ },
3218
+ required: ['uploadUrl', 'token', 'expiresAt', 'expiresInSeconds', 'maxBytes'],
3219
+ },
3220
+ // A read-scoped caller has nothing to do with an upload token: the only
3221
+ // thing it unlocks is a write. Refused at the handler factory, by scope,
3222
+ // before the token is minted.
3223
+ write: true,
3224
+ handler: async (_a, ctx: ToolContext) => uploads.issue(ctx.user),
3225
+ });
3226
+
3227
+ mount({
3228
+ name: 'apply_file_upload',
3229
+ gated: true,
3230
+ description:
3231
+ 'Land a file you have already uploaded (see `request_file_upload`) in a folder on a branch, in ONE commit, as you. ' +
3232
+ 'A single file lands under the name it was sent with; a zip lands as its entries, keeping their folder structure. ' +
3233
+ 'Returns `{ destination, count, total, files }`: one entry per path, each `{ path, outcome }` — `created` / ' +
3234
+ '`replaced` / `updated`, or `refused` with `error` (the code) and `message` (why). `count` is how many landed and ' +
3235
+ '`total` how many paths there were; `files` is cut to the first 25 unless you pass `all: true`. ' +
3236
+ 'Every path is judged one by one — by your write access, the platform-file rules and what is already there — ' +
3237
+ 'exactly as `write_file` judges it, and a refused path does not stop the others. ' +
3238
+ 'The token is single-use: it is spent by the apply that lands it, and refused if you use it twice, let it ' +
3239
+ 'expire, or present one issued to somebody else. `mode` means what it means on `write_file`.',
3240
+ inputs: {
3241
+ type: 'object',
3242
+ properties: {
3243
+ branch: BRANCH_INPUT,
3244
+ token: str('The `token` from `request_file_upload`, after you have POSTed the file to its `uploadUrl`.'),
3245
+ destination: wsPath(kbDirName, 'Folder the upload lands in (created if it is not there yet)'),
3246
+ mode: WRITE_MODE_INPUT,
3247
+ all: {
3248
+ type: 'boolean',
3249
+ description:
3250
+ 'List EVERY path in `files` instead of the first 25. `total` always says how many there were, so ask for ' +
3251
+ 'all only when you need to read each outcome.',
3252
+ },
3253
+ sessionId: SESSION_ID_INPUT,
3254
+ },
3255
+ required: ['branch', 'token', 'destination'],
3256
+ additionalProperties: false,
3257
+ },
3258
+ outputs: {
3259
+ type: 'object',
3260
+ properties: {
3261
+ destination: str('The folder the upload was applied to (echoes the input).'),
3262
+ count: int('How many paths landed — the entries in `files` whose `outcome` is not `refused`.'),
3263
+ total: int('How many paths the upload held, whether or not `files` lists them all.'),
3264
+ files: {
3265
+ type: 'array',
3266
+ description: 'One entry per path, in the order the upload held them. Cut to 25 unless `all` was true.',
3267
+ items: {
3268
+ type: 'object',
3269
+ properties: {
3270
+ path: str('The workspace path this entry was judged at.'),
3271
+ outcome: {
3272
+ type: 'string',
3273
+ enum: ['created', 'replaced', 'updated', 'refused'],
3274
+ description: 'What happened at this path. `refused` means nothing was written there.',
3275
+ },
3276
+ error: str('Present when `outcome` is `refused`: the refusal code — e.g. `exists`, `missing`, `invalid_entry`, `platform_file`, `write-denied`.'),
3277
+ message: str('Present when `outcome` is `refused`: the full refusal, the same one `write_file` would have given.'),
3278
+ },
3279
+ required: ['path', 'outcome'],
3280
+ },
3281
+ },
3282
+ truncated: { type: 'boolean', description: 'True when `files` was cut: `total` is larger than what it lists. Pass `all: true` for the rest.' },
3283
+ },
3284
+ required: ['destination', 'count', 'total', 'files'],
3285
+ },
3286
+ write: true,
3287
+ // So a protected-branch refusal arrives as `write-denied`, with the
3288
+ // change-request steps, exactly as it does from write_file.
3289
+ proposable: true,
3290
+ handler: async (a, ctx: ToolContext) => applyFileUpload(a, ctx, uploads),
3291
+ });
3292
+ }
3293
+
2833
3294
  // ── shell (internal-only) ───────────────────────────────────────────────
2834
3295
  mount({
2835
3296
  name: 'execute_command',