@bevel-software/platform-core-backend 0.23.0 → 0.25.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 (238) 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 +13 -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 +95 -1
  64. package/dist/modules/database/migrate.d.ts.map +1 -1
  65. package/dist/modules/database/migrate.js +390 -2
  66. package/dist/modules/database/migrate.js.map +1 -1
  67. package/dist/modules/kb-fs/locking-filesystem.d.ts +17 -0
  68. package/dist/modules/kb-fs/locking-filesystem.d.ts.map +1 -1
  69. package/dist/modules/kb-fs/locking-filesystem.js +29 -0
  70. package/dist/modules/kb-fs/locking-filesystem.js.map +1 -1
  71. package/dist/modules/mcp/mcp.service.d.ts +8 -0
  72. package/dist/modules/mcp/mcp.service.d.ts.map +1 -1
  73. package/dist/modules/mcp/mcp.service.js +38 -8
  74. package/dist/modules/mcp/mcp.service.js.map +1 -1
  75. package/dist/modules/plugins/join-request-records.store.d.ts.map +1 -1
  76. package/dist/modules/plugins/join-request-records.store.js +7 -4
  77. package/dist/modules/plugins/join-request-records.store.js.map +1 -1
  78. package/dist/modules/tool-auth/external-api-key.service.d.ts.map +1 -1
  79. package/dist/modules/tool-auth/external-api-key.service.js +8 -2
  80. package/dist/modules/tool-auth/external-api-key.service.js.map +1 -1
  81. package/dist/modules/tool-manuals/tool-manuals.service.d.ts.map +1 -1
  82. package/dist/modules/tool-manuals/tool-manuals.service.js +30 -0
  83. package/dist/modules/tool-manuals/tool-manuals.service.js.map +1 -1
  84. package/dist/modules/tool-manuals/tool-manuals.tools.d.ts.map +1 -1
  85. package/dist/modules/tool-manuals/tool-manuals.tools.js +42 -31
  86. package/dist/modules/tool-manuals/tool-manuals.tools.js.map +1 -1
  87. package/dist/modules/tool-registry/description-length.d.ts +80 -0
  88. package/dist/modules/tool-registry/description-length.d.ts.map +1 -0
  89. package/dist/modules/tool-registry/description-length.js +108 -0
  90. package/dist/modules/tool-registry/description-length.js.map +1 -0
  91. package/dist/modules/workflow/git/git.service.d.ts +25 -0
  92. package/dist/modules/workflow/git/git.service.d.ts.map +1 -1
  93. package/dist/modules/workflow/git/git.service.js +40 -1
  94. package/dist/modules/workflow/git/git.service.js.map +1 -1
  95. package/dist/modules/workflow/pending-commits.service.d.ts.map +1 -1
  96. package/dist/modules/workflow/pending-commits.service.js +5 -1
  97. package/dist/modules/workflow/pending-commits.service.js.map +1 -1
  98. package/dist/modules/workflow/recovery-bot.d.ts.map +1 -1
  99. package/dist/modules/workflow/recovery-bot.js +7 -3
  100. package/dist/modules/workflow/recovery-bot.js.map +1 -1
  101. package/dist/modules/workflow/review-workflow/review-workflow.service.d.ts.map +1 -1
  102. package/dist/modules/workflow/review-workflow/review-workflow.service.js +12 -3
  103. package/dist/modules/workflow/review-workflow/review-workflow.service.js.map +1 -1
  104. package/dist/modules/workflow/workflow.service.d.ts.map +1 -1
  105. package/dist/modules/workflow/workflow.service.js +4 -1
  106. package/dist/modules/workflow/workflow.service.js.map +1 -1
  107. package/dist/modules/workspace/agent-upload.routes.d.ts +77 -0
  108. package/dist/modules/workspace/agent-upload.routes.d.ts.map +1 -0
  109. package/dist/modules/workspace/agent-upload.routes.js +210 -0
  110. package/dist/modules/workspace/agent-upload.routes.js.map +1 -0
  111. package/dist/modules/workspace/agent-upload.store.d.ts +284 -0
  112. package/dist/modules/workspace/agent-upload.store.d.ts.map +1 -0
  113. package/dist/modules/workspace/agent-upload.store.js +553 -0
  114. package/dist/modules/workspace/agent-upload.store.js.map +1 -0
  115. package/dist/modules/workspace/startup/steps/seed-tree.d.ts.map +1 -1
  116. package/dist/modules/workspace/startup/steps/seed-tree.js +3 -3
  117. package/dist/modules/workspace/startup/steps/seed-tree.js.map +1 -1
  118. package/dist/modules/workspace/startup/steps/template-source.d.ts +40 -0
  119. package/dist/modules/workspace/startup/steps/template-source.d.ts.map +1 -1
  120. package/dist/modules/workspace/startup/steps/template-source.js +46 -4
  121. package/dist/modules/workspace/startup/steps/template-source.js.map +1 -1
  122. package/dist/modules/workspace/upload-limits.d.ts +13 -0
  123. package/dist/modules/workspace/upload-limits.d.ts.map +1 -0
  124. package/dist/modules/workspace/upload-limits.js +13 -0
  125. package/dist/modules/workspace/upload-limits.js.map +1 -0
  126. package/dist/modules/workspace/workspace.routes.d.ts.map +1 -1
  127. package/dist/modules/workspace/workspace.routes.js +1 -1
  128. package/dist/modules/workspace/workspace.routes.js.map +1 -1
  129. package/dist/modules/workspace/workspace.service.d.ts +13 -0
  130. package/dist/modules/workspace/workspace.service.d.ts.map +1 -1
  131. package/dist/modules/workspace/workspace.service.js +61 -33
  132. package/dist/modules/workspace/workspace.service.js.map +1 -1
  133. package/dist/modules/workspace/workspace.tools.d.ts +11 -9
  134. package/dist/modules/workspace/workspace.tools.d.ts.map +1 -1
  135. package/dist/modules/workspace/workspace.tools.js +570 -134
  136. package/dist/modules/workspace/workspace.tools.js.map +1 -1
  137. package/dist/modules/workspace/write-denial.d.ts +0 -6
  138. package/dist/modules/workspace/write-denial.d.ts.map +1 -1
  139. package/dist/modules/workspace/write-denial.js +0 -6
  140. package/dist/modules/workspace/write-denial.js.map +1 -1
  141. package/dist/modules/workspace/zip-entry-rules.d.ts +114 -0
  142. package/dist/modules/workspace/zip-entry-rules.d.ts.map +1 -0
  143. package/dist/modules/workspace/zip-entry-rules.js +154 -0
  144. package/dist/modules/workspace/zip-entry-rules.js.map +1 -0
  145. package/dist/shared/column-crypto.d.ts +194 -0
  146. package/dist/shared/column-crypto.d.ts.map +1 -0
  147. package/dist/shared/column-crypto.js +144 -0
  148. package/dist/shared/column-crypto.js.map +1 -0
  149. package/dist/shared/token-crypto.d.ts.map +1 -1
  150. package/dist/shared/token-crypto.js +25 -1
  151. package/dist/shared/token-crypto.js.map +1 -1
  152. package/dist/tenancy/static-tenant-source.d.ts.map +1 -1
  153. package/dist/tenancy/static-tenant-source.js +1 -0
  154. package/dist/tenancy/static-tenant-source.js.map +1 -1
  155. package/dist/tenancy/tenant-secrets.d.ts +5 -1
  156. package/dist/tenancy/tenant-secrets.d.ts.map +1 -1
  157. package/dist/tenancy/tenant-secrets.js +4 -0
  158. package/dist/tenancy/tenant-secrets.js.map +1 -1
  159. package/kb-template/AGENTS.md +42 -0
  160. package/migrations/0016_pii_encryption.sql +20 -0
  161. package/migrations/meta/0016_snapshot.json +2327 -0
  162. package/migrations/meta/_journal.json +7 -0
  163. package/package.json +3 -3
  164. package/src/core/__tests__/lifecycle.test.ts +71 -4
  165. package/src/core/create-core-server.ts +21 -3
  166. package/src/core/create-core-services.ts +27 -1
  167. package/src/core/lifecycle.ts +19 -0
  168. package/src/core-config.ts +18 -0
  169. package/src/index.ts +25 -0
  170. package/src/modules/access/__tests__/users-db-double.ts +21 -12
  171. package/src/modules/access/access.routes.ts +4 -1
  172. package/src/modules/access/directory-sync-bot.ts +7 -3
  173. package/src/modules/agent-instructions/__tests__/agent-instructions.route.test.ts +8 -4
  174. package/src/modules/agent-instructions/__tests__/compose.test.ts +19 -10
  175. package/src/modules/agent-instructions/__tests__/shared-file-rules.test.ts +238 -0
  176. package/src/modules/agent-instructions/agent-instructions.routes.ts +12 -2
  177. package/src/modules/agent-instructions/compose.ts +50 -7
  178. package/src/modules/agent-instructions/index.ts +12 -0
  179. package/src/modules/agent-instructions/shared-file-rules.ts +314 -0
  180. package/src/modules/audit/agent-audit.service.ts +4 -2
  181. package/src/modules/auth/__tests__/account-deactivation.test.ts +2 -1
  182. package/src/modules/auth/__tests__/account-erasure.approval-gate.test.ts +6 -2
  183. package/src/modules/auth/__tests__/account.routes.test.ts +6 -3
  184. package/src/modules/auth/__tests__/auth.service.test.ts +3 -1
  185. package/src/modules/auth/account-erasure.service.ts +69 -18
  186. package/src/modules/auth/auth.service.ts +33 -23
  187. package/src/modules/code-mode/__tests__/chain-runtime.e2e.test.ts +335 -0
  188. package/src/modules/code-mode/__tests__/code-mode.tool.test.ts +46 -2
  189. package/src/modules/code-mode/code-mode.tool.ts +80 -34
  190. package/src/modules/database/__tests__/connection.test.ts +12 -0
  191. package/src/modules/database/__tests__/pii-backfill.pg.test.ts +780 -0
  192. package/src/modules/database/connection.ts +117 -0
  193. package/src/modules/database/core-schema.ts +81 -31
  194. package/src/modules/database/migrate.ts +540 -2
  195. package/src/modules/kb-fs/__tests__/locking-filesystem.test.ts +93 -0
  196. package/src/modules/kb-fs/locking-filesystem.ts +37 -0
  197. package/src/modules/mcp/__tests__/mcp.e2e.test.ts +4 -3
  198. package/src/modules/mcp/__tests__/mcp.service.test.ts +47 -7
  199. package/src/modules/mcp/mcp.service.ts +46 -7
  200. package/src/modules/plugins/join-request-records.store.ts +7 -4
  201. package/src/modules/tool-auth/external-api-key.service.ts +8 -2
  202. package/src/modules/tool-manuals/__tests__/tool-manuals.service.test.ts +151 -0
  203. package/src/modules/tool-manuals/tool-manuals.service.ts +37 -0
  204. package/src/modules/tool-manuals/tool-manuals.tools.ts +44 -31
  205. package/src/modules/tool-registry/__tests__/tool-description-length.test.ts +378 -0
  206. package/src/modules/tool-registry/description-length.ts +111 -0
  207. package/src/modules/workflow/git/__tests__/git.service.prFetchFailure.test.ts +170 -0
  208. package/src/modules/workflow/git/git.service.ts +47 -1
  209. package/src/modules/workflow/pending-commits.service.ts +5 -1
  210. package/src/modules/workflow/recovery-bot.ts +7 -3
  211. package/src/modules/workflow/review-workflow/__tests__/carry-approvals-forward.test.ts +4 -0
  212. package/src/modules/workflow/review-workflow/__tests__/erase-approver.test.ts +25 -3
  213. package/src/modules/workflow/review-workflow/review-workflow.service.ts +12 -3
  214. package/src/modules/workflow/workflow.service.ts +4 -1
  215. package/src/modules/workspace/__tests__/agent-uploads.test.ts +1604 -0
  216. package/src/modules/workspace/__tests__/escape-sequences.routes.test.ts +24 -14
  217. package/src/modules/workspace/__tests__/workspace.service.any-workspace-credentials.test.ts +156 -0
  218. package/src/modules/workspace/__tests__/workspace.service.replaced-repository.test.ts +77 -1
  219. package/src/modules/workspace/__tests__/workspace.service.test.ts +57 -0
  220. package/src/modules/workspace/__tests__/workspace.tools.agents-file.test.ts +39 -36
  221. package/src/modules/workspace/__tests__/workspace.tools.test.ts +196 -46
  222. package/src/modules/workspace/agent-upload.routes.ts +214 -0
  223. package/src/modules/workspace/agent-upload.store.ts +668 -0
  224. package/src/modules/workspace/startup/steps/__tests__/steps.test.ts +9 -9
  225. package/src/modules/workspace/startup/steps/seed-tree.ts +3 -6
  226. package/src/modules/workspace/startup/steps/template-source.ts +53 -5
  227. package/src/modules/workspace/upload-limits.ts +12 -0
  228. package/src/modules/workspace/workspace.routes.ts +1 -2
  229. package/src/modules/workspace/workspace.service.ts +63 -37
  230. package/src/modules/workspace/workspace.tools.ts +647 -148
  231. package/src/modules/workspace/write-denial.ts +0 -8
  232. package/src/modules/workspace/zip-entry-rules.ts +173 -0
  233. package/src/shared/__tests__/column-crypto.test.ts +217 -0
  234. package/src/shared/column-crypto.ts +218 -0
  235. package/src/shared/token-crypto.ts +28 -1
  236. package/src/tenancy/__tests__/static-tenant-source.test.ts +4 -0
  237. package/src/tenancy/static-tenant-source.ts +1 -0
  238. package/src/tenancy/tenant-secrets.ts +5 -1
