@fugood/bricks-ctor 2.25.0-beta.5 → 2.25.0-beta.51

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 (187) hide show
  1. package/compile/__tests__/config-diff.test.js +100 -0
  2. package/compile/__tests__/index.test.js +386 -0
  3. package/compile/__tests__/util.test.js +337 -0
  4. package/compile/action-name-map.ts +64 -0
  5. package/compile/config-diff.ts +155 -0
  6. package/compile/index.ts +278 -34
  7. package/compile/util.ts +34 -10
  8. package/package.json +7 -3
  9. package/skills/bricks-ctor/SKILL.md +23 -17
  10. package/skills/bricks-ctor/{rules → references}/animation.md +3 -2
  11. package/skills/bricks-ctor/{rules → references}/architecture-patterns.md +18 -0
  12. package/skills/bricks-ctor/{rules → references}/automations.md +11 -0
  13. package/skills/bricks-ctor/references/buttress.md +245 -0
  14. package/skills/bricks-ctor/references/data-calculation.md +239 -0
  15. package/skills/bricks-ctor/references/simulator.md +132 -0
  16. package/skills/bricks-ctor/references/source-editing-tools.md +81 -0
  17. package/skills/bricks-ctor/references/verification-toolchain.md +200 -0
  18. package/skills/bricks-design/SKILL.md +150 -45
  19. package/skills/bricks-design/references/architecture-truths.md +132 -0
  20. package/skills/bricks-design/references/avoiding-complexity.md +91 -0
  21. package/skills/bricks-design/references/design-critique.md +195 -0
  22. package/skills/bricks-design/references/design-languages.md +265 -0
  23. package/skills/bricks-design/references/performance.md +116 -0
  24. package/skills/bricks-design/references/presentation-and-slideshow.md +137 -0
  25. package/skills/bricks-design/references/translating-inputs.md +152 -0
  26. package/skills/bricks-design/references/variations-and-tweaks.md +124 -0
  27. package/skills/bricks-design/references/when-the-brief-is-branded.md +284 -0
  28. package/skills/bricks-design/references/when-the-brief-is-vague.md +85 -0
  29. package/skills/bricks-design/references/workflow.md +134 -0
  30. package/skills/bricks-ux/SKILL.md +114 -0
  31. package/skills/bricks-ux/references/accessibility.md +162 -0
  32. package/skills/bricks-ux/references/flow-states.md +175 -0
  33. package/skills/bricks-ux/references/interaction-archetypes.md +189 -0
  34. package/skills/bricks-ux/references/monitoring-screens.md +153 -0
  35. package/skills/bricks-ux/references/pressable-composition.md +126 -0
  36. package/skills/bricks-ux/references/user-journey.md +168 -0
  37. package/skills/bricks-ux/references/ux-critique.md +256 -0
  38. package/tools/__tests__/_cli-error.test.ts +35 -0
  39. package/tools/__tests__/_mcp-config.test.ts +67 -0
  40. package/tools/_cli-error.ts +17 -0
  41. package/tools/_edits-log.ts +41 -0
  42. package/tools/_git-author.ts +10 -2
  43. package/tools/_last-pushed-commit.ts +28 -0
  44. package/tools/_mcp-config.ts +42 -0
  45. package/tools/_shell.ts +8 -1
  46. package/tools/deploy.ts +17 -6
  47. package/tools/mcp-env.ts +13 -0
  48. package/tools/mcp-server.ts +8 -0
  49. package/tools/mcp-tools/__tests__/data-calc-editing.test.js +516 -0
  50. package/tools/mcp-tools/__tests__/entry-editing.test.js +866 -0
  51. package/tools/mcp-tools/__tests__/huggingface.test.ts +49 -0
  52. package/tools/mcp-tools/__tests__/icons.test.ts +21 -0
  53. package/tools/mcp-tools/__tests__/mcp-env.test.js +19 -0
  54. package/tools/mcp-tools/_editing-helpers.ts +58 -0
  55. package/tools/mcp-tools/_verify.ts +50 -0
  56. package/tools/mcp-tools/compile.ts +21 -9
  57. package/tools/mcp-tools/data-calc-editing.ts +1349 -0
  58. package/tools/mcp-tools/entry-editing.ts +2336 -0
  59. package/tools/mcp-tools/huggingface.ts +23 -13
  60. package/tools/mcp-tools/icons.ts +23 -7
  61. package/tools/mcp-tools/media.ts +4 -1
  62. package/tools/postinstall.ts +95 -38
  63. package/tools/pull.ts +93 -22
  64. package/tools/push-config.ts +114 -0
  65. package/tools/{preview-main.mjs → simulator-main.mjs} +207 -12
  66. package/tools/simulator-preload.cjs +16 -0
  67. package/tools/{preview.ts → simulator.ts} +4 -4
  68. package/types/{animation.ts → animation.d.ts} +24 -8
  69. package/types/{automation.ts → automation.d.ts} +16 -20
  70. package/types/{brick-base.ts → brick-base.d.ts} +1 -1
  71. package/types/bricks/{Camera.ts → Camera.d.ts} +8 -8
  72. package/types/bricks/{Chart.ts → Chart.d.ts} +4 -4
  73. package/types/bricks/{GenerativeMedia.ts → GenerativeMedia.d.ts} +15 -15
  74. package/types/bricks/{Icon.ts → Icon.d.ts} +7 -7
  75. package/types/bricks/{Image.ts → Image.d.ts} +21 -9
  76. package/types/bricks/{Items.ts → Items.d.ts} +7 -7
  77. package/types/bricks/{Lottie.ts → Lottie.d.ts} +10 -10
  78. package/types/bricks/{Maps.ts → Maps.d.ts} +11 -11
  79. package/types/bricks/{QrCode.ts → QrCode.d.ts} +7 -7
  80. package/types/bricks/{Rect.ts → Rect.d.ts} +7 -7
  81. package/types/bricks/{RichText.ts → RichText.d.ts} +12 -9
  82. package/types/bricks/{Rive.ts → Rive.d.ts} +9 -9
  83. package/types/bricks/Scene3D.d.ts +676 -0
  84. package/types/bricks/{Sketch.ts → Sketch.d.ts} +6 -6
  85. package/types/bricks/{Slideshow.ts → Slideshow.d.ts} +7 -7
  86. package/types/bricks/{Svg.ts → Svg.d.ts} +7 -7
  87. package/types/bricks/{Text.ts → Text.d.ts} +9 -9
  88. package/types/bricks/{TextInput.ts → TextInput.d.ts} +10 -10
  89. package/types/bricks/{Video.ts → Video.d.ts} +12 -12
  90. package/types/bricks/{VideoStreaming.ts → VideoStreaming.d.ts} +10 -10
  91. package/types/bricks/{WebRtcStream.ts → WebRtcStream.d.ts} +1 -1
  92. package/types/bricks/{WebView.ts → WebView.d.ts} +4 -4
  93. package/types/bricks/{index.ts → index.d.ts} +1 -0
  94. package/types/{common.ts → common.d.ts} +3 -6
  95. package/types/data-calc-command/base.d.ts +57 -0
  96. package/types/data-calc-command/collection.d.ts +418 -0
  97. package/types/data-calc-command/color.d.ts +432 -0
  98. package/types/data-calc-command/constant.d.ts +50 -0
  99. package/types/data-calc-command/datetime.d.ts +147 -0
  100. package/types/data-calc-command/file.d.ts +129 -0
  101. package/types/data-calc-command/index.d.ts +13 -0
  102. package/types/data-calc-command/iteratee.d.ts +23 -0
  103. package/types/data-calc-command/logictype.d.ts +190 -0
  104. package/types/data-calc-command/math.d.ts +275 -0
  105. package/types/data-calc-command/object.d.ts +119 -0
  106. package/types/data-calc-command/sandbox.d.ts +66 -0
  107. package/types/data-calc-command/string.d.ts +407 -0
  108. package/types/{data-calc.ts → data-calc.d.ts} +1 -0
  109. package/types/{data.ts → data.d.ts} +4 -2
  110. package/types/generators/{Assistant.ts → Assistant.d.ts} +19 -0
  111. package/types/generators/{LlmGgml.ts → LlmGgml.d.ts} +43 -1
  112. package/types/generators/{LlmMlx.ts → LlmMlx.d.ts} +1 -0
  113. package/types/generators/{RerankerGgml.ts → RerankerGgml.d.ts} +5 -1
  114. package/types/generators/{SoundRecorder.ts → SoundRecorder.d.ts} +10 -1
  115. package/types/generators/{SpeechToTextGgml.ts → SpeechToTextGgml.d.ts} +6 -1
  116. package/types/generators/{SttAppleBuiltin.ts → SttAppleBuiltin.d.ts} +27 -4
  117. package/types/generators/{ThermalPrinter.ts → ThermalPrinter.d.ts} +9 -7
  118. package/types/generators/{VadGgml.ts → VadGgml.d.ts} +12 -2
  119. package/types/{subspace.ts → subspace.d.ts} +1 -1
  120. package/utils/__tests__/calc.test.js +25 -0
  121. package/utils/__tests__/id.test.js +154 -0
  122. package/utils/calc.ts +5 -1
  123. package/utils/data.ts +5 -7
  124. package/utils/event-props.ts +17 -0
  125. package/utils/id.ts +109 -56
  126. package/skills/bricks-ctor/rules/buttress.md +0 -156
  127. package/skills/bricks-ctor/rules/data-calculation.md +0 -209
  128. package/skills/bricks-design/LICENSE.txt +0 -180
  129. package/types/data-calc-command.ts +0 -7005
  130. /package/skills/bricks-ctor/{rules → references}/local-sync.md +0 -0
  131. /package/skills/bricks-ctor/{rules → references}/media-flow.md +0 -0
  132. /package/skills/bricks-ctor/{rules → references}/remote-data-bank.md +0 -0
  133. /package/skills/bricks-ctor/{rules → references}/standby-transition.md +0 -0
  134. /package/types/{canvas.ts → canvas.d.ts} +0 -0
  135. /package/types/{data-calc-script.ts → data-calc-script.d.ts} +0 -0
  136. /package/types/generators/{AlarmClock.ts → AlarmClock.d.ts} +0 -0
  137. /package/types/generators/{BleCentral.ts → BleCentral.d.ts} +0 -0
  138. /package/types/generators/{BlePeripheral.ts → BlePeripheral.d.ts} +0 -0
  139. /package/types/generators/{CanvasMap.ts → CanvasMap.d.ts} +0 -0
  140. /package/types/generators/{CastlesPay.ts → CastlesPay.d.ts} +0 -0
  141. /package/types/generators/{DataBank.ts → DataBank.d.ts} +0 -0
  142. /package/types/generators/{File.ts → File.d.ts} +0 -0
  143. /package/types/generators/{GraphQl.ts → GraphQl.d.ts} +0 -0
  144. /package/types/generators/{Http.ts → Http.d.ts} +0 -0
  145. /package/types/generators/{HttpServer.ts → HttpServer.d.ts} +0 -0
  146. /package/types/generators/{Information.ts → Information.d.ts} +0 -0
  147. /package/types/generators/{Intent.ts → Intent.d.ts} +0 -0
  148. /package/types/generators/{Iterator.ts → Iterator.d.ts} +0 -0
  149. /package/types/generators/{Keyboard.ts → Keyboard.d.ts} +0 -0
  150. /package/types/generators/{LlmAnthropicCompat.ts → LlmAnthropicCompat.d.ts} +0 -0
  151. /package/types/generators/{LlmAppleBuiltin.ts → LlmAppleBuiltin.d.ts} +0 -0
  152. /package/types/generators/{LlmMediaTekNeuroPilot.ts → LlmMediaTekNeuroPilot.d.ts} +0 -0
  153. /package/types/generators/{LlmOnnx.ts → LlmOnnx.d.ts} +0 -0
  154. /package/types/generators/{LlmOpenAiCompat.ts → LlmOpenAiCompat.d.ts} +0 -0
  155. /package/types/generators/{LlmQualcommAiEngine.ts → LlmQualcommAiEngine.d.ts} +0 -0
  156. /package/types/generators/{Mcp.ts → Mcp.d.ts} +0 -0
  157. /package/types/generators/{McpServer.ts → McpServer.d.ts} +0 -0
  158. /package/types/generators/{MediaFlow.ts → MediaFlow.d.ts} +0 -0
  159. /package/types/generators/{MqttBroker.ts → MqttBroker.d.ts} +0 -0
  160. /package/types/generators/{MqttClient.ts → MqttClient.d.ts} +0 -0
  161. /package/types/generators/{Question.ts → Question.d.ts} +0 -0
  162. /package/types/generators/{RealtimeTranscription.ts → RealtimeTranscription.d.ts} +0 -0
  163. /package/types/generators/{SerialPort.ts → SerialPort.d.ts} +0 -0
  164. /package/types/generators/{SoundPlayer.ts → SoundPlayer.d.ts} +0 -0
  165. /package/types/generators/{SpeechToTextOnnx.ts → SpeechToTextOnnx.d.ts} +0 -0
  166. /package/types/generators/{SpeechToTextPlatform.ts → SpeechToTextPlatform.d.ts} +0 -0
  167. /package/types/generators/{SqLite.ts → SqLite.d.ts} +0 -0
  168. /package/types/generators/{Step.ts → Step.d.ts} +0 -0
  169. /package/types/generators/{Tcp.ts → Tcp.d.ts} +0 -0
  170. /package/types/generators/{TcpServer.ts → TcpServer.d.ts} +0 -0
  171. /package/types/generators/{TextToSpeechAppleBuiltin.ts → TextToSpeechAppleBuiltin.d.ts} +0 -0
  172. /package/types/generators/{TextToSpeechGgml.ts → TextToSpeechGgml.d.ts} +0 -0
  173. /package/types/generators/{TextToSpeechOnnx.ts → TextToSpeechOnnx.d.ts} +0 -0
  174. /package/types/generators/{TextToSpeechOpenAiLike.ts → TextToSpeechOpenAiLike.d.ts} +0 -0
  175. /package/types/generators/{Tick.ts → Tick.d.ts} +0 -0
  176. /package/types/generators/{Udp.ts → Udp.d.ts} +0 -0
  177. /package/types/generators/{VadOnnx.ts → VadOnnx.d.ts} +0 -0
  178. /package/types/generators/{VadTraditional.ts → VadTraditional.d.ts} +0 -0
  179. /package/types/generators/{VectorStore.ts → VectorStore.d.ts} +0 -0
  180. /package/types/generators/{Watchdog.ts → Watchdog.d.ts} +0 -0
  181. /package/types/generators/{WebCrawler.ts → WebCrawler.d.ts} +0 -0
  182. /package/types/generators/{WebRtc.ts → WebRtc.d.ts} +0 -0
  183. /package/types/generators/{WebSocket.ts → WebSocket.d.ts} +0 -0
  184. /package/types/generators/{index.ts → index.d.ts} +0 -0
  185. /package/types/{index.ts → index.d.ts} +0 -0
  186. /package/types/{switch.ts → switch.d.ts} +0 -0
  187. /package/types/{system.ts → system.d.ts} +0 -0
