@fugood/bricks-cli 2.26.0-beta.2 → 2.26.0-beta.3

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.
package/lib/3774.js CHANGED
@@ -2,7 +2,7 @@ export const __rspack_esm_id=3774;export const __rspack_esm_ids=[3774];export co
2
2
  # MCP entry-editing audit log
3
3
  ${l}
4
4
  `)}}),function(e){return i.apply(this,arguments)}),p=(n=a(function*(e,t){var r=o.join(e,".bricks");yield(0,s.mkdir)(r,{recursive:!0}),yield d(e),yield(0,s.appendFile)(o.join(r,"edits.jsonl"),`${JSON.stringify(t)}
5
- `)}),function(e,t){return n.apply(this,arguments)}),c=()=>({session:process.env.BRICKS_CTOR_SESSION_ID||process.env.CODEX_SESSION_ID,agent:process.env.BRICKS_CTOR_AGENT_ID||process.env.USER})},98009(e,t,r){r.d(t,{Gp:()=>v,HJ:()=>g,Hn:()=>p,JJ:()=>w,Kx:()=>k,LJ:()=>y,Pb:()=>P,R0:()=>_,RI:()=>u,Zj:()=>x,bf:()=>b,jc:()=>j,u4:()=>c,z5:()=>m,zu:()=>h});var i,n,a=r(68832),s=r(99436),o=r(58135),l=r(51455),d=r(76760),p={trailingComma:"all",tabWidth:2,semi:!1,singleQuote:!0,printWidth:100},c=e=>!!e&&"object"==typeof e&&!Array.isArray(e),u=(e,t)=>d.relative(e,t).replace(/\\/g,"/").replace(/^\.\/+/,""),f=(e,t)=>{var r=d.relative(e,t);return""!==r&&(r.startsWith(`..${d.sep}`)||".."===r||d.isAbsolute(r))?null:t},y=(i=s(function*(e,t){var r=a((yield Promise.all([(0,l.realpath)(e),(0,l.realpath)(t)])),2);return f(r[0],r[1])}),function(e,t){return i.apply(this,arguments)}),m=(n=s(function*(e,t){var r=yield(0,l.lstat)(t).catch(e=>{if(e?.code==="ENOENT")return null;throw e}),i=yield(0,l.realpath)(e);if(r){var n=yield(0,l.realpath)(t).catch(e=>{if(e?.code==="ENOENT")return null;throw e});return n?f(i,n):null}var a=yield(0,l.realpath)(d.dirname(t));return f(i,d.join(a,d.basename(t)))}),function(e,t){return n.apply(this,arguments)}),v=e=>o.isIdentifier(e)?e.name:o.isStringLiteral(e)||o.isNumericLiteral(e)?String(e.value):null,h=e=>/^[$A-Z_a-z][$\w]*$/.test(e)?o.identifier(e):o.stringLiteral(e),b=(e,t)=>e.properties.find(e=>!!o.isObjectProperty(e)&&v(e.key)===t),w=(e,t)=>{var r=b(e,t);if(r&&o.isStringLiteral(r.value))return r.value.value},x=e=>e.program.body.flatMap(e=>{if(!o.isExportNamedDeclaration(e)||!o.isVariableDeclaration(e.declaration))return[];var t=e.declaration;return t.declarations.flatMap(r=>{if(!o.isIdentifier(r.id))return[];var i,n=r.id.typeAnnotation;o.isTSTypeAnnotation(n)&&o.isTSTypeReference(n.typeAnnotation)&&o.isIdentifier(n.typeAnnotation.typeName)&&(i=n.typeAnnotation.typeName.name);var a=o.isObjectExpression(r.init)?r.init:void 0;return[{name:r.id.name,node:e,declaration:t,declarator:r,object:a,id:a?w(a,"id"):void 0,alias:a?w(a,"alias"):void 0,typeName:i}]})}),_=(e,t)=>{var r=new Set;for(var i of e.program.body){if(o.isImportDeclaration(i)){i.specifiers.forEach(e=>r.add(e.local.name));continue}o.isExportNamedDeclaration(i)&&o.isVariableDeclaration(i.declaration)&&i.declaration.declarations.forEach(e=>{o.isIdentifier(e.id)&&r.add(e.id.name)})}if(!r.has(t))return t;for(var n=1;r.has(`${t}${n}`);)n+=1;return`${t}${n}`},g=(e,t,r)=>{var i=b(e,t);if(i){i.value=r;return}e.properties.push(o.objectProperty(h(t),r))},j=(e,t)=>{var r=e.properties.findIndex(e=>!!o.isObjectProperty(e)&&v(e.key)===t);r>=0&&e.properties.splice(r,1)},P=(e,t)=>{var r=e.program.body,i=r.findLastIndex(e=>o.isImportDeclaration(e));r.splice(i+1,0,t)},k=(e,t,r)=>{var i=new Set(Array.from(r).filter(Boolean));if(0!==i.size){var n,a=function(e){return o.isImportDeclaration(e)&&"bricks-ctor"===e.source.value&&"type"===t==("type"===e.importKind)?(e.specifiers.forEach(e=>{if(o.isImportSpecifier(e)){var t=e.imported;o.isIdentifier(t)&&i.delete(t.name),o.isStringLiteral(t)&&i.delete(t.value)}}),i.forEach(t=>{e.specifiers.push(o.importSpecifier(o.identifier(t),o.identifier(t)))}),{v:void 0}):0};for(var s of e.program.body)if(0!==(n=a(s))&&n)return n.v;var l=o.importDeclaration(Array.from(i).map(e=>o.importSpecifier(o.identifier(e),o.identifier(e))),o.stringLiteral("bricks-ctor"));"type"===t&&(l.importKind="type"),P(e,l)}}},54452(e,t,r){r.d(t,{H:()=>p});var i,n,a=r(99436),s=r(75720),o=r(2985),l={FORCE_COLOR:"0",NO_COLOR:"1"},d=(i=a(function*(e){var t=yield(0,o.Re)(e);try{yield(0,s.sh)`bun compile`.cwd(e).env({...l,BRICKS_CTOR_ENABLE_EDITING_TOOLS:"0"}).text()}catch(e){var r=[e.stdout?.toString()??"",e.stderr?.toString()??"",e.message].filter(Boolean).join("\n").trim();return{status:"compile:failed",errors:r?[r]:["bun compile failed"]}}var i=yield(0,o.Re)(e);return{status:"compile:ok",errors:[],configChange:(0,o.m4)(t,i)}}),function(e){return i.apply(this,arguments)}),p=(n=a(function*(e,t){return"1"!==process.env.BRICKS_CTOR_MCP_DISABLE_COMPILE&&(void 0!==t?t:!["0","false","no","off"].includes((process.env.BRICKS_CTOR_MCP_EDIT_VERIFY??"true").toLowerCase()))?d(e):{status:"skipped",errors:[]}}),function(e,t){return n.apply(this,arguments)})},85949(e,t,r){r.a(e,async function(e,i){try{r.r(t),r.d(t,{__test__:()=>ts,register:()=>ta});var n,a,s,o,l,d,p,c,u,f,y,m,v,h,b,w,x,_,g,j,P,k,E,S,$,A,I,O,C,N,R,T=r(68832),D=r(99436),L=r(2235),F=r(46773),B=r(80004),K=r(58135),M=r(11978),z=r(79491),U=r(51455),q=r(77598),Y=r(76760),J=r(84867),H=r(54452),V=r(98009),G=r(3540),W=e([z]);z=(W.then?(await W)():W)[0];var Z=L.default||L,X=B.default||B,Q={"bricks.ts":{kind:"brick",namespace:"bricks",varPrefix:"b",idType:"brick",idPrefix:"BRICK_",typename:"Brick"},"generators.ts":{kind:"generator",namespace:"generators",varPrefix:"g",idType:"generator",idPrefix:"GENERATOR_",typename:"Generator"},"canvases.ts":{kind:"canvas",namespace:"canvases",varPrefix:"c",idType:"canvas",idPrefix:"CANVAS_",typename:"Canvas"},"data.ts":{kind:"data",namespace:"data",varPrefix:"d",idType:"data",idPrefix:"PROPERTY_BANK_DATA_NODE_",typename:"Data"},"animations.ts":{kind:"animation",namespace:"animations",varPrefix:"a",idType:"animation",idPrefix:"ANIMATION_",typename:"Animation"}};class to extends Error{constructor(e,t,r,i=!1){super(t),this.name="EntryEditingError",this.code=e,this.details=r,this.isMcpError=i}}var ee=(e,t)=>{if(Y.isAbsolute(t))throw new to("invalid_file","File must be project-relative",{file:t});var r=Y.resolve(e,t),i=Y.relative(e,r);if(i.startsWith("..")||Y.isAbsolute(i))throw new to("invalid_file","File must stay inside the project directory",{file:t});return r},et=(e,t)=>{try{return(0,F.parse)(e,{sourceType:"module",plugins:["typescript","topLevelAwait"],errorRecovery:!1})}catch(e){throw new to("parse_failed",`Cannot parse ${t} as TypeScript: ${e.message}. Edit this file directly.`,{file:t},!0)}},er=(n=D(function*(e,t){var r=yield(0,V.LJ)(e,t);if(!r)throw new to("invalid_file","File must stay inside the project directory",{file:(0,V.RI)(e,t)});var i=yield(0,U.readFile)(r,"utf8"),n=(0,V.RI)(e,t);return{source:i,ast:et(i,n),projectDir:e,absPath:t,ioPath:r,relPath:n,kind:(e=>{var t=Y.basename(e),r=Q[t];if(!r)throw new to("unsupported_file",`Unsupported entry file: ${t}`,{file:e,expected:Object.keys(Q)});return r})(t)}}),function(e,t){return n.apply(this,arguments)}),ei=(a=D(function*(e,t){var r=yield(0,V.z5)(e,t);if(!r)throw new to("invalid_file","File must stay inside the project directory",{file:(0,V.RI)(e,t)});return r}),function(e,t){return a.apply(this,arguments)}),en=(e,t)=>{var r=(0,V.Zj)(e.ast);if(t.entry){var i=r.find(e=>e.name===t.entry);if(i)return i;var n=r.filter(e=>e.alias===t.entry);if(1===n.length)return n[0];if(n.length>1)throw new to("ambiguous_reference",`Alias is ambiguous: ${t.entry}`,{file:e.relPath,entry:t.entry,matches:n.map(e=>e.name)});throw new to("entry_not_found",`Entry not found (by name or alias): ${t.entry}`,{file:e.relPath,entry:t.entry})}if(t.id){var a=r.find(e=>e.id===t.id);if(!a)throw new to("entry_not_found",`Entry id not found: ${t.id}`,{file:e.relPath,id:t.id});return a}throw new to("missing_target","Provide entry or id")},ea=e=>e.split(Y.sep).find(e=>/^subspace-\d+$/.test(e))||"unknown-subspace",es=e=>{var t=e.split(Y.sep),r=t.findIndex(e=>/^subspace-\d+$/.test(e));if(r<0)throw new to("invalid_file","Entry file must be inside subspaces/subspace-N",{file:e});return t.slice(0,r+1).join(Y.sep)},eo=(s=D(function*(e){var t=Y.join(e,"subspaces");return(yield(0,U.readdir)(t,{withFileTypes:!0}).catch(()=>[])).filter(e=>e.isDirectory()&&/^subspace-\d+$/.test(e.name)).map(e=>Y.join(t,e.name)).sort()}),function(e){return s.apply(this,arguments)}),el=(o=D(function*(e){var t=Object.keys(Q),r=yield(0,U.readdir)(e,{withFileTypes:!0}).catch(()=>[]),i=new Set(r.filter(e=>e.isFile()).map(e=>e.name));return t.filter(e=>i.has(e)).map(t=>Y.join(e,t))}),function(e){return o.apply(this,arguments)}),ed=(l=D(function*(e){var t=yield eo(e);return(yield Promise.all(t.map(el))).flat()}),function(e){return l.apply(this,arguments)}),ep=(d=D(function*(e,t){if(t.file)return ee(e,t.file);if(!t.id)throw new to("missing_file","Provide file, or provide id for global lookup");for(var r of yield ed(e)){var i=yield er(e,r);if((0,V.Zj)(i.ast).find(e=>e.id===t.id))return r}throw new to("entry_not_found",`Entry id not found: ${t.id}`,{id:t.id})}),function(e,t){return d.apply(this,arguments)}),ec=(p=D(function*(e,t){var r=yield ep(e,t),i=yield er(e,r),n=en(i,t),a=((e,t)=>{if(!e.object)throw new to("fallback_recommended",`Entry ${e.name} in ${t} is not a top-level exported object literal. Edit this file directly for this one.`,{file:t,entry:e.name,check:"top-level export const object literal"});return e.object})(n,i.relPath);return{parsed:i,entry:n,object:a}}),function(e,t){return p.apply(this,arguments)}),eu=(e,t)=>K.callExpression(K.identifier("makeId"),t?[K.stringLiteral(e),K.stringLiteral(t)]:[K.stringLiteral(e)]),ef=e=>{var t=[];for(var r of e.split(".").filter(Boolean))for(var i=/([^\[\]]+)|\[(\d+)\]/g,n=void 0;n=i.exec(r);)n[1]&&t.push({key:n[1]}),n[2]&&t.push({index:Number(n[2])});if(0===t.length)throw new to("invalid_path",`Invalid path: ${e}`,{path:e});return t},ey=e=>K.isTSAsExpression(e)||K.isTSSatisfiesExpression(e)||K.isTSNonNullExpression(e)||K.isParenthesizedExpression(e)?ey(e.expression):e,em=(e,t)=>{var r=ey(e);if(!K.isObjectExpression(r))throw new to("fallback_recommended",`Target path ${t} is not an object literal. Edit this file directly for this one.`,{path:t,expected:"object literal",actual:r.type});return r},ev=(e,t)=>{var r=ey(e);if(!K.isArrayExpression(r))throw new to("fallback_recommended",`Target path ${t} is not an array literal. Edit this file directly for this one.`,{path:t,expected:"array literal",actual:r.type});return r},eh=e=>"array"==("index"in e?"array":"object")?K.arrayExpression([]):K.objectExpression([]),eb=(c=D(function*(e,t,r,i){for(var n=ef(t),a=e,s=0;s<n.length;s+=1){var o=n[s],l=s===n.length-1;if("key"in o){var d=em(a,t);if(l)return void(0,V.HJ)(d,o.key,(yield eA(r,i)));var p=n[s+1],c=(0,V.bf)(d,o.key);c||(c=K.objectProperty((0,V.zu)(o.key),eh(p)),d.properties.push(c)),a=c.value;continue}var u=ev(a,t);if(o.index<0||o.index>u.elements.length)throw new to("invalid_path",`Array index out of range for ${t}`,{path:t,index:o.index});if(l){u.elements[o.index]=yield eA(r,i);return}u.elements[o.index]||(u.elements[o.index]=eh(n[s+1])),a=u.elements[o.index]}}),function(e,t,r,i){return c.apply(this,arguments)}),ew=(e,t)=>{for(var r=ef(t),i=e,n=0;n<r.length;n+=1){var a=r[n],s=n===r.length-1;if("key"in a){var o=em(i,t);if(s)return void(0,V.jc)(o,a.key);var l=(0,V.bf)(o,a.key);if(!l)return;i=l.value;continue}var d=ev(i,t);if(a.index<0||a.index>=d.elements.length)return;if(s)return void d.elements.splice(a.index,1);var p=d.elements[a.index];if(!p)return;i=p}},ex=(e,t)=>{var r=(0,V.bf)(e,"switches");if(!r)throw new to("fallback_recommended","Entry has no switches array",{path:"switches"});var i=ev(r.value,"switches"),n="number"==typeof t?t:i.elements.findIndex(e=>K.isObjectExpression(e)&&(0,V.JJ)(e,"id")===t);if(n<0||n>=i.elements.length)throw new to("entry_not_found",`Switch not found: ${t}`,{switch:t});var a=i.elements[n];if(!K.isObjectExpression(a))throw new to("fallback_recommended",`Switch ${String(t)} is not an object literal. Edit this file directly for this one.`,{switch:t});return a},e_=(e,t)=>{var r=t.replace(/\.[tj]sx?$/,""),i=Y.relative(Y.dirname(e),r).replace(/\\/g,"/");return i.startsWith(".")||(i=`./${i}`),i},eg=(e,t,r)=>{for(var i of e.ast.program.body)if(K.isImportDeclaration(i)&&i.source.value===t){var n=i.specifiers.find(e=>K.isImportDefaultSpecifier(e));if(n)return n.local.name}var a=(0,V.R0)(e.ast,r),s=K.importDeclaration([K.importDefaultSpecifier(K.identifier(a))],K.stringLiteral(t));return(0,V.Pb)(e.ast,s),a},ej=e=>{(0,V.Kx)(e.parsed.ast,"type",e.typeImports),(0,V.Kx)(e.parsed.ast,"value",e.valueImports)},eP=(u=D(function*(e,t,r){if(null==r||""===r)return t;if("number"==typeof r)return Y.join(e,"subspaces",`subspace-${r}`);var i=String(r);if(/^\d+$/.test(i))return Y.join(e,"subspaces",`subspace-${i}`);if(/^subspace-\d+$/.test(i))return Y.join(e,"subspaces",i);if(i.includes("/"))return ee(e,i);var n,a=yield eo(e),s=function*(){var t=Y.join(o,"index.ts"),r=yield(0,U.readFile)(t,"utf8").catch(()=>"");if(!r)return 0;var n=et(r,(0,V.RI)(e,t)),a=!1;if(X(n,{ObjectProperty(e){"id"===(0,V.Gp)(e.node.key)&&K.isStringLiteral(e.node.value)&&e.node.value.value===i&&(a=!0,e.stop())}}),a)return{v:o}};for(var o of a)if(n=yield*s(),0!==n&&n)return n.v;throw new to("reference_not_found",`Subspace not found: ${i}`,{subspace:i})}),function(e,t,r){return u.apply(this,arguments)}),ek=(f=D(function*(e,t){var r,i,n=es(e.parsed.absPath),a=yield eP(e.projectDir,n,t),s=Y.basename(a),o=/^subspace-(\d+)$/.exec(s);if(!o)throw new to("invalid_subspace",`Not a subspace directory: ${s}`,{subspace:t});var l=Y.join(a,"index.ts"),d=yield(0,U.readFile)(l,"utf8").catch(()=>null);if(null==d)throw new to("reference_not_found",`Subspace not found: ${t}`,{subspace:t});var p=(r=et(d,(0,V.RI)(e.projectDir,l)),X(r,{ObjectProperty(e){if("id"===(0,V.Gp)(e.node.key)){var t=e.node.value;K.isStringLiteral(t)&&t.value.startsWith("SUBSPACE_")&&(i=t.value,e.stop())}}}),i);if(!p)throw new to("invalid_subspace",`Subspace index has no SUBSPACE_ id: ${s}/index.ts`,{subspace:t});return{id:p,index:Number(o[1]),label:s,indexPath:l,isCurrent:Y.resolve(a)===Y.resolve(n)}}),function(e,t){return f.apply(this,arguments)}),eE=(y=D(function*(e,t){var r=yield ek(e,t);if(r.isCurrent)return e.references.push({input:t,id:r.id,sameFile:!1,display:`'${r.id}'`,targetAbsPath:r.indexPath}),{resolved:r,expression:K.stringLiteral(r.id)};var i=eg(e.parsed,`../${r.label}`,`subspace${r.index}`);return e.references.push({input:t,id:r.id,sameFile:!1,display:`() => ${i}`,targetAbsPath:r.indexPath}),{resolved:r,expression:K.arrowFunctionExpression([],K.identifier(i))}}),function(e,t){return y.apply(this,arguments)}),eS=(m=D(function*(e,t,r,i){var n=es(t),a=yield eP(e,n,i),s=yield el(a),o=[];for(var l of s){var d=yield er(e,l),p=d.kind;for(var c of(0,V.Zj)(d.ast))if(c.name===r||c.id===r||c.alias===r){var u=Y.resolve(l)===Y.resolve(t),f=Y.basename(a);o.push({input:r,id:c.id,alias:c.alias,varName:c.name,namespace:p.namespace,display:`${p.namespace}.${c.name}`,targetAbsPath:l,sameFile:u,subspaceLabel:f,importSource:u?void 0:e_(t,l)})}}if(0===o.length)throw new to("reference_not_found",`Reference not found: ${r}`,{ref:r,subspace:i??Y.basename(n)});if(o.length>1)throw new to("ambiguous_reference",`Reference is ambiguous: ${r}`,{ref:r,matches:o.map(t=>({file:(0,V.RI)(e,t.targetAbsPath),entry:t.varName,id:t.id,alias:t.alias}))});return o[0]}),function(e,t,r,i){return m.apply(this,arguments)}),e$=(v=D(function*(e,t,r){var i=yield eS(t.projectDir,t.parsed.absPath,e,r);if(i.sameFile)return t.references.push(i),K.identifier(i.varName);var n=es(t.parsed.absPath),a=es(i.targetAbsPath),s=i.subspaceLabel.replace(/[^a-zA-Z0-9_$]/g,""),o=n===a?i.namespace:`${s}${i.namespace[0].toUpperCase()}${i.namespace.slice(1)}`,l=((e,t,r,i)=>{for(var n of e.ast.program.body)if(K.isImportDeclaration(n)&&n.source.value===r){var a=n.specifiers.find(K.isImportNamespaceSpecifier);if(a)return a.local.name}var s=(0,V.R0)(e.ast,i),o=K.importDeclaration([K.importNamespaceSpecifier(K.identifier(s))],K.stringLiteral(r));return(0,V.Pb)(e.ast,o),s})(t.parsed,i.namespace,i.importSource,o);return i.importLocal=l,t.references.push({...i,display:`${l}.${i.varName}`,importLocal:l}),K.memberExpression(K.identifier(l),K.identifier(i.varName))}),function(e,t,r){return v.apply(this,arguments)}),eA=(h=D(function*(e,t){if((0,V.u4)(e)&&"string"==typeof e.expr&&1===Object.keys(e).length){var r=e.expr;try{return(0,F.parseExpression)(r,{plugins:["typescript"]})}catch(e){throw new to("invalid_expr",`Invalid TypeScript expression: ${e.message}`,{expr:r})}}if((0,V.u4)(e)&&"string"==typeof e.link){t.valueImports.add("linkData");var i=yield e$(e.link,t,e.subspace);return K.callExpression(K.identifier("linkData"),[K.arrowFunctionExpression([],i)])}if((0,V.u4)(e)&&"string"==typeof e.ref){var n=yield e$(e.ref,t,e.subspace);return K.arrowFunctionExpression([],n)}if(Array.isArray(e))return K.arrayExpression((yield Promise.all(e.map(e=>eA(e,t)))));if((0,V.u4)(e)){var a,s=yield Promise.all(Object.entries(e).map((a=D(function*([e,r]){return K.objectProperty((0,V.zu)(e),(yield eA(r,t)))}),function(e){return a.apply(this,arguments)})));return K.objectExpression(s)}return void 0===e?K.identifier("undefined"):K.valueToNode(e)}),function(e,t){return h.apply(this,arguments)}),eI=e=>e.map(e=>({input:e.input,id:e.id,alias:e.alias,resolved:e.importLocal?`${e.importLocal}.${e.varName}`:e.sameFile?e.varName:e.display,file:e.targetAbsPath})),eO=(b=D(function*(e){var t=Z(e.ast,{comments:!0},e.source).code,r=yield(0,z.format)(e.absPath,t,V.Hn);if(r.errors.length>0)throw new to("format_failed",`oxfmt failed for ${e.relPath}`,{file:e.relPath,errors:r.errors});return r.code}),function(e){return b.apply(this,arguments)}),eC=(w=D(function*(e){var t=yield eO(e);return et(t,e.relPath),yield(0,U.writeFile)(e.ioPath??(yield ei(e.projectDir,e.absPath)),t),t}),function(e){return w.apply(this,arguments)}),eN=(e,t)=>{if(e){var r=ea(e.absPath);return`${t?.name||"entry"} (${e.kind.kind}, ${r})`}},eR=(x=D(function*(e,t,r,i){var n={ts:new Date().toISOString(),tool:t,op:r?.op||(r?.set?"set":r?.unset?"unset":t),target:{file:r?.file,entry:r?.entry,id:r?.id},provenance:(0,G.S)()};try{var a=yield i(),s={...n,...a};return yield(0,G.a)(e,s).catch(e=>{s.auditError=e.message}),s}catch(i){var o=i instanceof to?i:new to("error",i.message||String(i),void 0,!0),l="fallback_recommended"===o.code?"fallback_recommended":"error",d={...n,outcome:l,input:r,error:{code:o.code,message:o.message,details:o.details},summary:"fallback_recommended"===l?`${t} could not safely edit this standard path; edit the file directly`:`${t} failed: ${o.message}`,isError:o.isMcpError||"error"===l};return yield(0,G.a)(e,d).catch(e=>{d.auditError=e.message}),d}}),function(e,t,r,i){return x.apply(this,arguments)}),eT=(_=D(function*(e,t){return eR(e,"edit_entry",t,D(function*(){var r=yield ec(e,t),i=r.parsed,n=r.entry,a=r.object,s={projectDir:e,parsed:i,references:[],typeImports:new Set,valueImports:new Set},o=null==t.switch?a:ex(a,t.switch);for(var l of Object.entries(t.set||{})){var d=T(l,2),p=d[0],c=d[1];yield eb(o,p,c,s)}for(var u of[...t.unset||[]].sort((e,t)=>{for(var r=ef(e).map(e=>"index"in e?e.index:-1),i=ef(t).map(e=>"index"in e?e.index:-1),n=0;n<Math.min(r.length,i.length);n+=1)if(r[n]!==i[n])return i[n]-r[n];return i.length-r.length}))ew(o,u);ej(s),yield eC(i);var f=yield(0,H.H)(e,t.verify),y=eN(i,n);return{file:i.relPath,entry:n.name,id:n.id,change:{set:t.set||{},unset:t.unset||[],references:eI(s.references)},outcome:"compile:failed"===f.status?"verify_failed":"ok",verify:f,summary:`edited ${y} -> ${f.status}`}}))}),function(e,t){return _.apply(this,arguments)}),eD=e=>{switch(e){case"IfStatement":return"an if statement";case"ForStatement":case"ForOfStatement":case"ForInStatement":return"a for loop";case"WhileStatement":case"DoWhileStatement":return"a while loop";case"SwitchStatement":return"a switch statement";case"TryStatement":return"a try/catch block";case"FunctionDeclaration":return"a function declaration";case"ReturnStatement":return"a return before the final statement";default:return`a ${e}`}},eL=(e,t)=>{for(var r=0;r<e.length;r+=1){var i=e[r],n=r===e.length-1;if("ExpressionStatement"===i.type){var a=eF(i.expression);if(a)return a;continue}if("VariableDeclaration"===i.type){for(var s of i.declarations)if("Identifier"!==s.id.type||!s.init)return"a destructuring or uninitialized declaration";continue}if(t&&n&&"ReturnStatement"===i.type){var o=i.argument?eF(i.argument):null;if(o)return o;continue}return eD(i.type)}return null},eF=e=>{if(e?.type!=="CallExpression"||e.arguments?.length||e.callee?.type!=="ArrowFunctionExpression"&&e.callee?.type!=="FunctionExpression")return null;var t=e.callee.body;return t?.type==="BlockStatement"?eL(t.body,!0):eF(t)},eB=(g=D(function*(e,t){if(e?.expr)return eA(e,t);var r,i=(e=>{if(!(0,V.u4)(e)||!(0,V.u4)(e.action))return e;var t=e.action,r={handler:e.handler,name:t.name??t.__actionName,waitAsync:e.waitAsync};if(t.cast&&(r.cast=t.cast),Array.isArray(t.params))for(var i of(r.params={},t.params)){if(!(0,V.u4)(i)||"string"!=typeof i.input)throw new to("invalid_action",'Compiled action params entries require { input: "name", value }',{param:i});r.params[i.input]=i.value}if(Array.isArray(t.dataParams))for(var n of(r.dataParams={},t.dataParams)){var a=(0,V.u4)(n?.input)?n.input.ref:n?.input;if("string"!=typeof a||!a)throw new to("invalid_action","Compiled action dataParams entries require { input: dataRef, value }",{param:n});r.dataParams[a]=n.value}return r})(e),n=i?.name;if(!n)throw new to("invalid_action","Action requires name");if("PROPERTY_BANK_EXPRESSION"===n&&(0,V.u4)(i.params)){var a=i.params.expression;"string"==typeof a&&(e=>{try{t=(0,M.qg)(e,{ecmaVersion:2020})}catch(t){throw new to("invalid_action",`PROPERTY_BANK_EXPRESSION does not parse: ${t.message}`,{expression:e})}var t,r=eL(t.body,!1);if(r)throw new to("invalid_action",`PROPERTY_BANK_EXPRESSION cannot evaluate ${r}: the runtime folds the expression into a single expression (expression statements, simple const/let declarations, and a final return inside an IIFE only). Use ternaries instead of statements, or move branching logic to a DataCalculationScript.`,{expression:e})})(a)}var s="System",o=i.cast;if("system"===i.handler||null==i.handler)r=K.stringLiteral("system"),o||=`SystemAction${n.toLowerCase().split("_").filter(Boolean).map(e=>`${e[0].toUpperCase()}${e.slice(1)}`).join("")}`;else if((0,V.u4)(i.handler)&&"string"==typeof i.handler.ref){var l=yield eS(t.projectDir,t.parsed.absPath,i.handler.ref,i.handler.subspace);if("bricks"!==l.namespace&&"generators"!==l.namespace)throw new to("invalid_action",`Action handler must be a brick or generator, got ${l.namespace}: ${i.handler.ref}`,{handler:i.handler});s="bricks"===l.namespace?"Brick":"Generator";var d=yield e$(i.handler.ref,t,i.handler.subspace);r=K.arrowFunctionExpression([],d)}else if((0,V.u4)(i.handler)&&null!=i.handler.subspace)r=(yield eE(t,i.handler.subspace)).expression,s="Subspace";else throw new to("invalid_action","Unsupported action handler",{handler:i.handler});var p=[K.objectProperty(K.identifier("__actionName"),K.stringLiteral(n)),K.objectProperty(K.identifier("parent"),K.stringLiteral(s)),K.objectProperty(K.identifier("name"),K.stringLiteral(n))];if(i.params){var c,u=yield Promise.all(Object.entries(i.params).map((c=D(function*([e,r]){return K.objectExpression([K.objectProperty(K.identifier("input"),K.stringLiteral(e)),K.objectProperty(K.identifier("value"),(yield eA(r,t)))])}),function(e){return c.apply(this,arguments)})));p.push(K.objectProperty(K.identifier("params"),K.arrayExpression(u)))}if(i.dataParams){var f,y=yield Promise.all(Object.entries(i.dataParams).map((f=D(function*([e,r]){var i=yield e$(e,t);return K.objectExpression([K.objectProperty(K.identifier("input"),K.arrowFunctionExpression([],i)),K.objectProperty(K.identifier("value"),(yield eA(r,t)))])}),function(e){return f.apply(this,arguments)})));p.push(K.objectProperty(K.identifier("dataParams"),K.arrayExpression(y)))}var m=K.objectExpression(p);return o&&(t.typeImports.add(o),m=K.tsAsExpression(m,K.tsTypeReference(K.identifier(o)))),K.objectExpression([K.objectProperty(K.identifier("handler"),r),K.objectProperty(K.identifier("action"),m),K.objectProperty(K.identifier("waitAsync"),K.booleanLiteral(!!i.waitAsync))])}),function(e,t){return g.apply(this,arguments)}),eK=(e,t,r)=>{var i=(0,V.bf)(e,t);return i||(i=K.objectProperty((0,V.zu)(t),K.objectExpression([])),e.properties.push(i)),em(i.value,r)},eM=(e,t,r)=>{var i=(0,V.bf)(e,t);return i||(i=K.objectProperty((0,V.zu)(t),K.arrayExpression([])),e.properties.push(i)),ev(i.value,r)},ez=(j=D(function*(e,t){return eR(e,"edit_events",t,D(function*(){var r=yield ec(e,t),i=r.parsed,n=r.entry,a=r.object,s={projectDir:e,parsed:i,references:[],typeImports:new Set,valueImports:new Set},o=null==t.switch?a:ex(a,t.switch),l=t.op;if("clear"===l||"remove"===l||"move"===l){var d=(0,V.bf)(o,"events"),p=d?em(d.value,"events"):null,c=p?(0,V.bf)(p,t.event):null,u=c?ev(c.value,`events.${t.event}`):null;if("clear"===l)p&&(0,V.jc)(p,t.event);else if("move"===l){if(null==t.index)throw new to("invalid_index","move requires index");if(!u||t.index<0||t.index>=u.elements.length)throw new to("invalid_index","move index out of range",{index:t.index});var f=Number(t.to);if(!Number.isFinite(f)||f<0||f>=u.elements.length)throw new to("invalid_index","move requires valid to index",{to:t.to});var y=u.elements.splice(t.index,1),m=T(y,1)[0];u.elements.splice(f,0,m)}else{if(null==t.index)throw new to("invalid_index","remove requires index");if(!u||t.index<0||t.index>=u.elements.length)throw new to("invalid_index","remove index out of range",{index:t.index});u.elements.splice(t.index,1),0===u.elements.length&&p&&(0,V.jc)(p,t.event)}}else if("add"===l||"replace"===l){var v=yield eB(t.action,s),h=eK(o,"events","events"),b=eM(h,t.event,`events.${t.event}`),w=t.index??b.elements.length;if("replace"===l){if(w<0||w>=b.elements.length)throw new to("invalid_index","replace index out of range",{index:w});b.elements[w]=v}else{if(w<0||w>b.elements.length)throw new to("invalid_index","add index out of range",{index:w});b.elements.splice(w,0,v)}}else throw new to("invalid_op",`Unsupported edit_events op: ${l}`);ej(s),yield eC(i);var x=yield(0,H.H)(e,t.verify);return{file:i.relPath,entry:n.name,id:n.id,change:{event:t.event,op:l,index:t.index,references:eI(s.references)},outcome:"compile:failed"===x.status?"verify_failed":"ok",verify:x,summary:`${l} event ${t.event} on ${eN(i,n)} -> ${x.status}`}}))}),function(e,t){return j.apply(this,arguments)}),eU=e=>{if((0,V.u4)(e)&&"string"==typeof e.expr)return e;if(!(0,V.u4)(e))throw new to("invalid_item","Canvas item requires frame { x, y, width, height }");for(var t of["x","y","width","height"])if("number"!=typeof e[t])throw new to("invalid_item",`Canvas item frame requires numeric ${t}`,{frame:e});return e},eq=(P=D(function*(e,t,r){if(!e?.ref&&e?.subspace==null)throw new to("invalid_item","Canvas item requires ref (brick) or subspace (embed)");var i,n=eU(e.frame??r);if(e.ref){var a=yield e$(e.ref,t,e.subspace);i=K.arrowFunctionExpression([],a)}else{var s=yield eE(t,e.subspace),o=s.resolved,l=s.expression;if(o.isCurrent)throw new to("invalid_item","A subspace cannot embed itself",{subspace:e.subspace});i=l}return K.objectExpression([K.objectProperty(K.identifier("item"),i),K.objectProperty(K.identifier("frame"),(yield eA(n,t))),...null==e.hidden?[]:[K.objectProperty(K.identifier("hidden"),K.booleanLiteral(!!e.hidden))]])}),function(e,t,r){return P.apply(this,arguments)}),eY=(k=D(function*(e,t){return eR(e,"edit_canvas_items",t,D(function*(){var r=yield ec(e,t),i=r.parsed,n=r.entry,a=r.object;if("canvas"!==i.kind.kind)throw new to("invalid_file","edit_canvas_items only edits canvases.ts entries",{file:i.relPath});var s={projectDir:e,parsed:i,references:[],typeImports:new Set,valueImports:new Set},o=eM(a,"items","items"),l=t.op;if("add"===l||"replace"===l){var d=yield eq(t.item,s,t.frame),p=t.index??o.elements.length;if("replace"===l){if(p<0||p>=o.elements.length)throw new to("invalid_index","replace index out of range",{index:p});o.elements[p]=d}else{if(p<0||p>o.elements.length)throw new to("invalid_index","add index out of range",{index:p});o.elements.splice(p,0,d)}}else if("remove"===l){if(null==t.index)throw new to("invalid_index","remove requires index");if(t.index<0||t.index>=o.elements.length)throw new to("invalid_index","remove index out of range",{index:t.index});o.elements.splice(t.index,1)}else if("move"===l){if(null==t.index)throw new to("invalid_index","move requires index");if(!t.frame)throw new to("invalid_item","move requires frame");if(t.index<0||t.index>=o.elements.length)throw new to("invalid_index","move index out of range",{index:t.index});var c=o.elements[t.index];if(!K.isObjectExpression(c))throw new to("fallback_recommended","Canvas item is not an object literal",{index:t.index});(0,V.HJ)(c,"frame",(yield eA(eU(t.frame),s)))}else throw new to("invalid_op",`Unsupported edit_canvas_items op: ${l}`);ej(s),yield eC(i);var u=yield(0,H.H)(e,t.verify);return{file:i.relPath,entry:n.name,id:n.id,change:{op:l,index:t.index,references:eI(s.references)},outcome:"compile:failed"===u.status?"verify_failed":"ok",verify:u,summary:`${l} canvas item on ${eN(i,n)} -> ${u.status}`}}))}),function(e,t){return k.apply(this,arguments)}),eJ=(E=D(function*(e,t){var r=(e=>{switch(e?.__typename){case"SwitchCondInnerStateCurrentCanvas":return{type:"inner_state",key:"current_canvas",value:e.value,subspace:e.subspace};case"SwitchCondInnerStateOutlet":return{type:"inner_state",outlet:e.outlet,value:e.value};case"SwitchCondData":return{type:"property_bank",ref:e.data??e.ref,value:e.value,subspace:e.subspace};case"SwitchCondPropertyBankByItemKey":return{type:"property_bank_by_item_key",ref:e.data??e.ref,value:e.value,subspace:e.subspace};case"SwitchCondItemKeyMapping":return{type:"item_key_mapping",key:e.key,value:e.value};default:return e}})(e);if(r?.expr)return eA(r,t);if(r?.type==="inner_state"&&"current_canvas"===r.key){var i=yield e$(r.value,t,r.subspace);return K.objectExpression([K.objectProperty(K.identifier("__typename"),K.stringLiteral("SwitchCondInnerStateCurrentCanvas")),K.objectProperty(K.identifier("value"),K.arrowFunctionExpression([],i))])}if(r?.type==="inner_state"){var n=r.outlet||r.key;if(!n)throw new to("invalid_switch","Switch inner-state outlet condition requires outlet or key");return K.objectExpression([K.objectProperty(K.identifier("__typename"),K.stringLiteral("SwitchCondInnerStateOutlet")),K.objectProperty(K.identifier("outlet"),K.stringLiteral(n)),K.objectProperty(K.identifier("value"),(yield eA(r.value,t)))])}if(r?.type==="item_key_mapping"){if(!r.key)throw new to("invalid_switch","Switch item key mapping condition requires key");return K.objectExpression([K.objectProperty(K.identifier("__typename"),K.stringLiteral("SwitchCondItemKeyMapping")),K.objectProperty(K.identifier("key"),K.stringLiteral(r.key)),K.objectProperty(K.identifier("value"),(yield eA(r.value,t)))])}var a=r?.ref||r?.data||r?.key;if(!a)throw new to("invalid_switch","Switch condition requires data ref");var s=yield e$(a,t,r.subspace);return K.objectExpression([K.objectProperty(K.identifier("__typename"),K.stringLiteral(r?.type==="property_bank_by_item_key"?"SwitchCondPropertyBankByItemKey":"SwitchCondData")),K.objectProperty(K.identifier("data"),K.arrowFunctionExpression([],s)),K.objectProperty(K.identifier("value"),(yield eA(r.value,t)))])}),function(e,t){return E.apply(this,arguments)}),eH=new Set(["id","title","description","conds","override","property","outlets","animation","events","disabled","break"]),eV=(S=D(function*(e,t){for(var r of Object.keys(e))if(!eH.has(r))throw new to("invalid_switch",`Unknown switch field: ${r}`,{field:r,supported:Array.from(eH)});if(void 0!==e.events)throw new to("invalid_switch","Set switch events with edit_events using its switch parameter");if(e.id&&!/^BRICK_STATE_GROUP_[0-9a-fA-F-]{36}$/.test(e.id))throw new to("invalid_switch","Switch id must match BRICK_STATE_GROUP_<uuid>; omit id to generate one",{id:e.id});var i,n=e.id?K.stringLiteral(e.id):eu("switch");e.id||t.valueImports.add("makeId");var a=[K.objectProperty(K.identifier("id"),n)];for(var s of(null!=e.title&&a.push(K.objectProperty(K.identifier("title"),K.stringLiteral(e.title))),null!=e.description&&a.push(K.objectProperty(K.identifier("description"),K.stringLiteral(e.description))),e.conds&&a.push(K.objectProperty(K.identifier("conds"),K.arrayExpression((yield Promise.all(e.conds.map((i=D(function*(e){return K.objectExpression([K.objectProperty(K.identifier("method"),K.stringLiteral(e.method||"==")),K.objectProperty(K.identifier("cond"),(yield eJ(e.cond||e,t)))])}),function(e){return i.apply(this,arguments)}))))))),e.override&&a.push(K.objectProperty(K.identifier("override"),(yield eA(e.override,t)))),["property","outlets","animation"]))null!=e[s]&&a.push(K.objectProperty(K.identifier(s),(yield eA(e[s],t))));return null!=e.disabled&&a.push(K.objectProperty(K.identifier("disabled"),K.booleanLiteral(!!e.disabled))),null!=e.break&&a.push(K.objectProperty(K.identifier("break"),K.booleanLiteral(!!e.break))),K.objectExpression(a)}),function(e,t){return S.apply(this,arguments)}),eG=($=D(function*(e,t){return eR(e,"edit_switches",t,D(function*(){var r=yield ec(e,t),i=r.parsed,n=r.entry,a=r.object,s={projectDir:e,parsed:i,references:[],typeImports:new Set,valueImports:new Set},o=eM(a,"switches","switches"),l=t.op,d=e=>"number"==typeof e?e:e?o.elements.findIndex(t=>K.isObjectExpression(t)&&(0,V.JJ)(t,"id")===e):-1;if("add"===l||"replace"===l){var p=yield eV(t.switch||{},s),c=null==t.index?o.elements.length:d(t.index);if("replace"===l){if(c<0||c>=o.elements.length)throw new to("invalid_index","replace index out of range",{index:c});o.elements[c]=p}else{if(c<0||c>o.elements.length)throw new to("invalid_index","add requires a valid switch id or index",{index:t.index});o.elements.splice(c,0,p)}}else if("remove"===l){var u=d(t.index);if(u<0||u>=o.elements.length)throw new to("invalid_index","remove requires a valid switch id or index",{index:t.index});o.elements.splice(u,1)}else if("move"===l){var f=d(t.index);if(f<0||f>=o.elements.length)throw new to("invalid_index","move requires a valid switch id or index",{index:t.index});var y=Number(t.to);if(!Number.isFinite(y)||y<0||y>=o.elements.length)throw new to("invalid_index","move requires valid to index",{to:t.to});var m=o.elements.splice(f,1),v=T(m,1)[0];o.elements.splice(y,0,v)}else throw new to("invalid_op",`Unsupported edit_switches op: ${l}`);ej(s),yield eC(i);var h=yield(0,H.H)(e,t.verify);return{file:i.relPath,entry:n.name,id:n.id,change:{op:l,index:t.index,references:eI(s.references)},outcome:"compile:failed"===h.status?"verify_failed":"ok",verify:h,summary:`${l} switch on ${eN(i,n)} -> ${h.status}`}}))}),function(e,t){return $.apply(this,arguments)}),eW=(A=D(function*(e,t,r,i){var n=[K.objectProperty(K.identifier("__typename"),K.stringLiteral(e.typename)),K.objectProperty(K.identifier("id"),r)];return t.alias&&n.push(K.objectProperty(K.identifier("alias"),K.stringLiteral(t.alias))),null!=t.title&&n.push(K.objectProperty(K.identifier("title"),K.stringLiteral(t.title))),null!=t.description&&n.push(K.objectProperty(K.identifier("description"),K.stringLiteral(t.description))),"brick"===e.kind||"generator"===e.kind?(n.push(K.objectProperty(K.identifier("templateKey"),K.stringLiteral(t.templateKey||""))),n.push(K.objectProperty(K.identifier("property"),K.objectExpression([]))),n.push(K.objectProperty(K.identifier("events"),K.objectExpression([]))),n.push(K.objectProperty(K.identifier("outlets"),K.objectExpression([]))),"brick"===e.kind&&n.push(K.objectProperty(K.identifier("animation"),K.objectExpression([]))),n.push(K.objectProperty(K.identifier("switches"),K.arrayExpression([])))):"canvas"===e.kind?(n.push(K.objectProperty(K.identifier("property"),K.objectExpression([]))),n.push(K.objectProperty(K.identifier("events"),K.objectExpression([]))),n.push(K.objectProperty(K.identifier("switches"),K.arrayExpression([]))),n.push(K.objectProperty(K.identifier("items"),K.arrayExpression([])))):"data"===e.kind?(n.push(K.objectProperty(K.identifier("type"),K.stringLiteral(t.dataType||"any"))),n.push(K.objectProperty(K.identifier("schema"),K.objectExpression([]))),n.push(K.objectProperty(K.identifier("events"),K.objectExpression([]))),n.push(K.objectProperty(K.identifier("value"),K.identifier("undefined")))):"animation"===e.kind&&(n.push(K.objectProperty(K.identifier("runType"),K.stringLiteral("once"))),n.push(K.objectProperty(K.identifier("property"),K.stringLiteral("opacity"))),n.push(K.objectProperty(K.identifier("config"),(yield eA({__type:"AnimationTimingConfig",toValue:1,duration:300,easing:"",delay:0,isInteraction:!0},i))))),K.objectExpression(n)}),function(e,t,r,i){return A.apply(this,arguments)}),eZ=(I=D(function*(e,t,r){var i=Y.basename(t);for(var n of(yield ed(e)).filter(e=>Y.basename(e)===i)){var a=yield er(e,n);if((0,V.Zj)(a.ast).some(e=>e.alias===r))return!0}return!1}),function(e,t,r){return I.apply(this,arguments)}),eX=(O=D(function*(e,t){return eR(e,"new_entry",t,D(function*(){if(!t.file)throw new to("missing_file","new_entry requires file");if(!t.type)throw new to("missing_type","new_entry requires TypeScript type");var r=ee(e,t.file),i=yield er(e,r),n=new Set((0,V.Zj)(i.ast).map(e=>e.name)),a="string"==typeof t.id?t.id:void 0,s=a||"string"!=typeof t.alias||!t.alias||(yield eZ(e,r,t.alias))?void 0:t.alias,o=a?K.stringLiteral(a):eu(i.kind.idType,s),l=t.entry||((e,t,r,i)=>{var n,a=(e=>{if(!e)return null;var t=e.replace(/[^a-zA-Z0-9_$]/g,"");return t?(/^[0-9]/.test(t)&&(t=`_${t}`),t):null})(i)||(r?`${t.varPrefix}${n=r.replace(/^[A-Z_]+/g,""),`${n.substr(15,3)}${n.substr(20,1)}`}`:`${t.varPrefix}Entry`);if(!e.has(a))return a;for(var s=1;e.has(`${a}${s}`);)s+=1;return`${a}${s}`})(n,i.kind,a,t.alias||t.title),d={projectDir:e,parsed:i,references:[],typeImports:new Set([t.type]),valueImports:new Set};a||d.valueImports.add("makeId");var p=yield eW(i.kind,t,o,d),c=K.variableDeclarator(K.identifier(l),p);for(var u of(c.id.typeAnnotation=K.tsTypeAnnotation(K.tsTypeReference(K.identifier(t.type))),i.ast.program.body.push(K.exportNamedDeclaration(K.variableDeclaration("const",[c]))),Object.entries(t.set||{}))){var f=T(u,2),y=f[0],m=f[1];yield eb(p,y,m,d)}for(var v of t.events||[]){if(!(0,V.u4)(v)||"string"!=typeof v.event||!v.event||!v.action)throw new to("invalid_action","events entries require { event, action }",{event:v});var h=eK(p,"events","events");eM(h,v.event,`events.${v.event}`).elements.push((yield eB(v.action,d)))}ej(d),yield eC(i);var b=yield(0,H.H)(e,t.verify);return{file:i.relPath,entry:l,id:a,idExpression:a??(s?`makeId('${i.kind.idType}', '${s}')`:`makeId('${i.kind.idType}')`),change:{set:t.set||{},events:t.events||[],references:eI(d.references)},outcome:"compile:failed"===b.status?"verify_failed":"ok",verify:b,summary:`created ${l} (${i.kind.kind}, ${ea(i.absPath)}) -> ${b.status}`}}))}),function(e,t){return O.apply(this,arguments)}),eQ=(e,t)=>{var r;return K.isArrowFunctionExpression(e)&&0===e.params.length&&(r=e.body,!!r&&(K.isIdentifier(r)?r.name===t.varName:!!K.isMemberExpression(r)&&!!K.isIdentifier(r.object)&&!!K.isIdentifier(r.property)&&r.object.name===t.namespace&&r.property.name===t.varName))},e0=(e,t)=>K.isCallExpression(e)&&K.isIdentifier(e.callee,{name:"linkData"})&&eQ(e.arguments[0],t),e1=(e,t)=>{if(!e)return!1;if(eQ(e,t)||e0(e,t))return!0;var r=!1;return X(K.file(K.program([K.expressionStatement(K.cloneNode(e,!0))])),{ArrowFunctionExpression(e){eQ(e.node,t)&&(r=!0,e.stop())},CallExpression(e){e0(e.node,t)&&(r=!0,e.stop())}}),r},e4=(e,t,r,i=[],n={})=>{if(K.isProgram(e))return void e.body.forEach((e,a)=>e4(e,t,r,[...i,String(a)],n));if(K.isExportNamedDeclaration(e)&&e.declaration)return void e4(e.declaration,t,r,i,n);if(K.isVariableDeclaration(e))return void e.declarations.forEach((e,a)=>e4(e,t,r,[...i,String(a)],n));if(K.isVariableDeclarator(e)&&e.init)return void e4(e.init,t,r,i,n);if(K.isObjectExpression(e)){for(var a=e.properties.length-1;a>=0;a-=1){var s=e.properties[a];if(K.isObjectProperty(s)){var o=(0,V.Gp)(s.key)||`property-${a}`,l=[...i,o];if(eQ(s.value,t)||e0(s.value,t)){i.includes("outlets")?(e.properties.splice(a,1),r.push({action:"drop_outlet",path:l.join(".")})):n.dataCalc&&("output"===o||"error"===o)?(s.value=K.nullLiteral(),r.push({action:"null_output",path:l.join(".")})):(s.value=K.identifier("undefined"),r.push({action:"null_link",path:l.join(".")}));continue}e4(s.value,t,r,l,n)}}return}if(K.isArrayExpression(e))for(var d=i[i.length-1],p=i.includes("events")&&"events"!==d,c=n.dataCalc?["items","params","dataParams","conds","switches","inputs","outputs"]:["items","params","dataParams","conds","switches"],u=e.elements.length-1;u>=0;u-=1){var f=e.elements[u];if(f){var y=[...i,String(u)];if(e1(f,t)&&(c.includes(d)||p||eQ(f,t))){e.elements.splice(u,1),r.push({action:p?"delete_event_handler":n.dataCalc&&("inputs"===d||"outputs"===d)?"remove_io_item":"remove_reference_item",path:y.join(".")});continue}e4(f,t,r,y,n)}}},e5=(e,t)=>{var r=e.ast.program.body.indexOf(t.node);r>=0&&e.ast.program.body.splice(r,1)},e9=(C=D(function*(e,t,r){if("project"===r)return ed(e);var i=es(t),n=yield el(i),a=Y.join(i,"data-calc"),s=yield(0,U.readdir)(a,{withFileTypes:!0}).catch(()=>[]);return[...n,...s.filter(e=>e.isFile()&&e.name.endsWith(".ts")).map(e=>Y.join(a,e.name))]}),function(e,t,r){return C.apply(this,arguments)}),e8=(N=D(function*(e,t){return eR(e,"remove_entry",t,D(function*(){var r,i=yield ec(e,t),n=i.parsed,a=i.entry,s={varName:a.name,namespace:n.kind.namespace,id:a.id},o=yield e9(e,n.absPath,t.scope),l=[],d=yield Promise.all(o.map((r=D(function*(t){var r=yield(0,U.readFile)(t,"utf8");return{absPath:t,relPath:(0,V.RI)(e,t),source:r,ast:et(r,(0,V.RI)(e,t)),kind:Q[Y.basename(t)]||n.kind}}),function(e){return r.apply(this,arguments)}))),p=function*(e){var t,r,i,o,d;(o=(e.absPath===n.absPath?(t=a.name,r=K.cloneNode(e.ast,!0),i={...e,ast:r},e5(i,en(i,{entry:t})),i):e).ast,d=[],X(o,{ArrowFunctionExpression(e){eQ(e.node,s)&&d.push({type:"ref",loc:e.node.loc?.start})},CallExpression(e){e0(e.node,s)&&d.push({type:"link",loc:e.node.loc?.start})}}),d).forEach(t=>l.push({file:e.relPath,...t}))};for(var c of d)yield*p(c);if(t.strict&&l.length>0)return{file:n.relPath,entry:a.name,id:a.id,outcome:"refused",touchedSites:l,verify:{status:"skipped",errors:[]},summary:`refused to remove ${eN(n,a)}; ${l.length} reference(s) found`};var u=function*(t){var r=[],i={dataCalc:t.absPath.split(Y.sep).includes("data-calc")};if(t.absPath===n.absPath&&(e5(t,en(t,{entry:a.name})),r.push({action:"remove_entry",path:a.name})),e4(t.ast.program,s,r,[],i),0===r.length)return 1;var o=yield eO(t);et(o,t.relPath),yield(0,U.writeFile)((yield ei(e,t.absPath)),o),r.forEach(e=>l.push({file:t.relPath,...e}))};for(var f of d)if(yield*u(f))continue;var y=yield(0,H.H)(e,t.verify);return{file:n.relPath,entry:a.name,id:a.id,outcome:"compile:failed"===y.status?"verify_failed":"ok",touchedSites:l,verify:y,summary:`removed ${eN(n,a)} with ${l.length} touched site(s) -> ${y.status}`}}))}),function(e,t){return N.apply(this,arguments)}),e7=(R=D(function*(e,t){return eR(e,"new_subspace",t,D(function*(){var r=Y.join(e,"root.ts"),i=(0,V.RI)(e,r),n=yield(0,U.readFile)(r,"utf8").catch(()=>null);if(null==n)throw new to("invalid_file","Project has no root.ts to wire the subspace into");var a={source:n,ast:et(n,i),projectDir:e,absPath:r,relPath:i},s=a.ast.program.body.find(e=>K.isExportDefaultDeclaration(e));if(!s||!K.isArrayExpression(s.declaration))throw new to("fallback_recommended","root.ts default export is not a subspace array literal; wire the new subspace manually",{file:i});var o=(yield eo(e)).reduce((e,t)=>{var r=/^subspace-(\d+)$/.exec(Y.basename(t));return r?Math.max(e,Number(r[1])):e},-1)+1,l=`subspace-${o}`,d=Y.join(e,"subspaces",l),p=`SUBSPACE_${(0,q.randomUUID)()}`,c=`CANVAS_${(0,q.randomUUID)()}`,u=(({subspaceId:e,canvasId:t,title:r,description:i,layout:n,portal:a})=>{var s=[`width: ${n.width}`,`height: ${n.height}`,...n.resizeMode?[`resizeMode: '${n.resizeMode}'`]:[]];return{"data.ts":"import type { Data } from 'bricks-ctor'\n","bricks.ts":"import type { Brick } from 'bricks-ctor'\n","generators.ts":"import type { Generator } from 'bricks-ctor'\n","animations.ts":"import type { Animation } from 'bricks-ctor'\n","canvases.ts":`import type { Canvas } from 'bricks-ctor'
5
+ `)}),function(e,t){return n.apply(this,arguments)}),c=()=>({session:process.env.BRICKS_CTOR_SESSION_ID||process.env.CODEX_SESSION_ID,agent:process.env.BRICKS_CTOR_AGENT_ID||process.env.USER})},98009(e,t,r){r.d(t,{Gp:()=>v,HJ:()=>g,Hn:()=>p,JJ:()=>w,Kx:()=>k,LJ:()=>y,Pb:()=>P,R0:()=>_,RI:()=>u,Zj:()=>x,bf:()=>b,jc:()=>j,u4:()=>c,z5:()=>m,zu:()=>h});var i,n,a=r(68832),s=r(99436),o=r(58135),l=r(51455),d=r(76760),p={trailingComma:"all",tabWidth:2,semi:!1,singleQuote:!0,printWidth:100},c=e=>!!e&&"object"==typeof e&&!Array.isArray(e),u=(e,t)=>d.relative(e,t).replace(/\\/g,"/").replace(/^\.\/+/,""),f=(e,t)=>{var r=d.relative(e,t);return""!==r&&(r.startsWith(`..${d.sep}`)||".."===r||d.isAbsolute(r))?null:t},y=(i=s(function*(e,t){var r=a((yield Promise.all([(0,l.realpath)(e),(0,l.realpath)(t)])),2);return f(r[0],r[1])}),function(e,t){return i.apply(this,arguments)}),m=(n=s(function*(e,t){var r=yield(0,l.lstat)(t).catch(e=>{if(e?.code==="ENOENT")return null;throw e}),i=yield(0,l.realpath)(e);if(r){var n=yield(0,l.realpath)(t).catch(e=>{if(e?.code==="ENOENT")return null;throw e});return n?f(i,n):null}var a=yield(0,l.realpath)(d.dirname(t));return f(i,d.join(a,d.basename(t)))}),function(e,t){return n.apply(this,arguments)}),v=e=>o.isIdentifier(e)?e.name:o.isStringLiteral(e)||o.isNumericLiteral(e)?String(e.value):null,h=e=>/^[$A-Z_a-z][$\w]*$/.test(e)?o.identifier(e):o.stringLiteral(e),b=(e,t)=>e.properties.find(e=>!!o.isObjectProperty(e)&&v(e.key)===t),w=(e,t)=>{var r=b(e,t);if(r&&o.isStringLiteral(r.value))return r.value.value},x=e=>e.program.body.flatMap(e=>{if(!o.isExportNamedDeclaration(e)||!o.isVariableDeclaration(e.declaration))return[];var t=e.declaration;return t.declarations.flatMap(r=>{if(!o.isIdentifier(r.id))return[];var i,n=r.id.typeAnnotation;o.isTSTypeAnnotation(n)&&o.isTSTypeReference(n.typeAnnotation)&&o.isIdentifier(n.typeAnnotation.typeName)&&(i=n.typeAnnotation.typeName.name);var a=o.isObjectExpression(r.init)?r.init:void 0;return[{name:r.id.name,node:e,declaration:t,declarator:r,object:a,id:a?w(a,"id"):void 0,alias:a?w(a,"alias"):void 0,typeName:i}]})}),_=(e,t)=>{var r=new Set;for(var i of e.program.body){if(o.isImportDeclaration(i)){i.specifiers.forEach(e=>r.add(e.local.name));continue}o.isExportNamedDeclaration(i)&&o.isVariableDeclaration(i.declaration)&&i.declaration.declarations.forEach(e=>{o.isIdentifier(e.id)&&r.add(e.id.name)})}if(!r.has(t))return t;for(var n=1;r.has(`${t}${n}`);)n+=1;return`${t}${n}`},g=(e,t,r)=>{var i=b(e,t);if(i){i.value=r;return}e.properties.push(o.objectProperty(h(t),r))},j=(e,t)=>{var r=e.properties.findIndex(e=>!!o.isObjectProperty(e)&&v(e.key)===t);r>=0&&e.properties.splice(r,1)},P=(e,t)=>{var r=e.program.body,i=r.findLastIndex(e=>o.isImportDeclaration(e));r.splice(i+1,0,t)},k=(e,t,r)=>{var i=new Set(Array.from(r).filter(Boolean));if(0!==i.size){var n,a=function(e){return o.isImportDeclaration(e)&&"bricks-ctor"===e.source.value&&"type"===t==("type"===e.importKind)?(e.specifiers.forEach(e=>{if(o.isImportSpecifier(e)){var t=e.imported;o.isIdentifier(t)&&i.delete(t.name),o.isStringLiteral(t)&&i.delete(t.value)}}),i.forEach(t=>{e.specifiers.push(o.importSpecifier(o.identifier(t),o.identifier(t)))}),{v:void 0}):0};for(var s of e.program.body)if(0!==(n=a(s))&&n)return n.v;var l=o.importDeclaration(Array.from(i).map(e=>o.importSpecifier(o.identifier(e),o.identifier(e))),o.stringLiteral("bricks-ctor"));"type"===t&&(l.importKind="type"),P(e,l)}}},54452(e,t,r){r.d(t,{H:()=>p});var i,n,a=r(99436),s=r(75720),o=r(2985),l={FORCE_COLOR:"0",NO_COLOR:"1"},d=(i=a(function*(e){var t=yield(0,o.Re)(e);try{yield(0,s.sh)`bun compile`.cwd(e).env({...l,BRICKS_CTOR_ENABLE_EDITING_TOOLS:"0"}).text()}catch(e){var r=[e.stdout?.toString()??"",e.stderr?.toString()??"",e.message].filter(Boolean).join("\n").trim();return{status:"compile:failed",errors:r?[r]:["bun compile failed"]}}var i=yield(0,o.Re)(e);return{status:"compile:ok",errors:[],configChange:(0,o.m4)(t,i)}}),function(e){return i.apply(this,arguments)}),p=(n=a(function*(e,t){return"1"!==process.env.BRICKS_CTOR_MCP_DISABLE_COMPILE&&(void 0!==t?t:!["0","false","no","off"].includes((process.env.BRICKS_CTOR_MCP_EDIT_VERIFY??"true").toLowerCase()))?d(e):{status:"skipped",errors:[]}}),function(e,t){return n.apply(this,arguments)})},85949(e,t,r){r.a(e,async function(e,i){try{r.r(t),r.d(t,{__test__:()=>ty,register:()=>tf});var n,a,s,o,l,d,p,c,u,f,y,m,v,h,b,w,x,_,g,j,P,k,E,S,$,A,I,O,C,N,R,T=r(68832),D=r(99436),L=r(44668),F=r(5018),B=r(63315),K=r(30409),M=r(40906),z=r(59410),U=r(2235),q=r(46773),Y=r(80004),J=r(58135),H=r(11978),V=r(79491),G=r(51455),W=r(77598),Z=r(76760),X=r(84867),Q=r(54452),ee=r(98009),et=r(3540),er=e([V]);function ei(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(ei=function(){return!!e})()}V=(er.then?(await er)():er)[0];var en=U.default||U,ea=Y.default||Y,es={"bricks.ts":{kind:"brick",namespace:"bricks",varPrefix:"b",idType:"brick",idPrefix:"BRICK_",typename:"Brick"},"generators.ts":{kind:"generator",namespace:"generators",varPrefix:"g",idType:"generator",idPrefix:"GENERATOR_",typename:"Generator"},"canvases.ts":{kind:"canvas",namespace:"canvases",varPrefix:"c",idType:"canvas",idPrefix:"CANVAS_",typename:"Canvas"},"data.ts":{kind:"data",namespace:"data",varPrefix:"d",idType:"data",idPrefix:"PROPERTY_BANK_DATA_NODE_",typename:"Data"},"animations.ts":{kind:"animation",namespace:"animations",varPrefix:"a",idType:"animation",idPrefix:"ANIMATION_",typename:"Animation"}},eo=function(e){function t(e,r,i,n=!1){var a,s,o;return F(this,t),s=t,o=[r],s=K(s),(a=B(this,ei()?Reflect.construct(s,o||[],K(this).constructor):s.apply(this,o))).name="EntryEditingError",a.code=e,a.details=i,a.isMcpError=n,a}return M(t,e),L(t)}(z(Error)),el=(e,t)=>{if(Z.isAbsolute(t))throw new eo("invalid_file","File must be project-relative",{file:t});var r=Z.resolve(e,t),i=Z.relative(e,r);if(i.startsWith("..")||Z.isAbsolute(i))throw new eo("invalid_file","File must stay inside the project directory",{file:t});return r},ed=(e,t)=>{try{return(0,q.parse)(e,{sourceType:"module",plugins:["typescript","topLevelAwait"],errorRecovery:!1})}catch(e){throw new eo("parse_failed",`Cannot parse ${t} as TypeScript: ${e.message}. Edit this file directly.`,{file:t},!0)}},ep=(n=D(function*(e,t){var r=yield(0,ee.LJ)(e,t);if(!r)throw new eo("invalid_file","File must stay inside the project directory",{file:(0,ee.RI)(e,t)});var i=yield(0,G.readFile)(r,"utf8"),n=(0,ee.RI)(e,t);return{source:i,ast:ed(i,n),projectDir:e,absPath:t,ioPath:r,relPath:n,kind:(e=>{var t=Z.basename(e),r=es[t];if(!r)throw new eo("unsupported_file",`Unsupported entry file: ${t}`,{file:e,expected:Object.keys(es)});return r})(t)}}),function(e,t){return n.apply(this,arguments)}),ec=(a=D(function*(e,t){var r=yield(0,ee.z5)(e,t);if(!r)throw new eo("invalid_file","File must stay inside the project directory",{file:(0,ee.RI)(e,t)});return r}),function(e,t){return a.apply(this,arguments)}),eu=(e,t)=>{var r=(0,ee.Zj)(e.ast);if(t.entry){var i=r.find(e=>e.name===t.entry);if(i)return i;var n=r.filter(e=>e.alias===t.entry);if(1===n.length)return n[0];if(n.length>1)throw new eo("ambiguous_reference",`Alias is ambiguous: ${t.entry}`,{file:e.relPath,entry:t.entry,matches:n.map(e=>e.name)});throw new eo("entry_not_found",`Entry not found (by name or alias): ${t.entry}`,{file:e.relPath,entry:t.entry})}if(t.id){var a=r.find(e=>e.id===t.id);if(!a)throw new eo("entry_not_found",`Entry id not found: ${t.id}`,{file:e.relPath,id:t.id});return a}throw new eo("missing_target","Provide entry or id")},ef=e=>e.split(Z.sep).find(e=>/^subspace-\d+$/.test(e))||"unknown-subspace",ey=e=>{var t=e.split(Z.sep),r=t.findIndex(e=>/^subspace-\d+$/.test(e));if(r<0)throw new eo("invalid_file","Entry file must be inside subspaces/subspace-N",{file:e});return t.slice(0,r+1).join(Z.sep)},em=(s=D(function*(e){var t=Z.join(e,"subspaces");return(yield(0,G.readdir)(t,{withFileTypes:!0}).catch(()=>[])).filter(e=>e.isDirectory()&&/^subspace-\d+$/.test(e.name)).map(e=>Z.join(t,e.name)).sort()}),function(e){return s.apply(this,arguments)}),ev=(o=D(function*(e){var t=Object.keys(es),r=yield(0,G.readdir)(e,{withFileTypes:!0}).catch(()=>[]),i=new Set(r.filter(e=>e.isFile()).map(e=>e.name));return t.filter(e=>i.has(e)).map(t=>Z.join(e,t))}),function(e){return o.apply(this,arguments)}),eh=(l=D(function*(e){var t=yield em(e);return(yield Promise.all(t.map(ev))).flat()}),function(e){return l.apply(this,arguments)}),eb=(d=D(function*(e,t){if(t.file)return el(e,t.file);if(!t.id)throw new eo("missing_file","Provide file, or provide id for global lookup");for(var r of yield eh(e)){var i=yield ep(e,r);if((0,ee.Zj)(i.ast).find(e=>e.id===t.id))return r}throw new eo("entry_not_found",`Entry id not found: ${t.id}`,{id:t.id})}),function(e,t){return d.apply(this,arguments)}),ew=(p=D(function*(e,t){var r=yield eb(e,t),i=yield ep(e,r),n=eu(i,t),a=((e,t)=>{if(!e.object)throw new eo("fallback_recommended",`Entry ${e.name} in ${t} is not a top-level exported object literal. Edit this file directly for this one.`,{file:t,entry:e.name,check:"top-level export const object literal"});return e.object})(n,i.relPath);return{parsed:i,entry:n,object:a}}),function(e,t){return p.apply(this,arguments)}),ex=(e,t)=>J.callExpression(J.identifier("makeId"),t?[J.stringLiteral(e),J.stringLiteral(t)]:[J.stringLiteral(e)]),e_=e=>{var t=[];for(var r of e.split(".").filter(Boolean))for(var i=/([^\[\]]+)|\[(\d+)\]/g,n=void 0;n=i.exec(r);)n[1]&&t.push({key:n[1]}),n[2]&&t.push({index:Number(n[2])});if(0===t.length)throw new eo("invalid_path",`Invalid path: ${e}`,{path:e});return t},eg=e=>J.isTSAsExpression(e)||J.isTSSatisfiesExpression(e)||J.isTSNonNullExpression(e)||J.isParenthesizedExpression(e)?eg(e.expression):e,ej=(e,t)=>{var r=eg(e);if(!J.isObjectExpression(r))throw new eo("fallback_recommended",`Target path ${t} is not an object literal. Edit this file directly for this one.`,{path:t,expected:"object literal",actual:r.type});return r},eP=(e,t)=>{var r=eg(e);if(!J.isArrayExpression(r))throw new eo("fallback_recommended",`Target path ${t} is not an array literal. Edit this file directly for this one.`,{path:t,expected:"array literal",actual:r.type});return r},ek=e=>"array"==("index"in e?"array":"object")?J.arrayExpression([]):J.objectExpression([]),eE=(c=D(function*(e,t,r,i){for(var n=e_(t),a=e,s=0;s<n.length;s+=1){var o=n[s],l=s===n.length-1;if("key"in o){var d=ej(a,t);if(l)return void(0,ee.HJ)(d,o.key,(yield eL(r,i)));var p=n[s+1],c=(0,ee.bf)(d,o.key);c||(c=J.objectProperty((0,ee.zu)(o.key),ek(p)),d.properties.push(c)),a=c.value;continue}var u=eP(a,t);if(o.index<0||o.index>u.elements.length)throw new eo("invalid_path",`Array index out of range for ${t}`,{path:t,index:o.index});if(l){u.elements[o.index]=yield eL(r,i);return}u.elements[o.index]||(u.elements[o.index]=ek(n[s+1])),a=u.elements[o.index]}}),function(e,t,r,i){return c.apply(this,arguments)}),eS=(e,t)=>{for(var r=e_(t),i=e,n=0;n<r.length;n+=1){var a=r[n],s=n===r.length-1;if("key"in a){var o=ej(i,t);if(s)return void(0,ee.jc)(o,a.key);var l=(0,ee.bf)(o,a.key);if(!l)return;i=l.value;continue}var d=eP(i,t);if(a.index<0||a.index>=d.elements.length)return;if(s)return void d.elements.splice(a.index,1);var p=d.elements[a.index];if(!p)return;i=p}},e$=(e,t)=>{var r=(0,ee.bf)(e,"switches");if(!r)throw new eo("fallback_recommended","Entry has no switches array",{path:"switches"});var i=eP(r.value,"switches"),n="number"==typeof t?t:i.elements.findIndex(e=>J.isObjectExpression(e)&&(0,ee.JJ)(e,"id")===t);if(n<0||n>=i.elements.length)throw new eo("entry_not_found",`Switch not found: ${t}`,{switch:t});var a=i.elements[n];if(!J.isObjectExpression(a))throw new eo("fallback_recommended",`Switch ${String(t)} is not an object literal. Edit this file directly for this one.`,{switch:t});return a},eA=(e,t)=>{var r=t.replace(/\.[tj]sx?$/,""),i=Z.relative(Z.dirname(e),r).replace(/\\/g,"/");return i.startsWith(".")||(i=`./${i}`),i},eI=(e,t,r)=>{for(var i of e.ast.program.body)if(J.isImportDeclaration(i)&&i.source.value===t){var n=i.specifiers.find(e=>J.isImportDefaultSpecifier(e));if(n)return n.local.name}var a=(0,ee.R0)(e.ast,r),s=J.importDeclaration([J.importDefaultSpecifier(J.identifier(a))],J.stringLiteral(t));return(0,ee.Pb)(e.ast,s),a},eO=e=>{(0,ee.Kx)(e.parsed.ast,"type",e.typeImports),(0,ee.Kx)(e.parsed.ast,"value",e.valueImports)},eC=(u=D(function*(e,t,r){if(null==r||""===r)return t;if("number"==typeof r)return Z.join(e,"subspaces",`subspace-${r}`);var i=String(r);if(/^\d+$/.test(i))return Z.join(e,"subspaces",`subspace-${i}`);if(/^subspace-\d+$/.test(i))return Z.join(e,"subspaces",i);if(i.includes("/"))return el(e,i);var n,a=yield em(e),s=function*(){var t=Z.join(o,"index.ts"),r=yield(0,G.readFile)(t,"utf8").catch(()=>"");if(!r)return 0;var n=ed(r,(0,ee.RI)(e,t)),a=!1;if(ea(n,{ObjectProperty(e){"id"===(0,ee.Gp)(e.node.key)&&J.isStringLiteral(e.node.value)&&e.node.value.value===i&&(a=!0,e.stop())}}),a)return{v:o}};for(var o of a)if(n=yield*s(),0!==n&&n)return n.v;throw new eo("reference_not_found",`Subspace not found: ${i}`,{subspace:i})}),function(e,t,r){return u.apply(this,arguments)}),eN=(f=D(function*(e,t){var r,i,n=ey(e.parsed.absPath),a=yield eC(e.projectDir,n,t),s=Z.basename(a),o=/^subspace-(\d+)$/.exec(s);if(!o)throw new eo("invalid_subspace",`Not a subspace directory: ${s}`,{subspace:t});var l=Z.join(a,"index.ts"),d=yield(0,G.readFile)(l,"utf8").catch(()=>null);if(null==d)throw new eo("reference_not_found",`Subspace not found: ${t}`,{subspace:t});var p=(r=ed(d,(0,ee.RI)(e.projectDir,l)),ea(r,{ObjectProperty(e){if("id"===(0,ee.Gp)(e.node.key)){var t=e.node.value;J.isStringLiteral(t)&&t.value.startsWith("SUBSPACE_")&&(i=t.value,e.stop())}}}),i);if(!p)throw new eo("invalid_subspace",`Subspace index has no SUBSPACE_ id: ${s}/index.ts`,{subspace:t});return{id:p,index:Number(o[1]),label:s,indexPath:l,isCurrent:Z.resolve(a)===Z.resolve(n)}}),function(e,t){return f.apply(this,arguments)}),eR=(y=D(function*(e,t){var r=yield eN(e,t);if(r.isCurrent)return e.references.push({input:t,id:r.id,sameFile:!1,display:`'${r.id}'`,targetAbsPath:r.indexPath}),{resolved:r,expression:J.stringLiteral(r.id)};var i=eI(e.parsed,`../${r.label}`,`subspace${r.index}`);return e.references.push({input:t,id:r.id,sameFile:!1,display:`() => ${i}`,targetAbsPath:r.indexPath}),{resolved:r,expression:J.arrowFunctionExpression([],J.identifier(i))}}),function(e,t){return y.apply(this,arguments)}),eT=(m=D(function*(e,t,r,i){var n=ey(t),a=yield eC(e,n,i),s=yield ev(a),o=[];for(var l of s){var d=yield ep(e,l),p=d.kind;for(var c of(0,ee.Zj)(d.ast))if(c.name===r||c.id===r||c.alias===r){var u=Z.resolve(l)===Z.resolve(t),f=Z.basename(a);o.push({input:r,id:c.id,alias:c.alias,varName:c.name,namespace:p.namespace,display:`${p.namespace}.${c.name}`,targetAbsPath:l,sameFile:u,subspaceLabel:f,importSource:u?void 0:eA(t,l)})}}if(0===o.length)throw new eo("reference_not_found",`Reference not found: ${r}`,{ref:r,subspace:i??Z.basename(n)});if(o.length>1)throw new eo("ambiguous_reference",`Reference is ambiguous: ${r}`,{ref:r,matches:o.map(t=>({file:(0,ee.RI)(e,t.targetAbsPath),entry:t.varName,id:t.id,alias:t.alias}))});return o[0]}),function(e,t,r,i){return m.apply(this,arguments)}),eD=(v=D(function*(e,t,r){var i=yield eT(t.projectDir,t.parsed.absPath,e,r);if(i.sameFile)return t.references.push(i),J.identifier(i.varName);var n=ey(t.parsed.absPath),a=ey(i.targetAbsPath),s=i.subspaceLabel.replace(/[^a-zA-Z0-9_$]/g,""),o=n===a?i.namespace:`${s}${i.namespace[0].toUpperCase()}${i.namespace.slice(1)}`,l=((e,t,r,i)=>{for(var n of e.ast.program.body)if(J.isImportDeclaration(n)&&n.source.value===r){var a=n.specifiers.find(J.isImportNamespaceSpecifier);if(a)return a.local.name}var s=(0,ee.R0)(e.ast,i),o=J.importDeclaration([J.importNamespaceSpecifier(J.identifier(s))],J.stringLiteral(r));return(0,ee.Pb)(e.ast,o),s})(t.parsed,i.namespace,i.importSource,o);return i.importLocal=l,t.references.push({...i,display:`${l}.${i.varName}`,importLocal:l}),J.memberExpression(J.identifier(l),J.identifier(i.varName))}),function(e,t,r){return v.apply(this,arguments)}),eL=(h=D(function*(e,t){if((0,ee.u4)(e)&&"string"==typeof e.expr&&1===Object.keys(e).length){var r=e.expr;try{return(0,q.parseExpression)(r,{plugins:["typescript"]})}catch(e){throw new eo("invalid_expr",`Invalid TypeScript expression: ${e.message}`,{expr:r})}}if((0,ee.u4)(e)&&"string"==typeof e.link){t.valueImports.add("linkData");var i=yield eD(e.link,t,e.subspace);return J.callExpression(J.identifier("linkData"),[J.arrowFunctionExpression([],i)])}if((0,ee.u4)(e)&&"string"==typeof e.ref){var n=yield eD(e.ref,t,e.subspace);return J.arrowFunctionExpression([],n)}if(Array.isArray(e))return J.arrayExpression((yield Promise.all(e.map(e=>eL(e,t)))));if((0,ee.u4)(e)){var a,s=yield Promise.all(Object.entries(e).map((a=D(function*([e,r]){return J.objectProperty((0,ee.zu)(e),(yield eL(r,t)))}),function(e){return a.apply(this,arguments)})));return J.objectExpression(s)}return void 0===e?J.identifier("undefined"):J.valueToNode(e)}),function(e,t){return h.apply(this,arguments)}),eF=e=>e.map(e=>({input:e.input,id:e.id,alias:e.alias,resolved:e.importLocal?`${e.importLocal}.${e.varName}`:e.sameFile?e.varName:e.display,file:e.targetAbsPath})),eB=(b=D(function*(e){var t=en(e.ast,{comments:!0},e.source).code,r=yield(0,V.format)(e.absPath,t,ee.Hn);if(r.errors.length>0)throw new eo("format_failed",`oxfmt failed for ${e.relPath}`,{file:e.relPath,errors:r.errors});return r.code}),function(e){return b.apply(this,arguments)}),eK=(w=D(function*(e){var t=yield eB(e);return ed(t,e.relPath),yield(0,G.writeFile)(e.ioPath??(yield ec(e.projectDir,e.absPath)),t),t}),function(e){return w.apply(this,arguments)}),eM=(e,t)=>{if(e){var r=ef(e.absPath);return`${t?.name||"entry"} (${e.kind.kind}, ${r})`}},ez=(x=D(function*(e,t,r,i){var n={ts:new Date().toISOString(),tool:t,op:r?.op||(r?.set?"set":r?.unset?"unset":t),target:{file:r?.file,entry:r?.entry,id:r?.id},provenance:(0,et.S)()};try{var a=yield i(),s={...n,...a};return yield(0,et.a)(e,s).catch(e=>{s.auditError=e.message}),s}catch(i){var o=i instanceof eo?i:new eo("error",i.message||String(i),void 0,!0),l="fallback_recommended"===o.code?"fallback_recommended":"error",d={...n,outcome:l,input:r,error:{code:o.code,message:o.message,details:o.details},summary:"fallback_recommended"===l?`${t} could not safely edit this standard path; edit the file directly`:`${t} failed: ${o.message}`,isError:o.isMcpError||"error"===l};return yield(0,et.a)(e,d).catch(e=>{d.auditError=e.message}),d}}),function(e,t,r,i){return x.apply(this,arguments)}),eU=(_=D(function*(e,t){return ez(e,"edit_entry",t,D(function*(){var r=yield ew(e,t),i=r.parsed,n=r.entry,a=r.object,s={projectDir:e,parsed:i,references:[],typeImports:new Set,valueImports:new Set},o=null==t.switch?a:e$(a,t.switch);for(var l of Object.entries(t.set||{})){var d=T(l,2),p=d[0],c=d[1];yield eE(o,p,c,s)}for(var u of[...t.unset||[]].sort((e,t)=>{for(var r=e_(e).map(e=>"index"in e?e.index:-1),i=e_(t).map(e=>"index"in e?e.index:-1),n=0;n<Math.min(r.length,i.length);n+=1)if(r[n]!==i[n])return i[n]-r[n];return i.length-r.length}))eS(o,u);eO(s),yield eK(i);var f=yield(0,Q.H)(e,t.verify),y=eM(i,n);return{file:i.relPath,entry:n.name,id:n.id,change:{set:t.set||{},unset:t.unset||[],references:eF(s.references)},outcome:"compile:failed"===f.status?"verify_failed":"ok",verify:f,summary:`edited ${y} -> ${f.status}`}}))}),function(e,t){return _.apply(this,arguments)}),eq=e=>{switch(e){case"IfStatement":return"an if statement";case"ForStatement":case"ForOfStatement":case"ForInStatement":return"a for loop";case"WhileStatement":case"DoWhileStatement":return"a while loop";case"SwitchStatement":return"a switch statement";case"TryStatement":return"a try/catch block";case"FunctionDeclaration":return"a function declaration";case"ReturnStatement":return"a return before the final statement";default:return`a ${e}`}},eY=(e,t)=>{for(var r=0;r<e.length;r+=1){var i=e[r],n=r===e.length-1;if("ExpressionStatement"===i.type){var a=eJ(i.expression);if(a)return a;continue}if("VariableDeclaration"===i.type){for(var s of i.declarations)if("Identifier"!==s.id.type||!s.init)return"a destructuring or uninitialized declaration";continue}if(t&&n&&"ReturnStatement"===i.type){var o=i.argument?eJ(i.argument):null;if(o)return o;continue}return eq(i.type)}return null},eJ=e=>{if(e?.type!=="CallExpression"||e.arguments?.length||e.callee?.type!=="ArrowFunctionExpression"&&e.callee?.type!=="FunctionExpression")return null;var t=e.callee.body;return t?.type==="BlockStatement"?eY(t.body,!0):eJ(t)},eH=(g=D(function*(e,t){if(e?.expr)return eL(e,t);var r,i=(e=>{if(!(0,ee.u4)(e)||!(0,ee.u4)(e.action))return e;var t=e.action,r={handler:e.handler,name:t.name??t.__actionName,waitAsync:e.waitAsync};if(t.cast&&(r.cast=t.cast),Array.isArray(t.params))for(var i of(r.params={},t.params)){if(!(0,ee.u4)(i)||"string"!=typeof i.input)throw new eo("invalid_action",'Compiled action params entries require { input: "name", value }',{param:i});r.params[i.input]=i.value}if(Array.isArray(t.dataParams))for(var n of(r.dataParams={},t.dataParams)){var a=(0,ee.u4)(n?.input)?n.input.ref:n?.input;if("string"!=typeof a||!a)throw new eo("invalid_action","Compiled action dataParams entries require { input: dataRef, value }",{param:n});r.dataParams[a]=n.value}return r})(e),n=i?.name;if(!n)throw new eo("invalid_action","Action requires name");if("PROPERTY_BANK_EXPRESSION"===n&&(0,ee.u4)(i.params)){var a=i.params.expression;"string"==typeof a&&(e=>{try{t=(0,H.qg)(e,{ecmaVersion:2020})}catch(t){throw new eo("invalid_action",`PROPERTY_BANK_EXPRESSION does not parse: ${t.message}`,{expression:e})}var t,r=eY(t.body,!1);if(r)throw new eo("invalid_action",`PROPERTY_BANK_EXPRESSION cannot evaluate ${r}: the runtime folds the expression into a single expression (expression statements, simple const/let declarations, and a final return inside an IIFE only). Use ternaries instead of statements, or move branching logic to a DataCalculationScript.`,{expression:e})})(a)}var s="System",o=i.cast;if("system"===i.handler||null==i.handler)r=J.stringLiteral("system"),o||=`SystemAction${n.toLowerCase().split("_").filter(Boolean).map(e=>`${e[0].toUpperCase()}${e.slice(1)}`).join("")}`;else if((0,ee.u4)(i.handler)&&"string"==typeof i.handler.ref){var l=yield eT(t.projectDir,t.parsed.absPath,i.handler.ref,i.handler.subspace);if("bricks"!==l.namespace&&"generators"!==l.namespace)throw new eo("invalid_action",`Action handler must be a brick or generator, got ${l.namespace}: ${i.handler.ref}`,{handler:i.handler});s="bricks"===l.namespace?"Brick":"Generator";var d=yield eD(i.handler.ref,t,i.handler.subspace);r=J.arrowFunctionExpression([],d)}else if((0,ee.u4)(i.handler)&&null!=i.handler.subspace)r=(yield eR(t,i.handler.subspace)).expression,s="Subspace";else throw new eo("invalid_action","Unsupported action handler",{handler:i.handler});var p=[J.objectProperty(J.identifier("__actionName"),J.stringLiteral(n)),J.objectProperty(J.identifier("parent"),J.stringLiteral(s)),J.objectProperty(J.identifier("name"),J.stringLiteral(n))];if(i.params){var c,u=yield Promise.all(Object.entries(i.params).map((c=D(function*([e,r]){return J.objectExpression([J.objectProperty(J.identifier("input"),J.stringLiteral(e)),J.objectProperty(J.identifier("value"),(yield eL(r,t)))])}),function(e){return c.apply(this,arguments)})));p.push(J.objectProperty(J.identifier("params"),J.arrayExpression(u)))}if(i.dataParams){var f,y=yield Promise.all(Object.entries(i.dataParams).map((f=D(function*([e,r]){var i=yield eD(e,t);return J.objectExpression([J.objectProperty(J.identifier("input"),J.arrowFunctionExpression([],i)),J.objectProperty(J.identifier("value"),(yield eL(r,t)))])}),function(e){return f.apply(this,arguments)})));p.push(J.objectProperty(J.identifier("dataParams"),J.arrayExpression(y)))}var m=J.objectExpression(p);return o&&(t.typeImports.add(o),m=J.tsAsExpression(m,J.tsTypeReference(J.identifier(o)))),J.objectExpression([J.objectProperty(J.identifier("handler"),r),J.objectProperty(J.identifier("action"),m),J.objectProperty(J.identifier("waitAsync"),J.booleanLiteral(!!i.waitAsync))])}),function(e,t){return g.apply(this,arguments)}),eV=(e,t,r)=>{var i=(0,ee.bf)(e,t);return i||(i=J.objectProperty((0,ee.zu)(t),J.objectExpression([])),e.properties.push(i)),ej(i.value,r)},eG=(e,t,r)=>{var i=(0,ee.bf)(e,t);return i||(i=J.objectProperty((0,ee.zu)(t),J.arrayExpression([])),e.properties.push(i)),eP(i.value,r)},eW=(j=D(function*(e,t){return ez(e,"edit_events",t,D(function*(){var r=yield ew(e,t),i=r.parsed,n=r.entry,a=r.object,s={projectDir:e,parsed:i,references:[],typeImports:new Set,valueImports:new Set},o=null==t.switch?a:e$(a,t.switch),l=t.op;if("clear"===l||"remove"===l||"move"===l){var d=(0,ee.bf)(o,"events"),p=d?ej(d.value,"events"):null,c=p?(0,ee.bf)(p,t.event):null,u=c?eP(c.value,`events.${t.event}`):null;if("clear"===l)p&&(0,ee.jc)(p,t.event);else if("move"===l){if(null==t.index)throw new eo("invalid_index","move requires index");if(!u||t.index<0||t.index>=u.elements.length)throw new eo("invalid_index","move index out of range",{index:t.index});var f=Number(t.to);if(!Number.isFinite(f)||f<0||f>=u.elements.length)throw new eo("invalid_index","move requires valid to index",{to:t.to});var y=u.elements.splice(t.index,1),m=T(y,1)[0];u.elements.splice(f,0,m)}else{if(null==t.index)throw new eo("invalid_index","remove requires index");if(!u||t.index<0||t.index>=u.elements.length)throw new eo("invalid_index","remove index out of range",{index:t.index});u.elements.splice(t.index,1),0===u.elements.length&&p&&(0,ee.jc)(p,t.event)}}else if("add"===l||"replace"===l){var v=yield eH(t.action,s),h=eV(o,"events","events"),b=eG(h,t.event,`events.${t.event}`),w=t.index??b.elements.length;if("replace"===l){if(w<0||w>=b.elements.length)throw new eo("invalid_index","replace index out of range",{index:w});b.elements[w]=v}else{if(w<0||w>b.elements.length)throw new eo("invalid_index","add index out of range",{index:w});b.elements.splice(w,0,v)}}else throw new eo("invalid_op",`Unsupported edit_events op: ${l}`);eO(s),yield eK(i);var x=yield(0,Q.H)(e,t.verify);return{file:i.relPath,entry:n.name,id:n.id,change:{event:t.event,op:l,index:t.index,references:eF(s.references)},outcome:"compile:failed"===x.status?"verify_failed":"ok",verify:x,summary:`${l} event ${t.event} on ${eM(i,n)} -> ${x.status}`}}))}),function(e,t){return j.apply(this,arguments)}),eZ=e=>{if((0,ee.u4)(e)&&"string"==typeof e.expr)return e;if(!(0,ee.u4)(e))throw new eo("invalid_item","Canvas item requires frame { x, y, width, height }");for(var t of["x","y","width","height"])if("number"!=typeof e[t])throw new eo("invalid_item",`Canvas item frame requires numeric ${t}`,{frame:e});return e},eX=(P=D(function*(e,t,r){if(!e?.ref&&e?.subspace==null)throw new eo("invalid_item","Canvas item requires ref (brick) or subspace (embed)");var i,n=eZ(e.frame??r);if(e.ref){var a=yield eD(e.ref,t,e.subspace);i=J.arrowFunctionExpression([],a)}else{var s=yield eR(t,e.subspace),o=s.resolved,l=s.expression;if(o.isCurrent)throw new eo("invalid_item","A subspace cannot embed itself",{subspace:e.subspace});i=l}return J.objectExpression([J.objectProperty(J.identifier("item"),i),J.objectProperty(J.identifier("frame"),(yield eL(n,t))),...null==e.hidden?[]:[J.objectProperty(J.identifier("hidden"),J.booleanLiteral(!!e.hidden))]])}),function(e,t,r){return P.apply(this,arguments)}),eQ=(k=D(function*(e,t){return ez(e,"edit_canvas_items",t,D(function*(){var r=yield ew(e,t),i=r.parsed,n=r.entry,a=r.object;if("canvas"!==i.kind.kind)throw new eo("invalid_file","edit_canvas_items only edits canvases.ts entries",{file:i.relPath});var s={projectDir:e,parsed:i,references:[],typeImports:new Set,valueImports:new Set},o=eG(a,"items","items"),l=t.op;if("add"===l||"replace"===l){var d=yield eX(t.item,s,t.frame),p=t.index??o.elements.length;if("replace"===l){if(p<0||p>=o.elements.length)throw new eo("invalid_index","replace index out of range",{index:p});o.elements[p]=d}else{if(p<0||p>o.elements.length)throw new eo("invalid_index","add index out of range",{index:p});o.elements.splice(p,0,d)}}else if("remove"===l){if(null==t.index)throw new eo("invalid_index","remove requires index");if(t.index<0||t.index>=o.elements.length)throw new eo("invalid_index","remove index out of range",{index:t.index});o.elements.splice(t.index,1)}else if("move"===l){if(null==t.index)throw new eo("invalid_index","move requires index");if(!t.frame)throw new eo("invalid_item","move requires frame");if(t.index<0||t.index>=o.elements.length)throw new eo("invalid_index","move index out of range",{index:t.index});var c=o.elements[t.index];if(!J.isObjectExpression(c))throw new eo("fallback_recommended","Canvas item is not an object literal",{index:t.index});(0,ee.HJ)(c,"frame",(yield eL(eZ(t.frame),s)))}else throw new eo("invalid_op",`Unsupported edit_canvas_items op: ${l}`);eO(s),yield eK(i);var u=yield(0,Q.H)(e,t.verify);return{file:i.relPath,entry:n.name,id:n.id,change:{op:l,index:t.index,references:eF(s.references)},outcome:"compile:failed"===u.status?"verify_failed":"ok",verify:u,summary:`${l} canvas item on ${eM(i,n)} -> ${u.status}`}}))}),function(e,t){return k.apply(this,arguments)}),e0=(E=D(function*(e,t){var r=(e=>{switch(e?.__typename){case"SwitchCondInnerStateCurrentCanvas":return{type:"inner_state",key:"current_canvas",value:e.value,subspace:e.subspace};case"SwitchCondInnerStateOutlet":return{type:"inner_state",outlet:e.outlet,value:e.value};case"SwitchCondData":return{type:"property_bank",ref:e.data??e.ref,value:e.value,subspace:e.subspace};case"SwitchCondPropertyBankByItemKey":return{type:"property_bank_by_item_key",ref:e.data??e.ref,value:e.value,subspace:e.subspace};case"SwitchCondItemKeyMapping":return{type:"item_key_mapping",key:e.key,value:e.value};default:return e}})(e);if(r?.expr)return eL(r,t);if(r?.type==="inner_state"&&"current_canvas"===r.key){var i=yield eD(r.value,t,r.subspace);return J.objectExpression([J.objectProperty(J.identifier("__typename"),J.stringLiteral("SwitchCondInnerStateCurrentCanvas")),J.objectProperty(J.identifier("value"),J.arrowFunctionExpression([],i))])}if(r?.type==="inner_state"){var n=r.outlet||r.key;if(!n)throw new eo("invalid_switch","Switch inner-state outlet condition requires outlet or key");return J.objectExpression([J.objectProperty(J.identifier("__typename"),J.stringLiteral("SwitchCondInnerStateOutlet")),J.objectProperty(J.identifier("outlet"),J.stringLiteral(n)),J.objectProperty(J.identifier("value"),(yield eL(r.value,t)))])}if(r?.type==="item_key_mapping"){if(!r.key)throw new eo("invalid_switch","Switch item key mapping condition requires key");return J.objectExpression([J.objectProperty(J.identifier("__typename"),J.stringLiteral("SwitchCondItemKeyMapping")),J.objectProperty(J.identifier("key"),J.stringLiteral(r.key)),J.objectProperty(J.identifier("value"),(yield eL(r.value,t)))])}var a=r?.ref||r?.data||r?.key;if(!a)throw new eo("invalid_switch","Switch condition requires data ref");var s=yield eD(a,t,r.subspace);return J.objectExpression([J.objectProperty(J.identifier("__typename"),J.stringLiteral(r?.type==="property_bank_by_item_key"?"SwitchCondPropertyBankByItemKey":"SwitchCondData")),J.objectProperty(J.identifier("data"),J.arrowFunctionExpression([],s)),J.objectProperty(J.identifier("value"),(yield eL(r.value,t)))])}),function(e,t){return E.apply(this,arguments)}),e1=new Set(["id","title","description","conds","override","property","outlets","animation","events","disabled","break"]),e4=(S=D(function*(e,t){for(var r of Object.keys(e))if(!e1.has(r))throw new eo("invalid_switch",`Unknown switch field: ${r}`,{field:r,supported:Array.from(e1)});if(void 0!==e.events)throw new eo("invalid_switch","Set switch events with edit_events using its switch parameter");if(e.id&&!/^BRICK_STATE_GROUP_[0-9a-fA-F-]{36}$/.test(e.id))throw new eo("invalid_switch","Switch id must match BRICK_STATE_GROUP_<uuid>; omit id to generate one",{id:e.id});var i,n=e.id?J.stringLiteral(e.id):ex("switch");e.id||t.valueImports.add("makeId");var a=[J.objectProperty(J.identifier("id"),n)];for(var s of(null!=e.title&&a.push(J.objectProperty(J.identifier("title"),J.stringLiteral(e.title))),null!=e.description&&a.push(J.objectProperty(J.identifier("description"),J.stringLiteral(e.description))),e.conds&&a.push(J.objectProperty(J.identifier("conds"),J.arrayExpression((yield Promise.all(e.conds.map((i=D(function*(e){return J.objectExpression([J.objectProperty(J.identifier("method"),J.stringLiteral(e.method||"==")),J.objectProperty(J.identifier("cond"),(yield e0(e.cond||e,t)))])}),function(e){return i.apply(this,arguments)}))))))),e.override&&a.push(J.objectProperty(J.identifier("override"),(yield eL(e.override,t)))),["property","outlets","animation"]))null!=e[s]&&a.push(J.objectProperty(J.identifier(s),(yield eL(e[s],t))));return null!=e.disabled&&a.push(J.objectProperty(J.identifier("disabled"),J.booleanLiteral(!!e.disabled))),null!=e.break&&a.push(J.objectProperty(J.identifier("break"),J.booleanLiteral(!!e.break))),J.objectExpression(a)}),function(e,t){return S.apply(this,arguments)}),e5=($=D(function*(e,t){return ez(e,"edit_switches",t,D(function*(){var r=yield ew(e,t),i=r.parsed,n=r.entry,a=r.object,s={projectDir:e,parsed:i,references:[],typeImports:new Set,valueImports:new Set},o=eG(a,"switches","switches"),l=t.op,d=e=>"number"==typeof e?e:e?o.elements.findIndex(t=>J.isObjectExpression(t)&&(0,ee.JJ)(t,"id")===e):-1;if("add"===l||"replace"===l){var p=yield e4(t.switch||{},s),c=null==t.index?o.elements.length:d(t.index);if("replace"===l){if(c<0||c>=o.elements.length)throw new eo("invalid_index","replace index out of range",{index:c});o.elements[c]=p}else{if(c<0||c>o.elements.length)throw new eo("invalid_index","add requires a valid switch id or index",{index:t.index});o.elements.splice(c,0,p)}}else if("remove"===l){var u=d(t.index);if(u<0||u>=o.elements.length)throw new eo("invalid_index","remove requires a valid switch id or index",{index:t.index});o.elements.splice(u,1)}else if("move"===l){var f=d(t.index);if(f<0||f>=o.elements.length)throw new eo("invalid_index","move requires a valid switch id or index",{index:t.index});var y=Number(t.to);if(!Number.isFinite(y)||y<0||y>=o.elements.length)throw new eo("invalid_index","move requires valid to index",{to:t.to});var m=o.elements.splice(f,1),v=T(m,1)[0];o.elements.splice(y,0,v)}else throw new eo("invalid_op",`Unsupported edit_switches op: ${l}`);eO(s),yield eK(i);var h=yield(0,Q.H)(e,t.verify);return{file:i.relPath,entry:n.name,id:n.id,change:{op:l,index:t.index,references:eF(s.references)},outcome:"compile:failed"===h.status?"verify_failed":"ok",verify:h,summary:`${l} switch on ${eM(i,n)} -> ${h.status}`}}))}),function(e,t){return $.apply(this,arguments)}),e9=(A=D(function*(e,t,r,i){var n=[J.objectProperty(J.identifier("__typename"),J.stringLiteral(e.typename)),J.objectProperty(J.identifier("id"),r)];return t.alias&&n.push(J.objectProperty(J.identifier("alias"),J.stringLiteral(t.alias))),null!=t.title&&n.push(J.objectProperty(J.identifier("title"),J.stringLiteral(t.title))),null!=t.description&&n.push(J.objectProperty(J.identifier("description"),J.stringLiteral(t.description))),"brick"===e.kind||"generator"===e.kind?(n.push(J.objectProperty(J.identifier("templateKey"),J.stringLiteral(t.templateKey||""))),n.push(J.objectProperty(J.identifier("property"),J.objectExpression([]))),n.push(J.objectProperty(J.identifier("events"),J.objectExpression([]))),n.push(J.objectProperty(J.identifier("outlets"),J.objectExpression([]))),"brick"===e.kind&&n.push(J.objectProperty(J.identifier("animation"),J.objectExpression([]))),n.push(J.objectProperty(J.identifier("switches"),J.arrayExpression([])))):"canvas"===e.kind?(n.push(J.objectProperty(J.identifier("property"),J.objectExpression([]))),n.push(J.objectProperty(J.identifier("events"),J.objectExpression([]))),n.push(J.objectProperty(J.identifier("switches"),J.arrayExpression([]))),n.push(J.objectProperty(J.identifier("items"),J.arrayExpression([])))):"data"===e.kind?(n.push(J.objectProperty(J.identifier("type"),J.stringLiteral(t.dataType||"any"))),n.push(J.objectProperty(J.identifier("schema"),J.objectExpression([]))),n.push(J.objectProperty(J.identifier("events"),J.objectExpression([]))),n.push(J.objectProperty(J.identifier("value"),J.identifier("undefined")))):"animation"===e.kind&&(n.push(J.objectProperty(J.identifier("runType"),J.stringLiteral("once"))),n.push(J.objectProperty(J.identifier("property"),J.stringLiteral("opacity"))),n.push(J.objectProperty(J.identifier("config"),(yield eL({__type:"AnimationTimingConfig",toValue:1,duration:300,easing:"",delay:0,isInteraction:!0},i))))),J.objectExpression(n)}),function(e,t,r,i){return A.apply(this,arguments)}),e8=(I=D(function*(e,t,r){var i=Z.basename(t);for(var n of(yield eh(e)).filter(e=>Z.basename(e)===i)){var a=yield ep(e,n);if((0,ee.Zj)(a.ast).some(e=>e.alias===r))return!0}return!1}),function(e,t,r){return I.apply(this,arguments)}),e6=(O=D(function*(e,t){return ez(e,"new_entry",t,D(function*(){if(!t.file)throw new eo("missing_file","new_entry requires file");if(!t.type)throw new eo("missing_type","new_entry requires TypeScript type");var r=el(e,t.file),i=yield ep(e,r),n=new Set((0,ee.Zj)(i.ast).map(e=>e.name)),a="string"==typeof t.id?t.id:void 0,s=a||"string"!=typeof t.alias||!t.alias||(yield e8(e,r,t.alias))?void 0:t.alias,o=a?J.stringLiteral(a):ex(i.kind.idType,s),l=t.entry||((e,t,r,i)=>{var n,a=(e=>{if(!e)return null;var t=e.replace(/[^a-zA-Z0-9_$]/g,"");return t?(/^[0-9]/.test(t)&&(t=`_${t}`),t):null})(i)||(r?`${t.varPrefix}${n=r.replace(/^[A-Z_]+/g,""),`${n.substr(15,3)}${n.substr(20,1)}`}`:`${t.varPrefix}Entry`);if(!e.has(a))return a;for(var s=1;e.has(`${a}${s}`);)s+=1;return`${a}${s}`})(n,i.kind,a,t.alias||t.title),d={projectDir:e,parsed:i,references:[],typeImports:new Set([t.type]),valueImports:new Set};a||d.valueImports.add("makeId");var p=yield e9(i.kind,t,o,d),c=J.variableDeclarator(J.identifier(l),p);for(var u of(c.id.typeAnnotation=J.tsTypeAnnotation(J.tsTypeReference(J.identifier(t.type))),i.ast.program.body.push(J.exportNamedDeclaration(J.variableDeclaration("const",[c]))),Object.entries(t.set||{}))){var f=T(u,2),y=f[0],m=f[1];yield eE(p,y,m,d)}for(var v of t.events||[]){if(!(0,ee.u4)(v)||"string"!=typeof v.event||!v.event||!v.action)throw new eo("invalid_action","events entries require { event, action }",{event:v});var h=eV(p,"events","events");eG(h,v.event,`events.${v.event}`).elements.push((yield eH(v.action,d)))}eO(d),yield eK(i);var b=yield(0,Q.H)(e,t.verify);return{file:i.relPath,entry:l,id:a,idExpression:a??(s?`makeId('${i.kind.idType}', '${s}')`:`makeId('${i.kind.idType}')`),change:{set:t.set||{},events:t.events||[],references:eF(d.references)},outcome:"compile:failed"===b.status?"verify_failed":"ok",verify:b,summary:`created ${l} (${i.kind.kind}, ${ef(i.absPath)}) -> ${b.status}`}}))}),function(e,t){return O.apply(this,arguments)}),e7=(e,t)=>{var r;return J.isArrowFunctionExpression(e)&&0===e.params.length&&(r=e.body,!!r&&(J.isIdentifier(r)?r.name===t.varName:!!J.isMemberExpression(r)&&!!J.isIdentifier(r.object)&&!!J.isIdentifier(r.property)&&r.object.name===t.namespace&&r.property.name===t.varName))},e2=(e,t)=>J.isCallExpression(e)&&J.isIdentifier(e.callee,{name:"linkData"})&&e7(e.arguments[0],t),e3=(e,t)=>{if(!e)return!1;if(e7(e,t)||e2(e,t))return!0;var r=!1;return ea(J.file(J.program([J.expressionStatement(J.cloneNode(e,!0))])),{ArrowFunctionExpression(e){e7(e.node,t)&&(r=!0,e.stop())},CallExpression(e){e2(e.node,t)&&(r=!0,e.stop())}}),r},te=(e,t,r,i=[],n={})=>{if(J.isProgram(e))return void e.body.forEach((e,a)=>te(e,t,r,[...i,String(a)],n));if(J.isExportNamedDeclaration(e)&&e.declaration)return void te(e.declaration,t,r,i,n);if(J.isVariableDeclaration(e))return void e.declarations.forEach((e,a)=>te(e,t,r,[...i,String(a)],n));if(J.isVariableDeclarator(e)&&e.init)return void te(e.init,t,r,i,n);if(J.isObjectExpression(e)){for(var a=e.properties.length-1;a>=0;a-=1){var s=e.properties[a];if(J.isObjectProperty(s)){var o=(0,ee.Gp)(s.key)||`property-${a}`,l=[...i,o];if(e7(s.value,t)||e2(s.value,t)){i.includes("outlets")?(e.properties.splice(a,1),r.push({action:"drop_outlet",path:l.join(".")})):n.dataCalc&&("output"===o||"error"===o)?(s.value=J.nullLiteral(),r.push({action:"null_output",path:l.join(".")})):(s.value=J.identifier("undefined"),r.push({action:"null_link",path:l.join(".")}));continue}te(s.value,t,r,l,n)}}return}if(J.isArrayExpression(e))for(var d=i[i.length-1],p=i.includes("events")&&"events"!==d,c=n.dataCalc?["items","params","dataParams","conds","switches","inputs","outputs"]:["items","params","dataParams","conds","switches"],u=e.elements.length-1;u>=0;u-=1){var f=e.elements[u];if(f){var y=[...i,String(u)];if(e3(f,t)&&(c.includes(d)||p||e7(f,t))){e.elements.splice(u,1),r.push({action:p?"delete_event_handler":n.dataCalc&&("inputs"===d||"outputs"===d)?"remove_io_item":"remove_reference_item",path:y.join(".")});continue}te(f,t,r,y,n)}}},tt=(e,t)=>{var r=e.ast.program.body.indexOf(t.node);r>=0&&e.ast.program.body.splice(r,1)},tr=(C=D(function*(e,t,r){if("project"===r)return eh(e);var i=ey(t),n=yield ev(i),a=Z.join(i,"data-calc"),s=yield(0,G.readdir)(a,{withFileTypes:!0}).catch(()=>[]);return[...n,...s.filter(e=>e.isFile()&&e.name.endsWith(".ts")).map(e=>Z.join(a,e.name))]}),function(e,t,r){return C.apply(this,arguments)}),ti=(N=D(function*(e,t){return ez(e,"remove_entry",t,D(function*(){var r,i=yield ew(e,t),n=i.parsed,a=i.entry,s={varName:a.name,namespace:n.kind.namespace,id:a.id},o=yield tr(e,n.absPath,t.scope),l=[],d=yield Promise.all(o.map((r=D(function*(t){var r=yield(0,G.readFile)(t,"utf8");return{absPath:t,relPath:(0,ee.RI)(e,t),source:r,ast:ed(r,(0,ee.RI)(e,t)),kind:es[Z.basename(t)]||n.kind}}),function(e){return r.apply(this,arguments)}))),p=function*(e){var t,r,i,o,d;(o=(e.absPath===n.absPath?(t=a.name,r=J.cloneNode(e.ast,!0),i={...e,ast:r},tt(i,eu(i,{entry:t})),i):e).ast,d=[],ea(o,{ArrowFunctionExpression(e){e7(e.node,s)&&d.push({type:"ref",loc:e.node.loc?.start})},CallExpression(e){e2(e.node,s)&&d.push({type:"link",loc:e.node.loc?.start})}}),d).forEach(t=>l.push({file:e.relPath,...t}))};for(var c of d)yield*p(c);if(t.strict&&l.length>0)return{file:n.relPath,entry:a.name,id:a.id,outcome:"refused",touchedSites:l,verify:{status:"skipped",errors:[]},summary:`refused to remove ${eM(n,a)}; ${l.length} reference(s) found`};var u=function*(t){var r=[],i={dataCalc:t.absPath.split(Z.sep).includes("data-calc")};if(t.absPath===n.absPath&&(tt(t,eu(t,{entry:a.name})),r.push({action:"remove_entry",path:a.name})),te(t.ast.program,s,r,[],i),0===r.length)return 1;var o=yield eB(t);ed(o,t.relPath),yield(0,G.writeFile)((yield ec(e,t.absPath)),o),r.forEach(e=>l.push({file:t.relPath,...e}))};for(var f of d)if(yield*u(f))continue;var y=yield(0,Q.H)(e,t.verify);return{file:n.relPath,entry:a.name,id:a.id,outcome:"compile:failed"===y.status?"verify_failed":"ok",touchedSites:l,verify:y,summary:`removed ${eM(n,a)} with ${l.length} touched site(s) -> ${y.status}`}}))}),function(e,t){return N.apply(this,arguments)}),tn=(R=D(function*(e,t){return ez(e,"new_subspace",t,D(function*(){var r=Z.join(e,"root.ts"),i=(0,ee.RI)(e,r),n=yield(0,G.readFile)(r,"utf8").catch(()=>null);if(null==n)throw new eo("invalid_file","Project has no root.ts to wire the subspace into");var a={source:n,ast:ed(n,i),projectDir:e,absPath:r,relPath:i},s=a.ast.program.body.find(e=>J.isExportDefaultDeclaration(e));if(!s||!J.isArrayExpression(s.declaration))throw new eo("fallback_recommended","root.ts default export is not a subspace array literal; wire the new subspace manually",{file:i});var o=(yield em(e)).reduce((e,t)=>{var r=/^subspace-(\d+)$/.exec(Z.basename(t));return r?Math.max(e,Number(r[1])):e},-1)+1,l=`subspace-${o}`,d=Z.join(e,"subspaces",l),p=`SUBSPACE_${(0,W.randomUUID)()}`,c=`CANVAS_${(0,W.randomUUID)()}`,u=(({subspaceId:e,canvasId:t,title:r,description:i,layout:n,portal:a})=>{var s=[`width: ${n.width}`,`height: ${n.height}`,...n.resizeMode?[`resizeMode: '${n.resizeMode}'`]:[]];return{"data.ts":"import type { Data } from 'bricks-ctor'\n","bricks.ts":"import type { Brick } from 'bricks-ctor'\n","generators.ts":"import type { Generator } from 'bricks-ctor'\n","animations.ts":"import type { Animation } from 'bricks-ctor'\n","canvases.ts":`import type { Canvas } from 'bricks-ctor'
6
6
 