@@ -1,16 +1,17 @@
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 { ToolError } from '../tool-helpers/tool.contract.js';
5
6
  import { BRANCH_INPUT, toolDef } from '../tool-helpers/tool-def.js';
6
7
  import { notifyAgentRead, assertAgentWriteAllowed, SESSION_ID_INPUT, } from './agent-access.gate.js';
7
8
  import { requireInternalSource, requireExternalSource } from '../tool-auth/tool-auth.middleware.js';
8
9
  import { workspaceIdForBranch } from '../../shared/workspace-id.js';
9
- import { assertBranchProvided } from '../../shared/domain-errors.js';
10
+ import { assertBranchProvided, GitInternalsError, WorkflowValidationError } from '../../shared/domain-errors.js';
10
11
  // Leaf-level shared primitive (same exception `workspace.service.ts` already
11
12
  // relies on) — not a workflow service, so this stays inside the module boundary.
12
13
  import { assertValidBranchName } from '../kb-fs/branch-name.js';
13
- import { assertInsideRepo, assertRepoRootNameFreeArgs, normalizePathArgs } from '../kb-fs/repo-path.js';
14
+ import { assertInsideRepo, assertRepoRootNameFree, assertRepoRootNameFreeArgs, isInsideRepo, normalizePathArgs, } from '../kb-fs/repo-path.js';
14
15
  import { GitGuardedFilesystem } from '../kb-fs/git-guarded-filesystem.js';
15
16
  import { assertNoGitInternalsSegment, assertNotGitInternals, hasGitInternalsSegment } from '../../shared/git-internals.js';
16
17
  import { isRolesYamlPath } from '../access-model/roles-yaml-guard.js';
@@ -23,14 +24,16 @@ import { fileTypeOf, needsContent } from './file-readers/content-mode.js';
23
24
  import { createFileReaderRegistry } from './file-readers/file-reader.registry.js';
24
25
  import { DocumentReader } from './file-readers/document-reader.js';
25
26
  import { mcpImageResult } from '@bevel-software/platform-mcp-core';
26
- import { LEGACY_AGENTS_FILE, folderPlaceholderPath, isFolderPlaceholder, isPlatformFile, isPlatformFolder, platformFileCreationRefusal, platformFileNames, platformFileRefusal, platformFolderRefusal, entryExistsMessage, } from '@bevel-software/platform-shared';
27
+ import { folderPlaceholderPath, isFolderPlaceholder, isPlatformFile, isPlatformFolder, platformFileCreationRefusal, platformFileRefusal, platformFileUploadRefusal, platformFolderRefusal, entryExistsMessage, } from '@bevel-software/platform-shared';
27
28
  import { AccessDeniedError } from '../access-model/access-errors.js';
28
29
  import { removeEmptyDirs } from './empty-dirs.js';
29
- import { PROPOSAL_ROUTE_NOTE, rethrowAsWriteDenial } from './write-denial.js';
30
+ import { rethrowAsWriteDenial } from './write-denial.js';
31
+ import { sharedRulesPointer } from '../agent-instructions/shared-file-rules.js';
30
32
  import { notFound, orDeclaredNotFound, orNotFound } from './not-found.js';
