@fugood/bricks-project 2.25.0-beta.42 → 2.25.0-beta.43

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