7
7
  export const cMain: Canvas = {
8
8
  __typename: 'Canvas',
@@ -41,4 +41,4 @@ export default {
41
41
  } as Subspace
42
42
 
43
43
  export { bricks, generators, canvases, data }
44
- `}})({subspaceId:p,canvasId:c,title:t.title,description:t.description??"",layout:{width:t.layout?.width??96,height:t.layout?.height??54,resizeMode:t.layout?.resizeMode},portal:t.portal});yield(0,U.mkdir)(Y.join(d,"data-calc"),{recursive:!0});var f=[];for(var y of Object.entries(u)){var m=T(y,2),v=m[0],h=m[1],b=Y.join(d,v),w=yield(0,z.format)(b,h,V.Hn);yield(0,U.writeFile)((yield ei(e,b)),w.errors.length>0?h:w.code),f.push((0,V.RI)(e,b))}var x=eg(a,`./subspaces/${l}`,`subspace${o}`);s.declaration.elements.push(K.identifier(x)),yield eC(a);var _=yield(0,H.H)(e,t.verify);return{subspace:l,id:p,index:o,files:f,change:{op:"new_subspace",rootImport:x},outcome:"compile:failed"===_.status?"verify_failed":"ok",verify:_,summary:`new_subspace ${l} (${t.title}) wired into root.ts -> ${_.status}`}}))}),function(e,t){return R.apply(this,arguments)}),e2=e=>({content:[{type:"text",text:JSON.stringify(e,null,2)}],isError:e.isError||void 0}),e6=J.bz().describe('Value grammar: JSON scalars/arrays/objects emit literals; { link: "dataIdOrAlias" } emits linkData(() => data.dX) for property/data-link values; { ref: "idOrAliasOrVar", subspace?: "subspace-1"|1|"SUBSPACE_id" } emits () => namespace.varName; { expr: "raw TypeScript expression" } is spliced verbatim.'),e3=J.Yj().describe("Dotted entry path to edit, for example title, property.url, outlets.response, animation.show, value, type, switches[0].property.text, or items[0].frame."),te=J.Yj().describe("Project-relative entry file path, for example subspaces/subspace-0/bricks.ts, generators.ts, canvases.ts, data.ts, or animations.ts."),tt=J.Yj().describe("Exported const name or entity alias to edit, for example bWelcomeText, gApiClient, cMain, or an alias like welcomeText."),tr=J.Yj().describe("Entry id fallback. When file is omitted, scans project subspaces for this id."),ti=J.zM().describe("Override compile verification for this call. Defaults to BRICKS_CTOR_MCP_EDIT_VERIFY, otherwise true."),tn={file:te.optional(),entry:tt.optional(),id:tr.optional(),verify:ti.optional()};function ta(e,t){var r,i,n,a,s,o,l;e.tool("edit_entry","Edit map-shaped facets on an existing bricks-ctor entry by source AST. Use set/unset with dotted paths and the shared value grammar.",{...tn,set:J.g1(e3,e6).describe("Map of dotted paths to values. Values use the shared grammar: JSON literals, { link }, { ref }, or { expr }.").optional(),unset:J.YO(e3).describe("Dotted paths to remove.").optional(),switch:J.KC([J.Yj(),J.ai()]).describe("Optional switch id or zero-based switch index; edits that switch object instead of the entry root.").optional()},(r=D(function*(e){return e2((yield eT(t,e)))}),function(e){return r.apply(this,arguments)})),e.tool("edit_events","Edit an event action array on an entry or switch. Adds/removes/replaces/moves/clears EventAction objects.",{...tn,event:J.Yj().describe("Camel-case source event key such as onPress, showStart, update, enter, or firstEnter."),op:J.k5(["add","remove","replace","move","clear"]).describe("Array operation. add inserts at index or appends; replace/remove require index; move reorders index to `to`; clear removes the event key."),index:J.ai().describe("Zero-based event action index. For add this is the insertion position.").optional(),to:J.ai().describe("Destination zero-based index for move.").optional(),action:e6.describe('For add/replace, the flattened form: { handler: "system"|{ref}|{subspace: "subspace-1"|1|"SUBSPACE_id"}, name: "ACTION_NAME", params?: { inputName: value }, dataParams?: { dataRef: value }, cast?: "TypeName", waitAsync?: boolean }. Cross-subspace {subspace} handlers emit a () => subspaceN getter; the emitting subspace itself stays a literal id. The compiled source form { handler, action: { name, params: [...], dataParams: [...] }, waitAsync } and { expr: "raw EventAction" } are also accepted.').optional(),switch:J.KC([J.Yj(),J.ai()]).describe("Optional switch id or zero-based switch index; edits that switch events object.").optional()},(i=D(function*(e){return e2((yield ez(t,e)))}),function(e){return i.apply(this,arguments)})),e.tool("edit_canvas_items","Edit a Canvas entry items array. Use add/remove/replace to place bricks or move to update an item frame.",{...tn,op:J.k5(["add","remove","replace","move"]).describe("Canvas item operation. add inserts/appends, replace/remove use index, move updates frame at index."),index:J.ai().describe("Zero-based canvas item index.").optional(),item:e6.describe('For add/replace: { ref: "brickIdOrAliasOrVar", subspace?: ..., frame: { x, y, width, height, ... }, hidden?: boolean } places a brick; { subspace: "subspace-1"|1|"SUBSPACE_id", frame: ... } without ref embeds that subspace (emits a () => subspaceN getter). Frames require numeric x/y/width/height.').optional(),frame:e6.describe("Replacement frame such as { x, y, width, height }. Required for move; for add/replace it is used when item.frame is omitted.").optional()},(n=D(function*(e){return e2((yield eY(t,e)))}),function(e){return n.apply(this,arguments)})),e.tool("edit_switches","Edit an entry switches array. Use edit_entry/edit_events with switch when changing switch facet bodies.",{...tn,op:J.k5(["add","remove","replace","move"]).describe("Switch array operation. add inserts/appends, replace/remove use index, move reorders to `to`."),index:J.KC([J.Yj(),J.ai()]).describe("Switch id or zero-based switch index. For add, this is optional insertion position.").optional(),to:J.ai().describe("Destination zero-based index for move.").optional(),switch:e6.describe('For add/replace: { id? (BRICK_STATE_GROUP_<uuid>; omit to auto-generate), title?, description?, conds?: [{ method: "=="|"!="|">"|"<"|">="|"<=", cond }], override?: { animation?, event?, property?, outlet? }, property?, outlets?, animation?, disabled?, break? }. Cond forms: { type: "inner_state", key: "current_canvas", value: canvasRef }, { type: "inner_state", outlet: "outletName", value }, { type: "property_bank", ref: dataRef, value }, { type: "property_bank_by_item_key", ref: dataRef, value }, { type: "item_key_mapping", key: "<item field path>", value }, a compiled { __typename: "SwitchCond..." } object, or { expr }. Set switch events with edit_events using its switch parameter.').optional()},(a=D(function*(e){return e2((yield eG(t,e)))}),function(e){return a.apply(this,arguments)})),e.tool("new_entry","Create a minimal standard-style exported entry skeleton in an entry file, then optionally apply set/events edits.",{file:te,entry:tt.describe("Optional exported const name. Defaults from alias/title/id.").optional(),templateKey:J.Yj().describe("Brick/generator templateKey such as BRICK_TEXT or GENERATOR_HTTP.").optional(),type:J.Yj().describe("TypeScript type imported from bricks-ctor, for example BrickText, GeneratorHTTP, Canvas, Data, or Animation."),alias:J.Yj().describe("Optional entry alias. Also influences default exported const name.").optional(),title:J.Yj().describe("Optional entry title.").optional(),description:J.Yj().describe("Optional entry description.").optional(),id:tr.describe("Optional explicit id. If omitted, the tool generates one with the file-kind prefix.").optional(),dataType:J.Yj().describe("For data.ts only: initial Data.type value. Defaults to any.").optional(),set:J.g1(e3,e6).describe("Optional initial dotted-path values applied after creating the skeleton. Values use JSON literals, { link }, { ref }, or { expr }.").optional(),events:J.YO(e6).describe("Optional initial event actions as objects with { event, action }.").optional(),verify:ti.optional()},(s=D(function*(e){return e2((yield eX(t,e)))}),function(e){return s.apply(this,arguments)})),e.tool("remove_entry","Remove an entry. By default cascades same-subspace references in standard entry object/array shapes; strict mode refuses when references exist.",{...tn,strict:J.zM().describe("When true, do not edit files; refuse and return reference sites if the entry is referenced.").optional(),scope:J.k5(["subspace","project"]).describe("Reference scan scope. subspace is default; project scans all subspaces.").optional()},(o=D(function*(e){return e2((yield e8(t,e)))}),function(e){return o.apply(this,arguments)})),e.tool("new_subspace","Scaffold a new subspaces/subspace-N directory (standard entry files + root canvas, fixed SUBSPACE_ id) and wire it into root.ts. Embed it afterwards with edit_canvas_items { subspace } or target it with edit_events { handler: { subspace } }.",{title:J.Yj().describe("Subspace title shown in the editor."),description:J.Yj().describe("Optional subspace description.").optional(),layout:J.Ik({width:J.ai(),height:J.ai(),resizeMode:J.k5(["cover","stretch"]).optional()}).describe("Subspace grid the embed frame scales; defaults to { width: 96, height: 54 }. Use a smaller grid plus resizeMode: 'stretch' for panel modules.").optional(),portal:J.k5(["top","left","bottom","right"]).describe("Dock the subspace to a viewport edge as an always-on overlay instead of a canvas-embeddable module.").optional(),verify:ti.optional()},(l=D(function*(e){return e2((yield e7(t,e)))}),function(e){return l.apply(this,arguments)}))}var ts={editEntry:eT,editEvents:ez,editCanvasItems:eY,editSwitches:eG,newEntry:eX,newSubspace:e7,removeEntry:e8,resolveReference:eS};i()}catch(e){i(e)}})}};
44
+ `}})({subspaceId:p,canvasId:c,title:t.title,description:t.description??"",layout:{width:t.layout?.width??96,height:t.layout?.height??54,resizeMode:t.layout?.resizeMode},portal:t.portal});yield(0,G.mkdir)(Z.join(d,"data-calc"),{recursive:!0});var f=[];for(var y of Object.entries(u)){var m=T(y,2),v=m[0],h=m[1],b=Z.join(d,v),w=yield(0,V.format)(b,h,ee.Hn);yield(0,G.writeFile)((yield ec(e,b)),w.errors.length>0?h:w.code),f.push((0,ee.RI)(e,b))}var x=eI(a,`./subspaces/${l}`,`subspace${o}`);s.declaration.elements.push(J.identifier(x)),yield eK(a);var _=yield(0,Q.H)(e,t.verify);return{subspace:l,id:p,index:o,files:f,change:{op:"new_subspace",rootImport:x},outcome:"compile:failed"===_.status?"verify_failed":"ok",verify:_,summary:`new_subspace ${l} (${t.title}) wired into root.ts -> ${_.status}`}}))}),function(e,t){return R.apply(this,arguments)}),ta=e=>({content:[{type:"text",text:JSON.stringify(e,null,2)}],isError:e.isError||void 0}),ts=X.bz().describe('Value grammar: JSON scalars/arrays/objects emit literals; { link: "dataIdOrAlias" } emits linkData(() => data.dX) for property/data-link values; { ref: "idOrAliasOrVar", subspace?: "subspace-1"|1|"SUBSPACE_id" } emits () => namespace.varName; { expr: "raw TypeScript expression" } is spliced verbatim.'),to=X.Yj().describe("Dotted entry path to edit, for example title, property.url, outlets.response, animation.show, value, type, switches[0].property.text, or items[0].frame."),tl=X.Yj().describe("Project-relative entry file path, for example subspaces/subspace-0/bricks.ts, generators.ts, canvases.ts, data.ts, or animations.ts."),td=X.Yj().describe("Exported const name or entity alias to edit, for example bWelcomeText, gApiClient, cMain, or an alias like welcomeText."),tp=X.Yj().describe("Entry id fallback. When file is omitted, scans project subspaces for this id."),tc=X.zM().describe("Override compile verification for this call. Defaults to BRICKS_CTOR_MCP_EDIT_VERIFY, otherwise true."),tu={file:tl.optional(),entry:td.optional(),id:tp.optional(),verify:tc.optional()};function tf(e,t){var r,i,n,a,s,o,l;e.tool("edit_entry","Edit map-shaped facets on an existing bricks-ctor entry by source AST. Use set/unset with dotted paths and the shared value grammar.",{...tu,set:X.g1(to,ts).describe("Map of dotted paths to values. Values use the shared grammar: JSON literals, { link }, { ref }, or { expr }.").optional(),unset:X.YO(to).describe("Dotted paths to remove.").optional(),switch:X.KC([X.Yj(),X.ai()]).describe("Optional switch id or zero-based switch index; edits that switch object instead of the entry root.").optional()},(r=D(function*(e){return ta((yield eU(t,e)))}),function(e){return r.apply(this,arguments)})),e.tool("edit_events","Edit an event action array on an entry or switch. Adds/removes/replaces/moves/clears EventAction objects.",{...tu,event:X.Yj().describe("Camel-case source event key such as onPress, showStart, update, enter, or firstEnter."),op:X.k5(["add","remove","replace","move","clear"]).describe("Array operation. add inserts at index or appends; replace/remove require index; move reorders index to `to`; clear removes the event key."),index:X.ai().describe("Zero-based event action index. For add this is the insertion position.").optional(),to:X.ai().describe("Destination zero-based index for move.").optional(),action:ts.describe('For add/replace, the flattened form: { handler: "system"|{ref}|{subspace: "subspace-1"|1|"SUBSPACE_id"}, name: "ACTION_NAME", params?: { inputName: value }, dataParams?: { dataRef: value }, cast?: "TypeName", waitAsync?: boolean }. Cross-subspace {subspace} handlers emit a () => subspaceN getter; the emitting subspace itself stays a literal id. The compiled source form { handler, action: { name, params: [...], dataParams: [...] }, waitAsync } and { expr: "raw EventAction" } are also accepted.').optional(),switch:X.KC([X.Yj(),X.ai()]).describe("Optional switch id or zero-based switch index; edits that switch events object.").optional()},(i=D(function*(e){return ta((yield eW(t,e)))}),function(e){return i.apply(this,arguments)})),e.tool("edit_canvas_items","Edit a Canvas entry items array. Use add/remove/replace to place bricks or move to update an item frame.",{...tu,op:X.k5(["add","remove","replace","move"]).describe("Canvas item operation. add inserts/appends, replace/remove use index, move updates frame at index."),index:X.ai().describe("Zero-based canvas item index.").optional(),item:ts.describe('For add/replace: { ref: "brickIdOrAliasOrVar", subspace?: ..., frame: { x, y, width, height, ... }, hidden?: boolean } places a brick; { subspace: "subspace-1"|1|"SUBSPACE_id", frame: ... } without ref embeds that subspace (emits a () => subspaceN getter). Frames require numeric x/y/width/height.').optional(),frame:ts.describe("Replacement frame such as { x, y, width, height }. Required for move; for add/replace it is used when item.frame is omitted.").optional()},(n=D(function*(e){return ta((yield eQ(t,e)))}),function(e){return n.apply(this,arguments)})),e.tool("edit_switches","Edit an entry switches array. Use edit_entry/edit_events with switch when changing switch facet bodies.",{...tu,op:X.k5(["add","remove","replace","move"]).describe("Switch array operation. add inserts/appends, replace/remove use index, move reorders to `to`."),index:X.KC([X.Yj(),X.ai()]).describe("Switch id or zero-based switch index. For add, this is optional insertion position.").optional(),to:X.ai().describe("Destination zero-based index for move.").optional(),switch:ts.describe('For add/replace: { id? (BRICK_STATE_GROUP_<uuid>; omit to auto-generate), title?, description?, conds?: [{ method: "=="|"!="|">"|"<"|">="|"<=", cond }], override?: { animation?, event?, property?, outlet? }, property?, outlets?, animation?, disabled?, break? }. Cond forms: { type: "inner_state", key: "current_canvas", value: canvasRef }, { type: "inner_state", outlet: "outletName", value }, { type: "property_bank", ref: dataRef, value }, { type: "property_bank_by_item_key", ref: dataRef, value }, { type: "item_key_mapping", key: "<item field path>", value }, a compiled { __typename: "SwitchCond..." } object, or { expr }. Set switch events with edit_events using its switch parameter.').optional()},(a=D(function*(e){return ta((yield e5(t,e)))}),function(e){return a.apply(this,arguments)})),e.tool("new_entry","Create a minimal standard-style exported entry skeleton in an entry file, then optionally apply set/events edits.",{file:tl,entry:td.describe("Optional exported const name. Defaults from alias/title/id.").optional(),templateKey:X.Yj().describe("Brick/generator templateKey such as BRICK_TEXT or GENERATOR_HTTP.").optional(),type:X.Yj().describe("TypeScript type imported from bricks-ctor, for example BrickText, GeneratorHTTP, Canvas, Data, or Animation."),alias:X.Yj().describe("Optional entry alias. Also influences default exported const name.").optional(),title:X.Yj().describe("Optional entry title.").optional(),description:X.Yj().describe("Optional entry description.").optional(),id:tp.describe("Optional explicit id. If omitted, the tool generates one with the file-kind prefix.").optional(),dataType:X.Yj().describe("For data.ts only: initial Data.type value. Defaults to any.").optional(),set:X.g1(to,ts).describe("Optional initial dotted-path values applied after creating the skeleton. Values use JSON literals, { link }, { ref }, or { expr }.").optional(),events:X.YO(ts).describe("Optional initial event actions as objects with { event, action }.").optional(),verify:tc.optional()},(s=D(function*(e){return ta((yield e6(t,e)))}),function(e){return s.apply(this,arguments)})),e.tool("remove_entry","Remove an entry. By default cascades same-subspace references in standard entry object/array shapes; strict mode refuses when references exist.",{...tu,strict:X.zM().describe("When true, do not edit files; refuse and return reference sites if the entry is referenced.").optional(),scope:X.k5(["subspace","project"]).describe("Reference scan scope. subspace is default; project scans all subspaces.").optional()},(o=D(function*(e){return ta((yield ti(t,e)))}),function(e){return o.apply(this,arguments)})),e.tool("new_subspace","Scaffold a new subspaces/subspace-N directory (standard entry files + root canvas, fixed SUBSPACE_ id) and wire it into root.ts. Embed it afterwards with edit_canvas_items { subspace } or target it with edit_events { handler: { subspace } }.",{title:X.Yj().describe("Subspace title shown in the editor."),description:X.Yj().describe("Optional subspace description.").optional(),layout:X.Ik({width:X.ai(),height:X.ai(),resizeMode:X.k5(["cover","stretch"]).optional()}).describe("Subspace grid the embed frame scales; defaults to { width: 96, height: 54 }. Use a smaller grid plus resizeMode: 'stretch' for panel modules.").optional(),portal:X.k5(["top","left","bottom","right"]).describe("Dock the subspace to a viewport edge as an always-on overlay instead of a canvas-embeddable module.").optional(),verify:tc.optional()},(l=D(function*(e){return ta((yield tn(t,e)))}),function(e){return l.apply(this,arguments)}))}var ty={editEntry:eU,editEvents:eW,editCanvasItems:eQ,editSwitches:e5,newEntry:e6,newSubspace:tn,removeEntry:ti,resolveReference:eT};i()}catch(e){i(e)}})}};
package/lib/3976.js CHANGED
@@ -2,13 +2,13 @@ export const __rspack_esm_id=3976;export const __rspack_esm_ids=[3976];export co
2
2
  # MCP entry-editing audit log