31
33
  import { logger } from '../../shared/logging.js';
32
34
  import { printable } from '../../shared/printable.js';
33
35
  import { DestinationTakenError, inspectDestination } from '../../shared/rename-no-replace.js';
36
+ import { isSymlinkZipEntry, isZipNoiseEntry, readZipEntry, zipEntryName, zipEntryNameRefusal, zipEntrySegments, } from './zip-entry-rules.js';
34
37
  const log = logger('workspace-tools');
35
38
  /** How many files `file_stat` counts under a folder before it stops and says so. */
36
39
  const DESCENDANTS_CAP = 10_000;
@@ -122,53 +125,23 @@ async function keepFolderOf(fs, ctx, branch, removedPath, kbDirName) {
122
125
  throw err;
123
126
  }
124
127
  }
125
- /**
126
- * Appended (centrally, in `mount`) to EVERY workspace tool description. The
127
- * platform's managed agent guide sits at the workspace root and documents the
128
- * conventions of that knowledge base; agents (ours and external) should consult
129
- * it before touching files. It rides on every entrypoint — reads (grep/
130
- * list_files/file_stat) included — because any of them can be a session's first
131
- * touch.
132
- *
133
- * `CLAUDE.md` is named as a fallback because knowledge bases seeded before the
134
- * rename still carry one, and the seeder never deletes a file it did not
135
- * expect. Naming both means an agent finds the conventions either way, instead
136
- * of reading none because it looked for the newer name and stopped.
137
- *
138
- * WHEN THE GUIDE HAS BEEN RENAMED the sentence names two files, ours first. The
139
- * second is the organisation's OWN `AGENTS.md`, which on such a deployment is
140
- * ordinary content the platform never touches — and which no harness reads for a
141
- * remote agent, because a remote agent has no checkout. Telling it to read both
142
- * is the only way the conventions the customer actually wrote reach the agent
143
- * working in their knowledge base. Under the default name the wording collapses
144
- * to the one file it has always named.
145
- *
146
- * A FUNCTION of the layout, called when a description is built: the name is a
147
- * deployment setting, and a module-scope string would snapshot the default.
148
- */
149
- function kbConventionsNote(layout) {
150
- const agentsFile = layout.agentsFile ?? LEGACY_AGENTS_FILE;
151
- if (agentsFile === LEGACY_AGENTS_FILE) {
152
- 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.';
153
- }
154
- return (` Before your first read or change in a workspace, read \`${agentsFile}\` at the KB root, then ` +
155
- '`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.');
156
- }
157
- /** The platform files as a tool description lists them — the guide under its own name. */
158
- function platformFileList(layout) {
159
- return platformFileNames(layout)
160
- .map((name) => `\`${name}\``)
161
- .join(', ');
162
- }
163
128
  const int = (description) => ({ type: 'integer', description });
164
129
  const str = (description) => ({ type: 'string', description });
165
130
  /**
166
- * Where pictures go, on the two tools that write pages. An agent in core cannot
167
- * upload bytes yet (TODOS.md), but it can write the page with the link a person
168
- * will satisfy, and this sentence is what keeps every page it writes on the
169
- * README's convention: images beside the page, linked relatively.
131
+ * The upload route, named on every tool that takes content as a JSON string.
132
+ *
133
+ * ONE sentence, and the tools' own: it is what stops the three failures the
134
+ * route was built for. An agent landing 27 files read each one and typed it
135
+ * out again as a tool argument: a 37 KB write was truncated mid-answer, a page
136
+ * of regex backslashes failed to parse as a JSON parameter, and a PNG could not
137
+ * be sent at all. None of that is discoverable from a refusal — a truncated
138
+ * write reports success — so the tools that invite it name where the bytes
139
+ * should go instead, in the description itself, for a client that reads
140
+ * nothing else. WHY, and how the route is used, is one of the shared rules
141
+ * (`agent-instructions/shared-file-rules.ts`): said in full on three
142
+ * descriptions it took each of them past the length a client cuts at.
170
143
  */
171
- const IMAGE_CONVENTION_NOTE = ' 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.';
144
+ const UPLOAD_ROUTE_NOTE = ' Large, escape-heavy or binary content does not go through here: use `request_file_upload` + `apply_file_upload`.';
172
145
  /**
173
146
  * A path input that names the clone folder, and says what happens when it does
174
147
  * not. The tools are rooted at the WORKSPACE dir, one level above the git clone,
@@ -202,6 +175,9 @@ const RESERVED_ROOT_NAME_TARGETS = {
202
175
  copy_file: ['dest'],
203
176
  move_file: ['dest'],
204
177
  unzip: ['destination'],
178
+ // The folder the upload lands in. Each of its own paths is checked again
179
+ // inside the handler — an archive chooses its entry names, not the caller.
180
+ apply_file_upload: ['destination'],
205
181
  };
206
182
  function asText(content) {
207
183
  return typeof content === 'string' ? content : content.toString('utf8');
@@ -219,14 +195,6 @@ function asBytes(content) {
219
195
  * `read_file`, which extracts unbudgeted) will cover the rest.
220
196
  */
221
197
  const UNCACHED_DOCS_PER_GREP = 20;
222
- /**
223
- * THE binary capability contract, stated once and appended (in `mount`) to
224
- * every file tool's description — which is also what `tools_info` returns.
225
- * The split it states is enforced by the reader registry: the text tools
226
- * refuse what their reader marks not `textEditable` (and binary content under
227
- * any name) with a `binary_not_writable` refusal; the byte tools never look.
228
- */
229
- export const CONTENT_RULE = ' 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.';
230
198
  /** What a `binary_not_writable` refusal points to, in the order to try them. */
231
199
  const BINARY_USE_INSTEAD = ['upload', 'copy_file', 'move_file'];
232
200
  /**
@@ -237,7 +205,7 @@ const BINARY_USE_INSTEAD = ['upload', 'copy_file', 'move_file'];
237
205
  */
238
206
  function binaryNotWritable(fileKind, explanation) {
239
207
  return new ToolError(`${explanation} [binary_not_writable: this file's kind is ${fileKind}; write_file, write_files and edit_file accept text only. ` +
240
- 'Use upload for new bytes (`request_upload_token` + `apply_upload` where offered, otherwise Upload in the app), ' +
208
+ 'Use upload for new bytes (`request_file_upload` + `apply_file_upload`, or Upload in the app), ' +
241
209
  'or copy_file / move_file to place bytes that are already in the workspace.]', 415, { kind: 'binary_not_writable', fileKind, useInstead: [...BINARY_USE_INSTEAD] });
242
210
  }
243
211
  /** The generic why, for a reader without format-specific refusal copy. */