@@ -0,0 +1,1349 @@
1
+ import generateModule from '@babel/generator'
2
+ import { parse, parseExpression } from '@babel/parser'
3
+ import * as t from '@babel/types'
4
+ import { parse as parseSandboxModule } from 'acorn'
5
+ import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
6
+ import { format as formatWithOxfmt } from 'oxfmt'
7
+ import { mkdir, readFile, readdir, rm, writeFile } from 'node:fs/promises'
8
+ import path from 'node:path'
9
+ import { z } from 'zod'
10
+
11
+ import { verifyProject } from './_verify'
12
+ import {
13
+ getObjectProperty,
14
+ getStringProperty,
15
+ isRecord,
16
+ makeObjectKey,
17
+ oxfmtOptions,
18
+ projectRelativePath,
19
+ removeObjectProperty,
20
+ setObjectProperty,
21
+ } from './_editing-helpers'
22
+ import { appendEditRecord, editProvenance } from '../_edits-log'
23
+
24
+ const generate = (generateModule as any).default || generateModule
25
+
26
+ type ParsedFile = {
27
+ ast: t.File
28
+ source: string
29
+ absPath: string
30
+ relPath: string
31
+ }
32
+
33
+ type ExportEntry = {
34
+ name: string
35
+ object?: t.ObjectExpression
36
+ id?: string
37
+ alias?: string
38
+ typeName?: string
39
+ }
40
+
41
+ type ReferenceResolution = {
42
+ input: string
43
+ id?: string
44
+ alias?: string
45
+ varName: string
46
+ sameFile: boolean
47
+ importSource?: string
48
+ }
49
+
50
+ type EditContext = {
51
+ projectDir: string
52
+ parsed: ParsedFile
53
+ references: ReferenceResolution[]
54
+ typeImports: Set<string>
55
+ valueImports: Set<string>
56
+ }
57
+
58
+ type CalcTarget = {
59
+ parsed: ParsedFile
60
+ object: t.ObjectExpression
61
+ slug: string
62
+ sandboxFile: string
63
+ }
64
+
65
+ class DataCalcEditingError extends Error {
66
+ code: string
67
+ details?: Record<string, unknown>
68
+ isMcpError: boolean
69
+
70
+ constructor(
71
+ code: string,
72
+ message: string,
73
+ details?: Record<string, unknown>,
74
+ isMcpError = false,
75
+ ) {
76
+ super(message)
77
+ this.name = 'DataCalcEditingError'
78
+ this.code = code
79
+ this.details = details
80
+ this.isMcpError = isMcpError
81
+ }
82
+ }
83
+
84
+ const resolveProjectPath = (projectDir: string, file: string) => {
85
+ if (path.isAbsolute(file)) {
86
+ throw new DataCalcEditingError('invalid_file', 'File must be project-relative', { file })
87
+ }
88
+
89
+ const absPath = path.resolve(projectDir, file)
90
+ const relative = path.relative(projectDir, absPath)
91
+ if (relative.startsWith('..') || path.isAbsolute(relative)) {
92
+ throw new DataCalcEditingError('invalid_file', 'File must stay inside the project directory', {
93
+ file,
94
+ })
95
+ }
96
+ return absPath
97
+ }
98
+
99
+ const parseFileSource = (source: string, relPath: string) => {
100
+ try {
101
+ return parse(source, {
102
+ sourceType: 'module',
103
+ plugins: ['typescript', 'topLevelAwait'],
104
+ errorRecovery: false,
105
+ })
106
+ } catch (err: any) {
107
+ throw new DataCalcEditingError(
108
+ 'parse_failed',
109
+ `Cannot parse ${relPath} as TypeScript: ${err.message}. Edit this file directly.`,
110
+ { file: relPath },
111
+ true,
112
+ )
113
+ }
114
+ }
115
+
116
+ const readParsedFile = async (projectDir: string, absPath: string): Promise<ParsedFile> => {
117
+ const source = await readFile(absPath, 'utf8')
118
+ const relPath = projectRelativePath(projectDir, absPath)
119
+ return {
120
+ source,
121
+ ast: parseFileSource(source, relPath),
122
+ absPath,
123
+ relPath,
124
+ }
125
+ }
126
+
127
+ const getExportEntries = (ast: t.File): ExportEntry[] =>
128
+ ast.program.body.flatMap((statement) => {
129
+ if (!t.isExportNamedDeclaration(statement)) return []
130
+ if (!t.isVariableDeclaration(statement.declaration)) return []
131
+ return statement.declaration.declarations.flatMap((declarator) => {
132
+ if (!t.isIdentifier(declarator.id)) return []
133
+
134
+ const typeAnnotation = declarator.id.typeAnnotation
135
+ let typeName: string | undefined
136
+ if (
137
+ t.isTSTypeAnnotation(typeAnnotation) &&
138
+ t.isTSTypeReference(typeAnnotation.typeAnnotation) &&
139
+ t.isIdentifier(typeAnnotation.typeAnnotation.typeName)
140
+ ) {
141
+ typeName = typeAnnotation.typeAnnotation.typeName.name
142
+ }
143
+
144
+ const object = t.isObjectExpression(declarator.init) ? declarator.init : undefined
145
+ return [
146
+ {
147
+ name: declarator.id.name,
148
+ object,
149
+ id: object ? getStringProperty(object, 'id') : undefined,
150
+ alias: object ? getStringProperty(object, 'alias') : undefined,
151
+ typeName,
152
+ },
153
+ ]
154
+ })
155
+ })
156
+
157
+ const getCalcDirFromSubspaceDir = (subspaceDir: string) => path.join(subspaceDir, 'data-calc')
158
+
159
+ const getSubspaceDirFromCalcFile = (absPath: string) => {
160
+ const parts = absPath.split(path.sep)
161
+ const index = parts.findIndex((part) => /^subspace-\d+$/.test(part))
162
+ if (index < 0) {
163
+ throw new DataCalcEditingError(
164
+ 'invalid_file',
165
+ 'Data-calc file must be inside subspaces/subspace-N/data-calc',
166
+ { file: absPath },
167
+ )
168
+ }
169
+ return parts.slice(0, index + 1).join(path.sep)
170
+ }
171
+
172
+ const resolveSubspaceDir = (projectDir: string, subspace?: string | number) => {
173
+ if (subspace == null || subspace === '') return path.join(projectDir, 'subspaces/subspace-0')
174
+ if (typeof subspace === 'number') {
175
+ return path.join(projectDir, 'subspaces', `subspace-${subspace}`)
176
+ }
177
+
178
+ const normalized = String(subspace)
179
+ if (/^\d+$/.test(normalized)) return path.join(projectDir, 'subspaces', `subspace-${normalized}`)
180
+ if (/^subspace-\d+$/.test(normalized)) return path.join(projectDir, 'subspaces', normalized)
181
+ if (normalized.includes('/')) return resolveProjectPath(projectDir, normalized)
182
+
183
+ throw new DataCalcEditingError(
184
+ 'unsupported_subspace',
185
+ `Unsupported subspace locator: ${normalized}`,
186
+ {
187
+ subspace: normalized,
188
+ },
189
+ )
190
+ }
191
+
192
+ const calcSlugFromFile = (absPath: string) => {
193
+ const basename = path.basename(absPath)
194
+ const match = /^data-calculation-(.+)\.ts$/.exec(basename)
195
+ if (!match) {
196
+ throw new DataCalcEditingError('invalid_file', 'Expected data-calculation-{slug}.ts file', {
197
+ file: absPath,
198
+ })
199
+ }
200
+ return match[1]
201
+ }
202
+
203
+ const getDataCalcFiles = async (dataCalcDir: string) => {
204
+ const entries = await readdir(dataCalcDir, { withFileTypes: true }).catch(() => [])
205
+ return entries
206
+ .filter(
207
+ (entry) =>
208
+ entry.isFile() &&
209
+ /^data-calculation-.+\.ts$/.test(entry.name) &&
210
+ !entry.name.endsWith('.sandbox.ts'),
211
+ )
212
+ .map((entry) => path.join(dataCalcDir, entry.name))
213
+ .sort()
214
+ }
215
+
216
+ const extractCalcObject = (parsed: ParsedFile) => {
217
+ const entries = getExportEntries(parsed.ast)
218
+ const calcEntry = entries.find((entry) => entry.name === 'dataCalculation')
219
+ if (!calcEntry || !calcEntry.object) {
220
+ throw new DataCalcEditingError(
221
+ 'fallback_recommended',
222
+ `Data calc ${parsed.relPath} is not a single exported object literal. Edit this file directly for this one.`,
223
+ { file: parsed.relPath, check: 'export const dataCalculation object literal' },
224
+ )
225
+ }
226
+
227
+ const typename = getStringProperty(calcEntry.object, '__typename')
228
+ if (typename !== 'DataCalculationScript') {
229
+ throw new DataCalcEditingError(
230
+ 'fallback_recommended',
231
+ `Data calc ${parsed.relPath} is ${typename || 'not DataCalculationScript'}. DataCalculationMap is out of scope; edit this file directly.`,
232
+ { file: parsed.relPath, typename },
233
+ )
234
+ }
235
+
236
+ return calcEntry.object
237
+ }
238
+
239
+ const getCodeExpression = (object: t.ObjectExpression): t.Expression | null => {
240
+ const value = getObjectProperty(object, 'code')?.value
241
+ return value && t.isExpression(value) ? value : null
242
+ }
243
+
244
+ // Sibling sandbox files only: a plain `./name.sandbox.js` basename. Anything else
245
+ // (nested paths, ../ traversal, non-sandbox files) is not ours to rewrite or delete.
246
+ const isSandboxFilename = (value: string) => /^(\.\/)?[^/\\]+\.sandbox\.js$/.test(value)
247
+
248
+ const readCodeUrlFilename = (code: t.Expression | null | undefined) => {
249
+ const expression = t.isAwaitExpression(code) ? code.argument : code
250
+ if (!t.isCallExpression(expression)) return null
251
+ const firstArg = expression.arguments[0]
252
+ if (!t.isNewExpression(firstArg)) return null
253
+ if (!t.isIdentifier(firstArg.callee) || firstArg.callee.name !== 'URL') return null
254
+ const filenameArg = firstArg.arguments[0]
255
+ if (!t.isStringLiteral(filenameArg)) return null
256
+ return filenameArg.value
257
+ }
258
+
259
+ const sandboxFilenameFromCodeExpression = (
260
+ code: t.Expression | null | undefined,
261
+ fallbackSlug: string,
262
+ ) => {
263
+ const filename = readCodeUrlFilename(code)
264
+ if (!filename || !isSandboxFilename(filename)) {
265
+ return `data-calculation-${fallbackSlug}.sandbox.js`
266
+ }
267
+ return filename.replace(/^\.\//, '')
268
+ }
269
+
270
+ const isRecognizedCodeExpression = (code: t.Expression | null | undefined) => {
271
+ if (!code) return false
272
+ if (t.isStringLiteral(code) || t.isTemplateLiteral(code)) return true
273
+ const filename = readCodeUrlFilename(code)
274
+ return filename != null && isSandboxFilename(filename)
275
+ }
276
+
277
+ const resolveCalcTarget = async (projectDir: string, input: any): Promise<CalcTarget> => {
278
+ let absPath: string | undefined
279
+
280
+ if (input.file) {
281
+ absPath = resolveProjectPath(projectDir, input.file)
282
+ } else {
283
+ const subspaceDir = resolveSubspaceDir(projectDir, input.subspace)
284
+ const calcDir = getCalcDirFromSubspaceDir(subspaceDir)
285
+ const files = await getDataCalcFiles(calcDir)
286
+ const calc = input.calc
287
+ if (!calc) {
288
+ throw new DataCalcEditingError('missing_calc', 'Provide file or subspace+calc')
289
+ }
290
+
291
+ for (const file of files) {
292
+ if (calc === calcSlugFromFile(file)) {
293
+ absPath = file
294
+ break
295
+ }
296
+ // Tolerate unparseable / non-Script siblings while scanning: they only opt out
297
+ // of alias/id matching here; standard-style checks run on the resolved target.
298
+ try {
299
+ const parsed = await readParsedFile(projectDir, file)
300
+ const entry = getExportEntries(parsed.ast).find((item) => item.name === 'dataCalculation')
301
+ if (entry && (calc === entry.alias || calc === entry.id)) {
302
+ absPath = file
303
+ break
304
+ }
305
+ } catch {
306
+ continue
307
+ }
308
+ }
309
+ }
310
+
311
+ if (!absPath) {
312
+ throw new DataCalcEditingError('calc_not_found', `Data calc not found: ${input.calc}`, {
313
+ calc: input.calc,
314
+ subspace: input.subspace ?? 'subspace-0',
315
+ })
316
+ }
317
+
318
+ const parsed = await readParsedFile(projectDir, absPath)
319
+ const object = extractCalcObject(parsed)
320
+ const slug = calcSlugFromFile(absPath)
321
+ const sandboxFile = sandboxFilenameFromCodeExpression(getCodeExpression(object), slug)
322
+ return { parsed, object, slug, sandboxFile }
323
+ }
324
+
325
+ const relativeImportSource = (fromFile: string, toFile: string) => {
326
+ let rel = path.relative(path.dirname(fromFile), toFile).replace(/\\/g, '/')
327
+ if (!rel.startsWith('.')) rel = `./${rel}`
328
+ return rel.replace(/\.(ts|tsx|js|jsx)$/, '')
329
+ }
330
+
331
+ const insertImport = (ast: t.File, declaration: t.ImportDeclaration) => {
332
+ const body = ast.program.body
333
+ const lastImportIndex = body.findLastIndex((statement) => t.isImportDeclaration(statement))
334
+ body.splice(lastImportIndex + 1, 0, declaration)
335
+ }
336
+
337
+ const ensureNamespaceImport = (parsed: ParsedFile, source: string, preferredLocal: string) => {
338
+ for (const statement of parsed.ast.program.body) {
339
+ if (!t.isImportDeclaration(statement) || statement.source.value !== source) continue
340
+ const namespace = statement.specifiers.find(
341
+ (specifier): specifier is t.ImportNamespaceSpecifier =>
342
+ t.isImportNamespaceSpecifier(specifier),
343
+ )
344
+ if (namespace) return namespace.local.name
345
+ }
346
+
347
+ const declaration = t.importDeclaration(
348
+ [t.importNamespaceSpecifier(t.identifier(preferredLocal))],
349
+ t.stringLiteral(source),
350
+ )
351
+ insertImport(parsed.ast, declaration)
352
+ return preferredLocal
353
+ }
354
+
355
+ const ensureBricksCtorImport = (
356
+ ast: t.File,
357
+ importKind: 'type' | 'value',
358
+ names: Iterable<string>,
359
+ ) => {
360
+ const missing = new Set(Array.from(names).filter(Boolean))
361
+ if (missing.size === 0) return
362
+
363
+ for (const statement of ast.program.body) {
364
+ if (!t.isImportDeclaration(statement) || statement.source.value !== 'bricks-ctor') continue
365
+ const isTypeImport = statement.importKind === 'type'
366
+ if ((importKind === 'type') !== isTypeImport) continue
367
+
368
+ statement.specifiers.forEach((specifier) => {
369
+ if (!t.isImportSpecifier(specifier)) return
370
+ const imported = specifier.imported
371
+ if (t.isIdentifier(imported)) missing.delete(imported.name)
372
+ if (t.isStringLiteral(imported)) missing.delete(imported.value)
373
+ })
374
+
375
+ missing.forEach((name) => {
376
+ statement.specifiers.push(t.importSpecifier(t.identifier(name), t.identifier(name)))
377
+ })
378
+ return
379
+ }
380
+
381
+ const declaration = t.importDeclaration(
382
+ Array.from(missing).map((name) => t.importSpecifier(t.identifier(name), t.identifier(name))),
383
+ t.stringLiteral('bricks-ctor'),
384
+ )
385
+ if (importKind === 'type') declaration.importKind = 'type'
386
+ insertImport(ast, declaration)
387
+ }
388
+
389
+ const ensureReadFileImport = (ast: t.File) => {
390
+ for (const statement of ast.program.body) {
391
+ if (!t.isImportDeclaration(statement) || statement.source.value !== 'node:fs/promises') {
392
+ continue
393
+ }
394
+ const hasReadFile = statement.specifiers.some(
395
+ (specifier) =>
396
+ t.isImportSpecifier(specifier) &&
397
+ t.isIdentifier(specifier.imported) &&
398
+ specifier.imported.name === 'readFile',
399
+ )
400
+ if (!hasReadFile) {
401
+ statement.specifiers.push(
402
+ t.importSpecifier(t.identifier('readFile'), t.identifier('readFile')),
403
+ )
404
+ }
405
+ return
406
+ }
407
+
408
+ insertImport(
409
+ ast,
410
+ t.importDeclaration(
411
+ [t.importSpecifier(t.identifier('readFile'), t.identifier('readFile'))],
412
+ t.stringLiteral('node:fs/promises'),
413
+ ),
414
+ )
415
+ }
416
+
417
+ const applyPendingImports = (ctx: EditContext) => {
418
+ ensureBricksCtorImport(ctx.parsed.ast, 'type', ctx.typeImports)
419
+ ensureBricksCtorImport(ctx.parsed.ast, 'value', ctx.valueImports)
420
+ }
421
+
422
+ const resolveDataReference = async (
423
+ projectDir: string,
424
+ currentFile: string,
425
+ ref: string,
426
+ subspace?: string | number,
427
+ ): Promise<ReferenceResolution> => {
428
+ const currentSubspaceDir = getSubspaceDirFromCalcFile(currentFile)
429
+ const targetSubspaceDir =
430
+ subspace == null ? currentSubspaceDir : resolveSubspaceDir(projectDir, subspace)
431
+ const dataFile = path.join(targetSubspaceDir, 'data.ts')
432
+ const parsed = await readParsedFile(projectDir, dataFile)
433
+ const matches = getExportEntries(parsed.ast).filter(
434
+ (entry) => entry.name === ref || entry.id === ref || entry.alias === ref,
435
+ )
436
+
437
+ if (matches.length === 0) {
438
+ throw new DataCalcEditingError('reference_not_found', `Data reference not found: ${ref}`, {
439
+ ref,
440
+ subspace: path.basename(targetSubspaceDir),
441
+ })
442
+ }
443
+ if (matches.length > 1) {
444
+ throw new DataCalcEditingError('ambiguous_reference', `Data reference is ambiguous: ${ref}`, {
445
+ ref,
446
+ matches: matches.map((match) => ({
447
+ file: projectRelativePath(projectDir, dataFile),
448
+ entry: match.name,
449
+ id: match.id,
450
+ alias: match.alias,
451
+ })),
452
+ })
453
+ }
454
+
455
+ const sameFile = path.resolve(dataFile) === path.resolve(currentFile)
456
+ return {
457
+ input: ref,
458
+ id: matches[0].id,
459
+ alias: matches[0].alias,
460
+ varName: matches[0].name,
461
+ sameFile,
462
+ importSource: sameFile ? undefined : relativeImportSource(currentFile, dataFile),
463
+ }
464
+ }
465
+
466
+ const dataGetterExpression = async (input: any, ctx: EditContext): Promise<t.Expression> => {
467
+ if (isRecord(input) && typeof input.expr === 'string') {
468
+ return parseExpression(input.expr, { plugins: ['typescript'] }) as t.Expression
469
+ }
470
+
471
+ const ref = typeof input === 'string' ? input : isRecord(input) ? input.ref : undefined
472
+ if (typeof ref !== 'string' || !ref) {
473
+ throw new DataCalcEditingError('invalid_ref', 'Data getter requires a data ref string')
474
+ }
475
+
476
+ const resolved = await resolveDataReference(
477
+ ctx.projectDir,
478
+ ctx.parsed.absPath,
479
+ ref,
480
+ isRecord(input) ? (input.subspace as any) : undefined,
481
+ )
482
+ const local = resolved.sameFile
483
+ ? 'data'
484
+ : ensureNamespaceImport(ctx.parsed, resolved.importSource || '../data', 'data')
485
+ ctx.references.push(resolved)
486
+ return t.arrowFunctionExpression(
487
+ [],
488
+ t.memberExpression(t.identifier(local), t.identifier(resolved.varName)),
489
+ )
490
+ }
491
+
492
+ const nullableDataGetterExpression = async (value: any, ctx: EditContext) => {
493
+ if (value == null) return t.nullLiteral()
494
+ return dataGetterExpression(value, ctx)
495
+ }
496
+
497
+ // Alias-keyed makeId calls hash to the same uuid regardless of declaration order, so
498
+ // recompiles stay stable when sibling entries are added or removed.
499
+ const makeIdCallExpression = (idType: string, alias?: string) =>
500
+ t.callExpression(
501
+ t.identifier('makeId'),
502
+ alias ? [t.stringLiteral(idType), t.stringLiteral(alias)] : [t.stringLiteral(idType)],
503
+ )
504
+
505
+ // True when another calc anywhere in the project already uses the alias — the aliased
506
+ // makeId form would collide at compile time.
507
+ const aliasUsedInCalcs = async (projectDir: string, alias: string) => {
508
+ const subspacesDir = path.join(projectDir, 'subspaces')
509
+ const entries = await readdir(subspacesDir, { withFileTypes: true }).catch(() => [])
510
+ for (const entry of entries) {
511
+ if (!entry.isDirectory() || !/^subspace-\d+$/.test(entry.name)) continue
512
+ const files = await getDataCalcFiles(path.join(subspacesDir, entry.name, 'data-calc'))
513
+ for (const file of files) {
514
+ try {
515
+ const parsed = await readParsedFile(projectDir, file)
516
+ const calcEntry = getExportEntries(parsed.ast).find(
517
+ (item) => item.name === 'dataCalculation',
518
+ )
519
+ if (calcEntry?.alias === alias) return true
520
+ } catch {
521
+ continue
522
+ }
523
+ }
524
+ }
525
+ return false
526
+ }
527
+
528
+ // Required by the DataCalculationScript type; unsetting them yields a calc that
529
+ // crashes compile with an unrelated-looking error instead of a clear refusal here.
530
+ const requiredCalcFields = new Set([
531
+ '__typename',
532
+ 'id',
533
+ 'code',
534
+ 'enableAsync',
535
+ 'inputs',
536
+ 'output',
537
+ 'outputs',
538
+ 'error',
539
+ ])
540
+
541
+ const makeCodeReadFileExpression = (sandboxFile: string) =>
542
+ t.awaitExpression(
543
+ t.callExpression(t.identifier('readFile'), [
544
+ t.newExpression(t.identifier('URL'), [
545
+ t.stringLiteral(`./${sandboxFile}`),
546
+ t.memberExpression(
547
+ t.metaProperty(t.identifier('import'), t.identifier('meta')),
548
+ t.identifier('url'),
549
+ ),
550
+ ]),
551
+ t.stringLiteral('utf8'),
552
+ ]),
553
+ )
554
+
555
+ const expressionFromInput = async (input: any, ctx: EditContext): Promise<t.Expression> => {
556
+ if (isRecord(input)) {
557
+ if (typeof input.expr === 'string') {
558
+ return parseExpression(input.expr, { plugins: ['typescript'] }) as t.Expression
559
+ }
560
+ if (typeof input.ref === 'string') return dataGetterExpression(input, ctx)
561
+ }
562
+ if (input === null) return t.nullLiteral()
563
+ if (input === undefined) return t.identifier('undefined')
564
+ if (typeof input === 'string') return t.stringLiteral(input)
565
+ if (typeof input === 'number') return t.numericLiteral(input)
566
+ if (typeof input === 'boolean') return t.booleanLiteral(input)
567
+ if (Array.isArray(input)) {
568
+ return t.arrayExpression(
569
+ await Promise.all(input.map((value) => expressionFromInput(value, ctx))),
570
+ )
571
+ }
572
+ if (isRecord(input)) {
573
+ const properties = await Promise.all(
574
+ Object.entries(input).map(async ([key, value]) =>
575
+ t.objectProperty(makeObjectKey(key), await expressionFromInput(value, ctx)),
576
+ ),
577
+ )
578
+ return t.objectExpression(properties)
579
+ }
580
+ throw new DataCalcEditingError('invalid_value', `Unsupported value: ${String(input)}`)
581
+ }
582
+
583
+ const printAndFormat = async (parsed: ParsedFile) => {
584
+ const generated = generate(parsed.ast, { comments: true }, parsed.source).code
585
+ const formatted = await formatWithOxfmt(parsed.absPath, generated, oxfmtOptions)
586
+ if (formatted.errors.length > 0) {
587
+ throw new DataCalcEditingError('format_failed', `oxfmt failed for ${parsed.relPath}`, {
588
+ file: parsed.relPath,
589
+ errors: formatted.errors,
590
+ })
591
+ }
592
+ return formatted.code
593
+ }
594
+
595
+ const writeParsedFile = async (parsed: ParsedFile) => {
596
+ const code = await printAndFormat(parsed)
597
+ parseFileSource(code, parsed.relPath)
598
+ await writeFile(parsed.absPath, code)
599
+ return code
600
+ }
601
+
602
+ const responseFor = (result: any): any => ({
603
+ content: [{ type: 'text' as const, text: JSON.stringify(result, null, 2) }],
604
+ isError: result.isError || undefined,
605
+ })
606
+
607
+ const referenceInputDetails = (references: ReferenceResolution[]) =>
608
+ references.map((reference) => ({
609
+ input: reference.input,
610
+ id: reference.id,
611
+ alias: reference.alias,
612
+ entry: reference.varName,
613
+ }))
614
+
615
+ const runOperation = async (
616
+ projectDir: string,
617
+ tool: string,
618
+ input: any,
619
+ operation: () => Promise<any>,
620
+ ) => {
621
+ const startedAt = new Date().toISOString()
622
+ const provenance = editProvenance()
623
+ try {
624
+ const result = await operation()
625
+ await appendEditRecord(projectDir, {
626
+ ts: startedAt,
627
+ tool,
628
+ input,
629
+ provenance,
630
+ outcome: result.outcome,
631
+ summary: result.summary,
632
+ result,
633
+ })
634
+ return result
635
+ } catch (err: any) {
636
+ const isMcpError = err instanceof DataCalcEditingError
637
+ const outcome =
638
+ isMcpError && err.code === 'fallback_recommended' ? 'fallback_recommended' : 'error'
639
+ const result = {
640
+ outcome,
641
+ // Fallback recommendations are guidance, not MCP errors (mirrors entry-editing).
642
+ isError: outcome === 'error',
643
+ error: {
644
+ code: isMcpError ? err.code : 'unexpected_error',
645
+ message: err.message,
646
+ details: isMcpError ? err.details : undefined,
647
+ },
648
+ summary: `${tool} failed: ${err.message}`,
649
+ }
650
+ await appendEditRecord(projectDir, {
651
+ ts: startedAt,
652
+ tool,
653
+ input,
654
+ provenance,
655
+ outcome: result.outcome,
656
+ summary: result.summary,
657
+ error: result.error,
658
+ }).catch(() => undefined)
659
+ return result
660
+ }
661
+ }
662
+
663
+ const slugify = (value: string) => {
664
+ const slug = value
665
+ .trim()
666
+ .replace(/([a-z0-9])([A-Z])/g, '$1-$2')
667
+ .toLowerCase()
668
+ .replace(/[^a-z0-9]+/g, '-')
669
+ .replace(/^-+|-+$/g, '')
670
+ return slug || 'calc'
671
+ }
672
+
673
+ const nextFreeSlug = async (dataCalcDir: string, preferred?: string) => {
674
+ const existing = new Set((await getDataCalcFiles(dataCalcDir)).map(calcSlugFromFile))
675
+ if (preferred) {
676
+ let slug = slugify(preferred)
677
+ if (!existing.has(slug)) return slug
678
+ let index = 1
679
+ while (existing.has(`${slug}-${index}`)) index += 1
680
+ return `${slug}-${index}`
681
+ }
682
+
683
+ let index = 0
684
+ while (existing.has(String(index))) index += 1
685
+ return String(index)
686
+ }
687
+
688
+ // Compile unwraps the sandbox with the same acorn parse (compile/index.ts
689
+ // compileScriptCalculationCode, ecmaVersion 2020) and silently falls back to the raw
690
+ // wrapped string when it fails, so an unparseable sandbox must be rejected here.
691
+ const sandboxParses = (source: string) => {
692
+ try {
693
+ parseSandboxModule(source, { sourceType: 'module', ecmaVersion: 2020 })
694
+ return true
695
+ } catch {
696
+ return false
697
+ }
698
+ }
699
+
700
+ const wrapSandboxCode = (code?: string) => {
701
+ const body = code ?? ''
702
+ if (/export\s+(async\s+)?function\s+main\s*\(/.test(body)) {
703
+ const wrapped = body.endsWith('\n') ? body : `${body}\n`
704
+ if (!sandboxParses(wrapped)) {
705
+ throw new DataCalcEditingError(
706
+ 'invalid_code',
707
+ 'Sandbox code does not parse as a module (note: top-level await requires export async function main)',
708
+ )
709
+ }
710
+ return wrapped
711
+ }
712
+ const trimmed = body.trim()
713
+ if (!trimmed) return 'export function main() {\n}\n'
714
+ // Bodies using top-level await (enableAsync mode) only parse inside an async main;
715
+ // compile unwraps either wrapper form to the same script body.
716
+ for (const asyncPrefix of ['', 'async ']) {
717
+ const wrapped = `export ${asyncPrefix}function main() {\n${trimmed}\n}\n`
718
+ if (sandboxParses(wrapped)) return wrapped
719
+ }
720
+ throw new DataCalcEditingError(
721
+ 'invalid_code',
722
+ 'Sandbox code does not parse as a script body (statements with top-level return)',
723
+ )
724
+ }
725
+
726
+ const regenerateDataCalcIndex = async (projectDir: string, dataCalcDir: string) => {
727
+ await mkdir(dataCalcDir, { recursive: true })
728
+ const files = await getDataCalcFiles(dataCalcDir)
729
+ const imports = files
730
+ .map((file, index) => {
731
+ const slug = calcSlugFromFile(file)
732
+ return `import { dataCalculation as dataCalculation${index} } from './data-calculation-${slug}'`
733
+ })
734
+ .join('\n')
735
+ const list = files.map((_, index) => `dataCalculation${index}`).join(',\n ')
736
+ const source = `${imports}
737
+
738
+ export const dataCalculation = [
739
+ ${list}
740
+ ]
741
+ `
742
+ const indexPath = path.join(dataCalcDir, 'index.ts')
743
+ const parsed: ParsedFile = {
744
+ absPath: indexPath,
745
+ relPath: projectRelativePath(projectDir, indexPath),
746
+ source,
747
+ ast: parseFileSource(source, projectRelativePath(projectDir, indexPath)),
748
+ }
749
+ await writeParsedFile(parsed)
750
+ return projectRelativePath(projectDir, indexPath)
751
+ }
752
+
753
+ const getDefaultExportObject = (ast: t.File) => {
754
+ for (const statement of ast.program.body) {
755
+ if (!t.isExportDefaultDeclaration(statement)) continue
756
+ const declaration = statement.declaration
757
+ if (t.isObjectExpression(declaration)) return declaration
758
+ if (t.isTSAsExpression(declaration) && t.isObjectExpression(declaration.expression)) {
759
+ return declaration.expression
760
+ }
761
+ }
762
+ return null
763
+ }
764
+
765
+ const ensureSubspaceRootDataCalcImport = async (
766
+ projectDir: string,
767
+ subspaceDir: string,
768
+ ): Promise<{ touched?: string; warning?: string } | null> => {
769
+ const indexPath = path.join(subspaceDir, 'index.ts')
770
+ const relPath = projectRelativePath(projectDir, indexPath)
771
+ const source = await readFile(indexPath, 'utf8').catch((err: any) => {
772
+ if (err?.code === 'ENOENT') return null
773
+ throw err
774
+ })
775
+ if (source == null) {
776
+ return { warning: `${relPath} not found; wire the data-calc import manually` }
777
+ }
778
+
779
+ const parsed = await readParsedFile(projectDir, indexPath)
780
+ const object = getDefaultExportObject(parsed.ast)
781
+ if (!object) {
782
+ return {
783
+ warning: `${relPath} has no default-export object; wire the data-calc import manually`,
784
+ }
785
+ }
786
+
787
+ const property = getObjectProperty(object, 'dataCalculation')
788
+ if (property && t.isIdentifier(property.value)) return null
789
+ if (property && !(t.isArrayExpression(property.value) && property.value.elements.length === 0)) {
790
+ // Only the codegen minimal-subspace shape (dataCalculation: []) is safe to rewire;
791
+ // replacing any other value (inline calcs, spreads) would silently drop config.
792
+ return {
793
+ warning: `${relPath} has a non-empty dataCalculation value; wire the data-calc import manually`,
794
+ }
795
+ }
796
+
797
+ const alreadyImported = parsed.ast.program.body.some(
798
+ (statement) =>
799
+ t.isImportDeclaration(statement) &&
800
+ (statement.source.value === './data-calc' || statement.source.value === './data-calc/index'),
801
+ )
802
+ if (!alreadyImported) {
803
+ insertImport(
804
+ parsed.ast,
805
+ t.importDeclaration(
806
+ [t.importSpecifier(t.identifier('dataCalculation'), t.identifier('dataCalculation'))],
807
+ t.stringLiteral('./data-calc'),
808
+ ),
809
+ )
810
+ }
811
+
812
+ if (!property) {
813
+ const dataCalculationProperty = t.objectProperty(
814
+ t.identifier('dataCalculation'),
815
+ t.identifier('dataCalculation'),
816
+ )
817
+ dataCalculationProperty.shorthand = true
818
+ object.properties.push(dataCalculationProperty)
819
+ } else {
820
+ property.value = t.identifier('dataCalculation')
821
+ if (t.isIdentifier(property.key)) property.shorthand = true
822
+ }
823
+
824
+ await writeParsedFile(parsed)
825
+ return { touched: parsed.relPath }
826
+ }
827
+
828
+ const buildIoObject = async (field: 'inputs' | 'outputs', input: any, ctx: EditContext) => {
829
+ if (!input.key) {
830
+ throw new DataCalcEditingError('missing_key', `${field} item requires key`)
831
+ }
832
+ if (input.data == null) {
833
+ throw new DataCalcEditingError('missing_data', `${field} item requires data`)
834
+ }
835
+ const properties: t.ObjectProperty[] = [
836
+ t.objectProperty(t.identifier('key'), t.stringLiteral(input.key)),
837
+ t.objectProperty(t.identifier('data'), await dataGetterExpression(input.data, ctx)),
838
+ ]
839
+ if (field === 'inputs') {
840
+ properties.push(
841
+ t.objectProperty(t.identifier('trigger'), t.booleanLiteral(input.trigger !== false)),
842
+ )
843
+ }
844
+ return t.objectExpression(properties)
845
+ }
846
+
847
+ const buildIoArrayExpression = async (
848
+ field: 'inputs' | 'outputs',
849
+ items: any[],
850
+ ctx: EditContext,
851
+ ) => {
852
+ if (field === 'inputs') {
853
+ const keys = new Set<string>()
854
+ for (const item of items) {
855
+ if (keys.has(item?.key)) {
856
+ throw new DataCalcEditingError('duplicate_key', `Input key already exists: ${item.key}`, {
857
+ key: item.key,
858
+ })
859
+ }
860
+ keys.add(item?.key)
861
+ }
862
+ }
863
+ return t.arrayExpression(await Promise.all(items.map((item) => buildIoObject(field, item, ctx))))
864
+ }
865
+
866
+ const getOrCreateArrayProperty = (object: t.ObjectExpression, key: string) => {
867
+ const existing = getObjectProperty(object, key)
868
+ if (existing) {
869
+ if (!t.isArrayExpression(existing.value)) {
870
+ throw new DataCalcEditingError(
871
+ 'fallback_recommended',
872
+ `${key} is not an array. Edit this file directly.`,
873
+ )
874
+ }
875
+ return existing.value
876
+ }
877
+ const array = t.arrayExpression([])
878
+ object.properties.push(t.objectProperty(t.identifier(key), array))
879
+ return array
880
+ }
881
+
882
+ const findIoIndex = (array: t.ArrayExpression, target: { key?: string; index?: number }) => {
883
+ if (typeof target.index === 'number') return target.index
884
+ if (!target.key) return -1
885
+ const matches = array.elements
886
+ .map((element, index) => ({ element, index }))
887
+ .filter(
888
+ ({ element }) =>
889
+ t.isObjectExpression(element) && getStringProperty(element, 'key') === target.key,
890
+ )
891
+ if (matches.length > 1) {
892
+ throw new DataCalcEditingError('ambiguous_key', `IO key is ambiguous: ${target.key}`, {
893
+ key: target.key,
894
+ count: matches.length,
895
+ })
896
+ }
897
+ return matches[0]?.index ?? -1
898
+ }
899
+
900
+ const assertInputKeyUnique = (array: t.ArrayExpression, key: string, ignoreIndex?: number) => {
901
+ const duplicate = array.elements.some(
902
+ (element, index) =>
903
+ index !== ignoreIndex &&
904
+ t.isObjectExpression(element) &&
905
+ getStringProperty(element, 'key') === key,
906
+ )
907
+ if (duplicate) {
908
+ throw new DataCalcEditingError('duplicate_key', `Input key already exists: ${key}`, { key })
909
+ }
910
+ }
911
+
912
+ const buildCalcObject = async (
913
+ input: any,
914
+ sandboxFile: string,
915
+ ctx: EditContext,
916
+ stableIdAlias?: string,
917
+ ) => {
918
+ ctx.typeImports.add('DataCalculationScript')
919
+ ctx.valueImports.add('makeId')
920
+ ensureReadFileImport(ctx.parsed.ast)
921
+
922
+ const properties: t.ObjectProperty[] = [
923
+ t.objectProperty(t.identifier('__typename'), t.stringLiteral('DataCalculationScript')),
924
+ t.objectProperty(
925
+ t.identifier('id'),
926
+ input.id
927
+ ? t.stringLiteral(input.id)
928
+ : makeIdCallExpression('property_bank_calc', stableIdAlias),
929
+ ),
930
+ ]
931
+ if (input.alias)
932
+ properties.push(t.objectProperty(t.identifier('alias'), t.stringLiteral(input.alias)))
933
+ if (input.title != null)
934
+ properties.push(t.objectProperty(t.identifier('title'), t.stringLiteral(input.title)))
935
+ if (input.description != null) {
936
+ properties.push(
937
+ t.objectProperty(t.identifier('description'), t.stringLiteral(input.description)),
938
+ )
939
+ }
940
+ if (input.note != null)
941
+ properties.push(t.objectProperty(t.identifier('note'), t.stringLiteral(input.note)))
942
+
943
+ properties.push(t.objectProperty(t.identifier('code'), makeCodeReadFileExpression(sandboxFile)))
944
+ properties.push(
945
+ t.objectProperty(t.identifier('enableAsync'), t.booleanLiteral(!!input.enableAsync)),
946
+ )
947
+ if (input.triggerMode != null) {
948
+ properties.push(
949
+ t.objectProperty(t.identifier('triggerMode'), t.stringLiteral(input.triggerMode)),
950
+ )
951
+ }
952
+
953
+ properties.push(
954
+ t.objectProperty(
955
+ t.identifier('inputs'),
956
+ await buildIoArrayExpression('inputs', input.inputs || [], ctx),
957
+ ),
958
+ )
959
+ properties.push(
960
+ t.objectProperty(t.identifier('output'), await nullableDataGetterExpression(input.output, ctx)),
961
+ )
962
+ properties.push(
963
+ t.objectProperty(
964
+ t.identifier('outputs'),
965
+ await buildIoArrayExpression('outputs', input.outputs || [], ctx),
966
+ ),
967
+ )
968
+ properties.push(
969
+ t.objectProperty(t.identifier('error'), await nullableDataGetterExpression(input.error, ctx)),
970
+ )
971
+
972
+ return t.objectExpression(properties)
973
+ }
974
+
975
+ const createCalcParsedFile = (projectDir: string, absPath: string): ParsedFile => {
976
+ const relPath = projectRelativePath(projectDir, absPath)
977
+ const source = 'export const dataCalculation = {}\n'
978
+ const ast = parseFileSource(source, relPath)
979
+ ast.program.body = []
980
+ return { ast, source, absPath, relPath }
981
+ }
982
+
983
+ const newDataCalc = async (projectDir: string, input: any) =>
984
+ runOperation(projectDir, 'new_data_calc', input, async () => {
985
+ const subspaceDir = resolveSubspaceDir(projectDir, input.subspace)
986
+ const dataCalcDir = getCalcDirFromSubspaceDir(subspaceDir)
987
+ await mkdir(dataCalcDir, { recursive: true })
988
+ const slug = await nextFreeSlug(dataCalcDir, input.alias)
989
+ const sandboxFile = `data-calculation-${slug}.sandbox.js`
990
+ const calcPath = path.join(dataCalcDir, `data-calculation-${slug}.ts`)
991
+ const sandboxPath = path.join(dataCalcDir, sandboxFile)
992
+ const parsed = createCalcParsedFile(projectDir, calcPath)
993
+ const ctx: EditContext = {
994
+ projectDir,
995
+ parsed,
996
+ references: [],
997
+ typeImports: new Set(),
998
+ valueImports: new Set(),
999
+ }
1000
+ const stableIdAlias =
1001
+ !input.id &&
1002
+ typeof input.alias === 'string' &&
1003
+ input.alias &&
1004
+ !(await aliasUsedInCalcs(projectDir, input.alias))
1005
+ ? input.alias
1006
+ : undefined
1007
+ const object = await buildCalcObject(input, sandboxFile, ctx, stableIdAlias)
1008
+ const declarator = t.variableDeclarator(t.identifier('dataCalculation'), object)
1009
+ ;(declarator.id as t.Identifier).typeAnnotation = t.tsTypeAnnotation(
1010
+ t.tsTypeReference(t.identifier('DataCalculationScript')),
1011
+ )
1012
+ parsed.ast.program.body.push(
1013
+ t.exportNamedDeclaration(t.variableDeclaration('const', [declarator])),
1014
+ )
1015
+ applyPendingImports(ctx)
1016
+
1017
+ await writeFile(sandboxPath, wrapSandboxCode(input.code))
1018
+ await writeParsedFile(parsed)
1019
+ const touchedSites = [
1020
+ { file: projectRelativePath(projectDir, calcPath), action: 'create_calc' },
1021
+ { file: projectRelativePath(projectDir, sandboxPath), action: 'write_sandbox' },
1022
+ ]
1023
+ touchedSites.push({
1024
+ file: await regenerateDataCalcIndex(projectDir, dataCalcDir),
1025
+ action: 'regenerate_index',
1026
+ })
1027
+ const rootWiring = await ensureSubspaceRootDataCalcImport(projectDir, subspaceDir)
1028
+ if (rootWiring?.touched) {
1029
+ touchedSites.push({ file: rootWiring.touched, action: 'wire_subspace_index' })
1030
+ }
1031
+
1032
+ const verify = await verifyProject(projectDir, input.verify)
1033
+ return {
1034
+ file: projectRelativePath(projectDir, calcPath),
1035
+ subspace: path.basename(subspaceDir),
1036
+ calc: slug,
1037
+ idExpression:
1038
+ input.id ??
1039
+ (stableIdAlias
1040
+ ? `makeId('property_bank_calc', '${stableIdAlias}')`
1041
+ : "makeId('property_bank_calc')"),
1042
+ outcome: verify.status === 'compile:failed' ? 'verify_failed' : 'ok',
1043
+ touchedSites,
1044
+ ...(rootWiring?.warning ? { warnings: [rootWiring.warning] } : {}),
1045
+ verify,
1046
+ references: referenceInputDetails(ctx.references),
1047
+ summary: `created data calc ${slug} in ${path.basename(subspaceDir)} -> ${verify.status}`,
1048
+ }
1049
+ })
1050
+
1051
+ const editDataCalc = async (projectDir: string, input: any) =>
1052
+ runOperation(projectDir, 'edit_data_calc', input, async () => {
1053
+ const target = await resolveCalcTarget(projectDir, input)
1054
+ const ctx: EditContext = {
1055
+ projectDir,
1056
+ parsed: target.parsed,
1057
+ references: [],
1058
+ typeImports: new Set(),
1059
+ valueImports: new Set(),
1060
+ }
1061
+ const touchedSites: Array<Record<string, unknown>> = []
1062
+
1063
+ for (const [key, value] of Object.entries(input.set || {})) {
1064
+ if (key === 'output' || key === 'error') {
1065
+ setObjectProperty(target.object, key, await nullableDataGetterExpression(value, ctx))
1066
+ } else if (key === 'inputs' || key === 'outputs') {
1067
+ if (!Array.isArray(value)) {
1068
+ throw new DataCalcEditingError('invalid_value', `${key} must be an array of IO items`)
1069
+ }
1070
+ setObjectProperty(target.object, key, await buildIoArrayExpression(key, value, ctx))
1071
+ } else if (key === 'code') {
1072
+ throw new DataCalcEditingError(
1073
+ 'invalid_field',
1074
+ 'Set code via the dedicated code parameter so it stays normalized to the sandbox file',
1075
+ )
1076
+ } else {
1077
+ setObjectProperty(target.object, key, await expressionFromInput(value, ctx))
1078
+ }
1079
+ }
1080
+ for (const key of input.unset || []) {
1081
+ if (requiredCalcFields.has(key)) {
1082
+ throw new DataCalcEditingError('invalid_field', `Cannot unset required field: ${key}`, {
1083
+ field: key,
1084
+ })
1085
+ }
1086
+ removeObjectProperty(target.object, key)
1087
+ }
1088
+
1089
+ if (input.code != null) {
1090
+ const codeExpression = getCodeExpression(target.object)
1091
+ if (!isRecognizedCodeExpression(codeExpression)) {
1092
+ throw new DataCalcEditingError(
1093
+ 'fallback_recommended',
1094
+ `Data calc ${target.parsed.relPath} has an unsupported code expression. Edit this file directly for this one.`,
1095
+ { file: target.parsed.relPath, field: 'code' },
1096
+ )
1097
+ }
1098
+ const sandboxFile = target.sandboxFile
1099
+ const sandboxPath = path.join(path.dirname(target.parsed.absPath), sandboxFile)
1100
+ await writeFile(sandboxPath, wrapSandboxCode(input.code))
1101
+ ensureReadFileImport(target.parsed.ast)
1102
+ setObjectProperty(target.object, 'code', makeCodeReadFileExpression(sandboxFile))
1103
+ touchedSites.push({
1104
+ file: projectRelativePath(projectDir, sandboxPath),
1105
+ action: 'write_sandbox',
1106
+ })
1107
+ }
1108
+
1109
+ applyPendingImports(ctx)
1110
+ await writeParsedFile(target.parsed)
1111
+ touchedSites.unshift({ file: target.parsed.relPath, action: 'edit_calc' })
1112
+ const verify = await verifyProject(projectDir, input.verify)
1113
+ return {
1114
+ file: target.parsed.relPath,
1115
+ calc: target.slug,
1116
+ outcome: verify.status === 'compile:failed' ? 'verify_failed' : 'ok',
1117
+ touchedSites,
1118
+ verify,
1119
+ references: referenceInputDetails(ctx.references),
1120
+ summary: `edited data calc ${target.slug} -> ${verify.status}`,
1121
+ }
1122
+ })
1123
+
1124
+ const editDataCalcIo = async (projectDir: string, input: any) =>
1125
+ runOperation(projectDir, 'edit_data_calc_io', input, async () => {
1126
+ const target = await resolveCalcTarget(projectDir, input)
1127
+ const ctx: EditContext = {
1128
+ projectDir,
1129
+ parsed: target.parsed,
1130
+ references: [],
1131
+ typeImports: new Set(),
1132
+ valueImports: new Set(),
1133
+ }
1134
+ const field = input.field as 'inputs' | 'outputs'
1135
+ const array = getOrCreateArrayProperty(target.object, field)
1136
+ const op = input.op
1137
+
1138
+ if (op === 'clear') {
1139
+ array.elements = []
1140
+ } else if (op === 'remove') {
1141
+ const index = findIoIndex(array, input)
1142
+ if (index < 0 || index >= array.elements.length) {
1143
+ throw new DataCalcEditingError('invalid_index', 'remove requires a valid key or index')
1144
+ }
1145
+ array.elements.splice(index, 1)
1146
+ } else if (op === 'add' || op === 'replace') {
1147
+ const index = op === 'replace' ? findIoIndex(array, input) : input.index
1148
+ if (op === 'replace' && (index < 0 || index >= array.elements.length)) {
1149
+ throw new DataCalcEditingError('invalid_index', 'replace requires a valid key or index')
1150
+ }
1151
+ if (
1152
+ op === 'add' &&
1153
+ typeof index === 'number' &&
1154
+ (index < 0 || index > array.elements.length)
1155
+ ) {
1156
+ throw new DataCalcEditingError('invalid_index', 'add index out of range', { index })
1157
+ }
1158
+ if (field === 'inputs')
1159
+ assertInputKeyUnique(array, input.key, op === 'replace' ? index : undefined)
1160
+ const item = await buildIoObject(field, input, ctx)
1161
+ if (op === 'replace') array.elements[index] = item
1162
+ else array.elements.splice(typeof index === 'number' ? index : array.elements.length, 0, item)
1163
+ } else {
1164
+ throw new DataCalcEditingError('invalid_op', `Unsupported edit_data_calc_io op: ${op}`)
1165
+ }
1166
+
1167
+ applyPendingImports(ctx)
1168
+ await writeParsedFile(target.parsed)
1169
+ const verify = await verifyProject(projectDir, input.verify)
1170
+ return {
1171
+ file: target.parsed.relPath,
1172
+ calc: target.slug,
1173
+ outcome: verify.status === 'compile:failed' ? 'verify_failed' : 'ok',
1174
+ change: { field, op, key: input.key, index: input.index },
1175
+ verify,
1176
+ references: referenceInputDetails(ctx.references),
1177
+ summary: `${op} ${field} on data calc ${target.slug} -> ${verify.status}`,
1178
+ }
1179
+ })
1180
+
1181
+ const removeDataCalc = async (projectDir: string, input: any) =>
1182
+ runOperation(projectDir, 'remove_data_calc', input, async () => {
1183
+ const target = await resolveCalcTarget(projectDir, input)
1184
+ const dataCalcDir = path.dirname(target.parsed.absPath)
1185
+ const sandboxPath = path.join(dataCalcDir, target.sandboxFile)
1186
+ await rm(target.parsed.absPath, { force: true })
1187
+ await rm(sandboxPath, { force: true })
1188
+ const indexRelPath = await regenerateDataCalcIndex(projectDir, dataCalcDir)
1189
+ const verify = await verifyProject(projectDir, input.verify)
1190
+ return {
1191
+ file: target.parsed.relPath,
1192
+ calc: target.slug,
1193
+ outcome: verify.status === 'compile:failed' ? 'verify_failed' : 'ok',
1194
+ touchedSites: [
1195
+ { file: target.parsed.relPath, action: 'delete_calc' },
1196
+ { file: projectRelativePath(projectDir, sandboxPath), action: 'delete_sandbox' },
1197
+ { file: indexRelPath, action: 'regenerate_index' },
1198
+ ],
1199
+ verify,
1200
+ summary: `removed data calc ${target.slug} -> ${verify.status}`,
1201
+ }
1202
+ })
1203
+
1204
+ const valueSchema = z
1205
+ .any()
1206
+ .describe(
1207
+ 'Value grammar: JSON literals, bare data ref strings for output/error/IO data, { ref, subspace }, or { expr: "raw TypeScript expression" }.',
1208
+ )
1209
+ const fileSchema = z
1210
+ .string()
1211
+ .describe(
1212
+ 'Project-relative data-calc file path, for example subspaces/subspace-0/data-calc/data-calculation-total.ts.',
1213
+ )
1214
+ const subspaceSchema = z
1215
+ .union([z.string(), z.number()])
1216
+ .describe(
1217
+ 'Subspace locator. Defaults to subspace-0; accepts 0, "0", "subspace-0", or a project-relative subspace path.',
1218
+ )
1219
+ const calcSchema = z
1220
+ .string()
1221
+ .describe('Data calc locator inside the subspace: alias, explicit string id, or filename slug.')
1222
+ const verifySchema = z
1223
+ .boolean()
1224
+ .describe(
1225
+ 'Override compile verification. Defaults to BRICKS_CTOR_MCP_EDIT_VERIFY, otherwise true.',
1226
+ )
1227
+ const targetSchema = {
1228
+ file: fileSchema.optional(),
1229
+ subspace: subspaceSchema.optional(),
1230
+ calc: calcSchema.optional(),
1231
+ verify: verifySchema.optional(),
1232
+ }
1233
+ const ioItemSchema = z
1234
+ .object({
1235
+ key: z.string().describe('Sandbox input/output key, for example "price" or "total".'),
1236
+ data: valueSchema.describe('Data ref as alias/id/varName, { ref, subspace }, or { expr }.'),
1237
+ trigger: z.boolean().describe('Inputs only; defaults true.').optional(),
1238
+ })
1239
+ .describe('DataCalculationScript IO item.')
1240
+
1241
+ export function register(server: McpServer, projectDir: string) {
1242
+ server.tool(
1243
+ 'new_data_calc',
1244
+ 'Create a standard DataCalculationScript in data-calc/{calc}.ts plus its sandbox JS file, regenerate data-calc/index.ts, and wire minimal subspace indexes.',
1245
+ {
1246
+ subspace: subspaceSchema.optional(),
1247
+ alias: z.string().describe('Optional alias; also drives the filename slug.').optional(),
1248
+ title: z.string().describe('Optional title.').optional(),
1249
+ description: z.string().describe('Optional description.').optional(),
1250
+ note: z.string().describe('Optional script note.').optional(),
1251
+ triggerMode: z
1252
+ .enum(['auto', 'manual'])
1253
+ .describe('Optional trigger mode; omitted by default.')
1254
+ .optional(),
1255
+ enableAsync: z
1256
+ .boolean()
1257
+ .describe('Whether the sandbox main may be async. Defaults false.')
1258
+ .optional(),
1259
+ code: z
1260
+ .string()
1261
+ .describe(
1262
+ 'Sandbox body. The tool wraps it as export function main() { ... } unless already wrapped.',
1263
+ )
1264
+ .optional(),
1265
+ inputs: z
1266
+ .array(ioItemSchema)
1267
+ .describe('Initial script inputs. Input keys must be unique.')
1268
+ .optional(),
1269
+ outputs: z
1270
+ .array(ioItemSchema)
1271
+ .describe('Initial fan-out outputs. Output keys may repeat.')
1272
+ .optional(),
1273
+ output: valueSchema.describe('Single output data ref or null.').optional(),
1274
+ error: valueSchema.describe('Error output data ref or null.').optional(),
1275
+ id: z
1276
+ .string()
1277
+ .describe(
1278
+ "Optional explicit id. Defaults to source expression makeId('property_bank_calc').",
1279
+ )
1280
+ .optional(),
1281
+ verify: verifySchema.optional(),
1282
+ },
1283
+ async (input: any) => responseFor(await newDataCalc(projectDir, input)),
1284
+ )
1285
+
1286
+ server.tool(
1287
+ 'edit_data_calc',
1288
+ 'Edit DataCalculationScript scalar fields, output/error refs, or sandbox code. Code edits normalize inline code to sandbox file-form.',
1289
+ {
1290
+ ...targetSchema,
1291
+ set: z
1292
+ .record(
1293
+ z
1294
+ .string()
1295
+ .describe(
1296
+ 'Top-level field path such as title, description, note, alias, triggerMode, enableAsync, output, or error.',
1297
+ ),
1298
+ valueSchema,
1299
+ )
1300
+ .describe(
1301
+ 'Fields to set. output/error accept bare data ref strings, { ref, subspace }, { expr }, or null; inputs/outputs accept whole replacement arrays of { key, data, trigger? }. Use the code parameter for code.',
1302
+ )
1303
+ .optional(),
1304
+ unset: z.array(z.string()).describe('Top-level fields to remove.').optional(),
1305
+ code: z
1306
+ .string()
1307
+ .describe(
1308
+ 'Replacement sandbox body. The tool wraps it as export function main() { ... } unless already wrapped.',
1309
+ )
1310
+ .optional(),
1311
+ },
1312
+ async (input: any) => responseFor(await editDataCalc(projectDir, input)),
1313
+ )
1314
+
1315
+ server.tool(
1316
+ 'edit_data_calc_io',
1317
+ 'Edit DataCalculationScript inputs or outputs arrays. Inputs require unique keys; outputs may repeat keys for fan-out.',
1318
+ {
1319
+ ...targetSchema,
1320
+ field: z.enum(['inputs', 'outputs']).describe('Which IO array to edit.'),
1321
+ op: z.enum(['add', 'remove', 'replace', 'clear']).describe('Array operation.'),
1322
+ key: z
1323
+ .string()
1324
+ .describe('IO key target. Ambiguous repeated output keys must use index.')
1325
+ .optional(),
1326
+ index: z.number().describe('Zero-based IO index target or add insertion index.').optional(),
1327
+ data: valueSchema
1328
+ .describe('For add/replace: data ref as string, { ref, subspace }, or { expr }.')
1329
+ .optional(),
1330
+ trigger: z.boolean().describe('Inputs only; defaults true.').optional(),
1331
+ },
1332
+ async (input: any) => responseFor(await editDataCalcIo(projectDir, input)),
1333
+ )
1334
+
1335
+ server.tool(
1336
+ 'remove_data_calc',
1337
+ 'Remove a standard DataCalculationScript .ts file plus its sandbox file and regenerate data-calc/index.ts. No reverse cascade is needed.',
1338
+ targetSchema,
1339
+ async (input: any) => responseFor(await removeDataCalc(projectDir, input)),
1340
+ )
1341
+ }
1342
+
1343
+ export const __test__ = {
1344
+ newDataCalc,
1345
+ editDataCalc,
1346
+ editDataCalcIo,
1347
+ removeDataCalc,
1348
+ resolveCalcTarget,
1349
+ }