3
3
  ${l}
4
4
  `)}}),function(e){return i.apply(this,arguments)}),u=(a=n(function*(e,r){var t=s.join(e,".bricks");yield(0,o.mkdir)(t,{recursive:!0}),yield c(e),yield(0,o.appendFile)(s.join(t,"edits.jsonl"),`${JSON.stringify(r)}
5
- `)}),function(e,r){return a.apply(this,arguments)}),d=()=>({session:process.env.BRICKS_CTOR_SESSION_ID||process.env.CODEX_SESSION_ID,agent:process.env.BRICKS_CTOR_AGENT_ID||process.env.USER})},98009(e,r,t){t.d(r,{Gp:()=>b,HJ:()=>w,Hn:()=>u,JJ:()=>g,Kx:()=>I,LJ:()=>y,Pb:()=>k,R0:()=>x,RI:()=>p,Zj:()=>_,bf:()=>h,jc:()=>j,u4:()=>d,z5:()=>m,zu:()=>v});var i,a,n=t(68832),o=t(99436),s=t(58135),l=t(51455),c=t(76760),u={trailingComma:"all",tabWidth:2,semi:!1,singleQuote:!0,printWidth:100},d=e=>!!e&&"object"==typeof e&&!Array.isArray(e),p=(e,r)=>c.relative(e,r).replace(/\\/g,"/").replace(/^\.\/+/,""),f=(e,r)=>{var t=c.relative(e,r);return""!==t&&(t.startsWith(`..${c.sep}`)||".."===t||c.isAbsolute(t))?null:r},y=(i=o(function*(e,r){var t=n((yield Promise.all([(0,l.realpath)(e),(0,l.realpath)(r)])),2);return f(t[0],t[1])}),function(e,r){return i.apply(this,arguments)}),m=(a=o(function*(e,r){var t=yield(0,l.lstat)(r).catch(e=>{if(e?.code==="ENOENT")return null;throw e}),i=yield(0,l.realpath)(e);if(t){var a=yield(0,l.realpath)(r).catch(e=>{if(e?.code==="ENOENT")return null;throw e});return a?f(i,a):null}var n=yield(0,l.realpath)(c.dirname(r));return f(i,c.join(n,c.basename(r)))}),function(e,r){return a.apply(this,arguments)}),b=e=>s.isIdentifier(e)?e.name:s.isStringLiteral(e)||s.isNumericLiteral(e)?String(e.value):null,v=e=>/^[$A-Z_a-z][$\w]*$/.test(e)?s.identifier(e):s.stringLiteral(e),h=(e,r)=>e.properties.find(e=>!!s.isObjectProperty(e)&&b(e.key)===r),g=(e,r)=>{var t=h(e,r);if(t&&s.isStringLiteral(t.value))return t.value.value},_=e=>e.program.body.flatMap(e=>{if(!s.isExportNamedDeclaration(e)||!s.isVariableDeclaration(e.declaration))return[];var r=e.declaration;return r.declarations.flatMap(t=>{if(!s.isIdentifier(t.id))return[];var i,a=t.id.typeAnnotation;s.isTSTypeAnnotation(a)&&s.isTSTypeReference(a.typeAnnotation)&&s.isIdentifier(a.typeAnnotation.typeName)&&(i=a.typeAnnotation.typeName.name);var n=s.isObjectExpression(t.init)?t.init:void 0;return[{name:t.id.name,node:e,declaration:r,declarator:t,object:n,id:n?g(n,"id"):void 0,alias:n?g(n,"alias"):void 0,typeName:i}]})}),x=(e,r)=>{var t=new Set;for(var i of e.program.body){if(s.isImportDeclaration(i)){i.specifiers.forEach(e=>t.add(e.local.name));continue}s.isExportNamedDeclaration(i)&&s.isVariableDeclaration(i.declaration)&&i.declaration.declarations.forEach(e=>{s.isIdentifier(e.id)&&t.add(e.id.name)})}if(!t.has(r))return r;for(var a=1;t.has(`${r}${a}`);)a+=1;return`${r}${a}`},w=(e,r,t)=>{var i=h(e,r);if(i){i.value=t;return}e.properties.push(s.objectProperty(v(r),t))},j=(e,r)=>{var t=e.properties.findIndex(e=>!!s.isObjectProperty(e)&&b(e.key)===r);t>=0&&e.properties.splice(t,1)},k=(e,r)=>{var t=e.program.body,i=t.findLastIndex(e=>s.isImportDeclaration(e));t.splice(i+1,0,r)},I=(e,r,t)=>{var i=new Set(Array.from(t).filter(Boolean));if(0!==i.size){var a,n=function(e){return s.isImportDeclaration(e)&&"bricks-ctor"===e.source.value&&"type"===r==("type"===e.importKind)?(e.specifiers.forEach(e=>{if(s.isImportSpecifier(e)){var r=e.imported;s.isIdentifier(r)&&i.delete(r.name),s.isStringLiteral(r)&&i.delete(r.value)}}),i.forEach(r=>{e.specifiers.push(s.importSpecifier(s.identifier(r),s.identifier(r)))}),{v:void 0}):0};for(var o of e.program.body)if(0!==(a=n(o))&&a)return a.v;var l=s.importDeclaration(Array.from(i).map(e=>s.importSpecifier(s.identifier(e),s.identifier(e))),s.stringLiteral("bricks-ctor"));"type"===r&&(l.importKind="type"),k(e,l)}}},54452(e,r,t){t.d(r,{H:()=>u});var i,a,n=t(99436),o=t(75720),s=t(2985),l={FORCE_COLOR:"0",NO_COLOR:"1"},c=(i=n(function*(e){var r=yield(0,s.Re)(e);try{yield(0,o.sh)`bun compile`.cwd(e).env({...l,BRICKS_CTOR_ENABLE_EDITING_TOOLS:"0"}).text()}catch(e){var t=[e.stdout?.toString()??"",e.stderr?.toString()??"",e.message].filter(Boolean).join("\n").trim();return{status:"compile:failed",errors:t?[t]:["bun compile failed"]}}var i=yield(0,s.Re)(e);return{status:"compile:ok",errors:[],configChange:(0,s.m4)(r,i)}}),function(e){return i.apply(this,arguments)}),u=(a=n(function*(e,r){return"1"!==process.env.BRICKS_CTOR_MCP_DISABLE_COMPILE&&(void 0!==r?r:!["0","false","no","off"].includes((process.env.BRICKS_CTOR_MCP_EDIT_VERIFY??"true").toLowerCase()))?c(e):{status:"skipped",errors:[]}}),function(e,r){return a.apply(this,arguments)})},69899(e,r,t){t.a(e,async function(e,i){try{t.r(r),t.d(r,{__test__:()=>eD,register:()=>eC});var a,n,o,s,l,c,u,d,p,f,y,m,b,v,h,g,_,x,w,j,k,I,S=t(68832),$=t(99436),E=t(2235),O=t(46773),P=t(58135),C=t(11978),D=t(79491),A=t(51455),L=t(76760),R=t(84867),N=t(54452),T=t(98009),F=t(3540),J=e([D]);D=(J.then?(await J)():J)[0];var Y=E.default||E;class eA extends Error{constructor(e,r,t,i=!1){super(r),this.name="DataCalcEditingError",this.code=e,this.details=t,this.isMcpError=i}}var M=(e,r)=>{if(L.isAbsolute(r))throw new eA("invalid_file","File must be project-relative",{file:r});var t=L.resolve(e,r),i=L.relative(e,t);if(i.startsWith("..")||L.isAbsolute(i))throw new eA("invalid_file","File must stay inside the project directory",{file:r});return t},z=(e,r)=>{try{return(0,O.parse)(e,{sourceType:"module",plugins:["typescript","topLevelAwait"],errorRecovery:!1})}catch(e){throw new eA("parse_failed",`Cannot parse ${r} as TypeScript: ${e.message}. Edit this file directly.`,{file:r},!0)}},q=(a=$(function*(e,r){var t=yield(0,T.LJ)(e,r);if(!t)throw new eA("invalid_file","File must stay inside the project directory",{file:(0,T.RI)(e,r)});var i=yield(0,A.readFile)(t,"utf8"),a=(0,T.RI)(e,r);return{source:i,ast:z(i,a),projectDir:e,absPath:r,ioPath:t,relPath:a}}),function(e,r){return a.apply(this,arguments)}),H=(n=$(function*(e,r){var t=yield(0,T.z5)(e,r);if(!t)throw new eA("invalid_file","File must stay inside the project directory",{file:(0,T.RI)(e,r)});return t}),function(e,r){return n.apply(this,arguments)}),K=(e,r)=>{if(null==r||""===r)return L.join(e,"subspaces/subspace-0");if("number"==typeof r)return L.join(e,"subspaces",`subspace-${r}`);var t=String(r);if(/^\d+$/.test(t))return L.join(e,"subspaces",`subspace-${t}`);if(/^subspace-\d+$/.test(t))return L.join(e,"subspaces",t);if(t.includes("/"))return M(e,t);throw new eA("unsupported_subspace",`Unsupported subspace locator: ${t}`,{subspace:t})},B=e=>{var r=L.basename(e),t=/^data-calculation-(.+)\.ts$/.exec(r);if(!t)throw new eA("invalid_file","Expected data-calculation-{slug}.ts file",{file:e});return t[1]},W=(o=$(function*(e){return(yield(0,A.readdir)(e,{withFileTypes:!0}).catch(()=>[])).filter(e=>e.isFile()&&/^data-calculation-.+\.ts$/.test(e.name)&&!e.name.endsWith(".sandbox.ts")).map(r=>L.join(e,r.name)).sort()}),function(e){return o.apply(this,arguments)}),Z=e=>{var r=(0,T.bf)(e,"code")?.value;return r&&P.isExpression(r)?r:null},U=e=>{var r=P.isAwaitExpression(e)?e.argument:e;if(!P.isCallExpression(r))return null;var t=r.arguments[0];if(!P.isNewExpression(t)||!P.isIdentifier(t.callee)||"URL"!==t.callee.name)return null;var i=t.arguments[0];return P.isStringLiteral(i)?i.value:null},V=(s=$(function*(e,r){if(r.file)a=M(e,r.file);else{var t,i,a,n=K(e,r.subspace),o=L.join(n,"data-calc"),s=yield W(o),l=r.calc;if(!l)throw new eA("missing_calc","Provide file or subspace+calc");for(var c of s){if(l===B(c)){a=c;break}try{var u=yield q(e,c),d=(0,T.Zj)(u.ast).find(e=>"dataCalculation"===e.name);if(d&&(l===d.alias||l===d.id)){a=c;break}}catch{continue}}}if(!a)throw new eA("calc_not_found",`Data calc not found: ${r.calc}`,{calc:r.calc,subspace:r.subspace??"subspace-0"});var p=yield q(e,a),f=(e=>{var r=(0,T.Zj)(e.ast).find(e=>"dataCalculation"===e.name);if(!r||!r.object)throw new eA("fallback_recommended",`Data calc ${e.relPath} is not a single exported object literal. Edit this file directly for this one.`,{file:e.relPath,check:"export const dataCalculation object literal"});var t=(0,T.JJ)(r.object,"__typename");if("DataCalculationScript"!==t)throw new eA("fallback_recommended",`Data calc ${e.relPath} is ${t||"not DataCalculationScript"}. DataCalculationMap is out of scope; edit this file directly.`,{file:e.relPath,typename:t});return r.object})(p),y=B(a),m=(t=Z(f),(i=U(t))&&/^(\.\/)?[^/\\]+\.sandbox\.js$/.test(i)?i.replace(/^\.\//,""):`data-calculation-${y}.sandbox.js`);return{parsed:p,object:f,slug:y,sandboxFile:m}}),function(e,r){return s.apply(this,arguments)}),G=e=>{for(var r of e.program.body)if(P.isImportDeclaration(r)&&"node:fs/promises"===r.source.value){r.specifiers.some(e=>P.isImportSpecifier(e)&&P.isIdentifier(e.imported)&&"readFile"===e.imported.name)||r.specifiers.push(P.importSpecifier(P.identifier("readFile"),P.identifier("readFile")));return}(0,T.Pb)(e,P.importDeclaration([P.importSpecifier(P.identifier("readFile"),P.identifier("readFile"))],P.stringLiteral("node:fs/promises")))},Q=e=>{(0,T.Kx)(e.parsed.ast,"type",e.typeImports),(0,T.Kx)(e.parsed.ast,"value",e.valueImports)},X=(l=$(function*(e,r,t,i){var a,n=(e=>{var r=e.split(L.sep),t=r.findIndex(e=>/^subspace-\d+$/.test(e));if(t<0)throw new eA("invalid_file","Data-calc file must be inside subspaces/subspace-N/data-calc",{file:e});return r.slice(0,t+1).join(L.sep)})(r),o=null==i?n:K(e,i),s=L.join(o,"data.ts"),l=yield q(e,s),c=(0,T.Zj)(l.ast).filter(e=>e.name===t||e.id===t||e.alias===t);if(0===c.length)throw new eA("reference_not_found",`Data reference not found: ${t}`,{ref:t,subspace:L.basename(o)});if(c.length>1)throw new eA("ambiguous_reference",`Data reference is ambiguous: ${t}`,{ref:t,matches:c.map(r=>({file:(0,T.RI)(e,s),entry:r.name,id:r.id,alias:r.alias}))});var u=L.resolve(s)===L.resolve(r);return{input:t,id:c[0].id,alias:c[0].alias,varName:c[0].name,sameFile:u,importSource:u?void 0:((a=L.relative(L.dirname(r),s).replace(/\\/g,"/")).startsWith(".")||(a=`./${a}`),a.replace(/\.(ts|tsx|js|jsx)$/,""))}}),function(e,r,t,i){return l.apply(this,arguments)}),ee=(c=$(function*(e,r){if((0,T.u4)(e)&&"string"==typeof e.expr)return(0,O.parseExpression)(e.expr,{plugins:["typescript"]});var t="string"==typeof e?e:(0,T.u4)(e)?e.ref:void 0;if("string"!=typeof t||!t)throw new eA("invalid_ref","Data getter requires a data ref string");var i=yield X(r.projectDir,r.parsed.absPath,t,(0,T.u4)(e)?e.subspace:void 0),a=i.sameFile?"data":((e,r,t)=>{for(var i of e.ast.program.body)if(P.isImportDeclaration(i)&&i.source.value===r){var a=i.specifiers.find(e=>P.isImportNamespaceSpecifier(e));if(a)return a.local.name}var n=(0,T.R0)(e.ast,t),o=P.importDeclaration([P.importNamespaceSpecifier(P.identifier(n))],P.stringLiteral(r));return(0,T.Pb)(e.ast,o),n})(r.parsed,i.importSource||"../data","data");return r.references.push(i),P.arrowFunctionExpression([],P.memberExpression(P.identifier(a),P.identifier(i.varName)))}),function(e,r){return c.apply(this,arguments)}),er=(u=$(function*(e,r){return null==e?P.nullLiteral():ee(e,r)}),function(e,r){return u.apply(this,arguments)}),et=(d=$(function*(e,r){var t=L.join(e,"subspaces");for(var i of yield(0,A.readdir)(t,{withFileTypes:!0}).catch(()=>[]))if(i.isDirectory()&&/^subspace-\d+$/.test(i.name))for(var a of yield W(L.join(t,i.name,"data-calc")))try{var n=yield q(e,a),o=(0,T.Zj)(n.ast).find(e=>"dataCalculation"===e.name);if(o?.alias===r)return!0}catch{continue}return!1}),function(e,r){return d.apply(this,arguments)}),ei=new Set(["__typename","id","code","enableAsync","inputs","output","outputs","error"]),ea=e=>P.awaitExpression(P.callExpression(P.identifier("readFile"),[P.newExpression(P.identifier("URL"),[P.stringLiteral(`./${e}`),P.memberExpression(P.metaProperty(P.identifier("import"),P.identifier("meta")),P.identifier("url"))]),P.stringLiteral("utf8")])),en=(p=$(function*(e,r){if((0,T.u4)(e)){if("string"==typeof e.expr)return(0,O.parseExpression)(e.expr,{plugins:["typescript"]});if("string"==typeof e.ref)return ee(e,r)}if(null===e)return P.nullLiteral();if(void 0===e)return P.identifier("undefined");if("string"==typeof e)return P.stringLiteral(e);if("number"==typeof e)return P.numericLiteral(e);if("boolean"==typeof e)return P.booleanLiteral(e);if(Array.isArray(e))return P.arrayExpression((yield Promise.all(e.map(e=>en(e,r)))));if((0,T.u4)(e)){var t,i=yield Promise.all(Object.entries(e).map((t=$(function*([e,t]){return P.objectProperty((0,T.zu)(e),(yield en(t,r)))}),function(e){return t.apply(this,arguments)})));return P.objectExpression(i)}throw new eA("invalid_value",`Unsupported value: ${String(e)}`)}),function(e,r){return p.apply(this,arguments)}),eo=(f=$(function*(e){var r=Y(e.ast,{comments:!0},e.source).code,t=yield(0,D.format)(e.absPath,r,T.Hn);if(t.errors.length>0)throw new eA("format_failed",`oxfmt failed for ${e.relPath}`,{file:e.relPath,errors:t.errors});return t.code}),function(e){return f.apply(this,arguments)}),es=(y=$(function*(e){var r=yield eo(e);return z(r,e.relPath),yield(0,A.writeFile)(e.ioPath??(yield H(e.projectDir,e.absPath)),r),r}),function(e){return y.apply(this,arguments)}),el=e=>({content:[{type:"text",text:JSON.stringify(e,null,2)}],isError:e.isError||void 0}),ec=e=>e.map(e=>({input:e.input,id:e.id,alias:e.alias,entry:e.varName})),eu=(m=$(function*(e,r,t,i){var a=new Date().toISOString(),n=(0,F.S)();try{var o=yield i();return yield(0,F.a)(e,{ts:a,tool:r,input:t,provenance:n,outcome:o.outcome,summary:o.summary,result:o}),o}catch(i){var s=i instanceof eA,l=s&&"fallback_recommended"===i.code?"fallback_recommended":"error",c={outcome:l,isError:"error"===l,error:{code:s?i.code:"unexpected_error",message:i.message,details:s?i.details:void 0},summary:`${r} failed: ${i.message}`};return yield(0,F.a)(e,{ts:a,tool:r,input:t,provenance:n,outcome:c.outcome,summary:c.summary,error:c.error}).catch(()=>void 0),c}}),function(e,r,t,i){return m.apply(this,arguments)}),ed=(b=$(function*(e,r){var t=new Set((yield W(e)).map(B));if(r){var i=r.trim().replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"calc";if(!t.has(i))return i;for(var a=1;t.has(`${i}-${a}`);)a+=1;return`${i}-${a}`}for(var n=0;t.has(String(n));)n+=1;return String(n)}),function(e,r){return b.apply(this,arguments)}),ep=e=>{try{return(0,C.qg)(e,{sourceType:"module",ecmaVersion:2020}),!0}catch{return!1}},ef=e=>{var r=e??"";if((e=>{try{var r=(0,C.qg)(e,{sourceType:"module",ecmaVersion:2020}).body[0];return r?.type==="ExportNamedDeclaration"&&r.declaration?.type==="FunctionDeclaration"&&r.declaration.id?.name==="main"}catch{return!1}})(r))return r.endsWith("\n")?r:`${r}
5
+ `)}),function(e,r){return a.apply(this,arguments)}),d=()=>({session:process.env.BRICKS_CTOR_SESSION_ID||process.env.CODEX_SESSION_ID,agent:process.env.BRICKS_CTOR_AGENT_ID||process.env.USER})},98009(e,r,t){t.d(r,{Gp:()=>b,HJ:()=>w,Hn:()=>u,JJ:()=>g,Kx:()=>I,LJ:()=>y,Pb:()=>k,R0:()=>x,RI:()=>p,Zj:()=>_,bf:()=>h,jc:()=>j,u4:()=>d,z5:()=>m,zu:()=>v});var i,a,n=t(68832),o=t(99436),s=t(58135),l=t(51455),c=t(76760),u={trailingComma:"all",tabWidth:2,semi:!1,singleQuote:!0,printWidth:100},d=e=>!!e&&"object"==typeof e&&!Array.isArray(e),p=(e,r)=>c.relative(e,r).replace(/\\/g,"/").replace(/^\.\/+/,""),f=(e,r)=>{var t=c.relative(e,r);return""!==t&&(t.startsWith(`..${c.sep}`)||".."===t||c.isAbsolute(t))?null:r},y=(i=o(function*(e,r){var t=n((yield Promise.all([(0,l.realpath)(e),(0,l.realpath)(r)])),2);return f(t[0],t[1])}),function(e,r){return i.apply(this,arguments)}),m=(a=o(function*(e,r){var t=yield(0,l.lstat)(r).catch(e=>{if(e?.code==="ENOENT")return null;throw e}),i=yield(0,l.realpath)(e);if(t){var a=yield(0,l.realpath)(r).catch(e=>{if(e?.code==="ENOENT")return null;throw e});return a?f(i,a):null}var n=yield(0,l.realpath)(c.dirname(r));return f(i,c.join(n,c.basename(r)))}),function(e,r){return a.apply(this,arguments)}),b=e=>s.isIdentifier(e)?e.name:s.isStringLiteral(e)||s.isNumericLiteral(e)?String(e.value):null,v=e=>/^[$A-Z_a-z][$\w]*$/.test(e)?s.identifier(e):s.stringLiteral(e),h=(e,r)=>e.properties.find(e=>!!s.isObjectProperty(e)&&b(e.key)===r),g=(e,r)=>{var t=h(e,r);if(t&&s.isStringLiteral(t.value))return t.value.value},_=e=>e.program.body.flatMap(e=>{if(!s.isExportNamedDeclaration(e)||!s.isVariableDeclaration(e.declaration))return[];var r=e.declaration;return r.declarations.flatMap(t=>{if(!s.isIdentifier(t.id))return[];var i,a=t.id.typeAnnotation;s.isTSTypeAnnotation(a)&&s.isTSTypeReference(a.typeAnnotation)&&s.isIdentifier(a.typeAnnotation.typeName)&&(i=a.typeAnnotation.typeName.name);var n=s.isObjectExpression(t.init)?t.init:void 0;return[{name:t.id.name,node:e,declaration:r,declarator:t,object:n,id:n?g(n,"id"):void 0,alias:n?g(n,"alias"):void 0,typeName:i}]})}),x=(e,r)=>{var t=new Set;for(var i of e.program.body){if(s.isImportDeclaration(i)){i.specifiers.forEach(e=>t.add(e.local.name));continue}s.isExportNamedDeclaration(i)&&s.isVariableDeclaration(i.declaration)&&i.declaration.declarations.forEach(e=>{s.isIdentifier(e.id)&&t.add(e.id.name)})}if(!t.has(r))return r;for(var a=1;t.has(`${r}${a}`);)a+=1;return`${r}${a}`},w=(e,r,t)=>{var i=h(e,r);if(i){i.value=t;return}e.properties.push(s.objectProperty(v(r),t))},j=(e,r)=>{var t=e.properties.findIndex(e=>!!s.isObjectProperty(e)&&b(e.key)===r);t>=0&&e.properties.splice(t,1)},k=(e,r)=>{var t=e.program.body,i=t.findLastIndex(e=>s.isImportDeclaration(e));t.splice(i+1,0,r)},I=(e,r,t)=>{var i=new Set(Array.from(t).filter(Boolean));if(0!==i.size){var a,n=function(e){return s.isImportDeclaration(e)&&"bricks-ctor"===e.source.value&&"type"===r==("type"===e.importKind)?(e.specifiers.forEach(e=>{if(s.isImportSpecifier(e)){var r=e.imported;s.isIdentifier(r)&&i.delete(r.name),s.isStringLiteral(r)&&i.delete(r.value)}}),i.forEach(r=>{e.specifiers.push(s.importSpecifier(s.identifier(r),s.identifier(r)))}),{v:void 0}):0};for(var o of e.program.body)if(0!==(a=n(o))&&a)return a.v;var l=s.importDeclaration(Array.from(i).map(e=>s.importSpecifier(s.identifier(e),s.identifier(e))),s.stringLiteral("bricks-ctor"));"type"===r&&(l.importKind="type"),k(e,l)}}},54452(e,r,t){t.d(r,{H:()=>u});var i,a,n=t(99436),o=t(75720),s=t(2985),l={FORCE_COLOR:"0",NO_COLOR:"1"},c=(i=n(function*(e){var r=yield(0,s.Re)(e);try{yield(0,o.sh)`bun compile`.cwd(e).env({...l,BRICKS_CTOR_ENABLE_EDITING_TOOLS:"0"}).text()}catch(e){var t=[e.stdout?.toString()??"",e.stderr?.toString()??"",e.message].filter(Boolean).join("\n").trim();return{status:"compile:failed",errors:t?[t]:["bun compile failed"]}}var i=yield(0,s.Re)(e);return{status:"compile:ok",errors:[],configChange:(0,s.m4)(r,i)}}),function(e){return i.apply(this,arguments)}),u=(a=n(function*(e,r){return"1"!==process.env.BRICKS_CTOR_MCP_DISABLE_COMPILE&&(void 0!==r?r:!["0","false","no","off"].includes((process.env.BRICKS_CTOR_MCP_EDIT_VERIFY??"true").toLowerCase()))?c(e):{status:"skipped",errors:[]}}),function(e,r){return a.apply(this,arguments)})},69899(e,r,t){t.a(e,async function(e,i){try{t.r(r),t.d(r,{__test__:()=>eY,register:()=>eJ});var a,n,o,s,l,c,u,d,p,f,y,m,b,v,h,g,_,x,w,j,k,I,S=t(68832),$=t(99436),E=t(44668),O=t(5018),P=t(63315),C=t(30409),D=t(40906),A=t(59410),R=t(2235),L=t(46773),N=t(58135),T=t(11978),F=t(79491),J=t(51455),Y=t(76760),M=t(84867),z=t(54452),q=t(98009),B=t(3540),H=e([F]);function K(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(K=function(){return!!e})()}F=(H.then?(await H)():H)[0];var W=R.default||R,Z=function(e){function r(e,t,i,a=!1){var n,o,s;return O(this,r),o=r,s=[t],o=C(o),(n=P(this,K()?Reflect.construct(o,s||[],C(this).constructor):o.apply(this,s))).name="DataCalcEditingError",n.code=e,n.details=i,n.isMcpError=a,n}return D(r,e),E(r)}(A(Error)),U=(e,r)=>{if(Y.isAbsolute(r))throw new Z("invalid_file","File must be project-relative",{file:r});var t=Y.resolve(e,r),i=Y.relative(e,t);if(i.startsWith("..")||Y.isAbsolute(i))throw new Z("invalid_file","File must stay inside the project directory",{file:r});return t},V=(e,r)=>{try{return(0,L.parse)(e,{sourceType:"module",plugins:["typescript","topLevelAwait"],errorRecovery:!1})}catch(e){throw new Z("parse_failed",`Cannot parse ${r} as TypeScript: ${e.message}. Edit this file directly.`,{file:r},!0)}},G=(a=$(function*(e,r){var t=yield(0,q.LJ)(e,r);if(!t)throw new Z("invalid_file","File must stay inside the project directory",{file:(0,q.RI)(e,r)});var i=yield(0,J.readFile)(t,"utf8"),a=(0,q.RI)(e,r);return{source:i,ast:V(i,a),projectDir:e,absPath:r,ioPath:t,relPath:a}}),function(e,r){return a.apply(this,arguments)}),Q=(n=$(function*(e,r){var t=yield(0,q.z5)(e,r);if(!t)throw new Z("invalid_file","File must stay inside the project directory",{file:(0,q.RI)(e,r)});return t}),function(e,r){return n.apply(this,arguments)}),X=(e,r)=>{if(null==r||""===r)return Y.join(e,"subspaces/subspace-0");if("number"==typeof r)return Y.join(e,"subspaces",`subspace-${r}`);var t=String(r);if(/^\d+$/.test(t))return Y.join(e,"subspaces",`subspace-${t}`);if(/^subspace-\d+$/.test(t))return Y.join(e,"subspaces",t);if(t.includes("/"))return U(e,t);throw new Z("unsupported_subspace",`Unsupported subspace locator: ${t}`,{subspace:t})},ee=e=>{var r=Y.basename(e),t=/^data-calculation-(.+)\.ts$/.exec(r);if(!t)throw new Z("invalid_file","Expected data-calculation-{slug}.ts file",{file:e});return t[1]},er=(o=$(function*(e){return(yield(0,J.readdir)(e,{withFileTypes:!0}).catch(()=>[])).filter(e=>e.isFile()&&/^data-calculation-.+\.ts$/.test(e.name)&&!e.name.endsWith(".sandbox.ts")).map(r=>Y.join(e,r.name)).sort()}),function(e){return o.apply(this,arguments)}),et=e=>{var r=(0,q.bf)(e,"code")?.value;return r&&N.isExpression(r)?r:null},ei=e=>{var r=N.isAwaitExpression(e)?e.argument:e;if(!N.isCallExpression(r))return null;var t=r.arguments[0];if(!N.isNewExpression(t)||!N.isIdentifier(t.callee)||"URL"!==t.callee.name)return null;var i=t.arguments[0];return N.isStringLiteral(i)?i.value:null},ea=(s=$(function*(e,r){if(r.file)a=U(e,r.file);else{var t,i,a,n=X(e,r.subspace),o=Y.join(n,"data-calc"),s=yield er(o),l=r.calc;if(!l)throw new Z("missing_calc","Provide file or subspace+calc");for(var c of s){if(l===ee(c)){a=c;break}try{var u=yield G(e,c),d=(0,q.Zj)(u.ast).find(e=>"dataCalculation"===e.name);if(d&&(l===d.alias||l===d.id)){a=c;break}}catch{continue}}}if(!a)throw new Z("calc_not_found",`Data calc not found: ${r.calc}`,{calc:r.calc,subspace:r.subspace??"subspace-0"});var p=yield G(e,a),f=(e=>{var r=(0,q.Zj)(e.ast).find(e=>"dataCalculation"===e.name);if(!r||!r.object)throw new Z("fallback_recommended",`Data calc ${e.relPath} is not a single exported object literal. Edit this file directly for this one.`,{file:e.relPath,check:"export const dataCalculation object literal"});var t=(0,q.JJ)(r.object,"__typename");if("DataCalculationScript"!==t)throw new Z("fallback_recommended",`Data calc ${e.relPath} is ${t||"not DataCalculationScript"}. DataCalculationMap is out of scope; edit this file directly.`,{file:e.relPath,typename:t});return r.object})(p),y=ee(a),m=(t=et(f),(i=ei(t))&&/^(\.\/)?[^/\\]+\.sandbox\.js$/.test(i)?i.replace(/^\.\//,""):`data-calculation-${y}.sandbox.js`);return{parsed:p,object:f,slug:y,sandboxFile:m}}),function(e,r){return s.apply(this,arguments)}),en=e=>{for(var r of e.program.body)if(N.isImportDeclaration(r)&&"node:fs/promises"===r.source.value){r.specifiers.some(e=>N.isImportSpecifier(e)&&N.isIdentifier(e.imported)&&"readFile"===e.imported.name)||r.specifiers.push(N.importSpecifier(N.identifier("readFile"),N.identifier("readFile")));return}(0,q.Pb)(e,N.importDeclaration([N.importSpecifier(N.identifier("readFile"),N.identifier("readFile"))],N.stringLiteral("node:fs/promises")))},eo=e=>{(0,q.Kx)(e.parsed.ast,"type",e.typeImports),(0,q.Kx)(e.parsed.ast,"value",e.valueImports)},es=(l=$(function*(e,r,t,i){var a,n=(e=>{var r=e.split(Y.sep),t=r.findIndex(e=>/^subspace-\d+$/.test(e));if(t<0)throw new Z("invalid_file","Data-calc file must be inside subspaces/subspace-N/data-calc",{file:e});return r.slice(0,t+1).join(Y.sep)})(r),o=null==i?n:X(e,i),s=Y.join(o,"data.ts"),l=yield G(e,s),c=(0,q.Zj)(l.ast).filter(e=>e.name===t||e.id===t||e.alias===t);if(0===c.length)throw new Z("reference_not_found",`Data reference not found: ${t}`,{ref:t,subspace:Y.basename(o)});if(c.length>1)throw new Z("ambiguous_reference",`Data reference is ambiguous: ${t}`,{ref:t,matches:c.map(r=>({file:(0,q.RI)(e,s),entry:r.name,id:r.id,alias:r.alias}))});var u=Y.resolve(s)===Y.resolve(r);return{input:t,id:c[0].id,alias:c[0].alias,varName:c[0].name,sameFile:u,importSource:u?void 0:((a=Y.relative(Y.dirname(r),s).replace(/\\/g,"/")).startsWith(".")||(a=`./${a}`),a.replace(/\.(ts|tsx|js|jsx)$/,""))}}),function(e,r,t,i){return l.apply(this,arguments)}),el=(c=$(function*(e,r){if((0,q.u4)(e)&&"string"==typeof e.expr)return(0,L.parseExpression)(e.expr,{plugins:["typescript"]});var t="string"==typeof e?e:(0,q.u4)(e)?e.ref:void 0;if("string"!=typeof t||!t)throw new Z("invalid_ref","Data getter requires a data ref string");var i=yield es(r.projectDir,r.parsed.absPath,t,(0,q.u4)(e)?e.subspace:void 0),a=i.sameFile?"data":((e,r,t)=>{for(var i of e.ast.program.body)if(N.isImportDeclaration(i)&&i.source.value===r){var a=i.specifiers.find(e=>N.isImportNamespaceSpecifier(e));if(a)return a.local.name}var n=(0,q.R0)(e.ast,t),o=N.importDeclaration([N.importNamespaceSpecifier(N.identifier(n))],N.stringLiteral(r));return(0,q.Pb)(e.ast,o),n})(r.parsed,i.importSource||"../data","data");return r.references.push(i),N.arrowFunctionExpression([],N.memberExpression(N.identifier(a),N.identifier(i.varName)))}),function(e,r){return c.apply(this,arguments)}),ec=(u=$(function*(e,r){return null==e?N.nullLiteral():el(e,r)}),function(e,r){return u.apply(this,arguments)}),eu=(d=$(function*(e,r){var t=Y.join(e,"subspaces");for(var i of yield(0,J.readdir)(t,{withFileTypes:!0}).catch(()=>[]))if(i.isDirectory()&&/^subspace-\d+$/.test(i.name))for(var a of yield er(Y.join(t,i.name,"data-calc")))try{var n=yield G(e,a),o=(0,q.Zj)(n.ast).find(e=>"dataCalculation"===e.name);if(o?.alias===r)return!0}catch{continue}return!1}),function(e,r){return d.apply(this,arguments)}),ed=new Set(["__typename","id","code","enableAsync","inputs","output","outputs","error"]),ep=e=>N.awaitExpression(N.callExpression(N.identifier("readFile"),[N.newExpression(N.identifier("URL"),[N.stringLiteral(`./${e}`),N.memberExpression(N.metaProperty(N.identifier("import"),N.identifier("meta")),N.identifier("url"))]),N.stringLiteral("utf8")])),ef=(p=$(function*(e,r){if((0,q.u4)(e)){if("string"==typeof e.expr)return(0,L.parseExpression)(e.expr,{plugins:["typescript"]});if("string"==typeof e.ref)return el(e,r)}if(null===e)return N.nullLiteral();if(void 0===e)return N.identifier("undefined");if("string"==typeof e)return N.stringLiteral(e);if("number"==typeof e)return N.numericLiteral(e);if("boolean"==typeof e)return N.booleanLiteral(e);if(Array.isArray(e))return N.arrayExpression((yield Promise.all(e.map(e=>ef(e,r)))));if((0,q.u4)(e)){var t,i=yield Promise.all(Object.entries(e).map((t=$(function*([e,t]){return N.objectProperty((0,q.zu)(e),(yield ef(t,r)))}),function(e){return t.apply(this,arguments)})));return N.objectExpression(i)}throw new Z("invalid_value",`Unsupported value: ${String(e)}`)}),function(e,r){return p.apply(this,arguments)}),ey=(f=$(function*(e){var r=W(e.ast,{comments:!0},e.source).code,t=yield(0,F.format)(e.absPath,r,q.Hn);if(t.errors.length>0)throw new Z("format_failed",`oxfmt failed for ${e.relPath}`,{file:e.relPath,errors:t.errors});return t.code}),function(e){return f.apply(this,arguments)}),em=(y=$(function*(e){var r=yield ey(e);return V(r,e.relPath),yield(0,J.writeFile)(e.ioPath??(yield Q(e.projectDir,e.absPath)),r),r}),function(e){return y.apply(this,arguments)}),eb=e=>({content:[{type:"text",text:JSON.stringify(e,null,2)}],isError:e.isError||void 0}),ev=e=>e.map(e=>({input:e.input,id:e.id,alias:e.alias,entry:e.varName})),eh=(m=$(function*(e,r,t,i){var a=new Date().toISOString(),n=(0,B.S)();try{var o=yield i();return yield(0,B.a)(e,{ts:a,tool:r,input:t,provenance:n,outcome:o.outcome,summary:o.summary,result:o}),o}catch(i){var s=i instanceof Z,l=s&&"fallback_recommended"===i.code?"fallback_recommended":"error",c={outcome:l,isError:"error"===l,error:{code:s?i.code:"unexpected_error",message:i.message,details:s?i.details:void 0},summary:`${r} failed: ${i.message}`};return yield(0,B.a)(e,{ts:a,tool:r,input:t,provenance:n,outcome:c.outcome,summary:c.summary,error:c.error}).catch(()=>void 0),c}}),function(e,r,t,i){return m.apply(this,arguments)}),eg=(b=$(function*(e,r){var t=new Set((yield er(e)).map(ee));if(r){var i=r.trim().replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"calc";if(!t.has(i))return i;for(var a=1;t.has(`${i}-${a}`);)a+=1;return`${i}-${a}`}for(var n=0;t.has(String(n));)n+=1;return String(n)}),function(e,r){return b.apply(this,arguments)}),e_=e=>{try{return(0,T.qg)(e,{sourceType:"module",ecmaVersion:2020}),!0}catch{return!1}},ex=e=>{var r=e??"";if((e=>{try{var r=(0,T.qg)(e,{sourceType:"module",ecmaVersion:2020}).body[0];return r?.type==="ExportNamedDeclaration"&&r.declaration?.type==="FunctionDeclaration"&&r.declaration.id?.name==="main"}catch{return!1}})(r))return r.endsWith("\n")?r:`${r}
6
6
  `;var t=r.trim();if(!t)return"export function main() {\n}\n";for(var i of["","async "]){var a=`export ${i}function main() {
7
7
  ${t}
8
8
  }