@@ -275,14 +243,14 @@ function assertNotDocumentEdit(readers, path) {
275
243
  *
276
244
  * Costs one read of the existing file, and only for readers that ask the
277
245
  * question. A path with nothing at it is a CREATE: there is nothing to destroy.
278
- * Returns the bytes it read (so a caller that needs the content next —
279
- * `edit_file` — does not read the file a second time), or undefined when it
280
- * had no reason to read or nothing existed.
246
+ * For the tools that REPLACE a file without needing what it held (`write_file`,
247
+ * `write_files`); `edit_file` holds the bytes already and asks
248
+ * `assertBytesTextEditable` of each reading it takes.
281
249
  */
282
250
  async function assertNotBinaryOverwrite(readers, path, fs) {
283
251
  const reader = readers.readerFor(path);
284
252
  if (reader.editRefusalForExisting === undefined)
285
- return undefined;
253
+ return;
286
254
  let existing;
287
255
  try {
288
256
  existing = asBytes(await fs.readFile(path));
@@ -293,13 +261,21 @@ async function assertNotBinaryOverwrite(readers, path, fs) {
293
261
  // permissions, I/O — means the existing content could not be inspected:
294
262
  // propagate it rather than let the write destroy bytes the gate never saw.
295
263
  if (isAbsence(err))
296
- return undefined; // nothing there yet
264
+ return; // nothing there yet
297
265
  throw err;
298
266
  }
299
- const refusal = reader.editRefusalForExisting(existing, path);
267
+ assertBytesTextEditable(readers, path, existing);
268
+ }
269
+ /**
270
+ * The same refusal, over bytes the caller already holds. Split out so a tool
271
+ * that reads the file more than once — `edit_file`, before the lock and again
272
+ * under it — judges EVERY reading with the one rule, and the bytes it replaces
273
+ * are always bytes this gate has seen.
274
+ */
275
+ function assertBytesTextEditable(readers, path, existing) {
276
+ const refusal = readers.readerFor(path).editRefusalForExisting?.(existing, path) ?? null;
300
277
  if (refusal !== null)
301
278
  throw binaryNotWritable('binary', refusal);
302
- return existing;
303
279
  }
304
280
  /**
305
281
  * The `mode` input, on both write tools. Stated on the input itself and not
@@ -314,30 +290,6 @@ const WRITE_MODE_INPUT = {
314
290
  'holds something; `overwrite` replaces what is there, and creates the file when there is nothing; `update` replaces an ' +
315
291
  'EXISTING file and refuses (`missing`) a path that holds nothing.',
316
292
  };
317
- /** The same three modes, said once, for both tool descriptions. */
318
- const WRITE_MODE_NOTE = ' `mode` decides what may happen at a path and DEFAULTS TO `create`: `create` writes a new file and refuses a path that ' +
319
- 'already exists (`exists`, with the path — pass `mode: overwrite` to replace it), `overwrite` replaces what is there ' +
320
- '(creating it if there is nothing), `update` replaces an existing file and refuses a path that does not exist (`missing`). ' +
321
- 'A refused path is left exactly as it was.';
322
- /**
323
- * What an agent needs to know about escape sequences in the content it sends,
324
- * on the three tools that take content as a JSON string.
325
- *
326
- * The three write routes — the MCP endpoint, the `/api/agent/tools/<name>`
327
- * route and `call_tool_chain` — were measured end to end against raw requests
328
- * and a byte-level read of the stored file (see
329
- * `__tests__/escape-sequences.routes.test.ts`): each stores content exactly as
330
- * the JSON string value decodes ONCE. So when an escape arrives already
331
- * decoded, the decoding happened in the client that built the request, and no
332
- * tool here can tell that content from content that was meant to be decoded.
333
- * Hence a warning rather than a fix, and the pointer to the one route whose
334
- * payload is bytes rather than a JSON string.
335
- */
336
- const ESCAPE_SEQUENCE_NOTE = ' Escape sequences: some clients decode them in arguments before sending, so content meant to CONTAIN an escape rather ' +
337
- 'than what it stands for (the six characters backslash, `u`, `0`, `0`, `4`, `1`, say, rather than the letter `A`) can ' +
338
- 'reach this tool already decoded — what arrives is stored byte for byte, so when that distinction matters, verify what ' +
339
- 'landed (`read_file`, or a hash) and send such content through the upload route (`request_upload_token` + `apply_upload` ' +
340
- 'where offered, otherwise Upload in the app), which lands it unchanged.';
341
293
  /** The refusal `create` gives on a path that already holds something. */
342
294
  function pathExists(path) {
343
295
  return new ToolError(`"${displayPath(path)}" already exists — pass mode: overwrite to replace it, or write to a different path.`, 409, { code: 'exists', path });
@@ -361,6 +313,144 @@ function decideWrite(mode, path, exists) {
361
313
  return 'updated';
362
314
  return exists ? 'replaced' : 'created';
363
315
  }
316
+ /**
317
+ * How many of an upload's paths the answer NAMES before it stops and says how
318
+ * many there were. A 300-file zip's full outcome list is pages of text an agent
319
+ * pays for on every call; 25 is enough to see the shape of what happened, and
320
+ * `total` plus `truncated` say that there is more. `all: true` asks for the
321
+ * rest, for a caller that really does have to read each one.
322
+ */
323
+ const APPLY_ANSWER_CAP = 25;
324
+ /**
325
+ * How many entries of one uploaded archive are landed, and how many bytes of
326
+ * uncompressed content in total.
327
+ *
328
+ * Tighter than `unzip`'s own caps on purpose. An apply lands its whole set as
329
+ * ONE commit, which means every entry's bytes are held in memory at once —
330
+ * the property that makes the commit atomic is the one that makes a zip bomb
331
+ * expensive. The upload itself is already bounded by the deployment's upload
332
+ * limit; these bound what that upload is allowed to expand into.
333
+ */
334
+ const APPLY_MAX_ENTRIES = 5_000;
335
+ const APPLY_MAX_TOTAL_BYTES = 128 * 1024 * 1024; // 128 MB uncompressed
336
+ /**
337
+ * Turn a stored upload into one planned path per file.
338
+ *
339
+ * A single file is one path: the destination plus the name it was sent with.
340
+ * A zip is one path per member, with the member's folder structure kept under
341
+ * the destination — judged by the same entry rules `unzip` applies
342
+ * (`zip-entry-rules.ts`), plus one `unzip` does not have: an entry that is a
343
+ * symbolic LINK is refused outright. A zip stores a link as a member whose
344
+ * bytes are its target text, so a reader that ignored the mode bits would
345
+ * write that text out as a file — content nobody sent, under a name that was
346
+ * meant to point elsewhere.
347
+ */
348
+ /** The refusal an entry gets when the archive would expand past what one commit lands. */
349
+ function tooLargeToApply() {
350
+ return `This archive expands past the ${APPLY_MAX_TOTAL_BYTES} byte total the apply lands in one commit; this entry was not applied.`;
351
+ }
352
+ async function planUpload(upload, destination, kbDirName) {
353
+ const bytes = await nodeFs.readFile(upload.absolutePath);
354
+ if (upload.kind !== 'zip') {
355
+ return [{ path: `${destination}/${upload.filename}`, content: bytes }];
356
+ }
357
+ let zip;
358
+ try {
359
+ zip = new AdmZip(bytes);
360
+ }
361
+ catch (err) {
362
+ throw new ToolError(`"${upload.filename}" could not be opened as a .zip archive: ${err instanceof Error ? err.message : String(err)}`, 422, { code: 'unreadable_archive' });
363
+ }
364
+ const planned = [];
365
+ let seen = 0;
366
+ let totalBytes = 0;
367
+ for (const entry of zip.getEntries()) {
368
+ const rawName = zipEntryName(entry.entryName);
369
+ if (isZipNoiseEntry(rawName))
370
+ continue;
371
+ if (seen >= APPLY_MAX_ENTRIES) {
372
+ planned.push({
373
+ path: rawName || '(empty)',
374
+ error: 'too_many_entries',
375
+ message: `This archive holds more than ${APPLY_MAX_ENTRIES} entries; the rest were not applied.`,
376
+ });
377
+ continue;
378
+ }
379
+ seen++;
380
+ const nameRefusal = zipEntryNameRefusal(rawName);
381
+ if (nameRefusal !== null) {
382
+ planned.push({ path: rawName || '(empty)', error: 'invalid_entry', message: nameRefusal });
383
+ continue;
384
+ }
385
+ if (isSymlinkZipEntry(entry)) {
386
+ planned.push({
387
+ path: rawName,
388
+ error: 'link',
389
+ message: `"${rawName}" is a symbolic link, not a file; an upload lands files, never links.`,
390
+ });
391
+ continue;
392
+ }
393
+ // A folder comes into being with the files under it (the write path mkdirs
394
+ // each parent), so a directory member has nothing of its own to land.
395
+ if (entry.isDirectory)
396
+ continue;
397
+ const segments = zipEntrySegments(rawName);
398
+ const target = [destination, ...segments].join('/');
399
+ // Belt and braces: `zipEntryNameRefusal` already refuses a `..` segment
400
+ // and a root-anchored name, so nothing should reach here that climbs out.
401
+ // The check stays because the cost of being wrong about that is bytes
402
+ // landing outside the folder the caller named.
403
+ if (!target.startsWith(`${destination}/`) || !isInsideRepo(target, kbDirName)) {
404
+ planned.push({ path: rawName, error: 'invalid_entry', message: 'Path escapes destination' });
405
+ continue;
406
+ }
407
+ // Through the one bounded reader `unzip` uses too, capped at what is left
408
+ // of the budget: a deflate stream can expand a thousandfold, and the
409
+ // header's declared size is the archive's claim, not a fact — an entry
410
+ // declaring ZERO would otherwise be inflated with no cap at all (see
411
+ // `readZipEntry`). A read that fails is this entry's outcome and no more.
412
+ const read = readZipEntry(entry, APPLY_MAX_TOTAL_BYTES - totalBytes);
413
+ if (!read.ok) {
414
+ planned.push(read.reason === 'too_large'
415
+ ? { path: rawName, error: 'too_large', message: tooLargeToApply() }
416
+ : { path: rawName, error: 'unreadable_entry', message: `"${rawName}" could not be read: ${read.detail}.` });
417
+ continue;
418
+ }
419
+ totalBytes += read.data.byteLength;
420
+ planned.push({ path: target, content: read.data });
421
+ }
422
+ return planned;
423
+ }
424
+ /**
425
+ * Record on `entry` that this path was refused, saying what the gate that
426
+ * refused it said. Four kinds of refusal count as one path's outcome: a
427
+ * typed tool refusal (`exists`, `platform_file`, the mode gate), a permission
428
+ * refusal (the caller may not write this path, where the DESTINATION was
429
+ * writable), the git folder in any spelling, and a path-shape refusal from the
430
+ * repository rules. Anything else
431
+ * is not a verdict about this path — it is a gate failing — so it travels on
432
+ * and the whole apply fails loudly, exactly as it does in `write_files`.
433
+ */
434
+ function refuseEntry(entry, err) {
435
+ entry.outcome = 'refused';
436
+ if (err instanceof ToolError) {
437
+ const details = (err.details ?? {});
438
+ entry.error = details.code ?? details.kind ?? 'refused';
439
+ entry.message = err.message;
440
+ return;
441
+ }
442
+ if (err instanceof AccessDeniedError) {
443
+ entry.error = 'write-denied';
444
+ entry.message = err.message;
445
+ return;
446
+ }
447
+ if (err instanceof GitInternalsError || err instanceof WorkflowValidationError) {
448
+ entry.error = err.payload?.kind ?? 'refused';
449
+ entry.message = err.message;
450
+ return;
451
+ }
452
+ throw err;
453
+ }
364
454
  /** The three modes, as a set the handler can check a raw argument against. */
365
455
  const WRITE_MODES = ['create', 'overwrite', 'update'];
366
456
  /**
@@ -541,7 +631,16 @@ skillSaveCheck,
541
631
  * would be made on. Optional so tool harnesses need not wire it; the read
542
632
  * verdict alone then decides, which differs only at a root.
543
633
  */
544
- changeGate) {
634
+ changeGate,
635
+ /**
636
+ * The upload-token store behind `request_file_upload` / `apply_file_upload`
637
+ * — the route an agent lands bytes by, without their content passing
638
+ * through the model. Optional for the same reason the two above are: a tool
639
+ * harness that is about the file primitives need not stand one up. Every
640
+ * real composition wires it (`create-core-server.ts`), and without it the
641
+ * two tools are not mounted at all rather than mounted and broken.
642
+ */
643
+ uploads) {
545
644
  const { kbDirName } = kb;
546
645
  /**
547
646
  * The one extension→reader registry every read-shaped decision routes
@@ -1083,10 +1182,14 @@ changeGate) {
1083
1182
  const linkRefusal = (path) => `"${path}" is a symbolic link; the agent tools never follow or remove links.`;
1084
1183
  const mount = (spec) => {
1085
1184
  const path = `/api/agent/tools/${spec.name}`;
1086
- // Every workspace entrypoint carries the agent-guide reminder, every file
1087
- // tool the one content rule, and every tool a permission can refuse the
1088
- // proposal route — appended once here so no tool (especially the
1089
- // read-only ones a session hits first) can miss them.
1185
+ // Every description ends with ONE sentence pointing at the rules these
1186
+ // tools share — the content rule, the agent guide, the write modes, the
1187
+ // dry-run protocol, the proposal route. They used to be appended here in
1188
+ // FULL, which made a description several thousand characters of text the
1189
+ // agent had already read on the tool above, and clients cut a long
1190
+ // description from the END, where what is specific to the tool sits. The
1191
+ // rules themselves are in the handshake instructions and in the managed
1192
+ // guide (see `shared-file-rules.ts`), stated once and from one text.
1090
1193
  // Whether a call to this tool MUST name a branch, read off the tool's own
1091
1194
  // declaration rather than assumed of the family. Every tool mounted here
1092
1195
  // requires `branch` today; keying on the schema means a tool that declares
@@ -1094,10 +1197,8 @@ changeGate) {
1094
1197
  // own route) is not handed a refusal it never asked for.
1095
1198
  const requiresBranch = (spec.inputs.required ?? []).includes('branch');
1096
1199
  const describe = () => (typeof spec.description === 'function' ? spec.description() : spec.description) +
1097
- (spec.proposable ? PROPOSAL_ROUTE_NOTE : '') +
1098
- (spec.fileTool === false ? '' : CONTENT_RULE) +
1099
- kbConventionsNote(kb.layout) +
1100
- (spec.gated ? agentAccessGate.notes.gatedToolNote() : '');
1200
+ (spec.gated ? agentAccessGate.notes.gatedToolNote() : '') +
1201
+ sharedRulesPointer(kb.layout);
1101
1202
  const def = toolDef({
1102
1203
  name: spec.name,
1103
1204
  description: describe(),
@@ -1246,7 +1347,13 @@ changeGate) {
1246
1347
  mount({
1247
1348
  name: 'read_file',
1248
1349
  gated: true,
1249
- description: '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.',
1350
+ description: 'Read a workspace file as text. Returns `{ path, content }`. What comes back for a document, an email file, an image ' +
1351
+ 'or any other binary file is the content rule\'s business (see the shared rules): text files as text, documents and ' +
1352
+ 'email files as extracted text, an image as the picture itself, anything else as a one-line description. ' +
1353
+ 'Optional `offset`/`limit` slice the content (characters for a file, bytes for a `__tool_chain_spill__/…` ref; ignored ' +
1354
+ 'for an image) — use them to page through large files or a `call_tool_chain` spill rather than reading multi-MB in full. ' +
1355
+ 'It also reads a `__tool_chain_spill__/…` ref back from a truncated `call_tool_chain`: such a ref belongs to no ' +
1356
+ 'workspace, so `branch` is ignored for it.',
1250
1357
  inputs: {
1251
1358
  type: 'object',
1252
1359
  properties: {
@@ -1350,12 +1457,17 @@ changeGate) {
1350
1457
  mount({
1351
1458
  name: 'file_stat',
1352
1459
  gated: true,
1353
- description: () => '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`.' +
1354
- ' Every entry also reports what you may DO with it. ' +
1355
- `\`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. ` +
1356
- '`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. ' +
1357
- '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. ' +
1358
- 'Call this before a move or delete to see what it would touch.',
1460
+ description: 'Get a file/directory\'s metadata (name, type, size, …) without returning content, and what you may DO with it. ' +
1461
+ 'A file also reports `contentMode`, `kind`, `mime`, `mimeSource` and `textEditable` — decided by the same readers ' +
1462
+ 'read_file, grep and the write tools use, so an extensionless text file is `text/plain`. ' +
1463
+ '`access: { read, write, download, owner }` is your own verdict under the access rules; pass `explainAccess: true` to ' +
1464
+ 'learn why, and who else holds each verb. ' +
1465
+ 'Call this before a move or delete: `managed`, `movable` and `deletable` answer the shared rules on what these tools ' +
1466
+ 'never move or delete, judged like the dry runs (on a draft branch writes are not gated); `movable` judges the SOURCE ' +
1467
+ 'side only, so the destination still wants a `move_file` dry run. ' +
1468
+ 'For a folder, `descendants` counts the files under it at any depth; counting stops at 10000 and ' +
1469
+ '`descendantsTruncated` says so, past which `movable` and `deletable` are false — a folder that large was not judged ' +
1470
+ 'in full, so run the `move_file` or `delete_folder` dry run for the real verdict.',
1359
1471
  inputs: {
1360
1472
  type: 'object',
1361
1473
  properties: {
@@ -1645,9 +1757,7 @@ changeGate) {
1645
1757
  gated: true,
1646
1758
  description: 'Write a workspace TEXT file. The change is committed + pushed as you. Returns `{ path, bytes, outcome }`, where `outcome` is ' +
1647
1759
  '`created`, `replaced` or `updated`.' +
1648
- WRITE_MODE_NOTE +
1649
- IMAGE_CONVENTION_NOTE +
1650
- ESCAPE_SEQUENCE_NOTE,
1760
+ UPLOAD_ROUTE_NOTE,
1651
1761
  inputs: {
1652
1762
  type: 'object',
1653
1763
  properties: {
@@ -1725,9 +1835,7 @@ changeGate) {
1725
1835
  '`created` / `replaced` / `updated` for a path it wrote, or `refused` with `error` (the code) and `message` (why) for a ' +
1726
1836
  'path it could not. `count` is how many were written. A path it refuses — the mode said no, or the file is not text — ' +
1727
1837
  'does not stop the others; read `files` to see what landed.' +
1728
- WRITE_MODE_NOTE +
1729
- IMAGE_CONVENTION_NOTE +
1730
- ESCAPE_SEQUENCE_NOTE,
1838
+ UPLOAD_ROUTE_NOTE,
1731
1839
  inputs: {
1732
1840
  type: 'object',
1733
1841
  properties: {
@@ -1891,7 +1999,7 @@ changeGate) {
1891
1999
  name: 'edit_file',
1892
2000
  gated: true,
1893
2001
  description: 'Replace an exact string in a workspace TEXT file. `old_string` must appear exactly once unless `replace_all`. Committed + pushed as you.' +
1894
- ESCAPE_SEQUENCE_NOTE,
2002
+ UPLOAD_ROUTE_NOTE,
1895
2003
  inputs: {
1896
2004
  type: 'object',
1897
2005
  properties: {
@@ -1920,28 +2028,56 @@ changeGate) {
1920
2028
  const path = a.path;
1921
2029
  const oldStr = a.old_string;
1922
2030
  const newStr = a.new_string;
1923
- // The overwrite gate already read the file when its reader asked the
1924
- // binary question — reuse those bytes instead of reading twice.
1925
- const content = await orNotFound(path, async () => {
1926
- const existing = await assertNotBinaryOverwrite(readers, path, fs);
1927
- return asText(existing ?? (await fs.readFile(path)));
1928
- });
1929
- const count = oldStr ? content.split(oldStr).length - 1 : 0;
1930
- if (count === 0)
1931
- throw new ToolError('old_string not found in the file.', 400);
1932
- if (count > 1 && a.replace_all !== true) {
1933
- throw new ToolError(`old_string appears ${count} times — add more context to make it unique, or set replace_all.`, 400);
2031
+ // Everything the tool decides about ONE reading of the file: may these
2032
+ // bytes be edited as text at all, is `old_string` there, is it unique,
2033
+ // and what the file becomes. One function, because the file is read
2034
+ // twice — before the lock and under it — and a reading that skipped any
2035
+ // of these questions would let bytes land that were never judged.
2036
+ // `split`/`join`, not `String.replace`, which reads `$&`, `$'`, `` $` ``
2037
+ // and `$$` in `new_string` as patterns and writes something the caller
2038
+ // never sent.
2039
+ const edit = (existing) => {
2040
+ assertBytesTextEditable(readers, path, existing);
2041
+ const text = asText(existing);
2042
+ const pieces = oldStr ? text.split(oldStr) : [text];
2043
+ const count = pieces.length - 1;
2044
+ if (count === 0)
2045
+ throw new ToolError('old_string not found in the file.', 400);
2046
+ if (count > 1 && a.replace_all !== true) {
2047
+ throw new ToolError(`old_string appears ${count} times — add more context to make it unique, or set replace_all.`, 400);
2048
+ }
2049
+ return { updated: pieces.join(newStr), replaced: count };
2050
+ };
2051
+ // A first verdict before any lock is taken, so an ordinary refusal costs
2052
+ // no lock cycle. It is a verdict about a file anyone may still change.
2053
+ let result = edit(await orNotFound(path, async () => asBytes(await fs.readFile(path))));
2054
+ // The one the answer carries is taken again with the path's lock HELD,
2055
+ // over the bytes read there (`write: true` guarantees the locking
2056
+ // filesystem): read, verdict and write are one step nobody can get
2057
+ // between. Taken before the lock only, two callers replacing the same
2058
+ // text — two runners claiming a work item by filling its empty owner
2059
+ // field — were BOTH told their edit landed, and the second silently
2060
+ // overwrote the first. A filesystem without the method has no lock to
2061
+ // read under, so the first verdict stands.
2062
+ const locking = fs;
2063
+ if (typeof locking.rewriteFile === 'function') {
2064
+ await locking.rewriteFile(path, (current) => {
2065
+ if (current === null)
2066
+ throw notFound(path);
2067
+ result = edit(current);
2068
+ return result.updated;
2069
+ });
1934
2070
  }
1935
- const updated = a.replace_all === true ? content.split(oldStr).join(newStr) : content.replace(oldStr, newStr);
1936
- await fs.writeFile(path, updated);
1937
- return { path, replaced: a.replace_all === true ? count : 1, ...(await saveWarnings(ctx, path, updated)) };
2071
+ else {
2072
+ await fs.writeFile(path, result.updated);
2073
+ }
2074
+ return { path, replaced: result.replaced, ...(await saveWarnings(ctx, path, result.updated)) };
1938
2075
  },
1939
2076
  });
1940
2077
  mount({
1941
2078
  name: 'delete_file',
1942
2079
  gated: true,
1943
- description: () => '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`. ' +
1944
- `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.`,
2080
+ description: '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`.',
1945
2081
  inputs: {
1946
2082
  type: 'object',
1947
2083
  properties: {
@@ -1995,10 +2131,12 @@ changeGate) {
1995
2131
  name: 'delete_folder',
1996
2132
  gated: true,
1997
2133
  description: '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. ' +
1998
- '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. ' +
1999
- '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. ' +
2000
- '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). ' +
2001
- '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.',
2134
+ 'The dry run answers `{ path, kind: "folder", descendants, files, filesTruncated, allowed, reason? }` — `descendants` is ' +
2135
+ 'the file count, `files` names up to 100 of them — and a non-empty folder wants `confirm: true`. ' +
2136
+ 'Beyond what the shared rules refuse, a folder HOLDING a symbolic link, or any file you may not write, is refused ' +
2137
+ '(the link itself is never removed), and a path that is a FILE ' +
2138
+ 'is refused with a pointer to `delete_file`. You must be able to write the folder\'s own platform files too: they go ' +
2139
+ 'with it in that same one change, so its files are never left ungoverned part-way.',
2002
2140
  inputs: {
2003
2141
  type: 'object',
2004
2142
  properties: {
@@ -2159,10 +2297,14 @@ changeGate) {
2159
2297
  mount({
2160
2298
  name: 'move_file',
2161
2299
  gated: true,
2162
- description: () => '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. ' +
2163
- `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. ` +
2164
- '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. ' +
2165
- '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.',
2300
+ // A plain string again: what refuses a move names the guide, and that is in
2301
+ // the shared rules now, which are rebuilt from the layout where they live.
2302
+ description: '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. ' +
2303
+ 'The destination must not exist — a move never overwrites a file or merges into a folder. Access follows the ' +
2304
+ 'DESTINATION folder, so a move can change what you (and others) may do with the file: the dry run answers ' +
2305
+ '`{ src, dest, kind, descendants, access: { before, after }, accessChanges, allowed, reason? }`, where `access` is your ' +
2306
+ 'own `{ read, write, download, owner }` at the source and at the destination AS IT WILL BE once the move has landed, ' +
2307
+ 'with every `access.md` inside a moved folder counted at its new place, and a move whose `accessChanges` is true wants `confirm: true`.',
2166
2308
  inputs: {
2167
2309
  type: 'object',
2168
2310
  properties: {
@@ -2498,6 +2640,300 @@ changeGate) {
2498
2640
  }), 'Nothing to extract');
2499
2641
  },
2500
2642
  });
2643
+ // ── uploads (bytes that never pass through the model) ───────────────────
2644
+ //
2645
+ // The pair exists because MCP tool arguments are JSON. Every byte an agent
2646
+ // sends through `write_file` is first typed out by the model, which
2647
+ // truncates long files, mangles backslash and `\u` escapes, and cannot carry
2648
+ // a PNG at all. `request_file_upload` answers an address; the agent POSTs
2649
+ // the file (or one zip holding many) there with any HTTP client;
2650
+ // `apply_file_upload` lands it on a branch in one commit. The bytes go from
2651
+ // the agent's disk to the server's and never enter a prompt.
2652
+ //
2653
+ /**
2654
+ * Why one of an upload's paths may not be landed, judged on the path ALONE —
2655
+ * or undefined when nothing about the name itself refuses it.
2656
+ *
2657
+ * The platform files are the whole of it. `access.md` governs who may read
2658
+ * and write the folder it sits in, `roles.yaml` says which roles exist, and
2659
+ * the agent guide is read as instructions: each is configuration the platform
2660
+ * obeys, and each has a write path that CHECKS the change (the roles gate
2661
+ * refuses an edit that would lock every admin out; a folder's access rules
2662
+ * are judged against who is asking). Bytes arriving by upload meet none of
2663
+ * those gates — they are a buffer the sender chose — so an upload never
2664
+ * lands one, whatever else the caller may write. `unzip` has refused
2665
+ * `roles.yaml` from an archive for the same reason; this is that rule, over
2666
+ * all four names.
2667
+ */
2668
+ const platformFileReason = (wsPath) => {
2669
+ const rel = toKbRelative(wsPath, kbDirName);
2670
+ return rel !== null && isPlatformFile(rel, kb.layout) ? platformFileUploadRefusal(rel) : undefined;
2671
+ };
2672
+ /**
2673
+ * `apply_file_upload`'s handler: resolve the stored bytes into one path per
2674
+ * file, judge each path the way `write_files` judges its own, and land the
2675
+ * survivors as ONE commit.
2676
+ *
2677
+ * The judging is deliberately the same shape as `write_files`, down to the
2678
+ * second verdict under the lock, because the promise the ticket makes is
2679
+ * that an upload is judged "exactly as `write_file` would judge it". Three
2680
+ * gates run per path and a path that fails one is that path's outcome and no
2681
+ * more: the deployment's write hook, the platform-file rule above, and the
2682
+ * `mode`. What is judged ONCE for the whole call is the destination — a
2683
+ * caller who may not write the folder at all gets one refusal naming the
2684
+ * change-request route, rather than the same refusal repeated per entry.
2685
+ */
2686
+ const applyFileUpload = async (a, ctx, uploads) => {
2687
+ const branch = a.branch;
2688
+ const token = a.token;
2689
+ if (typeof token !== 'string' || token === '') {
2690
+ throw new ToolError('Name the `token` `request_file_upload` answered with, after POSTing the file to its `uploadUrl`.', 400, { code: 'token-required' });
2691
+ }
2692
+ const mode = modeOf(a);
2693
+ const destination = a.destination.replace(/\/+$/, '');
2694
+ assertInsideRepo(destination, kbDirName);
2695
+ // CLAIMED, not consumed: an apply refused whole (a protected destination,
2696
+ // an archive that will not open) leaves the token alive so the caller can
2697
+ // retry somewhere else rather than send the bytes again. The claim is what
2698
+ // keeps it single-use meanwhile — a second apply finds the token in use.
2699
+ const upload = uploads.claim(token, ctx.user.id);
2700
+ let spent = false;
2701
+ try {
2702
+ const fs = await ctx.getFilesystem(branch);
2703
+ const root = await workspaceRoot(branch, ctx);
2704
+ // The destination, once, for the whole call. On a protected branch a
2705
+ // caller who may not write the folder gets the lock gate's own refusal —
2706
+ // which `rethrowAsWriteDenial` turns into `write-denied` with the
2707
+ // change-request steps — and nothing lands.
2708
+ const blockedDest = await writeBlocked(branch, ctx, [destination]);
2709
+ if (blockedDest.length > 0)
2710
+ throw await writeRefusal(branch, blockedDest[0], 'dir');
2711
+ if ((await kindOf(fs, destination)) === 'file') {
2712
+ throw new ToolError(`"${displayPath(destination)}" is a file, not a folder — \`destination\` names the folder the upload lands in.`, 409, { code: 'not_a_folder' });
2713
+ }
2714
+ const planned = await planUpload(upload, destination, kbDirName);
2715
+ const paths = planned.filter((p) => p.content !== undefined).map((p) => p.path);
2716
+ // One batched access read for every path, like `write_files` — empty on
2717
+ // a draft branch, where changes reach a protected branch only through a
2718
+ // change request.
2719
+ const blocked = new Set(await writeBlocked(branch, ctx, paths));
2720
+ const writes = [];
2721
+ const outcomes = [];
2722
+ /** The `files` entry for `writes[i]`, so the under-lock verdict can revise it. */
2723
+ const entryOf = [];
2724
+ for (const item of planned) {
2725
+ const entry = { path: item.path };
2726
+ outcomes.push(entry);
2727
+ if (item.content === undefined) {
2728
+ entry.outcome = 'refused';
2729
+ entry.error = item.error;
2730
+ entry.message = item.message;
2731
+ continue;
2732
+ }
2733
+ const wsPathOf = item.path;
2734
+ try {
2735
+ if (blocked.has(wsPathOf))
2736
+ throw await writeRefusal(branch, wsPathOf);
2737
+ const platform = platformFileReason(wsPathOf);
2738
+ if (platform !== undefined)
2739
+ throw new ToolError(platform, 422, { code: 'platform_file' });
2740
+ // The git folder is never a workspace path, in any spelling. A ZIP
2741
+ // entry's name has already met this rule in `zipEntryNameRefusal`; a
2742
+ // SINGLE uploaded file's has not — `.git` is a name the upload
2743
+ // route's `validateFilename` accepts — and the preflight that reads
2744
+ // the caller's own arguments never sees it either, because the name
2745
+ // came from the upload, not from the call. Asked here so that path
2746
+ // is REFUSED like any other, with the rest of the upload landing,
2747
+ // rather than failing the whole apply from inside `writeFiles`.
2748
+ assertNoGitInternalsSegment(wsPathOf);
2749
+ assertRepoRootNameFree(wsPathOf, kbDirName);
2750
+ // A link already on disk under the destination must not redirect
2751
+ // these bytes — the rule `unzip` applies per entry, applied here on
2752
+ // the path the write will take.
2753
+ const link = await symlinkOnPath(root, wsPathOf);
2754
+ if (link !== undefined) {
2755
+ throw new ToolError(`"${wsPathOf}" goes through the symbolic link "${link}"; an upload never follows links.`, 400, { code: 'symlink' });
2756
+ }
2757
+ writePolicy.assertPathWritable(ctx.sessionId, wsPathOf);
2758
+ await assertAgentWriteAllowed(agentAccessGate, ctx, branch, wsPathOf);
2759
+ // An earlier entry of this same upload counts as existing, as it
2760
+ // does in `write_files`: two `create` entries for one path are a
2761
+ // mistake the commit would otherwise hide.
2762
+ const exists = writes.some((w) => w.path === wsPathOf) || (await kindOf(fs, wsPathOf)) !== null;
2763
+ entry.outcome = decideWrite(mode, wsPathOf, exists);
2764
+ writes.push({ path: wsPathOf, content: item.content });
2765
+ entryOf.push(entry);
2766
+ }
2767
+ catch (err) {
2768
+ refuseEntry(entry, err);
2769
+ }
2770
+ }
2771
+ // The mode gate again, with every path's lock held — the verdict the
2772
+ // answer carries, for the reason `write_file` states at length. A path
2773
+ // whose verdict changed under the lock is dropped from the batch and
2774
+ // reported refused, leaving the rest to land.
2775
+ const recheck = async (pending) => {
2776
+ const kept = [];
2777
+ for (let i = 0; i < pending.length; i++) {
2778
+ const entry = entryOf[i];
2779
+ try {
2780
+ const exists = kept.some((k) => k.path === pending[i].path) || (await kindOf(fs, pending[i].path)) !== null;
2781
+ entry.outcome = decideWrite(mode, pending[i].path, exists);
2782
+ kept.push(pending[i]);
2783
+ }
2784
+ catch (err) {
2785
+ refuseEntry(entry, err);
2786
+ }
2787
+ }
2788
+ return kept;
2789
+ };
2790
+ if (writes.length > 0) {
2791
+ // `write: true` guarantees a LockingFilesystem here; `writeFiles` lands
2792
+ // the whole set as ONE commit and takes a Buffer as content, so bytes
2793
+ // reach disk exactly as they were sent — no text decode anywhere on
2794
+ // the way, which is what makes a PNG and a backslash-heavy page land
2795
+ // with the checksum they were uploaded with.
2796
+ const batching = fs;
2797
+ // In the DESTINATION folder's TURN, which `delete_folder` takes over the
2798
+ // same subtree (and `keepFolderOf` with it). `writeFiles` creates the
2799
+ // destination, and any folder above a zip entry on the way to it, as
2800
+ // part of landing the batch — and a folder delete running between that
2801
+ // creation and the commit enumerates the folder's files BEFORE these
2802
+ // exist and then removes the folder they are landing in, which is an
2803
+ // answer saying `created` for bytes that are already gone. The turn is
2804
+ // taken OUTSIDE `writeFiles`, so it is held across the under-lock
2805
+ // recheck and the commit both, and in the same order the delete takes
2806
+ // its own (the folder's turn first, then each path's lock), which is
2807
+ // what keeps two callers from waiting on each other's half.
2808
+ await ctx.workspaceService.withFolderTurn(workspaceIdForBranch(branch), destination, async () => {
2809
+ await batching.writeFiles(writes, `Apply upload of ${writes.length} file(s)`, [], recheck);
2810
+ });
2811
+ }
2812
+ // The token is spent once an ANSWER exists, even an answer in which
2813
+ // every path was refused: the apply ran and said what happened at each
2814
+ // path, and re-running it would say the same. Only a refusal that landed
2815
+ // nothing AND answered nothing (thrown above) gives the token back.
2816
+ spent = true;
2817
+ await uploads.consume(token);
2818
+ const listed = a.all === true ? outcomes : outcomes.slice(0, APPLY_ANSWER_CAP);
2819
+ return {
2820
+ destination,
2821
+ count: outcomes.filter((o) => o.outcome !== 'refused').length,
2822
+ total: outcomes.length,
2823
+ files: listed,
2824
+ ...(listed.length < outcomes.length ? { truncated: true } : {}),
2825
+ };
2826
+ }
2827
+ finally {
2828
+ if (!spent)
2829
+ uploads.release(token);
2830
+ }
2831
+ };
2832
+ // Mounted only when the composition supplied a store — see the `uploads`
2833
+ // parameter. Core always does.
2834
+ if (uploads) {
2835
+ mount({
2836
+ name: 'request_file_upload',
2837
+ fileTool: false,
2838
+ description:
2839
+ // Within the description cap (`tool-registry/description-length.ts`):
2840
+ // why a file goes this way is one of the shared rules, and the header
2841
+ // spelling of the token is on the `uploadUrl` output, where the
2842
+ // address it changes is.
2843
+ 'Ask for a one-time address to send FILE BYTES to, so their content never passes through this conversation. ' +
2844
+ 'Use it for anything `write_file` cannot carry faithfully: a large file, a file full of backslashes or `\\u` ' +
2845
+ 'escapes, a binary file (a PNG, a PDF, a zip), or many files at once (zip them). ' +
2846
+ 'Returns `{ uploadUrl, token, expiresAt, expiresInSeconds, maxBytes }`. THEN: ' +
2847
+ '(1) POST the file as the raw request body to `uploadUrl` with `?filename=<name>` — ' +
2848
+ '`curl -X POST --data-binary @skill.zip "<uploadUrl>?filename=skill.zip"` — which answers what it received; ' +
2849
+ '(2) call `apply_file_upload` with the same `token`, a `branch` and a destination folder. ' +
2850
+ 'One token carries one file or one zip, is bound to you and expires at `expiresAt`: an upload nobody applies ' +
2851
+ 'by then is deleted, and one over `maxBytes` is refused when you send it, naming the limit.',
2852
+ inputs: { type: 'object', properties: {}, additionalProperties: false },
2853
+ outputs: {
2854
+ type: 'object',
2855
+ properties: {
2856
+ uploadUrl: str('The absolute URL to POST the bytes to. Carries the token; add `?filename=<name>`. To keep the token out ' +
2857
+ 'of a URL — when the command line you send from is logged or shared — POST to this address without its ' +
2858
+ 'last (token) segment and send the token in an `x-upload-token` header instead.'),
2859
+ token: str('The token itself — what `apply_file_upload` takes, and what an `x-upload-token` header carries when you ' +
2860
+ 'would rather it not sit in a URL. Treat it as a credential.'),
2861
+ expiresAt: str('ISO-8601 instant after which the token, and any bytes sent with it, are gone.'),
2862
+ expiresInSeconds: int('Seconds from now until `expiresAt`.'),
2863
+ maxBytes: int('The largest upload this deployment accepts, in bytes.'),
2864
+ },
2865
+ required: ['uploadUrl', 'token', 'expiresAt', 'expiresInSeconds', 'maxBytes'],
2866
+ },
2867
+ // A read-scoped caller has nothing to do with an upload token: the only
2868
+ // thing it unlocks is a write. Refused at the handler factory, by scope,
2869
+ // before the token is minted.
2870
+ write: true,
2871
+ handler: async (_a, ctx) => uploads.issue(ctx.user),
2872
+ });
2873
+ mount({
2874
+ name: 'apply_file_upload',
2875
+ gated: true,
2876
+ description: 'Land a file you have already uploaded (see `request_file_upload`) in a folder on a branch, in ONE commit, as you. ' +
2877
+ 'A single file lands under the name it was sent with; a zip lands as its entries, keeping their folder structure. ' +
2878
+ 'Returns `{ destination, count, total, files }`: one entry per path, each `{ path, outcome }` — `created` / ' +
2879
+ '`replaced` / `updated`, or `refused` with `error` (the code) and `message` (why). `count` is how many landed and ' +
2880
+ '`total` how many paths there were; `files` is cut to the first 25 unless you pass `all: true`. ' +
2881
+ 'Every path is judged one by one — by your write access, the platform-file rules and what is already there — ' +
2882
+ 'exactly as `write_file` judges it, and a refused path does not stop the others. ' +
2883
+ 'The token is single-use: it is spent by the apply that lands it, and refused if you use it twice, let it ' +
2884
+ 'expire, or present one issued to somebody else. `mode` means what it means on `write_file`.',
2885
+ inputs: {
2886
+ type: 'object',
2887
+ properties: {
2888
+ branch: BRANCH_INPUT,
2889
+ token: str('The `token` from `request_file_upload`, after you have POSTed the file to its `uploadUrl`.'),
2890
+ destination: wsPath(kbDirName, 'Folder the upload lands in (created if it is not there yet)'),
2891
+ mode: WRITE_MODE_INPUT,
2892
+ all: {
2893
+ type: 'boolean',
2894
+ description: 'List EVERY path in `files` instead of the first 25. `total` always says how many there were, so ask for ' +
2895
+ 'all only when you need to read each outcome.',
2896
+ },
2897
+ sessionId: SESSION_ID_INPUT,
2898
+ },
2899
+ required: ['branch', 'token', 'destination'],
2900
+ additionalProperties: false,
2901
+ },
2902
+ outputs: {
2903
+ type: 'object',
2904
+ properties: {
2905
+ destination: str('The folder the upload was applied to (echoes the input).'),
2906
+ count: int('How many paths landed — the entries in `files` whose `outcome` is not `refused`.'),
2907
+ total: int('How many paths the upload held, whether or not `files` lists them all.'),
2908
+ files: {
2909
+ type: 'array',
2910
+ description: 'One entry per path, in the order the upload held them. Cut to 25 unless `all` was true.',
2911
+ items: {
2912
+ type: 'object',
2913
+ properties: {
2914
+ path: str('The workspace path this entry was judged at.'),
2915
+ outcome: {
2916
+ type: 'string',
2917
+ enum: ['created', 'replaced', 'updated', 'refused'],
2918
+ description: 'What happened at this path. `refused` means nothing was written there.',
2919
+ },
2920
+ error: str('Present when `outcome` is `refused`: the refusal code — e.g. `exists`, `missing`, `invalid_entry`, `platform_file`, `write-denied`.'),
2921
+ message: str('Present when `outcome` is `refused`: the full refusal, the same one `write_file` would have given.'),
2922
+ },
2923
+ required: ['path', 'outcome'],
2924
+ },
2925
+ },
2926
+ truncated: { type: 'boolean', description: 'True when `files` was cut: `total` is larger than what it lists. Pass `all: true` for the rest.' },
2927
+ },
2928
+ required: ['destination', 'count', 'total', 'files'],
2929
+ },
2930
+ write: true,
2931
+ // So a protected-branch refusal arrives as `write-denied`, with the
2932
+ // change-request steps, exactly as it does from write_file.
2933
+ proposable: true,
2934
+ handler: async (a, ctx) => applyFileUpload(a, ctx, uploads),
2935
+ });
2936
+ }
2501
2937
  // ── shell (internal-only) ───────────────────────────────────────────────
2502
2938
  mount({
2503
2939
  name: 'execute_command',