9
- `;if(ep(a))return a}throw new eA("invalid_code",/export\s+(async\s+)?function\s+main\s*\(/.test(r)?"Sandbox code does not parse as a module (note: top-level await requires export async function main)":"Sandbox code does not parse as a script body (statements with top-level return)")},ey=(v=$(function*(e,r){yield(0,A.mkdir)(r,{recursive:!0});var t=yield W(r),i=t.map((e,r)=>{var t=B(e);return`import { dataCalculation as dataCalculation${r} } from './data-calculation-${t}'`}).join("\n"),a=t.map((e,r)=>`dataCalculation${r}`).join(",\n "),n=`${i}
9
+ `;if(e_(a))return a}throw new Z("invalid_code",/export\s+(async\s+)?function\s+main\s*\(/.test(r)?"Sandbox code does not parse as a module (note: top-level await requires export async function main)":"Sandbox code does not parse as a script body (statements with top-level return)")},ew=(v=$(function*(e,r){yield(0,J.mkdir)(r,{recursive:!0});var t=yield er(r),i=t.map((e,r)=>{var t=ee(e);return`import { dataCalculation as dataCalculation${r} } from './data-calculation-${t}'`}).join("\n"),a=t.map((e,r)=>`dataCalculation${r}`).join(",\n "),n=`${i}
10
10
 
11
11
  export const dataCalculation = [
12
12
  ${a}
13
13
  ]
14
- `,o=L.join(r,"index.ts"),s={projectDir:e,absPath:o,relPath:(0,T.RI)(e,o),source:n,ast:z(n,(0,T.RI)(e,o))};return yield es(s),(0,T.RI)(e,o)}),function(e,r){return v.apply(this,arguments)}),em=(h=$(function*(e,r){var t=L.join(r,"index.ts"),i=(0,T.RI)(e,t),a=yield(0,A.readFile)(t,"utf8").catch(e=>{if(e?.code==="ENOENT")return null;throw e});if(null==a)return{warning:`${i} not found; wire the data-calc import manually`};var n=yield q(e,t),o=(e=>{for(var r of e.program.body)if(P.isExportDefaultDeclaration(r)){var t=r.declaration;if(P.isObjectExpression(t))return t;if(P.isTSAsExpression(t)&&P.isObjectExpression(t.expression))return t.expression}return null})(n.ast);if(!o)return{warning:`${i} has no default-export object; wire the data-calc import manually`};var s=(0,T.bf)(o,"dataCalculation");if(s&&P.isIdentifier(s.value))return null;if(s&&!(P.isArrayExpression(s.value)&&0===s.value.elements.length))return{warning:`${i} has a non-empty dataCalculation value; wire the data-calc import manually`};if(n.ast.program.body.some(e=>P.isImportDeclaration(e)&&("./data-calc"===e.source.value||"./data-calc/index"===e.source.value))||(0,T.Pb)(n.ast,P.importDeclaration([P.importSpecifier(P.identifier("dataCalculation"),P.identifier("dataCalculation"))],P.stringLiteral("./data-calc"))),s)s.value=P.identifier("dataCalculation"),P.isIdentifier(s.key)&&(s.shorthand=!0);else{var l=P.objectProperty(P.identifier("dataCalculation"),P.identifier("dataCalculation"));l.shorthand=!0,o.properties.push(l)}return yield es(n),{touched:n.relPath}}),function(e,r){return h.apply(this,arguments)}),eb=(g=$(function*(e,r,t){if(!r.key)throw new eA("missing_key",`${e} item requires key`);if(null==r.data)throw new eA("missing_data",`${e} item requires data`);var i=[P.objectProperty(P.identifier("key"),P.stringLiteral(r.key)),P.objectProperty(P.identifier("data"),(yield ee(r.data,t)))];return"inputs"===e&&i.push(P.objectProperty(P.identifier("trigger"),P.booleanLiteral(!1!==r.trigger))),P.objectExpression(i)}),function(e,r,t){return g.apply(this,arguments)}),ev=(_=$(function*(e,r,t){if("inputs"===e){var i=new Set;for(var a of r){if(i.has(a?.key))throw new eA("duplicate_key",`Input key already exists: ${a.key}`,{key:a.key});i.add(a?.key)}}var n=[];for(var o of r)n.push((yield eb(e,o,t)));return P.arrayExpression(n)}),function(e,r,t){return _.apply(this,arguments)}),eh=(e,r)=>{if("number"==typeof r.index)return r.index;if(!r.key)return -1;var t=e.elements.map((e,r)=>({element:e,index:r})).filter(({element:e})=>P.isObjectExpression(e)&&(0,T.JJ)(e,"key")===r.key);if(t.length>1)throw new eA("ambiguous_key",`IO key is ambiguous: ${r.key}`,{key:r.key,count:t.length});return t[0]?.index??-1},eg=(x=$(function*(e,r,t,i){let a;t.typeImports.add("DataCalculationScript"),t.valueImports.add("makeId"),G(t.parsed.ast);var n=[P.objectProperty(P.identifier("__typename"),P.stringLiteral("DataCalculationScript")),P.objectProperty(P.identifier("id"),e.id?P.stringLiteral(e.id):(a="property_bank_calc",P.callExpression(P.identifier("makeId"),i?[P.stringLiteral(a),P.stringLiteral(i)]:[P.stringLiteral(a)])))];return e.alias&&n.push(P.objectProperty(P.identifier("alias"),P.stringLiteral(e.alias))),null!=e.title&&n.push(P.objectProperty(P.identifier("title"),P.stringLiteral(e.title))),null!=e.description&&n.push(P.objectProperty(P.identifier("description"),P.stringLiteral(e.description))),null!=e.note&&n.push(P.objectProperty(P.identifier("note"),P.stringLiteral(e.note))),n.push(P.objectProperty(P.identifier("code"),ea(r))),n.push(P.objectProperty(P.identifier("enableAsync"),P.booleanLiteral(!!e.enableAsync))),null!=e.triggerMode&&n.push(P.objectProperty(P.identifier("triggerMode"),P.stringLiteral(e.triggerMode))),n.push(P.objectProperty(P.identifier("inputs"),(yield ev("inputs",e.inputs||[],t)))),n.push(P.objectProperty(P.identifier("output"),(yield er(e.output,t)))),n.push(P.objectProperty(P.identifier("outputs"),(yield ev("outputs",e.outputs||[],t)))),n.push(P.objectProperty(P.identifier("error"),(yield er(e.error,t)))),P.objectExpression(n)}),function(e,r,t,i){return x.apply(this,arguments)}),e_=(w=$(function*(e,r){return eu(e,"new_data_calc",r,$(function*(){var t,i,a,n=K(e,r.subspace),o=L.join(n,"data-calc");yield(0,A.mkdir)(o,{recursive:!0});var s=yield ed(o,r.alias),l=`data-calculation-${s}.sandbox.js`,c=L.join(o,`data-calculation-${s}.ts`),u=L.join(o,l),d=(t=(0,T.RI)(e,c),i="export const dataCalculation = {}\n",(a=z(i,t)).program.body=[],{ast:a,source:i,projectDir:e,absPath:c,relPath:t}),p={projectDir:e,parsed:d,references:[],typeImports:new Set,valueImports:new Set},f=r.id||"string"!=typeof r.alias||!r.alias||(yield et(e,r.alias))?void 0:r.alias,y=yield eg(r,l,p,f),m=P.variableDeclarator(P.identifier("dataCalculation"),y);m.id.typeAnnotation=P.tsTypeAnnotation(P.tsTypeReference(P.identifier("DataCalculationScript"))),d.ast.program.body.push(P.exportNamedDeclaration(P.variableDeclaration("const",[m]))),Q(p),yield(0,A.writeFile)((yield H(e,u)),ef(r.code)),yield es(d);var b=[{file:(0,T.RI)(e,c),action:"create_calc"},{file:(0,T.RI)(e,u),action:"write_sandbox"}];b.push({file:yield ey(e,o),action:"regenerate_index"});var v=yield em(e,n);v?.touched&&b.push({file:v.touched,action:"wire_subspace_index"});var h=yield(0,N.H)(e,r.verify);return{file:(0,T.RI)(e,c),subspace:L.basename(n),calc:s,idExpression:r.id??(f?`makeId('property_bank_calc', '${f}')`:"makeId('property_bank_calc')"),outcome:"compile:failed"===h.status?"verify_failed":"ok",touchedSites:b,...v?.warning?{warnings:[v.warning]}:{},verify:h,references:ec(p.references),summary:`created data calc ${s} in ${L.basename(n)} -> ${h.status}`}}))}),function(e,r){return w.apply(this,arguments)}),ex=(j=$(function*(e,r){return eu(e,"edit_data_calc",r,$(function*(){var t=yield V(e,r),i={projectDir:e,parsed:t.parsed,references:[],typeImports:new Set,valueImports:new Set},a=[];for(var n of Object.entries(r.set||{})){var o=S(n,2),s=o[0],l=o[1];if("output"===s||"error"===s)(0,T.HJ)(t.object,s,(yield er(l,i)));else if("inputs"===s||"outputs"===s){if(!Array.isArray(l))throw new eA("invalid_value",`${s} must be an array of IO items`);(0,T.HJ)(t.object,s,(yield ev(s,l,i)))}else if("code"===s)throw new eA("invalid_field","Set code via the dedicated code parameter so it stays normalized to the sandbox file");else(0,T.HJ)(t.object,s,(yield en(l,i)))}for(var c of r.unset||[]){if(ei.has(c))throw new eA("invalid_field",`Cannot unset required field: ${c}`,{field:c});(0,T.jc)(t.object,c)}if(null!=r.code){var u=Z(t.object);if(!(e=>{if(!e)return!1;if(P.isStringLiteral(e)||P.isTemplateLiteral(e))return!0;var r=U(e);return null!=r&&/^(\.\/)?[^/\\]+\.sandbox\.js$/.test(r)})(u))throw new eA("fallback_recommended",`Data calc ${t.parsed.relPath} has an unsupported code expression. Edit this file directly for this one.`,{file:t.parsed.relPath,field:"code"});var d=t.sandboxFile,p=L.join(L.dirname(t.parsed.absPath),d);yield(0,A.writeFile)((yield H(e,p)),ef(r.code)),G(t.parsed.ast),(0,T.HJ)(t.object,"code",ea(d)),a.push({file:(0,T.RI)(e,p),action:"write_sandbox"})}Q(i),yield es(t.parsed),a.unshift({file:t.parsed.relPath,action:"edit_calc"});var f=yield(0,N.H)(e,r.verify);return{file:t.parsed.relPath,calc:t.slug,outcome:"compile:failed"===f.status?"verify_failed":"ok",touchedSites:a,verify:f,references:ec(i.references),summary:`edited data calc ${t.slug} -> ${f.status}`}}))}),function(e,r){return j.apply(this,arguments)}),ew=(k=$(function*(e,r){return eu(e,"edit_data_calc_io",r,$(function*(){var t=yield V(e,r),i={projectDir:e,parsed:t.parsed,references:[],typeImports:new Set,valueImports:new Set},a=r.field,n=((e,r)=>{var t=(0,T.bf)(e,r);if(t){if(!P.isArrayExpression(t.value))throw new eA("fallback_recommended",`${r} is not an array. Edit this file directly.`);return t.value}var i=P.arrayExpression([]);return e.properties.push(P.objectProperty(P.identifier(r),i)),i})(t.object,a),o=r.op;if("clear"===o)n.elements=[];else if("remove"===o){var s=eh(n,r);if(s<0||s>=n.elements.length)throw new eA("invalid_index","remove requires a valid key or index");n.elements.splice(s,1)}else if("add"===o||"replace"===o){var l="replace"===o?eh(n,r):r.index;if("replace"===o&&(l<0||l>=n.elements.length))throw new eA("invalid_index","replace requires a valid key or index");if("add"===o&&"number"==typeof l&&(l<0||l>n.elements.length))throw new eA("invalid_index","add index out of range",{index:l});"inputs"===a&&((e,r,t)=>{if(e.elements.some((e,i)=>i!==t&&P.isObjectExpression(e)&&(0,T.JJ)(e,"key")===r))throw new eA("duplicate_key",`Input key already exists: ${r}`,{key:r})})(n,r.key,"replace"===o?l:void 0);var c=yield eb(a,r,i);"replace"===o?n.elements[l]=c:n.elements.splice("number"==typeof l?l:n.elements.length,0,c)}else throw new eA("invalid_op",`Unsupported edit_data_calc_io op: ${o}`);Q(i),yield es(t.parsed);var u=yield(0,N.H)(e,r.verify);return{file:t.parsed.relPath,calc:t.slug,outcome:"compile:failed"===u.status?"verify_failed":"ok",change:{field:a,op:o,key:r.key,index:r.index},verify:u,references:ec(i.references),summary:`${o} ${a} on data calc ${t.slug} -> ${u.status}`}}))}),function(e,r){return k.apply(this,arguments)}),ej=(I=$(function*(e,r){return eu(e,"remove_data_calc",r,$(function*(){var t=yield V(e,r),i=L.dirname(t.parsed.absPath),a=L.join(i,t.sandboxFile);yield(0,A.rm)(t.parsed.absPath,{force:!0}),yield(0,A.rm)(a,{force:!0});var n=yield ey(e,i),o=yield(0,N.H)(e,r.verify);return{file:t.parsed.relPath,calc:t.slug,outcome:"compile:failed"===o.status?"verify_failed":"ok",touchedSites:[{file:t.parsed.relPath,action:"delete_calc"},{file:(0,T.RI)(e,a),action:"delete_sandbox"},{file:n,action:"regenerate_index"}],verify:o,summary:`removed data calc ${t.slug} -> ${o.status}`}}))}),function(e,r){return I.apply(this,arguments)}),ek=R.bz().describe('Value grammar: JSON literals, bare data ref strings for output/error/IO data, { ref, subspace }, or { expr: "raw TypeScript expression" }.'),eI=R.Yj().describe("Project-relative data-calc file path, for example subspaces/subspace-0/data-calc/data-calculation-total.ts."),eS=R.KC([R.Yj(),R.ai()]).describe('Subspace locator. Defaults to subspace-0; accepts 0, "0", "subspace-0", or a project-relative subspace path.'),e$=R.Yj().describe("Data calc locator inside the subspace: alias, explicit string id, or filename slug."),eE=R.zM().describe("Override compile verification. Defaults to BRICKS_CTOR_MCP_EDIT_VERIFY, otherwise true."),eO={file:eI.optional(),subspace:eS.optional(),calc:e$.optional(),verify:eE.optional()},eP=R.Ik({key:R.Yj().describe('Sandbox input/output key, for example "price" or "total".'),data:ek.describe("Data ref as alias/id/varName, { ref, subspace }, or { expr }."),trigger:R.zM().describe("Inputs only; defaults true.").optional()}).describe("DataCalculationScript IO item.");function eC(e,r){var t,i,a,n;e.tool("new_data_calc","Create a standard DataCalculationScript in data-calc/{calc}.ts plus its sandbox JS file, regenerate data-calc/index.ts, and wire minimal subspace indexes.",{subspace:eS.optional(),alias:R.Yj().describe("Optional alias; also drives the filename slug.").optional(),title:R.Yj().describe("Optional title.").optional(),description:R.Yj().describe("Optional description.").optional(),note:R.Yj().describe("Optional script note.").optional(),triggerMode:R.k5(["auto","manual"]).describe("Optional trigger mode; omitted by default.").optional(),enableAsync:R.zM().describe("Whether the sandbox main may be async. Defaults false.").optional(),code:R.Yj().describe("Sandbox body. The tool wraps it as export function main() { ... } unless already wrapped.").optional(),inputs:R.YO(eP).describe("Initial script inputs. Input keys must be unique.").optional(),outputs:R.YO(eP).describe("Initial fan-out outputs. Output keys may repeat.").optional(),output:ek.describe("Single output data ref or null.").optional(),error:ek.describe("Error output data ref or null.").optional(),id:R.Yj().describe("Optional explicit id. Defaults to source expression makeId('property_bank_calc').").optional(),verify:eE.optional()},(t=$(function*(e){return el((yield e_(r,e)))}),function(e){return t.apply(this,arguments)})),e.tool("edit_data_calc","Edit DataCalculationScript scalar fields, output/error refs, or sandbox code. Code edits normalize inline code to sandbox file-form.",{...eO,set:R.g1(R.Yj().describe("Top-level field path such as title, description, note, alias, triggerMode, enableAsync, output, or error."),ek).describe("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.").optional(),unset:R.YO(R.Yj()).describe("Top-level fields to remove.").optional(),code:R.Yj().describe("Replacement sandbox body. The tool wraps it as export function main() { ... } unless already wrapped.").optional()},(i=$(function*(e){return el((yield ex(r,e)))}),function(e){return i.apply(this,arguments)})),e.tool("edit_data_calc_io","Edit DataCalculationScript inputs or outputs arrays. Inputs require unique keys; outputs may repeat keys for fan-out.",{...eO,field:R.k5(["inputs","outputs"]).describe("Which IO array to edit."),op:R.k5(["add","remove","replace","clear"]).describe("Array operation."),key:R.Yj().describe("IO key target. Ambiguous repeated output keys must use index.").optional(),index:R.ai().describe("Zero-based IO index target or add insertion index.").optional(),data:ek.describe("For add/replace: data ref as string, { ref, subspace }, or { expr }.").optional(),trigger:R.zM().describe("Inputs only; defaults true.").optional()},(a=$(function*(e){return el((yield ew(r,e)))}),function(e){return a.apply(this,arguments)})),e.tool("remove_data_calc","Remove a standard DataCalculationScript .ts file plus its sandbox file and regenerate data-calc/index.ts. No reverse cascade is needed.",eO,(n=$(function*(e){return el((yield ej(r,e)))}),function(e){return n.apply(this,arguments)}))}var eD={newDataCalc:e_,editDataCalc:ex,editDataCalcIo:ew,removeDataCalc:ej,resolveCalcTarget:V};i()}catch(e){i(e)}})}};
14
+ `,o=Y.join(r,"index.ts"),s={projectDir:e,absPath:o,relPath:(0,q.RI)(e,o),source:n,ast:V(n,(0,q.RI)(e,o))};return yield em(s),(0,q.RI)(e,o)}),function(e,r){return v.apply(this,arguments)}),ej=(h=$(function*(e,r){var t=Y.join(r,"index.ts"),i=(0,q.RI)(e,t),a=yield(0,J.readFile)(t,"utf8").catch(e=>{if(e?.code==="ENOENT")return null;throw e});if(null==a)return{warning:`${i} not found; wire the data-calc import manually`};var n=yield G(e,t),o=(e=>{for(var r of e.program.body)if(N.isExportDefaultDeclaration(r)){var t=r.declaration;if(N.isObjectExpression(t))return t;if(N.isTSAsExpression(t)&&N.isObjectExpression(t.expression))return t.expression}return null})(n.ast);if(!o)return{warning:`${i} has no default-export object; wire the data-calc import manually`};var s=(0,q.bf)(o,"dataCalculation");if(s&&N.isIdentifier(s.value))return null;if(s&&!(N.isArrayExpression(s.value)&&0===s.value.elements.length))return{warning:`${i} has a non-empty dataCalculation value; wire the data-calc import manually`};if(n.ast.program.body.some(e=>N.isImportDeclaration(e)&&("./data-calc"===e.source.value||"./data-calc/index"===e.source.value))||(0,q.Pb)(n.ast,N.importDeclaration([N.importSpecifier(N.identifier("dataCalculation"),N.identifier("dataCalculation"))],N.stringLiteral("./data-calc"))),s)s.value=N.identifier("dataCalculation"),N.isIdentifier(s.key)&&(s.shorthand=!0);else{var l=N.objectProperty(N.identifier("dataCalculation"),N.identifier("dataCalculation"));l.shorthand=!0,o.properties.push(l)}return yield em(n),{touched:n.relPath}}),function(e,r){return h.apply(this,arguments)}),ek=(g=$(function*(e,r,t){if(!r.key)throw new Z("missing_key",`${e} item requires key`);if(null==r.data)throw new Z("missing_data",`${e} item requires data`);var i=[N.objectProperty(N.identifier("key"),N.stringLiteral(r.key)),N.objectProperty(N.identifier("data"),(yield el(r.data,t)))];return"inputs"===e&&i.push(N.objectProperty(N.identifier("trigger"),N.booleanLiteral(!1!==r.trigger))),N.objectExpression(i)}),function(e,r,t){return g.apply(this,arguments)}),eI=(_=$(function*(e,r,t){if("inputs"===e){var i=new Set;for(var a of r){if(i.has(a?.key))throw new Z("duplicate_key",`Input key already exists: ${a.key}`,{key:a.key});i.add(a?.key)}}var n=[];for(var o of r)n.push((yield ek(e,o,t)));return N.arrayExpression(n)}),function(e,r,t){return _.apply(this,arguments)}),eS=(e,r)=>{if("number"==typeof r.index)return r.index;if(!r.key)return -1;var t=e.elements.map((e,r)=>({element:e,index:r})).filter(({element:e})=>N.isObjectExpression(e)&&(0,q.JJ)(e,"key")===r.key);if(t.length>1)throw new Z("ambiguous_key",`IO key is ambiguous: ${r.key}`,{key:r.key,count:t.length});return t[0]?.index??-1},e$=(x=$(function*(e,r,t,i){let a;t.typeImports.add("DataCalculationScript"),t.valueImports.add("makeId"),en(t.parsed.ast);var n=[N.objectProperty(N.identifier("__typename"),N.stringLiteral("DataCalculationScript")),N.objectProperty(N.identifier("id"),e.id?N.stringLiteral(e.id):(a="property_bank_calc",N.callExpression(N.identifier("makeId"),i?[N.stringLiteral(a),N.stringLiteral(i)]:[N.stringLiteral(a)])))];return e.alias&&n.push(N.objectProperty(N.identifier("alias"),N.stringLiteral(e.alias))),null!=e.title&&n.push(N.objectProperty(N.identifier("title"),N.stringLiteral(e.title))),null!=e.description&&n.push(N.objectProperty(N.identifier("description"),N.stringLiteral(e.description))),null!=e.note&&n.push(N.objectProperty(N.identifier("note"),N.stringLiteral(e.note))),n.push(N.objectProperty(N.identifier("code"),ep(r))),n.push(N.objectProperty(N.identifier("enableAsync"),N.booleanLiteral(!!e.enableAsync))),null!=e.triggerMode&&n.push(N.objectProperty(N.identifier("triggerMode"),N.stringLiteral(e.triggerMode))),n.push(N.objectProperty(N.identifier("inputs"),(yield eI("inputs",e.inputs||[],t)))),n.push(N.objectProperty(N.identifier("output"),(yield ec(e.output,t)))),n.push(N.objectProperty(N.identifier("outputs"),(yield eI("outputs",e.outputs||[],t)))),n.push(N.objectProperty(N.identifier("error"),(yield ec(e.error,t)))),N.objectExpression(n)}),function(e,r,t,i){return x.apply(this,arguments)}),eE=(w=$(function*(e,r){return eh(e,"new_data_calc",r,$(function*(){var t,i,a,n=X(e,r.subspace),o=Y.join(n,"data-calc");yield(0,J.mkdir)(o,{recursive:!0});var s=yield eg(o,r.alias),l=`data-calculation-${s}.sandbox.js`,c=Y.join(o,`data-calculation-${s}.ts`),u=Y.join(o,l),d=(t=(0,q.RI)(e,c),i="export const dataCalculation = {}\n",(a=V(i,t)).program.body=[],{ast:a,source:i,projectDir:e,absPath:c,relPath:t}),p={projectDir:e,parsed:d,references:[],typeImports:new Set,valueImports:new Set},f=r.id||"string"!=typeof r.alias||!r.alias||(yield eu(e,r.alias))?void 0:r.alias,y=yield e$(r,l,p,f),m=N.variableDeclarator(N.identifier("dataCalculation"),y);m.id.typeAnnotation=N.tsTypeAnnotation(N.tsTypeReference(N.identifier("DataCalculationScript"))),d.ast.program.body.push(N.exportNamedDeclaration(N.variableDeclaration("const",[m]))),eo(p),yield(0,J.writeFile)((yield Q(e,u)),ex(r.code)),yield em(d);var b=[{file:(0,q.RI)(e,c),action:"create_calc"},{file:(0,q.RI)(e,u),action:"write_sandbox"}];b.push({file:yield ew(e,o),action:"regenerate_index"});var v=yield ej(e,n);v?.touched&&b.push({file:v.touched,action:"wire_subspace_index"});var h=yield(0,z.H)(e,r.verify);return{file:(0,q.RI)(e,c),subspace:Y.basename(n),calc:s,idExpression:r.id??(f?`makeId('property_bank_calc', '${f}')`:"makeId('property_bank_calc')"),outcome:"compile:failed"===h.status?"verify_failed":"ok",touchedSites:b,...v?.warning?{warnings:[v.warning]}:{},verify:h,references:ev(p.references),summary:`created data calc ${s} in ${Y.basename(n)} -> ${h.status}`}}))}),function(e,r){return w.apply(this,arguments)}),eO=(j=$(function*(e,r){return eh(e,"edit_data_calc",r,$(function*(){var t=yield ea(e,r),i={projectDir:e,parsed:t.parsed,references:[],typeImports:new Set,valueImports:new Set},a=[];for(var n of Object.entries(r.set||{})){var o=S(n,2),s=o[0],l=o[1];if("output"===s||"error"===s)(0,q.HJ)(t.object,s,(yield ec(l,i)));else if("inputs"===s||"outputs"===s){if(!Array.isArray(l))throw new Z("invalid_value",`${s} must be an array of IO items`);(0,q.HJ)(t.object,s,(yield eI(s,l,i)))}else if("code"===s)throw new Z("invalid_field","Set code via the dedicated code parameter so it stays normalized to the sandbox file");else(0,q.HJ)(t.object,s,(yield ef(l,i)))}for(var c of r.unset||[]){if(ed.has(c))throw new Z("invalid_field",`Cannot unset required field: ${c}`,{field:c});(0,q.jc)(t.object,c)}if(null!=r.code){var u=et(t.object);if(!(e=>{if(!e)return!1;if(N.isStringLiteral(e)||N.isTemplateLiteral(e))return!0;var r=ei(e);return null!=r&&/^(\.\/)?[^/\\]+\.sandbox\.js$/.test(r)})(u))throw new Z("fallback_recommended",`Data calc ${t.parsed.relPath} has an unsupported code expression. Edit this file directly for this one.`,{file:t.parsed.relPath,field:"code"});var d=t.sandboxFile,p=Y.join(Y.dirname(t.parsed.absPath),d);yield(0,J.writeFile)((yield Q(e,p)),ex(r.code)),en(t.parsed.ast),(0,q.HJ)(t.object,"code",ep(d)),a.push({file:(0,q.RI)(e,p),action:"write_sandbox"})}eo(i),yield em(t.parsed),a.unshift({file:t.parsed.relPath,action:"edit_calc"});var f=yield(0,z.H)(e,r.verify);return{file:t.parsed.relPath,calc:t.slug,outcome:"compile:failed"===f.status?"verify_failed":"ok",touchedSites:a,verify:f,references:ev(i.references),summary:`edited data calc ${t.slug} -> ${f.status}`}}))}),function(e,r){return j.apply(this,arguments)}),eP=(k=$(function*(e,r){return eh(e,"edit_data_calc_io",r,$(function*(){var t=yield ea(e,r),i={projectDir:e,parsed:t.parsed,references:[],typeImports:new Set,valueImports:new Set},a=r.field,n=((e,r)=>{var t=(0,q.bf)(e,r);if(t){if(!N.isArrayExpression(t.value))throw new Z("fallback_recommended",`${r} is not an array. Edit this file directly.`);return t.value}var i=N.arrayExpression([]);return e.properties.push(N.objectProperty(N.identifier(r),i)),i})(t.object,a),o=r.op;if("clear"===o)n.elements=[];else if("remove"===o){var s=eS(n,r);if(s<0||s>=n.elements.length)throw new Z("invalid_index","remove requires a valid key or index");n.elements.splice(s,1)}else if("add"===o||"replace"===o){var l="replace"===o?eS(n,r):r.index;if("replace"===o&&(l<0||l>=n.elements.length))throw new Z("invalid_index","replace requires a valid key or index");if("add"===o&&"number"==typeof l&&(l<0||l>n.elements.length))throw new Z("invalid_index","add index out of range",{index:l});"inputs"===a&&((e,r,t)=>{if(e.elements.some((e,i)=>i!==t&&N.isObjectExpression(e)&&(0,q.JJ)(e,"key")===r))throw new Z("duplicate_key",`Input key already exists: ${r}`,{key:r})})(n,r.key,"replace"===o?l:void 0);var c=yield ek(a,r,i);"replace"===o?n.elements[l]=c:n.elements.splice("number"==typeof l?l:n.elements.length,0,c)}else throw new Z("invalid_op",`Unsupported edit_data_calc_io op: ${o}`);eo(i),yield em(t.parsed);var u=yield(0,z.H)(e,r.verify);return{file:t.parsed.relPath,calc:t.slug,outcome:"compile:failed"===u.status?"verify_failed":"ok",change:{field:a,op:o,key:r.key,index:r.index},verify:u,references:ev(i.references),summary:`${o} ${a} on data calc ${t.slug} -> ${u.status}`}}))}),function(e,r){return k.apply(this,arguments)}),eC=(I=$(function*(e,r){return eh(e,"remove_data_calc",r,$(function*(){var t=yield ea(e,r),i=Y.dirname(t.parsed.absPath),a=Y.join(i,t.sandboxFile);yield(0,J.rm)(t.parsed.absPath,{force:!0}),yield(0,J.rm)(a,{force:!0});var n=yield ew(e,i),o=yield(0,z.H)(e,r.verify);return{file:t.parsed.relPath,calc:t.slug,outcome:"compile:failed"===o.status?"verify_failed":"ok",touchedSites:[{file:t.parsed.relPath,action:"delete_calc"},{file:(0,q.RI)(e,a),action:"delete_sandbox"},{file:n,action:"regenerate_index"}],verify:o,summary:`removed data calc ${t.slug} -> ${o.status}`}}))}),function(e,r){return I.apply(this,arguments)}),eD=M.bz().describe('Value grammar: JSON literals, bare data ref strings for output/error/IO data, { ref, subspace }, or { expr: "raw TypeScript expression" }.'),eA=M.Yj().describe("Project-relative data-calc file path, for example subspaces/subspace-0/data-calc/data-calculation-total.ts."),eR=M.KC([M.Yj(),M.ai()]).describe('Subspace locator. Defaults to subspace-0; accepts 0, "0", "subspace-0", or a project-relative subspace path.'),eL=M.Yj().describe("Data calc locator inside the subspace: alias, explicit string id, or filename slug."),eN=M.zM().describe("Override compile verification. Defaults to BRICKS_CTOR_MCP_EDIT_VERIFY, otherwise true."),eT={file:eA.optional(),subspace:eR.optional(),calc:eL.optional(),verify:eN.optional()},eF=M.Ik({key:M.Yj().describe('Sandbox input/output key, for example "price" or "total".'),data:eD.describe("Data ref as alias/id/varName, { ref, subspace }, or { expr }."),trigger:M.zM().describe("Inputs only; defaults true.").optional()}).describe("DataCalculationScript IO item.");function eJ(e,r){var t,i,a,n;e.tool("new_data_calc","Create a standard DataCalculationScript in data-calc/{calc}.ts plus its sandbox JS file, regenerate data-calc/index.ts, and wire minimal subspace indexes.",{subspace:eR.optional(),alias:M.Yj().describe("Optional alias; also drives the filename slug.").optional(),title:M.Yj().describe("Optional title.").optional(),description:M.Yj().describe("Optional description.").optional(),note:M.Yj().describe("Optional script note.").optional(),triggerMode:M.k5(["auto","manual"]).describe("Optional trigger mode; omitted by default.").optional(),enableAsync:M.zM().describe("Whether the sandbox main may be async. Defaults false.").optional(),code:M.Yj().describe("Sandbox body. The tool wraps it as export function main() { ... } unless already wrapped.").optional(),inputs:M.YO(eF).describe("Initial script inputs. Input keys must be unique.").optional(),outputs:M.YO(eF).describe("Initial fan-out outputs. Output keys may repeat.").optional(),output:eD.describe("Single output data ref or null.").optional(),error:eD.describe("Error output data ref or null.").optional(),id:M.Yj().describe("Optional explicit id. Defaults to source expression makeId('property_bank_calc').").optional(),verify:eN.optional()},(t=$(function*(e){return eb((yield eE(r,e)))}),function(e){return t.apply(this,arguments)})),e.tool("edit_data_calc","Edit DataCalculationScript scalar fields, output/error refs, or sandbox code. Code edits normalize inline code to sandbox file-form.",{...eT,set:M.g1(M.Yj().describe("Top-level field path such as title, description, note, alias, triggerMode, enableAsync, output, or error."),eD).describe("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.").optional(),unset:M.YO(M.Yj()).describe("Top-level fields to remove.").optional(),code:M.Yj().describe("Replacement sandbox body. The tool wraps it as export function main() { ... } unless already wrapped.").optional()},(i=$(function*(e){return eb((yield eO(r,e)))}),function(e){return i.apply(this,arguments)})),e.tool("edit_data_calc_io","Edit DataCalculationScript inputs or outputs arrays. Inputs require unique keys; outputs may repeat keys for fan-out.",{...eT,field:M.k5(["inputs","outputs"]).describe("Which IO array to edit."),op:M.k5(["add","remove","replace","clear"]).describe("Array operation."),key:M.Yj().describe("IO key target. Ambiguous repeated output keys must use index.").optional(),index:M.ai().describe("Zero-based IO index target or add insertion index.").optional(),data:eD.describe("For add/replace: data ref as string, { ref, subspace }, or { expr }.").optional(),trigger:M.zM().describe("Inputs only; defaults true.").optional()},(a=$(function*(e){return eb((yield eP(r,e)))}),function(e){return a.apply(this,arguments)})),e.tool("remove_data_calc","Remove a standard DataCalculationScript .ts file plus its sandbox file and regenerate data-calc/index.ts. No reverse cascade is needed.",eT,(n=$(function*(e){return eb((yield eC(r,e)))}),function(e){return n.apply(this,arguments)}))}var eY={newDataCalc:eE,editDataCalc:eO,editDataCalcIo:eP,removeDataCalc:eC,resolveCalcTarget:ea};i()}catch(e){i(e)}})}};